<commit_before>////////////////////////////////////////////////////////////////////////////////
/// DISCLAIMER
///
/// Copyright 2014-2016 ArangoDB GmbH, Cologne, Germany
/// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
///     http://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Dr. Frank Celler
////////////////////////////////////////////////////////////////////////////////

#include "VocbaseContext.h"

#include <velocypack/Builder.h>
#include <velocypack/Exception.h>
#include <velocypack/Parser.h>
#include <velocypack/velocypack-aliases.h>

#include "ApplicationFeatures/ApplicationServer.h"
#include "Basics/tri-strings.h"
#include "Cluster/ServerState.h"
#include "Endpoint/ConnectionInfo.h"
#include "GeneralServer/AuthenticationFeature.h"
#include "Logger/Logger.h"
#include "RestServer/FeatureCacheFeature.h"
#include "Ssl/SslInterface.h"
#include "Utils/Events.h"
#include "VocBase/AuthInfo.h"
#include "VocBase/vocbase.h"

using namespace arangodb;
using namespace arangodb::basics;
using namespace arangodb::rest;

double VocbaseContext::ServerSessionTtl =
    60.0 * 60.0 * 24 * 60;  // 2 month session timeout

VocbaseContext::VocbaseContext(GeneralRequest* request, TRI_vocbase_t* vocbase)
    : RequestContext(request),
    _vocbase(vocbase),
    _authentication(nullptr) {
  TRI_ASSERT(_vocbase != nullptr);
  _authentication = FeatureCacheFeature::instance()->authenticationFeature();
  TRI_ASSERT(_authentication != nullptr);
}

VocbaseContext::~VocbaseContext() { _vocbase->release(); }

////////////////////////////////////////////////////////////////////////////////
/// @brief checks the authentication
////////////////////////////////////////////////////////////////////////////////

rest::ResponseCode VocbaseContext::authenticate() {
  TRI_ASSERT(_vocbase != nullptr);

  if (!_authentication->isEnabled()) {
    // no authentication required at all
    return rest::ResponseCode::OK;
  }

  std::string const& path = _request->requestPath();

  // mop: inside authenticateRequest() _request->user will be populated
  bool forceOpen = false;
  rest::ResponseCode result = authenticateRequest(&forceOpen);

  if (result == rest::ResponseCode::UNAUTHORIZED ||
      result == rest::ResponseCode::FORBIDDEN) {
    if (StringUtils::isPrefix(path, "/_open/") ||
        StringUtils::isPrefix(path, "/_admin/aardvark/") || path == "/") {
      // mop: these paths are always callable...they will be able to check
      // req.user when it could be validated
      result = rest::ResponseCode::OK;
      forceOpen = true;
    }
  }

  if (result != rest::ResponseCode::OK) {
    return result;
  }

  std::string const& username = _request->user();
  // mop: internal request => no username present
  if (username.empty()) {
    // mop: set user to root so that the foxx stuff
    // knows about us
    _request->setUser("root");
    return rest::ResponseCode::OK;
  }

  // check that we are allowed to see the database
  if (!forceOpen) {
    if (!StringUtils::isPrefix(path, "/_api/user/")) {
      std::string const& dbname = _request->databaseName();
      if (!username.empty() || !dbname.empty()) {
        AuthLevel level =
            _authentication->canUseDatabase(username, dbname);

        if (level != AuthLevel::RW) {
          events::NotAuthorized(_request);
          result = rest::ResponseCode::UNAUTHORIZED;
        }
      }
    }
  }

  return result;
}

rest::ResponseCode VocbaseContext::authenticateRequest(bool* forceOpen) {
#ifdef ARANGODB_HAVE_DOMAIN_SOCKETS
  // check if we need to run authentication for this type of
  // endpoint
  ConnectionInfo const& ci = _request->connectionInfo();

  if (ci.endpointType == Endpoint::DomainType::UNIX &&
      !_authentication->authenticationUnixSockets()) {
    // no authentication required for unix socket domain connections
    return rest::ResponseCode::OK;
  }
#endif

  std::string const& path = _request->requestPath();

  if (_authentication->authenticationSystemOnly()) {
    // authentication required, but only for /_api, /_admin etc.

    if (!path.empty()) {
      // check if path starts with /_
      if (path[0] != '/') {
        *forceOpen = true;
        return rest::ResponseCode::OK;
      }

      if (path.length() > 0 && path[1] != '_') {
        *forceOpen = true;
        return rest::ResponseCode::OK;
      }
    }
  }

  // .............................................................................
  // authentication required
  // .............................................................................

  bool found;
  std::string const& authStr =
      _request->header(StaticStrings::Authorization, found);

  if (!found) {
    events::CredentialsMissing(_request);
    return rest::ResponseCode::UNAUTHORIZED;
  }

  size_t methodPos = authStr.find_first_of(' ');

  if (methodPos == std::string::npos) {
    events::UnknownAuthenticationMethod(_request);
    return rest::ResponseCode::UNAUTHORIZED;
  }

  // skip over authentication method
  char const* auth = authStr.c_str() + methodPos;

  while (*auth == ' ') {
    ++auth;
  }

  LOG(DEBUG) << "Authorization header: " << authStr;

  if (TRI_CaseEqualString(authStr.c_str(), "basic ", 6)) {
    return basicAuthentication(auth);
  } else if (TRI_CaseEqualString(authStr.c_str(), "bearer ", 7)) {
    return jwtAuthentication(std::string(auth));
  } else {
    events::UnknownAuthenticationMethod(_request);
    return rest::ResponseCode::UNAUTHORIZED;
  }
}

////////////////////////////////////////////////////////////////////////////////
/// @brief checks the authentication via basic
////////////////////////////////////////////////////////////////////////////////

rest::ResponseCode VocbaseContext::basicAuthentication(char const* auth) {
  AuthResult result = _authentication->authInfo()->checkAuthentication(
      AuthInfo::AuthType::BASIC, auth);

  if (!result._authorized) {
    events::CredentialsBad(_request, rest::AuthenticationMethod::BASIC);
    return rest::ResponseCode::UNAUTHORIZED;
  }

  if (!result._username.empty()) {
    _request->setUser(std::move(result._username));
  }

  // we have a user name, verify 'mustChange'
  if (result._mustChange) {
    if ((_request->requestType() == rest::RequestType::PUT ||
         _request->requestType() == rest::RequestType::PATCH) &&
        StringUtils::isPrefix(_request->requestPath(), "/_api/user/")) {
      return rest::ResponseCode::OK;
    }

    events::PasswordChangeRequired(_request);
    return rest::ResponseCode::FORBIDDEN;
  }

  events::Authenticated(_request, rest::AuthenticationMethod::BASIC);
  return rest::ResponseCode::OK;
}

////////////////////////////////////////////////////////////////////////////////
/// @brief checks the authentication via jwt
////////////////////////////////////////////////////////////////////////////////

rest::ResponseCode VocbaseContext::jwtAuthentication(std::string const& auth) {
  AuthResult result = _authentication->authInfo()->checkAuthentication(
      AuthInfo::AuthType::JWT, auth);

  if (!result._authorized) {
    events::CredentialsBad(_request, rest::AuthenticationMethod::JWT);
    return rest::ResponseCode::UNAUTHORIZED;
  }

  // we have a user name, verify 'mustChange'
  if (!result._username.empty()) {
    _request->setUser(std::move(result._username));
  }
  events::Authenticated(_request, rest::AuthenticationMethod::JWT);

  return rest::ResponseCode::OK;
}
<commit_msg>Remove useless if<commit_after>////////////////////////////////////////////////////////////////////////////////
/// DISCLAIMER
///
/// Copyright 2014-2016 ArangoDB GmbH, Cologne, Germany
/// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
///     http://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Dr. Frank Celler
////////////////////////////////////////////////////////////////////////////////

#include "VocbaseContext.h"

#include <velocypack/Builder.h>
#include <velocypack/Exception.h>
#include <velocypack/Parser.h>
#include <velocypack/velocypack-aliases.h>

#include "ApplicationFeatures/ApplicationServer.h"
#include "Basics/tri-strings.h"
#include "Cluster/ServerState.h"
#include "Endpoint/ConnectionInfo.h"
#include "GeneralServer/AuthenticationFeature.h"
#include "Logger/Logger.h"
#include "RestServer/FeatureCacheFeature.h"
#include "Ssl/SslInterface.h"
#include "Utils/Events.h"
#include "VocBase/AuthInfo.h"
#include "VocBase/vocbase.h"

using namespace arangodb;
using namespace arangodb::basics;
using namespace arangodb::rest;

double VocbaseContext::ServerSessionTtl =
    60.0 * 60.0 * 24 * 60;  // 2 month session timeout

VocbaseContext::VocbaseContext(GeneralRequest* request, TRI_vocbase_t* vocbase)
    : RequestContext(request),
    _vocbase(vocbase),
    _authentication(nullptr) {
  TRI_ASSERT(_vocbase != nullptr);
  _authentication = FeatureCacheFeature::instance()->authenticationFeature();
  TRI_ASSERT(_authentication != nullptr);
}

VocbaseContext::~VocbaseContext() { _vocbase->release(); }

////////////////////////////////////////////////////////////////////////////////
/// @brief checks the authentication
////////////////////////////////////////////////////////////////////////////////

rest::ResponseCode VocbaseContext::authenticate() {
  TRI_ASSERT(_vocbase != nullptr);

  if (!_authentication->isEnabled()) {
    // no authentication required at all
    return rest::ResponseCode::OK;
  }

  std::string const& path = _request->requestPath();

  // mop: inside authenticateRequest() _request->user will be populated
  bool forceOpen = false;
  rest::ResponseCode result = authenticateRequest(&forceOpen);

  if (result == rest::ResponseCode::UNAUTHORIZED ||
      result == rest::ResponseCode::FORBIDDEN) {
    if (StringUtils::isPrefix(path, "/_open/") ||
        StringUtils::isPrefix(path, "/_admin/aardvark/") || path == "/") {
      // mop: these paths are always callable...they will be able to check
      // req.user when it could be validated
      result = rest::ResponseCode::OK;
      forceOpen = true;
    }
  }

  if (result != rest::ResponseCode::OK) {
    return result;
  }

  std::string const& username = _request->user();
  // mop: internal request => no username present
  if (username.empty()) {
    // mop: set user to root so that the foxx stuff
    // knows about us
    _request->setUser("root");
    return rest::ResponseCode::OK;
  }

  // check that we are allowed to see the database
  if (!forceOpen) {
    if (!StringUtils::isPrefix(path, "/_api/user/")) {
      std::string const& dbname = _request->databaseName();
      if (!username.empty() || !dbname.empty()) {
        AuthLevel level =
            _authentication->canUseDatabase(username, dbname);

        if (level != AuthLevel::RW) {
          events::NotAuthorized(_request);
          result = rest::ResponseCode::UNAUTHORIZED;
        }
      }
    }
  }

  return result;
}

rest::ResponseCode VocbaseContext::authenticateRequest(bool* forceOpen) {
#ifdef ARANGODB_HAVE_DOMAIN_SOCKETS
  // check if we need to run authentication for this type of
  // endpoint
  ConnectionInfo const& ci = _request->connectionInfo();

  if (ci.endpointType == Endpoint::DomainType::UNIX &&
      !_authentication->authenticationUnixSockets()) {
    // no authentication required for unix socket domain connections
    return rest::ResponseCode::OK;
  }
#endif

  std::string const& path = _request->requestPath();

  if (_authentication->authenticationSystemOnly()) {
    // authentication required, but only for /_api, /_admin etc.

    if (!path.empty()) {
      // check if path starts with /_
      if (path[0] != '/') {
        *forceOpen = true;
        return rest::ResponseCode::OK;
      }

      if (path.length() > 0 && path[1] != '_') {
        *forceOpen = true;
        return rest::ResponseCode::OK;
      }
    }
  }

  // .............................................................................
  // authentication required
  // .............................................................................

  bool found;
  std::string const& authStr =
      _request->header(StaticStrings::Authorization, found);

  if (!found) {
    events::CredentialsMissing(_request);
    return rest::ResponseCode::UNAUTHORIZED;
  }

  size_t methodPos = authStr.find_first_of(' ');

  if (methodPos == std::string::npos) {
    events::UnknownAuthenticationMethod(_request);
    return rest::ResponseCode::UNAUTHORIZED;
  }

  // skip over authentication method
  char const* auth = authStr.c_str() + methodPos;

  while (*auth == ' ') {
    ++auth;
  }

  LOG(DEBUG) << "Authorization header: " << authStr;

  if (TRI_CaseEqualString(authStr.c_str(), "basic ", 6)) {
    return basicAuthentication(auth);
  } else if (TRI_CaseEqualString(authStr.c_str(), "bearer ", 7)) {
    return jwtAuthentication(std::string(auth));
  } else {
    events::UnknownAuthenticationMethod(_request);
    return rest::ResponseCode::UNAUTHORIZED;
  }
}

////////////////////////////////////////////////////////////////////////////////
/// @brief checks the authentication via basic
////////////////////////////////////////////////////////////////////////////////

rest::ResponseCode VocbaseContext::basicAuthentication(char const* auth) {
  AuthResult result = _authentication->authInfo()->checkAuthentication(
      AuthInfo::AuthType::BASIC, auth);

  if (!result._authorized) {
    events::CredentialsBad(_request, rest::AuthenticationMethod::BASIC);
    return rest::ResponseCode::UNAUTHORIZED;
  }

  _request->setUser(std::move(result._username));

  // we have a user name, verify 'mustChange'
  if (result._mustChange) {
    if ((_request->requestType() == rest::RequestType::PUT ||
         _request->requestType() == rest::RequestType::PATCH) &&
        StringUtils::isPrefix(_request->requestPath(), "/_api/user/")) {
      return rest::ResponseCode::OK;
    }

    events::PasswordChangeRequired(_request);
    return rest::ResponseCode::FORBIDDEN;
  }

  events::Authenticated(_request, rest::AuthenticationMethod::BASIC);
  return rest::ResponseCode::OK;
}

////////////////////////////////////////////////////////////////////////////////
/// @brief checks the authentication via jwt
////////////////////////////////////////////////////////////////////////////////

rest::ResponseCode VocbaseContext::jwtAuthentication(std::string const& auth) {
  AuthResult result = _authentication->authInfo()->checkAuthentication(
      AuthInfo::AuthType::JWT, auth);

  if (!result._authorized) {
    events::CredentialsBad(_request, rest::AuthenticationMethod::JWT);
    return rest::ResponseCode::UNAUTHORIZED;
  }

  _request->setUser(std::move(result._username));
  events::Authenticated(_request, rest::AuthenticationMethod::JWT);

  return rest::ResponseCode::OK;
}
<|endoftext|>


<commit_before>#ifndef MIMOSA_HTTP_RESPONSE_WRITER_HH
# define MIMOSA_HTTP_RESPONSE_WRITER_HH

# include "../stream/stream.hh"
# include "../stream/direct-fd-stream.hh"
# include "../stream/buffer.hh"
# include "response.hh"

namespace mimosa
{
  namespace http
  {
    class ServerChannel;

    /**
     * This stream buffers output until sendHeader is called.
     * Then it writes directly to the underlying stream
     * XXX Remove internal buffer, and only support HTTP/1.1
     *
     * @ingroup Http
     */
    class ResponseWriter : public stream::Stream,
                           public Response
    {
    public:
      MIMOSA_DEF_PTR(ResponseWriter);

      ResponseWriter(ServerChannel & channel,
                     Time   write_timeout);
      ~ResponseWriter();

      /** Stream related stuff
       * @{ */

      /** If called before sendHeader(), sends the headers and
       * set transfer_encoding_ to kCodingChunked. */
      virtual int64_t write(const char * data, uint64_t nbytes, Time timeout = 0);
      /** @warning this should never be called, will abort */
      virtual int64_t read(char * data, uint64_t nbytes, Time timeout = 0);
      /** does nothing until sendHeader(), then flushes the write buffer */
      virtual bool flush(Time timeout = 0);

      /** @} */

      /** Writes the header to the client.
       * If content_length_ is 0 then the content length is unspecified
       * and the connection will close after this response (keep_alive_
       * will be set to false).
       * Until you call sendResponseHeader, everything you write to
       * body is buffered, so when you finishes Response knows the
       * amount of data to be written and set content_length_ */
      bool sendHeader(Time timeout = 0);

      void clear();

      inline Time writeTimeout() const
      {
        return write_timeout_ > 0 ? time() + write_timeout_ : 0;
      }

      inline ServerChannel & channel() const { return channel_; }

      /** @return nullptr if we can't convert the output stream to a direct fd */
      stream::DirectFdStream * directFdStream();

    private:
      friend class ServerChannel;

      /** tells that you finished to modify ResponseWriter and you will not
       * call write(). This method should only be called by ServerChannel. */
      bool finish(Time timeout);

      /** writes a chunk if transfer_encoding_ is kCodingChunked */
      int64_t writeChunk(const char *  data,
                         uint64_t      nbytes,
                         Time timeout);

      ServerChannel &       channel_;
      stream::Buffer::Slist buffers_;
      bool                  header_sent_;
      Time         write_timeout_;
    };
  }
}

#endif /* !MIMOSA_HTTP_RESPONSE_WRITER_HH */
<commit_msg>Fix doc.<commit_after>#ifndef MIMOSA_HTTP_RESPONSE_WRITER_HH
# define MIMOSA_HTTP_RESPONSE_WRITER_HH

# include "../stream/stream.hh"
# include "../stream/direct-fd-stream.hh"
# include "../stream/buffer.hh"
# include "response.hh"

namespace mimosa
{
  namespace http
  {
    class ServerChannel;

    /**
     * This stream buffers output until sendHeader is called.
     * Then it writes directly to the underlying stream
     * XXX Remove internal buffer, and only support HTTP/1.1
     *
     * @ingroup Http
     */
    class ResponseWriter : public stream::Stream,
                           public Response
    {
    public:
      MIMOSA_DEF_PTR(ResponseWriter);

      ResponseWriter(ServerChannel & channel,
                     Time   write_timeout);
      ~ResponseWriter();

      /** Stream related stuff
       * @{ */

      /** If called before sendHeader(), sends the headers and
       * set transfer_encoding_ to kCodingChunked. */
      virtual int64_t write(const char * data, uint64_t nbytes, Time timeout = 0);
      /** @warning this should never be called, will abort */
      virtual int64_t read(char * data, uint64_t nbytes, Time timeout = 0);
      /** does nothing until sendHeader(), then flushes the write buffer */
      virtual bool flush(Time timeout = 0);

      /** @} */

      /** Writes the header to the client.
       * If content_length_ is 0 then the content length is unspecified
       * and the connection will close after this response (keep_alive_
       * will be set to false).
       * Until you call sendHeader, everything you write to
       * body is buffered, so when you finishes Response knows the
       * amount of data to be written and set content_length_ */
      bool sendHeader(Time timeout = 0);

      void clear();

      inline Time writeTimeout() const
      {
        return write_timeout_ > 0 ? time() + write_timeout_ : 0;
      }

      inline ServerChannel & channel() const { return channel_; }

      /** @return nullptr if we can't convert the output stream to a direct fd */
      stream::DirectFdStream * directFdStream();

    private:
      friend class ServerChannel;

      /** tells that you finished to modify ResponseWriter and you will not
       * call write(). This method should only be called by ServerChannel. */
      bool finish(Time timeout);

      /** writes a chunk if transfer_encoding_ is kCodingChunked */
      int64_t writeChunk(const char *  data,
                         uint64_t      nbytes,
                         Time timeout);

      ServerChannel &       channel_;
      stream::Buffer::Slist buffers_;
      bool                  header_sent_;
      Time         write_timeout_;
    };
  }
}

#endif /* !MIMOSA_HTTP_RESPONSE_WRITER_HH */
<|endoftext|>


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

#include <cassert>
#include <iostream>
#include "pca_estimator.h"

namespace Torch {

PcaEstimator::PcaEstimator(int n_dim_, int n_eigen_, int minibatch_size_, real gamma_) : Object()
{
  n_dim = n_dim_;
  n_eigen = n_eigen_;
  minibatch_size = minibatch_size_;
  gamma = gamma_;
  lambda = 1e-3;

  n_observations = 0;
  minibatch_index = 0;

  Initialize();
}

void PcaEstimator::Initialize()
{
  Xt = new(allocator) Mat(n_eigen + minibatch_size, n_dim);
  Xt->zero();

  x_sum = new(allocator) Vec(n_dim);
  for (int i=0; i<x_sum->n; i++)
    x_sum->ptr[i] = 0.0;

  G = new(allocator) Mat(n_eigen + minibatch_size, n_eigen + minibatch_size);
  G->zero();
  for (int i=0; i<n_eigen; i++)
    G->ptr[i][i] = lambda;

  d = new(allocator) Vec(n_eigen + minibatch_size);
  for (int i=0; i<n_eigen+minibatch_size; i++)
    d->ptr[i] = 0.0;

  V = new(allocator)  Mat(n_eigen + minibatch_size, n_eigen + minibatch_size);
  V->zero();

  Ut = new(allocator)  Mat(n_eigen, n_dim);
  Ut->zero();
}

void PcaEstimator::Observe(Vec *x)
{
  assert(x->n == n_dim);

  n_observations++;

  // Add the *non-centered* observation to Xt.
  int row = n_eigen + minibatch_index;
  Xt->setRow(row, x);

  // Update the discounted sum of the observations.
  for (int i=0; i<x_sum->n; i++)
    x_sum->ptr[i] = x_sum->ptr[i] * gamma + x->ptr[i];

  // To get the mean, we must normalize the sum by:
  // /gamma^(n_observations-1) + /gamma^(n_observations-2) + ... + 1
  real normalizer = (1 - pow(gamma, (real)n_observations)) /(1 - gamma);
  real inv_normalizer = 1.0 / normalizer;

  // Now center the observation.
  // We will lose the first observation as it is the only one in the mean.
  Vec new_x(Xt->ptr[row], n_dim);
  for (int i=0; i<new_x.n; i++)
    new_x.ptr[i] -= x_sum->ptr[i] * inv_normalizer;

  // Multiply the centered observation by the discount compensator. Basically
  // we make this observation look "younger" than the previous ones. The actual
  // discount is applied in the reevaluation (and when solving the equations in
  // the case of TONGA) by multiplying every direction with the same aging factor.
  real rn = pow(gamma, -0.5*(minibatch_index+1));
  for (int i=0; i<n_dim; i++)
    Xt->ptr[row][i] *= rn;

  // Update the Gram Matrix. Xkt represents the currently used portion
  // of Xt (first rows).
  Vec new_g(G->ptr[row], row + 1);
  Mat *Xkt =  Xt->subMat(0,0,row,n_dim-1);
  mxMatMulVec(Xkt, x, &new_g);
  delete Xkt;

  // Now copy G(row,:) to G(:,row).
  // There are row+1 values, but the diag doesn't need to get copied.
  for (int i=0; i<row; i++)
    G->ptr[i][row] =  G->ptr[row][i];

  minibatch_index++;

  if(minibatch_index==minibatch_size)
    Reevaluate();

}

void PcaEstimator::Reevaluate()
{
  // TODO do the modifications to handle when this is not true.
  assert(minibatch_index==minibatch_size);

  // Regularize - not necessary but in case
  //for (int i=0; i<n_eigen+minibatch_size; i++)
  //  G->ptr[i][i] += lambda;

  // The Gram matrix is up to date. Get its low rank eigendecomposition.
  // TODO How to get only #n_eigen# elements?
  mxSymEig(G, V, d);

  // The eigen values and vectors are *NOT SORTED*. Furthermore, the vectors
  // are on the columns.
  // Find and sort the n_eigen first values and vectors using Dumb Sort
  for (int i=0; i<n_eigen; i++) {
    // Initialize the max search
    int max_index = i;
    real max_value = d->ptr[i];

    // Compare with remaining possibilities
    for (int j=i+1; j<n_eigen+minibatch_size; j++) {
      if (max_value < d->ptr[j])  {
        max_value = d->ptr[j];
        max_index = j;
      }
    }

    // Swap!
    d->ptr[max_index] = d->ptr[i];
    d->ptr[i] = max_value;
    mxSwapColsMat(V, i, max_index, -1, -1);
  }

  // Convert the n_eigen first eigenvectors of the Gram matrix contained in V
  // into *unnormalized* eigenvectors U of the covariance.
  Mat *Vk = V->subMat(0, 0, n_eigen+minibatch_index-1, n_eigen-1);
  mxTrMatMulMat(Vk, Xt, Ut);
  delete Vk;

  // Take into account the discount factor.
  // Here, minibatch index is minibacth_size. We age everyone. Because of the
  // previous multiplications to make some observations "younger" we multiply
  // everyone by the same factor.
  // TODO VERIFY THIS!
  real rn = pow(gamma, -0.5*(minibatch_index+1));
  real inv_rn2 = 1.0/(rn*rn);

  mxRealMulMat(1.0/rn, Ut, Ut);
  for (int i=0; i<d->n; i++)
    d->ptr[i] *= inv_rn2;

  //---------------------
  /*
  std::cout << "*** Reevaluate! ***" << std::endl;
  real normalizer = (1.0 - pow(gamma, (real)n_observations)) /(1.0 - gamma);
  real inv_normalizer = 1.0 / normalizer;
  std::cout << "inv_normalizer: " << inv_normalizer << std::endl;
  for (int i=0; i<n_eigen; i++)
    std::cout << d->ptr[i] * inv_normalizer << std::endl;
  */
  //---------------------

  // Update Xt, G and minibatch_index
  Mat *Xkt =  Xt->subMat(0,0,n_eigen-1,n_dim-1);
  Xkt->copy(Ut);
  delete Xkt;

  for (int i=0; i<n_eigen; i++)
    G->ptr[i][i] = d->ptr[i];

  minibatch_index=0;
}

void PcaEstimator::GetLeadingEigen(Vec *the_d, Mat *the_Vt)
{

  // Copy the eigen values and normalize them by (1 - pow(gamma,real(t+1)))/(1 - gamma);
  the_d->copy(d);

  real normalizer = (1.0 - pow(gamma, (real)n_observations)) /(1.0 - gamma);
  real inv_normalizer = 1.0 / normalizer;

  for (int i=0; i<the_d->n; i++)
    the_d->ptr[i] *= inv_normalizer;

  // Copy the unnormalized eigen vectors and normalize them
  the_Vt->copy(Ut);

  // Normalize
  Vec a_eigenvec(NULL, n_dim);
  for (int i=0; i<the_Vt->m; i++) {
    a_eigenvec.ptr = the_Vt->ptr[i];
    real inv_norm2 = 1.0 / a_eigenvec.norm2();
    for (int j=0; j<the_Vt->n; j++)
      the_Vt->ptr[i][j] *= inv_norm2;
    assert( fabs(a_eigenvec.norm2() - 1.0) < 1e-6 );
  }

}

PcaEstimator::~PcaEstimator()
{
}

}
<commit_msg>Bugfix: SwapRows actually swaps columns and vice-versa. Modified code to take this into account.<commit_after>// Copyright 2008 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//

#include <cassert>
#include <iostream>
#include "pca_estimator.h"

namespace Torch {

PcaEstimator::PcaEstimator(int n_dim_, int n_eigen_, int minibatch_size_, real gamma_) : Object()
{
  n_dim = n_dim_;
  n_eigen = n_eigen_;
  minibatch_size = minibatch_size_;
  gamma = gamma_;
  lambda = 1e-3;

  n_observations = 0;
  minibatch_index = 0;

  Initialize();
}

void PcaEstimator::Initialize()
{
  Xt = new(allocator) Mat(n_eigen + minibatch_size, n_dim);
  Xt->zero();

  x_sum = new(allocator) Vec(n_dim);
  for (int i=0; i<x_sum->n; i++)
    x_sum->ptr[i] = 0.0;

  G = new(allocator) Mat(n_eigen + minibatch_size, n_eigen + minibatch_size);
  G->zero();
  for (int i=0; i<n_eigen; i++)
    G->ptr[i][i] = lambda;

  d = new(allocator) Vec(n_eigen + minibatch_size);
  for (int i=0; i<n_eigen+minibatch_size; i++)
    d->ptr[i] = 0.0;

  V = new(allocator)  Mat(n_eigen + minibatch_size, n_eigen + minibatch_size);
  V->zero();

  Ut = new(allocator)  Mat(n_eigen, n_dim);
  Ut->zero();
}

void PcaEstimator::Observe(Vec *x)
{
  assert(x->n == n_dim);

  n_observations++;

  // Add the *non-centered* observation to Xt.
  int row = n_eigen + minibatch_index;
  Xt->setRow(row, x);

  // Update the discounted sum of the observations.
  for (int i=0; i<x_sum->n; i++)
    x_sum->ptr[i] = x_sum->ptr[i] * gamma + x->ptr[i];

  // To get the mean, we must normalize the sum by:
  // /gamma^(n_observations-1) + /gamma^(n_observations-2) + ... + 1
  real normalizer = (1 - pow(gamma, (real)n_observations)) /(1 - gamma);
  real inv_normalizer = 1.0 / normalizer;

  // Now center the observation.
  // We will lose the first observation as it is the only one in the mean.
  Vec new_x(Xt->ptr[row], n_dim);
  for (int i=0; i<new_x.n; i++)
    new_x.ptr[i] -= x_sum->ptr[i] * inv_normalizer;

  // Multiply the centered observation by the discount compensator. Basically
  // we make this observation look "younger" than the previous ones. The actual
  // discount is applied in the reevaluation (and when solving the equations in
  // the case of TONGA) by multiplying every direction with the same aging factor.
  real rn = pow(gamma, -0.5*(minibatch_index+1));
  for (int i=0; i<n_dim; i++)
    Xt->ptr[row][i] *= rn;

  // Update the Gram Matrix. Xkt represents the currently used portion
  // of Xt (first rows).
  Vec new_g(G->ptr[row], row + 1);
  Mat *Xkt =  Xt->subMat(0,0,row,n_dim-1);
  mxMatMulVec(Xkt, x, &new_g);
  delete Xkt;

  // Now copy G(row,:) to G(:,row).
  // There are row+1 values, but the diag doesn't need to get copied.
  for (int i=0; i<row; i++)
    G->ptr[i][row] =  G->ptr[row][i];

  minibatch_index++;

  if(minibatch_index==minibatch_size)
    Reevaluate();

}

void PcaEstimator::Reevaluate()
{
  // TODO do the modifications to handle when this is not true.
  assert(minibatch_index==minibatch_size);

  // Regularize - not necessary but in case
  //for (int i=0; i<n_eigen+minibatch_size; i++)
  //  G->ptr[i][i] += lambda;

  // The Gram matrix is up to date. Get its low rank eigendecomposition.
  // TODO How to get only #n_eigen# elements?
  mxSymEig(G, V, d);

  // The eigen values and vectors are *NOT SORTED*. Furthermore, the vectors
  // are on the columns.
  // Find and sort the n_eigen first values and vectors using Dumb Sort
  for (int i=0; i<n_eigen; i++) {
    // Initialize the max search
    int max_index = i;
    real max_value = d->ptr[i];

    // Compare with remaining possibilities
    for (int j=i+1; j<n_eigen+minibatch_size; j++) {
      if (max_value < d->ptr[j])  {
        max_value = d->ptr[j];
        max_index = j;
      }
    }

    // Swap!
    d->ptr[max_index] = d->ptr[i];
    d->ptr[i] = max_value;
    // WARNING! We want to swap columns but the method to do this is called
    // SWAP *ROWS*
    //mxSwapColsMat(V, i, max_index, -1, -1);
    mxSwapRowsMat(V, i, max_index, -1, -1);
  }

  // Convert the n_eigen first eigenvectors of the Gram matrix contained in V
  // into *unnormalized* eigenvectors U of the covariance.
  Mat *Vk = V->subMat(0, 0, n_eigen+minibatch_index-1, n_eigen-1);
  mxTrMatMulMat(Vk, Xt, Ut);
  delete Vk;

  // Take into account the discount factor.
  // Here, minibatch index is minibacth_size. We age everyone. Because of the
  // previous multiplications to make some observations "younger" we multiply
  // everyone by the same factor.
  // TODO VERIFY THIS!
  real rn = pow(gamma, -0.5*(minibatch_index+1));
  real inv_rn2 = 1.0/(rn*rn);

  mxRealMulMat(1.0/rn, Ut, Ut);
  for (int i=0; i<d->n; i++)
    d->ptr[i] *= inv_rn2;

  //---------------------
/*
  std::cout << "*** Reevaluate! ***" << std::endl;
  real normalizer = (1.0 - pow(gamma, (real)n_observations)) /(1.0 - gamma);
  real inv_normalizer = 1.0 / normalizer;
  std::cout << "inv_normalizer: " << inv_normalizer << std::endl;
  for (int i=0; i<n_eigen+minibatch_size; i++)
    std::cout << d->ptr[i] * inv_normalizer << std::endl;
*/
  //---------------------

  // Update Xt, G and minibatch_index
  Mat *Xkt =  Xt->subMat(0,0,n_eigen-1,n_dim-1);
  Xkt->copy(Ut);
  delete Xkt;

  for (int i=0; i<n_eigen; i++)
    G->ptr[i][i] = d->ptr[i];

  minibatch_index=0;
}

void PcaEstimator::GetLeadingEigen(Vec *the_d, Mat *the_Vt)
{

  // Copy the eigen values and normalize them by (1 - pow(gamma,real(t+1)))/(1 - gamma);
  the_d->copy(d);

  real normalizer = (1.0 - pow(gamma, (real)n_observations)) /(1.0 - gamma);
  real inv_normalizer = 1.0 / normalizer;

  for (int i=0; i<the_d->n; i++)
    the_d->ptr[i] *= inv_normalizer;

  // Copy the unnormalized eigen vectors and normalize them
  the_Vt->copy(Ut);

  // Normalize
  Vec a_eigenvec(NULL, n_dim);
  for (int i=0; i<the_Vt->m; i++) {
    a_eigenvec.ptr = the_Vt->ptr[i];
    real inv_norm2 = 1.0 / a_eigenvec.norm2();
    for (int j=0; j<the_Vt->n; j++)
      the_Vt->ptr[i][j] *= inv_norm2;
    assert( fabs(a_eigenvec.norm2() - 1.0) < 1e-6 );
  }

}

PcaEstimator::~PcaEstimator()
{
}

}
<|endoftext|>


<commit_before>#include "Vector3D.hpp"
#include <cmath>

using namespace RealRT;

Vector3D::Vector3D(float i, float j, float k)
{
    _I = i;
    _J = j;
    _K = k;
}

explicit Vector3D::Vector3D(const float *values)
{
    _I = values[0];
    _J = values[1];
    _K = values[2];
}

Vector3D(std::initializer_list<float> list)
{
    _I = list[0];
    _J = list[1];
    _K = list[2];
}

float Vector3D::I(void) const
{
    return _I;
}

float Vector3D::J(void) const
{
    return _J;
}

float Vector3D::K(void) const
{
    return _K;
}

Vector3D Vector3D::Add(const Vector3D &v)
{
    return Vector3D(_I + v._I, _J + v._J, _K + v._K);
}

Vector3D Vector3D::Subtract(const Vector3D &v)
{
    return Vector3D(_I - v._I, _J - v._J, _K - v._K);
}

Vector3D Vector3D::Normalize(void)
{
    return Scale(1.f / Magnitude());
}

float Vector3D::Distance(const Vector3D &rhs) const
{
    return std::sqrt(this->Dot(*this - rhs));
}

float Magnitude(void) const
{
    return std::sqrt(Dot(*this));
}

Vector3D Vector3D::Scale(float scalar)
{
    return Vector3D(_I * scalar, _J * scalar, _K * scalar);
}

Vector3D Vector3D::Clip(float maxVal)
{
    return Vector3D(_I > maxVal ? maxVal : _I,
                    _J > maxVal ? maxVal : _J,
                    _K > maxVal ? maxVal : _K);
}

Vector3D Vector3D::Weight(const Vector3D &rhs) const
{
    return Vector3D(_I * rhs._I, _J * rhs._J, _K * rhs._K);
}

float Vector3D::Dot(const Vector3D &rhs) const
{
    return (_I * rhs._I) + (_J * rhs._J) + (_K * rhs._K);
}

Vector3D Vector3D::Cross(const Vector3D &rhs) const
{
    return Vector3D(
       (_J * rhs._K) - (rhs._J * _K)  ,
     -((_I * rhs._K) - (rhs._I * _K)) ,
       (_I * rhs._J) - (rhs._I * _J) );
}

float Vector3D::operator [](int i) const
{
    switch(i)
    {
        case 0:
            return _I;

        case 1:
            return _J;

        case 2:
            return _K;

        default:
            throw Exception("Vector3D index out of bounds");
    }
}

bool Vector3D::operator ==(const Vector3D &rhs) const
{
    return _I == rhs._I && _J == rhs._J && _K == rhs._K;
}

bool Vector3D::operator !=(const Vector3D &rhs) const
{
    return !(*this == rhs);
}

bool Vector3D::operator <(const Vector3D &rhs) const
{
    return Norm() < rhs.Norm();
}

bool Vector3D::operator <=(const Vector3D &rhs) const
{
    return Norm() <= rhs.Norm();
}

bool Vector3D::operator >(const Vector3D &rhs) const
{
    return Norm() > rhs.Norm();
}

bool Vector3D::operator >=(const Vector3D &rhs) const
{
    return Norm() >= rhs.Norm();
}

Vector3D Vector3D::operator +(const Vector3D &rhs) const
{
    return Add(rhs);
}

Vector3D Vector3D::operator -(const Vector3D &rhs) const
{
    return Subtract(rhs);
}

Vector3D &Vector3D::operator +=(const Vector3D &rhs)
{
    _I += rhs._I;
    _J += rhs._J;
    _K += rhs._K;

    return *this;
}

Vector3D &Vector3D::operator -=(const Vector3D &rhs)
{
    _I -= rhs._I;
    _J -= rhs._J;
    _K -= rhs._K;

    return *this;
}

Vector3D operator *(float scalar, const Vector3D &v)
{
    return v.Scale(scalar);
}

Vector3D operator *(const Vector3D &v, float scalar)
{
    return v.Scale(scalar);
}

float Vector3D::operator *(const Vector3D &rhs) const
{
    return this->Dot(rhs);
}

Vector3D &Vector3D::operator *=(float scalar)
{
    _I *= scalar;
    _J *= scalar;
    _K *= scalar;

    return *this;
}

Vector3D Vector3D::operator %(const Vector3D &rhs) const
{
    return this->Cross(rhs);
}

Vector3D &Vector3D::operator %=(const Vector3D &rhs)
{
	_I =   (_J * rhs._K) - (rhs._J * _K) ;
    _J = -((_I * rhs._K) - (rhs._I * _K));
    _K =   (_I * rhs._J) - (rhs._I * _J) ;

    return *this;
}

std::ostream &operator<<(std::ostream &os, const Vector3D &obj)
{
    os << "[" << obj._I << " " << obj._J << " " << obj._K << "]";
    return os;
}

std::istream &operator>>(std::istream &is, Vector3D &obj)
{
    float i, j, k;

    is.ignore(1, '[');
    is >> i >> j >> k;
    is.ignore(1, ']');

    return is;
}

<commit_msg>Added missing const declarations to source<commit_after>#include "Vector3D.hpp"
#include <cmath>

using namespace RealRT;

Vector3D::Vector3D(float i, float j, float k)
{
    _I = i;
    _J = j;
    _K = k;
}

explicit Vector3D::Vector3D(const float *values)
{
    _I = values[0];
    _J = values[1];
    _K = values[2];
}

Vector3D(std::initializer_list<float> list)
{
    _I = list[0];
    _J = list[1];
    _K = list[2];
}

float Vector3D::I(void) const
{
    return _I;
}

float Vector3D::J(void) const
{
    return _J;
}

float Vector3D::K(void) const
{
    return _K;
}

Vector3D Vector3D::Add(const Vector3D &v) const
{
    return Vector3D(_I + v._I, _J + v._J, _K + v._K);
}

Vector3D Vector3D::Subtract(const Vector3D &v)
{
    return Vector3D(_I - v._I, _J - v._J, _K - v._K);
}

Vector3D Vector3D::Normalize(void) const
{
    return Scale(1.f / Magnitude());
}

float Vector3D::Distance(const Vector3D &rhs) const
{
    return std::sqrt(this->Dot(*this - rhs));
}

float Magnitude(void) const
{
    return std::sqrt(Dot(*this));
}

Vector3D Vector3D::Scale(float scalar) const
{
    return Vector3D(_I * scalar, _J * scalar, _K * scalar);
}

Vector3D Vector3D::Clip(float maxVal) const
{
    return Vector3D(_I > maxVal ? maxVal : _I,
                    _J > maxVal ? maxVal : _J,
                    _K > maxVal ? maxVal : _K);
}

Vector3D Vector3D::Weight(const Vector3D &rhs) const
{
    return Vector3D(_I * rhs._I, _J * rhs._J, _K * rhs._K);
}

float Vector3D::Dot(const Vector3D &rhs) const
{
    return (_I * rhs._I) + (_J * rhs._J) + (_K * rhs._K);
}

Vector3D Vector3D::Cross(const Vector3D &rhs) const
{
    return Vector3D(
       (_J * rhs._K) - (rhs._J * _K)  ,
     -((_I * rhs._K) - (rhs._I * _K)) ,
       (_I * rhs._J) - (rhs._I * _J) );
}

float Vector3D::operator [](int i) const
{
    switch(i)
    {
        case 0:
            return _I;

        case 1:
            return _J;

        case 2:
            return _K;

        default:
            throw Exception("Vector3D index out of bounds");
    }
}

bool Vector3D::operator ==(const Vector3D &rhs) const
{
    return _I == rhs._I && _J == rhs._J && _K == rhs._K;
}

bool Vector3D::operator !=(const Vector3D &rhs) const
{
    return !(*this == rhs);
}

bool Vector3D::operator <(const Vector3D &rhs) const
{
    return Norm() < rhs.Norm();
}

bool Vector3D::operator <=(const Vector3D &rhs) const
{
    return Norm() <= rhs.Norm();
}

bool Vector3D::operator >(const Vector3D &rhs) const
{
    return Norm() > rhs.Norm();
}

bool Vector3D::operator >=(const Vector3D &rhs) const
{
    return Norm() >= rhs.Norm();
}

Vector3D Vector3D::operator +(const Vector3D &rhs) const
{
    return Add(rhs);
}

Vector3D Vector3D::operator -(const Vector3D &rhs) const
{
    return Subtract(rhs);
}

Vector3D &Vector3D::operator +=(const Vector3D &rhs)
{
    _I += rhs._I;
    _J += rhs._J;
    _K += rhs._K;

    return *this;
}

Vector3D &Vector3D::operator -=(const Vector3D &rhs)
{
    _I -= rhs._I;
    _J -= rhs._J;
    _K -= rhs._K;

    return *this;
}

Vector3D operator *(float scalar, const Vector3D &v)
{
    return v.Scale(scalar);
}

Vector3D operator *(const Vector3D &v, float scalar)
{
    return v.Scale(scalar);
}

float Vector3D::operator *(const Vector3D &rhs) const
{
    return this->Dot(rhs);
}

Vector3D &Vector3D::operator *=(float scalar)
{
    _I *= scalar;
    _J *= scalar;
    _K *= scalar;

    return *this;
}

Vector3D Vector3D::operator %(const Vector3D &rhs) const
{
    return this->Cross(rhs);
}

Vector3D &Vector3D::operator %=(const Vector3D &rhs)
{
	_I =   (_J * rhs._K) - (rhs._J * _K) ;
    _J = -((_I * rhs._K) - (rhs._I * _K));
    _K =   (_I * rhs._J) - (rhs._I * _J) ;

    return *this;
}

std::ostream &operator<<(std::ostream &os, const Vector3D &obj)
{
    os << "[" << obj._I << " " << obj._J << " " << obj._K << "]";
    return os;
}

std::istream &operator>>(std::istream &is, Vector3D &obj)
{
    float i, j, k;

    is.ignore(1, '[');
    is >> i >> j >> k;
    is.ignore(1, ']');

    return is;
}

<|endoftext|>


<commit_before>//
//  main.cpp
//  Unit Tests
//
//  Created by Evan McCartney-Melstad on 12/31/14.
//  Copyright (c) 2014 Evan McCartney-Melstad. All rights reserved.
//

#define CATCH_CONFIG_MAIN  // This tells Catch to provide a main() - only do this in one cpp file
#include "../cPWP/generateSimulatedData.h"
#include "../cPWP/bamsToBin.h"
#include "../cPWP/calcPWP.h"
#include "catch.hpp"
#include <string>
#include <iostream>
#include <fstream>

/*
TEST_CASE( "Simulated reads are generated", "[generateReads]" ) {
    // Make sure that the read simulation finishes
    REQUIRE( generateReadsAndMap(1, 0.01, "0.0", "300", "50", "1000000", "100", "1234", "scaffold_0.fasta") == 0);
}
 */

TEST_CASE( "Generate reference genome for simulation tests", "[generateReference]") {
    REQUIRE( createReferenceGenome(1000000, 0.42668722, "simulatedReferenceGenome.fasta") == 0 );
}

TEST_CASE ( "Mutate a reference genome", "[mutateRefGenome]") {
    REQUIRE( createMutatedGenome("simulatedReferenceGenome.fasta", "simulatedReferenceGenomeMutated.fasta", 0.01) == 0);
}

TEST_CASE( "Generate sequence reads", "[perfectReads]") {
    REQUIRE( generatePerfectReads ("simulatedReferenceGenome.fasta", 1, 100, 300, "normalRef") == 0);
    //generatePerfectReads (std::string reference, unsigned int stagger, unsigned int readLengths, unsigned int fragmentLengths, std::string readPrefix);
}

TEST_CASE( " Mapping first set of reads", "[mapReads]") {
    REQUIRE( mapReads("simulatedReferenceGenome.fasta", "normalRef_R1.fastq", "normalRef_R2.fastq", "normal.bam", "25") == 0);
}

/*
TEST_CASE( "Generate sequence reads 2", "[perfectReads2]") {
    REQUIRE( generatePerfectReads ("simulatedReferenceGenomeMutated.fasta", 1, 100, 300, "mutatedRef") == 0);
}

*/

TEST_CASE( " Mapping second set of reads", "[mapReads2]") {
    REQUIRE( mapReads("simulatedReferenceGenome.fasta", "mutatedRef_R1.fastq", "mutatedRef_R2.fastq", "mutated.bam", "25") == 0);
}

TEST_CASE( "Create heterozygous R1", "[createHet]") {
    REQUIRE( createHeterozygousGenome("normalRef_R1.fastq", "mutatedRef_R1.fastq", "hetRef_R1.fastq") == 0);
}

TEST_CASE( "Create heterozygous R2", "[createHet]") {
    REQUIRE( createHeterozygousGenome("normalRef_R2.fastq", "mutatedRef_R2.fastq", "hetRef_R2.fastq") == 0);
}

TEST_CASE( " Mapping het reads", "[mapReads2]") {
    REQUIRE( mapReads("simulatedReferenceGenome.fasta", "hetRef_R1.fastq", "hetRef_R2.fastq", "het.bam", "25") == 0);
}

TEST_CASE( "Run ANGSD on simulated reads", "[runANGSD]" ) {
    REQUIRE( runANGSDforReadCounts("bamlist.txt", "angsdOut", "25", "angsdOutLog.txt") == 0);
}

/*

TEST_CASE( "Generate mutated reference genomes and simulate reads", "[genomeAndReadSim]") {
    REQUIRE( generateReadsAndMap(3, 0.01, "300", "25", "10000", "100", "1234", "simulatedReferenceGenome.fasta", "25") == 0);
}

TEST_CASE( "Run ANGSD on simulated reads", "[runANGSD]" ) {
    REQUIRE( runANGSDforReadCounts("bamlist.txt", "angsdOut", "25", "angsdOutLog.txt") == 0);
}

 */

TEST_CASE( "Convert ANGSD read counts to unsigned chars for major and minor counts", "[convertCountsToBinary]") {
    REQUIRE( convertANGSDcountsToBinary("angsdOut", "angsdOut.readCounts.binary", 2, 5000) == 0); // 5000 as a max because we don't want to exclude any loci for this test
}

TEST_CASE( "Calculate PWP from the binary representations of the ANGSD readcounts", "[calcPWP]") {
    REQUIRE( calcPWPfromBinaryFile ("angsdOut.readCounts.binary", 0, 2, "testingOut.pwp", 30) == 0);
}

<commit_msg>Minor changes<commit_after>//
//  main.cpp
//  Unit Tests
//
//  Created by Evan McCartney-Melstad on 12/31/14.
//  Copyright (c) 2014 Evan McCartney-Melstad. All rights reserved.
//

#define CATCH_CONFIG_MAIN  // This tells Catch to provide a main() - only do this in one cpp file
#include "../cPWP/generateSimulatedData.h"
#include "../cPWP/bamsToBin.h"
#include "../cPWP/calcPWP.h"
#include "catch.hpp"
#include <string>
#include <iostream>
#include <fstream>

/*
TEST_CASE( "Simulated reads are generated", "[generateReads]" ) {
    // Make sure that the read simulation finishes
    REQUIRE( generateReadsAndMap(1, 0.01, "0.0", "300", "50", "1000000", "100", "1234", "scaffold_0.fasta") == 0);
}
 */

TEST_CASE( "Generate reference genome for simulation tests", "[generateReference]") {
    REQUIRE( createReferenceGenome(1000000, 0.42668722, "simulatedReferenceGenome.fasta") == 0 );
}

TEST_CASE ( "Mutate a reference genome", "[mutateRefGenome]") {
    REQUIRE( createMutatedGenome("simulatedReferenceGenome.fasta", "simulatedReferenceGenomeMutated.fasta", 0.01) == 0);
}

TEST_CASE( "Generate sequence reads", "[perfectReads]") {
    REQUIRE( generatePerfectReads ("simulatedReferenceGenome.fasta", 1, 100, 300, "normalRef") == 0);
    //generatePerfectReads (std::string reference, unsigned int stagger, unsigned int readLengths, unsigned int fragmentLengths, std::string readPrefix);
}

TEST_CASE( " Mapping first set of reads", "[mapReads]") {
    REQUIRE( mapReads("simulatedReferenceGenome.fasta", "normalRef_R1.fastq", "normalRef_R2.fastq", "normal.bam", "25") == 0);
}

TEST_CASE( "Generate sequence reads 2", "[perfectReads2]") {
    REQUIRE( generatePerfectReads ("simulatedReferenceGenomeMutated.fasta", 1, 100, 300, "mutatedRef") == 0);
}

/*
TEST_CASE( " Mapping second set of reads", "[mapReads2]") {
    REQUIRE( mapReads("simulatedReferenceGenome.fasta", "mutatedRef_R1.fastq", "mutatedRef_R2.fastq", "mutated.bam", "25") == 0);
}
 */

TEST_CASE( "Create heterozygous R1", "[createHet]") {
    REQUIRE( createHeterozygousGenome("normalRef_R1.fastq", "mutatedRef_R1.fastq", "hetRef_R1.fastq") == 0);
}

TEST_CASE( "Create heterozygous R2", "[createHet]") {
    REQUIRE( createHeterozygousGenome("normalRef_R2.fastq", "mutatedRef_R2.fastq", "hetRef_R2.fastq") == 0);
}

TEST_CASE( " Mapping het reads", "[mapReads2]") {
    REQUIRE( mapReads("simulatedReferenceGenome.fasta", "hetRef_R1.fastq", "hetRef_R2.fastq", "het.bam", "25") == 0);
}

TEST_CASE( "Run ANGSD on simulated reads", "[runANGSD]" ) {
    REQUIRE( runANGSDforReadCounts("bamlist.txt", "angsdOut", "25", "angsdOutLog.txt") == 0);
}

/*

TEST_CASE( "Generate mutated reference genomes and simulate reads", "[genomeAndReadSim]") {
    REQUIRE( generateReadsAndMap(3, 0.01, "300", "25", "10000", "100", "1234", "simulatedReferenceGenome.fasta", "25") == 0);
}

TEST_CASE( "Run ANGSD on simulated reads", "[runANGSD]" ) {
    REQUIRE( runANGSDforReadCounts("bamlist.txt", "angsdOut", "25", "angsdOutLog.txt") == 0);
}

 */

TEST_CASE( "Convert ANGSD read counts to unsigned chars for major and minor counts", "[convertCountsToBinary]") {
    REQUIRE( convertANGSDcountsToBinary("angsdOut", "angsdOut.readCounts.binary", 2, 5000) == 0); // 5000 as a max because we don't want to exclude any loci for this test
}

TEST_CASE( "Calculate PWP from the binary representations of the ANGSD readcounts", "[calcPWP]") {
    REQUIRE( calcPWPfromBinaryFile ("angsdOut.readCounts.binary", 0, 2, "testingOut.pwp", 30) == 0);
}

<|endoftext|>


<commit_before>#include "V9Slice.h"
#include "VGlobal.h"

void V9Slice::updateTransform()
{
	sf::Vector2f origin = sf::Vector2f(Origin.x * Size.x, Origin.y * Size.y);

	float angle = -Angle * VFRAME_PI / 180.f;
	float cosine = static_cast<float>(std::cos(angle));
	float sine = static_cast<float>(std::sin(angle));
	float sxc = Scale.x * cosine;
	float syc = Scale.y * cosine;
	float sxs = Scale.x * sine;
	float sys = Scale.y * sine;
	float tx = -Origin.x * sxc - Origin.y * sys + (Position + origin).x;
	float ty = Origin.x * sxs - Origin.y * syc + (Position + origin).y;

	renderState.transform =
		sf::Transform(sxc, sys, tx,
			-sxs, syc, ty,
			0.f, 0.f, 1.f);

	if (vertexArray[0].color != Tint)
	{
		for (unsigned int i = 0; i < vertexArray.getVertexCount(); i++)
			vertexArray[i].color = Tint;
	}
}

void V9Slice::updateFrame()
{
	Size.x = Size.x < cornerSize.x * 2 ? cornerSize.x * 2 : Size.x;
	Size.y = Size.y < cornerSize.y * 2 ? cornerSize.y * 2 : Size.y;

	sf::Vector2f barSize = Size - (cornerSize * 2.0f);

	//1 2
	//0 3

	//Top Left Corner
	vertexArray[(0 * 4) + 0].position = sf::Vector2f();
	vertexArray[(0 * 4) + 1].position = sf::Vector2f(cornerSize.x, 0.0f);
	vertexArray[(0 * 4) + 2].position = sf::Vector2f(cornerSize.x, cornerSize.y);
	vertexArray[(0 * 4) + 3].position = sf::Vector2f(0.0f, cornerSize.y);
	vertexArray[(0 * 4) + 0].texCoords = sf::Vector2f(textureRect.left, textureRect.top);
	vertexArray[(0 * 4) + 1].texCoords = sf::Vector2f(textureRect.left + cornerSize.x, textureRect.top);
	vertexArray[(0 * 4) + 2].texCoords = sf::Vector2f(textureRect.left + cornerSize.x, textureRect.top + cornerSize.y);
	vertexArray[(0 * 4) + 3].texCoords = sf::Vector2f(textureRect.left, textureRect.top + cornerSize.y);

	//Top Bar
	vertexArray[(1 * 4) + 0].position = sf::Vector2f(cornerSize.x, 0.0f);
	vertexArray[(1 * 4) + 1].position = sf::Vector2f(cornerSize.x + barSize.x, 0.0f);
	vertexArray[(1 * 4) + 2].position = sf::Vector2f(cornerSize.x + barSize.x, cornerSize.y);
	vertexArray[(1 * 4) + 3].position = sf::Vector2f(cornerSize.x, cornerSize.y);
	vertexArray[(1 * 4) + 0].texCoords = sf::Vector2f(textureRect.left + cornerSize.x, textureRect.top);
	vertexArray[(1 * 4) + 1].texCoords = sf::Vector2f(textureRect.left + textureRect.width - cornerSize.x, textureRect.top);
	vertexArray[(1 * 4) + 2].texCoords = sf::Vector2f(textureRect.left + textureRect.width - cornerSize.x, textureRect.top + cornerSize.y);
	vertexArray[(1 * 4) + 3].texCoords = sf::Vector2f(textureRect.left + cornerSize.x, textureRect.top + cornerSize.y);

	//Top Right Corner
	vertexArray[(2 * 4) + 0].position = sf::Vector2f(Size.x - cornerSize.x, 0.0f);
	vertexArray[(2 * 4) + 1].position = sf::Vector2f(Size.x, 0.0f);
	vertexArray[(2 * 4) + 2].position = sf::Vector2f(Size.x, cornerSize.y);
	vertexArray[(2 * 4) + 3].position = sf::Vector2f(Size.x - cornerSize.x, cornerSize.y);
	vertexArray[(2 * 4) + 0].texCoords = sf::Vector2f(textureRect.left + textureRect.width - cornerSize.x, textureRect.top);
	vertexArray[(2 * 4) + 1].texCoords = sf::Vector2f(textureRect.left + textureRect.width, textureRect.top);
	vertexArray[(2 * 4) + 2].texCoords = sf::Vector2f(textureRect.left + textureRect.width, textureRect.top + cornerSize.y);
	vertexArray[(2 * 4) + 3].texCoords = sf::Vector2f(textureRect.left + textureRect.width - cornerSize.x, textureRect.top + cornerSize.y);

	//Left Bar
	vertexArray[(3 * 4) + 0].position = sf::Vector2f(0.0f, cornerSize.y);
	vertexArray[(3 * 4) + 1].position = sf::Vector2f(cornerSize.x, cornerSize.y);
	vertexArray[(3 * 4) + 2].position = sf::Vector2f(cornerSize.x, cornerSize.y + barSize.y);
	vertexArray[(3 * 4) + 3].position = sf::Vector2f(0.0f, cornerSize.y + barSize.y);
	vertexArray[(3 * 4) + 0].texCoords = sf::Vector2f(textureRect.left, textureRect.top + cornerSize.y);
	vertexArray[(3 * 4) + 1].texCoords = sf::Vector2f(textureRect.left + cornerSize.x, textureRect.top + cornerSize.y);
	vertexArray[(3 * 4) + 2].texCoords = sf::Vector2f(textureRect.left + cornerSize.x, textureRect.top + textureRect.height - cornerSize.y);
	vertexArray[(3 * 4) + 3].texCoords = sf::Vector2f(textureRect.left, textureRect.top + textureRect.height - cornerSize.y);

	//Centre
	vertexArray[(4 * 4) + 0].position = sf::Vector2f(cornerSize.x, cornerSize.y);
	vertexArray[(4 * 4) + 1].position = sf::Vector2f(cornerSize.x + barSize.x, cornerSize.y);
	vertexArray[(4 * 4) + 2].position = sf::Vector2f(cornerSize.x + barSize.x, cornerSize.y + barSize.y);
	vertexArray[(4 * 4) + 3].position = sf::Vector2f(cornerSize.x, cornerSize.y + barSize.y);
	vertexArray[(4 * 4) + 0].texCoords = sf::Vector2f(textureRect.left + cornerSize.x, textureRect.top + cornerSize.y);
	vertexArray[(4 * 4) + 1].texCoords = sf::Vector2f(textureRect.left + textureRect.width - cornerSize.x, textureRect.top + cornerSize.y);
	vertexArray[(4 * 4) + 2].texCoords = sf::Vector2f(textureRect.left + textureRect.width - cornerSize.x, textureRect.top + textureRect.height - cornerSize.y);
	vertexArray[(4 * 4) + 3].texCoords = sf::Vector2f(textureRect.left + cornerSize.x, textureRect.top + textureRect.height - cornerSize.y);

	//Right Bar
	vertexArray[(5 * 4) + 0].position = sf::Vector2f(Size.x - cornerSize.x, cornerSize.y);
	vertexArray[(5 * 4) + 1].position = sf::Vector2f(Size.x, cornerSize.y);
	vertexArray[(5 * 4) + 2].position = sf::Vector2f(Size.x, cornerSize.y + barSize.y);
	vertexArray[(5 * 4) + 3].position = sf::Vector2f(Size.x - cornerSize.x, cornerSize.y + barSize.y);
	vertexArray[(5 * 4) + 0].texCoords = sf::Vector2f(textureRect.left + textureRect.width - cornerSize.x, textureRect.top + cornerSize.y);
	vertexArray[(5 * 4) + 1].texCoords = sf::Vector2f(textureRect.left + textureRect.width, textureRect.top + cornerSize.y);
	vertexArray[(5 * 4) + 2].texCoords = sf::Vector2f(textureRect.left + textureRect.width, textureRect.top + textureRect.height - cornerSize.y);
	vertexArray[(5 * 4) + 3].texCoords = sf::Vector2f(textureRect.left + textureRect.width - cornerSize.x, textureRect.top + textureRect.height - cornerSize.y);

	//Bottom Left Corner
	vertexArray[(6 * 4) + 0].position = sf::Vector2f(0.0f, Size.y - cornerSize.y);
	vertexArray[(6 * 4) + 1].position = sf::Vector2f(cornerSize.x, Size.y - cornerSize.y);
	vertexArray[(6 * 4) + 2].position = sf::Vector2f(cornerSize.x, Size.y);
	vertexArray[(6 * 4) + 3].position = sf::Vector2f(0.0f, Size.y);
	vertexArray[(6 * 4) + 0].texCoords = sf::Vector2f(textureRect.left, textureRect.top + textureRect.height - cornerSize.y);
	vertexArray[(6 * 4) + 1].texCoords = sf::Vector2f(textureRect.left + cornerSize.x, textureRect.top + textureRect.height - cornerSize.y);
	vertexArray[(6 * 4) + 2].texCoords = sf::Vector2f(textureRect.left + cornerSize.x, textureRect.top + textureRect.height);
	vertexArray[(6 * 4) + 3].texCoords = sf::Vector2f(textureRect.left, textureRect.top + textureRect.height);

	//Bottom Bar
	vertexArray[(7 * 4) + 0].position = sf::Vector2f(cornerSize.x, Size.y - cornerSize.y);
	vertexArray[(7 * 4) + 1].position = sf::Vector2f(cornerSize.x + barSize.x, Size.y - cornerSize.y);
	vertexArray[(7 * 4) + 2].position = sf::Vector2f(cornerSize.x + barSize.x, Size.y);
	vertexArray[(7 * 4) + 3].position = sf::Vector2f(cornerSize.x, Size.y);
	vertexArray[(7 * 4) + 0].texCoords = sf::Vector2f(textureRect.left + cornerSize.x, textureRect.top + textureRect.height - cornerSize.y);
	vertexArray[(7 * 4) + 1].texCoords = sf::Vector2f(textureRect.left + textureRect.width - cornerSize.x, textureRect.top + textureRect.height - cornerSize.y);
	vertexArray[(7 * 4) + 2].texCoords = sf::Vector2f(textureRect.left + textureRect.width - cornerSize.x, textureRect.top + textureRect.height);
	vertexArray[(7 * 4) + 3].texCoords = sf::Vector2f(textureRect.left + cornerSize.x, textureRect.top + textureRect.height);

	//Bottom Right Corner
	vertexArray[(8 * 4) + 0].position = sf::Vector2f(Size.x - cornerSize.x, Size.y - cornerSize.y);
	vertexArray[(8 * 4) + 1].position = sf::Vector2f(Size.x, Size.y - cornerSize.y);
	vertexArray[(8 * 4) + 2].position = sf::Vector2f(Size.x, Size.y);
	vertexArray[(8 * 4) + 3].position = sf::Vector2f(Size.x - cornerSize.x, Size.y);
	vertexArray[(8 * 4) + 0].texCoords = sf::Vector2f(textureRect.left + textureRect.width - cornerSize.x, textureRect.top + textureRect.height - cornerSize.y);
	vertexArray[(8 * 4) + 1].texCoords = sf::Vector2f(textureRect.left + textureRect.width, textureRect.top + textureRect.height - cornerSize.y);
	vertexArray[(8 * 4) + 2].texCoords = sf::Vector2f(textureRect.left + textureRect.width, textureRect.top + textureRect.height);
	vertexArray[(8 * 4) + 3].texCoords = sf::Vector2f(textureRect.left + textureRect.width - cornerSize.x, textureRect.top + textureRect.height);
}

V9Slice::V9Slice(sf::Vector2f Position, sf::Vector2f Size, const sf::String& Filename, const sf::Vector2f& Corner) : VObject(Position, Size)
{
	vertexArray.setPrimitiveType(sf::Quads);
	vertexArray.resize(4 * 9);

	if (Filename != "")
		LoadGraphic(Filename, Corner);

#if _DEBUG
	DebugColor = sf::Color(0, 255, 0, 128);
#endif
}

V9Slice::V9Slice(float x, float y, float width, float height, const sf::String& Filename, const sf::Vector2f& Corner) : VObject(x, y, width, height)
{
	vertexArray.setPrimitiveType(sf::Quads);
	vertexArray.resize(4 * 9);

	if (Filename != "")
		LoadGraphic(Filename, Corner);

#if _DEBUG
	DebugColor = sf::Color(0, 255, 0, 128);
#endif
}

V9Slice* V9Slice::LoadGraphic(const sf::String& filename, const sf::Vector2f& corner, const sf::IntRect& rect)
{
	renderState.texture = &VGlobal::p()->Content->LoadTexture(filename);
	cornerSize = corner;
	textureRect = rect == sf::IntRect() ? sf::IntRect(sf::Vector2i(), sf::Vector2i(renderState.texture->getSize())) : rect;

	return this;
}

V9Slice* V9Slice::LoadGraphicFromTexture(sf::Texture& texture, const sf::Vector2f& corner, const sf::IntRect& rect)
{
	renderState.texture = &texture;
	cornerSize = corner;
	textureRect = rect == sf::IntRect() ? sf::IntRect(sf::Vector2i(), sf::Vector2i(renderState.texture->getSize())) : rect;

	return this;
}

void V9Slice::Draw(sf::RenderTarget& RenderTarget)
{
	VSUPERCLASS::Draw(RenderTarget);

	updateFrame();

	sf::View renderTargetView = RenderTarget.getView();
	sf::View scrollView = RenderTarget.getDefaultView();

	if (TestInView(renderTargetView, &scrollView, this, renderState.transform.transformRect(vertexArray.getBounds())))
	{
		RenderTarget.setView(scrollView);
		RenderTarget.draw(vertexArray, renderState);
		RenderTarget.setView(renderTargetView);
	}
}
<commit_msg>Float casting<commit_after>#include "V9Slice.h"
#include "VGlobal.h"

void V9Slice::updateTransform()
{
	sf::Vector2f origin = sf::Vector2f(Origin.x * Size.x, Origin.y * Size.y);

	float angle = -Angle * VFRAME_PI / 180.f;
	float cosine = static_cast<float>(std::cos(angle));
	float sine = static_cast<float>(std::sin(angle));
	float sxc = Scale.x * cosine;
	float syc = Scale.y * cosine;
	float sxs = Scale.x * sine;
	float sys = Scale.y * sine;
	float tx = -Origin.x * sxc - Origin.y * sys + (Position + origin).x;
	float ty = Origin.x * sxs - Origin.y * syc + (Position + origin).y;

	renderState.transform =
		sf::Transform(sxc, sys, tx,
			-sxs, syc, ty,
			0.f, 0.f, 1.f);

	if (vertexArray[0].color != Tint)
	{
		for (unsigned int i = 0; i < vertexArray.getVertexCount(); i++)
			vertexArray[i].color = Tint;
	}
}

void V9Slice::updateFrame()
{
	Size.x = Size.x < cornerSize.x * 2 ? cornerSize.x * 2 : Size.x;
	Size.y = Size.y < cornerSize.y * 2 ? cornerSize.y * 2 : Size.y;

	sf::Vector2f barSize = Size - (cornerSize * 2.0f);

	//1 2
	//0 3

	//Top Left Corner
	vertexArray[(0 * 4) + 0].position = sf::Vector2f();
	vertexArray[(0 * 4) + 1].position = sf::Vector2f(cornerSize.x, 0.0f);
	vertexArray[(0 * 4) + 2].position = sf::Vector2f(cornerSize.x, cornerSize.y);
	vertexArray[(0 * 4) + 3].position = sf::Vector2f(0.0f, cornerSize.y);
	vertexArray[(0 * 4) + 0].texCoords = sf::Vector2f((float)textureRect.left, (float)textureRect.top);
	vertexArray[(0 * 4) + 1].texCoords = sf::Vector2f((float)textureRect.left + cornerSize.x, (float)textureRect.top);
	vertexArray[(0 * 4) + 2].texCoords = sf::Vector2f((float)textureRect.left + cornerSize.x, (float)textureRect.top + cornerSize.y);
	vertexArray[(0 * 4) + 3].texCoords = sf::Vector2f((float)textureRect.left, (float)textureRect.top + cornerSize.y);

	//Top Bar
	vertexArray[(1 * 4) + 0].position = sf::Vector2f(cornerSize.x, 0.0f);
	vertexArray[(1 * 4) + 1].position = sf::Vector2f(cornerSize.x + barSize.x, 0.0f);
	vertexArray[(1 * 4) + 2].position = sf::Vector2f(cornerSize.x + barSize.x, cornerSize.y);
	vertexArray[(1 * 4) + 3].position = sf::Vector2f(cornerSize.x, cornerSize.y);
	vertexArray[(1 * 4) + 0].texCoords = sf::Vector2f((float)textureRect.left + cornerSize.x, (float)textureRect.top);
	vertexArray[(1 * 4) + 1].texCoords = sf::Vector2f((float)textureRect.left + textureRect.width - cornerSize.x, (float)textureRect.top);
	vertexArray[(1 * 4) + 2].texCoords = sf::Vector2f((float)textureRect.left + textureRect.width - cornerSize.x, (float)textureRect.top + cornerSize.y);
	vertexArray[(1 * 4) + 3].texCoords = sf::Vector2f((float)textureRect.left + cornerSize.x, (float)textureRect.top + cornerSize.y);

	//Top Right Corner
	vertexArray[(2 * 4) + 0].position = sf::Vector2f(Size.x - cornerSize.x, 0.0f);
	vertexArray[(2 * 4) + 1].position = sf::Vector2f(Size.x, 0.0f);
	vertexArray[(2 * 4) + 2].position = sf::Vector2f(Size.x, cornerSize.y);
	vertexArray[(2 * 4) + 3].position = sf::Vector2f(Size.x - cornerSize.x, cornerSize.y);
	vertexArray[(2 * 4) + 0].texCoords = sf::Vector2f((float)textureRect.left + textureRect.width - cornerSize.x, (float)textureRect.top);
	vertexArray[(2 * 4) + 1].texCoords = sf::Vector2f((float)textureRect.left + textureRect.width, (float)textureRect.top);
	vertexArray[(2 * 4) + 2].texCoords = sf::Vector2f((float)textureRect.left + textureRect.width, (float)textureRect.top + cornerSize.y);
	vertexArray[(2 * 4) + 3].texCoords = sf::Vector2f((float)textureRect.left + textureRect.width - cornerSize.x, (float)textureRect.top + cornerSize.y);

	//Left Bar
	vertexArray[(3 * 4) + 0].position = sf::Vector2f(0.0f, cornerSize.y);
	vertexArray[(3 * 4) + 1].position = sf::Vector2f(cornerSize.x, cornerSize.y);
	vertexArray[(3 * 4) + 2].position = sf::Vector2f(cornerSize.x, cornerSize.y + barSize.y);
	vertexArray[(3 * 4) + 3].position = sf::Vector2f(0.0f, cornerSize.y + barSize.y);
	vertexArray[(3 * 4) + 0].texCoords = sf::Vector2f((float)textureRect.left, (float)textureRect.top + cornerSize.y);
	vertexArray[(3 * 4) + 1].texCoords = sf::Vector2f((float)textureRect.left + cornerSize.x, (float)textureRect.top + cornerSize.y);
	vertexArray[(3 * 4) + 2].texCoords = sf::Vector2f((float)textureRect.left + cornerSize.x, (float)textureRect.top + textureRect.height - cornerSize.y);
	vertexArray[(3 * 4) + 3].texCoords = sf::Vector2f((float)textureRect.left, (float)textureRect.top + textureRect.height - cornerSize.y);

	//Centre
	vertexArray[(4 * 4) + 0].position = sf::Vector2f(cornerSize.x, cornerSize.y);
	vertexArray[(4 * 4) + 1].position = sf::Vector2f(cornerSize.x + barSize.x, cornerSize.y);
	vertexArray[(4 * 4) + 2].position = sf::Vector2f(cornerSize.x + barSize.x, cornerSize.y + barSize.y);
	vertexArray[(4 * 4) + 3].position = sf::Vector2f(cornerSize.x, cornerSize.y + barSize.y);
	vertexArray[(4 * 4) + 0].texCoords = sf::Vector2f((float)textureRect.left + cornerSize.x, (float)textureRect.top + cornerSize.y);
	vertexArray[(4 * 4) + 1].texCoords = sf::Vector2f((float)textureRect.left + textureRect.width - cornerSize.x, (float)textureRect.top + cornerSize.y);
	vertexArray[(4 * 4) + 2].texCoords = sf::Vector2f((float)textureRect.left + textureRect.width - cornerSize.x, (float)textureRect.top + textureRect.height - cornerSize.y);
	vertexArray[(4 * 4) + 3].texCoords = sf::Vector2f((float)textureRect.left + cornerSize.x, (float)textureRect.top + textureRect.height - cornerSize.y);

	//Right Bar
	vertexArray[(5 * 4) + 0].position = sf::Vector2f(Size.x - cornerSize.x, cornerSize.y);
	vertexArray[(5 * 4) + 1].position = sf::Vector2f(Size.x, cornerSize.y);
	vertexArray[(5 * 4) + 2].position = sf::Vector2f(Size.x, cornerSize.y + barSize.y);
	vertexArray[(5 * 4) + 3].position = sf::Vector2f(Size.x - cornerSize.x, cornerSize.y + barSize.y);
	vertexArray[(5 * 4) + 0].texCoords = sf::Vector2f((float)textureRect.left + textureRect.width - cornerSize.x, (float)textureRect.top + cornerSize.y);
	vertexArray[(5 * 4) + 1].texCoords = sf::Vector2f((float)textureRect.left + textureRect.width, (float)textureRect.top + cornerSize.y);
	vertexArray[(5 * 4) + 2].texCoords = sf::Vector2f((float)textureRect.left + textureRect.width, (float)textureRect.top + textureRect.height - cornerSize.y);
	vertexArray[(5 * 4) + 3].texCoords = sf::Vector2f((float)textureRect.left + textureRect.width - cornerSize.x, (float)textureRect.top + textureRect.height - cornerSize.y);

	//Bottom Left Corner
	vertexArray[(6 * 4) + 0].position = sf::Vector2f(0.0f, Size.y - cornerSize.y);
	vertexArray[(6 * 4) + 1].position = sf::Vector2f(cornerSize.x, Size.y - cornerSize.y);
	vertexArray[(6 * 4) + 2].position = sf::Vector2f(cornerSize.x, Size.y);
	vertexArray[(6 * 4) + 3].position = sf::Vector2f(0.0f, Size.y);
	vertexArray[(6 * 4) + 0].texCoords = sf::Vector2f((float)textureRect.left, (float)textureRect.top + textureRect.height - cornerSize.y);
	vertexArray[(6 * 4) + 1].texCoords = sf::Vector2f((float)textureRect.left + cornerSize.x, (float)textureRect.top + textureRect.height - cornerSize.y);
	vertexArray[(6 * 4) + 2].texCoords = sf::Vector2f((float)textureRect.left + cornerSize.x, (float)textureRect.top + textureRect.height);
	vertexArray[(6 * 4) + 3].texCoords = sf::Vector2f((float)textureRect.left, (float)textureRect.top + textureRect.height);

	//Bottom Bar
	vertexArray[(7 * 4) + 0].position = sf::Vector2f(cornerSize.x, Size.y - cornerSize.y);
	vertexArray[(7 * 4) + 1].position = sf::Vector2f(cornerSize.x + barSize.x, Size.y - cornerSize.y);
	vertexArray[(7 * 4) + 2].position = sf::Vector2f(cornerSize.x + barSize.x, Size.y);
	vertexArray[(7 * 4) + 3].position = sf::Vector2f(cornerSize.x, Size.y);
	vertexArray[(7 * 4) + 0].texCoords = sf::Vector2f((float)textureRect.left + cornerSize.x, (float)textureRect.top + textureRect.height - cornerSize.y);
	vertexArray[(7 * 4) + 1].texCoords = sf::Vector2f((float)textureRect.left + textureRect.width - cornerSize.x, (float)textureRect.top + textureRect.height - cornerSize.y);
	vertexArray[(7 * 4) + 2].texCoords = sf::Vector2f((float)textureRect.left + textureRect.width - cornerSize.x, (float)textureRect.top + textureRect.height);
	vertexArray[(7 * 4) + 3].texCoords = sf::Vector2f((float)textureRect.left + cornerSize.x, (float)textureRect.top + textureRect.height);

	//Bottom Right Corner
	vertexArray[(8 * 4) + 0].position = sf::Vector2f(Size.x - cornerSize.x, Size.y - cornerSize.y);
	vertexArray[(8 * 4) + 1].position = sf::Vector2f(Size.x, Size.y - cornerSize.y);
	vertexArray[(8 * 4) + 2].position = sf::Vector2f(Size.x, Size.y);
	vertexArray[(8 * 4) + 3].position = sf::Vector2f(Size.x - cornerSize.x, Size.y);
	vertexArray[(8 * 4) + 0].texCoords = sf::Vector2f((float)textureRect.left + textureRect.width - cornerSize.x, (float)textureRect.top + textureRect.height - cornerSize.y);
	vertexArray[(8 * 4) + 1].texCoords = sf::Vector2f((float)textureRect.left + textureRect.width, (float)textureRect.top + textureRect.height - cornerSize.y);
	vertexArray[(8 * 4) + 2].texCoords = sf::Vector2f((float)textureRect.left + textureRect.width, (float)textureRect.top + textureRect.height);
	vertexArray[(8 * 4) + 3].texCoords = sf::Vector2f((float)textureRect.left + textureRect.width - cornerSize.x, (float)textureRect.top + textureRect.height);
}

V9Slice::V9Slice(sf::Vector2f Position, sf::Vector2f Size, const sf::String& Filename, const sf::Vector2f& Corner) : VObject(Position, Size)
{
	vertexArray.setPrimitiveType(sf::Quads);
	vertexArray.resize(4 * 9);

	if (Filename != "")
		LoadGraphic(Filename, Corner);

#if _DEBUG
	DebugColor = sf::Color(0, 255, 0, 128);
#endif
}

V9Slice::V9Slice(float x, float y, float width, float height, const sf::String& Filename, const sf::Vector2f& Corner) : VObject(x, y, width, height)
{
	vertexArray.setPrimitiveType(sf::Quads);
	vertexArray.resize(4 * 9);

	if (Filename != "")
		LoadGraphic(Filename, Corner);

#if _DEBUG
	DebugColor = sf::Color(0, 255, 0, 128);
#endif
}

V9Slice* V9Slice::LoadGraphic(const sf::String& filename, const sf::Vector2f& corner, const sf::IntRect& rect)
{
	renderState.texture = &VGlobal::p()->Content->LoadTexture(filename);
	cornerSize = corner;
	textureRect = rect == sf::IntRect() ? sf::IntRect(sf::Vector2i(), sf::Vector2i(renderState.texture->getSize())) : rect;

	return this;
}

V9Slice* V9Slice::LoadGraphicFromTexture(sf::Texture& texture, const sf::Vector2f& corner, const sf::IntRect& rect)
{
	renderState.texture = &texture;
	cornerSize = corner;
	textureRect = rect == sf::IntRect() ? sf::IntRect(sf::Vector2i(), sf::Vector2i(renderState.texture->getSize())) : rect;

	return this;
}

void V9Slice::Draw(sf::RenderTarget& RenderTarget)
{
	VSUPERCLASS::Draw(RenderTarget);

	updateFrame();

	sf::View renderTargetView = RenderTarget.getView();
	sf::View scrollView = RenderTarget.getDefaultView();

	if (TestInView(renderTargetView, &scrollView, this, renderState.transform.transformRect(vertexArray.getBounds())))
	{
		RenderTarget.setView(scrollView);
		RenderTarget.draw(vertexArray, renderState);
		RenderTarget.setView(renderTargetView);
	}
}
<|endoftext|>


<commit_before>#ifndef __VIDEO_PROCESSOR_HPP__
#define __VIDEO_PROCESSOR_HPP__

#include "opencv2/video/tracking.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/highgui/highgui.hpp"

#include <iostream>

using namespace cv;
using namespace std;

struct VideoProcessor
{

    VideoProcessor(VideoCapture &Frames, string WindowName)
    :   frames(Frames),
        wndname(WindowName),
        rotate(0.0),
        scale(1),
        paused(true),
        quit(false),
        selecting(false),
        frameCount(0)
    {
        namedWindow(wndname.c_str(), CV_WINDOW_AUTOSIZE);
        setMouseCallback(wndname.c_str(), on_mouse, this);
    }

    virtual ~VideoProcessor()
    {
    }

    // Applies scaling or rotational transformation to input movie.
    void SetTransform(int Rotate, int Scale)
    {
        rotate = Rotate;
        scale = Scale;
    }

    // Sets an initial selection window to select target region.
    void SetSelection(const Rect &Selection)
    {
        selection = Selection;
    }

    void Play(bool Paused)
    {
        paused = Paused;

        quit = !next_frame();
        if (!quit)
        {
            process_frame(image);

            if (selection.height > 0 && selection.width > 0)
            {
                region_selected(selection);
            }

            imshow( wndname.c_str(), image );
        }

        while ( !quit )
        {
            if (!paused)
            {
                process_frame(image);
                imshow(wndname.c_str(), image);
                quit = !next_frame();
            }

            char c = (char)waitKey(10);

            switch (c)
            {
            case 'p':
                paused = !paused;
                process_frame(image);
                break ;

            case 27:
                quit = true;
                break ;

            default:
                break ;
            }

        }

    }

    void pause()
    {
        paused = true;
    }

    void select(int x, int y, bool StartStop)
    {
        if (selecting)
        {
            Mat roi(image, selection);
            bitwise_not(roi, roi);

            selection.width = std::abs(x - selection.x);
            selection.height = std::abs(y - selection.y);

            roi = Mat(image, selection);
            bitwise_not(roi, roi);

            imshow(wndname.c_str(), image);
        }

        if (StartStop)
        {
            if (!selecting)
            {
                selection.x = x;
                selection.y = y;
                selection.width = 1;
                selection.height = 1;
            }
            else
            {
                if (selection.area() > 16)
                {
                    cout << "Region selected x=" << selection.x << " y=" << selection.y
                         << " h=" << selection.height << " w=" << selection.width << endl;

                    region_selected(selection);
                }
                else
                {
                    cout << "Slection area not big enough to track." << endl;
                }

                Mat roi(image, selection);

                bitwise_not(roi, roi);
                imshow(wndname.c_str(), image);
            }

            selecting = !selecting;
        }
    }

protected:

    virtual void process_frame(Mat image)
    {
    }

    virtual void region_selected(const Rect &Selection)
    {
    }

    int             frameCount;

private:

    VideoCapture    &frames;
    string          wndname;
    Mat             image;      // Current frame image.
    double          rotate;
    int             scale;
    bool            paused;
    bool            quit;
    bool            selecting;
    Rect            selection;

    bool next_frame()
    {
        bool    empty;
        Mat     frame;

        frameCount++;

        frames >> frame;
        empty = frame.empty();
        if (!empty)
        {
            frame.copyTo(image);

            if (rotate != 0.0)
            {
                Point2f src_center(image.cols/2.0F, image.rows/2.0F);
                Mat     rot_mat;

                rot_mat = getRotationMatrix2D(src_center, rotate, 1.0);
                warpAffine(image, image, rot_mat, image.size());
            }

            resize(image, image, Size(image.cols/scale, image.rows/scale));
        }

        return !empty;
    }

    static void on_mouse(int event, int x, int y, int, void *arg)
    {
        VideoProcessor    *vidstream = (VideoProcessor*)arg;

        switch (event)
        {
        case CV_EVENT_LBUTTONDOWN:
            //vidstream->select(x, y, SELECTING_START);
            break;
        case CV_EVENT_LBUTTONUP:
            vidstream->select(x, y, true);
            break;
        default:
            vidstream->select(x, y, false);
            break;

        }
    }

};

#endif
<commit_msg>Fix double process_frame on pause press<commit_after>#ifndef __VIDEO_PROCESSOR_HPP__
#define __VIDEO_PROCESSOR_HPP__

#include "opencv2/video/tracking.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/highgui/highgui.hpp"

#include <iostream>

using namespace cv;
using namespace std;

struct VideoProcessor
{

    VideoProcessor(VideoCapture &Frames, string WindowName)
    :   frames(Frames),
        wndname(WindowName),
        rotate(0.0),
        scale(1),
        paused(true),
        quit(false),
        selecting(false),
        frameCount(0)
    {
        namedWindow(wndname.c_str(), CV_WINDOW_AUTOSIZE);
        setMouseCallback(wndname.c_str(), on_mouse, this);
    }

    virtual ~VideoProcessor()
    {
    }

    // Applies scaling or rotational transformation to input movie.
    void SetTransform(int Rotate, int Scale)
    {
        rotate = Rotate;
        scale = Scale;
    }

    // Sets an initial selection window to select target region.
    void SetSelection(const Rect &Selection)
    {
        selection = Selection;
    }

    void Play(bool Paused)
    {
        paused = Paused;

        quit = !next_frame();
        if (!quit)
        {
            process_frame(image);

            if (selection.height > 0 && selection.width > 0)
            {
                region_selected(selection);
            }

            imshow( wndname.c_str(), image );
        }

        while ( !quit )
        {
            if (!paused)
            {
                process_frame(image);
                imshow(wndname.c_str(), image);
                quit = !next_frame();
            }

            char c = (char)waitKey(10);

            switch (c)
            {
            case 'p':
                paused = !paused;
                break ;

            case 27:
                quit = true;
                break ;

            default:
                break ;
            }

        }

    }

    void pause()
    {
        paused = true;
    }

    void select(int x, int y, bool StartStop)
    {
        if (selecting)
        {
            Mat roi(image, selection);
            bitwise_not(roi, roi);

            selection.width = std::abs(x - selection.x);
            selection.height = std::abs(y - selection.y);

            roi = Mat(image, selection);
            bitwise_not(roi, roi);

            imshow(wndname.c_str(), image);
        }

        if (StartStop)
        {
            if (!selecting)
            {
                selection.x = x;
                selection.y = y;
                selection.width = 1;
                selection.height = 1;
            }
            else
            {
                if (selection.area() > 16)
                {
                    cout << "Region selected x=" << selection.x << " y=" << selection.y
                         << " h=" << selection.height << " w=" << selection.width << endl;

                    region_selected(selection);
                }
                else
                {
                    cout << "Slection area not big enough to track." << endl;
                }

                Mat roi(image, selection);

                bitwise_not(roi, roi);
                imshow(wndname.c_str(), image);
            }

            selecting = !selecting;
        }
    }

protected:

    virtual void process_frame(Mat image)
    {
    }

    virtual void region_selected(const Rect &Selection)
    {
    }

    int             frameCount;

private:

    VideoCapture    &frames;
    string          wndname;
    Mat             image;      // Current frame image.
    double          rotate;
    int             scale;
    bool            paused;
    bool            quit;
    bool            selecting;
    Rect            selection;

    bool next_frame()
    {
        bool    empty;
        Mat     frame;

        frameCount++;

        frames >> frame;
        empty = frame.empty();
        if (!empty)
        {
            frame.copyTo(image);

            if (rotate != 0.0)
            {
                Point2f src_center(image.cols/2.0F, image.rows/2.0F);
                Mat     rot_mat;

                rot_mat = getRotationMatrix2D(src_center, rotate, 1.0);
                warpAffine(image, image, rot_mat, image.size());
            }

            resize(image, image, Size(image.cols/scale, image.rows/scale));
        }

        return !empty;
    }

    static void on_mouse(int event, int x, int y, int, void *arg)
    {
        VideoProcessor    *vidstream = (VideoProcessor*)arg;

        switch (event)
        {
        case CV_EVENT_LBUTTONDOWN:
            //vidstream->select(x, y, SELECTING_START);
            break;
        case CV_EVENT_LBUTTONUP:
            vidstream->select(x, y, true);
            break;
        default:
            vidstream->select(x, y, false);
            break;

        }
    }

};

#endif
<|endoftext|>


<commit_before>#include "IFaceManager.h"

////////////////////////////////////////
CIFaceManager::~CIFaceManager()
{
}
////////////////////////////////////////

CIFaceManager::CIFaceManager()
{
	IFaces[gameFactory].name = "CreateInterfaceFn gameFactory";
	IFaces[interfaceFactory].name = "CreateInterfaceFn interfaceFactory";
	IFaces[EngineServer].name = "VEngineServer";
	IFaces[EventManager2].name = "GAMEEVENTSMANAGER";
	IFaces[PlayerInfoManager].name = "PlayerInfoManager";
	IFaces[ServerPluginHelpers].name = "ISERVERPLUGINHELPERS";
	IFaces[GameDLL].name = "ServerGameDLL";
	IFaces[GameEnts].name = "ServerGameEnts";
	IFaces[GameClients].name = "ServerGameClients";
	IFaces[Trace].name = "EngineTraceServer";

#ifdef NCZ_CSS
	IFaces[EngineServer].compiled_version = 23;
	IFaces[EventManager2].compiled_version = 2;
	IFaces[PlayerInfoManager].compiled_version = 2;
	IFaces[ServerPluginHelpers].compiled_version = 1;
	IFaces[GameDLL].compiled_version = 10;
	IFaces[GameEnts].compiled_version = 1;
	IFaces[GameClients].compiled_version = 4;
	IFaces[Trace].compiled_version = 3;
#endif // NCZ_CSS

	IFaces[gameFactory].factory = gameFactory;
	IFaces[interfaceFactory].factory = interfaceFactory;
	IFaces[EngineServer].factory = interfaceFactory;
	IFaces[EventManager2].factory = interfaceFactory;
	IFaces[PlayerInfoManager].factory = gameFactory;
	IFaces[ServerPluginHelpers].factory = interfaceFactory;
	IFaces[GameDLL].factory = gameFactory;
	IFaces[GameEnts].factory = gameFactory;
	IFaces[GameClients].factory = gameFactory;
	IFaces[Trace].factory = interfaceFactory;

	for(int x = 0; x < INTERFACES_COUNT; ++x)
	{
		IFaces[x].version = 0;
		IFaces[x].IFacePtr = nullptr;
	}
}

ptr CIFaceManager::_GetIFacePtr(IFaceIndex Index) const
{
	return IFaces[Index].IFacePtr;
}

const char * CIFaceManager::_GetIFaceName(IFaceIndex Index) const
{
	return IFaces[Index].name;
}

ptr CIFaceManager::_GetFactoryPtr(IFactoryIndex Index) const
{
	return IFaces[Index].IFacePtr;
}

ptr CIFaceManager::_GetIFaceFactoryPtr(IFaceIndex Index) const
{
	return _GetFactoryPtr(IFaces[Index].factory);
}

void CIFaceManager::_UpdateIFacePtr(IFaceIndex Index, ptr newPtr)
{
	IFaces[Index].IFacePtr = newPtr;
}

void CIFaceManager::UpdateIFactoryPtr(IFactoryIndex Index, ptr newPtr)
{
	Msg("[NoCheatZ 4] CIFaceManager - Info : Registering %s at %x.\n", IFaces[Index].name, newPtr);
	IFaces[Index].IFacePtr = newPtr;

#ifdef IFACEMANAGER_AUTOINIT
	if(IFaces[interfaceFactory].IFacePtr && IFaces[gameFactory].IFacePtr)
	{
		for(int x = EngineServer; x <= Trace; x++)
		{
			if(IFaces[x].IFacePtr != nullptr) continue;
			if(x == Globals) continue;

			ptr pIFace = nullptr;
			CreateInterfaceFn Factory = reinterpret_cast<CreateInterfaceFn>(_GetFactoryPtr(IFaces[x].factory));

			int i_v = 40;
			char s_v[64];
			while ( !pIFace )
			{
				--i_v;
				if(i_v == 0)
				{
					pIFace = nullptr;
					break;
				}
				if(i_v < 10)
				{
					sprintf(s_v, "%s00%d\0", IFaces[x].name, i_v);
				}
				else if(i_v > 9)
				{
					sprintf(s_v, "%s0%d\0", IFaces[x].name, i_v);
				}
				pIFace = (ptr)Factory(s_v, nullptr);
			}
			IFaces[x].version = i_v;
			IFaces[x].IFacePtr = pIFace;
			Msg("[NoCheatZ 4] CIFaceManager - Info : Registering interface %s at %x.\n", s_v, IFaces[x].IFacePtr);
			if(IFaces[x].version != IFaces[x].compiled_version) Msg("CIFaceManager - Warning : Using other version of interface %s.\n", IFaces[x].name);
		}
		if(this->GetIplayers() && IFaces[Globals].IFacePtr == nullptr)
		{
			Msg("[NoCheatZ 4] CIFaceManager - Info : Registering GlobalVars at %x.\n", this->GetIplayers()->GetGlobalVars());
			IFaces[Globals].IFacePtr = this->GetIplayers()->GetGlobalVars();
		}

	}
#endif
}

void CIFaceManager::_UpdateIFaceName(IFaceIndex Index, const char * name)
{
	IFaces[Index].name = name;
}

#ifndef IFACEMANAGER_AUTOINIT
ptr CIFaceManager::GetIFace(IFaceIndex Index)
{
	ptr pIFace = nullptr;
	CreateInterfaceFn Factory = reinterpret_cast<CreateInterfaceFn>(_GetIFaceFactoryPtr(Index));
	if(_GetIFacePtr(Index) != nullptr) return _GetIFacePtr(Index);

	int i_v = 40;
	char s_v[64];
	while ( !pIFace )
	{
		--i_v;
		if(i_v < 0)
		{
			return nullptr;
		}
		if(i_v < 10)
		{
			sMsg(s_v, "%s00%d", IFaces[Index].name, i_v);
		}
		else if(i_v > 9)
		{
			sMsg(s_v, "%s0%d", IFaces[Index].name, i_v);
		}
		pIFace = (ptr)Factory(s_v, nullptr);
	}
	IFaces[Index].version = i_v;
	_UpdateIFacePtr(Index, pIFace);
	return pIFace;
}

IVEngineServer* CIFaceManager::GetIengine()
{
	return reinterpret_cast<IVEngineServer*>(GetIFace(IFaceIndex::EngineServer));
}

IGameEventManager2* CIFaceManager::GetIevents()
{
	return reinterpret_cast<IGameEventManager2*>(GetIFace(IFaceIndex::EventManager2));
}

IPlayerInfoManager* CIFaceManager::GetIplayers()
{
	return reinterpret_cast<IPlayerInfoManager*>(GetIFace(IFaceIndex::PlayerInfoManager));
}

IServerPluginHelpers* CIFaceManager::GetIpluginhelpers()
{
	return reinterpret_cast<IServerPluginHelpers*>(GetIFace(IFaceIndex::ServerPluginHelpers));
}

IServerGameDLL* CIFaceManager::GetIgamedll()
{
	return reinterpret_cast<IServerGameDLL*>(GetIFace(IFaceIndex::GameDLL));
}

IEngineTrace* CIFaceManager::GetItrace()
{
	return reinterpret_cast<IEngineTrace*>(GetIFace(IFaceIndex::Trace));
}

IServerGameEnts* CIFaceManager::GetIents()
{
	return reinterpret_cast<IServerGameEnts*>(GetIFace(IFaceIndex::GameEnts));
}

IServerGameClients* CIFaceManager::GetIclients()
{
	return reinterpret_cast<IServerGameClients*>(GetIFace(IFaceIndex::GameClients));
}

CGlobalVars* CIFaceManager::GetGlobals()
{
	if((ptr)(GetIFace(IFaceIndex::Globals))) return reinterpret_cast<CGlobalVars*>(GetIFace(IFaceIndex::Globals));
	if((ptr)(GetIFace(IFaceIndex::PlayerInfoManager)))
	{
		if(GetIplayers()->GetGlobalVars())
		{
			_UpdateIFacePtr(IFaceIndex::Globals, GetIplayers()->GetGlobalVars());
			return GetIplayers()->GetGlobalVars();
		}
	}
	return nullptr;
}

#else

ptr CIFaceManager::GetIFace(IFaceIndex Index) const
{
	return _GetIFacePtr(Index);
}

IVEngineServer* CIFaceManager::GetIengine() const
{
	return reinterpret_cast<IVEngineServer*>(GetIFace(EngineServer));
}

IGameEventManager2* CIFaceManager::GetIevents() const
{
	return reinterpret_cast<IGameEventManager2*>(GetIFace(EventManager2));
}

IPlayerInfoManager* CIFaceManager::GetIplayers() const
{
	return reinterpret_cast<IPlayerInfoManager*>(GetIFace(PlayerInfoManager));
}

IServerPluginHelpers* CIFaceManager::GetIpluginhelpers() const
{
	return reinterpret_cast<IServerPluginHelpers*>(GetIFace(ServerPluginHelpers));
}

IServerGameDLL* CIFaceManager::GetIgamedll() const
{
	return reinterpret_cast<IServerGameDLL*>(GetIFace(GameDLL));
}

IEngineTrace* CIFaceManager::GetItrace() const
{
	return reinterpret_cast<IEngineTrace*>(GetIFace(Trace));
}

IServerGameEnts* CIFaceManager::GetIents() const
{
	return reinterpret_cast<IServerGameEnts*>(GetIFace(GameEnts));
}

IServerGameClients* CIFaceManager::GetIclients() const
{
	return reinterpret_cast<IServerGameClients*>(GetIFace(GameClients));
}

CGlobalVars* CIFaceManager::GetGlobals() const
{
	return reinterpret_cast<CGlobalVars*>(GetIFace(Globals));
}

#endif

<commit_msg>Using version integers from the sdk headers by default<commit_after>#include "IFaceManager.h"

////////////////////////////////////////
CIFaceManager::~CIFaceManager()
{
}
////////////////////////////////////////

CIFaceManager::CIFaceManager()
{
	IFaces[gameFactory].name = "CreateInterfaceFn gameFactory";
	IFaces[interfaceFactory].name = "CreateInterfaceFn interfaceFactory";
	IFaces[EngineServer].name = "VEngineServer";
	IFaces[EventManager2].name = "GAMEEVENTSMANAGER";
	IFaces[PlayerInfoManager].name = "PlayerInfoManager";
	IFaces[ServerPluginHelpers].name = "ISERVERPLUGINHELPERS";
	IFaces[GameDLL].name = "ServerGameDLL";
	IFaces[GameEnts].name = "ServerGameEnts";
	IFaces[GameClients].name = "ServerGameClients";
	IFaces[Trace].name = "EngineTraceServer";

	IFaces[EngineServer].compiled_version = INTERFACEVERSION_VENGINESERVER_INT;
	IFaces[EventManager2].compiled_version = INTERFACEVERSION_GAMEEVENTSMANAGER2_INT;
	IFaces[PlayerInfoManager].compiled_version = INTERFACEVERSION_PLAYERINFOMANAGER_INT;
	IFaces[ServerPluginHelpers].compiled_version = INTERFACEVERSION_PLUGINHELPERSCHECK_INT;
	IFaces[GameDLL].compiled_version = INTERFACEVERSION_SERVERGAMEDLL_INT;
	IFaces[GameEnts].compiled_version = INTERFACEVERSION_SERVERGAMEENTS_INT;
	IFaces[GameClients].compiled_version = INTERFACEVERSION_SERVERGAMECLIENTS_INT;
	IFaces[Trace].compiled_version = INTERFACEVERSION_ENGINETRACE_SERVER_INT;

	IFaces[gameFactory].factory = gameFactory;
	IFaces[interfaceFactory].factory = interfaceFactory;
	IFaces[EngineServer].factory = interfaceFactory;
	IFaces[EventManager2].factory = interfaceFactory;
	IFaces[PlayerInfoManager].factory = gameFactory;
	IFaces[ServerPluginHelpers].factory = interfaceFactory;
	IFaces[GameDLL].factory = gameFactory;
	IFaces[GameEnts].factory = gameFactory;
	IFaces[GameClients].factory = gameFactory;
	IFaces[Trace].factory = interfaceFactory;

	for(int x = 0; x < INTERFACES_COUNT; ++x)
	{
		IFaces[x].version = 0;
		IFaces[x].IFacePtr = nullptr;
	}
}

ptr CIFaceManager::_GetIFacePtr(IFaceIndex Index) const
{
	return IFaces[Index].IFacePtr;
}

const char * CIFaceManager::_GetIFaceName(IFaceIndex Index) const
{
	return IFaces[Index].name;
}

ptr CIFaceManager::_GetFactoryPtr(IFactoryIndex Index) const
{
	return IFaces[Index].IFacePtr;
}

ptr CIFaceManager::_GetIFaceFactoryPtr(IFaceIndex Index) const
{
	return _GetFactoryPtr(IFaces[Index].factory);
}

void CIFaceManager::_UpdateIFacePtr(IFaceIndex Index, ptr newPtr)
{
	IFaces[Index].IFacePtr = newPtr;
}

void CIFaceManager::UpdateIFactoryPtr(IFactoryIndex Index, ptr newPtr)
{
	Msg("[NoCheatZ 4] CIFaceManager - Info : Registering %s at %x.\n", IFaces[Index].name, newPtr);
	IFaces[Index].IFacePtr = newPtr;

#ifdef IFACEMANAGER_AUTOINIT
	if(IFaces[interfaceFactory].IFacePtr && IFaces[gameFactory].IFacePtr)
	{
		for(int x = EngineServer; x <= Trace; x++)
		{
			if(IFaces[x].IFacePtr != nullptr) continue;
			if(x == Globals) continue;

			ptr pIFace = nullptr;
			CreateInterfaceFn Factory = reinterpret_cast<CreateInterfaceFn>(_GetFactoryPtr(IFaces[x].factory));

			int i_v = 40;
			char s_v[64];
			while ( !pIFace )
			{
				--i_v;
				if(i_v == 0)
				{
					pIFace = nullptr;
					break;
				}
				if(i_v < 10)
				{
					sprintf(s_v, "%s00%d\0", IFaces[x].name, i_v);
				}
				else if(i_v > 9)
				{
					sprintf(s_v, "%s0%d\0", IFaces[x].name, i_v);
				}
				pIFace = (ptr)Factory(s_v, nullptr);
			}
			IFaces[x].version = i_v;
			IFaces[x].IFacePtr = pIFace;
			Msg("[NoCheatZ 4] CIFaceManager - Info : Registering interface %s at %x.\n", s_v, IFaces[x].IFacePtr);
			if(IFaces[x].version != IFaces[x].compiled_version) Msg("CIFaceManager - Warning : Using other version of interface %s.\n", IFaces[x].name);
		}
		if(this->GetIplayers() && IFaces[Globals].IFacePtr == nullptr)
		{
			Msg("[NoCheatZ 4] CIFaceManager - Info : Registering GlobalVars at %x.\n", this->GetIplayers()->GetGlobalVars());
			IFaces[Globals].IFacePtr = this->GetIplayers()->GetGlobalVars();
		}

	}
#endif
}

void CIFaceManager::_UpdateIFaceName(IFaceIndex Index, const char * name)
{
	IFaces[Index].name = name;
}

#ifndef IFACEMANAGER_AUTOINIT
ptr CIFaceManager::GetIFace(IFaceIndex Index)
{
	ptr pIFace = nullptr;
	CreateInterfaceFn Factory = reinterpret_cast<CreateInterfaceFn>(_GetIFaceFactoryPtr(Index));
	if(_GetIFacePtr(Index) != nullptr) return _GetIFacePtr(Index);

	int i_v = 40;
	char s_v[64];
	while ( !pIFace )
	{
		--i_v;
		if(i_v < 0)
		{
			return nullptr;
		}
		if(i_v < 10)
		{
			sMsg(s_v, "%s00%d", IFaces[Index].name, i_v);
		}
		else if(i_v > 9)
		{
			sMsg(s_v, "%s0%d", IFaces[Index].name, i_v);
		}
		pIFace = (ptr)Factory(s_v, nullptr);
	}
	IFaces[Index].version = i_v;
	_UpdateIFacePtr(Index, pIFace);
	return pIFace;
}

IVEngineServer* CIFaceManager::GetIengine()
{
	return reinterpret_cast<IVEngineServer*>(GetIFace(IFaceIndex::EngineServer));
}

IGameEventManager2* CIFaceManager::GetIevents()
{
	return reinterpret_cast<IGameEventManager2*>(GetIFace(IFaceIndex::EventManager2));
}

IPlayerInfoManager* CIFaceManager::GetIplayers()
{
	return reinterpret_cast<IPlayerInfoManager*>(GetIFace(IFaceIndex::PlayerInfoManager));
}

IServerPluginHelpers* CIFaceManager::GetIpluginhelpers()
{
	return reinterpret_cast<IServerPluginHelpers*>(GetIFace(IFaceIndex::ServerPluginHelpers));
}

IServerGameDLL* CIFaceManager::GetIgamedll()
{
	return reinterpret_cast<IServerGameDLL*>(GetIFace(IFaceIndex::GameDLL));
}

IEngineTrace* CIFaceManager::GetItrace()
{
	return reinterpret_cast<IEngineTrace*>(GetIFace(IFaceIndex::Trace));
}

IServerGameEnts* CIFaceManager::GetIents()
{
	return reinterpret_cast<IServerGameEnts*>(GetIFace(IFaceIndex::GameEnts));
}

IServerGameClients* CIFaceManager::GetIclients()
{
	return reinterpret_cast<IServerGameClients*>(GetIFace(IFaceIndex::GameClients));
}

CGlobalVars* CIFaceManager::GetGlobals()
{
	if((ptr)(GetIFace(IFaceIndex::Globals))) return reinterpret_cast<CGlobalVars*>(GetIFace(IFaceIndex::Globals));
	if((ptr)(GetIFace(IFaceIndex::PlayerInfoManager)))
	{
		if(GetIplayers()->GetGlobalVars())
		{
			_UpdateIFacePtr(IFaceIndex::Globals, GetIplayers()->GetGlobalVars());
			return GetIplayers()->GetGlobalVars();
		}
	}
	return nullptr;
}

#else

ptr CIFaceManager::GetIFace(IFaceIndex Index) const
{
	return _GetIFacePtr(Index);
}

IVEngineServer* CIFaceManager::GetIengine() const
{
	return reinterpret_cast<IVEngineServer*>(GetIFace(EngineServer));
}

IGameEventManager2* CIFaceManager::GetIevents() const
{
	return reinterpret_cast<IGameEventManager2*>(GetIFace(EventManager2));
}

IPlayerInfoManager* CIFaceManager::GetIplayers() const
{
	return reinterpret_cast<IPlayerInfoManager*>(GetIFace(PlayerInfoManager));
}

IServerPluginHelpers* CIFaceManager::GetIpluginhelpers() const
{
	return reinterpret_cast<IServerPluginHelpers*>(GetIFace(ServerPluginHelpers));
}

IServerGameDLL* CIFaceManager::GetIgamedll() const
{
	return reinterpret_cast<IServerGameDLL*>(GetIFace(GameDLL));
}

IEngineTrace* CIFaceManager::GetItrace() const
{
	return reinterpret_cast<IEngineTrace*>(GetIFace(Trace));
}

IServerGameEnts* CIFaceManager::GetIents() const
{
	return reinterpret_cast<IServerGameEnts*>(GetIFace(GameEnts));
}

IServerGameClients* CIFaceManager::GetIclients() const
{
	return reinterpret_cast<IServerGameClients*>(GetIFace(GameClients));
}

CGlobalVars* CIFaceManager::GetGlobals() const
{
	return reinterpret_cast<CGlobalVars*>(GetIFace(Globals));
}

#endif

<|endoftext|>


<commit_before>#include "btcwif.h"

#include <cassert>

#include <ecdsa/base58.h>

#include "utils.h"

namespace btc {
namespace wif {

std::string PrivateKeyToWif(const std::vector<uint8_t> &priv_key) {
  // 0. Preparing...
  std::vector<uint8_t> pk2(priv_key.size() + 1);

  // 1. 0x80 to front.
  pk2[0] = 0x80;
  memcpy(pk2.data() + 1, priv_key.data(), priv_key.size());

  // 2. 0x01 to back.
  pk2.push_back(0x01);

  // 3. Perform SHA256 on extended key.
  std::vector<uint8_t> check_sum_half = utils::sha256(pk2.data(), pk2.size());
  std::vector<uint8_t> check_sum =
      utils::sha256(check_sum_half.data(), check_sum_half.size());

  // 4. Add 4 bytes from check sum to pk2.
  std::vector<uint8_t> pk4(pk2.size() + 4);
  memcpy(pk4.data(), pk2.data(), pk2.size());
  memcpy(pk4.data() + pk2.size(), check_sum.data(), 4);

  // 5. Base58
  return base58::EncodeBase58(pk4);
}

std::vector<uint8_t> WifToPrivateKey(const std::string &priv_key_str) {
  // 1. Revert base58 to data.
  std::vector<uint8_t> pk1;
  assert(base58::DecodeBase58(priv_key_str, pk1));

  // 2. Calculate size.
  size_t size;
  size_t add_index = pk1.size() - 4;
  if (pk1[add_index] == 0x01) {
    size = pk1.size() - 6;
  } else {
    size = pk1.size() - 5;
  }

  // 3. Remove first 1 byte, last 4 byte(s) and
  // last 1 byte if it equals to 0x01.
  std::vector<uint8_t> pk2(size);
  memcpy(pk2.data(), pk1.data() + 1, size);

  return pk2;
}

}  // namespace wif
}  // namespace btc
<commit_msg>Fix comment format.<commit_after>#include "btcwif.h"

#include <cassert>

#include <ecdsa/base58.h>

#include "utils.h"

namespace btc {
namespace wif {

std::string PrivateKeyToWif(const std::vector<uint8_t> &priv_key) {
  // 0. Preparing...
  std::vector<uint8_t> pk2(priv_key.size() + 1);

  // 1. 0x80 to front.
  pk2[0] = 0x80;
  memcpy(pk2.data() + 1, priv_key.data(), priv_key.size());

  // 2. 0x01 to back.
  pk2.push_back(0x01);

  // 3. Perform SHA256 on extended key.
  std::vector<uint8_t> check_sum_half = utils::sha256(pk2.data(), pk2.size());
  std::vector<uint8_t> check_sum =
      utils::sha256(check_sum_half.data(), check_sum_half.size());

  // 4. Add 4 bytes from check sum to pk2.
  std::vector<uint8_t> pk4(pk2.size() + 4);
  memcpy(pk4.data(), pk2.data(), pk2.size());
  memcpy(pk4.data() + pk2.size(), check_sum.data(), 4);

  // 5. Base58
  return base58::EncodeBase58(pk4);
}

std::vector<uint8_t> WifToPrivateKey(const std::string &priv_key_str) {
  // 1. Revert base58 to data.
  std::vector<uint8_t> pk1;
  assert(base58::DecodeBase58(priv_key_str, pk1));

  // 2. Calculate size.
  size_t size;
  size_t add_index = pk1.size() - 4;
  if (pk1[add_index] == 0x01) {
    size = pk1.size() - 6;
  } else {
    size = pk1.size() - 5;
  }

  // 3. Remove first 1 byte, last 4 byte(s) and
  //   last 1 byte if it equals to 0x01.
  std::vector<uint8_t> pk2(size);
  memcpy(pk2.data(), pk1.data() + 1, size);

  return pk2;
}

}  // namespace wif
}  // namespace btc
<|endoftext|>