<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: precompiled_tools.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: kz $ $Date: 2007-05-10 16:38:26 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library 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
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

// MARKER(update_precomp.py): Generated on 2006-09-01 17:50:15.029610

#ifdef PRECOMPILED_HEADERS
//---MARKER---
#include "sal/config.h"
#include "sal/types.h"

#include "basegfx/point/b2dpoint.hxx"
#include "basegfx/polygon/b2dpolygon.hxx"
#include "basegfx/polygon/b2dpolygontools.hxx"
#include "basegfx/polygon/b2dpolypolygon.hxx"
#include "basegfx/polygon/b2dpolypolygontools.hxx"
#include "basegfx/vector/b2dvector.hxx"

#include "boost/static_assert.hpp"

#include "com/sun/star/lang/Locale.hpp"
#include "com/sun/star/uno/Reference.hxx"
#include "com/sun/star/uno/Sequence.hxx"
#include "com/sun/star/util/XStringWidth.hpp"

#include "comphelper/fileformat.h"

#include "cppuhelper/implbase1.hxx"

#include "i18npool/lang.h"
#include "i18npool/mslangid.hxx"

#include "osl/diagnose.h"
#include "osl/endian.h"
#include "osl/file.hxx"
#include "osl/interlck.h"
#include "osl/module.h"
#include "osl/module.hxx"
#include "osl/mutex.hxx"
#include "osl/process.h"
#include "osl/security.h"
#include "osl/thread.h"

#include "rtl/alloc.h"
#include "rtl/crc.h"
#include "rtl/digest.h"
#include "rtl/instance.hxx"
#include "rtl/logfile.hxx"
#include "rtl/math.hxx"
#include "rtl/memory.h"
#include "rtl/string.h"
#include "rtl/string.hxx"
#include "rtl/tencinfo.h"
#include "rtl/textcvt.h"
#include "rtl/textenc.h"
#include "rtl/ustrbuf.hxx"
#include "rtl/ustring.h"
#include "rtl/ustring.hxx"

#include "sys/stat.h"
#include "sys/types.h"

#include "vos/macros.hxx"
#include "vos/mutex.hxx"
#include "vos/process.hxx"
#include "vos/signal.hxx"
#include "vos/timer.hxx"
//---MARKER---
#endif
<commit_msg>INTEGRATION: CWS changefileheader (1.3.108); FILE MERGED 2008/03/28 15:41:06 rt 1.3.108.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: precompiled_tools.hxx,v $
 * $Revision: 1.4 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org 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 Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

// MARKER(update_precomp.py): Generated on 2006-09-01 17:50:15.029610

#ifdef PRECOMPILED_HEADERS
//---MARKER---
#include "sal/config.h"
#include "sal/types.h"

#include "basegfx/point/b2dpoint.hxx"
#include "basegfx/polygon/b2dpolygon.hxx"
#include "basegfx/polygon/b2dpolygontools.hxx"
#include "basegfx/polygon/b2dpolypolygon.hxx"
#include "basegfx/polygon/b2dpolypolygontools.hxx"
#include "basegfx/vector/b2dvector.hxx"

#include "boost/static_assert.hpp"

#include "com/sun/star/lang/Locale.hpp"
#include "com/sun/star/uno/Reference.hxx"
#include "com/sun/star/uno/Sequence.hxx"
#include "com/sun/star/util/XStringWidth.hpp"

#include "comphelper/fileformat.h"

#include "cppuhelper/implbase1.hxx"

#include "i18npool/lang.h"
#include "i18npool/mslangid.hxx"

#include "osl/diagnose.h"
#include "osl/endian.h"
#include "osl/file.hxx"
#include "osl/interlck.h"
#include "osl/module.h"
#include "osl/module.hxx"
#include "osl/mutex.hxx"
#include "osl/process.h"
#include "osl/security.h"
#include "osl/thread.h"

#include "rtl/alloc.h"
#include "rtl/crc.h"
#include "rtl/digest.h"
#include "rtl/instance.hxx"
#include "rtl/logfile.hxx"
#include "rtl/math.hxx"
#include "rtl/memory.h"
#include "rtl/string.h"
#include "rtl/string.hxx"
#include "rtl/tencinfo.h"
#include "rtl/textcvt.h"
#include "rtl/textenc.h"
#include "rtl/ustrbuf.hxx"
#include "rtl/ustring.h"
#include "rtl/ustring.hxx"

#include "sys/stat.h"
#include "sys/types.h"

#include "vos/macros.hxx"
#include "vos/mutex.hxx"
#include "vos/process.hxx"
#include "vos/signal.hxx"
#include "vos/timer.hxx"
//---MARKER---
#endif
<|endoftext|>


<commit_before>#include <stdio.h>
#include <iostream>
#include <vector>
#include <boost/program_options.hpp>

#include <davix.hpp>
#include "davix_test_lib.h"

namespace po = boost::program_options;
using namespace Davix;

#define SSTR(message) static_cast<std::ostringstream&>(std::ostringstream().flush() << message).str()

#define DECLARE_TEST() std::cout << "Performing test: " << __FUNCTION__ << " on " << uri << std::endl

const std::string testString("This is a file generated by davix tests. It is safe to delete.");
const std::string testfile("davix-testfile-");

#define ASSERT(assertion, msg) \
    if((assertion) == false) throw std::runtime_error( SSTR(__FILE__ << ":" << __LINE__ << " (" << __func__ << "): Assertion " << #assertion << " failed.\n" << msg))

void initialization() {
    if(getenv("DEBUG")) {
        davix_set_log_level(DAVIX_LOG_ALL);
    }
}

std::vector<std::string> split(const std::string str, const std::string delim) {
    size_t prev = 0, cur;
    std::vector<std::string> results;
    while((cur = str.find(delim, prev)) != std::string::npos) {
        results.push_back(str.substr(prev, cur-prev));
        prev = cur + delim.size();
    }
    std::string last = str.substr(prev, str.size()-prev);
    if(last.size() != 0)
        results.push_back(last);

    return results;
}

namespace Auth {
enum Type {AWS, PROXY, AZURE, NONE};
Type fromString(const std::string &str) {
    if(str == "aws")
        return Auth::AWS;
    if(str == "proxy")
        return Auth::PROXY;
    if(str == "azure")
        return Auth::AZURE;
    if(str == "none")
        return Auth::NONE;

    throw std::invalid_argument(SSTR(str << " not a valid authentication method"));
};
};

po::variables_map parse_args(int argc, char** argv) {
    po::options_description desc("davix functional tests runner");

    desc.add_options()
        ("help", "produce help message")
        ("auth", po::value<std::string>()->default_value("none"), "authentication method to use (proxy, aws, none)")
        ("s3accesskey", po::value<std::string>(), "s3 access key")
        ("s3secretkey", po::value<std::string>(), "s3 secret key")
        ("s3region", po::value<std::string>(), "s3 region")
        ("azurekey", po::value<std::string>(), "azure key")
        ("s3alternate", "s3 alternate")
        ("cert", po::value<std::string>(), "path to the proxy certificate to use")
        ("uri", po::value<std::string>(), "uri to test against")
        ("command", po::value<std::vector<std::string> >()->multitoken(), "test to run")
        ;

    po::variables_map vm;
    po::store(po::parse_command_line(argc, argv, desc), vm);
    po::notify(vm);

    if (vm.count("help")) {
        std::cout << desc << "\n";
        exit(1);
    }
    return vm;
}

std::string opt(const po::variables_map &vm, const std::string key) {
    return vm[key].as<std::string>();
}

void authentication(const po::variables_map &vm, const Auth::Type &auth, RequestParams &params) {
    if(auth == Auth::AWS) {
        params.setProtocol(RequestProtocol::AwsS3);

        ASSERT(vm.count("s3accesskey") != 0, "--s3accesskey is required when using s3");
        ASSERT(vm.count("s3secretkey") != 0, "--s3secretkey is required when using s3");

        params.setAwsAuthorizationKeys(opt(vm, "s3secretkey"), opt(vm, "s3accesskey"));
        if(vm.count("s3region") != 0) params.setAwsRegion(opt(vm, "s3region"));
        if(vm.count("s3alternate") != 0) params.setAwsAlternate(true);
    }
    else if(auth == Auth::PROXY) {
        configure_grid_env("proxy", params);
    }
    else if(auth == Auth::AZURE) {
        ASSERT(vm.count("azurekey") != 0, "--azurekey is required when using Azure");

        params.setProtocol(RequestProtocol::Azure);
        params.setAzureKey(opt(vm, "azurekey"));
    }
    else {
        ASSERT(false, "unknown authentication method");
    }
}

void depopulate(const RequestParams &params, Uri uri, int nfiles) {
    DECLARE_TEST();

    for(int i = 1; i <= nfiles; i++) {
        Context context;
        Uri u(uri);
        u.addPathSegment(SSTR(testfile << i));
        DavFile file(context, params, u);
        file.deletion(&params);
        std::cout << "File " << i << " deleted successfully." << std::endl;
    }
    std::cout << "All OK" << std::endl;
}

std::string string_from_mode(mode_t mode){
    const char* rmask ="xwr";
    std::string str(10,'-');

    str[0] = (S_ISDIR(mode))?'d':'-';
    for(size_t i=0; i < 9; ++i){
        str[9-i] = (( mode & (0x01 << i))?(rmask[i%3]):'-');
    }
    return str;
}

void statdir(const RequestParams &params, Uri uri) {
    DECLARE_TEST();
    Context context;
    DavFile file(context, params, uri);
    StatInfo info;
    file.statInfo(&params, info);
    std::cout << string_from_mode(info.mode) << std::endl;

    ASSERT(S_ISDIR(info.mode), "not a directory");
}

void makeCollection(const RequestParams &params, Uri uri) {
    DECLARE_TEST();

    Context context;
    DavFile file(context, params, uri);
    file.makeCollection(&params);

    // make sure it is empty
    DavFile::Iterator it = file.listCollection(&params);
    ASSERT(it.name() == "" && !it.next(), "Newly created directory not empty!");

    // do a stat, make sure it's a dir
    statdir(params, uri);

    Uri u2 = uri;
    u2.ensureTrailingSlash();
    statdir(params, u2);

    std::cout << "Done!" << std::endl;
}

/* stat a file, make sure it's a file */
void statfile(const RequestParams &params, const Uri uri) {
    DECLARE_TEST();
    Context context;
    DavFile file(context, params, uri);
    StatInfo info;
    file.statInfo(&params, info);
    std::cout << string_from_mode(info.mode) << std::endl;

    ASSERT(! S_ISDIR(info.mode), "not a file");
}

void populate(const RequestParams &params, const Uri uri, const int nfiles) {
    DECLARE_TEST();

    for(int i = 1; i <= nfiles; i++) {
        Context context;
        Uri u(uri);
        u.addPathSegment(SSTR(testfile << i));
        DavFile file(context, params, u);
        file.put(NULL, testString.c_str(), testString.size());
        std::cout << "File " << i << " uploaded successfully." << std::endl;
        std::cout << u << std::endl;

        statfile(params, u);
    }
}

// count the number of files in folder
void countfiles(const RequestParams &params, const Uri uri, const int nfiles) {
    DECLARE_TEST();
    Context context;
    DavFile file(context, params, uri);
    DavFile::Iterator it = file.listCollection(&params);
    int i = 0;

    do {
        i++;
    } while(it.next());

    ASSERT(i == nfiles, "wrong number of files; expected " << nfiles << ", found " << i);
    std::cout << "All OK" << std::endl;
}

// confirm that the files listed are the exact same ones uploaded during a populate test
void listing(const RequestParams &params, const Uri uri, const int nfiles) {
    DECLARE_TEST();
    int hits[nfiles+1];
    for(int i = 0; i <= nfiles; i++) hits[i] = 0;

    Context context;
    DavFile file(context, params, uri);
    DavFile::Iterator it = file.listCollection(&params);

    int i = 0;
    do {
        i++;
        std::string name = it.name();
        std::cout << "Found " << name << std::endl;

        // make sure the filenames are the same as the ones we uploaded
        ASSERT(name.size() > testfile.size(), "Unexpected filename: " << name);
        std::string part1 = name.substr(0, testfile.size());
        std::string part2 = name.substr(testfile.size(), name.size()-1);

        ASSERT(part1 == testfile, "Unexpected filename: " << part1);
        int num = atoi(part2.c_str());
        ASSERT(num > 0, "Unexpected file number: " << num);
        ASSERT(num <= nfiles, "Unexpected file number: " << num);
        hits[num]++;
    } while(it.next());

    // count all hits to make sure all have exactly one
    ASSERT(i == nfiles, "wrong number of files; expected " << nfiles << ", found " << i);
    for(int i = 1; i <= nfiles; i++)
        ASSERT(hits[i] == 1, "hits check for file" << i << " failed. Expected 1, found " << hits[i]);

    std::cout << "All OK" << std::endl;
}

/* upload a file and move it around */
void putMoveDelete(const RequestParams &params, const Uri uri) {
    DECLARE_TEST();
    Uri u = uri;
    Uri u2 = uri;
    u.addPathSegment(SSTR(testfile << "put-move-delete"));
    u2.addPathSegment(SSTR(testfile << "put-move-delete-MOVED"));

    Context context;
    DavFile file(context, params, u);
    file.put(&params, testString.c_str(), testString.size());

    DavFile movedFile(context, params, u2);
    file.move(&params, movedFile);

    movedFile.deletion(&params);
    std::cout << "All OK" << std::endl;
}

void remove(const RequestParams &params, const Uri uri) {
    DECLARE_TEST();

    // a very dangerous test.. Make sure that uri at least
    // contains "davix-test" in its path.
    bool safePath = uri.getPath().find("davix-test") != std::string::npos;
    ASSERT(safePath, "Uri given does not contain the string 'davix-test'. Refusing to perform delete operation for safety.");

    Context context;
    DavFile file(context, params, uri);
    file.deletion(&params);
}

int run(int argc, char** argv) {
    RequestParams params;
    params.setOperationRetry(0);

    po::variables_map vm = parse_args(argc, argv);
    Auth::Type auth = Auth::fromString(opt(vm, "auth"));

    ASSERT(vm.count("command") != 0, "--command is necessary");
    ASSERT(vm.count("uri") != 0, "--uri is necessary");

    std::vector<std::string> cmd = vm["command"].as<std::vector<std::string> >();
    Uri uri = Uri(opt(vm, "uri"));

    authentication(vm, auth, params);

    if(cmd[0] == "makeCollection") {
        ASSERT(cmd.size() == 1, "Wrong number of arguments to makeCollection");
        makeCollection(params, uri);
    }
    else if(cmd[0] == "populate") {
        ASSERT(cmd.size() == 2, "Wrong number of arguments to populate");
        populate(params, uri, atoi(cmd[1].c_str()));
    }
    else if(cmd[0] == "remove") {
        ASSERT(cmd.size() == 1, "Wrong number of arguments to remove");
        remove(params, uri);
    }
    else if(cmd[0] == "listing") {
        ASSERT(cmd.size() == 2, "Wrong number of arguments to listing");
        listing(params, uri, atoi(cmd[1].c_str()));
    }
    else if(cmd[0] == "putMoveDelete") {
        ASSERT(cmd.size() == 1, "Wrong number of arguments to putMoveDelete");
        putMoveDelete(params, uri);
    }
    else if(cmd[0] == "depopulate") {
        ASSERT(cmd.size() == 2, "Wrong number of arguments to depopulate");
        depopulate(params, uri, atoi(cmd[1].c_str()));
    }
    else if(cmd[0] == "countfiles") {
        ASSERT(cmd.size() == 2, "Wrong number of arguments to countfiles");
        countfiles(params, uri, atoi(cmd[1].c_str()));
    }
    else if(cmd[0] == "statdir") {
        ASSERT(cmd.size() == 1, "Wrong number of arguments to statdir");
        statdir(params, uri);
    }
    else if(cmd[0] == "statfile") {
        ASSERT(cmd.size() == 1, "Wrong number of arguments to statdir");
        statfile(params, uri);
    }
    else {
        ASSERT(false, "Unknown command: " << cmd[0]);
    }
}

int main(int argc, char** argv) {
    try {
        initialization();
        run(argc, argv);
    }
    catch(std::exception &e) {
        std::cout << e.what() << std::endl;
        return 1;
    }

    return 0;
}
<commit_msg>Fix clang build<commit_after>#include <stdio.h>
#include <iostream>
#include <vector>
#include <boost/program_options.hpp>

#include <davix.hpp>
#include "davix_test_lib.h"

namespace po = boost::program_options;
using namespace Davix;

#define SSTR(message) static_cast<std::ostringstream&>(std::ostringstream().flush() << message).str()

#define DECLARE_TEST() std::cout << "Performing test: " << __FUNCTION__ << " on " << uri << std::endl

const std::string testString("This is a file generated by davix tests. It is safe to delete.");
const std::string testfile("davix-testfile-");

#define ASSERT(assertion, msg) \
    if((assertion) == false) throw std::runtime_error( SSTR(__FILE__ << ":" << __LINE__ << " (" << __func__ << "): Assertion " << #assertion << " failed.\n" << msg))

void initialization() {
    if(getenv("DEBUG")) {
        davix_set_log_level(DAVIX_LOG_ALL);
    }
}

std::vector<std::string> split(const std::string str, const std::string delim) {
    size_t prev = 0, cur;
    std::vector<std::string> results;
    while((cur = str.find(delim, prev)) != std::string::npos) {
        results.push_back(str.substr(prev, cur-prev));
        prev = cur + delim.size();
    }
    std::string last = str.substr(prev, str.size()-prev);
    if(last.size() != 0)
        results.push_back(last);

    return results;
}

namespace Auth {
enum Type {AWS, PROXY, AZURE, NONE};
Type fromString(const std::string &str) {
    if(str == "aws")
        return Auth::AWS;
    if(str == "proxy")
        return Auth::PROXY;
    if(str == "azure")
        return Auth::AZURE;
    if(str == "none")
        return Auth::NONE;

    throw std::invalid_argument(SSTR(str << " not a valid authentication method"));
};
};

po::variables_map parse_args(int argc, char** argv) {
    po::options_description desc("davix functional tests runner");

    desc.add_options()
        ("help", "produce help message")
        ("auth", po::value<std::string>()->default_value("none"), "authentication method to use (proxy, aws, none)")
        ("s3accesskey", po::value<std::string>(), "s3 access key")
        ("s3secretkey", po::value<std::string>(), "s3 secret key")
        ("s3region", po::value<std::string>(), "s3 region")
        ("azurekey", po::value<std::string>(), "azure key")
        ("s3alternate", "s3 alternate")
        ("cert", po::value<std::string>(), "path to the proxy certificate to use")
        ("uri", po::value<std::string>(), "uri to test against")
        ("command", po::value<std::vector<std::string> >()->multitoken(), "test to run")
        ;

    po::variables_map vm;
    po::store(po::parse_command_line(argc, argv, desc), vm);
    po::notify(vm);

    if (vm.count("help")) {
        std::cout << desc << "\n";
        exit(1);
    }
    return vm;
}

std::string opt(const po::variables_map &vm, const std::string key) {
    return vm[key].as<std::string>();
}

void authentication(const po::variables_map &vm, const Auth::Type &auth, RequestParams &params) {
    if(auth == Auth::AWS) {
        params.setProtocol(RequestProtocol::AwsS3);

        ASSERT(vm.count("s3accesskey") != 0, "--s3accesskey is required when using s3");
        ASSERT(vm.count("s3secretkey") != 0, "--s3secretkey is required when using s3");

        params.setAwsAuthorizationKeys(opt(vm, "s3secretkey"), opt(vm, "s3accesskey"));
        if(vm.count("s3region") != 0) params.setAwsRegion(opt(vm, "s3region"));
        if(vm.count("s3alternate") != 0) params.setAwsAlternate(true);
    }
    else if(auth == Auth::PROXY) {
        configure_grid_env("proxy", params);
    }
    else if(auth == Auth::AZURE) {
        ASSERT(vm.count("azurekey") != 0, "--azurekey is required when using Azure");

        params.setProtocol(RequestProtocol::Azure);
        params.setAzureKey(opt(vm, "azurekey"));
    }
    else {
        ASSERT(false, "unknown authentication method");
    }
}

void depopulate(const RequestParams &params, Uri uri, int nfiles) {
    DECLARE_TEST();

    for(int i = 1; i <= nfiles; i++) {
        Context context;
        Uri u(uri);
        u.addPathSegment(SSTR(testfile << i));
        DavFile file(context, params, u);
        file.deletion(&params);
        std::cout << "File " << i << " deleted successfully." << std::endl;
    }
    std::cout << "All OK" << std::endl;
}

std::string string_from_mode(mode_t mode){
    const char* rmask ="xwr";
    std::string str(10,'-');

    str[0] = (S_ISDIR(mode))?'d':'-';
    for(size_t i=0; i < 9; ++i){
        str[9-i] = (( mode & (0x01 << i))?(rmask[i%3]):'-');
    }
    return str;
}

void statdir(const RequestParams &params, Uri uri) {
    DECLARE_TEST();
    Context context;
    DavFile file(context, params, uri);
    StatInfo info;
    file.statInfo(&params, info);
    std::cout << string_from_mode(info.mode) << std::endl;

    ASSERT(S_ISDIR(info.mode), "not a directory");
}

void makeCollection(const RequestParams &params, Uri uri) {
    DECLARE_TEST();

    Context context;
    DavFile file(context, params, uri);
    file.makeCollection(&params);

    // make sure it is empty
    DavFile::Iterator it = file.listCollection(&params);
    ASSERT(it.name() == "" && !it.next(), "Newly created directory not empty!");

    // do a stat, make sure it's a dir
    statdir(params, uri);

    Uri u2 = uri;
    u2.ensureTrailingSlash();
    statdir(params, u2);

    std::cout << "Done!" << std::endl;
}

/* stat a file, make sure it's a file */
void statfile(const RequestParams &params, const Uri uri) {
    DECLARE_TEST();
    Context context;
    DavFile file(context, params, uri);
    StatInfo info;
    file.statInfo(&params, info);
    std::cout << string_from_mode(info.mode) << std::endl;

    ASSERT(! S_ISDIR(info.mode), "not a file");
}

void populate(const RequestParams &params, const Uri uri, const int nfiles) {
    DECLARE_TEST();

    for(int i = 1; i <= nfiles; i++) {
        Context context;
        Uri u(uri);
        u.addPathSegment(SSTR(testfile << i));
        DavFile file(context, params, u);
        file.put(NULL, testString.c_str(), testString.size());
        std::cout << "File " << i << " uploaded successfully." << std::endl;
        std::cout << u << std::endl;

        statfile(params, u);
    }
}

// count the number of files in folder
void countfiles(const RequestParams &params, const Uri uri, const int nfiles) {
    DECLARE_TEST();
    Context context;
    DavFile file(context, params, uri);
    DavFile::Iterator it = file.listCollection(&params);
    int i = 0;

    do {
        i++;
    } while(it.next());

    ASSERT(i == nfiles, "wrong number of files; expected " << nfiles << ", found " << i);
    std::cout << "All OK" << std::endl;
}

// confirm that the files listed are the exact same ones uploaded during a populate test
void listing(const RequestParams &params, const Uri uri, const int nfiles) {
    DECLARE_TEST();
    int hits[nfiles+1];
    for(int i = 0; i <= nfiles; i++) hits[i] = 0;

    Context context;
    DavFile file(context, params, uri);
    DavFile::Iterator it = file.listCollection(&params);

    int i = 0;
    do {
        i++;
        std::string name = it.name();
        std::cout << "Found " << name << std::endl;

        // make sure the filenames are the same as the ones we uploaded
        ASSERT(name.size() > testfile.size(), "Unexpected filename: " << name);
        std::string part1 = name.substr(0, testfile.size());
        std::string part2 = name.substr(testfile.size(), name.size()-1);

        ASSERT(part1 == testfile, "Unexpected filename: " << part1);
        int num = atoi(part2.c_str());
        ASSERT(num > 0, "Unexpected file number: " << num);
        ASSERT(num <= nfiles, "Unexpected file number: " << num);
        hits[num]++;
    } while(it.next());

    // count all hits to make sure all have exactly one
    ASSERT(i == nfiles, "wrong number of files; expected " << nfiles << ", found " << i);
    for(int i = 1; i <= nfiles; i++)
        ASSERT(hits[i] == 1, "hits check for file" << i << " failed. Expected 1, found " << hits[i]);

    std::cout << "All OK" << std::endl;
}

/* upload a file and move it around */
void putMoveDelete(const RequestParams &params, const Uri uri) {
    DECLARE_TEST();
    Uri u = uri;
    Uri u2 = uri;
    u.addPathSegment(SSTR(testfile << "put-move-delete"));
    u2.addPathSegment(SSTR(testfile << "put-move-delete-MOVED"));

    Context context;
    DavFile file(context, params, u);
    file.put(&params, testString.c_str(), testString.size());

    DavFile movedFile(context, params, u2);
    file.move(&params, movedFile);

    movedFile.deletion(&params);
    std::cout << "All OK" << std::endl;
}

void remove(const RequestParams &params, const Uri uri) {
    DECLARE_TEST();

    // a very dangerous test.. Make sure that uri at least
    // contains "davix-test" in its path.
    bool safePath = uri.getPath().find("davix-test") != std::string::npos;
    ASSERT(safePath, "Uri given does not contain the string 'davix-test'. Refusing to perform delete operation for safety.");

    Context context;
    DavFile file(context, params, uri);
    file.deletion(&params);
}

void run(int argc, char** argv) {
    RequestParams params;
    params.setOperationRetry(0);

    po::variables_map vm = parse_args(argc, argv);
    Auth::Type auth = Auth::fromString(opt(vm, "auth"));

    ASSERT(vm.count("command") != 0, "--command is necessary");
    ASSERT(vm.count("uri") != 0, "--uri is necessary");

    std::vector<std::string> cmd = vm["command"].as<std::vector<std::string> >();
    Uri uri = Uri(opt(vm, "uri"));

    authentication(vm, auth, params);

    if(cmd[0] == "makeCollection") {
        ASSERT(cmd.size() == 1, "Wrong number of arguments to makeCollection");
        makeCollection(params, uri);
    }
    else if(cmd[0] == "populate") {
        ASSERT(cmd.size() == 2, "Wrong number of arguments to populate");
        populate(params, uri, atoi(cmd[1].c_str()));
    }
    else if(cmd[0] == "remove") {
        ASSERT(cmd.size() == 1, "Wrong number of arguments to remove");
        remove(params, uri);
    }
    else if(cmd[0] == "listing") {
        ASSERT(cmd.size() == 2, "Wrong number of arguments to listing");
        listing(params, uri, atoi(cmd[1].c_str()));
    }
    else if(cmd[0] == "putMoveDelete") {
        ASSERT(cmd.size() == 1, "Wrong number of arguments to putMoveDelete");
        putMoveDelete(params, uri);
    }
    else if(cmd[0] == "depopulate") {
        ASSERT(cmd.size() == 2, "Wrong number of arguments to depopulate");
        depopulate(params, uri, atoi(cmd[1].c_str()));
    }
    else if(cmd[0] == "countfiles") {
        ASSERT(cmd.size() == 2, "Wrong number of arguments to countfiles");
        countfiles(params, uri, atoi(cmd[1].c_str()));
    }
    else if(cmd[0] == "statdir") {
        ASSERT(cmd.size() == 1, "Wrong number of arguments to statdir");
        statdir(params, uri);
    }
    else if(cmd[0] == "statfile") {
        ASSERT(cmd.size() == 1, "Wrong number of arguments to statdir");
        statfile(params, uri);
    }
    else {
        ASSERT(false, "Unknown command: " << cmd[0]);
    }
}

int main(int argc, char** argv) {
    try {
        initialization();
        run(argc, argv);
    }
    catch(std::exception &e) {
        std::cout << e.what() << std::endl;
        return 1;
    }

    return 0;
}
<|endoftext|>


<commit_before>//=======================================================================
// Copyright (c) 2014-2016 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
//  http://opensource.org/licenses/MIT)
//=======================================================================

#ifdef ETL_VECTORIZE_IMPL
#ifdef __AVX__
#define TEST_VEC
#elif defined(__SSE3__)
#define TEST_VEC
#endif
#endif

#define MUL_FUNCTOR(name, ...)                        \
    struct name {                                     \
        template <typename A, typename B, typename C> \
        static void apply(A&& a, B&& b, C& c) {       \
            __VA_ARGS__;                              \
        }                                             \
    };

MUL_FUNCTOR(default_gemm, c = etl::mul(a, b))
MUL_FUNCTOR(lazy_gemm, c = etl::lazy_mul(a, b))
MUL_FUNCTOR(strassen_gemm, c = etl::strassen_mul(a, b))
MUL_FUNCTOR(std_gemm, c = selected_helper(etl::gemm_impl::STD, a* b))

MUL_FUNCTOR(default_gemv, c = etl::mul(a, b))
MUL_FUNCTOR(std_gemv, c = selected_helper(etl::gemm_impl::STD, a * b))

MUL_FUNCTOR(default_gevm, c = etl::mul(a, b))
MUL_FUNCTOR(std_gevm, c = selected_helper(etl::gemm_impl::STD, a* b))

#define GEMM_TEST_CASE_SECTION_DEFAULT MUL_TEST_CASE_SECTIONS(default_gemm, default_gemm)
#define GEMM_TEST_CASE_SECTION_LAZY MUL_TEST_CASE_SECTIONS(lazy_gemm, lazy_gemm)
#define GEMM_TEST_CASE_SECTION_STD MUL_TEST_CASE_SECTIONS(std_gemm, std_gemm)
#define GEMM_TEST_CASE_SECTION_STRASSEN MUL_TEST_CASE_SECTIONS(strassen_gemm, strassen_gemm)

#define GEMV_TEST_CASE_SECTION_DEFAULT MUL_TEST_CASE_SECTIONS(default_gemv, default_gemv)
#define GEMV_TEST_CASE_SECTION_STD MUL_TEST_CASE_SECTIONS(std_gemv, std_gemv)

#define GEVM_TEST_CASE_SECTION_DEFAULT MUL_TEST_CASE_SECTIONS(default_gevm, default_gevm)
#define GEVM_TEST_CASE_SECTION_STD MUL_TEST_CASE_SECTIONS(std_gevm, std_gevm)

#ifdef TEST_VEC
MUL_FUNCTOR(vec_gemv, c = selected_helper(etl::gemm_impl::VEC, a * b))
MUL_FUNCTOR(vec_gevm, c = selected_helper(etl::gemm_impl::STD, a * b))
MUL_FUNCTOR(vec_gemm, c = selected_helper(etl::gemm_impl::STD, a * b))
#define GEMV_TEST_CASE_SECTION_VEC MUL_TEST_CASE_SECTIONS(vec_gemv, vec_gemv)
#define GEVM_TEST_CASE_SECTION_VEC MUL_TEST_CASE_SECTIONS(vec_gevm, vec_gevm)
#define GEMM_TEST_CASE_SECTION_VEC MUL_TEST_CASE_SECTIONS(vec_gemm, vec_gemm)
#else
#define GEMV_TEST_CASE_SECTION_VEC
#define GEVM_TEST_CASE_SECTION_VEC
#define GEMM_TEST_CASE_SECTION_VEC
#endif

#ifdef ETL_BLAS_MODE
MUL_FUNCTOR(blas_gemm, c = selected_helper(etl::gemm_impl::BLAS, a* b))
MUL_FUNCTOR(blas_gemv, c = selected_helper(etl::gemm_impl::BLAS, a* b))
MUL_FUNCTOR(blas_gevm, c = selected_helper(etl::gemm_impl::BLAS, a* b))
#define GEMM_TEST_CASE_SECTION_BLAS MUL_TEST_CASE_SECTIONS(blas_gemm, blas_gemm)
#define GEMV_TEST_CASE_SECTION_BLAS MUL_TEST_CASE_SECTIONS(blas_gemv, blas_gemv)
#define GEVM_TEST_CASE_SECTION_BLAS MUL_TEST_CASE_SECTIONS(blas_gevm, blas_gevm)
#else
#define GEMM_TEST_CASE_SECTION_BLAS
#define GEMV_TEST_CASE_SECTION_BLAS
#define GEVM_TEST_CASE_SECTION_BLAS
#endif

#ifdef ETL_CUBLAS_MODE
MUL_FUNCTOR(cublas_gemm, c = selected_helper(etl::gemm_impl::CUBLAS, a* b))
MUL_FUNCTOR(cublas_gemv, c = selected_helper(etl::gemm_impl::CUBLAS, a* b))
MUL_FUNCTOR(cublas_gevm, c = selected_helper(etl::gemm_impl::CUBLAS, a* b))
#define GEMM_TEST_CASE_SECTION_CUBLAS MUL_TEST_CASE_SECTIONS(cublas_gemm, cublas_gemm)
#define GEMV_TEST_CASE_SECTION_CUBLAS MUL_TEST_CASE_SECTIONS(cublas_gemv, cublas_gemv)
#define GEVM_TEST_CASE_SECTION_CUBLAS MUL_TEST_CASE_SECTIONS(cublas_gevm, cublas_gevm)
#else
#define GEMM_TEST_CASE_SECTION_CUBLAS
#define GEMV_TEST_CASE_SECTION_CUBLAS
#define GEVM_TEST_CASE_SECTION_CUBLAS
#endif

#define MUL_TEST_CASE_DECL(name, description)                                  \
    template <typename T, typename Impl>                                       \
    static void UNIQUE_NAME(____C_A_T_C_H____T_E_M_P_L_A_TE____T_E_S_T____)(); \
    ETL_TEST_CASE(name, description)

#define MUL_TEST_CASE_SECTION(Tn, Impln)                                          \
    ETL_SECTION(#Tn "_" #Impln) {                                                 \
        UNIQUE_NAME(____C_A_T_C_H____T_E_M_P_L_A_TE____T_E_S_T____)<Tn, Impln>(); \
    }

#define MUL_TEST_CASE_DEFN               \
    template <typename T, typename Impl> \
    static void UNIQUE_NAME(____C_A_T_C_H____T_E_M_P_L_A_TE____T_E_S_T____)()

#define MUL_TEST_CASE_SECTIONS(S1, S2) \
    MUL_TEST_CASE_SECTION(float, S1)   \
    MUL_TEST_CASE_SECTION(double, S2)

#define GEMM_TEST_CASE(name, description)   \
    MUL_TEST_CASE_DECL(name, description) { \
        GEMM_TEST_CASE_SECTION_DEFAULT      \
        GEMM_TEST_CASE_SECTION_STD          \
        GEMM_TEST_CASE_SECTION_LAZY         \
        GEMM_TEST_CASE_SECTION_STRASSEN     \
        GEMM_TEST_CASE_SECTION_BLAS         \
        GEMM_TEST_CASE_SECTION_VEC         \
        GEMM_TEST_CASE_SECTION_CUBLAS       \
    }                                       \
    MUL_TEST_CASE_DEFN

#define GEMM_TEST_CASE_PRE(name, description)   \
    MUL_TEST_CASE_DECL(name, description) { \
        GEMM_TEST_CASE_SECTION_DEFAULT      \
        GEMM_TEST_CASE_SECTION_STD          \
        GEMM_TEST_CASE_SECTION_LAZY         \
        GEMM_TEST_CASE_SECTION_BLAS         \
        GEMM_TEST_CASE_SECTION_VEC         \
        GEMM_TEST_CASE_SECTION_CUBLAS       \
    }                                       \
    MUL_TEST_CASE_DEFN

#define GEMV_TEST_CASE(name, description)   \
    MUL_TEST_CASE_DECL(name, description) { \
        GEMV_TEST_CASE_SECTION_DEFAULT      \
        GEMV_TEST_CASE_SECTION_STD          \
        GEMV_TEST_CASE_SECTION_VEC          \
        GEMV_TEST_CASE_SECTION_BLAS         \
        GEMV_TEST_CASE_SECTION_CUBLAS       \
    }                                       \
    MUL_TEST_CASE_DEFN

#define GEVM_TEST_CASE(name, description)   \
    MUL_TEST_CASE_DECL(name, description) { \
        GEVM_TEST_CASE_SECTION_DEFAULT      \
        GEVM_TEST_CASE_SECTION_STD          \
        GEVM_TEST_CASE_SECTION_VEC          \
        GEVM_TEST_CASE_SECTION_BLAS         \
        GEVM_TEST_CASE_SECTION_CUBLAS       \
    }                                       \
    MUL_TEST_CASE_DEFN

#define CGEMM_TEST_CASE(name, description)   \
    MUL_TEST_CASE_DECL(name, description) { \
        GEMM_TEST_CASE_SECTION_DEFAULT      \
        GEMM_TEST_CASE_SECTION_STD          \
        GEMM_TEST_CASE_SECTION_LAZY         \
        GEMM_TEST_CASE_SECTION_BLAS         \
        GEMM_TEST_CASE_SECTION_VEC         \
        GEMM_TEST_CASE_SECTION_CUBLAS       \
    }                                       \
    MUL_TEST_CASE_DEFN

#define CGEMV_TEST_CASE(name, description)   \
    MUL_TEST_CASE_DECL(name, description) { \
        GEMV_TEST_CASE_SECTION_DEFAULT      \
        GEMV_TEST_CASE_SECTION_STD          \
        GEMV_TEST_CASE_SECTION_VEC          \
        GEMV_TEST_CASE_SECTION_BLAS         \
        GEMV_TEST_CASE_SECTION_CUBLAS       \
    }                                       \
    MUL_TEST_CASE_DEFN

#define CGEVM_TEST_CASE(name, description)   \
    MUL_TEST_CASE_DECL(name, description) { \
        GEVM_TEST_CASE_SECTION_DEFAULT      \
        GEVM_TEST_CASE_SECTION_STD          \
        GEVM_TEST_CASE_SECTION_VEC          \
        GEVM_TEST_CASE_SECTION_BLAS         \
        GEVM_TEST_CASE_SECTION_CUBLAS       \
    }                                       \
    MUL_TEST_CASE_DEFN
<commit_msg>Unify<commit_after>//=======================================================================
// Copyright (c) 2014-2016 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
//  http://opensource.org/licenses/MIT)
//=======================================================================

#ifdef ETL_VECTORIZE_IMPL
#ifdef __AVX__
#define TEST_VEC
#elif defined(__SSE3__)
#define TEST_VEC
#endif
#endif

#define MUL_FUNCTOR(name, ...)                        \
    struct name {                                     \
        template <typename A, typename B, typename C> \
        static void apply(A&& a, B&& b, C& c) {       \
            __VA_ARGS__;                              \
        }                                             \
    };

MUL_FUNCTOR(default_gemm, c = a * b)
MUL_FUNCTOR(lazy_gemm, c = etl::lazy_mul(a, b))
MUL_FUNCTOR(strassen_gemm, c = etl::strassen_mul(a, b))
MUL_FUNCTOR(std_gemm, c = selected_helper(etl::gemm_impl::STD, a* b))

MUL_FUNCTOR(default_gemv, c = etl::mul(a, b))
MUL_FUNCTOR(std_gemv, c = selected_helper(etl::gemm_impl::STD, a * b))

MUL_FUNCTOR(default_gevm, c = etl::mul(a, b))
MUL_FUNCTOR(std_gevm, c = selected_helper(etl::gemm_impl::STD, a* b))

#define GEMM_TEST_CASE_SECTION_DEFAULT MUL_TEST_CASE_SECTIONS(default_gemm, default_gemm)
#define GEMM_TEST_CASE_SECTION_LAZY MUL_TEST_CASE_SECTIONS(lazy_gemm, lazy_gemm)
#define GEMM_TEST_CASE_SECTION_STD MUL_TEST_CASE_SECTIONS(std_gemm, std_gemm)
#define GEMM_TEST_CASE_SECTION_STRASSEN MUL_TEST_CASE_SECTIONS(strassen_gemm, strassen_gemm)

#define GEMV_TEST_CASE_SECTION_DEFAULT MUL_TEST_CASE_SECTIONS(default_gemv, default_gemv)
#define GEMV_TEST_CASE_SECTION_STD MUL_TEST_CASE_SECTIONS(std_gemv, std_gemv)

#define GEVM_TEST_CASE_SECTION_DEFAULT MUL_TEST_CASE_SECTIONS(default_gevm, default_gevm)
#define GEVM_TEST_CASE_SECTION_STD MUL_TEST_CASE_SECTIONS(std_gevm, std_gevm)

#ifdef TEST_VEC
MUL_FUNCTOR(vec_gemv, c = selected_helper(etl::gemm_impl::VEC, a * b))
MUL_FUNCTOR(vec_gevm, c = selected_helper(etl::gemm_impl::STD, a * b))
MUL_FUNCTOR(vec_gemm, c = selected_helper(etl::gemm_impl::STD, a * b))
#define GEMV_TEST_CASE_SECTION_VEC MUL_TEST_CASE_SECTIONS(vec_gemv, vec_gemv)
#define GEVM_TEST_CASE_SECTION_VEC MUL_TEST_CASE_SECTIONS(vec_gevm, vec_gevm)
#define GEMM_TEST_CASE_SECTION_VEC MUL_TEST_CASE_SECTIONS(vec_gemm, vec_gemm)
#else
#define GEMV_TEST_CASE_SECTION_VEC
#define GEVM_TEST_CASE_SECTION_VEC
#define GEMM_TEST_CASE_SECTION_VEC
#endif

#ifdef ETL_BLAS_MODE
MUL_FUNCTOR(blas_gemm, c = selected_helper(etl::gemm_impl::BLAS, a* b))
MUL_FUNCTOR(blas_gemv, c = selected_helper(etl::gemm_impl::BLAS, a* b))
MUL_FUNCTOR(blas_gevm, c = selected_helper(etl::gemm_impl::BLAS, a* b))
#define GEMM_TEST_CASE_SECTION_BLAS MUL_TEST_CASE_SECTIONS(blas_gemm, blas_gemm)
#define GEMV_TEST_CASE_SECTION_BLAS MUL_TEST_CASE_SECTIONS(blas_gemv, blas_gemv)
#define GEVM_TEST_CASE_SECTION_BLAS MUL_TEST_CASE_SECTIONS(blas_gevm, blas_gevm)
#else
#define GEMM_TEST_CASE_SECTION_BLAS
#define GEMV_TEST_CASE_SECTION_BLAS
#define GEVM_TEST_CASE_SECTION_BLAS
#endif

#ifdef ETL_CUBLAS_MODE
MUL_FUNCTOR(cublas_gemm, c = selected_helper(etl::gemm_impl::CUBLAS, a* b))
MUL_FUNCTOR(cublas_gemv, c = selected_helper(etl::gemm_impl::CUBLAS, a* b))
MUL_FUNCTOR(cublas_gevm, c = selected_helper(etl::gemm_impl::CUBLAS, a* b))
#define GEMM_TEST_CASE_SECTION_CUBLAS MUL_TEST_CASE_SECTIONS(cublas_gemm, cublas_gemm)
#define GEMV_TEST_CASE_SECTION_CUBLAS MUL_TEST_CASE_SECTIONS(cublas_gemv, cublas_gemv)
#define GEVM_TEST_CASE_SECTION_CUBLAS MUL_TEST_CASE_SECTIONS(cublas_gevm, cublas_gevm)
#else
#define GEMM_TEST_CASE_SECTION_CUBLAS
#define GEMV_TEST_CASE_SECTION_CUBLAS
#define GEVM_TEST_CASE_SECTION_CUBLAS
#endif

#define MUL_TEST_CASE_DECL(name, description)                                  \
    template <typename T, typename Impl>                                       \
    static void UNIQUE_NAME(____C_A_T_C_H____T_E_M_P_L_A_TE____T_E_S_T____)(); \
    ETL_TEST_CASE(name, description)

#define MUL_TEST_CASE_SECTION(Tn, Impln)                                          \
    ETL_SECTION(#Tn "_" #Impln) {                                                 \
        UNIQUE_NAME(____C_A_T_C_H____T_E_M_P_L_A_TE____T_E_S_T____)<Tn, Impln>(); \
    }

#define MUL_TEST_CASE_DEFN               \
    template <typename T, typename Impl> \
    static void UNIQUE_NAME(____C_A_T_C_H____T_E_M_P_L_A_TE____T_E_S_T____)()

#define MUL_TEST_CASE_SECTIONS(S1, S2) \
    MUL_TEST_CASE_SECTION(float, S1)   \
    MUL_TEST_CASE_SECTION(double, S2)

#define GEMM_TEST_CASE(name, description)   \
    MUL_TEST_CASE_DECL(name, description) { \
        GEMM_TEST_CASE_SECTION_DEFAULT      \
        GEMM_TEST_CASE_SECTION_STD          \
        GEMM_TEST_CASE_SECTION_LAZY         \
        GEMM_TEST_CASE_SECTION_STRASSEN     \
        GEMM_TEST_CASE_SECTION_BLAS         \
        GEMM_TEST_CASE_SECTION_VEC         \
        GEMM_TEST_CASE_SECTION_CUBLAS       \
    }                                       \
    MUL_TEST_CASE_DEFN

#define GEMM_TEST_CASE_PRE(name, description)   \
    MUL_TEST_CASE_DECL(name, description) { \
        GEMM_TEST_CASE_SECTION_DEFAULT      \
        GEMM_TEST_CASE_SECTION_STD          \
        GEMM_TEST_CASE_SECTION_LAZY         \
        GEMM_TEST_CASE_SECTION_BLAS         \
        GEMM_TEST_CASE_SECTION_VEC         \
        GEMM_TEST_CASE_SECTION_CUBLAS       \
    }                                       \
    MUL_TEST_CASE_DEFN

#define GEMV_TEST_CASE(name, description)   \
    MUL_TEST_CASE_DECL(name, description) { \
        GEMV_TEST_CASE_SECTION_DEFAULT      \
        GEMV_TEST_CASE_SECTION_STD          \
        GEMV_TEST_CASE_SECTION_VEC          \
        GEMV_TEST_CASE_SECTION_BLAS         \
        GEMV_TEST_CASE_SECTION_CUBLAS       \
    }                                       \
    MUL_TEST_CASE_DEFN

#define GEVM_TEST_CASE(name, description)   \
    MUL_TEST_CASE_DECL(name, description) { \
        GEVM_TEST_CASE_SECTION_DEFAULT      \
        GEVM_TEST_CASE_SECTION_STD          \
        GEVM_TEST_CASE_SECTION_VEC          \
        GEVM_TEST_CASE_SECTION_BLAS         \
        GEVM_TEST_CASE_SECTION_CUBLAS       \
    }                                       \
    MUL_TEST_CASE_DEFN

#define CGEMM_TEST_CASE(name, description)   \
    MUL_TEST_CASE_DECL(name, description) { \
        GEMM_TEST_CASE_SECTION_DEFAULT      \
        GEMM_TEST_CASE_SECTION_STD          \
        GEMM_TEST_CASE_SECTION_LAZY         \
        GEMM_TEST_CASE_SECTION_BLAS         \
        GEMM_TEST_CASE_SECTION_VEC         \
        GEMM_TEST_CASE_SECTION_CUBLAS       \
    }                                       \
    MUL_TEST_CASE_DEFN

#define CGEMV_TEST_CASE(name, description)   \
    MUL_TEST_CASE_DECL(name, description) { \
        GEMV_TEST_CASE_SECTION_DEFAULT      \
        GEMV_TEST_CASE_SECTION_STD          \
        GEMV_TEST_CASE_SECTION_VEC          \
        GEMV_TEST_CASE_SECTION_BLAS         \
        GEMV_TEST_CASE_SECTION_CUBLAS       \
    }                                       \
    MUL_TEST_CASE_DEFN

#define CGEVM_TEST_CASE(name, description)   \
    MUL_TEST_CASE_DECL(name, description) { \
        GEVM_TEST_CASE_SECTION_DEFAULT      \
        GEVM_TEST_CASE_SECTION_STD          \
        GEVM_TEST_CASE_SECTION_VEC          \
        GEVM_TEST_CASE_SECTION_BLAS         \
        GEVM_TEST_CASE_SECTION_CUBLAS       \
    }                                       \
    MUL_TEST_CASE_DEFN
<|endoftext|>


<commit_before>#include <new>
#include <typeinfo>
#include <string>
#include <list>
#include <map>

#include <cstdarg>
#include <cstdlib>
#include <cstdio>
#include <cerrno>
#include <ctime>

#include "Server.hpp"
#include "Prototypes.hpp"
<commit_msg>Update Engine.hpp<commit_after>#include <new>
#include <typeinfo>
#include <string>
#include <list>
#include <map>

#include <cstdarg>
#include <cstdlib>
#include <cstdio>
#include <cerrno>
#include <ctime>

#include "Server.hpp"
#include "Socket.hpp"
#include "Prototypes.hpp"
<|endoftext|>


<commit_before>/*
 * gst-droid
 *
 * Copyright (C) 2014 Mohammed Sameer <msameer@foolab.org>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library 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
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public
 * License along with this library; if not, write to the
 * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
 * Boston, MA 02110-1301, USA.
 */

#include "videoplayer.h"
#include <QQmlInfo>
#include <QTimer>
#include "renderer.h"
#include <QPainter>
#include <QMatrix4x4>
#include <cmath>

VideoPlayer::VideoPlayer(QQuickItem *parent) :
  QQuickPaintedItem(parent),
  m_renderer(0),
  m_bin(0),
  m_src(0),
  m_sink(0) {

  setRenderTarget(QQuickPaintedItem::FramebufferObject);
  setSmooth(false);
  setAntialiasing(false);
}

VideoPlayer::~VideoPlayer() {
  stop();

  if (m_bin) {
    gst_object_unref(m_bin);
    m_bin = 0;
  }
}

void VideoPlayer::componentComplete() {
  QQuickPaintedItem::componentComplete();
}

void VideoPlayer::classBegin() {
  QQuickPaintedItem::classBegin();

  m_bin = gst_pipeline_new (NULL);
  m_src = gst_element_factory_make("droidcamsrc", NULL);
  gst_bin_add (GST_BIN (m_bin), m_src);

  GstBus *bus = gst_element_get_bus(m_bin);
  gst_bus_add_watch(bus, bus_call, this);
  gst_object_unref(bus);
}

bool VideoPlayer::start() {
  if (!m_renderer) {
    m_renderer = QtCamViewfinderRenderer::create(this);
    if (!m_renderer) {
      qmlInfo(this) << "Failed to create viewfinder renderer";
      return false;
    }

    QObject::connect(m_renderer, SIGNAL(updateRequested()), this, SLOT(updateRequested()));
  }

  m_renderer->resize(QSizeF(width(), height()));

  if (!m_bin) {
    qmlInfo(this) << "no playbin";
    return false;
  }

  if (!m_sink) {
    m_sink = m_renderer->sinkElement();
    gst_bin_add (GST_BIN (m_bin), m_sink);
    gst_element_link_pads (m_src, "vfsrc", m_sink, "sink");
  } else {
    // This will allow resetting EGLDisplay
    m_renderer->sinkElement();
  }

  if (gst_element_set_state(m_bin, GST_STATE_PLAYING) == GST_STATE_CHANGE_FAILURE) {
    qmlInfo(this) << "error setting pipeline to PLAYING";
    return false;
  }

  return true;
}

bool VideoPlayer::stop() {
  if (gst_element_set_state(m_bin, GST_STATE_NULL) == GST_STATE_CHANGE_FAILURE) {
    qmlInfo(this) << "error setting pipeline to NULL";
    return false;
  }

  m_renderer->reset();

  return true;
}

void VideoPlayer::geometryChanged(const QRectF& newGeometry, const QRectF& oldGeometry) {
  QQuickPaintedItem::geometryChanged(newGeometry, oldGeometry);

  if (m_renderer) {
    m_renderer->resize(newGeometry.size());
  }
}

void VideoPlayer::paint(QPainter *painter) {
  painter->fillRect(contentsBoundingRect(), Qt::black);

  if (!m_renderer) {
    return;
  }

  bool needsNativePainting = m_renderer->needsNativePainting();

  if (needsNativePainting) {
    painter->beginNativePainting();
  }

  m_renderer->paint(QMatrix4x4(painter->combinedTransform()), painter->viewport());

  if (needsNativePainting) {
    painter->endNativePainting();
  }
}

gboolean VideoPlayer::bus_call(GstBus *bus, GstMessage *msg, gpointer data) {
  Q_UNUSED(bus);

  VideoPlayer *that = (VideoPlayer *) data;

  gchar *debug = NULL;
  GError *err = NULL;

  switch (GST_MESSAGE_TYPE(msg)) {
  case GST_MESSAGE_EOS:
    that->stop();
    break;

  case GST_MESSAGE_ERROR:
    gst_message_parse_error (msg, &err, &debug);
    qWarning() << "Error" << err->message;

    emit that->error(err->message, err->code, debug);
    that->stop();

    if (err) {
      g_error_free (err);
    }

    if (debug) {
      g_free (debug);
    }

    break;

  default:
    break;
  }

  return TRUE;
}

void VideoPlayer::updateRequested() {
  update();
}
<commit_msg>make simple-camera use camerabin<commit_after>/*
 * gst-droid
 *
 * Copyright (C) 2014 Mohammed Sameer <msameer@foolab.org>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library 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
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public
 * License along with this library; if not, write to the
 * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
 * Boston, MA 02110-1301, USA.
 */

#include "videoplayer.h"
#include <QQmlInfo>
#include <QTimer>
#include "renderer.h"
#include <QPainter>
#include <QMatrix4x4>
#include <cmath>

VideoPlayer::VideoPlayer(QQuickItem *parent) :
  QQuickPaintedItem(parent),
  m_renderer(0),
  m_bin(0),
  m_src(0),
  m_sink(0) {

  setRenderTarget(QQuickPaintedItem::FramebufferObject);
  setSmooth(false);
  setAntialiasing(false);
}

VideoPlayer::~VideoPlayer() {
  stop();

  if (m_bin) {
    gst_object_unref(m_bin);
    m_bin = 0;
  }
}

void VideoPlayer::componentComplete() {
  QQuickPaintedItem::componentComplete();
}

void VideoPlayer::classBegin() {
  QQuickPaintedItem::classBegin();

  m_bin = gst_element_factory_make("camerabin", NULL);
  m_src = gst_element_factory_make("droidcamsrc", NULL);
  GstElement *src = gst_element_factory_make ("pulsesrc", NULL);
  g_object_set (m_bin, "audio-source", src, "camera-source", m_src, NULL);

  GstBus *bus = gst_element_get_bus(m_bin);
  gst_bus_add_watch(bus, bus_call, this);
  gst_object_unref(bus);
}

bool VideoPlayer::start() {
  if (!m_renderer) {
    m_renderer = QtCamViewfinderRenderer::create(this);
    if (!m_renderer) {
      qmlInfo(this) << "Failed to create viewfinder renderer";
      return false;
    }

    QObject::connect(m_renderer, SIGNAL(updateRequested()), this, SLOT(updateRequested()));
  }

  m_renderer->resize(QSizeF(width(), height()));

  if (!m_bin) {
    qmlInfo(this) << "no playbin";
    return false;
  }

  if (!m_sink) {
    m_sink = m_renderer->sinkElement();
    g_object_set (m_bin, "viewfinder-sink", m_sink, NULL);
  } else {
    // This will allow resetting EGLDisplay
    m_renderer->sinkElement();
  }

  if (gst_element_set_state(m_bin, GST_STATE_PLAYING) == GST_STATE_CHANGE_FAILURE) {
    qmlInfo(this) << "error setting pipeline to PLAYING";
    return false;
  }

  return true;
}

bool VideoPlayer::stop() {
  if (gst_element_set_state(m_bin, GST_STATE_NULL) == GST_STATE_CHANGE_FAILURE) {
    qmlInfo(this) << "error setting pipeline to NULL";
    return false;
  }

  m_renderer->reset();

  return true;
}

void VideoPlayer::geometryChanged(const QRectF& newGeometry, const QRectF& oldGeometry) {
  QQuickPaintedItem::geometryChanged(newGeometry, oldGeometry);

  if (m_renderer) {
    m_renderer->resize(newGeometry.size());
  }
}

void VideoPlayer::paint(QPainter *painter) {
  painter->fillRect(contentsBoundingRect(), Qt::black);

  if (!m_renderer) {
    return;
  }

  bool needsNativePainting = m_renderer->needsNativePainting();

  if (needsNativePainting) {
    painter->beginNativePainting();
  }

  m_renderer->paint(QMatrix4x4(painter->combinedTransform()), painter->viewport());

  if (needsNativePainting) {
    painter->endNativePainting();
  }
}

gboolean VideoPlayer::bus_call(GstBus *bus, GstMessage *msg, gpointer data) {
  Q_UNUSED(bus);

  VideoPlayer *that = (VideoPlayer *) data;

  gchar *debug = NULL;
  GError *err = NULL;

  switch (GST_MESSAGE_TYPE(msg)) {
  case GST_MESSAGE_EOS:
    that->stop();
    break;

  case GST_MESSAGE_ERROR:
    gst_message_parse_error (msg, &err, &debug);
    qWarning() << "Error" << err->message;

    emit that->error(err->message, err->code, debug);
    that->stop();

    if (err) {
      g_error_free (err);
    }

    if (debug) {
      g_free (debug);
    }

    break;

  default:
    break;
  }

  return TRUE;
}

void VideoPlayer::updateRequested() {
  update();
}
<|endoftext|>


<commit_before>#define BOOST_TEST_MODULE "MultiViewGeometry/Geometry/Point Tracks"

#include <DO/Sara/Core/DebugUtilities.hpp>
#include <DO/Sara/Core/StringFormat.hpp>
#include <DO/Sara/MultiViewGeometry/FeatureGraph.hpp>

#include <boost/foreach.hpp>
#include <boost/graph/graph_utility.hpp>
#include <boost/graph/incremental_components.hpp>
#include <boost/pending/disjoint_sets.hpp>
#include <boost/test/unit_test.hpp>

using namespace DO::Sara;

struct ConnectedComponents
{
  using Vertex = boost::graph_traits<FeatureGraph>::vertex_descriptor;
  using VertexIndex = boost::graph_traits<FeatureGraph>::vertices_size_type;

  using Rank = VertexIndex *;
  using Parent = Vertex *;

  using Components = boost::component_index<VertexIndex>;

  ConnectedComponents(FeatureGraph& graph)
    : g{graph}
    , rank{boost::num_vertices(graph)}
    , parent{boost::num_vertices(graph)}
  {
  }

  FeatureGraph& g;
  std::vector<Rank> rank;
  std::vector<Vertex> parent;
};

using DisjointSets = boost::disjoint_sets<ConnectedComponents::Rank,
                                          ConnectedComponents::Parent>;

BOOST_AUTO_TEST_CASE(test_feature_graph)
{
  auto g = FeatureGraph{};

  auto v1 = boost::add_vertex({0, 0}, g);
  auto v2 = boost::add_vertex({0, 1}, g);
  auto v3 = boost::add_vertex({1, 1}, g);
  auto v4 = boost::add_vertex({1, 1}, g);

  SARA_DEBUG << "g[v1] = " << format("(%d, %d)", g[v1].image_id, g[v1].local_id)
             << std::endl;
  SARA_DEBUG << "g[v2] = " << format("(%d, %d)", g[v2].image_id, g[v2].local_id)
             << std::endl;
  SARA_DEBUG << "g[v3] = " << format("(%d, %d)", g[v3].image_id, g[v3].local_id)
             << std::endl;
  SARA_DEBUG << "g[v4] = " << format("(%d, %d)", g[v4].image_id, g[v4].local_id)
             << std::endl;

  const auto [e1, b1] = boost::add_edge(v1, v4, g);
  const auto [e2, b2] = boost::add_edge(v2, v3, g);

  SARA_CHECK(e1);
  SARA_CHECK(e2);

  BOOST_CHECK(b1);
  BOOST_CHECK(b2);

  boost::print_graph(g, "");

  auto tracks = ConnectedComponents{g};
  //DisjointSets ds(tracks.rank[0], tracks.parent[0]);

  //boost::initialize_incremental_components(g, ds);
  //boost::incremental_components(g, ds);

  //ConnectedComponents::Components components(tracks.parent.begin(),
  //                                           tracks.parent.end());
  //// Iterate through the component indices
  //BOOST_FOREACH (ConnectedComponents::VertexIndex current_index, components)
  //{
  //  std::cout << "component " << current_index << " contains: ";

  //  // Iterate through the child vertex indices for [current_index]
  //  BOOST_FOREACH (ConnectedComponents::VertexIndex child_index,
  //                 components[current_index])
  //  {
  //    std::cout << child_index << " ";
  //  }

  //  std::cout << std::endl;
  //}
}
<commit_msg>MAINT: save work about incremental connected components.<commit_after>#define BOOST_TEST_MODULE "MultiViewGeometry/Geometry/Point Tracks"

#include <DO/Sara/Core/DebugUtilities.hpp>
#include <DO/Sara/Core/StringFormat.hpp>
#include <DO/Sara/MultiViewGeometry/FeatureGraph.hpp>

#include <boost/foreach.hpp>
#include <boost/graph/graph_utility.hpp>
#include <boost/graph/incremental_components.hpp>
#include <boost/pending/disjoint_sets.hpp>
#include <boost/test/unit_test.hpp>

using namespace DO::Sara;

struct ConnectedComponents
{
  using Vertex = boost::graph_traits<FeatureGraph>::vertex_descriptor;
  using VertexIndex = boost::graph_traits<FeatureGraph>::vertices_size_type;

  using Rank = VertexIndex *;
  using Parent = Vertex *;

  using Components = boost::component_index<VertexIndex>;

  ConnectedComponents(FeatureGraph& graph)
    : g{graph}
    , rank{boost::num_vertices(graph)}
    , parent{boost::num_vertices(graph)}
  {
  }

  FeatureGraph& g;
  std::vector<VertexIndex> rank;
  std::vector<Vertex> parent;
};

using DisjointSets = boost::disjoint_sets<ConnectedComponents::Rank,
                                          ConnectedComponents::Parent>;

BOOST_AUTO_TEST_CASE(test_connected_components)
{
  const int N = 6;
  FeatureGraph G(N);
  boost::add_edge(0, 1, G);
  boost::add_edge(1, 4, G);
  boost::add_edge(4, 0, G);
  boost::add_edge(2, 5, G);

  std::vector<int> c(num_vertices(G));
  int num = boost::connected_components(
      G, make_iterator_property_map(c.begin(),
                                    boost::get(boost::vertex_index, G), c[0]));

  std::cout << std::endl;
  std::cout << "Total number of components: " << num << std::endl;
  for (auto i = c.begin(); i != c.end(); ++i)
    std::cout << "Vertex " << i - c.begin() << " is in component " << *i
              << std::endl;
  std::cout << std::endl;
}

BOOST_AUTO_TEST_CASE(test_incremental_connected_components)
{
  using Vertex = boost::graph_traits<FeatureGraph>::vertex_descriptor;
  using VertexIndex = boost::graph_traits<FeatureGraph>::vertices_size_type;

  using Rank = VertexIndex*;
  using Parent = Vertex*;

  // constexpr auto VERTEX_COUNT = 6;
  // auto graph = FeatureGraph(VERTEX_COUNT);
  auto graph = FeatureGraph{};
  auto v0 = boost::add_vertex({0, 0}, graph);
  auto v1 = boost::add_vertex({0, 1}, graph);
  auto v2 = boost::add_vertex({0, 2}, graph);
  auto v3 = boost::add_vertex({1, 0}, graph);
  auto v4 = boost::add_vertex({1, 1}, graph);
  auto v5 = boost::add_vertex({1, 2}, graph);

  auto rank = std::vector<VertexIndex>(num_vertices(graph));
  auto parent = std::vector<Vertex>(num_vertices(graph));

  boost::disjoint_sets<Rank, Parent> ds(&rank[0], &parent[0]);

  boost::initialize_incremental_components(graph, ds);
  boost::incremental_components(graph, ds);

  boost::graph_traits<FeatureGraph>::edge_descriptor edge;
  bool flag;

  boost::tie(edge, flag) = boost::add_edge(v0, v1, graph);
  ds.union_set(v0, v1);

  boost::tie(edge, flag) = boost::add_edge(v1, v4, graph);
  ds.union_set(v1, v4);

  boost::tie(edge, flag) = boost::add_edge(v4, v0, graph);
  ds.union_set(v4, v0);

  boost::tie(edge, flag) = boost::add_edge(v2, v5, graph);
  ds.union_set(v2, v5);

  std::cout << "An undirected graph:" << std::endl;
  boost::print_graph(graph, boost::get(boost::vertex_index, graph));
  std::cout << std::endl;

  for (auto [v, v_end] = boost::vertices(graph); v != v_end; ++v) {
    std::cout << "representative[" << *v << "] = " <<
    ds.find_set(*v) << std::endl;
  }

  std::cout << std::endl;

  using Components = boost::component_index<VertexIndex>;

  Components components(parent.begin(), parent.end());

  // Iterate through the component indices
  for (auto c: components) {
    std::cout << "component " << c << " contains: ";

    // Iterate through the child vertex indices for [c]
    for(auto [child, child_end] = components[c]; child != child_end; ++child) {
      std::cout << *child << " ";
    }

    std::cout << std::endl;
  }
}
<|endoftext|>


<commit_before>// The MIT License (MIT)

// Copyright (c) 2014 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 JSONPP_DETAIL_UNICODE_HPP
#define JSONPP_DETAIL_UNICODE_HPP

#if defined(_WIN32)
#if !defined(WIN32_LEAN_AND_MEAN)
#define WIN32_LEAN_AND_MEAN 0xFEEDC0DE
#endif // WIN32_LEAN_AND_MEAN
#if !defined(NOMINMAX)
#define NOMINMAX 0xFEEDC0DE
#endif // NOMINMAX
#include <windows.h>
#endif
#include <string>
#include <stdexcept>
#include <system_error>
#include <cerrno>

namespace json {
inline namespace v1 {
namespace detail {
#if defined(_WIN32)
inline std::u16string utf8_to_utf16(const std::string& utf8) {
    static_assert(sizeof(wchar_t) == sizeof(char16_t), "wchar_t must be 16 bits");
    std::wstring temp;
    auto required_size = ::MultiByteToWideChar(CP_UTF8, 0, &utf8[0], static_cast<int>(utf8.size()), nullptr, 0);
    temp.resize(required_size);
    if(::MultiByteToWideChar(CP_UTF8, 0, &utf8[0], static_cast<int>(utf8.size()), &temp[0], required_size) == 0) {
        throw std::runtime_error("unable to convert from UTF-8 to UTF-16");
    }
    return { temp.begin(), temp.end() };
}
#else
inline std::u16string utf8_to_utf16(const std::string& utf8) {
    std::u16string result;
    using size_type = decltype(utf8.size());
    std::invalid_argument invalid_utf8("Invalid UTF-8 string given");
    size_type i = 0;
    while(i < utf8.size()) {
        char32_t codepoint;
        size_type iterations = 0;
        unsigned char byte = utf8[i++];
        if(byte <= 0x7F) {
            codepoint = byte;
        }
        else if(byte <= 0xBF) {
            throw invalid_utf8;
        }
        else if(byte <= 0xDF) {
            codepoint = byte & 0x1F;
            iterations = 1;
        }
        else if(byte <= 0xEF) {
            codepoint = byte & 0x0F;
            iterations = 2;
        }
        else if(byte <= 0xF7) {
            codepoint = byte & 0x07;
            iterations = 3;
        }
        else {
            throw invalid_utf8;
        }

        for(size_type j = 0; j < iterations; ++j) {
            if(i == utf8.size()) {
                throw invalid_utf8;
            }
            unsigned char next_byte = utf8[i++];
            if(next_byte < 0x80 || next_byte > 0xBF) {
                throw invalid_utf8;
            }

            codepoint = (codepoint << 6) + (next_byte & 0x3F);
        }
        if(codepoint > 0x10FFFF || (codepoint >= 0xD800 && codepoint <= 0xDFFF)) {
            throw invalid_utf8;
        }

        if(codepoint <= 0xFFFF) {
            result.push_back(codepoint);
        }
        else {
            codepoint -= 0x10000;
            result.push_back((codepoint >> 10) + 0xD800);
            result.push_back((codepoint & 0x3FF) + 0xDC00);
        }
    }

    return result;
}
#endif
} // detail
} // v1
} // json

#if defined(WIN32_LEAN_AND_MEAN) && WIN32_LEAN_AND_MEAN == 0xFEEDC0DE
#undef WIN32_LEAN_AND_MEAN
#endif

#if defined(NOMINMAX) && NOMINMAX == 0xFEEDC0DE
#undef NOMINMAX
#endif

#endif // JSONPP_DETAIL_UNICODE_HPP
<commit_msg>Better way of undefining flags.<commit_after>// The MIT License (MIT)

// Copyright (c) 2014 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 JSONPP_DETAIL_UNICODE_HPP
#define JSONPP_DETAIL_UNICODE_HPP

#if defined(_WIN32)
#define JSONPP_CLEAN_UP_DEFINES 0
#if !defined(WIN32_LEAN_AND_MEAN)
#define WIN32_LEAN_AND_MEAN
#undef JSONPP_CLEAN_UP_DEFINES
#define JSONPP_CLEAN_UP_DEFINES 1
#endif // WIN32_LEAN_AND_MEAN
#if !defined(NOMINMAX)
#undef JSONPP_CLEAN_UP_DEFINES
#define JSONPP_CLEAN_UP_DEFINES 2
#define NOMINMAX
#endif // NOMINMAX
#include <windows.h>
#endif
#include <string>
#include <stdexcept>
#include <system_error>
#include <cerrno>

namespace json {
inline namespace v1 {
namespace detail {
#if defined(_WIN32)
inline std::u16string utf8_to_utf16(const std::string& utf8) {
    static_assert(sizeof(wchar_t) == sizeof(char16_t), "wchar_t must be 16 bits");
    std::wstring temp;
    auto required_size = ::MultiByteToWideChar(CP_UTF8, 0, &utf8[0], static_cast<int>(utf8.size()), nullptr, 0);
    temp.resize(required_size);
    if(::MultiByteToWideChar(CP_UTF8, 0, &utf8[0], static_cast<int>(utf8.size()), &temp[0], required_size) == 0) {
        throw std::runtime_error("unable to convert from UTF-8 to UTF-16");
    }
    return { temp.begin(), temp.end() };
}
#else
inline std::u16string utf8_to_utf16(const std::string& utf8) {
    std::u16string result;
    using size_type = decltype(utf8.size());
    std::invalid_argument invalid_utf8("Invalid UTF-8 string given");
    size_type i = 0;
    while(i < utf8.size()) {
        char32_t codepoint;
        size_type iterations = 0;
        unsigned char byte = utf8[i++];
        if(byte <= 0x7F) {
            codepoint = byte;
        }
        else if(byte <= 0xBF) {
            throw invalid_utf8;
        }
        else if(byte <= 0xDF) {
            codepoint = byte & 0x1F;
            iterations = 1;
        }
        else if(byte <= 0xEF) {
            codepoint = byte & 0x0F;
            iterations = 2;
        }
        else if(byte <= 0xF7) {
            codepoint = byte & 0x07;
            iterations = 3;
        }
        else {
            throw invalid_utf8;
        }

        for(size_type j = 0; j < iterations; ++j) {
            if(i == utf8.size()) {
                throw invalid_utf8;
            }
            unsigned char next_byte = utf8[i++];
            if(next_byte < 0x80 || next_byte > 0xBF) {
                throw invalid_utf8;
            }

            codepoint = (codepoint << 6) + (next_byte & 0x3F);
        }
        if(codepoint > 0x10FFFF || (codepoint >= 0xD800 && codepoint <= 0xDFFF)) {
            throw invalid_utf8;
        }

        if(codepoint <= 0xFFFF) {
            result.push_back(codepoint);
        }
        else {
            codepoint -= 0x10000;
            result.push_back((codepoint >> 10) + 0xD800);
            result.push_back((codepoint & 0x3FF) + 0xDC00);
        }
    }

    return result;
}
#endif
} // detail
} // v1
} // json

#if defined(JSONPP_CLEAN_UP_DEFINES)
#if JSONPP_CLEAN_UP_DEFINES >= 1
#undef WIN32_LEAN_AND_MEAN
#endif
#if JSONPP_CLEAN_UP_DEFINES >= 2
#undef NOMINMAX
#endif
#undef JSONPP_CLEAN_UP_DEFINES
#endif

#endif // JSONPP_DETAIL_UNICODE_HPP
<|endoftext|>


<commit_before>#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <vector>
#include <iostream>

#include "genome.h"

using namespace std;

int main(int argc, const char **argv)
{
 	if(argc != 4)
	{
		cout<<"usage: " << endl;
		cout<<"       " << argv[0] << " RPKM2TPM <in-gtf-file> <out-gtf-file>"<<endl;
		cout<<"       " << argv[0] << " FPKM2TPM <in-gtf-file> <out-gtf-file>"<<endl;
		cout<<"       " << argv[0] << " format <in-gtf-file> <out-gtf-file>"<<endl;
		cout<<"       " << argv[0] << " filter <min-transcript-coverage> <in-gtf-file> <out-gtf-file>"<<endl;
		return 0;
	}

	if(string(argv[1]) == "FPKM2TPM")
	{
		genome gm(argv[2]);
		gm.assign_TPM_by_FPKM();
		gm.write(argv[3]);
	}

	if(string(argv[1]) == "RPKM2TPM")
	{
		genome gm(argv[2]);
		gm.assign_TPM_by_RPKM();
		gm.write(argv[3]);
	}

	if(string(argv[1]) == "format")
	{
		genome gm(argv[2]);
		gm.write(argv[3]);
	}

	if(string(argv[1]) == "filter")
	{
		double c = atof(argv[2]);
		genome gm(argv[3]);
		gm.filter_low_coverage_transcripts(c);
		gm.write(argv[4]);
	}

    return 0;
}
<commit_msg>update<commit_after>#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <vector>
#include <iostream>

#include "genome.h"

using namespace std;

int main(int argc, const char **argv)
{
 	if(argc == 1)
	{
		cout<<"usage: " << endl;
		cout<<"       " << argv[0] << " RPKM2TPM <in-gtf-file> <out-gtf-file>"<<endl;
		cout<<"       " << argv[0] << " FPKM2TPM <in-gtf-file> <out-gtf-file>"<<endl;
		cout<<"       " << argv[0] << " format <in-gtf-file> <out-gtf-file>"<<endl;
		cout<<"       " << argv[0] << " filter <min-transcript-coverage> <in-gtf-file> <out-gtf-file>"<<endl;
		return 0;
	}

	if(string(argv[1]) == "FPKM2TPM")
	{
		genome gm(argv[2]);
		gm.assign_TPM_by_FPKM();
		gm.write(argv[3]);
	}

	if(string(argv[1]) == "RPKM2TPM")
	{
		genome gm(argv[2]);
		gm.assign_TPM_by_RPKM();
		gm.write(argv[3]);
	}

	if(string(argv[1]) == "format")
	{
		genome gm(argv[2]);
		gm.write(argv[3]);
	}

	if(string(argv[1]) == "filter")
	{
		double c = atof(argv[2]);
		genome gm(argv[3]);
		gm.filter_low_coverage_transcripts(c);
		gm.write(argv[4]);
	}

    return 0;
}
<|endoftext|>


<commit_before>
#include "DemoPipeline.h"

#include <glbinding/gl/enum.h>

#include <gloperate/gloperate.h>

#include <gloperate/stages/base/TextureLoadStage.h>
#include <gloperate/stages/base/BasicFramebufferStage.h>
#include <gloperate/stages/base/FramebufferStage.h>
#include <gloperate/stages/base/TextureStage.h>
#include <gloperate/stages/base/ProgramStage.h>
#include <gloperate/stages/base/RenderPassStage.h>
#include <gloperate/stages/base/RasterizationStage.h>
#include <gloperate/stages/base/ClearStage.h>
#include <gloperate/stages/base/ShapeStage.h>
#include <gloperate/stages/base/TimerStage.h>
#include <gloperate/stages/base/TransformStage.h>
#include <gloperate/stages/navigation/TrackballStage.h>
#include <gloperate/rendering/Shape.h>
#include <gloperate/rendering/Quad.h>

CPPEXPOSE_COMPONENT(DemoPipeline, gloperate::Stage)

using namespace cppexpose;
using namespace gloperate;

DemoPipeline::DemoPipeline(Environment * environment, const std::string & name)
: Pipeline(environment, "DemoPipeline", name)
, renderInterface(this)
, shape("shape", this, ShapeType::Box)
, texture("texture", this)
, angle("angle", this, 0.0f)
, rotate("rotate", this, false)
, color("color", this, Color(255, 255, 255, 255))
, m_timer(cppassist::make_unique<TimerStage>(environment, "Timer"))
, m_trackball(cppassist::make_unique<TrackballStage>(environment, "Trackball"))
, m_shape(cppassist::make_unique<ShapeStage>(environment, "Shape"))
, m_texture(cppassist::make_unique<TextureLoadStage>(environment, "Texture"))
, m_framebuffer(cppassist::make_unique<BasicFramebufferStage>(environment, "Framebuffer"))
, m_clear(cppassist::make_unique<ClearStage>(environment, "Clear"))
, m_shapeTransform(cppassist::make_unique<TransformStage>(environment, "ShapeTransform"))
, m_shapeProgram(cppassist::make_unique<ProgramStage>(environment, "ShapeProgram"))
, m_shapeRenderPass(cppassist::make_unique<RenderPassStage>(environment, "ShapeRenderPass"))
, m_shapeRasterization(cppassist::make_unique<RasterizationStage>(environment, "ShapeRasterization"))
, m_colorizeProgram(cppassist::make_unique<ProgramStage>(environment, "ColorizeProgram"))
, m_colorizeRenderPass(cppassist::make_unique<RenderPassStage>(environment, "ColorizeRenderPass"))
, m_colorizeRasterization(cppassist::make_unique<RasterizationStage>(environment, "ColorizeRasterization"))
{
    // Get data path
    std::string dataPath = gloperate::dataPath();

    // Setup parameters
    texture = dataPath + "/gloperate/textures/gloperate-logo.glraw";

    angle.setOption("minimumValue", 0.0f);
    angle.setOption("maximumValue", 6.3f);

    rotate.valueChanged.connect(this, &DemoPipeline::onRotateChanged);

    // Timer stage
    addStage(m_timer.get());
    m_timer->interval = 6.3f;

    // Trackball stage
    addStage(m_trackball.get());
    m_trackball->viewport << renderInterface.deviceViewport;

    // Shape stage
    addStage(m_shape.get());
    m_shape->shapeType << this->shape;
    m_shape->width     = 1.0f;
    m_shape->height    = 1.0f;
    m_shape->depth     = 1.0f;
    m_shape->radius    = 1.0f;
    m_shape->texCoords = true;

    // Texture loader stage
    addStage(m_texture.get());
    m_texture->filename << texture;

    // Framebuffer stage
    addStage(m_framebuffer.get());
    m_framebuffer->viewport << renderInterface.deviceViewport;

    // Clear stage
    addStage(m_clear.get());
    m_clear->renderInterface.targetFBO << m_framebuffer->fbo;
    m_clear->renderInterface.deviceViewport << renderInterface.deviceViewport;
    m_clear->renderInterface.backgroundColor = glm::vec4(0.0f, 0.0f, 0.0f, 1.0f);
    m_clear->colorTexture << m_framebuffer->colorTexture;
    m_clear->createInput("renderPass") << m_shapeRenderPass->renderPass;

    // Transform stage for shape
    addStage(m_shapeTransform.get());
    m_shapeTransform->rotationAngle << angle;

    // Program stage for shape
    addStage(m_shapeProgram.get());
    *m_shapeProgram->createInput<cppassist::FilePath>("vertexShader")   = dataPath + "/gloperate/shaders/geometry/geometry.vert";
    *m_shapeProgram->createInput<cppassist::FilePath>("fragmentShader") = dataPath + "/gloperate/shaders/geometry/geometry.frag";

    // Render pass stage for shape
    addStage(m_shapeRenderPass.get());
    m_shapeRenderPass->culling = false;
    m_shapeRenderPass->drawable << m_shape->drawable;
    m_shapeRenderPass->program << m_shapeProgram->program;
    m_shapeRenderPass->camera << m_trackball->camera;
    m_shapeRenderPass->modelMatrix << m_shapeTransform->modelMatrix;
    m_shapeRenderPass->createInput("color") << this->color;
    m_shapeRenderPass->createInput("tex0") << m_texture->texture;

    // Rasterization stage for shape
    addStage(m_shapeRasterization.get());
    m_shapeRasterization->renderInterface.targetFBO << m_clear->fboOut;
    m_shapeRasterization->renderInterface.deviceViewport << renderInterface.deviceViewport;
    m_shapeRasterization->drawable << m_shapeRenderPass->renderPass;
    m_shapeRasterization->colorTexture << m_clear->colorTextureOut;

    // Colorize program stage
    addStage(m_colorizeProgram.get());
    *m_colorizeProgram->createInput<cppassist::FilePath>("shader1") = dataPath + "/gloperate/shaders/geometry/screenaligned.vert";
    *m_colorizeProgram->createInput<cppassist::FilePath>("shader2") = dataPath + "/gloperate/shaders/demo/colorize.frag";

    // Colorize render pass stage
    addStage(m_colorizeRenderPass.get());
    // m_colorizeRenderPass->drawable is set in onContextInit()
    m_colorizeRenderPass->program << m_colorizeProgram->program;
    m_colorizeRenderPass->culling = false;
    m_colorizeRenderPass->createInput("color") << this->color;
    m_colorizeRenderPass->createInput("source") << m_shapeRasterization->colorTextureOut;

    // Colorize rasterization stage
    addStage(m_colorizeRasterization.get());
    m_colorizeRasterization->renderInterface.targetFBO << renderInterface.targetFBO;
    m_colorizeRasterization->renderInterface.deviceViewport << renderInterface.deviceViewport;
    m_colorizeRasterization->drawable << m_colorizeRenderPass->renderPass;

    // Outputs
    renderInterface.rendered << m_colorizeRasterization->renderInterface.rendered;

    // Start rotation
    rotate = true;
}

DemoPipeline::~DemoPipeline()
{
}

void DemoPipeline::onContextInit(AbstractGLContext * context)
{
    Pipeline::onContextInit(context);

    m_quad = cppassist::make_unique<Quad>(2.0f);

    m_colorizeRenderPass->drawable = m_quad.get();
}

void DemoPipeline::onContextDeinit(AbstractGLContext * context)
{
    Pipeline::onContextDeinit(context);

    m_quad = nullptr;
}

void DemoPipeline::onRotateChanged(const bool & rotate)
{
    if (rotate) {
        m_timer->virtualTime = *angle;
        angle << m_timer->virtualTime;
        m_timer->timeDelta << renderInterface.timeDelta;
    } else {
        angle.disconnect();
        angle = *m_timer->virtualTime;
        m_timer->timeDelta.disconnect();
    }
}
<commit_msg>Finish DemoPipeline<commit_after>
#include "DemoPipeline.h"

#include <glbinding/gl/enum.h>

#include <gloperate/gloperate.h>

#include <gloperate/stages/base/TextureLoadStage.h>
#include <gloperate/stages/base/BasicFramebufferStage.h>
#include <gloperate/stages/base/FramebufferStage.h>
#include <gloperate/stages/base/TextureStage.h>
#include <gloperate/stages/base/ProgramStage.h>
#include <gloperate/stages/base/RenderPassStage.h>
#include <gloperate/stages/base/RasterizationStage.h>
#include <gloperate/stages/base/ClearStage.h>
#include <gloperate/stages/base/ShapeStage.h>
#include <gloperate/stages/base/TimerStage.h>
#include <gloperate/stages/base/TransformStage.h>
#include <gloperate/stages/navigation/TrackballStage.h>
#include <gloperate/rendering/Shape.h>
#include <gloperate/rendering/Quad.h>

CPPEXPOSE_COMPONENT(DemoPipeline, gloperate::Stage)

using namespace cppexpose;
using namespace gloperate;

DemoPipeline::DemoPipeline(Environment * environment, const std::string & name)
: Pipeline(environment, "DemoPipeline", name)
, renderInterface(this)
, shape("shape", this, ShapeType::Box)
, texture("texture", this)
, angle("angle", this, 0.0f)
, rotate("rotate", this, false)
, color("color", this, Color(255, 255, 255, 255))
, m_timer(cppassist::make_unique<TimerStage>(environment, "Timer"))
, m_trackball(cppassist::make_unique<TrackballStage>(environment, "Trackball"))
, m_shape(cppassist::make_unique<ShapeStage>(environment, "Shape"))
, m_texture(cppassist::make_unique<TextureLoadStage>(environment, "Texture"))
, m_framebuffer(cppassist::make_unique<BasicFramebufferStage>(environment, "Framebuffer"))
, m_clear(cppassist::make_unique<ClearStage>(environment, "Clear"))
, m_shapeTransform(cppassist::make_unique<TransformStage>(environment, "ShapeTransform"))
, m_shapeProgram(cppassist::make_unique<ProgramStage>(environment, "ShapeProgram"))
, m_shapeRenderPass(cppassist::make_unique<RenderPassStage>(environment, "ShapeRenderPass"))
, m_shapeRasterization(cppassist::make_unique<RasterizationStage>(environment, "ShapeRasterization"))
, m_colorizeProgram(cppassist::make_unique<ProgramStage>(environment, "ColorizeProgram"))
, m_colorizeRenderPass(cppassist::make_unique<RenderPassStage>(environment, "ColorizeRenderPass"))
, m_colorizeRasterization(cppassist::make_unique<RasterizationStage>(environment, "ColorizeRasterization"))
{
    // Get data path
    std::string dataPath = gloperate::dataPath();

    // Setup parameters
    texture = dataPath + "/gloperate/textures/gloperate-logo.glraw";

    angle.setOption("minimumValue", 0.0f);
    angle.setOption("maximumValue", 2.0f * glm::pi<float>());
    angle.setOption("updateOnDrag", true);

    rotate.valueChanged.connect(this, &DemoPipeline::onRotateChanged);

    // Timer stage
    addStage(m_timer.get());
    m_timer->interval = 2.0f * glm::pi<float>();

    // Trackball stage
    addStage(m_trackball.get());
    m_trackball->viewport << renderInterface.deviceViewport;

    // Shape stage
    addStage(m_shape.get());
    m_shape->shapeType << this->shape;
    m_shape->width     = 1.0f;
    m_shape->height    = 1.0f;
    m_shape->depth     = 1.0f;
    m_shape->radius    = 1.0f;
    m_shape->texCoords = true;

    // Texture loader stage
    addStage(m_texture.get());
    m_texture->filename << texture;

    // Framebuffer stage
    addStage(m_framebuffer.get());
    m_framebuffer->viewport << renderInterface.deviceViewport;

    // Clear stage
    addStage(m_clear.get());
    m_clear->renderInterface.targetFBO << m_framebuffer->fbo;
    m_clear->renderInterface.deviceViewport << renderInterface.deviceViewport;
    m_clear->renderInterface.backgroundColor = glm::vec4(0.0f, 0.0f, 0.0f, 1.0f);
    m_clear->colorTexture << m_framebuffer->colorTexture;
    m_clear->createInput("renderPass") << m_shapeRenderPass->renderPass;

    // Transform stage for shape
    addStage(m_shapeTransform.get());
    m_shapeTransform->rotationAngle << angle;

    // Program stage for shape
    addStage(m_shapeProgram.get());
    *m_shapeProgram->createInput<cppassist::FilePath>("vertexShader")   = dataPath + "/gloperate/shaders/geometry/geometry.vert";
    *m_shapeProgram->createInput<cppassist::FilePath>("fragmentShader") = dataPath + "/gloperate/shaders/geometry/geometry.frag";

    // Render pass stage for shape
    addStage(m_shapeRenderPass.get());
    m_shapeRenderPass->culling = false;
    m_shapeRenderPass->drawable << m_shape->drawable;
    m_shapeRenderPass->program << m_shapeProgram->program;
    m_shapeRenderPass->camera << m_trackball->camera;
    m_shapeRenderPass->modelMatrix << m_shapeTransform->modelMatrix;
    m_shapeRenderPass->createInput("color") << this->color;
    m_shapeRenderPass->createInput("tex0") << m_texture->texture;

    // Rasterization stage for shape
    addStage(m_shapeRasterization.get());
    m_shapeRasterization->renderInterface.targetFBO << m_clear->fboOut;
    m_shapeRasterization->renderInterface.deviceViewport << renderInterface.deviceViewport;
    m_shapeRasterization->drawable << m_shapeRenderPass->renderPass;
    m_shapeRasterization->colorTexture << m_clear->colorTextureOut;

    // Colorize program stage
    addStage(m_colorizeProgram.get());
    *m_colorizeProgram->createInput<cppassist::FilePath>("shader1") = dataPath + "/gloperate/shaders/geometry/screenaligned.vert";
    *m_colorizeProgram->createInput<cppassist::FilePath>("shader2") = dataPath + "/gloperate/shaders/demo/colorize.frag";

    // Colorize render pass stage
    addStage(m_colorizeRenderPass.get());
    // m_colorizeRenderPass->drawable is set in onContextInit()
    m_colorizeRenderPass->program << m_colorizeProgram->program;
    m_colorizeRenderPass->culling = false;
    m_colorizeRenderPass->createInput("color") << this->color;
    m_colorizeRenderPass->createInput("source") << m_shapeRasterization->colorTextureOut;

    // Colorize rasterization stage
    addStage(m_colorizeRasterization.get());
    m_colorizeRasterization->renderInterface.targetFBO << renderInterface.targetFBO;
    m_colorizeRasterization->renderInterface.deviceViewport << renderInterface.deviceViewport;
    m_colorizeRasterization->drawable << m_colorizeRenderPass->renderPass;

    // Outputs
    renderInterface.rendered << m_colorizeRasterization->renderInterface.rendered;

    // Start rotation
    rotate = true;
}

DemoPipeline::~DemoPipeline()
{
}

void DemoPipeline::onContextInit(AbstractGLContext * context)
{
    Pipeline::onContextInit(context);

    m_quad = cppassist::make_unique<Quad>(2.0f);

    m_colorizeRenderPass->drawable = m_quad.get();
}

void DemoPipeline::onContextDeinit(AbstractGLContext * context)
{
    Pipeline::onContextDeinit(context);

    m_quad = nullptr;
}

void DemoPipeline::onRotateChanged(const bool & rotate)
{
    // Switch rotation on
    if (rotate)
    {
        // Set timer to current rotation value
        m_timer->virtualTime = *angle;

        // Connect angle to timer and resume timer
        angle << m_timer->virtualTime;
        m_timer->timeDelta << renderInterface.timeDelta;
    }

    // Switch rotation off
    else
    {
        // Set angle to current timer value
        angle.disconnect();
        angle = *m_timer->virtualTime;

        // Stop time
        m_timer->timeDelta.disconnect();
    }
}
<|endoftext|>