<commit_before>/*
 * File:   main.cpp
 * Author: vlad
 *
 * Created on December 12, 2013, 10:38 PM
 */

#include <iostream>
#include <cmath>

#include "qpp.h"
#include "matlab.h" // support for MATLAB

// TODO: expandout function
// TODO: dyad function
// TODO: proj (dya) function
// TODO: ip (inner product function) function, make it general to return matrices
// TODO: check that everything works for expressions in ALL FILES!!!!
// TODO: Error class
// TODO: change all for(s) to column major order
// TODO: use .data() raw pointer instead of looping
// TODO: use a Singleton Engine class (with static members) to get rid of qpp.cpp
// TODO: look at unaryExpr for functors!!!!
// TODO: test that everything works with GenProducts!
// TODO: implement selfadjoint eigensolver
// TODO: re-write everything so it works only for matrices (not expressions)

using namespace std;

using namespace qpp;
using namespace qpp::types;

int myfunc(const cplx &z)
{
	return std::abs(z);
}

template<typename Derived>
void printFirstRow(const Derived& x)
{
	cout << x.row(0) << endl;
}

//int main(int argc, char **argv)
int main()
{
	_init();

	std::cout << std::fixed; // use fixed format for nice formatting
//	std::cout << std::scientific;
	std::cout << std::setprecision(4); // only for fixed or scientific modes

	cout << "Starting qpp..." << endl;

	// MATLAB interface testing
	cmat randu = rand_unitary(3);
	cout << endl;
	displn(randu);

	saveMATLAB<cplx>(randu, "/Users/vlad/tmp/test.mat", "randu", "w");
	cmat res = loadMATLAB<cplx>("/Users/vlad/tmp/test.mat", "randu");
	cout << endl;
	displn(randu - res);

	// functor testing
	auto lambda = [](const cplx& z)->int
	{	return abs(z);};

	cmat mat1(3, 3);
	mat1 << 1, -2.56, 335.2321, -4, 5.244, -6.1, 7, -8, 9. + 2.78 * ct::ii;

	cout << endl;
	displn(mat1);

	cout << endl;
	displn(fun<cmat, int>(mat1 * mat1, lambda));

	cout << endl;
	displn(fun<cmat>(mat1 * mat1, myfunc));

	// other functions
	cout << endl;
	cmat mat11 = mat1 * mat1;
	displn(kron((cmat) (mat1 * mat1), cmat(mat1 * mat1)));

	mat11 = cmat::Random(3, 3);
	mat11 = mat11 + adjoint(mat11);
	cmat mat2(2, 2);
	mat2 << 1, ct::ii, -ct::ii, 1;
	// eigenvalue test
	cout << endl << hevals<cmat>(mat11) << endl;
	displn(
			mat11 * hevects(mat11).col(0)
					- (hevals(mat11)(0)) * hevects(mat11).col(0));

	cout << endl << mat11 << endl << endl;
	printFirstRow(mat11);

	cout << endl;
	displn(transpose(mat11));
	cout << typeid(transpose(mat11)).name() << endl<<endl;

	//displn(transpose(mat11 * mat11));
	//cout << typeid(transpose(mat11*mat11)).name() << endl;

	cout << endl << "Exiting qpp..." << endl;
}
<commit_msg>commit<commit_after>/*
 * File:   main.cpp
 * Author: vlad
 *
 * Created on December 12, 2013, 10:38 PM
 */

#include <iostream>
#include <cmath>

#include "qpp.h"
#include "matlab.h" // support for MATLAB

// TODO: expandout function
// TODO: dyad function
// TODO: proj (dya) function
// TODO: ip (inner product function) function, make it general to return matrices
// TODO: check that everything works for expressions in ALL FILES!!!!
// TODO: Error class
// TODO: change all for(s) to column major order
// TODO: use .data() raw pointer instead of looping
// TODO: use a Singleton Engine class (with static members) to get rid of qpp.cpp
// TODO: look at unaryExpr for functors!!!!
// TODO: test that everything works with GenProducts!
// TODO: implement selfadjoint eigensolver
// TODO: re-write everything so it works only for matrices (not expressions)

using namespace std;

using namespace qpp;
using namespace qpp::types;

int myfunc(const cplx &z)
{
	return std::abs(z);
}

template<typename Derived>
void printFirstRow(const Derived& x)
{
	cout << x.row(0) << endl;
}

//int main(int argc, char **argv)
int main()
{
	_init();

	std::cout << std::fixed; // use fixed format for nice formatting
//	std::cout << std::scientific;
	std::cout << std::setprecision(4); // only for fixed or scientific modes

	cout << "Starting qpp..." << endl;

	// MATLAB interface testing
	cmat randu = rand_unitary(3);
	cout << endl;
	displn(randu);

	saveMATLAB<cplx>(randu, "/Users/vlad/tmp/test.mat", "randu", "w");
	cmat res = loadMATLAB<cplx>("/Users/vlad/tmp/test.mat", "randu");
	cout << endl;
	displn(randu - res);

	// functor testing
	auto lambda = [](const cplx& z)->int
	{	return abs(z);};

	cmat mat1(3, 3);
	mat1 << 1, -2.56, 335.2321, -4, 5.244, -6.1, 7, -8, 9. + 2.78 * ct::ii;

	cout << endl;
	displn(mat1);

	cout << endl;
	displn(fun<cmat, int>(mat1 * mat1, lambda));

	cout << endl;
	displn(fun<cmat>(mat1 * mat1, myfunc));

	// other functions
	cout << endl;
	cmat mat11 = mat1 * mat1;
	displn(kron((cmat) (mat1 * mat1), cmat(mat1 * mat1)));

	mat11 = cmat::Random(3, 3);
	mat11 = mat11 + adjoint(mat11);
	cmat mat2(2, 2);
	mat2 << 1, ct::ii, -ct::ii, 1;
	// eigenvalue test
	cout << endl << hevals<cmat>(mat11) << endl;
	displn(
			mat11 * hevects(mat11).col(0)
					- (hevals(mat11)(0)) * hevects(mat11).col(0));

	cout << endl << mat11 << endl << endl;
	printFirstRow(mat11);

	cout << endl;
	displn(transpose(mat11));
	cout << typeid(transpose(mat11)).name() << endl<<endl;

	displn(transpose(mat11 * mat11));
	cout << typeid(transpose(mat11*mat11)).name() << endl;

	cout << endl << "Exiting qpp..." << endl;
}
<|endoftext|>


<commit_before>#include <fstream>
#include <vector>
#include <locale.h>
#include "LogEntryFilter.h"
#include "LogEntryRootFilter.h"
#include "LogEntryMessageFilter.h"
#include "LogEntryTimeFilter.h"
#include "FileUtils.hpp"
#include "CommandLineUtils.hpp"
#include "LogEntryParser.h"
#include "Rearranger.h"
#include "LogEntryFilterFactory.h"
#include "alphanum.hpp"

using namespace std;

#ifdef _WIN32
#define kPathSeparator '\\'
#else
#define kPathSeparator '/'
#endif

void sortFiles(vector<string> &files);

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

    setlocale(LC_ALL, "");
    int ret = 0;
    if (argc == 1 || cmdOptionExists(argv, argv + argc, "--help")) {
        cout << "LogUtil: A handy tool to merge/filter log files.\ngit: https://github.com/yhd4711499/LogUtil.git\n\n";
        cout << "usage :\tlogutil";
        cout << "\t[-d] [-f] [-o] [-r] [-start] [-end]\n\n";
        cout << "\t-d\tmerge all files under the directory.\n";
        cout << "\t-f\tsort the log file.\n";
        cout << "\t-o\toutput file. [<file_or_dirname>_ALL.log] will be used if not set.\n\t\tor [std] to print output to stdout.\n";
        cout << "\t-r\tfilter rules.\n";
        cout << "\nAdvanced usage:\n\n";
        cout << "\t-start/end\tshow logs between [start , end), \"YYYY-mm-dd hh:MM:SS.SSS\" .\n\n";
        cout << "examples :\n";
        cout << "\tlogutil ~/LogDir\n";
        cout << "\tlogutil ~/LogDir -o std\n";
        cout << "\tlogutil -d ~/LogDir\n";
        cout << "\tlogutil -d ~/LogDir -start 2016-06-18\n";
        cout << "\tlogutil -d ~/LogDir -start 2016-06-18 -end 2016-06-19\n";
        cout << "\tlogutil -d ~/LogDir -r ~/block_rules.json\n";
        cout << "\tlogutil -d ~/LogDir -o ~/Log_ALL.log\n";
        cout << "\tlogutil -f ~/LogDir/log.log -o ~/Log_ALL.log\n";
        return 0;
    }
    vector<string> files;
    char *dirname = nullptr, *filename = nullptr, *outputFilename = nullptr;

    if (argc == 2) {
        if (isFile(argv[1])) {
            filename = argv[1];
        } else {
            dirname = argv[1];
        }
    } else {
        dirname = getCmdOption(argv, argv + argc, "-d");
        filename = getCmdOption(argv, argv + argc, "-f");
    }

    if (filename) {
        files.push_back(filename);
    }

    if (dirname) {
        ret = listFiles(dirname, files);
        if (ret != 0) {
            cerr << "Failed to visit dir : " << dirname << endl;
            return ret;
        }
    }

    if (files.size() > 1) {
        sortFiles(files);
    }

    char *filterRultFile = getCmdOption(argv, argv + argc, "-r");
    char *startTime = getCmdOption(argv, argv + argc, "-start");
    char *endTime = getCmdOption(argv, argv + argc, "-end");

    outputFilename = getCmdOption(argv, argv + argc, "-o");
    if (!strncmp(outputFilename, "std", 3)) {
        outputFilename = NULL;
    } else if (!outputFilename) {
        if (filename) {
            string folderName, filenameWoDir;
            splitFilename(string(filename), folderName, filenameWoDir);

            string newFilename(folderName + kPathSeparator + "All_" + filenameWoDir);
            outputFilename = new char[newFilename.length() + 1];
            strcpy(outputFilename, newFilename.c_str());
        }
        else if (dirname) {
            string newFilename(string(dirname) + kPathSeparator + "All.log");
            outputFilename = new char[newFilename.length() + 1];
            strcpy(outputFilename, newFilename.c_str());
        }
    }

    LogEntryFilterFactory::registerCreator("root", LogEntryRootFilter::creator);
    LogEntryFilterFactory::registerCreator("log", LogEntryMessageFilter::creator);
    LogEntryFilterFactory::registerCreator("time", LogEntryTimeFilter::creator);

    LogEntryParser parser;

    if (filterRultFile) {
        auto fileRuleStream = fstream(filterRultFile);
        json fileRuleJson;
        fileRuleStream >> fileRuleJson;
        parser.addFilter(LogEntryFilterFactory::create(fileRuleJson));
    }

    if (startTime || endTime) {
        string start = startTime ? (string) startTime : "";
        string end = endTime ? (string) endTime : "";
        LogEntryTimeFilter *filter = new LogEntryTimeFilter(
                LogEntryTimeFilter::getDate(start),
                LogEntryTimeFilter::getTime(start),
                LogEntryTimeFilter::getDate(end),
                LogEntryTimeFilter::getTime(end),
                true);
        parser.addFilter(filter);
    }

    vector<LogEntry *> entries;

    for (string file : files) {
        try {
            parser.parseFile(file, entries);
        } catch (runtime_error &error) {
            cerr << "Failed to parse file : " << file << ". error: " << error.what() << endl;
        } catch (...) {
            cerr << "Failed to parse file : " << file << endl;
        }
    }

    Rearranger rearranger;
    rearranger.sort(entries);

    int index = 1;
    for (LogEntry *entry : entries) {
        entry->line.orderedIndex = index;
        index += entry->line.lines.size();
    }

    if (outputFilename) {
        ofstream os(outputFilename);
        for (LogEntry *entry : entries) {
            os << *entry;
        }
        printf("All done. File saved to %s\n", outputFilename);
    } else {
        for (LogEntry *entry : entries) {
            cout << *entry;
        }
    }

    return 0;
}

void sortFiles(vector<string> &files) {
    /*
     * A little tricky here: files must be sorted in natural order on filename.
     * Or output result might be mis-ordered on log entries with same timestamp but stored in separate files.
     *
     * For example.
     *
     * We'ev two logs files:
     *
     * 9.log ([2000-1-1 00:00:00,000] A)
     * 10.log ([2000-1-1 00:00:00,000] B)
     *
     * log [A] is printed before log [B] but both in the same time [2000-1-1 00:00:00,000].
     *
     * After sorting by ascii comparing on filename:
     * 10.log
     * 9.log
     *
     * Then we first parse [B] from 10.log and then [A] from 9.log:
     *
     * [2000-1-1 00:00:00,000] B
     * [2000-1-1 00:00:00,000] A
     *
     * So the sorting order of files must be the same as generating.
     *
     */
    sort(files.begin(), files.end(), [](string &lhs, string &rhs) {
            return doj::alphanum_comp(lhs, rhs) < 0;
        });
}<commit_msg>- : bug (null pointer)<commit_after>#include <fstream>
#include <vector>
#include <locale.h>
#include "LogEntryFilter.h"
#include "LogEntryRootFilter.h"
#include "LogEntryMessageFilter.h"
#include "LogEntryTimeFilter.h"
#include "FileUtils.hpp"
#include "CommandLineUtils.hpp"
#include "LogEntryParser.h"
#include "Rearranger.h"
#include "LogEntryFilterFactory.h"
#include "alphanum.hpp"

using namespace std;

#ifdef _WIN32
#define kPathSeparator '\\'
#else
#define kPathSeparator '/'
#endif

void sortFiles(vector<string> &files);

int main(int argc, char *argv[]) {
    setlocale(LC_ALL, "");
    int ret = 0;
    if (argc == 1 || cmdOptionExists(argv, argv + argc, "--help")) {
        cout << "LogUtil: A handy tool to merge/filter log files.\ngit: https://github.com/yhd4711499/LogUtil.git\n\n";
        cout << "usage :\tlogutil";
        cout << "\t[-d] [-f] [-o] [-r] [-start] [-end]\n\n";
        cout << "\t-d\tmerge all files under the directory.\n";
        cout << "\t-f\tsort the log file.\n";
        cout << "\t-o\toutput file. [<file_or_dirname>_ALL.log] will be used if not set.\n\t\tor [std] to print output to stdout.\n";
        cout << "\t-r\tfilter rules.\n";
        cout << "\nAdvanced usage:\n\n";
        cout << "\t-start/end\tshow logs between [start , end), \"YYYY-mm-dd hh:MM:SS.SSS\" .\n\n";
        cout << "examples :\n";
        cout << "\tlogutil ~/LogDir\n";
        cout << "\tlogutil ~/LogDir -o std\n";
        cout << "\tlogutil -d ~/LogDir\n";
        cout << "\tlogutil -d ~/LogDir -start 2016-06-18\n";
        cout << "\tlogutil -d ~/LogDir -start 2016-06-18 -end 2016-06-19\n";
        cout << "\tlogutil -d ~/LogDir -r ~/block_rules.json\n";
        cout << "\tlogutil -d ~/LogDir -o ~/Log_ALL.log\n";
        cout << "\tlogutil -f ~/LogDir/log.log -o ~/Log_ALL.log\n";
        return 0;
    }
    vector<string> files;
    char *dirname = nullptr, *filename = nullptr, *outputFilename = nullptr;

    if (argc == 2) {
        if (isFile(argv[1])) {
            filename = argv[1];
        } else {
            dirname = argv[1];
        }
    } else {
        dirname = getCmdOption(argv, argv + argc, "-d");
        filename = getCmdOption(argv, argv + argc, "-f");
    }

    if (filename) {
        files.push_back(filename);
    }

    if (dirname) {
        ret = listFiles(dirname, files);
        if (ret != 0) {
            cerr << "Failed to visit dir : " << dirname << endl;
            return ret;
        }
    }

    if (files.size() > 1) {
        sortFiles(files);
    }

    char *filterRultFile = getCmdOption(argv, argv + argc, "-r");
    char *startTime = getCmdOption(argv, argv + argc, "-start");
    char *endTime = getCmdOption(argv, argv + argc, "-end");

    outputFilename = getCmdOption(argv, argv + argc, "-o");
    if (outputFilename && !strncmp(outputFilename, "std", 3)) {
        outputFilename = NULL;
    } else if (!outputFilename) {
        if (filename) {
            string folderName, filenameWoDir;
            splitFilename(string(filename), folderName, filenameWoDir);

            string newFilename(folderName + kPathSeparator + "All_" + filenameWoDir);
            outputFilename = new char[newFilename.length() + 1];
            strcpy(outputFilename, newFilename.c_str());
        }
        else if (dirname) {
            string newFilename(string(dirname) + kPathSeparator + "All.log");
            outputFilename = new char[newFilename.length() + 1];
            strcpy(outputFilename, newFilename.c_str());
        }
    }

    LogEntryFilterFactory::registerCreator("root", LogEntryRootFilter::creator);
    LogEntryFilterFactory::registerCreator("log", LogEntryMessageFilter::creator);
    LogEntryFilterFactory::registerCreator("time", LogEntryTimeFilter::creator);

    LogEntryParser parser;

    if (filterRultFile) {
        auto fileRuleStream = fstream(filterRultFile);
        json fileRuleJson;
        fileRuleStream >> fileRuleJson;
        parser.addFilter(LogEntryFilterFactory::create(fileRuleJson));
    }

    if (startTime || endTime) {
        string start = startTime ? (string) startTime : "";
        string end = endTime ? (string) endTime : "";
        LogEntryTimeFilter *filter = new LogEntryTimeFilter(
                LogEntryTimeFilter::getDate(start),
                LogEntryTimeFilter::getTime(start),
                LogEntryTimeFilter::getDate(end),
                LogEntryTimeFilter::getTime(end),
                true);
        parser.addFilter(filter);
    }

    vector<LogEntry *> entries;

    for (string file : files) {
        try {
            parser.parseFile(file, entries);
        } catch (runtime_error &error) {
            cerr << "Failed to parse file : " << file << ". error: " << error.what() << endl;
        } catch (...) {
            cerr << "Failed to parse file : " << file << endl;
        }
    }

    Rearranger rearranger;
    rearranger.sort(entries);

    int index = 1;
    for (LogEntry *entry : entries) {
        entry->line.orderedIndex = index;
        index += entry->line.lines.size();
    }

    if (outputFilename) {
        ofstream os(outputFilename);
        for (LogEntry *entry : entries) {
            os << *entry;
        }
        printf("All done. File saved to %s\n", outputFilename);
    } else {
        for (LogEntry *entry : entries) {
            cout << *entry;
        }
    }

    return 0;
}

void sortFiles(vector<string> &files) {
    /*
     * A little tricky here: files must be sorted in natural order on filename.
     * Or output result might be mis-ordered on log entries with same timestamp but stored in separate files.
     *
     * For example.
     *
     * We'ev two logs files:
     *
     * 9.log ([2000-1-1 00:00:00,000] A)
     * 10.log ([2000-1-1 00:00:00,000] B)
     *
     * log [A] is printed before log [B] but both in the same time [2000-1-1 00:00:00,000].
     *
     * After sorting by ascii comparing on filename:
     * 10.log
     * 9.log
     *
     * Then we first parse [B] from 10.log and then [A] from 9.log:
     *
     * [2000-1-1 00:00:00,000] B
     * [2000-1-1 00:00:00,000] A
     *
     * So the sorting order of files must be the same as generating.
     *
     */
    sort(files.begin(), files.end(), [](string &lhs, string &rhs) {
            return doj::alphanum_comp(lhs, rhs) < 0;
        });
}<|endoftext|>


<commit_before>/*
 * Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES)
 *
 * This file is part of Orfeo Toolbox
 *
 *     https://www.orfeo-toolbox.org/
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <chrono>
#include <sstream>
#include <iomanip>

#include "otbStopwatch.h"

namespace otb
{

Stopwatch
::Stopwatch()
  : m_StartTime(), m_ElapsedMilliseconds(), m_IsRunning()
{
}

void
Stopwatch
::Start()
{
  if (!this->m_IsRunning)
    {
    this->m_IsRunning = true;
    this->m_StartTime = this->GetTimestamp();
    }
}

void
Stopwatch
::Stop()
{
  if (this->m_IsRunning)
    {
    this->m_ElapsedMilliseconds += GetRunningElapsedTime();
    this->m_IsRunning = false;
    }
}

void
Stopwatch
::Reset()
{
  this->m_ElapsedMilliseconds = 0;
  this->m_IsRunning = false;
}

void
Stopwatch
::Restart()
{
  this->m_ElapsedMilliseconds = 0;
  this->m_IsRunning = true;
  this->m_StartTime = this->GetTimestamp();
}

Stopwatch::DurationType
Stopwatch
::GetElapsedMilliseconds() const
{
  auto result = this->m_ElapsedMilliseconds;

  if (this->m_IsRunning)
    result += this->GetRunningElapsedTime();

  return result;
}

std::string
Stopwatch
::GetElapsedHumanReadableTime() const
{
  auto result = this->GetElapsedMilliseconds();
  int seconds = result/1000;
  int hours = seconds / 3600;
  seconds -= (hours * 3600);
  int minutes = seconds / 60;
  seconds -= (minutes * 60);
  std::ostringstream os;
  if (hours > 0)
    os << hours << "h " << std::setfill('0') << std::setw(2);
  if (minutes > 0 or hours>0)
    os << minutes << "m " << std::setfill('0') << std::setw(2);
  os << seconds << "s";
  return os.str();
}

bool
Stopwatch
::IsRunning() const
{
  return this->m_IsRunning;
}

Stopwatch
Stopwatch
::StartNew()
{
  Stopwatch sw;
  sw.Start();

  return sw;
}

inline
Stopwatch::TimepointType
Stopwatch
::GetTimestamp() const
{
  auto now = std::chrono::steady_clock::now();
  return std::chrono::duration_cast<std::chrono::milliseconds>(now.time_since_epoch()).count();
}

inline
Stopwatch::DurationType
Stopwatch
::GetRunningElapsedTime() const
{
  return this->GetTimestamp() - this->m_StartTime;
}

}
<commit_msg>COMP: Fix or operator not well supported by MSVC (+ a few style edits)<commit_after>/*
 * Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES)
 *
 * This file is part of Orfeo Toolbox
 *
 *     https://www.orfeo-toolbox.org/
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <chrono>
#include <sstream>
#include <iomanip>

#include "otbStopwatch.h"

namespace otb
{

Stopwatch
::Stopwatch()
  : m_StartTime(), m_ElapsedMilliseconds(), m_IsRunning()
{
}

void
Stopwatch
::Start()
{
  if (!this->m_IsRunning)
    {
    this->m_IsRunning = true;
    this->m_StartTime = this->GetTimestamp();
    }
}

void
Stopwatch
::Stop()
{
  if (this->m_IsRunning)
    {
    this->m_ElapsedMilliseconds += GetRunningElapsedTime();
    this->m_IsRunning = false;
    }
}

void
Stopwatch
::Reset()
{
  this->m_ElapsedMilliseconds = 0;
  this->m_IsRunning = false;
}

void
Stopwatch
::Restart()
{
  this->m_ElapsedMilliseconds = 0;
  this->m_IsRunning = true;
  this->m_StartTime = this->GetTimestamp();
}

Stopwatch::DurationType
Stopwatch
::GetElapsedMilliseconds() const
{
  auto result = this->m_ElapsedMilliseconds;

  if (this->m_IsRunning)
    result += this->GetRunningElapsedTime();

  return result;
}

std::string
Stopwatch
::GetElapsedHumanReadableTime() const
{
  auto result = this->GetElapsedMilliseconds();
  int seconds = result / 1000;
  int hours = seconds / 3600;
  seconds -= hours * 3600;
  int minutes = seconds / 60;
  seconds -= minutes * 60;
  std::ostringstream os;
  if (hours > 0)
    os << hours << "h " << std::setfill('0') << std::setw(2);
  if (minutes > 0 || hours > 0)
    os << minutes << "m " << std::setfill('0') << std::setw(2);
  os << seconds << "s";
  return os.str();
}

bool
Stopwatch
::IsRunning() const
{
  return this->m_IsRunning;
}

Stopwatch
Stopwatch
::StartNew()
{
  Stopwatch sw;
  sw.Start();

  return sw;
}

inline
Stopwatch::TimepointType
Stopwatch
::GetTimestamp() const
{
  auto now = std::chrono::steady_clock::now();
  return std::chrono::duration_cast<std::chrono::milliseconds>(now.time_since_epoch()).count();
}

inline
Stopwatch::DurationType
Stopwatch
::GetRunningElapsedTime() const
{
  return this->GetTimestamp() - this->m_StartTime;
}

}
<|endoftext|>


<commit_before>//
//  Parser.cpp
//  snowcrash
//
//  Created by Zdenek Nemec on 4/8/13.
//  Copyright (c) 2013 Apiary.io. All rights reserved.
//

#include <exception>
#include <sstream>
#include "Parser.h"
#include "MarkdownParser.h"
#include "BlueprintParser.h"

using namespace snowcrash;

const int SourceAnnotation::OK;

void Parser::parse(const SourceData& source, Result& result, Blueprint& blueprint)
{
    try {
        // Parse Markdown
        MarkdownBlock::Stack markdown;
        MarkdownParser markdownParser;
        markdownParser.parse(source, result, markdown);

        if (result.error.code != Error::OK)
            return;

        // Parse Blueprint
        BlueprintParser::Parse(source, markdown, result, blueprint);
    }
    catch (const std::exception& e) {

        std::stringstream ss;
        ss << "parser exception: '" << e.what() << "'";
        result.error = Error(ss.str(), 1);
    }
    catch (...) {

        result.error = Error("parser exception has occured", 1);
    }
}
<commit_msg>Add tabs & CR sanity check<commit_after>//
//  Parser.cpp
//  snowcrash
//
//  Created by Zdenek Nemec on 4/8/13.
//  Copyright (c) 2013 Apiary.io. All rights reserved.
//

#include <exception>
#include <sstream>
#include "Parser.h"
#include "MarkdownParser.h"
#include "BlueprintParser.h"

using namespace snowcrash;

const int SourceAnnotation::OK;

// Check source for unsupported character \t & \r
// Returns true if passed (not found), false otherwise
static bool CheckSource(const SourceData& source, Result& result)
{
    std::string::size_type pos = source.find("\t");
    if (pos != std::string::npos) {
        result.error = Error("the use of tab(s) `\\t` in source data isn't currently supported, please contact makers", 2);
        return false;
    }

    pos = source.find("\r");
    if (pos != std::string::npos) {
        result.error = Error("the use of carriage return(s) `\\r` in source data isn't currently supported, please contact makers", 2);
        return false;
    }

    return true;
}

void Parser::parse(const SourceData& source, Result& result, Blueprint& blueprint)
{
    try {

        // Sanity Check
        if (!CheckSource(source, result))
            return;

        // Parse Markdown
        MarkdownBlock::Stack markdown;
        MarkdownParser markdownParser;
        markdownParser.parse(source, result, markdown);

        if (result.error.code != Error::OK)
            return;

        // Parse Blueprint
        BlueprintParser::Parse(source, markdown, result, blueprint);
    }
    catch (const std::exception& e) {

        std::stringstream ss;
        ss << "parser exception: '" << e.what() << "'";
        result.error = Error(ss.str(), 1);
    }
    catch (...) {

        result.error = Error("parser exception has occured", 1);
    }
}
<|endoftext|>


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

The Medical Imaging Interaction Toolkit (MITK)

Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.

This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.

See LICENSE.txt or http://www.mitk.org for details.

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

#include <mitkTestFixture.h>
#include <mitkTestingMacros.h>

#include <mitkIRESTManager.h>
#include <mitkIRESTObserver.h>
#include <mitkRESTClient.h>
#include <mitkRESTUtil.h>

#include <usGetModuleContext.h>
#include <usModuleContext.h>
#include <usServiceReference.h>

#include <vtkDebugLeaks.h>

class mitkRESTClientTestSuite : public mitk::TestFixture, mitk::IRESTObserver
{
  CPPUNIT_TEST_SUITE(mitkRESTClientTestSuite);
  // MITK_TEST(GetRequestValidURI_ReturnsExpectedJSON); GET requests do not support content yet?
  MITK_TEST(MultipleGetRequestValidURI_AllTasksFinish);
  // MITK_TEST(PutRequestValidURI_ReturnsExpectedJSON); Does not work reliably on dart clients
  // MITK_TEST(PostRequestValidURI_ReturnsExpectedJSON);              -- " --
  MITK_TEST(GetRequestInvalidURI_ThrowsException);
  MITK_TEST(PutRequestInvalidURI_ThrowsException);
  MITK_TEST(PostRequestInvalidURI_ThrowsException);
  CPPUNIT_TEST_SUITE_END();

public:
  mitk::IRESTManager *m_Service;
  web::json::value m_Data;

  web::http::http_response Notify(const web::uri &,
                                  const web::json::value &,
                                  const web::http::method &,
                                  const mitk::RESTUtil::ParamMap &headers) override
  {
    auto response = web::http::http_response();
    response.set_body(m_Data);
    response.set_status_code(web::http::status_codes::OK);

    return response;
  }

  /**
   * @brief Setup Always call this method before each Test-case to ensure correct and new intialization of the used
   * members for a new test case. (If the members are not used in a test, the method does not need to be called).
   */
  void setUp() override
  {
    m_Data = web::json::value();
    m_Data[U("userId")] = web::json::value(1);
    m_Data[U("id")] = web::json::value(1);
    m_Data[U("title")] = web::json::value(U("this is a title"));
    m_Data[U("body")] = web::json::value(U("this is a body"));

    us::ServiceReference<mitk::IRESTManager> serviceRef =
      us::GetModuleContext()->GetServiceReference<mitk::IRESTManager>();
    if (serviceRef)
    {
      m_Service = us::GetModuleContext()->GetService(serviceRef);
    }

    if (!m_Service)
    {
      CPPUNIT_FAIL("Getting Service in setUp() failed");
    }

    m_Service->ReceiveRequest(U("http://localhost:8080/clienttest"), this);
  }

  void tearDown() override { m_Service->HandleDeleteObserver(this); }

  void GetRequestValidURI_ReturnsExpectedJSON()
  {
    web::json::value result;

    m_Service->SendRequest(U("http://localhost:8080/clienttest"))
      .then([&](pplx::task<web::json::value> resultTask) {
        try
        {
          result = resultTask.get();
        }
        catch (const mitk::Exception &exception)
        {
          MITK_ERROR << exception.what();
          return;
        }
      })
      .wait();

    CPPUNIT_ASSERT_MESSAGE("Result is the expected JSON value", result == m_Data);
  }

  void MultipleGetRequestValidURI_AllTasksFinish()
  {
    int count = 0;

    // Create multiple tasks e.g. as shown below
    std::vector<pplx::task<void>> tasks;
    for (int i = 0; i < 20; ++i)
    {
      pplx::task<void> singleTask = m_Service->SendRequest(U("http://localhost:8080/clienttest"))
                                      .then([&](pplx::task<web::json::value> resultTask) {
                                        // Do something when a single task is done
                                        try
                                        {
                                          resultTask.get();
                                          count += 1;
                                        }
                                        catch (const mitk::Exception &exception)
                                        {
                                          MITK_ERROR << exception.what();
                                          return;
                                        }
                                      });
      tasks.emplace_back(singleTask);
    }
    // Create a joinTask which includes all tasks you've created
    auto joinTask = pplx::when_all(begin(tasks), end(tasks));
    // Run asynchonously
    joinTask
      .then([&](pplx::task<void> resultTask) {
        // Do something when all tasks are finished
        try
        {
          resultTask.get();
          count += 1;
        }
        catch (const mitk::Exception &exception)
        {
          MITK_ERROR << exception.what();
          return;
        }
      })
      .wait();

    CPPUNIT_ASSERT_MESSAGE("Multiple Requests", 21 == count);
  }

  void PutRequestValidURI_ReturnsExpectedJSON()
  {
    // optional: link might get invalid or content is changed
    web::json::value result;

    m_Service
      ->SendJSONRequest(
        U("https://jsonplaceholder.typicode.com/posts/1"), mitk::IRESTManager::RequestType::Put)
      .then([&](pplx::task<web::json::value> resultTask) {
        try
        {
          result = resultTask.get();
        }
        catch (const mitk::Exception &exception)
        {
          MITK_ERROR << exception.what();
          return;
        }
      })
      .wait();

    CPPUNIT_ASSERT_MESSAGE(
      "Result is the expected JSON value, check if the link is still valid since this is an optional test",
      result == m_Data);
  }

  void PostRequestValidURI_ReturnsExpectedJSON()
  {
    // optional: link might get invalid or content is changed
    web::json::value result;
    web::json::value data;

    data[U("userId")] = m_Data[U("userId")];
    data[U("title")] = m_Data[U("title")];
    data[U("body")] = m_Data[U("body")];

    m_Service
      ->SendJSONRequest(U("https://jsonplaceholder.typicode.com/posts"), mitk::IRESTManager::RequestType::Post, &data)
      .then([&](pplx::task<web::json::value> resultTask) {
        try
        {
          result = resultTask.get();
        }
        catch (const mitk::Exception &exception)
        {
          MITK_ERROR << exception.what();
          return;
        }
      })
      .wait();

    data[U("id")] = web::json::value(101);
    CPPUNIT_ASSERT_MESSAGE(
      "Result is the expected JSON value, check if the link is still valid since this is an optional test",
      result == data);
  }

  void PostRequestHeaders_Success()
  {
    mitk::RESTUtil::ParamMap headers;
    headers.insert(mitk::RESTUtil::ParamMap::value_type(
      U("Content-Type"), U("multipart/related; type=\"application/dicom\"; boundary=boundary")));

    m_Service->SendRequest(U("http://localhost:8080/clienttest")).then([&](pplx::task<web::json::value> resultTask) {
      // Do something when a single task is done
      try
      {
        resultTask.get();
      }
      catch (const mitk::Exception &exception)
      {
        MITK_ERROR << exception.what();
        return;
      }
    });
  }

  void GetException()
  {
    // Method which makes a get request to an invalid uri
    web::json::value result;

    m_Service->SendRequest(U("http://localhost:1234/invalid"))
      .then([&](pplx::task<web::json::value> resultTask) { result = resultTask.get(); })
      .wait();
  }
  void GetRequestInvalidURI_ThrowsException() { CPPUNIT_ASSERT_THROW(GetException(), mitk::Exception); }

  void PutException()
  {
    // Method which makes a put request to an invalid uri
    web::json::value result;

    m_Service->SendJSONRequest(U("http://localhost:1234/invalid"), mitk::IRESTManager::RequestType::Put, &m_Data)
      .then([&](pplx::task<web::json::value> resultTask) { result = resultTask.get(); })
      .wait();
  }
  void PutRequestInvalidURI_ThrowsException() { CPPUNIT_ASSERT_THROW(PutException(), mitk::Exception); }

  void PostException()
  {
    // Method which makes a post request to an invalid uri
    web::json::value result;

    m_Service->SendJSONRequest(U("http://localhost:1234/invalid"), mitk::IRESTManager::RequestType::Post, &m_Data)
      .then([&](pplx::task<web::json::value> resultTask) { result = resultTask.get(); })
      .wait();
  }
  void PostRequestInvalidURI_ThrowsException() { CPPUNIT_ASSERT_THROW(PostException(), mitk::Exception); }
};

MITK_TEST_SUITE_REGISTRATION(mitkRESTClient)
<commit_msg>Remove unused parameter<commit_after>/*===================================================================

The Medical Imaging Interaction Toolkit (MITK)

Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.

This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.

See LICENSE.txt or http://www.mitk.org for details.

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

#include <mitkTestFixture.h>
#include <mitkTestingMacros.h>

#include <mitkIRESTManager.h>
#include <mitkIRESTObserver.h>
#include <mitkRESTClient.h>
#include <mitkRESTUtil.h>

#include <usGetModuleContext.h>
#include <usModuleContext.h>
#include <usServiceReference.h>

#include <vtkDebugLeaks.h>

class mitkRESTClientTestSuite : public mitk::TestFixture, mitk::IRESTObserver
{
  CPPUNIT_TEST_SUITE(mitkRESTClientTestSuite);
  // MITK_TEST(GetRequestValidURI_ReturnsExpectedJSON); GET requests do not support content yet?
  MITK_TEST(MultipleGetRequestValidURI_AllTasksFinish);
  // MITK_TEST(PutRequestValidURI_ReturnsExpectedJSON); Does not work reliably on dart clients
  // MITK_TEST(PostRequestValidURI_ReturnsExpectedJSON);              -- " --
  MITK_TEST(GetRequestInvalidURI_ThrowsException);
  MITK_TEST(PutRequestInvalidURI_ThrowsException);
  MITK_TEST(PostRequestInvalidURI_ThrowsException);
  CPPUNIT_TEST_SUITE_END();

public:
  mitk::IRESTManager *m_Service;
  web::json::value m_Data;

  web::http::http_response Notify(const web::uri &,
                                  const web::json::value &,
                                  const web::http::method &,
                                  const mitk::RESTUtil::ParamMap &) override
  {
    auto response = web::http::http_response();
    response.set_body(m_Data);
    response.set_status_code(web::http::status_codes::OK);

    return response;
  }

  /**
   * @brief Setup Always call this method before each Test-case to ensure correct and new intialization of the used
   * members for a new test case. (If the members are not used in a test, the method does not need to be called).
   */
  void setUp() override
  {
    m_Data = web::json::value();
    m_Data[U("userId")] = web::json::value(1);
    m_Data[U("id")] = web::json::value(1);
    m_Data[U("title")] = web::json::value(U("this is a title"));
    m_Data[U("body")] = web::json::value(U("this is a body"));

    us::ServiceReference<mitk::IRESTManager> serviceRef =
      us::GetModuleContext()->GetServiceReference<mitk::IRESTManager>();
    if (serviceRef)
    {
      m_Service = us::GetModuleContext()->GetService(serviceRef);
    }

    if (!m_Service)
    {
      CPPUNIT_FAIL("Getting Service in setUp() failed");
    }

    m_Service->ReceiveRequest(U("http://localhost:8080/clienttest"), this);
  }

  void tearDown() override { m_Service->HandleDeleteObserver(this); }

  void GetRequestValidURI_ReturnsExpectedJSON()
  {
    web::json::value result;

    m_Service->SendRequest(U("http://localhost:8080/clienttest"))
      .then([&](pplx::task<web::json::value> resultTask) {
        try
        {
          result = resultTask.get();
        }
        catch (const mitk::Exception &exception)
        {
          MITK_ERROR << exception.what();
          return;
        }
      })
      .wait();

    CPPUNIT_ASSERT_MESSAGE("Result is the expected JSON value", result == m_Data);
  }

  void MultipleGetRequestValidURI_AllTasksFinish()
  {
    int count = 0;

    // Create multiple tasks e.g. as shown below
    std::vector<pplx::task<void>> tasks;
    for (int i = 0; i < 20; ++i)
    {
      pplx::task<void> singleTask = m_Service->SendRequest(U("http://localhost:8080/clienttest"))
                                      .then([&](pplx::task<web::json::value> resultTask) {
                                        // Do something when a single task is done
                                        try
                                        {
                                          resultTask.get();
                                          count += 1;
                                        }
                                        catch (const mitk::Exception &exception)
                                        {
                                          MITK_ERROR << exception.what();
                                          return;
                                        }
                                      });
      tasks.emplace_back(singleTask);
    }
    // Create a joinTask which includes all tasks you've created
    auto joinTask = pplx::when_all(begin(tasks), end(tasks));
    // Run asynchonously
    joinTask
      .then([&](pplx::task<void> resultTask) {
        // Do something when all tasks are finished
        try
        {
          resultTask.get();
          count += 1;
        }
        catch (const mitk::Exception &exception)
        {
          MITK_ERROR << exception.what();
          return;
        }
      })
      .wait();

    CPPUNIT_ASSERT_MESSAGE("Multiple Requests", 21 == count);
  }

  void PutRequestValidURI_ReturnsExpectedJSON()
  {
    // optional: link might get invalid or content is changed
    web::json::value result;

    m_Service
      ->SendJSONRequest(
        U("https://jsonplaceholder.typicode.com/posts/1"), mitk::IRESTManager::RequestType::Put)
      .then([&](pplx::task<web::json::value> resultTask) {
        try
        {
          result = resultTask.get();
        }
        catch (const mitk::Exception &exception)
        {
          MITK_ERROR << exception.what();
          return;
        }
      })
      .wait();

    CPPUNIT_ASSERT_MESSAGE(
      "Result is the expected JSON value, check if the link is still valid since this is an optional test",
      result == m_Data);
  }

  void PostRequestValidURI_ReturnsExpectedJSON()
  {
    // optional: link might get invalid or content is changed
    web::json::value result;
    web::json::value data;

    data[U("userId")] = m_Data[U("userId")];
    data[U("title")] = m_Data[U("title")];
    data[U("body")] = m_Data[U("body")];

    m_Service
      ->SendJSONRequest(U("https://jsonplaceholder.typicode.com/posts"), mitk::IRESTManager::RequestType::Post, &data)
      .then([&](pplx::task<web::json::value> resultTask) {
        try
        {
          result = resultTask.get();
        }
        catch (const mitk::Exception &exception)
        {
          MITK_ERROR << exception.what();
          return;
        }
      })
      .wait();

    data[U("id")] = web::json::value(101);
    CPPUNIT_ASSERT_MESSAGE(
      "Result is the expected JSON value, check if the link is still valid since this is an optional test",
      result == data);
  }

  void PostRequestHeaders_Success()
  {
    mitk::RESTUtil::ParamMap headers;
    headers.insert(mitk::RESTUtil::ParamMap::value_type(
      U("Content-Type"), U("multipart/related; type=\"application/dicom\"; boundary=boundary")));

    m_Service->SendRequest(U("http://localhost:8080/clienttest")).then([&](pplx::task<web::json::value> resultTask) {
      // Do something when a single task is done
      try
      {
        resultTask.get();
      }
      catch (const mitk::Exception &exception)
      {
        MITK_ERROR << exception.what();
        return;
      }
    });
  }

  void GetException()
  {
    // Method which makes a get request to an invalid uri
    web::json::value result;

    m_Service->SendRequest(U("http://localhost:1234/invalid"))
      .then([&](pplx::task<web::json::value> resultTask) { result = resultTask.get(); })
      .wait();
  }
  void GetRequestInvalidURI_ThrowsException() { CPPUNIT_ASSERT_THROW(GetException(), mitk::Exception); }

  void PutException()
  {
    // Method which makes a put request to an invalid uri
    web::json::value result;

    m_Service->SendJSONRequest(U("http://localhost:1234/invalid"), mitk::IRESTManager::RequestType::Put, &m_Data)
      .then([&](pplx::task<web::json::value> resultTask) { result = resultTask.get(); })
      .wait();
  }
  void PutRequestInvalidURI_ThrowsException() { CPPUNIT_ASSERT_THROW(PutException(), mitk::Exception); }

  void PostException()
  {
    // Method which makes a post request to an invalid uri
    web::json::value result;

    m_Service->SendJSONRequest(U("http://localhost:1234/invalid"), mitk::IRESTManager::RequestType::Post, &m_Data)
      .then([&](pplx::task<web::json::value> resultTask) { result = resultTask.get(); })
      .wait();
  }
  void PostRequestInvalidURI_ThrowsException() { CPPUNIT_ASSERT_THROW(PostException(), mitk::Exception); }
};

MITK_TEST_SUITE_REGISTRATION(mitkRESTClient)
<|endoftext|>


<commit_before>
#define _GLIBCXX_USE_NANOSLEEP

#include "main.hpp"
#include <algorithm>

/*
    What I know:
        Cipher 1:
            is a shift cipher. Offset 13, so basically ROT-13!

        Cipher 2:
            is not a regular shift cipher.
            is a Vigenere cipher. Key length of 9!

        Cipher 3:
            is not a regular shift cipher.
            does not appear to be a Vigenere cipher, checked keylengths [1-50]

            could be columnar transposition
            could be monoalphabetic substitution

        Cipher 4:
            is not a regular shift cipher.
            does not appear to be a Vigenere cipher, checked keylengths [1-50]

            could be columnar transposition
            could be monoalphabetic substitution

Ceasar cipher - no cipher
shift cipher - Cipher 1, no other cipher
monoalphabetic substitution cipher
one-time-pad - basically uncrackable without finding secret key
columnar transposition - of those, could be rail cipher or regular
vignere cipher - Cipher 2, no other cipher

*/

int main(int argc, char** argv)
{
    auto cipher1lower = toLowerCase(cipher1);
    auto cipher2lower = toLowerCase(cipher2);
    auto cipher3lower = toLowerCase(cipher3);
    auto cipher4lower = toLowerCase(cipher4);
//"wecrlteerdsoeefeaocaivden"
    std::cout << crackRailCipher("wireeedseeeacaecvdltnrofo") << std::endl;
/*
    std::cout << "Cipher 1, attempted crack of shift cipher:" << std::endl;
    std::cout << cipher1lower << std::endl;
    std::cout << crackShiftCipher(cipher1lower) << std::endl;
    std::cout << "-----------------------------------------------" << std::endl;*/
/*
    std::cout << "Cipher 2, attempted crack of Vigenere cipher:" << std::endl;
    std::cout << crackVigenereCipher(cipher2lower) << std::endl;
    std::cout << "-----------------------------------------------" << std::endl;*/
/*
    std::cout << "Cipher 4, attempted crack of vigenere cipher:" << std::endl;
    std::cout << crackVigenereCipher(cipher4lower) << std::endl;
    std::cout << "-----------------------------------------------" << std::endl;*/
}

std::string crackShiftCipher(const std::string& ciphertext)
{
    float bestDeviation = 4096;
    std::string currentGuess;

    for (std::size_t shift = 0; shift <= 26; shift++)
    {
        std::string copy(ciphertext);
        for (std::size_t j = 0; j < ciphertext.size(); j++)
            copy[j] = (ciphertext[j] - 97 + shift) % 26 + 97;

        float dev = getDeviationFromEnglish(copy);
        if (dev < bestDeviation)
        {
            bestDeviation = dev;
            currentGuess = copy;
        }
    }

    return currentGuess;
}

std::string crackVigenereCipher(const std::string& ciphertext)
{
    float bestDeviation = 4096;
    std::string currentGuess;

    for (std::size_t keyLength = 1; keyLength <= 25; keyLength++)
    {
        std::string whole(ciphertext); //will be overridden

        for (std::size_t offset = 0; offset < keyLength; offset++)
        {
            std::string subStr;
            for (std::size_t j = offset; j < ciphertext.size(); j += keyLength)
                subStr += ciphertext[j];

            auto cracked = crackShiftCipher(subStr);
            for (std::size_t j = 0; j < subStr.size(); j++)
                whole[j * keyLength + offset] = cracked[j];
        }

        float dev = getDeviationFromEnglish(whole);
        if (dev < bestDeviation)
        {
            bestDeviation = dev;
            currentGuess = whole;

            std::cout << std::endl;
            std::cout << "Better guess! Keylength of " << keyLength << std::endl;
            std::cout << "Deviation from English: " << dev << std::endl;
            std::cout << currentGuess << std::endl;
        }
    }

    return currentGuess;
}

//wearediscoveredfleeatonce
//wecrlteerdsoeefeadcaivden

std::string crackRailCipher(const std::string& ciphertext)
{
    int maxKeyLength = 40;
    if (maxKeyLength >= ciphertext.size())
        maxKeyLength = ciphertext.size();

    //for (int keyLength = 2; keyLength < maxKeyLength; keyLength++)
    int keyLength = 4;
    {
        std::string plaintext(ciphertext);

        int cipherIndex = 0;
        for (int offset = 0; offset < keyLength; offset++)
        {
            int diff = (keyLength - 1) * 2 - offset * 2;

            if (offset == keyLength - 1)
                diff = (keyLength - 1) * 2;
            std::cout << diff << std::endl;
            for (int j = offset; j < ciphertext.size(); j += diff)
            {
                plaintext[j] = ciphertext[cipherIndex];
                cipherIndex++;
            }
        }

        std::cout << cipherIndex << ", " << ciphertext.size() << std::endl;

        std::cout << keyLength << ": " << plaintext << std::endl;
    }

    return "";
}

std::string toLowerCase(const std::string& str)
{
    std::string copy(str);
    std::transform(copy.begin(), copy.end(), copy.begin(), ::tolower);
    return copy;
}

float getDeviationFromEnglish(const std::string& str)
{
    FrequencyMap map;

    for (std::size_t j = 0; j < str.size(); j++)
        map[str[j]] = map[str[j]] + 1;

    auto ENGLISH = getEnglishFrequencyMap();
    float deviation = 0;
    for (auto& x: map)
    {
        float diff = x.second / str.size() - ENGLISH[x.first] / 100;
        deviation += diff * diff;
    }

    return deviation;
}

FrequencyMap getEnglishFrequencyMap()
{
    static FrequencyMap english;

    if (!english.empty())
        return english;

    english['a'] = 8.167f;
    english['b'] = 1.492f;
    english['c'] = 2.783f;
    english['d'] = 4.253f;
    english['e'] = 12.702f;
    english['f'] = 2.228f;
    english['g'] = 2.015f;
    english['h'] = 6.094f;
    english['i'] = 6.966f;
    english['j'] = 0.153f;
    english['k'] = 0.772f;
    english['l'] = 4.025f;
    english['m'] = 2.406f;
    english['n'] = 6.749f;
    english['o'] = 7.507f;
    english['p'] = 1.929f;
    english['q'] = 0.095f;
    english['r'] = 5.987f;
    english['s'] = 6.327f;
    english['t'] = 9.056f;
    english['u'] = 2.758f;
    english['v'] = 0.978f;
    english['w'] = 2.360f;
    english['x'] = 0.150f;
    english['y'] = 1.974f;
    english['z'] = 0.075f;

    return english;
}
<commit_msg>notes on other ciphers<commit_after>
#define _GLIBCXX_USE_NANOSLEEP

#include "main.hpp"
#include <algorithm>

/*
    What I know:
        Cipher 1:
            is a shift cipher. Shift key is 13, so basically ROT-13!

        Cipher 2:
            is not a regular shift cipher.
            is a Vigenere cipher. Key length of 9, key worcester

        Cipher 3:
            is not a regular shift cipher.
            does not appear to be a Vigenere cipher, checked keylengths [1-50]
            does not appear to be a Fence Rail cipher, checked leylengths [1-25]
            has very flat frequencies, suggesting something unusual
                monoalphabetic sub or column transpose couldn't do this
                One-time pad? Vigenere? Vigenere autokey? Hill?
                Variance from English: 0.0282431
                One-time pad is impossible, V autokey nor Hill were listed.

        Cipher 4:
            is not a regular shift cipher.
            does not appear to be a Vigenere cipher, checked keylengths [1-50]
            does not appear to be a Fence Rail cipher, checked leylengths [1-25]
            has varying frequency distributions, suggesting substitutions
                Monoalphabetic? Columnar transpose? Affine cipher (p28)?
                Variance from English: 0.0521973

Hints and notes:
Ceasar cipher - no cipher, rough distribution graph
shift cipher - Cipher 1, no other cipher, rough distribution graph
monoalphabetic substitution cipher, rough distribution graph
one-time-pad - basically uncrackable without finding secret key, flat distrib
columnar transposition - rail or regular, rough distribution graph
vignere cipher - Cipher 2, no other cipher, flat distribution

*/

int main(int argc, char** argv)
{
    auto cipher1lower = toLowerCase(cipher1);
    auto cipher2lower = toLowerCase(cipher2);
    auto cipher3lower = toLowerCase(cipher3);
    auto cipher4lower = toLowerCase(cipher4);

    std::cout << "Cipher 1, attempted crack of shift cipher:" << std::endl;
    std::cout << cipher1lower << std::endl;
    std::cout << crackShiftCipher(cipher1lower) << std::endl;
    std::cout << "-----------------------------------------------" << std::endl;

    std::cout << "Cipher 2, attempted crack of Vigenere cipher:" << std::endl;
    std::cout << cipher2lower << std::endl;
    std::cout << crackVigenereCipher(cipher2lower) << std::endl;
    std::cout << "-----------------------------------------------" << std::endl;
/*
    std::cout << "Cipher 4, attempted crack of vigenere cipher:" << std::endl;
    std::cout << crackVigenereCipher(cipher4lower) << std::endl;
    std::cout << "-----------------------------------------------" << std::endl;

    //std::cout << crackRailCipher("wireeedseeeacaecvdltnrofo") << std::endl;

    //std::cout << getDeviationFromEnglish(cipher3lower) << std::endl;
    //std::cout << getDeviationFromEnglish(cipher4lower) << std::endl;

    std::cout << crackVigenereCipher(cipher3lower) << std::endl;*/
}

std::string crackShiftCipher(const std::string& ciphertext)
{
    float bestDeviation = 4096;
    std::string currentGuess;
    int best = -1;

    for (std::size_t shift = 0; shift <= 26; shift++)
    {
        std::string copy(ciphertext);
        for (std::size_t j = 0; j < ciphertext.size(); j++)
            copy[j] = (ciphertext[j] - 97 + shift) % 26 + 97;

        float dev = getDeviationFromEnglish(copy);
        if (dev < bestDeviation)
        {
            bestDeviation = dev;
            currentGuess = copy;
            best = shift;
        }
    }

    return currentGuess;
}

std::string crackVigenereCipher(const std::string& ciphertext)
{
    float bestDeviation = 4096;
    std::string currentGuess;

    for (std::size_t keyLength = 1; keyLength <= 20; keyLength++)
    {
        std::string whole(ciphertext); //will be overridden

        for (std::size_t offset = 0; offset < keyLength; offset++)
        {
            std::string subStr;
            for (std::size_t j = offset; j < ciphertext.size(); j += keyLength)
                subStr += ciphertext[j];

            auto cracked = crackShiftCipher(subStr);
            for (std::size_t j = 0; j < subStr.size(); j++)
                whole[j * keyLength + offset] = cracked[j];
        }

        float dev = getDeviationFromEnglish(whole);

        if (dev < bestDeviation)
        {
            bestDeviation = dev;
            currentGuess = whole;

            std::cout << std::endl;
            std::cout << "Better guess! Keylength of " << keyLength << std::endl;
            std::cout << "Deviation from English: " << dev << std::endl;
            std::cout << currentGuess << std::endl;
        }
    }

    return currentGuess;
}

std::string crackRailCipher(const std::string& ciphertext)
{
    int maxKeyLength = 40;
    if (maxKeyLength >= ciphertext.size())
        maxKeyLength = ciphertext.size();

    for (int keyLength = 2; keyLength < maxKeyLength; keyLength++)
    {
        std::string plaintext(ciphertext);

        int cipherIndex = 0;
        for (int offset = 0; offset < keyLength; offset++)
        {
            int diff = (keyLength - 1) * 2 - offset * 2;

            if (offset == keyLength - 1)
                diff = (keyLength - 1) * 2;

            for (int j = offset; j < ciphertext.size(); j += diff)
            {
                plaintext[j] = ciphertext[cipherIndex];
                cipherIndex++;
            }
        }

        std::cout << keyLength << ": " << plaintext << std::endl;
    }

    return "";
}

std::string toLowerCase(const std::string& str)
{
    std::string copy(str);
    std::transform(copy.begin(), copy.end(), copy.begin(), ::tolower);
    return copy;
}

float getDeviationFromEnglish(const std::string& str)
{
    FrequencyMap map;

    for (std::size_t j = 0; j < str.size(); j++)
        map[str[j]] = map[str[j]] + 1;

    auto ENGLISH = getEnglishFrequencyMap();
    float deviation = 0;
    for (auto& x: map)
    {
        float diff = x.second / str.size() - ENGLISH[x.first] / 100;
        deviation += diff * diff;
    }

    return deviation;
}

FrequencyMap getEnglishFrequencyMap()
{
    static FrequencyMap english;

    if (!english.empty())
        return english;

    english['a'] = 8.167f;
    english['b'] = 1.492f;
    english['c'] = 2.783f;
    english['d'] = 4.253f;
    english['e'] = 12.702f;
    english['f'] = 2.228f;
    english['g'] = 2.015f;
    english['h'] = 6.094f;
    english['i'] = 6.966f;
    english['j'] = 0.153f;
    english['k'] = 0.772f;
    english['l'] = 4.025f;
    english['m'] = 2.406f;
    english['n'] = 6.749f;
    english['o'] = 7.507f;
    english['p'] = 1.929f;
    english['q'] = 0.095f;
    english['r'] = 5.987f;
    english['s'] = 6.327f;
    english['t'] = 9.056f;
    english['u'] = 2.758f;
    english['v'] = 0.978f;
    english['w'] = 2.360f;
    english['x'] = 0.150f;
    english['y'] = 1.974f;
    english['z'] = 0.075f;

    return english;
}
<|endoftext|>


<commit_before>#include <signal.h>

#include <iostream>
#include <boost/asio.hpp>
#include <boost/asio/coroutine.hpp>
#include <network/http/server.hpp>
#include <network/http/http_request.hpp>
#include <network/http/http_protocol.hpp>

using namespace network::http;

int main()
{
    boost::asio::io_service io_service;
    network::http::server<http_protocol> server(io_service);

    boost::asio::signal_set signals(io_service);
    signals.add(SIGINT);
    signals.add(SIGTERM);

#if defined(SIGQUIT)
    signals.add(SIGQUIT);
#endif // defined(SIGQUIT)

    signals.async_wait([&](const boost::system::error_code& error, int signal_number) {
        io_service.stop();
    });

    boost::system::error_code ec = server.listen("127.0.0.1", "10081");

    if (ec)
        return 1;

    io_service.run();

    return 0;
}
<commit_msg>不要な include を削除<commit_after>#include <signal.h>

#include <iostream>

#include <boost/asio.hpp>
#include <network/http/server.hpp>
#include <network/http/http_protocol.hpp>

using namespace network::http;

int main()
{
    boost::asio::io_service io_service;
    network::http::server<http_protocol> server(io_service);

    boost::asio::signal_set signals(io_service);
    signals.add(SIGINT);
    signals.add(SIGTERM);

#if defined(SIGQUIT)
    signals.add(SIGQUIT);
#endif // defined(SIGQUIT)

    signals.async_wait([&](const boost::system::error_code& error, int signal_number) {
        io_service.stop();
    });

    boost::system::error_code ec = server.listen("127.0.0.1", "10081");

    if (ec)
        return 1;

    io_service.run();

    return 0;
}
<|endoftext|>


<commit_before>#include "WPILib.h"
#include "../ADBLib/src/ADBLib.h"
#include "auton/AutoBot.h"
#include "DreadbotDIO.h"
#include <unistd.h>
using namespace ADBLib;

class Robot: public IterativeRobot
{
private:
	TractionDrive* drivebase;
	CANTalon* motors[5];
	Joystick* jys;
	Joystick* jys2;
	ADBLib::Controller gpd;
	ADBLib::Controller gpd2;
	Compressor* compressor;
	Preferences* prefs;
	AHRS* ahrs;
	MultiVision* mv;

	SimplePneumatic* shooterPiston;
	SimplePneumatic* liftArm;
	SimplePneumatic* extendArm;
	SimplePneumatic* tail;
	SimplePneumatic* mandibles;
	CANTalon* fan;

	bool armElevAlt; //Stores if the alternate control was used last or not. true = alt, false=regular
	enum {UP, DOWN} armPos;

	AutoBot* autobot;

	void RobotInit()
	{
		//Awful hack in need of replacement
		system("if [ -f \"/sysLog.txt\" ] ; then i=0; while [ -f \"/robologs/sysLog.$i.txt\" ] ; do ((i++)) ; done ; mv \"/sysLog.txt\" \"/robologs/sysLog.$i.txt\" ; fi ;");

		prefs = Preferences::GetInstance();
		compressor = new Compressor(1);
		jys = new Joystick(0);
		jys2 = new Joystick(1);
		gpd.setJoystick(jys);
		gpd2.setJoystick(jys2);
		gpd.parseConfig("/ControlConfig.xml");
		gpd2.parseConfig("/ControlConfig.xml");
		gpd2.switchProfile("secondary");

		for (int i = 1; i < 5; i++)
		{
			motors[i] = new CANTalon(i);
			motors[i]->SetControlMode(CANTalon::kPercentVbus);
			motors[i]->SetVoltageRampRate(0.5);
		}
		motors[2]->SetInverted(true);
		motors[1]->SetInverted(true);
		drivebase = new TractionDrive(motors[4], motors[2], motors[3], motors[1]);
		ahrs = new AHRS(SPI::Port::kMXP);
		mv = new MultiVision;
		mv->switchCamera("cam0");

		liftArm = new SimplePneumatic(new DoubleSolenoid(0, 1));
		shooterPiston = new SimplePneumatic(new Solenoid(3));
		extendArm = new SimplePneumatic(new Solenoid(2));
		tail = new SimplePneumatic(new Solenoid(5));
		mandibles = new SimplePneumatic(new Solenoid(4));
		fan = new CANTalon(5);

		autobot = new AutoBot;
		autobot->init(drivebase, shooterPiston, liftArm, extendArm, ahrs);

		armElevAlt = true;
		armPos = DOWN; //This might result in odd behavior at start

		Logger::log("Finished initializing robot; starting GRIP...", "sysLog");

		//if (fork() == 0)
		//	system("/home/lvuser/grip &");

		Logger::log("Successfully started GRIP!", "sysLog");
	}

	void AutonomousInit()
	{
		Logger::log("Started AUTONOMOUS with mode" + to_string(AutoBot::BREACH) + "!", "sysLog");
		fan->Set(1);
		autobot->switchMode(getAutonMode());
		compressor->Start();
	}

	void AutonomousPeriodic()
	{
		autobot->update();
	}

	void TeleopInit()
	{
		Logger::log("Started TELEOP!", "sysLog");
		compressor->Start();
		fan->Set(1);
		jys->SetRumble(Joystick::kLeftRumble, 1024);
	}

	void TeleopPeriodic()
	{
		//Vision during teleop
		mv->postImage();

		//Primary driver controls
		mandibles->set(gpd["mandibles"]);

		if (gpd["armUp"] || gpd["armDown"])
		{
			armElevAlt = false;
			if (gpd["armUp"])
			{
				armPos = UP;
				liftArm->set(1);
			}
			else if (gpd["armDown"])
			{
				armPos = DOWN;
				liftArm->set(-1);
			}
		}
		if (gpd2["armElevAlt"] != 0 || armElevAlt)
		{
			double input = gpd2["armElevAlt"];
			if (input < 0) //No, these comparisons are NOT flipped. I don't know why though.
			{
				armPos = UP;
				liftArm->set(1);
			}
			else if (input > 0)
			{
				armPos = DOWN;
				liftArm->set(-1);
			}
			else
				liftArm->set(0);
			armElevAlt = true;
		}

		if (gpd["shooter"])
		{ //Shooter behavior varies with arm position
			if (armPos == UP)
			{
				extendArm->set(1);
				Wait(0.49);
				shooterPiston->set(1);
				Wait(0.3);
				shooterPiston->set(0);
			}
			else
			{
				shooterPiston->set(1);
				Wait(0.3);
				shooterPiston->set(0);
			}
		}
		drivebase->drive(0, -gpd["transY"], gpd["rot"]);

		extendArm->set(gpd2["extendArm"]);
		tail->set(gpd2["tail"]);
	}

	void DisabledInit()
	{
		Logger::log("DISABLING robot!", "sysLog");
		Logger::flushLogBuffers();
		compressor->Stop();
		fan->Set(0);
	}

	void TestInit()
	{
		Logger::log("Started TEST!", "sysLog");
		compressor->Start();
	}

	void TestPeriodic()
	{

	}
};

START_ROBOT_CLASS(Robot);
<commit_msg>Add log file saving based on Mr. King's initLog() function<commit_after>#include "WPILib.h"
#include "../ADBLib/src/ADBLib.h"
#include "auton/AutoBot.h"
#include "DreadbotDIO.h"
#include <unistd.h>
#include <dirent.h>
#include <regex>
#include <sys/stat.h>
#include <string>
using namespace ADBLib;
using std::string;

void moveLog();

class Robot: public IterativeRobot
{
private:
	TractionDrive* drivebase;
	CANTalon* motors[5];
	Joystick* jys;
	Joystick* jys2;
	ADBLib::Controller gpd;
	ADBLib::Controller gpd2;
	Compressor* compressor;
	Preferences* prefs;
	AHRS* ahrs;
	MultiVision* mv;

	SimplePneumatic* shooterPiston;
	SimplePneumatic* liftArm;
	SimplePneumatic* extendArm;
	SimplePneumatic* tail;
	SimplePneumatic* mandibles;
	CANTalon* fan;

	bool armElevAlt; //Stores if the alternate control was used last or not. true = alt, false=regular
	enum {UP, DOWN} armPos;

	AutoBot* autobot;

	void RobotInit()
	{
		//Takes the existing sysLog.txt file in / and moves it to /logfiles/
		//Also increments the log file name by a number so old logs are preserved.
		moveLog();

		prefs = Preferences::GetInstance();
		compressor = new Compressor(1);
		jys = new Joystick(0);
		jys2 = new Joystick(1);
		gpd.setJoystick(jys);
		gpd2.setJoystick(jys2);
		gpd.parseConfig("/ControlConfig.xml");
		gpd2.parseConfig("/ControlConfig.xml");
		gpd2.switchProfile("secondary");

		for (int i = 1; i < 5; i++)
		{
			motors[i] = new CANTalon(i);
			motors[i]->SetControlMode(CANTalon::kPercentVbus);
			motors[i]->SetVoltageRampRate(0.5);
		}
		motors[2]->SetInverted(true);
		motors[1]->SetInverted(true);
		drivebase = new TractionDrive(motors[4], motors[2], motors[3], motors[1]);
		ahrs = new AHRS(SPI::Port::kMXP);
		mv = new MultiVision;
		mv->switchCamera("cam0");

		liftArm = new SimplePneumatic(new DoubleSolenoid(0, 1));
		shooterPiston = new SimplePneumatic(new Solenoid(3));
		extendArm = new SimplePneumatic(new Solenoid(2));
		tail = new SimplePneumatic(new Solenoid(5));
		mandibles = new SimplePneumatic(new Solenoid(4));
		fan = new CANTalon(5);

		autobot = new AutoBot;
		autobot->init(drivebase, shooterPiston, liftArm, extendArm, ahrs);

		armElevAlt = true;
		armPos = DOWN; //This might result in odd behavior at start

		Logger::log("Finished initializing robot; starting GRIP...", "sysLog");

		//if (fork() == 0)
		//	system("/home/lvuser/grip &");

		Logger::log("Successfully started GRIP!", "sysLog");
	}

	void AutonomousInit()
	{
		Logger::log("Started AUTONOMOUS with mode" + to_string(AutoBot::BREACH) + "!", "sysLog");
		fan->Set(1);
		autobot->switchMode(getAutonMode());
		compressor->Start();
	}

	void AutonomousPeriodic()
	{
		autobot->update();
	}

	void TeleopInit()
	{
		Logger::log("Started TELEOP!", "sysLog");
		compressor->Start();
		fan->Set(1);
		jys->SetRumble(Joystick::kLeftRumble, 1024);
	}

	void TeleopPeriodic()
	{
		//Vision during teleop
		mv->postImage();

		//Primary driver controls
		mandibles->set(gpd["mandibles"]);

		if (gpd["armUp"] || gpd["armDown"])
		{
			armElevAlt = false;
			if (gpd["armUp"])
			{
				armPos = UP;
				liftArm->set(1);
			}
			else if (gpd["armDown"])
			{
				armPos = DOWN;
				liftArm->set(-1);
			}
		}
		if (gpd2["armElevAlt"] != 0 || armElevAlt)
		{
			double input = gpd2["armElevAlt"];
			if (input < 0) //No, these comparisons are NOT flipped. I don't know why though.
			{
				armPos = UP;
				liftArm->set(1);
			}
			else if (input > 0)
			{
				armPos = DOWN;
				liftArm->set(-1);
			}
			else
				liftArm->set(0);
			armElevAlt = true;
		}

		if (gpd["shooter"])
		{ //Shooter behavior varies with arm position
			if (armPos == UP)
			{
				extendArm->set(1);
				Wait(0.49);
				shooterPiston->set(1);
				Wait(0.3);
				shooterPiston->set(0);
			}
			else
			{
				shooterPiston->set(1);
				Wait(0.3);
				shooterPiston->set(0);
			}
		}
		drivebase->drive(0, -gpd["transY"], gpd["rot"]);

		extendArm->set(gpd2["extendArm"]);
		tail->set(gpd2["tail"]);
	}

	void DisabledInit()
	{
		Logger::log("DISABLING robot!", "sysLog");
		Logger::flushLogBuffers();
		compressor->Stop();
		fan->Set(0);
	}

	void TestInit()
	{
		Logger::log("Started TEST!", "sysLog");
		compressor->Start();
	}

	void TestPeriodic()
	{

	}
};

void moveLog()
{
	//Credit to Mr. King for most of this function. It's been tweaked a lot to
	//CPP-ify it (for the sake of making it easier to explain to new programmers)
	//but everything filesystem-y is from him. Thank you!

	const string logdir = "/";
	const string savedir = "/logfiles/";
	const string prefix = "sysLog";
	const string f_extens = ".txt";

	// Will just give harmless error if directory already exists.
	// If there's a real error we'll catch it when the opendir() call
	// below fails. (returns NULL in case of failure)
	mkdir(savedir.c_str(), 0777);
	DIR* dp = opendir(savedir.c_str());
	if (!dp)
		return;

	// Find the highest existing saved sysLog
	int max = 0;
	std::regex reg("\\d+");
	dirent* ent = readdir(dp);
	while (ent)
	{
		std::smatch matches;
		if (std::regex_search(string(ent->d_name), matches, reg))
		{
			int n = stoi(matches.str(0));
			if (n > max)
				max = n;
		}

		ent = readdir(dp);
	}
	string dst = savedir + prefix + "_" + std::to_string(max + 1) + f_extens;
	rename((logdir + prefix + f_extens).c_str(), dst.c_str());
}

START_ROBOT_CLASS(Robot);
<|endoftext|>


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

#include "joynr/exceptions/JoynrException.h"
#include "joynr/JoynrRuntime.h"
#include "joynr/Settings.h"
#include "joynr/tests/DefaultMultipleVersionsInterfaceProvider.h"
#include "joynr/tests/DefaultMultipleVersionsInterface1Provider.h"
#include "joynr/tests/DefaultMultipleVersionsInterface2Provider.h"
#include "joynr/tests/MultipleVersionsInterface1Proxy.h"
#include "joynr/tests/MultipleVersionsInterface2Proxy.h"
#include "joynr/tests/v2/MultipleVersionsInterfaceProxy.h"

#include "tests/JoynrTest.h"

using namespace ::testing;
using namespace joynr;

class MultipleVersionsTest : public Test
{
protected:
    MultipleVersionsTest()
    {
    }

    void SetUp() override
    {
        runtime1 = JoynrRuntime::createRuntime(
                std::make_unique<Settings>("test-resources/libjoynrSystemIntegration1.settings"),
                failOnFatalRuntimeError);
        runtime2 = JoynrRuntime::createRuntime(
                std::make_unique<Settings>("test-resources/libjoynrSystemIntegration2.settings"),
                failOnFatalRuntimeError);
        discoveryQos.setDiscoveryTimeoutMs(100);
        discoveryQos.setDiscoveryScope(types::DiscoveryScope::LOCAL_ONLY);
        providerQos.setScope(types::ProviderScope::LOCAL);
    }

    void TearDown() override
    {
        test::util::removeAllCreatedSettingsAndPersistencyFiles();
    }

    template <typename T>
    std::shared_ptr<T> buildProxy(std::shared_ptr<JoynrRuntime> runtime)
    {
        std::shared_ptr<ProxyBuilder<T>> testProxyBuilder(
                runtime->createProxyBuilder<T>(testDomain));
        return testProxyBuilder->setMessagingQos(messagingQos)
                ->setDiscoveryQos(discoveryQos)
                ->build();
    }

    /**
     * Builds a proxy of type T in the specified runtime. Then sets UInt8Attribute1
     * to the specified value and checks if the set value can be retrieved correctly.
     *
     * @param runtime Builds the proxy in runtime.
     * @param value Sets the attribute to value.
     */
    template <typename T>
    void setAndCheckAttribute(std::shared_ptr<JoynrRuntime> runtime, const uint8_t value)
    {
        std::shared_ptr<T> testProxy = buildProxy<T>(runtime);

        uint8_t uInt8Result = 0;

        testProxy->setUInt8Attribute1(value);
        testProxy->getUInt8Attribute1(uInt8Result);

        ASSERT_EQ(value, uInt8Result);
    }

    /**
     * Registers 2 providers and a fitting proxy for each. Then checks if methods of the providers
     *can be called correctly.
     *
     * @param secondRuntime If this is set to true, the second provider and its proxy are
     *registered/build in a second runtime.
     */
    void buildTwoProvidersAndPerformChecks(bool secondRuntime)
    {
        std::shared_ptr<JoynrRuntime> selectedRuntime;
        if (secondRuntime) {
            selectedRuntime = runtime2;
        } else {
            selectedRuntime = runtime1;
        }

        auto testProvider1 = std::make_shared<tests::DefaultMultipleVersionsInterface1Provider>();
        runtime1->registerProvider<tests::MultipleVersionsInterface1Provider>(
                testDomain, testProvider1, providerQos);
        auto testProvider2 = std::make_shared<tests::DefaultMultipleVersionsInterface2Provider>();
        selectedRuntime->registerProvider<tests::MultipleVersionsInterface2Provider>(
                testDomain, testProvider2, providerQos);

        setAndCheckAttribute<tests::MultipleVersionsInterface1Proxy>(
                runtime1, expectedUInt8Result1);
        setAndCheckAttribute<tests::MultipleVersionsInterface2Proxy>(
                selectedRuntime, expectedUInt8Result2);

        runtime1->unregisterProvider<tests::MultipleVersionsInterface1Provider>(
                testDomain, testProvider1);
        selectedRuntime->unregisterProvider<tests::MultipleVersionsInterface2Provider>(
                testDomain, testProvider2);
    }

    const std::string testDomain = "multipleVersionsTestDomain";
    const uint8_t expectedUInt8Result1 = 50;
    const uint8_t expectedUInt8Result2 = 100;

    DiscoveryQos discoveryQos;
    MessagingQos messagingQos;
    types::ProviderQos providerQos;
    std::shared_ptr<JoynrRuntime> runtime1;
    std::shared_ptr<JoynrRuntime> runtime2;

private:
    DISALLOW_COPY_AND_ASSIGN(MultipleVersionsTest);
};

TEST_F(MultipleVersionsTest, twoProxiesOfDifferentVersioningTypesVsOneProvider)
{
    auto testProvider = std::make_shared<tests::DefaultMultipleVersionsInterfaceProvider>();
    runtime1->registerProvider<tests::MultipleVersionsInterfaceProvider>(
            testDomain, testProvider, providerQos);

    setAndCheckAttribute<tests::MultipleVersionsInterface2Proxy>(runtime1, expectedUInt8Result1);
    setAndCheckAttribute<tests::v2::MultipleVersionsInterfaceProxy>(runtime1, expectedUInt8Result2);

    runtime1->unregisterProvider<tests::MultipleVersionsInterfaceProvider>(
            testDomain, testProvider);
}

TEST_F(MultipleVersionsTest, twoProvidersOfDifferentVersionsAndTwoFittingProxiesInSingleRuntime)
{
    buildTwoProvidersAndPerformChecks(false);
}

TEST_F(MultipleVersionsTest, twoProvidersWithFittingProxiesInDifferentRuntimes)
{
    buildTwoProvidersAndPerformChecks(true);
}
<commit_msg>[C++] Fixed MultipleVersionsTest by using separate CC settings per runtime<commit_after>/*
 * #%L
 * %%
 * Copyright (C) 2018 BMW Car IT GmbH
 * %%
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * #L%
 */
#include <gtest/gtest.h>

#include "joynr/exceptions/JoynrException.h"
#include "joynr/JoynrRuntime.h"
#include "joynr/Settings.h"
#include "joynr/tests/DefaultMultipleVersionsInterfaceProvider.h"
#include "joynr/tests/DefaultMultipleVersionsInterface1Provider.h"
#include "joynr/tests/DefaultMultipleVersionsInterface2Provider.h"
#include "joynr/tests/MultipleVersionsInterface1Proxy.h"
#include "joynr/tests/MultipleVersionsInterface2Proxy.h"
#include "joynr/tests/v2/MultipleVersionsInterfaceProxy.h"

#include "tests/JoynrTest.h"

using namespace ::testing;
using namespace joynr;

class MultipleVersionsTest : public Test
{
protected:
    MultipleVersionsTest()
    {
    }

    void SetUp() override
    {
        const Settings libjoynrSettings1("test-resources/libjoynrSystemIntegration1.settings");
        const Settings libjoynrSettings2("test-resources/libjoynrSystemIntegration2.settings");
        auto settings1 = std::make_unique<Settings>("test-resources/MqttSystemIntegrationTest1.settings");
        auto settings2 = std::make_unique<Settings>("test-resources/MqttSystemIntegrationTest2.settings");
        Settings::merge(libjoynrSettings1, *settings1, false);
        Settings::merge(libjoynrSettings2, *settings2, false);

        runtime1 = JoynrRuntime::createRuntime(std::move(settings1), failOnFatalRuntimeError);
        runtime2 = JoynrRuntime::createRuntime(std::move(settings2), failOnFatalRuntimeError);
        discoveryQos.setDiscoveryTimeoutMs(100);
        discoveryQos.setDiscoveryScope(types::DiscoveryScope::LOCAL_ONLY);
        providerQos.setScope(types::ProviderScope::LOCAL);
    }

    void TearDown() override
    {
        test::util::removeAllCreatedSettingsAndPersistencyFiles();
    }

    template <typename T>
    std::shared_ptr<T> buildProxy(std::shared_ptr<JoynrRuntime> runtime)
    {
        std::shared_ptr<ProxyBuilder<T>> testProxyBuilder(
                runtime->createProxyBuilder<T>(testDomain));
        return testProxyBuilder->setMessagingQos(messagingQos)
                ->setDiscoveryQos(discoveryQos)
                ->build();
    }

    /**
     * Builds a proxy of type T in the specified runtime. Then sets UInt8Attribute1
     * to the specified value and checks if the set value can be retrieved correctly.
     *
     * @param runtime Builds the proxy in runtime.
     * @param value Sets the attribute to value.
     */
    template <typename T>
    void setAndCheckAttribute(std::shared_ptr<JoynrRuntime> runtime, const uint8_t value)
    {
        std::shared_ptr<T> testProxy = buildProxy<T>(runtime);

        uint8_t uInt8Result = 0;

        testProxy->setUInt8Attribute1(value);
        testProxy->getUInt8Attribute1(uInt8Result);

        ASSERT_EQ(value, uInt8Result);
    }

    /**
     * Registers 2 providers and a fitting proxy for each. Then checks if methods of the providers
     *can be called correctly.
     *
     * @param secondRuntime If this is set to true, the second provider and its proxy are
     *registered/build in a second runtime.
     */
    void buildTwoProvidersAndPerformChecks(bool secondRuntime)
    {
        std::shared_ptr<JoynrRuntime> selectedRuntime;
        if (secondRuntime) {
            selectedRuntime = runtime2;
        } else {
            selectedRuntime = runtime1;
        }

        auto testProvider1 = std::make_shared<tests::DefaultMultipleVersionsInterface1Provider>();
        runtime1->registerProvider<tests::MultipleVersionsInterface1Provider>(
                testDomain, testProvider1, providerQos);
        auto testProvider2 = std::make_shared<tests::DefaultMultipleVersionsInterface2Provider>();
        selectedRuntime->registerProvider<tests::MultipleVersionsInterface2Provider>(
                testDomain, testProvider2, providerQos);

        setAndCheckAttribute<tests::MultipleVersionsInterface1Proxy>(
                runtime1, expectedUInt8Result1);
        setAndCheckAttribute<tests::MultipleVersionsInterface2Proxy>(
                selectedRuntime, expectedUInt8Result2);

        runtime1->unregisterProvider<tests::MultipleVersionsInterface1Provider>(
                testDomain, testProvider1);
        selectedRuntime->unregisterProvider<tests::MultipleVersionsInterface2Provider>(
                testDomain, testProvider2);
    }

    const std::string testDomain = "multipleVersionsTestDomain";
    const uint8_t expectedUInt8Result1 = 50;
    const uint8_t expectedUInt8Result2 = 100;

    DiscoveryQos discoveryQos;
    MessagingQos messagingQos;
    types::ProviderQos providerQos;
    std::shared_ptr<JoynrRuntime> runtime1;
    std::shared_ptr<JoynrRuntime> runtime2;

private:
    DISALLOW_COPY_AND_ASSIGN(MultipleVersionsTest);
};

TEST_F(MultipleVersionsTest, twoProxiesOfDifferentVersioningTypesVsOneProvider)
{
    auto testProvider = std::make_shared<tests::DefaultMultipleVersionsInterfaceProvider>();
    runtime1->registerProvider<tests::MultipleVersionsInterfaceProvider>(
            testDomain, testProvider, providerQos);

    setAndCheckAttribute<tests::MultipleVersionsInterface2Proxy>(runtime1, expectedUInt8Result1);
    setAndCheckAttribute<tests::v2::MultipleVersionsInterfaceProxy>(runtime1, expectedUInt8Result2);

    runtime1->unregisterProvider<tests::MultipleVersionsInterfaceProvider>(
            testDomain, testProvider);
}

TEST_F(MultipleVersionsTest, twoProvidersOfDifferentVersionsAndTwoFittingProxiesInSingleRuntime)
{
    buildTwoProvidersAndPerformChecks(false);
}

TEST_F(MultipleVersionsTest, twoProvidersWithFittingProxiesInDifferentRuntimes)
{
    buildTwoProvidersAndPerformChecks(true);
}
<|endoftext|>