<commit_before>/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements. See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership. The ASF licenses this file
 * to you 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 <thrift/thrift-config.h>

#include <algorithm>
#include <iostream>
#include <random>

#include <thrift/transport/TSocketPool.h>

using std::pair;
using std::string;
using std::vector;

namespace apache {
namespace thrift {
namespace transport {

using stdcxx::shared_ptr;

/**
 * TSocketPoolServer implementation
 *
 */
TSocketPoolServer::TSocketPoolServer()
  : host_(""), port_(0), socket_(THRIFT_INVALID_SOCKET), lastFailTime_(0), consecutiveFailures_(0) {
}

/**
 * Constructor for TSocketPool server
 */
TSocketPoolServer::TSocketPoolServer(const string& host, int port)
  : host_(host),
    port_(port),
    socket_(THRIFT_INVALID_SOCKET),
    lastFailTime_(0),
    consecutiveFailures_(0) {
}

/**
 * TSocketPool implementation.
 *
 */

TSocketPool::TSocketPool()
  : TSocket(),
    numRetries_(1),
    retryInterval_(60),
    maxConsecutiveFailures_(1),
    randomize_(true),
    alwaysTryLast_(true) {
}

TSocketPool::TSocketPool(const vector<string>& hosts, const vector<int>& ports)
  : TSocket(),
    numRetries_(1),
    retryInterval_(60),
    maxConsecutiveFailures_(1),
    randomize_(true),
    alwaysTryLast_(true) {
  if (hosts.size() != ports.size()) {
    GlobalOutput("TSocketPool::TSocketPool: hosts.size != ports.size");
    throw TTransportException(TTransportException::BAD_ARGS);
  }

  for (unsigned int i = 0; i < hosts.size(); ++i) {
    addServer(hosts[i], ports[i]);
  }
}

TSocketPool::TSocketPool(const vector<pair<string, int> >& servers)
  : TSocket(),
    numRetries_(1),
    retryInterval_(60),
    maxConsecutiveFailures_(1),
    randomize_(true),
    alwaysTryLast_(true) {
  for (unsigned i = 0; i < servers.size(); ++i) {
    addServer(servers[i].first, servers[i].second);
  }
}

TSocketPool::TSocketPool(const vector<shared_ptr<TSocketPoolServer> >& servers)
  : TSocket(),
    servers_(servers),
    numRetries_(1),
    retryInterval_(60),
    maxConsecutiveFailures_(1),
    randomize_(true),
    alwaysTryLast_(true) {
}

TSocketPool::TSocketPool(const string& host, int port)
  : TSocket(),
    numRetries_(1),
    retryInterval_(60),
    maxConsecutiveFailures_(1),
    randomize_(true),
    alwaysTryLast_(true) {
  addServer(host, port);
}

TSocketPool::~TSocketPool() {
  vector<shared_ptr<TSocketPoolServer> >::const_iterator iter = servers_.begin();
  vector<shared_ptr<TSocketPoolServer> >::const_iterator iterEnd = servers_.end();
  for (; iter != iterEnd; ++iter) {
    setCurrentServer(*iter);
    TSocketPool::close();
  }
}

void TSocketPool::addServer(const string& host, int port) {
  servers_.push_back(shared_ptr<TSocketPoolServer>(new TSocketPoolServer(host, port)));
}

void TSocketPool::addServer(shared_ptr<TSocketPoolServer>& server) {
  if (server) {
    servers_.push_back(server);
  }
}

void TSocketPool::setServers(const vector<shared_ptr<TSocketPoolServer> >& servers) {
  servers_ = servers;
}

void TSocketPool::getServers(vector<shared_ptr<TSocketPoolServer> >& servers) {
  servers = servers_;
}

void TSocketPool::setNumRetries(int numRetries) {
  numRetries_ = numRetries;
}

void TSocketPool::setRetryInterval(int retryInterval) {
  retryInterval_ = retryInterval;
}

void TSocketPool::setMaxConsecutiveFailures(int maxConsecutiveFailures) {
  maxConsecutiveFailures_ = maxConsecutiveFailures;
}

void TSocketPool::setRandomize(bool randomize) {
  randomize_ = randomize;
}

void TSocketPool::setAlwaysTryLast(bool alwaysTryLast) {
  alwaysTryLast_ = alwaysTryLast;
}

void TSocketPool::setCurrentServer(const shared_ptr<TSocketPoolServer>& server) {
  currentServer_ = server;
  host_ = server->host_;
  port_ = server->port_;
  socket_ = server->socket_;
}

/**
 * This function throws an exception if socket open fails. When socket
 * opens fails, the socket in the current server is reset.
 */
/* TODO: without apc we ignore a lot of functionality from the php version */
void TSocketPool::open() {

  size_t numServers = servers_.size();
  if (numServers == 0) {
    socket_ = THRIFT_INVALID_SOCKET;
    throw TTransportException(TTransportException::NOT_OPEN);
  }

  if (isOpen()) {
    return;
  }

  if (randomize_ && numServers > 1) {
#if __cplusplus >= 201500L // c++17
    std::random_device rng;
    std::mt19937 urng(rng());
    std::shuffle(servers_.begin(), servers_.end(), urng);
#else
    std::random_shuffle(servers_.begin(), servers_.end());
#endif
  }

  for (size_t i = 0; i < numServers; ++i) {

    shared_ptr<TSocketPoolServer>& server = servers_[i];
    // Impersonate the server socket
    setCurrentServer(server);

    if (isOpen()) {
      // already open means we're done
      return;
    }

    bool retryIntervalPassed = (server->lastFailTime_ == 0);
    bool isLastServer = alwaysTryLast_ ? (i == (numServers - 1)) : false;

    if (server->lastFailTime_ > 0) {
      // The server was marked as down, so check if enough time has elapsed to retry
      time_t elapsedTime = time(NULL) - server->lastFailTime_;
      if (elapsedTime > retryInterval_) {
        retryIntervalPassed = true;
      }
    }

    if (retryIntervalPassed || isLastServer) {
      for (int j = 0; j < numRetries_; ++j) {
        try {
          TSocket::open();
        } catch (const TException &e) {
          string errStr = "TSocketPool::open failed " + getSocketInfo() + ": " + e.what();
          GlobalOutput(errStr.c_str());
          socket_ = THRIFT_INVALID_SOCKET;
          continue;
        }

        // Copy over the opened socket so that we can keep it persistent
        server->socket_ = socket_;
        // reset lastFailTime_ is required
        server->lastFailTime_ = 0;
        // success
        return;
      }

      ++server->consecutiveFailures_;
      if (server->consecutiveFailures_ > maxConsecutiveFailures_) {
        // Mark server as down
        server->consecutiveFailures_ = 0;
        server->lastFailTime_ = time(NULL);
      }
    }
  }

  GlobalOutput("TSocketPool::open: all connections failed");
  throw TTransportException(TTransportException::NOT_OPEN);
}

void TSocketPool::close() {
  TSocket::close();
  if (currentServer_) {
    currentServer_->socket_ = THRIFT_INVALID_SOCKET;
  }
}
}
}
} // apache::thrift::transport
<commit_msg>Correct c++17 definition<commit_after>/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements. See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership. The ASF licenses this file
 * to you 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 <thrift/thrift-config.h>

#include <algorithm>
#include <iostream>
#include <random>

#include <thrift/transport/TSocketPool.h>

using std::pair;
using std::string;
using std::vector;

namespace apache {
namespace thrift {
namespace transport {

using stdcxx::shared_ptr;

/**
 * TSocketPoolServer implementation
 *
 */
TSocketPoolServer::TSocketPoolServer()
  : host_(""), port_(0), socket_(THRIFT_INVALID_SOCKET), lastFailTime_(0), consecutiveFailures_(0) {
}

/**
 * Constructor for TSocketPool server
 */
TSocketPoolServer::TSocketPoolServer(const string& host, int port)
  : host_(host),
    port_(port),
    socket_(THRIFT_INVALID_SOCKET),
    lastFailTime_(0),
    consecutiveFailures_(0) {
}

/**
 * TSocketPool implementation.
 *
 */

TSocketPool::TSocketPool()
  : TSocket(),
    numRetries_(1),
    retryInterval_(60),
    maxConsecutiveFailures_(1),
    randomize_(true),
    alwaysTryLast_(true) {
}

TSocketPool::TSocketPool(const vector<string>& hosts, const vector<int>& ports)
  : TSocket(),
    numRetries_(1),
    retryInterval_(60),
    maxConsecutiveFailures_(1),
    randomize_(true),
    alwaysTryLast_(true) {
  if (hosts.size() != ports.size()) {
    GlobalOutput("TSocketPool::TSocketPool: hosts.size != ports.size");
    throw TTransportException(TTransportException::BAD_ARGS);
  }

  for (unsigned int i = 0; i < hosts.size(); ++i) {
    addServer(hosts[i], ports[i]);
  }
}

TSocketPool::TSocketPool(const vector<pair<string, int> >& servers)
  : TSocket(),
    numRetries_(1),
    retryInterval_(60),
    maxConsecutiveFailures_(1),
    randomize_(true),
    alwaysTryLast_(true) {
  for (unsigned i = 0; i < servers.size(); ++i) {
    addServer(servers[i].first, servers[i].second);
  }
}

TSocketPool::TSocketPool(const vector<shared_ptr<TSocketPoolServer> >& servers)
  : TSocket(),
    servers_(servers),
    numRetries_(1),
    retryInterval_(60),
    maxConsecutiveFailures_(1),
    randomize_(true),
    alwaysTryLast_(true) {
}

TSocketPool::TSocketPool(const string& host, int port)
  : TSocket(),
    numRetries_(1),
    retryInterval_(60),
    maxConsecutiveFailures_(1),
    randomize_(true),
    alwaysTryLast_(true) {
  addServer(host, port);
}

TSocketPool::~TSocketPool() {
  vector<shared_ptr<TSocketPoolServer> >::const_iterator iter = servers_.begin();
  vector<shared_ptr<TSocketPoolServer> >::const_iterator iterEnd = servers_.end();
  for (; iter != iterEnd; ++iter) {
    setCurrentServer(*iter);
    TSocketPool::close();
  }
}

void TSocketPool::addServer(const string& host, int port) {
  servers_.push_back(shared_ptr<TSocketPoolServer>(new TSocketPoolServer(host, port)));
}

void TSocketPool::addServer(shared_ptr<TSocketPoolServer>& server) {
  if (server) {
    servers_.push_back(server);
  }
}

void TSocketPool::setServers(const vector<shared_ptr<TSocketPoolServer> >& servers) {
  servers_ = servers;
}

void TSocketPool::getServers(vector<shared_ptr<TSocketPoolServer> >& servers) {
  servers = servers_;
}

void TSocketPool::setNumRetries(int numRetries) {
  numRetries_ = numRetries;
}

void TSocketPool::setRetryInterval(int retryInterval) {
  retryInterval_ = retryInterval;
}

void TSocketPool::setMaxConsecutiveFailures(int maxConsecutiveFailures) {
  maxConsecutiveFailures_ = maxConsecutiveFailures;
}

void TSocketPool::setRandomize(bool randomize) {
  randomize_ = randomize;
}

void TSocketPool::setAlwaysTryLast(bool alwaysTryLast) {
  alwaysTryLast_ = alwaysTryLast;
}

void TSocketPool::setCurrentServer(const shared_ptr<TSocketPoolServer>& server) {
  currentServer_ = server;
  host_ = server->host_;
  port_ = server->port_;
  socket_ = server->socket_;
}

/**
 * This function throws an exception if socket open fails. When socket
 * opens fails, the socket in the current server is reset.
 */
/* TODO: without apc we ignore a lot of functionality from the php version */
void TSocketPool::open() {

  size_t numServers = servers_.size();
  if (numServers == 0) {
    socket_ = THRIFT_INVALID_SOCKET;
    throw TTransportException(TTransportException::NOT_OPEN);
  }

  if (isOpen()) {
    return;
  }

  if (randomize_ && numServers > 1) {
#if __cplusplus >= 201703L
    std::random_device rng;
    std::mt19937 urng(rng());
    std::shuffle(servers_.begin(), servers_.end(), urng);
#else
    std::random_shuffle(servers_.begin(), servers_.end());
#endif
  }

  for (size_t i = 0; i < numServers; ++i) {

    shared_ptr<TSocketPoolServer>& server = servers_[i];
    // Impersonate the server socket
    setCurrentServer(server);

    if (isOpen()) {
      // already open means we're done
      return;
    }

    bool retryIntervalPassed = (server->lastFailTime_ == 0);
    bool isLastServer = alwaysTryLast_ ? (i == (numServers - 1)) : false;

    if (server->lastFailTime_ > 0) {
      // The server was marked as down, so check if enough time has elapsed to retry
      time_t elapsedTime = time(NULL) - server->lastFailTime_;
      if (elapsedTime > retryInterval_) {
        retryIntervalPassed = true;
      }
    }

    if (retryIntervalPassed || isLastServer) {
      for (int j = 0; j < numRetries_; ++j) {
        try {
          TSocket::open();
        } catch (const TException &e) {
          string errStr = "TSocketPool::open failed " + getSocketInfo() + ": " + e.what();
          GlobalOutput(errStr.c_str());
          socket_ = THRIFT_INVALID_SOCKET;
          continue;
        }

        // Copy over the opened socket so that we can keep it persistent
        server->socket_ = socket_;
        // reset lastFailTime_ is required
        server->lastFailTime_ = 0;
        // success
        return;
      }

      ++server->consecutiveFailures_;
      if (server->consecutiveFailures_ > maxConsecutiveFailures_) {
        // Mark server as down
        server->consecutiveFailures_ = 0;
        server->lastFailTime_ = time(NULL);
      }
    }
  }

  GlobalOutput("TSocketPool::open: all connections failed");
  throw TTransportException(TTransportException::NOT_OPEN);
}

void TSocketPool::close() {
  TSocket::close();
  if (currentServer_) {
    currentServer_->socket_ = THRIFT_INVALID_SOCKET;
  }
}
}
}
} // apache::thrift::transport
<|endoftext|>


<commit_before>#include <bits/stdc++.h>
using namespace std;

// BIT to find number of elements <= x in range [l, r] supporting updates.
// all elements a[i] must be such that 1 <= a[i] <= N (but you can always
// compress the input numbers, if necessary!)

// maximum number of different elements
const int N = 2e5+5;

// block size
const int M = 2e3;

// input array
int a[N];

struct bit {
  int ft[N+5];
  void add(int i, int x) {
    for (; i <= N; i += i&-i) ft[i] += x;
  }
  int query(int i) {
    int ans = 0; for (; i > 0; i -= i&-i) ans += ft[i]; return ans;
  }
} block[(N+M-1)/M+5];

int getblock(int i) { return (i-1)/M+1; }
int blockright(int b) { return b*M; }
int blockleft(int b) { return blockright(b-1)+1; }

void update(int i, int x) {
  int b = getblock(i);
  block[b].add(a[i],-1);
  a[i] = x;
  block[b].add(a[i],1);
}

int query(int l, int r, int x) {
  if (r < l) return 0;
  int L = getblock(l), R = getblock(r), ans = 0;
  if (L == R) {
    for (int i = l; i <= r; i++) ans += (a[i] <= x);
    return ans;
  }
  for (int i = l; i <= blockright(L); i++) ans += (a[i] <= x);
  for (int b = L+1; b <= R-1; b++) ans += block[b].query(x);
  for (int i = blockleft(R); i <= r; i++) ans += (a[i] <= x);
  return ans;
}

int main() {
  return 0;
}
<commit_msg>Fixing bug<commit_after>#include <bits/stdc++.h>
using namespace std;

// BIT to find number of elements <= x in range [l, r] supporting updates.
// all elements a[i] must be such that 1 <= a[i] <= N (but you can always
// compress the input numbers, if necessary!)

// maximum number of different elements
const int N = 2e5+5;

// block size
const int M = 2e3;

// input array
int a[N];

struct bit {
  int ft[N+5];
  void add(int i, int x) {
    for (; 0 < i && i <= N; i += i&-i) ft[i] += x;
  }
  int query(int i) {
    int ans = 0; for (; 0 < i; i -= i&-i) ans += ft[i]; return ans;
  }
} block[(N+M-1)/M+5];

int getblock(int i) { return (i-1)/M+1; }
int blockright(int b) { return b*M; }
int blockleft(int b) { return blockright(b-1)+1; }

void update(int i, int x) {
  int b = getblock(i);
  block[b].add(a[i],-1);
  a[i] = x;
  block[b].add(a[i],1);
}

int query(int l, int r, int x) {
  if (r < l) return 0;
  int L = getblock(l), R = getblock(r), ans = 0;
  if (L == R) {
    for (int i = l; i <= r; i++) ans += (a[i] <= x);
    return ans;
  }
  for (int i = l; i <= blockright(L); i++) ans += (a[i] <= x);
  for (int b = L+1; b <= R-1; b++) ans += block[b].query(x);
  for (int i = blockleft(R); i <= r; i++) ans += (a[i] <= x);
  return ans;
}

int main() {
  return 0;
}
<|endoftext|>


<commit_before>#include <bits/stdc++.h>
using namespace std;

// BIT to find number of elements <= x in range [l, r] supporting updates
// all elements a_i must be such that 1 <= a_i <= N (compress if necessary!)

// maximum number of different elements
const int N = 2e5+5;

// block size
const int M = 2e3;

// input array
int a[N];

struct bit {
  int ft[N+1];
  void add(int i, int x) {
    for (; i <= N; i += i&-i) ft[i] += x;
  }
  int query(int i) {
    int ans = 0; for (; i > 0; i -= i&-i) ans += ft[i]; return ans;
  }
} block[(N+M-1)/M+5];

int getblock(int i) { return (i-1)/M+1; }
int blockright(int b) { return b*M; }
int blockleft(int b) { return blockright(b-1)+1; }

void update(int i, int x) {
  int b = getblock(i);
  block[b].add(a[i],-1);
  a[i] = x;
  block[b].add(a[i],1);
}

int query(int l, int r, int x) {
  if (r < l) return 0;
  int L = getblock(l), R = getblock(r), ans = 0;
  if (L == R) {
    for (int i = l; i <= r; i++) ans += (a[i] <= x);
    return ans;
  }
  for (int i = l; i <= blockright(L); i++) ans += (a[i] <= x);
  for (int b = L+1; b <= R-1; b++) ans += block[b].query(x);
  for (int i = blockleft(R); i <= r; i++) ans += (a[i] <= x);
  return ans;
}

int main() {
  return 0;
}
<commit_msg>Update data structure<commit_after>#include <bits/stdc++.h>
using namespace std;

// BIT to find number of elements <= x in range [l, r] supporting updates
// all elements a_i must be such that 1 <= a_i <= N (compress if necessary!)

// maximum number of different elements
const int N = 2e5+5;

// block size
const int M = 2e3;

// input array
int a[N];

struct bit {
  int ft[N];
  void add(int i, int x) {
    for (; i < N; i += i&-i) ft[i] += x;
  }
  int query(int i) {
    int ans = 0; for (; i > 0; i -= i&-i) ans += ft[i]; return ans;
  }
} block[(N+M-1)/M+5];

int getblock(int i) { return (i-1)/M+1; }
int blockright(int b) { return b*M; }
int blockleft(int b) { return blockright(b-1)+1; }

void update(int i, int x) {
  int b = getblock(i);
  block[b].add(a[i],-1);
  a[i] = x;
  block[b].add(a[i],1);
}

int query(int l, int r, int x) {
  if (r < l) return 0;
  int L = getblock(l), R = getblock(r), ans = 0;
  if (L == R) {
    for (int i = l; i <= r; i++) ans += (a[i] <= x);
    return ans;
  }
  for (int i = l; i <= blockright(L); i++) ans += (a[i] <= x);
  for (int b = L+1; b <= R-1; b++) ans += block[b].query(x);
  for (int i = blockleft(R); i <= r; i++) ans += (a[i] <= x);
  return ans;
}

int main() {
  return 0;
}
<|endoftext|>


<commit_before>/// HEADER
#include "transform_filter.h"

/// COMPONENT
#include <csapex_transform/transform_message.h>

/// PROJECT
#include <csapex/model/connector_out.h>
#include <csapex/model/connector_in.h>
#include <utils_param/parameter_factory.h>

/// SYSTEM
#include <csapex/utility/register_apex_plugin.h>
#define BOOST_SIGNALS_NO_DEPRECATION_WARNING

#define RAD_TO_DEG(x) ((x) * 57.29578)

CSAPEX_REGISTER_CLASS(csapex::TransformFilter, csapex::Node)

using namespace csapex;
using namespace csapex::connection_types;

TransformFilter::TransformFilter()
{
    addTag(Tag::get("Transform"));
    addTag(Tag::get("Filter"));

    median_matrix_.resize(6);

    // Initialize the out_vector_latch with zeros
    for (int i = 0; i < 6; i++) {
        out_vector_latch_.push_back(0);
    }
}

void TransformFilter::setup()
{
    input_transform_ = addInput<connection_types::TransformMessage>("Raw Transformation");

    output_transform_ = addOutput<connection_types::TransformMessage>("Filtered Transformation");
    output_text_ = addOutput<DirectMessage<std::string> >("String"); // create a debug output

    addParameter(param::ParameterFactory::declare("filter size", 1, 10000, 200, 100));
}

void TransformFilter::process()
{
    filter_size_ =  (unsigned int)param<int>("filter size");

    // Output Varibales
    double x,y,z;
    double roll, pitch, yaw;
    std::stringstream stringstream;

    // Get data from input
    TransformMessage::Ptr trafo_msg = input_transform_->getMessage<TransformMessage>();
    tf::Transform tf_raw = trafo_msg->value;
    tf::Transform tf_filtered;

    // Run the filter Algorithmn
    runFilter(tf_raw, tf_filtered);

    // Convert the Result to x,y,z r,p,y for debug display
    tfToXYZrpy(tf_filtered, x, y, z, roll, pitch, yaw);

    // Publish Output - Debug
    stringstream << "x = " << x << ",y = " << y << ",z = " << z
                 << ",r = " << RAD_TO_DEG(roll) << ",p = " << RAD_TO_DEG(pitch)<< ",y = " << RAD_TO_DEG(yaw);
    DirectMessage<std::string>::Ptr text_msg(new DirectMessage<std::string>);
    text_msg->value = stringstream.str();
    output_text_->publish(text_msg);

    // Publish Output - Transformation
    connection_types::TransformMessage::Ptr msg(new connection_types::TransformMessage);
    msg->value = tf_filtered;
    output_transform_->publish(msg);
}

void TransformFilter::tfToXYZrpy(tf::Transform& in, double& x, double& y, double& z, double& roll, double& pitch, double& yaw)
{
    // Extract the origin
    tf::Vector3 origin = in.getOrigin();
    x = origin.getX();
    y = origin.getY();
    z = origin.getZ();

    // Extract the rotation
    tf::Matrix3x3 rotation(in.getRotation());
    rotation.getEulerYPR(roll, pitch, yaw);
}

void TransformFilter::runFilter(tf::Transform& in_new, tf::Transform& out)
{
    double x,y,z;
    double roll, pitch, yaw;

    tfToXYZrpy(in_new, x, y, z, roll, pitch, yaw);

    std::vector<double> out_vector;

    // Check if not all values are zero
//    bool out_vector_latch_is_zero = true;
//    for(std::vector<double>::iterator j=out_vector_latch_.begin();j!=out_vector_latch_.end();++j) {
//        out_vector_latch_is_zero = ((*j ==0) && out_vector_latch_is_zero);
//    }
//    if (! out_vector_latch_is_zero) {

        // filter zeros from invalid transformation
        double test = x+y+z + roll + pitch + yaw;
        if (test != 0) {

            //Eigen::Matrix<float, 1, 6> in_vector(x, y, z, roll, pitch, yaw); // row vector
            std::vector<double> in_vector;
            in_vector.push_back(x);
            in_vector.push_back(y);
            in_vector.push_back(z);

            in_vector.push_back(roll);
            in_vector.push_back(pitch);
            in_vector.push_back(yaw);

            // Save new values in median_matrix_
            for (unsigned int i = 0; i< in_vector.size(); i++) {
                // Some thing like a moving average filter
                if (median_matrix_[i].size() < filter_size_) {
                    median_matrix_[i].push_back(in_vector[i]); // append values, if filter is not full
                } else {
                    median_matrix_[i][filter_index_] = in_vector[i]; // insert values if filter is full
                }

                // Remove the elements of the back, if the filter size was reduced
                while(filter_size_ < median_matrix_[i].size()) {
                    median_matrix_[i].pop_back();
                }
            }
            filter_index_ = (filter_index_ + 1) % filter_size_; // rotate the index

            // Calculate the mean over the vector
            for (unsigned int i = 0; i< in_vector.size(); i++) {
                out_vector.push_back(mean(median_matrix_[i]));
            }
            out_vector_latch_ = out_vector;
        }
//    } else {
//        // Return 0 for all values if the vector was 0 before
//        for (unsigned int i = 0; i< 6; i++) {
//            out_vector.push_back(0.0);
//        }
//        out_vector_latch_ = out_vector;
//    }

    // Convert x y z , r p y back to Origin an Quaternion
    tf::Vector3 origin(out_vector_latch_.at(0), out_vector_latch_.at(1), out_vector_latch_.at(2));
    out.setOrigin(origin);

    tf::Quaternion rotation = tf::createQuaternionFromRPY(out_vector_latch_.at(3), out_vector_latch_.at(4), out_vector_latch_.at(5));
    out.setRotation(rotation);
}

double TransformFilter::mean(std::vector<double> in)
{
    double sum_of_elems = 0;
    for(std::vector<double>::iterator j=in.begin();j!=in.end();++j) {
        sum_of_elems += *j;
    }
    std::cout << "SIZE " << in.size() << std::endl;
    if (in.size() != 0) {
        return sum_of_elems / in.size();
    } else {
        return 0;
    }
}
<commit_msg>removed comment<commit_after>/// HEADER
#include "transform_filter.h"

/// COMPONENT
#include <csapex_transform/transform_message.h>

/// PROJECT
#include <csapex/model/connector_out.h>
#include <csapex/model/connector_in.h>
#include <utils_param/parameter_factory.h>

/// SYSTEM
#include <csapex/utility/register_apex_plugin.h>
#define BOOST_SIGNALS_NO_DEPRECATION_WARNING

#define RAD_TO_DEG(x) ((x) * 57.29578)

CSAPEX_REGISTER_CLASS(csapex::TransformFilter, csapex::Node)

using namespace csapex;
using namespace csapex::connection_types;

TransformFilter::TransformFilter()
{
    addTag(Tag::get("Transform"));
    addTag(Tag::get("Filter"));

    median_matrix_.resize(6);

    // Initialize the out_vector_latch with zeros
    for (int i = 0; i < 6; i++) {
        out_vector_latch_.push_back(0);
    }
}

void TransformFilter::setup()
{
    input_transform_ = addInput<connection_types::TransformMessage>("Raw Transformation");

    output_transform_ = addOutput<connection_types::TransformMessage>("Filtered Transformation");
    output_text_ = addOutput<DirectMessage<std::string> >("String"); // create a debug output

    addParameter(param::ParameterFactory::declare("filter size", 1, 10000, 200, 100));
}

void TransformFilter::process()
{
    filter_size_ =  (unsigned int)param<int>("filter size");

    // Output Varibales
    double x,y,z;
    double roll, pitch, yaw;
    std::stringstream stringstream;

    // Get data from input
    TransformMessage::Ptr trafo_msg = input_transform_->getMessage<TransformMessage>();
    tf::Transform tf_raw = trafo_msg->value;
    tf::Transform tf_filtered;

    // Run the filter Algorithmn
    runFilter(tf_raw, tf_filtered);

    // Convert the Result to x,y,z r,p,y for debug display
    tfToXYZrpy(tf_filtered, x, y, z, roll, pitch, yaw);

    // Publish Output - Debug
    stringstream << "x = " << x << ",y = " << y << ",z = " << z
                 << ",r = " << RAD_TO_DEG(roll) << ",p = " << RAD_TO_DEG(pitch)<< ",y = " << RAD_TO_DEG(yaw);
    DirectMessage<std::string>::Ptr text_msg(new DirectMessage<std::string>);
    text_msg->value = stringstream.str();
    output_text_->publish(text_msg);

    // Publish Output - Transformation
    connection_types::TransformMessage::Ptr msg(new connection_types::TransformMessage);
    msg->value = tf_filtered;
    output_transform_->publish(msg);
}

void TransformFilter::tfToXYZrpy(tf::Transform& in, double& x, double& y, double& z, double& roll, double& pitch, double& yaw)
{
    // Extract the origin
    tf::Vector3 origin = in.getOrigin();
    x = origin.getX();
    y = origin.getY();
    z = origin.getZ();

    // Extract the rotation
    tf::Matrix3x3 rotation(in.getRotation());
    rotation.getEulerYPR(roll, pitch, yaw);
}

void TransformFilter::runFilter(tf::Transform& in_new, tf::Transform& out)
{
    double x,y,z;
    double roll, pitch, yaw;

    tfToXYZrpy(in_new, x, y, z, roll, pitch, yaw);

    std::vector<double> out_vector;

        // filter zeros from invalid transformation
        double test = x+y+z + roll + pitch + yaw;
        if (test != 0) {

            //Eigen::Matrix<float, 1, 6> in_vector(x, y, z, roll, pitch, yaw); // row vector
            std::vector<double> in_vector;
            in_vector.push_back(x);
            in_vector.push_back(y);
            in_vector.push_back(z);

            in_vector.push_back(roll);
            in_vector.push_back(pitch);
            in_vector.push_back(yaw);

            // Save new values in median_matrix_
            for (unsigned int i = 0; i< in_vector.size(); i++) {
                // Some thing like a moving average filter
                if (median_matrix_[i].size() < filter_size_) {
                    median_matrix_[i].push_back(in_vector[i]); // append values, if filter is not full
                } else {
                    median_matrix_[i][filter_index_] = in_vector[i]; // insert values if filter is full
                }

                // Remove the elements of the back, if the filter size was reduced
                while(filter_size_ < median_matrix_[i].size()) {
                    median_matrix_[i].pop_back();
                }
            }
            filter_index_ = (filter_index_ + 1) % filter_size_; // rotate the index

            // Calculate the mean over the vector
            for (unsigned int i = 0; i< in_vector.size(); i++) {
                out_vector.push_back(mean(median_matrix_[i]));
            }
            out_vector_latch_ = out_vector;
        }

    // Convert x y z , r p y back to Origin an Quaternion
    tf::Vector3 origin(out_vector_latch_.at(0), out_vector_latch_.at(1), out_vector_latch_.at(2));
    out.setOrigin(origin);

    tf::Quaternion rotation = tf::createQuaternionFromRPY(out_vector_latch_.at(3), out_vector_latch_.at(4), out_vector_latch_.at(5));
    out.setRotation(rotation);
}

double TransformFilter::mean(std::vector<double> in)
{
    double sum_of_elems = 0;
    for(std::vector<double>::iterator j=in.begin();j!=in.end();++j) {
        sum_of_elems += *j;
    }
    std::cout << "SIZE " << in.size() << std::endl;
    if (in.size() != 0) {
        return sum_of_elems / in.size();
    } else {
        return 0;
    }
}
<|endoftext|>


<commit_before>#include <osgFX/Scribe>
#include <osgFX/Registry>

#include <osg/GL>
#include <osg/PolygonOffset>
#include <osg/Material>
#include <osg/LineWidth>
#include <osg/PolygonMode>

#include <string.h>

using namespace osgFX;

namespace
{

    // register a prototype for this effect
    Registry::Proxy proxy(new Scribe);

    // default technique class
    class DefaultTechnique: public Technique {
    public:
        DefaultTechnique(osg::Material *wf_mat, osg::LineWidth *wf_lw)
            : Technique(), wf_mat_(wf_mat), wf_lw_(wf_lw) {}

            bool validate(osg::State &) const
            {
                return strncmp((const char*)glGetString(GL_VERSION), "1.1", 3) >= 0;
            }

    protected:

        void define_passes()
        {
            // implement pass #1
            {
                osg::ref_ptr<osg::StateSet> ss = new osg::StateSet;

                osg::ref_ptr<osg::PolygonOffset> polyoffset = new osg::PolygonOffset;
                polyoffset->setFactor(1.0f);
                polyoffset->setUnits(1.0f);
                ss->setAttributeAndModes(polyoffset.get(), osg::StateAttribute::OVERRIDE|osg::StateAttribute::ON);

                addPass(ss.get());
            }

            // implement pass #2
            {
                osg::ref_ptr<osg::StateSet> ss = new osg::StateSet;

                osg::ref_ptr<osg::PolygonMode> polymode = new osg::PolygonMode;
                polymode->setMode(osg::PolygonMode::FRONT_AND_BACK, osg::PolygonMode::LINE);
                ss->setAttributeAndModes(polymode.get(), osg::StateAttribute::OVERRIDE|osg::StateAttribute::ON);

                wf_lw_->setWidth(1);
                ss->setAttributeAndModes(wf_lw_.get(), osg::StateAttribute::OVERRIDE|osg::StateAttribute::ON);

                wf_mat_->setColorMode(osg::Material::OFF);
                wf_mat_->setDiffuse(osg::Material::FRONT_AND_BACK, osg::Vec4(0, 0, 0, 1));
                wf_mat_->setAmbient(osg::Material::FRONT_AND_BACK, osg::Vec4(0, 0, 0, 1));
                wf_mat_->setSpecular(osg::Material::FRONT_AND_BACK, osg::Vec4(0, 0, 0, 1));
                wf_mat_->setEmission(osg::Material::FRONT_AND_BACK, osg::Vec4(1.0f, 1.0f, 1.0f, 1.0f));
                ss->setAttributeAndModes(wf_mat_.get(), osg::StateAttribute::OVERRIDE|osg::StateAttribute::ON);

                ss->setMode(GL_LIGHTING, osg::StateAttribute::OVERRIDE|osg::StateAttribute::ON);
                ss->setTextureMode(0, GL_TEXTURE_1D, osg::StateAttribute::OVERRIDE|osg::StateAttribute::OFF);
                ss->setTextureMode(0, GL_TEXTURE_2D, osg::StateAttribute::OVERRIDE|osg::StateAttribute::OFF);

                   addPass(ss.get());
            }
        }

    private:
        osg::ref_ptr<osg::Material> wf_mat_;
        osg::ref_ptr<osg::LineWidth> wf_lw_;
    };

}

Scribe::Scribe()
:    Effect(),
    wf_mat_(new osg::Material),
    wf_lw_(new osg::LineWidth)
{
}

Scribe::Scribe(const Scribe &copy, const osg::CopyOp &copyop)
:    Effect(copy, copyop),
    wf_mat_(static_cast<osg::Material *>(copyop(copy.wf_mat_.get()))),
    wf_lw_(static_cast<osg::LineWidth *>(copyop(copy.wf_lw_.get())))
{
}

bool Scribe::define_techniques()
{
    addTechnique(new DefaultTechnique(wf_mat_.get(), wf_lw_.get()));
    return true;
}
<commit_msg>Fixed osgFX::Scribe so that is handled setting of colour and line width correctly, by setting up the Materiail and LineWidth attributes within the Scribe constructor.<commit_after>#include <osgFX/Scribe>
#include <osgFX/Registry>

#include <osg/GL>
#include <osg/PolygonOffset>
#include <osg/Material>
#include <osg/LineWidth>
#include <osg/PolygonMode>

#include <string.h>

using namespace osgFX;

namespace
{

    // register a prototype for this effect
    Registry::Proxy proxy(new Scribe);

    // default technique class
    class DefaultTechnique: public Technique {
    public:
        DefaultTechnique(osg::Material *wf_mat, osg::LineWidth *wf_lw)
            : Technique(), wf_mat_(wf_mat), wf_lw_(wf_lw) {}

            bool validate(osg::State &) const
            {
                return strncmp((const char*)glGetString(GL_VERSION), "1.1", 3) >= 0;
            }

    protected:

        void define_passes()
        {
            // implement pass #1
            {
                osg::ref_ptr<osg::StateSet> ss = new osg::StateSet;

                osg::ref_ptr<osg::PolygonOffset> polyoffset = new osg::PolygonOffset;
                polyoffset->setFactor(1.0f);
                polyoffset->setUnits(1.0f);
                ss->setAttributeAndModes(polyoffset.get(), osg::StateAttribute::OVERRIDE|osg::StateAttribute::ON);

                addPass(ss.get());
            }

            // implement pass #2
            {
                osg::ref_ptr<osg::StateSet> ss = new osg::StateSet;

                osg::ref_ptr<osg::PolygonMode> polymode = new osg::PolygonMode;
                polymode->setMode(osg::PolygonMode::FRONT_AND_BACK, osg::PolygonMode::LINE);
                ss->setAttributeAndModes(polymode.get(), osg::StateAttribute::OVERRIDE|osg::StateAttribute::ON);

                ss->setAttributeAndModes(wf_lw_.get(), osg::StateAttribute::OVERRIDE|osg::StateAttribute::ON);

                ss->setAttributeAndModes(wf_mat_.get(), osg::StateAttribute::OVERRIDE|osg::StateAttribute::ON);

                ss->setMode(GL_LIGHTING, osg::StateAttribute::OVERRIDE|osg::StateAttribute::ON);
                ss->setTextureMode(0, GL_TEXTURE_1D, osg::StateAttribute::OVERRIDE|osg::StateAttribute::OFF);
                ss->setTextureMode(0, GL_TEXTURE_2D, osg::StateAttribute::OVERRIDE|osg::StateAttribute::OFF);

                addPass(ss.get());
            }
        }

    private:
        osg::ref_ptr<osg::Material> wf_mat_;
        osg::ref_ptr<osg::LineWidth> wf_lw_;
    };

}

Scribe::Scribe()
:    Effect(),
    wf_mat_(new osg::Material),
    wf_lw_(new osg::LineWidth)
{
    wf_lw_->setWidth(1.0f);

    wf_mat_->setColorMode(osg::Material::OFF);
    wf_mat_->setDiffuse(osg::Material::FRONT_AND_BACK, osg::Vec4(0.0f, 0.0f, 0.0f, 1.0f));
    wf_mat_->setAmbient(osg::Material::FRONT_AND_BACK, osg::Vec4(0.0f, 0.0f, 0.0f, 1.0f));
    wf_mat_->setSpecular(osg::Material::FRONT_AND_BACK, osg::Vec4(0.0f, 0.0f, 0.0f, 1.0f));
    wf_mat_->setEmission(osg::Material::FRONT_AND_BACK, osg::Vec4(1.0f,1.0f,1.0f,1.0f));
}

Scribe::Scribe(const Scribe &copy, const osg::CopyOp &copyop)
:    Effect(copy, copyop),
    wf_mat_(static_cast<osg::Material *>(copyop(copy.wf_mat_.get()))),
    wf_lw_(static_cast<osg::LineWidth *>(copyop(copy.wf_lw_.get())))
{
}

bool Scribe::define_techniques()
{
    addTechnique(new DefaultTechnique(wf_mat_.get(), wf_lw_.get()));
    return true;
}
<|endoftext|>


<commit_before>/**
 * This file is part of the "FnordMetric" project
 *   Copyright (c) 2014 Paul Asmuth, Google Inc.
 *
 * FnordMetric is free software: you can redistribute it and/or modify it under
 * the terms of the GNU General Public License v3.0. You should have received a
 * copy of the GNU General Public License along with this program. If not, see
 * <http://www.gnu.org/licenses/>.
 */
#include <fnord-base/inspect.h>

namespace fnord {

template <>
std::string inspect<bool>(const bool& value) {
  return value == true ? "true" : "false";
}

template <>
std::string inspect<int>(const int& value) {
  return std::to_string(value);
}

template <>
std::string inspect<unsigned int>(const unsigned int& value) {
  return std::to_string(value);
}

template <>
std::string inspect<unsigned long>(const unsigned long& value) {
  return std::to_string(value);
}

template <>
std::string inspect<unsigned long long>(const unsigned long long& value) {
  return std::to_string(value);
}

template <>
std::string inspect<unsigned char>(const unsigned char& value) {
  return std::to_string(value);
}

template <>
std::string inspect<long long>(
    const long long& value) {
  return std::to_string(value);
}

template <>
std::string inspect<long>(
    const long& value) {
  return std::to_string(value);
}

template <>
std::string inspect<unsigned short>(
    const unsigned short& value) {
  return std::to_string(value);
}

template <>
std::string inspect<float>(const float& value) {
  return std::to_string(value);
}

template <>
std::string inspect<double>(const double& value) {
  return std::to_string(value);
}

template <>
std::string inspect<std::string>(const std::string& value) {
  return value;
}

template <>
std::string inspect<char const*>(char const* const& value) {
  return std::string(value);
}

template <>
std::string inspect<void*>(void* const& value) {
  return "<ptr>";
}

template <>
std::string inspect<const void*>(void const* const& value) {
  return "<ptr>";
}

template <>
std::string inspect<std::exception>(const std::exception& e) {
  return e.what();
}

} // namespace fnord

<commit_msg>simplistic lucene indexing<commit_after>/**
 * This file is part of the "FnordMetric" project
 *   Copyright (c) 2014 Paul Asmuth, Google Inc.
 *
 * FnordMetric is free software: you can redistribute it and/or modify it under
 * the terms of the GNU General Public License v3.0. You should have received a
 * copy of the GNU General Public License along with this program. If not, see
 * <http://www.gnu.org/licenses/>.
 */
#include <fnord-base/inspect.h>

namespace fnord {

template <>
std::string inspect<bool>(const bool& value) {
  return value == true ? "true" : "false";
}

template <>
std::string inspect<int>(const int& value) {
  return std::to_string(value);
}

template <>
std::string inspect<unsigned int>(const unsigned int& value) {
  return std::to_string(value);
}

template <>
std::string inspect<unsigned long>(const unsigned long& value) {
  return std::to_string(value);
}

template <>
std::string inspect<unsigned long long>(const unsigned long long& value) {
  return std::to_string(value);
}

template <>
std::string inspect<unsigned char>(const unsigned char& value) {
  return std::to_string(value);
}

template <>
std::string inspect<long long>(
    const long long& value) {
  return std::to_string(value);
}

template <>
std::string inspect<long>(
    const long& value) {
  return std::to_string(value);
}

template <>
std::string inspect<unsigned short>(
    const unsigned short& value) {
  return std::to_string(value);
}

template <>
std::string inspect<float>(const float& value) {
  return std::to_string(value);
}

template <>
std::string inspect<double>(const double& value) {
  return std::to_string(value);
}

template <>
std::string inspect<std::string>(const std::string& value) {
  return value;
}

template <>
std::string inspect<std::wstring>(const std::wstring& value) {
  std::string out;
  out.assign(value.begin(), value.end());
  return out;
}

template <>
std::string inspect<char const*>(char const* const& value) {
  return std::string(value);
}

template <>
std::string inspect<void*>(void* const& value) {
  return "<ptr>";
}

template <>
std::string inspect<const void*>(void const* const& value) {
  return "<ptr>";
}

template <>
std::string inspect<std::exception>(const std::exception& e) {
  return e.what();
}

} // namespace fnord

<|endoftext|>


<commit_before>/*

Copyright (c) 2015, Project OSRM contributors
All rights reserved.

Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:

Redistributions of source code must retain the above copyright notice, this list
of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright notice, this
list of conditions and the following disclaimer in the documentation and/or
other materials provided with the distribution.

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 HOLDER 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.

*/

#ifndef SHARED_MEMORY_FACTORY_HPP
#define SHARED_MEMORY_FACTORY_HPP

#include "../util/osrm_exception.hpp"
#include "../util/simple_logger.hpp"

#include <boost/filesystem.hpp>
#include <boost/filesystem/fstream.hpp>
#include <boost/interprocess/mapped_region.hpp>
#ifndef WIN32
#include <boost/interprocess/xsi_shared_memory.hpp>
#else
#include <boost/interprocess/shared_memory_object.hpp>
#endif

#ifdef __linux__
#include <sys/ipc.h>
#include <sys/shm.h>
#endif

// #include <cstring>
#include <cstdint>

#include <algorithm>
#include <exception>

struct OSRMLockFile
{
    boost::filesystem::path operator()()
    {
        boost::filesystem::path temp_dir = boost::filesystem::temp_directory_path();
        boost::filesystem::path lock_file = temp_dir / "osrm.lock";
        return lock_file;
    }
};

#ifndef WIN32
class SharedMemory
{

    // Remove shared memory on destruction
    class shm_remove
    {
      private:
        int m_shmid;
        bool m_initialized;

      public:
        void SetID(int shmid)
        {
            m_shmid = shmid;
            m_initialized = true;
        }

        shm_remove() : m_shmid(INT_MIN), m_initialized(false) {}
        shm_remove(const shm_remove &) = delete;
        ~shm_remove()
        {
            if (m_initialized)
            {
                SimpleLogger().Write(logDEBUG) << "automatic memory deallocation";
                if (!boost::interprocess::xsi_shared_memory::remove(m_shmid))
                {
                    SimpleLogger().Write(logDEBUG) << "could not deallocate id " << m_shmid;
                }
            }
        }
    };

  public:
    void *Ptr() const { return region.get_address(); }

    SharedMemory() = delete;
    SharedMemory(const SharedMemory &) = delete;

    template <typename IdentifierT>
    SharedMemory(const boost::filesystem::path &lock_file,
                 const IdentifierT id,
                 const uint64_t size = 0,
                 bool read_write = false,
                 bool remove_prev = true)
        : key(lock_file.string().c_str(), id)
    {
        if (0 == size)
        { // read_only
            shm = boost::interprocess::xsi_shared_memory(boost::interprocess::open_only, key);

            region = boost::interprocess::mapped_region(
                shm,
                (read_write ? boost::interprocess::read_write : boost::interprocess::read_only));
        }
        else
        { // writeable pointer
            // remove previously allocated mem
            if (remove_prev)
            {
                Remove(key);
            }
            shm = boost::interprocess::xsi_shared_memory(boost::interprocess::open_or_create, key,
                                                         size);
#ifdef __linux__
            if (-1 == shmctl(shm.get_shmid(), SHM_LOCK, nullptr))
            {
                if (ENOMEM == errno)
                {
                    SimpleLogger().Write(logWARNING) << "could not lock shared memory to RAM";
                }
            }
#endif
            region = boost::interprocess::mapped_region(shm, boost::interprocess::read_write);

            remover.SetID(shm.get_shmid());
            SimpleLogger().Write(logDEBUG) << "writeable memory allocated " << size << " bytes";
        }
    }

    template <typename IdentifierT> static bool RegionExists(const IdentifierT id)
    {
        bool result = true;
        try
        {
            OSRMLockFile lock_file;
            boost::interprocess::xsi_key key(lock_file().string().c_str(), id);
            result = RegionExists(key);
        }
        catch (...)
        {
            result = false;
        }
        return result;
    }

    template <typename IdentifierT> static bool Remove(const IdentifierT id)
    {
        OSRMLockFile lock_file;
        boost::interprocess::xsi_key key(lock_file().string().c_str(), id);
        return Remove(key);
    }

  private:
    static bool RegionExists(const boost::interprocess::xsi_key &key)
    {
        bool result = true;
        try
        {
            boost::interprocess::xsi_shared_memory shm(boost::interprocess::open_only, key);
        }
        catch (...)
        {
            result = false;
        }
        return result;
    }

    static bool Remove(const boost::interprocess::xsi_key &key)
    {
        bool ret = false;
        try
        {
            SimpleLogger().Write(logDEBUG) << "deallocating prev memory";
            boost::interprocess::xsi_shared_memory xsi(boost::interprocess::open_only, key);
            ret = boost::interprocess::xsi_shared_memory::remove(xsi.get_shmid());
        }
        catch (const boost::interprocess::interprocess_exception &e)
        {
            if (e.get_error_code() != boost::interprocess::not_found_error)
            {
                throw;
            }
        }
        return ret;
    }

    boost::interprocess::xsi_key key;
    boost::interprocess::xsi_shared_memory shm;
    boost::interprocess::mapped_region region;
    shm_remove remover;
};
#else
// Windows - specific code
class SharedMemory
{
    SharedMemory(const SharedMemory &) = delete;
    // Remove shared memory on destruction
    class shm_remove
    {
      private:
        shm_remove(const shm_remove &) = delete;
        char *m_shmid;
        bool m_initialized;

      public:
        void SetID(char *shmid)
        {
            m_shmid = shmid;
            m_initialized = true;
        }

        shm_remove() : m_shmid("undefined"), m_initialized(false) {}

        ~shm_remove()
        {
            if (m_initialized)
            {
                SimpleLogger().Write(logDEBUG) << "automatic memory deallocation";
                if (!boost::interprocess::shared_memory_object::remove(m_shmid))
                {
                    SimpleLogger().Write(logDEBUG) << "could not deallocate id " << m_shmid;
                }
            }
        }
    };

  public:
    void *Ptr() const { return region.get_address(); }

    SharedMemory(const boost::filesystem::path &lock_file,
                 const int id,
                 const uint64_t size = 0,
                 bool read_write = false,
                 bool remove_prev = true)
    {
        sprintf(key, "%s.%d", "osrm.lock", id);
        if (0 == size)
        { // read_only
            shm = boost::interprocess::shared_memory_object(
                boost::interprocess::open_only, key,
                read_write ? boost::interprocess::read_write : boost::interprocess::read_only);
            region = boost::interprocess::mapped_region(
                shm, read_write ? boost::interprocess::read_write : boost::interprocess::read_only);
        }
        else
        { // writeable pointer
            // remove previously allocated mem
            if (remove_prev)
            {
                Remove(key);
            }
            shm = boost::interprocess::shared_memory_object(boost::interprocess::open_or_create,
                                                            key, boost::interprocess::read_write);
            shm.truncate(size);
            region = boost::interprocess::mapped_region(shm, boost::interprocess::read_write);

            remover.SetID(key);
            SimpleLogger().Write(logDEBUG) << "writeable memory allocated " << size << " bytes";
        }
    }

    static bool RegionExists(const int id)
    {
        bool result = true;
        try
        {
            char k[500];
            build_key(id, k);
            result = RegionExists(k);
        }
        catch (...)
        {
            result = false;
        }
        return result;
    }

    static bool Remove(const int id)
    {
        char k[500];
        build_key(id, k);
        return Remove(k);
    }

  private:
    static void build_key(int id, char *key) { sprintf(key, "%s.%d", "osrm.lock", id); }

    static bool RegionExists(const char *key)
    {
        bool result = true;
        try
        {
            boost::interprocess::shared_memory_object shm(boost::interprocess::open_only, key,
                                                          boost::interprocess::read_write);
        }
        catch (...)
        {
            result = false;
        }
        return result;
    }

    static bool Remove(char *key)
    {
        bool ret = false;
        try
        {
            SimpleLogger().Write(logDEBUG) << "deallocating prev memory";
            ret = boost::interprocess::shared_memory_object::remove(key);
        }
        catch (const boost::interprocess::interprocess_exception &e)
        {
            if (e.get_error_code() != boost::interprocess::not_found_error)
            {
                throw;
            }
        }
        return ret;
    }

    char key[500];
    boost::interprocess::shared_memory_object shm;
    boost::interprocess::mapped_region region;
    shm_remove remover;
};
#endif

template <class LockFileT = OSRMLockFile> class SharedMemoryFactory_tmpl
{
  public:
    template <typename IdentifierT>
    static SharedMemory *Get(const IdentifierT &id,
                             const uint64_t size = 0,
                             bool read_write = false,
                             bool remove_prev = true)
    {
        try
        {
            LockFileT lock_file;
            if (!boost::filesystem::exists(lock_file()))
            {
                if (0 == size)
                {
                    throw osrm::exception("lock file does not exist, exiting");
                }
                else
                {
                    boost::filesystem::ofstream ofs(lock_file());
                    ofs.close();
                }
            }
            return new SharedMemory(lock_file(), id, size, read_write, remove_prev);
        }
        catch (const boost::interprocess::interprocess_exception &e)
        {
            SimpleLogger().Write(logWARNING) << "caught exception: " << e.what() << ", code "
                                             << e.get_error_code();
            throw osrm::exception(e.what());
        }
    }

    SharedMemoryFactory_tmpl() = delete;
    SharedMemoryFactory_tmpl(const SharedMemoryFactory_tmpl &) = delete;
};

using SharedMemoryFactory = SharedMemoryFactory_tmpl<>;

#endif // SHARED_MEMORY_FACTORY_HPP
<commit_msg>Fix shared memory non-copyable properties<commit_after>/*

Copyright (c) 2015, Project OSRM contributors
All rights reserved.

Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:

Redistributions of source code must retain the above copyright notice, this list
of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright notice, this
list of conditions and the following disclaimer in the documentation and/or
other materials provided with the distribution.

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 HOLDER 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.

*/

#ifndef SHARED_MEMORY_FACTORY_HPP
#define SHARED_MEMORY_FACTORY_HPP

#include "../util/osrm_exception.hpp"
#include "../util/simple_logger.hpp"

#include <boost/filesystem.hpp>
#include <boost/filesystem/fstream.hpp>
#include <boost/interprocess/mapped_region.hpp>
#ifndef WIN32
#include <boost/interprocess/xsi_shared_memory.hpp>
#else
#include <boost/interprocess/shared_memory_object.hpp>
#endif

#ifdef __linux__
#include <sys/ipc.h>
#include <sys/shm.h>
#endif

// #include <cstring>
#include <cstdint>

#include <algorithm>
#include <exception>

struct OSRMLockFile
{
    boost::filesystem::path operator()()
    {
        boost::filesystem::path temp_dir = boost::filesystem::temp_directory_path();
        boost::filesystem::path lock_file = temp_dir / "osrm.lock";
        return lock_file;
    }
};

#ifndef WIN32
class SharedMemory
{

    // Remove shared memory on destruction
    class shm_remove
    {
      private:
        int m_shmid;
        bool m_initialized;

      public:
        void SetID(int shmid)
        {
            m_shmid = shmid;
            m_initialized = true;
        }

        shm_remove() : m_shmid(INT_MIN), m_initialized(false) {}
        shm_remove(const shm_remove &) = delete;
        ~shm_remove()
        {
            if (m_initialized)
            {
                SimpleLogger().Write(logDEBUG) << "automatic memory deallocation";
                if (!boost::interprocess::xsi_shared_memory::remove(m_shmid))
                {
                    SimpleLogger().Write(logDEBUG) << "could not deallocate id " << m_shmid;
                }
            }
        }
    };

  public:
    void *Ptr() const { return region.get_address(); }

    SharedMemory() = delete;
    SharedMemory(const SharedMemory &) = delete;
    SharedMemory &operator=(const SharedMemory &) = delete;

    template <typename IdentifierT>
    SharedMemory(const boost::filesystem::path &lock_file,
                 const IdentifierT id,
                 const uint64_t size = 0,
                 bool read_write = false,
                 bool remove_prev = true)
        : key(lock_file.string().c_str(), id)
    {
        if (0 == size)
        { // read_only
            shm = boost::interprocess::xsi_shared_memory(boost::interprocess::open_only, key);

            region = boost::interprocess::mapped_region(
                shm,
                (read_write ? boost::interprocess::read_write : boost::interprocess::read_only));
        }
        else
        { // writeable pointer
            // remove previously allocated mem
            if (remove_prev)
            {
                Remove(key);
            }
            shm = boost::interprocess::xsi_shared_memory(boost::interprocess::open_or_create, key,
                                                         size);
#ifdef __linux__
            if (-1 == shmctl(shm.get_shmid(), SHM_LOCK, nullptr))
            {
                if (ENOMEM == errno)
                {
                    SimpleLogger().Write(logWARNING) << "could not lock shared memory to RAM";
                }
            }
#endif
            region = boost::interprocess::mapped_region(shm, boost::interprocess::read_write);

            remover.SetID(shm.get_shmid());
            SimpleLogger().Write(logDEBUG) << "writeable memory allocated " << size << " bytes";
        }
    }

    template <typename IdentifierT> static bool RegionExists(const IdentifierT id)
    {
        bool result = true;
        try
        {
            OSRMLockFile lock_file;
            boost::interprocess::xsi_key key(lock_file().string().c_str(), id);
            result = RegionExists(key);
        }
        catch (...)
        {
            result = false;
        }
        return result;
    }

    template <typename IdentifierT> static bool Remove(const IdentifierT id)
    {
        OSRMLockFile lock_file;
        boost::interprocess::xsi_key key(lock_file().string().c_str(), id);
        return Remove(key);
    }

  private:
    static bool RegionExists(const boost::interprocess::xsi_key &key)
    {
        bool result = true;
        try
        {
            boost::interprocess::xsi_shared_memory shm(boost::interprocess::open_only, key);
        }
        catch (...)
        {
            result = false;
        }
        return result;
    }

    static bool Remove(const boost::interprocess::xsi_key &key)
    {
        bool ret = false;
        try
        {
            SimpleLogger().Write(logDEBUG) << "deallocating prev memory";
            boost::interprocess::xsi_shared_memory xsi(boost::interprocess::open_only, key);
            ret = boost::interprocess::xsi_shared_memory::remove(xsi.get_shmid());
        }
        catch (const boost::interprocess::interprocess_exception &e)
        {
            if (e.get_error_code() != boost::interprocess::not_found_error)
            {
                throw;
            }
        }
        return ret;
    }

    boost::interprocess::xsi_key key;
    boost::interprocess::xsi_shared_memory shm;
    boost::interprocess::mapped_region region;
    shm_remove remover;
};
#else
// Windows - specific code
class SharedMemory
{
    SharedMemory(const SharedMemory &) = delete;
    SharedMemory &operator=(const SharedMemory &) = delete;
    // Remove shared memory on destruction
    class shm_remove
    {
      private:
        shm_remove(const shm_remove &) = delete;
        shm_remove &operator=(const shm_remove &) = delete;
        char *m_shmid;
        bool m_initialized;

      public:
        void SetID(char *shmid)
        {
            m_shmid = shmid;
            m_initialized = true;
        }

        shm_remove() : m_shmid("undefined"), m_initialized(false) {}

        ~shm_remove()
        {
            if (m_initialized)
            {
                SimpleLogger().Write(logDEBUG) << "automatic memory deallocation";
                if (!boost::interprocess::shared_memory_object::remove(m_shmid))
                {
                    SimpleLogger().Write(logDEBUG) << "could not deallocate id " << m_shmid;
                }
            }
        }
    };

  public:
    void *Ptr() const { return region.get_address(); }

    SharedMemory(const boost::filesystem::path &lock_file,
                 const int id,
                 const uint64_t size = 0,
                 bool read_write = false,
                 bool remove_prev = true)
    {
        sprintf(key, "%s.%d", "osrm.lock", id);
        if (0 == size)
        { // read_only
            shm = boost::interprocess::shared_memory_object(
                boost::interprocess::open_only, key,
                read_write ? boost::interprocess::read_write : boost::interprocess::read_only);
            region = boost::interprocess::mapped_region(
                shm, read_write ? boost::interprocess::read_write : boost::interprocess::read_only);
        }
        else
        { // writeable pointer
            // remove previously allocated mem
            if (remove_prev)
            {
                Remove(key);
            }
            shm = boost::interprocess::shared_memory_object(boost::interprocess::open_or_create,
                                                            key, boost::interprocess::read_write);
            shm.truncate(size);
            region = boost::interprocess::mapped_region(shm, boost::interprocess::read_write);

            remover.SetID(key);
            SimpleLogger().Write(logDEBUG) << "writeable memory allocated " << size << " bytes";
        }
    }

    static bool RegionExists(const int id)
    {
        bool result = true;
        try
        {
            char k[500];
            build_key(id, k);
            result = RegionExists(k);
        }
        catch (...)
        {
            result = false;
        }
        return result;
    }

    static bool Remove(const int id)
    {
        char k[500];
        build_key(id, k);
        return Remove(k);
    }

  private:
    static void build_key(int id, char *key) { sprintf(key, "%s.%d", "osrm.lock", id); }

    static bool RegionExists(const char *key)
    {
        bool result = true;
        try
        {
            boost::interprocess::shared_memory_object shm(boost::interprocess::open_only, key,
                                                          boost::interprocess::read_write);
        }
        catch (...)
        {
            result = false;
        }
        return result;
    }

    static bool Remove(char *key)
    {
        bool ret = false;
        try
        {
            SimpleLogger().Write(logDEBUG) << "deallocating prev memory";
            ret = boost::interprocess::shared_memory_object::remove(key);
        }
        catch (const boost::interprocess::interprocess_exception &e)
        {
            if (e.get_error_code() != boost::interprocess::not_found_error)
            {
                throw;
            }
        }
        return ret;
    }

    char key[500];
    boost::interprocess::shared_memory_object shm;
    boost::interprocess::mapped_region region;
    shm_remove remover;
};
#endif

template <class LockFileT = OSRMLockFile> class SharedMemoryFactory_tmpl
{
  public:
    template <typename IdentifierT>
    static SharedMemory *Get(const IdentifierT &id,
                             const uint64_t size = 0,
                             bool read_write = false,
                             bool remove_prev = true)
    {
        try
        {
            LockFileT lock_file;
            if (!boost::filesystem::exists(lock_file()))
            {
                if (0 == size)
                {
                    throw osrm::exception("lock file does not exist, exiting");
                }
                else
                {
                    boost::filesystem::ofstream ofs(lock_file());
                    ofs.close();
                }
            }
            return new SharedMemory(lock_file(), id, size, read_write, remove_prev);
        }
        catch (const boost::interprocess::interprocess_exception &e)
        {
            SimpleLogger().Write(logWARNING) << "caught exception: " << e.what() << ", code "
                                             << e.get_error_code();
            throw osrm::exception(e.what());
        }
    }

    SharedMemoryFactory_tmpl() = delete;
    SharedMemoryFactory_tmpl(const SharedMemoryFactory_tmpl &) = delete;
    SharedMemoryFactory_tmpl &operator=(const SharedMemoryFactory_tmpl &) = delete;
};

using SharedMemoryFactory = SharedMemoryFactory_tmpl<>;

#endif // SHARED_MEMORY_FACTORY_HPP
<|endoftext|>


<commit_before>// Copyright (c) 2011-2014 The Bitcoin developers
// Copyright (c) 2013-2015 The Anoncoin Core developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

// Many builder specific things set in the config file, ENABLE_WALLET is a good example.  Don't forget to include it this way in your source files.
#if defined(HAVE_CONFIG_H)
#include "config/anoncoin-config.h"
#endif

#include "splashscreen.h"

#include "clientversion.h"
#include "init.h"
#include "ui_interface.h"
#include "util.h"
#ifdef ENABLE_WALLET
#include "wallet.h"
#endif

#include <QApplication>
#include <QPainter>

SplashScreen::SplashScreen(const QPixmap &pixmap, Qt::WindowFlags f, bool isTestNet) :
    QSplashScreen(pixmap, f)
{
    setAutoFillBackground(true);

    // set reference point, paddings
    int paddingTop              = 236;
    int paddingCopyrightTop     = 18;

    float fontFactor            = 1.0;

    // define text to place
    QString versionText     = QString("VERSION %1").arg(QString::fromStdString(FormatFullVersion()));
    QString copyrightText1   = QChar(0xA9)+QString(" 2013-%1 ").arg(COPYRIGHT_YEAR) + QString(tr("ANONCOIN CORE DEVELOPERS"));
    //QString testnetAddText  = QString(tr("[testnet]")); // This string is already included in the background image

    QString font            = "Courier New";

    // load the bitmap for writing some text over it
    QPixmap newPixmap;
    if(isTestNet) {
        newPixmap     = QPixmap(":/images/splash_testnet");
    }
    else {
        newPixmap     = QPixmap(":/images/splash");
    }

    QPainter pixPaint(&newPixmap);
    pixPaint.setPen(QColor(250,250,250));
    pixPaint.setFont(QFont(font, 12*fontFactor));

    QFontMetrics fm = pixPaint.fontMetrics();

    // draw version
    pixPaint.drawText(newPixmap.width()/2-fm.width(versionText)/2,paddingTop,versionText);

    // draw copyright stuff
    pixPaint.setFont(QFont(font, 12*fontFactor));
    pixPaint.drawText(newPixmap.width()/2-fm.width(copyrightText1)/2,paddingTop+paddingCopyrightTop,copyrightText1);

    // draw testnet string if testnet is on. This is no longer necessary as this is included in the background image
    //if(isTestNet) {
    //    QFont boldFont = QFont(font, 10*fontFactor);
    //    boldFont.setWeight(QFont::Bold);
    //    pixPaint.setFont(boldFont);
    //    fm = pixPaint.fontMetrics();
    //    int testnetAddTextWidth  = fm.width(testnetAddText);
    //    pixPaint.drawText(newPixmap.width()-testnetAddTextWidth-10,15,testnetAddText);
    //}

    pixPaint.end();

    this->setPixmap(newPixmap);

    subscribeToCoreSignals();
}

SplashScreen::~SplashScreen()
{
    unsubscribeFromCoreSignals();
}

void SplashScreen::slotFinish(QWidget *mainWin)
{
    finish(mainWin);
}

static void InitMessage(SplashScreen *splash, const std::string &message)
{
	QFont initfont;
	initfont.setFamily("Courier New");
	initfont.setPixelSize(12);
	initfont.setCapitalization(initfont.AllUppercase);
	splash->setFont(initfont);

	std::string message_cr;
	message_cr = message + "\n";

    QMetaObject::invokeMethod(splash, "showMessage",
        Qt::QueuedConnection,
        Q_ARG(QString, QString::fromStdString(message_cr)),
        Q_ARG(int, Qt::AlignBottom|Qt::AlignHCenter),
        //Q_ARG(int, Qt::AlignHCenter),
        Q_ARG(QColor, QColor(0,0,0)));
}

static void ShowProgress(SplashScreen *splash, const std::string &title, int nProgress)
{
    InitMessage(splash, title + strprintf("%d", nProgress) + "%");
}

#ifdef ENABLE_WALLET
static void ConnectWallet(SplashScreen *splash, CWallet* wallet)
{
    wallet->ShowProgress.connect(boost::bind(ShowProgress, splash, _1, _2));
}
#endif

void SplashScreen::subscribeToCoreSignals()
{
    // Connect signals to client
    uiInterface.InitMessage.connect(boost::bind(InitMessage, this, _1));
#ifdef ENABLE_WALLET
    uiInterface.LoadWallet.connect(boost::bind(ConnectWallet, this, _1));
#endif
}

void SplashScreen::unsubscribeFromCoreSignals()
{
    // Disconnect signals from client
    uiInterface.InitMessage.disconnect(boost::bind(InitMessage, this, _1));
#ifdef ENABLE_WALLET
    if(pwalletMain)
        pwalletMain->ShowProgress.disconnect(boost::bind(ShowProgress, this, _1, _2));
#endif
}
<commit_msg>remove comments from code<commit_after>// Copyright (c) 2011-2014 The Bitcoin developers
// Copyright (c) 2013-2015 The Anoncoin Core developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

// Many builder specific things set in the config file, ENABLE_WALLET is a good example.  Don't forget to include it this way in your source files.
#if defined(HAVE_CONFIG_H)
#include "config/anoncoin-config.h"
#endif

#include "splashscreen.h"

#include "clientversion.h"
#include "init.h"
#include "ui_interface.h"
#include "util.h"
#ifdef ENABLE_WALLET
#include "wallet.h"
#endif

#include <QApplication>
#include <QPainter>

SplashScreen::SplashScreen(const QPixmap &pixmap, Qt::WindowFlags f, bool isTestNet) :
    QSplashScreen(pixmap, f)
{
    setAutoFillBackground(true);

    // set reference point, paddings
    int paddingTop              = 236;
    int paddingCopyrightTop     = 18;

    float fontFactor            = 1.0;

    // define text to place
    QString versionText     = QString("VERSION %1").arg(QString::fromStdString(FormatFullVersion()));
    QString copyrightText1   = QChar(0xA9)+QString(" 2013-%1 ").arg(COPYRIGHT_YEAR) + QString(tr("ANONCOIN CORE DEVELOPERS"));
    //QString testnetAddText  = QString(tr("[testnet]")); // This string is already included in the background image

    QString font            = "Courier New";

    // load the bitmap for writing some text over it
    QPixmap newPixmap;
    if(isTestNet) {
        newPixmap     = QPixmap(":/images/splash_testnet");
    }
    else {
        newPixmap     = QPixmap(":/images/splash");
    }

    QPainter pixPaint(&newPixmap);
    pixPaint.setPen(QColor(250,250,250));
    pixPaint.setFont(QFont(font, 12*fontFactor));

    QFontMetrics fm = pixPaint.fontMetrics();

    // draw version
    pixPaint.drawText(newPixmap.width()/2-fm.width(versionText)/2,paddingTop,versionText);

    // draw copyright stuff
    pixPaint.setFont(QFont(font, 12*fontFactor));
    pixPaint.drawText(newPixmap.width()/2-fm.width(copyrightText1)/2,paddingTop+paddingCopyrightTop,copyrightText1);

    // draw testnet string if testnet is on. This is no longer necessary as this is included in the background image
    //if(isTestNet) {
    //    QFont boldFont = QFont(font, 10*fontFactor);
    //    boldFont.setWeight(QFont::Bold);
    //    pixPaint.setFont(boldFont);
    //    fm = pixPaint.fontMetrics();
    //    int testnetAddTextWidth  = fm.width(testnetAddText);
    //    pixPaint.drawText(newPixmap.width()-testnetAddTextWidth-10,15,testnetAddText);
    //}

    pixPaint.end();

    this->setPixmap(newPixmap);

    subscribeToCoreSignals();
}

SplashScreen::~SplashScreen()
{
    unsubscribeFromCoreSignals();
}

void SplashScreen::slotFinish(QWidget *mainWin)
{
    finish(mainWin);
}

static void InitMessage(SplashScreen *splash, const std::string &message)
{
	QFont initfont;
	initfont.setFamily("Courier New");
	initfont.setPixelSize(12);
	initfont.setCapitalization(initfont.AllUppercase);
	splash->setFont(initfont);

	std::string message_cr;
	message_cr = message + "\n";

    QMetaObject::invokeMethod(splash, "showMessage",
        Qt::QueuedConnection,
        Q_ARG(QString, QString::fromStdString(message_cr)),
        Q_ARG(int, Qt::AlignBottom|Qt::AlignHCenter),
        Q_ARG(QColor, QColor(0,0,0)));
}

static void ShowProgress(SplashScreen *splash, const std::string &title, int nProgress)
{
    InitMessage(splash, title + strprintf("%d", nProgress) + "%");
}

#ifdef ENABLE_WALLET
static void ConnectWallet(SplashScreen *splash, CWallet* wallet)
{
    wallet->ShowProgress.connect(boost::bind(ShowProgress, splash, _1, _2));
}
#endif

void SplashScreen::subscribeToCoreSignals()
{
    // Connect signals to client
    uiInterface.InitMessage.connect(boost::bind(InitMessage, this, _1));
#ifdef ENABLE_WALLET
    uiInterface.LoadWallet.connect(boost::bind(ConnectWallet, this, _1));
#endif
}

void SplashScreen::unsubscribeFromCoreSignals()
{
    // Disconnect signals from client
    uiInterface.InitMessage.disconnect(boost::bind(InitMessage, this, _1));
#ifdef ENABLE_WALLET
    if(pwalletMain)
        pwalletMain->ShowProgress.disconnect(boost::bind(ShowProgress, this, _1, _2));
#endif
}
<|endoftext|>


<commit_before>#include <Windows.h>
#include <stdio.h>
#include <sstream>
#include <memory>
#include <filesystem>

namespace fs = std::tr2::sys;

#pragma comment(lib, "Version.lib")

struct LANGANDCODEPAGE {
	WORD wLanguage;
	WORD wCodePage;
};

class SubBlock
{
	LPVOID block;
	std::string prefix;
	static std::string make_prefix(const LANGANDCODEPAGE& translation)
	{
		char prefix[100];
		sprintf_s(prefix, "\\StringFileInfo\\%04x%04x\\", translation.wLanguage, translation.wCodePage);
		return prefix;
	}
public:
	SubBlock() : block(nullptr) {}

	SubBlock(LPVOID block, const LANGANDCODEPAGE& translation)
		: block(block)
		, prefix(make_prefix(translation))
	{

	}

	explicit operator bool() const { return !!block; }

	std::string query(const char* name)
	{
		if (!block)
			return{};

		LPVOID buffer;
		UINT size = 0;
		if (VerQueryValueA(block, (prefix + name).c_str(), &buffer, &size))
			return (char*)buffer;

		return{};
	}
};

class VersionInfo
{
	std::unique_ptr<char[]> block;
	LANGANDCODEPAGE *translations;
	UINT translation_count;
public:
	explicit VersionInfo(const std::string& path)
		: translations(nullptr)
		, translation_count(0)
	{
		auto size = GetFileVersionInfoSizeA(path.c_str(), nullptr);
		if (!size)
		{
			auto err = GetLastError();
			if (err == ERROR_RESOURCE_TYPE_NOT_FOUND ||
				err == ERROR_RESOURCE_NAME_NOT_FOUND ||
				err == ERROR_RESOURCE_LANG_NOT_FOUND)
			{
				printf("No VERSIONINFO (%s).\n", path.c_str());
			}
			return;
		}

		block.reset( new (std::nothrow) char[size] );
		if (!block)
		{
			printf("OOM while getting VERSIONINFO.\n");
			return;
		}

		if (!GetFileVersionInfoA(path.c_str(), 0, size, block.get()))
		{
			printf("GetFileVersionInfo error (%d).\n", GetLastError());
			block.reset();
			return;
		}

		if (!VerQueryValueA(block.get(), "\\VarFileInfo\\Translation", (LPVOID*)&translations, &translation_count) ||
			translation_count < sizeof(LANGANDCODEPAGE))
		{
			printf("No \\VarFileInfo\\Translation in VERSIONINFO.\n");
			block.reset();
			return;
		}

		translation_count /= sizeof(LANGANDCODEPAGE);
	}

	explicit operator bool() const { return !!block; }

	SubBlock operator[](UINT i)
	{
		if (i >= translation_count)
			return{};

		return{ block.get(), translations[i] };
	}
};

std::string PluginInfo(const std::string& path)
{
	VersionInfo info{ path };
	if (!info)
		return std::string();

	auto block = info[0];
	if (!block)
		return std::string();

	auto ProductName = block.query("ProductName");
	auto FileDescription = block.query("FileDescription");
	auto FileVersion = block.query("FileVersion");
	auto MIMEType = block.query("MIMEType");

	if (MIMEType.empty())
		return std::string();

	// plugin-entry =
	//    <file-path> +
	//    ["#" + <name> + ["#" + <description> + ["#" + <version>]]] +
	//    *1( LWS + ";" + LWS + <mime-type> )

	printf("Adding %s (%s)\n", ProductName.c_str(), MIMEType.c_str());
	return path + "#" + ProductName + "#" + FileDescription + "#" + FileVersion + ";" + MIMEType;
}

std::string PluginInfos(const std::string& dir)
{
	std::string out;
	bool first = true;

	fs::directory_iterator cur{ dir }, end{};
	for (; cur != end; ++cur)
	{
		auto&& entry = *cur;
		auto info = PluginInfo(entry.path().file_string());
		if (info.empty())
			continue;

		if (first) first = false;
		else out.push_back(',');
		out += info;
	}

	return out;
}

bool needs_escaping(const std::string& arg)
{
	for (auto&& c : arg)
	{
		if (c == ' ' || c == '"')
			return true;
	}

	return false;
}

std::string do_escape(const std::string& arg)
{
	std::string out;
	out.reserve(arg.length() + 2); // +10%
	out.push_back('"');
	out.append(arg);
	out.push_back('"');

	return out;
}

std::string escape(const std::string& arg)
{
	if (needs_escaping(arg))
		return do_escape(arg);
	return arg;
}

int main(int argc, char* argv[])
{
	if (argc < 2)
	{
		fprintf(stderr, "pp-launcher <chrome.exe> [<chrome switches>]\n");
		return 1;
	}

	char buffer[2048];
	GetModuleFileNameA(nullptr, buffer, sizeof(buffer));
	auto slash = strrchr(buffer, '\\');
	if (slash)
		slash[1] = 0;

	auto plugins = PluginInfos(buffer);
	if (plugins.empty())
	{
		printf("No modules with VERISONINFO and MIMEType found.\n");
		return 1;
	}

	std::ostringstream o;
	for (int i = 1; i < argc; ++i)
		o << escape(argv[i]) << ' ';
	o << escape("--register-pepper-plugins=" + plugins);
	auto cmd = o.str();

	PROCESS_INFORMATION proc = {};
	STARTUPINFOA startup = { sizeof(STARTUPINFO) };

	if (!CreateProcessA(argv[1], (char*)cmd.c_str(), nullptr, nullptr, TRUE, 0, nullptr, nullptr, &startup, &proc))
	{
		printf("CreateProcess failed (%d).\n", GetLastError());
		return 1;
	}

	printf("Waiting...\n");
	WaitForSingleObject(proc.hProcess, INFINITE);
	CloseHandle(proc.hProcess);
	CloseHandle(proc.hThread);

	return 0;
}
<commit_msg>Extracting before CWD<commit_after>#include <Windows.h>
#include <stdio.h>
#include <sstream>
#include <memory>
#include <filesystem>

namespace fs = std::tr2::sys;

#pragma comment(lib, "Version.lib")

struct LANGANDCODEPAGE {
	WORD wLanguage;
	WORD wCodePage;
};

class SubBlock
{
	LPVOID block;
	std::string prefix;
	static std::string make_prefix(const LANGANDCODEPAGE& translation)
	{
		char prefix[100];
		sprintf_s(prefix, "\\StringFileInfo\\%04x%04x\\", translation.wLanguage, translation.wCodePage);
		return prefix;
	}
public:
	SubBlock() : block(nullptr) {}

	SubBlock(LPVOID block, const LANGANDCODEPAGE& translation)
		: block(block)
		, prefix(make_prefix(translation))
	{

	}

	explicit operator bool() const { return !!block; }

	std::string query(const char* name)
	{
		if (!block)
			return{};

		LPVOID buffer;
		UINT size = 0;
		if (VerQueryValueA(block, (prefix + name).c_str(), &buffer, &size))
			return (char*)buffer;

		return{};
	}
};

class VersionInfo
{
	std::unique_ptr<char[]> block;
	LANGANDCODEPAGE *translations;
	UINT translation_count;
public:
	explicit VersionInfo(const std::string& path)
		: translations(nullptr)
		, translation_count(0)
	{
		auto size = GetFileVersionInfoSizeA(path.c_str(), nullptr);
		if (!size)
		{
			auto err = GetLastError();
			if (err == ERROR_RESOURCE_TYPE_NOT_FOUND ||
				err == ERROR_RESOURCE_NAME_NOT_FOUND ||
				err == ERROR_RESOURCE_LANG_NOT_FOUND)
			{
				printf("No VERSIONINFO (%s).\n", path.c_str());
			}
			return;
		}

		block.reset( new (std::nothrow) char[size] );
		if (!block)
		{
			printf("OOM while getting VERSIONINFO.\n");
			return;
		}

		if (!GetFileVersionInfoA(path.c_str(), 0, size, block.get()))
		{
			printf("GetFileVersionInfo error (%d).\n", GetLastError());
			block.reset();
			return;
		}

		if (!VerQueryValueA(block.get(), "\\VarFileInfo\\Translation", (LPVOID*)&translations, &translation_count) ||
			translation_count < sizeof(LANGANDCODEPAGE))
		{
			printf("No \\VarFileInfo\\Translation in VERSIONINFO.\n");
			block.reset();
			return;
		}

		translation_count /= sizeof(LANGANDCODEPAGE);
	}

	explicit operator bool() const { return !!block; }

	SubBlock operator[](UINT i)
	{
		if (i >= translation_count)
			return{};

		return{ block.get(), translations[i] };
	}
};

std::string PluginInfo(const std::string& path)
{
	VersionInfo info{ path };
	if (!info)
		return std::string();

	auto block = info[0];
	if (!block)
		return std::string();

	auto ProductName = block.query("ProductName");
	auto FileDescription = block.query("FileDescription");
	auto FileVersion = block.query("FileVersion");
	auto MIMEType = block.query("MIMEType");

	if (MIMEType.empty())
		return std::string();

	// plugin-entry =
	//    <file-path> +
	//    ["#" + <name> + ["#" + <description> + ["#" + <version>]]] +
	//    *1( LWS + ";" + LWS + <mime-type> )

	printf("Adding %s (%s)\n", ProductName.c_str(), MIMEType.c_str());
	return path + "#" + ProductName + "#" + FileDescription + "#" + FileVersion + ";" + MIMEType;
}

std::string PluginInfos(const std::string& dir)
{
	std::string out;
	bool first = true;

	fs::directory_iterator cur{ dir }, end{};
	for (; cur != end; ++cur)
	{
		auto&& entry = *cur;
		auto info = PluginInfo(entry.path().file_string());
		if (info.empty())
			continue;

		if (first) first = false;
		else out.push_back(',');
		out += info;
	}

	return out;
}

bool needs_escaping(const std::string& arg)
{
	for (auto&& c : arg)
	{
		if (c == ' ' || c == '"')
			return true;
	}

	return false;
}

std::string do_escape(const std::string& arg)
{
	std::string out;
	out.reserve(arg.length() + 2); // +10%
	out.push_back('"');
	out.append(arg);
	out.push_back('"');

	return out;
}

std::string escape(const std::string& arg)
{
	if (needs_escaping(arg))
		return do_escape(arg);
	return arg;
}

std::string module_dir()
{
	char buffer[2048];
	GetModuleFileNameA(nullptr, buffer, sizeof(buffer));
	auto slash = strrchr(buffer, '\\');
	if (slash)
		slash[1] = 0;

	return buffer;
}

int main(int argc, char* argv[])
{
	if (argc < 2)
	{
		fprintf(stderr, "pp-launcher <chrome.exe> [<chrome switches>]\n");
		return 1;
	}

	auto plugins = PluginInfos(module_dir());
	if (plugins.empty())
	{
		printf("No modules with VERISONINFO and MIMEType found.\n");
		return 1;
	}

	std::ostringstream o;
	for (int i = 1; i < argc; ++i)
		o << escape(argv[i]) << ' ';
	o << escape("--register-pepper-plugins=" + plugins);
	auto cmd = o.str();

	PROCESS_INFORMATION proc = {};
	STARTUPINFOA startup = { sizeof(STARTUPINFO) };

	if (!CreateProcessA(argv[1], (char*)cmd.c_str(), nullptr, nullptr, TRUE, 0, nullptr, nullptr, &startup, &proc))
	{
		printf("CreateProcess failed (%d).\n", GetLastError());
		return 1;
	}

	printf("Waiting...\n");
	WaitForSingleObject(proc.hProcess, INFINITE);
	CloseHandle(proc.hProcess);
	CloseHandle(proc.hThread);

	return 0;
}
<|endoftext|>


<commit_before>/*M///////////////////////////////////////////////////////////////////////////////////////
//
//  IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
//  By downloading, copying, installing or using the software you agree to this license.
//  If you do not agree to this license, do not download, install,
//  copy or use the software.
//
//
//                           License Agreement
//                For Open Source Computer Vision Library
//
// Copyright (C) 2010-2012, Multicoreware, Inc., all rights reserved.
// Copyright (C) 2010-2012, Advanced Micro Devices, Inc., all rights reserved.
// Third party copyrights are property of their respective owners.
//
// @Authors
//    Fangfang Bai, fangfang@multicorewareinc.com
//    Jin Ma,       jin@multicorewareinc.com
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
//   * Redistribution's of source code must retain the above copyright notice,
//     this list of conditions and the following disclaimer.
//
//   * Redistribution's in binary form must reproduce the above copyright notice,
//     this list of conditions and the following disclaimer in the documentation
//     and/or other materials provided with the distribution.
//
//   * The name of the copyright holders may not 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 Intel Corporation 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.
//
//M*/
#include "perf_precomp.hpp"

using namespace perf;

///////////// Haar ////////////////////////
PERF_TEST(HaarFixture, Haar)
{
    vector<Rect> faces;

    Mat img = imread(getDataPath("gpu/haarcascade/basketball1.png"), CV_LOAD_IMAGE_GRAYSCALE);
    ASSERT_TRUE(!img.empty()) << "can't open basketball1.png";
    declare.in(img);

    if (RUN_PLAIN_IMPL)
    {
        CascadeClassifier faceCascade;
        ASSERT_TRUE(faceCascade.load(getDataPath("gpu/haarcascade/haarcascade_frontalface_alt.xml")))
                << "can't load haarcascade_frontalface_alt.xml";

        TEST_CYCLE() faceCascade.detectMultiScale(img, faces,
                                                     1.1, 2, 0 | CV_HAAR_SCALE_IMAGE, Size(30, 30));

        SANITY_CHECK(faces, 4 + 1e-4);
    }
    else if (RUN_OCL_IMPL)
    {
        ocl::OclCascadeClassifier faceCascade;
        ocl::oclMat oclImg(img);

        ASSERT_TRUE(faceCascade.load(getDataPath("gpu/haarcascade/haarcascade_frontalface_alt.xml")))
                << "can't load haarcascade_frontalface_alt.xml";

        OCL_TEST_CYCLE() faceCascade.detectMultiScale(oclImg, faces,
                                     1.1, 2, 0 | CV_HAAR_SCALE_IMAGE, Size(30, 30));

        SANITY_CHECK(faces, 4 + 1e-4);
    }
    else
        OCL_PERF_ELSE
}

using namespace std;
using namespace cv;
using namespace perf;
using std::tr1::make_tuple;
using std::tr1::get;

typedef std::tr1::tuple<std::string, std::string, int> OCL_Cascade_Image_MinSize_t;
typedef perf::TestBaseWithParam<OCL_Cascade_Image_MinSize_t> OCL_Cascade_Image_MinSize;

PERF_TEST_P( OCL_Cascade_Image_MinSize, CascadeClassifier,
             testing::Combine(
                testing::Values( string("cv/cascadeandhog/cascades/haarcascade_frontalface_alt.xml") ),
                testing::Values( string("cv/shared/lena.png"),
                                 string("cv/cascadeandhog/images/bttf301.png"),
                                 string("cv/cascadeandhog/images/class57.png") ),
                testing::Values(30, 64, 90) ) )
{
    const string cascasePath = get<0>(GetParam());
    const string imagePath   = get<1>(GetParam());
    const int min_size = get<2>(GetParam());
    Size minSize(min_size, min_size);
    vector<Rect> faces;

    Mat img = imread(getDataPath(imagePath), IMREAD_GRAYSCALE);
    ASSERT_TRUE(!img.empty()) << "Can't load source image: " << getDataPath(imagePath);
    equalizeHist(img, img);
    declare.in(img);

    if (RUN_PLAIN_IMPL)
    {
        CascadeClassifier cc;
        ASSERT_TRUE(cc.load(getDataPath(cascasePath))) << "Can't load cascade file: " << getDataPath(cascasePath);

        while (next())
        {
            faces.clear();

            startTimer();
            cc.detectMultiScale(img, faces, 1.1, 3, 0, minSize);
            stopTimer();
        }
    }
    else if (RUN_OCL_IMPL)
    {
        ocl::oclMat uimg(img);
        ocl::OclCascadeClassifier cc;
        ASSERT_TRUE(cc.load(getDataPath(cascasePath))) << "Can't load cascade file: " << getDataPath(cascasePath);

        while (next())
        {
            faces.clear();
            ocl::finish();

            startTimer();
            cc.detectMultiScale(uimg, faces, 1.1, 3, 0, minSize);
            stopTimer();
        }
    }
    else
        OCL_PERF_ELSE

        //sort(faces.begin(), faces.end(), comparators::RectLess());
        SANITY_CHECK_NOTHING();//(faces, min_size/5);
        // using SANITY_CHECK_NOTHING() since OCL and PLAIN version may find different faces number
}
<commit_msg>temporary disabling hanging test<commit_after>/*M///////////////////////////////////////////////////////////////////////////////////////
//
//  IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
//  By downloading, copying, installing or using the software you agree to this license.
//  If you do not agree to this license, do not download, install,
//  copy or use the software.
//
//
//                           License Agreement
//                For Open Source Computer Vision Library
//
// Copyright (C) 2010-2012, Multicoreware, Inc., all rights reserved.
// Copyright (C) 2010-2012, Advanced Micro Devices, Inc., all rights reserved.
// Third party copyrights are property of their respective owners.
//
// @Authors
//    Fangfang Bai, fangfang@multicorewareinc.com
//    Jin Ma,       jin@multicorewareinc.com
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
//   * Redistribution's of source code must retain the above copyright notice,
//     this list of conditions and the following disclaimer.
//
//   * Redistribution's in binary form must reproduce the above copyright notice,
//     this list of conditions and the following disclaimer in the documentation
//     and/or other materials provided with the distribution.
//
//   * The name of the copyright holders may not 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 Intel Corporation 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.
//
//M*/
#include "perf_precomp.hpp"

using namespace perf;

///////////// Haar ////////////////////////
PERF_TEST(HaarFixture, Haar)
{
    vector<Rect> faces;

    Mat img = imread(getDataPath("gpu/haarcascade/basketball1.png"), CV_LOAD_IMAGE_GRAYSCALE);
    ASSERT_TRUE(!img.empty()) << "can't open basketball1.png";
    declare.in(img);

    if (RUN_PLAIN_IMPL)
    {
        CascadeClassifier faceCascade;
        ASSERT_TRUE(faceCascade.load(getDataPath("gpu/haarcascade/haarcascade_frontalface_alt.xml")))
                << "can't load haarcascade_frontalface_alt.xml";

        TEST_CYCLE() faceCascade.detectMultiScale(img, faces,
                                                     1.1, 2, 0 | CV_HAAR_SCALE_IMAGE, Size(30, 30));

        SANITY_CHECK(faces, 4 + 1e-4);
    }
    else if (RUN_OCL_IMPL)
    {
        ocl::OclCascadeClassifier faceCascade;
        ocl::oclMat oclImg(img);

        ASSERT_TRUE(faceCascade.load(getDataPath("gpu/haarcascade/haarcascade_frontalface_alt.xml")))
                << "can't load haarcascade_frontalface_alt.xml";

        OCL_TEST_CYCLE() faceCascade.detectMultiScale(oclImg, faces,
                                     1.1, 2, 0 | CV_HAAR_SCALE_IMAGE, Size(30, 30));

        SANITY_CHECK(faces, 4 + 1e-4);
    }
    else
        OCL_PERF_ELSE
}

using namespace std;
using namespace cv;
using namespace perf;
using std::tr1::make_tuple;
using std::tr1::get;

typedef std::tr1::tuple<std::string, std::string, int> OCL_Cascade_Image_MinSize_t;
typedef perf::TestBaseWithParam<OCL_Cascade_Image_MinSize_t> OCL_Cascade_Image_MinSize;

PERF_TEST_P( OCL_Cascade_Image_MinSize, CascadeClassifier,
             testing::Combine(
                testing::Values( string("cv/cascadeandhog/cascades/haarcascade_frontalface_alt.xml") ),
                testing::Values( string("cv/shared/lena.png"),
                                 string("cv/cascadeandhog/images/bttf301.png")/*,
                                 string("cv/cascadeandhog/images/class57.png")*/ ),
                testing::Values(30, 64, 90) ) )
{
    const string cascasePath = get<0>(GetParam());
    const string imagePath   = get<1>(GetParam());
    const int min_size = get<2>(GetParam());
    Size minSize(min_size, min_size);
    vector<Rect> faces;

    Mat img = imread(getDataPath(imagePath), IMREAD_GRAYSCALE);
    ASSERT_TRUE(!img.empty()) << "Can't load source image: " << getDataPath(imagePath);
    equalizeHist(img, img);
    declare.in(img);

    if (RUN_PLAIN_IMPL)
    {
        CascadeClassifier cc;
        ASSERT_TRUE(cc.load(getDataPath(cascasePath))) << "Can't load cascade file: " << getDataPath(cascasePath);

        while (next())
        {
            faces.clear();

            startTimer();
            cc.detectMultiScale(img, faces, 1.1, 3, 0, minSize);
            stopTimer();
        }
    }
    else if (RUN_OCL_IMPL)
    {
        ocl::oclMat uimg(img);
        ocl::OclCascadeClassifier cc;
        ASSERT_TRUE(cc.load(getDataPath(cascasePath))) << "Can't load cascade file: " << getDataPath(cascasePath);

        while (next())
        {
            faces.clear();
            ocl::finish();

            startTimer();
            cc.detectMultiScale(uimg, faces, 1.1, 3, 0, minSize);
            stopTimer();
        }
    }
    else
        OCL_PERF_ELSE

        //sort(faces.begin(), faces.end(), comparators::RectLess());
        SANITY_CHECK_NOTHING();//(faces, min_size/5);
        // using SANITY_CHECK_NOTHING() since OCL and PLAIN version may find different faces number
}
<|endoftext|>