<commit_before>//------------------------------------------------------------------------------
//
// Arion
//
// Extract metadata and create beautiful thumbnails of your images.
//
// ------------
//   main.cpp
// ------------
//
// Copyright (c) 2015 Paul Filitchkin, Snapwire
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
//    * Redistributions of source code must retain the above copyright notice,
//     this list of conditions and the following disclaimer.
//
//    * Redistributions in binary form must reproduce the above copyright
//      notice, this list of conditions and the following disclaimer in
//      the documentation and/or other materials provided with the
//      distribution.
//
//    * Neither the name of the organization nor the names of its contributors
//      may be used to endorse or promote products derived from this software
//      without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
// OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
// OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
// ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//------------------------------------------------------------------------------

// Local
#include "models/operation.hpp"
#include "models/resize.hpp"
#include "models/read_meta.hpp"
#include "utils/utils.hpp"
#include "arion.hpp"

// Boost
#include <boost/exception/info.hpp>
#include <boost/exception/error_info.hpp>
#include <boost/exception/all.hpp>
#include <boost/filesystem.hpp>
#include <boost/foreach.hpp>
#include <boost/program_options.hpp>
#include <boost/lexical_cast.hpp>

// Stdlib
#include <iostream>
#include <string>

using namespace boost::program_options;
using namespace std;

#define ARION_VERSION "0.1.0"

//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
void showHelp(options_description& desc)
{
  cerr << desc << endl;
}

//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
int main(int argc, char* argv[])
{
  try
  {
    positional_options_description p;
    p.add("input", 1);

    string description = "Arion v";
    description += ARION_VERSION;
    description += "\n\n Arguments";

    options_description desc(description);

    desc.add_options()
        ("help", "Produce this help message")
        ("version", "Print version")
        ("input", value< string >(), "The input operations to execute in JSON");

    variables_map vm;

    store(command_line_parser(argc, argv).options(desc).positional(p).run(), vm);

    notify(vm);

    string inputJson;

    if (vm.count("help"))
    {
      showHelp(desc);
      return 1;
    }

    if (vm.count("version"))
    {
      cout << "{\"version\":\"" << ARION_VERSION << "\"}" << endl;
      return 0;
    }

    if (vm.count("input"))
    {
      inputJson = vm["input"].as<string>();
    }
    else
    {
      cout << "You must provide the input operations to execute" << endl << endl;
      showHelp(desc);
      return 1;
    }

    Arion arion;

    if (!arion.setup(inputJson))
    {
      cout << arion.getJson();
      exit(-1);
    }

    bool result = arion.run();

    cout << arion.getJson();

    if (result)
    {
      exit(0);
    }
    else
    {
      exit(-1);
    }
  }
  catch (std::exception& e)
  {
    Utils::exitWithError(e.what());
  }

  return 0;
}
<commit_msg>version change<commit_after>//------------------------------------------------------------------------------
//
// Arion
//
// Extract metadata and create beautiful thumbnails of your images.
//
// ------------
//   main.cpp
// ------------
//
// Copyright (c) 2015 Paul Filitchkin, Snapwire
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
//    * Redistributions of source code must retain the above copyright notice,
//     this list of conditions and the following disclaimer.
//
//    * Redistributions in binary form must reproduce the above copyright
//      notice, this list of conditions and the following disclaimer in
//      the documentation and/or other materials provided with the
//      distribution.
//
//    * Neither the name of the organization nor the names of its contributors
//      may be used to endorse or promote products derived from this software
//      without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
// OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
// OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
// ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//------------------------------------------------------------------------------

// Local
#include "models/operation.hpp"
#include "models/resize.hpp"
#include "models/read_meta.hpp"
#include "utils/utils.hpp"
#include "arion.hpp"

// Boost
#include <boost/exception/info.hpp>
#include <boost/exception/error_info.hpp>
#include <boost/exception/all.hpp>
#include <boost/filesystem.hpp>
#include <boost/foreach.hpp>
#include <boost/program_options.hpp>
#include <boost/lexical_cast.hpp>

// Stdlib
#include <iostream>
#include <string>

using namespace boost::program_options;
using namespace std;

#define ARION_VERSION "0.2.0-beta1"

//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
void showHelp(options_description& desc)
{
  cerr << desc << endl;
}

//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
int main(int argc, char* argv[])
{
  try
  {
    positional_options_description p;
    p.add("input", 1);

    string description = "Arion v";
    description += ARION_VERSION;
    description += "\n\n Arguments";

    options_description desc(description);

    desc.add_options()
        ("help", "Produce this help message")
        ("version", "Print version")
        ("input", value< string >(), "The input operations to execute in JSON");

    variables_map vm;

    store(command_line_parser(argc, argv).options(desc).positional(p).run(), vm);

    notify(vm);

    string inputJson;

    if (vm.count("help"))
    {
      showHelp(desc);
      return 1;
    }

    if (vm.count("version"))
    {
      cout << "{\"version\":\"" << ARION_VERSION << "\"}" << endl;
      return 0;
    }

    if (vm.count("input"))
    {
      inputJson = vm["input"].as<string>();
    }
    else
    {
      cout << "You must provide the input operations to execute" << endl << endl;
      showHelp(desc);
      return 1;
    }

    Arion arion;

    if (!arion.setup(inputJson))
    {
      cout << arion.getJson();
      exit(-1);
    }

    bool result = arion.run();

    cout << arion.getJson();

    if (result)
    {
      exit(0);
    }
    else
    {
      exit(-1);
    }
  }
  catch (std::exception& e)
  {
    Utils::exitWithError(e.what());
  }

  return 0;
}
<|endoftext|>


<commit_before>#include <QGuiApplication>
#include <QtQuick/QQuickView>
#include <QtWebView/QtWebView>
#include <QtDebug>

#include "main.moc"

int main(int argc, char *argv[])
{
  QGuiApplication app(argc, argv);
  QtWebView::initialize();
  QGuiApplication::setApplicationDisplayName(
    QCoreApplication::translate("main", "Kiosk"));

  QQuickView view;
  view.setSource(QUrl("qrc:/main.qml"));
  view.show();

  return app.exec();
}
<commit_msg>Add option management.<commit_after>// http://doc.qt.io/qt-5/qtwebview-minibrowser-example.html
#include <getopt.h>
#include <iostream>

#include <QGuiApplication>
#include <QtQuick/QQuickView>
#include <QtWebView/QtWebView>
#include <QtDebug>

#include "main.moc"

#define VERSION "0.0.1"

int version() {
  std::cout << "kiosk " << VERSION;
#if DEBUG
  std::cout << " -- debug version";
#endif
  std::cout << std::endl;
  std::cout << "Copyright (C) 2017 Jean-Daniel Michaud." << std::endl;
  std::cout << "License MIT: MIT License <https://opensource.org/licenses/MIT>." << std::endl;
  std::cout << "This is free software: you are free to change and redistribute it." << std::endl;
  std::cout << "There is NO WARRANTY, to the extent permitted by law." << std::endl;
  std::cout << std::endl;
  std::cout << "Written by Jean-Daniel Michaud" << std::endl;
  return 0;
}

int help() {
  std::cout << "Usage: ggrep [OPTION]... [URL]" << std::endl;
  return 0;
}

int do_version, do_help, url_specified;
struct option longopts[] = {
   { "version", no_argument,       & do_version,    1   },
   { "help",    no_argument,       & do_help,       1   },
   { 0, 0, 0, 0 }
};

void manage_options(int argc, char **argv, std::string url) {
  // If no url is provided, the value is ""
  char c;
  while ((c = getopt_long(argc, argv, "vh", longopts, NULL)) != -1) {
    switch (c) {
    case 0: /* getopt_long() set a variable, just keep going */
      break;
    case 'h':
      help();
      exit(0);
    case 'v':
      version();
      exit(0);
    case 1:
      break;
    case ':':   /* missing option argument */
      std::cerr << argv[0] << "option `-" << optopt
                << "' requires an argument" << std::endl;
      break;
    case '?':
    default:    /* invalid option */
      std::cerr << argv[0] << "option `-" << optopt
                << "' is invalid: ignored" << std::endl;
      break;
    }
  }
  // Treat non option argument (url)
  url = argv[optind];
  // Just ignore all subsequent arguments
}

int main(int argc, char *argv[])
{
  std::string url = "";
  manage_options(argc, argv, url);
  if (url == "") {
    url = "about:blank";
  }

  QGuiApplication app(argc, argv);
  QtWebView::initialize();
  QGuiApplication::setApplicationDisplayName(
    QCoreApplication::translate("main", "Kiosk"));

  QQuickView view;
  view.setSource(QUrl("qrc:/main.qml"));
  view.show();

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


<commit_before>#include <iostream>
#include <sstream>
#include <algorithm>
#include <vector>
#include <iomanip>

#include "parser.hpp"

// Formatting functions
std::string to_percet_str(double value)
{
    if (value > 0 && value < 0.0001)
        return "< 0.01 %";
    return std::to_string(value * 100) + " %";
}

std::ostream& bold(std::ostream& output)
{
    return output << "\e[1m";
}

std::ostream& red(std::ostream& output)
{
    return output << "\e[1;31m";
}

std::ostream& blue(std::ostream& output)
{
    return output << "\e[1;34m";
}

std::ostream& reset(std::ostream& output)
{
    return output << "\e[0m";
}

// Output message functions
template<typename ErrorType>
void error_message(ErrorType& error, dice::lexer_location loc)
{
    std::cerr
        << bold << "[line: " << loc.line
                << "][column: " << loc.col << "] "
        << reset
        << red << "error: " << reset << error.what() << std::endl << std::endl;
}

void print_result(const dice::random_variable<int, double>& value)
{
    // print constant values as constants
    if (value.is_constant())
    {
        std::cout << value.value() << std::endl;
        return;
    }

    // print the distribution sorted by value
    std::vector<std::pair<std::int32_t, double>> dist{
        value.probability().begin(),
        value.probability().end()
    };
    std::sort(dist.begin(), dist.end(), [](auto&& a, auto&& b)
    {
        return a.first < b.first;
    });

    std::cout << bold << std::setw(10) << std::right << "Value" << reset;
    std::cout << bold << std::setw(15) << std::right << "Probability" << reset << std::endl;

    for (auto&& pair : dist)
    {
        std::cout
            << bold << std::setw(10) << std::right << pair.first << reset << ": "
            << std::setw(12) << to_percet_str(pair.second) << std::endl;
    }
}

void print_result(std::unique_ptr<dice::base_value>& value)
{
    auto scalar_int = dynamic_cast<dice::dice_int*>(value.get());
    if (scalar_int != nullptr)
    {
        std::cout << scalar_int->data() << std::endl;
        return;
    }
    auto scalar_double = dynamic_cast<dice::dice_double*>(value.get());
    if (scalar_double != nullptr)
    {
        std::cout << scalar_double->data() << std::endl;
        return;
    }
    auto rv = dynamic_cast<dice::dice_rand_var*>(value.get());
    print_result(rv->data());
}

int main(int argc, char** argv)
{
    if (argc > 1)
    {
        // concatenate arguments to form an expression
        std::string expr;
        for (int i = 1; i < argc; ++i)
            expr += argv[i];
        std::stringstream input{ expr };

        // parse and interpret the expression
        dice::lexer lexer{ &input };
        dice::parser parser{ &lexer };
        dice::parser::value_type result;
        try
        {
            result = parser.parse();
        }
        catch (dice::parse_error& error)
        {
            error_message(error, lexer.location());
            return 1;
        }
        catch (dice::compiler_error& error)
        {
            error_message(error, lexer.location());
            return 1;
        }
        print_result(result);
    }
    else
    {
        std::cerr << "Usage: dice_cli <expr>" << std::endl
            << "   <expr> is an arbitrary expression" << std::endl
            << "          multiple arguments will be concatenated" << std::endl;
        return 1;
    }
    return 0;
}<commit_msg>Pass std::cerr as error output for the lexer in CLI<commit_after>#include <iostream>
#include <sstream>
#include <algorithm>
#include <vector>
#include <iomanip>

#include "parser.hpp"

// Formatting functions
std::string to_percet_str(double value)
{
    if (value > 0 && value < 0.0001)
        return "< 0.01 %";
    return std::to_string(value * 100) + " %";
}

std::ostream& bold(std::ostream& output)
{
    return output << "\e[1m";
}

std::ostream& red(std::ostream& output)
{
    return output << "\e[1;31m";
}

std::ostream& blue(std::ostream& output)
{
    return output << "\e[1;34m";
}

std::ostream& reset(std::ostream& output)
{
    return output << "\e[0m";
}

// Output message functions
template<typename ErrorType>
void error_message(ErrorType& error, dice::lexer_location loc)
{
    std::cerr
        << bold << "[line: " << loc.line
                << "][column: " << loc.col << "] "
        << reset
        << red << "error: " << reset << error.what() << std::endl << std::endl;
}

void print_result(const dice::random_variable<int, double>& value)
{
    // print constant values as constants
    if (value.is_constant())
    {
        std::cout << value.value() << std::endl;
        return;
    }

    // print the distribution sorted by value
    std::vector<std::pair<int, double>> dist{
        value.probability().begin(),
        value.probability().end()
    };
    std::sort(dist.begin(), dist.end(), [](auto&& a, auto&& b)
    {
        return a.first < b.first;
    });

    std::cout << bold << std::setw(10) << std::right << "Value" << reset;
    std::cout << bold << std::setw(15) << std::right << "Probability" << reset << std::endl;

    for (auto&& pair : dist)
    {
        std::cout
            << bold << std::setw(10) << std::right << pair.first << reset << ": "
            << std::setw(12) << to_percet_str(pair.second) << std::endl;
    }
}

void print_result(std::unique_ptr<dice::base_value>&& value)
{
    auto scalar_int = dynamic_cast<dice::dice_int*>(value.get());
    if (scalar_int != nullptr)
    {
        std::cout << scalar_int->data() << std::endl;
        return;
    }
    auto scalar_double = dynamic_cast<dice::dice_double*>(value.get());
    if (scalar_double != nullptr)
    {
        std::cout << scalar_double->data() << std::endl;
        return;
    }
    auto rv = dynamic_cast<dice::dice_rand_var*>(value.get());
    print_result(rv->data());
}

int main(int argc, char** argv)
{
    if (argc > 1)
    {
        // concatenate arguments to form an expression
        std::string expr;
        for (int i = 1; i < argc; ++i)
            expr += argv[i];
        std::stringstream input{ expr };

        // parse and interpret the expression
        dice::lexer lexer{ &input, &std::cerr };
        dice::parser parser{ &lexer };
        dice::parser::value_type result;
        print_result(parser.parse());
    }
    else
    {
        std::cerr << "Usage: dice_cli <expr>" << std::endl
            << "   <expr> is an arbitrary expression" << std::endl
            << "          multiple arguments will be concatenated" << std::endl;
        return 1;
    }
    return 0;
}<|endoftext|>


<commit_before>#include "StdAfx.h"

ofstream logfile;    // Log file.
SYSTEMTIME lt;

struct CreateLogfileError : public exception
{
  const char * what () const throw ()
    {
      return "Could not create logfile.";
    }
};

/*
    ultracomm -- main
*/

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

    int exit_status;

    const bool blocking = true;  // block until ulterius commands have succeeded
    const bool lazy_param_set = true;  // Do not set ultrasound params if they already have the correct value.
    int verbose;

    try {
        UltracommOptions uopt = UltracommOptions::UltracommOptions(argc, argv);
        verbose = uopt.opt["verbose"].as<int>();

        std::string outname = uopt.opt["output"].as<string>();
/* TODO: fix log handling for freeze-only */
        if (outname == "")
        {
            outname = "U:\\freeze";
        }
        std::string logname = outname + ".log.txt";
        logfile.open(logname, ios::out | ios::binary);
        if (logfile.fail())
        {
            throw CreateLogfileError();
        }
        GetSystemTime(&lt);
        logfile << "main: Connecting to ultracomm. Localtime: " << lt.wHour << ":" << lt.wMinute << ":" << lt.wSecond << "." << lt.wMilliseconds << "\n";
        logfile.flush();

        /* Temporary hack to swallow access violation errors at program end. */
        if (uopt.opt.count("error-hack"))
        {
            SetErrorMode(SetErrorMode(0) | SEM_NOGPFAULTERRORBOX | SEM_FAILCRITICALERRORS);
            GetSystemTime(&lt);
            logfile << "main: Using SetErrorMode to capture access violations: " << lt.wHour << ":" << lt.wMinute << ":" << lt.wSecond << "." << lt.wMilliseconds << "\n";
            logfile.flush();
        }

        Ultracomm uc = Ultracomm::Ultracomm(uopt, logfile);
//        Ultracomm uc = Ultracomm::Ultracomm(uopt);
        try {
            // Connect to Ultrasonix and set parameters.
            GetSystemTime(&lt);
            logfile << "main: Connecting to ultrasonix. Localtime: " << lt.wHour << ":" << lt.wMinute << ":" << lt.wSecond << "." << lt.wMilliseconds << "\n";
            logfile.flush();
            uc.connect();
        }
        catch(const Ultracomm::ConnectionError& e) {
            cerr << "(stderr) Caught ConnectionError.\n";
            cerr << e.what() << "\n";
            GetSystemTime(&lt);
            logfile << "main: Caught ConnectionError. Localtime: " << lt.wSecond << "." << lt.wMilliseconds << "\n";
            logfile << e.what() << "\n";
            logfile.flush();
            exit_status = CONNECTION_ERROR;
            goto EXIT;
        }
        try {
            GetSystemTime(&lt);
            logfile << "main: Setting parameters. Localtime: " << lt.wHour << ":" << lt.wMinute << ":" << lt.wSecond << "." << lt.wMilliseconds << "\n";
            logfile.flush();
            uc.set_int_imaging_params(lazy_param_set);
            uc.check_int_imaging_params();
        }
        catch(const Ultracomm::ParameterMismatchError& e) {
            cerr << "Caught ParameterMismatchError.\n";
            cerr << e.what() << "\n";
            GetSystemTime(&lt);
            logfile << "main: Caught ParameterMismtachError. Localtime: " << lt.wSecond << "." << lt.wMilliseconds << "\n";
            logfile << e.what() << "\n";
            logfile.flush();
            exit_status = PARAMETER_MISMATCH_ERROR;
            goto EXIT;
        }
        uc.freeze(blocking);

        if (uopt.opt.count("dump-params")) {
            uc.dump_params();
        }
        else if (! uopt.opt.count("freeze-only")) {
            // Start acquisition, wait for user interaction, then stop.
//            uc.unset_data_to_acquire(blocking);
            uc.set_data_to_acquire(blocking);
            //uc.freeze(blocking);
            uc.set_callback("data");
            uc.unfreeze(blocking);
            if (! uopt.opt.count("named-pipe")) {
                cout << "*** Acquiring images. Press any key to stop. ***\n";
                _getch();  // Wait for user input.
            }
            else {
                if (verbose) {
                    cout << "*** Acquiring images. Waiting on named pipe. ***\n";
                }
                block_on_named_pipe();
                if (verbose) {
                    cout << "*** Read data from named pipe. ***\n";
                }
            }
            uc.set_callback("no-op");
            uc.freeze(blocking);
            // When unset_data_to_acquire() is not used, we often get several frames
            // of repeat data in our ulterius callback.
            if (uopt.opt["acqmode"].as<string>() == "buffered") {
                // Get data from Ultrasonix and save to file.
                uc.save_data();
            }
        }
// TODO: determine if this delay is necessary or helpful.
        Sleep(200);  // allow time for callbacks to finish

        // We're done.
        if (uopt.opt.count("delay-exit")) {
            cout << "*** ultracomm finished. Press any key to exit the program. ***\n";
            _getch();  // Wait for user input.
        }
        uc.disconnect();
        GetSystemTime(&lt);
        logfile << "main: disconnected from ultracomm. Localtime: " << lt.wHour << ":" << lt.wMinute << ":" << lt.wSecond << "." << lt.wMilliseconds << "\n";
        logfile.flush();
        exit_status = EXIT_SUCCESS;
    }
    catch(const UltracommOptions::WantsToStop& e) {   // --help or --version
        e.what();   // Doesn't do much besides avoid unused variable warning.
        exit_status = EXIT_SUCCESS;
        goto EXIT;
    }
    catch(const UltracommOptions::WantsToStopWithDelay& e) {
        e.what();   // Doesn't do much besides avoid unused variable warning.
        cout << "*** ultracomm finished. Press any key to exit the program. ***\n";
        _getch();  // Wait for user input.
        exit_status = EXIT_SUCCESS;
        goto EXIT;
    }
    catch(const po::required_option& e) { // e.g. missing --address
        cerr << "Missing required option: " << e.what() << "\n";
        exit_status = MISSING_REQUIRED_OPTION_ERROR;
        goto EXIT;
    }
    catch(const po::error& e) {  // e.g. an incomplete argument or command line syntax error
        cerr << "Error in program options: " << e.what() << "\n";
        exit_status = BAD_OPTION_ERROR;
        goto EXIT;
    }
    catch(const UltracommOptions::MissingOptionsFileError& e) {
        cerr << "Caught MissingOptionsFileError.\n";
        cerr << e.what() << "\n";
        exit_status = MISSING_OPTIONS_FILE_ERROR;
        goto EXIT;
    }
    catch(const UltracommOptions::UnimplementedFeatureError& e) {
        cerr << "Caught UnimplementedFeatureError.\n";
        cerr << e.what() << "\n";
        exit_status = UNIMPLEMENTED_FEATURE_ERROR;
        goto EXIT;
    }
    catch(const CreateLogfileError& e) {
        cerr << "Caught CreateLogfileError.\n";
        cerr << e.what() << "\n";
        exit_status = CREATE_LOGFILE_ERROR;
        goto EXIT;
    }
    catch(const Ultracomm::NoFramesError& e) {
        cerr << "Caught NoFramesError.\n";
        cerr << e.what() << "\n";
        exit_status = NO_FRAMES_ERROR;
        goto EXIT;
    }
    catch(const exception& e) {
        cerr << "Exception: " << e.what() << "\n";
        GetSystemTime(&lt);
        logfile << "main: Caught generic exception " << lt.wHour << ":" << lt.wMinute << ":" << lt.wSecond << "." << lt.wMilliseconds << "\n";
        logfile << e.what() << "\n";
        logfile.flush();
        exit_status = UNKNOWN_ERROR;
        goto EXIT;
    }
    catch(...) {
        cerr << "Unhandled exception of unknown type!\n";
        GetSystemTime(&lt);
        logfile << "main: Caught exception of unknown type " << lt.wHour << ":" << lt.wMinute << ":" << lt.wSecond << "." << lt.wMilliseconds << "\n";
        logfile.flush();
        exit_status = UNKNOWN_ERROR;
        goto EXIT;
    }

    EXIT:
    GetSystemTime(&lt);
    logfile << "main: Exiting with returncode " << exit_status << ". Localtime: " << lt.wHour << ":" << lt.wMinute << ":" << lt.wSecond << "." << lt.wMilliseconds << "\n";
    logfile.flush();
    return exit_status;
}

<commit_msg>No logfile for --freeze-only.<commit_after>#include "StdAfx.h"

ofstream logfile;    // Log file.
SYSTEMTIME lt;

struct CreateLogfileError : public exception
{
  const char * what () const throw ()
    {
      return "Could not create logfile.";
    }
};

/*
    ultracomm -- main
*/

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

    int exit_status;

    const bool blocking = true;  // block until ulterius commands have succeeded
    const bool lazy_param_set = true;  // Do not set ultrasound params if they already have the correct value.
    int verbose;

    try {
        UltracommOptions uopt = UltracommOptions::UltracommOptions(argc, argv);
        verbose = uopt.opt["verbose"].as<int>();

        if (! uopt.opt.count("freeze-only"))
        {
            std::string outname = uopt.opt["output"].as<string>();
            std::string logname = outname + ".log.txt";
            logfile.open(logname, ios::out | ios::binary);
            if (logfile.fail())
            {
                throw CreateLogfileError();
            }
            GetSystemTime(&lt);
            logfile << "main: Connecting to ultracomm. Localtime: " << lt.wHour << ":" << lt.wMinute << ":" << lt.wSecond << "." << lt.wMilliseconds << "\n";
            logfile.flush();
        }

        /* Temporary hack to swallow access violation errors at program end. */
        if (uopt.opt.count("error-hack"))
        {
            SetErrorMode(SetErrorMode(0) | SEM_NOGPFAULTERRORBOX | SEM_FAILCRITICALERRORS);
            GetSystemTime(&lt);
            logfile << "main: Using SetErrorMode to capture access violations: " << lt.wHour << ":" << lt.wMinute << ":" << lt.wSecond << "." << lt.wMilliseconds << "\n";
            logfile.flush();
        }

        Ultracomm uc = Ultracomm::Ultracomm(uopt, logfile);
//        Ultracomm uc = Ultracomm::Ultracomm(uopt);
        try {
            // Connect to Ultrasonix and set parameters.
            if (logfile)
            {
                GetSystemTime(&lt);
                logfile << "main: Connecting to ultrasonix. Localtime: " << lt.wHour << ":" << lt.wMinute << ":" << lt.wSecond << "." << lt.wMilliseconds << "\n";
                logfile.flush();
            }
            uc.connect();
        }
        catch(const Ultracomm::ConnectionError& e) {
            cerr << "(stderr) Caught ConnectionError.\n";
            cerr << e.what() << "\n";
            if (logfile)
            {
                GetSystemTime(&lt);
                logfile << "main: Caught ConnectionError. Localtime: " << lt.wSecond << "." << lt.wMilliseconds << "\n";
                logfile << e.what() << "\n";
                logfile.flush();
            }
            exit_status = CONNECTION_ERROR;
            goto EXIT;
        }
        try {
            if (logfile)
            {
                GetSystemTime(&lt);
                logfile << "main: Setting parameters. Localtime: " << lt.wHour << ":" << lt.wMinute << ":" << lt.wSecond << "." << lt.wMilliseconds << "\n";
                logfile.flush();
            }
            uc.set_int_imaging_params(lazy_param_set);
            uc.check_int_imaging_params();
        }
        catch(const Ultracomm::ParameterMismatchError& e) {
            cerr << "Caught ParameterMismatchError.\n";
            cerr << e.what() << "\n";
            if (logfile)
            {
                GetSystemTime(&lt);
                logfile << "main: Caught ParameterMismtachError. Localtime: " << lt.wSecond << "." << lt.wMilliseconds << "\n";
                logfile << e.what() << "\n";
                logfile.flush();
            }
            exit_status = PARAMETER_MISMATCH_ERROR;
            goto EXIT;
        }
        uc.freeze(blocking);

        if (uopt.opt.count("dump-params")) {
            uc.dump_params();
        }
        else if (! uopt.opt.count("freeze-only")) {
            // Start acquisition, wait for user interaction, then stop.
//            uc.unset_data_to_acquire(blocking);
            uc.set_data_to_acquire(blocking);
            //uc.freeze(blocking);
            uc.set_callback("data");
            uc.unfreeze(blocking);
            if (! uopt.opt.count("named-pipe")) {
                cout << "*** Acquiring images. Press any key to stop. ***\n";
                _getch();  // Wait for user input.
            }
            else {
                if (verbose) {
                    cout << "*** Acquiring images. Waiting on named pipe. ***\n";
                }
                block_on_named_pipe();
                if (verbose) {
                    cout << "*** Read data from named pipe. ***\n";
                }
            }
            uc.set_callback("no-op");
            uc.freeze(blocking);
            // When unset_data_to_acquire() is not used, we often get several frames
            // of repeat data in our ulterius callback.
            if (uopt.opt["acqmode"].as<string>() == "buffered") {
                // Get data from Ultrasonix and save to file.
                uc.save_data();
            }
        }
// TODO: determine if this delay is necessary or helpful.
        Sleep(200);  // allow time for callbacks to finish

        // We're done.
        if (uopt.opt.count("delay-exit")) {
            cout << "*** ultracomm finished. Press any key to exit the program. ***\n";
            _getch();  // Wait for user input.
        }
        uc.disconnect();
        if (logfile)
        {
            GetSystemTime(&lt);
            logfile << "main: disconnected from ultracomm. Localtime: " << lt.wHour << ":" << lt.wMinute << ":" << lt.wSecond << "." << lt.wMilliseconds << "\n";
            logfile.flush();
        }
        exit_status = EXIT_SUCCESS;
    }
    catch(const UltracommOptions::WantsToStop& e) {   // --help or --version
        e.what();   // Doesn't do much besides avoid unused variable warning.
        exit_status = EXIT_SUCCESS;
        goto EXIT;
    }
    catch(const UltracommOptions::WantsToStopWithDelay& e) {
        e.what();   // Doesn't do much besides avoid unused variable warning.
        cout << "*** ultracomm finished. Press any key to exit the program. ***\n";
        _getch();  // Wait for user input.
        exit_status = EXIT_SUCCESS;
        goto EXIT;
    }
    catch(const po::required_option& e) { // e.g. missing --address
        cerr << "Missing required option: " << e.what() << "\n";
        exit_status = MISSING_REQUIRED_OPTION_ERROR;
        goto EXIT;
    }
    catch(const po::error& e) {  // e.g. an incomplete argument or command line syntax error
        cerr << "Error in program options: " << e.what() << "\n";
        exit_status = BAD_OPTION_ERROR;
        goto EXIT;
    }
    catch(const UltracommOptions::MissingOptionsFileError& e) {
        cerr << "Caught MissingOptionsFileError.\n";
        cerr << e.what() << "\n";
        exit_status = MISSING_OPTIONS_FILE_ERROR;
        goto EXIT;
    }
    catch(const UltracommOptions::UnimplementedFeatureError& e) {
        cerr << "Caught UnimplementedFeatureError.\n";
        cerr << e.what() << "\n";
        exit_status = UNIMPLEMENTED_FEATURE_ERROR;
        goto EXIT;
    }
    catch(const CreateLogfileError& e) {
        cerr << "Caught CreateLogfileError.\n";
        cerr << e.what() << "\n";
        exit_status = CREATE_LOGFILE_ERROR;
        goto EXIT;
    }
    catch(const Ultracomm::NoFramesError& e) {
        cerr << "Caught NoFramesError.\n";
        cerr << e.what() << "\n";
        exit_status = NO_FRAMES_ERROR;
        goto EXIT;
    }
    catch(const exception& e) {
        cerr << "Exception: " << e.what() << "\n";
        if (logfile)
        {
            GetSystemTime(&lt);
            logfile << "main: Caught generic exception " << lt.wHour << ":" << lt.wMinute << ":" << lt.wSecond << "." << lt.wMilliseconds << "\n";
            logfile << e.what() << "\n";
            logfile.flush();
        }
        exit_status = UNKNOWN_ERROR;
        goto EXIT;
    }
    catch(...) {
        cerr << "Unhandled exception of unknown type!\n";
        if (logfile)
        {
            GetSystemTime(&lt);
            logfile << "main: Caught exception of unknown type " << lt.wHour << ":" << lt.wMinute << ":" << lt.wSecond << "." << lt.wMilliseconds << "\n";
            logfile.flush();
        }
        exit_status = UNKNOWN_ERROR;
        goto EXIT;
    }

    EXIT:
    if (logfile)
    {
        GetSystemTime(&lt);
        logfile << "main: Exiting with returncode " << exit_status << ". Localtime: " << lt.wHour << ":" << lt.wMinute << ":" << lt.wSecond << "." << lt.wMilliseconds << "\n";
        logfile.flush();
    }
    return exit_status;
}

<|endoftext|>


<commit_before>
#include <Arduino.h>
#include <Adafruit_GFX.h>
#include <Wire.h>
#include <Adafruit_SSD1306.h>

#ifndef OLED_RESET_PIN
#define OLED_RESET_PIN 4
#endif
Adafruit_SSD1306 display(OLED_RESET_PIN);

#define NES_LATCH 2
#define NES_CLOCK 3
#define NES_DATA_IN 4
#define BTN_UP    B11110111
#define BTN_DOWN  B11111011
#define BTN_LEFT  B11111101
#define BTN_RIGHT B11111110
#define BTN_SELECT B11011111
#define BTN_START B11101111
#define BTN_A     B01111111
#define BTN_B     B10111111

#define SCREEN_MENU 0
#define SCREEN_GAME 1

byte current_screen = SCREEN_MENU;

byte controller_data = 0;

int xpos = 0;
int ypos = 0;
bool input_latch = false;

void setup() {
  display.begin();
  display.clearDisplay();
  display.display();

  pinMode(NES_LATCH, OUTPUT);
  pinMode(NES_CLOCK, OUTPUT);
  pinMode(NES_DATA_IN, INPUT);

  digitalWrite(NES_LATCH, HIGH);
  digitalWrite(NES_CLOCK, HIGH);
}

void read_controller() {
  controller_data = 0;
  digitalWrite(NES_LATCH, LOW);
  digitalWrite(NES_CLOCK, LOW);

  digitalWrite(NES_LATCH, HIGH);
  delayMicroseconds(2);
  digitalWrite(NES_LATCH, LOW);

  controller_data = digitalRead(NES_DATA_IN);

  for (int i = 1; i <= 7; i++) {
    digitalWrite(NES_CLOCK, HIGH);
    delayMicroseconds(2);
    controller_data = controller_data << 1;
    controller_data = controller_data + digitalRead(NES_DATA_IN);
    delayMicroseconds(4);
    digitalWrite(NES_CLOCK, LOW);
  }
}

byte screen_menu() {
  if (controller_data == BTN_START) return SCREEN_GAME;

  display.clearDisplay();
  display.setTextColor(WHITE);

  display.setTextSize(2);
  display.setCursor(0, 0);
  display.print("ROUGELIKE");

  display.setTextSize(1);
  display.setCursor(0, 32);
  display.print("Press START to begin");

  display.display();

  return SCREEN_MENU;
}

byte screen_game() {
  switch (controller_data) {
    case BTN_UP:
      if (!input_latch) ypos -= 1;
      input_latch = true;
      break;
    case BTN_LEFT:
      if (!input_latch) xpos -= 1;
      input_latch = true;
      break;
    case BTN_RIGHT:
      if (!input_latch) xpos += 1;
      input_latch = true;
      break;
    case BTN_DOWN:
      if (!input_latch) ypos += 1;
      input_latch = true;
      break;
    default:
      input_latch = false;
      break;
    // case BTN_A: display.print("A"); break;
    // case BTN_B: display.print("B"); break;
    // case BTN_START: display.print("START"); break;
    // case BTN_SELECT: display.print("SELECT"); break;
  }

  if (xpos < 0) xpos = 0;
  if (xpos > 15) xpos = 15;
  if (ypos < 0) ypos = 0;
  if (ypos > 7) ypos = 7;

  // Reset display
  display.clearDisplay();
  display.setTextSize(1);
  display.setTextColor(WHITE);

  display.setCursor(xpos*8, ypos*8);
  display.print("@");

  display.display();

  return SCREEN_GAME;
}

void loop() {
  read_controller();
  switch (current_screen) {
    case SCREEN_MENU:
      current_screen = screen_menu();
      break;
    case SCREEN_GAME:
      current_screen = screen_game();
      break;
    default:
      display.clearDisplay();
      display.setCursor(0, 0);
      display.print("Unknown screen.");
      display.display();
      break;
  }
}
<commit_msg>Added in "background"<commit_after>
#include <Arduino.h>
#include <Adafruit_GFX.h>
#include <Wire.h>
#include <Adafruit_SSD1306.h>

#ifndef OLED_RESET_PIN
#define OLED_RESET_PIN 4
#endif
Adafruit_SSD1306 display(OLED_RESET_PIN);

#define NES_LATCH 2
#define NES_CLOCK 3
#define NES_DATA_IN 4
#define BTN_UP    B11110111
#define BTN_DOWN  B11111011
#define BTN_LEFT  B11111101
#define BTN_RIGHT B11111110
#define BTN_SELECT B11011111
#define BTN_START B11101111
#define BTN_A     B01111111
#define BTN_B     B10111111

#define SCREEN_MENU 0
#define SCREEN_GAME 1

byte current_screen = SCREEN_MENU;

byte controller_data = 0;

int xpos = 0;
int ypos = 0;
bool input_latch = false;

void setup() {
  display.begin();
  display.clearDisplay();
  display.display();

  pinMode(NES_LATCH, OUTPUT);
  pinMode(NES_CLOCK, OUTPUT);
  pinMode(NES_DATA_IN, INPUT);

  digitalWrite(NES_LATCH, HIGH);
  digitalWrite(NES_CLOCK, HIGH);
}

void read_controller() {
  controller_data = 0;
  digitalWrite(NES_LATCH, LOW);
  digitalWrite(NES_CLOCK, LOW);

  digitalWrite(NES_LATCH, HIGH);
  delayMicroseconds(2);
  digitalWrite(NES_LATCH, LOW);

  controller_data = digitalRead(NES_DATA_IN);

  for (int i = 1; i <= 7; i++) {
    digitalWrite(NES_CLOCK, HIGH);
    delayMicroseconds(2);
    controller_data = controller_data << 1;
    controller_data = controller_data + digitalRead(NES_DATA_IN);
    delayMicroseconds(4);
    digitalWrite(NES_CLOCK, LOW);
  }
}

byte screen_menu() {
  if (controller_data == BTN_START) return SCREEN_GAME;

  display.clearDisplay();
  display.setTextColor(WHITE);

  display.setTextSize(2);
  display.setCursor(0, 0);
  display.print("ROUGELIKE");

  display.setTextSize(1);
  display.setCursor(0, 32);
  display.print("Press START to begin");

  display.display();

  return SCREEN_MENU;
}

byte screen_game() {
  switch (controller_data) {
    case BTN_UP:
      if (!input_latch) ypos -= 1;
      input_latch = true;
      break;
    case BTN_LEFT:
      if (!input_latch) xpos -= 1;
      input_latch = true;
      break;
    case BTN_RIGHT:
      if (!input_latch) xpos += 1;
      input_latch = true;
      break;
    case BTN_DOWN:
      if (!input_latch) ypos += 1;
      input_latch = true;
      break;
    default:
      input_latch = false;
      break;
    // case BTN_A: display.print("A"); break;
    // case BTN_B: display.print("B"); break;
    // case BTN_START: display.print("START"); break;
    // case BTN_SELECT: display.print("SELECT"); break;
  }

  if (xpos < 0) xpos = 0;
  if (xpos > 15) xpos = 15;
  if (ypos < 0) ypos = 0;
  if (ypos > 7) ypos = 7;

  // Reset display
  display.clearDisplay();
  display.setTextSize(1);
  display.setTextColor(WHITE);

  for (int i = 0; i < 16; i++) {
    for (int j = 0; j < 16; j++) {
      display.setCursor(i * 8, j * 8);
      display.print('.');
    }
  }

  display.setTextColor(WHITE, BLACK);
  display.setCursor(xpos*8, ypos*8);
  display.print('@');

  display.display();

  return SCREEN_GAME;
}

void loop() {
  read_controller();
  switch (current_screen) {
    case SCREEN_MENU:
      current_screen = screen_menu();
      break;
    case SCREEN_GAME:
      current_screen = screen_game();
      break;
    default:
      display.clearDisplay();
      display.setCursor(0, 0);
      display.print("Unknown screen.");
      display.display();
      break;
  }
}
<|endoftext|>


<commit_before>#include <QFileInfo>
#include <QtCore/QCoreApplication>
#include <iostream>
#include <cache.h>
#include <transform.h>
#include <exec.h>

using namespace std;

string helpText = "\nMessers Heisenberg, AppuDB and Giri, The Purveyors of Speed\n\n<< PRESENTS >>\n\n\
Medusa 2.7.3 beta\nCopyright (c) 2013-2014, Rahul De, Apoorv Agarwal and Aakash Giri, VIT University\n\
Licensed under BSD 3-Clause\n\nUsage: medusa [options] file\n\nOptions:\n\
-install\tInstall External Python module\n--help, -h\tDispaly this information\n-c\t\tCompile to Dart only\n";

int main(int argc, char **argv) {
    QCoreApplication app(argc, argv);
    Cache cache;
    Transform transformer;
    Exec exec;
    QStringList args = app.arguments();
    bool cStop = false, install = false;
    QString path, name, code, art;
    QFile artFile("art.txt");

    if (app.arguments().size() == 1) {
        artFile.open(QIODevice::ReadOnly | QIODevice::Text);
        art = artFile.readAll();
        artFile.close();

        cout << helpText << art.toStdString();
        return 0;
    }

    foreach (QString arg, app.arguments()) {
        if (arg == "--help" || arg == "-h") {
            artFile.open(QIODevice::ReadOnly | QIODevice::Text);
            art = artFile.readAll();
            artFile.close();

            cout << helpText << art.toStdString();
            return 0;
        }
        else if (arg == "-c")
            cStop = true;
        else if (arg == "-install")
            install = true;
        else {
            QFileInfo pyFile(arg);
            path = pyFile.absoluteFilePath();
            name = pyFile.completeBaseName();
        }
    }

    if (install) {
        if (QFile::copy(path, "lib/" + name + ".py"))
            cout << QString(name + ".py").toStdString() + " successfully Installed into Medusa!" << endl;
        else
            cerr << "Couldn't Install: " + QString(name + ".py").toStdString() << endl;
        return 0;
    }

    if (cache.isCached(path, code) || transformer.transform(path, code))
        exec.run(code, name + ".dart", cStop);

    return 0;
}<commit_msg>Optimized Entry Point<commit_after>#include <QFileInfo>
#include <QtCore/QCoreApplication>
#include <iostream>
#include <cache.h>
#include <transform.h>
#include <exec.h>

using namespace std;

string helpText = "\nMessers Heisenberg, AppuDB and Giri, The Purveyors of Speed\n\n<< PRESENTS >>\n\n\
Medusa 2.7.3 beta\nCopyright (c) 2013-2014, Rahul De, Apoorv Agarwal and Aakash Giri, VIT University\n\
Licensed under BSD 3-Clause\n\nUsage: medusa [options] file\n\nOptions:\n\
-install\tInstall External Python module\n--help, -h\tDispaly this information\n-c\t\tCompile to Dart only\n";

int main(int argc, char **argv) {
    QCoreApplication app(argc, argv);
    Cache cache;
    Transform transformer;
    Exec exec;
    QStringList args = app.arguments();
    bool cStop = false;
    QString path, name, code, art;
    QFile artFile("art.txt");

    if (app.arguments().size() == 1) {
        artFile.open(QIODevice::ReadOnly | QIODevice::Text);
        art = artFile.readAll();
        artFile.close();

        cout << helpText << art.toStdString();
        return 0;
    }

    foreach (QString arg, app.arguments()) {
        if (arg == "--help" || arg == "-h") {
            artFile.open(QIODevice::ReadOnly | QIODevice::Text);
            art = artFile.readAll();
            artFile.close();

            cout << helpText << art.toStdString();
            return 0;
        }
        else if (arg == "-c")
            cStop = true;
        else if (arg == "-install") {
            if (QFile::copy(path, "lib/" + name + ".py"))
                cout << QString(name + ".py").toStdString() + " successfully Installed into Medusa!" << endl;
            else
                cerr << "Couldn't Install: " + QString(name + ".py").toStdString() << endl;
            return 0;
        }
        else {
            QFileInfo pyFile(arg);
            path = pyFile.absoluteFilePath();
            name = pyFile.completeBaseName();
        }
    }

    if (cache.isCached(path, code) || transformer.transform(path, code))
        exec.run(code, name + ".dart", cStop);

    return 0;
}<|endoftext|>


<commit_before>#include <cstdio>
#include <cstdlib>
#include <cctype>
#include <cstring>
#include <unistd.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <vector>
#include <string>
#include <iostream>

#include "functions.h"

int main(int argc, char** argv)
{
  // print welcome message and prompt
  printf("Welcome to rshell!\n");

  std::string prompt;

  char* cbuff = getlogin();

  if (cbuff == NULL)
  {
    perror("getlogin");
  }
  else
  {
    prompt += cbuff;
  }

  cbuff = new char[4096];
  if (gethostname(cbuff, (unsigned)4096) == -1)
  {
    perror("gethostname");
  }
  else
  {
    prompt += '@';
    prompt += cbuff;
  }

  delete[] cbuff;

  prompt += " > ";

  bool ext = false;

  while (!ext)
  {
    // holds a single command and its arguments
    Command cmd;
    // holds multiple commands
    std::vector<Command> cmds;
    // hold a raw line of input
    std::string line;

    // print prompt and get a line of text (done in condition)
    printf("%s", prompt.c_str());
    getline(std::cin, line);

    // look for comments
    if (line.find("#") != std::string::npos)
    {
      // remove them if necessary (they're useless)
      line = line.substr(0, line.find("#"));
    }

    // remove leading whitespace
    while (line.size() > 0 && (line[0] == ' ' || line[0] == '\t' || line[0] == ';'))
    {
      line = line.substr(1, line.size() - 1);
    }

    // adding this makes parsing easier
    line += "; ";

    if (std::cin.fail())
    {
      printf("\nGoodbye!\n");
      exit(0);
    }

    int mode = GETWORD;
    unsigned begin = 0;

    // prepare cmd
    cmd.connector = NONE;

    // syntax error flag
    bool se = false;

    // starts with a connector? I don't think so
    if (line.size() > 0 && isConn(line[0]) && line[0] != ';')
    {
      se = true;
    }

    // handle the input
    for(unsigned i = 0; i < line.size() && !se; ++i)
    {
      bool con   = isConn(line[i]);
      bool space = isspace(line[i]);

      // if we're getting a word and there's a whitespace or connector here
      if (mode == GETWORD && (space || con))
      {
        // chunk the last term and throw it into the vector
        char* c = stocstr(line.substr(begin, i - begin));
        if (strlen(c) > 0)
        {
          cmd.args.push_back(c);
        }
        else
        {
          // only happens when nothing is entered. breaks so nothing more happens
          break;
        }

        if (space)
        {
          mode = TRIMSPACE;
        }
        else // it's a connector
        {
          handleCon(cmds, cmd, line, mode, begin, i, se);
        }
      }
      else if (mode == TRIMSPACE && (!space || con))
      {
        if (con && cmd.args.empty())
        {

// (cmds[cmds.size() - 1].connector == AND || cmds[cmds.size() - 1].connector == OR))

          // if (line[i] != ';' || cmds[cmds.size() - 1].connector !=
          // {
            // why this test? two reasons:
            //   1) it
          if (line[i] != ';')
            se = true;
          // }
        }
        else if (con)
        {
          handleCon(cmds, cmd, line, mode, begin, i, se);
        }
        else
        {
          mode = GETWORD;
          begin = i;
        }
      }
      else if (mode == HANDLESEMI && line[i] != ';')
      {
        if (isConn(line[i]))
        {
          se = true;
        }
        else if (isspace(line[i]))
        {
          mode = TRIMSPACE;
        }
        else // it's a word
        {
          mode = GETWORD;
          begin = i;
        }
      }
    }

    // if the last command has a continuation connector, syntax error
    if (cmds.size() > 0 && (cmds[cmds.size() - 1].connector == AND
                        ||  cmds[cmds.size() - 1].connector == OR))
    {
      se = true;
    }

    // if there was a syntax error
    if (se)
    {
      printf("Syntax error\n");
      continue;
    }

    // now to execute all the commands
    for(unsigned i = 0; i < cmds.size(); ++i)
    {
      int exitStatus = 0;
      char* arg = cmds[i].args[0];
      if (strcmp(arg, "exit") == 0)
      {
        ext = true;
        break;
      }
      char** argv = new char*[cmds[i].args.size() + 1];
      for(unsigned j = 0; j < cmds[i].args.size(); ++j)
      {
        argv[j] = cmds[i].args[j];
      }
      argv[cmds[i].args.size()] = 0;

      // arg and argv are now prepared
      pid_t pid = fork();
      if (pid == -1)
      {
        perror("fork");
        exit(1);
      }
      else if (pid == 0) // child process
      {
        if (execvp(arg, argv) == -1)
        {
          // if there's a return value, there was a problem
          // -1 indicates a problem, specifically
          perror("execvp");
          exit(1);
        }
      }
      else // parent process
      {
        if (waitpid(pid, &exitStatus, 0) == -1)
        {
          perror("waitpid");
          exit(1);
        }
      }
      if (!exitStatus) // all is good (0)
      {
        while (i < cmds.size() && cmds[i].connector == OR)
        {
          ++i;
        }
      }
      else // last command failed
      {
        while (i < cmds.size() && cmds[i].connector == AND)
        {
          ++i;
        }
      }
    }

    // deallocate allocated memory
    for(unsigned i = 0; i < cmds.size(); ++i)
    {
      for(unsigned j = 0; j < cmds[i].args.size(); ++j)
      {
        delete[] cmds[i].args[j];
      }
    }
  }
  printf("Goodbye!\n");
  return 0;
}

<commit_msg>tried to fix an unfixable memory leak<commit_after>#include <cstdio>
#include <cstdlib>
#include <cctype>
#include <cstring>
#include <unistd.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <vector>
#include <string>
#include <iostream>

#include "functions.h"

int main(int argc, char** argv)
{
  // print welcome message and prompt
  printf("Welcome to rshell!\n");

  std::string prompt;

  char* cbuff = getlogin();

  if (cbuff == NULL)
  {
    perror("getlogin");
  }
  else
  {
    prompt += cbuff;
  }

  cbuff = new char[4096];
  if (gethostname(cbuff, (unsigned)4096) == -1)
  {
    perror("gethostname");
  }
  else
  {
    prompt += '@';
    prompt += cbuff;
  }

  delete[] cbuff;

  prompt += " > ";

  bool ext = false;

  while (!ext)
  {
    // holds a single command and its arguments
    Command cmd;
    // holds multiple commands
    std::vector<Command> cmds;
    // hold a raw line of input
    std::string line;

    // print prompt and get a line of text (done in condition)
    printf("%s", prompt.c_str());
    getline(std::cin, line);

    // look for comments
    if (line.find("#") != std::string::npos)
    {
      // remove them if necessary (they're useless)
      line = line.substr(0, line.find("#"));
    }

    // remove leading whitespace
    while (line.size() > 0 && (line[0] == ' ' || line[0] == '\t' || line[0] == ';'))
    {
      line = line.substr(1, line.size() - 1);
    }

    // adding this makes parsing easier
    line += "; ";

    if (std::cin.fail())
    {
      printf("\nGoodbye!\n");
      exit(0);
    }

    int mode = GETWORD;
    unsigned begin = 0;

    // prepare cmd
    cmd.connector = NONE;

    // syntax error flag
    bool se = false;

    // starts with a connector? I don't think so
    if (line.size() > 0 && isConn(line[0]) && line[0] != ';')
    {
      se = true;
    }

    // handle the input
    for(unsigned i = 0; i < line.size() && !se; ++i)
    {
      bool con   = isConn(line[i]);
      bool space = isspace(line[i]);

      // if we're getting a word and there's a whitespace or connector here
      if (mode == GETWORD && (space || con))
      {
        // chunk the last term and throw it into the vector
        char* c = stocstr(line.substr(begin, i - begin));
        if (strlen(c) > 0)
        {
          cmd.args.push_back(c);
        }
        else
        {
          // only happens when nothing is entered. breaks so nothing more happens
          break;
        }

        if (space)
        {
          mode = TRIMSPACE;
        }
        else // it's a connector
        {
          handleCon(cmds, cmd, line, mode, begin, i, se);
        }
      }
      else if (mode == TRIMSPACE && (!space || con))
      {
        if (con && cmd.args.empty())
        {

// (cmds[cmds.size() - 1].connector == AND || cmds[cmds.size() - 1].connector == OR))

          // if (line[i] != ';' || cmds[cmds.size() - 1].connector !=
          // {
            // why this test? two reasons:
            //   1) it
          if (line[i] != ';')
            se = true;
          // }
        }
        else if (con)
        {
          handleCon(cmds, cmd, line, mode, begin, i, se);
        }
        else
        {
          mode = GETWORD;
          begin = i;
        }
      }
      else if (mode == HANDLESEMI && line[i] != ';')
      {
        if (isConn(line[i]))
        {
          se = true;
        }
        else if (isspace(line[i]))
        {
          mode = TRIMSPACE;
        }
        else // it's a word
        {
          mode = GETWORD;
          begin = i;
        }
      }
    }

    // if the last command has a continuation connector, syntax error
    if (cmds.size() > 0 && (cmds[cmds.size() - 1].connector == AND
                        ||  cmds[cmds.size() - 1].connector == OR))
    {
      se = true;
    }

    // if there was a syntax error
    if (se)
    {
      printf("Syntax error\n");
      continue;
    }

    // now to execute all the commands
    for(unsigned i = 0; i < cmds.size(); ++i)
    {
      int exitStatus = 0;
      char* arg = cmds[i].args[0];
      if (strcmp(arg, "exit") == 0)
      {
        ext = true;
        break;
      }
      char** argv = new char*[cmds[i].args.size() + 1];
      for(unsigned j = 0; j < cmds[i].args.size(); ++j)
      {
        argv[j] = cmds[i].args[j];
      }
      argv[cmds[i].args.size()] = 0;

      // arg and argv are now prepared
      pid_t pid = fork();
      if (pid == -1)
      {
        perror("fork");
        exit(1);
      }
      else if (pid == 0) // child process
      {
        if (execvp(arg, argv) == -1)
        {
          // if there's a return value, there was a problem
          // -1 indicates a problem, specifically
          perror("execvp");
          delete[] argv;
          exit(1);
        }
      }
      else // parent process
      {
        if (waitpid(pid, &exitStatus, 0) == -1)
        {
          perror("waitpid");
          exit(1);
        }
      }
      if (!exitStatus) // all is good (0)
      {
        while (i < cmds.size() && cmds[i].connector == OR)
        {
          ++i;
        }
      }
      else // last command failed
      {
        while (i < cmds.size() && cmds[i].connector == AND)
        {
          ++i;
        }
      }
    }

    // deallocate allocated memory
    for(unsigned i = 0; i < cmds.size(); ++i)
    {
      for(unsigned j = 0; j < cmds[i].args.size(); ++j)
      {
        delete[] cmds[i].args[j];
      }
    }
  }
  printf("Goodbye!\n");
  return 0;
}

<|endoftext|>


<commit_before>//----------------------------------------------------------------------------
// main.cpp
//
// main for pathed
//
// Copyright (C) 2011 Neil Butterworth
//----------------------------------------------------------------------------

#include <iostream>
#include "cmdline.h"
#include "error.h"
#include "registry.h"

using namespace std;

//----------------------------------------------------------------------------
// Flags controling behaviour in various ways.
//----------------------------------------------------------------------------

const char * const ADD_FLAG = "-r";			// add to path
const char * const REM_FLAG = "-r";			// remove from path
const char * const SYS_FLAG = "-s";			// use system instead of user path
const char * const EXIST_FLAG = "-f";		// check path exists on disk
const char * const LIST_FLAG = "-l";		// list current path
const char * const QUERY_FLAG = "-q";		// list current path
const char * const VERIFY_FLAG = "-v";		// verify path

static bool Remove = false,
			Add = false,
			UseSys = false,
			List = false,
			CheckExist = true,
			QueryPath = false,
			Verify = false;

//----------------------------------------------------------------------------
// Set flags from the command line, shifting them off as they are set.
//----------------------------------------------------------------------------

void SetFlags( CmdLine & cl ) {
	while( cl.Argc() > 1 ) {
		string s = cl.Argv(1);
		if ( s.size() && s[0] == '-' ) {
			if ( s == REM_FLAG ) {
				Remove = true;
			}
			else if ( s == ADD_FLAG ) {
				Add = true;
			}
			else if ( s == SYS_FLAG ) {
				UseSys = true;
			}
			else if ( s == EXIST_FLAG ) {
				CheckExist = false;
			}
			else if ( s == LIST_FLAG ) {
				List = true;
			}
			else if ( s == QUERY_FLAG ) {
				QueryPath = true;
			}
			else if ( s == VERIFY_FLAG ) {
				Verify = true;
			}
			else {
				throw Error( "Invalid flag: " + s );
			}
			cl.Shift(1);
		}
		else {
			break;
		}
	}
}

//----------------------------------------------------------------------------
// List PATH to stdout, one directory per line
//----------------------------------------------------------------------------

void ListPath() {
	RegPath path( UseSys ? HKEY_LOCAL_MACHINE : HKEY_CURRENT_USER );
	for ( unsigned int i = 0; i < path.Count(); i++ ) {
		cout << path.At(i) << "\n";
	}
}

//----------------------------------------------------------------------------
// Add an entry to the path
//----------------------------------------------------------------------------

void AddPath( CmdLine & cl ) {
	if ( CheckExist ) {
		DWORD attr = GetFileAttributes( cl.Argv(1).c_str() );
		if ( attr == INVALID_FILE_ATTRIBUTES || ! (attr & FILE_ATTRIBUTE_DIRECTORY ) ) {
			throw Error( "No such directory: " + cl.Argv(1));
		}
	}

	RegPath path( UseSys ? HKEY_LOCAL_MACHINE : HKEY_CURRENT_USER );
	if ( path.Find( cl.Argv(1) ) ) {
		throw Error( cl.Argv(1) + " is already on the path" );
	}
	path.Add( cl.Argv(1) );
}

//----------------------------------------------------------------------------
// Remove entry from the path
//----------------------------------------------------------------------------

void RemovePath( CmdLine & cl ) {
	RegPath path( UseSys ? HKEY_LOCAL_MACHINE : HKEY_CURRENT_USER );
	if ( ! path.Find( cl.Argv(1) ) ) {
		throw Error( cl.Argv(1) + " is not on the path" );
	}
	path.Remove( cl.Argv(1) );
}

//----------------------------------------------------------------------------
// See if directory is on the path, if so return success code (not boolean!)
//----------------------------------------------------------------------------

int FindPath( CmdLine & cl ) {
	RegPath path( UseSys ? HKEY_LOCAL_MACHINE : HKEY_CURRENT_USER );
	return  path.Find( cl.Argv(1) ) ? 0 : 1;
}

//----------------------------------------------------------------------------
// Verify directories on path exist.
//----------------------------------------------------------------------------

int VerifyPath() {
	RegPath path( UseSys ? HKEY_LOCAL_MACHINE : HKEY_CURRENT_USER );
	int bad = 0;
	for ( unsigned int i = 0; i < path.Count(); i++ ) {
		DWORD attr = GetFileAttributes( path.At(i).c_str() );
		if ( attr == INVALID_FILE_ATTRIBUTES ) {
			cout << "No such directory: " << path.At(i) << "\n";
			bad++;
		}
		else if ( ! (attr & FILE_ATTRIBUTE_DIRECTORY ) ) {
			cout << "Not a directory: " << path.At(i) << "\n";
			bad++;
		}
	}
	return bad == 0 ? 0 : 1;
}

//----------------------------------------------------------------------------
// Display help
//----------------------------------------------------------------------------

void Help() {

	cout <<

	"pathed is a command-line tool for changing the Windows path in the registry\n"
	"Version 0.1\n"
	"Copyright (C) 2011 Neil Butterworth\n\n"
	"usage: pathed [-a | -r | -l  | -q | -v] [-s] [-f] [dir]\n\n"
	"pathed -a dir    adds dir to the path in  the registry\n"
	"pathed -r dir    removes  dir from the path in the registry\n"
	"pathed -l        lists the entries on the current path\n"
	"pathed -q dir    queries registry, returns 0 if dir is on path, 1 otherwise\n"
	"pathed -v        verifies that all directories on the path exist\n\n"
	"By default, pathed works on the path in HKEY_CURRENT_USER. You can make it use\n"
	"the system path in HKEY_LOCAL_MACHINE by using the -s flag.\n\n"
	"Normally, pathed will check a directory exists on disk before adding it to the\n"
	"path. To prevent this, use the -f flag.\n\n"
	"AS WITH ALL COMMANDS THAT CHANGE THE REGISTRY, PATHED CAN CAUSE DAMAGE IF YOU\n"
	"DO NOT KNOW WHAT YOU ARE DOING. IF IN DOUBT, DO NOT USE IT!\n"

	<< endl;
}

//----------------------------------------------------------------------------
// Main for pathed
//----------------------------------------------------------------------------

int main( int argc, char *argv[] )
{
	try {
		CmdLine cl( argc, argv );

		SetFlags( cl );

		if ( cl.Argc() == 1 && ! ( List || Verify) ) {
			Help();
			return 0;
		}
		else if ( ! (List || Add || QueryPath || Remove || Verify)  ) {
			throw Error( "Need one of -a, -r, -l, -q or -v" );
		}

		if ( List ) {
			ListPath();
		}
		else if ( Verify ) {
			return VerifyPath();
		}
		else if ( QueryPath ) {
			return FindPath( cl );
		}
		else if ( Remove ) {
			RemovePath( cl );
		}
		else {
			AddPath( cl );
		}

		return 0;
	}
	catch( const Error & e ) {
		cerr << e.what() << endl;
		return 1;
	}
	catch( ... ) {
		cerr << "Unexpected exception" << endl;
		return 1;
	}
}
<commit_msg>initial path expansion stuff ok<commit_after>//----------------------------------------------------------------------------
// main.cpp
//
// main for pathed
//
// Copyright (C) 2011 Neil Butterworth
//----------------------------------------------------------------------------

#include <iostream>
#include "cmdline.h"
#include "error.h"
#include "registry.h"

using namespace std;

//----------------------------------------------------------------------------
// Flags controling behaviour in various ways.
//----------------------------------------------------------------------------

const char * const ADD_FLAG = "-r";			// add to path
const char * const REM_FLAG = "-r";			// remove from path
const char * const SYS_FLAG = "-s";			// use system instead of user path
const char * const EXIST_FLAG = "-f";		// check path exists on disk
const char * const LIST_FLAG = "-l";		// list current path
const char * const QUERY_FLAG = "-q";		// list current path
const char * const VERIFY_FLAG = "-v";		// verify path
const char * const EXPAND_FLAG = "-x";		// expand path

static bool Remove = false,
			Add = false,
			UseSys = false,
			List = false,
			CheckExist = true,
			QueryPath = false,
			Verify = false,
			Expand = false;

//----------------------------------------------------------------------------
// Set flags from the command line, shifting them off as they are set.
//----------------------------------------------------------------------------

void SetFlags( CmdLine & cl ) {
	while( cl.Argc() > 1 ) {
		string s = cl.Argv(1);
		if ( s.size() && s[0] == '-' ) {
			if ( s == REM_FLAG ) {
				Remove = true;
			}
			else if ( s == ADD_FLAG ) {
				Add = true;
			}
			else if ( s == SYS_FLAG ) {
				UseSys = true;
			}
			else if ( s == EXPAND_FLAG ) {
				Expand = true;
			}
			else if ( s == EXIST_FLAG ) {
				CheckExist = false;
			}
			else if ( s == LIST_FLAG ) {
				List = true;
			}
			else if ( s == QUERY_FLAG ) {
				QueryPath = true;
			}
			else if ( s == VERIFY_FLAG ) {
				Verify = true;
			}
			else {
				throw Error( "Invalid flag: " + s );
			}
			cl.Shift(1);
		}
		else {
			break;
		}
	}
}

//----------------------------------------------------------------------------
// Get env var value
//----------------------------------------------------------------------------

string GetEnv( const string &  name ) {
	const char * val = getenv( name.c_str() );
	return val == 0 ? "" : val;
}

//----------------------------------------------------------------------------
// Expand occurrences of %X% in the path name with the relevant environment
// variable setting.
//----------------------------------------------------------------------------

string ExpandPath( const std::string &  adir ) {
	string rv, envname;
	bool inenv = false;
	unsigned int i = 0;
	while( i < adir.size() ) {
		char c = adir[i++];
		if ( c == '%' && inenv ) {
			rv += GetEnv( envname );
			inenv = false;
			envname = "";
		}
		else if ( c == '%' && ! inenv ) {
			envname = "";
			inenv = true;
		}
		else if ( inenv ) {
			envname += c;
		}
		else {
			rv += c;
		}
	}
	if ( envname != "" ) {
		rv += GetEnv( envname );
	}
	return rv;
}

//----------------------------------------------------------------------------
// List PATH to stdout, one directory per line
//----------------------------------------------------------------------------

void ListPath() {
	RegPath path( UseSys ? HKEY_LOCAL_MACHINE : HKEY_CURRENT_USER );
	for ( unsigned int i = 0; i < path.Count(); i++ ) {
		cout << ( Expand ? ExpandPath( path.At(i) ) : path.At(i) ) << "\n";
	}
}

//----------------------------------------------------------------------------
// Add an entry to the path
//----------------------------------------------------------------------------

void AddPath( CmdLine & cl ) {
	if ( CheckExist ) {
		DWORD attr = GetFileAttributes( cl.Argv(1).c_str() );
		if ( attr == INVALID_FILE_ATTRIBUTES || ! (attr & FILE_ATTRIBUTE_DIRECTORY ) ) {
			throw Error( "No such directory: " + cl.Argv(1));
		}
	}

	RegPath path( UseSys ? HKEY_LOCAL_MACHINE : HKEY_CURRENT_USER );
	if ( path.Find( cl.Argv(1) ) ) {
		throw Error( cl.Argv(1) + " is already on the path" );
	}
	path.Add( cl.Argv(1) );
}

//----------------------------------------------------------------------------
// Remove entry from the path
//----------------------------------------------------------------------------

void RemovePath( CmdLine & cl ) {
	RegPath path( UseSys ? HKEY_LOCAL_MACHINE : HKEY_CURRENT_USER );
	if ( ! path.Find( cl.Argv(1) ) ) {
		throw Error( cl.Argv(1) + " is not on the path" );
	}
	path.Remove( cl.Argv(1) );
}

//----------------------------------------------------------------------------
// See if directory is on the path, if so return success code (not boolean!)
//----------------------------------------------------------------------------

int FindPath( CmdLine & cl ) {
	RegPath path( UseSys ? HKEY_LOCAL_MACHINE : HKEY_CURRENT_USER );
	return  path.Find( cl.Argv(1) ) ? 0 : 1;
}

//----------------------------------------------------------------------------
// Verify directories on path exist.
//----------------------------------------------------------------------------

int VerifyPath() {
	RegPath path( UseSys ? HKEY_LOCAL_MACHINE : HKEY_CURRENT_USER );
	int bad = 0;
	for ( unsigned int i = 0; i < path.Count(); i++ ) {
		string epath = Expand ? ExpandPath( path.At(i) ) : path.At(i);
		DWORD attr = GetFileAttributes( epath.c_str() );
		if ( attr == INVALID_FILE_ATTRIBUTES ) {
			cout << "No such directory: " << epath << "\n";
			bad++;
		}
		else if ( ! (attr & FILE_ATTRIBUTE_DIRECTORY ) ) {
			cout << "Not a directory: " << epath << "\n";
			bad++;
		}
	}
	return bad == 0 ? 0 : 1;
}

//----------------------------------------------------------------------------
// Display help
//----------------------------------------------------------------------------

void Help() {

	cout <<

	"pathed is a command-line tool for changing the Windows path in the registry\n"
	"Version 0.1\n"
	"Copyright (C) 2011 Neil Butterworth\n\n"
	"usage: pathed [-a | -r | -l  | -q | -v] [-s] [-f]  [-x] [dir]\n\n"
	"pathed -a dir    adds dir to the path in  the registry\n"
	"pathed -r dir    removes  dir from the path in the registry\n"
	"pathed -l        lists the entries on the current path\n"
	"pathed -q dir    queries registry, returns 0 if dir is on path, 1 otherwise\n"
	"pathed -v        verifies that all directories on the path exist\n\n"
	"By default, pathed works on the path in HKEY_CURRENT_USER. You can make it use\n"
	"the system path in HKEY_LOCAL_MACHINE by using the -s flag.\n\n"
	"Normally, pathed will check a directory exists on disk before adding it to the\n"
	"path. To prevent this, use the -f flag.\n\n"
	"Paths conting environment variables such as %systemroot% will not normally have\n"
	"the variables expanded to their values. To expand them, use the -x flag\n\n"
	"AS WITH ALL COMMANDS THAT CHANGE THE REGISTRY, PATHED CAN CAUSE DAMAGE IF YOU\n"
	"DO NOT KNOW WHAT YOU ARE DOING. IF IN DOUBT, DO NOT USE IT!\n"

	<< endl;
}

//----------------------------------------------------------------------------
// Main for pathed
//----------------------------------------------------------------------------

int main( int argc, char *argv[] )
{
	try {
		CmdLine cl( argc, argv );

		SetFlags( cl );

		if ( cl.Argc() == 1 && ! ( List || Verify) ) {
			Help();
			return 0;
		}
		else if ( ! (List || Add || QueryPath || Remove || Verify)  ) {
			throw Error( "Need one of -a, -r, -l, -q or -v" );
		}

		if ( List ) {
			ListPath();
		}
		else if ( Verify ) {
			return VerifyPath();
		}
		else if ( QueryPath ) {
			return FindPath( cl );
		}
		else if ( Remove ) {
			RemovePath( cl );
		}
		else {
			AddPath( cl );
		}

		return 0;
	}
	catch( const Error & e ) {
		cerr << e.what() << endl;
		return 1;
	}
	catch( ... ) {
		cerr << "Unexpected exception" << endl;
		return 1;
	}
}
<|endoftext|>


<commit_before>/*
 * main.cpp
 *
 * Author: Ben Lai, Ming Tsang, Peggy Lau
 * Copyright (c) 2015 HKUST SmartCar Team
 * Refer to LICENSE for details
 */

#include <libbase/k60/mcg.h>

#include <libsc/lib_guard.h>
#include <libsc/k60/system.h>

#include "launcher.h"

using namespace camera;

namespace libbase
{
namespace k60
{

Mcg::Config Mcg::GetMcgConfig()
{
	Mcg::Config config;
	config.external_oscillator_khz = 50000;
	config.core_clock_khz = 150000;
	return config;
}

}
}

int main()
{
	LIBSC_GUARD();

	libsc::k60::System::Init();

	Launcher launcher(nullptr);
	launcher.Run();
	return 0;
}
<commit_msg>Use default clock<commit_after>/*
 * main.cpp
 *
 * Author: Ben Lai, Ming Tsang, Peggy Lau
 * Copyright (c) 2015 HKUST SmartCar Team
 * Refer to LICENSE for details
 */

#include <libbase/k60/mcg.h>

#include <libsc/lib_guard.h>
#include <libsc/k60/system.h>

#include "launcher.h"

using namespace camera;

namespace libbase
{
namespace k60
{

Mcg::Config Mcg::GetMcgConfig()
{
	Mcg::Config config;
	config.external_oscillator_khz = 50000;
	//config.core_clock_khz = 150000;
	return config;
}

}
}

int main()
{
	LIBSC_GUARD();

	libsc::k60::System::Init();

	Launcher launcher(nullptr);
	launcher.Run();
	return 0;
}
<|endoftext|>


<commit_before>#include <iostream>
#include <mutex>
#include <queue>
#include <thread>
#include <tuple>
#include <condition_variable>

#include "input_file_reader.hpp"
#include "minimize.hpp"
#include "comparator.hpp"
#include "result.hpp"

// mutex for shared resources
static std::mutex g_tasks_mutex;

// conditonal variable for shared resources
static std::condition_variable g_cv;

// global queue with two pointers to the sequences
// they are compared directly if the both sequence lengths are small enough
static std::queue<std::tuple<OLC::Sequence*, OLC::Sequence*>> g_sequence_pairs;

// global queue with two pointers to vectors of minimizers
// we use this instead if the sequences are too long
static std::queue<std::tuple<std::vector<OLC::Minimizer>*, std::vector<OLC::Minimizer>*>> g_minimizer_pairs;

static void worker()
{
  // Get the task and remove it from the pool
  g_tasks_mutex.lock();

  const std::tuple<OLC::Sequence*, OLC::Sequence*> sequence_pair = g_sequence_pairs.front();
  g_sequence_pairs.pop();
  const std::tuple<std::vector<OLC::Minimizer>*, std::vector<OLC::Minimizer>*> minimizer_pair = g_minimizer_pairs.front();
  g_minimizer_pairs.pop();

  g_tasks_mutex.unlock();

  // Get the task sequences
  const OLC::Sequence* sequence1 = std::get<0>(sequence_pair);
  const OLC::Sequence* sequence2 = std::get<1>(sequence_pair);

  // Pull out the wrapped nucleotide vectors
  const std::vector<OLC::Nucleotide> nucleotides1 = sequence1->getNucleotides()->getSequence();
  const std::vector<OLC::Nucleotide> nucleotides2 = sequence2->getNucleotides()->getSequence();

  // If small enough, no need to use minimizers
  if (nucleotides1.size() < 20000 && nucleotides2.size() < 20000)
  {
    const OLC::Overlap overlap = compare(nucleotides1, nucleotides2);
    const uint32_t overlapFirstEnd = overlap.getEndFirst();
    const uint32_t overlapSecondEnd = overlap.getEndSecond();
    const uint32_t overlapFirstStart = overlap.getStartFirst();
    const uint32_t overlapSecondStart = overlap.getStartSecond();
    const uint32_t overlapLength = overlapFirstEnd - overlapFirstStart + 1;

    const std::string sequence1_ident = sequence1->getIdentifier();
    const std::string sequence2_ident = sequence2->getIdentifier();

    int32_t ahang = overlapFirstStart;
    int32_t bhang = nucleotides2.size() - overlapSecondEnd;

    if (overlapSecondStart > overlapFirstStart)
      ahang *= 1;

    if (nucleotides1.size() > overlapSecondEnd)
      bhang *= 1;

    //TODO: Add into result queue
    const OLC::Result result(sequence1_ident, sequence2_ident, overlapLength, ahang, bhang);
  }
  else
  {

  }

  return;
}

int main(int argc, char** argv)
{
  std::ios_base::sync_with_stdio(false);

  if (argc != 3)
  {
    std::cout << "Usage: " << argv[0] << " <minimum overlap length L> <FASTQ or FASTA file>\n";
    return 1;
  }

  // file with the data
  const std::string file = std::string(argv[2]);

  // L is the minimum overlap length
  const uint32_t L = std::stoi(argv[1]);

  // window size
  const uint32_t w = (L + 1) / 2;

  // size of the k-mer
  const uint32_t k = (L + 1) / 2;

  // read phase
  OLC::InputFileReader reader(file);
  const std::vector<OLC::Sequence*> sequences = reader.readSequences();
  std::vector<std::vector<OLC::Minimizer>> minimizers;

  for (size_t i = 0; i < sequences.size(); ++i)
  {
    const auto sequence = sequences[i]->getNucleotides()->getSequence();

    // calculate minimizers - both interior and end minimizers
    minimizers.push_back(minimize(sequence, w, k));
  }

  // generate tasks so we can do this in parallel if possible
  std::queue<std::tuple<uint32_t, uint32_t>> tasks;

  for (uint32_t i = 0; i < sequences.size(); ++i)
  {
    for (uint32_t j = i + 1; j < sequences.size(); ++j)
    {
      g_sequence_pairs.emplace(sequences[i], sequences[j]);
      g_minimizer_pairs.emplace(&minimizers[i], &minimizers[j]);
    }
  }

  // use concurrent minimizer matching
  std::vector<std::thread> threads(std::thread::hardware_concurrency());

  for (uint8_t i = 0; i < threads.size(); ++i)
    threads[i] = std::thread(worker);

  for (uint8_t i = 0; i < threads.size(); ++i)
    threads[i].join();

  // cleanup
  for (size_t i = 0; i < sequences.size(); ++i)
    delete sequences[i];

  return 0;
}
<commit_msg>main: Fix negative ahang and bhang<commit_after>#include <iostream>
#include <mutex>
#include <queue>
#include <thread>
#include <tuple>
#include <condition_variable>

#include "input_file_reader.hpp"
#include "minimize.hpp"
#include "comparator.hpp"
#include "result.hpp"

// mutex for shared resources
static std::mutex g_tasks_mutex;

// conditonal variable for shared resources
static std::condition_variable g_cv;

// global queue with two pointers to the sequences
// they are compared directly if the both sequence lengths are small enough
static std::queue<std::tuple<OLC::Sequence*, OLC::Sequence*>> g_sequence_pairs;

// global queue with two pointers to vectors of minimizers
// we use this instead if the sequences are too long
static std::queue<std::tuple<std::vector<OLC::Minimizer>*, std::vector<OLC::Minimizer>*>> g_minimizer_pairs;

static void worker()
{
  // Get the task and remove it from the pool
  g_tasks_mutex.lock();

  const std::tuple<OLC::Sequence*, OLC::Sequence*> sequence_pair = g_sequence_pairs.front();
  g_sequence_pairs.pop();
  const std::tuple<std::vector<OLC::Minimizer>*, std::vector<OLC::Minimizer>*> minimizer_pair = g_minimizer_pairs.front();
  g_minimizer_pairs.pop();

  g_tasks_mutex.unlock();

  // Get the task sequences
  const OLC::Sequence* sequence1 = std::get<0>(sequence_pair);
  const OLC::Sequence* sequence2 = std::get<1>(sequence_pair);

  // Pull out the wrapped nucleotide vectors
  const std::vector<OLC::Nucleotide> nucleotides1 = sequence1->getNucleotides()->getSequence();
  const std::vector<OLC::Nucleotide> nucleotides2 = sequence2->getNucleotides()->getSequence();

  // If small enough, no need to use minimizers
  if (nucleotides1.size() < 20000 && nucleotides2.size() < 20000)
  {
    const OLC::Overlap overlap = compare(nucleotides1, nucleotides2);
    const uint32_t overlapFirstEnd = overlap.getEndFirst();
    const uint32_t overlapSecondEnd = overlap.getEndSecond();
    const uint32_t overlapFirstStart = overlap.getStartFirst();
    const uint32_t overlapSecondStart = overlap.getStartSecond();
    const uint32_t overlapLength = overlapFirstEnd - overlapFirstStart + 1;

    const std::string sequence1_ident = sequence1->getIdentifier();
    const std::string sequence2_ident = sequence2->getIdentifier();

    int32_t ahang = overlapFirstStart;
    int32_t bhang = nucleotides2.size() - overlapSecondEnd;

    if (overlapSecondStart > overlapFirstStart) {
      ahang *= -1;
    }

    if (nucleotides1.size() > overlapSecondEnd) {
      bhang *= -1;
    }

    //TODO: Add into result queue
    const OLC::Result result(sequence1_ident, sequence2_ident, overlapLength, ahang, bhang);
  }
  else
  {

  }

  return;
}

int main(int argc, char** argv)
{
  std::ios_base::sync_with_stdio(false);

  if (argc != 3)
  {
    std::cout << "Usage: " << argv[0] << " <minimum overlap length L> <FASTQ or FASTA file>\n";
    return 1;
  }

  // file with the data
  const std::string file = std::string(argv[2]);

  // L is the minimum overlap length
  const uint32_t L = std::stoi(argv[1]);

  // window size
  const uint32_t w = (L + 1) / 2;

  // size of the k-mer
  const uint32_t k = (L + 1) / 2;

  // read phase
  OLC::InputFileReader reader(file);
  const std::vector<OLC::Sequence*> sequences = reader.readSequences();
  std::vector<std::vector<OLC::Minimizer>> minimizers;

  for (size_t i = 0; i < sequences.size(); ++i)
  {
    const auto sequence = sequences[i]->getNucleotides()->getSequence();

    // calculate minimizers - both interior and end minimizers
    minimizers.push_back(minimize(sequence, w, k));
  }

  // generate tasks so we can do this in parallel if possible
  std::queue<std::tuple<uint32_t, uint32_t>> tasks;

  for (uint32_t i = 0; i < sequences.size(); ++i)
  {
    for (uint32_t j = i + 1; j < sequences.size(); ++j)
    {
      g_sequence_pairs.emplace(sequences[i], sequences[j]);
      g_minimizer_pairs.emplace(&minimizers[i], &minimizers[j]);
    }
  }

  // use concurrent minimizer matching
  std::vector<std::thread> threads(std::thread::hardware_concurrency());

  for (uint8_t i = 0; i < threads.size(); ++i)
    threads[i] = std::thread(worker);

  for (uint8_t i = 0; i < threads.size(); ++i)
    threads[i].join();

  // cleanup
  for (size_t i = 0; i < sequences.size(); ++i)
    delete sequences[i];

  return 0;
}
<|endoftext|>


<commit_before>/*
	Optimal Read Normalization Algorithm:
	Developed by : Dilip A Durai and Marcel H Schulz
*/

#include <gatb/gatb_core.hpp>
#include <iostream>
#include <string.h>
#include <math.h>
#include <algorithm>

typedef Kmer<>::Type bloom;
static const char* STR_BASE = "-base";
static const char* STR_INPUT = "-input";
static const char* STR_OUTPUT = "-output";
static const char* STR_KMER = "-kmer";

int readacceptance(Graph graph, Kmer<>::ModelCanonical::Iterator itKmer, Kmer<>::ModelCanonical model, unsigned int *counter, double base){
	int acceptance=0;
	for (itKmer.first(); !itKmer.isDone(); itKmer.next())
	{
		std::string s = model.toString (itKmer->value());
		const char* sq = s.c_str();
		Node node = graph.buildNode(sq);
		double threshold=0;
		//Checking whether the node exists.
		auto index = graph.nodeMPHFIndex(node);
		auto abund = graph.queryAbundance(node);
		threshold = ceil((log(abund)/log(base)));
		if(threshold>abund)
		{
			threshold=abund;
		}
		if(threshold<1)
		{
			threshold=1;
		}
		if(counter[index] < threshold)
		{
			__sync_fetch_and_add (&acceptance, 1);
			//__sync_fetch_and_add (&counter[index], 1);
	       	}
	}
	return acceptance;
}

class ORNA : public Tool
{
public:
	ORNA(): Tool("ORNA")
	{
		getParser()->push_front (new OptionOneParam (STR_KMER, "kmer required",  false, "21"));
	        getParser()->push_front (new OptionOneParam (STR_INPUT, "Input File",  true));
	        getParser()->push_front (new OptionOneParam (STR_OUTPUT, "Output File",  true));
		getParser()->push_front (new OptionOneParam (STR_BASE, "Base for the logarithmic function",  true));

	}
	void execute()
	{
		int count=0;
		double base=getInput()->getDouble(STR_BASE);
		int user_kmer = getInput()->getInt(STR_KMER);
		int kmer = user_kmer + 1;
		const char* filename = (getInput()->get(STR_INPUT))->getString();
		const char* out_file= (getInput()->get(STR_OUTPUT))->getString();

		int nbCores = getInput()->getInt(STR_NB_CORES);

		Dispatcher dispatcher(nbCores) ;
		ISynchronizer* synchro = System::thread().newSynchronizer();	//Locking a section

		//Variables required for GATB
		IBank* bank = Bank::open (filename);
		ProgressIterator<Sequence> itSeq (*bank);
		IBank* outBank = new BankFasta (out_file);

		//Creating a graph and an iterator. from the parameters. The threshold value is kept as the minimum abundance parameter of the graph. kmer size is the actual kmer+1
		Graph graph = Graph::create (Bank::open(filename), "-kmer-size %d -abundance-min 1", kmer);
		GraphIterator<Node> it = graph.iterator();

		long node_size= it.size();
		unsigned int *counter = new unsigned int[node_size];

		//Initializing the counter for each node in the de Bruijn graph
		for(int i=0;i<node_size;i++)
		{
		    counter[i]=0;
		}

		//Iterating over sequences
		dispatcher.iterate (itSeq, [&] (Sequence& seq)
		{
			int length = seq.getDataSize();
			int flag=1;
			int gb = 1;
			int acceptance=0;

			Kmer<>::ModelCanonical model (kmer);
			Kmer<>::ModelCanonical::Iterator itKmer (model);
			itKmer.setData (seq.getData());
			char* data = seq.getDataBuffer();
			//checking the thresholding
			if(flag==1){
				acceptance=readacceptance(graph, itKmer, model, counter, base);
			}
			if(acceptance > 0)
			{
				for (itKmer.first(); !itKmer.isDone(); itKmer.next())
				{
					std::string s = model.toString (itKmer->value());
					const char* sq = s.c_str();
					Node node = graph.buildNode(sq);
					//Checking whether the node exists.
					if(graph.contains(node))
		       			{
						auto index = graph.nodeMPHFIndex(node);
						__sync_fetch_and_add (&counter[index], 1);
					}
				}
				synchro->lock();
				outBank->insert(seq);
				count++;
				synchro->unlock();
			}

		});
		std::cout << "Kept " << count << " reads" <<  std::endl;

		//Free the memory
		std::string filename1 = string(filename).substr(string(filename).find_last_of("/\\") + 1);
		size_t lindex = filename1.find_last_of(".");
		filename1 = (filename1.substr(0,lindex)) + string(".h5");
		remove(filename1.c_str());

		delete [] counter;
		bank->flush();
		outBank->flush();
	}
};

int main (int argc, char* argv[])
{
	try{
		ORNA().run(argc,argv);
		return EXIT_SUCCESS;
	}
	catch(Exception& e){
		std::cout << "EXCEPTION: " << e.getMessage() << std::endl;
        	return EXIT_FAILURE;
	}

}

<commit_msg>Paired end mode addition<commit_after>/*
	Optimal Read Normalization Algorithm:
	Developed by : Dilip A Durai and Marcel H Schulz
*/

#include <gatb/gatb_core.hpp>
#include <iostream>
#include <string.h>
#include <math.h>
#include <algorithm>

typedef Kmer<>::Type bloom;
static const char* STR_BASE = "-base";
static const char* STR_INPUT = "-input";
static const char* STR_OUTPUT = "-output";
static const char* STR_KMER = "-kmer";
static const char* STR_PAIR1 = "-pair1";
static const char* STR_PAIR2 = "-pair2";

int readacceptance(Graph graph, Kmer<>::ModelCanonical::Iterator itKmer, Kmer<>::ModelCanonical model, unsigned short *counter, double base){
	int acceptance=0;
	for (itKmer.first(); !itKmer.isDone(); itKmer.next())
	{
		std::string s = model.toString (itKmer->value());
		const char* sq = s.c_str();
		Node node = graph.buildNode(sq);
		double threshold=0;
		//Checking whether the node exists.
		auto index = graph.nodeMPHFIndex(node);
		auto abund = graph.queryAbundance(node);
		threshold = ceil((log(abund)/log(base)));
		if(threshold>abund)
		{
			threshold=abund;
		}
		if(threshold<1)
		{
			threshold=1;
		}
		if(counter[index] < threshold)
		{
			__sync_fetch_and_add (&acceptance, 1);
			break;
			//__sync_fetch_and_add (&counter[index], 1);
	       	}
	}
	return acceptance;
}

void singleend(const char* filename, const char* out_file, double base, unsigned short kmer, int nbCores)
{
	int count=0;
	//const char* error = getError(filename , pair1, pair2);

	Dispatcher dispatcher(nbCores) ;
	ISynchronizer* synchro = System::thread().newSynchronizer();	//Locking a section

	//Variables required for GATB
	IBank* bank = Bank::open (filename);
	ProgressIterator<Sequence> itSeq (*bank);
	IBank* outBank = new BankFasta (out_file);

	//Creating a graph and an iterator. from the parameters. The threshold value is kept as the minimum abundance parameter of the graph. kmer size is the actual kmer+1
	Graph graph = Graph::create (Bank::open(filename), "-kmer-size %d -abundance-min 1", kmer);
	GraphIterator<Node> it = graph.iterator();

	long node_size= it.size();
	unsigned short *counter = new unsigned short[node_size];

	//Initializing the counter for each node in the de Bruijn graph
	for(int i=0;i<node_size;i++)
	{
	    counter[i]=0;
	}

	//Iterating over sequences
	dispatcher.iterate (itSeq, [&] (Sequence& seq)
	{
		int length = seq.getDataSize();
		int flag=1;
		int gb = 1;
		int acceptance=0;

		Kmer<>::ModelCanonical model (kmer);
		Kmer<>::ModelCanonical::Iterator itKmer (model);
		itKmer.setData (seq.getData());
		char* data = seq.getDataBuffer();

		//checking the thresholding
		if(flag==1){
			acceptance=readacceptance(graph, itKmer, model, counter, base);
		}
		if(acceptance > 0)
		{
			for (itKmer.first(); !itKmer.isDone(); itKmer.next())
			{
				std::string s = model.toString (itKmer->value());
				const char* sq = s.c_str();
				Node node = graph.buildNode(sq);
				//Checking whether the node exists.
				if(graph.contains(node))
	       			{
					auto index = graph.nodeMPHFIndex(node);
					__sync_fetch_and_add (&counter[index], 1);
				}
			}
			synchro->lock();
			outBank->insert(seq);
			count++;
			synchro->unlock();
		}

	});
	std::cout << "Kept " << count << " reads" <<  std::endl;

	//Free the memory
	std::string filename1 = string(filename).substr(string(filename).find_last_of("/\\") + 1);
	size_t lindex = filename1.find_last_of(".");
	filename1 = (filename1.substr(0,lindex)) + string(".h5");
	remove(filename1.c_str());

	delete [] counter;
	bank->flush();
	outBank->flush();
}

void pairedend(const char* read1, const char* read2, const char* out_file, double base, unsigned short kmer )
{
	IBank* bank1 = Bank::open (read1);
	LOCAL (bank1);
        IBank* bank2 = Bank::open (read2);
	LOCAL (bank2);

	IBank* outBank = new BankFasta (out_file);

	Graph graph = Graph::create ("-in %s,%s -kmer-size %d -abundance-min 1", read1, read2, kmer);
	GraphIterator<Node> NodeIterator = graph.iterator();
	long node_size= NodeIterator.size();
	unsigned short *counter = new unsigned short[node_size];

	for(int i=0;i<node_size;i++)
        {
            counter[i]=0;
        }

	int cnt=0;
	int count=0;
	int num_sequence=0;
	int *pos;
	int size;
	int index;
	unsigned short length;
	int tmp=0;

	// We iterate the two banks. Note how we provide two iterators from the two banks.
        PairedIterator<Sequence> itPair (bank1->iterator(), bank2->iterator());
        for(itPair.first(); !itPair.isDone(); itPair.next())
        {
        	num_sequence++;
        }
        //int inisize=2;
	std::vector<int> tempBank;

	Kmer<>::ModelCanonical model (kmer);
	Kmer<>::ModelCanonical::Iterator itKmer (model);
	Kmer<>::ModelCanonical::Iterator itKmer1 (model);

	//Iteration 1

	for (itPair.first(); !itPair.isDone(); itPair.next())
        {
            Sequence& s1 = itPair.item().first;
            Sequence& s2 = itPair.item().second;

	    int acceptance1=0;
	    int acceptance2=0;

	    itKmer.setData (s1.getData());
	    itKmer1.setData (s2.getData());

	    //checking the thresholding
	    acceptance1 = readacceptance(graph, itKmer, model, counter, base);
	    acceptance2 = readacceptance(graph, itKmer1, model, counter, base);
	    if(acceptance1 > 0 && acceptance2>0)
	    {
		for (itKmer.first(); !itKmer.isDone(); itKmer.next())
	    	{
			std::string s = model.toString (itKmer->value());
			const char* sq = s.c_str();
			Node node = graph.buildNode(sq);
			double threshold=0;
			//Checking whether the node exists.
			if(graph.contains(node))
			{
				auto index = graph.nodeMPHFIndex(node);
				auto abund = graph.queryAbundance(node);
				threshold = ceil((log(abund)/log(base)));
				if(threshold>abund)
				{
					threshold=abund;
				}
				if(threshold<1)
				{
					threshold=1;
				}
				if(counter[index] < threshold)
				{
					counter[index]=counter[index]+1;
				}
			}
		}
		for (itKmer1.first(); !itKmer1.isDone(); itKmer1.next())
	    	{
			std::string s = model.toString (itKmer1->value());
			const char* sq = s.c_str();
			Node node = graph.buildNode(sq);
			double threshold=0;
			//Checking whether the node exists.
			if(graph.contains(node))
			{
				auto index = graph.nodeMPHFIndex(node);
				auto abund = graph.queryAbundance(node);
				threshold = ceil((log(abund)/log(base)));
				if(threshold>abund)
				{
					threshold=abund;
				}
				if(threshold<1)
				{
					threshold=1;
				}
				if(counter[index] < threshold)
				{
					counter[index]=counter[index]+1;
				}
			}
	    	}
	    	outBank->insert(s1);
		outBank->insert(s2);
		count++;
	    }
	    else if(acceptance1>0 || acceptance2>0){
	      	tempBank.push_back(tmp);
	    }
	    else{
	    }
	    tmp++;
        }

	int coun=0;
	int tmp_index=0;
	std::cout << "Second Iteration" <<  std::endl;

	for (itPair.first(); !itPair.isDone() && tmp_index<tempBank.size(); itPair.next())
	{
        	if(coun==tempBank[tmp_index])
        	{
		    Sequence& s1 = itPair.item().first;
		    Sequence& s2 = itPair.item().second;

		    int acceptance1=0;
		    int acceptance2=0;
		    int acceptance=0;

		    itKmer.setData (s1.getData());
		    itKmer1.setData (s2.getData());

		    //checking the thresholding
		    acceptance1 = readacceptance(graph, itKmer, model, counter, base);
		    acceptance2 = readacceptance(graph, itKmer1, model, counter, base);

		    if(acceptance1 > 0 || acceptance2 > 0)
		    {
			for (itKmer1.first(); !itKmer1.isDone(); itKmer1.next())
		    	{
				std::string s = model.toString (itKmer->value());
				const char* sq = s.c_str();
				Node node = graph.buildNode(sq);
				double threshold=0;
				//Checking whether the node exists.
				if(graph.contains(node)){
					auto index = graph.nodeMPHFIndex(node);
					auto abund = graph.queryAbundance(node);
					threshold = ceil((log(abund)/log(base)));
					if(threshold>abund){
						threshold=abund;
					}
					if(threshold<1){
						threshold=1;
					}
					if(counter[index] < threshold){
						counter[index]=counter[index]+1;
					}
				}
			}
			for (itKmer.first(); !itKmer.isDone(); itKmer.next())
		    	{
				std::string s = model.toString (itKmer->value());
				const char* sq = s.c_str();
				Node node = graph.buildNode(sq);
				double threshold=0;
				//Checking whether the node exists.
				if(graph.contains(node))
				{
					auto index = graph.nodeMPHFIndex(node);
					auto abund = graph.queryAbundance(node);
					threshold = ceil((log(abund)/log(base)));
					if(threshold>abund)
					{
						threshold=abund;
					}
					if(threshold<1)
					{
						threshold=1;
					}
					if(counter[index] < threshold)
					{
						counter[index]=counter[index]+1;
					}
				}
		    	}
			outBank->insert(s1);
			outBank->insert(s2);
			count++;
		   }
		   tmp_index++;
		}
		coun++;
        }
	std::cout << "kept " << count << " reads" <<  std::endl;
	bank1->flush();
	bank2->flush();
	delete [] counter;
	outBank->flush();
}

class ORNA : public Tool
{
public:
	ORNA(): Tool("ORNA")
	{
		getParser()->push_front (new OptionOneParam (STR_KMER, "kmer required",  false, "21"));
	        getParser()->push_front (new OptionOneParam (STR_INPUT, "Input File",  false, "ORNAERROR"));
	        getParser()->push_front (new OptionOneParam (STR_OUTPUT, "Output File",  false, "Normalized.fa"));
		getParser()->push_front (new OptionOneParam (STR_BASE, "Base for the logarithmic function",  false, "3"));
		getParser()->push_front (new OptionOneParam (STR_PAIR1, "First read of the pair", false, "ORNAERROR" ));
		getParser()->push_front (new OptionOneParam (STR_PAIR2, "Second read of the pair", false, "ORNAERROR" ));
	}
	void execute()
	{
		const char* filename = (getInput()->get(STR_INPUT))->getString();
		const char* read1= (getInput()->get(STR_PAIR1))->getString();
		const char* read2= (getInput()->get(STR_PAIR2))->getString();
		double base=getInput()->getDouble(STR_BASE);
		int user_kmer = getInput()->getInt(STR_KMER);
		const char* out_file= (getInput()->get(STR_OUTPUT))->getString();
		int nbCores = getInput()->getInt(STR_NB_CORES);
		unsigned short pairflag = 0;
		unsigned short kmer = user_kmer + 1;
		unsigned short cores = sysconf(_SC_NPROCESSORS_ONLN);
		if(nbCores==cores){
			nbCores=1;
		}
		if(std::strcmp(filename, "ORNAERROR") == 0)
		{
			std::cout << "Running ORNA in paired end mode" << std::endl;
			if((std::strcmp(read1, "ORNAERROR") == 0) && (std::strcmp(read2, "ORNAERROR") == 0))
			{
				std::cout << "Input File(s) missing. Please refer to the help" << std::endl;
			}
			if (((std::strcmp(read1, "ORNAERROR") != 0) && (std::strcmp(read2, "ORNAERROR") == 0)) || ((std::strcmp(read1, "ORNAERROR") == 0) && (std::strcmp(read2, "ORNAERROR") != 0)))
			{
				std::cout << "One of the pair files is missing. Please refer to the help" << std::endl;
			}
			if((std::strcmp(read1, "ORNAERROR") != 0) && (std::strcmp(read2, "ORNAERROR") != 0))
			{
				pairflag = 1;
			}
		}
		if(pairflag==0)
		{
			std::cout << "Running ORNA in single end mode" << std::endl;
			singleend(filename, out_file, base, kmer, nbCores);
		}
		else
		{
			std::cout << "Running ORNA in paired end mode" << std::endl;
			pairedend(read1, read2, out_file, base, kmer);
		}
	}
};

int main (int argc, char* argv[])
{
	try{
		ORNA().run(argc,argv);
		return EXIT_SUCCESS;
	}
	catch(Exception& e){
		std::cout << "EXCEPTION: " << e.getMessage() << std::endl;
        	return EXIT_FAILURE;
	}

}

<|endoftext|>


<commit_before>#include <sys/types.h>
#include <netinet/in.h>

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

	return 0;
}
<commit_msg>Added binding to socket at specified address. Error messages added for when binding or connection fails.<commit_after>#include <sys/types.h>
#include <netinet/in.h>
#include <sys/socket.h>

int main(int argc, char *argv[])
{
	//Declare a socket instance here.
	struct sockaddr_in server;
	string address = "192.168.0.1";
	inet_aton(address, &server.sin_addr.s_addr);

	int s = socket(AF_INET, SOCK_STREAM, 0);

	if (s == -1) {
		cout << "Invalid socket descriptor.";
		return -1;
	} else {
		cout << "Socket bound.";
	}

	cout << "Connecting to socket on address: " << address << " port: "
			<< server.sin_port << endl;

	if (connect(s, (struct sockaddr *) &server, sizeof(server)) == -1) {
		cout << "Socket connection failed.";
		return -1;
	}

	//Instantiate reader thread here; bind to connected socket.
	//Instantiate writer thread here; bind to connected socket.

	//Signal the writer thread to subscribe to the events.
	//Put the following into the buffer, and notify the writer thread:
	//out = "request(100,view)\n";
	//writerThread.notify();

	//Begin main control loop:
	//{
	//	//Check if we've received something from the socket.
		//The local buffer will contain it since the reader thread outputs directly into the buffer.
		//cout << "RECEIVED COMMAND: " << endl;
		//cout << buffer << endl;
	//}

	return 0;
}
<|endoftext|>