<commit_before>#include <iostream>
#include <math.h>
#include <string>
#include <vector>
#include "mex.h"

#include <nix.hpp>

#include "handle.h"
#include "arguments.h"

// *** datatype converter

template<typename T>
struct to_mx_class_id {

    static mxClassID value() {
        nix::DataType dtype = nix::to_data_type<T>::value;
        switch (dtype) {
            case nix::DataType::Double:
                return mxDOUBLE_CLASS;

            default:
                mexErrMsgIdAndTxt("MATLAB:toclassid:notimplemented", "Implement me!");
                return mxVOID_CLASS;
        }
    }

};

template<typename T>
mxArray* vector_to_array(const std::vector<T> &v) {
    mxClassID klass_id = to_mx_class_id<T>::value();
    mxArray *data = mxCreateNumericMatrix(1, v.size(), klass_id, mxREAL);
    double *ptr = mxGetPr(data);
    memcpy(ptr, v.data(), sizeof(T) * v.size());
    return data;
}

// *** functions ***

static void entity_destory(const extractor &input, infusor &output)
{
    mexPrintf("[+] entity_destory\n");
    handle h = input.hdl(1);
    h.destroy();
}

static void open_file(const extractor &input, infusor &output)
{
    input.require_arguments({mxCHAR_CLASS, mxCHAR_CLASS}, true);
    mexPrintf("[+] open_file\n");

    std::string name = input.str(1);

    nix::File fn = nix::File::open(name, nix::FileMode::ReadWrite);
    handle h = handle(fn);

    output.set(0, h);
}

static void list_blocks(const extractor &input, infusor &output)
{
    mexPrintf("[+] list_blocks\n");
    nix::File fd = input.entity<nix::File>(1);

    std::vector<nix::Block> blocks = fd.blocks();

    std::vector<const char *> fields = { "name", "id" };

    mxArray *sa =  mxCreateStructMatrix(blocks.size(), 1, fields.size(), fields.data());

    for (size_t n = 0; n < blocks.size(); n++) {
        mxSetFieldByNumber(sa, n, 0, mxCreateString(blocks[n].name().c_str()));
        mxSetFieldByNumber(sa, n, 1, mxCreateString(blocks[n].id().c_str()));
    }

    output.set(0, sa);
}

static void list_data_arrays(const extractor &input, infusor &output)
{
    mexPrintf("[+] list_data_arrays\n");

    nix::File nf = input.entity<nix::File>(1);
    nix::Block block = nf.getBlock(input.str(2));

    std::vector<nix::DataArray> arr = block.dataArrays();

    std::vector<const char *> fields = { "name", "id" };

    mxArray *sa =  mxCreateStructMatrix(arr.size(), 1, fields.size(), fields.data());

    for (size_t n = 0; n < arr.size(); n++) {
        mxSetFieldByNumber(sa, n, 0, mxCreateString(arr[n].name().c_str()));
        mxSetFieldByNumber(sa, n, 1, mxCreateString(arr[n].id().c_str()));
    }

    output.set(0, sa);
}

static void open_block(const extractor &input, infusor &output)
{
    mexPrintf("[+] list_data_arrays\n");
    nix::File nf = input.entity<nix::File>(1);
    nix::Block block = nf.getBlock(input.str(2));
    handle bb = handle(block);
    output.set(0, bb);
}

static void open_data_array(const extractor &input, infusor &output)
{
    mexPrintf("[+] list_data_arrays\n");
    nix::Block block = input.entity<nix::Block>(1);
    nix::DataArray da = block.getDataArray(input.str(2));
    handle bd = handle(da);
    output.set(0, bd);
}

static mxArray * ndsize_to_mxarray(const nix::NDSize &size)
{
    mxArray *res = mxCreateNumericMatrix(1, size.size(), mxUINT64_CLASS, mxREAL);
    void *ptr = mxGetData(res);
    uint64_t *data = static_cast<uint64_t *>(ptr);

    for (size_t i = 0; i < size.size(); i++) {
        data[i] = static_cast<uint64_t>(size[i]);
    }

    return res;
}

static nix::NDSize mx_array_to_ndsize(const mxArray *arr) {

    size_t m = mxGetM(arr);
    size_t n = mxGetN(arr);

    //if (m != 1 && n != 1)

    size_t k = std::max(n, m);
    nix::NDSize size(k);

    double *data = mxGetPr(arr);
    for (size_t i = 0; i < size.size(); i++) {
        size[i] = static_cast<nix::NDSize::value_type>(data[i]);
    }

    return size;
}

static mxArray *nmCreateScalar(uint32_t val) {
    mxArray *arr = mxCreateNumericMatrix(1, 1, mxUINT32_CLASS, mxREAL);
    void *data = mxGetData(arr);
    memcpy(data, &val, sizeof(uint32_t));
    return arr;
}

static mxArray *dim_to_struct(nix::SetDimension dim) {

    std::vector<const char *> fields = { "type", "type_id", "label" };
    mxArray *sa =  mxCreateStructMatrix(1, 1, fields.size(), fields.data());

    mxSetFieldByNumber(sa, 0, 0, mxCreateString("set"));
    mxSetFieldByNumber(sa, 0, 1, nmCreateScalar(1));

    std::vector<std::string> labels = dim.labels();
    return sa;
}

static mxArray *dim_to_struct(nix::SampledDimension dim) {

    std::vector<const char *> fields = { "type", "type_id", "interval", "label", "unit"};
    mxArray *sa =  mxCreateStructMatrix(1, 1, fields.size(), fields.data());

    mxSetFieldByNumber(sa, 0, 0, mxCreateString("sampled"));
    mxSetFieldByNumber(sa, 0, 1, nmCreateScalar(2));
    mxSetFieldByNumber(sa, 0, 2, mxCreateDoubleScalar(dim.samplingInterval()));

    boost::optional<std::string> label = dim.label();
    if (label) {
        mxSetFieldByNumber(sa, 0, 3, mxCreateString(label->c_str()));
    }

    boost::optional<std::string> unit = dim.unit();
    if (unit) {
        mxSetFieldByNumber(sa, 0, 4, mxCreateString(unit->c_str()));
    }

    return sa;
}

static mxArray *dim_to_struct(nix::RangeDimension dim) {

    std::vector<const char *> fields = { "type", "type_id" };
    mxArray *sa =  mxCreateStructMatrix(1, 1, fields.size(), fields.data());

    mxSetFieldByNumber(sa, 0, 0, mxCreateString("range"));
    mxSetFieldByNumber(sa, 0, 1, nmCreateScalar(3));
    return sa;
}

static void data_array_describe(const extractor &input, infusor &output)
{
    mexPrintf("[+] block_describe_data_array\n");
    nix::DataArray da = input.entity<nix::DataArray>(1);

    std::vector<const char *> fields = { "name", "id", "shape",  "unit", "dimensions", "label",
                                         "polynom_coefficients"};
    mxArray *sa =  mxCreateStructMatrix(1, 1, fields.size(), fields.data());

    mxSetFieldByNumber(sa, 0, 0, mxCreateString(da.name().c_str()));
    mxSetFieldByNumber(sa, 0, 1, mxCreateString(da.id().c_str()));
    mxSetFieldByNumber(sa, 0, 2, ndsize_to_mxarray(da.dataExtent()));

    boost::optional<std::string> unit = da.unit();
    if (unit) {
        mxSetFieldByNumber(sa, 0, 3, mxCreateString(unit->c_str()));
    }

    size_t ndims = da.dimensionCount();

    mxArray *dims = mxCreateCellMatrix(1, ndims);
    std::vector<nix::Dimension> da_dims = da.dimensions();

    for(size_t i = 0; i < ndims; i++) {
        mxArray *ca;

        switch(da_dims[i].dimensionType()) {
            case nix::DimensionType::Set:
                ca = dim_to_struct(da_dims[i].asSetDimension());
                break;
            case nix::DimensionType::Range:
                ca = dim_to_struct(da_dims[i].asRangeDimension());
                break;
            case nix::DimensionType::Sample:
                ca = dim_to_struct(da_dims[i].asSampledDimension());
                break;
        }

        mxSetCell(dims, i, ca);
    }

    mxSetFieldByNumber(sa, 0, 4, dims);

    boost::optional<std::string> label = da.label();
    if (unit) {
        mxSetFieldByNumber(sa, 0, 5, mxCreateString(label->c_str()));
    }

    std::vector<double> pc = da.polynomCoefficients();

    if (!pc.empty()) {
        mxSetFieldByNumber(sa, 0, 6, vector_to_array(pc));
    }

    output.set(0, sa);
}

static void data_array_read_all(const extractor &input, infusor &output)
{
    mexPrintf("[+] block_describe_data_array\n");
    nix::DataArray da = input.entity<nix::DataArray>(1);

    nix::NDSize size = da.dataExtent();
    std::vector<mwSize> dims(size.size());

    for (size_t i = 0; i < size.size(); i++) {
        dims[i] = static_cast<mwSize>(size[i]);
    }

    mxArray *data = mxCreateNumericArray(size.size(), dims.data(), mxDOUBLE_CLASS, mxREAL);
    double *ptr = mxGetPr(data);

    nix::NDSize offset(size.size(), 0);
    da.getData(nix::DataType::Double , ptr, size, offset);

    output.set(0, data);
}

// *** ***

typedef void (*fn_t)(const extractor &input, infusor &output);

struct fendpoint {

fendpoint(std::string name, fn_t fn) : name(name), fn(fn) {}

    std::string name;
    fn_t fn;
};

const std::vector<fendpoint> funcs = {
        {"Entity::destroy", entity_destory},
        {"File::open", open_file},
        {"File::listBlocks", list_blocks},
        {"File::listDataArrays", list_data_arrays},
        {"File::openBlock", open_block},
        {"Block::openDataArray", open_data_array},
        {"DataArray::describe", data_array_describe},
        {"DataArray::readAll", data_array_read_all}
};

// main entry point
void mexFunction(int            nlhs,
                 mxArray       *lhs[],
                 int            nrhs,
                 const mxArray *rhs[])
{
    extractor input(rhs, nrhs);
    infusor   output(lhs, nlhs);

    std::string cmd = input.str(0);

    mexPrintf("[F] %s\n", cmd.c_str());

    bool processed = false;
    for (const auto &fn : funcs) {
        if (fn.name == cmd) {
            try {
                fn.fn(input, output);
            } catch (std::exception &e) {
                mexErrMsgIdAndTxt("MATLAB:arg:dispatch", e.what());
            } catch (...) {
                mexErrMsgIdAndTxt("MATLAB:arg:dispatch", "unkown exception");
            }
            processed = true;
            break;
        }
    }

    if (!processed) {
        mexErrMsgIdAndTxt("MATLAB:arg:dispatch", "Unkown command");
    }
}

<commit_msg>specialize vector_to_array<>() for std::string<commit_after>#include <iostream>
#include <math.h>
#include <string>
#include <vector>
#include "mex.h"

#include <nix.hpp>

#include "handle.h"
#include "arguments.h"

// *** datatype converter

template<typename T>
struct to_mx_class_id {

    static mxClassID value() {
        nix::DataType dtype = nix::to_data_type<T>::value;
        switch (dtype) {
            case nix::DataType::Double:
                return mxDOUBLE_CLASS;

            default:
                mexErrMsgIdAndTxt("MATLAB:toclassid:notimplemented", "Implement me!");
                return mxVOID_CLASS;
        }
    }

};

template<typename T>
mxArray* vector_to_array(const std::vector<T> &v) {
    mxClassID klass_id = to_mx_class_id<T>::value();
    mxArray *data = mxCreateNumericMatrix(1, v.size(), klass_id, mxREAL);
    double *ptr = mxGetPr(data);
    memcpy(ptr, v.data(), sizeof(T) * v.size());
    return data;
}

template<>
mxArray* vector_to_array(const std::vector<std::string> &v) {
    mxArray *data = mxCreateCellMatrix(1, v.size());
    for (size_t i = 0; i < v.size(); i++) {
        mxSetCell(data, i, mxCreateString(v[i].c_str()));
    }

    return data;
}

// *** functions ***

static void entity_destory(const extractor &input, infusor &output)
{
    mexPrintf("[+] entity_destory\n");
    handle h = input.hdl(1);
    h.destroy();
}

static void open_file(const extractor &input, infusor &output)
{
    input.require_arguments({mxCHAR_CLASS, mxCHAR_CLASS}, true);
    mexPrintf("[+] open_file\n");

    std::string name = input.str(1);

    nix::File fn = nix::File::open(name, nix::FileMode::ReadWrite);
    handle h = handle(fn);

    output.set(0, h);
}

static void list_blocks(const extractor &input, infusor &output)
{
    mexPrintf("[+] list_blocks\n");
    nix::File fd = input.entity<nix::File>(1);

    std::vector<nix::Block> blocks = fd.blocks();

    std::vector<const char *> fields = { "name", "id" };

    mxArray *sa =  mxCreateStructMatrix(blocks.size(), 1, fields.size(), fields.data());

    for (size_t n = 0; n < blocks.size(); n++) {
        mxSetFieldByNumber(sa, n, 0, mxCreateString(blocks[n].name().c_str()));
        mxSetFieldByNumber(sa, n, 1, mxCreateString(blocks[n].id().c_str()));
    }

    output.set(0, sa);
}

static void list_data_arrays(const extractor &input, infusor &output)
{
    mexPrintf("[+] list_data_arrays\n");

    nix::File nf = input.entity<nix::File>(1);
    nix::Block block = nf.getBlock(input.str(2));

    std::vector<nix::DataArray> arr = block.dataArrays();

    std::vector<const char *> fields = { "name", "id" };

    mxArray *sa =  mxCreateStructMatrix(arr.size(), 1, fields.size(), fields.data());

    for (size_t n = 0; n < arr.size(); n++) {
        mxSetFieldByNumber(sa, n, 0, mxCreateString(arr[n].name().c_str()));
        mxSetFieldByNumber(sa, n, 1, mxCreateString(arr[n].id().c_str()));
    }

    output.set(0, sa);
}

static void open_block(const extractor &input, infusor &output)
{
    mexPrintf("[+] list_data_arrays\n");
    nix::File nf = input.entity<nix::File>(1);
    nix::Block block = nf.getBlock(input.str(2));
    handle bb = handle(block);
    output.set(0, bb);
}

static void open_data_array(const extractor &input, infusor &output)
{
    mexPrintf("[+] list_data_arrays\n");
    nix::Block block = input.entity<nix::Block>(1);
    nix::DataArray da = block.getDataArray(input.str(2));
    handle bd = handle(da);
    output.set(0, bd);
}

static mxArray * ndsize_to_mxarray(const nix::NDSize &size)
{
    mxArray *res = mxCreateNumericMatrix(1, size.size(), mxUINT64_CLASS, mxREAL);
    void *ptr = mxGetData(res);
    uint64_t *data = static_cast<uint64_t *>(ptr);

    for (size_t i = 0; i < size.size(); i++) {
        data[i] = static_cast<uint64_t>(size[i]);
    }

    return res;
}

static nix::NDSize mx_array_to_ndsize(const mxArray *arr) {

    size_t m = mxGetM(arr);
    size_t n = mxGetN(arr);

    //if (m != 1 && n != 1)

    size_t k = std::max(n, m);
    nix::NDSize size(k);

    double *data = mxGetPr(arr);
    for (size_t i = 0; i < size.size(); i++) {
        size[i] = static_cast<nix::NDSize::value_type>(data[i]);
    }

    return size;
}

static mxArray *nmCreateScalar(uint32_t val) {
    mxArray *arr = mxCreateNumericMatrix(1, 1, mxUINT32_CLASS, mxREAL);
    void *data = mxGetData(arr);
    memcpy(data, &val, sizeof(uint32_t));
    return arr;
}

static mxArray *dim_to_struct(nix::SetDimension dim) {

    std::vector<const char *> fields = { "type", "type_id", "label" };
    mxArray *sa =  mxCreateStructMatrix(1, 1, fields.size(), fields.data());

    mxSetFieldByNumber(sa, 0, 0, mxCreateString("set"));
    mxSetFieldByNumber(sa, 0, 1, nmCreateScalar(1));

    std::vector<std::string> labels = dim.labels();
    return sa;
}

static mxArray *dim_to_struct(nix::SampledDimension dim) {

    std::vector<const char *> fields = { "type", "type_id", "interval", "label", "unit"};
    mxArray *sa =  mxCreateStructMatrix(1, 1, fields.size(), fields.data());

    mxSetFieldByNumber(sa, 0, 0, mxCreateString("sampled"));
    mxSetFieldByNumber(sa, 0, 1, nmCreateScalar(2));
    mxSetFieldByNumber(sa, 0, 2, mxCreateDoubleScalar(dim.samplingInterval()));

    boost::optional<std::string> label = dim.label();
    if (label) {
        mxSetFieldByNumber(sa, 0, 3, mxCreateString(label->c_str()));
    }

    boost::optional<std::string> unit = dim.unit();
    if (unit) {
        mxSetFieldByNumber(sa, 0, 4, mxCreateString(unit->c_str()));
    }

    return sa;
}

static mxArray *dim_to_struct(nix::RangeDimension dim) {

    std::vector<const char *> fields = { "type", "type_id" };
    mxArray *sa =  mxCreateStructMatrix(1, 1, fields.size(), fields.data());

    mxSetFieldByNumber(sa, 0, 0, mxCreateString("range"));
    mxSetFieldByNumber(sa, 0, 1, nmCreateScalar(3));
    return sa;
}

static void data_array_describe(const extractor &input, infusor &output)
{
    mexPrintf("[+] block_describe_data_array\n");
    nix::DataArray da = input.entity<nix::DataArray>(1);

    std::vector<const char *> fields = { "name", "id", "shape",  "unit", "dimensions", "label",
                                         "polynom_coefficients"};
    mxArray *sa =  mxCreateStructMatrix(1, 1, fields.size(), fields.data());

    mxSetFieldByNumber(sa, 0, 0, mxCreateString(da.name().c_str()));
    mxSetFieldByNumber(sa, 0, 1, mxCreateString(da.id().c_str()));
    mxSetFieldByNumber(sa, 0, 2, ndsize_to_mxarray(da.dataExtent()));

    boost::optional<std::string> unit = da.unit();
    if (unit) {
        mxSetFieldByNumber(sa, 0, 3, mxCreateString(unit->c_str()));
    }

    size_t ndims = da.dimensionCount();

    mxArray *dims = mxCreateCellMatrix(1, ndims);
    std::vector<nix::Dimension> da_dims = da.dimensions();

    for(size_t i = 0; i < ndims; i++) {
        mxArray *ca;

        switch(da_dims[i].dimensionType()) {
            case nix::DimensionType::Set:
                ca = dim_to_struct(da_dims[i].asSetDimension());
                break;
            case nix::DimensionType::Range:
                ca = dim_to_struct(da_dims[i].asRangeDimension());
                break;
            case nix::DimensionType::Sample:
                ca = dim_to_struct(da_dims[i].asSampledDimension());
                break;
        }

        mxSetCell(dims, i, ca);
    }

    mxSetFieldByNumber(sa, 0, 4, dims);

    boost::optional<std::string> label = da.label();
    if (unit) {
        mxSetFieldByNumber(sa, 0, 5, mxCreateString(label->c_str()));
    }

    std::vector<double> pc = da.polynomCoefficients();

    if (!pc.empty()) {
        mxSetFieldByNumber(sa, 0, 6, vector_to_array(pc));
    }

    output.set(0, sa);
}

static void data_array_read_all(const extractor &input, infusor &output)
{
    mexPrintf("[+] block_describe_data_array\n");
    nix::DataArray da = input.entity<nix::DataArray>(1);

    nix::NDSize size = da.dataExtent();
    std::vector<mwSize> dims(size.size());

    for (size_t i = 0; i < size.size(); i++) {
        dims[i] = static_cast<mwSize>(size[i]);
    }

    mxArray *data = mxCreateNumericArray(size.size(), dims.data(), mxDOUBLE_CLASS, mxREAL);
    double *ptr = mxGetPr(data);

    nix::NDSize offset(size.size(), 0);
    da.getData(nix::DataType::Double , ptr, size, offset);

    output.set(0, data);
}

// *** ***

typedef void (*fn_t)(const extractor &input, infusor &output);

struct fendpoint {

fendpoint(std::string name, fn_t fn) : name(name), fn(fn) {}

    std::string name;
    fn_t fn;
};

const std::vector<fendpoint> funcs = {
        {"Entity::destroy", entity_destory},
        {"File::open", open_file},
        {"File::listBlocks", list_blocks},
        {"File::listDataArrays", list_data_arrays},
        {"File::openBlock", open_block},
        {"Block::openDataArray", open_data_array},
        {"DataArray::describe", data_array_describe},
        {"DataArray::readAll", data_array_read_all}
};

// main entry point
void mexFunction(int            nlhs,
                 mxArray       *lhs[],
                 int            nrhs,
                 const mxArray *rhs[])
{
    extractor input(rhs, nrhs);
    infusor   output(lhs, nlhs);

    std::string cmd = input.str(0);

    mexPrintf("[F] %s\n", cmd.c_str());

    bool processed = false;
    for (const auto &fn : funcs) {
        if (fn.name == cmd) {
            try {
                fn.fn(input, output);
            } catch (std::exception &e) {
                mexErrMsgIdAndTxt("MATLAB:arg:dispatch", e.what());
            } catch (...) {
                mexErrMsgIdAndTxt("MATLAB:arg:dispatch", "unkown exception");
            }
            processed = true;
            break;
        }
    }

    if (!processed) {
        mexErrMsgIdAndTxt("MATLAB:arg:dispatch", "Unkown command");
    }
}

<|endoftext|>


<commit_before>/*
*   AED - 2015
*
*   Autor: Ferreyra, Maximiliano Gastn.
*
*   Legajjo: 155911-4.
*
*   Fecha: 20150411
*/

#include <iostream>

using namespace std;

int main(){

    /*
    * Declaramos variables que vamos a utilizar durante el programa.
    */

    int num1 = 37;
    int num2 = 4;

cout << "===============================================================================\n" << endl;
cout << "|                          Trabajo Practico No 1 AED                           |" << endl;
cout << "|                 \"Tipos de Datos y sus Operaciones Basicas\"                   |" << endl;
cout << "|           Alumno: Ferreyra, Maximiliano Gaston || Legajo: 155911-4           |" << endl;
cout << "===============================================================================" << endl;

cout << "_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _\n" << endl;

cout << "Tipo de dato: Int" << endl;
cout << "_________________\n" << endl;

cout << "Suma (num1 + num2): " << num1 + num2 << endl;
cout << "Resta (num1 - num2): " << num1 - num2 << endl;
cout << "Multiplicacion (num1 * num2): " << num1 * num2 << endl;
cout << "Division (num1 / num2): " << num1 / num2 << endl;
cout << "Resto de Division Entera (num1 % num2): " << num1 % num2 << "\n" << endl;
}

<commit_msg>Se agrega tipo de dato: Float<commit_after>/*
*   AED - 2015
*
*   Autor: Ferreyra, Maximiliano Gastn.
*
*   Legajjo: 155911-4.
*
*   Fecha: 20150411
*/

#include <iostream>

using namespace std;

int main(){

    /*
    * Declaramos variables que vamos a utilizar durante el programa.
    */

    int num1 = 37;
    int num2 = 4;

    float num3 = 35.7;
    float num4 = 9.4;

    double num5 = 38.99;
    double num6 = 21.65;

cout << "===============================================================================\n" << endl;
cout << "|                          Trabajo Practico No 1 AED                           |" << endl;
cout << "|                 \"Tipos de Datos y sus Operaciones Basicas\"                   |" << endl;
cout << "|           Alumno: Ferreyra, Maximiliano Gaston || Legajo: 155911-4           |" << endl;
cout << "===============================================================================" << endl;

cout << "_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _\n" << endl;

// Tipo de datos INT

cout << "Tipo de dato: Int" << endl;
cout << "_________________\n" << endl;

cout << "Suma (num1 + num2): " << num1 + num2 << endl;
cout << "Resta (num1 - num2): " << num1 - num2 << endl;
cout << "Multiplicacion (num1 * num2): " << num1 * num2 << endl;
cout << "Division (num1 / num2): " << num1 / num2 << endl;
cout << "Resto de Division Entera (num1 % num2): " << num1 % num2 << "\n" << endl;

// Tipo de datos Float

cout << "Tipo de dato: Float" << endl;
cout << "_________________\n" << endl;

cout << "Suma (num3 + num4): " << num3 + num4 << endl;
cout << "Resta (num3 - num4): " << num3 - num4 << endl;
cout << "Multiplicacion (num3 * num4): " << num3 * num4 << endl;
cout << "Division (num3 / num4): " << num3 / num4 << endl;
// No se puede obtener un resto de una divisin de datos del tipo Float.
}

<|endoftext|>


<commit_before>#include "consoleui.h"

int main()
{
    ConsoleUI ui;

    ui.run();

    return 0;
    //Test. jonh
}

<commit_msg>tok ut comment i main<commit_after>#include "consoleui.h"

int main()
{
    ConsoleUI ui;

    ui.run();

    return 0;
}

<|endoftext|>


<commit_before>#include <iostream>

//proper sdl header inclusion as per documentation
#include <SDL.h>

using namespace std;

int main() {

    const int SCREEN_WIDTH = 800;
    const int SCREEN_HEIGHT = 600;

    if (SDL_Init(SDL_INIT_VIDEO) < 0) {
        cout << "failed" << endl;
        return 1;
    }

    SDL_Window *window = SDL_CreateWindow("Cider Fire",
                                          SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT,
                                          SDL_WINDOW_SHOWN);

    if (window == NULL) {
        cout << SDL_GetError() << endl;
        SDL_Quit();
        return 2;
    }

    bool quit = false;

    SDL_Event event;

    while (!quit) {
//        Update particles
//        Draw particles
//        Check for messages or events

        while (SDL_PollEvent(&event)) {
            if (event.type == SDL_QUIT) {
                quit = true;
            }
        }
    }

    SDL_DestroyWindow(window);
    SDL_Quit();

    return 0;
}
<commit_msg>Implemented texture, buffer and renderer.<commit_after>#include <iostream>

//proper sdl header inclusion as per documentation
#include <SDL.h>

using namespace std;

int main() {

    const int SCREEN_WIDTH = 800;
    const int SCREEN_HEIGHT = 600;

    if (SDL_Init(SDL_INIT_VIDEO) < 0) {
        cout << "failed" << endl;
        return 1;
    }

    SDL_Window *window = SDL_CreateWindow("Cider Fire",
                                          SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT,
                                          SDL_WINDOW_SHOWN);

    if (window == NULL) {
        cout << SDL_GetError() << endl;
        SDL_Quit();
        return 2;
    }

    SDL_Renderer *renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_PRESENTVSYNC);
    SDL_Texture *texture = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_RGBA8888,
                                             SDL_TEXTUREACCESS_STATIC, SCREEN_WIDTH, SCREEN_HEIGHT);

    if (renderer == NULL) {
        cout << "could not create rendered" << endl;
        SDL_DestroyWindow(window);
        SDL_Quit();
        return 3;
    }

    if (texture == NULL) {
        cout << "could not create texture" << endl;
        SDL_DestroyRenderer(renderer);
        SDL_DestroyWindow(window);
        SDL_Quit();
        return 4;
    }

    //RGBA 8888 = 32

    Uint32 *buffer = new Uint32[SCREEN_WIDTH * SCREEN_HEIGHT];

    memset(buffer, 0xFF, SCREEN_WIDTH*SCREEN_HEIGHT*sizeof(Uint32));

    SDL_UpdateTexture(texture, NULL, buffer, SCREEN_WIDTH * sizeof(Uint32));
    SDL_RenderClear(renderer);
    SDL_RenderCopy(renderer, texture, NULL, NULL);
    SDL_RenderPresent(renderer);

    bool quit = false;

    SDL_Event event;

    while (!quit) {
//        Update particles
//        Draw particles
//        Check for messages or events

        while (SDL_PollEvent(&event)) {
            if (event.type == SDL_QUIT) {
                quit = true;
            }
        }
    }

    delete[] buffer;
    SDL_DestroyRenderer(renderer);
    SDL_DestroyTexture(texture);
    SDL_DestroyWindow(window);
    SDL_Quit();

    return 0;
}
<|endoftext|>


<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * Version: MPL 1.1 / GPLv3+ / LGPLv3+
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (the "License"); you may not use this file except in compliance with
 * the License or as specified alternatively below. You may obtain a copy of
 * the License at http://www.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * Major Contributor(s):
 * [ Copyright (C) 2011 SUSE <cbosdonnat@suse.com> (initial developer) ]
 *
 * All Rights Reserved.
 *
 * For minor contributions see the git repository.
 *
 * Alternatively, the contents of this file may be used under the terms of
 * either the GNU General Public License Version 3 or later (the "GPLv3+"), or
 * the GNU Lesser General Public License Version 3 or later (the "LGPLv3+"),
 * in which case the provisions of the GPLv3+ or the LGPLv3+ are applicable
 * instead of those above.
 */

#include <edtwin.hxx>
#include <FrameControlsManager.hxx>
#include <HeaderFooterWin.hxx>
#include <PageBreakWin.hxx>
#include <pagefrm.hxx>
#include <viewopt.hxx>
#include <view.hxx>
#include <wrtsh.hxx>

using namespace std;

namespace
{
    class FramePredicate
    {
        const SwFrm* m_pToMatch;

        public:
            FramePredicate( const SwFrm* pFrm ) : m_pToMatch( pFrm ) { };
            virtual ~FramePredicate() {};

            virtual bool operator()( SwFrameControlPtr pToCheck )
                { return m_pToMatch == pToCheck->GetFrame(); };
    };
}

SwFrameControlsManager::SwFrameControlsManager( SwEditWin* pEditWin ) :
    m_pEditWin( pEditWin ),
    m_aControls( )
{
}

SwFrameControlsManager::~SwFrameControlsManager()
{
    map< FrameControlType, vector< SwFrameControlPtr > >::iterator pIt = m_aControls.begin();

    while ( pIt != m_aControls.end() )
    {
        pIt->second.clear( );
        ++pIt;
    }
    m_aControls.clear();
}

SwFrameControlsManager::SwFrameControlsManager( const SwFrameControlsManager& rCopy ) :
    m_pEditWin( rCopy.m_pEditWin ),
    m_aControls( rCopy.m_aControls )
{
}

const SwFrameControlsManager& SwFrameControlsManager::operator=( const SwFrameControlsManager& rCopy )
{
    m_pEditWin = rCopy.m_pEditWin;
    m_aControls = rCopy.m_aControls;
    return *this;
}

SwFrameControlPtr SwFrameControlsManager::GetControl( FrameControlType eType, const SwFrm* pFrm )
{
    SwFrameControlPtr pControl;

    vector< SwFrameControlPtr >& aControls = m_aControls[eType];

    vector< SwFrameControlPtr >::iterator pIt = find_if(
            aControls.begin(), aControls.end( ), FramePredicate( pFrm ) );

    if ( pIt != aControls.end() )
        pControl = *pIt;

    return pControl;
}

std::vector< SwFrameControlPtr >& SwFrameControlsManager::GetControls( FrameControlType eType )
{
    return m_aControls[eType];
}

void SwFrameControlsManager::AddControl( FrameControlType eType, SwFrameControlPtr pControl )
{
    m_aControls[eType].push_back( pControl );
}

void SwFrameControlsManager::RemoveControls( const SwFrm* pFrm )
{
    map< FrameControlType, vector< SwFrameControlPtr > >::iterator pIt = m_aControls.begin();

    while ( pIt != m_aControls.end() )
    {
        vector< SwFrameControlPtr >& aVect = pIt->second;
        aVect.erase( remove_if( aVect.begin(),
                                aVect.end(),
                                FramePredicate( pFrm ) ), aVect.end() );
        ++pIt;
    }
}

void SwFrameControlsManager::HideControls( FrameControlType eType )
{
    vector< SwFrameControlPtr >::iterator pIt = m_aControls[eType].begin();
    while ( pIt != m_aControls[eType].end() )
    {
        ( *pIt )->ShowAll( false );
        pIt++;
    }
}

void SwFrameControlsManager::SetReadonlyControls( bool bReadonly )
{
    map< FrameControlType, vector< SwFrameControlPtr > >::iterator pIt = m_aControls.begin();

    while ( pIt != m_aControls.end() )
    {
        vector< SwFrameControlPtr >::iterator pVectIt = pIt->second.begin();
        while ( pVectIt != pIt->second.end() )
        {
            ( *pVectIt )->SetReadonly( bReadonly );
            ++pVectIt;
        }
        ++pIt;
    }
}

void SwFrameControlsManager::SetHeaderFooterControl( const SwPageFrm* pPageFrm, bool bHeader, Point aOffset )
{
    // Check if we already have the control
    SwFrameControlPtr pControl;

    vector< SwFrameControlPtr >& aControls = m_aControls[HeaderFooter];

    vector< SwFrameControlPtr >::iterator pIt = aControls.begin();
    while ( pIt != aControls.end() && !pControl.get() )
    {
        SwHeaderFooterWin* pToTest = dynamic_cast< SwHeaderFooterWin* >( pIt->get() );
        if ( pToTest->GetPageFrame( ) == pPageFrm &&
             pToTest->IsHeader( ) == bHeader )
            pControl = *pIt;
        pIt++;
    }

    if ( !pControl.get() )
    {
        SwFrameControlPtr pNewControl( new SwHeaderFooterWin( m_pEditWin, pPageFrm, bHeader ) );
        const SwViewOption* pViewOpt = m_pEditWin->GetView().GetWrtShell().GetViewOptions();
        pNewControl->SetReadonly( pViewOpt->IsReadonly() );
        AddControl( HeaderFooter, pNewControl );
        pControl.swap( pNewControl );
    }

    Rectangle aPageRect = m_pEditWin->LogicToPixel( pPageFrm->Frm().SVRect() );

    SwHeaderFooterWin* pHFWin = dynamic_cast< SwHeaderFooterWin* >( pControl.get() );
    pHFWin->SetOffset( aOffset, aPageRect.Left(), aPageRect.Right() );

    if ( !pHFWin->IsVisible() )
        pControl->ShowAll( true );
}

void SwFrameControlsManager::SetPageBreakControl( const SwPageFrm* pPageFrm )
{
    // Check if we already have the control
    SwFrameControlPtr pControl;

    vector< SwFrameControlPtr >& aControls = m_aControls[PageBreak];

    vector< SwFrameControlPtr >::iterator pIt = aControls.begin();
    while ( pIt != aControls.end() && !pControl.get() )
    {
        SwPageBreakWin* pToTest = dynamic_cast< SwPageBreakWin* >( pIt->get() );
        if ( pToTest->GetPageFrame( ) == pPageFrm )
            pControl = *pIt;
        pIt++;
    }

    if ( !pControl.get() )
    {
        SwFrameControlPtr pNewControl( new SwPageBreakWin( m_pEditWin, pPageFrm ) );
        const SwViewOption* pViewOpt = m_pEditWin->GetView().GetWrtShell().GetViewOptions();
        pNewControl->SetReadonly( pViewOpt->IsReadonly() );
        AddControl( PageBreak, pNewControl );
        pControl.swap( pNewControl );
    }

    SwPageBreakWin* pWin = dynamic_cast< SwPageBreakWin* >( pControl.get() );
    pWin->UpdatePosition();
    if ( !pWin->IsVisible() )
        pControl->ShowAll( true );
}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>Some cppcheck cleaning<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * Version: MPL 1.1 / GPLv3+ / LGPLv3+
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (the "License"); you may not use this file except in compliance with
 * the License or as specified alternatively below. You may obtain a copy of
 * the License at http://www.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * Major Contributor(s):
 * [ Copyright (C) 2011 SUSE <cbosdonnat@suse.com> (initial developer) ]
 *
 * All Rights Reserved.
 *
 * For minor contributions see the git repository.
 *
 * Alternatively, the contents of this file may be used under the terms of
 * either the GNU General Public License Version 3 or later (the "GPLv3+"), or
 * the GNU Lesser General Public License Version 3 or later (the "LGPLv3+"),
 * in which case the provisions of the GPLv3+ or the LGPLv3+ are applicable
 * instead of those above.
 */

#include <edtwin.hxx>
#include <FrameControlsManager.hxx>
#include <HeaderFooterWin.hxx>
#include <PageBreakWin.hxx>
#include <pagefrm.hxx>
#include <viewopt.hxx>
#include <view.hxx>
#include <wrtsh.hxx>

using namespace std;

namespace
{
    class FramePredicate
    {
        const SwFrm* m_pToMatch;

        public:
            FramePredicate( const SwFrm* pFrm ) : m_pToMatch( pFrm ) { };
            virtual ~FramePredicate() {};

            virtual bool operator()( SwFrameControlPtr pToCheck )
                { return m_pToMatch == pToCheck->GetFrame(); };
    };
}

SwFrameControlsManager::SwFrameControlsManager( SwEditWin* pEditWin ) :
    m_pEditWin( pEditWin ),
    m_aControls( )
{
}

SwFrameControlsManager::~SwFrameControlsManager()
{
    map< FrameControlType, vector< SwFrameControlPtr > >::iterator pIt = m_aControls.begin();

    while ( pIt != m_aControls.end() )
    {
        pIt->second.clear( );
        ++pIt;
    }
    m_aControls.clear();
}

SwFrameControlsManager::SwFrameControlsManager( const SwFrameControlsManager& rCopy ) :
    m_pEditWin( rCopy.m_pEditWin ),
    m_aControls( rCopy.m_aControls )
{
}

const SwFrameControlsManager& SwFrameControlsManager::operator=( const SwFrameControlsManager& rCopy )
{
    m_pEditWin = rCopy.m_pEditWin;
    m_aControls = rCopy.m_aControls;
    return *this;
}

SwFrameControlPtr SwFrameControlsManager::GetControl( FrameControlType eType, const SwFrm* pFrm )
{
    SwFrameControlPtr pControl;

    vector< SwFrameControlPtr >& aControls = m_aControls[eType];

    vector< SwFrameControlPtr >::iterator pIt = find_if(
            aControls.begin(), aControls.end( ), FramePredicate( pFrm ) );

    if ( pIt != aControls.end() )
        pControl = *pIt;

    return pControl;
}

std::vector< SwFrameControlPtr >& SwFrameControlsManager::GetControls( FrameControlType eType )
{
    return m_aControls[eType];
}

void SwFrameControlsManager::AddControl( FrameControlType eType, SwFrameControlPtr pControl )
{
    m_aControls[eType].push_back( pControl );
}

void SwFrameControlsManager::RemoveControls( const SwFrm* pFrm )
{
    map< FrameControlType, vector< SwFrameControlPtr > >::iterator pIt = m_aControls.begin();

    while ( pIt != m_aControls.end() )
    {
        vector< SwFrameControlPtr >& aVect = pIt->second;
        aVect.erase( remove_if( aVect.begin(),
                                aVect.end(),
                                FramePredicate( pFrm ) ), aVect.end() );
        ++pIt;
    }
}

void SwFrameControlsManager::HideControls( FrameControlType eType )
{
    vector< SwFrameControlPtr >::iterator pIt = m_aControls[eType].begin();
    while ( pIt != m_aControls[eType].end() )
    {
        ( *pIt )->ShowAll( false );
        ++pIt;
    }
}

void SwFrameControlsManager::SetReadonlyControls( bool bReadonly )
{
    map< FrameControlType, vector< SwFrameControlPtr > >::iterator pIt = m_aControls.begin();

    while ( pIt != m_aControls.end() )
    {
        vector< SwFrameControlPtr >::iterator pVectIt = pIt->second.begin();
        while ( pVectIt != pIt->second.end() )
        {
            ( *pVectIt )->SetReadonly( bReadonly );
            ++pVectIt;
        }
        ++pIt;
    }
}

void SwFrameControlsManager::SetHeaderFooterControl( const SwPageFrm* pPageFrm, bool bHeader, Point aOffset )
{
    // Check if we already have the control
    SwFrameControlPtr pControl;

    vector< SwFrameControlPtr >& aControls = m_aControls[HeaderFooter];

    vector< SwFrameControlPtr >::iterator pIt = aControls.begin();
    while ( pIt != aControls.end() && !pControl.get() )
    {
        SwHeaderFooterWin* pToTest = dynamic_cast< SwHeaderFooterWin* >( pIt->get() );
        if ( pToTest->GetPageFrame( ) == pPageFrm &&
             pToTest->IsHeader( ) == bHeader )
            pControl = *pIt;
        ++pIt;
    }

    if ( !pControl.get() )
    {
        SwFrameControlPtr pNewControl( new SwHeaderFooterWin( m_pEditWin, pPageFrm, bHeader ) );
        const SwViewOption* pViewOpt = m_pEditWin->GetView().GetWrtShell().GetViewOptions();
        pNewControl->SetReadonly( pViewOpt->IsReadonly() );
        AddControl( HeaderFooter, pNewControl );
        pControl.swap( pNewControl );
    }

    Rectangle aPageRect = m_pEditWin->LogicToPixel( pPageFrm->Frm().SVRect() );

    SwHeaderFooterWin* pHFWin = dynamic_cast< SwHeaderFooterWin* >( pControl.get() );
    pHFWin->SetOffset( aOffset, aPageRect.Left(), aPageRect.Right() );

    if ( !pHFWin->IsVisible() )
        pControl->ShowAll( true );
}

void SwFrameControlsManager::SetPageBreakControl( const SwPageFrm* pPageFrm )
{
    // Check if we already have the control
    SwFrameControlPtr pControl;

    vector< SwFrameControlPtr >& aControls = m_aControls[PageBreak];

    vector< SwFrameControlPtr >::iterator pIt = aControls.begin();
    while ( pIt != aControls.end() && !pControl.get() )
    {
        SwPageBreakWin* pToTest = dynamic_cast< SwPageBreakWin* >( pIt->get() );
        if ( pToTest->GetPageFrame( ) == pPageFrm )
            pControl = *pIt;
        ++pIt;
    }

    if ( !pControl.get() )
    {
        SwFrameControlPtr pNewControl( new SwPageBreakWin( m_pEditWin, pPageFrm ) );
        const SwViewOption* pViewOpt = m_pEditWin->GetView().GetWrtShell().GetViewOptions();
        pNewControl->SetReadonly( pViewOpt->IsReadonly() );
        AddControl( PageBreak, pNewControl );
        pControl.swap( pNewControl );
    }

    SwPageBreakWin* pWin = dynamic_cast< SwPageBreakWin* >( pControl.get() );
    pWin->UpdatePosition();
    if ( !pWin->IsVisible() )
        pControl->ShowAll( true );
}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|>


<commit_before>#include <ncurses.h>

#include "board.hpp"
#include "color.hpp"
#include "reversi.hpp"
using namespace roadagain;

int main()
{
    initscr();
    cbreak();
    noecho();
    Colors::init();

    Reversi reversi;
    reversi.start();
    reversi.play();
    getch();

    endwin();
    return (0);
}
<commit_msg>Hided cursor<commit_after>#include <ncurses.h>

#include "board.hpp"
#include "color.hpp"
#include "reversi.hpp"
using namespace roadagain;

int main()
{
    initscr();
    cbreak();
    noecho();
    curs_set(0);
    Colors::init();

    Reversi reversi;
    reversi.start();
    reversi.play();
    getch();

    endwin();
    return (0);
}
<|endoftext|>


<commit_before>

#include <iostream>
#include <vector>
#include <fstream>
using namespace std;

#ifdef _DEBUG
#include <vld.h>
#endif

#include <wiz/ClauText.h>

// rename?
bool IsEmpty(vector<int>& chk_brace, const string& str)
{
	for (int i = 0; i < str.size(); ++i) {
		if ('{' == str[i]) {
			chk_brace.push_back(0);
		}
		else if ('}' == str[i]) {
			if (chk_brace.empty()) {
				chk_brace.push_back(1);
				return false;
			}
			else {
				chk_brace.pop_back();
			}
		}
	}

	return chk_brace.empty();
}
void SaveWithOutEvent(ostream& stream, wiz::load_data::UserType* ut, int depth)
{
	int itemListCount = 0;
	int userTypeListCount = 0;

	for (int i = 0; i < ut->GetCommentListSize(); ++i) {
		for (int k = 0; k < depth; ++k) {
			stream << "\t";
		}
		stream << (ut->GetCommentList(i));

		if (i < ut->GetCommentListSize() - 1 || 0 == ut->GetIListSize()) {
			stream << "\n";
		}
	}

	for (int i = 0; i < ut->GetIListSize(); ++i) {
		//std::cout << "ItemList" << endl;
		if (ut->IsItemList(i)) {
			for (int j = 0; j < ut->GetItemList(itemListCount).size(); j++) {
				string temp;
				for (int k = 0; k < depth; ++k) {
					temp += "\t";
				}
				if (ut->GetItemList(itemListCount).GetName() != "") {
					temp += ut->GetItemList(itemListCount).GetName();
					temp += "=";
				}
				temp += ut->GetItemList(itemListCount).Get(j);
				if (j != ut->GetItemList(itemListCount).size() - 1) {
					temp += "\n";
				}
				stream << temp;
			}
			if (i != ut->GetIListSize() - 1) {
				stream << "\n";
			}
			itemListCount++;
		}
		else if (ut->IsUserTypeList(i)) {
			if (ut->GetUserTypeList(userTypeListCount)->GetName() == "Event"
				|| ut->GetUserTypeList(userTypeListCount)->GetName() == "Main") {
				userTypeListCount++;
				continue;
			}

			// std::cout << "UserTypeList" << endl;
			for (int k = 0; k < depth; ++k) {
				stream << "\t";
			}

			if (ut->GetUserTypeList(userTypeListCount)->GetName() != "") {
				stream << ut->GetUserTypeList(userTypeListCount)->GetName() << "=";
			}

			stream << "{\n";

			SaveWithOutEvent(stream, ut->GetUserTypeList(userTypeListCount), depth + 1);
			stream << "\n";

			for (int k = 0; k < depth; ++k) {
				stream << "\t";
			}
			stream << "}";
			if (i != ut->GetIListSize() - 1) {
				stream << "\n";
			}

			userTypeListCount++;
		}
	}
}

int main(void)
{
	wiz::load_data::UserType global;
	vector<int> chk_brace;
	string command;
	string totalCommand;

	while (true)
	{
		cout << "<< : "; //
		getline(cin, command);

		if (command.empty()) {
			continue;
		}

		if (!command.empty() && '$' == command[0]) {
			if ("$print" == command) {
				cout << ">> : global" << endl;
				//cout << global.ToString() << endl;
				global.Save1(cout);
				cout << endl;
			}
			else if ("$print_data_only" == command) {
				cout << ">> : global" << endl;
				SaveWithOutEvent(cout, &global, 0);
				cout << endl;
			}
			else if ("$exit" == command) {
				break;
			}
			else if ("$M" == command) {
				MStyleTest(&global);  // for windows!
				system("cls"); // for windows!

				gotoxy(0, 0);
				setcolor(7, 0);

				cout << ">> : $M end" << endl;
			}
			else if (wiz::String::startsWith(command, "$call"))
			{
				wiz::load_data::UserType test;

				try {
					if (wiz::load_data::LoadData::LoadDataFromString(command, test))
					{
						try {
							wiz::load_data:: UserType ut = global;
							const string id = test.GetItemList(0).Get(0);
							const string result = excute_module("Main = { $call = { id = " + id + "} }", &ut, ExcuteData(), 1);

							global = std::move(ut);
							cout << endl << "excute result is : " << result << endl;
						}
						catch (...) // any exception..
						{
							cout << ">> : $call id or excute module error" << endl;
						}
					}
					else {
						cout << ">> : $call Error" << endl;
					}
				}
				catch (...) {
					cout << ">> : $call load data from string error" << endl;
				}
			}
			else if (wiz::String::startsWith(command, "$load"))
			{
				wiz::load_data::UserType test;

				if (wiz::load_data::LoadData::LoadDataFromString(command, test))
				{
					try {
						const string name = test.GetItemList(0).Get(0);
						const string result = wiz::String::substring(name, 1, name.size() - 2);

						if (wiz::load_data::LoadData::LoadDataFromFile(result, global)) {}
						else {
							cout << ">> : load data from file error" << endl;
						}
					}
					catch (...) // any exception..
					{
						cout << ">> : load error" << endl;
					}
				}
				else {
					cout << ">> : $load syntax Error" << endl;
				}
			}
			else if (wiz::String::startsWith(command, "$save_event_only"))
			{
				wiz::load_data::UserType test;

				if (wiz::load_data::LoadData::LoadDataFromString(command, test))
				{
					ofstream outFile;

					try {
						const string name = test.GetItemList(0).Get(0);
						const string result = wiz::String::substring(name, 1, name.size() - 2);

						outFile.open(result);
						if (outFile.fail()) {
							//
						}
						else {
							for (int i = 0; i < global.GetUserTypeListSize(); ++i) {
								if (global.GetUserTypeList(i)->GetName() == "Event") {
									outFile << "Event = {\n";
									global.GetUserTypeList(i)->Save1(outFile, 1);
									outFile << "\n}\n";
								}
							}
							outFile.close();
						}
					}
					catch (...) // any exception..
					{
						if (outFile.is_open()) {
							outFile.close();
						}
						cout << ">> : $save_event_only error" << endl;
					}
				}
				else {
					cout << ">> : $save_event_only syntax Error" << endl;
				}
			}

			else if (wiz::String::startsWith(command, "$save_data_only"))
			{
				wiz::load_data::UserType test;

				if (wiz::load_data::LoadData::LoadDataFromString(command, test))
				{
					ofstream outFile;

					try {
						const string name = test.GetItemList(0).Get(0);
						const string result = wiz::String::substring(name, 1, name.size() - 2);

						outFile.open(result);
						if (outFile.fail()) {
							//
						}
						else {
							SaveWithOutEvent(outFile, &global, 0);
							outFile.close();
						}
					}
					catch (...) // any exception..
					{
						if (outFile.is_open()) {
							outFile.close();
						}
						cout << ">> : $save_data_only error" << endl;
					}
				}
			}
			else if (wiz::String::startsWith(command, "$save"))
			{
				wiz::load_data::UserType test;
				if (wiz::load_data::LoadData::LoadDataFromString(command, test))
				{
					const string name = test.GetItemList(0).Get(0);
					const string result = wiz::String::substring(name, 1, name.size() - 2);

					if (wiz::load_data::LoadData::SaveWizDB(global, result, "1")) {

					}
					else {
						cout << ">> : $save error" << endl;
					}
				}
				else {
					cout << ">> : $save syntax Error" << endl;
				}
			}
			else if ("$cls" == command) {
				system("cls"); // for windows!
			}
		}
		else {
			if (IsEmpty(chk_brace, command)) {
				command.append("\n");

				totalCommand.append(command);
				if (wiz::load_data::LoadData::LoadDataFromString(totalCommand, global)) {
					cout << ">> : Data Added!" << endl;
				}
				else {
					cout << ">> : Error : loaddata from string " << endl;
				}
				command = "";
				totalCommand = "";
			}
			else {
				if (chk_brace[0] == 1) {
					cout << ">> : Error in command, reset command" << endl;
					totalCommand = "";
					command = "";
					chk_brace.clear();
				}
				else {
					command.append("\n");

					totalCommand.append(command);
					command = "";
				}
			}
		}
	}

	return 0;
}

<commit_msg>using C++17<commit_after>

#include <iostream>
#include <vector>
#include <fstream>

#ifdef _DEBUG
#include <vld.h>
#endif

#include <wiz/ClauText.h>

// rename?
bool IsEmpty(std::vector<int>& chk_brace, const std::string& str)
{
	for (int i = 0; i < str.size(); ++i) {
		if ('{' == str[i]) {
			chk_brace.push_back(0);
		}
		else if ('}' == str[i]) {
			if (chk_brace.empty()) {
				chk_brace.push_back(1);
				return false;
			}
			else {
				chk_brace.pop_back();
			}
		}
	}

	return chk_brace.empty();
}
void SaveWithOutEvent(std::ostream& stream, wiz::load_data::UserType* ut, int depth)
{
	int itemListCount = 0;
	int userTypeListCount = 0;

	for (int i = 0; i < ut->GetCommentListSize(); ++i) {
		for (int k = 0; k < depth; ++k) {
			stream << "\t";
		}
		stream << (ut->GetCommentList(i));

		if (i < ut->GetCommentListSize() - 1 || 0 == ut->GetIListSize()) {
			stream << "\n";
		}
	}

	for (int i = 0; i < ut->GetIListSize(); ++i) {
		//std::cout << "ItemList" << endl;
		if (ut->IsItemList(i)) {
			for (int j = 0; j < ut->GetItemList(itemListCount).size(); j++) {
				std::string temp;
				for (int k = 0; k < depth; ++k) {
					temp += "\t";
				}
				if (ut->GetItemList(itemListCount).GetName() != "") {
					temp += ut->GetItemList(itemListCount).GetName();
					temp += "=";
				}
				temp += ut->GetItemList(itemListCount).Get(j);
				if (j != ut->GetItemList(itemListCount).size() - 1) {
					temp += "\n";
				}
				stream << temp;
			}
			if (i != ut->GetIListSize() - 1) {
				stream << "\n";
			}
			itemListCount++;
		}
		else if (ut->IsUserTypeList(i)) {
			if (ut->GetUserTypeList(userTypeListCount)->GetName() == "Event"
				|| ut->GetUserTypeList(userTypeListCount)->GetName() == "Main") {
				userTypeListCount++;
				continue;
			}

			// std::cout << "UserTypeList" << endl;
			for (int k = 0; k < depth; ++k) {
				stream << "\t";
			}

			if (ut->GetUserTypeList(userTypeListCount)->GetName() != "") {
				stream << ut->GetUserTypeList(userTypeListCount)->GetName() << "=";
			}

			stream << "{\n";

			SaveWithOutEvent(stream, ut->GetUserTypeList(userTypeListCount), depth + 1);
			stream << "\n";

			for (int k = 0; k < depth; ++k) {
				stream << "\t";
			}
			stream << "}";
			if (i != ut->GetIListSize() - 1) {
				stream << "\n";
			}

			userTypeListCount++;
		}
	}
}

int main(void)
{
	wiz::load_data::UserType global;
	std::vector<int> chk_brace;
	std::string command;
	std::string totalCommand;

	while (true)
	{
		std::cout << "<< : "; //
		std::getline(std::cin, command);

		if (command.empty()) {
			continue;
		}

		// Evnent = {
		//		$call = { id = 0 } # tab or 鿩!!
		if (!command.empty() && '$' == command[0]) {
			if ("$print" == command) {
				std::cout << ">> : global" << std::endl;
				//cout << global.ToString() << endl;
				global.Save1(std::cout);
				std::cout << std::endl;
			}
			else if ("$print_data_only" == command) {
				std::cout << ">> : global" << std::endl;
				SaveWithOutEvent(std::cout, &global, 0);
				std::cout << std::endl;
			}
			else if ("$exit" == command) {
				break;
			}
			else if ("$M" == command) {
				MStyleTest(&global);  // for windows!
				system("cls"); // for windows!

				gotoxy(0, 0);
				setcolor(7, 0);

				std::cout << ">> : $M end" << std::endl;
			}
			else if (wiz::String::startsWith(command, "$call"))
			{
				wiz::load_data::UserType test;

				try {
					if (wiz::load_data::LoadData::LoadDataFromString(command, test))
					{
						try {
							wiz::load_data:: UserType ut = global;
							const std::string id = test.GetItemList(0).Get(0);
							const std::string result = excute_module("Main = { $call = { id = " + id + "} }", &ut, ExcuteData(), 1);

							global = std::move(ut);
							std::cout << std::endl << "excute result is : " << result << std::endl;
						}
						catch (...) // any exception..
						{
							std::cout << ">> : $call id or excute module error" << std::endl;
						}
					}
					else {
						std::cout << ">> : $call Error" << std::endl;
					}
				}
				catch (...) {
					std::cout << ">> : $call load data from string error" << std::endl;
				}
			}
			else if (wiz::String::startsWith(command, "$load"))
			{
				wiz::load_data::UserType test;

				if (wiz::load_data::LoadData::LoadDataFromString(command, test))
				{
					try {
						const std::string name = test.GetItemList(0).Get(0);
						const std::string result = wiz::String::substring(name, 1, name.size() - 2);

						if (wiz::load_data::LoadData::LoadDataFromFile(result, global)) {}
						else {
							std::cout << ">> : load data from file error" << std::endl;
						}
					}
					catch (...) // any exception..
					{
						std::cout << ">> : load error" << std::endl;
					}
				}
				else {
					std::cout << ">> : $load syntax Error" << std::endl;
				}
			}
			else if (wiz::String::startsWith(command, "$save_event_only"))
			{
				wiz::load_data::UserType test;

				if (wiz::load_data::LoadData::LoadDataFromString(command, test))
				{
					std::ofstream outFile;

					try {
						const std::string name = test.GetItemList(0).Get(0);
						const std::string result = wiz::String::substring(name, 1, name.size() - 2);

						outFile.open(result);
						if (outFile.fail()) {
							//
						}
						else {
							for (int i = 0; i < global.GetUserTypeListSize(); ++i) {
								if (global.GetUserTypeList(i)->GetName() == "Event") {
									outFile << "Event = {\n";
									global.GetUserTypeList(i)->Save1(outFile, 1);
									outFile << "\n}\n";
								}
							}
							outFile.close();
						}
					}
					catch (...) // any exception..
					{
						if (outFile.is_open()) {
							outFile.close();
						}
						std::cout << ">> : $save_event_only error" << std::endl;
					}
				}
				else {
					std::cout << ">> : $save_event_only syntax Error" << std::endl;
				}
			}

			else if (wiz::String::startsWith(command, "$save_data_only"))
			{
				wiz::load_data::UserType test;

				if (wiz::load_data::LoadData::LoadDataFromString(command, test))
				{
					std::ofstream outFile;

					try {
						const std::string name = test.GetItemList(0).Get(0);
						const std::string result = wiz::String::substring(name, 1, name.size() - 2);

						outFile.open(result);
						if (outFile.fail()) {
							//
						}
						else {
							SaveWithOutEvent(outFile, &global, 0);
							outFile.close();
						}
					}
					catch (...) // any exception..
					{
						if (outFile.is_open()) {
							outFile.close();
						}
						std::cout << ">> : $save_data_only error" << std::endl;
					}
				}
			}
			else if (wiz::String::startsWith(command, "$save"))
			{
				wiz::load_data::UserType test;
				if (wiz::load_data::LoadData::LoadDataFromString(command, test))
				{
					const std::string name = test.GetItemList(0).Get(0);
					const std::string result = wiz::String::substring(name, 1, name.size() - 2);

					if (wiz::load_data::LoadData::SaveWizDB(global, result, "1")) {

					}
					else {
						std::cout << ">> : $save error" << std::endl;
					}
				}
				else {
					std::cout << ">> : $save syntax Error" << std::endl;
				}
			}
			else if ("$cls" == command) {
				system("cls"); // for windows!
			}
		}
		else {
			if (IsEmpty(chk_brace, command)) {
				command.append("\n");

				totalCommand.append(command);
				if (wiz::load_data::LoadData::LoadDataFromString(totalCommand, global)) {
					std::cout << ">> : Data Added!" << std::endl;
				}
				else {
					std::cout << ">> : Error : loaddata from string " << std::endl;
				}
				command = "";
				totalCommand = "";
			}
			else {
				if (chk_brace[0] == 1) {
					std::cout << ">> : Error in command, reset command" << std::endl;
					totalCommand = "";
					command = "";
					chk_brace.clear();
				}
				else {
					command.append("\n");

					totalCommand.append(command);
					command = "";
				}
			}
		}
	}

	return 0;
}

<|endoftext|>


<commit_before>int main() {}
<commit_msg>Began work on parser.<commit_after>#include <iostream>

int main(int argc, char** argv) {
	if (argc == 1) {
		std::cout << argv[0] << " takes 1 argument." << std::endl;
		std::cout << "Please pass the name of a file to read from." << std::endl;
	}
}
<|endoftext|>


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

template<class Derived, typename Delegate>
class using_;

template<class Derived, typename Delegate>
auto DerivedType(using_<Derived, Delegate> &) -> Derived;

template<class Derived, typename Delegate>
auto DelegateType(using_<Derived, Delegate> &) -> Delegate;

template<class Base>
auto &delegate(Base &base)
{
    using Derived = decltype(DerivedType(base));

    //! Downcast to the derived class
    auto &derived = static_cast<Derived &>(base);

    using Delegate = decltype(DelegateType(base));

    //! Now invoke the conversion operator
    return static_cast<Delegate &>(derived);
}

template<class Class, typename... T>
struct DelayedImpl
{
    using type = Class;
};

template<class Class, typename... T>
using Delayed = typename DelayedImpl<Class, T...>::type;

#define MEMBER(member)                                                                          \
    template<typename... T>                                                                     \
    auto member(T &&... args) -> decltype(DelegateType(std::declval<Delayed<decltype(*this), T...>>()).member(std::forward<T>(args)...)) \
    {                                                                                \
        return delegate(*this).member(std::forward<T>(args)...);                                \
    }                                                                                \

template<class Derived, typename Delegate>
class using_
{
public:
    MEMBER(push_back)
    MEMBER(begin)
    MEMBER(end)
};

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

private:
    T data;
};

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

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

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

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

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

    auto z = x + y;

    std::cout << z << std::endl;
    std::cout << typeid(z).name() << std::endl;
}
<commit_msg>Added a static assertion.<commit_after>#include <iostream>
#include <vector>

template<class Derived, typename Delegate>
class using_;

template<class Derived, typename Delegate>
auto DerivedType(using_<Derived, Delegate> &) -> Derived;

template<class Derived, typename Delegate>
auto DelegateType(using_<Derived, Delegate> &) -> Delegate;

template<class Base>
auto &delegate(Base &base)
{
    using Derived = decltype(DerivedType(base));
    static_assert(std::is_base_of_v<Base, Derived>);

    //! Downcast to the derived class
    auto &derived = static_cast<Derived &>(base);

    using Delegate = decltype(DelegateType(base));

    //! Now invoke the conversion operator
    return static_cast<Delegate &>(derived);
}

template<class Class, typename... T>
struct DelayedImpl
{
    using type = Class;
};

template<class Class, typename... T>
using Delayed = typename DelayedImpl<Class, T...>::type;

#define MEMBER(member)                                                                          \
    template<typename... T>                                                                     \
    auto member(T &&... args) -> decltype(DelegateType(std::declval<Delayed<decltype(*this), T...>>()).member(std::forward<T>(args)...)) \
    {                                                                                \
        return delegate(*this).member(std::forward<T>(args)...);                                \
    }                                                                                \

template<class Derived, typename Delegate>
class using_
{
public:
    MEMBER(push_back)
    MEMBER(begin)
    MEMBER(end)
};

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

private:
    T data;
};

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

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

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

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

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

    auto z = x + y;

    std::cout << z << std::endl;
    std::cout << typeid(z).name() << std::endl;
}
<|endoftext|>


<commit_before>#include <cstring>
#include <iostream>
#include "permuter.cpp"
#include "param.cpp"
#include "options.cpp"

#define ENDL "\n"

using namespace std;

void showIntro() {
    cout << "Dictionary Generator v1.0 - by Miguel Espinoza - http://purefan.me" << ENDL;
    cout << ENDL;
    cout << "| This program takes words from a file and permutes them into a  |" << ENDL;
    cout << "| dictionary that can be used in brute force attacks.            |" << ENDL;
    cout << "| Intended only for educational purposes, do not use it for evil |" << ENDL;
    cout << "| By using this software you agree to release the author(s) from |" << ENDL;
    cout << "| any liability and responsibility.                              |" << ENDL;
    cout << ENDL;
}

/**
 * KISS Require 2 params
 */
int main(int argc, char *argv[]) {
    showIntro();

    Param num_range_from = Param();
    num_range_from.setDescription("Tells from which number to start");
    num_range_from.setShortForm('s');
    num_range_from.setLongForm("num-range-from");

    Param num_range_to = Param();
    num_range_to.setDescription("Tells the maximum number to be used in the range");
    num_range_to.setShortForm('w');
    num_range_to.setLongForm("mix-words");

    Param lower_case = Param();
    lower_case.setDescription("Converts every character to lower case: BALL -> [bALL, BaLL, BAlL, BALl, baLL, BalL, BAll, balL, Ball, ball]");
    lower_case.setShortForm('l');
    lower_case.setLongForm("lower-case");

    Param upper_case = Param();
    upper_case.setDescription("Converts every character to upper case: ball -> [Ball, bAll, baLl, balL, BAll, bALl, baLL, BALl, bALL, BALL]");
    upper_case.setShortForm('u');
    upper_case.setLongForm("upper-case");

    Param mix_case = Param();
    mix_case.setDescription("Combines upper and lower cases in every possible way");
    mix_case.setShortForm('m');
    mix_case.setLongForm("mixed-case");

    Param add_numbers_beginning = Param();
    add_numbers_beginning.setDescription("Adds leading numbers to the beginning of the word. Requires the params \"num-range-from\" and \"num-range-to\": BALL -> [0BALL, 1BALL, 2BALL, 3BALL, 4BALL, ...]");
    add_numbers_beginning.setShortForm('n');
    add_numbers_beginning.setLongForm("leading-numbers");
    add_numbers_beginning.setRequires(num_range_from);
    add_numbers_beginning.setRequires(num_range_to);

    Param add_numbers_end = Param();
    add_numbers_end.setDescription("Adds trailing numbers to the end of the word. Requires the params \"num-range-from\" and \"num-range-to\": BALL -> [BALL0, BALL1, BALL2, BALL3, BALL4, ...]");
    add_numbers_end.setShortForm('N');
    add_numbers_end.setLongForm("trailing-numbers");
    add_numbers_end.setRequires(num_range_from);
    add_numbers_end.setRequires(num_range_to);

    Param add_numbers_in_between = Param();
    add_numbers_in_between.setDescription("Adds numbers between each letter. Requires the params \"num-range-from\" and \"num-range-to\": BALL -> [B0ALL, BA0LL, BAL0L, B1ALL, BA1LL, ...]");
    add_numbers_in_between.setShortForm('i');
    add_numbers_in_between.setLongForm("numbers-between");
    add_numbers_in_between.setRequires(num_range_from);
    add_numbers_in_between.setRequires(num_range_to);

    Param mix_words = Param();
    mix_words.setDescription("Mixes words from the source file: [hello, bye, red] -> [hellobye, byehello, hellored, redhello, byered, redbye]");
    mix_words.setShortForm('w');
    mix_words.setLongForm("mix-words");

    Param source_file = Param();
    source_file.setDescription("Tells which file has the words that will be permuted.");
    source_file.setShortForm('f');
    source_file.setLongForm("source-file");
    source_file.setAllowEmpty();

    Param target_file = Param();
    target_file.setDescription("Tells which file will store the permuted words.");
    target_file.setShortForm('t');
    target_file.setLongForm("target-file");
    target_file.setAllowEmpty();

    std::vector<std::string> arguments(argv + 1, argv + argc);
    Options main_options = Options();
    main_options.addParam(lower_case);
    main_options.addParam(upper_case);
    main_options.addParam(mix_case);
    main_options.addParam(add_numbers_beginning);
    main_options.addParam(add_numbers_end);
    main_options.addParam(add_numbers_in_between);
    main_options.addParam(mix_words);
    main_options.addParam(source_file);
    main_options.addParam(target_file);
    main_options.registerArgs(arguments);

    // SUPER important
    std::locale::global(std::locale("sv_SE"));

    if (main_options.areParamsOk()) {
        if (main_options.hasCommands()) {
            main_options.runCommands();
        } else {
            Permuter myPermuter = Permuter();
            myPermuter.setOptions(main_options);

            if (myPermuter.allGood() == true) {
                myPermuter.run();
            }
        }
    }

    return 0;
}<commit_msg>Bug: Use a different long name<commit_after>#include <cstring>
#include <iostream>
#include "permuter.cpp"
#include "param.cpp"
#include "options.cpp"

#define ENDL "\n"

using namespace std;

void showIntro() {
    cout << "Dictionary Generator v1.0 - by Miguel Espinoza - http://purefan.me" << ENDL;
    cout << ENDL;
    cout << "| This program takes words from a file and permutes them into a  |" << ENDL;
    cout << "| dictionary that can be used in brute force attacks.            |" << ENDL;
    cout << "| Intended only for educational purposes, do not use it for evil |" << ENDL;
    cout << "| By using this software you agree to release the author(s) from |" << ENDL;
    cout << "| any liability and responsibility.                              |" << ENDL;
    cout << ENDL;
}

/**
 * KISS Require 2 params
 */
int main(int argc, char *argv[]) {
    showIntro();

    Param num_range_from = Param();
    num_range_from.setDescription("Tells from which number to start");
    num_range_from.setShortForm('s');
    num_range_from.setLongForm("num-range-from");

    Param num_range_to = Param();
    num_range_to.setDescription("Tells the maximum number to be used in the range");
    num_range_to.setShortForm('w');
    num_range_to.setLongForm("num-range-to");

    Param lower_case = Param();
    lower_case.setDescription("Converts every character to lower case: BALL -> [bALL, BaLL, BAlL, BALl, baLL, BalL, BAll, balL, Ball, ball]");
    lower_case.setShortForm('l');
    lower_case.setLongForm("lower-case");

    Param upper_case = Param();
    upper_case.setDescription("Converts every character to upper case: ball -> [Ball, bAll, baLl, balL, BAll, bALl, baLL, BALl, bALL, BALL]");
    upper_case.setShortForm('u');
    upper_case.setLongForm("upper-case");

    Param mix_case = Param();
    mix_case.setDescription("Combines upper and lower cases in every possible way");
    mix_case.setShortForm('m');
    mix_case.setLongForm("mixed-case");

    Param add_numbers_beginning = Param();
    add_numbers_beginning.setDescription("Adds leading numbers to the beginning of the word. Requires the params \"num-range-from\" and \"num-range-to\": BALL -> [0BALL, 1BALL, 2BALL, 3BALL, 4BALL, ...]");
    add_numbers_beginning.setShortForm('n');
    add_numbers_beginning.setLongForm("leading-numbers");
    add_numbers_beginning.setRequires(num_range_from);
    add_numbers_beginning.setRequires(num_range_to);

    Param add_numbers_end = Param();
    add_numbers_end.setDescription("Adds trailing numbers to the end of the word. Requires the params \"num-range-from\" and \"num-range-to\": BALL -> [BALL0, BALL1, BALL2, BALL3, BALL4, ...]");
    add_numbers_end.setShortForm('N');
    add_numbers_end.setLongForm("trailing-numbers");
    add_numbers_end.setRequires(num_range_from);
    add_numbers_end.setRequires(num_range_to);

    Param add_numbers_in_between = Param();
    add_numbers_in_between.setDescription("Adds numbers between each letter. Requires the params \"num-range-from\" and \"num-range-to\": BALL -> [B0ALL, BA0LL, BAL0L, B1ALL, BA1LL, ...]");
    add_numbers_in_between.setShortForm('i');
    add_numbers_in_between.setLongForm("numbers-between");
    add_numbers_in_between.setRequires(num_range_from);
    add_numbers_in_between.setRequires(num_range_to);

    Param mix_words = Param();
    mix_words.setDescription("Mixes words from the source file: [hello, bye, red] -> [hellobye, byehello, hellored, redhello, byered, redbye]");
    mix_words.setShortForm('w');
    mix_words.setLongForm("mix-words");

    Param source_file = Param();
    source_file.setDescription("Tells which file has the words that will be permuted.");
    source_file.setShortForm('f');
    source_file.setLongForm("source-file");
    source_file.setAllowEmpty();

    Param target_file = Param();
    target_file.setDescription("Tells which file will store the permuted words.");
    target_file.setShortForm('t');
    target_file.setLongForm("target-file");
    target_file.setAllowEmpty();

    std::vector<std::string> arguments(argv + 1, argv + argc);
    Options main_options = Options();
    main_options.addParam(lower_case);
    main_options.addParam(upper_case);
    main_options.addParam(mix_case);
    main_options.addParam(add_numbers_beginning);
    main_options.addParam(add_numbers_end);
    main_options.addParam(add_numbers_in_between);
    main_options.addParam(mix_words);
    main_options.addParam(source_file);
    main_options.addParam(target_file);
    main_options.registerArgs(arguments);

    // SUPER important
    std::locale::global(std::locale("sv_SE"));

    if (main_options.areParamsOk()) {
        if (main_options.hasCommands()) {
            main_options.runCommands();
        } else {
            Permuter myPermuter = Permuter();
            myPermuter.setOptions(main_options);

            if (myPermuter.allGood() == true) {
                myPermuter.run();
            }
        }
    }

    return 0;
}<|endoftext|>


<commit_before>#include "mdns.hpp"

#include <v8.h>

#include "mdns_utils.hpp"
#include "dns_service_ref.hpp"
#include "txt_record_ref.hpp"
#ifdef NODE_MDNS_USE_SOCKET_WATCHER
# include "socket_watcher.hpp"
#endif

using namespace v8;
using namespace node;

namespace node_mdns {

// === dns_sd ===========================================
NAN_METHOD(DNSServiceRegister);
NAN_METHOD(DNSServiceRefSockFD);
NAN_METHOD(DNSServiceProcessResult);
NAN_METHOD(DNSServiceBrowse);
NAN_METHOD(DNSServiceRefDeallocate);
NAN_METHOD(DNSServiceResolve);
NAN_METHOD(DNSServiceEnumerateDomains);
#ifdef HAVE_DNSSERVICEGETADDRINFO
NAN_METHOD(DNSServiceGetAddrInfo);
#endif
NAN_METHOD(TXTRecordCreate);
NAN_METHOD(TXTRecordDeallocate);
//NAN_METHOD(TXTRecordGetCount);
NAN_METHOD(TXTRecordSetValue);
NAN_METHOD(TXTRecordGetLength);

// === posix ============================================
#ifdef NODE_MDNS_HAVE_INTERFACE_NAME_CONVERSION
NAN_METHOD(if_nametoindex);
NAN_METHOD(if_indextoname);
#endif

// === additions ========================================
NAN_METHOD(txtRecordBufferToObject);
NAN_METHOD(exportConstants);
NAN_METHOD(buildException);

// === locals ===========================================

void defineFunction(Handle<Object> target, const char * name, NanFunctionCallback f);
void addConstants(Handle<Object> target);

void
init(Handle<Object> target) {
    NanScope();

    ServiceRef::Initialize( target );
    TxtRecordRef::Initialize( target );
#ifdef NODE_MDNS_USE_SOCKET_WATCHER
    SocketWatcher::Initialize( target );
#endif

    defineFunction(target, "DNSServiceRegister", DNSServiceRegister);
    defineFunction(target, "DNSServiceRefSockFD", DNSServiceRefSockFD);
    defineFunction(target, "DNSServiceProcessResult", DNSServiceProcessResult);
    defineFunction(target, "DNSServiceBrowse", DNSServiceBrowse);
    defineFunction(target, "DNSServiceRefDeallocate", DNSServiceRefDeallocate);
    defineFunction(target, "DNSServiceResolve", DNSServiceResolve);
    defineFunction(target, "DNSServiceEnumerateDomains",
            DNSServiceEnumerateDomains);
#ifdef HAVE_DNSSERVICEGETADDRINFO
    defineFunction(target, "DNSServiceGetAddrInfo", DNSServiceGetAddrInfo);
#endif
    defineFunction(target, "TXTRecordCreate", TXTRecordCreate);
    defineFunction(target, "TXTRecordDeallocate", TXTRecordDeallocate);
    //defineFunction(target, "TXTRecordGetCount", TXTRecordGetCount);
    defineFunction(target, "TXTRecordSetValue", TXTRecordSetValue);
    defineFunction(target, "TXTRecordGetLength", TXTRecordGetLength);

#ifdef NODE_MDNS_HAVE_INTERFACE_NAME_CONVERSION
    defineFunction(target, "if_nametoindex", if_nametoindex);
    defineFunction(target, "if_indextoname", if_indextoname);
#endif

    defineFunction(target, "txtRecordBufferToObject", txtRecordBufferToObject);
    defineFunction(target, "buildException", buildException);
    defineFunction(target, "exportConstants", exportConstants);

    addConstants(target);
}

inline
void
defineFunction(Handle<Object> target, const char * name, NanFunctionCallback f) {
    target->Set(NanNew(name),
            NanNew<FunctionTemplate>(f)->GetFunction());
}

NAN_METHOD(buildException) {
    NanScope();
    if (argumentCountMismatch(args, 1)) {
        NanReturnValue(throwArgumentCountMismatchException(args, 1));
    }
    if ( ! args[0]->IsInt32()) {
        NanReturnValue(throwTypeError("argument 1 must be an integer "
                "(DNSServiceErrorType)"));
    }

    DNSServiceErrorType error = args[0]->Int32Value();
    NanReturnValue(buildException(error));
}

void
addConstants(Handle<Object> target) {
    // DNS Classes
    NODE_DEFINE_CONSTANT(target, kDNSServiceClass_IN);

    // DNS Error Codes
    NODE_DEFINE_CONSTANT(target, kDNSServiceErr_NoError);
    NODE_DEFINE_CONSTANT(target, kDNSServiceErr_Unknown);
    NODE_DEFINE_CONSTANT(target, kDNSServiceErr_NoSuchName);
    NODE_DEFINE_CONSTANT(target, kDNSServiceErr_NoMemory);
    NODE_DEFINE_CONSTANT(target, kDNSServiceErr_BadParam);
    NODE_DEFINE_CONSTANT(target, kDNSServiceErr_BadReference);
    NODE_DEFINE_CONSTANT(target, kDNSServiceErr_BadState);
    NODE_DEFINE_CONSTANT(target, kDNSServiceErr_BadFlags);
    NODE_DEFINE_CONSTANT(target, kDNSServiceErr_Unsupported);
    NODE_DEFINE_CONSTANT(target, kDNSServiceErr_NotInitialized);
    NODE_DEFINE_CONSTANT(target, kDNSServiceErr_AlreadyRegistered);
    NODE_DEFINE_CONSTANT(target, kDNSServiceErr_NameConflict);
    NODE_DEFINE_CONSTANT(target, kDNSServiceErr_Invalid);
    NODE_DEFINE_CONSTANT(target, kDNSServiceErr_Firewall);
    NODE_DEFINE_CONSTANT(target, kDNSServiceErr_Incompatible);
    NODE_DEFINE_CONSTANT(target, kDNSServiceErr_BadInterfaceIndex);
    NODE_DEFINE_CONSTANT(target, kDNSServiceErr_Refused);
    NODE_DEFINE_CONSTANT(target, kDNSServiceErr_NoSuchRecord);
    NODE_DEFINE_CONSTANT(target, kDNSServiceErr_NoAuth);
    NODE_DEFINE_CONSTANT(target, kDNSServiceErr_NoSuchKey);
    NODE_DEFINE_CONSTANT(target, kDNSServiceErr_NATTraversal);
    NODE_DEFINE_CONSTANT(target, kDNSServiceErr_DoubleNAT);
    NODE_DEFINE_CONSTANT(target, kDNSServiceErr_BadTime);
#ifdef kDNSServiceErr_BadSig
    NODE_DEFINE_CONSTANT(target, kDNSServiceErr_BadSig);
#endif
#ifdef kDNSServiceErr_BadKey
    NODE_DEFINE_CONSTANT(target, kDNSServiceErr_BadKey);
#endif
#ifdef kDNSServiceErr_Transient
    NODE_DEFINE_CONSTANT(target, kDNSServiceErr_Transient);
#endif
#ifdef kDNSServiceErr_ServiceNotRunning
    NODE_DEFINE_CONSTANT(target, kDNSServiceErr_ServiceNotRunning);
#endif
#ifdef kDNSServiceErr_NATPortMappingUnsupported
    NODE_DEFINE_CONSTANT(target, kDNSServiceErr_NATPortMappingUnsupported);
#endif
#ifdef kDNSServiceErr_NATPortMappingDisabled
    NODE_DEFINE_CONSTANT(target, kDNSServiceErr_NATPortMappingDisabled);
#endif
#ifdef kDNSServiceErr_NoRouter
    NODE_DEFINE_CONSTANT(target, kDNSServiceErr_NoRouter);
#endif
#ifdef kDNSServiceErr_PollingMode
    NODE_DEFINE_CONSTANT(target, kDNSServiceErr_PollingMode);
#endif

    // Interface Index
#ifdef kDNSServiceInterfaceIndexAny
    NODE_DEFINE_CONSTANT(target, kDNSServiceInterfaceIndexAny);
#endif
#ifdef kDNSServiceInterfaceIndexLocalOnly
    NODE_DEFINE_CONSTANT(target, kDNSServiceInterfaceIndexLocalOnly);
#endif
#ifdef kDNSServiceInterfaceIndexP2P
    NODE_DEFINE_CONSTANT(target, kDNSServiceInterfaceIndexP2P);
#endif
#ifdef kDNSServiceInterfaceIndexUnicast
    NODE_DEFINE_CONSTANT(target, kDNSServiceInterfaceIndexUnicast);
#endif

    // DNS Service Types
    NODE_DEFINE_CONSTANT(target, kDNSServiceType_A);
    NODE_DEFINE_CONSTANT(target, kDNSServiceType_NS);
    NODE_DEFINE_CONSTANT(target, kDNSServiceType_MD);
    NODE_DEFINE_CONSTANT(target, kDNSServiceType_MF);
    NODE_DEFINE_CONSTANT(target, kDNSServiceType_CNAME);
    NODE_DEFINE_CONSTANT(target, kDNSServiceType_SOA);
    NODE_DEFINE_CONSTANT(target, kDNSServiceType_MB);
    NODE_DEFINE_CONSTANT(target, kDNSServiceType_MG);
    NODE_DEFINE_CONSTANT(target, kDNSServiceType_MR);
    NODE_DEFINE_CONSTANT(target, kDNSServiceType_NULL);
    NODE_DEFINE_CONSTANT(target, kDNSServiceType_WKS);
    NODE_DEFINE_CONSTANT(target, kDNSServiceType_PTR);
    NODE_DEFINE_CONSTANT(target, kDNSServiceType_HINFO);
    NODE_DEFINE_CONSTANT(target, kDNSServiceType_MINFO);
    NODE_DEFINE_CONSTANT(target, kDNSServiceType_MX);
    NODE_DEFINE_CONSTANT(target, kDNSServiceType_TXT);
    NODE_DEFINE_CONSTANT(target, kDNSServiceType_RP);
    NODE_DEFINE_CONSTANT(target, kDNSServiceType_AFSDB);
    NODE_DEFINE_CONSTANT(target, kDNSServiceType_X25);
    NODE_DEFINE_CONSTANT(target, kDNSServiceType_ISDN);
    NODE_DEFINE_CONSTANT(target, kDNSServiceType_RT);
    NODE_DEFINE_CONSTANT(target, kDNSServiceType_NSAP);
    NODE_DEFINE_CONSTANT(target, kDNSServiceType_NSAP_PTR);
    NODE_DEFINE_CONSTANT(target, kDNSServiceType_SIG);
    NODE_DEFINE_CONSTANT(target, kDNSServiceType_KEY);
    NODE_DEFINE_CONSTANT(target, kDNSServiceType_PX);
    NODE_DEFINE_CONSTANT(target, kDNSServiceType_GPOS);
    NODE_DEFINE_CONSTANT(target, kDNSServiceType_AAAA);
    NODE_DEFINE_CONSTANT(target, kDNSServiceType_LOC);
    NODE_DEFINE_CONSTANT(target, kDNSServiceType_NXT);
    NODE_DEFINE_CONSTANT(target, kDNSServiceType_EID);
    NODE_DEFINE_CONSTANT(target, kDNSServiceType_NIMLOC);
    NODE_DEFINE_CONSTANT(target, kDNSServiceType_SRV);
    NODE_DEFINE_CONSTANT(target, kDNSServiceType_ATMA);
    NODE_DEFINE_CONSTANT(target, kDNSServiceType_NAPTR);
    NODE_DEFINE_CONSTANT(target, kDNSServiceType_KX);
    NODE_DEFINE_CONSTANT(target, kDNSServiceType_CERT);
    NODE_DEFINE_CONSTANT(target, kDNSServiceType_A6);
    NODE_DEFINE_CONSTANT(target, kDNSServiceType_DNAME);
    NODE_DEFINE_CONSTANT(target, kDNSServiceType_SINK);
    NODE_DEFINE_CONSTANT(target, kDNSServiceType_OPT);
#ifdef kDNSServiceType_APL
    NODE_DEFINE_CONSTANT(target, kDNSServiceType_APL);
#endif
#ifdef kDNSServiceType_DS
    NODE_DEFINE_CONSTANT(target, kDNSServiceType_DS);
#endif
#ifdef kDNSServiceType_SSHFP
    NODE_DEFINE_CONSTANT(target, kDNSServiceType_SSHFP);
#endif
#ifdef kDNSServiceType_IPSECKEY
    NODE_DEFINE_CONSTANT(target, kDNSServiceType_IPSECKEY);
#endif
#ifdef kDNSServiceType_RRSIG
    NODE_DEFINE_CONSTANT(target, kDNSServiceType_RRSIG);
#endif
#ifdef kDNSServiceType_NSEC
    NODE_DEFINE_CONSTANT(target, kDNSServiceType_NSEC);
#endif
#ifdef kDNSServiceType_DNSKEY
    NODE_DEFINE_CONSTANT(target, kDNSServiceType_DNSKEY);
#endif
#ifdef kDNSServiceType_DHCID
    NODE_DEFINE_CONSTANT(target, kDNSServiceType_DHCID);
#endif
#ifdef kDNSServiceType_NSEC3
    NODE_DEFINE_CONSTANT(target, kDNSServiceType_NSEC3);
#endif
#ifdef kDNSServiceType_NSEC3PARAM
    NODE_DEFINE_CONSTANT(target, kDNSServiceType_NSEC3PARAM);
#endif
#ifdef kDNSServiceType_HIP
    NODE_DEFINE_CONSTANT(target, kDNSServiceType_HIP);
#endif
#ifdef kDNSServiceType_SPF
    NODE_DEFINE_CONSTANT(target, kDNSServiceType_SPF);
#endif
#ifdef kDNSServiceType_UINFO
    NODE_DEFINE_CONSTANT(target, kDNSServiceType_UINFO);
#endif
#ifdef kDNSServiceType_UID
    NODE_DEFINE_CONSTANT(target, kDNSServiceType_UID);
#endif
#ifdef kDNSServiceType_GID
    NODE_DEFINE_CONSTANT(target, kDNSServiceType_GID);
#endif
#ifdef kDNSServiceType_UNSPEC
    NODE_DEFINE_CONSTANT(target, kDNSServiceType_UNSPEC);
#endif
    NODE_DEFINE_CONSTANT(target, kDNSServiceType_TKEY);
    NODE_DEFINE_CONSTANT(target, kDNSServiceType_TSIG);
    NODE_DEFINE_CONSTANT(target, kDNSServiceType_IXFR);
    NODE_DEFINE_CONSTANT(target, kDNSServiceType_AXFR);
    NODE_DEFINE_CONSTANT(target, kDNSServiceType_MAILB);
    NODE_DEFINE_CONSTANT(target, kDNSServiceType_MAILA);
    NODE_DEFINE_CONSTANT(target, kDNSServiceType_ANY);

    // General Flags
    NODE_DEFINE_CONSTANT(target, kDNSServiceFlagsMoreComing);
    NODE_DEFINE_CONSTANT(target, kDNSServiceFlagsAdd);
    NODE_DEFINE_CONSTANT(target, kDNSServiceFlagsDefault);
    NODE_DEFINE_CONSTANT(target, kDNSServiceFlagsNoAutoRename);
    NODE_DEFINE_CONSTANT(target, kDNSServiceFlagsShared);
    NODE_DEFINE_CONSTANT(target, kDNSServiceFlagsUnique);
    NODE_DEFINE_CONSTANT(target, kDNSServiceFlagsBrowseDomains);
    NODE_DEFINE_CONSTANT(target, kDNSServiceFlagsRegistrationDomains);
    NODE_DEFINE_CONSTANT(target, kDNSServiceFlagsLongLivedQuery);
    NODE_DEFINE_CONSTANT(target, kDNSServiceFlagsAllowRemoteQuery);
    NODE_DEFINE_CONSTANT(target, kDNSServiceFlagsForceMulticast);
#ifdef kDNSServiceFlagsForce
    NODE_DEFINE_CONSTANT(target, kDNSServiceFlagsForce);
#endif
#ifdef kDNSServiceFlagsReturnIntermediates
    NODE_DEFINE_CONSTANT(target, kDNSServiceFlagsReturnIntermediates);
#endif
#ifdef kDNSServiceFlagsNonBrowsable
    NODE_DEFINE_CONSTANT(target, kDNSServiceFlagsNonBrowsable);
#endif
#ifdef kDNSServiceFlagsShareConnection
    NODE_DEFINE_CONSTANT(target, kDNSServiceFlagsShareConnection);
#endif
#ifdef kDNSServiceFlagsSuppressUnusable
    NODE_DEFINE_CONSTANT(target, kDNSServiceFlagsSuppressUnusable);
#endif
}

NAN_METHOD(exportConstants) {
    NanScope();
    if (argumentCountMismatch(args, 1)) {
        NanReturnValue(throwArgumentCountMismatchException(args, 1));
    }
    if ( ! args[0]->IsObject()) {
        NanReturnValue(throwTypeError("argument 1 must be an object."));
    }

    addConstants(args[0]->ToObject());
    NanReturnUndefined();
}

} // end of namespace node_mdns

NODE_MODULE(dns_sd_bindings,node_mdns::init);
<commit_msg>adding v4v6<commit_after>#include "mdns.hpp"

#include <v8.h>

#include "mdns_utils.hpp"
#include "dns_service_ref.hpp"
#include "txt_record_ref.hpp"
#ifdef NODE_MDNS_USE_SOCKET_WATCHER
# include "socket_watcher.hpp"
#endif

using namespace v8;
using namespace node;

namespace node_mdns {

// === dns_sd ===========================================
NAN_METHOD(DNSServiceRegister);
NAN_METHOD(DNSServiceRefSockFD);
NAN_METHOD(DNSServiceProcessResult);
NAN_METHOD(DNSServiceBrowse);
NAN_METHOD(DNSServiceRefDeallocate);
NAN_METHOD(DNSServiceResolve);
NAN_METHOD(DNSServiceEnumerateDomains);
#ifdef HAVE_DNSSERVICEGETADDRINFO
NAN_METHOD(DNSServiceGetAddrInfo);
#endif
NAN_METHOD(TXTRecordCreate);
NAN_METHOD(TXTRecordDeallocate);
//NAN_METHOD(TXTRecordGetCount);
NAN_METHOD(TXTRecordSetValue);
NAN_METHOD(TXTRecordGetLength);

// === posix ============================================
#ifdef NODE_MDNS_HAVE_INTERFACE_NAME_CONVERSION
NAN_METHOD(if_nametoindex);
NAN_METHOD(if_indextoname);
#endif

// === additions ========================================
NAN_METHOD(txtRecordBufferToObject);
NAN_METHOD(exportConstants);
NAN_METHOD(buildException);

// === locals ===========================================

void defineFunction(Handle<Object> target, const char * name, NanFunctionCallback f);
void addConstants(Handle<Object> target);

void
init(Handle<Object> target) {
    NanScope();

    ServiceRef::Initialize( target );
    TxtRecordRef::Initialize( target );
#ifdef NODE_MDNS_USE_SOCKET_WATCHER
    SocketWatcher::Initialize( target );
#endif

    defineFunction(target, "DNSServiceRegister", DNSServiceRegister);
    defineFunction(target, "DNSServiceRefSockFD", DNSServiceRefSockFD);
    defineFunction(target, "DNSServiceProcessResult", DNSServiceProcessResult);
    defineFunction(target, "DNSServiceBrowse", DNSServiceBrowse);
    defineFunction(target, "DNSServiceRefDeallocate", DNSServiceRefDeallocate);
    defineFunction(target, "DNSServiceResolve", DNSServiceResolve);
    defineFunction(target, "DNSServiceEnumerateDomains",
            DNSServiceEnumerateDomains);
#ifdef HAVE_DNSSERVICEGETADDRINFO
    defineFunction(target, "DNSServiceGetAddrInfo", DNSServiceGetAddrInfo);
#endif
    defineFunction(target, "TXTRecordCreate", TXTRecordCreate);
    defineFunction(target, "TXTRecordDeallocate", TXTRecordDeallocate);
    //defineFunction(target, "TXTRecordGetCount", TXTRecordGetCount);
    defineFunction(target, "TXTRecordSetValue", TXTRecordSetValue);
    defineFunction(target, "TXTRecordGetLength", TXTRecordGetLength);

#ifdef NODE_MDNS_HAVE_INTERFACE_NAME_CONVERSION
    defineFunction(target, "if_nametoindex", if_nametoindex);
    defineFunction(target, "if_indextoname", if_indextoname);
#endif

    defineFunction(target, "txtRecordBufferToObject", txtRecordBufferToObject);
    defineFunction(target, "buildException", buildException);
    defineFunction(target, "exportConstants", exportConstants);

    addConstants(target);
}

inline
void
defineFunction(Handle<Object> target, const char * name, NanFunctionCallback f) {
    target->Set(NanNew(name),
            NanNew<FunctionTemplate>(f)->GetFunction());
}

NAN_METHOD(buildException) {
    NanScope();
    if (argumentCountMismatch(args, 1)) {
        NanReturnValue(throwArgumentCountMismatchException(args, 1));
    }
    if ( ! args[0]->IsInt32()) {
        NanReturnValue(throwTypeError("argument 1 must be an integer "
                "(DNSServiceErrorType)"));
    }

    DNSServiceErrorType error = args[0]->Int32Value();
    NanReturnValue(buildException(error));
}

void
addConstants(Handle<Object> target) {
    // DNS Classes
    NODE_DEFINE_CONSTANT(target, kDNSServiceClass_IN);

    // DNS Error Codes
    NODE_DEFINE_CONSTANT(target, kDNSServiceErr_NoError);
    NODE_DEFINE_CONSTANT(target, kDNSServiceErr_Unknown);
    NODE_DEFINE_CONSTANT(target, kDNSServiceErr_NoSuchName);
    NODE_DEFINE_CONSTANT(target, kDNSServiceErr_NoMemory);
    NODE_DEFINE_CONSTANT(target, kDNSServiceErr_BadParam);
    NODE_DEFINE_CONSTANT(target, kDNSServiceErr_BadReference);
    NODE_DEFINE_CONSTANT(target, kDNSServiceErr_BadState);
    NODE_DEFINE_CONSTANT(target, kDNSServiceErr_BadFlags);
    NODE_DEFINE_CONSTANT(target, kDNSServiceErr_Unsupported);
    NODE_DEFINE_CONSTANT(target, kDNSServiceErr_NotInitialized);
    NODE_DEFINE_CONSTANT(target, kDNSServiceErr_AlreadyRegistered);
    NODE_DEFINE_CONSTANT(target, kDNSServiceErr_NameConflict);
    NODE_DEFINE_CONSTANT(target, kDNSServiceErr_Invalid);
    NODE_DEFINE_CONSTANT(target, kDNSServiceErr_Firewall);
    NODE_DEFINE_CONSTANT(target, kDNSServiceErr_Incompatible);
    NODE_DEFINE_CONSTANT(target, kDNSServiceErr_BadInterfaceIndex);
    NODE_DEFINE_CONSTANT(target, kDNSServiceErr_Refused);
    NODE_DEFINE_CONSTANT(target, kDNSServiceErr_NoSuchRecord);
    NODE_DEFINE_CONSTANT(target, kDNSServiceErr_NoAuth);
    NODE_DEFINE_CONSTANT(target, kDNSServiceErr_NoSuchKey);
    NODE_DEFINE_CONSTANT(target, kDNSServiceErr_NATTraversal);
    NODE_DEFINE_CONSTANT(target, kDNSServiceErr_DoubleNAT);
    NODE_DEFINE_CONSTANT(target, kDNSServiceErr_BadTime);
#ifdef kDNSServiceErr_BadSig
    NODE_DEFINE_CONSTANT(target, kDNSServiceErr_BadSig);
#endif
#ifdef kDNSServiceErr_BadKey
    NODE_DEFINE_CONSTANT(target, kDNSServiceErr_BadKey);
#endif
#ifdef kDNSServiceErr_Transient
    NODE_DEFINE_CONSTANT(target, kDNSServiceErr_Transient);
#endif
#ifdef kDNSServiceErr_ServiceNotRunning
    NODE_DEFINE_CONSTANT(target, kDNSServiceErr_ServiceNotRunning);
#endif
#ifdef kDNSServiceErr_NATPortMappingUnsupported
    NODE_DEFINE_CONSTANT(target, kDNSServiceErr_NATPortMappingUnsupported);
#endif
#ifdef kDNSServiceErr_NATPortMappingDisabled
    NODE_DEFINE_CONSTANT(target, kDNSServiceErr_NATPortMappingDisabled);
#endif
#ifdef kDNSServiceErr_NoRouter
    NODE_DEFINE_CONSTANT(target, kDNSServiceErr_NoRouter);
#endif
#ifdef kDNSServiceErr_PollingMode
    NODE_DEFINE_CONSTANT(target, kDNSServiceErr_PollingMode);
#endif

    // Interface Index
#ifdef kDNSServiceInterfaceIndexAny
    NODE_DEFINE_CONSTANT(target, kDNSServiceInterfaceIndexAny);
#endif
#ifdef kDNSServiceInterfaceIndexLocalOnly
    NODE_DEFINE_CONSTANT(target, kDNSServiceInterfaceIndexLocalOnly);
#endif
#ifdef kDNSServiceInterfaceIndexP2P
    NODE_DEFINE_CONSTANT(target, kDNSServiceInterfaceIndexP2P);
#endif
#ifdef kDNSServiceInterfaceIndexUnicast
    NODE_DEFINE_CONSTANT(target, kDNSServiceInterfaceIndexUnicast);
#endif

    // DNS Service Types
    NODE_DEFINE_CONSTANT(target, kDNSServiceType_A);
    NODE_DEFINE_CONSTANT(target, kDNSServiceType_NS);
    NODE_DEFINE_CONSTANT(target, kDNSServiceType_MD);
    NODE_DEFINE_CONSTANT(target, kDNSServiceType_MF);
    NODE_DEFINE_CONSTANT(target, kDNSServiceType_CNAME);
    NODE_DEFINE_CONSTANT(target, kDNSServiceType_SOA);
    NODE_DEFINE_CONSTANT(target, kDNSServiceType_MB);
    NODE_DEFINE_CONSTANT(target, kDNSServiceType_MG);
    NODE_DEFINE_CONSTANT(target, kDNSServiceType_MR);
    NODE_DEFINE_CONSTANT(target, kDNSServiceType_NULL);
    NODE_DEFINE_CONSTANT(target, kDNSServiceType_WKS);
    NODE_DEFINE_CONSTANT(target, kDNSServiceType_PTR);
    NODE_DEFINE_CONSTANT(target, kDNSServiceType_HINFO);
    NODE_DEFINE_CONSTANT(target, kDNSServiceType_MINFO);
    NODE_DEFINE_CONSTANT(target, kDNSServiceType_MX);
    NODE_DEFINE_CONSTANT(target, kDNSServiceType_TXT);
    NODE_DEFINE_CONSTANT(target, kDNSServiceType_RP);
    NODE_DEFINE_CONSTANT(target, kDNSServiceType_AFSDB);
    NODE_DEFINE_CONSTANT(target, kDNSServiceType_X25);
    NODE_DEFINE_CONSTANT(target, kDNSServiceType_ISDN);
    NODE_DEFINE_CONSTANT(target, kDNSServiceType_RT);
    NODE_DEFINE_CONSTANT(target, kDNSServiceType_NSAP);
    NODE_DEFINE_CONSTANT(target, kDNSServiceType_NSAP_PTR);
    NODE_DEFINE_CONSTANT(target, kDNSServiceType_SIG);
    NODE_DEFINE_CONSTANT(target, kDNSServiceType_KEY);
    NODE_DEFINE_CONSTANT(target, kDNSServiceType_PX);
    NODE_DEFINE_CONSTANT(target, kDNSServiceType_GPOS);
    NODE_DEFINE_CONSTANT(target, kDNSServiceType_AAAA);
    NODE_DEFINE_CONSTANT(target, kDNSServiceType_LOC);
    NODE_DEFINE_CONSTANT(target, kDNSServiceType_NXT);
    NODE_DEFINE_CONSTANT(target, kDNSServiceType_EID);
    NODE_DEFINE_CONSTANT(target, kDNSServiceType_NIMLOC);
    NODE_DEFINE_CONSTANT(target, kDNSServiceType_SRV);
    NODE_DEFINE_CONSTANT(target, kDNSServiceType_ATMA);
    NODE_DEFINE_CONSTANT(target, kDNSServiceType_NAPTR);
    NODE_DEFINE_CONSTANT(target, kDNSServiceType_KX);
    NODE_DEFINE_CONSTANT(target, kDNSServiceType_CERT);
    NODE_DEFINE_CONSTANT(target, kDNSServiceType_A6);
    NODE_DEFINE_CONSTANT(target, kDNSServiceType_DNAME);
    NODE_DEFINE_CONSTANT(target, kDNSServiceType_SINK);
    NODE_DEFINE_CONSTANT(target, kDNSServiceType_OPT);
#ifdef kDNSServiceType_APL
    NODE_DEFINE_CONSTANT(target, kDNSServiceType_APL);
#endif
#ifdef kDNSServiceType_DS
    NODE_DEFINE_CONSTANT(target, kDNSServiceType_DS);
#endif
#ifdef kDNSServiceType_SSHFP
    NODE_DEFINE_CONSTANT(target, kDNSServiceType_SSHFP);
#endif
#ifdef kDNSServiceType_IPSECKEY
    NODE_DEFINE_CONSTANT(target, kDNSServiceType_IPSECKEY);
#endif
#ifdef kDNSServiceType_RRSIG
    NODE_DEFINE_CONSTANT(target, kDNSServiceType_RRSIG);
#endif
#ifdef kDNSServiceType_NSEC
    NODE_DEFINE_CONSTANT(target, kDNSServiceType_NSEC);
#endif
#ifdef kDNSServiceType_DNSKEY
    NODE_DEFINE_CONSTANT(target, kDNSServiceType_DNSKEY);
#endif
#ifdef kDNSServiceType_DHCID
    NODE_DEFINE_CONSTANT(target, kDNSServiceType_DHCID);
#endif
#ifdef kDNSServiceType_NSEC3
    NODE_DEFINE_CONSTANT(target, kDNSServiceType_NSEC3);
#endif
#ifdef kDNSServiceType_NSEC3PARAM
    NODE_DEFINE_CONSTANT(target, kDNSServiceType_NSEC3PARAM);
#endif
#ifdef kDNSServiceType_HIP
    NODE_DEFINE_CONSTANT(target, kDNSServiceType_HIP);
#endif
#ifdef kDNSServiceType_SPF
    NODE_DEFINE_CONSTANT(target, kDNSServiceType_SPF);
#endif
#ifdef kDNSServiceType_UINFO
    NODE_DEFINE_CONSTANT(target, kDNSServiceType_UINFO);
#endif
#ifdef kDNSServiceType_UID
    NODE_DEFINE_CONSTANT(target, kDNSServiceType_UID);
#endif
#ifdef kDNSServiceType_GID
    NODE_DEFINE_CONSTANT(target, kDNSServiceType_GID);
#endif
#ifdef kDNSServiceType_UNSPEC
    NODE_DEFINE_CONSTANT(target, kDNSServiceType_UNSPEC);
#endif
    NODE_DEFINE_CONSTANT(target, kDNSServiceType_TKEY);
    NODE_DEFINE_CONSTANT(target, kDNSServiceType_TSIG);
    NODE_DEFINE_CONSTANT(target, kDNSServiceType_IXFR);
    NODE_DEFINE_CONSTANT(target, kDNSServiceType_AXFR);
    NODE_DEFINE_CONSTANT(target, kDNSServiceType_MAILB);
    NODE_DEFINE_CONSTANT(target, kDNSServiceType_MAILA);
    NODE_DEFINE_CONSTANT(target, kDNSServiceType_ANY);

    // General Flags
    NODE_DEFINE_CONSTANT(target, kDNSServiceFlagsMoreComing);
    NODE_DEFINE_CONSTANT(target, kDNSServiceFlagsAdd);
    NODE_DEFINE_CONSTANT(target, kDNSServiceFlagsDefault);
    NODE_DEFINE_CONSTANT(target, kDNSServiceFlagsNoAutoRename);
    NODE_DEFINE_CONSTANT(target, kDNSServiceFlagsShared);
    NODE_DEFINE_CONSTANT(target, kDNSServiceFlagsUnique);
    NODE_DEFINE_CONSTANT(target, kDNSServiceFlagsBrowseDomains);
    NODE_DEFINE_CONSTANT(target, kDNSServiceFlagsRegistrationDomains);
    NODE_DEFINE_CONSTANT(target, kDNSServiceFlagsLongLivedQuery);
    NODE_DEFINE_CONSTANT(target, kDNSServiceFlagsAllowRemoteQuery);
    NODE_DEFINE_CONSTANT(target, kDNSServiceFlagsForceMulticast);
#ifdef kDNSServiceFlagsForce
    NODE_DEFINE_CONSTANT(target, kDNSServiceFlagsForce);
#endif
#ifdef kDNSServiceFlagsReturnIntermediates
    NODE_DEFINE_CONSTANT(target, kDNSServiceFlagsReturnIntermediates);
#endif
#ifdef kDNSServiceFlagsNonBrowsable
    NODE_DEFINE_CONSTANT(target, kDNSServiceFlagsNonBrowsable);
#endif
#ifdef kDNSServiceFlagsShareConnection
    NODE_DEFINE_CONSTANT(target, kDNSServiceFlagsShareConnection);
#endif
#ifdef kDNSServiceFlagsSuppressUnusable
    NODE_DEFINE_CONSTANT(target, kDNSServiceFlagsSuppressUnusable);
#endif
    NODE_DEFINE_CONSTANT(target, kDNSServiceProtocol_IPv4);
    NODE_DEFINE_CONSTANT(target, kDNSServiceProtocol_IPv6);
}

NAN_METHOD(exportConstants) {
    NanScope();
    if (argumentCountMismatch(args, 1)) {
        NanReturnValue(throwArgumentCountMismatchException(args, 1));
    }
    if ( ! args[0]->IsObject()) {
        NanReturnValue(throwTypeError("argument 1 must be an object."));
    }

    addConstants(args[0]->ToObject());
    NanReturnUndefined();
}

} // end of namespace node_mdns

NODE_MODULE(dns_sd_bindings,node_mdns::init);
<|endoftext|>