<commit_before>#include <iostream>
#include <iomanip> // << fixed << setprecision(xxx)
#include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ;
#include <vector>
#include <string> // to_string(nnn) // substr(m, n) // stoi(nnn)
#include <complex>
#include <tuple> // get<n>(xxx)
#include <queue>
#include <stack>
#include <map> // if (M.find(key) != M.end()) { }
#include <set> // S.insert(M);
// if (S.find(key) != S.end()) { }
// for (auto it=S.begin(); it != S.end(); it++) { }
// auto it = S.lower_bound(M);
#include <random> // random_device rd; mt19937 mt(rd());
#include <cctype>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib> // atoi(xxx)
using namespace std;

#define DEBUG 0 // change 0 -> 1 if we need debug.
// insert #if<tab> by my emacs. #if DEBUG == 1 ... #end

typedef long long ll;

// const int dx[4] = {1, 0, -1, 0};
// const int dy[4] = {0, 1, 0, -1};

// const int C = 1e6+10;
// const ll M = 1000000007;

int R, C;
string S[50];

vector<vector<bool> > V[50];

void make_V() {
  vector<bool> emp;
  V[0].push_back(emp);
  for (auto k = 0; k < C; ++k) {
    if (S[0][k] == '.') {
      for (auto x : V[k]) {
        x.push_back(true);
        x.push_back(false);
        V[x.size()].push_back(x);
      }
      for (auto x : V[k]) {
        x.push_back(false);
        V[x.size()].push_back(x);
      }
    } else {
      for (auto x : V[k]) {
        x.push_back(false);
        V[x.size()].push_back(x);
      }
    }
  }
}

int main () {
  cin >> R >> C;
  for (auto i = 0; i < R; ++i) {
    cin >> S[i];
  }
  make_V();
  int ans = 0;
  for (auto x : V[C]) {
    bool f[50][50];
    for (auto i = 0; i < C; ++i) {
      f[0][i] = x[i];
    }
    for (auto i = 1; i < R; ++i) {
      for (auto j = 0; j < C; ++j) {
        if (!f[i-1][j] && (j == 0 || !f[i][j-1]) && S[i][j] == '.') {
          f[i][j] = true;
        } else {
          f[i][j] = false;
        }
      }
    }
    int tans = 0;
    for (auto i = 0; i < R; ++i) {
      for (auto j = 0; j < C; ++j) {
        if (f[i][j]) tans++;
#if DEBUG == 1
        cerr << (f[i][j] ? '#' : ((S[i][j] == '.') ? '.' : '*'));
#endif
      }
      cerr << endl;
    }
#if DEBUG == 1
    cerr << tans << endl;
#endif
    ans = max(ans, tans);
  }
  cout << ans << endl;
}
<commit_msg>tried C.cpp to 'C'<commit_after>#include <iostream>
#include <iomanip> // << fixed << setprecision(xxx)
#include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ;
#include <vector>
#include <string> // to_string(nnn) // substr(m, n) // stoi(nnn)
#include <complex>
#include <tuple> // get<n>(xxx)
#include <queue>
#include <stack>
#include <map> // if (M.find(key) != M.end()) { }
#include <set> // S.insert(M);
// if (S.find(key) != S.end()) { }
// for (auto it=S.begin(); it != S.end(); it++) { }
// auto it = S.lower_bound(M);
#include <random> // random_device rd; mt19937 mt(rd());
#include <cctype>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib> // atoi(xxx)
using namespace std;

#define DEBUG 1 // change 0 -> 1 if we need debug.
// insert #if<tab> by my emacs. #if DEBUG == 1 ... #end

typedef long long ll;

// const int dx[4] = {1, 0, -1, 0};
// const int dy[4] = {0, 1, 0, -1};

// const int C = 1e6+10;
// const ll M = 1000000007;

int R, C;
string S[50];

vector<vector<bool> > V[50];

void make_V() {
  vector<bool> emp;
  V[0].push_back(emp);
  for (auto k = 0; k < C; ++k) {
    if (S[0][k] == '.') {
      for (auto x : V[k]) {
        x.push_back(true);
        x.push_back(false);
        V[x.size()].push_back(x);
      }
      for (auto x : V[k]) {
        x.push_back(false);
        V[x.size()].push_back(x);
      }
    } else {
      for (auto x : V[k]) {
        x.push_back(false);
        V[x.size()].push_back(x);
      }
    }
  }
}

int main () {
  cin >> R >> C;
  for (auto i = 0; i < R; ++i) {
    cin >> S[i];
  }
  make_V();
  int ans = 0;
  for (auto x : V[C]) {
    bool f[50][50];
    for (auto i = 0; i < C; ++i) {
      f[0][i] = x[i];
    }
    for (auto i = 1; i < R; ++i) {
      for (auto j = 0; j < C; ++j) {
        if (!f[i-1][j] && (j == 0 || !f[i][j-1]) && S[i][j] == '.') {
          f[i][j] = true;
        } else {
          f[i][j] = false;
        }
      }
    }
    int tans = 0;
    for (auto i = 0; i < R; ++i) {
      for (auto j = 0; j < C; ++j) {
        if (f[i][j]) tans++;
#if DEBUG == 1
        cerr << (f[i][j] ? '#' : ((S[i][j] == '.') ? '.' : '*'));
#endif
      }
#if DEBUG == 1
      cerr << endl;
#endif
    }
#if DEBUG == 1
    cerr << tans << endl;
#endif
    ans = max(ans, tans);
  }
  cout << ans << endl;
}
<|endoftext|>


<commit_before>// This file doesn't adhere to the standard EABI !

#include "common.th"

#define ROWS 40
#define COLS 80
#define SIZEOF_SNAKE 4

_start:
#ifndef SIM
    bare_metal_init()
#endif
    prologue

#ifndef SIM
    call(init_display)
    call(disable_cursor)
#endif

#ifdef TEST
    c <- rel(_start) ; call(srand) # seed based on where we are loaded
#endif

    n <- rel(snakes)
    e <- rel(snakes_after)
init:
    call(rand)
    j <- b >> 27 // 5 bits
    k <- b >> 21 ; k <- k & 0x3f // 6 bits
    j <- j + ((40 - 32) / 2) ; j -> [n + 2]
    k <- k + ((80 - 64) / 2) ; k -> [n + 3]

    n <- n + SIZEOF_SNAKE
    j <- n < e
    jnzrel(j,init)

    g <- -1 // constant
L_loop:
    n <- rel(snakes)
L_snake:
    // j:k = row:col
    j <- [n + 2]
    k <- [n + 3]

    // direction and character choice are not independent variables
    call(rand)
    f <- b // save away random value for later
    d <- f >> 30 // a direction 0 - 3 ; clockwise, 0 = up

    // start get_incrs
    // direction map
    // 0 -> -1  0
    // 1 ->  0  1
    // 2 ->  1  0
    // 3 ->  0 -1

    h <- d & 1 + g // 1 -> 0, 0 -> -1
    i <- d & 2 + g // 2 -> 1, 0 -> -1

    b <- i & h
    c <- -i
    c <- c &~ h

    // end get_incrs

    j <- j + b
    k <- k + c

    // start clamp
    // Check for out-of-bounds and bounce off the wall
    b <- j >= ROWS  ; j <- b << 1 + j
    b <- j >= a + 1 ; j <- b << 1 + j
    c <- k >= COLS  ; k <- c << 1 + k
    c <- k >= a + 1 ; k <- c << 1 + k
    // end clamp

    j -> [n + 2] // store new row, col
    k -> [n + 3]

    i <- [n + 1]
    c <- f >> i
    h <- i <> 0 // special case when shift-value is zero : no randomness
    c <- c & h
    h <- [n + 0]
    c <- c + h
    d <- j * 80 + k     // d is offset into display
    e <- 0x100
    e <- e << 8         // e is video base
    c -> [e + d + 0x10] // e is d characters past start of text region

    n <- n + SIZEOF_SNAKE
    e <- rel(snakes_after)
    j <- n < e
    jnzrel(j,L_snake)
    goto(L_loop) // infinite loop

snakes:
    // base type, shift distance for rand(), row, col
    .word 'A', 28, 0, 0;
    .word '0', 29, 0, 0;
    .word '-', 31, 0, 0;
    .word ':', 31, 0, 0;
    .word '*', 31, 0, 0;
    .word '(', 31, 0, 0;

    .word ' ',  0, 0, 0; // eraser snakes
    .word ' ',  0, 0, 0;
    .word ' ',  0, 0, 0;
    .word ' ',  0, 0, 0;
    .word ' ',  0, 0, 0;
    .word ' ',  0, 0, 0;
snakes_after: .word 0

<commit_msg>Update bm_snake for new VRAM address from cff20a<commit_after>// This file doesn't adhere to the standard EABI !

#include "common.th"

#define ROWS 40
#define COLS 80
#define SIZEOF_SNAKE 4

_start:
#ifndef SIM
    bare_metal_init()
#endif
    prologue

#ifndef SIM
    call(init_display)
    call(disable_cursor)
#endif

#ifdef TEST
    c <- rel(_start) ; call(srand) # seed based on where we are loaded
#endif

    n <- rel(snakes)
    e <- rel(snakes_after)
init:
    call(rand)
    j <- b >> 27 // 5 bits
    k <- b >> 21 ; k <- k & 0x3f // 6 bits
    j <- j + ((40 - 32) / 2) ; j -> [n + 2]
    k <- k + ((80 - 64) / 2) ; k -> [n + 3]

    n <- n + SIZEOF_SNAKE
    j <- n < e
    jnzrel(j,init)

    g <- -1 // constant
L_loop:
    n <- rel(snakes)
L_snake:
    // j:k = row:col
    j <- [n + 2]
    k <- [n + 3]

    // direction and character choice are not independent variables
    call(rand)
    f <- b // save away random value for later
    d <- f >> 30 // a direction 0 - 3 ; clockwise, 0 = up

    // start get_incrs
    // direction map
    // 0 -> -1  0
    // 1 ->  0  1
    // 2 ->  1  0
    // 3 ->  0 -1

    h <- d & 1 + g // 1 -> 0, 0 -> -1
    i <- d & 2 + g // 2 -> 1, 0 -> -1

    b <- i & h
    c <- -i
    c <- c &~ h

    // end get_incrs

    j <- j + b
    k <- k + c

    // start clamp
    // Check for out-of-bounds and bounce off the wall
    b <- j >= ROWS  ; j <- b << 1 + j
    b <- j >= a + 1 ; j <- b << 1 + j
    c <- k >= COLS  ; k <- c << 1 + k
    c <- k >= a + 1 ; k <- c << 1 + k
    // end clamp

    j -> [n + 2] // store new row, col
    k -> [n + 3]

    i <- [n + 1]
    c <- f >> i
    h <- i <> 0 // special case when shift-value is zero : no randomness
    c <- c & h
    h <- [n + 0]
    c <- c + h
    d <- j * 80 + k     // d is offset into display
    e <- 0x100
    e <- e << 8         // e is video base
    c -> [e + d]        // e is d characters past start of text region

    n <- n + SIZEOF_SNAKE
    e <- rel(snakes_after)
    j <- n < e
    jnzrel(j,L_snake)
    goto(L_loop) // infinite loop

snakes:
    // base type, shift distance for rand(), row, col
    .word 'A', 28, 0, 0;
    .word '0', 29, 0, 0;
    .word '-', 31, 0, 0;
    .word ':', 31, 0, 0;
    .word '*', 31, 0, 0;
    .word '(', 31, 0, 0;

    .word ' ',  0, 0, 0; // eraser snakes
    .word ' ',  0, 0, 0;
    .word ' ',  0, 0, 0;
    .word ' ',  0, 0, 0;
    .word ' ',  0, 0, 0;
    .word ' ',  0, 0, 0;
snakes_after: .word 0

<|endoftext|>


<commit_before>#pragma once

namespace rs {
	//! 単なる型のラッパー
	/*! Idか普通の数値かでオーバーロードしたい場合なんかに使用 */
	template <class T>
	struct Wrapper {
		T	value;
		Wrapper() = default;
		explicit Wrapper(const T& t): value(t) {}

		// 数値と明確に区別したいので暗黙的な変換はしない
	};
}
<commit_msg>wrapper: 各種比較演算子を定義<commit_after>#pragma once

namespace rs {
	//! 単なる型のラッパー
	/*! Idか普通の数値かでオーバーロードしたい場合なんかに使用 */
	template <class T>
	struct Wrapper {
		T	value;
		Wrapper() = default;
		explicit Wrapper(const T& t): value(t) {}
		// 数値と明確に区別したいので暗黙的な変換はしない

		#define DEF_OP(op) \
			bool operator op (const T& t) const { return value op t; } \
			bool operator op (const Wrapper& w) const { return value op w.value; }
			DEF_OP(==)
			DEF_OP(!=)
			DEF_OP(<)
			DEF_OP(>)
			DEF_OP(<=)
			DEF_OP(>=)
		#undef DEF_OP
	};
}
<|endoftext|>


<commit_before>#define DEBUG 1

/**
 * File    : C.cpp
 * Author  : Kazune Takahashi
 * Created : 2019-3-30 21:04:45
 * Powered by Visual Studio Code
 */

#include <iostream>
#include <iomanip>   // << fixed << setprecision(xxx)
#include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ;
#include <vector>
#include <string> // to_string(nnn) // substr(m, n) // stoi(nnn)
#include <complex>
#include <tuple>
#include <queue>
#include <stack>
#include <map> // if (M.find(key) != M.end()) { }
#include <set>
#include <functional>
#include <random> // auto rd = bind(uniform_int_distribution<int>(0, 9), mt19937(10101010));
#include <chrono> // std::chrono::system_clock::time_point start_time, end_time;
// start = std::chrono::system_clock::now();
// double elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(end_time-start_time).count();
#include <cctype>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib>
using namespace std;

typedef long long ll;

// const int dx[4] = {1, 0, -1, 0};
// const int dy[4] = {0, 1, 0, -1};

// const int C = 1e6+10;
// const ll M = 1000000007;

int N, Q;
string S;
string T = "";
string D = "";

int f(int n)
{
  for (auto i = 0; i < Q; i++)
  {
    if (S[n] == T[i])
    {
      if (D[i] == 'L')
      {
        n--;
      }
      else
      {
        n++;
      }
    }
    if (!(0 <= n && n < N))
    {
      return n;
    }
  }
  return n;
}

int main()
{
  cin >> N >> Q;
  for (auto i = 0; i < N; i++)
  {
    string t, d;
    cin >> t >> d;
    T = T + t;
    D = D + d;
  }
  int ok = N;
  int ng = -1;
  while (abs(ok - ng) > 1)
  {
    int t = (ok + ng) / 2;
    if (f(t) == -1)
    {
      ng = t;
    }
    else
    {
      ok = t;
    }
  }
  int left = ok;
  ok = -1;
  ng = N;
  while (abs(ok - ng) > 1)
  {
    int t = (ok + ng) / 2;
    if (f(t) == N)
    {
      ng = t;
    }
    else
    {
      ok = t;
    }
  }
  int right = ok;
  cout << right - left + 1 << endl;
}<commit_msg>tried C.cpp to 'C'<commit_after>#define DEBUG 1

/**
 * File    : C.cpp
 * Author  : Kazune Takahashi
 * Created : 2019-3-30 21:04:45
 * Powered by Visual Studio Code
 */

#include <iostream>
#include <iomanip>   // << fixed << setprecision(xxx)
#include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ;
#include <vector>
#include <string> // to_string(nnn) // substr(m, n) // stoi(nnn)
#include <complex>
#include <tuple>
#include <queue>
#include <stack>
#include <map> // if (M.find(key) != M.end()) { }
#include <set>
#include <functional>
#include <random> // auto rd = bind(uniform_int_distribution<int>(0, 9), mt19937(10101010));
#include <chrono> // std::chrono::system_clock::time_point start_time, end_time;
// start = std::chrono::system_clock::now();
// double elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(end_time-start_time).count();
#include <cctype>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib>
using namespace std;

typedef long long ll;

// const int dx[4] = {1, 0, -1, 0};
// const int dy[4] = {0, 1, 0, -1};

// const int C = 1e6+10;
// const ll M = 1000000007;

int N, Q;
string S;
string T = "";
string D = "";

int f(int n)
{
  for (auto i = 0; i < Q; i++)
  {
    if (S[n] == T[i])
    {
      if (D[i] == 'L')
      {
        n--;
      }
      else
      {
        n++;
      }
    }
    if (!(0 <= n && n < N))
    {
      return n;
    }
  }
  return n;
}

int main()
{
  cin >> N >> Q;
  for (auto i = 0; i < N; i++)
  {
    string t, d;
    cin >> t >> d;
    T = T + t;
    D = D + d;
  }
  int ok = N;
  int ng = -1;
  while (abs(ok - ng) > 1)
  {
    int t = (ok + ng) / 2;
    if (f(t) == -1)
    {
      ng = t;
    }
    else
    {
      ok = t;
    }
  }
  int left = ok;
  ok = -1;
  ng = N;
  while (abs(ok - ng) > 1)
  {
    int t = (ok + ng) / 2;
    if (f(t) == N)
    {
      ng = t;
    }
    else
    {
      ok = t;
    }
  }
  int right = ok;
#if DEBUG == 1
  cerr << "left = " << left << ", right = " << right << endl;
  cerr << "f(" << left << ") = " << f(left) << endl;
  cerr << "f(" << right << ") = " << f(right) << endl;
#endif
  cout << right - left + 1 << endl;
}<|endoftext|>


<commit_before><commit_msg>add note in crash handler<commit_after><|endoftext|>


<commit_before>#include "Rolenator.h"

Rolenator::Rolenator()
{
	QTextCodec::setCodecForCStrings(QTextCodec::codecForName("UTF-8"));
	this->db = QSqlDatabase::addDatabase("QMYSQL","db");
	this->db.setHostName("localhost");
	this->db.setDatabaseName("rolenator");
	this->db.setPort(3307);
	this->db.setUserName("root");
	this->db.setPassword("brs42");
	if(!this->db.open())
		std::cout << "Error opening the database connection!\n";
	this->loginHandler = new LoginHandler(this);
	DAORegistry::setUserDAO(new UserDAO(&this->db));
	DAORegistry::setEventDAO(new EventDAO(&this->db));
	DAORegistry::setInviteDAO(new InviteDAO(&this->db));
	DAORegistry::setMessageDAO(new MessageDAO(&this->db));
	/*

	this->viewEventHandler = new ViewEventHandler(this,event);*/
}

Rolenator::~Rolenator()
{
	this->db.close();
}

void Rolenator::goToRegister(){
	delete this->loginHandler;
	this->registerHandler = new RegisterHandler(this);
}

void Rolenator::goToLogin(){
	//delete handler;
	this->loginHandler = new LoginHandler(this);
}

void Rolenator::goToEdit(Event* event){
	//this->eventEditHandler = new EventEditHandler(this,event,user);
}

#include "Rolenator.moc"
<commit_msg>A online database<commit_after>#include "Rolenator.h"

Rolenator::Rolenator()
{
	QTextCodec::setCodecForCStrings(QTextCodec::codecForName("UTF-8"));
	this->db = QSqlDatabase::addDatabase("QMYSQL","db");
	this->db.setHostName("db4free.net");
	this->db.setDatabaseName("rolenator");
	this->db.setPort(3306);
	this->db.setUserName("killertux");
	this->db.setPassword("mtfbwy");

	/*this->db.setHostName("localhost");
	this->db.setDatabaseName("rolenator");
	this->db.setPort(3307);
	this->db.setUserName("root");
	this->db.setPassword("brs42");*/

	if(!this->db.open())
		std::cout << "Error opening the database connection!\n";
	this->loginHandler = new LoginHandler(this);
	DAORegistry::setUserDAO(new UserDAO(&this->db));
	DAORegistry::setEventDAO(new EventDAO(&this->db));
	DAORegistry::setInviteDAO(new InviteDAO(&this->db));
	DAORegistry::setMessageDAO(new MessageDAO(&this->db));
	/*

	this->viewEventHandler = new ViewEventHandler(this,event);*/
}

Rolenator::~Rolenator()
{
	this->db.close();
}

void Rolenator::goToRegister(){
	delete this->loginHandler;
	this->registerHandler = new RegisterHandler(this);
}

void Rolenator::goToLogin(){
	//delete handler;
	this->loginHandler = new LoginHandler(this);
}

void Rolenator::goToEdit(Event* event){
	//this->eventEditHandler = new EventEditHandler(this,event,user);
}

#include "Rolenator.moc"
<|endoftext|>


<commit_before>#include <QApplication>
#include <QDataStream>
#include <QErrorMessage>
#include <QFile>
#include <QFileDialog>
#include <QHBoxLayout>
#include <QIODevice>
#include <QLabel>
#include <QLocalServer>
#include <QLocalSocket>
#include <QNetworkAccessManager>
#include <QNetworkReply>
#include <QNetworkRequest>
#include <QProgressBar>
#include <QPushButton>
#include <QVBoxLayout>
#include <QWidget>

#define USER_AGENT  "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko)" \
                    "Chrome/55.0.0.0 Safari/537.36 DobosTorta/dev-" GIT_VERSION

#define CONNECTION_NAME  "dobostorta-downloader.sock"

class TortaRequestHandler : public QLocalServer {
Q_OBJECT

private:
    TortaRequestHandler() {
        listen(CONNECTION_NAME);
        connect(this, &QLocalServer::newConnection, this, &TortaRequestHandler::newConnection);
    }

    void newConnection() {
        QLocalSocket *sock = nextPendingConnection();
        connect(sock, &QLocalSocket::disconnected, sock, &QLocalSocket::close);

        sock->waitForReadyRead();

        QDataStream stream(sock);
        QByteArray data;
        stream >> data;
        emit receivedRequest({data});
    }

public:
    ~TortaRequestHandler() {
        close();
    }

    static TortaRequestHandler *open() {
        auto server = new TortaRequestHandler();
        if (server->isListening())
            return server;

        delete server;
        return nullptr;
    }

    static bool request(const QUrl &url) {
        QLocalSocket sock;
        sock.connectToServer(CONNECTION_NAME);

        if (!sock.isValid()) {
            qCritical() << tr("Failed to open socket: ") << sock.errorString();
            return false;
        }

        QByteArray block;
        QDataStream stream(&block, QIODevice::WriteOnly);
        stream << url.toEncoded();
        sock.write(block);

        sock.waitForBytesWritten();

        return true;
    }

signals:
    void receivedRequest(const QUrl &url);
};

class TortaDownload : public QWidget {
Q_OBJECT

private:
    QNetworkReply * const reply;
    QVBoxLayout layout;
    QProgressBar progress;
    QPushButton button;

    void saveTo(const QString &path) {
        QFile file(path);
        if (!file.open(QIODevice::WriteOnly)) {
            (new QErrorMessage(this))->showMessage(tr("Failed open %1: %2")
                                                   .arg(path).arg(file.errorString()));
            return;
        }

        file.write(reply->readAll());
        file.close();
    }

public:
    TortaDownload(QWidget *parent, QNetworkReply *reply, const QString &filePath)
            : QWidget(parent), reply(reply), layout(this), progress(this), button("cancel", this) {
        setLayout(&layout);

        auto horizontal = new QHBoxLayout;
        layout.addLayout(horizontal);

        auto left = new QVBoxLayout;
        horizontal->addLayout(left, 1);

        QFileInfo info(filePath);
        auto path = new QHBoxLayout;
        path->setAlignment(Qt::AlignLeft);
        path->setSpacing(0);
        left->addLayout(path);
        auto fpath = new QLabel(info.dir().path() + "/", this);
        path->addWidget(fpath);
        auto fname = new QLabel(info.fileName(), this);
        fname->setStyleSheet("font-weight: bold;");
        path->addWidget(fname);

        auto url = new QLabel(QString("%1").arg(reply->url().toString()),
                              this);
        url->setOpenExternalLinks(true);
        left->addWidget(url);

        horizontal->addWidget(&button);
        connect(&button, &QPushButton::clicked, [this, reply]{
            if (reply->isRunning())
                reply->abort();
            else
                emit clear();
        });

        layout.addWidget(&progress);

        connect(reply, &QNetworkReply::downloadProgress, [this](qint64 received, qint64 total){
            progress.setRange(0, total);
            progress.setValue(received);
        });
        connect(reply, &QNetworkReply::finished, [this, filePath, reply]{
            if (reply->error() && reply->error() != QNetworkReply::OperationCanceledError) {
                (new QErrorMessage(this))->showMessage(tr("Failed download: %1")
                                                       .arg(reply->errorString()));
            } else {
                progress.setValue(progress.maximum());
                saveTo(filePath);
            }
            button.setText("clear");
        });
    }

signals:
    void clear();
};

class TortaDL : public QWidget {
Q_OBJECT

private:
    QVBoxLayout layout;
    QNetworkAccessManager manager;
    TortaRequestHandler *handler;

protected:
    void closeEvent(QCloseEvent *e) {
        handler->close();
        QWidget::closeEvent(e);
    }

public:
    TortaDL(TortaRequestHandler *handler) : handler(handler) {
        setWindowTitle("Dobostorta downloader");

        layout.setAlignment(Qt::AlignTop);
        setLayout(&layout);

        connect(handler, &TortaRequestHandler::receivedRequest,
                [this](const QUrl &url){ startDownload(url); });
    }

    void startDownload(const QUrl &url, const QString &fname) {
        QNetworkRequest request(url);
        request.setRawHeader("User-Agent", USER_AGENT);

        auto dl = new TortaDownload(this, manager.get(request), fname);

        layout.addWidget(dl);

        connect(dl, &TortaDownload::clear, [this, dl]{
            layout.removeWidget(dl);
            delete dl;
        });
    }

    void startDownload(const QUrl &url) {
        const QString path(QFileDialog::getSaveFileName(this, tr("Save file"), url.fileName()));
        if (path != "")
            startDownload(url, path);
    }
};

int main(int argc, char **argv) {
    QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
    QApplication app(argc, argv);

    auto handler = TortaRequestHandler::open();
    if (handler == nullptr) {
        for (int i=1; i<argc; i++) {
            if (!TortaRequestHandler::request({argv[i]}))
                return -1;
        }

        return 0;
    }

    TortaDL win(handler);
    win.show();

    for (int i=1; i<argc; i++)
        win.startDownload({argv[i]});

    return app.exec();
}

#include "main.moc"
<commit_msg>Enhanced interface of downloader<commit_after>#include <QApplication>
#include <QDataStream>
#include <QErrorMessage>
#include <QFile>
#include <QFileDialog>
#include <QHBoxLayout>
#include <QIODevice>
#include <QLabel>
#include <QLocalServer>
#include <QLocalSocket>
#include <QNetworkAccessManager>
#include <QNetworkReply>
#include <QNetworkRequest>
#include <QProgressBar>
#include <QPushButton>
#include <QVBoxLayout>
#include <QWidget>

#define USER_AGENT  "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko)" \
                    "Chrome/55.0.0.0 Safari/537.36 DobosTorta/dev-" GIT_VERSION

#define CONNECTION_NAME  "dobostorta-downloader.sock"

class TortaRequestHandler : public QLocalServer {
Q_OBJECT

private:
    TortaRequestHandler() {
        listen(CONNECTION_NAME);
        connect(this, &QLocalServer::newConnection, this, &TortaRequestHandler::newConnection);
    }

    void newConnection() {
        QLocalSocket *sock = nextPendingConnection();
        connect(sock, &QLocalSocket::disconnected, sock, &QLocalSocket::close);

        sock->waitForReadyRead();

        QDataStream stream(sock);
        QByteArray data;
        stream >> data;
        emit receivedRequest({data});
    }

public:
    ~TortaRequestHandler() {
        close();
    }

    static TortaRequestHandler *open() {
        auto server = new TortaRequestHandler();
        if (server->isListening())
            return server;

        delete server;
        return nullptr;
    }

    static bool request(const QUrl &url) {
        QLocalSocket sock;
        sock.connectToServer(CONNECTION_NAME);

        if (!sock.isValid()) {
            qCritical() << tr("Failed to open socket: ") << sock.errorString();
            return false;
        }

        QByteArray block;
        QDataStream stream(&block, QIODevice::WriteOnly);
        stream << url.toEncoded();
        sock.write(block);

        sock.waitForBytesWritten();

        return true;
    }

signals:
    void receivedRequest(const QUrl &url);
};

class TortaDownload : public QWidget {
Q_OBJECT

private:
    QNetworkReply * const reply;
    QVBoxLayout layout;
    QProgressBar progress;
    QPushButton button;

    void saveTo(const QString &path) {
        QFile file(path);
        if (!file.open(QIODevice::WriteOnly)) {
            (new QErrorMessage(this))->showMessage(tr("Failed open %1: %2")
                                                   .arg(path).arg(file.errorString()));
            return;
        }

        file.write(reply->readAll());
        file.close();
    }

public:
    TortaDownload(QWidget *parent, QNetworkReply *reply, const QString &filePath)
            : QWidget(parent), reply(reply), layout(this), progress(this), button("cancel", this) {
        setLayout(&layout);

        auto horizontal = new QHBoxLayout;
        layout.addLayout(horizontal);

        auto left = new QVBoxLayout;
        horizontal->addLayout(left, 1);

        QFileInfo info(filePath);
        auto path = new QHBoxLayout;
        path->setAlignment(Qt::AlignLeft);
        path->setSpacing(0);
        left->addLayout(path);
        auto fpath = new QLabel(info.dir().path() + "/", this);
        path->addWidget(fpath);
        auto fname = new QLabel(info.fileName(), this);
        fname->setStyleSheet("font-weight: bold;");
        path->addWidget(fname);

        auto url = new QLabel(QString("%1").arg(reply->url().toString()),
                              this);
        url->setOpenExternalLinks(true);
        left->addWidget(url);

        horizontal->addWidget(&button);
        connect(&button, &QPushButton::clicked, [this, reply]{
            if (reply->isRunning())
                reply->abort();
            else
                emit clear();
        });

        layout.addWidget(&progress);

        connect(reply, &QNetworkReply::downloadProgress, [this](qint64 received, qint64 total){
            progress.setRange(0, total);
            progress.setValue(received);
        });
        connect(reply, &QNetworkReply::finished, [this, filePath, reply]{
            if (reply->error() && reply->error() != QNetworkReply::OperationCanceledError) {
                (new QErrorMessage(this))->showMessage(tr("Failed download: %1")
                                                       .arg(reply->errorString()));
            } else {
                progress.setValue(progress.maximum());
                saveTo(filePath);
            }
            button.setText("clear");
        });
    }

signals:
    void clear();
};

class TortaDL : public QWidget {
Q_OBJECT

private:
    QVBoxLayout layout;
    QNetworkAccessManager manager;
    TortaRequestHandler *handler;

protected:
    void closeEvent(QCloseEvent *e) {
        handler->close();
        QWidget::closeEvent(e);
    }

public:
    TortaDL(TortaRequestHandler *handler) : handler(handler) {
        setWindowTitle("Dobostorta downloader");

        layout.setAlignment(Qt::AlignTop);
        setLayout(&layout);

        connect(handler, &TortaRequestHandler::receivedRequest,
                [this](const QUrl &url){ startDownload(url); });
    }

    void startDownload(const QUrl &url, const QString &fname) {
        QNetworkRequest request(url);
        request.setRawHeader("User-Agent", USER_AGENT);

        auto dl = new TortaDownload(this, manager.get(request), fname);

        layout.addWidget(dl);

        connect(dl, &TortaDownload::clear, [this, dl]{
            layout.removeWidget(dl);
            delete dl;
        });
    }

    bool startDownload(const QUrl &url) {
        const QString path(QFileDialog::getSaveFileName(this, tr("Save file"), url.fileName()));
        if (path != "")
            startDownload(url, path);
        return path != "";
    }
};

int main(int argc, char **argv) {
    if (argc == 1) {
        qWarning("Dobostorta Downloader\n$ %s URL...", argv[0]);
        return -1;
    }

    QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
    QApplication app(argc, argv);

    auto handler = TortaRequestHandler::open();
    if (handler == nullptr) {
        for (int i=1; i<argc; i++) {
            if (!TortaRequestHandler::request({argv[i]}))
                return -1;
        }

        return 0;
    }

    TortaDL win(handler);

    bool started = false;
    for (int i=1; i<argc; i++)
        started = started || win.startDownload({argv[i]});

    if (!started) {
        win.close();
        return 1;
    }

    win.show();

    return app.exec();
}

#include "main.moc"
<|endoftext|>


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

/**
 * @file StraightLine.cpp
 */

#include "StraightLine.hpp"
#include <mathlib/mathlib.h>
#include <float.h>

#define VEL_ZERO_THRESHOLD 0.001f // Threshold to compare if the target velocity is zero
#define DECELERATION_MAX 8.0f     // The vehicles maximum deceleration TODO check to create param

using namespace matrix;

StraightLine::StraightLine(ModuleParams *parent, const float &deltatime, const matrix::Vector3f &pos) :
	ModuleParams(parent),
	_deltatime(deltatime), _pos(pos)
{

}

void StraightLine::generateSetpoints(matrix::Vector3f &position_setpoint, matrix::Vector3f &velocity_setpoint)
{
	// Check if target position has been reached
	if (_desired_speed_at_target < VEL_ZERO_THRESHOLD &&
	    (_pos - _target).length() < NAV_ACC_RAD.get()) {
		// Vehicle has reached target. Lock position
		position_setpoint = _target;
		velocity_setpoint = Vector3f(0.0f, 0.0f, 0.0f);

		return;
	}

	// unit vector in the direction of the straight line
	Vector3f u_orig_to_target = (_target - _origin).unit_or_zero();
	// vector from origin to current position
	Vector3f orig_to_pos = _pos - _origin;
	// current position projected perpendicularly onto desired line
	Vector3f closest_pt_on_line = _origin + u_orig_to_target * (orig_to_pos * u_orig_to_target);
	// previous velocity in the direction of the line
	float speed_sp_prev = math::max(velocity_setpoint * u_orig_to_target, 0.0f);

	// Calculate accelerating/decelerating distance depending on speed, speed at target and acceleration/deceleration
	float acc_dec_distance = fabs((_desired_speed * _desired_speed) - (_desired_speed_at_target *
				      _desired_speed_at_target)) / 2.0f;
	acc_dec_distance /= _desired_speed > _desired_speed_at_target ? _desired_deceleration : _desired_acceleration;

	float dist_to_target = (_target - _pos).length(); // distance to target

	// Either accelerate or decelerate
	float speed_sp    = dist_to_target > acc_dec_distance ? _desired_speed        :  _desired_speed_at_target;
	float max_acc_dec = speed_sp > speed_sp_prev          ? _desired_acceleration : -_desired_deceleration;

	float acc_track = (speed_sp - speed_sp_prev) / _deltatime;

	if (fabs(acc_track) > fabs(max_acc_dec)) {
		// accelerate/decelerate with desired acceleration/deceleration towards target
		speed_sp = speed_sp_prev + max_acc_dec * _deltatime;
	}

	// constrain the velocity
	speed_sp = math::constrain(speed_sp, 0.0f, _desired_speed);

	// set the position and velocity setpoints
	position_setpoint = closest_pt_on_line;
	velocity_setpoint = u_orig_to_target * speed_sp;
}

float StraightLine::getMaxAcc()
{
	// check if origin and target are different points
	if ((_target - _origin).length() < FLT_EPSILON) {
		return MPC_ACC_HOR_MAX.get();
	}

	// unit vector in the direction of the straight line
	Vector3f u_orig_to_target = (_target - _origin).unit_or_zero();

	// calculate the maximal horizontal acceleration
	float divider = Vector2f(u_orig_to_target.data()).length();
	float max_acc_hor = MPC_ACC_HOR_MAX.get();

	if (divider > FLT_EPSILON) {
		max_acc_hor /= divider;

	} else {
		max_acc_hor *= 1000.0f;
	}

	// calculate the maximal vertical acceleration
	float max_acc_vert_original = u_orig_to_target(2) < 0 ? MPC_ACC_UP_MAX.get() : MPC_ACC_DOWN_MAX.get();
	float max_acc_vert = max_acc_vert_original;

	if (fabs(u_orig_to_target(2)) > FLT_EPSILON) {
		max_acc_vert /= fabs(u_orig_to_target(2));

	} else {
		max_acc_vert *= 1000.0f;
	}

	return math::min(max_acc_hor, max_acc_vert);
}

float StraightLine::getMaxVel()
{
	// check if origin and target are different points
	if ((_target - _origin).length() < FLT_EPSILON) {
		return MPC_XY_VEL_MAX.get();
	}

	// unit vector in the direction of the straight line
	Vector3f u_orig_to_target = (_target - _origin).unit_or_zero();

	// calculate the maximal horizontal velocity
	float divider = Vector2f(u_orig_to_target.data()).length();
	float max_vel_hor = MPC_XY_VEL_MAX.get();

	if (divider > FLT_EPSILON) {
		max_vel_hor /= divider;

	} else {
		max_vel_hor *= 1000.0f;
	}

	// calculate the maximal vertical velocity
	float max_vel_vert_directional = u_orig_to_target(2) < 0 ? MPC_Z_VEL_MAX_UP.get() : MPC_Z_VEL_MAX_DN.get();
	float max_vel_vert = max_vel_vert_directional;

	if (fabs(u_orig_to_target(2)) > FLT_EPSILON) {
		max_vel_vert /= fabs(u_orig_to_target(2));

	} else {
		max_vel_vert *= 1000.0f;
	}

	return math::min(max_vel_hor, max_vel_vert);
}

void StraightLine::setAllDefaults()
{
	_desired_speed = getMaxVel();
	_desired_speed_at_target = 0.0f;
	_desired_acceleration = getMaxAcc();
	_desired_deceleration = DECELERATION_MAX;
}

void StraightLine::setLineFromTo(const matrix::Vector3f &origin, const matrix::Vector3f &target)
{
	if (PX4_ISFINITE(target(0)) && PX4_ISFINITE(target(1)) && PX4_ISFINITE(target(2)) &&
	    PX4_ISFINITE(origin(0)) && PX4_ISFINITE(origin(1)) && PX4_ISFINITE(origin(2))) {
		_target = target;
		_origin = origin;

		// set all parameters to their default value (depends on the direction)
		setAllDefaults();
	}
}

void StraightLine::setSpeed(const float &speed)
{
	float vel_max = getMaxVel();

	if (speed > 0 && speed < vel_max) {
		_desired_speed = speed;

	} else if (speed > vel_max) {
		_desired_speed = vel_max;
	}
}

void StraightLine::setSpeedAtTarget(const float &speed_at_target)
{
	float vel_max = getMaxVel();

	if (speed_at_target > 0 && speed_at_target < vel_max) {
		_desired_speed_at_target = speed_at_target;

	} else if (speed_at_target > vel_max) {
		_desired_speed_at_target = vel_max;
	}
}

void StraightLine::setAcceleration(const float &acc)
{
	float acc_max = getMaxVel();

	if (acc > 0 && acc < acc_max) {
		_desired_acceleration = acc;

	} else if (acc > acc_max) {
		_desired_acceleration = acc_max;
	}
}

void StraightLine::setDeceleration(const float &dec)
{
	if (dec > 0 && dec < DECELERATION_MAX) {
		_desired_deceleration = dec;

	} else if (dec > DECELERATION_MAX) {
		_desired_deceleration = DECELERATION_MAX;
	}
}
<commit_msg>FlightTask StraighLine: check values before dividing<commit_after>/****************************************************************************
 *
 *   Copyright (c) 2018 PX4 Development Team. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 * 3. Neither the name PX4 nor the names of its contributors may be
 *    used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
 * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 *
 ****************************************************************************/

/**
 * @file StraightLine.cpp
 */

#include "StraightLine.hpp"
#include <mathlib/mathlib.h>
#include <float.h>

#define VEL_ZERO_THRESHOLD 0.001f // Threshold to compare if the target velocity is zero
#define DECELERATION_MAX 8.0f     // The vehicles maximum deceleration TODO check to create param

using namespace matrix;

StraightLine::StraightLine(ModuleParams *parent, const float &deltatime, const matrix::Vector3f &pos) :
	ModuleParams(parent),
	_deltatime(deltatime), _pos(pos)
{

}

void StraightLine::generateSetpoints(matrix::Vector3f &position_setpoint, matrix::Vector3f &velocity_setpoint)
{
	// Check if target position has been reached
	if (_desired_speed_at_target < VEL_ZERO_THRESHOLD &&
	    (_pos - _target).length() < NAV_ACC_RAD.get()) {
		// Vehicle has reached target. Lock position
		position_setpoint = _target;
		velocity_setpoint = Vector3f(0.0f, 0.0f, 0.0f);

		return;
	}

	// unit vector in the direction of the straight line
	Vector3f u_orig_to_target = (_target - _origin).unit_or_zero();
	// vector from origin to current position
	Vector3f orig_to_pos = _pos - _origin;
	// current position projected perpendicularly onto desired line
	Vector3f closest_pt_on_line = _origin + u_orig_to_target * (orig_to_pos * u_orig_to_target);
	// previous velocity in the direction of the line
	float speed_sp_prev = math::max(velocity_setpoint * u_orig_to_target, 0.0f);

	// Calculate accelerating/decelerating distance depending on speed, speed at target and acceleration/deceleration
	float acc_dec_distance = fabs((_desired_speed * _desired_speed) - (_desired_speed_at_target *
				      _desired_speed_at_target)) / 2.0f;
	acc_dec_distance /= _desired_speed > _desired_speed_at_target ? _desired_deceleration : _desired_acceleration;

	float dist_to_target = (_target - _pos).length(); // distance to target

	// Either accelerate or decelerate
	float speed_sp    = dist_to_target > acc_dec_distance ? _desired_speed        :  _desired_speed_at_target;
	float max_acc_dec = speed_sp > speed_sp_prev          ? _desired_acceleration : -_desired_deceleration;

	float acc_track = 0.0f;

	if (_deltatime > FLT_EPSILON) {
		acc_track = (speed_sp - speed_sp_prev) / _deltatime;
	}

	if (fabs(acc_track) > fabs(max_acc_dec)) {
		// accelerate/decelerate with desired acceleration/deceleration towards target
		speed_sp = speed_sp_prev + max_acc_dec * _deltatime;
	}

	// constrain the velocity
	speed_sp = math::constrain(speed_sp, 0.0f, _desired_speed);

	// set the position and velocity setpoints
	position_setpoint = closest_pt_on_line;
	velocity_setpoint = u_orig_to_target * speed_sp;
}

float StraightLine::getMaxAcc()
{
	// check if origin and target are different points
	if ((_target - _origin).length() < FLT_EPSILON) {
		return MPC_ACC_HOR_MAX.get();
	}

	// unit vector in the direction of the straight line
	Vector3f u_orig_to_target = (_target - _origin).unit_or_zero();

	// calculate the maximal horizontal acceleration
	float divider = Vector2f(u_orig_to_target.data()).length();
	float max_acc_hor = MPC_ACC_HOR_MAX.get();

	if (divider > FLT_EPSILON) {
		max_acc_hor /= divider;

	} else {
		max_acc_hor *= 1000.0f;
	}

	// calculate the maximal vertical acceleration
	float max_acc_vert_original = u_orig_to_target(2) < 0 ? MPC_ACC_UP_MAX.get() : MPC_ACC_DOWN_MAX.get();
	float max_acc_vert = max_acc_vert_original;

	if (fabs(u_orig_to_target(2)) > FLT_EPSILON) {
		max_acc_vert /= fabs(u_orig_to_target(2));

	} else {
		max_acc_vert *= 1000.0f;
	}

	return math::min(max_acc_hor, max_acc_vert);
}

float StraightLine::getMaxVel()
{
	// check if origin and target are different points
	if ((_target - _origin).length() < FLT_EPSILON) {
		return MPC_XY_VEL_MAX.get();
	}

	// unit vector in the direction of the straight line
	Vector3f u_orig_to_target = (_target - _origin).unit_or_zero();

	// calculate the maximal horizontal velocity
	float divider = Vector2f(u_orig_to_target.data()).length();
	float max_vel_hor = MPC_XY_VEL_MAX.get();

	if (divider > FLT_EPSILON) {
		max_vel_hor /= divider;

	} else {
		max_vel_hor *= 1000.0f;
	}

	// calculate the maximal vertical velocity
	float max_vel_vert_directional = u_orig_to_target(2) < 0 ? MPC_Z_VEL_MAX_UP.get() : MPC_Z_VEL_MAX_DN.get();
	float max_vel_vert = max_vel_vert_directional;

	if (fabs(u_orig_to_target(2)) > FLT_EPSILON) {
		max_vel_vert /= fabs(u_orig_to_target(2));

	} else {
		max_vel_vert *= 1000.0f;
	}

	return math::min(max_vel_hor, max_vel_vert);
}

void StraightLine::setAllDefaults()
{
	_desired_speed = getMaxVel();
	_desired_speed_at_target = 0.0f;
	_desired_acceleration = getMaxAcc();
	_desired_deceleration = DECELERATION_MAX;
}

void StraightLine::setLineFromTo(const matrix::Vector3f &origin, const matrix::Vector3f &target)
{
	if (PX4_ISFINITE(target(0)) && PX4_ISFINITE(target(1)) && PX4_ISFINITE(target(2)) &&
	    PX4_ISFINITE(origin(0)) && PX4_ISFINITE(origin(1)) && PX4_ISFINITE(origin(2))) {
		_target = target;
		_origin = origin;

		// set all parameters to their default value (depends on the direction)
		setAllDefaults();
	}
}

void StraightLine::setSpeed(const float &speed)
{
	float vel_max = getMaxVel();

	if (speed > FLT_EPSILON && speed < vel_max) {
		_desired_speed = speed;

	} else if (speed > vel_max) {
		_desired_speed = vel_max;
	}
}

void StraightLine::setSpeedAtTarget(const float &speed_at_target)
{
	float vel_max = getMaxVel();

	if (speed_at_target > FLT_EPSILON && speed_at_target < vel_max) {
		_desired_speed_at_target = speed_at_target;

	} else if (speed_at_target > vel_max) {
		_desired_speed_at_target = vel_max;
	}
}

void StraightLine::setAcceleration(const float &acc)
{
	float acc_max = getMaxVel();

	if (acc > FLT_EPSILON && acc < acc_max) {
		_desired_acceleration = acc;

	} else if (acc > acc_max) {
		_desired_acceleration = acc_max;
	}
}

void StraightLine::setDeceleration(const float &dec)
{
	if (dec > FLT_EPSILON && dec < DECELERATION_MAX) {
		_desired_deceleration = dec;

	} else if (dec > DECELERATION_MAX) {
		_desired_deceleration = DECELERATION_MAX;
	}
}
<|endoftext|>


<commit_before>// -*- C++ -*-
//
//  Copyright (C) 2012, Vaclav Zeman. All rights reserved.
//
//  Redistribution and use in source and binary forms, with or without modifica-
//  tion, are permitted provided that the following conditions are met:
//
//  1. Redistributions of  source code must  retain the above copyright  notice,
//     this list of conditions and the following disclaimer.
//
//  2. Redistributions in binary form must reproduce the above copyright notice,
//     this list of conditions and the following disclaimer in the documentation
//     and/or other materials provided with the distribution.
//
//  THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
//  INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
//  FITNESS  FOR A PARTICULAR  PURPOSE ARE  DISCLAIMED.  IN NO  EVENT SHALL  THE
//  APACHE SOFTWARE  FOUNDATION  OR ITS CONTRIBUTORS  BE LIABLE FOR  ANY DIRECT,
//  INDIRECT, INCIDENTAL, SPECIAL,  EXEMPLARY, OR CONSEQUENTIAL  DAMAGES (INCLU-
//  DING, BUT NOT LIMITED TO, PROCUREMENT  OF SUBSTITUTE GOODS OR SERVICES; LOSS
//  OF USE, DATA, OR  PROFITS; OR BUSINESS  INTERRUPTION)  HOWEVER CAUSED AND ON
//  ANY  THEORY OF LIABILITY,  WHETHER  IN CONTRACT,  STRICT LIABILITY,  OR TORT
//  (INCLUDING  NEGLIGENCE OR  OTHERWISE) ARISING IN  ANY WAY OUT OF THE  USE OF
//  THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

#include <log4cplus/config/defines.hxx>

#if defined (LOG4CPLUS_HAVE_SYS_TYPES_H)
#include <sys/types.h>
#endif
#if defined (LOG4CPLUS_HAVE_SYS_STAT_H)
#include <sys/stat.h>
#endif
#if defined (LOG4CPLUS_HAVE_SYS_FILE_H)
#include <sys/file.h>
#endif
#if defined (LOG4CPLUS_HAVE_UNISTD_H)
#include <unistd.h>
#endif
#if defined (LOG4CPLUS_HAVE_FCNTL_H)
#include <fcntl.h>
#endif

#include <stdexcept>
#include <cerrno>

#include <log4cplus/helpers/lockfile.h>
#include <log4cplus/helpers/stringhelper.h>

#if defined (_WIN32)
#else
#  if defined (O_EXLOCK)
#    define LOG4CPLUS_USE_O_EXLOCK
#  elif defined (LOG4CPLUS_HAVE_FCNTL) && defined (F_SETLKW)
#    define LOG4CPLUS_USE_SETLKW
#  elif defined (LOG4CPLUS_HAVE_LOCKF)
#    define LOG4CPLUS_USE_LOCKF
#  elif defined (LOG4CPLUS_HAVE_FLOCK)
#    define LOG4CPLUS_USE_FLOCK
#  endif
#  if defined (LOG4CPLUS_USE_O_EXLOCK) || defined (LOG4CPLUS_USE_SETLKW) \
    || defined (LOG4CPLUS_USE_LOCKF) || defined (LOG4CPLUS_USE_FLOCK)
#    define LOG4CPLUS_USE_POSIX_LOCKING
#  endif
#endif

#if ! defined (LOG4CPLUS_USE_POSIX_LOCKING) && ! defined (_WIN32)
#error "no usable file locking"
#endif

namespace log4cplus { namespace helpers {

#if defined (LOG4CPLUS_USE_POSIX_LOCKING)
int const OPEN_FLAGS = O_RDWR | O_CREAT
#if defined (O_CLOEXEC)
    | O_CLOEXEC
#endif
    ;

mode_t const OPEN_MODE = (S_IRWXU ^ S_IXUSR)
    | (S_IRWXG ^ S_IXGRP)
    | (S_IRWXO ^ S_IXOTH);

#endif

struct LockFile::Impl
{
#if defined (LOG4CPLUS_USE_POSIX_LOCKING)
    int fd;

#elif defined (_WIN32)
    HANDLE fh;

#endif
};

//
//
//

LockFile::LockFile (tstring const & lf)
    : lock_file_name (lf)
    , data (new LockFile::Impl)
{
#if defined (LOG4CPLUS_USE_O_EXLOCK)
    data->fd = -1;

#elif defined (LOG4CPLUS_USE_LOCKF) || defined (LOG4CPLUS_USE_FLOCK) \
    || defined (LOG4CPLUS_USE_SETLKW)
    open (OPEN_FLAGS);

#endif
}

LockFile::~LockFile ()
{
#if defined (LOG4CPLUS_USE_POSIX_LOCKING)
    if (data->fd >= 0)
        ::close (data->fd);

#endif

    delete data;
}

void
LockFile::open (int open_flags) const
{
#if defined (LOG4CPLUS_USE_POSIX_LOCKING)
    data->fd = ::open (LOG4CPLUS_TSTRING_TO_STRING (lock_file_name).c_str (),
        open_flags, OPEN_MODE);
    if (data->fd == -1)
    {
        throw std::runtime_error (
            std::string ("could not open or create file ") + lock_file_name);
    }

#elif defined (_WIN32)
#endif
}

void
LockFile::close () const
{
#if defined (LOG4CPLUS_USE_POSIX_LOCKING)
    ::close (data->fd);

#elif defined (_WIN32)
#endif
}

void
LockFile::lock () const
{
#if defined (LOG4CPLUS_USE_O_EXLOCK)
    open (OPEN_FLAGS | O_EXLOCK);

#elif defined (LOG4CPLUS_USE_SETLKW)
    int ret = 0;

    do
    {
        struct flock fl;
        fl.l_type = F_WRLCK;
        fl.l_whence = SEEK_SET;
        fl.l_start = 0;
        fl.l_len = 0;
        ret = fcntl (data->fd, F_SETLKW, &fl);
        if (ret == -1 && errno != EINTR)
            throw std::runtime_error (std::string ("fcntl(F_SETLKW) failed: ")
                + convertIntegerToString (errno));
    }
    while (ret == -1);

#elif defined (LOG4CPLUS_USE_LOCKF)
    int ret = 0;

    do
    {
        ret = lockf (data->fd, F_LOCK, 0);
        if (ret == -1 && errno != EINTR)
            throw std::runtime_error (std::string ("lockf() failed: ")
                + convertIntegerToString (errno));
    }
    while (ret == -1);

#elif defined (LOG4CPLUS_USE_FLOCK)
    int ret = 0;

    do
    {
        ret = flock (data->fd, LOCK_EX);
        if (ret == -1 && errno != EINTR)
            throw std::runtime_error (std::string ("fcntl(F_SETLKW) failed: ")
                + convertIntegerToString (errno));
    }
    while (ret == -1);

#elif defined (_WIN32)
#endif
}

void LockFile::unlock () const
{
#if defined (LOG4CPLUS_USE_O_EXLOCK)
    close ();

#elif defined (LOG4CPLUS_USE_SETLKW)
    struct flock fl;
    fl.l_type = F_UNLCK;
    fl.l_whence = SEEK_SET;
    fl.l_start = 0;
    fl.l_len = 0;
    int ret = fcntl (data->fd, F_SETLKW, &fl);
    if (ret != 0)
        throw std::runtime_error (std::string ("fcntl(F_SETLKW) failed: ")
            + convertIntegerToString (errno));

#elif defined (LOG4CPLUS_USE_LOCKF)
    int ret = lockf (data->fd, F_ULOCK, 0);
    if (ret != 0)
        throw std::runtime_error (std::string ("lockf() failed: ")
            + convertIntegerToString (errno));

#elif defined (LOG4CPLUS_USE_FLOCK)
    int ret = flock (data->fd, LOCK_UN);
    if (ret != 0)
        throw std::runtime_error (std::string ("flock() failed: ")
            + convertIntegerToString (errno));

#endif

}

} } // namespace log4cplus { namespace helpers {
<commit_msg>lockfile.cxx: Handle missing O_CLOEXEC by issuing fcntl() with FD_CLOEXEC after open(). Replace bare throws by LogLog::error() calls.<commit_after>// -*- C++ -*-
//
//  Copyright (C) 2012, Vaclav Zeman. All rights reserved.
//
//  Redistribution and use in source and binary forms, with or without modifica-
//  tion, are permitted provided that the following conditions are met:
//
//  1. Redistributions of  source code must  retain the above copyright  notice,
//     this list of conditions and the following disclaimer.
//
//  2. Redistributions in binary form must reproduce the above copyright notice,
//     this list of conditions and the following disclaimer in the documentation
//     and/or other materials provided with the distribution.
//
//  THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
//  INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
//  FITNESS  FOR A PARTICULAR  PURPOSE ARE  DISCLAIMED.  IN NO  EVENT SHALL  THE
//  APACHE SOFTWARE  FOUNDATION  OR ITS CONTRIBUTORS  BE LIABLE FOR  ANY DIRECT,
//  INDIRECT, INCIDENTAL, SPECIAL,  EXEMPLARY, OR CONSEQUENTIAL  DAMAGES (INCLU-
//  DING, BUT NOT LIMITED TO, PROCUREMENT  OF SUBSTITUTE GOODS OR SERVICES; LOSS
//  OF USE, DATA, OR  PROFITS; OR BUSINESS  INTERRUPTION)  HOWEVER CAUSED AND ON
//  ANY  THEORY OF LIABILITY,  WHETHER  IN CONTRACT,  STRICT LIABILITY,  OR TORT
//  (INCLUDING  NEGLIGENCE OR  OTHERWISE) ARISING IN  ANY WAY OUT OF THE  USE OF
//  THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

#include <log4cplus/config/defines.hxx>

#if defined (LOG4CPLUS_HAVE_SYS_TYPES_H)
#include <sys/types.h>
#endif
#if defined (LOG4CPLUS_HAVE_SYS_STAT_H)
#include <sys/stat.h>
#endif
#if defined (LOG4CPLUS_HAVE_SYS_FILE_H)
#include <sys/file.h>
#endif
#if defined (LOG4CPLUS_HAVE_UNISTD_H)
#include <unistd.h>
#endif
#if defined (LOG4CPLUS_HAVE_FCNTL_H)
#include <fcntl.h>
#endif

#include <stdexcept>
#include <cerrno>

#include <log4cplus/helpers/lockfile.h>
#include <log4cplus/helpers/stringhelper.h>
#include <log4cplus/helpers/loglog.h>

#if defined (_WIN32)
#else
#  if defined (O_EXLOCK)
#    define LOG4CPLUS_USE_O_EXLOCK
#  elif defined (LOG4CPLUS_HAVE_FCNTL) && defined (F_SETLKW)
#    define LOG4CPLUS_USE_SETLKW
#  elif defined (LOG4CPLUS_HAVE_LOCKF)
#    define LOG4CPLUS_USE_LOCKF
#  elif defined (LOG4CPLUS_HAVE_FLOCK)
#    define LOG4CPLUS_USE_FLOCK
#  endif
#  if defined (LOG4CPLUS_USE_O_EXLOCK) || defined (LOG4CPLUS_USE_SETLKW) \
    || defined (LOG4CPLUS_USE_LOCKF) || defined (LOG4CPLUS_USE_FLOCK)
#    define LOG4CPLUS_USE_POSIX_LOCKING
#  endif
#endif

#if ! defined (LOG4CPLUS_USE_POSIX_LOCKING) && ! defined (_WIN32)
#error "no usable file locking"
#endif

namespace log4cplus { namespace helpers {

#if defined (LOG4CPLUS_USE_POSIX_LOCKING)
int const OPEN_FLAGS = O_RDWR | O_CREAT
#if defined (O_CLOEXEC)
    | O_CLOEXEC
#endif
    ;

mode_t const OPEN_MODE = (S_IRWXU ^ S_IXUSR)
    | (S_IRWXG ^ S_IXGRP)
    | (S_IRWXO ^ S_IXOTH);

#endif

struct LockFile::Impl
{
#if defined (LOG4CPLUS_USE_POSIX_LOCKING)
    int fd;

#elif defined (_WIN32)
    HANDLE fh;

#endif
};

//
//
//

LockFile::LockFile (tstring const & lf)
    : lock_file_name (lf)
    , data (new LockFile::Impl)
{
#if defined (LOG4CPLUS_USE_O_EXLOCK)
    data->fd = -1;

#elif defined (LOG4CPLUS_USE_LOCKF) || defined (LOG4CPLUS_USE_FLOCK) \
    || defined (LOG4CPLUS_USE_SETLKW)
    open (OPEN_FLAGS);

#endif
}

LockFile::~LockFile ()
{
#if defined (LOG4CPLUS_USE_POSIX_LOCKING)
    if (data->fd >= 0)
        ::close (data->fd);

#endif

    delete data;
}

void
LockFile::open (int open_flags) const
{
    LogLog & loglog = getLogLog ();

#if defined (LOG4CPLUS_USE_POSIX_LOCKING)
    data->fd = ::open (LOG4CPLUS_TSTRING_TO_STRING (lock_file_name).c_str (),
        open_flags, OPEN_MODE);
    if (data->fd == -1)
        loglog.error (std::string ("could not open or create file ")
            + lock_file_name, true);

#if ! defined (O_CLOEXEC) && defined (FD_CLOEXEC)
    int ret = fcntl (data->fd, F_SETFD, FD_CLOEXEC);
    if (ret == -1)
        loglog.warn (std::string ("could not set FD_CLOEXEC on file ")
            + lock_file_name);

#endif

#elif defined (_WIN32)
#endif
}

void
LockFile::close () const
{
#if defined (LOG4CPLUS_USE_POSIX_LOCKING)
    ::close (data->fd);

#elif defined (_WIN32)
#endif
}

void
LockFile::lock () const
{
    LogLog & loglog = getLogLog ();
    int ret = 0;

#if defined (LOG4CPLUS_USE_O_EXLOCK)
    open (OPEN_FLAGS | O_EXLOCK);

#elif defined (LOG4CPLUS_USE_SETLKW)
    do
    {
        struct flock fl;
        fl.l_type = F_WRLCK;
        fl.l_whence = SEEK_SET;
        fl.l_start = 0;
        fl.l_len = 0;
        ret = fcntl (data->fd, F_SETLKW, &fl);
        if (ret == -1 && errno != EINTR)
            loglog.error (std::string ("fcntl(F_SETLKW) failed: ")
                + convertIntegerToString (errno), true);
    }
    while (ret == -1);

#elif defined (LOG4CPLUS_USE_LOCKF)
    do
    {
        ret = lockf (data->fd, F_LOCK, 0);
        if (ret == -1 && errno != EINTR)
            loglog.error (std::string ("lockf() failed: ")
                + convertIntegerToString (errno), true);
    }
    while (ret == -1);

#elif defined (LOG4CPLUS_USE_FLOCK)
    do
    {
        ret = flock (data->fd, LOCK_EX);
        if (ret == -1 && errno != EINTR)
            loglog.error (std::string ("flock() failed: ")
                + convertIntegerToString (errno), true);
    }
    while (ret == -1);

#elif defined (_WIN32)
#endif
}

void LockFile::unlock () const
{
    LogLog & loglog = getLogLog ();
    int ret = 0;

#if defined (LOG4CPLUS_USE_O_EXLOCK)
    close ();

#elif defined (LOG4CPLUS_USE_SETLKW)
    struct flock fl;
    fl.l_type = F_UNLCK;
    fl.l_whence = SEEK_SET;
    fl.l_start = 0;
    fl.l_len = 0;
    ret = fcntl (data->fd, F_SETLKW, &fl);
    if (ret != 0)
        loglog.error (std::string ("fcntl(F_SETLKW) failed: ")
            + convertIntegerToString (errno), true);

#elif defined (LOG4CPLUS_USE_LOCKF)
    ret = lockf (data->fd, F_ULOCK, 0);
    if (ret != 0)
        loglog.error (std::string ("lockf() failed: ")
            + convertIntegerToString (errno), true);

#elif defined (LOG4CPLUS_USE_FLOCK)
    ret = flock (data->fd, LOCK_UN);
    if (ret != 0)
        loglog.error (std::string ("flock() failed: ")
            + convertIntegerToString (errno), true);

#endif

}

} } // namespace log4cplus { namespace helpers {
<|endoftext|>


<commit_before>// Module:  Log4CPLUS
// File:    loglevel.cxx
// Created: 6/2001
// Author:  Tad E. Smith
//
//
// Copyright 2001-2013 Tad E. Smith
//
// 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 <log4cplus/loglevel.h>
#include <log4cplus/helpers/loglog.h>
#include <log4cplus/helpers/stringhelper.h>
#include <log4cplus/internal/internal.h>
#include <algorithm>

namespace log4cplus
{

namespace
{

// The strings here are not simple tstring constants to allow using these
// strings and log4cplus itself in client code during static variables
// initialization. If they are simple tstring constants then, due to undefined
// order of initialization between translation units, they might be
// uninitialized before they are used by the client code. One possible solution
// to this is to use compiler specific attributes and/or pragmas to influence
// initialization order/priority. Another solution is using function local
// static variables, which are initialized on first use. We choose this
// implementation because it is more portable than compiler specific means.

#define DEF_LL_STRING(_logLevel)                                        \
static tstring const & _logLevel ## _STRING ()                          \
{                                                                       \
    static tstring const str (LOG4CPLUS_TEXT (#_logLevel));             \
    return str;                                                         \
}

DEF_LL_STRING (OFF)
DEF_LL_STRING (FATAL)
DEF_LL_STRING (ERROR)
DEF_LL_STRING (WARN)
DEF_LL_STRING (INFO)
DEF_LL_STRING (DEBUG)
DEF_LL_STRING (TRACE)
DEF_LL_STRING (ALL)
DEF_LL_STRING (NOTSET)
DEF_LL_STRING (UNKNOWN)

#undef DEF_LL_STRING

static
tstring const &
defaultLogLevelToStringMethod(LogLevel ll)
{
    switch(ll) {
        case OFF_LOG_LEVEL:     return OFF_STRING();
        case FATAL_LOG_LEVEL:   return FATAL_STRING();
        case ERROR_LOG_LEVEL:   return ERROR_STRING();
        case WARN_LOG_LEVEL:    return WARN_STRING();
        case INFO_LOG_LEVEL:    return INFO_STRING();
        case DEBUG_LOG_LEVEL:   return DEBUG_STRING();
        case TRACE_LOG_LEVEL:   return TRACE_STRING();
        //case ALL_LOG_LEVEL:     return ALL_STRING();
        case NOT_SET_LOG_LEVEL: return NOTSET_STRING();
    };

    return internal::empty_str;
}

static
LogLevel
defaultStringToLogLevelMethod(const tstring& s)
{
#if __cplusplus < 201103L
    if (s.empty ())
        return NOT_SET_LOG_LEVEL;

    // The above check is only necessary prior to C++11 standard. Since C++11,
    // accessing str[0] is always safe as it returns '\0' for empty string.
#endif

    switch (s[0])
    {
#define DEF_LLMATCH(_chr, _logLevel)                 \
        case _chr: if (s == _logLevel ## _STRING ()) \
            return _logLevel ## _LOG_LEVEL; break;

        DEF_LLMATCH ('O', OFF);
        DEF_LLMATCH ('F', FATAL);
        DEF_LLMATCH ('E', ERROR);
        DEF_LLMATCH ('W', WARN);
        DEF_LLMATCH ('I', INFO);
        DEF_LLMATCH ('D', DEBUG);
        DEF_LLMATCH ('T', TRACE);
        DEF_LLMATCH ('A', ALL);

#undef DEF_LLMATCH
    }

    return NOT_SET_LOG_LEVEL;
}

} // namespace

void
initializeLogLevelStrings ()
{
    OFF_STRING();
    FATAL_STRING();
    ERROR_STRING();
    WARN_STRING();
    INFO_STRING();
    DEBUG_STRING();
    TRACE_STRING();
    ALL_STRING();
    NOTSET_STRING();
}

//////////////////////////////////////////////////////////////////////////////
// LogLevelManager ctors and dtor
//////////////////////////////////////////////////////////////////////////////

LogLevelManager::LogLevelManager()
{
    LogLevelToStringMethodRec rec;
    rec.func = defaultLogLevelToStringMethod;
    rec.use_1_0 = false;
    toStringMethods.push_back (rec);

    fromStringMethods.push_back (defaultStringToLogLevelMethod);
}

LogLevelManager::~LogLevelManager()
{ }

//////////////////////////////////////////////////////////////////////////////
// LogLevelManager public methods
//////////////////////////////////////////////////////////////////////////////

tstring const &
LogLevelManager::toString(LogLevel ll) const
{
    tstring const * ret;
    for (LogLevelToStringMethodList::const_iterator it
        = toStringMethods.begin (); it != toStringMethods.end (); ++it)
    {
        LogLevelToStringMethodRec const & rec = *it;
        if (rec.use_1_0)
        {
            // Use TLS to store the result to allow us to return
            // a reference.
            tstring & ll_str = internal::get_ptd ()->ll_str;
            rec.func_1_0 (ll).swap (ll_str);
            ret = &ll_str;
        }
        else
            ret = &rec.func (ll);

        if (! ret->empty ())
            return *ret;
    }

    return UNKNOWN_STRING();
}

LogLevel
LogLevelManager::fromString(const tstring& arg) const
{
    tstring s = helpers::toUpper(arg);

    for (StringToLogLevelMethodList::const_iterator it
        = fromStringMethods.begin (); it != fromStringMethods.end (); ++it)
    {
        LogLevel ret = (*it) (s);
        if (ret != NOT_SET_LOG_LEVEL)
            return ret;
    }

    helpers::getLogLog ().error (
        LOG4CPLUS_TEXT ("Unrecognized log level: ")
        + arg);

    return NOT_SET_LOG_LEVEL;
}

void
LogLevelManager::pushToStringMethod(LogLevelToStringMethod newToString)
{
    LogLevelToStringMethodRec rec;
    rec.func = newToString;
    rec.use_1_0 = false;
    toStringMethods.push_back (rec);
}

void
LogLevelManager::pushToStringMethod(LogLevelToStringMethod_1_0 newToString)
{
    LogLevelToStringMethodRec rec;
    rec.func_1_0 = newToString;
    rec.use_1_0 = true;
    toStringMethods.push_back (rec);
}

void
LogLevelManager::pushFromStringMethod(StringToLogLevelMethod newFromString)
{
    fromStringMethods.push_back (newFromString);
}

} // namespace log4cplus
<commit_msg>loglevel.cxx: Insert to/from string/log level conversion functions to the beginning of vector to favour user defined log levels and conversion functions.<commit_after>// Module:  Log4CPLUS
// File:    loglevel.cxx
// Created: 6/2001
// Author:  Tad E. Smith
//
//
// Copyright 2001-2013 Tad E. Smith
//
// 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 <log4cplus/loglevel.h>
#include <log4cplus/helpers/loglog.h>
#include <log4cplus/helpers/stringhelper.h>
#include <log4cplus/internal/internal.h>
#include <algorithm>

namespace log4cplus
{

namespace
{

// The strings here are not simple tstring constants to allow using these
// strings and log4cplus itself in client code during static variables
// initialization. If they are simple tstring constants then, due to undefined
// order of initialization between translation units, they might be
// uninitialized before they are used by the client code. One possible solution
// to this is to use compiler specific attributes and/or pragmas to influence
// initialization order/priority. Another solution is using function local
// static variables, which are initialized on first use. We choose this
// implementation because it is more portable than compiler specific means.

#define DEF_LL_STRING(_logLevel)                                        \
static tstring const & _logLevel ## _STRING ()                          \
{                                                                       \
    static tstring const str (LOG4CPLUS_TEXT (#_logLevel));             \
    return str;                                                         \
}

DEF_LL_STRING (OFF)
DEF_LL_STRING (FATAL)
DEF_LL_STRING (ERROR)
DEF_LL_STRING (WARN)
DEF_LL_STRING (INFO)
DEF_LL_STRING (DEBUG)
DEF_LL_STRING (TRACE)
DEF_LL_STRING (ALL)
DEF_LL_STRING (NOTSET)
DEF_LL_STRING (UNKNOWN)

#undef DEF_LL_STRING

static
tstring const &
defaultLogLevelToStringMethod(LogLevel ll)
{
    switch(ll) {
        case OFF_LOG_LEVEL:     return OFF_STRING();
        case FATAL_LOG_LEVEL:   return FATAL_STRING();
        case ERROR_LOG_LEVEL:   return ERROR_STRING();
        case WARN_LOG_LEVEL:    return WARN_STRING();
        case INFO_LOG_LEVEL:    return INFO_STRING();
        case DEBUG_LOG_LEVEL:   return DEBUG_STRING();
        case TRACE_LOG_LEVEL:   return TRACE_STRING();
        //case ALL_LOG_LEVEL:     return ALL_STRING();
        case NOT_SET_LOG_LEVEL: return NOTSET_STRING();
    };

    return internal::empty_str;
}

static
LogLevel
defaultStringToLogLevelMethod(const tstring& s)
{
#if __cplusplus < 201103L
    if (s.empty ())
        return NOT_SET_LOG_LEVEL;

    // The above check is only necessary prior to C++11 standard. Since C++11,
    // accessing str[0] is always safe as it returns '\0' for empty string.
#endif

    switch (s[0])
    {
#define DEF_LLMATCH(_chr, _logLevel)                 \
        case _chr: if (s == _logLevel ## _STRING ()) \
            return _logLevel ## _LOG_LEVEL; break;

        DEF_LLMATCH ('O', OFF);
        DEF_LLMATCH ('F', FATAL);
        DEF_LLMATCH ('E', ERROR);
        DEF_LLMATCH ('W', WARN);
        DEF_LLMATCH ('I', INFO);
        DEF_LLMATCH ('D', DEBUG);
        DEF_LLMATCH ('T', TRACE);
        DEF_LLMATCH ('A', ALL);

#undef DEF_LLMATCH
    }

    return NOT_SET_LOG_LEVEL;
}

} // namespace

void
initializeLogLevelStrings ()
{
    OFF_STRING();
    FATAL_STRING();
    ERROR_STRING();
    WARN_STRING();
    INFO_STRING();
    DEBUG_STRING();
    TRACE_STRING();
    ALL_STRING();
    NOTSET_STRING();
}

//////////////////////////////////////////////////////////////////////////////
// LogLevelManager ctors and dtor
//////////////////////////////////////////////////////////////////////////////

LogLevelManager::LogLevelManager()
{
    pushToStringMethod (defaultLogLevelToStringMethod);

    pushFromStringMethod (defaultStringToLogLevelMethod);
}

LogLevelManager::~LogLevelManager()
{ }

//////////////////////////////////////////////////////////////////////////////
// LogLevelManager public methods
//////////////////////////////////////////////////////////////////////////////

tstring const &
LogLevelManager::toString(LogLevel ll) const
{
    tstring const * ret;
    for (LogLevelToStringMethodList::const_iterator it
        = toStringMethods.begin (); it != toStringMethods.end (); ++it)
    {
        LogLevelToStringMethodRec const & rec = *it;
        if (rec.use_1_0)
        {
            // Use TLS to store the result to allow us to return
            // a reference.
            tstring & ll_str = internal::get_ptd ()->ll_str;
            rec.func_1_0 (ll).swap (ll_str);
            ret = &ll_str;
        }
        else
            ret = &rec.func (ll);

        if (! ret->empty ())
            return *ret;
    }

    return UNKNOWN_STRING();
}

LogLevel
LogLevelManager::fromString(const tstring& arg) const
{
    tstring s = helpers::toUpper(arg);

    for (StringToLogLevelMethodList::const_iterator it
        = fromStringMethods.begin (); it != fromStringMethods.end (); ++it)
    {
        LogLevel ret = (*it) (s);
        if (ret != NOT_SET_LOG_LEVEL)
            return ret;
    }

    helpers::getLogLog ().error (
        LOG4CPLUS_TEXT ("Unrecognized log level: ")
        + arg);

    return NOT_SET_LOG_LEVEL;
}

void
LogLevelManager::pushToStringMethod(LogLevelToStringMethod newToString)
{
    LogLevelToStringMethodRec rec;
    rec.func = newToString;
    rec.use_1_0 = false;
    toStringMethods.insert (toStringMethods.begin (), rec);
}

void
LogLevelManager::pushToStringMethod(LogLevelToStringMethod_1_0 newToString)
{
    LogLevelToStringMethodRec rec;
    rec.func_1_0 = newToString;
    rec.use_1_0 = true;
    toStringMethods.insert (toStringMethods.begin (), rec);
}

void
LogLevelManager::pushFromStringMethod(StringToLogLevelMethod newFromString)
{
    fromStringMethods.insert (fromStringMethods.begin (), newFromString);
}

} // namespace log4cplus
<|endoftext|>


<commit_before><commit_msg>A program to encrypt/decrypt text<commit_after><|endoftext|>


<commit_before><commit_msg>CefBrowserPlugin working with full-hd video on a sphere :)<commit_after><|endoftext|>


<commit_before>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights.  These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "dummylightsensor.h"
#include <QDebug>
#include <QtGlobal>

const char *dummylightsensor::id("dummy.lightsensor");

dummylightsensor::dummylightsensor(QSensor *sensor)
    : dummycommon(sensor)
{
    setReading<QAmbientLightReading>(&m_reading);
}

void dummylightsensor::poll()
{
    m_reading.setTimestamp(getTimestamp());
    if ((qrand() % 100) == 0)
        m_reading.setLightLevel(QAmbientLightReading::Dark);
    else
        m_reading.setLightLevel(QAmbientLightReading::Light);

    newReadingAvailable();
}

<commit_msg>Make the dummy light sensor do something!<commit_after>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights.  These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "dummylightsensor.h"
#include <QDebug>
#include <QtGlobal>

const char *dummylightsensor::id("dummy.lightsensor");

dummylightsensor::dummylightsensor(QSensor *sensor)
    : dummycommon(sensor)
{
    setReading<QAmbientLightReading>(&m_reading);
    addDataRate(100,100);
    sensor->setDataRate(100);
}

void dummylightsensor::poll()
{
    m_reading.setTimestamp(getTimestamp());
    if ((qrand() % 100) == 0)
        m_reading.setLightLevel(QAmbientLightReading::Dark);
    else
        m_reading.setLightLevel(QAmbientLightReading::Light);

    newReadingAvailable();
}

<|endoftext|>


<commit_before><commit_msg>added stdlib.h to FfmpegEncoder.cpp for solving the setenv error message in compilation<commit_after><|endoftext|>


<commit_before>#include "unit_test.hpp"
#include "math/momentum.hpp"
#include "math/epsilon.hpp"

namespace test
{
        template
        <
                typename tscalar,
                typename tsize
        >
        void check_momentum(const tscalar momentum, const tsize range)
        {
                math::momentum_scalar_t<tscalar> mom00(momentum);
                math::momentum_scalar_t<tscalar> mom01(momentum);
                math::momentum_scalar_t<tscalar> mom10(momentum);
                math::momentum_scalar_t<tscalar> mom11(momentum);

                const auto epsilon = math::epsilon1<tscalar>();
                auto powm = momentum;
                for (tsize i = 1; i <= range; ++ i, powm *= momentum)
                {
                        mom00.update(tscalar(0));
                        mom01.update(tscalar(0));
                        mom10.update(tscalar(1));
                        mom11.update(tscalar(1));

                        const auto base00 = tscalar(0);
                        const auto base01 = powm;
                        const auto base10 = tscalar(1) - powm;
                        const auto base11 = tscalar(1);

                        NANOCV_CHECK_CLOSE(mom00.value(), base00, epsilon);
                        NANOCV_CHECK_CLOSE(mom01.value(), base01, epsilon);
                        NANOCV_CHECK_CLOSE(mom10.value(), base10, epsilon);
                        NANOCV_CHECK_CLOSE(mom11.value(), base11, epsilon);
                }
        }

        template
        <
                typename tvector,
                typename tscalar = typename tvector::Scalar,
                typename tsize = typename tvector::Index
        >
        void check_momentum(const tsize dims, const tscalar momentum, const tsize range)
        {
                math::momentum_vector_t<tvector> mom00(momentum, dims);
                math::momentum_vector_t<tvector> mom01(momentum, dims);
                math::momentum_vector_t<tvector> mom10(momentum, dims);
                math::momentum_vector_t<tvector> mom11(momentum, dims);

                const auto epsilon = math::epsilon1<tscalar>();
                auto powm = momentum;
                for (tsize i = 1; i <= range; ++ i, powm *= momentum)
                {
                        mom00.update(tvector::Constant(dims, tscalar(0)));
                        mom01.update(tvector::Constant(dims, tscalar(0)));
                        mom10.update(tvector::Constant(dims, tscalar(1)));
                        mom11.update(tvector::Constant(dims, tscalar(1)));

                        const auto base00 = tvector::Constant(dims, tscalar(0));
                        const auto base01 = tvector::Constant(dims, powm);
                        const auto base10 = tvector::Constant(dims, tscalar(1) - powm);
                        const auto base11 = tvector::Constant(dims, tscalar(1));

                        NANOCV_CHECK_EIGEN_CLOSE(mom00.value(), base00, epsilon);
                        NANOCV_CHECK_EIGEN_CLOSE(mom01.value(), base01, epsilon);
                        NANOCV_CHECK_EIGEN_CLOSE(mom10.value(), base10, epsilon);
                        NANOCV_CHECK_EIGEN_CLOSE(mom11.value(), base11, epsilon);
                }
        }
}

NANOCV_BEGIN_MODULE(test_momentum)

NANOCV_CASE(scalar)
{
        test::check_momentum<double>(0.1, 123);
        test::check_momentum<double>(0.5, 127);
        test::check_momentum<double>(0.9, 253);
}

NANOCV_CASE(vector)
{
        test::check_momentum<Eigen::VectorXd>(13, 0.1, 98);
        test::check_momentum<Eigen::VectorXd>(17, 0.5, 75);
        test::check_momentum<Eigen::VectorXd>(11, 0.9, 54);
}

NANOCV_END_MODULE()
<commit_msg>fix unit test for momentum<commit_after>#include "unit_test.hpp"
#include "math/momentum.hpp"
#include "math/epsilon.hpp"

namespace test
{
        template
        <
                typename tscalar,
                typename tsize
        >
        void check_momentum(const tscalar momentum, const tsize range)
        {
                math::momentum_scalar_t<tscalar> mom00(momentum);
                math::momentum_scalar_t<tscalar> mom01(momentum);
                math::momentum_scalar_t<tscalar> mom10(1 - momentum);
                math::momentum_scalar_t<tscalar> mom11(1 - momentum);

                const auto epsilon = math::epsilon1<tscalar>();
                for (tsize i = 1; i <= range; ++ i)
                {
                        const auto base00 = momentum;
                        const auto base01 = 1 - momentum;
                        const auto base10 = momentum;
                        const auto base11 = 1 - momentum;

                        mom00.update(base00);
                        mom01.update(base01);
                        mom10.update(base10);
                        mom11.update(base11);

                        NANOCV_CHECK_CLOSE(mom00.value(), base00, epsilon);
                        NANOCV_CHECK_CLOSE(mom01.value(), base01, epsilon);
                        NANOCV_CHECK_CLOSE(mom10.value(), base10, epsilon);
                        NANOCV_CHECK_CLOSE(mom11.value(), base11, epsilon);
                }
        }

        template
        <
                typename tvector,
                typename tscalar = typename tvector::Scalar,
                typename tsize = typename tvector::Index
        >
        void check_momentum(const tsize dims, const tscalar momentum, const tsize range)
        {
                math::momentum_vector_t<tvector> mom00(momentum, dims);
                math::momentum_vector_t<tvector> mom01(momentum, dims);
                math::momentum_vector_t<tvector> mom10(1 - momentum, dims);
                math::momentum_vector_t<tvector> mom11(1 - momentum, dims);

                const auto epsilon = math::epsilon1<tscalar>();
                for (tsize i = 1; i <= range; ++ i)
                {
                        const auto base00 = tvector::Constant(dims, momentum);
                        const auto base01 = tvector::Constant(dims, 1 - momentum);
                        const auto base10 = tvector::Constant(dims, momentum);
                        const auto base11 = tvector::Constant(dims, 1 - momentum);

                        mom00.update(base00);
                        mom01.update(base01);
                        mom10.update(base10);
                        mom11.update(base11);

                        NANOCV_CHECK_EIGEN_CLOSE(mom00.value(), base00, epsilon);
                        NANOCV_CHECK_EIGEN_CLOSE(mom01.value(), base01, epsilon);
                        NANOCV_CHECK_EIGEN_CLOSE(mom10.value(), base10, epsilon);
                        NANOCV_CHECK_EIGEN_CLOSE(mom11.value(), base11, epsilon);
                }
        }
}

NANOCV_BEGIN_MODULE(test_momentum)

NANOCV_CASE(scalar)
{
        test::check_momentum<double>(0.1, 123);
        test::check_momentum<double>(0.5, 127);
        test::check_momentum<double>(0.9, 253);
}

NANOCV_CASE(vector)
{
        test::check_momentum<Eigen::VectorXd>(13, 0.1, 98);
        test::check_momentum<Eigen::VectorXd>(17, 0.5, 75);
        test::check_momentum<Eigen::VectorXd>(11, 0.9, 54);
}

NANOCV_END_MODULE()
<|endoftext|>


<commit_before>#include <reversed.hpp>

#include <vector>
#include <array>
#include <string>
#include <utility>

#include "catch.hpp"

#define DECLARE_REVERSE_ITERATOR
#include "helpers.hpp"
#undef DECLARE_REVERSE_ITERATOR

using iter::reversed;
using Vec = const std::vector<int>;

TEST_CASE("reversed: can reverse a vector", "[reversed]") {
  Vec ns = {10, 20, 30, 40};
  std::vector<int> v;
  SECTION("Normal call") {
    auto r = reversed(ns);
    v.assign(std::begin(r), std::end(r));
  }
  SECTION("Pipe") {
    auto r = ns | reversed;
    v.assign(std::begin(r), std::end(r));
  }

  Vec vc = {40, 30, 20, 10};

  REQUIRE(v == vc);
}

TEST_CASE("reversed: can reverse an array", "[reversed]") {
  int ns[] = {10, 20, 30, 40};
  auto r = reversed(ns);

  Vec v(std::begin(r), std::end(r));
  Vec vc = {40, 30, 20, 10};

  REQUIRE(v == vc);
}

TEST_CASE("reversed: empty when iterable is empty", "[reversed]") {
  Vec emp{};
  auto r = reversed(emp);
  REQUIRE(std::begin(r) == std::end(r));
}

TEST_CASE("reversed: moves rvalues and binds to lvalues", "[reversed]") {
  itertest::BasicIterable<int> bi{1, 2};
  itertest::BasicIterable<int> bi2{1, 2};
  reversed(bi);
  REQUIRE_FALSE(bi.was_moved_from());

  reversed(std::move(bi2));
  REQUIRE(bi2.was_moved_from());
}

TEST_CASE("reversed: doesn't move or copy elements of array", "[reversed]") {
  constexpr itertest::SolidInt arr[] = {{6}, {7}, {8}};
  for (auto&& i : reversed(arr)) {
    (void)i;
  }
}

TEST_CASE("reversed: with iterable doesn't move or copy elems", "[reversed]") {
  constexpr std::array<itertest::SolidInt, 3> arr{{{6}, {7}, {8}}};
  for (auto&& i : reversed(arr)) {
    (void)i;
  }
}

TEST_CASE("reversed: iterator meets requirements", "[reversed]") {
  Vec v;
  auto r = reversed(v);
  REQUIRE(itertest::IsIterator<decltype(std::begin(r))>::value);

  int a[1];
  auto ra = reversed(a);
  REQUIRE(itertest::IsIterator<decltype(std::begin(ra))>::value);
}

template <typename T>
using ImpT = decltype(reversed(std::declval<T>()));
TEST_CASE("reversed: has correct ctor and assign ops", "[reversed]") {
  REQUIRE(itertest::IsMoveConstructibleOnly<ImpT<std::string&>>::value);
  REQUIRE(itertest::IsMoveConstructibleOnly<ImpT<std::string>>::value);
}
<commit_msg>Tests reversed with different begin and end<commit_after>#include <reversed.hpp>

#include <vector>
#include <array>
#include <string>
#include <utility>

#include "catch.hpp"

#define DECLARE_REVERSE_ITERATOR
#include "helpers.hpp"
#undef DECLARE_REVERSE_ITERATOR

using iter::reversed;
using Vec = const std::vector<int>;

TEST_CASE("reversed: can reverse a vector", "[reversed]") {
  Vec ns = {10, 20, 30, 40};
  std::vector<int> v;
  SECTION("Normal call") {
    auto r = reversed(ns);
    v.assign(std::begin(r), std::end(r));
  }
  SECTION("Pipe") {
    auto r = ns | reversed;
    v.assign(std::begin(r), std::end(r));
  }

  Vec vc = {40, 30, 20, 10};

  REQUIRE(v == vc);
}

#if 0
TEST_CASE("reversed: Works with different begin and end types",
    "[reversed]") {
  CharRange cr{'d'};
  auto r = reversed(cr);
  Vec v(r.begin(), r.end());
  Vec vc{'c', 'b', 'a'};
  REQUIRE(v == vc);
}
#endif

TEST_CASE("reversed: can reverse an array", "[reversed]") {
  int ns[] = {10, 20, 30, 40};
  auto r = reversed(ns);

  Vec v(std::begin(r), std::end(r));
  Vec vc = {40, 30, 20, 10};

  REQUIRE(v == vc);
}

TEST_CASE("reversed: empty when iterable is empty", "[reversed]") {
  Vec emp{};
  auto r = reversed(emp);
  REQUIRE(std::begin(r) == std::end(r));
}

TEST_CASE("reversed: moves rvalues and binds to lvalues", "[reversed]") {
  itertest::BasicIterable<int> bi{1, 2};
  itertest::BasicIterable<int> bi2{1, 2};
  reversed(bi);
  REQUIRE_FALSE(bi.was_moved_from());

  reversed(std::move(bi2));
  REQUIRE(bi2.was_moved_from());
}

TEST_CASE("reversed: doesn't move or copy elements of array", "[reversed]") {
  constexpr itertest::SolidInt arr[] = {{6}, {7}, {8}};
  for (auto&& i : reversed(arr)) {
    (void)i;
  }
}

TEST_CASE("reversed: with iterable doesn't move or copy elems", "[reversed]") {
  constexpr std::array<itertest::SolidInt, 3> arr{{{6}, {7}, {8}}};
  for (auto&& i : reversed(arr)) {
    (void)i;
  }
}

TEST_CASE("reversed: iterator meets requirements", "[reversed]") {
  Vec v;
  auto r = reversed(v);
  REQUIRE(itertest::IsIterator<decltype(std::begin(r))>::value);

  int a[1];
  auto ra = reversed(a);
  REQUIRE(itertest::IsIterator<decltype(std::begin(ra))>::value);
}

template <typename T>
using ImpT = decltype(reversed(std::declval<T>()));
TEST_CASE("reversed: has correct ctor and assign ops", "[reversed]") {
  REQUIRE(itertest::IsMoveConstructibleOnly<ImpT<std::string&>>::value);
  REQUIRE(itertest::IsMoveConstructibleOnly<ImpT<std::string>>::value);
}
<|endoftext|>