<commit_before>#include "Tensor.hpp"
#include <string>
#include <algorithm>
#include <numeric>
#include <cassert>

mlopenTensorDescriptor::mlopenTensorDescriptor() {}

mlopenTensorDescriptor::mlopenTensorDescriptor(mlopenDataType_t t, const int* plens, int size)
: type(t), lens(plens, plens+size)
{
	this->CalculateStrides();
}
mlopenTensorDescriptor::mlopenTensorDescriptor(mlopenDataType_t t, const int* plens, const int* pstrides, int size)
: type(t), lens(plens, plens+size), strides(pstrides, pstrides+size)
{}

void mlopenTensorDescriptor::CalculateStrides()
{
	strides.clear();
	strides.resize(lens.size(), 0);
	strides.back() = 1;
	std::partial_sum(lens.rbegin(), lens.rend()-1, strides.rbegin()+1, std::multiplies<int>());
}

const std::vector<int>& mlopenTensorDescriptor::GetLengths() const
{
	return lens;
}
const std::vector<int>& mlopenTensorDescriptor::GetStrides() const
{
	return strides;
}
int mlopenTensorDescriptor::GetSize() const
{
	assert(lens.size() == strides.size());
	return lens.size();
}
mlopenDataType_t mlopenTensorDescriptor::GetType() const
{
	return this->type;
}

int mlopenTensorDescriptor::GetIndex(std::initializer_list<int> l) const
{
	assert(l.size() <= this->GetSize());
	return std::inner_product(l.begin(), l.end(), strides.begin(), 0);
}

bool mlopenTensorDescriptor::operator==(const mlopenTensorDescriptor& rhs) const
{
	assert(this->lens.size() == rhs.strides.size());
	return this->type == rhs.type and this->lens == rhs.lens and this->strides == rhs.strides;
}

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

int mlopenGetTensorIndex(mlopenTensorDescriptor_t tensorDesc, std::initializer_list<int> indices)
{
	return tensorDesc->GetIndex(indices);
}
<commit_msg>fixed and and not to make it run on MS VS<commit_after>#include "Tensor.hpp"
#include <string>
#include <algorithm>
#include <numeric>
#include <cassert>

mlopenTensorDescriptor::mlopenTensorDescriptor() {}

mlopenTensorDescriptor::mlopenTensorDescriptor(mlopenDataType_t t, const int* plens, int size)
: type(t), lens(plens, plens+size)
{
	this->CalculateStrides();
}
mlopenTensorDescriptor::mlopenTensorDescriptor(mlopenDataType_t t, const int* plens, const int* pstrides, int size)
: type(t), lens(plens, plens+size), strides(pstrides, pstrides+size)
{}

void mlopenTensorDescriptor::CalculateStrides()
{
	strides.clear();
	strides.resize(lens.size(), 0);
	strides.back() = 1;
	std::partial_sum(lens.rbegin(), lens.rend()-1, strides.rbegin()+1, std::multiplies<int>());
}

const std::vector<int>& mlopenTensorDescriptor::GetLengths() const
{
	return lens;
}
const std::vector<int>& mlopenTensorDescriptor::GetStrides() const
{
	return strides;
}
int mlopenTensorDescriptor::GetSize() const
{
	assert(lens.size() == strides.size());
	return lens.size();
}
mlopenDataType_t mlopenTensorDescriptor::GetType() const
{
	return this->type;
}

int mlopenTensorDescriptor::GetIndex(std::initializer_list<int> l) const
{
	assert(l.size() <= this->GetSize());
	return std::inner_product(l.begin(), l.end(), strides.begin(), 0);
}

bool mlopenTensorDescriptor::operator==(const mlopenTensorDescriptor& rhs) const
{
	assert(this->lens.size() == rhs.strides.size());
	return this->type == rhs.type && this->lens == rhs.lens && this->strides == rhs.strides;
}

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

int mlopenGetTensorIndex(mlopenTensorDescriptor_t tensorDesc, std::initializer_list<int> indices)
{
	return tensorDesc->GetIndex(indices);
}
<|endoftext|>


<commit_before>#include "Ticket.h"

Ticket::Ticket(string event, string username, int ticketNumber, double cost) {
	this->event = event;
	this->username = username;
	this->ticketNumber = ticketNumber;
	this->cost = cost;
}

Ticket::~Ticket() {
	delete event;
	delete username;
	delete ticketNumber;
	delete cost;
}

string Ticket::getEvent() {
    return this->event;
}

void Ticket::setEvent(string event) {
    this->event = event;
}

string Ticket::getUsername() {
    return this->username;
}

void Ticket::setUsername(string userName) {
    this->username = userName;
}

int Ticket::getTicketNumber() {
    return this->ticketNumber;
}

void Ticket::setTicketNumber(int ticketNumber) {
    this->ticketNumber = ticketNumber;
}

double Ticket::getCost() {
    return this->cost;
}

void Ticket::setCost(double cost) {
    this->cost = cost;
}

void Ticket::decreaseTicketNumber(int ticketNumber) {
	this->ticketNumber -= ticketNumber;
}
<commit_msg>FIXED: No need to delete strings. http://stackoverflow.com/questions/2365624/should-i-delete-the-string-members-of-a-c-class<commit_after>#include "Ticket.h"

Ticket::Ticket(string event, string username, int ticketNumber, double cost) {
	this->event = event;
	this->username = username;
	this->ticketNumber = ticketNumber;
	this->cost = cost;
}

// http://stackoverflow.com/questions/2365624/should-i-delete-the-string-members-of-a-c-class
Ticket::~Ticket() {
	// delete event;
	// delete username;
	// delete ticketNumber;
	// delete cost;
}

string Ticket::getEvent() {
    return this->event;
}

void Ticket::setEvent(string event) {
    this->event = event;
}

string Ticket::getUsername() {
    return this->username;
}

void Ticket::setUsername(string userName) {
    this->username = userName;
}

int Ticket::getTicketNumber() {
    return this->ticketNumber;
}

void Ticket::setTicketNumber(int ticketNumber) {
    this->ticketNumber = ticketNumber;
}

double Ticket::getCost() {
    return this->cost;
}

void Ticket::setCost(double cost) {
    this->cost = cost;
}

void Ticket::decreaseTicketNumber(int ticketNumber) {
	this->ticketNumber -= ticketNumber;
}
<|endoftext|>


<commit_before>#pragma ident "$Id$"
//============================================================================
//
//  This file is part of GPSTk, the GPS Toolkit.
//
//  The GPSTk is free software; you can redistribute it and/or modify
//  it under the terms of the GNU Lesser General Public License as published
//  by the Free Software Foundation; either version 2.1 of the License, or
//  any later version.
//
//  The GPSTk is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//  GNU Lesser General Public License for more details.
//
//  You should have received a copy of the GNU Lesser General Public
//  License along with GPSTk; if not, write to the Free Software Foundation,
//  Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
//
//  Dagoberto Salazar - gAGE. 2007
//
//============================================================================

#ifndef GPSTK_TYPEID_HPP
#define GPSTK_TYPEID_HPP

#include <iostream>
#include <iomanip>
#include <sstream>
#include <string>
#include <map>
#include "RinexObsHeader.hpp"

/**
 * @file TypeID.hpp
 * gpstk::TypeID - This class was written taking as inspiration ObsID. The
   objective of this class is to create an index able to represent any type
   of observation, correction, model parameter or other data value of interest
   for GNSS data processing. This class is extensible in run-time, so the
   programmer may add indexes on-demand.
 */

namespace gpstk
{

   /**
    * This class creates an index able to represent any type of observation,
    * correction, model parameter or other data value of interest for GNSS
    * data processing.
    */

   class TypeID
   {
   public:
      /// The type of the data value.
      enum ValueType
      {
         Unknown,
         // Observation-related types
         C1,        ///< GPS civil code observation in L1 frequency
         C2,        ///< GPS civil code observation in L2 frequency
         P1,        ///< GPS precise code observation in L1 frequency
         P2,        ///< GPS precise code observation in L2 frequency
         L1,        ///< GPS phase observation in L1 frequency
         L2,        ///< GPS phase observation in L2 frequency
         D1,        ///< GPS doppler observation in L1 frequency
         D2,        ///< GPS doppler observation in L2 frequency
         S1,        ///< GPS signal strength observation in L1 frequency
         S2,        ///< GPS signal strength observation in L2 frequency
         T1,        ///< Transit integrated doppler observation in L1 frequency
         T2,        ///< Transit integrated doppler observation in L2 frequency
         SSI1,      ///< Signal strength indicator/index, L1 frequency
         LLI1,      ///< Loss of Lock Indicator/ lock count, L1 frequency
         SSI2,      ///< Signal strength indicator/index, L2 frequency
         LLI2,      ///< Loss of Lock Indicator/ lock count, L2 frequency
         // v 2.11
         C5,        ///< GPS L5C-code pseudorange
         L5,        ///< GPS phase observation in L5 frequency
         D5,        ///< GPS doppler observation in L5 frequency
         S5,        ///< GPS signal strength observation in L5 frequency
         SSI5,      ///< Signal strength indicator/index, L5 frequency
         LLI5,      ///< Loss of Lock Indicator/ lock count, L5 frequency
         // Galileo-related
         C6,        ///< Galileo E6-code pseudorange
         L6,        ///< Galileo phase observation in L6 frequency
         D6,        ///< Galileo doppler observation in L6 frequency
         S6,        ///< Galileo signal strength observation in L6 frequency
         SSI6,      ///< Signal strength indicator/index, L6 frequency
         LLI6,      ///< Loss of Lock Indicator/ lock count, L6 frequency
         C7,        ///< Galileo E5b-code pseudorange
         L7,        ///< Galileo phase observation in L5b frequency
         D7,        ///< Galileo doppler observation in L5b frequency
         S7,        ///< Galileo signal strength observation in L5b frequency
         SSI7,      ///< Signal strength indicator/index, L5b frequency
         LLI7,      ///< Loss of Lock Indicator/ lock count, L5b frequency
         C8,        ///< Galileo E5a+b-code pseudorange
         L8,        ///< Galileo phase observation in L5a+b frequency
         D8,        ///< Galileo doppler observation in L5a+b frequency
         S8,        ///< Galileo signal strength observation in L5a+b frequency
         SSI8,      ///< Signal strength indicator/index, L5a+b frequency
         LLI8,      ///< Loss of Lock Indicator/ lock count, L5a+b frequency
         // Combination-related types
         PC,        ///< Code-based ionosphere-free combination
         LC,        ///< Phase-based ionosphere-free combination
         PI,        ///< Code-based ionospheric combination
         LI,        ///< Phase-based ionospheric combination
         Pdelta,    ///< Narrow-lane combination
         Ldelta,    ///< Wide-lane combination
         // Model-related types
         rho,       ///< Geometric distance satellite-receiver
         dtSat,     ///< Satellite clock offset
         rel,       ///< Relativistic delay
         tropo,     ///< Vertical tropospheric delay, total
         dryTropo,  ///< Vertical tropospheric delay, dry component
         wetTropo,  ///< Vertical tropospheric delay, wet component
         tropoSlant, ///< Slant tropospheric delay, total
         iono,      ///< Vertical ionospheric delay
         ionoSlant, ///< Slant ionospheric delay
         inst,      ///< Instrumental delay
         MP,        ///< Multipath bias
         windUp,    ///< Wind-up effect
         B,         ///< Phase ambiguity
         elevation, ///< Satellite elevation
         azimuth,   ///< Satellite azimuth
         // Equation system-related types
         PR,        ///< Prefit residual
         rhoX,      ///< Unit vector from satellite to receiver, X component
         rhoY,      ///< Unit vector from satellite to receiver, Y component
         rhoZ,      ///< Unit vector from satellite to receiver, Z component
         dX,        ///< Position bias, X component
         dY,        ///< Position bias, Y component
         dZ,        ///< Position bias, Z component
         dt,        ///< Receiver clock offset
         dLat,      ///< Position bias, Latitude component
         dLon,      ///< Position bias, Longitude component
         dH,        ///< Position bias, Height component
         weight,    ///< Weight assigned to a given observation
         // Other types
         sigma,     ///< Standard deviation
         Last,      ///< used to extend this...
         Placeholder = Last+1000
      };

      /// empty constructor, creates an invalid object
      TypeID()
         : type(Unknown) {};

      /// Explicit constructor
      TypeID(ValueType vt)
         : type(vt) {};

      /// Equality requires all fields to be the same
      virtual bool operator==(const TypeID& right) const
      { return type==right.type; }

      /// This ordering is somewhat arbitrary but is required to be able
      /// to use an TypeID as an index to a std::map. If an application needs
      /// some other ordering, inherit and override this function.
      virtual bool operator<(const TypeID& right) const
      { return type < right.type; }

      bool operator!=(const TypeID& right) const
      { return !(operator==(right)); }

      bool operator>(const TypeID& right) const
      {  return (!operator<(right) && !operator==(right)); }

      bool operator<=(const TypeID& right) const
      { return (operator<(right) || operator==(right)); }

      bool operator>=(const TypeID& right) const
      { return !(operator<(right)); }

      /// Assignment operator
      virtual TypeID operator=(const TypeID& right)
      {
        if ( this == &right ) return (*this);
        (*this).type = right.type;
        return *this;
      }

      /// Convenience output method
      virtual std::ostream& dump(std::ostream& s) const;

      /// Returns true if this is a valid TypeID. Basically just
      /// checks that the enum is defined
      virtual bool isValid() const;

      /// Destructor
      virtual ~TypeID() {}

      static ValueType newValueType(const std::string& s);

      // Field
      /// Type of the value
      ValueType  type;

      static std::map< ValueType, std::string > tStrings;

   public:
      class Initializer
      {
      public:
         Initializer();
      };

      static Initializer TypeIDsingleton;

   }; // class TypeID

   namespace StringUtils
   {
      /// convert this object to a string representation
      std::string asString(const TypeID& p);
   }

   /// stream output for TypeID
   std::ostream& operator<<(std::ostream& s, const TypeID& p);

   /// Conversion from RinexObsType to TypeID
   inline TypeID::ValueType RinexType2TypeID(const RinexObsHeader::RinexObsType& rot)
   {
        if (rot == RinexObsHeader::UN) return TypeID::Unknown;
        if (rot == RinexObsHeader::C1) return TypeID::C1;
        if (rot == RinexObsHeader::C2) return TypeID::C2;
        if (rot == RinexObsHeader::P1) return TypeID::P1;
        if (rot == RinexObsHeader::P2) return TypeID::P2;
        if (rot == RinexObsHeader::L1) return TypeID::L1;
        if (rot == RinexObsHeader::L2) return TypeID::L2;
        if (rot == RinexObsHeader::D1) return TypeID::D1;
        if (rot == RinexObsHeader::D2) return TypeID::D2;
        if (rot == RinexObsHeader::S1) return TypeID::S1;
        if (rot == RinexObsHeader::S2) return TypeID::S2;
        // v 2.11
        if (rot == RinexObsHeader::C5) return TypeID::C5;
        if (rot == RinexObsHeader::L5) return TypeID::L5;
        if (rot == RinexObsHeader::D5) return TypeID::D5;
        if (rot == RinexObsHeader::S5) return TypeID::S5;
        // Galileo-related
        if (rot == RinexObsHeader::C6) return TypeID::C6;
        if (rot == RinexObsHeader::L6) return TypeID::L6;
        if (rot == RinexObsHeader::D6) return TypeID::D6;
        if (rot == RinexObsHeader::S6) return TypeID::S6;
        if (rot == RinexObsHeader::C7) return TypeID::C7;
        if (rot == RinexObsHeader::L7) return TypeID::L7;
        if (rot == RinexObsHeader::D7) return TypeID::D7;
        if (rot == RinexObsHeader::S7) return TypeID::S7;
        if (rot == RinexObsHeader::C8) return TypeID::C8;
        if (rot == RinexObsHeader::L8) return TypeID::L8;
        if (rot == RinexObsHeader::D8) return TypeID::D8;
        if (rot == RinexObsHeader::S8) return TypeID::S8;

        // Just in case, but it should never get this far
        return TypeID::Unknown;
   }

} // namespace gpstk
#endif
<commit_msg>Added TypeID postfit, and prefit identifier was changed.<commit_after>#pragma ident "$Id$"
//============================================================================
//
//  This file is part of GPSTk, the GPS Toolkit.
//
//  The GPSTk is free software; you can redistribute it and/or modify
//  it under the terms of the GNU Lesser General Public License as published
//  by the Free Software Foundation; either version 2.1 of the License, or
//  any later version.
//
//  The GPSTk is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//  GNU Lesser General Public License for more details.
//
//  You should have received a copy of the GNU Lesser General Public
//  License along with GPSTk; if not, write to the Free Software Foundation,
//  Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
//
//  Dagoberto Salazar - gAGE. 2007
//
//============================================================================

#ifndef GPSTK_TYPEID_HPP
#define GPSTK_TYPEID_HPP

#include <iostream>
#include <iomanip>
#include <sstream>
#include <string>
#include <map>
#include "RinexObsHeader.hpp"

/**
 * @file TypeID.hpp
 * gpstk::TypeID - This class was written taking as inspiration ObsID. The
   objective of this class is to create an index able to represent any type
   of observation, correction, model parameter or other data value of interest
   for GNSS data processing. This class is extensible in run-time, so the
   programmer may add indexes on-demand.
 */

namespace gpstk
{

   /**
    * This class creates an index able to represent any type of observation,
    * correction, model parameter or other data value of interest for GNSS
    * data processing.
    */

   class TypeID
   {
   public:
      /// The type of the data value.
      enum ValueType
      {
         Unknown,
         // Observation-related types
         C1,        ///< GPS civil code observation in L1 frequency
         C2,        ///< GPS civil code observation in L2 frequency
         P1,        ///< GPS precise code observation in L1 frequency
         P2,        ///< GPS precise code observation in L2 frequency
         L1,        ///< GPS phase observation in L1 frequency
         L2,        ///< GPS phase observation in L2 frequency
         D1,        ///< GPS doppler observation in L1 frequency
         D2,        ///< GPS doppler observation in L2 frequency
         S1,        ///< GPS signal strength observation in L1 frequency
         S2,        ///< GPS signal strength observation in L2 frequency
         T1,        ///< Transit integrated doppler observation in L1 frequency
         T2,        ///< Transit integrated doppler observation in L2 frequency
         SSI1,      ///< Signal strength indicator/index, L1 frequency
         LLI1,      ///< Loss of Lock Indicator/ lock count, L1 frequency
         SSI2,      ///< Signal strength indicator/index, L2 frequency
         LLI2,      ///< Loss of Lock Indicator/ lock count, L2 frequency
         // v 2.11
         C5,        ///< GPS L5C-code pseudorange
         L5,        ///< GPS phase observation in L5 frequency
         D5,        ///< GPS doppler observation in L5 frequency
         S5,        ///< GPS signal strength observation in L5 frequency
         SSI5,      ///< Signal strength indicator/index, L5 frequency
         LLI5,      ///< Loss of Lock Indicator/ lock count, L5 frequency
         // Galileo-related
         C6,        ///< Galileo E6-code pseudorange
         L6,        ///< Galileo phase observation in L6 frequency
         D6,        ///< Galileo doppler observation in L6 frequency
         S6,        ///< Galileo signal strength observation in L6 frequency
         SSI6,      ///< Signal strength indicator/index, L6 frequency
         LLI6,      ///< Loss of Lock Indicator/ lock count, L6 frequency
         C7,        ///< Galileo E5b-code pseudorange
         L7,        ///< Galileo phase observation in L5b frequency
         D7,        ///< Galileo doppler observation in L5b frequency
         S7,        ///< Galileo signal strength observation in L5b frequency
         SSI7,      ///< Signal strength indicator/index, L5b frequency
         LLI7,      ///< Loss of Lock Indicator/ lock count, L5b frequency
         C8,        ///< Galileo E5a+b-code pseudorange
         L8,        ///< Galileo phase observation in L5a+b frequency
         D8,        ///< Galileo doppler observation in L5a+b frequency
         S8,        ///< Galileo signal strength observation in L5a+b frequency
         SSI8,      ///< Signal strength indicator/index, L5a+b frequency
         LLI8,      ///< Loss of Lock Indicator/ lock count, L5a+b frequency
         // Combination-related types
         PC,        ///< Code-based ionosphere-free combination
         LC,        ///< Phase-based ionosphere-free combination
         PI,        ///< Code-based ionospheric combination
         LI,        ///< Phase-based ionospheric combination
         Pdelta,    ///< Narrow-lane combination
         Ldelta,    ///< Wide-lane combination
         // Model-related types
         rho,       ///< Geometric distance satellite-receiver
         dtSat,     ///< Satellite clock offset
         rel,       ///< Relativistic delay
         tropo,     ///< Vertical tropospheric delay, total
         dryTropo,  ///< Vertical tropospheric delay, dry component
         wetTropo,  ///< Vertical tropospheric delay, wet component
         tropoSlant, ///< Slant tropospheric delay, total
         iono,      ///< Vertical ionospheric delay
         ionoSlant, ///< Slant ionospheric delay
         inst,      ///< Instrumental delay
         MP,        ///< Multipath bias
         windUp,    ///< Wind-up effect
         B,         ///< Phase ambiguity
         elevation, ///< Satellite elevation
         azimuth,   ///< Satellite azimuth
         // Equation system-related types
         prefit,    ///< Prefit residual
         postfit,   ///< Postfit residual
         rhoX,      ///< Unit vector from satellite to receiver, X component
         rhoY,      ///< Unit vector from satellite to receiver, Y component
         rhoZ,      ///< Unit vector from satellite to receiver, Z component
         dX,        ///< Position bias, X component
         dY,        ///< Position bias, Y component
         dZ,        ///< Position bias, Z component
         dt,        ///< Receiver clock offset
         dLat,      ///< Position bias, Latitude component
         dLon,      ///< Position bias, Longitude component
         dH,        ///< Position bias, Height component
         weight,    ///< Weight assigned to a given observation
         // Other types
         sigma,     ///< Standard deviation
         Last,      ///< used to extend this...
         Placeholder = Last+1000
      };

      /// empty constructor, creates an invalid object
      TypeID()
         : type(Unknown) {};

      /// Explicit constructor
      TypeID(ValueType vt)
         : type(vt) {};

      /// Equality requires all fields to be the same
      virtual bool operator==(const TypeID& right) const
      { return type==right.type; }

      /// This ordering is somewhat arbitrary but is required to be able
      /// to use an TypeID as an index to a std::map. If an application needs
      /// some other ordering, inherit and override this function.
      virtual bool operator<(const TypeID& right) const
      { return type < right.type; }

      bool operator!=(const TypeID& right) const
      { return !(operator==(right)); }

      bool operator>(const TypeID& right) const
      {  return (!operator<(right) && !operator==(right)); }

      bool operator<=(const TypeID& right) const
      { return (operator<(right) || operator==(right)); }

      bool operator>=(const TypeID& right) const
      { return !(operator<(right)); }

      /// Assignment operator
      virtual TypeID operator=(const TypeID& right)
      {
        if ( this == &right ) return (*this);
        (*this).type = right.type;
        return *this;
      }

      /// Convenience output method
      virtual std::ostream& dump(std::ostream& s) const;

      /// Returns true if this is a valid TypeID. Basically just
      /// checks that the enum is defined
      virtual bool isValid() const;

      /// Destructor
      virtual ~TypeID() {}

      static ValueType newValueType(const std::string& s);

      // Field
      /// Type of the value
      ValueType  type;

      static std::map< ValueType, std::string > tStrings;

   public:
      class Initializer
      {
      public:
         Initializer();
      };

      static Initializer TypeIDsingleton;

   }; // class TypeID

   namespace StringUtils
   {
      /// convert this object to a string representation
      std::string asString(const TypeID& p);
   }

   /// stream output for TypeID
   std::ostream& operator<<(std::ostream& s, const TypeID& p);

   /// Conversion from RinexObsType to TypeID
   inline TypeID::ValueType RinexType2TypeID(const RinexObsHeader::RinexObsType& rot)
   {
        if (rot == RinexObsHeader::UN) return TypeID::Unknown;
        if (rot == RinexObsHeader::C1) return TypeID::C1;
        if (rot == RinexObsHeader::C2) return TypeID::C2;
        if (rot == RinexObsHeader::P1) return TypeID::P1;
        if (rot == RinexObsHeader::P2) return TypeID::P2;
        if (rot == RinexObsHeader::L1) return TypeID::L1;
        if (rot == RinexObsHeader::L2) return TypeID::L2;
        if (rot == RinexObsHeader::D1) return TypeID::D1;
        if (rot == RinexObsHeader::D2) return TypeID::D2;
        if (rot == RinexObsHeader::S1) return TypeID::S1;
        if (rot == RinexObsHeader::S2) return TypeID::S2;
        // v 2.11
        if (rot == RinexObsHeader::C5) return TypeID::C5;
        if (rot == RinexObsHeader::L5) return TypeID::L5;
        if (rot == RinexObsHeader::D5) return TypeID::D5;
        if (rot == RinexObsHeader::S5) return TypeID::S5;
        // Galileo-related
        if (rot == RinexObsHeader::C6) return TypeID::C6;
        if (rot == RinexObsHeader::L6) return TypeID::L6;
        if (rot == RinexObsHeader::D6) return TypeID::D6;
        if (rot == RinexObsHeader::S6) return TypeID::S6;
        if (rot == RinexObsHeader::C7) return TypeID::C7;
        if (rot == RinexObsHeader::L7) return TypeID::L7;
        if (rot == RinexObsHeader::D7) return TypeID::D7;
        if (rot == RinexObsHeader::S7) return TypeID::S7;
        if (rot == RinexObsHeader::C8) return TypeID::C8;
        if (rot == RinexObsHeader::L8) return TypeID::L8;
        if (rot == RinexObsHeader::D8) return TypeID::D8;
        if (rot == RinexObsHeader::S8) return TypeID::S8;

        // Just in case, but it should never get this far
        return TypeID::Unknown;
   }

} // namespace gpstk
#endif
<|endoftext|>


<commit_before>// Copyright (c) 2016-2020 The Karbowanec developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include "Update.h"
#include "Settings.h"
#include <QApplication>
#include <QDesktopServices>
#include <QJsonDocument>
#include <QMessageBox>
#include <QtNetwork>
#include <QVersionNumber>

using namespace WalletGui;

Updater::Updater(QObject *parent) :
    QObject(parent)
{
}

void Updater::checkForUpdate()
{
    manager = new QNetworkAccessManager(this);
    if(manager->networkAccessible() == QNetworkAccessManager::Accessible)
    {
        connect(manager, SIGNAL(finished(QNetworkReply*)),
                this, SLOT(replyFinished(QNetworkReply*)));
        QNetworkRequest request((QUrl(KARBO_UPDATE_URL)));
        request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
        manager->get(request);
    }
}

void Updater::replyFinished (QNetworkReply *reply)
{
    if(reply->error())
    {
        QString error = QString(tr("Error: %1")).arg(reply->errorString());
        QMessageBox::information(nullptr, tr("Unable to check for update"), error, QMessageBox::Ok);
    }
    else
    {
        QString ourVersionStr = Settings::instance().getVersion().split("-")[0];
        if (ourVersionStr.startsWith(QStringLiteral("v.")))
            ourVersionStr.remove(0, 2);
        else if (ourVersionStr.startsWith('v'))
                 ourVersionStr.remove(0, 1);

        QByteArray response_data = reply->readAll();
        QJsonDocument json = QJsonDocument::fromJson(response_data);

        QString remoteVersionStr = json[0]["name"].toString();
        if (remoteVersionStr.startsWith(QStringLiteral("v.")))
            remoteVersionStr.remove(0, 2);
        else if (remoteVersionStr.startsWith('v'))
                 remoteVersionStr.remove(0, 1);

        int suffixIndex;
        QVersionNumber ourVersion = QVersionNumber::fromString(ourVersionStr, &suffixIndex);
        QVersionNumber remoteVersion = QVersionNumber::fromString(remoteVersionStr, &suffixIndex);

        bool r = QVersionNumber::compare(ourVersion, remoteVersion) < 0;
        if (r) {
             if (QMessageBox::warning(nullptr, QObject::tr("New version available"), QObject::tr("There is an update available.\nDo you want to go to the download page?"), QMessageBox::Ok, QMessageBox::Cancel) == QMessageBox::Ok) {
                 QDesktopServices::openUrl(QUrl(KARBO_DOWNLOAD_URL));
             }
        }
    }
    reply->deleteLater();
}
<commit_msg>Fix failure to build on some systems due to error no match for ‘operator[]’<commit_after>// Copyright (c) 2016-2020 The Karbowanec developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include "Update.h"
#include "Settings.h"
#include <QApplication>
#include <QDesktopServices>
#include <QJsonDocument>
#include <QMessageBox>
#include <QtNetwork>
#include <QVersionNumber>

using namespace WalletGui;

Updater::Updater(QObject *parent) :
    QObject(parent)
{
}

void Updater::checkForUpdate()
{
    manager = new QNetworkAccessManager(this);
    if(manager->networkAccessible() == QNetworkAccessManager::Accessible)
    {
        connect(manager, SIGNAL(finished(QNetworkReply*)),
                this, SLOT(replyFinished(QNetworkReply*)));
        QNetworkRequest request((QUrl(KARBO_UPDATE_URL)));
        request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
        manager->get(request);
    }
}

void Updater::replyFinished (QNetworkReply *reply)
{
    if(reply->error())
    {
        QString error = QString(tr("Error: %1")).arg(reply->errorString());
        QMessageBox::information(nullptr, tr("Unable to check for update"), error, QMessageBox::Ok);
    }
    else
    {
        QString ourVersionStr = Settings::instance().getVersion().split("-")[0];
        if (ourVersionStr.startsWith(QStringLiteral("v.")))
            ourVersionStr.remove(0, 2);
        else if (ourVersionStr.startsWith('v'))
                 ourVersionStr.remove(0, 1);

        QJsonArray jsonArray = QJsonDocument::fromJson(reply->readAll()).array();
        QString remoteVersionStr = jsonArray[0].toObject()["name"].toString();
        if (remoteVersionStr.startsWith(QStringLiteral("v.")))
            remoteVersionStr.remove(0, 2);
        else if (remoteVersionStr.startsWith('v'))
                 remoteVersionStr.remove(0, 1);

        int suffixIndex;
        QVersionNumber ourVersion = QVersionNumber::fromString(ourVersionStr, &suffixIndex);
        QVersionNumber remoteVersion = QVersionNumber::fromString(remoteVersionStr, &suffixIndex);

        bool r = QVersionNumber::compare(ourVersion, remoteVersion) < 0;
        if (r) {
             if (QMessageBox::warning(nullptr, QObject::tr("New version available"), QObject::tr("There is an update available.\nDo you want to go to the download page?"), QMessageBox::Ok, QMessageBox::Cancel) == QMessageBox::Ok) {
                 QDesktopServices::openUrl(QUrl(KARBO_DOWNLOAD_URL));
             }
        }
    }
    reply->deleteLater();
}
<|endoftext|>


<commit_before>#ifndef __NODE_MAPNIK_UTILS_H__
#define __NODE_MAPNIK_UTILS_H__

// v8
#include <v8.h>

// node
#include <node.h>

// stl
#include <string>

// core types
#include <mapnik/unicode.hpp>
#include <mapnik/value.hpp>

// boost
#include <boost/variant/static_visitor.hpp>

#define TOSTR(obj) (*String::Utf8Value((obj)->ToString()))

#define FUNCTION_ARG(I, VAR)                                            \
  if (args.Length() <= (I) || !args[I]->IsFunction())                   \
    return ThrowException(Exception::TypeError(                         \
                  String::New("Argument " #I " must be a function")));  \
  Local<Function> VAR = Local<Function>::Cast(args[I]);

#define ATTR(t, name, get, set) \
  t->InstanceTemplate()->SetAccessor(String::NewSymbol(name), get, set);

using namespace v8;
using namespace node;

namespace node_mapnik {

// adapted to work for both mapnik features and mapnik parameters
struct params_to_object : public boost::static_visitor<>
{
public:
    params_to_object( Local<Object>& ds, std::string key):
        ds_(ds),
        key_(key) {}

    void operator () ( int val )
    {
        ds_->Set(String::NewSymbol(key_.c_str()), Integer::New(val) );
    }

    void operator () ( double val )
    {
        ds_->Set(String::NewSymbol(key_.c_str()), Number::New(val) );
    }

    void operator () ( std::string const& val )
    {

        ds_->Set(String::NewSymbol(key_.c_str()), String::New(val.c_str()) );
    }

    void operator () ( UnicodeString const& val)
    {
        std::string buffer;
        mapnik::to_utf8(val,buffer);
        ds_->Set(String::NewSymbol(key_.c_str()), String::New(buffer.c_str()) );
    }

    void operator () ( mapnik::value_null const& val )
    {
        ds_->Set(String::NewSymbol(key_.c_str()), Undefined() );
    }

private:
    Local<Object>& ds_;
    std::string key_;
};

struct value_converter: public boost::static_visitor<Local<Value> >
{
    Local<Value> operator () ( int val ) const
    {
        return Integer::New(val);
    }

    Local<Value> operator () ( double val ) const
    {
        return Number::New(val);
    }

    Local<Value> operator () ( std::string const& val ) const
    {

        return String::New(val.c_str());
    }

    Local<Value> operator () ( UnicodeString const& val) const
    {
        std::string buffer;
        mapnik::to_utf8(val,buffer);
        return String::New(buffer.c_str());
    }

    Local<Value> operator () ( mapnik::value_null const& val ) const
    {
        return String::New("");//Undefined();
    }
};

}
#endif
<commit_msg>expose proper serialization of boolean types<commit_after>#ifndef __NODE_MAPNIK_UTILS_H__
#define __NODE_MAPNIK_UTILS_H__

// v8
#include <v8.h>

// node
#include <node.h>

// stl
#include <string>

// core types
#include <mapnik/unicode.hpp>
#include <mapnik/value.hpp>

// boost
#include <boost/variant/static_visitor.hpp>

#define TOSTR(obj) (*String::Utf8Value((obj)->ToString()))

#define FUNCTION_ARG(I, VAR)                                            \
  if (args.Length() <= (I) || !args[I]->IsFunction())                   \
    return ThrowException(Exception::TypeError(                         \
                  String::New("Argument " #I " must be a function")));  \
  Local<Function> VAR = Local<Function>::Cast(args[I]);

#define ATTR(t, name, get, set) \
  t->InstanceTemplate()->SetAccessor(String::NewSymbol(name), get, set);

using namespace v8;
using namespace node;

namespace node_mapnik {

// adapted to work for both mapnik features and mapnik parameters
struct params_to_object : public boost::static_visitor<>
{
public:
    params_to_object( Local<Object>& ds, std::string key):
        ds_(ds),
        key_(key) {}

    void operator () ( int val )
    {
        ds_->Set(String::NewSymbol(key_.c_str()), Integer::New(val) );
    }

    void operator () ( bool val )
    {
        ds_->Set(String::NewSymbol(key_.c_str()), Boolean::New(val) );
    }

    void operator () ( double val )
    {
        ds_->Set(String::NewSymbol(key_.c_str()), Number::New(val) );
    }

    void operator () ( std::string const& val )
    {

        ds_->Set(String::NewSymbol(key_.c_str()), String::New(val.c_str()) );
    }

    void operator () ( UnicodeString const& val)
    {
        std::string buffer;
        mapnik::to_utf8(val,buffer);
        ds_->Set(String::NewSymbol(key_.c_str()), String::New(buffer.c_str()) );
    }

    void operator () ( mapnik::value_null const& val )
    {
        ds_->Set(String::NewSymbol(key_.c_str()), Undefined() );
    }

private:
    Local<Object>& ds_;
    std::string key_;
};

struct value_converter: public boost::static_visitor<Local<Value> >
{
    Local<Value> operator () ( int val ) const
    {
        return Integer::New(val);
    }

    Local<Value> operator () ( double val ) const
    {
        return Number::New(val);
    }

    Local<Value> operator () ( std::string const& val ) const
    {

        return String::New(val.c_str());
    }

    Local<Value> operator () ( UnicodeString const& val) const
    {
        std::string buffer;
        mapnik::to_utf8(val,buffer);
        return String::New(buffer.c_str());
    }

    Local<Value> operator () ( mapnik::value_null const& val ) const
    {
        return String::New("");//Undefined();
    }
};

}
#endif
<|endoftext|>


<commit_before>#ifndef _UTILS_H
#define _UTILS_H

namespace utils {
    enum TYPE{
        VAR,
        CTE,
        FUN1,
        FUN2,
        SIZETYPE //sizeof deve ser sempre o último elemento do enum e será
                //utilizado para informar o tamanho do enum.
    };

    enum FUNC1{
        LN,
        EXP,
        SQRT,
        SIN,
        COS,
        TAN,
        SIZEFUNC1
    };

    enum FUNC2{
        ADD,
        SUB,
        MULT,
        DIV,
        POW,
        SIZEFUNC2
    };

    double func1_solver(int F_id, double v);
    double func2_solver(int F_id, double v1, double v2);
    double rad_to_degrees(double v);

    //funções de 2 parâmetros
    double  div(double v1, double v2);
    double  add(double, double);
    double  sub(double v1, double v2);
    double mult(double v1, double v2);
    double  pow(double v1, double v2);

    //funções de 1 parâmetro
    double   sin(double v);
    double   cos(double v);
    double   tan(double v);
    double    ln(double v);
    double   exp(double v);
    double  sqrt(double v);

}
#endif<commit_msg>1.1.1 Renomeamento de funções<commit_after>#ifndef _UTILS_H
#define _UTILS_H

namespace utils {
    enum TYPE{
        VAR,
        CTE,
        FUN1,
        FUN2,
        SIZETYPE //sizeof deve ser sempre o último elemento do enum e será
                //utilizado para informar o tamanho do enum.
    };

    enum FUNC1{
        LN,
        EXP,
        SQRT,
        SIN,
        COS,
        TAN,
        SIZEFUNC1
    };

    enum FUNC2{
        ADD,
        SUB,
        MULT,
        DIV,
        POW,
        SIZEFUNC2
    };

    double func1_solver(int F_id, double v);
    double func2_solver(int F_id, double v1, double v2);
    double rad_to_degrees(double v);

    //funções de 2 parâmetros
    double  uDiv(double v1, double v2);
    double  uAdd(double, double);
    double  uSub(double v1, double v2);
    double uMult(double v1, double v2);
    double  uPow(double v1, double v2);

    //funções de 1 parâmetro
    double   uSin(double v);
    double   uCos(double v);
    double   uTan(double v);
    double    uLn(double v);
    double   uExp(double v);
    double  uSqrt(double v);

}
#endif
<|endoftext|>


<commit_before>#pragma once
#include <bts/db/level_map.hpp>
#include <map>
#include <fc/exception/exception.hpp>
#include <fc/thread/thread.hpp>

namespace bts { namespace db {

   template<typename Key, typename Value, class CacheType = std::map<Key,Value> >
   class cached_level_map
   {
      public:
         void open( const fc::path& dir, bool create = true, bool flush_on_store = true )
         {
           _flush_on_store = flush_on_store;
           _db.open( dir, create );
           for( auto itr = _db.begin(); itr.valid(); ++itr )
              _cache[itr.key()]  = itr.value();
         }

         void close()
         {
            if(_pending_flush.valid() )
               _pending_flush.wait();
            else
               flush();
            _cache.clear();
            _dirty.clear();
            _dirty_remove.clear();
            _db.close();
         }

         bool get_flush_on_store()
         {
            return _flush_on_store;
         }
         void set_flush_on_store( bool should_flush )
         {
            if( should_flush )
               flush();
            _flush_on_store = should_flush;
         }

         void flush()
         {
            // TODO...
            // start batch
            for( auto item : _dirty )
               _db.store( item, _cache[item] );
            for( auto item : _dirty_remove )
               _db.remove( item );
            // end batch
            _dirty.clear();
            _dirty_remove.clear();
         }

        fc::optional<Value> fetch_optional( const Key& k )
        {
           auto itr = _cache.find(k);
           if( itr != _cache.end() ) return itr->second;
           return fc::optional<Value>();
        }

        Value fetch( const Key& key ) const
        { try {
           auto itr = _cache.find(key);
           if( itr != _cache.end() ) return itr->second;
           FC_CAPTURE_AND_THROW( fc::key_not_found_exception, (key) );
        } FC_CAPTURE_AND_RETHROW( (key) ) }

        void store( const Key& key, const Value& value )
        { try {
             _cache[key] = value;
             if( _flush_on_store )
             {
                 _dirty.insert(key);
                 _dirty_remove.erase(key);
                 if( !_pending_flush.valid() || _pending_flush.ready() )
                    _pending_flush = fc::async( [this](){ flush(); }, "cached_level_map::flush" );
                _db.store( key, value );
             } else {
                 _dirty.insert(key);
                 _dirty_remove.erase(key);
             }
        } FC_CAPTURE_AND_RETHROW( (key)(value) ) }

        bool last( Key& k )
        {
           auto ritr = _cache.rbegin();
           if( ritr != _cache.rend() )
           {
              k = ritr->first;
              return true;
           }
           return false;
        }
        bool last( Key& k, Value& v )
        {
           flush();
           return _db.last( k, v );
        }

        void remove( const Key& key )
        { try {
           _cache.erase(key);
           if( _flush_on_store )
           {
              _db.remove(key);
              _dirty.erase(key);
           } else {
              _dirty_remove.insert(key);
           }
        } FC_CAPTURE_AND_RETHROW( (key) ) }

        class iterator
        {
           public:
             iterator(){}
             bool valid()const { return _it != _end; }

             Key   key()const { return _it->first; }
             Value value()const { return _it->second; }

             iterator& operator++()    { ++_it; return *this; }
             iterator  operator++(int) {
                auto backup = *this;
                ++_it;
                return backup;
             }

             iterator& operator--()
             {
                if( _it == _begin )
                   _it = _end;
                else
                   --_it;
                return *this;
             }
             iterator  operator--(int) {
                auto backup = *this;
                operator--();
                return backup;
             }

           protected:
             friend class cached_level_map;
             iterator( typename CacheType::const_iterator it, typename CacheType::const_iterator begin, typename CacheType::const_iterator end )
             :_it(it),_begin(begin),_end(end)
             { }

             typename CacheType::const_iterator _it;
             typename CacheType::const_iterator _begin;
             typename CacheType::const_iterator _end;
        };
        iterator begin()const
        {
           return iterator( _cache.begin(), _cache.begin(), _cache.end() );
        }
        iterator last()
        {
           if( _cache.empty() )
              return iterator( _cache.end(), _cache.begin(), _cache.end() );
           return iterator( --_cache.end(), _cache.begin(), _cache.end() );
        }

        iterator find( const Key& key )
        {
           return iterator( _cache.find(key), _cache.begin(), _cache.end() );
        }
        iterator lower_bound( const Key& key )
        {
           return iterator( _cache.lower_bound(key), _cache.begin(), _cache.end() );
        }

      private:
        CacheType                _cache;
        std::set<Key>            _dirty;
        std::set<Key>            _dirty_remove;
        level_map<Key,Value>     _db;
        bool                     _flush_on_store;
        fc::future<void>         _pending_flush;
   };

} }
<commit_msg>Disable removal caching in cached_level_map for now<commit_after>#pragma once
#include <bts/db/level_map.hpp>
#include <map>
#include <fc/exception/exception.hpp>
#include <fc/thread/thread.hpp>

namespace bts { namespace db {

   template<typename Key, typename Value, class CacheType = std::map<Key,Value> >
   class cached_level_map
   {
      public:
         void open( const fc::path& dir, bool create = true, bool flush_on_store = true )
         {
           _flush_on_store = flush_on_store;
           _db.open( dir, create );
           for( auto itr = _db.begin(); itr.valid(); ++itr )
              _cache[itr.key()]  = itr.value();
         }

         void close()
         {
            if(_pending_flush.valid() )
               _pending_flush.wait();
            else
               flush();
            _cache.clear();
            _dirty.clear();
            _dirty_remove.clear();
            _db.close();
         }

         bool get_flush_on_store()
         {
            return _flush_on_store;
         }
         void set_flush_on_store( bool should_flush )
         {
            if( should_flush )
               flush();
            _flush_on_store = should_flush;
         }

         void flush()
         {
            // TODO...
            // start batch
            for( auto item : _dirty )
               _db.store( item, _cache[item] );
            for( auto item : _dirty_remove )
               _db.remove( item );
            // end batch
            _dirty.clear();
            _dirty_remove.clear();
         }

        fc::optional<Value> fetch_optional( const Key& k )
        {
           auto itr = _cache.find(k);
           if( itr != _cache.end() ) return itr->second;
           return fc::optional<Value>();
        }

        Value fetch( const Key& key ) const
        { try {
           auto itr = _cache.find(key);
           if( itr != _cache.end() ) return itr->second;
           FC_CAPTURE_AND_THROW( fc::key_not_found_exception, (key) );
        } FC_CAPTURE_AND_RETHROW( (key) ) }

        void store( const Key& key, const Value& value )
        { try {
             _cache[key] = value;
             if( _flush_on_store )
             {
                 _dirty.insert(key);
                 _dirty_remove.erase(key);
                 if( !_pending_flush.valid() || _pending_flush.ready() )
                    _pending_flush = fc::async( [this](){ flush(); }, "cached_level_map::flush" );
                _db.store( key, value );
             } else {
                 _dirty.insert(key);
                 _dirty_remove.erase(key);
             }
        } FC_CAPTURE_AND_RETHROW( (key)(value) ) }

        bool last( Key& k )
        {
           auto ritr = _cache.rbegin();
           if( ritr != _cache.rend() )
           {
              k = ritr->first;
              return true;
           }
           return false;
        }
        bool last( Key& k, Value& v )
        {
           flush();
           return _db.last( k, v );
        }

        void remove( const Key& key )
        { try {
           _cache.erase(key);
           //Possibly some bugs in the _dirty_remove logic; disable for now...
            _db.remove(key);
            _dirty.erase(key);
//           if( _flush_on_store )
//           {
//              _db.remove(key);
//              _dirty.erase(key);
//           } else {
//              _dirty_remove.insert(key);
//           }
        } FC_CAPTURE_AND_RETHROW( (key) ) }

        class iterator
        {
           public:
             iterator(){}
             bool valid()const { return _it != _end; }

             Key   key()const { return _it->first; }
             Value value()const { return _it->second; }

             iterator& operator++()    { ++_it; return *this; }
             iterator  operator++(int) {
                auto backup = *this;
                ++_it;
                return backup;
             }

             iterator& operator--()
             {
                if( _it == _begin )
                   _it = _end;
                else
                   --_it;
                return *this;
             }
             iterator  operator--(int) {
                auto backup = *this;
                operator--();
                return backup;
             }

           protected:
             friend class cached_level_map;
             iterator( typename CacheType::const_iterator it, typename CacheType::const_iterator begin, typename CacheType::const_iterator end )
             :_it(it),_begin(begin),_end(end)
             { }

             typename CacheType::const_iterator _it;
             typename CacheType::const_iterator _begin;
             typename CacheType::const_iterator _end;
        };
        iterator begin()const
        {
           return iterator( _cache.begin(), _cache.begin(), _cache.end() );
        }
        iterator last()
        {
           if( _cache.empty() )
              return iterator( _cache.end(), _cache.begin(), _cache.end() );
           return iterator( --_cache.end(), _cache.begin(), _cache.end() );
        }

        iterator find( const Key& key )
        {
           return iterator( _cache.find(key), _cache.begin(), _cache.end() );
        }
        iterator lower_bound( const Key& key )
        {
           return iterator( _cache.lower_bound(key), _cache.begin(), _cache.end() );
        }

      private:
        CacheType                _cache;
        std::set<Key>            _dirty;
        std::set<Key>            _dirty_remove;
        level_map<Key,Value>     _db;
        bool                     _flush_on_store;
        fc::future<void>         _pending_flush;
   };

} }
<|endoftext|>


<commit_before>/*
This file is part of Bohrium and copyright (c) 2012 the Bohrium
team <http://www.bh107.org>.

Bohrium is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as
published by the Free Software Foundation, either version 3
of the License, or (at your option) any later version.

Bohrium is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the
GNU Lesser General Public License along with Bohrium.

If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once

#include <vector>
#include <sstream>
#include <stdexcept>
#include <sys/mman.h>
#include <bh_util.hpp>

namespace bohrium {

class MallocCache {
private:
    struct Segment {
        std::uint64_t nbytes;
        void *mem;
    };
    std::vector<Segment> _segments;
    uint64_t _total_num_bytes = 0;
    uint64_t _total_num_lookups = 0;
    uint64_t _total_num_misses = 0;
    uint64_t _total_mem_allocated = 0;
    uint64_t _max_mem_allocated = 0;

    static constexpr uint64_t MAX_NBYTES = 1000000;

    void *_malloc(uint64_t nbytes) {
        // Allocate page-size aligned memory.
        // The MAP_PRIVATE and MAP_ANONYMOUS flags is not 100% portable. See:
        // <http://stackoverflow.com/questions/4779188/how-to-use-mmap-to-allocate-a-memory-in-heap>
        void *ret = mmap(0, nbytes, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
        if (ret == MAP_FAILED or ret == nullptr) {
            std::stringstream ss;
            ss << "MallocCache() could not allocate a data region. Returned error code: " << strerror(errno);
            throw std::runtime_error(ss.str());
        }
        _total_mem_allocated += nbytes;
        if (_total_mem_allocated > _max_mem_allocated) {
            _max_mem_allocated = _total_mem_allocated;
        }
//        std::cout << "malloc       - nbytes: " << nbytes << ",  addr: " << ret << std::endl;
        return ret;
    }

    void _free(void *mem, uint64_t nbytes) {
//        std::cout << "free         - nbytes: " << nbytes << ",  addr: " << mem << std::endl;
        assert(mem != nullptr);
        if (munmap(mem, nbytes) != 0) {
            std::stringstream ss;
            ss << "MallocCache() could not free a data region. " << "Returned error code: " << strerror(errno);
            throw std::runtime_error(ss.str());
        }
        assert(_max_mem_allocated >= nbytes);
        _total_mem_allocated -= nbytes;
    }

    void _erase(std::vector<Segment>::iterator first,
                std::vector<Segment>::iterator last, bool call_free) {
        for (auto it = first; it != last; ++it) {
            if (call_free) {
                _free(it->mem, it->nbytes);
            }
            _total_num_bytes -= it->nbytes;
        }
        _segments.erase(first, last);
    }

    void _erase(std::vector<Segment>::iterator position, bool call_free) {
        _erase(position, std::next(position), call_free);
    }

    void _erase(std::vector<Segment>::reverse_iterator position, bool call_free) {
        // Notice, we need to iterate `position` once when converting from reverse to regular iterator
        _erase(std::next(position).base(), call_free);
    }

public:

    uint64_t shrink(uint64_t nbytes) {
        uint64_t count = 0;
        std::vector<Segment>::iterator it;
        for (it = _segments.begin(); it != _segments.end() and count < nbytes; ++it) {
            count += it->nbytes;
        }
        _erase(_segments.begin(), it, true);
        return count;
    }

    uint64_t shrinkToFit(uint64_t total_num_bytes) {
        if (total_num_bytes < _total_num_bytes) {
            shrink(_total_num_bytes - total_num_bytes);
        }
        return _total_num_bytes;
    }

    void *alloc(uint64_t nbytes) {
        if (nbytes == 0) {
            return nullptr;
        }
        ++_total_num_lookups;
        // Check for segment of size `nbytes`, which is a cache hit!
        for (auto it = _segments.rbegin(); it != _segments.rend(); ++it) { // Search in reverse
            if (it->nbytes == nbytes) {
                void *ret = it->mem;
                assert(ret != nullptr);
                _erase(it, false);
    //            std::cout << "cache hit!   - nbytes: " << nbytes << ",  addr: " << ret << std::endl;
                return ret;
            }
        }
        ++_total_num_misses;
        void *ret = _malloc(nbytes); // Cache miss
    //    std::cout << "cache miss!  - nbytes: " << nbytes << ",  addr: " << ret << std::endl;
        return ret;
    }

    void free(uint64_t nbytes, void *memory) {
        // Let's make sure that we don't exceed `MAX_NBYTES`
        if (nbytes > MAX_NBYTES) {
            return _free(memory, nbytes);
        }
        shrinkToFit(MAX_NBYTES - nbytes);

        // Insert the segment at the end of `_segments`
        Segment seg;
        seg.nbytes = nbytes;
        seg.mem = memory;
        _segments.push_back(seg);
        _total_num_bytes += nbytes;
//        std::cout << "cache insert - nbytes: " << nbytes << ",  addr: " << seg.mem << std::endl;
    }

    ~MallocCache() {
        shrinkToFit(0);
        assert(_total_num_bytes == 0);
    }

    uint64_t getTotalNumBytes() const {
        return _total_num_bytes;
    }

    uint64_t getTotalNumLookups() const {
        return _total_num_lookups;
    }

    uint64_t getTotalNumMisses() const {
        return _total_num_misses;
    }

    uint64_t getMaxMemAllocated() const {
        return _max_mem_allocated;
    }

};

} // Namespace bohrium
<commit_msg>malloc: added pprint<commit_after>/*
This file is part of Bohrium and copyright (c) 2012 the Bohrium
team <http://www.bh107.org>.

Bohrium is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as
published by the Free Software Foundation, either version 3
of the License, or (at your option) any later version.

Bohrium is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the
GNU Lesser General Public License along with Bohrium.

If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once

#include <vector>
#include <sstream>
#include <stdexcept>
#include <sys/mman.h>
#include <bh_util.hpp>

namespace bohrium {

class MallocCache {
private:
    struct Segment {
        std::uint64_t nbytes;
        void *mem;
    };
    std::vector<Segment> _segments;
    uint64_t _total_num_bytes = 0;
    uint64_t _total_num_lookups = 0;
    uint64_t _total_num_misses = 0;
    uint64_t _total_mem_allocated = 0;
    uint64_t _max_mem_allocated = 0;

    static constexpr uint64_t MAX_NBYTES = 1000000;

    void *_malloc(uint64_t nbytes) {
        // Allocate page-size aligned memory.
        // The MAP_PRIVATE and MAP_ANONYMOUS flags is not 100% portable. See:
        // <http://stackoverflow.com/questions/4779188/how-to-use-mmap-to-allocate-a-memory-in-heap>
        void *ret = mmap(0, nbytes, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
        if (ret == MAP_FAILED or ret == nullptr) {
            std::stringstream ss;
            ss << "MallocCache() could not allocate a data region. Returned error code: " << strerror(errno);
            throw std::runtime_error(ss.str());
        }
        _total_mem_allocated += nbytes;
        if (_total_mem_allocated > _max_mem_allocated) {
            _max_mem_allocated = _total_mem_allocated;
        }
//        std::cout << "malloc       - nbytes: " << nbytes << ",  addr: " << ret << std::endl;
        return ret;
    }

    void _free(void *mem, uint64_t nbytes) {
//        std::cout << "free         - nbytes: " << nbytes << ",  addr: " << mem << std::endl;
        assert(mem != nullptr);
        if (munmap(mem, nbytes) != 0) {
            std::stringstream ss;
            ss << "MallocCache() could not free a data region. " << "Returned error code: " << strerror(errno);
            throw std::runtime_error(ss.str());
        }
        assert(_max_mem_allocated >= nbytes);
        _total_mem_allocated -= nbytes;
    }

    void _erase(std::vector<Segment>::iterator first,
                std::vector<Segment>::iterator last, bool call_free) {
        for (auto it = first; it != last; ++it) {
            if (call_free) {
                _free(it->mem, it->nbytes);
            }
            _total_num_bytes -= it->nbytes;
        }
        _segments.erase(first, last);
    }

    void _erase(std::vector<Segment>::iterator position, bool call_free) {
        _erase(position, std::next(position), call_free);
    }

    void _erase(std::vector<Segment>::reverse_iterator position, bool call_free) {
        // Notice, we need to iterate `position` once when converting from reverse to regular iterator
        _erase(std::next(position).base(), call_free);
    }

public:

    std::string pprint() {
        std::stringstream ss;
        ss << "Malloc Cache: \n";
        for(const Segment &seg: _segments) {
            ss << "  (" << seg.nbytes << "B, " << seg.mem << ")\n";
        }
        return ss.str();
    }

    uint64_t shrink(uint64_t nbytes) {
        uint64_t count = 0;
        std::vector<Segment>::iterator it;
        for (it = _segments.begin(); it != _segments.end() and count < nbytes; ++it) {
            count += it->nbytes;
        }
        _erase(_segments.begin(), it, true);
        return count;
    }

    uint64_t shrinkToFit(uint64_t total_num_bytes) {
        if (total_num_bytes < _total_num_bytes) {
            shrink(_total_num_bytes - total_num_bytes);
        }
        return _total_num_bytes;
    }

    void *alloc(uint64_t nbytes) {
        if (nbytes == 0) {
            return nullptr;
        }
        ++_total_num_lookups;
        // Check for segment of size `nbytes`, which is a cache hit!
        for (auto it = _segments.rbegin(); it != _segments.rend(); ++it) { // Search in reverse
            if (it->nbytes == nbytes) {
                void *ret = it->mem;
                assert(ret != nullptr);
                _erase(it, false);
    //            std::cout << "cache hit!   - nbytes: " << nbytes << ",  addr: " << ret << std::endl;
                return ret;
            }
        }
        ++_total_num_misses;
        void *ret = _malloc(nbytes); // Cache miss
    //    std::cout << "cache miss!  - nbytes: " << nbytes << ",  addr: " << ret << std::endl;
        return ret;
    }

    void free(uint64_t nbytes, void *memory) {
        // Let's make sure that we don't exceed `MAX_NBYTES`
        if (nbytes > MAX_NBYTES) {
            return _free(memory, nbytes);
        }
        shrinkToFit(MAX_NBYTES - nbytes);

        // Insert the segment at the end of `_segments`
        Segment seg;
        seg.nbytes = nbytes;
        seg.mem = memory;
        _segments.push_back(seg);
        _total_num_bytes += nbytes;
//        std::cout << "cache insert - nbytes: " << nbytes << ",  addr: " << seg.mem << std::endl;
    }

    ~MallocCache() {
        shrinkToFit(0);
        assert(_total_num_bytes == 0);
    }

    uint64_t getTotalNumBytes() const {
        return _total_num_bytes;
    }

    uint64_t getTotalNumLookups() const {
        return _total_num_lookups;
    }

    uint64_t getTotalNumMisses() const {
        return _total_num_misses;
    }

    uint64_t getMaxMemAllocated() const {
        return _max_mem_allocated;
    }

};

} // Namespace bohrium
<|endoftext|>


<commit_before>// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2021 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include <banman.h>

#include <netaddress.h>
#include <node/ui_interface.h>
#include <sync.h>
#include <util/system.h>
#include <util/time.h>
#include <util/translation.h>

BanMan::BanMan(fs::path ban_file, CClientUIInterface* client_interface, int64_t default_ban_time)
    : m_client_interface(client_interface), m_ban_db(std::move(ban_file)), m_default_ban_time(default_ban_time)
{
    if (m_client_interface) m_client_interface->InitMessage(_("Loading banlist…").translated);

    int64_t n_start = GetTimeMillis();
    if (m_ban_db.Read(m_banned)) {
        SweepBanned(); // sweep out unused entries

        LogPrint(BCLog::NET, "Loaded %d banned node addresses/subnets  %dms\n", m_banned.size(),
                 GetTimeMillis() - n_start);
    } else {
        LogPrintf("Recreating the banlist database\n");
        m_banned = {};
        m_is_dirty = true;
    }

    DumpBanlist();
}

BanMan::~BanMan()
{
    DumpBanlist();
}

void BanMan::DumpBanlist()
{
    static Mutex dump_mutex;
    LOCK(dump_mutex);

    SweepBanned(); // clean unused entries (if bantime has expired)

    if (!BannedSetIsDirty()) return;

    int64_t n_start = GetTimeMillis();

    banmap_t banmap;
    GetBanned(banmap);
    if (m_ban_db.Write(banmap)) {
        SetBannedSetDirty(false);
    }

    LogPrint(BCLog::NET, "Flushed %d banned node addresses/subnets to disk  %dms\n", banmap.size(),
             GetTimeMillis() - n_start);
}

void BanMan::ClearBanned()
{
    {
        LOCK(m_cs_banned);
        m_banned.clear();
        m_is_dirty = true;
    }
    DumpBanlist(); //store banlist to disk
    if (m_client_interface) m_client_interface->BannedListChanged();
}

bool BanMan::IsDiscouraged(const CNetAddr& net_addr)
{
    LOCK(m_cs_banned);
    return m_discouraged.contains(net_addr.GetAddrBytes());
}

bool BanMan::IsBanned(const CNetAddr& net_addr)
{
    auto current_time = GetTime();
    LOCK(m_cs_banned);
    for (const auto& it : m_banned) {
        CSubNet sub_net = it.first;
        CBanEntry ban_entry = it.second;

        if (current_time < ban_entry.nBanUntil && sub_net.Match(net_addr)) {
            return true;
        }
    }
    return false;
}

bool BanMan::IsBanned(const CSubNet& sub_net)
{
    auto current_time = GetTime();
    LOCK(m_cs_banned);
    banmap_t::iterator i = m_banned.find(sub_net);
    if (i != m_banned.end()) {
        CBanEntry ban_entry = (*i).second;
        if (current_time < ban_entry.nBanUntil) {
            return true;
        }
    }
    return false;
}

void BanMan::Ban(const CNetAddr& net_addr, int64_t ban_time_offset, bool since_unix_epoch)
{
    CSubNet sub_net(net_addr);
    Ban(sub_net, ban_time_offset, since_unix_epoch);
}

void BanMan::Discourage(const CNetAddr& net_addr)
{
    LOCK(m_cs_banned);
    m_discouraged.insert(net_addr.GetAddrBytes());
}

void BanMan::Ban(const CSubNet& sub_net, int64_t ban_time_offset, bool since_unix_epoch)
{
    CBanEntry ban_entry(GetTime());

    int64_t normalized_ban_time_offset = ban_time_offset;
    bool normalized_since_unix_epoch = since_unix_epoch;
    if (ban_time_offset <= 0) {
        normalized_ban_time_offset = m_default_ban_time;
        normalized_since_unix_epoch = false;
    }
    ban_entry.nBanUntil = (normalized_since_unix_epoch ? 0 : GetTime()) + normalized_ban_time_offset;

    {
        LOCK(m_cs_banned);
        if (m_banned[sub_net].nBanUntil < ban_entry.nBanUntil) {
            m_banned[sub_net] = ban_entry;
            m_is_dirty = true;
        } else
            return;
    }
    if (m_client_interface) m_client_interface->BannedListChanged();

    //store banlist to disk immediately
    DumpBanlist();
}

bool BanMan::Unban(const CNetAddr& net_addr)
{
    CSubNet sub_net(net_addr);
    return Unban(sub_net);
}

bool BanMan::Unban(const CSubNet& sub_net)
{
    {
        LOCK(m_cs_banned);
        if (m_banned.erase(sub_net) == 0) return false;
        m_is_dirty = true;
    }
    if (m_client_interface) m_client_interface->BannedListChanged();
    DumpBanlist(); //store banlist to disk immediately
    return true;
}

void BanMan::GetBanned(banmap_t& banmap)
{
    LOCK(m_cs_banned);
    // Sweep the banlist so expired bans are not returned
    SweepBanned();
    banmap = m_banned; //create a thread safe copy
}

void BanMan::SweepBanned()
{
    int64_t now = GetTime();
    bool notify_ui = false;
    {
        LOCK(m_cs_banned);
        banmap_t::iterator it = m_banned.begin();
        while (it != m_banned.end()) {
            CSubNet sub_net = (*it).first;
            CBanEntry ban_entry = (*it).second;
            if (!sub_net.IsValid() || now > ban_entry.nBanUntil) {
                m_banned.erase(it++);
                m_is_dirty = true;
                notify_ui = true;
                LogPrint(BCLog::NET, "Removed banned node address/subnet: %s\n", sub_net.ToString());
            } else
                ++it;
        }
    }
    // update UI
    if (notify_ui && m_client_interface) {
        m_client_interface->BannedListChanged();
    }
}

bool BanMan::BannedSetIsDirty()
{
    LOCK(m_cs_banned);
    return m_is_dirty;
}

void BanMan::SetBannedSetDirty(bool dirty)
{
    LOCK(m_cs_banned); //reuse m_banned lock for the m_is_dirty flag
    m_is_dirty = dirty;
}
<commit_msg>Fix data race condition in BanMan::DumpBanlist()<commit_after>// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2021 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include <banman.h>

#include <netaddress.h>
#include <node/ui_interface.h>
#include <sync.h>
#include <util/system.h>
#include <util/time.h>
#include <util/translation.h>

BanMan::BanMan(fs::path ban_file, CClientUIInterface* client_interface, int64_t default_ban_time)
    : m_client_interface(client_interface), m_ban_db(std::move(ban_file)), m_default_ban_time(default_ban_time)
{
    if (m_client_interface) m_client_interface->InitMessage(_("Loading banlist…").translated);

    int64_t n_start = GetTimeMillis();
    if (m_ban_db.Read(m_banned)) {
        SweepBanned(); // sweep out unused entries

        LogPrint(BCLog::NET, "Loaded %d banned node addresses/subnets  %dms\n", m_banned.size(),
                 GetTimeMillis() - n_start);
    } else {
        LogPrintf("Recreating the banlist database\n");
        m_banned = {};
        m_is_dirty = true;
    }

    DumpBanlist();
}

BanMan::~BanMan()
{
    DumpBanlist();
}

void BanMan::DumpBanlist()
{
    static Mutex dump_mutex;
    LOCK(dump_mutex);

    {
        LOCK(m_cs_banned);
        SweepBanned();
        if (!BannedSetIsDirty()) return;
    }

    int64_t n_start = GetTimeMillis();

    banmap_t banmap;
    GetBanned(banmap);
    if (m_ban_db.Write(banmap)) {
        SetBannedSetDirty(false);
    }

    LogPrint(BCLog::NET, "Flushed %d banned node addresses/subnets to disk  %dms\n", banmap.size(),
             GetTimeMillis() - n_start);
}

void BanMan::ClearBanned()
{
    {
        LOCK(m_cs_banned);
        m_banned.clear();
        m_is_dirty = true;
    }
    DumpBanlist(); //store banlist to disk
    if (m_client_interface) m_client_interface->BannedListChanged();
}

bool BanMan::IsDiscouraged(const CNetAddr& net_addr)
{
    LOCK(m_cs_banned);
    return m_discouraged.contains(net_addr.GetAddrBytes());
}

bool BanMan::IsBanned(const CNetAddr& net_addr)
{
    auto current_time = GetTime();
    LOCK(m_cs_banned);
    for (const auto& it : m_banned) {
        CSubNet sub_net = it.first;
        CBanEntry ban_entry = it.second;

        if (current_time < ban_entry.nBanUntil && sub_net.Match(net_addr)) {
            return true;
        }
    }
    return false;
}

bool BanMan::IsBanned(const CSubNet& sub_net)
{
    auto current_time = GetTime();
    LOCK(m_cs_banned);
    banmap_t::iterator i = m_banned.find(sub_net);
    if (i != m_banned.end()) {
        CBanEntry ban_entry = (*i).second;
        if (current_time < ban_entry.nBanUntil) {
            return true;
        }
    }
    return false;
}

void BanMan::Ban(const CNetAddr& net_addr, int64_t ban_time_offset, bool since_unix_epoch)
{
    CSubNet sub_net(net_addr);
    Ban(sub_net, ban_time_offset, since_unix_epoch);
}

void BanMan::Discourage(const CNetAddr& net_addr)
{
    LOCK(m_cs_banned);
    m_discouraged.insert(net_addr.GetAddrBytes());
}

void BanMan::Ban(const CSubNet& sub_net, int64_t ban_time_offset, bool since_unix_epoch)
{
    CBanEntry ban_entry(GetTime());

    int64_t normalized_ban_time_offset = ban_time_offset;
    bool normalized_since_unix_epoch = since_unix_epoch;
    if (ban_time_offset <= 0) {
        normalized_ban_time_offset = m_default_ban_time;
        normalized_since_unix_epoch = false;
    }
    ban_entry.nBanUntil = (normalized_since_unix_epoch ? 0 : GetTime()) + normalized_ban_time_offset;

    {
        LOCK(m_cs_banned);
        if (m_banned[sub_net].nBanUntil < ban_entry.nBanUntil) {
            m_banned[sub_net] = ban_entry;
            m_is_dirty = true;
        } else
            return;
    }
    if (m_client_interface) m_client_interface->BannedListChanged();

    //store banlist to disk immediately
    DumpBanlist();
}

bool BanMan::Unban(const CNetAddr& net_addr)
{
    CSubNet sub_net(net_addr);
    return Unban(sub_net);
}

bool BanMan::Unban(const CSubNet& sub_net)
{
    {
        LOCK(m_cs_banned);
        if (m_banned.erase(sub_net) == 0) return false;
        m_is_dirty = true;
    }
    if (m_client_interface) m_client_interface->BannedListChanged();
    DumpBanlist(); //store banlist to disk immediately
    return true;
}

void BanMan::GetBanned(banmap_t& banmap)
{
    LOCK(m_cs_banned);
    // Sweep the banlist so expired bans are not returned
    SweepBanned();
    banmap = m_banned; //create a thread safe copy
}

void BanMan::SweepBanned()
{
    int64_t now = GetTime();
    bool notify_ui = false;
    {
        LOCK(m_cs_banned);
        banmap_t::iterator it = m_banned.begin();
        while (it != m_banned.end()) {
            CSubNet sub_net = (*it).first;
            CBanEntry ban_entry = (*it).second;
            if (!sub_net.IsValid() || now > ban_entry.nBanUntil) {
                m_banned.erase(it++);
                m_is_dirty = true;
                notify_ui = true;
                LogPrint(BCLog::NET, "Removed banned node address/subnet: %s\n", sub_net.ToString());
            } else
                ++it;
        }
    }
    // update UI
    if (notify_ui && m_client_interface) {
        m_client_interface->BannedListChanged();
    }
}

bool BanMan::BannedSetIsDirty()
{
    LOCK(m_cs_banned);
    return m_is_dirty;
}

void BanMan::SetBannedSetDirty(bool dirty)
{
    LOCK(m_cs_banned); //reuse m_banned lock for the m_is_dirty flag
    m_is_dirty = dirty;
}
<|endoftext|>


<commit_before>#include "beacon.h"
#include "util.h"
#include "uint256.h"
#include "key.h"
#include "main.h"

std::vector<std::string> split(std::string s, std::string delim);
extern std::string SignBlockWithCPID(std::string sCPID, std::string sBlockHash);
extern bool VerifyCPIDSignature(std::string sCPID, std::string sBlockHash, std::string sSignature);
std::string RetrieveBeaconValueWithMaxAge(const std::string& cpid, int64_t iMaxSeconds);
int64_t GetRSAWeightByCPIDWithRA(std::string cpid);

namespace
{
    std::string GetNetSuffix()
    {
        return fTestNet ? "testnet" : "";
    }
}

bool GenerateBeaconKeys(const std::string &cpid, std::string &sOutPubKey, std::string &sOutPrivKey)
{
    // First Check the Index - if it already exists, use it
    sOutPrivKey = GetArgument("privatekey" + cpid + GetNetSuffix(), "");
    sOutPubKey  = GetArgument("publickey" + cpid + GetNetSuffix(), "");

    // If current keypair is not empty, but is invalid, allow the new keys to be stored, otherwise return 1: (10-25-2016)
    if (!sOutPrivKey.empty() && !sOutPubKey.empty())
    {
        uint256 hashBlock = GetRandHash();
        std::string sSignature = SignBlockWithCPID(cpid,hashBlock.GetHex());
        bool fResult = VerifyCPIDSignature(cpid, hashBlock.GetHex(), sSignature);
        if (fResult)
        {
            printf("\r\nGenerateNewKeyPair::Current keypair is valid.\r\n");
            return false;
        }
    }

    // Generate the Keypair
    CKey key;
    key.MakeNewKey(false);
    CPrivKey vchPrivKey = key.GetPrivKey();
    sOutPrivKey = HexStr<CPrivKey::iterator>(vchPrivKey.begin(), vchPrivKey.end());
    sOutPubKey = HexStr(key.GetPubKey().Raw());

    return true;
}

void StoreBeaconKeys(
        const std::string &cpid,
        const std::string &pubKey,
        const std::string &privKey)
{
    WriteKey("publickey" + cpid + GetNetSuffix(), pubKey);
    WriteKey("privatekey" + cpid + GetNetSuffix(), privKey);
}

std::string GetStoredBeaconPrivateKey(const std::string& cpid)
{
    return GetArgument("privatekey" + cpid + GetNetSuffix(), "");
}

std::string GetStoredBeaconPublicKey(const std::string& cpid)
{
    return GetArgument("publickey" + cpid + GetNetSuffix(), "");
}

void ActivateBeaconKeys(
        const std::string &cpid,
        const std::string &pubKey,
        const std::string &privKey)
{
    SetArgument("publickey" + cpid + GetNetSuffix(), pubKey);
    SetArgument("privatekey" + cpid + GetNetSuffix(), privKey);
}

// Move more beacon functions - iFoggz

void GetBeaconElements(std::string& sBeacon,std::string& out_cpid, std::string& out_address, std::string& out_publickey)
{
   if (sBeacon.empty()) return;
   std::string sContract = DecodeBase64(sBeacon);
   std::vector<std::string> vContract = split(sContract.c_str(),";");
   if (vContract.size() < 4) return;
   out_cpid = vContract[0];
   out_address = vContract[2];
   out_publickey = vContract[3];
}

std::string GetBeaconPublicKey(const std::string& cpid, bool bAdvertisingBeacon)
{
   //3-26-2017 - Ensure beacon public key is within 6 months of network age (If advertising, let it be returned as missing after 5 months, to ensure the public key is renewed seamlessly).
   int iMonths = bAdvertisingBeacon ? 5 : 6;
   int64_t iMaxSeconds = 60 * 24 * 30 * iMonths * 60;
   std::string sBeacon = RetrieveBeaconValueWithMaxAge(cpid, iMaxSeconds);
   if (sBeacon.empty()) return "";
   // Beacon data structure: CPID,hashRand,Address,beacon public key: base64 encoded
   std::string sContract = DecodeBase64(sBeacon);
   std::vector<std::string> vContract = split(sContract.c_str(),";");
   if (vContract.size() < 4) return "";
   std::string sBeaconPublicKey = vContract[3];
   return sBeaconPublicKey;
}

int64_t BeaconTimeStamp(std::string& cpid, bool bZeroOutAfterPOR)
{
            std::string sBeacon = mvApplicationCache["beacon;" + cpid];
            int64_t iLocktime = mvApplicationCacheTimestamp["beacon;" + cpid];
            int64_t iRSAWeight = GetRSAWeightByCPIDWithRA(cpid);
            if (fDebug10) printf("\r\n Beacon %s, Weight %f, Locktime %f \r\n",sBeacon.c_str(),(double)iRSAWeight,(double)iLocktime);
            if (bZeroOutAfterPOR && iRSAWeight==0) iLocktime = 0;
            return iLocktime;

}

bool HasActiveBeacon(const std::string& cpid)
{
    return GetBeaconPublicKey(cpid, false).empty() == false;
}

std::string RetrieveBeaconValueWithMaxAge(const std::string& cpid, int64_t iMaxSeconds)
{
    const std::string key = "beacon;" + cpid;
    const std::string& value = mvApplicationCache[key];

    // Compare the age of the beacon to the age of the current block. If we have
    // no current block we assume that the beacon is valid.
    int64_t iAge = pindexBest != NULL
          ? pindexBest->nTime - mvApplicationCacheTimestamp[key]
          : 0;

    return (iAge > iMaxSeconds)
          ? ""
          : value;
}
<commit_msg>spacing corrections<commit_after>#include "beacon.h"
#include "util.h"
#include "uint256.h"
#include "key.h"
#include "main.h"

std::vector<std::string> split(std::string s, std::string delim);
extern std::string SignBlockWithCPID(std::string sCPID, std::string sBlockHash);
extern bool VerifyCPIDSignature(std::string sCPID, std::string sBlockHash, std::string sSignature);
std::string RetrieveBeaconValueWithMaxAge(const std::string& cpid, int64_t iMaxSeconds);
int64_t GetRSAWeightByCPIDWithRA(std::string cpid);

namespace
{
    std::string GetNetSuffix()
    {
        return fTestNet ? "testnet" : "";
    }
}

bool GenerateBeaconKeys(const std::string &cpid, std::string &sOutPubKey, std::string &sOutPrivKey)
{
    // First Check the Index - if it already exists, use it
    sOutPrivKey = GetArgument("privatekey" + cpid + GetNetSuffix(), "");
    sOutPubKey  = GetArgument("publickey" + cpid + GetNetSuffix(), "");

    // If current keypair is not empty, but is invalid, allow the new keys to be stored, otherwise return 1: (10-25-2016)
    if (!sOutPrivKey.empty() && !sOutPubKey.empty())
    {
        uint256 hashBlock = GetRandHash();
        std::string sSignature = SignBlockWithCPID(cpid,hashBlock.GetHex());
        bool fResult = VerifyCPIDSignature(cpid, hashBlock.GetHex(), sSignature);
        if (fResult)
        {
            printf("\r\nGenerateNewKeyPair::Current keypair is valid.\r\n");
            return false;
        }
    }

    // Generate the Keypair
    CKey key;
    key.MakeNewKey(false);
    CPrivKey vchPrivKey = key.GetPrivKey();
    sOutPrivKey = HexStr<CPrivKey::iterator>(vchPrivKey.begin(), vchPrivKey.end());
    sOutPubKey = HexStr(key.GetPubKey().Raw());

    return true;
}

void StoreBeaconKeys(
        const std::string &cpid,
        const std::string &pubKey,
        const std::string &privKey)
{
    WriteKey("publickey" + cpid + GetNetSuffix(), pubKey);
    WriteKey("privatekey" + cpid + GetNetSuffix(), privKey);
}

std::string GetStoredBeaconPrivateKey(const std::string& cpid)
{
    return GetArgument("privatekey" + cpid + GetNetSuffix(), "");
}

std::string GetStoredBeaconPublicKey(const std::string& cpid)
{
    return GetArgument("publickey" + cpid + GetNetSuffix(), "");
}

void ActivateBeaconKeys(
        const std::string &cpid,
        const std::string &pubKey,
        const std::string &privKey)
{
    SetArgument("publickey" + cpid + GetNetSuffix(), pubKey);
    SetArgument("privatekey" + cpid + GetNetSuffix(), privKey);
}

// Move more beacon functions - iFoggz

void GetBeaconElements(std::string& sBeacon,std::string& out_cpid, std::string& out_address, std::string& out_publickey)
{
    if (sBeacon.empty()) return;
    std::string sContract = DecodeBase64(sBeacon);
    std::vector<std::string> vContract = split(sContract.c_str(),";");
    if (vContract.size() < 4) return;
    out_cpid = vContract[0];
    out_address = vContract[2];
    out_publickey = vContract[3];
}

std::string GetBeaconPublicKey(const std::string& cpid, bool bAdvertisingBeacon)
{
    //3-26-2017 - Ensure beacon public key is within 6 months of network age (If advertising, let it be returned as missing after 5 months, to ensure the public key is renewed seamlessly).
    int iMonths = bAdvertisingBeacon ? 5 : 6;
    int64_t iMaxSeconds = 60 * 24 * 30 * iMonths * 60;
    std::string sBeacon = RetrieveBeaconValueWithMaxAge(cpid, iMaxSeconds);
    if (sBeacon.empty()) return "";
    // Beacon data structure: CPID,hashRand,Address,beacon public key: base64 encoded
    std::string sContract = DecodeBase64(sBeacon);
    std::vector<std::string> vContract = split(sContract.c_str(),";");
    if (vContract.size() < 4) return "";
    std::string sBeaconPublicKey = vContract[3];
    return sBeaconPublicKey;
}

int64_t BeaconTimeStamp(std::string& cpid, bool bZeroOutAfterPOR)
{
    std::string sBeacon = mvApplicationCache["beacon;" + cpid];
    int64_t iLocktime = mvApplicationCacheTimestamp["beacon;" + cpid];
    int64_t iRSAWeight = GetRSAWeightByCPIDWithRA(cpid);
    if (fDebug10) printf("\r\n Beacon %s, Weight %f, Locktime %f \r\n",sBeacon.c_str(),(double)iRSAWeight,(double)iLocktime);
    if (bZeroOutAfterPOR && iRSAWeight==0) iLocktime = 0;
    return iLocktime;

}

bool HasActiveBeacon(const std::string& cpid)
{
    return GetBeaconPublicKey(cpid, false).empty() == false;
}

std::string RetrieveBeaconValueWithMaxAge(const std::string& cpid, int64_t iMaxSeconds)
{
    const std::string key = "beacon;" + cpid;
    const std::string& value = mvApplicationCache[key];

    // Compare the age of the beacon to the age of the current block. If we have
    // no current block we assume that the beacon is valid.
    int64_t iAge = pindexBest != NULL
          ? pindexBest->nTime - mvApplicationCacheTimestamp[key]
          : 0;

    return (iAge > iMaxSeconds)
          ? ""
          : value;
}
<|endoftext|>


<commit_before>/*
 *  beagle.cpp
 *  BEAGLE
 *
 * @author Andrew Rambaut
 * @author Marc Suchard
 *
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <list>
#include <vector>

#include "beagle.h"
#include "BeagleImpl.h"

#ifdef CUDA
	#include "CUDA/BeagleCUDAImpl.h"
#endif
#include "CPU/BeagleCPUImpl.h"

BeagleImpl **instances = NULL;
int instanceCount = 0;

std::list<BeagleImplFactory*> implFactory;

ResourceList* getResourceList() {
	return null;
}

int createInstance(
				int bufferCount,
				int tipCount,
				int stateCount,
				int patternCount,
				int eigenDecompositionCount,
				int matrixCount,
				int* resourceList,
				int resourceCount,
				int preferenceFlags,
				int requirementFlags )
{
	// Set-up a list of implementation factories in trial-order
	if (implFactory.size() == 0) {
#ifdef CUDA
		implFactory.push_back(new BeagleCUDAImplFactory());
#endif
		implFactory.push_back(new BeagleCPUImplFactory());
	}

	// Try each implementation
    for(std::list<BeagleImplFactory*>::iterator factory = implFactory.begin();
		factory != implFactory.end(); factory++) {
    	fprintf(stderr,"BEAGLE bootstrap: %s - ",(*factory)->getName());

    	BeagleImpl* beagle = (*factory)->createImpl(
    		bufferCount,
    		tipCount,
    		stateCount,
    		patternCount,
    		eigenDecompositionCount,
    		matrixCount);

    	if (beagle != NULL) {
    		fprintf(stderr,"Success\n");
    		int instance = instanceCount;
    	    instanceCount++;
    	    instances = (BeagleImpl **)realloc(instances, sizeof(BeagleImpl *) * instanceCount);
    	    instances[instance] = beagle;
    	    return instance;
    	}
    	fprintf(stderr,"Failed\n");
    }

    // No implementations found or appropriate
    return ERROR;
}

void initializeInstance(
						int *instance,
						int instanceCount,
						InstanceDetails* returnInfo)
{
}

void finalize(int *instance, int instanceCount)
{
	for (int i = 0; i < instanceCount; i++) {
	    delete instances[instance];
    	instances[instance] = 0L;
	}
}

int setPartials(
                    int* instance,
                    int instanceCount,
					int bufferIndex,
					const double* inPartials)
{
	for (int i = 0; i < instanceCount; i++)
	    instances[instance]->setTipPartials(bufferIndex, inPartials);

	return 0;
}

int getPartials(int* instance, int bufferIndex, double *outPartials)
{
	for (int i = 0; i < instanceCount; i++)
	    instances[instance]->getPartials(bufferIndex, outPartials);

	return 0;
}

int setTipStates(
                  int* instance,
                  int instanceCount,
				  int tipIndex,
				  const int* inStates)
{
	for (int i = 0; i < instanceCount; i++)
  		instances[instance]->setTipStates(tipIndex, inStates);

	return 0;
}

int setStateFrequencies(int* instance,
                         int instanceCount,
                         const double* inStateFrequencies)
{
 	for (int i = 0; i < instanceCount; i++)
   		instances[instance]->setStateFrequencies(inStateFrequencies);
	return 0;
}

int setEigenDecomposition(
                           int* instance,
                           int instanceCount,
						   int eigenIndex,
						   const double** inEigenVectors,
						   const double** inInverseEigenVectors,
						   const double* inEigenValues)
{
 	for (int i = 0; i < instanceCount; i++)
  		instances[instance]->setEigenDecomposition(eigenIndex, inEigenVectors, inInverseEigenVectors, inEigenValues);
	return 0;
}

int setTransitionMatrix(	int* instance,
                			int matrixIndex,
                			const double* inMatrix)
{
 	for (int i = 0; i < instanceCount; i++)
  		instances[instance]->setTransitionMatrix(matrixIndex, inMatrix);
	return 0;
}

int updateTransitionMatrices(
                                            int* instance,
                                            int instanceCount,
                                            int eigenIndex,
                                            const int* probabilityIndices,
                                            const int* firstDerivativeIndices,
                                            const int* secondDervativeIndices,
                                            const double* edgeLengths,
                                            int count)
{
 	for (int i = 0; i < instanceCount; i++)
  		instances[instance]->updateTransitionMatrices(eigenIndex, probabilityIndices, firstDerivativeIndices, secondDervativeIndices, edgeLengths, count);
	return 0;
}

int updatePartials(
                       int* instance,
                       int instanceCount,
					   int* operations,
					   int operationCount,
					   int rescale)
{
 	for (int i = 0; i < instanceCount; i++)
  		instances[instance]->calculatePartials(operations, operationCount, rescale);
	return 0;
}

int calculateRootLogLikelihoods(
                             int* instance,
                             int instanceCount,
		                     const int* bufferIndices,
		                     int count,
		                     const double* weights,
		                     const double** stateFrequencies,
			                 double* outLogLikelihoods)
{
 	for (int i = 0; i < instanceCount; i++)
   		instances[instance]->calculateLogLikelihoods(bufferIndices, count, weights, stateFrequencies, outLogLikelihoods);
	return 0;
}

int calculateEdgeLogLikelihoods(
							 int* instance,
							 int instanceCount,
		                     const int* parentBufferIndices,
		                     const int* childBufferIndices,
		                     const int* probabilityIndices,
		                     const int* firstDerivativeIndices,
		                     const int* secondDerivativeIndices,
		                     int count,
		                     const double* weights,
		                     const double** stateFrequencies,
		                     double* outLogLikelihoods,
			                 double* outFirstDerivatives,
			                 double* outSecondDerivatives)
{
 	for (int i = 0; i < instanceCount; i++)
   		instances[instance]->calculateEdgeLogLikelihoods(
   											parentBufferIndices,
   											childBufferIndices,
   											probabilityIndices,
   											firstDerivativeIndices,
   											secondDerivativeIndices,
											count,
											weights,
											stateFrequencies,
											outLogLikelihoods,
											outFirstDerivatives,
											outSecondDerivatives);
	return 0;
}

<commit_msg>Updated beagle.cpp to the new API<commit_after>/*
 *  beagle.cpp
 *  BEAGLE
 *
 * @author Andrew Rambaut
 * @author Marc Suchard
 *
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <list>
#include <vector>

#include "beagle.h"
#include "BeagleImpl.h"

#ifdef CUDA
	#include "CUDA/BeagleCUDAImpl.h"
#endif
#include "CPU/BeagleCPUImpl.h"

BeagleImpl **instances = NULL;
int instanceCount = 0;

std::list<BeagleImplFactory*> implFactory;

ResourceList* getResourceList() {
	return null;
}

int createInstance(
				int bufferCount,
				int tipCount,
				int stateCount,
				int patternCount,
				int eigenDecompositionCount,
				int matrixCount,
				int* resourceList,
				int resourceCount,
				int preferenceFlags,
				int requirementFlags )
{
	// Set-up a list of implementation factories in trial-order
	if (implFactory.size() == 0) {
#ifdef CUDA
		implFactory.push_back(new BeagleCUDAImplFactory());
#endif
		implFactory.push_back(new BeagleCPUImplFactory());
	}

	// Try each implementation
    for(std::list<BeagleImplFactory*>::iterator factory = implFactory.begin();
		factory != implFactory.end(); factory++) {
    	fprintf(stderr,"BEAGLE bootstrap: %s - ",(*factory)->getName());

    	BeagleImpl* beagle = (*factory)->createImpl(
    		bufferCount,
    		tipCount,
    		stateCount,
    		patternCount,
    		eigenDecompositionCount,
    		matrixCount);

    	if (beagle != NULL) {
    		fprintf(stderr,"Success\n");
    		int instance = instanceCount;
    	    instanceCount++;
    	    instances = (BeagleImpl **)realloc(instances, sizeof(BeagleImpl *) * instanceCount);
    	    instances[instance] = beagle;
    	    return instance;
    	}
    	fprintf(stderr,"Failed\n");
    }

    // No implementations found or appropriate
    return ERROR;
}

void initializeInstance(
						int *instance,
						int instanceCount,
						InstanceDetails* returnInfo)
{
	// TODO: Actual creation of instances should wait until here
}

void finalize(int *instance, int instanceCount)
{
	for (int i = 0; i < instanceCount; i++) {
	    delete instances[instance];
    	instances[instance] = 0L;
	}
}

int setPartials(
                    int* instance,
                    int instanceCount,
					int bufferIndex,
					const double* inPartials)
{
	for (int i = 0; i < instanceCount; i++)
	    instances[instance]->setTipPartials(bufferIndex, inPartials);

	return 0;
}

int getPartials(int* instance, int bufferIndex, double *outPartials)
{
	for (int i = 0; i < instanceCount; i++)
	    instances[instance]->getPartials(bufferIndex, outPartials);

	return 0;
}

int setTipStates(
                  int* instance,
                  int instanceCount,
				  int tipIndex,
				  const int* inStates)
{
	for (int i = 0; i < instanceCount; i++)
  		instances[instance]->setTipStates(tipIndex, inStates);

	return 0;
}

int setEigenDecomposition(
                           int* instance,
                           int instanceCount,
						   int eigenIndex,
						   const double** inEigenVectors,
						   const double** inInverseEigenVectors,
						   const double* inEigenValues)
{
 	for (int i = 0; i < instanceCount; i++)
  		instances[instance]->setEigenDecomposition(eigenIndex, inEigenVectors, inInverseEigenVectors, inEigenValues);
	return 0;
}

int setTransitionMatrix(	int* instance,
                			int matrixIndex,
                			const double* inMatrix)
{
 	for (int i = 0; i < instanceCount; i++)
  		instances[instance]->setTransitionMatrix(matrixIndex, inMatrix);
	return 0;
}

int updateTransitionMatrices(
                                            int* instance,
                                            int instanceCount,
                                            int eigenIndex,
                                            const int* probabilityIndices,
                                            const int* firstDerivativeIndices,
                                            const int* secondDervativeIndices,
                                            const double* edgeLengths,
                                            int count)
{
 	for (int i = 0; i < instanceCount; i++)
  		instances[instance]->updateTransitionMatrices(eigenIndex, probabilityIndices, firstDerivativeIndices, secondDervativeIndices, edgeLengths, count);
	return 0;
}

int updatePartials(
                       int* instance,
                       int instanceCount,
					   int* operations,
					   int operationCount,
					   int rescale)
{
 	for (int i = 0; i < instanceCount; i++)
  		instances[instance]->calculatePartials(operations, operationCount, rescale);
	return 0;
}

int calculateRootLogLikelihoods(
                             int* instance,
                             int instanceCount,
		                     const int* bufferIndices,
		                     int count,
		                     const double* weights,
		                     const double** stateFrequencies,
			                 double* outLogLikelihoods)
{
 	for (int i = 0; i < instanceCount; i++)
   		instances[instance]->calculateLogLikelihoods(bufferIndices, count, weights, stateFrequencies, outLogLikelihoods);
	return 0;
}

int calculateEdgeLogLikelihoods(
							 int* instance,
							 int instanceCount,
		                     const int* parentBufferIndices,
		                     const int* childBufferIndices,
		                     const int* probabilityIndices,
		                     const int* firstDerivativeIndices,
		                     const int* secondDerivativeIndices,
		                     int count,
		                     const double* weights,
		                     const double** stateFrequencies,
		                     double* outLogLikelihoods,
			                 double* outFirstDerivatives,
			                 double* outSecondDerivatives)
{
 	for (int i = 0; i < instanceCount; i++)
   		instances[instance]->calculateEdgeLogLikelihoods(
   											parentBufferIndices,
   											childBufferIndices,
   											probabilityIndices,
   											firstDerivativeIndices,
   											secondDerivativeIndices,
											count,
											weights,
											stateFrequencies,
											outLogLikelihoods,
											outFirstDerivatives,
											outSecondDerivatives);
	return 0;
}

<|endoftext|>