<commit_before>#ifndef __BH_VE_CPU_BACKENDS
#define __BH_VE_CPU_BACKENDS

#include <iostream>
#include <cstring>
#include <cstdarg>
#include <cstdlib>
#include <cstdio>
#include <string>
#include <cstring>
#include <stdexcept>
#include <vector>
#include <unordered_map>
#include "dirent.h"
#include <dlfcn.h>
#include <unistd.h>
#include "utils.cpp"
#include <fcntl.h>

// Create nice error-messages...
int error(int errnum, const char *fmt, ...) {
    va_list va;
    int ret;

    char err_msg[500];
    sprintf(err_msg, "Error[%d, %s] from: %s", errnum, strerror(errnum), fmt);
    va_start(va, fmt);
    ret = vfprintf(stderr, err_msg, va);
    va_end(va);
    return ret;
}

int error(const char *err_msg, const char *fmt, ...) {
    va_list va;
    int ret;

    char err_txt[500];
    sprintf(err_txt, "Error[%s] from: %s", err_msg, fmt);
    va_start(va, fmt);
    ret = vfprintf(stderr, err_txt, va);
    va_end(va);
    return ret;
}

typedef void (*func)(int tool, ...);
//typedef std::map<std::string, func> func_storage;
//typedef std::map<std::string, void*> handle_storage;

typedef std::unordered_map<std::string, func> func_storage;
typedef std::unordered_map<std::string, void*> handle_storage;

/**
 *  TODO: Load existing objects at startup.
 *          Then pre-compilation and warmup rounds will be possible.
 */

/**
 * The compiler interface.
 *
 * Becomes what it compiles.
 */
class compiler {
public:
    virtual bool compile(std::string symbol, const char* sourcecode, size_t source_len) = 0;
};

/**
 * compile() forks and executes a system process, the process along with
 * arguments must be provided as argument at time of construction.
 * The process must be able to consume sourcecode via stdin and produce
 * a shared object file.
 * The compiled shared-object is then loaded and made available for execute().
 *
 * Examples:
 *
 *  process tcc("tcc -O2 -march=core2 -fPIC -x c -shared - -o ");
 *  process gcc("gcc -O2 -march=core2 -fPIC -x c -shared - -o ");
 *  process clang("clang -O2 -march=core2 -fPIC -x c -shared - -o ");
 *
 */
class process: compiler {
public:
    func_storage funcs;

    process(
        std::string process_str,
        std::string object_path,
        std::string kernel_path,
        bool do_preload
    ) :
        process_str(process_str),
        object_path(object_path),
        kernel_path(kernel_path)
    {
        // Create an identifier with low collision...
        static const char alphanum[] =
            "0123456789"
            "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
            "abcdefghijklmnopqrstuvwxyz";

        srand(getpid());
        for (int i = 0; i < 7; ++i) {
            uid[i] = alphanum[rand() % (sizeof(alphanum) - 1)];
            uid[i] = 'a';
        }
        uid[6] = 0;

        if (do_preload) {     // Now load all objects...
            preload();
        }
    }

    bool symbol_ready(std::string symbol) {
        return funcs.count(symbol) > 0;
    }

    size_t preload()
    {
        DIR *dir;
        struct dirent *ent;
        size_t nloaded = 0;
        if ((dir = opendir (object_path.c_str())) != NULL) {
            while ((ent = readdir (dir)) != NULL) {
                size_t fn_len = strlen(ent->d_name);

                if (14>fn_len) {              // Not what we want
                    continue;
                }

                std::string fn(ent->d_name),
                            lib_fn;

                if (0==fn.compare(0,3, "BH_")) {        // Single
                    lib_fn.assign(fn, 0, fn_len-10);    // Remove "_xxxxxx.so"
                    if (load(lib_fn, lib_fn)) {
                        ++nloaded;
                    };                                  // Multiple
                } else if (0==fn.compare(fn_len-4, 4, ".ind")) {
                    lib_fn.assign(fn, 0, fn_len-11);    // Remove "_xxxxxx.ind"
                    std::string index_fn = lib_path(lib_fn.c_str(), "ind");

                    std::vector<std::string> symbols;
                    std::ifstream symbol_file(index_fn);
                    for(std::string symbol; getline(symbol_file, symbol);) {
                        symbols.push_back(symbol);
                    }
                    symbol_file.close();

                    nloaded += load(symbols, lib_fn);

                } else {                                        // Ignore
                    std::cout << "Ignorning non-loadable file: ";
                    std::cout << "[" << fn << "] ";
                    std::cout << "found in object-path." << std::endl;
                }
            }
            closedir (dir);
            return nloaded;
        } else {
            throw std::runtime_error("Failed opening bla bla lba.");
        }
    }

    /**
     *  Load a single symbol from library symbol into func-storage.
     */
    bool load(std::string symbol, std::string library)
    {
        char *error_msg = NULL;             // Buffer for dlopen errors
        int errnum = 0;

        std::string library_fn = lib_path(  // "./objects/<symbol>_XXXXXX"
                library.c_str(),
                "so"
        );

        if (0==handles.count(library)) {    // Open library
            handles[library] = dlopen(
                library_fn.c_str(),
                RTLD_NOW
            );
            errnum = errno;
        }
        if (!handles[library]) {            // Check that it opened
            error(
                errnum,
                "Failed openening library; dlopen(filename='%s', RTLF_NOW) failed.",
                library_fn.c_str()
            );
            return false;
        }

        dlerror();                          // Clear any existing error then,
        funcs[symbol] = (func)dlsym(        // Load symbol/function
            handles[library],
            symbol.c_str()
        );
        error_msg = dlerror();
        if (error_msg) {
            error(
                error_msg,
                "dlsym( handle='%s', symbol='%s' )\n",
                library_fn.c_str(),
                symbol.c_str()
            );
            free(error_msg);
            return false;
        }
        return true;
    }

    /**
     *  Load multiple symbols from library into func-storage.
     */
    bool load(std::vector<std::string> symbols, std::string library)
    {
        bool res = true;
        for(std::vector<std::string>::iterator symbol=symbols.begin();
            (symbol != symbols.end()) && res;
            ++symbol
        ) {
            res *= load(*symbol, library);
        }
        return res;
    }

    /**
     *  Write source-code to file.
     *  Filename will be along the lines of: kernel/<symbol>_<UID>.c
     *  NOTE: Does not overwrite existing files.
     */
    bool src_to_file(std::string symbol, const char* sourcecode, size_t source_len)
    {
        int kernel_fd;              // Kernel file-descriptor
        FILE *kernel_fp = NULL;     // Handle for kernel-file
        const char *mode = "w";
        int err;
        std::string kernel_fn = krn_path(symbol.c_str(), ".c");
        kernel_fd = open(kernel_fn.c_str(), O_WRONLY | O_CREAT | O_EXCL, 0644);
        if ((!kernel_fd) || (kernel_fd<1)) {
            err = errno;
            error(err, "Failed opening kernel-file [%s] in src_to_file(...).\n", kernel_fn.c_str());
            return false;
        }
        kernel_fp = fdopen(kernel_fd, mode);
        if (!kernel_fp) {
            err = errno;
            error(err, "fdopen(fildes= %d, flags= %s).", kernel_fd, mode);
            return false;
        }
        fwrite(sourcecode, 1, source_len, kernel_fp);
        fflush(kernel_fp);
        fclose(kernel_fp);
        close(kernel_fd);

        return true;
    }

    bool compile(std::string library, const char* sourcecode, size_t source_len)
    {
        std::string cmd = command(library.c_str(), "so");
        FILE *cmd_stdin     = NULL;                     // Handle for library-file
        cmd_stdin = popen(cmd.c_str(), "w");            // Execute the command
        if (!cmd_stdin) {
            std::cout << "Err: Could not execute process! ["<< cmd <<"]" << std::endl;
            return false;
        }
        fwrite(sourcecode, 1, source_len, cmd_stdin);   // Write sourcecode to stdin
        fflush(cmd_stdin);
        pclose(cmd_stdin);

        return true;
    }

    ~process()
    {   /*
        if (handle) {
            dlclose(handle);
            handle = NULL;
        }*/
    }

    const char* get_uid(void)
    {
        return uid;
    }

    std::string lib_path(const char *lib_name, const char *ext)
    {
        return  object_path + "/" +\
                std::string(lib_name)    + "_" +\
                std::string(get_uid())   + "." +\
                std::string(ext);
    }

    std::string krn_path(const char *krn_name, const char *ext)
    {
        return  kernel_path + "/" +\
                std::string(krn_name)    + "_" +\
                std::string(get_uid())   + "." +\
                std::string(ext);
    }

    std::string command(const char *lib_name, const char *ext)
    {
        return  process_str + " "+\
                object_path + "/" +\
                std::string(lib_name)    + "_" +\
                std::string(get_uid())   + "." +\
                std::string(ext);
    }

private:
    handle_storage handles;
    char uid[7];
    std::string process_str;
    std::string object_path;
    std::string kernel_path;

};

#endif

<commit_msg>cpu: Fixed that annoying extra "." in source-code filenames.<commit_after>#ifndef __BH_VE_CPU_BACKENDS
#define __BH_VE_CPU_BACKENDS

#include <iostream>
#include <cstring>
#include <cstdarg>
#include <cstdlib>
#include <cstdio>
#include <string>
#include <cstring>
#include <stdexcept>
#include <vector>
#include <unordered_map>
#include "dirent.h"
#include <dlfcn.h>
#include <unistd.h>
#include "utils.cpp"
#include <fcntl.h>

// Create nice error-messages...
int error(int errnum, const char *fmt, ...) {
    va_list va;
    int ret;

    char err_msg[500];
    sprintf(err_msg, "Error[%d, %s] from: %s", errnum, strerror(errnum), fmt);
    va_start(va, fmt);
    ret = vfprintf(stderr, err_msg, va);
    va_end(va);
    return ret;
}

int error(const char *err_msg, const char *fmt, ...) {
    va_list va;
    int ret;

    char err_txt[500];
    sprintf(err_txt, "Error[%s] from: %s", err_msg, fmt);
    va_start(va, fmt);
    ret = vfprintf(stderr, err_txt, va);
    va_end(va);
    return ret;
}

typedef void (*func)(int tool, ...);
//typedef std::map<std::string, func> func_storage;
//typedef std::map<std::string, void*> handle_storage;

typedef std::unordered_map<std::string, func> func_storage;
typedef std::unordered_map<std::string, void*> handle_storage;

/**
 *  TODO: Load existing objects at startup.
 *          Then pre-compilation and warmup rounds will be possible.
 */

/**
 * The compiler interface.
 *
 * Becomes what it compiles.
 */
class compiler {
public:
    virtual bool compile(std::string symbol, const char* sourcecode, size_t source_len) = 0;
};

/**
 * compile() forks and executes a system process, the process along with
 * arguments must be provided as argument at time of construction.
 * The process must be able to consume sourcecode via stdin and produce
 * a shared object file.
 * The compiled shared-object is then loaded and made available for execute().
 *
 * Examples:
 *
 *  process tcc("tcc -O2 -march=core2 -fPIC -x c -shared - -o ");
 *  process gcc("gcc -O2 -march=core2 -fPIC -x c -shared - -o ");
 *  process clang("clang -O2 -march=core2 -fPIC -x c -shared - -o ");
 *
 */
class process: compiler {
public:
    func_storage funcs;

    process(
        std::string process_str,
        std::string object_path,
        std::string kernel_path,
        bool do_preload
    ) :
        process_str(process_str),
        object_path(object_path),
        kernel_path(kernel_path)
    {
        // Create an identifier with low collision...
        static const char alphanum[] =
            "0123456789"
            "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
            "abcdefghijklmnopqrstuvwxyz";

        srand(getpid());
        for (int i = 0; i < 7; ++i) {
            uid[i] = alphanum[rand() % (sizeof(alphanum) - 1)];
            uid[i] = 'a';
        }
        uid[6] = 0;

        if (do_preload) {     // Now load all objects...
            preload();
        }
    }

    bool symbol_ready(std::string symbol) {
        return funcs.count(symbol) > 0;
    }

    size_t preload()
    {
        DIR *dir;
        struct dirent *ent;
        size_t nloaded = 0;
        if ((dir = opendir (object_path.c_str())) != NULL) {
            while ((ent = readdir (dir)) != NULL) {
                size_t fn_len = strlen(ent->d_name);

                if (14>fn_len) {              // Not what we want
                    continue;
                }

                std::string fn(ent->d_name),
                            lib_fn;

                if (0==fn.compare(0,3, "BH_")) {        // Single
                    lib_fn.assign(fn, 0, fn_len-10);    // Remove "_xxxxxx.so"
                    if (load(lib_fn, lib_fn)) {
                        ++nloaded;
                    };                                  // Multiple
                } else if (0==fn.compare(fn_len-4, 4, ".ind")) {
                    lib_fn.assign(fn, 0, fn_len-11);    // Remove "_xxxxxx.ind"
                    std::string index_fn = lib_path(lib_fn.c_str(), "ind");

                    std::vector<std::string> symbols;
                    std::ifstream symbol_file(index_fn);
                    for(std::string symbol; getline(symbol_file, symbol);) {
                        symbols.push_back(symbol);
                    }
                    symbol_file.close();

                    nloaded += load(symbols, lib_fn);

                } else {                                        // Ignore
                    std::cout << "Ignorning non-loadable file: ";
                    std::cout << "[" << fn << "] ";
                    std::cout << "found in object-path." << std::endl;
                }
            }
            closedir (dir);
            return nloaded;
        } else {
            throw std::runtime_error("Failed opening bla bla lba.");
        }
    }

    /**
     *  Load a single symbol from library symbol into func-storage.
     */
    bool load(std::string symbol, std::string library)
    {
        char *error_msg = NULL;             // Buffer for dlopen errors
        int errnum = 0;

        std::string library_fn = lib_path(  // "./objects/<symbol>_XXXXXX"
                library.c_str(),
                "so"
        );

        if (0==handles.count(library)) {    // Open library
            handles[library] = dlopen(
                library_fn.c_str(),
                RTLD_NOW
            );
            errnum = errno;
        }
        if (!handles[library]) {            // Check that it opened
            error(
                errnum,
                "Failed openening library; dlopen(filename='%s', RTLF_NOW) failed.",
                library_fn.c_str()
            );
            return false;
        }

        dlerror();                          // Clear any existing error then,
        funcs[symbol] = (func)dlsym(        // Load symbol/function
            handles[library],
            symbol.c_str()
        );
        error_msg = dlerror();
        if (error_msg) {
            error(
                error_msg,
                "dlsym( handle='%s', symbol='%s' )\n",
                library_fn.c_str(),
                symbol.c_str()
            );
            free(error_msg);
            return false;
        }
        return true;
    }

    /**
     *  Load multiple symbols from library into func-storage.
     */
    bool load(std::vector<std::string> symbols, std::string library)
    {
        bool res = true;
        for(std::vector<std::string>::iterator symbol=symbols.begin();
            (symbol != symbols.end()) && res;
            ++symbol
        ) {
            res *= load(*symbol, library);
        }
        return res;
    }

    /**
     *  Write source-code to file.
     *  Filename will be along the lines of: kernel/<symbol>_<UID>.c
     *  NOTE: Does not overwrite existing files.
     */
    bool src_to_file(std::string symbol, const char* sourcecode, size_t source_len)
    {
        int kernel_fd;              // Kernel file-descriptor
        FILE *kernel_fp = NULL;     // Handle for kernel-file
        const char *mode = "w";
        int err;
        std::string kernel_fn = krn_path(symbol.c_str(), "c");
        kernel_fd = open(kernel_fn.c_str(), O_WRONLY | O_CREAT | O_EXCL, 0644);
        if ((!kernel_fd) || (kernel_fd<1)) {
            err = errno;
            error(err, "Failed opening kernel-file [%s] in src_to_file(...).\n", kernel_fn.c_str());
            return false;
        }
        kernel_fp = fdopen(kernel_fd, mode);
        if (!kernel_fp) {
            err = errno;
            error(err, "fdopen(fildes= %d, flags= %s).", kernel_fd, mode);
            return false;
        }
        fwrite(sourcecode, 1, source_len, kernel_fp);
        fflush(kernel_fp);
        fclose(kernel_fp);
        close(kernel_fd);

        return true;
    }

    bool compile(std::string library, const char* sourcecode, size_t source_len)
    {
        std::string cmd = command(library.c_str(), "so");
        FILE *cmd_stdin     = NULL;                     // Handle for library-file
        cmd_stdin = popen(cmd.c_str(), "w");            // Execute the command
        if (!cmd_stdin) {
            std::cout << "Err: Could not execute process! ["<< cmd <<"]" << std::endl;
            return false;
        }
        fwrite(sourcecode, 1, source_len, cmd_stdin);   // Write sourcecode to stdin
        fflush(cmd_stdin);
        pclose(cmd_stdin);

        return true;
    }

    ~process()
    {   /*
        if (handle) {
            dlclose(handle);
            handle = NULL;
        }*/
    }

    const char* get_uid(void)
    {
        return uid;
    }

    std::string lib_path(const char *lib_name, const char *ext)
    {
        return  object_path + "/" +\
                std::string(lib_name)    + "_" +\
                std::string(get_uid())   + "." +\
                std::string(ext);
    }

    std::string krn_path(const char *krn_name, const char *ext)
    {
        return  kernel_path + "/" +\
                std::string(krn_name)    + "_" +\
                std::string(get_uid())   + "." +\
                std::string(ext);
    }

    std::string command(const char *lib_name, const char *ext)
    {
        return  process_str + " "+\
                object_path + "/" +\
                std::string(lib_name)    + "_" +\
                std::string(get_uid())   + "." +\
                std::string(ext);
    }

private:
    handle_storage handles;
    char uid[7];
    std::string process_str;
    std::string object_path;
    std::string kernel_path;

};

#endif

<|endoftext|>


<commit_before>// --------------------------------------------------------------------------------------------------
//  Copyright (c) 2016 Microsoft Corporation
//
//  Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
//  associated documentation files (the "Software"), to deal in the Software without restriction,
//  including without limitation the rights to use, copy, modify, merge, publish, distribute,
//  sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
//  furnished to do so, subject to the following conditions:
//
//  The above copyright notice and this permission notice shall be included in all copies or
//  substantial portions of the Software.
//
//  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT
//  NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
//  NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
//  DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// --------------------------------------------------------------------------------------------------

// Header:
#include "TimestampedReward.h"

// Local:
#include "FindSchemaFile.h"

// Boost:
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/date_time/posix_time/posix_time_io.hpp>

// STL:
#include <sstream>

namespace malmo
{
    TimestampedReward::TimestampedReward()
    {
    }

    TimestampedReward::TimestampedReward(float reward)
    {
        this->values[0] = static_cast<double>(reward);
    }

    TimestampedReward& TimestampedReward::createFromXML(boost::posix_time::ptime timestamp, std::string xml_string)
    {
        this->timestamp = timestamp;

        const bool validate = true;

        xml_schema::properties props;
        props.schema_location(xml_namespace, FindSchemaFile("MissionEnded.xsd"));

        xml_schema::flags flags = 0;
        if( !validate )
            flags = flags | xml_schema::flags::dont_validate;

        std::istringstream iss(xml_string);
        std::unique_ptr<malmo::schemas::Reward> reward = malmo::schemas::Reward_(iss, flags, props);
        setValuesFromRewardStructure(*reward);
        return *this;
    }

    TimestampedReward& TimestampedReward::createFromSimpleString(boost::posix_time::ptime timestamp, std::string simple_string)
    {
        this->timestamp = timestamp;

        // String should be comma-delimited sets of <dimension>:<value>.
        size_t nextpos = 0, lastpos = 0;
        while (nextpos != std::string::npos)
        {
            nextpos = simple_string.find(",", lastpos);
            std::string token = (nextpos != std::string::npos) ? simple_string.substr(lastpos, nextpos - lastpos) : simple_string.substr(lastpos);
            size_t split = token.find(":");
            if (split == std::string::npos)
            {
                throw std::runtime_error("Malformed reward message.");
            }
            else
            {
                int dimension = std::stoi(token.substr(0, split));
                double value = std::stod(token.substr(split + 1));
                this->values[dimension] = value;
            }
            lastpos = nextpos + 1;
        }
    }

    TimestampedReward::TimestampedReward(boost::posix_time::ptime timestamp,const schemas::Reward& reward)
        : timestamp(timestamp)
    {
        setValuesFromRewardStructure(reward);
    }

    void TimestampedReward::setValuesFromRewardStructure(const schemas::Reward& reward)
    {
        this->values.clear();
        for( const schemas::Value& r : reward.Value() ) {
            this->values[ r.dimension() ] = static_cast<double>( r.value() );
        }
    }

    schemas::Reward TimestampedReward::getAsRewardStructure() const
    {
        schemas::Reward reward;
        for( std::map<int,double>::const_iterator it = this->values.begin(); it!= this->values.end(); it++) {
            schemas::Value value( it->first, it->second );
            reward.Value().push_back( value );
        }
        return reward;
    }

    std::string TimestampedReward::getAsXML( bool prettyPrint ) const
    {
        std::ostringstream oss;

        xml_schema::namespace_infomap map;
        map[""].name = xml_namespace;
        map[""].schema = "MissionEnded.xsd";

        xml_schema::flags flags = 0;
        if( !prettyPrint )
            flags = flags | xml_schema::flags::dont_pretty_print;

        Reward_( oss, this->getAsRewardStructure(), map, "UTF-8", flags );

        return oss.str();
    }

    std::string TimestampedReward::getAsSimpleString() const
    {
        std::ostringstream oss;
        for (std::map<int, double>::const_iterator it = this->values.begin(); it != this->values.end(); it++) {
            if (it != this->values.begin())
                oss << ",";
            oss << it->first << ":" << it->second;
        }
        return oss.str();
    }

    bool TimestampedReward::hasValueOnDimension(int dimension) const
    {
        return this->values.find(dimension) != this->values.end();
    }

    double TimestampedReward::getValueOnDimension(int dimension) const
    {
        return this->values.at(dimension);
    }

    double TimestampedReward::getValue() const
    {
        return this->values.at(0);
    }

    void TimestampedReward::add(const TimestampedReward& other)
    {
        for( std::map<int,double>::const_iterator it = this->values.begin(); it!= this->values.end(); it++) {
            int dimension = it->first;
            double value = it->second;
            if( this->values.find(dimension) != this->values.end() )
                this->values[dimension] += value;
            else
                this->values[dimension] = value;
        }
    }

    std::ostream& operator<<(std::ostream& os, const TimestampedReward& tsf)
    {
        os << "TimestampedReward: " << to_simple_string(tsf.timestamp);
        for( std::map<int,double>::const_iterator it = tsf.values.begin(); it!= tsf.values.end(); it++) {
            os  << ", " << it->first << ":" << it->second;
        }
        return os;
    }
}
<commit_msg>Fix: TimestampedReward::add was broken, causing occasional doubling of rewards.<commit_after>// --------------------------------------------------------------------------------------------------
//  Copyright (c) 2016 Microsoft Corporation
//
//  Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
//  associated documentation files (the "Software"), to deal in the Software without restriction,
//  including without limitation the rights to use, copy, modify, merge, publish, distribute,
//  sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
//  furnished to do so, subject to the following conditions:
//
//  The above copyright notice and this permission notice shall be included in all copies or
//  substantial portions of the Software.
//
//  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT
//  NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
//  NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
//  DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// --------------------------------------------------------------------------------------------------

// Header:
#include "TimestampedReward.h"

// Local:
#include "FindSchemaFile.h"

// Boost:
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/date_time/posix_time/posix_time_io.hpp>

// STL:
#include <sstream>

namespace malmo
{
    TimestampedReward::TimestampedReward()
    {
    }

    TimestampedReward::TimestampedReward(float reward)
    {
        this->values[0] = static_cast<double>(reward);
    }

    TimestampedReward& TimestampedReward::createFromXML(boost::posix_time::ptime timestamp, std::string xml_string)
    {
        this->timestamp = timestamp;

        const bool validate = true;

        xml_schema::properties props;
        props.schema_location(xml_namespace, FindSchemaFile("MissionEnded.xsd"));

        xml_schema::flags flags = 0;
        if( !validate )
            flags = flags | xml_schema::flags::dont_validate;

        std::istringstream iss(xml_string);
        std::unique_ptr<malmo::schemas::Reward> reward = malmo::schemas::Reward_(iss, flags, props);
        setValuesFromRewardStructure(*reward);
        return *this;
    }

    TimestampedReward& TimestampedReward::createFromSimpleString(boost::posix_time::ptime timestamp, std::string simple_string)
    {
        this->timestamp = timestamp;

        // String should be comma-delimited sets of <dimension>:<value>.
        size_t nextpos = 0, lastpos = 0;
        while (nextpos != std::string::npos)
        {
            nextpos = simple_string.find(",", lastpos);
            std::string token = (nextpos != std::string::npos) ? simple_string.substr(lastpos, nextpos - lastpos) : simple_string.substr(lastpos);
            size_t split = token.find(":");
            if (split == std::string::npos)
            {
                throw std::runtime_error("Malformed reward message.");
            }
            else
            {
                int dimension = std::stoi(token.substr(0, split));
                double value = std::stod(token.substr(split + 1));
                this->values[dimension] = value;
            }
            lastpos = nextpos + 1;
        }
    }

    TimestampedReward::TimestampedReward(boost::posix_time::ptime timestamp,const schemas::Reward& reward)
        : timestamp(timestamp)
    {
        setValuesFromRewardStructure(reward);
    }

    void TimestampedReward::setValuesFromRewardStructure(const schemas::Reward& reward)
    {
        this->values.clear();
        for( const schemas::Value& r : reward.Value() ) {
            this->values[ r.dimension() ] = static_cast<double>( r.value() );
        }
    }

    schemas::Reward TimestampedReward::getAsRewardStructure() const
    {
        schemas::Reward reward;
        for( std::map<int,double>::const_iterator it = this->values.begin(); it!= this->values.end(); it++) {
            schemas::Value value( it->first, it->second );
            reward.Value().push_back( value );
        }
        return reward;
    }

    std::string TimestampedReward::getAsXML( bool prettyPrint ) const
    {
        std::ostringstream oss;

        xml_schema::namespace_infomap map;
        map[""].name = xml_namespace;
        map[""].schema = "MissionEnded.xsd";

        xml_schema::flags flags = 0;
        if( !prettyPrint )
            flags = flags | xml_schema::flags::dont_pretty_print;

        Reward_( oss, this->getAsRewardStructure(), map, "UTF-8", flags );

        return oss.str();
    }

    std::string TimestampedReward::getAsSimpleString() const
    {
        std::ostringstream oss;
        for (std::map<int, double>::const_iterator it = this->values.begin(); it != this->values.end(); it++) {
            if (it != this->values.begin())
                oss << ",";
            oss << it->first << ":" << it->second;
        }
        return oss.str();
    }

    bool TimestampedReward::hasValueOnDimension(int dimension) const
    {
        return this->values.find(dimension) != this->values.end();
    }

    double TimestampedReward::getValueOnDimension(int dimension) const
    {
        return this->values.at(dimension);
    }

    double TimestampedReward::getValue() const
    {
        return this->values.at(0);
    }

    void TimestampedReward::add(const TimestampedReward& other)
    {
        for( std::map<int,double>::const_iterator it = other.values.begin(); it!= other.values.end(); it++) {
            int dimension = it->first;
            double value = it->second;
            if( this->values.find(dimension) != this->values.end() )
                this->values[dimension] += value;
            else
                this->values[dimension] = value;
        }
    }

    std::ostream& operator<<(std::ostream& os, const TimestampedReward& tsf)
    {
        os << "TimestampedReward: " << to_simple_string(tsf.timestamp);
        for( std::map<int,double>::const_iterator it = tsf.values.begin(); it!= tsf.values.end(); it++) {
            os  << ", " << it->first << ":" << it->second;
        }
        return os;
    }
}
<|endoftext|>


<commit_before>/*
  Copyright 2008 Larry Gritz and the other authors and contributors.
  All Rights Reserved.

  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 software's owners 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
  OWNER 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.

  (This is the Modified BSD License)
*/

#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <ctime>
#include <iostream>
#include <iterator>

#include <QtGui>

#include <boost/foreach.hpp>

#include "imageio.h"
using namespace OpenImageIO;
#include "imageviewer.h"
#include "timer.h"
#include "argparse.h"

static bool verbose = false;
static bool foreground_mode = false;
static std::vector<std::string> filenames;

static int
parse_files (int argc, const char *argv[])
{
    for (int i = 0;  i < argc;  i++)
        filenames.push_back (argv[i]);
    return 0;
}

static void
getargs (int argc, char *argv[])
{
    bool help = false;
    ArgParse ap;
    ap.options ("Usage:  iv [options] [filename...]",
                  "%*", parse_files, "",
                  "--help", &help, "Print help message",
                  "-v", &verbose, "Verbose status messages",
                  "-F", &foreground_mode, "Foreground mode",
                  NULL);
    if (ap.parse (argc, (const char**)argv) < 0) {
        std::cerr << ap.error_message() << std::endl;
        ap.usage ();
        exit (EXIT_FAILURE);
    }
    if (help) {
        ap.usage ();
        exit (EXIT_FAILURE);
    }
}

/// Try to put the process into the background so it doesn't continue to
/// tie up any shell that it was launched from.  Return true if successful,
/// false if it was unable to do so.
static bool
put_in_background (int argc, char *argv[])
{
    // You would think that this would be sufficient:
    //   pid_t pid = fork ();
    //   if (pid < 0)       // Some kind of error, we were unable to background
    //      return false;
    //   if (pid == 0)
    //       return true;   // This is the child process, so continue with life
    //   // Otherwise, this is the parent process, so terminate
    //   exit (0);
    // But it's not.  On OS X, it's not safe to fork() if your app is linked
    // against certain libraries or frameworks.  So the only thing that I
    // think is safe is to exec a new process.
    // Another solution is this:
    //    daemon (1, 1);
    // But it suffers from the same problem on OS X, and seems to just be
    // a wrapper for fork.

#ifdef __linux
    // Simplest case:
    daemon (1, 1);
    return true;
#endif

#ifdef __APPLE__
#if 0
    // Another solution -- But I can't seem to make this work!
    std::vector<char *> newargs;
    newargs.push_back ("-F");
    for (int i = 0;  i < argc;  ++i)
        newargs.push_back (argv[i]);
    newargs.push_back (NULL);
    if (fork())
        exit (0);
    execv ("/Users/lg/lg/proj/oiio/dist/macosx/bin/iv" /*argv[0]*/, &newargs[0]);
    exit (0);
#endif

#if 1
    // This one works -- just call system(), but we have to properly
    // quote all the arguments in case filenames have spaces in them.
    std::string newcmd = std::string(argv[0]) + " -F";
    for (int i = 1;  i < argc;  ++i) {
        newcmd += " \"";
        newcmd += argv[i];
        newcmd += "\"";
    }
    newcmd += " &";
    if (system (newcmd.c_str()) != -1)
        exit (0);
    return true;
#endif

#endif

#ifdef WIN32
    // FIXME: How to do this for win32?  Somebody told me that it's not
    // necessary at all, and we just have to rename 'main' to 'winMain'
    // for it to become a backgrounded app.
    return false;
#endif
}

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

    if (! foreground_mode)
        put_in_background (argc, argv);

    // LG
//    Q_INIT_RESOURCE(iv);
    QApplication app(argc, argv);
    ImageViewer *mainWin = new ImageViewer;
    mainWin->show();

    // Make sure we are the top window with the focus.
    mainWin->raise ();
    mainWin->activateWindow ();

    BOOST_FOREACH (const std::string &s, filenames) {
        mainWin->add_image (s);
    }

    mainWin->current_image (0);

    int r = app.exec();
    // OK to clean up here
    return r;
}
<commit_msg>iv: set up the underlying IC with a reasonable cache size and with  "autotile" turned on.  Also, when -v is used or when compiled with DEBUG, print IC and memory stats before exiting.<commit_after>/*
  Copyright 2008 Larry Gritz and the other authors and contributors.
  All Rights Reserved.

  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 software's owners 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
  OWNER 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.

  (This is the Modified BSD License)
*/

#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <ctime>
#include <iostream>
#include <iterator>

#include <QtGui>

#include <boost/foreach.hpp>

#include "imageio.h"
using namespace OpenImageIO;
#include "imageviewer.h"
#include "timer.h"
#include "argparse.h"
#include "sysutil.h"
#include "strutil.h"
#include "imagecache.h"

static bool verbose = false;
static bool foreground_mode = false;
static std::vector<std::string> filenames;

static int
parse_files (int argc, const char *argv[])
{
    for (int i = 0;  i < argc;  i++)
        filenames.push_back (argv[i]);
    return 0;
}

static void
getargs (int argc, char *argv[])
{
    bool help = false;
    ArgParse ap;
    ap.options ("Usage:  iv [options] [filename...]",
                  "%*", parse_files, "",
                  "--help", &help, "Print help message",
                  "-v", &verbose, "Verbose status messages",
                  "-F", &foreground_mode, "Foreground mode",
                  NULL);
    if (ap.parse (argc, (const char**)argv) < 0) {
        std::cerr << ap.error_message() << std::endl;
        ap.usage ();
        exit (EXIT_FAILURE);
    }
    if (help) {
        ap.usage ();
        exit (EXIT_FAILURE);
    }
}

/// Try to put the process into the background so it doesn't continue to
/// tie up any shell that it was launched from.  Return true if successful,
/// false if it was unable to do so.
static bool
put_in_background (int argc, char *argv[])
{
    // You would think that this would be sufficient:
    //   pid_t pid = fork ();
    //   if (pid < 0)       // Some kind of error, we were unable to background
    //      return false;
    //   if (pid == 0)
    //       return true;   // This is the child process, so continue with life
    //   // Otherwise, this is the parent process, so terminate
    //   exit (0);
    // But it's not.  On OS X, it's not safe to fork() if your app is linked
    // against certain libraries or frameworks.  So the only thing that I
    // think is safe is to exec a new process.
    // Another solution is this:
    //    daemon (1, 1);
    // But it suffers from the same problem on OS X, and seems to just be
    // a wrapper for fork.

#ifdef __linux
    // Simplest case:
    daemon (1, 1);
    return true;
#endif

#ifdef __APPLE__
#if 0
    // Another solution -- But I can't seem to make this work!
    std::vector<char *> newargs;
    newargs.push_back ("-F");
    for (int i = 0;  i < argc;  ++i)
        newargs.push_back (argv[i]);
    newargs.push_back (NULL);
    if (fork())
        exit (0);
    execv ("/Users/lg/lg/proj/oiio/dist/macosx/bin/iv" /*argv[0]*/, &newargs[0]);
    exit (0);
#endif

#if 1
    // This one works -- just call system(), but we have to properly
    // quote all the arguments in case filenames have spaces in them.
    std::string newcmd = std::string(argv[0]) + " -F";
    for (int i = 1;  i < argc;  ++i) {
        newcmd += " \"";
        newcmd += argv[i];
        newcmd += "\"";
    }
    newcmd += " &";
    if (system (newcmd.c_str()) != -1)
        exit (0);
    return true;
#endif

#endif

#ifdef WIN32
    // FIXME: How to do this for win32?  Somebody told me that it's not
    // necessary at all, and we just have to rename 'main' to 'winMain'
    // for it to become a backgrounded app.
    return false;
#endif
}

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

    if (! foreground_mode)
        put_in_background (argc, argv);

    // LG
//    Q_INIT_RESOURCE(iv);
    QApplication app(argc, argv);
    ImageViewer *mainWin = new ImageViewer;
    mainWin->show();

    // Set up the imagecache with parameters that make sense for iv
    ImageCache *imagecache = ImageCache::create (true);
    imagecache->attribute ("max_memory_MB", 512.0);  /* Seems fair */
    imagecache->attribute ("autotile", 256);

    // Make sure we are the top window with the focus.
    mainWin->raise ();
    mainWin->activateWindow ();

    // Add the images
    BOOST_FOREACH (const std::string &s, filenames) {
        mainWin->add_image (s);
    }

    mainWin->current_image (0);

    int r = app.exec();
    // OK to clean up here

#ifndef DEBUG
    if (verbose)
#endif
    {
        size_t mem = Sysutil::memory_used (true);
        std::cout << "iv total memory used: " << Strutil::memformat (mem) << "\n";
        std::cout << "\n";
        std::cout << imagecache->getstats (1+verbose) << "\n";
    }

    return r;
}
<|endoftext|>


<commit_before>/*=========================================================================

  Program:   Insight Segmentation & Registration Toolkit (ITK)
  Module:    itkKalmanLinearEstimatorTest.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

Copyright (c) 2001 Insight Consortium
All rights reserved.

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.

 * The name of the Insight Consortium, nor the names of any consortium members,
   nor of any contributors, may be used to endorse or promote products derived
   from this software without specific prior written permission.

  * Modified source versions must be plainly marked as such, and must not be
    misrepresented as being the original software.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER 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 AUTHORS OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

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

#include "itkKalmanLinearEstimator.h"

/**
 *  This program test one instantiation of the itk::KalmanLinearEstimator class
 *
 *  The test is done by providing a Linear Equation in 6D for which the
 *  coefficients are known. A population of samples is generated and
 *  passed to the KalmanLinearEstimator.
 *
 */

int main()
{

  typedef itk::KalmanLinearEstimator<double,6> KalmanFilterType;

  typedef KalmanFilterType::VectorType    VectorType;
  typedef KalmanFilterType::MatrixType    MatrixType;
  typedef KalmanFilterType::ValueType     ValueType;

  KalmanFilterType filter;

  filter.ClearEstimation();
  filter.SetVariance(1.0);

  ValueType     measure;
  VectorType    predictor;

  VectorType    planeEquation;

  planeEquation(0) = 9.0;
  planeEquation(1) = 6.0;
  planeEquation(2) = 7.0;
  planeEquation(3) = 9.0;
  planeEquation(4) = 4.0;
  planeEquation(5) = 6.0;

  const unsigned int N = 10;

  predictor(5)  =  1.0;
  for(unsigned int ax=0; ax < N; ax++)
    {
    predictor(0)  = ax;
    for(unsigned int bx=0; bx < N; bx++)
      {
      predictor(1)  = bx;
      for(unsigned int cx=0; cx < N; cx++)
        {
        predictor(2)  = cx;
        for(unsigned int dx=0; dx < N; dx++)
          {
          predictor(3)  = dx;
          for(unsigned int ex=0; ex < N; ex++)
            {
            predictor(4)  =  ex;

            measure = dot_product( predictor, planeEquation );

            filter.UpdateWithNewMeasure(measure,predictor);

            }
          }
        }
      }
    }

  VectorType estimation = filter.GetEstimator();

  std::cout << std::endl << "The Right answer should be : " << std::endl;
  std::cout << planeEquation;

  std::cout << std::endl << "The Estimation is : " << std::endl;
  std::cout << estimation;

  VectorType error = estimation - planeEquation;
  ValueType errorMagnitude =  dot_product( error, error );

  std::cout << std::endl << "Errors : " << std::endl;
  std::cout << error;

  std::cout << std::endl << "Error Magnitude : " << std::endl;
  std::cout << errorMagnitude;

  std::cout << std::endl << "Variance : " << std::endl;
  std::cout << filter.GetVariance();

  std::cout << std::endl << std::endl;

  bool pass = true;

  const float tolerance = 1e-4;

  if( errorMagnitude > tolerance )
    {
    pass = false;
    }

  if( !pass )
    {
    std::cout << "Test failed." << std::endl;
    return EXIT_FAILURE;
    }

  std::cout << "Test passed." << std::endl;
  return EXIT_SUCCESS;

}
<commit_msg>ERR: Added missing include of <iostream><commit_after>/*=========================================================================

  Program:   Insight Segmentation & Registration Toolkit (ITK)
  Module:    itkKalmanLinearEstimatorTest.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

Copyright (c) 2001 Insight Consortium
All rights reserved.

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.

 * The name of the Insight Consortium, nor the names of any consortium members,
   nor of any contributors, may be used to endorse or promote products derived
   from this software without specific prior written permission.

  * Modified source versions must be plainly marked as such, and must not be
    misrepresented as being the original software.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER 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 AUTHORS OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

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

#include "itkKalmanLinearEstimator.h"

#include <iostream>

/**
 *  This program test one instantiation of the itk::KalmanLinearEstimator class
 *
 *  The test is done by providing a Linear Equation in 6D for which the
 *  coefficients are known. A population of samples is generated and
 *  passed to the KalmanLinearEstimator.
 *
 */

int main()
{

  typedef itk::KalmanLinearEstimator<double,6> KalmanFilterType;

  typedef KalmanFilterType::VectorType    VectorType;
  typedef KalmanFilterType::MatrixType    MatrixType;
  typedef KalmanFilterType::ValueType     ValueType;

  KalmanFilterType filter;

  filter.ClearEstimation();
  filter.SetVariance(1.0);

  ValueType     measure;
  VectorType    predictor;

  VectorType    planeEquation;

  planeEquation(0) = 9.0;
  planeEquation(1) = 6.0;
  planeEquation(2) = 7.0;
  planeEquation(3) = 9.0;
  planeEquation(4) = 4.0;
  planeEquation(5) = 6.0;

  const unsigned int N = 10;

  predictor(5)  =  1.0;
  for(unsigned int ax=0; ax < N; ax++)
    {
    predictor(0)  = ax;
    for(unsigned int bx=0; bx < N; bx++)
      {
      predictor(1)  = bx;
      for(unsigned int cx=0; cx < N; cx++)
        {
        predictor(2)  = cx;
        for(unsigned int dx=0; dx < N; dx++)
          {
          predictor(3)  = dx;
          for(unsigned int ex=0; ex < N; ex++)
            {
            predictor(4)  =  ex;

            measure = dot_product( predictor, planeEquation );

            filter.UpdateWithNewMeasure(measure,predictor);

            }
          }
        }
      }
    }

  VectorType estimation = filter.GetEstimator();

  std::cout << std::endl << "The Right answer should be : " << std::endl;
  std::cout << planeEquation;

  std::cout << std::endl << "The Estimation is : " << std::endl;
  std::cout << estimation;

  VectorType error = estimation - planeEquation;
  ValueType errorMagnitude =  dot_product( error, error );

  std::cout << std::endl << "Errors : " << std::endl;
  std::cout << error;

  std::cout << std::endl << "Error Magnitude : " << std::endl;
  std::cout << errorMagnitude;

  std::cout << std::endl << "Variance : " << std::endl;
  std::cout << filter.GetVariance();

  std::cout << std::endl << std::endl;

  bool pass = true;

  const float tolerance = 1e-4;

  if( errorMagnitude > tolerance )
    {
    pass = false;
    }

  if( !pass )
    {
    std::cout << "Test failed." << std::endl;
    return EXIT_FAILURE;
    }

  std::cout << "Test passed." << std::endl;
  return EXIT_SUCCESS;

}
<|endoftext|>


<commit_before>/*
 * V1.cpp
 *
 *  Created on: Jul 30, 2008
 *      Author: rasmussn
 */

#include "../include/pv_common.h"
#include "../include/default_params.h"
#include "../connections/PVConnection.h"
#include "HyPerLayer.hpp"
#include "V1.hpp"

#include <assert.h>
#include <float.h>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

namespace PV
{

LIFParams LIFDefaultParams =
{
    V_REST, V_EXC, V_INH, V_INHB,            // V (mV)
    TAU_VMEM, TAU_EXC, TAU_INH, TAU_INHB,
    VTH_REST,  TAU_VTH, DELTA_VTH,	     // tau (ms)
    250, 0*NOISE_AMP*( 1.0/TAU_EXC ) * ( ( TAU_INH * (V_REST-V_INH) + TAU_INHB * (V_REST-V_INHB) ) / (V_EXC-V_REST) ),
    250, 0*NOISE_AMP*1.0,
    250, 0*NOISE_AMP*1.0                       // noise (G)
};

V1::V1(const char* name, HyPerCol * hc)
  : HyPerLayer(name, hc)
{
   initialize(TypeLIFSimple);
}

V1::V1(const char* name, HyPerCol * hc, PVLayerType type)
  : HyPerLayer(name, hc)
{
   initialize(type);
}

int V1::initialize(PVLayerType type)
{
   float time = 0.0f;

   setParams(parent->parameters(), &LIFDefaultParams);

   pvlayer_setFuncs(clayer, (INIT_FN) &LIF2_init, (UPDATE_FN) &LIF2_update_exact_linear);
   this->clayer->layerType = type;

   parent->addLayer(this);

   if (parent->parameters()->value(name, "restart", 0) != 0) {
      readState(name, &time);
   }

   // initialize OpenCL parameters
   //
   CLDevice * device = parent->getCLDevice();
   updatestate_kernel = device->createKernel("LIF_updatestate.cl", "LIF_updatestate.cl");

   // TODO - fix to use device and layer parameters
   if (device->id() == 1) {
      nxl = 1;
      nyl = 1;
   }
   else {
      nxl = 16;
      nyl = 16;
   }

   size_t lsize    = clayer->numNeurons*sizeof(pvdata_t);
   size_t lsize_ex = clayer->numExtended*sizeof(pvdata_t);

   clBuffers.V    = device->createBuffer(lsize, clayer->V);
   clBuffers.G_E  = device->createBuffer(lsize, clayer->G_E);
   clBuffers.G_I  = device->createBuffer(lsize, clayer->G_I);
   clBuffers.G_IB = device->createBuffer(lsize, clayer->G_IB);
   clBuffers.phi  = device->createBuffer(lsize, clayer->phi);
   clBuffers.activity = device->createBuffer(lsize_ex, clayer->activity);

   int argid = 0;
   updatestate_kernel->setKernelArg(argid++, clBuffers.V);

   return 0;
}

int V1::setParams(PVParams * params, LIFParams * p)
{
   float dt = .001 * parent->getDeltaTime();  // seconds

   clayer->params = (float *) malloc(sizeof(*p));
   assert(clayer->params != NULL);
   memcpy(clayer->params, p, sizeof(*p));

   clayer->numParams = sizeof(*p) / sizeof(float);
   assert(clayer->numParams == 17);

   LIFParams * cp = (LIFParams *) clayer->params;

   if (params->present(name, "Vrest")) cp->Vrest = params->value(name, "Vrest");
   if (params->present(name, "Vexc"))  cp->Vexc  = params->value(name, "Vexc");
   if (params->present(name, "Vinh"))  cp->Vinh  = params->value(name, "Vinh");
   if (params->present(name, "VinhB")) cp->VinhB = params->value(name, "VinhB");

   if (params->present(name, "tau"))   cp->tau   = params->value(name, "tau");
   if (params->present(name, "tauE"))  cp->tauE  = params->value(name, "tauE");
   if (params->present(name, "tauI"))  cp->tauI  = params->value(name, "tauI");
   if (params->present(name, "tauIB")) cp->tauIB = params->value(name, "tauIB");

   if (params->present(name, "VthRest"))  cp->VthRest  = params->value(name, "VthRest");
   if (params->present(name, "tauVth"))   cp->tauVth   = params->value(name, "tauVth");
   if (params->present(name, "deltaVth")) cp->deltaVth = params->value(name, "deltaVth");

   if (params->present(name, "noiseAmpE"))   cp->noiseAmpE   = params->value(name, "noiseAmpE");
   if (params->present(name, "noiseAmpI"))   cp->noiseAmpI   = params->value(name, "noiseAmpI");
   if (params->present(name, "noiseAmpIB"))  cp->noiseAmpIB  = params->value(name, "noiseAmpIB");

   if (params->present(name, "noiseFreqE")) {
      cp->noiseFreqE  = params->value(name, "noiseFreqE");
      if (dt * cp->noiseFreqE > 1.0) cp->noiseFreqE = 1.0 / dt;
   }
   if (params->present(name, "noiseFreqI")) {
      cp->noiseFreqI  = params->value(name, "noiseFreqI");
      if (dt * cp->noiseFreqI > 1.0) cp->noiseFreqI = 1.0 / dt;
   }
   if (params->present(name, "noiseFreqIB")) {
      cp->noiseFreqIB = params->value(name, "noiseFreqIB");
      if (dt * cp->noiseFreqIB > 1.0) cp->noiseFreqIB = 1.0 / dt;
   }

   return 0;
}

int V1::updateStateOpenCL(float time, float dt)
{
   int status = CL_SUCCESS;

   // setup and run kernel
   // a. unmap the state variables so device can read and write
   // b. pass state variables to kernel
   // c. run kernel
   // e. map the state variable for processing on CPU

   const int nx = clayer->loc.nx;
   const int ny = clayer->loc.ny;

   updatestate_kernel->run(nx, ny, nxl, nyl);

   return status;
}

int V1::updateState(float time, float dt)
{
   PVParams * params = parent->parameters();

   pv_debug_info("[%d]: V1::updateState:", clayer->columnId);

   int spikingFlag = (int) params->value(name, "spikingFlag", 1);

   if (spikingFlag != 0) {
#ifndef PV_USE_OPENCL
      return LIF2_update_exact_linear(clayer, dt);
#else
      return updateStateOpenCL(time, dt);
#endif
   }

   // just copy accumulation buffer to membrane potential
   // and activity buffer (nonspiking)

   updateV();
   setActivity();
   resetPhiBuffers();

   return 0;
}

int V1::updateV() {
   pvdata_t * V = getV();
   pvdata_t ** phi = getCLayer()->phi;
   pvdata_t * phiExc = phi[PHI_EXC];
   pvdata_t * phiInh = phi[PHI_INH];
   for( int k=0; k<getNumNeurons(); k++ ) {
      V[k] = phiExc[k] - phiInh[k];
#undef SET_MAX
#ifdef SET_MAX
      V[k] = V[k] > 1.0f ? 1.0f : V[k];
#endif
#undef SET_THRESH
#ifdef SET_THRESH
      V[k] = V[k] < 0.5f ? 0.0f : V[k];
#endif
   }
   return EXIT_SUCCESS;
}

int V1::setActivity() {
   const int nx = getLayerLoc()->nx;
   const int ny = getLayerLoc()->ny;
   const int nf = getCLayer()->numFeatures;
   const int marginWidth = getLayerLoc()->nPad;
   pvdata_t * activity = getCLayer()->activity->data;
   pvdata_t * V = getV();
   for( int k=0; k<getNumExtended(); k++ ) {
      activity[k] = 0; // Would it be faster to only do the margins?
   }
   for( int k=0; k<getNumNeurons(); k++ ) {
      int kex = kIndexExtended( k, nx, ny, nf, marginWidth );
      activity[kex] = V[k];
   }
   return EXIT_SUCCESS;
}

int V1::resetPhiBuffers() {
   pvdata_t ** phi = getCLayer()->phi;
   int n = getNumNeurons();
   resetBuffer( phi[PHI_EXC], n );
   resetBuffer( phi[PHI_INH], n );
   return EXIT_SUCCESS;
}

int V1::resetBuffer( pvdata_t * buf, int numItems ) {
   for( int k=0; k<numItems; k++ ) buf[k] = 0.0;
   return EXIT_SUCCESS;
}

int V1::writeState(const char * path, float time)
{
   HyPerLayer::writeState(path, time);

#ifdef DEBUG_OUTPUT
   // print activity at center of image

   int sx = clayer->numFeatures;
   int sy = sx*clayer->loc.nx;
   pvdata_t * a = clayer->activity->data;

   int n = (int) (sy*(clayer->loc.ny/2 - 1) + sx*(clayer->loc.nx/2));
   for (int f = 0; f < clayer->numFeatures; f++) {
      printf("f = %d, a[%d] = %f\n", f, n, a[n]);
      n += 1;
   }
   printf("\n");

   n = (int) (sy*(clayer->loc.ny/2 - 1) + sx*(clayer->loc.nx/2));
   n -= 8;
   for (int f = 0; f < clayer->numFeatures; f++) {
      printf("f = %d, a[%d] = %f\n", f, n, a[n]);
      n += 1;
   }
#endif

   return 0;
}

int V1::findPostSynaptic(int dim, int maxSize, int col,
// input: which layer, which neuron
		HyPerLayer *lSource, float pos[],

		// output: how many of our neurons are connected.
		// an array with their indices.
		// an array with their feature vectors.
		int* nNeurons, int nConnectedNeurons[], float *vPos)
{
	return 0;
}

} // namespace PV
<commit_msg>Deleted some OBSOLETE code.  Added some OpenCL implementation in preparation for real stuff.  Actually mostly consistent use of #ifdef PV_USE_OPENCL to remove implementation.<commit_after>/*
 * V1.cpp
 *
 *  Created on: Jul 30, 2008
 *      Author: rasmussn
 */

#include "../include/pv_common.h"
#include "../include/default_params.h"
#include "../connections/PVConnection.h"
#include "HyPerLayer.hpp"
#include "V1.hpp"

#include <assert.h>
#include <float.h>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

namespace PV
{

LIFParams LIFDefaultParams =
{
    V_REST, V_EXC, V_INH, V_INHB,            // V (mV)
    TAU_VMEM, TAU_EXC, TAU_INH, TAU_INHB,
    VTH_REST,  TAU_VTH, DELTA_VTH,	     // tau (ms)
    250, 0*NOISE_AMP*( 1.0/TAU_EXC ) * ( ( TAU_INH * (V_REST-V_INH) + TAU_INHB * (V_REST-V_INHB) ) / (V_EXC-V_REST) ),
    250, 0*NOISE_AMP*1.0,
    250, 0*NOISE_AMP*1.0                       // noise (G)
};

V1::V1(const char* name, HyPerCol * hc)
  : HyPerLayer(name, hc)
{
   initialize(TypeLIFSimple);
}

V1::V1(const char* name, HyPerCol * hc, PVLayerType type)
  : HyPerLayer(name, hc)
{
   initialize(type);
}

int V1::initialize(PVLayerType type)
{
   float time = 0.0f;

   setParams(parent->parameters(), &LIFDefaultParams);

   pvlayer_setFuncs(clayer, (INIT_FN) &LIF2_init, (UPDATE_FN) &LIF2_update_exact_linear);
   this->clayer->layerType = type;

   parent->addLayer(this);

   if (parent->parameters()->value(name, "restart", 0) != 0) {
      readState(name, &time);
   }

#ifdef PV_USE_OPENCL
   // initialize OpenCL parameters
   //
   CLDevice * device = parent->getCLDevice();
   updatestate_kernel = device->createKernel("LIF_updatestate.cl", "LIF_updatestate.cl");

   // TODO - fix to use device and layer parameters
   if (device->id() == 1) {
      nxl = 1;
      nyl = 1;
   }
   else {
      nxl = 16;
      nyl = 16;
   }

   size_t lsize    = clayer->numNeurons*sizeof(pvdata_t);
   size_t lsize_ex = clayer->numExtended*sizeof(pvdata_t);

   clBuffers.V    = device->createBuffer(lsize, clayer->V);
   clBuffers.G_E  = device->createBuffer(lsize, clayer->G_E);
   clBuffers.G_I  = device->createBuffer(lsize, clayer->G_I);
   clBuffers.G_IB = device->createBuffer(lsize, clayer->G_IB);
   clBuffers.phi  = device->createBuffer(lsize, clayer->phi);
   clBuffers.activity = device->createBuffer(lsize_ex, clayer->activity);

   int argid = 0;
   updatestate_kernel->setKernelArg(argid++, clBuffers.V);
#endif

   return 0;
}

int V1::setParams(PVParams * params, LIFParams * p)
{
   float dt = .001 * parent->getDeltaTime();  // seconds

   clayer->params = (float *) malloc(sizeof(*p));
   assert(clayer->params != NULL);
   memcpy(clayer->params, p, sizeof(*p));

   clayer->numParams = sizeof(*p) / sizeof(float);
   assert(clayer->numParams == 17);

   LIFParams * cp = (LIFParams *) clayer->params;

   if (params->present(name, "Vrest")) cp->Vrest = params->value(name, "Vrest");
   if (params->present(name, "Vexc"))  cp->Vexc  = params->value(name, "Vexc");
   if (params->present(name, "Vinh"))  cp->Vinh  = params->value(name, "Vinh");
   if (params->present(name, "VinhB")) cp->VinhB = params->value(name, "VinhB");

   if (params->present(name, "tau"))   cp->tau   = params->value(name, "tau");
   if (params->present(name, "tauE"))  cp->tauE  = params->value(name, "tauE");
   if (params->present(name, "tauI"))  cp->tauI  = params->value(name, "tauI");
   if (params->present(name, "tauIB")) cp->tauIB = params->value(name, "tauIB");

   if (params->present(name, "VthRest"))  cp->VthRest  = params->value(name, "VthRest");
   if (params->present(name, "tauVth"))   cp->tauVth   = params->value(name, "tauVth");
   if (params->present(name, "deltaVth")) cp->deltaVth = params->value(name, "deltaVth");

   if (params->present(name, "noiseAmpE"))   cp->noiseAmpE   = params->value(name, "noiseAmpE");
   if (params->present(name, "noiseAmpI"))   cp->noiseAmpI   = params->value(name, "noiseAmpI");
   if (params->present(name, "noiseAmpIB"))  cp->noiseAmpIB  = params->value(name, "noiseAmpIB");

   if (params->present(name, "noiseFreqE")) {
      cp->noiseFreqE  = params->value(name, "noiseFreqE");
      if (dt * cp->noiseFreqE > 1.0) cp->noiseFreqE = 1.0 / dt;
   }
   if (params->present(name, "noiseFreqI")) {
      cp->noiseFreqI  = params->value(name, "noiseFreqI");
      if (dt * cp->noiseFreqI > 1.0) cp->noiseFreqI = 1.0 / dt;
   }
   if (params->present(name, "noiseFreqIB")) {
      cp->noiseFreqIB = params->value(name, "noiseFreqIB");
      if (dt * cp->noiseFreqIB > 1.0) cp->noiseFreqIB = 1.0 / dt;
   }

   return 0;
}

#ifdef PV_USE_OPENCL
int V1::updateStateOpenCL(float time, float dt)
{
   int status = CL_SUCCESS;

   // setup and run kernel
   // a. unmap the state variables so device can read and write
   // b. pass state variables to kernel
   // c. run kernel
   // e. map the state variable for processing on CPU

   const int nx = clayer->loc.nx;
   const int ny = clayer->loc.ny;

   updatestate_kernel->run(nx, ny, nxl, nyl);

   return status;
}
#endif

int V1::updateState(float time, float dt)
{
   PVParams * params = parent->parameters();

   pv_debug_info("[%d]: V1::updateState:", clayer->columnId);

   int spikingFlag = (int) params->value(name, "spikingFlag", 1);

   if (spikingFlag != 0) {
#ifndef PV_USE_OPENCL
      return LIF2_update_exact_linear(clayer, dt);
#else
      return updateStateOpenCL(time, dt);
#endif
   }

   // just copy accumulation buffer to membrane potential
   // and activity buffer (nonspiking)

   updateV();
   setActivity();
   resetPhiBuffers();

   return 0;
}

int V1::updateV() {
   pvdata_t * V = getV();
   pvdata_t ** phi = getCLayer()->phi;
   pvdata_t * phiExc = phi[PHI_EXC];
   pvdata_t * phiInh = phi[PHI_INH];
   for( int k=0; k<getNumNeurons(); k++ ) {
      V[k] = phiExc[k] - phiInh[k];
#undef SET_MAX
#ifdef SET_MAX
      V[k] = V[k] > 1.0f ? 1.0f : V[k];
#endif
#undef SET_THRESH
#ifdef SET_THRESH
      V[k] = V[k] < 0.5f ? 0.0f : V[k];
#endif
   }
   return EXIT_SUCCESS;
}

int V1::setActivity() {
   const int nx = getLayerLoc()->nx;
   const int ny = getLayerLoc()->ny;
   const int nf = getCLayer()->numFeatures;
   const int marginWidth = getLayerLoc()->nPad;
   pvdata_t * activity = getCLayer()->activity->data;
   pvdata_t * V = getV();
   for( int k=0; k<getNumExtended(); k++ ) {
      activity[k] = 0; // Would it be faster to only do the margins?
   }
   for( int k=0; k<getNumNeurons(); k++ ) {
      int kex = kIndexExtended( k, nx, ny, nf, marginWidth );
      activity[kex] = V[k];
   }
   return EXIT_SUCCESS;
}

int V1::resetPhiBuffers() {
   pvdata_t ** phi = getCLayer()->phi;
   int n = getNumNeurons();
   resetBuffer( phi[PHI_EXC], n );
   resetBuffer( phi[PHI_INH], n );
   return EXIT_SUCCESS;
}

int V1::resetBuffer( pvdata_t * buf, int numItems ) {
   for( int k=0; k<numItems; k++ ) buf[k] = 0.0;
   return EXIT_SUCCESS;
}

int V1::writeState(const char * path, float time)
{
   HyPerLayer::writeState(path, time);

#ifdef DEBUG_OUTPUT
   // print activity at center of image

   int sx = clayer->numFeatures;
   int sy = sx*clayer->loc.nx;
   pvdata_t * a = clayer->activity->data;

   int n = (int) (sy*(clayer->loc.ny/2 - 1) + sx*(clayer->loc.nx/2));
   for (int f = 0; f < clayer->numFeatures; f++) {
      printf("f = %d, a[%d] = %f\n", f, n, a[n]);
      n += 1;
   }
   printf("\n");

   n = (int) (sy*(clayer->loc.ny/2 - 1) + sx*(clayer->loc.nx/2));
   n -= 8;
   for (int f = 0; f < clayer->numFeatures; f++) {
      printf("f = %d, a[%d] = %f\n", f, n, a[n]);
      n += 1;
   }
#endif

   return 0;
}

int V1::findPostSynaptic(int dim, int maxSize, int col,
// input: which layer, which neuron
		HyPerLayer *lSource, float pos[],

		// output: how many of our neurons are connected.
		// an array with their indices.
		// an array with their feature vectors.
		int* nNeurons, int nConnectedNeurons[], float *vPos)
{
	return 0;
}

} // namespace PV
<|endoftext|>


<commit_before>/*
 * #%L
 * %%
 * Copyright (C) 2011 - 2013 BMW Car IT GmbH
 * %%
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * #L%
 */
#include "MockLocalCapabilitiesDirectoryCallback.h"

#include <thread>

using namespace joynr;

MockLocalCapabilitiesDirectoryCallback::MockLocalCapabilitiesDirectoryCallback()
    : ILocalCapabilitiesCallback(),
      results(),
      semaphore(0) {
}

void MockLocalCapabilitiesDirectoryCallback::capabilitiesReceived(std::vector<CapabilityEntry> capabilities) {
    this->results = capabilities;
    semaphore.notify();
}

std::vector<CapabilityEntry> MockLocalCapabilitiesDirectoryCallback::getResults(int timeout) {
    const int waitInterval = 20;
    for (int i = 0; i < timeout; i += waitInterval) {
        std::this_thread::sleep_for(std::chrono::milliseconds(waitInterval));
        if (semaphore.waitFor()) {
            semaphore.notify();
            return results;
        }
    }

    return results;
}

void MockLocalCapabilitiesDirectoryCallback::clearResults(){
    semaphore.wait();
    results.clear();
}

MockLocalCapabilitiesDirectoryCallback::~MockLocalCapabilitiesDirectoryCallback() {
    results.clear();
}
<commit_msg>[C++] Make LocalCapabilitiesDirectoryTests more stable<commit_after>/*
 * #%L
 * %%
 * Copyright (C) 2011 - 2013 BMW Car IT GmbH
 * %%
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * #L%
 */
#include "MockLocalCapabilitiesDirectoryCallback.h"

#include <thread>

using namespace joynr;

MockLocalCapabilitiesDirectoryCallback::MockLocalCapabilitiesDirectoryCallback()
    : ILocalCapabilitiesCallback(),
      results(),
      semaphore(1) {
    semaphore.wait();
}

void MockLocalCapabilitiesDirectoryCallback::capabilitiesReceived(std::vector<CapabilityEntry> capabilities) {
    this->results = capabilities;
    semaphore.notify();
}

std::vector<CapabilityEntry> MockLocalCapabilitiesDirectoryCallback::getResults(int timeout) {
    const int waitInterval = 20;
    for (int i = 0; i < timeout; i += waitInterval) {
        std::this_thread::sleep_for(std::chrono::milliseconds(waitInterval));
        if (semaphore.waitFor()) {
            semaphore.notify();
            return results;
        }
    }

    return results;
}

void MockLocalCapabilitiesDirectoryCallback::clearResults(){
    semaphore.waitFor();
    results.clear();
}

MockLocalCapabilitiesDirectoryCallback::~MockLocalCapabilitiesDirectoryCallback() {
    results.clear();
}
<|endoftext|>


<commit_before>// The MIT License (MIT)

// Copyright (c) 2013 Danny Y., Rapptz

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

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

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

#ifndef SOL_STATE_HPP
#define SOL_STATE_HPP

#include "error.hpp"
#include "table.hpp"
#include <memory>

namespace sol {
namespace detail {
template<class T, class...>
struct are_same : std::true_type {};

template<class T, class U, class... Args>
struct are_same<T, U, Args...> : std::integral_constant<bool, std::is_same<T, U>::value && are_same<T, Args...>::value> {};

int atpanic(lua_State* L) {
    std::string err = lua_tostring(L, -1);
    throw sol_error(err);
}
} // detail

enum class lib : char {
    base,
    package,
    coroutine,
    string,
    os,
    math,
    table,
    debug,
    bit32,
    io,
    count
};

class state {
private:
    std::unique_ptr<lua_State, void(*)(lua_State*)> L;
    table reg;
    table global;
public:
    state():
    L(luaL_newstate(), lua_close),
    reg(L.get(), LUA_REGISTRYINDEX),
    global(reg.get<table>(LUA_RIDX_GLOBALS)) {
        lua_atpanic(L.get(), detail::atpanic);
    }

    state(const std::string& filename):
    L(luaL_newstate(), lua_close),
    reg(L.get(), LUA_REGISTRYINDEX),
    global(reg.get<table>(LUA_RIDX_GLOBALS)) {
        lua_atpanic(L.get(), detail::atpanic);
        open_file(filename);
    }

    template<typename... Args>
    void open_libraries(Args&&... args) {
        static_assert(detail::are_same<lib, Args...>::value, "all types must be libraries");
        if(sizeof...(args) == 0) {
            luaL_openlibs(L.get());
            return;
        }

        lib libraries[1 + sizeof...(args)] = { lib::count, std::forward<Args>(args)... };

        for(auto&& library : libraries) {
            switch(library) {
            case lib::base:
                luaL_requiref(L.get(), "base", luaopen_base, 1);
                break;
            case lib::package:
                luaL_requiref(L.get(), "package", luaopen_package, 1);
                break;
            case lib::coroutine:
                luaL_requiref(L.get(), "coroutine", luaopen_coroutine, 1);
                break;
            case lib::string:
                luaL_requiref(L.get(), "string", luaopen_string, 1);
                break;
            case lib::table:
                luaL_requiref(L.get(), "table", luaopen_table, 1);
                break;
            case lib::math:
                luaL_requiref(L.get(), "math", luaopen_math, 1);
                break;
            case lib::bit32:
                luaL_requiref(L.get(), "bit32", luaopen_bit32, 1);
                break;
            case lib::io:
                luaL_requiref(L.get(), "io", luaopen_io, 1);
                break;
            case lib::os:
                luaL_requiref(L.get(), "os", luaopen_os, 1);
                break;
            case lib::debug:
                luaL_requiref(L.get(), "debug", luaopen_debug, 1);
                break;
            case lib::count:
                break;
            }
        }
    }

    void script(const std::string& code) {
        if(luaL_dostring(L.get(), code.c_str())) {
            lua_error(L.get());
        }
    }

    void open_file(const std::string& filename) {
        if(luaL_dofile(L.get(), filename.c_str())) {
            lua_error(L.get());
        }
    }

    template<typename T, typename U>
    T get(U&& key) const {
        return global.get<T>(std::forward<U>(key));
    }

    template<typename T, typename U>
    state& set(T&& key, U&& value) {
        global.set(std::forward<T>(key), std::forward<U>(value));
        return *this;
    }

    template<typename T, typename TFx>
    state& set_function(T&& key, TFx&& fx) {
        global.set_function(std::forward<T>(key), std::forward<TFx>(fx));
        return *this;
    }

    template<typename T, typename TFx, typename TM>
    state& set_function(T&& key, TFx&& fx, TM& mem) {
        global.set_function(std::forward<T>(key), std::forward<TFx>(fx), mem);
        return *this;
    }

    template<typename T>
    table create_table(T&& key, int narr = 0, int nrec = 0) {
        if(narr == 0 && nrec == 0) {
            lua_newtable(L.get());
        }
        else {
            lua_createtable(L.get(), narr, nrec);
        }

        table result(L.get());
        lua_pop(L.get(), 1);
        global.set(std::forward<T>(key), result);
        return result;
    }

    table create_table(int narr = 0, int nrec = 0) {
        if(narr == 0 && nrec == 0) {
            lua_newtable(L.get());
        }
        else {
            lua_createtable(L.get(), narr, nrec);
        }

        table result(L.get());
        lua_pop(L.get(), 1);
        return result;
    }

    table global_table() const {
        return global;
    }

    table registry() const {
        return reg;
    }
};
} // sol

#endif // SOL_STATE_HPP<commit_msg>Remove construction from a filename as it's pretty useless<commit_after>// The MIT License (MIT)

// Copyright (c) 2013 Danny Y., Rapptz

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

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

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

#ifndef SOL_STATE_HPP
#define SOL_STATE_HPP

#include "error.hpp"
#include "table.hpp"
#include <memory>

namespace sol {
namespace detail {
template<class T, class...>
struct are_same : std::true_type {};

template<class T, class U, class... Args>
struct are_same<T, U, Args...> : std::integral_constant<bool, std::is_same<T, U>::value && are_same<T, Args...>::value> {};

int atpanic(lua_State* L) {
    std::string err = lua_tostring(L, -1);
    throw sol_error(err);
}
} // detail

enum class lib : char {
    base,
    package,
    coroutine,
    string,
    os,
    math,
    table,
    debug,
    bit32,
    io,
    count
};

class state {
private:
    std::unique_ptr<lua_State, void(*)(lua_State*)> L;
    table reg;
    table global;
public:
    state():
    L(luaL_newstate(), lua_close),
    reg(L.get(), LUA_REGISTRYINDEX),
    global(reg.get<table>(LUA_RIDX_GLOBALS)) {
        lua_atpanic(L.get(), detail::atpanic);
    }

    template<typename... Args>
    void open_libraries(Args&&... args) {
        static_assert(detail::are_same<lib, Args...>::value, "all types must be libraries");
        if(sizeof...(args) == 0) {
            luaL_openlibs(L.get());
            return;
        }

        lib libraries[1 + sizeof...(args)] = { lib::count, std::forward<Args>(args)... };

        for(auto&& library : libraries) {
            switch(library) {
            case lib::base:
                luaL_requiref(L.get(), "base", luaopen_base, 1);
                break;
            case lib::package:
                luaL_requiref(L.get(), "package", luaopen_package, 1);
                break;
            case lib::coroutine:
                luaL_requiref(L.get(), "coroutine", luaopen_coroutine, 1);
                break;
            case lib::string:
                luaL_requiref(L.get(), "string", luaopen_string, 1);
                break;
            case lib::table:
                luaL_requiref(L.get(), "table", luaopen_table, 1);
                break;
            case lib::math:
                luaL_requiref(L.get(), "math", luaopen_math, 1);
                break;
            case lib::bit32:
                luaL_requiref(L.get(), "bit32", luaopen_bit32, 1);
                break;
            case lib::io:
                luaL_requiref(L.get(), "io", luaopen_io, 1);
                break;
            case lib::os:
                luaL_requiref(L.get(), "os", luaopen_os, 1);
                break;
            case lib::debug:
                luaL_requiref(L.get(), "debug", luaopen_debug, 1);
                break;
            case lib::count:
                break;
            }
        }
    }

    void script(const std::string& code) {
        if(luaL_dostring(L.get(), code.c_str())) {
            lua_error(L.get());
        }
    }

    void open_file(const std::string& filename) {
        if(luaL_dofile(L.get(), filename.c_str())) {
            lua_error(L.get());
        }
    }

    template<typename T, typename U>
    T get(U&& key) const {
        return global.get<T>(std::forward<U>(key));
    }

    template<typename T, typename U>
    state& set(T&& key, U&& value) {
        global.set(std::forward<T>(key), std::forward<U>(value));
        return *this;
    }

    template<typename T, typename TFx>
    state& set_function(T&& key, TFx&& fx) {
        global.set_function(std::forward<T>(key), std::forward<TFx>(fx));
        return *this;
    }

    template<typename T, typename TFx, typename TM>
    state& set_function(T&& key, TFx&& fx, TM& mem) {
        global.set_function(std::forward<T>(key), std::forward<TFx>(fx), mem);
        return *this;
    }

    template<typename T>
    table create_table(T&& key, int narr = 0, int nrec = 0) {
        if(narr == 0 && nrec == 0) {
            lua_newtable(L.get());
        }
        else {
            lua_createtable(L.get(), narr, nrec);
        }

        table result(L.get());
        lua_pop(L.get(), 1);
        global.set(std::forward<T>(key), result);
        return result;
    }

    table create_table(int narr = 0, int nrec = 0) {
        if(narr == 0 && nrec == 0) {
            lua_newtable(L.get());
        }
        else {
            lua_createtable(L.get(), narr, nrec);
        }

        table result(L.get());
        lua_pop(L.get(), 1);
        return result;
    }

    table global_table() const {
        return global;
    }

    table registry() const {
        return reg;
    }
};
} // sol

#endif // SOL_STATE_HPP<|endoftext|>


<commit_before>/*
	This file is part of cpp-ethereum.

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

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

	You should have received a copy of the GNU General Public License
	along with cpp-ethereum.  If not, see <http://www.gnu.org/licenses/>.
*/
/**
 * @author Christian <c@ethdev.com>
 * @date 2014
 * Solidity commandline compiler.
 */

#include <string>
#include <iostream>
#include <fstream>

#include <boost/program_options.hpp>
#include <boost/filesystem.hpp>

#include "BuildInfo.h"
#include <libdevcore/Common.h>
#include <libdevcore/CommonData.h>
#include <libdevcore/CommonIO.h>
#include <libevmcore/Instruction.h>
#include <libsolidity/Scanner.h>
#include <libsolidity/Parser.h>
#include <libsolidity/ASTPrinter.h>
#include <libsolidity/NameAndTypeResolver.h>
#include <libsolidity/Exceptions.h>
#include <libsolidity/CompilerStack.h>
#include <libsolidity/SourceReferenceFormatter.h>

using namespace std;
using namespace dev;
using namespace solidity;
namespace po = boost::program_options;

void version()
{
	cout << "solc, the solidity complier commandline interface " << dev::Version << endl
		 << "  by Christian <c@ethdev.com> and Lefteris <lefteris@ethdev.com>, (c) 2014." << endl
		 << "Build: " << DEV_QUOTED(ETH_BUILD_PLATFORM) << "/" << DEV_QUOTED(ETH_BUILD_TYPE) << endl;
	exit(0);
}

enum class AstOutput
{
	STDOUT,
	FILE,
	BOTH
};

std::istream& operator>>(std::istream& _in, AstOutput& io_output)
{
	std::string token;
	_in >> token;
	if (token == "stdout")
		io_output = AstOutput::STDOUT;
	else if (token == "file")
		io_output = AstOutput::FILE;
	else if (token == "both")
		io_output = AstOutput::BOTH;
	else
		throw boost::program_options::invalid_option_value(token);
	return _in;
}

int main(int argc, char** argv)
{
	// Declare the supported options.
	po::options_description desc("Allowed options");
	desc.add_options()
	("help", "Show help message and exit")
	("version", "Show version and exit")
	("optimize", po::value<bool>()->default_value(false), "Optimize bytecode for size")
	("input-file", po::value<vector<string>>(), "input file")
	("ast", po::value<AstOutput>(),
	 "Request to output the AST of the contract. Legal values:\n"
	 "\tstdout: Print it to standar output\n"
	 "\tfile: Print it to a file with same name\n");

	// All positional options should be interpreted as input files
	po::positional_options_description p;
	p.add("input-file", -1);

	// parse the compiler arguments
	po::variables_map vm;
	try
	{
		po::store(po::command_line_parser(argc, argv).options(desc).positional(p).allow_unregistered().run(), vm);
	}
	catch (po::error const& exception)
	{
		cout << exception.what() << endl;
		return -1;
	}
	po::notify(vm);

	if (vm.count("help")) {
		cout << desc;
		return 0;
	}

	if (vm.count("version")) {
		version();
		return 0;
	}
	map<string, string> sourceCodes;
	if (!vm.count("input-file"))
	{
		string s;
		while (!cin.eof())
		{
			getline(cin, s);
			sourceCodes["<stdin>"].append(s);
		}
	}
	else
		for (string const& infile: vm["input-file"].as<vector<string>>())
			sourceCodes[infile] = asString(dev::contents(infile));

	CompilerStack compiler;
	try
	{
		for (auto const& sourceCode: sourceCodes)
			compiler.addSource(sourceCode.first, sourceCode.second);
		compiler.compile( vm["optimize"].as<bool>());
	}
	catch (ParserError const& exception)
	{
		SourceReferenceFormatter::printExceptionInformation(cerr, exception, "Parser error", compiler);
		return -1;
	}
	catch (DeclarationError const& exception)
	{
		SourceReferenceFormatter::printExceptionInformation(cerr, exception, "Declaration error", compiler);
		return -1;
	}
	catch (TypeError const& exception)
	{
		SourceReferenceFormatter::printExceptionInformation(cerr, exception, "Type error", compiler);
		return -1;
	}
	catch (CompilerError const& exception)
	{
		SourceReferenceFormatter::printExceptionInformation(cerr, exception, "Compiler error", compiler);
		return -1;
	}
	catch (InternalCompilerError const& exception)
	{
		SourceReferenceFormatter::printExceptionInformation(cerr, exception, "Internal compiler error", compiler);
		return -1;
	}
	catch (Exception const& exception)
	{
		cerr << "Exception during compilation: " << boost::diagnostic_information(exception) << endl;
		return -1;
	}
	catch (...)
	{
		cerr << "Unknown exception during compilation." << endl;
		return -1;
	}

	// do we need AST output?
	if (vm.count("ast"))
	{
		auto choice = vm["ast"].as<AstOutput>();
		if (choice != AstOutput::FILE)
		{
			cout << "Syntax trees:" << endl << endl;
			for (auto const& sourceCode: sourceCodes)
			{
				cout << endl << "======= " << sourceCode.first << " =======" << endl;
				ASTPrinter printer(compiler.getAST(sourceCode.first), sourceCode.second);
				printer.print(cout);
			}
		}

		if (choice != AstOutput::STDOUT)
		{
			for (auto const& sourceCode: sourceCodes)
			{
				boost::filesystem::path p(sourceCode.first);
				ofstream outFile(p.stem().string() + ".ast");
				ASTPrinter printer(compiler.getAST(sourceCode.first), sourceCode.second);
				printer.print(outFile);
				outFile.close();
			}
		}
	}

	vector<string> contracts = compiler.getContractNames();
	cout << endl << "Contracts:" << endl;
	for (string const& contract: contracts)
	{
		cout << endl << "======= " << contract << " =======" << endl
			 << "EVM assembly:" << endl;
		compiler.streamAssembly(cout, contract);
		cout << "Opcodes:" << endl
			 << eth::disassemble(compiler.getBytecode(contract)) << endl
			 << "Binary: " << toHex(compiler.getBytecode(contract)) << endl
			 << "Interface specification: " << compiler.getJsonDocumentation(contract, DocumentationType::ABI_INTERFACE) << endl
			 << "Natspec user documentation: " << compiler.getJsonDocumentation(contract, DocumentationType::NATSPEC_USER) << endl
			 << "Natspec developer documentation: " << compiler.getJsonDocumentation(contract, DocumentationType::NATSPEC_DEV) << endl;
	}

	return 0;
}
<commit_msg>Solc evm assembly to either file or stdout option<commit_after>/*
	This file is part of cpp-ethereum.

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

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

	You should have received a copy of the GNU General Public License
	along with cpp-ethereum.  If not, see <http://www.gnu.org/licenses/>.
*/
/**
 * @author Christian <c@ethdev.com>
 * @date 2014
 * Solidity commandline compiler.
 */

#include <string>
#include <iostream>
#include <fstream>

#include <boost/program_options.hpp>
#include <boost/filesystem.hpp>

#include "BuildInfo.h"
#include <libdevcore/Common.h>
#include <libdevcore/CommonData.h>
#include <libdevcore/CommonIO.h>
#include <libevmcore/Instruction.h>
#include <libsolidity/Scanner.h>
#include <libsolidity/Parser.h>
#include <libsolidity/ASTPrinter.h>
#include <libsolidity/NameAndTypeResolver.h>
#include <libsolidity/Exceptions.h>
#include <libsolidity/CompilerStack.h>
#include <libsolidity/SourceReferenceFormatter.h>

using namespace std;
using namespace dev;
using namespace solidity;
namespace po = boost::program_options;

void version()
{
	cout << "solc, the solidity complier commandline interface " << dev::Version << endl
		 << "  by Christian <c@ethdev.com> and Lefteris <lefteris@ethdev.com>, (c) 2014." << endl
		 << "Build: " << DEV_QUOTED(ETH_BUILD_PLATFORM) << "/" << DEV_QUOTED(ETH_BUILD_TYPE) << endl;
	exit(0);
}

enum class OutputType
{
	STDOUT,
	FILE,
	BOTH
};

#define outputTypeStr "Legal values:\n"\
	 "\tstdout: Print it to standard output\n"\
	 "\tfile: Print it to a file with same name\n"\
	"\tboth: Print both to a file and the stdout\n"

std::istream& operator>>(std::istream& _in, OutputType& io_output)
{
	std::string token;
	_in >> token;
	if (token == "stdout")
		io_output = OutputType::STDOUT;
	else if (token == "file")
		io_output = OutputType::FILE;
	else if (token == "both")
		io_output = OutputType::BOTH;
	else
		throw boost::program_options::invalid_option_value(token);
	return _in;
}

int main(int argc, char** argv)
{
	// Declare the supported options.
	po::options_description desc("Allowed options");
	desc.add_options()
	("help", "Show help message and exit")
	("version", "Show version and exit")
	("optimize", po::value<bool>()->default_value(false), "Optimize bytecode for size")
	("input-file", po::value<vector<string>>(), "input file")
	("ast", po::value<OutputType>(),
	 "Request to output the AST of the contract. " outputTypeStr)
	("asm", po::value<OutputType>(),
	 "Request to output the EVM assembly of the contract. "  outputTypeStr);

	// All positional options should be interpreted as input files
	po::positional_options_description p;
	p.add("input-file", -1);

	// parse the compiler arguments
	po::variables_map vm;
	try
	{
		po::store(po::command_line_parser(argc, argv).options(desc).positional(p).allow_unregistered().run(), vm);
	}
	catch (po::error const& exception)
	{
		cout << exception.what() << endl;
		return -1;
	}
	po::notify(vm);

	if (vm.count("help")) {
		cout << desc;
		return 0;
	}

	if (vm.count("version")) {
		version();
		return 0;
	}
	map<string, string> sourceCodes;
	if (!vm.count("input-file"))
	{
		string s;
		while (!cin.eof())
		{
			getline(cin, s);
			sourceCodes["<stdin>"].append(s);
		}
	}
	else
		for (string const& infile: vm["input-file"].as<vector<string>>())
			sourceCodes[infile] = asString(dev::contents(infile));

	CompilerStack compiler;
	try
	{
		for (auto const& sourceCode: sourceCodes)
			compiler.addSource(sourceCode.first, sourceCode.second);
		compiler.compile( vm["optimize"].as<bool>());
	}
	catch (ParserError const& exception)
	{
		SourceReferenceFormatter::printExceptionInformation(cerr, exception, "Parser error", compiler);
		return -1;
	}
	catch (DeclarationError const& exception)
	{
		SourceReferenceFormatter::printExceptionInformation(cerr, exception, "Declaration error", compiler);
		return -1;
	}
	catch (TypeError const& exception)
	{
		SourceReferenceFormatter::printExceptionInformation(cerr, exception, "Type error", compiler);
		return -1;
	}
	catch (CompilerError const& exception)
	{
		SourceReferenceFormatter::printExceptionInformation(cerr, exception, "Compiler error", compiler);
		return -1;
	}
	catch (InternalCompilerError const& exception)
	{
		SourceReferenceFormatter::printExceptionInformation(cerr, exception, "Internal compiler error", compiler);
		return -1;
	}
	catch (Exception const& exception)
	{
		cerr << "Exception during compilation: " << boost::diagnostic_information(exception) << endl;
		return -1;
	}
	catch (...)
	{
		cerr << "Unknown exception during compilation." << endl;
		return -1;
	}

	// do we need AST output?
	if (vm.count("ast"))
	{
		auto choice = vm["ast"].as<OutputType>();
		if (choice != OutputType::FILE)
		{
			cout << "Syntax trees:" << endl << endl;
			for (auto const& sourceCode: sourceCodes)
			{
				cout << endl << "======= " << sourceCode.first << " =======" << endl;
				ASTPrinter printer(compiler.getAST(sourceCode.first), sourceCode.second);
				printer.print(cout);
			}
		}

		if (choice != OutputType::STDOUT)
		{
			for (auto const& sourceCode: sourceCodes)
			{
				boost::filesystem::path p(sourceCode.first);
				ofstream outFile(p.stem().string() + ".ast");
				ASTPrinter printer(compiler.getAST(sourceCode.first), sourceCode.second);
				printer.print(outFile);
				outFile.close();
			}
		}
	}

	vector<string> contracts = compiler.getContractNames();
	// do we need EVM assembly?
	if (vm.count("asm"))
	{
		auto choice = vm["asm"].as<OutputType>();
		for (string const& contract: contracts)
		{
			if (choice != OutputType::FILE)
			{
				cout << endl << "======= " << contract << " =======" << endl
					 << "EVM assembly:" << endl;
				compiler.streamAssembly(cout, contract);
			}

			if (choice != OutputType::STDOUT)
			{
				ofstream outFile(contract + ".evm");
				compiler.streamAssembly(outFile, contract);
				outFile.close();
			}
		}
	}

	cout << endl << "Contracts:" << endl;
	for (string const& contract: contracts)
	{
		cout << "Opcodes:" << endl
			 << eth::disassemble(compiler.getBytecode(contract)) << endl
			 << "Binary: " << toHex(compiler.getBytecode(contract)) << endl
			 << "Interface specification: " << compiler.getJsonDocumentation(contract, DocumentationType::ABI_INTERFACE) << endl
			 << "Natspec user documentation: " << compiler.getJsonDocumentation(contract, DocumentationType::NATSPEC_USER) << endl
			 << "Natspec developer documentation: " << compiler.getJsonDocumentation(contract, DocumentationType::NATSPEC_DEV) << endl;
	}

	return 0;
}
<|endoftext|>


<commit_before>#include "MidasThread.h"
#include <qdebug.h>
#include <Windows.h>

MidasThread::MidasThread()
{
}

MidasThread::~MidasThread()
{

}

void MidasThread::run()
{
    qDebug() << "running spawned thread.";

    for (int i = 0; i < 100000; i++)
    {
        emit outputCount(i);
        Sleep(100);
    }

    return;
}<commit_msg>last commit on this branch, then freezing to integrate midas on a seperate branch<commit_after>#include "MidasThread.h"
#include <qdebug.h>
#include <Windows.h>

MidasThread::MidasThread()
{
}

MidasThread::~MidasThread()
{

}

void MidasThread::run()
{
    qDebug() << "running spawned thread.";

    for (int i = 0; i < 100000; i++)
    {
        emit outputCount(i);
        Sleep(25);
    }

    return;
}<|endoftext|>