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

#include <novatel_gps_driver/parsers/corrimudata.h>
#include <novatel_gps_driver/parsers/header.h>
#include <boost/make_shared.hpp>

const std::string novatel_gps_driver::CorrImuDataParser::MESSAGE_NAME = "CORRIMUDATA";

uint32_t novatel_gps_driver::CorrImuDataParser::GetMessageId() const
{
  return MESSAGE_ID;
}

const std::string novatel_gps_driver::CorrImuDataParser::GetMessageName() const
{
  return MESSAGE_NAME;
}

novatel_gps_msgs::NovatelCorrectedImuDataPtr
novatel_gps_driver::CorrImuDataParser::ParseBinary(const novatel_gps_driver::BinaryMessage& bin_msg) throw(ParseException)
{
  if (bin_msg.data_.size() != BINARY_LENGTH)
  {
    std::stringstream error;
    error << "Unexpected corrimudata message size: " << bin_msg.data_.size();
    throw ParseException(error.str());
  }
  novatel_gps_msgs::NovatelCorrectedImuDataPtr ros_msg = boost::make_shared<novatel_gps_msgs::NovatelCorrectedImuData>();
  HeaderParser h_parser;
  ros_msg->novatel_msg_header = h_parser.ParseBinary(bin_msg);
  ros_msg->novatel_msg_header.message_name = "CORRIMUDATA";

  ros_msg->gps_week_num = ParseUInt32(&bin_msg.data_[0]);
  ros_msg->gps_seconds = ParseDouble(&bin_msg.data_[4]);
  ros_msg->pitch_rate = ParseDouble(&bin_msg.data_[12]);
  ros_msg->roll_rate = ParseDouble(&bin_msg.data_[20]);
  ros_msg->yaw_rate = ParseDouble(&bin_msg.data_[28]);
  ros_msg->lateral_acceleration = ParseDouble(&bin_msg.data_[36]);
  ros_msg->longitudinal_acceleration = ParseDouble(&bin_msg.data_[44]);
  ros_msg->vertical_acceleration = ParseDouble(&bin_msg.data_[52]);

  return ros_msg;
}

novatel_gps_msgs::NovatelCorrectedImuDataPtr
novatel_gps_driver::CorrImuDataParser::ParseAscii(const novatel_gps_driver::NovatelSentence& sentence) throw(ParseException)
{
  if (sentence.body.size() != ASCII_FIELDS)
  {
    std::stringstream error;
    error << "Unexpected number of fields in CORRIMUDATA log: " << sentence.body.size();
    throw ParseException(error.str());
  }
  novatel_gps_msgs::NovatelCorrectedImuDataPtr msg = boost::make_shared<novatel_gps_msgs::NovatelCorrectedImuData>();
  HeaderParser h_parser;
  msg->novatel_msg_header = h_parser.ParseAscii(sentence);

  bool valid = true;

  valid &= ParseUInt32(sentence.body[0], msg->gps_week_num);
  valid &= ParseDouble(sentence.body[1], msg->gps_seconds);
  valid &= ParseDouble(sentence.body[2], msg->pitch_rate);
  valid &= ParseDouble(sentence.body[3], msg->roll_rate);
  valid &= ParseDouble(sentence.body[4], msg->yaw_rate);
  valid &= ParseDouble(sentence.body[5], msg->lateral_acceleration);
  valid &= ParseDouble(sentence.body[6], msg->longitudinal_acceleration);
  valid &= ParseDouble(sentence.body[7], msg->vertical_acceleration);

  if (!valid)
  {
    throw ParseException("Error parsing CORRIMUDATA log.");
  }

  return msg;
}


text:
#include <iomanip>
#include <iostream>
#include <boost/uuid/uuid.hpp>
#include <boost/uuid/uuid_generators.hpp>

int main() {
    // create an uuid generator
    boost::uuids::random_generator gen{};

    // generate 2 UUIDs
    for (auto i : { 0, 0 }) {
        // generate
        auto uuid = gen();

        // print it out
        for (auto& i : uuid)
            std::cout << std::setw(2) << std::setfill('0')
                << std::hex << std::uppercase
                << static_cast<int>(i) << " ";

        std::cout << "\n\n";
    }
}

ext: cpp


text:
/**
 *    Copyright (C) 2014 MongoDB Inc.
 *
 *    This program is free software: you can redistribute it and/or  modify
 *    it under the terms of the GNU Affero General Public License, version 3,
 *    as published by the Free Software Foundation.
 *
 *    This program 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 Affero General Public License for more details.
 *
 *    You should have received a copy of the GNU Affero General Public License
 *    along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 *    As a special exception, the copyright holders give permission to link the
 *    code of portions of this program with the OpenSSL library under certain
 *    conditions as described in each individual source file and distribute
 *    linked combinations including the program with the OpenSSL library. You
 *    must comply with the GNU Affero General Public License in all respects for
 *    all of the code used other than as permitted herein. If you modify file(s)
 *    with this exception, you may extend this exception to your version of the
 *    file(s), but you are not obligated to do so. If you do not wish to do so,
 *    delete this exception statement from your version. If you delete this
 *    exception statement from all source files in the program, then also delete
 *    it in the license file.
 */

#define MONGO_LOG_DEFAULT_COMPONENT ::mongo::logger::LogComponent::kReplication

#include "mongo/platform/basic.h"

#include "mongo/db/repl/repl_coordinator_legacy.h"

#include <boost/thread/thread.hpp>

#include "mongo/base/status.h"
#include "mongo/bson/optime.h"
#include "mongo/db/dbhelpers.h"
#include "mongo/db/instance.h"
#include "mongo/db/repl/bgsync.h"
#include "mongo/db/repl/connections.h"
#include "mongo/db/repl/handshake_args.h"
#include "mongo/db/repl/is_master_response.h"
#include "mongo/db/repl/master_slave.h"
#include "mongo/db/repl/member.h"
#include "mongo/db/repl/oplog.h" // for newRepl()
#include "mongo/db/repl/repl_coordinator_external_state_impl.h"
#include "mongo/db/repl/repl_set_heartbeat_args.h"
#include "mongo/db/repl/repl_set_heartbeat_response.h"
#include "mongo/db/repl/repl_set_seed_list.h"
#include "mongo/db/repl/repl_settings.h"
#include "mongo/db/repl/replset_commands.h"
#include "mongo/db/repl/rs.h"
#include "mongo/db/repl/rs_config.h"
#include "mongo/db/repl/rs_initiate.h"
#include "mongo/db/repl/rslog.h"
#include "mongo/db/repl/update_position_args.h"
#include "mongo/db/repl/write_concern.h"
#include "mongo/db/write_concern_options.h"
#include "mongo/util/assert_util.h"
#include "mongo/util/fail_point_service.h"
#include "mongo/util/log.h"

namespace mongo {

namespace repl {

    LegacyReplicationCoordinator::LegacyReplicationCoordinator(const ReplSettings& settings) :
            _maintenanceMode(0), _settings(settings) {
        // this is ok but micros or combo with some rand() and/or 64 bits might be better --
        // imagine a restart and a clock correction simultaneously (very unlikely but possible...)
        _rbid = (int) curTimeMillis64();
    }
    LegacyReplicationCoordinator::~LegacyReplicationCoordinator() {}

    void LegacyReplicationCoordinator::startReplication(OperationContext* txn) {
        if (!isReplEnabled()) {
            return;
        }

        ReplicationCoordinatorExternalStateImpl externalState;
        _myRID = externalState.ensureMe(txn);

        // if we are going to be a replica set, we aren't doing other forms of replication.
        if (!_settings.replSet.empty()) {
            if (_settings.slave || _settings.master) {
                log() << "***" << endl;
                log() << "ERROR: can't use --slave or --master replication options with --replSet";
                log() << "***" << endl;
            }

            ReplSetSeedList *replSetSeedList = new ReplSetSeedList(&externalState,
                                                                   _settings.replSet);
            boost::thread t(stdx::bind(&startReplSets, replSetSeedList));
        } else {
            startMasterSlave();
        }
    }

    void LegacyReplicationCoordinator::shutdown() {
    }

    ReplSettings& LegacyReplicationCoordinator::getSettings() {
        return _settings;
    }

    ReplicationCoordinator::Mode LegacyReplicationCoordinator::getReplicationMode() const {
        if (theReplSet) {
            return modeReplSet;
        } else if (_settings.slave || _settings.master) {
            return modeMasterSlave;
        }
        return modeNone;
    }

    MemberState LegacyReplicationCoordinator::getCurrentMemberState() const {
        invariant(getReplicationMode() == modeReplSet);
        return theReplSet->state();
    }

    void LegacyReplicationCoordinator::clearSyncSourceBlacklist() {
        theReplSet->clearVetoes();
    }

    ReplicationCoordinator::StatusAndDuration LegacyReplicationCoordinator::awaitReplication(
            const OperationContext* txn,
            const OpTime& ts,
            const WriteConcernOptions& writeConcern) {

        Timer timeoutTimer;

        if (writeConcern.wNumNodes <= 1 && writeConcern.wMode.empty()) {
            // no desired replication check
            return StatusAndDuration(Status::OK(), Milliseconds(timeoutTimer.millis()));
        }

        const Mode replMode = getReplicationMode();
        if (replMode == modeNone || serverGlobalParams.configsvr) {
            // no replication check needed (validated above)
            return StatusAndDuration(Status::OK(), Milliseconds(timeoutTimer.millis()));
        }

        if (writeConcern.wMode == "majority" && replMode == modeMasterSlave) {
            // with master/slave, majority is equivalent to w=1
            return StatusAndDuration(Status::OK(), Milliseconds(timeoutTimer.millis()));
        }

        if (ts.isNull()) {
            // If waiting for the empty optime, always say it's been replicated.
            return StatusAndDuration(Status::OK(), Milliseconds(timeoutTimer.millis()));
        }

        try {
            while (1) {
                if (!writeConcern.wMode.empty()) {
                    if (opReplicatedEnough(ts, writeConcern.wMode)) {
                        return StatusAndDuration(Status::OK(), Milliseconds(timeoutTimer.millis()));
                    }
                }
                else if (opReplicatedEnough(ts, writeConcern.wNumNodes)) {
                    return StatusAndDuration(Status::OK(), Milliseconds(timeoutTimer.millis()));
                }

                if (writeConcern.wTimeout > 0 && timeoutTimer.millis() >= writeConcern.wTimeout) {
                    return StatusAndDuration(Status(ErrorCodes::ExceededTimeLimit,
                                                     "waiting for replication timed out"),
                                              Milliseconds(timeoutTimer.millis()));
                }

                if (writeConcern.wTimeout == -1) {
                    return StatusAndDuration(Status(ErrorCodes::ExceededTimeLimit,
                                                     "replication not finished when checked"),
                                              Milliseconds(timeoutTimer.millis()));
                }

                // TODO (dannenberg) is this the best sleep amount?
                sleepmillis(1);
                txn->checkForInterrupt();
            }

        }
        catch (const DBException& ex) {
            return StatusAndDuration(ex.toStatus(), Milliseconds(timeoutTimer.millis()));
        }
    }

    ReplicationCoordinator::StatusAndDuration
            LegacyReplicationCoordinator::awaitReplicationOfLastOpForClient(
                    const OperationContext* txn,
                    const WriteConcernOptions& writeConcern) {
        return awaitReplication(txn, txn->getClient()->getLastOp(), writeConcern);
    }

    ReplicationCoordinator::StatusAndDuration
            LegacyReplicationCoordinator::awaitReplicationOfLastOpApplied(
                    const OperationContext* txn,
                    const WriteConcernOptions& writeConcern) {
        return awaitReplication(txn, theReplSet->lastOpTimeWritten, writeConcern);
    }

namespace {
    /**
     * Waits up to timeout milliseconds for one secondary to get within threshold milliseconds
     * of us.
     */
    Status _waitForSecondary(const ReplicationCoordinator::Milliseconds& timeout,
                             const ReplicationCoordinator::Milliseconds& threshold) {
        if (theReplSet->getConfig().members.size() <= 1) {
            return Status(ErrorCodes::ExceededTimeLimit,
                          mongoutils::str::stream() << "no secondaries within " <<
                                  threshold.total_seconds() << " seconds of my optime");
        }

        long long timeoutTime, now, start;
        timeoutTime = now = start = curTimeMillis64()/1000;
        timeoutTime += timeout.total_seconds();

        OpTime lastOp = repl::theReplSet->lastOpTimeWritten;
        OpTime closest = repl::theReplSet->lastOtherElectableOpTime();
        long long int diff = lastOp.getSecs() - closest.getSecs();
        while (now <= timeoutTime && (diff < 0 || diff > threshold.total_seconds())) {
            sleepsecs(1);
            now = curTimeMillis64() / 1000;

            lastOp = repl::theReplSet->lastOpTimeWritten;
            closest = repl::theReplSet->lastOtherElectableOpTime();
            diff = lastOp.getSecs() - closest.getSecs();
        }

        if (diff < 0) {
            // not our problem but we'll wait until things settle down
            return Status(ErrorCodes::SecondaryAheadOfPrimary,
                          "someone is ahead of the primary?");
        }
        if (diff > threshold.total_seconds()) {
            return Status(ErrorCodes::ExceededTimeLimit,
                          mongoutils::str::stream() << "no secondaries within " <<
                                  threshold.total_seconds() << " seconds of my optime");
        }
        return Status::OK();
    }
} // namespace

    Status LegacyReplicationCoordinator::stepDown(OperationContext* txn,
                                                  bool force,
                                                  const Milliseconds& waitTime,
                                                  const Milliseconds& stepdownTime) {
        invariant(getReplicationMode() == modeReplSet);
        if (!getCurrentMemberState().primary()) {
            return Status(ErrorCodes::NotMaster, "not primary so can't step down");
        }

        if (!force) {
            Status status = _waitForSecondary(waitTime, Milliseconds(10 * 1000));
            if (!status.isOK()) {
                return status;
            }
        }

        // step down
        bool worked = repl::theReplSet->stepDown(txn, stepdownTime.total_seconds());
        if (!worked) {
            return Status(ErrorCodes::NotMaster, "not primary so can't step down");
        }
        return Status::OK();
    }

    bool LegacyReplicationCoordinator::isMasterForReportingPurposes() {
        // we must check replSet since because getReplicationMode() isn't aware of modeReplSet
        // until theReplSet is initialized
        if (_settings.usingReplSets()) {
            if (theReplSet && getCurrentMemberState().primary()) {
                return true;
            }
            return false;
        }

        if (!_settings.slave)
            return true;

        if (replAllDead) {
            return false;
        }

        if (_settings.master) {
            // if running with --master --slave, allow.
            return true;
        }

        return false;
    }

    bool LegacyReplicationCoordinator::canAcceptWritesForDatabase(const StringData& dbName) {
        // we must check replSet since because getReplicationMode() isn't aware of modeReplSet
        // until theReplSet is initialized
        if (_settings.usingReplSets()) {
            if (theReplSet && getCurrentMemberState().primary()) {
                return true;
            }
            return dbName == "local";
        }

        if (!_settings.slave)
            return true;

        // TODO(dannenberg) replAllDead is bad and should be removed when master slave is removed
        if (replAllDead) {
            return dbName == "local";
        }

        if (_settings.master) {
            // if running with --master --slave, allow.
            return true;
        }

        return dbName == "local";
    }

    Status LegacyReplicationCoordinator::checkCanServeReadsFor(OperationContext* txn,
                                                               const NamespaceString& ns,
                                                               bool slaveOk) {
        if (txn->isGod()) {
            return Status::OK();
        }
        if (canAcceptWritesForDatabase(ns.db())) {
            return Status::OK();
        }
        if (getReplicationMode() == modeMasterSlave && _settings.slave == SimpleSlave) {
            return Status::OK();
        }
        if (slaveOk) {
            if (getReplicationMode() == modeMasterSlave || getReplicationMode() == modeNone) {
                return Status::OK();
            }
            if (getCurrentMemberState().secondary()) {
                return Status::OK();
            }
            return Status(ErrorCodes::NotMasterOrSecondaryCode,
                         "not master or secondary; cannot currently read from this replSet member");
        }
        return Status(ErrorCodes::NotMasterNoSlaveOkCode,
                      "not master and slaveOk=false");

    }

    bool LegacyReplicationCoordinator::shouldIgnoreUniqueIndex(const IndexDescriptor* idx) {
        if (!idx->unique()) {
            return false;
        }
        if (!theReplSet) {
            return false;
        }
        // see SERVER-6671
        MemberState ms = theReplSet->state();
        if (! ((ms == MemberState::RS_STARTUP2) ||
               (ms == MemberState::RS_RECOVERING) ||
               (ms == MemberState::RS_ROLLBACK))) {
            return false;
        }
        // Never ignore _id index
        if (idx->isIdIndex()) {
            return false;
        }

        return true;
    }

    Status LegacyReplicationCoordinator::setLastOptime(OperationContext* txn,
                                                       const OID& rid,
                                                       const OpTime& ts) {
        {
            boost::lock_guard<boost::mutex> lock(_mutex);
            SlaveOpTimeMap::const_iterator it(_slaveOpTimeMap.find(rid));

            if (rid != getMyRID()) {
                if ((it != _slaveOpTimeMap.end()) && (ts <= it->second)) {
                    // Only update if ts is newer than what we have already
                    return Status::OK();
                }

                BSONObj config;
                if (getReplicationMode() == modeReplSet) {
                    invariant(_ridMemberMap.count(rid));
                    Member* mem = _ridMemberMap[rid];
                    invariant(mem);
                    config = BSON("_id" << mem->id() << "host" << mem->h().toString());
                }
                else if (getReplicationMode() == modeMasterSlave){
                    config = BSON("host" << txn->getClient()->getRemote().toString());
                }
                LOG(2) << "received notification that node with RID " << rid << " and config "
                       << config << " has reached optime: " << ts;

                // This is what updates the progress information used for satisfying write concern
                // and wakes up threads waiting for replication.
                if (!updateSlaveTracking(BSON("_id" << rid), config, ts)) {
                    return Status(ErrorCodes::NodeNotFound,
                                  str::stream() << "could not update node with _id: "
                                          << config["_id"].Int() << " and RID " << rid
                                          << " because it cannot be found in current ReplSetConfig "
                                          << theReplSet->getConfig().toString());
                }
            }

            // This updates the _slaveOpTimeMap which is used for forwarding slave progress
            // upstream in chained replication.
            LOG(2) << "Updating our knowledge of the replication progress for node with RID " <<
                    rid << " to be at optime " << ts;
            _slaveOpTimeMap[rid] = ts;
        }

        if (getReplicationMode() == modeReplSet && !getCurrentMemberState().primary()) {
            // pass along if we are not primary
            theReplSet->syncSourceFeedback.forwardSlaveProgress();
        }
        return Status::OK();
    }

    Status LegacyReplicationCoordinator::setMyLastOptime(OperationContext* txn, const OpTime& ts) {
        if (getReplicationMode() == modeReplSet) {
            theReplSet->lastOpTimeWritten = ts;
        }
        return setLastOptime(txn, _myRID, ts);
    }

    OpTime LegacyReplicationCoordinator::getMyLastOptime() const {
        boost::lock_guard<boost::mutex> lock(_mutex);

        SlaveOpTimeMap::const_iterator it(_slaveOpTimeMap.find(_myRID));
        if (it == _slaveOpTimeMap.end()) {
            return OpTime(0,0);
        }
        OpTime legacyMapOpTime = it->second;
        OpTime legacyOpTime = theReplSet->lastOpTimeWritten;
        // TODO(emilkie): SERVER-15209
        // This currently fails because a PRIMARY can see an old optime for itself
        // come through the spanning tree, which updates the slavemap but not the variable.
        // replsets_priority1.js is a test that hits this condition (sometimes) and fails.
        //fassert(18695, legacyOpTime == legacyMapOpTime);
        return legacyOpTime;
    }

    OID LegacyReplicationCoordinator::getElectionId() {
        return theReplSet->getElectionId();
    }

    OID LegacyReplicationCoordinator::getMyRID() const {
        return _myRID;
    }

    int LegacyReplicationCoordinator::getMyId() const {
        invariant(theReplSet);
        return theReplSet->myConfig()._id;
    }

    void LegacyReplicationCoordinator::setFollowerMode(const MemberState& newState) {
        if (newState.secondary() &&
                theReplSet->state().recovering() &&
                theReplSet->mgr->shouldBeRecoveringDueToAuthIssue()) {
            // If tryToGoLiveAsSecondary is trying to take us from RECOVERING to SECONDARY, but we
            // still have an authIssue, don't actually change states.
            return;
        }
        theReplSet->changeState(newState);
    }

    bool LegacyReplicationCoordinator::isWaitingForApplierToDrain() {
        return BackgroundSync::get()->isAssumingPrimary_inlock();
    }

    void LegacyReplicationCoordinator::signalDrainComplete() {
        // nothing further to do
    }

    void LegacyReplicationCoordinator::prepareReplSetUpdatePositionCommand(
            OperationContext* txn,
            BSONObjBuilder* cmdBuilder) {
        invariant(getReplicationMode() == modeReplSet);
        boost::lock_guard<boost::mutex> lock(_mutex);
        cmdBuilder->append("replSetUpdatePosition", 1);
        // create an array containing objects each member connected to us and for ourself
        BSONArrayBuilder arrayBuilder(cmdBuilder->subarrayStart("optimes"));
        OID myID = getMyRID();
        {
            for (SlaveOpTimeMap::const_iterator itr = _slaveOpTimeMap.begin();
                    itr != _slaveOpTimeMap.end(); ++itr) {
                const OID& rid = itr->first;
                BSONObjBuilder entry(arrayBuilder.subobjStart());
                entry.append("_id", rid);
                entry.append("optime", itr->second);
                // SERVER-14550 Even though the "config" field isn't used on the other end in 2.8,
                // we need to keep sending it for 2.6 compatibility.
                // TODO(spencer): Remove this after 2.8 is released.
                if (rid == myID) {
                    entry.append("config", theReplSet->myConfig().asBson());
                }
                else {
                    Member* member = _ridMemberMap[rid];
                    invariant(member);
                    BSONObj config = member->config().asBson();
                    entry.append("config", config);
                }
            }
        }
    }

    void LegacyReplicationCoordinator::prepareReplSetUpdatePositionCommandHandshakes(
            OperationContext* txn,
            std::vector<BSONObj>* handshakes) {
        invariant(getReplicationMode() == modeReplSet);
        boost::lock_guard<boost::mutex> lock(_mutex);
        // handshake obj for us
        BSONObjBuilder cmd;
        cmd.append("replSetUpdatePosition", 1);
        BSONObjBuilder sub (cmd.subobjStart("handshake"));
        sub.append("handshake", getMyRID());
        sub.append("member", theReplSet->selfId());
        sub.append("config", theReplSet->myConfig().asBson());
        sub.doneFast();
        handshakes->push_back(cmd.obj());

        // handshake objs for all chained members
        for (OIDMemberMap::const_iterator itr = _ridMemberMap.begin();
             itr != _ridMemberMap.end(); ++itr) {
            BSONObjBuilder cmd;
            cmd.append("replSetUpdatePosition", 1);
            // outer handshake indicates this is a handshake command
            // inner is needed as part of the structure to be passed to gotHandshake
            BSONObjBuilder subCmd (cmd.subobjStart("handshake"));
            subCmd.append("handshake", itr->first);
            subCmd.append("member", itr->second->id());
            subCmd.append("config", itr->second->config().asBson());
            subCmd.doneFast();
            handshakes->push_back(cmd.obj());
        }
    }

    Status LegacyReplicationCoordinator::processReplSetGetStatus(BSONObjBuilder* result) {
        theReplSet->summarizeStatus(*result);
        return Status::OK();
    }

    void LegacyReplicationCoordinator::fillIsMasterForReplSet(IsMasterResponse* result) {
        invariant(getSettings().usingReplSets());
        if (getReplicationMode() != ReplicationCoordinator::modeReplSet
                || getCurrentMemberState().removed()) {
            result->markAsNoConfig();
        }
        else {
            BSONObjBuilder resultBuilder;
            theReplSet->fillIsMaster(resultBuilder);
            Status status = result->initialize(resultBuilder.done());
            fassert(18821, status);
        }
    }

    void LegacyReplicationCoordinator::processReplSetGetConfig(BSONObjBuilder* result) {
        result->append("config", theReplSet->config().asBson());
    }

    bool LegacyReplicationCoordinator::_setMaintenanceMode_inlock(OperationContext* txn,
                                                                  bool activate) {
        if (theReplSet->state().primary()) {
            return false;
        }

        if (activate) {
            log() << "replSet going into maintenance mode (" << _maintenanceMode
                  << " other tasks)" << rsLog;

            _maintenanceMode++;
            theReplSet->changeState(MemberState::RS_RECOVERING);
        }
        else if (_maintenanceMode > 0) {
            _maintenanceMode--;
            // no need to change state, syncTail will try to go live as a secondary soon

            log() << "leaving maintenance mode (" << _maintenanceMode << " other tasks)" << rsLog;
        }
        else {
            return false;
        }

        fassert(16844, _maintenanceMode >= 0);
        return true;
    }

    Status LegacyReplicationCoordinator::setMaintenanceMode(OperationContext* txn, bool activate) {
        // Lock here to prevent state from changing between checking the state and changing it
        Lock::GlobalWrite writeLock(txn->lockState());
        boost::lock_guard<boost::mutex> lock(_mutex);

        if (!_setMaintenanceMode_inlock(txn, activate)) {
            if (theReplSet->isPrimary()) {
                return Status(ErrorCodes::NotSecondary, "primaries can't modify maintenance mode");
            }
            else {
                return Status(ErrorCodes::OperationFailed, "already out of maintenance mode");
            }
        }
        return Status::OK();
    }

    bool LegacyReplicationCoordinator::getMaintenanceMode() {
        boost::lock_guard<boost::mutex> lock(_mutex);
        return _maintenanceMode > 0;
    }

    Status LegacyReplicationCoordinator::processHeartbeat(const ReplSetHeartbeatArgs& args,
                                                          ReplSetHeartbeatResponse* response) {
        if (args.getProtocolVersion() != 1) {
            return Status(ErrorCodes::BadValue, "incompatible replset protocol version");
        }

        {
            if (_settings.ourSetName() != args.getSetName()) {
                log() << "replSet set names do not match, our cmdline: " << _settings.replSet
                      << rsLog;
                log() << "replSet s: " << args.getSetName() << rsLog;
                response->noteMismatched();
                return Status(ErrorCodes::BadValue, "repl set names do not match");
            }
        }

        response->noteReplSet();
        if( (theReplSet == 0) || (theReplSet->startupStatus == ReplSetImpl::LOADINGCONFIG) ) {
            if (!args.getSenderHost().empty()) {
                scoped_lock lck( _settings.discoveredSeeds_mx );
                _settings.discoveredSeeds.insert(args.getSenderHost().toString());
            }
            response->setHbMsg("still initializing");
            return Status::OK();
        }

        if (theReplSet->name() != args.getSetName()) {
            response->noteMismatched();
            return Status(ErrorCodes::BadValue, "repl set names do not match (2)");
        }
        response->setSetName(theReplSet->name());

        MemberState currentState = theReplSet->state();
        response->setState(currentState.s);
        if (currentState == MemberState::RS_PRIMARY) {
            response->setElectionTime(theReplSet->getElectionTime().asDate());
        }

        response->setElectable(theReplSet->iAmElectable());
        response->setHbMsg(theReplSet->hbmsg());
        response->setTime(Seconds(time(0)));
        response->setOpTime(theReplSet->lastOpTimeWritten.asDate());
        const HostAndPort syncTarget = BackgroundSync::get()->getSyncTarget();
        if (!syncTarget.empty()) {
            response->setSyncingTo(syncTarget.toString());
        }

        int v = theReplSet->config().version;
        response->setVersion(v);
        if (v > args.getConfigVersion()) {
            ReplicaSetConfig config;
            fassert(18635, config.initialize(theReplSet->config().asBson()));
            response->setConfig(config);
        }

        Member* from = NULL;
        if (v == args.getConfigVersion() && args.getSenderId() != -1) {
            from = theReplSet->getMutableMember(args.getSenderId());
        }
        if (!from) {
            from = theReplSet->findByName(args.getSenderHost().toString());
            if (!from) {
                return Status::OK();
            }
        }

        // if we thought that this node is down, let it know
        if (!from->hbinfo().up()) {
            response->noteStateDisagreement();
        }

        // note that we got a heartbeat from this node
        theReplSet->mgr->send(stdx::bind(&ReplSet::msgUpdateHBRecv,
                                         theReplSet, from->hbinfo().id(), time(0)));

        return Status::OK();
    }

    Status LegacyReplicationCoordinator::checkReplEnabledForCommand(BSONObjBuilder* result) {
        if (!_settings.usingReplSets()) {
            if (serverGlobalParams.configsvr) {
                result->append("info", "configsvr"); // for shell prompt
            }
            return Status(ErrorCodes::NoReplicationEnabled, "not running with --replSet");
        }

        if( theReplSet == 0 ) {
            result->append("startupStatus", ReplSet::startupStatus);
            if( ReplSet::startupStatus == ReplSet::EMPTYCONFIG )
                result->append("info", "run rs.initiate(...) if not yet done for the set");
            return Status(ErrorCodes::NotYetInitialized, ReplSet::startupStatusMsg.empty() ?
                    "replset unknown error 2" : ReplSet::startupStatusMsg.get());
        }

        return Status::OK();
    }

    Status LegacyReplicationCoordinator::processReplSetReconfig(OperationContext* txn,
                                                                const ReplSetReconfigArgs& args,
                                                                BSONObjBuilder* resultObj) {

        if( args.force && !theReplSet ) {
            _settings.reconfig = args.newConfigObj.getOwned();
            resultObj->append("msg",
                              "will try this config momentarily, try running rs.conf() again in a "
                                      "few seconds");
            return Status::OK();
        }

        // TODO(dannenberg) once reconfig processing has been figured out in the impl, this should
        // be moved out of processReplSetReconfig and into the command body like all other cmds
        Status status = checkReplEnabledForCommand(resultObj);
        if (!status.isOK()) {
            return status;
        }

        if( !args.force && !theReplSet->box.getState().primary() ) {
            return Status(ErrorCodes::NotMaster,
                          "replSetReconfig command must be sent to the current replica set "
                                  "primary.");
        }

        try {
            {
                // just make sure we can get a write lock before doing anything else.  we'll
                // reacquire one later.  of course it could be stuck then, but this check lowers the
                // risk if weird things are up - we probably don't want a change to apply 30 minutes
                // after the initial attempt.
                time_t t = time(0);
                Lock::GlobalWrite lk(txn->lockState());
                if( time(0)-t > 20 ) {
                    return Status(ErrorCodes::ExceededTimeLimit,
                                  "took a long time to get write lock, so not initiating.  "
                                          "Initiate when server less busy?");
                }
            }

            scoped_ptr<ReplSetConfig> newConfig(ReplSetConfig::make(txn, args.newConfigObj, args.force));

            log() << "replSet replSetReconfig config object parses ok, " <<
                    newConfig->members.size() << " members specified" << rsLog;

            Status status = ReplSetConfig::legalChange(theReplSet->getConfig(), *newConfig);
            if (!status.isOK()) {
                return status;
            }

            checkMembersUpForConfigChange(*newConfig, *resultObj, false);

            log() << "replSet replSetReconfig [2]" << rsLog;

            theReplSet->haveNewConfig(txn, *newConfig, true);
            ReplSet::startupStatusMsg.set("replSetReconfig'd");
        }
        catch(const DBException& e) {
            log() << "replSet replSetReconfig exception: " << e.what() << rsLog;
            return e.toStatus();
        }

        resetSlaveCache();
        return Status::OK();
    }

    Status LegacyReplicationCoordinator::processReplSetInitiate(OperationContext* txn,
                                                                const BSONObj& configObj,
                                                                BSONObjBuilder* resultObj) {

        log() << "replSet replSetInitiate admin command received from client" << rsLog;

        if (!_settings.usingReplSets()) {
            return Status(ErrorCodes::NoReplicationEnabled, "server is not running with --replSet");
        }

        if( theReplSet ) {
            resultObj->append("info",
                              "try querying " + rsConfigNs + " to see current configuration");
            return Status(ErrorCodes::AlreadyInitialized, "already initialized");
        }

        try {
            {
                // just make sure we can get a write lock before doing anything else.  we'll
                // reacquire one later.  of course it could be stuck then, but this check lowers the
                // risk if weird things are up.
                time_t t = time(0);
                Lock::GlobalWrite lk(txn->lockState());
                if( time(0)-t > 10 ) {
                    return Status(ErrorCodes::ExceededTimeLimit,
                                  "took a long time to get write lock, so not initiating.  "
                                          "Initiate when server less busy?");
                }

                /* check that we don't already have an oplog.  that could cause issues.
                   it is ok if the initiating member has *other* data than that.
                   */
                BSONObj o;
                if( Helpers::getFirst(txn, rsoplog, o) ) {
                    return Status(ErrorCodes::AlreadyInitialized,
                                  rsoplog + string(" is not empty on the initiating member.  "
                                          "cannot initiate."));
                }
            }

            if( ReplSet::startupStatus == ReplSet::BADCONFIG ) {
                resultObj->append("info", ReplSet::startupStatusMsg.get());
                return Status(ErrorCodes::InvalidReplicaSetConfig,
                              "server already in BADCONFIG state (check logs); not initiating");
            }
            if( ReplSet::startupStatus != ReplSet::EMPTYCONFIG ) {
                resultObj->append("startupStatus", ReplSet::startupStatus);
                resultObj->append("info", _settings.replSet);
                return Status(ErrorCodes::InvalidReplicaSetConfig,
                              "all members and seeds must be reachable to initiate set");
            }

            scoped_ptr<ReplSetConfig> newConfig;
            try {
                newConfig.reset(ReplSetConfig::make(txn, configObj));
            } catch (const DBException& e) {
                log() << "replSet replSetInitiate exception: " << e.what() << rsLog;
                return Status(ErrorCodes::InvalidReplicaSetConfig,
                              mongoutils::str::stream() << "couldn't parse cfg object " << e.what());
            }

            if( newConfig->version > 1 ) {
                return Status(ErrorCodes::InvalidReplicaSetConfig,
                              "can't initiate with a version number greater than 1");
            }

            log() << "replSet replSetInitiate config object parses ok, " <<
                    newConfig->members.size() << " members specified" << rsLog;

            checkMembersUpForConfigChange(*newConfig, *resultObj, true);

            log() << "replSet replSetInitiate all members seem up" << rsLog;

            createOplog(txn);

            Lock::GlobalWrite lk(txn->lockState());
            BSONObj comment = BSON( "msg" << "initiating set");
            newConfig->saveConfigLocally(txn, comment);
            log() << "replSet replSetInitiate config now saved locally.  "
                "Should come online in about a minute." << rsLog;
            resultObj->append("info",
                              "Config now saved locally.  Should come online in about a minute.");
            ReplSet::startupStatus = ReplSet::SOON;
            ReplSet::startupStatusMsg.set("Received replSetInitiate - "
                                          "should come online shortly.");
        }
        catch(const DBException& e ) {
            return e.toStatus();
        }

        return Status::OK();
    }

    Status LegacyReplicationCoordinator::processReplSetGetRBID(BSONObjBuilder* resultObj) {
        resultObj->append("rbid", _rbid);
        return Status::OK();
    }

namespace {
    bool _shouldVeto(unsigned id, std::string* errmsg) {
        const Member* primary = theReplSet->box.getPrimary();
        const Member* hopeful = theReplSet->findById(id);
        const Member *highestPriority = theReplSet->getMostElectable();

        if (!hopeful) {
            *errmsg = str::stream() << "replSet couldn't find member with id " << id;
            return true;
        }

        if (theReplSet->isPrimary() &&
            theReplSet->lastOpTimeWritten >= hopeful->hbinfo().opTime) {
            // hbinfo is not updated, so we have to check the primary's last optime separately
            *errmsg = str::stream() << "I am already primary, " << hopeful->fullName() <<
                " can try again once I've stepped down";
            return true;
        }

        if (primary &&
                (hopeful->hbinfo().id() != primary->hbinfo().id()) &&
                (primary->hbinfo().opTime >= hopeful->hbinfo().opTime)) {
            // other members might be aware of more up-to-date nodes
            *errmsg = str::stream() << hopeful->fullName() <<
                " is trying to elect itself but " << primary->fullName() <<
                " is already primary and more up-to-date";
            return true;
        }

        if (highestPriority &&
            highestPriority->config().priority > hopeful->config().priority) {
            *errmsg = str::stream() << hopeful->fullName() << " has lower priority than " <<
                highestPriority->fullName();
            return true;
        }

        if (!theReplSet->isElectable(id)) {
            *errmsg = str::stream() << "I don't think " << hopeful->fullName() <<
                " is electable";
            return true;
        }

        return false;
    }
} // namespace

    Status LegacyReplicationCoordinator::processReplSetFresh(const ReplSetFreshArgs& args,
                                                             BSONObjBuilder* resultObj){
        if( args.setName != theReplSet->name() ) {
            return Status(ErrorCodes::ReplicaSetNotFound,
                          str::stream() << "wrong repl set name. Expected: " <<
                                  theReplSet->name() << ", received: " << args.setName);
        }

        bool weAreFresher = false;
        if( theReplSet->config().version > args.cfgver ) {
            log() << "replSet member " << args.who << " is not yet aware its cfg version " <<
                    args.cfgver << " is stale" << rsLog;
            resultObj->append("info", "config version stale");
            weAreFresher = true;
        }
        // check not only our own optime, but any other member we can reach
        else if( args.opTime < theReplSet->lastOpTimeWritten ||
                 args.opTime < theReplSet->lastOtherOpTime())  {
            weAreFresher = true;
        }
        resultObj->appendDate("opTime", theReplSet->lastOpTimeWritten.asDate());
        resultObj->append("fresher", weAreFresher);

        std::string errmsg;
        bool veto = _shouldVeto(args.id, &errmsg);
        resultObj->append("veto", veto);
        if (veto) {
            resultObj->append("errmsg", errmsg);
        }

        return Status::OK();
    }

    Status LegacyReplicationCoordinator::processReplSetElect(const ReplSetElectArgs& args,
                                                             BSONObjBuilder* resultObj) {
        theReplSet->electCmdReceived(args.set, args.whoid, args.cfgver, args.round, resultObj);
        return Status::OK();
    }

    void LegacyReplicationCoordinator::incrementRollbackID() {
        ++_rbid;
    }

    Status LegacyReplicationCoordinator::processReplSetFreeze(int secs, BSONObjBuilder* resultObj) {
        if (theReplSet->freeze(secs)) {
            if (secs == 0) {
                resultObj->append("info","unfreezing");
            }
        }
        if (secs == 1) {
            resultObj->append("warning", "you really want to freeze for only 1 second?");
        }
        return Status::OK();
    }

    Status LegacyReplicationCoordinator::processReplSetSyncFrom(const HostAndPort& target,
                                                                BSONObjBuilder* resultObj) {
        resultObj->append("syncFromRequested", target.toString());

        return theReplSet->forceSyncFrom(target.toString(), resultObj);
    }

    Status LegacyReplicationCoordinator::processReplSetUpdatePosition(
            OperationContext* txn,
            const UpdatePositionArgs& updates) {

        for (UpdatePositionArgs::UpdateIterator update = updates.updatesBegin();
                update != updates.updatesEnd();
                ++update) {
            Status status = setLastOptime(txn, update->rid, update->ts);
            if (!status.isOK()) {
                return status;
            }
        }
        return Status::OK();
    }

    Status LegacyReplicationCoordinator::processHandshake(const OperationContext* txn,
                                                          const HandshakeArgs& handshake) {
        LOG(2) << "Received handshake " << handshake.toBSON();

        boost::lock_guard<boost::mutex> lock(_mutex);
        if (getReplicationMode() != modeReplSet) {
            return Status::OK();
        }

        int memberID = handshake.getMemberId();
        Member* member = theReplSet->getMutableMember(memberID);
        // it is possible that a node that was removed in a reconfig tried to handshake this node
        // in that case, the Member will no longer be in theReplSet's _members List and member
        // will be NULL
        if (!member) {
            return Status(ErrorCodes::NodeNotFound,
                          str::stream() << "Node with replica set member ID " << memberID <<
                                  " could not be found in replica set config while attempting to "
                                  "associate it with RID " << handshake.getRid() <<
                                  " in replication handshake. ReplSet config: " <<
                                  theReplSet->getConfig().toString());
        }

        _ridMemberMap[handshake.getRid()] = member;
        theReplSet->syncSourceFeedback.forwardSlaveHandshake();
        return Status::OK();
    }

    bool LegacyReplicationCoordinator::buildsIndexes() {
        return theReplSet->buildIndexes();
    }

    vector<HostAndPort> LegacyReplicationCoordinator::getHostsWrittenTo(const OpTime& op) {
        vector<BSONObj> configs = repl::getHostsWrittenTo(op);
        vector<HostAndPort> hosts;
        for (size_t i = 0; i < configs.size(); ++i) {
            hosts.push_back(HostAndPort(configs[i]["host"].String()));
        }
        return hosts;
    }

    vector<HostAndPort> LegacyReplicationCoordinator::getOtherNodesInReplSet() const {
        std::vector<HostAndPort> rsMembers;
        const unsigned rsSelfId = theReplSet->selfId();
        const std::vector<repl::ReplSetConfig::MemberCfg>& rsMemberConfigs =
            repl::theReplSet->config().members;
        for (size_t i = 0; i < rsMemberConfigs.size(); ++i) {
            const unsigned otherId = rsMemberConfigs[i]._id;
            if (rsSelfId == otherId)
                continue;
            const repl::Member* other = repl::theReplSet->findById(otherId);
            if (!other) {
                continue;
            }
            rsMembers.push_back(other->h());
        }
        return rsMembers;
    }

    Status LegacyReplicationCoordinator::checkIfWriteConcernCanBeSatisfied(
            const WriteConcernOptions& writeConcern) const {
        // TODO: rewrite this method with the correct version. Note that this just a
        // temporary stub for secondary throttle.

        if (getReplicationMode() == ReplicationCoordinator::modeReplSet) {
            if (writeConcern.wNumNodes > 1 && theReplSet->config().getMajority() <= 1) {
                return Status(ErrorCodes::CannotSatisfyWriteConcern, "not enough nodes");
            }
        }

        return Status::OK();
    }

    BSONObj LegacyReplicationCoordinator::getGetLastErrorDefault() {
        if (getReplicationMode() == modeReplSet) {
            return theReplSet->getLastErrorDefault;
        }
        return BSONObj();
    }

    bool LegacyReplicationCoordinator::isReplEnabled() const {
        return _settings.usingReplSets() || _settings.slave || _settings.master;
    }

    HostAndPort LegacyReplicationCoordinator::chooseNewSyncSource() {
        const Member* member = theReplSet->getMemberToSyncTo();
        if (member) {
            return member->h();
        }
        else {
            return HostAndPort();
        }
    }

    void LegacyReplicationCoordinator::blacklistSyncSource(const HostAndPort& host, Date_t until) {
        theReplSet->veto(host.toString(), until);
    }

    void LegacyReplicationCoordinator::resetLastOpTimeFromOplog(OperationContext* txn) {
        theReplSet->loadLastOpTimeWritten(txn, false);
    }

    bool LegacyReplicationCoordinator::shouldChangeSyncSource(const HostAndPort& currentSource) {
        return theReplSet->shouldChangeSyncTarget(currentSource);
    }

} // namespace repl
} // namespace mongo

max_stars_repo_name: TylerBrock/mongo

max_issues_repo_name: TylerBrock/mongo

max_forks_repo_name: TylerBrock/mongo


text: #include <boost/algorithm/cxx11/find_if_not.hpp>

ext: hpp

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


text:
/*    Copyright (c) 2010-2019, Delft University of Technology
 *    All rigths reserved
 *
 *    This file is part of the Tudat. Redistribution and use in source and
 *    binary forms, with or without modification, are permitted exclusively
 *    under the terms of the Modified BSD license. You should have received
 *    a copy of the license with this file. If not, please or visit:
 *    http://tudat.tudelft.nl/LICENSE.
 *
 *    References
 *      Blake, W.B. Missile Datcom User's Manual - 1997 Fortran 90 Version, AFRL-VA-WP-TR-1998-3009
 *          Air Force Research Laboratory, 1998.
 *
 */

#include <iostream>
#include <iterator>
#include <sstream>

#include "tudat/astro/basic_astro/unitConversions.h"

#include "tudat/io/missileDatcomData.h"
#include "tudat/io/missileDatcomReader.h"
#include "tudat/io/basicInputOutput.h"
#include "tudat/math/basic/mathematicalConstants.h"

#include <boost/algorithm/string.hpp>
#include <cmath>

namespace tudat
{
namespace input_output
{

using unit_conversions::convertDegreesToRadians;
using std::iterator;

//! Constructor that reads and processes Missile Datcom output.
MissileDatcomData::MissileDatcomData( const std::string& fileNameAndPath )
{
    MissileDatcomReader myMissileDatcomReader( fileNameAndPath );
    convertDatcomData( myMissileDatcomReader.getMissileDatcomData( ) );
}

//! Function to convert the MissileDatcomData.
void MissileDatcomData::convertDatcomData( const std::vector< double >& datcomData )
{
    std::vector< double > datcomDataToBeConverted = datcomData;

    // Add an extra item at the begin, such that the first real value is at entry 1.
    // The same indices as described in the MissileDatcom user manual can now be used.
    std::vector< double >::iterator it;
    it = datcomDataToBeConverted.begin( );
    datcomDataToBeConverted.insert( it,-0.0 );

    // The first "card" is the Flight condition data array, which is the same for every "case".
    numberOfAnglesOfAttack_ = datcomDataToBeConverted[ 1 ];

    for ( int iteratorDataVector_= 2; iteratorDataVector_ < ( 2 + numberOfAnglesOfAttack_ );
          iteratorDataVector_++ )
    {
        angleOfAttack_.push_back( datcomDataToBeConverted[ iteratorDataVector_ ] );
    }

    sideslipAngle_ = datcomDataToBeConverted[ 22 ];

    rollAngle_ = datcomDataToBeConverted[ 23 ];

    numberOfMachNumbers_ = datcomDataToBeConverted[ 24 ];

    for ( int iteratorDataVector_= 25; iteratorDataVector_ < ( 25 + numberOfMachNumbers_ );
          iteratorDataVector_++ )
    {
        machNumber_.push_back( datcomDataToBeConverted[ iteratorDataVector_ ] );
    }

    for ( int iteratorDataVector_= 45; iteratorDataVector_ < ( 25 + numberOfMachNumbers_ );
          iteratorDataVector_++ )
    {
        altitudes_.push_back( datcomDataToBeConverted[ iteratorDataVector_ ] );
    }

    for ( int iteratorDataVector_= 66; iteratorDataVector_ < ( 66 + numberOfMachNumbers_ );
          iteratorDataVector_++ )
    {
        reynoldsNumbers_.push_back( datcomDataToBeConverted[ iteratorDataVector_ ] );
    }

    for ( int iteratorDataVector_= 86; iteratorDataVector_ < (86 +numberOfMachNumbers_);
          iteratorDataVector_++ )
    {
        freeStreamVelocities_.push_back( datcomDataToBeConverted[ iteratorDataVector_ ] );
    }

    for ( int iteratorDataVector_= 106; iteratorDataVector_ < (106 + numberOfMachNumbers_);
          iteratorDataVector_++ )
    {
        freeStreamStaticTemperatures_.push_back( datcomDataToBeConverted[ iteratorDataVector_ ] );
    }

    // NOTE apperently the last entry of flight card is not written to de for004.dat file.
    // According to the user manual the last entry should be 145, this entry is not found in the
    // for004.dat file.
    for ( int iteratorDataVector_= 126; iteratorDataVector_ <= 144; iteratorDataVector_++ )
    {
        freeStreamStaticPressure_.push_back( datcomDataToBeConverted[ iteratorDataVector_ ] );
    }

    // Loop over Mach, angle of attack and coefficient index to fill the static coefficient array.
    for (int machIndex = 0; machIndex < numberOfMachNumbers_; machIndex++ )
    {
        for (int angleOfAttackIndex = 0; angleOfAttackIndex < numberOfAnglesOfAttack_;
            angleOfAttackIndex++ )
        {
            for (int coefficientIndex = 0; coefficientIndex < 6; coefficientIndex++ )
            {
                // The second index begins at entry 145
                // The first section has 144 entries, the second 220 and the last 400. Therefore
                // there is a repetition after 144+220+400=764 entries.
                // every coefficients has 20 entries.
                int dataVectorIndex_ = 145 + 764 * machIndex + angleOfAttackIndex
                                   + 20 * coefficientIndex;
                staticCoefficients_[ machIndex ][ angleOfAttackIndex ][ coefficientIndex ] =
                        datcomDataToBeConverted[ dataVectorIndex_ ];
            }

            for ( int coefficientIndex = 6; coefficientIndex < 11; coefficientIndex++ )
            {
                // The second index begins at entry 145
                // The first section has 144 entries, the second 220 and the last 400. Therefore
                // there is a repetition after 144+220+400=764 entries.
                // every coefficients has 20 entries.
                // The coefficients are in per degree and needs to be converted to per radian
                int dataVectorIndex_ = 145 + 764 * machIndex + angleOfAttackIndex
                                   + 20 * coefficientIndex;
                staticCoefficients_[ machIndex ][ angleOfAttackIndex ][ coefficientIndex ] =
                        datcomDataToBeConverted[ dataVectorIndex_ ]
                        / convertDegreesToRadians( 1.0 );
            }
        }
    }

    // Loop over Mach, angle of attack and coefficient index to fill the dynamic coefficient array.
    for ( int machIndex = 0; machIndex < numberOfMachNumbers_; machIndex++ )
    {
        for ( int angleOfAttackIndex = 0; angleOfAttackIndex < numberOfAnglesOfAttack_;
            angleOfAttackIndex++ )
        {
            for ( int coefficientIndex = 0; coefficientIndex < 20; coefficientIndex++ )
            {
                // The third index begins at entry 365.
                // The first section has 144 entries, the second 220 and the last 400. Therefore
                // there is a repetition after 144+220+400=764 entries.
                // every coefficients has 20 entries.
                // WARNINNG: possible error in datcom user manual. It looks like to values are
                // always in per radian (instead per degree, which is mentioned in the manual).
                int dataVectorIndex_ = 365 + 764 * machIndex + angleOfAttackIndex
                                   + 20 * coefficientIndex;
                dynamicCoefficients_[ machIndex ][ angleOfAttackIndex ][ coefficientIndex ] =
                     datcomDataToBeConverted[ dataVectorIndex_ ];
            }
        }
    }
}

//! Function to access the static coefficient database.
double MissileDatcomData::getStaticCoefficient( int machIndex, int angleOfAttackIndex,
                                                StaticCoefficientNames coefficientIndex )
{
    return staticCoefficients_[ machIndex ][ angleOfAttackIndex ][ coefficientIndex ];
}

//! Function to access the dynamic coefficient database.
double MissileDatcomData::getDynamicCoefficient( int machIndex, int angleOfAttackIndex,
                                                 DynamicCoefficientNames coefficientIndex )
{
    return dynamicCoefficients_[ machIndex ][ angleOfAttackIndex ][ coefficientIndex ];
}

//! Write the database to CSV files.
void MissileDatcomData::writeAllCoefficientsToFiles( const std::string& fileNameBase,
                                                 const int basePrecision,
                                                 const int exponentWidth )
{
    // Write coefficients to a file separately for each angle of attack.
    for ( unsigned int i = 0; i < angleOfAttack_.size( ) ; i++ )
    {
        // Make filename for specific angle of attack.
        std::ostringstream stringstream;
        stringstream << fileNameBase << "_" << i;
        std::string fileName = stringstream.str( );

        // Open output file.
        std::ofstream outputFile;
        outputFile.open( fileName.c_str( ) );
        outputFile.precision( 10 );

        // Iterate over all Mach numbers in database.
        for ( unsigned int j = 0; j < machNumber_.size( ) ; j++ )
        {
            // Write angle of attack and mach number.
            outputFile << angleOfAttack_[ i ] << " " << machNumber_[ j ] << " ";

            // Write static coefficients.
            for ( int k = 0; k < 11; k++ )
            {
                outputFile << printInFormattedScientificNotation(
                                  staticCoefficients_[ j ][ i ][ k ], basePrecision,
                                  exponentWidth ) << " ";
            }

            // Write dynamic coefficients.
            for ( int k = 0; k < 19; k++ )
            {

                outputFile << printInFormattedScientificNotation(
                                  dynamicCoefficients_[ j ][ i ][ k ], basePrecision,
                                  exponentWidth ) << " ";
            }

            outputFile << printInFormattedScientificNotation(
                              dynamicCoefficients_[ j ][ i ][ 19 ], basePrecision,
                              exponentWidth ) << std::endl;
        }

        outputFile.close( );
    }
}

// Convert degrees to radians
double deg2Rad( const double deg ) { return deg * tudat::mathematical_constants::PI / 180.0 ;}

//! Write the force and moment aerodynamic coefficients to files
void MissileDatcomData::writeForceAndMomentCoefficientsToFiles( const std::string& fileNameBase,
                                                 const int basePrecision,
                                                 const int exponentWidth )
{
    // Define string streams for file header and contents
    std::stringstream header;
    std::stringstream CFxstream; std::stringstream CFystream; std::stringstream CFzstream;
    std::stringstream CMxstream; std::stringstream CMystream; std::stringstream CMzstream;

    // Put the mach numbers and angle of attacks to the header stream
    header << "2\n";
    std::copy(machNumber_.begin(), machNumber_.end(), std::ostream_iterator<double>(header, "\t"));
    header << "\n";
    std::vector<double> angleOfAttackRadians_;

    // Convert the angle of attacks from degrees to radians
    angleOfAttackRadians_.resize( angleOfAttack_.size() );
    std::transform( angleOfAttack_.begin(), angleOfAttack_.end(), angleOfAttackRadians_.begin(), deg2Rad );
    std::copy(angleOfAttackRadians_.begin(), angleOfAttackRadians_.end(), std::ostream_iterator<double>(header, "\t"));
    header << "\n\n";

    // Loop trough the mach numbers and angle of attacks
    for (unsigned int i = 0; i < machNumber_.size() ; i++ )
    {
        for (unsigned int j = 0; j < angleOfAttack_.size() ; j++ )
        {
            // Compute the real drag and lift coefficients depending on the angle of attack
            double alpha = angleOfAttackRadians_[j];
            const double cd = staticCoefficients_[ i ][ j ][ ca ];
            const double cl = staticCoefficients_[ i ][ j ][ cn ];
            const double CD = cd * std::cos(alpha) + cl * std::sin(alpha);
            const double CL = -cd * std::sin(alpha) + cl * std::cos(alpha);

            // Add the coefficients to the relevant streams
            CFxstream << CD;                                    // Drag force coefficient (X direction)
            CFystream << staticCoefficients_[ i ][ j ][ cy ];   // Sideslip force coefficient (Y direction)
            CFzstream << CL;                                    // Lift force coefficient (Z direction)
            CMxstream << staticCoefficients_[ i ][ j ][ cll ];  // Roll moment coefficient (around X)
            CMystream << staticCoefficients_[ i ][ j ][ cm ];   // Pitch moment coefficient (around Y)
            CMzstream << staticCoefficients_[ i ][ j ][ cln ];  // Yaw moment coefficient (around Z)
            // Add separating tabulation (unless we are at the end of the line)
            if (j != angleOfAttack_.size() - 1)
            {
                CFxstream << "\t"; CFystream << "\t"; CFzstream << "\t";
                CMxstream << "\t"; CMystream << "\t"; CMzstream << "\t";
            }
        }
        // Add separating new lines (unless we are at the end of the file)
        if (i != machNumber_.size() - 1)
        {
            CFxstream << "\n"; CFystream << "\n"; CFzstream << "\n";
            CMxstream << "\n"; CMystream << "\n"; CMzstream << "\n";
        }
    }

    // Save the streams to relevant data files
    std::vector<std::string> streamsStrings = {CFxstream.str(), CFystream.str(), CFzstream.str(), CMxstream.str(), CMystream.str(), CMzstream.str()};
    std::vector<std::string> names = {"CFx", "CFy", "CFz", "CMx", "CMy", "CMz"};
    for ( unsigned int i = 0; i < 6; i++ )
    {
        std::ofstream out(fileNameBase + names[i] + ".dat");
        out << header.str() << streamsStrings[i];
        out.close();
    }
}

} // namespace input_output
} // namespace tudat


text:
#include <iostream>
#include <cstring> // runtime strcmp()

#include <boost/mp11.hpp>

using boost::mp11::mp_list;
using boost::mp11::mp_replace_at_c;
using boost::mp11::mp_size_t;
using boost::mp11::mp_at_c;
using boost::mp11::mp_plus;
using boost::mp11::mp_reverse;
using boost::mp11::mp_less;
using boost::mp11::mp_repeat_c;
using boost::mp11::mp_append;

template<int I> using mp_char = std::integral_constant<char, I>;

template <class C>
constexpr size_t seq_size(C)
{
    auto seq_ = C::value();
    int idx = 0;
    for (; seq_[idx++] !='\0'; ){}
    return idx-1;
}

template <class C1, class C2>
constexpr size_t linear_b_c_table_size(C1, C2)
{
    return (seq_size(C1{})+1)*(seq_size(C2{})+1);
}

template <class Seq2>
constexpr size_t indices_to_linear(size_t i, size_t j, Seq2)
{
    return (i)*(seq_size(Seq2{})+1)+j;
}

template <size_t LinearIndex, class Seq2>
constexpr auto linear_to_indices(Seq2)
{
    using i_type = mp_size_t<LinearIndex / (seq_size(Seq2{})+1)>;
    using j_type = mp_size_t<LinearIndex % (seq_size(Seq2{})+1)>;
    return std::pair{i_type(), j_type()};
}

template <int beg, int end, class Seq1, class Seq2>
constexpr auto LCS_Length(auto && bb_, auto && cc_, Seq1 seq1, Seq2 seq2)
{
    if constexpr (beg==end)
    {
        return std::pair{bb_, cc_};
    } else
    {
        constexpr auto w = linear_to_indices<beg>(seq2);
        constexpr auto i = w.first;
        constexpr auto j = w.second;

        if constexpr ((i>0) && (i <= seq_size(seq1)) && (j>0) && (j <= seq_size(seq2)))
        {
            using c_type = std::decay_t<decltype(cc_)>;
            using b_type = std::decay_t<decltype(bb_)>;

            if constexpr (Seq1::value()[i-1] == Seq2::value()[j-1])
            {
                using new_cc = mp_replace_at_c<c_type,  beg, mp_plus<mp_at_c<c_type, indices_to_linear(i - 1,
                        j - 1, seq2)>, mp_size_t<1>>>;
                using new_bb = mp_replace_at_c<b_type,  beg, mp_char<'\\'>>;
                return LCS_Length<beg + 1, end>(new_bb(), new_cc(), seq1, seq2);
            }
            else
            {
                using elem1 = mp_at_c<c_type, indices_to_linear(i - 1, j, seq2)>;
                using elem2 = mp_at_c<c_type, indices_to_linear(i, j - 1, seq2)>;

                if constexpr (!mp_less<elem1, elem2>::value)
                {
                    using new_cc = mp_replace_at_c<c_type,  beg, mp_at_c<c_type, indices_to_linear(i - 1, j, seq2)>>;
                    using new_bb = mp_replace_at_c<b_type,  beg, mp_char<'|'>>;
                    return LCS_Length<beg + 1, end>(new_bb(), new_cc(), seq1, seq2);
                }
                else
                {
                    using new_cc = mp_replace_at_c<c_type,  beg, mp_at_c<c_type, indices_to_linear(i, j - 1, seq2)>>;
                    using new_bb = mp_replace_at_c<b_type,  beg, mp_char<'-'>>;
                    return LCS_Length<beg + 1, end>(new_bb(), new_cc(), seq1, seq2);
                }
            }
        } else
        {
            return LCS_Length<beg + 1, end>(bb_,cc_, seq1, seq2);
        }
    }
}

template <int i, int j, class Seq1, class Seq2>
auto print_LCS_mangled(auto && b, auto && LCS_mangled, Seq1 seq1, Seq2 seq2)
{
    if constexpr((i > 0) && (j > 0))
    {
        using b_table_type = std::decay_t<decltype(b)>;
        if constexpr(std::is_same_v<mp_at_c<b_table_type, indices_to_linear(i, j, seq2)>, mp_char<'\\'>>)
        {
            using result_list_type = std::decay_t<decltype(LCS_mangled)>;
            return print_LCS_mangled<i-1,j-1>(b, mp_append<result_list_type, mp_list<mp_char<Seq1::value()[i-1]>>>(), seq1, seq2);
        } else
        if constexpr(std::is_same_v<mp_at_c<b_table_type, indices_to_linear(i, j, seq2)>, mp_char<'|'>>)
        {
            return print_LCS_mangled<i-1,j>(b, LCS_mangled, seq1, seq2);
        } else
        {
            return print_LCS_mangled<i,j-1>(b, LCS_mangled, seq1, seq2);
        }
    } else
    {
        using result_list_type = std::decay_t<decltype(LCS_mangled)>;
        return mp_reverse<result_list_type>();
    }
}

template <class Seq1, class Seq2>
constexpr auto LCS_mangled(Seq1 s1, Seq2 s2)
{
    using b_table = mp_repeat_c<mp_list<mp_char<' '>>, linear_b_c_table_size(s1, s2)>;
    using c_table = mp_repeat_c<mp_list<mp_size_t<0>>, linear_b_c_table_size(s1, s2)>;
    using LCS_Length_type = decltype(LCS_Length<0, linear_b_c_table_size(s1, s2)>(b_table(), c_table(), s1, s2));
    return print_LCS_mangled<seq_size(s1),seq_size(s2)>(LCS_Length_type().first, mp_list<>(), s1, s2);
}

using boost::mp11::mp_for_each;
using boost::mp11::mp_size;

template <class List>
struct mplist_to_char_const
{
    class apply
    {
    public:
        constexpr explicit apply(int value) : s(value), arr{0} {}

        constexpr operator char const *() const
        {
            return arr.data();
        }

        template <class C>
        constexpr void operator()( C ) { *(arr.data()+s) = C::value; s += 1; }

    private:
        int s;
        std::array<char, mp_size<List>::value + 1> arr;
    };

    constexpr decltype(auto) operator()() const
    {
        return mp_for_each<List>( apply(0));
    }
};

constexpr bool str_eq(char const* const s, char const* const t)
{
    return (*s == *t) && (*s == 0 || str_eq(s + 1, t + 1));
}

struct SEQUENCE_1 {constexpr static auto value() {return "0A00B000FB00";}};
struct SEQUENCE_2 {constexpr static auto value() {return "OOAOOOBFOOOBOOO";}};
using result_mp_list = decltype(LCS_mangled(SEQUENCE_1{}, SEQUENCE_2{}));
static_assert(std::is_same_v<result_mp_list, mp_list<mp_char<'A'>, mp_char<'B'>,  mp_char<'F'>,  mp_char<'B'>>>);
constexpr auto result = mplist_to_char_const<result_mp_list>().operator()();
static_assert(str_eq(result,"ABFB"));

int main()
{
    assert(strcmp(result, "ABFB") == 0);
    std::cout << result << std::endl;
    return 0;
}

max_stars_repo_name: wiluite/cormen-for-fun

max_issues_repo_name: wiluite/cormen-for-fun

max_forks_repo_name: wiluite/cormen-for-fun


text:
// This file is part of SWGANH which is released under the MIT license.
// See file LICENSE or go to http://swganh.com/LICENSE

#include "mysql_account_provider.h"

#include <boost/date_time/posix_time/posix_time.hpp>

#include "swganh/logger.h"

#include "swganh/database/database_manager.h"

using namespace swganh::login;
using namespace providers;
using namespace swganh::login;
using namespace std;

MysqlAccountProvider::MysqlAccountProvider(swganh::database::DatabaseManager* db_manager)
    : AccountProviderInterface()
    , db_manager_(db_manager) {}

shared_ptr<Account> MysqlAccountProvider::FindByUsername(string username)
{
    shared_ptr<Account> account = nullptr;

    try
    {
        auto conn = db_manager_->getConnection("galaxy_manager");
        auto statement = shared_ptr<sql::PreparedStatement>(conn->prepareStatement("CALL sp_FindAccountByUsername(?);"));
        statement->setString(1, username);
        auto result_set = unique_ptr<sql::ResultSet>(statement->executeQuery());

        if (result_set->next())
        {
            account = make_shared<Account>(true);

            account->account_id(result_set->getInt("id"));
            account->username(result_set->getString("username"));
            account->password(result_set->getString("password"));
            account->salt(result_set->getString("salt"));
            if (result_set->getInt("enabled") == 1)
            {
                account->Enable();
            }
            else
            {
                account->Disable();
            }

            account->algorithm("sha1");
        }
        else
        {
            LOG(warning) << "No account information found for user: " << username << endl;
        }
        while(statement->getMoreResults());
    }
    catch(sql::SQLException &e)
    {
        LOG(error) << "SQLException at " << __FILE__ << " (" << __LINE__ << ": " << __FUNCTION__ << ")";
        LOG(error) << "MySQL Error: (" << e.getErrorCode() << ": " << e.getSQLState() << ") " << e.what();
    }
    return account;
}
void MysqlAccountProvider::EndSessions()
{
    try
    {
        auto conn = db_manager_->getConnection("galaxy_manager");
        auto statement = shared_ptr<sql::PreparedStatement>(conn->prepareStatement("CALL sp_DeleteSessions();"));
        /* int rows_updated = */
        statement->executeUpdate();

    }
    catch(sql::SQLException &e)
    {
        LOG(error) << "SQLException at " << __FILE__ << " (" << __LINE__ << ": " << __FUNCTION__ << ")";
        LOG(error) << "MySQL Error: (" << e.getErrorCode() << ": " << e.getSQLState() << ") " << e.what();
    }
}
uint32_t MysqlAccountProvider::FindBySessionKey(const string& session_key)
{
    uint32_t account_id = 0;

    try
    {
        auto conn = db_manager_->getConnection("galaxy_manager");
        auto statement = shared_ptr<sql::PreparedStatement>(conn->prepareStatement("CALL sp_FindAccountBySessionKey(?)"));
        statement->setString(1, session_key);
        auto result_set = unique_ptr<sql::ResultSet>(statement->executeQuery());

        if (result_set->next())
        {
            account_id = result_set->getInt("account");

        }
        else
        {
            LOG(warning) << "No account found for session_key: " << session_key << endl;
        }
        while(statement->getMoreResults());
    }
    catch(sql::SQLException &e)
    {
        LOG(error) << "SQLException at " << __FILE__ << " (" << __LINE__ << ": " << __FUNCTION__ << ")";
        LOG(error) << "MySQL Error: (" << e.getErrorCode() << ": " << e.getSQLState() << ") " << e.what();
    }
    return account_id;
}
bool MysqlAccountProvider::CreateAccountSession(uint32_t account_id, const std::string& session_key)
{
    bool success = false;
    try
    {
        string sql = "call sp_CreateAccountSession(?,?);";
        auto conn = db_manager_->getConnection("galaxy_manager");
        auto statement = shared_ptr<sql::PreparedStatement>(conn->prepareStatement(sql));
        statement->setUInt64(1, account_id);
        statement->setString(2, session_key);
        auto rows_updated = statement->executeUpdate();
        if (rows_updated > 0)
            success = true;

    }
    catch(sql::SQLException &e)
    {
        LOG(error) << "SQLException at " << __FILE__ << " (" << __LINE__ << ": " << __FUNCTION__ << ")";
        LOG(error) << "MySQL Error: (" << e.getErrorCode() << ": " << e.getSQLState() << ") " << e.what();
    }

    return success;
}

bool MysqlAccountProvider::AutoRegisterAccount(std::string username, std::string password)
{
    bool success = false;
    try
    {
        string sql = "call sp_CreateAccount(?,?,?);";
        auto conn = db_manager_->getConnection("galaxy_manager");
        auto statement = shared_ptr<sql::PreparedStatement>(conn->prepareStatement(sql));
        statement->setString(1, username);
        statement->setString(2, password);
        statement->setString(3, "");
        auto results = unique_ptr<sql::ResultSet>(statement->executeQuery());
        if (results->next())
        {
            if (CreatePlayerAccount(results->getUInt64(1)))
                success = true;
        }
        while(statement->getMoreResults());
    }
    catch(sql::SQLException &e)
    {
        LOG(error) << "SQLException at " << __FILE__ << " (" << __LINE__ << ": " << __FUNCTION__ << ")";
        LOG(error) << "MySQL Error: (" << e.getErrorCode() << ": " << e.getSQLState() << ") " << e.what();
    }

    return success;
}
bool MysqlAccountProvider::CreatePlayerAccount(uint64_t account_id)
{
    bool success = false;
    try
    {
        string sql = "call sp_CreatePlayerAccount(?);";
        auto conn = db_manager_->getConnection("galaxy");
        auto statement = shared_ptr<sql::PreparedStatement>(conn->prepareStatement(sql));
        statement->setUInt64(1, account_id);
        auto rows_updated = statement->executeUpdate();
        if (rows_updated > 0)
            success = true;
    }
    catch(sql::SQLException &e)
    {
        LOG(error) << "SQLException at " << __FILE__ << " (" << __LINE__ << ": " << __FUNCTION__ << ")";
        LOG(error) << "MySQL Error: (" << e.getErrorCode() << ": " << e.getSQLState() << ") " << e.what();
    }

    return success;
}

ext: cc

max_stars_repo_name: obi-two/GameServer

max_issues_repo_name: obi-two/GameServer

max_forks_repo_name: obi-two/GameServer


text:
#ifndef BLUB_CORE_SIGNAL_HPP
#define BLUB_CORE_SIGNAL_HPP

#include "blub/core/globals.hpp"

#include <boost/signals2/signal.hpp>

namespace blub
{

template <typename T>
class signal : public boost::signals2::signal<T>
{
private:
    typedef boost::signals2::signal<T> t_base;

public:

    signal()
        : boost::signals2::signal<T>()
    {;}

    uint32 getNumSlots() const
    {
        return t_base::num_slots();
    }

    void disconnectAllSlots()
    {
        t_base::disconnect_all_slots();
    }
};

}

#endif // BLUB_CORE_SIGNAL_HPP


text:
#pragma once

#include <golos/protocol/authority.hpp>

#include <fc/variant.hpp>

#include <boost/container/flat_set.hpp>

#include <string>
#include <vector>

//
// Place DECLARE_OPERATION_TYPE in a .hpp file to declare
// functions related to your operation type
//
#define DECLARE_OPERATION_TYPE(OperationType)           \
namespace fc {                                          \
                                                        \
void to_variant(const OperationType&, fc::variant&);    \
void from_variant(const fc::variant&, OperationType&);  \
                                                        \
} /* fc */                                              \
                                                        \
namespace golos { namespace protocol {                  \
                                                        \
void operation_validate(const OperationType&);          \
void operation_get_required_authorities(                \
    const OperationType& op,                            \
    flat_set<account_name_type>& active,                \
    flat_set<account_name_type>& owner,                 \
    flat_set<account_name_type>& posting,               \
    vector<authority>& other);                          \
                                                        \
} } /* golos::protocol */

max_stars_repo_name: rusladder/LadderChain

max_issues_repo_name: rusladder/LadderChain

max_forks_repo_name: rusladder/LadderChain


text:
#include "util.h"

#include "clientversion.h"
#include "primitives/transaction.h"
#include "random.h"
#include "sync.h"
#include "utilstrencodings.h"
#include "utilmoneystr.h"
#include "test/test_bitcoin.h"

#include <stdint.h>
#include <vector>

#include "chainparams.h"
#include "consensus/consensus.h"
#include "consensus/validation.h"
#include "key.h"
#include "main.h"
#include "miner.h"
#include "pubkey.h"
#include "random.h"
#include "txdb.h"
#include "txmempool.h"
#include "ui_interface.h"
#include "rpc/server.h"
#include "rpc/register.h"
#include "zerocoin.h"

#include "test/fixtures.h"
#include "test/testutil.h"

#include "wallet/db.h"
#include "wallet/wallet.h"

#include <boost/filesystem.hpp>
#include <boost/test/unit_test.hpp>
#include <boost/thread.hpp>

BOOST_FIXTURE_TEST_SUITE(zerocoin_to_sigma_remint_tests, ZerocoinTestingSetup200)

BOOST_AUTO_TEST_CASE(remint_basic_test)
{
    string denomination;
    vector<uint256> vtxid;
    std::vector<string> denominations = {"1", "10", "25", "50", "100", "100"};

    string stringError;
    CZerocoinState *zerocoinState = CZerocoinState::GetZerocoinState();

    pwalletMain->SetBroadcastTransactions(true);

    // Mint 1 XZC zerocoin and remint it on wrong fork
    BOOST_CHECK_MESSAGE(pwalletMain->CreateZerocoinMintModel(stringError, "1"), stringError + " - Create Mint failed");
    CreateAndProcessBlock({}, scriptPubKey);
    CBlockIndex *forkBlockIndex = chainActive.Tip();
    // Get to the sigma portion
    for (int i=0; i<200; i++)
        CreateAndProcessBlock({}, scriptPubKey);
    CWalletTx remintOnWrongForkTx;
    BOOST_CHECK_MESSAGE(pwalletMain->CreateZerocoinToSigmaRemintModel(stringError, ZEROCOIN_TX_VERSION_2, (libzerocoin::CoinDenomination)1, &remintOnWrongForkTx), stringError + " - Remint failed");
    CreateAndProcessBlock({}, scriptPubKey);

    // Invalidate chain
    {
        LOCK(cs_main);
        CValidationState state;
        InvalidateBlock(state, Params(), forkBlockIndex);
    }
    // Mint and remint txs should be in the mempool now, clear them
    mempool.clear();

    for (int i=0; i<6; i++) {
        denomination = denominations[i];
        string stringError;

        //Verify Mint is successful
        BOOST_CHECK_MESSAGE(pwalletMain->CreateZerocoinMintModel(stringError, denomination.c_str()), stringError + " - Create Mint failed");

        //Verify Mint gets in the mempool
        BOOST_CHECK_MESSAGE(mempool.size() == 1, "Zerocoin mint was not added to mempool");

        CreateAndProcessBlock({}, scriptPubKey);
    }

    for (int i=0; i<5; i++)
        CreateAndProcessBlock({}, scriptPubKey);

    // spend coin for 100 xzc
    BOOST_CHECK_MESSAGE(pwalletMain->CreateZerocoinSpendModel(stringError, "", "100", false, true), stringError + " - 100 xzc spend failed");
    CreateAndProcessBlock({}, scriptPubKey);
    BOOST_CHECK_MESSAGE(zerocoinState->usedCoinSerials.size() == 1, "Incorrect used coin serial state after zerocoin spend");
    CBigNum zcSpentSerial = *zerocoinState->usedCoinSerials.begin();

    // get to the sigma portion
    for (int i=0; i<200; i++) {
        CBlock b = CreateAndProcessBlock({}, scriptPubKey);
    }
    // Intentionally do not remint the second 100
    for (int i=0; i<5; i++) {
        BOOST_CHECK_MESSAGE(pwalletMain->CreateZerocoinToSigmaRemintModel(stringError, ZEROCOIN_TX_VERSION_2, (libzerocoin::CoinDenomination)atoi(denominations[i].c_str())), stringError + " - Remint failed");
        BOOST_CHECK_MESSAGE(mempool.size() == 1, "Zerocoin remint was not added to mempool");
        for (int i=0; i<5; i++)
            CreateAndProcessBlock({}, scriptPubKey);
    }

    // test if sigma mints are spendable
    BOOST_CHECK_MESSAGE(pwalletMain->CreateZerocoinSpendModel(stringError, "", "25"), "Sigma spend failed");
    BOOST_CHECK_MESSAGE(mempool.size() == 1, "Spend was not added to mempool");

    for (int i=0; i<5; i++)
        CreateAndProcessBlock({}, scriptPubKey);

    // try double spend by modifying wallet and list of spent serials
    //Temporary disable usedCoinSerials check to force double spend in mempool
    CWalletDB walletdb(pwalletMain->strWalletFile);
    for (const Bignum &serial: zerocoinState->usedCoinSerials) {
        CZerocoinSpendEntry spendEntry;
        spendEntry.coinSerial = serial;
        walletdb.EraseCoinSpendSerialEntry(spendEntry);
    }

    std::list<CZerocoinEntry> zcEntries;
    walletdb.ListPubCoin(zcEntries);
    for (auto &zcEntry : zcEntries) {
        if (zcEntry.IsUsedForRemint) {
            zcEntry.IsUsed = zcEntry.IsUsedForRemint = false;
            walletdb.WriteZerocoinEntry(zcEntry);
        }
    }

    auto tempSerials = zerocoinState->usedCoinSerials;
    zerocoinState->usedCoinSerials.clear();

    // Retry remint of 1. Should pass for now
    BOOST_CHECK_MESSAGE(pwalletMain->CreateZerocoinToSigmaRemintModel(stringError, ZEROCOIN_TX_VERSION_2, (libzerocoin::CoinDenomination)1), stringError + " - Remint failed");

    // Restore state and generate a block. TestBlockValidity() should fail due to seen serial
    zerocoinState->usedCoinSerials = tempSerials;
    try {
        CreateAndProcessBlock({}, scriptPubKey);
        BOOST_FAIL("Block is created despite having double spend in it");
    }
    catch (std::runtime_error &err) {
        BOOST_CHECK(strstr(err.what(), "TestBlockValidity") != nullptr);
    }

    // clear mempool
    mempool.clear();
    // Block should be created now
    CreateAndProcessBlock({}, scriptPubKey);

    // Temporarily remove spent coin from the list of spent serials
    zerocoinState->usedCoinSerials.erase(zcSpentSerial);

    // Try remint for 100 xzc. Again should pass
    BOOST_CHECK_MESSAGE(pwalletMain->CreateZerocoinToSigmaRemintModel(stringError, ZEROCOIN_TX_VERSION_2, (libzerocoin::CoinDenomination)100), stringError + " - Remint failed");

    // Restore state and verify that it fails to get into the block because it was spent as zerocoin
    zerocoinState->usedCoinSerials = tempSerials;
    try {
        CreateAndProcessBlock({}, scriptPubKey);
        BOOST_FAIL("Block is created despite having double spend in it");
    }
    catch (std::runtime_error &err) {
        BOOST_CHECK(strstr(err.what(), "TestBlockValidity") != nullptr);
    }

    // clear mempool again
    mempool.clear();
    // Block should be created now
    CreateAndProcessBlock({}, scriptPubKey);

    // We've got remint saved that references zerocoin mint from the wrong fork. It shouldn't validate now
    pwalletMain->CommitTransaction(remintOnWrongForkTx);
    BOOST_CHECK_MESSAGE(mempool.size() == 0, "Remint for non-existent mint was added to the mempool");
}

BOOST_AUTO_TEST_CASE(remint_blacklist)
{
    string stringError;

    pwalletMain->SetBroadcastTransactions(true);

    //Verify Mint is successful
    BOOST_CHECK_MESSAGE(pwalletMain->CreateZerocoinMintModel(stringError, "1"), stringError + " - Create Mint failed");

    //Verify Mint gets in the mempool
    BOOST_CHECK_MESSAGE(mempool.size() == 1, "Zerocoin mint was not added to mempool");

    // get to the sigma portion
    for (int i=0; i<400; i++) {
        CBlock b = CreateAndProcessBlock({}, scriptPubKey);
    }

    // make an additional entry to the black list
    CWalletDB walletdb(pwalletMain->strWalletFile);
    std::list<CZerocoinEntry> pubCoins;
    walletdb.ListPubCoin(pubCoins);

    // there should be exactly one
    BOOST_CHECK(pubCoins.size() == 1);

    CZerocoinState::BlacklistPublicCoinValue(pubCoins.begin()->value);

    // Now remint should succeed but it should result in transaction in mempool
    BOOST_CHECK_MESSAGE(pwalletMain->CreateZerocoinToSigmaRemintModel(stringError, ZEROCOIN_TX_VERSION_2, (libzerocoin::CoinDenomination)1), stringError + " - Remint failed");
    BOOST_CHECK_MESSAGE(mempool.size() == 0, "Remint was added to the mempool despite blacklisted public coin value");
}

BOOST_AUTO_TEST_SUITE_END()


text: #include <boost/graph/r_c_shortest_paths.hpp>


text:
//=========================================================================
//  Copyright (c) Kitware, Inc.
//  All rights reserved.
//  See LICENSE.txt for details.
//
//  This software is distributed WITHOUT ANY WARRANTY; without even
//  the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
//  PURPOSE.  See the above copyright notice for more information.
//=========================================================================
#include "smtk/common/DateTime.h"

#include "boost/date_time/gregorian/gregorian.hpp"
#include <boost/date_time/local_time/local_time.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>

#include <exception>

namespace smtk
{
namespace common
{

/// Default constructor creates invalid ptime
DateTime::DateTime()
  : m_ptime(boost::posix_time::not_a_date_time)
{
}

bool DateTime::setComponents(
  int yr,
  int month,
  int day,
  int hr,
  int min,
  int sec,
  int msec,
  TimeZone* timeZone)
{
  // Construct date & time_duration components
  boost::gregorian::date ptimeDate(yr, month, day);
  // Cannot use main time_duration constructor because fractional_seconds
  // argument is ambiguous. Use milliseconds constructor instead.
  int msecTotal = 1000 * (hr * 3600 + min * 60 + sec) + msec;
  boost::posix_time::time_duration ptimeTime = boost::posix_time::milliseconds(msecTotal);

  // Convert depending on timeZone input
  if (timeZone)
  {
    // If time zone specified, convert to UTC
    boost::local_time::local_date_time local(
      ptimeDate,
      ptimeTime,
      timeZone->boostPointer(),
      boost::local_time::local_date_time::NOT_DATE_TIME_ON_ERROR);
    m_ptime = local.utc_time();
  }
  else
  {
    // If no tz, use as is
    m_ptime = boost::posix_time::ptime(ptimeDate, ptimeTime);
  }

  return this->isSet();
}

bool DateTime::components(
  int& yr,
  int& month,
  int& day,
  int& hr,
  int& min,
  int& sec,
  int& msec,
  TimeZone* timeZone) const
{
  if (!this->isSet())
  {
    return false;
  }

  if (timeZone && timeZone->isSet() && !timeZone->isUTC())
  {
    // Convert to local time
    boost::local_time::local_date_time local(m_ptime, timeZone->boostPointer());

    // Convert date
    boost::gregorian::date localDate = local.date();
    yr = localDate.year();
    month = localDate.month();
    day = localDate.day();

    // Convert time
    boost::posix_time::ptime ptimeLocal = local.local_time();
    boost::posix_time::time_duration workingTime = ptimeLocal.time_of_day();
    hr = static_cast<int>(workingTime.hours());
    min = static_cast<int>(workingTime.minutes());
    sec = static_cast<int>(workingTime.seconds());
    msec = static_cast<int>(workingTime.total_milliseconds() - 1000 * workingTime.total_seconds());

    return true;
  }

  // else use ptime
  boost::gregorian::date ptimeDate = m_ptime.date();
  yr = ptimeDate.year();
  month = ptimeDate.month();
  day = ptimeDate.day();

  boost::posix_time::time_duration ptimeTime = m_ptime.time_of_day();
  hr = static_cast<int>(ptimeTime.hours());
  min = static_cast<int>(ptimeTime.minutes());
  sec = static_cast<int>(ptimeTime.seconds());
  msec = static_cast<int>(ptimeTime.total_milliseconds() - 1000 * ptimeTime.total_seconds());

  return true;
}

bool DateTime::isSet() const
{
  return !m_ptime.is_special();
}

// Parse input string in canonical format only: YYYYMMDDThhmmss[.zzzzzz]
bool DateTime::deserialize(const std::string& ts)
{
  // Special case for uninitialized
  if (ts == "not-a-date-time")
  {
    m_ptime = boost::posix_time::ptime(boost::posix_time::not_a_date_time);
    return true;
  }

  try
  {
    m_ptime = boost::posix_time::from_iso_string(ts);
  }
  catch (std::exception& e)
  {
#ifndef NDEBUG
    std::cerr << "exception: " << e.what() << std::endl;
#else
    (void)e;
    ;
#endif
    m_ptime = boost::posix_time::not_a_date_time;
    return false;
  }

  return this->isSet();
}

// Converts data to canonical string format only: YYYYMMDDThhmmss.zzzzzz
std::string DateTime::serialize() const
{
  return boost::posix_time::to_iso_string(m_ptime);
}

/// Parse string using boost time_from_string(), NOT ISO compliant
bool DateTime::parseBoostFormat(const std::string& ts)
{
  try
  {
    m_ptime = boost::posix_time::time_from_string(ts);
  }
  catch (std::exception& e)
  {
#ifndef NDEBUG
    std::cerr << "exception: " << e.what() << std::endl;
#else
    (void)e;
    ;
#endif
    m_ptime = boost::posix_time::not_a_date_time;
    return false;
  }

  return this->isSet();
}

bool DateTime::operator==(const DateTime& dt) const
{
  return m_ptime == dt.m_ptime;
}

bool DateTime::operator<(const DateTime& dt) const
{
  return m_ptime < dt.m_ptime;
}

bool DateTime::operator>(const DateTime& dt) const
{
  return m_ptime > dt.m_ptime;
}

} // namespace common
} // namespace smtk

ext: cxx

max_stars_repo_name: jcfr/SMTK

max_issues_repo_name: jcfr/SMTK

max_forks_repo_name: jcfr/SMTK


text:
/**
   @file testudp.cpp
   @brief This file is part of Kalinka mediaserver.
   @author Ivan Murashko <ivan.murashko@gmail.com>

   Copyright (c) 2007-2012 Kalinka Team

   Permission is hereby granted, free of charge, to any person obtaining
   a copy of this software and associated documentation files (the
   "Software"), to deal in the Software without restriction, including
   without limitation the rights to use, copy, modify, merge, publish,
   distribute, sublicense, and/or sell copies of the Software, and to
   permit persons to whom the Software is furnished to do so, subject to
   the following conditions:

   The above copyright notice and this permission notice shall be included
   in all copies or substantial portions of the Software.

   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
   EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
   MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
   IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
   CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
   TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
   SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

   CHANGE HISTORY

   @date
   - 2009/05/21 created by ipp (Ivan Murashko)
   - 2009/08/02 header was changed by header.py script
   - 2010/01/06 header was changed by header.py script
   - 2011/01/01 header was changed by header.py script
   - 2012/02/03 header was changed by header.py script
*/

#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#include <boost/bind.hpp>

#include "testudp.h"
#include "exception.h"
#include "testdefines.h"
#include "testhttpthread.h"
#include "streamer.h"
#include "defines.h"
#include "utils.h"
#include "testutils.h"

#include "socket/routeinfo.h"

using namespace klk;
using namespace klk::http;

//
// TestProducerThread4UDP class
//

// Constructor
TestProducerThread4UDP::TestProducerThread4UDP(const sock::RouteInfo& route,
                                               const std::string& data) :
    TestProducerThread(route, data)
{
    BOOST_ASSERT(m_route.getProtocol() == sock::UDP);
}

// Destructor
TestProducerThread4UDP::~TestProducerThread4UDP()
{
}

// Main thread body
void TestProducerThread4UDP::mainLoop()
{
    klk_log(KLKLOG_DEBUG, "HTTP test: started UDP producer thread. "
            "Host: %s. Port: %u. Data: %s.",
            m_route.getHost().c_str(),
            m_route.getPort(),
            m_data.toString().c_str());

    ISocketPtr sock = sock::Factory::getSocket(sock::UDP);

    while(!isStopped())
    {
        // make the send data
        // contains path and be unique
        BinaryData data(m_data);
        BinaryData uuid(base::Utils::generateUUID());
        data.add(uuid);
        // send our data
        sock->send(m_route, data);
        // sleep for awhile
        sleep(1);
    }
}

//
// TestUDP class
//

// Constructor
TestUDP::TestUDP() :
    TestStreamer("testhttpstreamer_udp.sql")
{
}

// Tests main loop
void TestUDP::test()
{
    test::printOut("\nHTTP Streamer UDP input connections test ... ");

    // create producers
    sock::RouteInfo
        route1(TESTHOST1, TESTPORT1, sock::UDP, sock::UNICAST),
        route2(TESTHOST2, TESTPORT2, sock::UDP, sock::UNICAST);
    test::ThreadPtr
        thread1(new TestProducerThread4UDP(route1, TESTPATH1));
    m_scheduler.addTestThread(thread1);
    test::ThreadPtr
        thread2(new TestProducerThread4UDP(route2, TESTPATH2));
    m_scheduler.addTestThread(thread2);

    // no read in input
    // before start consumers
    //test::printOut("\n\tCheck initial no read");
    checkNoRead();

    // start consumer/producer threads
    m_scheduler.start();

    // wait for awhile
    //test::printOut("\n\tMain loop ...");
    sleep(20);

    // stop all consumer threads first
    //test::printOut("\n\tStoping consumers ...");
    std::for_each(m_consumers.begin(), m_consumers.end(),
                  boost::bind(&base::Scheduler::stopThread,
                              &m_scheduler, _1));

    // sleep for awhile
    //test::printOut("\n\tWait after stop ...");
    sleep(10);

    // no read in input
    // after stop consumers
    //test::printOut("\n\tCheck final no read");
    checkNoRead();

    // stop all others
    //test::printOut("\n\tStop all test threads");
    m_scheduler.stop();

    // check result in consumers/producers
    //test::printOut("\n\tCheck result in test threads");
    m_scheduler.checkResult();
}

// Checks that there is no any read in input threads
void TestUDP::checkNoRead()
{
    // There are should be two input threads but both
    // should not be assosiated with any socket

    Factory* factory =
        getModule<Streamer>(MODID)->m_httpfactory;
    CPPUNIT_ASSERT(factory);

    // check input info
    CPPUNIT_ASSERT(factory->m_inthreads);
    InThreadContainer::InThreadList list = factory->m_inthreads->m_list;
    CPPUNIT_ASSERT(list.size() == 2);
    bool was1 = false, was2 = false;
    for (InThreadContainer::InThreadList::iterator i = list.begin();
         i != list.end(); i++)
    {
        const InputInfoPtr info = (*i)->getInfo();
        CPPUNIT_ASSERT(info);
        CPPUNIT_ASSERT(info->getMediaTypeUuid() == TESTMTYPEUUID);

        if (info->getPath() == TESTPATH1)
        {
            CPPUNIT_ASSERT(was1 == false);
            // reader should not be initialized
            CPPUNIT_ASSERT((*i)->m_reader == NULL);
            // listener too (not join to multicast)
            CPPUNIT_ASSERT((*i)->m_listener == NULL);
            was1 = true;
        }
        else if (info->getPath() == TESTPATH2)
        {
            CPPUNIT_ASSERT(was2 == false);
            // reader should not be initialized
            CPPUNIT_ASSERT((*i)->m_reader == NULL);
            // listener too (not join to multicast)
            CPPUNIT_ASSERT((*i)->m_listener == NULL);
            was2 = true;
        }
        else
        {
            CPPUNIT_ASSERT(0);
        }
    }
    CPPUNIT_ASSERT(was1);
    CPPUNIT_ASSERT(was2);
}

max_stars_repo_name: ivanmurashko/kalinka

max_issues_repo_name: ivanmurashko/kalinka

max_forks_repo_name: ivanmurashko/kalinka


text: #include <boost/python/back_reference.hpp>