<commit_before>#ifndef SDD_CG_HPP
#define SDD_CG_HPP

#include <iostream>
#include <iomanip>
#include <fstream>
#include <vector>
#include <cmath>

#include <boost/range/algorithm.hpp>

#include <amgcl/amgcl.hpp>
#include <amgcl/backend/builtin.hpp>
#include <amgcl/adapter/crs_tuple.hpp>
#include <amgcl/coarsening/plain_aggregates.hpp>
#include <amgcl/coarsening/smoothed_aggregation.hpp>
#include <amgcl/relaxation/spai0.hpp>
#include <amgcl/solver/bicgstabl.hpp>
#include <amgcl/mpi/deflation.hpp>
#include <amgcl/profiler.hpp>

#include "domain_partition.hpp"

#define CONVECTION

struct linear_deflation {
    long n;
    double h;
    std::vector<long> idx;

    linear_deflation(long n) : n(n), h(1.0 / (n - 1)), idx(n * n) {}

    size_t dim() const { return 3; }

    double operator()(long i, int j) const {
        switch(j) {
            case 1:
                return h * (idx[i] % n);
            case 2:
                return h * (idx[i] / n);
            case 0:
            default:
                return 1;
        }
    }
};

int main(int argc, char *argv[]) {
    boost::mpi::environment  env;
    boost::mpi::communicator world;

    const long n  = argc > 1 ? atoi(argv[1]) : 1024;
    const long n2 = n * n;

    boost::array<long, 2> lo = { {0, 0} };
    boost::array<long, 2> hi = { {n - 1, n - 1} };

    amgcl::profiler<> prof;

    prof.tic("partition");
    domain_partition<2> part(lo, hi, world.size());
    const long chunk = part.size( world.rank() );

    std::vector<long> domain(world.size() + 1);
    all_gather(world, chunk, &domain[1]);
    boost::partial_sum(domain, domain.begin());

    const long chunk_start = domain[world.rank()];
    const long chunk_end   = domain[world.rank() + 1];

    linear_deflation lindef(n);
    std::vector<long> renum(n2);
    for(long j = 0, idx = 0; j < n; ++j) {
        for(long i = 0; i < n; ++i, ++idx) {
            boost::array<long, 2> p = {{i, j}};
            std::pair<int,long> v = part.index(p);
            renum[idx] = domain[v.first] + v.second;
            lindef.idx[renum[idx]] = idx;
        }
    }
    prof.toc("partition");

    prof.tic("assemble");
    std::vector<long>   ptr;
    std::vector<long>   col;
    std::vector<double> val;
    std::vector<double> rhs;

    ptr.reserve(chunk + 1);
    col.reserve(chunk * 5);
    val.reserve(chunk * 5);
    rhs.reserve(chunk);

    ptr.push_back(0);

    const double hinv = (n - 1);
    const double h2i  = (n - 1) * (n - 1);
    for(long j = 0, idx = 0; j < n; ++j) {
        for(long i = 0; i < n; ++i, ++idx) {
            if (renum[idx] < chunk_start || renum[idx] >= chunk_end) continue;

            if (j > 0)  {
                col.push_back(renum[idx - n]);
                val.push_back(-h2i);
            }

            if (i > 0) {
                col.push_back(renum[idx - 1]);
                val.push_back(-h2i
#ifdef CONVECTION
                        - hinv
#endif
                        );
            }

            col.push_back(renum[idx]);
            val.push_back(4 * h2i
#ifdef CONVECTION
                    + hinv
#endif
                    );

            if (i + 1 < n) {
                col.push_back(renum[idx + 1]);
                val.push_back(-h2i);
            }

            if (j + 1 < n) {
                col.push_back(renum[idx + n]);
                val.push_back(-h2i);
            }

            rhs.push_back(1);
            ptr.push_back( col.size() );
        }
    }
    prof.toc("assemble");

    prof.tic("setup");
    typedef amgcl::mpi::subdomain_deflation<
        amgcl::backend::builtin<double>,
        amgcl::coarsening::smoothed_aggregation<
            amgcl::coarsening::plain_aggregates
            >,
        amgcl::relaxation::spai0,
        amgcl::solver::bicgstabl
        > Solver;

    typename Solver::AMG_params    amg_prm;
    typename Solver::Solver_params slv_prm(2);
    Solver solve(world,
            boost::tie(chunk, ptr, col, val),
            lindef,
            amg_prm, slv_prm
            );
    prof.toc("setup");

    prof.tic("solve");
    std::vector<double> x(chunk, 0);
    size_t iters;
    double resid;
    boost::tie(iters, resid) = solve(rhs, x);
    prof.toc("solve");

    prof.tic("save");
    if (world.rank() == 0) {
        std::vector<double> X(n2);
        boost::copy(x, X.begin());

        for(int i = 1; i < world.size(); ++i)
            world.recv(i, 42, &X[domain[i]], domain[i+1] - domain[i]);

        std::ofstream f("out.dat", std::ios::binary);
        int m = n2;
        f.write((char*)&m, sizeof(int));
        for(long i = 0; i < n2; ++i)
            f.write((char*)&X[renum[i]], sizeof(double));
    } else {
        world.send(0, 42, x.data(), chunk);
    }
    prof.toc("save");

    if (world.rank() == 0) {
        std::cout
            << "Iterations: " << iters << std::endl
            << "Error:      " << resid << std::endl
            << std::endl
            << prof << std::endl;
    }
}

#endif
<commit_msg>Add recirculation example into sibdomain_deflation.cpp<commit_after>#ifndef SDD_CG_HPP
#define SDD_CG_HPP

#include <iostream>
#include <iomanip>
#include <fstream>
#include <vector>
#include <cmath>

#include <boost/range/algorithm.hpp>

#include <amgcl/amgcl.hpp>
#include <amgcl/backend/builtin.hpp>
#include <amgcl/adapter/crs_tuple.hpp>
#include <amgcl/coarsening/plain_aggregates.hpp>
#include <amgcl/coarsening/smoothed_aggregation.hpp>
#include <amgcl/relaxation/spai0.hpp>
#include <amgcl/solver/bicgstabl.hpp>
#include <amgcl/mpi/deflation.hpp>
#include <amgcl/profiler.hpp>

#include "domain_partition.hpp"

#define CONVECTION
#define RECIRCULATION

struct linear_deflation {
    long n;
    double h;
    std::vector<long> idx;

    linear_deflation(long n) : n(n), h(1.0 / (n - 1)), idx(n * n) {}

    size_t dim() const { return 3; }

    double operator()(long i, int j) const {
        switch(j) {
            case 1:
                return h * (idx[i] % n);
            case 2:
                return h * (idx[i] / n);
            case 0:
            default:
                return 1;
        }
    }
};

int main(int argc, char *argv[]) {
    boost::mpi::environment  env;
    boost::mpi::communicator world;

    const long n  = argc > 1 ? atoi(argv[1]) : 1024;
    const long n2 = n * n;

    boost::array<long, 2> lo = { {0, 0} };
    boost::array<long, 2> hi = { {n - 1, n - 1} };

    amgcl::profiler<> prof;

    prof.tic("partition");
    domain_partition<2> part(lo, hi, world.size());
    const long chunk = part.size( world.rank() );

    std::vector<long> domain(world.size() + 1);
    all_gather(world, chunk, &domain[1]);
    boost::partial_sum(domain, domain.begin());

    const long chunk_start = domain[world.rank()];
    const long chunk_end   = domain[world.rank() + 1];

    linear_deflation lindef(n);
    std::vector<long> renum(n2);
    for(long j = 0, idx = 0; j < n; ++j) {
        for(long i = 0; i < n; ++i, ++idx) {
            boost::array<long, 2> p = {{i, j}};
            std::pair<int,long> v = part.index(p);
            renum[idx] = domain[v.first] + v.second;
            lindef.idx[renum[idx]] = idx;
        }
    }
    prof.toc("partition");

    prof.tic("assemble");
    std::vector<long>   ptr;
    std::vector<long>   col;
    std::vector<double> val;
    std::vector<double> rhs;

    ptr.reserve(chunk + 1);
    col.reserve(chunk * 5);
    val.reserve(chunk * 5);
    rhs.reserve(chunk);

    ptr.push_back(0);

    const double hinv = (n - 1);
    const double h    = 1 / hinv;
    const double h2i  = (n - 1) * (n - 1);
#ifdef RECIRCULATION
    const double eps = 1e-2;

    for(long j = 0, idx = 0; j < n; ++j) {
        double y = h * j;
        for(long i = 0; i < n; ++i, ++idx) {
            double x = h * i;

            if (renum[idx] < chunk_start || renum[idx] >= chunk_end) continue;

            if (i == 0 || j == 0 || i + 1 == n || j + 1 == n) {
                col.push_back(renum[idx]);
                val.push_back(1);
                rhs.push_back(
                        sin(M_PI * x) + sin(M_PI * y) +
                        sin(13 * M_PI * x) + sin(13 * M_PI * y)
                        );
            } else {
                double a = -sin(M_PI * x) * cos(M_PI * y) * hinv;
                double b =  sin(M_PI * y) * cos(M_PI * x) * hinv;

                if (j > 0) {
                    col.push_back(renum[idx - n]);
                    val.push_back(-eps * h2i - std::max(b, 0.0));
                }

                if (i > 0) {
                    col.push_back(renum[idx - 1]);
                    val.push_back(-eps * h2i - std::max(a, 0.0));
                }

                col.push_back(renum[idx]);
                val.push_back(4 * eps * h2i + fabs(a) + fabs(b));

                if (i + 1 < n) {
                    col.push_back(renum[idx + 1]);
                    val.push_back(-eps * h2i + std::min(a, 0.0));
                }

                if (j + 1 < n) {
                    col.push_back(renum[idx + n]);
                    val.push_back(-eps * h2i + std::min(b, 0.0));
                }

                rhs.push_back(1.0);
            }
            ptr.push_back( col.size() );
        }
    }
#else
    for(long j = 0, idx = 0; j < n; ++j) {
        for(long i = 0; i < n; ++i, ++idx) {
            if (renum[idx] < chunk_start || renum[idx] >= chunk_end) continue;

            if (j > 0)  {
                col.push_back(renum[idx - n]);
                val.push_back(-h2i);
            }

            if (i > 0) {
                col.push_back(renum[idx - 1]);
                val.push_back(-h2i - hinv);
            }

            col.push_back(renum[idx]);
            val.push_back(4 * h2i + hinv);

            if (i + 1 < n) {
                col.push_back(renum[idx + 1]);
                val.push_back(-h2i);
            }

            if (j + 1 < n) {
                col.push_back(renum[idx + n]);
                val.push_back(-h2i);
            }

            rhs.push_back(1);
            ptr.push_back( col.size() );
        }
    }
#endif
    prof.toc("assemble");

    prof.tic("setup");
    typedef amgcl::mpi::subdomain_deflation<
        amgcl::backend::builtin<double>,
        amgcl::coarsening::smoothed_aggregation<
            amgcl::coarsening::plain_aggregates
            >,
        amgcl::relaxation::spai0,
        amgcl::solver::bicgstabl
        > Solver;

    typename Solver::AMG_params    amg_prm;
    typename Solver::Solver_params slv_prm(2);
    Solver solve(world,
            boost::tie(chunk, ptr, col, val),
            lindef,
            amg_prm, slv_prm
            );
    prof.toc("setup");

    prof.tic("solve");
    std::vector<double> x(chunk, 0);
    size_t iters;
    double resid;
    boost::tie(iters, resid) = solve(rhs, x);
    prof.toc("solve");

    prof.tic("save");
    if (world.rank() == 0) {
        std::vector<double> X(n2);
        boost::copy(x, X.begin());

        for(int i = 1; i < world.size(); ++i)
            world.recv(i, 42, &X[domain[i]], domain[i+1] - domain[i]);

        std::ofstream f("out.dat", std::ios::binary);
        int m = n2;
        f.write((char*)&m, sizeof(int));
        for(long i = 0; i < n2; ++i)
            f.write((char*)&X[renum[i]], sizeof(double));
    } else {
        world.send(0, 42, x.data(), chunk);
    }
    prof.toc("save");

    if (world.rank() == 0) {
        std::cout
            << "Iterations: " << iters << std::endl
            << "Error:      " << resid << std::endl
            << std::endl
            << prof << std::endl;
    }
}

#endif
<|endoftext|>


<commit_before>#include <iostream>
#include <string>
#include <sstream>
#include <fstream>
#include <bitcoin/client/watcher.hpp>

/**
 * Command-line interface to the wallet watcher service.
 */
class cli
{
public:
    ~cli();
    cli();

    int run();

private:
    void cmd_exit();
    void cmd_help();
    void cmd_connect(std::stringstream& args);
    void cmd_disconnect(std::stringstream& args);
    void cmd_watch(std::stringstream& args);
    void cmd_height();
    void cmd_tx_height(std::stringstream& args);
    void cmd_tx_watch(std::stringstream& args);
    void cmd_prioritize(std::stringstream& args);
    void cmd_utxos(std::stringstream& args);
    void cmd_save(std::stringstream& args);
    void cmd_load(std::stringstream& args);

    void callback(const libbitcoin::transaction_type& tx);

    bc::hash_digest read_txid(std::stringstream& args);
    bool read_address(std::stringstream& args, bc::payment_address& out);
    bool read_filename(std::stringstream& args, std::string& out);

    libwallet::watcher watcher;
    bool done_;
};

cli::~cli()
{
}

cli::cli()
  : done_(false)
{
    libwallet::watcher::callback cb =
        [this](const libbitcoin::transaction_type& tx)
        {
            callback(tx);
        };
    watcher.set_callback(cb);
}

int cli::run()
{
    while (!done_)
    {
        std::cout << "> " << std::flush;

        char line[1000];
        std::cin.getline(line, sizeof(line));
        std::stringstream reader(line);
        std::string command;
        reader >> command;

        if (command == "exit")              cmd_exit();
        else if (command == "help")         cmd_help();
        else if (command == "connect")      cmd_connect(reader);
        else if (command == "disconnect")   cmd_disconnect(reader);
        else if (command == "watch")        cmd_watch(reader);
        else if (command == "height")       cmd_height();
        else if (command == "txheight")     cmd_tx_height(reader);
        else if (command == "txwatch")      cmd_tx_watch(reader);
        else if (command == "prioritize")   cmd_prioritize(reader);
        else if (command == "utxos")        cmd_utxos(reader);
        else if (command == "save")         cmd_save(reader);
        else if (command == "load")         cmd_load(reader);
        else
            std::cout << "unknown command " << command << std::endl;
    }
    return 0;
}

void cli::cmd_exit()
{
    std::cout << "waiting for thread to stop..." << std::endl;
    done_ = true;
}

void cli::cmd_help()
{
    std::cout << "commands:" << std::endl;
    std::cout << "  exit              - leave the program" << std::endl;
    std::cout << "  help              - this menu" << std::endl;
    std::cout << "  connect <server>  - connect to obelisk server" << std::endl;
    std::cout << "  disconnect        - stop talking to the obelisk server" << std::endl;
    std::cout << "  watch <address>   - watch an address" << std::endl;
    std::cout << "  prioritize [<address>] - check an address more frequently" << std::endl;
    std::cout << "  utxos <address>   - get utxos for an address" << std::endl;
    std::cout << "  save <filename>   - dump the database to disk" << std::endl;
    std::cout << "  load <filename>   - load the database from disk" << std::endl;
}

void cli::cmd_connect(std::stringstream& args)
{
    std::string arg;
    args >> arg;
    if (!arg.size())
    {
        std::cout << "no server given" << std::endl;
        return;
    }
    std::cout << "connecting to " << arg << std::endl;

    watcher.connect(arg);
}

void cli::cmd_disconnect(std::stringstream& args)
{
    watcher.disconnect();
}

void cli::cmd_height()
{
    std::cout << watcher.get_last_block_height() << std::endl;
}

void cli::cmd_tx_height(std::stringstream& args)
{
    bc::hash_digest txid = read_txid(args);
    if (txid == bc::null_hash)
        return;
    std::cout << watcher.get_tx_height(txid) << std::endl;
}

void cli::cmd_tx_watch(std::stringstream& args)
{
    bc::hash_digest txid = read_txid(args);
    if (txid == bc::null_hash)
        return;
    watcher.watch_tx_mem(txid);
}

void cli::cmd_watch(std::stringstream& args)
{
    bc::payment_address address;
    if (!read_address(args, address))
        return;
    watcher.watch_address(address);
}

void cli::cmd_prioritize(std::stringstream& args)
{
    bc::payment_address address;
    std::string arg;
    args >> arg;
    if (arg.size())
        address.set_encoded(arg);
    watcher.prioritize_address(address);
}

void cli::cmd_utxos(std::stringstream& args)
{
    bc::payment_address address;
    if (!read_address(args, address))
        return;

    auto list = watcher.get_utxos(address);
    for (auto& utxo: list)
        std::cout << bc::encode_hex(utxo.point.hash) << ":" <<
            utxo.point.index << std::endl;
}

void cli::cmd_save(std::stringstream& args)
{
    std::string filename;
    if (!read_filename(args, filename))
        return;

    std::ofstream file(filename);
    if (!file.is_open())
    {
        std::cerr << "cannot open " << filename << std::endl;
        return;
    }

    auto db = watcher.serialize();
    file.write(reinterpret_cast<const char*>(db.data()), db.size());
    file.close();
}

void cli::cmd_load(std::stringstream& args)
{
    std::string filename;
    if (!read_filename(args, filename))
        return;

    std::ifstream file(filename, std::ios::in | std::ios::binary | std::ios::ate);
    if (!file.is_open())
    {
        std::cerr << "cannot open " << filename << std::endl;
        return;
    }

    std::streampos size = file.tellg();
    uint8_t *data = new uint8_t[size];
    file.seekg(0, std::ios::beg);
    file.read(reinterpret_cast<char*>(data), size);
    file.close();

    if (!watcher.load(bc::data_chunk(data, data + size)))
        std::cerr << "error while loading data" << std::endl;
}

void cli::callback(const libbitcoin::transaction_type& tx)
{
    auto txid = libbitcoin::encode_hex(libbitcoin::hash_transaction(tx));
    std::cout << "got transaction " << txid << std::endl;
}

bc::hash_digest cli::read_txid(std::stringstream& args)
{
    std::string arg;
    args >> arg;
    if (!arg.size())
    {
        std::cout << "no txid given" << std::endl;
        return bc::null_hash;
    }
    return bc::decode_hash(arg);
}

bool cli::read_address(std::stringstream& args, bc::payment_address& out)
{
    std::string arg;
    args >> arg;
    if (!arg.size())
    {
        std::cout << "no address given" << std::endl;
        return false;
    }

    if (!out.set_encoded(arg))
    {
        std::cout << "invalid address " << arg << std::endl;
        return false;
    }
    return true;
}

bool cli::read_filename(std::stringstream& args, std::string& out)
{
    args >> out;
    if (!out.size())
    {
        std::cout << "no file name given" << std::endl;
        return false;
    }
    return true;
}

int main()
{
    cli c;
    std::cout << "type \"help\" for instructions" << std::endl;
    return c.run();
}
<commit_msg>Make some simple watcher example cleanups<commit_after>#include <iostream>
#include <string>
#include <sstream>
#include <fstream>
#include <bitcoin/client/watcher.hpp>

/**
 * Command-line interface to the wallet watcher service.
 */
class cli
{
public:
    ~cli();
    cli();

    int run();

private:
    void cmd_exit();
    void cmd_help();
    void cmd_connect(std::stringstream& args);
    void cmd_disconnect(std::stringstream& args);
    void cmd_watch(std::stringstream& args);
    void cmd_height();
    void cmd_tx_height(std::stringstream& args);
    void cmd_tx_watch(std::stringstream& args);
    void cmd_prioritize(std::stringstream& args);
    void cmd_utxos(std::stringstream& args);
    void cmd_save(std::stringstream& args);
    void cmd_load(std::stringstream& args);

    void callback(const libbitcoin::transaction_type& tx);

    bc::hash_digest read_txid(std::stringstream& args);
    bool read_address(std::stringstream& args, bc::payment_address& out);
    bool read_filename(std::stringstream& args, std::string& out);

    libwallet::watcher watcher;
    bool done_;
};

cli::~cli()
{
}

cli::cli()
  : done_(false)
{
    libwallet::watcher::callback cb =
        [this](const libbitcoin::transaction_type& tx)
        {
            callback(tx);
        };
    watcher.set_callback(cb);
}

int cli::run()
{
    std::cout << "type \"help\" for instructions" << std::endl;

    while (!done_)
    {
        // Read a line:
        std::cout << "> " << std::flush;
        char line[1000];
        std::cin.getline(line, sizeof(line));

        // Extract the command:
        std::stringstream reader(line);
        std::string command;
        reader >> command;

        if (command == "exit")              cmd_exit();
        else if (command == "help")         cmd_help();
        else if (command == "connect")      cmd_connect(reader);
        else if (command == "disconnect")   cmd_disconnect(reader);
        else if (command == "watch")        cmd_watch(reader);
        else if (command == "height")       cmd_height();
        else if (command == "txheight")     cmd_tx_height(reader);
        else if (command == "txwatch")      cmd_tx_watch(reader);
        else if (command == "prioritize")   cmd_prioritize(reader);
        else if (command == "utxos")        cmd_utxos(reader);
        else if (command == "save")         cmd_save(reader);
        else if (command == "load")         cmd_load(reader);
        else
            std::cout << "unknown command " << command << std::endl;
    }
    return 0;
}

void cli::cmd_exit()
{
    std::cout << "waiting for thread to stop..." << std::endl;
    done_ = true;
}

void cli::cmd_help()
{
    std::cout << "commands:" << std::endl;
    std::cout << "  exit              - leave the program" << std::endl;
    std::cout << "  help              - this menu" << std::endl;
    std::cout << "  connect <server>  - connect to obelisk server" << std::endl;
    std::cout << "  disconnect        - stop talking to the obelisk server" << std::endl;
    std::cout << "  watch <address>   - watch an address" << std::endl;
    std::cout << "  prioritize [<address>] - check an address more frequently" << std::endl;
    std::cout << "  utxos <address>   - get utxos for an address" << std::endl;
    std::cout << "  save <filename>   - dump the database to disk" << std::endl;
    std::cout << "  load <filename>   - load the database from disk" << std::endl;
}

void cli::cmd_connect(std::stringstream& args)
{
    std::string arg;
    args >> arg;
    if (!arg.size())
    {
        std::cout << "no server given" << std::endl;
        return;
    }
    std::cout << "connecting to " << arg << std::endl;

    watcher.connect(arg);
}

void cli::cmd_disconnect(std::stringstream& args)
{
    watcher.disconnect();
}

void cli::cmd_height()
{
    std::cout << watcher.get_last_block_height() << std::endl;
}

void cli::cmd_tx_height(std::stringstream& args)
{
    bc::hash_digest txid = read_txid(args);
    if (txid == bc::null_hash)
        return;
    std::cout << watcher.get_tx_height(txid) << std::endl;
}

void cli::cmd_tx_watch(std::stringstream& args)
{
    bc::hash_digest txid = read_txid(args);
    if (txid == bc::null_hash)
        return;
    watcher.watch_tx_mem(txid);
}

void cli::cmd_watch(std::stringstream& args)
{
    bc::payment_address address;
    if (!read_address(args, address))
        return;
    watcher.watch_address(address);
}

void cli::cmd_prioritize(std::stringstream& args)
{
    bc::payment_address address;
    std::string arg;
    args >> arg;
    if (arg.size())
        address.set_encoded(arg);
    watcher.prioritize_address(address);
}

void cli::cmd_utxos(std::stringstream& args)
{
    bc::payment_address address;
    if (!read_address(args, address))
        return;

    auto list = watcher.get_utxos(address);
    for (auto& utxo: list)
        std::cout << bc::encode_hex(utxo.point.hash) << ":" <<
            utxo.point.index << std::endl;
}

void cli::cmd_save(std::stringstream& args)
{
    std::string filename;
    if (!read_filename(args, filename))
        return;

    std::ofstream file(filename);
    if (!file.is_open())
    {
        std::cerr << "cannot open " << filename << std::endl;
        return;
    }

    auto db = watcher.serialize();
    file.write(reinterpret_cast<const char*>(db.data()), db.size());
    file.close();
}

void cli::cmd_load(std::stringstream& args)
{
    std::string filename;
    if (!read_filename(args, filename))
        return;

    std::ifstream file(filename, std::ios::in | std::ios::binary | std::ios::ate);
    if (!file.is_open())
    {
        std::cerr << "cannot open " << filename << std::endl;
        return;
    }

    std::streampos size = file.tellg();
    uint8_t *data = new uint8_t[size];
    file.seekg(0, std::ios::beg);
    file.read(reinterpret_cast<char*>(data), size);
    file.close();

    if (!watcher.load(bc::data_chunk(data, data + size)))
        std::cerr << "error while loading data" << std::endl;
}

void cli::callback(const libbitcoin::transaction_type& tx)
{
    auto txid = libbitcoin::encode_hex(libbitcoin::hash_transaction(tx));
    std::cout << "got transaction " << txid << std::endl;
}

bc::hash_digest cli::read_txid(std::stringstream& args)
{
    std::string arg;
    args >> arg;
    if (!arg.size())
    {
        std::cout << "no txid given" << std::endl;
        return bc::null_hash;
    }
    return bc::decode_hash(arg);
}

bool cli::read_address(std::stringstream& args, bc::payment_address& out)
{
    std::string arg;
    args >> arg;
    if (!arg.size())
    {
        std::cout << "no address given" << std::endl;
        return false;
    }

    if (!out.set_encoded(arg))
    {
        std::cout << "invalid address " << arg << std::endl;
        return false;
    }
    return true;
}

bool cli::read_filename(std::stringstream& args, std::string& out)
{
    args >> out;
    if (!out.size())
    {
        std::cout << "no file name given" << std::endl;
        return false;
    }
    return true;
}

int main()
{
    cli c;
    return c.run();
}
<|endoftext|>


<commit_before>/**
 * logger_metrics_test.cc
 * Mich, 2014-11-17
 * Copyright (c) 2014 Datacratic Inc. All rights reserved.
 *
 * Manual test for the logger metrics. Provide the proper json config and
 * run.
 **/

#define BOOST_TEST_MAIN
#define BOOST_TEST_DYN_LINK

#include <boost/test/unit_test.hpp>
#include <boost/filesystem.hpp>
#include <boost/smart_ptr.hpp>
#include <boost/thread/barrier.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/regex.hpp>

#include "mongo/bson/bson.h"
#include "mongo/bson/bsonobj.h"
#include "mongo/client/dbclient.h"
#include "jml/utils/filter_streams.h"
#include "soa/service/testing/mongo_temporary_server.h"
#include "soa/logger/logger_metrics_interface.h"

using namespace ML;
using namespace Datacratic;
using namespace std;

BOOST_AUTO_TEST_CASE( test_logger_metrics ) {
    Mongo::MongoTemporaryServer mongo;
    setenv("CONFIG", "soa/logger/testing/logger_metrics_config.json", 1);
    shared_ptr<ILoggerMetrics> logger =
        ILoggerMetrics::setup("metricsLogger", "lalmetrics", "test");

    logger->logMeta({"a", "b"}, "taratapom");

    Json::Value config;
    filter_istream cfgStream("soa/logger/testing/logger_metrics_config.json");
    cfgStream >> config;

    Json::Value metricsLogger = config["metricsLogger"];
    auto conn = std::make_shared<mongo::DBClientConnection>();
    conn->connect(metricsLogger["hostAndPort"].asString());
    string err;
    if (!conn->auth(metricsLogger["database"].asString(),
                    metricsLogger["user"].asString(),
                    metricsLogger["pwd"].asString(), err)) {
        throw ML::Exception("Failed to log to mongo tmp server: %s",
                            err.c_str());
    }

    BOOST_CHECK_EQUAL(conn->count("test.lalmetrics"), 1);
    auto cursor = conn->query("test.lalmetrics", mongo::BSONObj());
    BOOST_CHECK(cursor->more());
    {
        mongo::BSONObj p = cursor->next();
        BOOST_CHECK_EQUAL(p.getFieldDotted("meta.a.b").String(), "taratapom");
    }

    logger->logMetrics({"fooValue"}, 123);
    ML::sleep(1); // Leave time for async write
    cursor = conn->query("test.lalmetrics", mongo::BSONObj());
    BOOST_CHECK(cursor->more());
    {
        mongo::BSONObj p = cursor->next();
        BOOST_CHECK_EQUAL(p["metrics"]["fooValue"].Number(), 123);
    }

    Json::Value block;
    block["alpha"] = 1;
    block["beta"] = 2;
    block["coco"] = Json::objectValue;
    block["coco"]["sanchez"] = 3;
    logger->logMetrics(block);
    ML::sleep(1); // Leave time for async write
    cursor = conn->query("test.lalmetrics", mongo::BSONObj());
    BOOST_CHECK(cursor->more());
    {
        mongo::BSONObj p = cursor->next();
        BOOST_CHECK_EQUAL(p["metrics"]["coco"]["sanchez"].Number(), 3);
    }
}
<commit_msg>logger_metrics_test: use "setupFromJson"<commit_after>/**
 * logger_metrics_test.cc
 * Mich, 2014-11-17
 * Copyright (c) 2014 Datacratic Inc. All rights reserved.
 *
 * Manual test for the logger metrics. Provide the proper json config and
 * run.
 **/

#define BOOST_TEST_MAIN
#define BOOST_TEST_DYN_LINK

#include <boost/test/unit_test.hpp>
#include <boost/filesystem.hpp>
#include <boost/smart_ptr.hpp>
#include <boost/thread/barrier.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/regex.hpp>

#include "mongo/bson/bson.h"
#include "mongo/bson/bsonobj.h"
#include "mongo/client/dbclient.h"
#include "jml/utils/filter_streams.h"
#include "soa/service/testing/mongo_temporary_server.h"
#include "soa/logger/logger_metrics_interface.h"

using namespace ML;
using namespace Datacratic;
using namespace std;

BOOST_AUTO_TEST_CASE( test_logger_metrics ) {
    Mongo::MongoTemporaryServer mongo;
    string filename("soa/logger/testing/logger_metrics_config.json");
    Json::Value config = Json::parseFromFile(filename);
    const Json::Value & metricsLogger = config["metricsLogger"];
    auto logger = ILoggerMetrics::setupFromJson(metricsLogger,
                                                "lalmetrics", "test");

    logger->logMeta({"a", "b"}, "taratapom");

    auto conn = std::make_shared<mongo::DBClientConnection>();
    conn->connect(metricsLogger["hostAndPort"].asString());
    string err;
    if (!conn->auth(metricsLogger["database"].asString(),
                    metricsLogger["user"].asString(),
                    metricsLogger["pwd"].asString(), err)) {
        throw ML::Exception("Failed to log to mongo tmp server: %s",
                            err.c_str());
    }

    BOOST_CHECK_EQUAL(conn->count("test.lalmetrics"), 1);
    auto cursor = conn->query("test.lalmetrics", mongo::BSONObj());
    BOOST_CHECK(cursor->more());
    {
        mongo::BSONObj p = cursor->next();
        BOOST_CHECK_EQUAL(p.getFieldDotted("meta.a.b").String(), "taratapom");
    }

    logger->logMetrics({"fooValue"}, 123);
    ML::sleep(1); // Leave time for async write
    cursor = conn->query("test.lalmetrics", mongo::BSONObj());
    BOOST_CHECK(cursor->more());
    {
        mongo::BSONObj p = cursor->next();
        BOOST_CHECK_EQUAL(p["metrics"]["fooValue"].Number(), 123);
    }

    Json::Value block;
    block["alpha"] = 1;
    block["beta"] = 2;
    block["coco"] = Json::objectValue;
    block["coco"]["sanchez"] = 3;
    logger->logMetrics(block);
    ML::sleep(1); // Leave time for async write
    cursor = conn->query("test.lalmetrics", mongo::BSONObj());
    BOOST_CHECK(cursor->more());
    {
        mongo::BSONObj p = cursor->next();
        BOOST_CHECK_EQUAL(p["metrics"]["coco"]["sanchez"].Number(), 3);
    }
}
<|endoftext|>


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

#include "gams.h"
#include <iostream>
#include <vector>

using namespace gams;
using namespace std;

#if defined(__unix__) || defined(__linux__) || defined(__APPLE__)

/// \file transport10.cpp
/// \brief This is the 10th model in a series of tutorial examples.
int main()
{
    cout << "---------- Transport 10 --------------" << endl;
    cout << "Transport 10 is a Microsoft Windows only example." << endl;
    return 0;
}

#else

#include <QAxObject>
#include <Windows.h> // includes "Ole2.h" that includes "objbase.h" to access CoInitialize() and CoUninitialize()

string getModelText()
{
    return  "  Sets                                                                     \n"
            "       i   canning plants                                                  \n"
            "       j   markets                                                         \n"
            "                                                                           \n"
            "  Parameters                                                               \n"
            "       a(i)   capacity of plant i in cases                                 \n"
            "       b(j)   demand at market j in cases                                  \n"
            "       d(i,j) distance in thousands of miles                               \n"
            "  Scalar f  freight in dollars per case per thousand miles /90/;           \n"
            "                                                                           \n"
            "$if not set gdxincname $abort 'no include file name for data file provided'\n"
            "$gdxin %gdxincname%                                                        \n"
            "$load i j a b d                                                            \n"
            "$gdxin                                                                     \n"
            "                                                                           \n"
            "  Parameter c(i,j)  transport cost in thousands of dollars per case ;      \n"
            "                                                                           \n"
            "            c(i,j) = f * d(i,j) / 1000 ;                                   \n"
            "                                                                           \n"
            "  Variables                                                                \n"
            "       x(i,j)  shipment quantities in cases                                \n"
            "       z       total transportation costs in thousands of dollars ;        \n"
            "                                                                           \n"
            "  Positive Variable x ;                                                    \n"
            "                                                                           \n"
            "  Equations                                                                \n"
            "       cost        define objective function                               \n"
            "       supply(i)   observe supply limit at plant i                         \n"
            "       demand(j)   satisfy demand at market j ;                            \n"
            "                                                                           \n"
            "  cost ..        z  =e=  sum((i,j), c(i,j)*x(i,j)) ;                       \n"
            "                                                                           \n"
            "  supply(i) ..   sum(j, x(i,j))  =l=  a(i) ;                               \n"
            "                                                                           \n"
            "  demand(j) ..   sum(i, x(i,j))  =g=  b(j) ;                               \n"
            "                                                                           \n"
            "  Model transport /all/ ;                                                  \n"
            "                                                                           \n"
            "  Solve transport using lp minimizing z ;                                  \n"
            "                                                                           \n"
            "  Display x.l, x.m ;                                                       \n";
}

/// Creates an 1 dimensional GAMSParameter and transfers data from an Excel sheet (horizontal ordered)
///
/// \param sheets The sheets object of an open Excel workbook
/// \param sheetName The name of the sheet to be read
/// \param db The GAMSDatabase where the GAMSParameter is created in
/// \param paramName The name of the new GAMSParameter
/// \param paramText The explplanatory text of the new GAMSParameter
/// \param set The GAMSSet for GAMSParameter dimension
/// \return The new GAMSParameter in the GAMSDatabase
///
GAMSParameter sheetToParameter(QAxObject* sheets, string sheetName
                               , GAMSDatabase db, string paramName, string paramText, GAMSSet set)
{
    QAxObject* sheet = sheets->querySubObject( "Item( string )", sheetName.c_str() );
    GAMSParameter param = db.addParameter(paramName, paramText, set);

    QAxObject* usedrange = sheet->querySubObject( "UsedRange");
    QAxObject * columns = usedrange->querySubObject("Columns");
    int intCols = columns->property("Count").toInt();

    for (int i = 1; i <= intCols; i++) {
        std::string name = sheet->querySubObject("Cells( int, int )", 1, i)->dynamicCall("Value()").toString().toStdString();
        double value = sheet->querySubObject("Cells( int, int )", 2, i)->dynamicCall("Value()").toDouble();
        set.addRecord(name);
        GAMSParameterRecord rec = param.addRecord(name);
        rec.setValue(value);
    }
    return param;
}

/// Creates a 2 dimensional GAMSParameter and transfers data from an Excel sheet
///
/// \param sheets The sheets object of an open Excel workbook
/// \param sheetName The name of the sheet to be read
/// \param db The GAMSDatabase where the GAMSParameter is created in
/// \param paramName The name of the new GAMSParameter
/// \param paramText The explplanatory text of the new GAMSParameter
/// \param set1 The GAMSSet for first GAMSParameter dimension
/// \param set2 The GAMSSet for second GAMSParameter dimension
/// \return The new GAMSParameter in the GAMSDatabase
///
GAMSParameter sheetToParameter(QAxObject* sheets, string sheetName
                               , GAMSDatabase db, string paramName, string paramText, GAMSSet set1, GAMSSet set2)
{
    QAxObject* sheet = sheets->querySubObject( "Item( string )", sheetName.c_str() );
    vector<GAMSDomain> sets {set1, set2};
    GAMSParameter param = db.addParameter(paramName, paramText, sets);

    QAxObject* usedrange = sheet->querySubObject( "UsedRange");
    QAxObject * columns = usedrange->querySubObject("Columns");
    int intCols = columns->property("Count").toInt();
    QAxObject * rows = usedrange->querySubObject("Rows");
    int intRows = rows->property("Count").toInt();

    for (int j = 2; j <= intCols; j++) {
        string namej = sheet->querySubObject("Cells( int, int )", 1, j)->dynamicCall("Value()").toString().toStdString();
        for (int i = 2; i <= intRows; ++i) {
            string namei = sheet->querySubObject("Cells( int, int )", i, 1)->dynamicCall("Value()").toString().toStdString();
            GAMSParameterRecord rec = param.addRecord(namei, namej);
            double value = sheet->querySubObject("Cells( int, int )", i, j)->dynamicCall("Value()").toDouble();
            rec.setValue(value);
        }
    }
    return param;
}

/// \file transport10.cpp
/// \brief This is the 10th model in a series of tutorial examples.
///
/// Here we show:
///   - How to fill a GAMSDatabase by reading from MS Excel
int main(int argc, char* argv[])
{
    cout << "---------- Transport 10 --------------" << endl;
    try {
        ::CoInitialize(0); // initialize thread to use ActiveX (some systems may need CoInititializeEx)

        GAMSWorkspaceInfo wsInfo;
        if (argc > 1)
            wsInfo.setSystemDirectory(argv[1]);
        GAMSWorkspace ws(wsInfo);

        // Creating the GAMSDatabase and fill with the workbook data
        GAMSDatabase db = ws.addDatabase();
        QString fileName = QString::fromStdString(ws.systemDirectory())+ cPathSep + "apifiles" + cPathSep + "Data" + cPathSep + "transport.xls";

        QAxObject* excel = new QAxObject( "Excel.Application", 0 );
        QAxObject* workbooks = excel->querySubObject( "Workbooks" );
        QAxObject* workbook = workbooks->querySubObject( "Open(const QString&)", fileName );
        QAxObject* sheets = workbook->querySubObject( "Worksheets" );

        GAMSSet i = db.addSet("i", 1, "Plants");
        GAMSSet j = db.addSet("j", 1, "Markets");

        // read parameters
        sheetToParameter(sheets, "capacity", db, "a", "Capacity", i);
        sheetToParameter(sheets, "demand", db, "b", "Demand", j);
        sheetToParameter(sheets, "distance", db, "d", "Distance", i, j);

        // clean up and close up
        workbook->dynamicCall("Close()");
        excel->dynamicCall("Quit()");

        // Create and run the GAMSJob
        GAMSOptions opt = ws.addOptions();
        GAMSJob t10 = ws.addJobFromString(getModelText());
        opt.setDefine("gdxincname", db.name());
        opt.setAllModelTypes("xpress");
        t10.run(opt, db);
        for (GAMSVariableRecord record : t10.outDB().getVariable("x"))
            cout << "x(" << record.key(0) << "," << record.key(1) << "): level=" << record.level() <<
                    " marginal=" << record.marginal() << endl;

        ::CoUninitialize();

    } catch (GAMSException &ex) {
        cout << "GAMSException occured: " << ex.what() << endl;
    } catch (exception &ex) {
        cout << ex.what() << endl;
    }

    return 0;
}
#endif
<commit_msg>xls -> xlsx<commit_after>/*
 *
 * GAMS - General Algebraic Modeling System C++ API
 *
 * Copyright (c) 2017-2022 GAMS Software GmbH <support@gams.com>
 * Copyright (c) 2017-2022 GAMS Development Corp. <support@gams.com>
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

#include "gams.h"
#include <iostream>
#include <vector>

using namespace gams;
using namespace std;

#if defined(__unix__) || defined(__linux__) || defined(__APPLE__)

/// \file transport10.cpp
/// \brief This is the 10th model in a series of tutorial examples.
int main()
{
    cout << "---------- Transport 10 --------------" << endl;
    cout << "Transport 10 is a Microsoft Windows only example." << endl;
    return 0;
}

#else

#include <QAxObject>
#include <Windows.h> // includes "Ole2.h" that includes "objbase.h" to access CoInitialize() and CoUninitialize()

string getModelText()
{
    return  "  Sets                                                                     \n"
            "       i   canning plants                                                  \n"
            "       j   markets                                                         \n"
            "                                                                           \n"
            "  Parameters                                                               \n"
            "       a(i)   capacity of plant i in cases                                 \n"
            "       b(j)   demand at market j in cases                                  \n"
            "       d(i,j) distance in thousands of miles                               \n"
            "  Scalar f  freight in dollars per case per thousand miles /90/;           \n"
            "                                                                           \n"
            "$if not set gdxincname $abort 'no include file name for data file provided'\n"
            "$gdxin %gdxincname%                                                        \n"
            "$load i j a b d                                                            \n"
            "$gdxin                                                                     \n"
            "                                                                           \n"
            "  Parameter c(i,j)  transport cost in thousands of dollars per case ;      \n"
            "                                                                           \n"
            "            c(i,j) = f * d(i,j) / 1000 ;                                   \n"
            "                                                                           \n"
            "  Variables                                                                \n"
            "       x(i,j)  shipment quantities in cases                                \n"
            "       z       total transportation costs in thousands of dollars ;        \n"
            "                                                                           \n"
            "  Positive Variable x ;                                                    \n"
            "                                                                           \n"
            "  Equations                                                                \n"
            "       cost        define objective function                               \n"
            "       supply(i)   observe supply limit at plant i                         \n"
            "       demand(j)   satisfy demand at market j ;                            \n"
            "                                                                           \n"
            "  cost ..        z  =e=  sum((i,j), c(i,j)*x(i,j)) ;                       \n"
            "                                                                           \n"
            "  supply(i) ..   sum(j, x(i,j))  =l=  a(i) ;                               \n"
            "                                                                           \n"
            "  demand(j) ..   sum(i, x(i,j))  =g=  b(j) ;                               \n"
            "                                                                           \n"
            "  Model transport /all/ ;                                                  \n"
            "                                                                           \n"
            "  Solve transport using lp minimizing z ;                                  \n"
            "                                                                           \n"
            "  Display x.l, x.m ;                                                       \n";
}

/// Creates an 1 dimensional GAMSParameter and transfers data from an Excel sheet (horizontal ordered)
///
/// \param sheets The sheets object of an open Excel workbook
/// \param sheetName The name of the sheet to be read
/// \param db The GAMSDatabase where the GAMSParameter is created in
/// \param paramName The name of the new GAMSParameter
/// \param paramText The explplanatory text of the new GAMSParameter
/// \param set The GAMSSet for GAMSParameter dimension
/// \return The new GAMSParameter in the GAMSDatabase
///
GAMSParameter sheetToParameter(QAxObject* sheets, string sheetName
                               , GAMSDatabase db, string paramName, string paramText, GAMSSet set)
{
    QAxObject* sheet = sheets->querySubObject( "Item( string )", sheetName.c_str() );
    GAMSParameter param = db.addParameter(paramName, paramText, set);

    QAxObject* usedrange = sheet->querySubObject( "UsedRange");
    QAxObject * columns = usedrange->querySubObject("Columns");
    int intCols = columns->property("Count").toInt();

    for (int i = 1; i <= intCols; i++) {
        std::string name = sheet->querySubObject("Cells( int, int )", 1, i)->dynamicCall("Value()").toString().toStdString();
        double value = sheet->querySubObject("Cells( int, int )", 2, i)->dynamicCall("Value()").toDouble();
        set.addRecord(name);
        GAMSParameterRecord rec = param.addRecord(name);
        rec.setValue(value);
    }
    return param;
}

/// Creates a 2 dimensional GAMSParameter and transfers data from an Excel sheet
///
/// \param sheets The sheets object of an open Excel workbook
/// \param sheetName The name of the sheet to be read
/// \param db The GAMSDatabase where the GAMSParameter is created in
/// \param paramName The name of the new GAMSParameter
/// \param paramText The explplanatory text of the new GAMSParameter
/// \param set1 The GAMSSet for first GAMSParameter dimension
/// \param set2 The GAMSSet for second GAMSParameter dimension
/// \return The new GAMSParameter in the GAMSDatabase
///
GAMSParameter sheetToParameter(QAxObject* sheets, string sheetName
                               , GAMSDatabase db, string paramName, string paramText, GAMSSet set1, GAMSSet set2)
{
    QAxObject* sheet = sheets->querySubObject( "Item( string )", sheetName.c_str() );
    vector<GAMSDomain> sets {set1, set2};
    GAMSParameter param = db.addParameter(paramName, paramText, sets);

    QAxObject* usedrange = sheet->querySubObject( "UsedRange");
    QAxObject * columns = usedrange->querySubObject("Columns");
    int intCols = columns->property("Count").toInt();
    QAxObject * rows = usedrange->querySubObject("Rows");
    int intRows = rows->property("Count").toInt();

    for (int j = 2; j <= intCols; j++) {
        string namej = sheet->querySubObject("Cells( int, int )", 1, j)->dynamicCall("Value()").toString().toStdString();
        for (int i = 2; i <= intRows; ++i) {
            string namei = sheet->querySubObject("Cells( int, int )", i, 1)->dynamicCall("Value()").toString().toStdString();
            GAMSParameterRecord rec = param.addRecord(namei, namej);
            double value = sheet->querySubObject("Cells( int, int )", i, j)->dynamicCall("Value()").toDouble();
            rec.setValue(value);
        }
    }
    return param;
}

/// \file transport10.cpp
/// \brief This is the 10th model in a series of tutorial examples.
///
/// Here we show:
///   - How to fill a GAMSDatabase by reading from MS Excel
int main(int argc, char* argv[])
{
    cout << "---------- Transport 10 --------------" << endl;
    try {
        ::CoInitialize(0); // initialize thread to use ActiveX (some systems may need CoInititializeEx)

        GAMSWorkspaceInfo wsInfo;
        if (argc > 1)
            wsInfo.setSystemDirectory(argv[1]);
        GAMSWorkspace ws(wsInfo);

        // Creating the GAMSDatabase and fill with the workbook data
        GAMSDatabase db = ws.addDatabase();
        QString fileName = QString::fromStdString(ws.systemDirectory())+ cPathSep + "apifiles" + cPathSep + "Data" + cPathSep + "transport.xlsx";

        QAxObject* excel = new QAxObject( "Excel.Application", 0 );
        QAxObject* workbooks = excel->querySubObject( "Workbooks" );
        QAxObject* workbook = workbooks->querySubObject( "Open(const QString&)", fileName );
        QAxObject* sheets = workbook->querySubObject( "Worksheets" );

        GAMSSet i = db.addSet("i", 1, "Plants");
        GAMSSet j = db.addSet("j", 1, "Markets");

        // read parameters
        sheetToParameter(sheets, "capacity", db, "a", "Capacity", i);
        sheetToParameter(sheets, "demand", db, "b", "Demand", j);
        sheetToParameter(sheets, "distance", db, "d", "Distance", i, j);

        // clean up and close up
        workbook->dynamicCall("Close()");
        excel->dynamicCall("Quit()");

        // Create and run the GAMSJob
        GAMSOptions opt = ws.addOptions();
        GAMSJob t10 = ws.addJobFromString(getModelText());
        opt.setDefine("gdxincname", db.name());
        opt.setAllModelTypes("xpress");
        t10.run(opt, db);
        for (GAMSVariableRecord record : t10.outDB().getVariable("x"))
            cout << "x(" << record.key(0) << "," << record.key(1) << "): level=" << record.level() <<
                    " marginal=" << record.marginal() << endl;

        ::CoUninitialize();

    } catch (GAMSException &ex) {
        cout << "GAMSException occured: " << ex.what() << endl;
    } catch (exception &ex) {
        cout << ex.what() << endl;
    }

    return 0;
}
#endif
<|endoftext|>


<commit_before>/*******************************************************************************
 * examples/wordcount/word_count_user_program.cpp
 *
 * Part of Project c7a.
 *
 *
 * This file has no license. Only Chuck Norris can compile it.
 ******************************************************************************/

#include <c7a/api/dia.hpp>
#include <c7a/api/reduce_node.hpp>
#include <c7a/common/string.hpp>

template <typename InStack>
auto word_count_user(c7a::DIARef<std::string, InStack> & input) {

    using WordPair = std::pair<std::string, int>;

    auto line_to_wordpairs =
        [](std::string line, auto emit) {
        for (const std::string& word : c7a::common::split(line, ' ')) {
            if (word.size() != 0)
                emit(WordPair(word, 1));
        }
    };

    auto key = [](WordPair in) {
                   return in.first;
               };

    auto red_fn =
        [](WordPair in1, WordPair in2) {
        return WordPair(in1.first, in1.second + in2.second);
    };

    auto word_pairs = input.FlatMap(line_to_wordpairs);

    return word_pairs.ReduceBy(key, red_fn);
}

//! The WordCount user program
int word_count(c7a::Context& ctx) {
    using c7a::Context;
    using WordPair = std::pair<std::string, int>;

    std::cout << "wordcount.in" << std::endl;
    auto lines = ReadLines(
        ctx,
        "wordcount.in",
        [](const std::string& line) {
            return line;
        });

    auto red_words = word_count_user(lines);

    red_words.WriteToFileSystem(
        "wordcount_" + std::to_string(ctx.rank()) + ".out",
        [](const WordPair& item) {
            return item.first + ": " + std::to_string(item.second);
        });

    return 0;
}

int word_count_generated(c7a::Context& ctx, size_t size) {
    using c7a::Context;
    using WordPair = std::pair<std::string, int>;

    auto lines = GenerateFromFile(
        ctx,
        "headwords",
        [](const std::string& line) {
            return line;
        },
        size);

    auto reduced_words = word_count_user(lines);

    reduced_words.WriteToFileSystem(
        "wordcount_" + std::to_string(ctx.rank()) + ".out",
        [](const WordPair& item) {
            return item.first + ": " + std::to_string(item.second);
        });
    return 0;
}

/******************************************************************************/
<commit_msg>Compactifying word count program<commit_after>/*******************************************************************************
 * examples/wordcount/word_count_user_program.cpp
 *
 * Part of Project c7a.
 *
 *
 * This file has no license. Only Chuck Norris can compile it.
 ******************************************************************************/

#include <c7a/api/dia.hpp>
#include <c7a/api/reduce_node.hpp>
#include <c7a/common/string.hpp>

template <typename InStack>
auto word_count_user(c7a::DIARef<std::string, InStack> & input) {

    using WordCount = std::pair<std::string, int>;

    auto word_pairs = input.FlatMap(
        [](std::string line, auto emit) {
            /* map lambda */
            for (const std::string& word : c7a::common::split(line, ' ')) {
                if (word.size() != 0)
                    emit(WordCount(word, 1));
            }
        });

    return word_pairs.ReduceBy(
        [](const WordCount& in) {
            /* reduction key: the word string */
            return in.first;
        },
        [](WordCount a, WordCount b) {
            /* associative reduction operator: add counters */
            return WordCount(a.first, a.second + b.second);
        });
}

//! The WordCount user program
int word_count(c7a::Context& ctx) {
    using c7a::Context;
    using WordCount = std::pair<std::string, int>;

    std::cout << "wordcount.in" << std::endl;
    auto lines = ReadLines(
        ctx,
        "wordcount.in",
        [](const std::string& line) {
            return line;
        });

    auto red_words = word_count_user(lines);

    red_words.WriteToFileSystem(
        "wordcount_" + std::to_string(ctx.rank()) + ".out",
        [](const WordCount& item) {
            return item.first + ": " + std::to_string(item.second);
        });

    return 0;
}

int word_count_generated(c7a::Context& ctx, size_t size) {
    using c7a::Context;
    using WordCount = std::pair<std::string, int>;

    auto lines = GenerateFromFile(
        ctx,
        "headwords",
        [](const std::string& line) {
            return line;
        },
        size);

    auto reduced_words = word_count_user(lines);

    reduced_words.WriteToFileSystem(
        "wordcount_" + std::to_string(ctx.rank()) + ".out",
        [](const WordCount& item) {
            return item.first + ": " + std::to_string(item.second);
        });
    return 0;
}

/******************************************************************************/
<|endoftext|>


<commit_before><commit_msg>lost instances temporary fix<commit_after><|endoftext|>


<commit_before>#include "Loggers.h"
#include "boost/log/utility/setup/console.hpp"
#include "boost/log/utility/setup/file.hpp"
#include "boost/log/sources/severity_channel_logger.hpp"
#include <boost/log/sources/severity_feature.hpp>
#include <boost/log/trivial.hpp>
#include <boost/log/expressions.hpp>
#include <boost/log/attributes.hpp>

void ILogger::TraceFormat(const char* format, ...)
{
	char buffer[64 * 1024];
	va_list arglist;
	va_start(arglist, format);
	vsprintf(buffer, format, arglist);
	va_end(arglist);
	this->Trace(buffer);
}

void ILogger::DebugFormat(const char* format, ...)
{
	char buffer[64 * 1024];
	va_list arglist;
	va_start(arglist, format);
	vsprintf(buffer, format, arglist);
	va_end(arglist);
	this->Debug(buffer);
}
void ILogger::InfoFormat(const char* format, ...)
{
	char buffer[64 * 1024];
	va_list arglist;
	va_start(arglist, format);
	vsprintf(buffer, format, arglist);
	va_end(arglist);
	this->Info(buffer);
}

void ILogger::WarningFormat(const char* format, ...)
{
	char buffer[64 * 1024];
	va_list arglist;
	va_start(arglist, format);
	vsprintf(buffer, format, arglist);
	va_end(arglist);
	this->Warning(buffer);
}

void ILogger::ErrorFormat(const char* format, ...)
{
	char buffer[64 * 1024];
	va_list arglist;
	va_start(arglist, format);
	vsprintf(buffer, format, arglist);
	va_end(arglist);
	this->Error(buffer);
}

void ILogger::FatalFormat(const char* format, ...)
{
	char buffer[64 * 1024];
	va_list arglist;
	va_start(arglist, format);
	vsprintf(buffer, format, arglist);
	va_end(arglist);
	this->Fatal(buffer);
}

class Logger : public ILogger
{
public:
	Logger(const char* component)
		: m_Logger(boost::log::keywords::channel = (component))
	{
	}

	virtual void Trace(const char * str) override
	{
		BOOST_LOG_SEV(m_Logger, boost::log::trivial::trace) << str;
	}

	virtual void Debug(const char * str) override
	{
		BOOST_LOG_SEV(m_Logger, boost::log::trivial::debug) << str;
	}

	virtual void Info(const char * str) override
	{
		BOOST_LOG_SEV(m_Logger, boost::log::trivial::info) << str;
	}

	virtual void Warning(const char * str) override
	{
		BOOST_LOG_SEV(m_Logger, boost::log::trivial::warning) << str;
	}

	virtual void Error(const char * str) override
	{
		BOOST_LOG_SEV(m_Logger, boost::log::trivial::error) << str;
	}

	virtual void Fatal(const char * str) override
	{
		BOOST_LOG_SEV(m_Logger, boost::log::trivial::fatal) << str;
	}
protected:
	boost::log::sources::severity_channel_logger_mt<boost::log::trivial::severity_level> m_Logger;
};

void LoggerFactory::InitLogger(boost::program_options::variables_map& vm)
{
	std::string logFormat = "[%TimeStamp%]: [%Severity%] [%Message%]";

	boost::log::core::get()->set_logging_enabled(false);
	boost::log::core::get()->add_global_attribute("TimeStamp", boost::log::attributes::local_clock());

	if (!vm["Logging.Console"].empty())
	{
		auto value = vm["Logging.Console"].as<std::string>();
		if (vm["Logging.Console"].as<std::string>() == "true")
		{
			boost::log::add_console_log(std::cout, boost::log::keywords::format = logFormat);
			boost::log::core::get()->set_logging_enabled(true);
		}
	}
	if (!vm["Logging.FileOutput"].empty())
	{
		auto fileName = vm["Logging.FileOutput"].as<std::string>();
		if (fileName != "")
		{
			boost::log::add_file_log(fileName, boost::log::keywords::format = logFormat);
			boost::log::core::get()->set_logging_enabled(true);
		}
	}
}

std::shared_ptr<ILogger> LoggerFactory::getLogger(const char* component)
{
	return std::make_shared<Logger>(component);
}
<commit_msg>Poco Logger -> not yet complete<commit_after>#include "Loggers.h"
#include "stdarg.h"

#include "Poco/ConsoleChannel.h"
#include "Poco/SplitterChannel.h"
#include "Poco/FormattingChannel.h"
#include "Poco/PatternFormatter.h"
#include "Poco/FileChannel.h"
#include "Poco/AutoPtr.h"
#include "Poco/Logger.h"

const int bufferSize = 64 * 1024;

void ILogger::TraceFormat(const char* format, ...)
{
	char buffer[bufferSize];
	va_list arglist;
	va_start(arglist, format);
	vsprintf(buffer, format, arglist);
	va_end(arglist);
	this->Trace(buffer);
}

void ILogger::DebugFormat(const char* format, ...)
{
	char buffer[bufferSize];
	va_list arglist;
	va_start(arglist, format);
	vsprintf(buffer, format, arglist);
	va_end(arglist);
	this->Debug(buffer);
}
void ILogger::InfoFormat(const char* format, ...)
{
	char buffer[bufferSize];
	va_list arglist;
	va_start(arglist, format);
	vsprintf(buffer, format, arglist);
	va_end(arglist);
	this->Info(buffer);
}

void ILogger::WarningFormat(const char* format, ...)
{
	char buffer[bufferSize];
	va_list arglist;
	va_start(arglist, format);
	vsprintf(buffer, format, arglist);
	va_end(arglist);
	this->Warning(buffer);
}

void ILogger::ErrorFormat(const char* format, ...)
{
	char buffer[bufferSize];
	va_list arglist;
	va_start(arglist, format);
	vsprintf(buffer, format, arglist);
	va_end(arglist);
	this->Error(buffer);
}

void ILogger::FatalFormat(const char* format, ...)
{
	char buffer[bufferSize];
	va_list arglist;
	va_start(arglist, format);
	vsprintf(buffer, format, arglist);
	va_end(arglist);
	this->Fatal(buffer);
}

class Logger : public ILogger
{
public:
	Logger(const char* component) :
		m_Logger(Poco::Logger::get(component))
	{
	}

	virtual void Trace(const char * str) override
	{
		m_Logger.trace(str);
	}

	virtual void Debug(const char * str) override
	{
		m_Logger.debug(str);
	}

	virtual void Info(const char * str) override
	{
		m_Logger.information(str);
	}

	virtual void Warning(const char * str) override
	{
		m_Logger.warning(str);
	}

	virtual void Error(const char * str) override
	{
		m_Logger.error(str);
	}

	virtual void Fatal(const char * str) override
	{
		m_Logger.fatal(str);

	}
protected:
	Poco::Logger& m_Logger;
};

void LoggerFactory::InitLogger(boost::program_options::variables_map& vm)
{
	Poco::AutoPtr<Poco::SplitterChannel> sChannel(new Poco::SplitterChannel());
	Poco::Logger::root().setChannel(sChannel);
	Poco::AutoPtr<Poco::PatternFormatter> pPF(new Poco::PatternFormatter());
	pPF->setProperty("pattern", "%Y-%m-%d %H:%M:%S [%P:%I] [%s]:[%p]: %t");
	Poco::AutoPtr<Poco::FormattingChannel> pFC(new Poco::FormattingChannel(pPF, sChannel));

	std::string logFormat = "[%TimeStamp%]: [%Severity%] [%Message%]";

	if (!vm["Logging.Console"].empty())
	{
		auto value = vm["Logging.Console"].as<std::string>();
		if (vm["Logging.Console"].as<std::string>() == "true")
		{
			Poco::AutoPtr<Poco::ConsoleChannel> cChannel;
			sChannel->addChannel(cChannel);
		}
	}

	if (!vm["Logging.FileOutput"].empty())
	{
		auto fileName = vm["Logging.FileOutput"].as<std::string>();
		if (fileName != "")
		{
			Poco::AutoPtr<Poco::FileChannel> pChannel(new Poco::FileChannel);
			pChannel->setProperty("path", fileName);
			sChannel->addChannel(pChannel);
		}
	}
}

std::shared_ptr<ILogger> LoggerFactory::getLogger(const char* component)
{
	return std::make_shared<Logger>(component);
}
<|endoftext|>


<commit_before>// Copyright (c) 2014 Intel Corporation. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "xwalk/runtime/browser/ui/native_app_window_aura.h"

#include "content/public/browser/web_contents.h"
#include "content/browser/web_contents/web_contents_view.h"
#include "ui/aura/client/aura_constants.h"
#include "ui/wm/core/default_activation_client.h"
#include "ui/aura/client/default_capture_client.h"
#include "ui/aura/env.h"
#include "ui/aura/layout_manager.h"
#include "ui/aura/test/test_focus_client.h"
#include "ui/aura/test/test_screen.h"
#include "ui/aura/test/test_window_tree_client.h"
#include "ui/aura/window.h"
#include "ui/aura/window_event_dispatcher.h"
#include "ui/base/cursor/cursor.h"
#include "ui/base/cursor/image_cursors.h"
#include "ui/base/ime/input_method.h"
#include "ui/base/ime/input_method_delegate.h"
#include "ui/base/ime/input_method_factory.h"
#include "ui/gfx/screen.h"
#include "ui/wm/core/cursor_manager.h"
#include "ui/wm/core/native_cursor_manager.h"
#include "ui/wm/core/native_cursor_manager_delegate.h"

namespace xwalk {

const int kDefaultTestWindowWidthDip = 800;
const int kDefaultTestWindowHeightDip = 600;

namespace {

class FillLayout : public aura::LayoutManager {
 public:
  explicit FillLayout(aura::Window* root)
      : root_(root) {
  }

  virtual ~FillLayout() {}

 private:
  // aura::LayoutManager:
  virtual void OnWindowResized() override {
  }

  virtual void OnWindowAddedToLayout(aura::Window* child) override {
    child->SetBounds(root_->bounds());
  }

  virtual void OnWillRemoveWindowFromLayout(aura::Window* child) override {
  }

  virtual void OnWindowRemovedFromLayout(aura::Window* child) override {
  }

  virtual void OnChildWindowVisibilityChanged(aura::Window* child,
                                              bool visible) override {
  }

  virtual void SetChildBounds(aura::Window* child,
                              const gfx::Rect& requested_bounds) override {
    SetChildBoundsDirect(child, requested_bounds);
  }

  aura::Window* root_;

  DISALLOW_COPY_AND_ASSIGN(FillLayout);
};

// Taken from app_shell.
// A class that bridges the gap between CursorManager and Aura. It borrows
// heavily from AshNativeCursorManager.
class ShellNativeCursorManager : public wm::NativeCursorManager {
 public:
  explicit ShellNativeCursorManager(aura::WindowTreeHost* host)
      : host_(host),
        image_cursors_(new ui::ImageCursors) {}
  virtual ~ShellNativeCursorManager() {}

  // wm::NativeCursorManager overrides.
  virtual void SetDisplay(
      const gfx::Display& display,
      wm::NativeCursorManagerDelegate* delegate) override {
    if (image_cursors_->SetDisplay(display, display.device_scale_factor()))
      SetCursor(delegate->GetCursor(), delegate);
  }

  virtual void SetCursor(
      gfx::NativeCursor cursor,
      wm::NativeCursorManagerDelegate* delegate) override {
    image_cursors_->SetPlatformCursor(&cursor);
    cursor.set_device_scale_factor(image_cursors_->GetScale());
    delegate->CommitCursor(cursor);

    if (delegate->IsCursorVisible())
      ApplyCursor(cursor);
  }

  virtual void SetVisibility(
      bool visible,
      wm::NativeCursorManagerDelegate* delegate) override {
    delegate->CommitVisibility(visible);

    if (visible) {
      SetCursor(delegate->GetCursor(), delegate);
    } else {
      gfx::NativeCursor invisible_cursor(ui::kCursorNone);
      image_cursors_->SetPlatformCursor(&invisible_cursor);
      ApplyCursor(invisible_cursor);
    }
  }

  virtual void SetCursorSet(
      ui::CursorSetType cursor_set,
      wm::NativeCursorManagerDelegate* delegate) override {
    image_cursors_->SetCursorSet(cursor_set);
    delegate->CommitCursorSet(cursor_set);
    if (delegate->IsCursorVisible())
      SetCursor(delegate->GetCursor(), delegate);
  }

  virtual void SetMouseEventsEnabled(
      bool enabled,
      wm::NativeCursorManagerDelegate* delegate) override {
    delegate->CommitMouseEventsEnabled(enabled);
    SetVisibility(delegate->IsCursorVisible(), delegate);
  }

 private:
  // Sets |cursor| as the active cursor within Aura.
  void ApplyCursor(gfx::NativeCursor cursor) {
    host_->SetCursor(cursor);
  }

  aura::WindowTreeHost* host_;  // Not owned.

  scoped_ptr<ui::ImageCursors> image_cursors_;

  DISALLOW_COPY_AND_ASSIGN(ShellNativeCursorManager);
};

class MinimalInputEventFilter : public ui::internal::InputMethodDelegate,
                                public ui::EventHandler {
 public:
  explicit MinimalInputEventFilter(aura::WindowTreeHost* host)
      : host_(host),
        input_method_(ui::CreateInputMethod(this,
                                            gfx::kNullAcceleratedWidget)) {
    input_method_->Init(true);
    host_->window()->AddPreTargetHandler(this);
    host_->window()->SetProperty(aura::client::kRootWindowInputMethodKey,
                                 input_method_.get());
  }

  virtual ~MinimalInputEventFilter() {
    host_->window()->RemovePreTargetHandler(this);
    host_->window()->SetProperty(aura::client::kRootWindowInputMethodKey,
                                 static_cast<ui::InputMethod*>(NULL));
  }

 private:
  // ui::EventHandler:
  virtual void OnKeyEvent(ui::KeyEvent* event) override {
    // See the comment in InputMethodEventFilter::OnKeyEvent() for details.
    if (event->IsTranslated()) {
      event->SetTranslated(false);
    } else if (input_method_->DispatchKeyEvent(*event)) {
      event->StopPropagation();
    }
  }

  // ui::internal::InputMethodDelegate:
  virtual bool DispatchKeyEventPostIME(const ui::KeyEvent& event) override {
    // See the comment in InputMethodEventFilter::DispatchKeyEventPostIME() for
    // details.
    ui::KeyEvent aura_event(event);
    aura_event.SetTranslated(true);
    ui::EventDispatchDetails details =
        host_->dispatcher()->OnEventFromSource(&aura_event);
    return aura_event.handled() || details.dispatcher_destroyed;
  }

  aura::WindowTreeHost* host_;
  scoped_ptr<ui::InputMethod> input_method_;

  DISALLOW_COPY_AND_ASSIGN(MinimalInputEventFilter);
};

}  // namespace

// mimicking Shell::ShellPlatformDataAura
NativeAppWindowAura::NativeAppWindowAura(
    const NativeAppWindow::CreateParams& create_params)
    : web_contents_(create_params.web_contents) {
  aura::Env::CreateInstance(true);
  const gfx::Size bounds =
      gfx::Size(kDefaultTestWindowWidthDip, kDefaultTestWindowHeightDip);
  host_.reset(aura::WindowTreeHost::Create(gfx::Rect(bounds)));
  host_->InitHost();
  host_->window()->SetLayoutManager(new FillLayout(host_->window()));

  focus_client_.reset(new aura::test::TestFocusClient());
  aura::client::SetFocusClient(host_->window(), focus_client_.get());

  new wm::DefaultActivationClient(host_->window());
  capture_client_.reset(
      new aura::client::DefaultCaptureClient(host_->window()));
  window_tree_client_.reset(
      new aura::test::TestWindowTreeClient(host_->window()));
  ime_filter_.reset(new MinimalInputEventFilter(host_.get()));

  cursor_manager_.reset(
      new wm::CursorManager(scoped_ptr<wm::NativeCursorManager>(
          new ShellNativeCursorManager(host_.get()))));
  cursor_manager_->SetDisplay(
      gfx::Screen::GetNativeScreen()->GetPrimaryDisplay());
  cursor_manager_->SetCursor(ui::kCursorPointer);
  aura::client::SetCursorClient(host_->window(), cursor_manager_.get());

  // mimicking Shell::PlatformSetContents
  aura::Window* content = web_contents_->GetNativeView();
  aura::Window* parent = host_->window();
  if (!parent->Contains(content))
    parent->AddChild(content);

  content->Show();
  parent->Show();

  web_contents_->Focus();
}

NativeAppWindowAura::~NativeAppWindowAura() {
  aura::Env::DeleteInstance();
}

gfx::NativeWindow NativeAppWindowAura::GetNativeWindow() const {
  return NULL;
}

void NativeAppWindowAura::UpdateIcon(const gfx::Image& icon) {
}

void NativeAppWindowAura::UpdateTitle(const base::string16& title) {
}

gfx::Rect NativeAppWindowAura::GetRestoredBounds() const {
  return gfx::Rect();
}

gfx::Rect NativeAppWindowAura::GetBounds() const {
  return host_->GetBounds();
}

void NativeAppWindowAura::SetBounds(const gfx::Rect& bounds) {
  host_->SetBounds(bounds);
}

void NativeAppWindowAura::Focus() {
}

void NativeAppWindowAura::Show() {
  host_->Show();
}

void NativeAppWindowAura::Hide() {
  host_->Hide();
}

void NativeAppWindowAura::Maximize() {
}

void NativeAppWindowAura::Minimize() {
}

void NativeAppWindowAura::SetFullscreen(bool fullscreen) {
}

void NativeAppWindowAura::Restore() {
}

void NativeAppWindowAura::FlashFrame(bool flash) {
}

void NativeAppWindowAura::Close() {
}

bool NativeAppWindowAura::IsActive() const {
  return true;
}

bool NativeAppWindowAura::IsMaximized() const {
  return true;
}

bool NativeAppWindowAura::IsMinimized() const {
  return false;
}

bool NativeAppWindowAura::IsFullscreen() const {
  return true;
}

// static
NativeAppWindow* NativeAppWindow::Create(
    const NativeAppWindow::CreateParams& create_params) {
  return new NativeAppWindowAura(create_params);
}

// static
void NativeAppWindow::Initialize() {
  // At least Athena, Content Shell and Chromecast use the "TestScreen" class
  // not exactly for testing but production instead. So I think we are fine on
  // using it as long they are using it as well.
  aura::TestScreen* screen = aura::TestScreen::Create(gfx::Size());
  gfx::Screen::SetScreenInstance(gfx::SCREEN_TYPE_NATIVE, screen);
}

}  // namespace xwalk
<commit_msg>runtime: Add cmd line option for changing native host window bounds<commit_after>// Copyright (c) 2014 Intel Corporation. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "xwalk/runtime/browser/ui/native_app_window_aura.h"

#include "base/command_line.h"
#include "content/public/browser/web_contents.h"
#include "content/browser/web_contents/web_contents_view.h"
#include "ui/aura/client/aura_constants.h"
#include "ui/wm/core/default_activation_client.h"
#include "ui/aura/client/default_capture_client.h"
#include "ui/aura/env.h"
#include "ui/aura/layout_manager.h"
#include "ui/aura/test/test_focus_client.h"
#include "ui/aura/test/test_screen.h"
#include "ui/aura/test/test_window_tree_client.h"
#include "ui/aura/window.h"
#include "ui/aura/window_event_dispatcher.h"
#include "ui/base/cursor/cursor.h"
#include "ui/base/cursor/image_cursors.h"
#include "ui/base/ime/input_method.h"
#include "ui/base/ime/input_method_delegate.h"
#include "ui/base/ime/input_method_factory.h"
#include "ui/gfx/screen.h"
#include "ui/wm/core/cursor_manager.h"
#include "ui/wm/core/native_cursor_manager.h"
#include "ui/wm/core/native_cursor_manager_delegate.h"

namespace xwalk {

const int kDefaultTestWindowWidthDip = 800;
const int kDefaultTestWindowHeightDip = 600;

const char kXwalkHostWindowBounds[] = "xwalk-host-window-bounds";

namespace {

class FillLayout : public aura::LayoutManager {
 public:
  explicit FillLayout(aura::Window* root)
      : root_(root) {
  }

  virtual ~FillLayout() {}

 private:
  // aura::LayoutManager:
  virtual void OnWindowResized() override {
  }

  virtual void OnWindowAddedToLayout(aura::Window* child) override {
    child->SetBounds(root_->bounds());
  }

  virtual void OnWillRemoveWindowFromLayout(aura::Window* child) override {
  }

  virtual void OnWindowRemovedFromLayout(aura::Window* child) override {
  }

  virtual void OnChildWindowVisibilityChanged(aura::Window* child,
                                              bool visible) override {
  }

  virtual void SetChildBounds(aura::Window* child,
                              const gfx::Rect& requested_bounds) override {
    SetChildBoundsDirect(child, requested_bounds);
  }

  aura::Window* root_;

  DISALLOW_COPY_AND_ASSIGN(FillLayout);
};

// Taken from app_shell.
// A class that bridges the gap between CursorManager and Aura. It borrows
// heavily from AshNativeCursorManager.
class ShellNativeCursorManager : public wm::NativeCursorManager {
 public:
  explicit ShellNativeCursorManager(aura::WindowTreeHost* host)
      : host_(host),
        image_cursors_(new ui::ImageCursors) {}
  virtual ~ShellNativeCursorManager() {}

  // wm::NativeCursorManager overrides.
  virtual void SetDisplay(
      const gfx::Display& display,
      wm::NativeCursorManagerDelegate* delegate) override {
    if (image_cursors_->SetDisplay(display, display.device_scale_factor()))
      SetCursor(delegate->GetCursor(), delegate);
  }

  virtual void SetCursor(
      gfx::NativeCursor cursor,
      wm::NativeCursorManagerDelegate* delegate) override {
    image_cursors_->SetPlatformCursor(&cursor);
    cursor.set_device_scale_factor(image_cursors_->GetScale());
    delegate->CommitCursor(cursor);

    if (delegate->IsCursorVisible())
      ApplyCursor(cursor);
  }

  virtual void SetVisibility(
      bool visible,
      wm::NativeCursorManagerDelegate* delegate) override {
    delegate->CommitVisibility(visible);

    if (visible) {
      SetCursor(delegate->GetCursor(), delegate);
    } else {
      gfx::NativeCursor invisible_cursor(ui::kCursorNone);
      image_cursors_->SetPlatformCursor(&invisible_cursor);
      ApplyCursor(invisible_cursor);
    }
  }

  virtual void SetCursorSet(
      ui::CursorSetType cursor_set,
      wm::NativeCursorManagerDelegate* delegate) override {
    image_cursors_->SetCursorSet(cursor_set);
    delegate->CommitCursorSet(cursor_set);
    if (delegate->IsCursorVisible())
      SetCursor(delegate->GetCursor(), delegate);
  }

  virtual void SetMouseEventsEnabled(
      bool enabled,
      wm::NativeCursorManagerDelegate* delegate) override {
    delegate->CommitMouseEventsEnabled(enabled);
    SetVisibility(delegate->IsCursorVisible(), delegate);
  }

 private:
  // Sets |cursor| as the active cursor within Aura.
  void ApplyCursor(gfx::NativeCursor cursor) {
    host_->SetCursor(cursor);
  }

  aura::WindowTreeHost* host_;  // Not owned.

  scoped_ptr<ui::ImageCursors> image_cursors_;

  DISALLOW_COPY_AND_ASSIGN(ShellNativeCursorManager);
};

class MinimalInputEventFilter : public ui::internal::InputMethodDelegate,
                                public ui::EventHandler {
 public:
  explicit MinimalInputEventFilter(aura::WindowTreeHost* host)
      : host_(host),
        input_method_(ui::CreateInputMethod(this,
                                            gfx::kNullAcceleratedWidget)) {
    input_method_->Init(true);
    host_->window()->AddPreTargetHandler(this);
    host_->window()->SetProperty(aura::client::kRootWindowInputMethodKey,
                                 input_method_.get());
  }

  virtual ~MinimalInputEventFilter() {
    host_->window()->RemovePreTargetHandler(this);
    host_->window()->SetProperty(aura::client::kRootWindowInputMethodKey,
                                 static_cast<ui::InputMethod*>(NULL));
  }

 private:
  // ui::EventHandler:
  virtual void OnKeyEvent(ui::KeyEvent* event) override {
    // See the comment in InputMethodEventFilter::OnKeyEvent() for details.
    if (event->IsTranslated()) {
      event->SetTranslated(false);
    } else if (input_method_->DispatchKeyEvent(*event)) {
      event->StopPropagation();
    }
  }

  // ui::internal::InputMethodDelegate:
  virtual bool DispatchKeyEventPostIME(const ui::KeyEvent& event) override {
    // See the comment in InputMethodEventFilter::DispatchKeyEventPostIME() for
    // details.
    ui::KeyEvent aura_event(event);
    aura_event.SetTranslated(true);
    ui::EventDispatchDetails details =
        host_->dispatcher()->OnEventFromSource(&aura_event);
    return aura_event.handled() || details.dispatcher_destroyed;
  }

  aura::WindowTreeHost* host_;
  scoped_ptr<ui::InputMethod> input_method_;

  DISALLOW_COPY_AND_ASSIGN(MinimalInputEventFilter);
};

}  // namespace

// mimicking Shell::ShellPlatformDataAura
NativeAppWindowAura::NativeAppWindowAura(
    const NativeAppWindow::CreateParams& create_params)
    : web_contents_(create_params.web_contents) {
  aura::Env::CreateInstance(true);
  gfx::Size size;

  base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
  if (command_line->HasSwitch(kXwalkHostWindowBounds)) {
    const std::string size_str =
        command_line->GetSwitchValueASCII(kXwalkHostWindowBounds);
    int width, height;
    if (sscanf(size_str.c_str(), "%d,%d", &width, &height) == 2)
      size = gfx::Size(width, height);
  }

  if (size.IsEmpty())
    size = gfx::Size(kDefaultTestWindowWidthDip, kDefaultTestWindowHeightDip);

  host_.reset(aura::WindowTreeHost::Create(gfx::Rect(size)));
  host_->InitHost();
  host_->window()->SetLayoutManager(new FillLayout(host_->window()));

  focus_client_.reset(new aura::test::TestFocusClient());
  aura::client::SetFocusClient(host_->window(), focus_client_.get());

  new wm::DefaultActivationClient(host_->window());
  capture_client_.reset(
      new aura::client::DefaultCaptureClient(host_->window()));
  window_tree_client_.reset(
      new aura::test::TestWindowTreeClient(host_->window()));
  ime_filter_.reset(new MinimalInputEventFilter(host_.get()));

  cursor_manager_.reset(
      new wm::CursorManager(scoped_ptr<wm::NativeCursorManager>(
          new ShellNativeCursorManager(host_.get()))));
  cursor_manager_->SetDisplay(
      gfx::Screen::GetNativeScreen()->GetPrimaryDisplay());
  cursor_manager_->SetCursor(ui::kCursorPointer);
  aura::client::SetCursorClient(host_->window(), cursor_manager_.get());

  // mimicking Shell::PlatformSetContents
  aura::Window* content = web_contents_->GetNativeView();
  aura::Window* parent = host_->window();
  if (!parent->Contains(content))
    parent->AddChild(content);

  content->Show();
  parent->Show();

  web_contents_->Focus();
}

NativeAppWindowAura::~NativeAppWindowAura() {
  aura::Env::DeleteInstance();
}

gfx::NativeWindow NativeAppWindowAura::GetNativeWindow() const {
  return NULL;
}

void NativeAppWindowAura::UpdateIcon(const gfx::Image& icon) {
}

void NativeAppWindowAura::UpdateTitle(const base::string16& title) {
}

gfx::Rect NativeAppWindowAura::GetRestoredBounds() const {
  return gfx::Rect();
}

gfx::Rect NativeAppWindowAura::GetBounds() const {
  return host_->GetBounds();
}

void NativeAppWindowAura::SetBounds(const gfx::Rect& bounds) {
  host_->SetBounds(bounds);
}

void NativeAppWindowAura::Focus() {
}

void NativeAppWindowAura::Show() {
  host_->Show();
}

void NativeAppWindowAura::Hide() {
  host_->Hide();
}

void NativeAppWindowAura::Maximize() {
}

void NativeAppWindowAura::Minimize() {
}

void NativeAppWindowAura::SetFullscreen(bool fullscreen) {
}

void NativeAppWindowAura::Restore() {
}

void NativeAppWindowAura::FlashFrame(bool flash) {
}

void NativeAppWindowAura::Close() {
}

bool NativeAppWindowAura::IsActive() const {
  return true;
}

bool NativeAppWindowAura::IsMaximized() const {
  return true;
}

bool NativeAppWindowAura::IsMinimized() const {
  return false;
}

bool NativeAppWindowAura::IsFullscreen() const {
  return true;
}

// static
NativeAppWindow* NativeAppWindow::Create(
    const NativeAppWindow::CreateParams& create_params) {
  return new NativeAppWindowAura(create_params);
}

// static
void NativeAppWindow::Initialize() {
  // At least Athena, Content Shell and Chromecast use the "TestScreen" class
  // not exactly for testing but production instead. So I think we are fine on
  // using it as long they are using it as well.
  aura::TestScreen* screen = aura::TestScreen::Create(gfx::Size());
  gfx::Screen::SetScreenInstance(gfx::SCREEN_TYPE_NATIVE, screen);
}

}  // namespace xwalk
<|endoftext|>