text:
#include <boost/algorithm/string/predicate.hpp>
#include "serial_comm.h"
#include <iostream>

using namespace std;
using namespace serial;

void serial_comm::safeWrite(string cmd) {
    cout << "Command: " << cmd;
    _port->write(cmd);
    _port->flushOutput();
    //sleep(1);
    usleep(0.1 * 1000 * 1000);
}

string serial_comm::safeRead() {
    string ret = _port->readline();
    return ret;
}

void serial_comm::Connect(string port) {
    int baudrate = 115200;
    Timeout my_timeout(6,6,0,6,0); // 6 millisecond read and write timeout
    cout << "port = " << port << endl;
    _port = new Serial(port, baudrate, my_timeout);

    // reset stuff
    safeWrite("unlogall\r\n");
    safeWrite("fix none\r\n");
    safeWrite("eventincontrol mark1 event positive\r\n");
    safeWrite("eventincontrol mark2 event positive\r\n");

    ///////// logging /////////////////
    //safeWrite("log mark1time onnew\r\n");
    safeWrite("log mark1pvaa onnew\r\n");
    safeWrite("log tagnextmark mark2 2\r\n");
    safeWrite("log taggedmark2pvaa onnew\r\n");
    //safeWrite("log mark2pvaa onnew\r\n");
    safeWrite("log inscovs ontime 1 0 nohold\r\n");
    safeWrite("log gpgst ontime 1 0 nohold\r\n");

    safeWrite("eventoutcontrol mark1 enable positive 10000000 10000000\r\n");
    //safeWrite(port, "log usb1 bestposa ontime 0.5 0 nohold\r\n");
}

/*
void serial_comm::Run() {
    safeWrite("eventoutcontrol mark2 enable positive 10000000 10000000\r\n");
    //safeWrite("eventoutcontrol mark2 enable positive 250000000 250000000\r\n");
}

*/
void serial_comm::Close() {
    safeWrite("eventoutcontrol mark1 disable\r\n");
    safeWrite("eventoutcontrol mark2 disable\r\n");
    safeWrite("eventincontrol mark1 disable\r\n");
    safeWrite("eventincontrol mark2 disable\r\n");
    safeWrite("unlogall\r\n");
    cout << "flushing GPS buffers" << endl;
    _port->flush();
    //sleep(1);
    usleep(0.1 * 1000 * 1000);
    // hack since flush doesn't do it:
    size_t buf_size = _port->available();
    cout << "bytes in buffer after flush: " << buf_size << endl;
    uint8_t* buf = (uint8_t*) malloc(sizeof(uint8_t)*buf_size);
    _port->read(buf, buf_size);
    free(buf);
    buf_size = _port->available();
    cout << "bytes in buffer after force clean: " << buf_size << endl;
    _port->close();
    delete _port;
}

ext: cpp

max_stars_repo_name: sameeptandon/sail-car-log

max_issues_repo_name: sameeptandon/sail-car-log

max_forks_repo_name: sameeptandon/sail-car-log


text:
/*
    Copyright (c) 2002-2009 Tampere University.

    This file is part of TTA-Based Codesign Environment (TCE).

    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.
 */
/**
 * @file MoveNode.cc
 *
 * Implementation of MoveNode class.
 *
 * Nodes are the minimum independent unit of information in a
 * minimally-ordered program representation. Typically, but not necessarily,
 * the nodes in a program representation are linked together by dependences
 * and thus form a graph.
 *
 * @author Ari Mets�halme 2006 (ari.metsahalme-no.spam-tut.fi)
 * @author Vladimir Guzma 2006 (vladimir.guzma-no.spam-tut.fi)
 * @note rating: red
 */

#include <iostream>
#include <climits>
#include <boost/format.hpp>

#include "MoveNode.hh"
#include "Port.hh"
#include "SpecialRegisterPort.hh"
#include "Bus.hh"
#include "UniversalMachine.hh"
#include "ProgramOperation.hh"
#include "POMDisassembler.hh"
#include "SetTools.hh"
#include "FUPort.hh"
#include "HWOperation.hh"
#include "TCEString.hh"
#include "Guard.hh"
#include "ControlUnit.hh"
#include "Terminal.hh"
#include "MoveGuard.hh"
#include "Operation.hh"
#include "Move.hh"
#include "Conversion.hh"
#include "Immediate.hh"
#include "Instruction.hh"

using namespace TTAMachine;

//#define PRINT_ID

/**
 * Constructor.
 *
 * Creates a new node with a smart pointer to the given Move.
 *
 * @param newmove the Move this node refers to.
 */
MoveNode::MoveNode(std::shared_ptr<TTAProgram::Move> newMove) :
    move_(newMove), immediate_(nullptr), srcOp_(nullptr), guardOp_(nullptr),
    cycle_(0), placed_(false), finalized_(false), isInFrontier_(false) {
}

/**
 * Constructor.
 *
 * Creates a new node with a smart pointer to the given immediate.
 *
 * @param imm the long immediate this node refers to.
 */
MoveNode::MoveNode(std::shared_ptr<TTAProgram::Immediate> imm) :
    move_(nullptr), immediate_(imm),  srcOp_(nullptr), guardOp_(nullptr),
    cycle_(0), placed_(false), finalized_(false), isInFrontier_(false) {
}

/**
 * Constructor.
 *
 * Creates a new node to be entry node.
 *
 */

MoveNode::MoveNode() :
    move_(nullptr), immediate_(nullptr), srcOp_(nullptr), guardOp_(nullptr),
    cycle_(0), placed_(false), finalized_(false), isInFrontier_(false) {
}

/**
 * Destructor.
 *
 * Deletes the owned Move instance.
 * Does not unregister this movenode from ProgramOperations.
 */
MoveNode::~MoveNode() {

    if (isSourceOperation()) {
        sourceOperation().removeOutputNode(*this);
    }
    if (isGuardOperation()) {
        guardOperation().removeGuardOutputNode(*this);
    }

    if (isDestinationOperation()) {
        for (unsigned int i = 0; i < destinationOperationCount(); i++) {
            destinationOperation(i).removeInputNode(*this);
        }
    }
}

/**
 * Creates a deep copy of MoveNode.
 *
 * Sets the source and destination operation of the copy to the same as
 * original. Does not copy the cycle.
 *
 * @return return copy of MoveNode.
 */
MoveNode*
MoveNode::copy() {

    MoveNode* newNode = NULL;
    if (move_ != NULL) {
        newNode = new MoveNode(move_->copy());
    } else {
        if (immediate_) {
            newNode = new MoveNode(immediate_->copy());
        } else {
            newNode = new MoveNode;
        }
    }

    if (isSourceOperation()) {
        sourceOperation().addOutputNode(*newNode);
        newNode->setSourceOperationPtr(sourceOperationPtr());
    }

    if (isDestinationOperation()) {
        for (unsigned int i = 0; i < destinationOperationCount(); i++) {
            destinationOperation(i).addInputNode(*newNode);
            newNode->addDestinationOperationPtr(destinationOperationPtr());
        }
    }
    return newNode;
}

/**
 * Tells whether the source of the MoveNode (move) belongs to an operation.
 *
 * @return True if the source of the MoveNode is an operation output.
 */
bool
MoveNode::isSourceOperation() const {
    if (move_ == NULL) {
        return false;
    }
    return srcOp_.get() != NULL;
}

/**
 * Tells whether the guard of the MoveNode (move) is a port guard from op.
 *
 * @return True if the source of the MoveNode is an operation output.
 */
bool
MoveNode::isGuardOperation() const {
    if (move_ == NULL) {
        return false;
    }
    return guardOp_.get() != NULL;
}

/**
 * Tells whether the node (move) reads a program variable or, if assigned, a
 * GPR.
 *
 * @return True if the source of the node is a variable or GPR.
 */
bool
MoveNode::isSourceVariable() const {
    if (move_ == NULL) {
        return false;
    }
    return move_->source().isGPR();
}

/**
 * Tells whether the node (move) reads the return address port.
 * GPR.
 *
 * @return True if the source of the node is the return address port.
 */
bool
MoveNode::isSourceRA() const {
    if (move_ == NULL) {
        return false;
    }
    return move_->source().isRA();
}

/**
 * Tells whether the node (move) reads a Immediate Register
 *
 * @return True if the source of the node is Immediate register.
 */
bool
MoveNode::isSourceImmediateRegister() const {
    if (move_ == NULL) {
        return false;
    }
    return move_->source().isImmediateRegister();
}

/**
 * Tells whether the source of the node (move) is a program constant. If
 * assigned, the constant is an in-line immediate.
 *
 * @return True if the source of the node is a constant.
 */
bool
MoveNode::isSourceConstant() const {
    if (move_ == NULL) {
        return false;
    }
    return move_->source().isImmediate();
}

/**
 * Tells whether the move belongs to an operation execution.
 *
 * @return True if the the node belongs to an operation.
 */
bool
MoveNode::isOperationMove() const {
    return isSourceOperation() || isDestinationOperation();
}

/**
 * Tells whether the node (move) writes a program variable or, if assigned,
 * a GPR.
 *
 * @return True if the destination of the node is a variable or GPR.
 */
bool
MoveNode::isDestinationVariable() const {
    if (move_ == NULL) {
        return false;
    }
    return move_->destination().isGPR();
}

/**
 * Tells whether the node is a ``software bypass'' - both its source and its
 * destination belong to operations.
 *
 * @return True if both source and destination of the node are operation
 *     terminals.
 */
bool
MoveNode::isBypass() const {
    return isSourceOperation() && isDestinationOperation();
}

/**
 * Tells whether the node is a register move, thus not belong to
 * any particular ProgramOperation.
 *
 * It's either an immediate move to an register or a register to register
 * copy.
 *
 * @return True if the move is a register to register copy.
 */
bool
MoveNode::isRegisterMove() const {
    return !isSourceOperation() && !isDestinationOperation();
}

/**
 * Returns true if this MoveNode is in the same ProgramOperation as the
 * given MoveNode.
 *
 * @return True if both MoveNodes belong to the same ProgramOperation.
 */
bool
MoveNode::inSameOperation(const MoveNode& other) const {

    if (other.isRegisterMove() || this->isRegisterMove())
        return false;

    unsigned int dopCount1 = destinationOperationCount();
    unsigned int dopCount2 = other.destinationOperationCount();

    if (isSourceOperation()) {
        if (other.isSourceOperation()) {
            if (&sourceOperation() == &other.sourceOperation()) {
                return true;
            }
        }
        for (unsigned int i = 0; i < dopCount2; i++) {
            if (&other.destinationOperation(i) == &sourceOperation()) {
                return true;
            }
        }
    }

    for (unsigned int i = 0; i < dopCount1; i++) {
        const ProgramOperation* dop = &destinationOperation(i);
        if (other.isSourceOperation()) {
            if (dop == &other.sourceOperation()) {
                return true;
            }
        }

        for (unsigned int j = 0; j < dopCount2; j++) {
            if (&other.destinationOperation(j) == dop) {
                return true;
            }
        }
    }
    return false;
}

/**
 * Tells whether is placed in the program representation, that is, has a
 * cycle assigned to it.
 *
 * @return True if a cycle is assigned to the node.
 */
bool
MoveNode::isPlaced() const {
    return placed_;
}

/**
 * Tells whether the node is fully assigned.
 *
 * A node is fully assigned when all the resources of the target processor
 * necessary to carry out the transport it specifies are assigned to it.
 *
 * @return True if all required scheduling resources of target machine are
 *      assigned to the node.
 */
bool
MoveNode::isAssigned() const {

    if (immediate_ != NULL) {
        TTAProgram::Instruction* parent = immediate_->parent();
        return parent != NULL &&
            &parent->instructionTemplate() !=
            &NullInstructionTemplate::instance();
    }

    if (move_ == NULL) {
        // probably a dummy ENTRYNODE or something
        return false;
    }

    /// Machine found is NOT UniversalMachine - we are happy
    if (!move_->bus().machine()->isUniversalMachine()) {
        if ((isSourceOperation() ||
            isSourceVariable() ||
            isSourceImmediateRegister()) &&
            (move_->source().port().parentUnit()->machine() !=
             move_->bus().machine())) {
            return false;
        }
        if ((isDestinationOperation() || isDestinationVariable()) &&
            (move_->destination().port().parentUnit()->machine() !=
             move_->bus().machine())) {
            return false;
        }
        return true;
    }
    return false;
}

/**
 * Tells whether the node is completely scheduled.
 *
 * A node is completely scheduled only if it is assigned to a program cycle
 * and the necessary resources of the target processor are assigned to it.
 *
 * @return True if the node is placed and assigned.
 */
bool
MoveNode::isScheduled() const {
    return isPlaced() && isAssigned();
}

/**
 * Returns the cycle (index) assigned to the node.
 *
 * @return The cycle in which the node is placed.
 * @exception InvalidData if the node is not placed.
 */
int
MoveNode::cycle() const {
    if (!isPlaced()){
        std::string msg = "MoveNode was not placed yet: " + toString();
        throw InvalidData(__FILE__, __LINE__, __func__, msg);
    } else {
        return cycle_;
    }
}

/**
 * Returns the enclosing scheduling scope of the node.
 *
 * @return A scheduling scope.
 */
Scope&
MoveNode::scope(){
    ///TODO: Intentionally falsified code
    /// Class Scope does not exists so far in real
    Scope* ns = new Scope;
    return *ns;
}

/**
 * Returns the instance of operation in the program whose output is the
 * source of this node.
 *
 * @return A program operation.
 * @exception InvalidData if the given node does not read an operation
 *     output.
 */
ProgramOperation&
MoveNode::sourceOperation() const {
    return *sourceOperationPtr().get();
}

ProgramOperationPtr
MoveNode::sourceOperationPtr() const {
    if (!isSourceOperation()){
        std::string msg =
            (boost::format(
                "MoveNode: '%s' source is not Operation.") % toString()).
            str();
        throw InvalidData(__FILE__, __LINE__, __func__, msg);
    } else {
        return srcOp_;
    }
}

/**
 * Returns the instance of operation in the program whose output is the
 * guard of this node.
 *
 * @return A program operation.
 * @exception InvalidData if the given node does not read an operation
 *     output.
 */
ProgramOperation&
MoveNode::guardOperation() const {
    return *guardOperationPtr().get();
}

ProgramOperationPtr
MoveNode::guardOperationPtr() const {
    if (!isGuardOperation()){
        std::string msg =
            (boost::format(
                "MoveNode: '%s' guard is not Operation.") % toString()).
            str();
        throw InvalidData(__FILE__, __LINE__, __func__, msg);
    } else {
        return guardOp_;
    }
}

/**
 * Set cycle for a node, also sets placed_
 * @param newcycle Cycle to which node is placed_
 * @throw InvalidData If node is already placed in cycle different from
 *                      newcycle
 */
void
MoveNode::setCycle(const int newcycle) {
    if (placed_ == true && cycle_ != newcycle) {
        std::string msg = "MoveNode is already placed in cycle ";
        msg += cycle_;
        msg += ".";
        throw InvalidData(__FILE__, __LINE__, __func__, msg);
    }
    cycle_ = newcycle;
    placed_ = true;
}

/**
 * Unset cycle from nodes
 * @throw InvalidData If node is not placed
 */
void
MoveNode::unsetCycle() {
    if (placed_ == false ) {
        std::string msg = "MoveNode is not placed.";
        throw InvalidData(__FILE__, __LINE__, __func__, msg);
    }
    cycle_ = 0;
    placed_ = false;
}

/**
 * Set a destination of MoveNode to ProgramOperation
 *
 * @param po Program operation that is destination of MoveNode
 */
void MoveNode::addDestinationOperationPtr(ProgramOperationPtr po) {
    dstOps_.push_back(po);
}
/**
 * Set a source of MoveNode to ProgramOperation
 *
 * @param po Program operation that is source of MoveNode
 */
void MoveNode::setSourceOperationPtr(ProgramOperationPtr po) {
    srcOp_ = po;
}

/**
 * Set a guard src of MoveNode to ProgramOperation
 *
 * @param po Program operation that is source of MoveNode
 */
void MoveNode::setGuardOperationPtr(ProgramOperationPtr po) {
    guardOp_ = po;
}

/**
 * Returns type of the MoveNode.
 *
 * Not yet used anywhere and types not decided so
 * current dummy implementation returns -1
 *
 * @return type of the node
 */
int
MoveNode::type() {
    return -1;
}

/**
 * Returns string with ID of the MoveNode.
 *
 * Not yet used anywhere except printing graph in .dot file. Returns the
 * disassembly of the move along with its id.
 *
 * @return The string with node ID.
 */
std::string
MoveNode::toString() const {
    if (move_ == NULL) {
        return "-1:\tENTRYNODE";
    }
#ifdef PRINT_ID
    std::string content = Conversion::toString(nodeID()) + " ";
#else
    std::string content;
#endif
    content +=  (isPlaced() ? Conversion::toString(cycle()) + " " :
                 std::string()) + POMDisassembler::disassemble(*move_);
    if (isScheduled()) {
        content += " Bus: " + move_->bus().name();
    }
    return content;
}

/**
 * Returns Dot representation of the node.
 *
 * Prints the disassembly of the move and sets the color of the node to red
 * in case it's scheduled.
 *
 * @return The string with node ID.
 */
std::string
MoveNode::dotString() const {

    std::string contents = GraphNode::dotString();
    if (isOperationMove()) {
        unsigned operationId = 0;

        // make the outline of the moves that belong to the same operation
        // of the same color to aid in schedule debugging
        if (isSourceOperation())
            operationId = sourceOperation().poId();
        else
            operationId = destinationOperation().poId();

        // hash the colors so that they are easy to separate/recognise.
        // srand();rand() pair only used as a hash function,
        // this needs to be deterministic.
        srand(operationId);
        int operationColor = rand() / (RAND_MAX>>24);

        contents +=
            (boost::format(
                ",color=\"#%.6x\"") % operationColor).str();
    }

    if (isScheduled()) {
        if (isFinalized()) {
            contents += ",shape=hexagon";
        } else {
            contents += ",shape=box";
        }
    } else {
        if (!isInFrontier_) {
            contents += ",shape=ellipse";
        } else {
            contents += ",shape=diamond";
        }

    }
    return contents;
}

/**
 * Returns the cycle the given result move can be scheduled earliest,
 * taking in the account the latency of the operation.
 *
 * In case the trigger move has not been scheduled yet, returns INT_MAX.
 *
 * @exception IllegalObject if this MoveNode is not a result read.
 */
int
MoveNode::earliestResultReadCycle() const {

    const ProgramOperation* po;

    int outputIndex;
    if (isSourceOperation()) {
        po = &sourceOperation();
        outputIndex = move_->source().operationIndex();
    } else {
        if (!isGuardOperation())
            throw IllegalParameters(
                __FILE__, __LINE__, __func__, "Not a result read move.");
        po = &guardOperation();
        outputIndex = po->outputIndexOfMove(*this);
    }
    try {
        MoveNode* trigger = po->triggeringMove();
        if (trigger == NULL || !trigger->isScheduled()) {
            return INT_MAX;
        }

        // find the latency of the operation output we are reading
        const TTAMachine::HWOperation& hwop =
            *trigger->move().destination().functionUnit().operation(
                po->operation().name());

        return trigger->cycle() + hwop.latency(outputIndex);
    } catch (const InvalidData& id) {
        // triggeringMove() throws if the triggering move cannot be resolved
        // again ignore this. causd by either
        // incorrect scheduling order ( in RM tests) or
        // broken machine ( catched by machinecheck now)
    } catch (const Exception& e) {
        abortWithError(e.errorMessageStack());
    }
    return INT_MAX;
}
/**
 * Returns the lates cycle the given trigger move can be scheduled at,
 * taking in the account the latency of the operation results.
 *
 * In case the none of the result moves has been scheduled yet, returns INT_MAX.
 *
 * @exception IllegalObject if this MoveNode is not a result read.
 */
int
MoveNode::latestTriggerWriteCycle() const {

    if (!isDestinationOperation())
        throw IllegalParameters(
            __FILE__, __LINE__, __func__, "Not a result read move.");

    const ProgramOperation& po = destinationOperation();
    int latestTrigger = INT_MAX;
    for (int i = 0; i < po.outputMoveCount(); i++){
        MoveNode& result = po.outputMove(i);
        if (!result.isScheduled()) {
            continue;
        }
        // find the latency of the operation output we are testing
        const TTAMachine::HWOperation& hwop =
            *result.move().source().functionUnit().operation(
                po.operation().name());
        // find the OSAL id of the operand of the output we are testing
        const int outputIndex = result.move().source().operationIndex();
        int latency = hwop.latency(outputIndex);
        latestTrigger = std::min(latestTrigger, result.cycle() - latency);
    }
    return latestTrigger;
}

/**
 * Unsets destination operation.
 *
 * Does not ask the ProgramOperation to remove this MoveNode from
 * it's input moves.
 */
void
MoveNode::clearDestinationOperation() {
    dstOps_.clear();
}

/**
 * Unsets destination operation.
 *
 * Does not ask the ProgramOperation to remove this MoveNode from
 * it's input moves.
 */
void
MoveNode::removeDestinationOperation(const ProgramOperation* ptr) {
    for (std::vector<ProgramOperationPtr>::iterator i = dstOps_.begin();
         i != dstOps_.end(); i++) {
        if (((*i).get()) == ptr) {
            dstOps_.erase(i);
            return;
        }
    }
    std::string msg = "Removed destination op not found in MoveNode";
    throw InvalidData(__FILE__, __LINE__, __func__, msg);
}

/**
 * Unsets source operation.
 *
 * Does not ask the ProgramOperation to remove this MoveNode from
 * it's output moves.
 */
void
MoveNode::unsetSourceOperation() {
    srcOp_ = ProgramOperationPtr();
}

/**
 * Unsets guard operation.
 *
 * Does not ask the ProgramOperation to remove this MoveNode from
 * it's output moves.
 */
void
MoveNode::unsetGuardOperation() {
    guardOp_ = ProgramOperationPtr();
}

/**
 * Returns the total guard latency of the guard of given move,
 * or 0 if the move is unconditional.
 */
int MoveNode::guardLatency() const {
    if (!isMove()) {
        return 0;
    }
    return move_->guardLatency();
}

/**
 * Checks if the source of the movenode is the given reg.
 *
 * This method assumes incoming reg name is in correct
 * rf.number format, and does not check it, due performance reasons.
 *
 * @param reg register to check against source of the movenode
 *
 * @return true if the source of the movenode is the given reg.
 *         false if some other reg or not reg.
 */
bool
MoveNode::isSourceReg(const std::string& reg) const {
    if (!isMove()) {
        return false;
    }
    if (!move().source().isGPR()) {
        return false;
    }

    // try to do as quickly as possible,
    // compare the reg in string and reg in terminalregister.
    size_t dotPlace = reg.find('.');
    const std::string& rfName = move().source().registerFile().name();
    if (reg.compare(0, dotPlace, rfName) != 0) {
        return false;
    }

    return atoi(reg.c_str()+dotPlace+1) == move().source().index();
}

bool MoveNode::isLastUnscheduledMoveOfDstOp() const {
    for (unsigned int i = 0; i < destinationOperationCount(); i++) {
        const ProgramOperation& po = destinationOperation(i);
        // ignore ops with just one input
        if (po.inputMoveCount() == 1) {
            continue;
        }
        bool fail = false;
        for (int j = 0; j < po.inputMoveCount(); j++) {
            MoveNode& inputNode = po.inputMove(j);
            if (&inputNode != this && !inputNode.isScheduled()) {
                fail = true;
                break;
            }
        }
        if (!fail)
            return true;
    }
    return false;
}

TTAProgram::Immediate& MoveNode::immediate() {
    return *immediate_;
}

const TTAProgram::Immediate& MoveNode::immediate() const {
    return *immediate_;
}

std::shared_ptr<TTAProgram::Immediate> MoveNode::immediatePtr() {
    return immediate_;
}

ext: cc

max_stars_repo_name: kanishkan/tce

max_issues_repo_name: kanishkan/tce

max_forks_repo_name: kanishkan/tce


text:
/*

Copyright (c) 2005-2016, University of Oxford.
All rights reserved.

University of Oxford means the Chancellor, Masters and Scholars of the
University of Oxford, having an administrative office at Wellington
Square, Oxford OX1 2JD, UK.

This file is part of Chaste.

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 the University of Oxford nor the names of its
   contributors may be used to endorse or promote products derived from this
   software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

*/

#ifndef POPULATIONTESTINGFORCE_HPP_
#define POPULATIONTESTINGFORCE_HPP_

#include "ChasteSerialization.hpp"
#include <boost/serialization/base_object.hpp>
#include "AbstractForce.hpp"

/**
 * A simple force law used to test node location updates across the off lattice population test files.
 */

template<unsigned  ELEMENT_DIM, unsigned SPACE_DIM=ELEMENT_DIM>
class PopulationTestingForce : public AbstractForce<ELEMENT_DIM, SPACE_DIM>
{
private:

    /**
     * Archiving.
     */
    friend class boost::serialization::access;

    /**
     * Boost Serialization method for archiving/checkpointing.
     * Archives the object and its member variables.
     *
     * @param archive  The boost archive.
     * @param version  The current version of this class.
     */
    template<class Archive>
    void serialize(Archive & archive, const unsigned int version)
    {
        archive & boost::serialization::base_object<AbstractForce<ELEMENT_DIM,SPACE_DIM> >(*this);
        archive & mWithPositionDependence;
    }

    /**
     * Whether the applied force should depend on the position of the node, or only its index
     * Defaults to true, since that's better for testing a variety of numerical methods.
     * Crypt tests require a position independent test force though.
     */
    bool mWithPositionDependence;

public:

    /**
     * Constructor.
     *
     * @param hasPositionDependence specifys which testing force to use (defaults to true)
     */
    PopulationTestingForce(bool hasPositionDependence = true);

    /**
     * Overridden AddForceContribution() method.
     *
     * @param rCellPopulation reference to the cell population
     *
     * THis has two forces depending on the member variable mWithPositionDependence
     *
     * If true then
     *
     * For node i
     * F[j] = 0.01 (j+1) i r[j]
     *
     * Where r is the position of node i.
     *
     * if false then
     *
     * F[j] = 0.01 (j+1) i
     *
     */
    void AddForceContribution(AbstractCellPopulation<ELEMENT_DIM,SPACE_DIM>& rCellPopulation);

    /**
     * Helper method to return the expected step location for ForwardEulerNumericalMethod.
     *
     * @return the expected location after one step
     *
     * @param nodeIndex the index of the node
     * @param damping the damping constant
     * @param oldLocation the old location of the node
     * @param dt the step size
     */
    c_vector<double, SPACE_DIM> GetExpectedOneStepLocationFE(unsigned nodeIndex,
                                                           double damping,
                                                           c_vector<double, SPACE_DIM>& oldLocation,
                                                           double dt);

    /**
     * Helper method to return the expected step location for RK4NumericalMethod.
     *
     * @return the expected location after one step
     *
     * @param nodeIndex the index of the node
     * @param damping the damping constant
     * @param oldLocation the old location of the node
     * @param dt the step size
     */
    c_vector<double, SPACE_DIM> GetExpectedOneStepLocationRK4(unsigned nodeIndex,
                                                           double damping,
                                                           c_vector<double, SPACE_DIM>& oldLocation,
                                                           double dt);

    /**
     * Helper method to return the expected step location for AdamsMoultonNumericalMethod.
     *
     * @return the expected location after one step
     *
     * @param nodeIndex the index of the node
     * @param damping the damping constant
     * @param oldLocation the old location of the node
     * @param dt the step size
     */
    c_vector<double, SPACE_DIM> GetExpectedOneStepLocationAM2(unsigned nodeIndex,
                                                           double damping,
                                                           c_vector<double, SPACE_DIM>& oldLocation,
                                                           double dt);

    /**
     * Helper method to return the expected step location for BackwardEulerNumericalMethod.
     *
     * @return the expected location after one step
     *
     * @param nodeIndex the index of the node
     * @param damping the damping constant
     * @param oldLocation the old location of the node
     * @param dt the step size
     */
    c_vector<double, SPACE_DIM> GetExpectedOneStepLocationBE(unsigned nodeIndex,
                                                           double damping,
                                                           c_vector<double, SPACE_DIM>& oldLocation,
                                                           double dt);

    /**
     * Overridden OutputForceParameters() method.
     *
     * @param rParamsFile the file stream to which the parameters are output
     */
    virtual void OutputForceParameters(out_stream& rParamsFile);
};

#include "SerializationExportWrapper.hpp"
EXPORT_TEMPLATE_CLASS_ALL_DIMS(PopulationTestingForce)

#endif /*POPULATIONTESTINGFORCE_HPP_*/

ext: hpp

max_stars_repo_name: uofs-simlab/ChasteOS

max_issues_repo_name: uofs-simlab/ChasteOS

max_forks_repo_name: uofs-simlab/ChasteOS


text:
// Copyright 2012 Daniel James.
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)

// This is also released into the public domain.

#if !defined(BOOST_HASH_EXAMPLES_SIPHASH_HEADER)
#define BOOST_HASH_EXAMPLES_SIPHASH_HEADER

#include <boost/cstdint.hpp>
#include <boost/utility/enable_if.hpp>

#include <string>
#include <vector>
#include <list>

namespace hash
{
    // Random key used to make sure the hash function isn't predictable.

    struct sipkey
    {
        boost::uint64_t k0, k1;
    };

    // Generate a secure sipkey.
    // This only works when boost::random_device is available.
    sipkey generate_sipkey();

    // This is the class that does the actual hashing.

    struct siphash_state
    {
        boost::uint64_t v0, v1, v2, v3;
        union {
            boost::uint64_t m;
            unsigned char buffer[8];
        };
        unsigned char buffered;
        unsigned char b;

        explicit siphash_state(sipkey const&);
        void update(void const*, unsigned);
        boost::uint64_t finalize();

    private:
        void sip_round(unsigned);
    };

    // The genereric hash function.
    //
    // Don't sepecialize this. Unless you really want to.

    template <typename T>
    struct siphash
    {
        sipkey key;

        /* implicit */ siphash(sipkey const& k) : key(k) {}
        std::size_t operator()(T const&) const;
    };

    // Add support for a type by specializing this class.
    //
    // 'Enable' is used as a SFINAE hook.

    template <typename T, typename Enable = void>
    struct siphash_impl
    {
        static void update(siphash_state&, T const&);
    };

    // The implementation of the generic hash function.

    template <typename T>
    std::size_t siphash<T>::operator()(T const& x) const
    {
        siphash_state state(key);
        siphash_impl<T>::update(state, x);
        return static_cast<std::size_t>(state.finalize());
    }

    // A couple of basic traits for hashing binary data.

    struct enable_siphash_false { enum { value = false }; };
    struct enable_siphash_true { enum { value = true }; };

    template <typename T>
    struct enable_siphash_binary : enable_siphash_false {};

    template <typename T>
    struct enable_siphash_binary_array
    {
        enum { value = enable_siphash_binary<T>::value &&
            sizeof(T[2]) == sizeof(T) * 2 };
    };

    // Some general purpose hash implementations, siphash_impl<T>
    // can inherit from these.

    template <typename T>
    struct siphash_binary_impl
    {
        static void update(siphash_state& state, int x)
        {
            state.update(&x, sizeof(x));
        }
    };

    template <typename T>
    struct siphash_container_impl
    {
        static void update(siphash_state& state, T const& x)
        {
            siphash_impl<typename T::value_type> value_impl;

            for (typename T::const_iterator begin = x.begin(),
                end = x.end(); begin != end; ++begin)
            {
                value_impl.update(state, *begin);
            }
        }
    };

    template <typename T, bool Enable = enable_siphash_binary_array<T>::value>
    struct siphash_binary_container_impl;

    template <typename T>
    struct siphash_binary_container_impl<T, false> :
        siphash_container_impl<T> {};

    template <typename T>
    struct siphash_binary_container_impl<T, true>
    {
        static void update(siphash_state& state, T const& x)
        {
            state.update(&*x.cbegin(), sizeof(T) * x.size());
        }
    };

    // Specialize siphash_impl for various types.

    template <typename T>
    struct siphash_impl<T,
        typename boost::enable_if_c<enable_siphash_binary<T>::value>::type
    > : siphash_binary_impl<T> {};

    template <typename T, typename Alloc>
    struct siphash_impl<std::list<T, Alloc> > :
        siphash_container_impl<T> {};

    template <typename T, typename Alloc>
    struct siphash_impl<std::vector<T, Alloc> > :
        siphash_binary_container_impl<T> {};

    template <typename T, typename Alloc>
    struct siphash_impl<std::basic_string<T, std::char_traits<T>, Alloc> > :
        siphash_binary_container_impl<T> {};

    // Specialize the binary trait for builtin types.

    template <> struct enable_siphash_binary<bool> :
        enable_siphash_true {};
    template <> struct enable_siphash_binary<char> :
        enable_siphash_true {};
    template <> struct enable_siphash_binary<unsigned char> :
        enable_siphash_true {};
    template <> struct enable_siphash_binary<signed char> :
        enable_siphash_true {};
    template <> struct enable_siphash_binary<short> :
        enable_siphash_true {};
    template <> struct enable_siphash_binary<unsigned short> :
        enable_siphash_true {};
    template <> struct enable_siphash_binary<int> :
        enable_siphash_true {};
    template <> struct enable_siphash_binary<unsigned int> :
        enable_siphash_true {};
    template <> struct enable_siphash_binary<long> :
        enable_siphash_true {};
    template <> struct enable_siphash_binary<unsigned long> :
        enable_siphash_true {};

#if !defined(BOOST_NO_INTRINSIC_WCHAR_T)
    template <> struct enable_siphash_binary<wchar_t> :
        enable_siphash_true {};
#endif

#if !defined(BOOST_NO_LONG_LONG)
    template <> struct enable_siphash_binary<boost::long_long_type> :
        enable_siphash_true {};
    template <> struct enable_siphash_binary<boost::ulong_long_type> :
        enable_siphash_true {};
#endif

#if defined(BOOST_HAS_INT128)
    template <> struct enable_siphash_binary<boost::int128_type> :
        boost::hash_detail::enable_hash_value {};
    template <> struct enable_siphash_binary<boost::uint128_type> :
        boost::hash_detail::enable_hash_value {};
#endif
}

#endif

max_stars_repo_name: smart-make/boost

max_issues_repo_name: smart-make/boost

max_forks_repo_name: smart-make/boost


text:
/* RevKit: A Toolkit for Reversible Circuit Design (www.revkit.org)
 * Copyright (C) 2009-2011  The RevKit Developers <revkit@informatik.uni-bremen.de>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

/**
 * @file write_blif.hpp
 *
 * @brief Writes a circuit to a BLIF file
 */

#ifndef WRITE_BLIF_HPP
#define WRITE_BLIF_HPP

#include <iostream>
#include <map>
#include <vector>

#include <boost/optional.hpp>

namespace revkit
{

  class circuit;
  class gate;

  /**
   * @brief Settings for write_blif
   *
   * @author RevKit
   * @since  1.0
   */
  struct write_blif_settings
  {
    /**
     * @brief Stores truth tables
     *
     * The key is the index of the respective target line.
     * The value is a map itself, which maps input monoms
     * to output values for that target.
     *
     * @author RevKit
     * @since  1.1.1
     */
    typedef std::map<unsigned, std::map<std::vector<boost::optional<bool> >, bool> > truth_table_map;

    /**
     * @brief Standard constructor
     *
     * Initializes default values
     *
     * @author RevKit
     * @since  1.0
     */
    write_blif_settings();

    /**
     * @brief Prefix for the auxiliary variables which are created by the algorithm
     *
     * Default value is \b tmp
     *
     * @author RevKit
     * @since  1.0
     */
    std::string tmp_signal_name;

    /**
     * @brief Sets if output should comply to BlifMV
     *
     * In BlifMV spaces are inserted between the elements
     * of the input cubes.
     *
     * Default value is \b false
     *
     * @author RevKit
     * @since  1.2
     */
    bool blif_mv;

    /**
     * @brief Sets an state prefix for output signals
     *
     * Since states have both the same input and output name
     * this prefix is prepended to the respective output names.
     *
     * Default value is \b out_
     *
     * @author RevKit
     * @since  1.3
     */
    std::string state_prefix;

    /**
     * @brief Sets if constant signals should keep their name
     *
     * Keeps constant names, but only if they are unique.
     *
     * Default value is \b false
     *
     * @author RevKit
     * @since  1.3
     */
    bool keep_constant_names;

    /**
     * @brief Operator for transforming the gates into BLIF code
     *
     * By convention the first input signals are for the target lines and then the control lines.
     * The number of output signals is the number of target lines.
     * Only the cubes have to be printed, not the \em .names declaration.
     *
     * This operator has to be overridden when new gate types should be supported.
     *
     * The signature of this operator changed in RevKit version 1.1.1
     *
     * @param g The current g to be transformed
     * @param map Truth table map to be filled with cubes (check the source code for examples) (since 1.1.1)
     *
     * @author RevKit
     * @since  1.0
     */
    virtual void operator()( const gate& g, truth_table_map& map ) const;

  };

  /**
   * @brief Writes a circuit to a BLIF file
   *
   * This function writes the circuit to a BLIF file.
   * Therefore, it is required that the circuit has names for all its inputs and outputs.
   *
   * @param circ Circuit
   * @param os Output stream where to write the result to. Default is \b STDOUT.
   * @param settings Settings
   *
   * @author RevKit
   * @since  1.0
   */
  void write_blif( const circuit& circ, std::ostream& os = std::cout, const write_blif_settings& settings = write_blif_settings() );

}

#endif /* WRITE_BLIF_HPP */

max_stars_repo_name: clairechingching/ScaffCC

max_issues_repo_name: clairechingching/ScaffCC

max_forks_repo_name: clairechingching/ScaffCC


text:
#include <boost/foreach.hpp>
#include <cctype>
#include "read_set.hpp"
#include "constants.hpp"

Alignment::Alignment()
    : start(-1)
    , end(-1)
    , cigar_len(0)
    , cigar(NULL)
    , strand(strand_na)
    , alnnum(0)
    , misaligned_pr(0.0)
{
}

Alignment::Alignment(const Alignment& a)
{
    start     = a.start;
    end       = a.end;
    paired    = a.paired;
    strand    = a.strand;
    alnnum    = a.alnnum;
    misaligned_pr  = a.misaligned_pr;
    cigar_len = a.cigar_len;
    cigar = new uint32_t[cigar_len];
    memcpy(cigar, a.cigar, cigar_len * sizeof(uint32_t));
}

Alignment::Alignment(const bam1_t* b)
{
    start     = bam_truepos(&b->core, bam1_cigar(b));
    end       = bam_trueend(&b->core, bam1_cigar(b)) - 1;
    strand    = bam1_strand(b);
    paired    = (b->core.flag & BAM_FPAIRED) != 0;

    unsigned int mismatch_count = 0;
    char* s = reinterpret_cast<char*>(bam_aux_get(b, "NM"));
    if (!s) s = reinterpret_cast<char*>(bam_aux_get(b, "nM"));
    if (s) {
        mismatch_count = (unsigned int) bam_aux2i(reinterpret_cast<unsigned char*>(s));
    }

    s = reinterpret_cast<char*>(bam_aux_get(b, "MD"));
    double misalign_likelihood[2] = {1.0, 1.0};
    if (s) {
        unsigned char* qs = bam1_qual(b);
        pos_t off = 0;
        char* t = s;
        unsigned long skip;
        while (*s) {
            skip = strtoul(s, &t, 10);
            if (t > s) {
                off += (pos_t) skip;
            }

            // probability the base is miscalled
            double p = pow(10.0, - (double) qs[off] / 10);
            misalign_likelihood[0] *=
                p + (1.0 - p) * constants::misaligned_mismatch_pr;
            misalign_likelihood[1] *=
                p + (1.0 - p) * constants::aligned_mismatch_pr;

            if (!*t) break;

            s = t + 1;
            ++off;
        }

    }
    else {
        misalign_likelihood[0] = pow(constants::misaligned_mismatch_pr, mismatch_count);
        misalign_likelihood[1] = pow(constants::aligned_mismatch_pr, mismatch_count);
    }

    misaligned_pr = (constants::misalign_prior * misalign_likelihood[0]) /
        ((constants::misalign_prior * misalign_likelihood[0]) +
         (1.0 - constants::misalign_prior) * misalign_likelihood[1]);

    s = reinterpret_cast<char*>(bam_aux_get(b, "HI"));
    alnnum = s ? (uint16_t) bam_aux2i(reinterpret_cast<unsigned char*>(s)) : 0;

    cigar_len = b->core.n_cigar;
    cigar     = new uint32_t [b->core.n_cigar];
    memcpy(cigar, bam1_cigar(b), cigar_len * sizeof(uint32_t));
}

Alignment::~Alignment()
{
    delete [] cigar;
}

bool Alignment::operator == (const bam1_t* b) const
{
    if (this->start != (pos_t) bam_truepos(&b->core, bam1_cigar(b))) return false;
    if (this->strand != bam1_strand(b)) return false;
    if (this->paired != ((b->core.flag & BAM_FPAIRED) != 0)) return false;

    uint16_t alnnum = 0;
    unsigned char* s = bam_aux_get(b, "HI");
    if (s) alnnum = (uint16_t) bam_aux2i(s);
    if (this->alnnum != alnnum) return false;

    if (this->cigar_len != b->core.n_cigar) return false;
    if (this->end != (pos_t) (bam_trueend(&b->core, bam1_cigar(b)) - 1)) return false;
    return memcmp(cigar, bam1_cigar(b), cigar_len * sizeof(uint32_t)) == 0;
}

bool Alignment::operator != (const bam1_t* b) const
{
    return !(*this == b);
}

bool Alignment::operator < (const Alignment& other) const
{
    if      (start  != other.start)  return start < other.start;
    else if (end    != other.end)    return end < other.end;
    else if (paired != other.paired) return paired < other.paired;
    else if (strand != other.strand) return strand < other.strand;
    else if (alnnum != other.alnnum) return alnnum < other.alnnum;
    //else if (mapq   != other.mapq)   return mapq < other.mapq;
    //else if (mismatch_count != other.mismatch_count) return mismatch_count < other.mismatch_count;
    else if (cigar_len != other.cigar_len) return cigar_len < other.cigar_len;
    else {
        return memcmp(cigar, other.cigar, cigar_len * sizeof(uint32_t)) < 0;
    }
}

bool Alignment::operator == (const Alignment& other) const
{
    return start     == other.start &&
           end       == other.end &&
           paired    == other.paired &&
           strand    == other.strand &&
           alnnum    == other.alnnum &&
           //mapq      == other.mapq &&
           cigar_len == other.cigar_len &&
           memcmp(cigar, other.cigar, cigar_len * sizeof(uint32_t)) == 0;
}

CigarIterator::CigarIterator()
    : owner(NULL)
    , i(0)
{
}

CigarIterator::CigarIterator(const Alignment& owner)
    : owner(&owner)
    , i(0)
{
    if (i < owner.cigar_len) {
        c.start = owner.start;
        c.end   = c.start + (owner.cigar[i] >> BAM_CIGAR_SHIFT) - 1;
        c.op    = owner.cigar[i] & BAM_CIGAR_MASK;
    }
    else {
        c.start = -1;
        c.end   = -1;
        c.op    = BAM_CPAD;
    }
}

void CigarIterator::increment()
{
    if (i >= owner->cigar_len) return;

    if (++i < owner->cigar_len) {
        c.start = c.end + 1;
        c.end   = c.start + (owner->cigar[i] >> BAM_CIGAR_SHIFT) - 1;
        c.op    = owner->cigar[i] & BAM_CIGAR_MASK;
    }
}

bool CigarIterator::equal(const CigarIterator& other) const
{
    if (owner == NULL || i >= owner->cigar_len) {
        return other.owner == NULL || other.i >= other.owner->cigar_len;
    }
    else if (other.owner == NULL || other.i >= other.owner->cigar_len) {
        return false;
    }
    else {
        return owner == other.owner && i == other.i;
    }
}

const Cigar& CigarIterator::dereference() const
{
    return c;
}

AlignedRead::AlignedRead()
    : start(-1)
    , end(-1)
    , paired(false)
{
}

AlignedRead::~AlignedRead()
{
}

bool AlignedRead::operator < (const AlignedRead& other) const
{
    if (this->mate1.size() != other.mate1.size()) {
        return this->mate1.size() < other.mate1.size();
    }

    if (this->mate2.size() != other.mate2.size()) {
        return this->mate2.size() < other.mate2.size();
    }

    if      (start != other.start) return start < other.start;
    else if (end   != other.end)   return end   < other.end;

    std::set<Alignment*, AlignmentPtrCmp> S, T;
    std::set<Alignment*, AlignmentPtrCmp>::iterator i, j;

    if (this->mate1.size() > 0) {
        S.insert(this->mate1.begin(), this->mate1.end());
        T.insert(other.mate1.begin(), other.mate1.end());

        if (S.size() != T.size()) return S.size() < T.size();

        i = S.begin();
        j = T.begin();
        while (i != S.end()) {
            if (**i < **j) return true;
            ++i;
            ++j;
        }

        S.clear();
        T.clear();
    }

    if (this->mate2.size() > 0) {
        S.insert(this->mate2.begin(), this->mate2.end());
        T.insert(other.mate2.begin(), other.mate2.end());

        if (S.size() != T.size()) return S.size() < T.size();

        i = S.begin();
        j = T.begin();
        while (i != S.end()) {
            if (**i < **j) return true;
            ++i;
            ++j;
        }
    }

    return false;
}

AlignmentPair::AlignmentPair()
    : mate1(NULL)
    , mate2(NULL)
{
}

AlignmentPair::AlignmentPair(const AlignmentPair& other)
    : mate1(other.mate1)
    , mate2(other.mate2)
{
}

bool AlignmentPair::operator == (const AlignmentPair& other) const
{
    if (mate1 == other.mate2 ||
        (mate1 != NULL && other.mate1 != NULL && *mate1 == *other.mate1)) {

        return mate2 == other.mate2 ||
            (mate2 != NULL && other.mate2 != NULL && *mate2 == *other.mate2);

    }
    else return false;
}

bool AlignmentPair::operator < (const AlignmentPair& other) const
{
    if (mate1 == other.mate1 ||
        (mate1 != NULL && other.mate1 != NULL && *mate1 == *other.mate1)) {

        if (mate2 == NULL)            return other.mate2 != NULL;
        else if (other.mate2 == NULL) return false;
        else                          return *mate2 < *other.mate2;
    }
    else {
        if (mate1 == NULL)            return true;
        else if (other.mate1 == NULL) return false;
        else                          return *mate1 < *other.mate1;
    }
}

bool AlignmentPair::valid_frag() const
{
    if (mate1 == NULL || mate2 == NULL) return true;
    if (mate1->alnnum != mate2->alnnum) return false;

    switch (constants::libtype) {
        case constants::LIBTYPE_FR:
            if (mate1->strand == mate2->strand) return false;
            if (mate1->strand == strand_pos)    return mate1->start <= mate2->start;
            else                                return mate1->start >= mate2->start;

        case constants::LIBTYPE_RF:
            if (mate1->strand == mate2->strand)  return false;
            if (mate1->strand == strand_pos)     return mate1->start >= mate2->start;
            else                                 return mate1->start <= mate2->start;

        case constants::LIBTYPE_FF:
            if (mate1->strand != mate2->strand) return false;
            if (mate1->strand == strand_pos)    return mate1->start <= mate2->start;
            else                                return mate1->start >= mate2->start;

        default:
            return false;
    }
}

std::pair<pos_t, pos_t> AlignmentPair::flanks_soft_clipping() const
{
    std::pair<pos_t, pos_t> clipping(0, 0);

    if (mate1 && mate2 && mate1->cigar_len > 0 && mate2->cigar_len > 0) {
        const Alignment *a1, *a2;
        if (mate1->strand == strand_pos) {
            a1 = mate1;
            a2 = mate2;
        }
        else {
            a1 = mate2;
            a2 = mate1;
        }

        if ((a1->cigar[0] & BAM_CIGAR_MASK) == BAM_CSOFT_CLIP) {
            clipping.first = a1->cigar[0] >> BAM_CIGAR_SHIFT;
        }

        if ((a2->cigar[a2->cigar_len - 1] & BAM_CIGAR_MASK) == BAM_CSOFT_CLIP) {
            clipping.second = a2->cigar[a2->cigar_len - 1] >> BAM_CIGAR_SHIFT;
        }
    }
    else {
        const Alignment* a = mate1 ? mate1 : mate2;
        if (a->cigar_len > 0) {
            if (a->strand == strand_pos &&
                    (a->cigar[0] & BAM_CIGAR_MASK) == BAM_CSOFT_CLIP) {
                clipping.first = a->cigar[0] >> BAM_CIGAR_SHIFT;
            }
            else if ((a->cigar[a->cigar_len - 1] & BAM_CIGAR_MASK) == BAM_CSOFT_CLIP) {
                clipping.second = a->cigar[a->cigar_len - 1] >> BAM_CIGAR_SHIFT;
            }
        }
    }

    return clipping;
}

/* A couple functions to assist with AlignmentPair::frag_len */
static bool exon_compatible_cigar_op(uint8_t op)
{
    return op == BAM_CMATCH || op == BAM_CSOFT_CLIP || op == BAM_CINS || op == BAM_CDEL;
}

static bool intron_compatible_cigar_op(uint8_t op)
{
    return op == BAM_CREF_SKIP || op == BAM_CSOFT_CLIP;
}

pos_t AlignmentPair::frag_len(const Transcript& t) const
{
    /* Reorder mates for convenience. */
    const Alignment *a1, *a2;
    if (mate1 != NULL && mate2 != NULL) {
        if (mate1->start <= mate2->start) {
            a1 = mate1;
            a2 = mate2;
        }
        else {
            a1 = mate2;
            a2 = mate1;
        }

#if 0
        /* NOTE: we currently don't allow one mate to be contained within the
         * other. This might occur if the mates are if different lengths, but
         * isn't likely to be a problem. This function will need some
         * modifications if it does prove to be an issue. */
        if (a1->end > a2->end) {
            return -1;
        }
#endif
    }
    else if (mate1 != NULL) {
        a1 = mate1;
        a2 = NULL;
    }
    else {
        a1 = mate2;
        a2 = NULL;
    }

    if (a1 && a1->start < t.min_start) {
        return -1;
    }
    if (a2 && a2->end > t.max_end) {
        return -1;
    }

    TranscriptIntronExonIterator e1(t);
    CigarIterator c1(*a1);
    pos_t intron_len = 0;

    // Skip any leading soft clip
    if (c1 != CigarIterator() && c1->op == BAM_CSOFT_CLIP) ++c1;
    Cigar c = *c1;

    while (e1 != TranscriptIntronExonIterator() && c1 != CigarIterator()) {
        // case 1: e entirely preceedes c
        if (c.start > e1->first.end) {
            ++e1;
        }

        // case 2: c is contained within e
        else if (c.end   >= e1->first.start
              && c.end   <= e1->first.end
              && c.start >= e1->first.start)
        {
            if (e1->second == EXONIC_INTERVAL_TYPE) {
                if (!exon_compatible_cigar_op(c.op)) {
                    return -1;
                }
            }
            else {
                if (!intron_compatible_cigar_op(c.op)) {
                    return -1;
                }
                intron_len += e1->first.end - e1->first.start + 1;
                ++e1;
            }

            ++c1;
            c = *c1;
        }

        // case 3: soft clipping partially overlapping an exon or intron
        else if (c.op == BAM_CSOFT_CLIP) {
            ++c1;
            c = *c1;
        }

        else if (c.end > e1->first.end && c.op == BAM_CMATCH) {
            if (e1->second == EXONIC_INTERVAL_TYPE &&
                c.end - e1->first.end <= constants::max_intron_overlap) {
                c.end = e1->first.end;
            }
            else if (e1->second == INTRONIC_INTERVAL_TYPE &&
                     e1->first.end >= c.start &&
                     e1->first.end - c.start < constants::max_intron_overlap) {
                c.start = e1->first.end + 1;
            }
            else return -1;
        }

        // case 4: c precedes partially overlaps e
        else {
            return -1;
        }
    }

    if (c1 != CigarIterator()) {
        return -1;
    }

    /* alignment is compatible, but single ended. */
    if (a2 == NULL) {
        return 0;
    }

    bool e2_sup_e1 = false; /* marks when e2 > e1 */
    TranscriptIntronExonIterator e2(t);
    CigarIterator c2(*a2);
    c = *c2;

    while (e2 != TranscriptIntronExonIterator() && c2 != CigarIterator()) {
        // case 1: e entirely preceedes c
        if (c.start > e2->first.end) {
            if (e2->second == INTRONIC_INTERVAL_TYPE && e2_sup_e1) {
                intron_len += e2->first.end - e2->first.start + 1;
            }

            if (e1 == e2) e2_sup_e1 = true;

            ++e2;
        }

        // case 2: c is contained within e
        else if (c.end   >= e2->first.start
              && c.end   <= e2->first.end
              && c.start >= e2->first.start)
        {
            if (e2->second == EXONIC_INTERVAL_TYPE) {
                if (!exon_compatible_cigar_op(c.op)) {
                    return -1;
                }
            }
            else {
                if (!intron_compatible_cigar_op(c.op)) {
                    return -1;
                }
            }

            ++c2;
            c = *c2;
        }

        // case 3: soft clipping partially overlapping an exon or intron
        else if (c.op == BAM_CSOFT_CLIP) {
            ++c2;
            c = *c2;
        }

        else if (c.end > e2->first.end && c.op == BAM_CMATCH) {
            if (e2->second == EXONIC_INTERVAL_TYPE &&
                c.end - e2->first.end <= constants::max_intron_overlap) {
                c.end = e2->first.end;
            }
            else if (e2->second == INTRONIC_INTERVAL_TYPE &&
                     e2->first.end >= c.start &&
                     e2->first.end - c.start < constants::max_intron_overlap) {
                c.start = e2->first.end + 1;
            }
            else return -1;
        }

        // case 4: c precedes or partially overlaps e
        else {
            return -1;
        }
    }

    // skip any trailing soft clip
    if (c2 != CigarIterator() && c2->op == BAM_CSOFT_CLIP) ++c2;

    if (c2 != CigarIterator()) {
        return -1;
    }

    pos_t fraglen =
        std::max<pos_t>(a2->end, a1->end) -
        std::min<pos_t>(a1->start, a2->start) + 1 - intron_len;

    // assert(fraglen > 0);
    // This can be false in the following case:
    //
    //        ...-----exon-----]-----------intron------------
    //  Mate 1:  MMMMMMMMMMMMMMMSSSSSSSSSSSS
    //  Mate 2:    MMMMMMMMMMMMMSSSSSSSSSSSSSS
    //
    // We may want to do some work to handle that correctly, but both mates
    // soft-clipping into an intron is probably relatively rare.

    return fraglen;
}

pos_t AlignmentPair::naive_frag_len() const
{
    if (mate1 == NULL || mate2 == NULL) return 0;
    pos_t len = 1 + std::max(mate2->end - mate1->start, mate1->end - mate2->start);
    /* The fragment length must be at leas as long as the reads themselves. */
    if (len < mate2->end - mate2->start + 1 ||
        len < mate1->end - mate1->start + 1) {
        return 0;
    }
    else return len;
}

strand_t AlignmentPair::strand() const
{
    if (mate1) return (strand_t) mate1->strand;
    else {
        switch (constants::libtype) {
            case constants::LIBTYPE_FF:
                return (strand_t) mate2->strand;

            case constants::LIBTYPE_FR:
            case constants::LIBTYPE_RF:
            default:
                return other_strand((strand_t) mate2->strand);
        }
    }
}

AlignedReadIterator::AlignedReadIterator()
    : r(NULL)
    , i(0)
    , j(0)
{
}

AlignedReadIterator::AlignedReadIterator(const AlignedRead& r)
    : r(&r)
    , i(0)
    , j(0)
{
    p.mate1 = r.mate1.empty() ? NULL : r.mate1[0];
    p.mate2 = r.mate2.empty() ? NULL : r.mate2[0];
}

AlignedReadIterator::~AlignedReadIterator()
{
}

void AlignedReadIterator::increment()
{
    if (finished()) return;
    do {
        if (r->mate1.size() == 0) {
            do {
                ++j;
            } while (j < r->mate2.size() && r->mate2[j] == r->mate2[j - 1]);
        }
        else if (r->mate2.size() == 0) {
            do {
                ++i;
            } while (i < r->mate1.size() && r->mate1[i] == r->mate1[i - 1]);
        }
        else {
            do {
                ++j;
            } while (j < r->mate2.size() && r->mate2[j] == r->mate2[j - 1]);

            if (j >= r->mate2.size()) {
                j = 0;
                do {
                    ++i;
                } while (i < r->mate1.size() && r->mate1[i] == r->mate1[i - 1]);
            }
        }

        p.mate1 = i < r->mate1.size() ? r->mate1[i] : NULL;
        p.mate2 = j < r->mate2.size() ? r->mate2[j] : NULL;
    } while (!finished() && !p.valid_frag());
}

bool AlignedReadIterator::finished() const
{
    return r == NULL ||
        (r->mate1.size() == 0 && j >= r->mate2.size()) ||
        (r->mate2.size() == 0 && i >= r->mate1.size()) ||
        (r->mate1.size() > 0 && r->mate2.size() > 0 && i >= r->mate1.size());
}

bool AlignedReadIterator::equal(const AlignedReadIterator& other) const
{
    if (finished()) {
        return other.finished();
    }
    else {
        if (other.finished()) return false;
        return r == other.r && i == other.i && j == other.j;
    }
}

const AlignmentPair& AlignedReadIterator::dereference() const
{
    return p;
}

ReadSet::ReadSet()
{
}

ReadSet::~ReadSet()
{
    clear();
}

void ReadSet::add_alignment(long idx, const bam1_t* b)
{
    AlignedRead* r;
    boost::unordered_map<long, AlignedRead*>::iterator i = rs.find(idx);
    if (i == rs.end()) {
        r = new AlignedRead();
        rs[idx] = r;
    } else {
        r = i->second;
    }

    Alignment* a = new Alignment(b);
    if (b->core.flag & BAM_FREAD1 || b->core.flag & BAM_FREAD2) r->paired = true;

    if (b->core.flag & BAM_FREAD2) r->mate2.push_back(a);
    else                           r->mate1.push_back(a);

    if (r->start == -1 || r->start > a->start) r->start = a->start;
    if (r->end   == -1 || r->end   < a->end)   r->end   = a->end;
}

void ReadSet::clear()
{
    for (boost::unordered_map<long, AlignedRead*>::iterator i = rs.begin(); i != rs.end(); ++i) {
        BOOST_FOREACH (Alignment* m, i->second->mate1) {
            delete m;
        }

        BOOST_FOREACH (Alignment* m, i->second->mate2) {
            delete m;
        }
        delete i->second;
    }

    rs.clear();
}

size_t ReadSet::size() const
{
    return rs.size();
}

void ReadSet::make_unique_read_counts(ReadSet::UniqueReadCounts& counts)
{
    ReadSet::UniqueReadCounts::iterator j;

    for (boost::unordered_map<long, AlignedRead*>::iterator i = rs.begin(); i != rs.end(); ++i) {
        AlignedRead* r = i->second;
        j = counts.find(r);
        if (j == counts.end()) {
            counts.insert(std::make_pair(r, 1));
        }
        else j->second += 1;
    }
}

max_stars_repo_name: dcjones/isolator

max_issues_repo_name: dcjones/isolator

max_forks_repo_name: dcjones/isolator


text:
// Copyright 2018 Hans Dembinski
//
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt
// or copy at http://www.boost.org/LICENSE_1_0.txt)

#include <boost/core/lightweight_test.hpp>
#include <boost/core/lightweight_test_trait.hpp>
#include <boost/histogram/axis.hpp>
#include <boost/histogram/axis/traits.hpp>
#include "std_ostream.hpp"
#include "throw_exception.hpp"
#include "utility_axis.hpp"

using namespace boost::histogram::axis;

int main() {
  // value_type
  {
    BOOST_TEST_TRAIT_SAME(traits::value_type<integer<int>>, int);
    BOOST_TEST_TRAIT_SAME(traits::value_type<category<int>>, int);
    BOOST_TEST_TRAIT_SAME(traits::value_type<regular<double>>, double);
  }

  // is_continuous
  {
    BOOST_TEST_TRAIT_TRUE((traits::is_continuous<regular<>>));
    BOOST_TEST_TRAIT_FALSE((traits::is_continuous<integer<int>>));
    BOOST_TEST_TRAIT_FALSE((traits::is_continuous<category<int>>));
    BOOST_TEST_TRAIT_TRUE((traits::is_continuous<integer<double>>));
  }

  // is_reducible
  {
    struct not_reducible {};
    struct reducible {
      reducible(const reducible&, index_type, index_type, unsigned);
    };

    BOOST_TEST_TRAIT_TRUE((traits::is_reducible<reducible>));
    BOOST_TEST_TRAIT_FALSE((traits::is_reducible<not_reducible>));

    BOOST_TEST_TRAIT_TRUE((traits::is_reducible<regular<>>));
    BOOST_TEST_TRAIT_TRUE((traits::is_reducible<variable<>>));
    BOOST_TEST_TRAIT_TRUE((traits::is_reducible<circular<>>));
    BOOST_TEST_TRAIT_TRUE((traits::is_reducible<integer<>>));
    BOOST_TEST_TRAIT_FALSE((traits::is_reducible<category<>>));
  }

  // static_is_inclusive
  {
    struct empty {};
    struct with_opts_not_inclusive {
      static constexpr unsigned options() { return option::underflow | option::overflow; }
      static constexpr bool inclusive() { return false; }
    };

    BOOST_TEST_TRAIT_FALSE((traits::static_is_inclusive<empty>));
    BOOST_TEST_TRAIT_FALSE((traits::static_is_inclusive<with_opts_not_inclusive>));

    BOOST_TEST_TRAIT_TRUE((traits::static_is_inclusive<regular<>>));
    BOOST_TEST_TRAIT_FALSE(
        (traits::static_is_inclusive<
            regular<double, boost::use_default, boost::use_default, option::growth_t>>));
    BOOST_TEST_TRAIT_FALSE(
        (traits::static_is_inclusive<regular<double, boost::use_default,
                                             boost::use_default, option::circular_t>>));

    BOOST_TEST_TRAIT_TRUE((traits::static_is_inclusive<variable<>>));
    BOOST_TEST_TRAIT_FALSE((traits::static_is_inclusive<
                            variable<double, boost::use_default, option::growth_t>>));
    BOOST_TEST_TRAIT_FALSE((traits::static_is_inclusive<
                            variable<double, boost::use_default, option::circular_t>>));

    BOOST_TEST_TRAIT_TRUE((traits::static_is_inclusive<integer<int>>));
    BOOST_TEST_TRAIT_TRUE((
        traits::static_is_inclusive<integer<int, boost::use_default, option::growth_t>>));
    BOOST_TEST_TRAIT_TRUE((traits::static_is_inclusive<
                           integer<int, boost::use_default, option::circular_t>>));

    BOOST_TEST_TRAIT_TRUE((traits::static_is_inclusive<integer<double>>));
    BOOST_TEST_TRAIT_FALSE((traits::static_is_inclusive<
                            integer<double, boost::use_default, option::growth_t>>));
    BOOST_TEST_TRAIT_FALSE((traits::static_is_inclusive<
                            integer<double, boost::use_default, option::circular_t>>));

    BOOST_TEST_TRAIT_TRUE((traits::static_is_inclusive<category<int>>));
    BOOST_TEST_TRAIT_TRUE((traits::static_is_inclusive<
                           category<int, boost::use_default, option::growth_t>>));
    BOOST_TEST_TRAIT_FALSE(
        (traits::static_is_inclusive<category<int, boost::use_default, option::none_t>>));
  }

  // index, rank, value, width
  {
    auto a = integer<>(1, 3);
    BOOST_TEST_EQ(traits::index(a, 1), 0);
    BOOST_TEST_EQ(traits::rank(a), 1);
    BOOST_TEST_EQ(traits::value(a, 0), 1);
    BOOST_TEST_EQ(traits::width(a, 0), 0);
    BOOST_TEST_EQ(traits::width(a, 0), 0);

    auto b = integer<double>(1, 3);
    BOOST_TEST_EQ(traits::index(b, 1), 0);
    BOOST_TEST_EQ(traits::rank(b), 1);
    BOOST_TEST_EQ(traits::value(b, 0), 1);
    BOOST_TEST_EQ(traits::width(b, 0), 1);
    BOOST_TEST(traits::static_options<decltype(b)>::test(option::underflow));

    auto c = category<std::string>{"red", "blue"};
    BOOST_TEST_EQ(traits::index(c, "blue"), 1);
    BOOST_TEST_EQ(traits::rank(c), 1);
    BOOST_TEST_EQ(traits::value(c, 0), std::string("red"));
    BOOST_TEST_EQ(traits::width(c, 0), 0);

    struct D {
      index_type index(const std::tuple<int, double>& args) const {
        return static_cast<index_type>(std::get<0>(args) + std::get<1>(args));
      }
      index_type size() const { return 5u; }
    } d;
    BOOST_TEST_EQ(traits::index(d, std::make_tuple(1, 2.0)), 3.0);
    BOOST_TEST_EQ(traits::rank(d), 2u);

    variant<D, integer<>> v;
    v = a;
    BOOST_TEST_EQ(traits::rank(v), 1u);
    v = d;
    BOOST_TEST_EQ(traits::rank(v), 2u);
  }

  // static_options, options()
  {
    using A = integer<>;
    BOOST_TEST_EQ(traits::static_options<A>::test(option::growth), false);
    auto expected = option::underflow | option::overflow;
    auto a = A{};
    BOOST_TEST_EQ(traits::options(a), expected);
    BOOST_TEST_EQ(traits::options(static_cast<A&>(a)), expected);
    BOOST_TEST_EQ(traits::options(static_cast<const A&>(a)), expected);
    BOOST_TEST_EQ(traits::options(std::move(a)), expected);

    using B = integer<int, null_type, option::growth_t>;
    BOOST_TEST_EQ(traits::static_options<B>::test(option::growth), true);
    BOOST_TEST_EQ(traits::options(B{}), option::growth);

    struct growing {
      auto update(double) { return std::make_pair(0, 0); }
    };
    using C = growing;
    BOOST_TEST_EQ(traits::static_options<C>::test(option::growth), true);
    auto c = C{};
    BOOST_TEST_EQ(traits::options(c), option::growth);
    BOOST_TEST_EQ(traits::options(static_cast<C&>(c)), option::growth);
    BOOST_TEST_EQ(traits::options(static_cast<const C&>(c)), option::growth);
    BOOST_TEST_EQ(traits::options(std::move(c)), option::growth);

    struct notgrowing {
      auto index(double) { return 0; }
    };
    using D = notgrowing;
    BOOST_TEST_EQ(traits::static_options<D>::test(option::growth), false);
    auto d = D{};
    BOOST_TEST_EQ(traits::options(d), option::none);
    BOOST_TEST_EQ(traits::options(static_cast<D&>(d)), option::none);
    BOOST_TEST_EQ(traits::options(static_cast<const D&>(d)), option::none);
    BOOST_TEST_EQ(traits::options(std::move(d)), option::none);
  }

  // update
  {
    auto a = integer<int, null_type, option::growth_t>();
    BOOST_TEST_EQ(traits::update(a, 0), (std::pair<index_type, index_type>(0, -1)));
    BOOST_TEST_THROWS(traits::update(a, "foo"), std::invalid_argument);

    variant<integer<int, null_type, option::growth_t>, integer<>> v(a);
    BOOST_TEST_EQ(traits::update(v, 0), (std::pair<index_type, index_type>(0, 0)));
  }

  // metadata
  {
    struct None {};

    struct Const {
      const int& metadata() const { return m; };
      int m = 0;
    };

    struct Both {
      const int& metadata() const { return m; };
      int& metadata() { return m; };
      int m = 0;
    };

    None none;
    BOOST_TEST_TRAIT_SAME(decltype(traits::metadata(none)), null_type&);
    BOOST_TEST_TRAIT_SAME(decltype(traits::metadata(static_cast<None&>(none))),
                          null_type&);
    BOOST_TEST_TRAIT_SAME(decltype(traits::metadata(static_cast<const None&>(none))),
                          const null_type&);

    Const c;
    BOOST_TEST_EQ(traits::metadata(c), 0);
    BOOST_TEST_EQ(traits::metadata(static_cast<Const&>(c)), 0);
    BOOST_TEST_EQ(traits::metadata(static_cast<const Const&>(c)), 0);

    Both b;
    BOOST_TEST_EQ(traits::metadata(b), 0);
    BOOST_TEST_EQ(traits::metadata(static_cast<Both&>(b)), 0);
    BOOST_TEST_EQ(traits::metadata(static_cast<const Both&>(b)), 0);
  }

  return boost::report_errors();
}


text:
//
// key-chain-manager.h
//
//  Created by Peter Gusev on 02 September 2016.
//  Copyright 2013-2016 Regents of the University of California
//

#ifndef __key_chain_manager_h__
#define __key_chain_manager_h__

#include <boost/shared_ptr.hpp>

namespace ndn
{
class KeyChain;
class Face;
class Data;
class ConfigPolicyManager;
class IdentityStorage;
class PrivateKeyStorage;
}

class KeyChainManager
{
  public:
    KeyChainManager(boost::shared_ptr<ndn::Face> face,
                    const std::string &identityName,
                    const std::string &instanceName,
                    const std::string &configPolicy,
                    unsigned int runTime);

    boost::shared_ptr<ndn::KeyChain> defaultKeyChain() { return defaultKeyChain_; }
    boost::shared_ptr<ndn::KeyChain> instanceKeyChain() { return instanceKeyChain_; }
    std::string instancePrefix() const { return instanceIdentity_; }

    const boost::shared_ptr<ndn::Data> instanceCertificate() const
    {
        return instanceCert_;
    }

  private:
    boost::shared_ptr<ndn::Face> face_;
    std::string signingIdentity_, instanceName_,
        configPolicy_, instanceIdentity_;
    unsigned int runTime_;

    boost::shared_ptr<ndn::ConfigPolicyManager> configPolicyManager_;
    boost::shared_ptr<ndn::KeyChain> defaultKeyChain_, instanceKeyChain_;
    // instanceCert_ is a certificate subclass of Data.
    boost::shared_ptr<ndn::Data> instanceCert_;
    boost::shared_ptr<ndn::IdentityStorage> identityStorage_;
    boost::shared_ptr<ndn::PrivateKeyStorage> privateKeyStorage_;

    void setupDefaultKeyChain();
    void setupInstanceKeyChain();
    void setupConfigPolicyManager();
    void createSigningIdentity();
    void createMemoryKeychain();
    void createInstanceIdentity();
    void createInstanceIdentityV2();
    void checkExists(const std::string &);
};

#endif

max_stars_repo_name: luckiday/ndnrtc

max_issues_repo_name: luckiday/ndnrtc

max_forks_repo_name: luckiday/ndnrtc


text:
/*
 * Copyright (c) 2018 Nicholas Corgan (n.corgan@gmail.com)
 *
 * Distributed under the MIT License (MIT) (See accompanying file LICENSE.txt
 * or copy at http://opensource.org/licenses/MIT)
 */

#include "daycare_impl.hpp"
#include "daycare_gen1impl.hpp"
#include "daycare_gen2impl.hpp"
#include "daycare_gcnimpl.hpp"

#include "exception_internal.hpp"

#include "database/database_common.hpp"
#include "database/enum_conversions.hpp"
#include "database/id_to_string.hpp"

#include <boost/assert.hpp>
#include <boost/thread/lock_guard.hpp>

// TODO: "None" Pokémon's game should match daycare's

namespace pkmn {

    daycare::sptr daycare::make(pkmn::e_game game)
    {
        int game_id = pkmn::database::game_enum_to_id(game);
        int generation = pkmn::database::game_id_to_generation(game_id);

        daycare::sptr ret;

        switch(generation)
        {
            case 1:
                ret = std::make_shared<daycare_gen1impl>(game_id);
                break;

            case 2:
                ret = std::make_shared<daycare_gen2impl>(game_id);
                break;

            case 3:
                if(game_is_gamecube(game_id))
                {
                    ret = std::make_shared<daycare_gcnimpl>(game_id);
                }
                else
                {
                    throw pkmn::unimplemented_error();
                }
                break;

            case 4:
            case 5:
            case 6:
            case 7:
                throw pkmn::unimplemented_error();

            default:
                throw std::out_of_range("Invalid game");
        }

        return ret;
    }

    daycare_impl::daycare_impl(int game_id):
        daycare(),
        _game_id(game_id),
        _generation(pkmn::database::game_id_to_generation(game_id)),
        _levelup_pokemon(),
        _breeding_pokemon(),
        _egg(nullptr),
        _p_native(nullptr),
        _is_our_mem(false)
    {}

    daycare_impl::~daycare_impl() {}

    pkmn::e_game daycare_impl::get_game()
    {
        return pkmn::database::game_id_to_enum(_game_id);
    }

    const pkmn::pokemon::sptr& daycare_impl::get_levelup_pokemon(
        int index
    )
    {
        int levelup_capacity = this->get_levelup_pokemon_capacity();

        // Same functionality, just better error messages for the given
        // situation
        if(levelup_capacity == 1)
        {
            pkmn::enforce_comparator(
                "Index",
                index,
                0,
                pkmn::value_comparator::EQ
            );
        }
        else
        {
            pkmn::enforce_bounds(
                "Index",
                index,
                0,
                (levelup_capacity - 1)
            );
        }

        boost::lock_guard<daycare_impl> lock(*this);

        return this->_get_levelup_pokemon_ref().at(index);
    }

    const pkmn::pokemon_list_t& daycare_impl::get_levelup_pokemon_as_vector()
    {
        boost::lock_guard<daycare_impl> lock(*this);

        return this->_get_levelup_pokemon_ref();
    }

    const pkmn::pokemon::sptr& daycare_impl::get_breeding_pokemon(
        int index
    )
    {
        if(!this->can_breed_pokemon())
        {
            throw pkmn::feature_not_in_game_error(
                      "Breeding",
                      this->get_game()
                  );
        }
        pkmn::enforce_bounds(
            "Index",
            index,
            0,
            (this->get_breeding_pokemon_capacity() - 1)
        );

        boost::lock_guard<daycare_impl> lock(*this);

        return this->_breeding_pokemon.at(index);
    }

    const pkmn::pokemon_list_t& daycare_impl::get_breeding_pokemon_as_vector()
    {
        if(!this->can_breed_pokemon())
        {
            throw pkmn::feature_not_in_game_error(
                      "Breeding",
                      this->get_game()
                  );
        }

        boost::lock_guard<daycare_impl> lock(*this);

        return _breeding_pokemon;
    }

    const pkmn::pokemon::sptr& daycare_impl::get_egg()
    {
        if(!this->can_breed_pokemon())
        {
            throw pkmn::feature_not_in_game_error(
                      "Breeding",
                      this->get_game()
                  );
        }

        boost::lock_guard<daycare_impl> lock(*this);

        return _egg;
    }

    void* daycare_impl::get_native()
    {
        boost::lock_guard<daycare_impl> lock(*this);

        _to_native_levelup();
        _to_native_breeding();

        return _p_native;
    }

    // Before Generation VII, daycares and nurseries were the same, so
    // we use a single vector. The choice of using the breeding vector
    // is arbitrary.
    pkmn::pokemon_list_t& daycare_impl::_get_levelup_pokemon_ref()
    {
        return (_generation < 7) ? _breeding_pokemon : _levelup_pokemon;
    }
}

max_stars_repo_name: ncorgan/libpkmn

max_issues_repo_name: PMArkive/libpkmn

max_forks_repo_name: PMArkive/libpkmn


text:
#pragma once

#include "parser_core.hpp"
#include <boost/spirit/repository/include/qi_confix.hpp>

namespace TwistedSpirit
{
    using boost::spirit::repository::confix;
}


text:
//==================================================================================================
/*!
  @file

  @copyright 2016 NumScale SAS
  @copyright 2016 J.T. Lapreste

  Distributed under the Boost Software License, Version 1.0.
  (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
*/
//==================================================================================================
#ifndef BOOST_SIMD_FUNCTION_DEINTERLEAVE_FIRST_HPP_INCLUDED
#define BOOST_SIMD_FUNCTION_DEINTERLEAVE_FIRST_HPP_INCLUDED

#if defined(DOXYGEN_ONLY)
namespace boost { namespace simd
{

 /*!

    @ingroup group-swar
    Function object implementing deinterleave_first capabilities

    Computes a vector from a combination of the two inputs.

    @par Semantic:

    For every parameters of type T
    @code
    T0 r = deinterleave_first(x,y);
    @endcode

    is equivalent to :

    @code
    r = [ x[0] x[1] ... x[n/2] y[0] y[1] ... y[n/2] ]
    @endcode

    with <tt> n = cardinal_of<T>::value </tt>

  **/
  const boost::dispatch::functor<tag::deinterleave_first_> deinterleave_first = {};
} }
#endif

#include <boost/simd/function/scalar/deinterleave_first.hpp>
#include <boost/simd/function/simd/deinterleave_first.hpp>

#endif


text:
/* Copyright 2016 Guillem Pascual */

#pragma once

#include "defs/intrusive.hpp"
#include <boost/intrusive_ptr.hpp>

#include "defs/common.hpp"

INCL_NOWARN
#include <glm/glm.hpp>
INCL_WARN

class Bezier;
class MapAwareEntity;
class Packet;

class MovementGenerator
{
public:
    virtual ~MovementGenerator();

    virtual boost::intrusive_ptr<Packet> packet() = 0;
    virtual glm::vec3 update(MapAwareEntity* owner, float elapsed) = 0;
    virtual bool hasNext() = 0;
};

class RandomMovement : public MovementGenerator
{
public:
    RandomMovement();
    virtual ~RandomMovement();

    boost::intrusive_ptr<Packet> packet() override;
    glm::vec3 update(MapAwareEntity* owner, float elapsed) override;
    bool hasNext() override;

private:
    bool _hasPoint;

    Bezier* _bezier;

    float _t;
    glm::vec2 _previous;
};

class Bezier
{
public:
    Bezier(glm::vec2 a, glm::vec2 b, glm::vec2 c, glm::vec2 d) :
        _a(a), _b(b), _c(c), _d(d)
    {}

    virtual ~Bezier();

    virtual glm::vec2 next(float t) = 0;
    virtual float increase(float t, float speed) = 0;

    inline glm::vec2 start() { return _a; }
    inline glm::vec2 startOffset() { return _b; }
    inline glm::vec2 endOffset() { return _c; }
    inline glm::vec2 end() { return _d; }

protected:
    glm::vec2 calc(float t)
    {
        float u = 1.0f - t;
        float tt = t * t;
        float uu = u * u;
        float uuu = uu * u;
        float ttt = tt * t;

        glm::vec2 p = uuu * _a;     // first term
        p += 3 * uu * t * _b;       // second term
        p += 3 * u * tt * _c;       // third term
        p += ttt * _d;              // fourth term

        return p;
    }

protected:
    glm::vec2 _a;
    glm::vec2 _b;
    glm::vec2 _c;
    glm::vec2 _d;
};

template <int len>
class SegmentedBezier : public Bezier
{
public:
    SegmentedBezier(glm::vec2 a, glm::vec2 b, glm::vec2 c, glm::vec2 d) :
        Bezier(a, b, c, d),
        _length(0)
    {
        _segments[0] = 0;

        glm::vec2 origin = calc(0);
        for (int i = 1; i <= len; i += 1)
        {
            glm::vec2 p = calc(i * (1.0f / len));
            _length += glm::distance(p, origin);
            _segments[i] = _length;
            origin = p;
        }
    }

    float increase(float t, float speed)
    {
        return speed / _length;
    }

    glm::vec2 next(float t)
    {
        return calc(map(t));
    }

protected:
    float map(float t)
    {
        float targetLength = t * _segments[len];
        int low = 0;
        int high = len;
        int index = 0;

        while (low < high)
        {
            index = low + (high - low) / 2;
            if (_segments[index] < targetLength)
            {
                low = index + 1;
            }
            else
            {
                high = index;
            }
        }

        if (_segments[index] > targetLength)
        {
            index--;
        }

        float lengthBefore = _segments[index];
        if (lengthBefore == targetLength)
        {
            return index / static_cast<float>(len);
        }

        return (index + (targetLength - lengthBefore) /
            static_cast<float>(_segments[index + 1] - lengthBefore)) / static_cast<float>(len);
    }

protected:
    float _segments[len + 1];
    float _length;
};

class DerivativeBezier : public Bezier
{
public:
    DerivativeBezier(glm::vec2 a, glm::vec2 b, glm::vec2 c, glm::vec2 d) :
        Bezier(a, b, c, d)
    {
        _dv1 = -3.0f * a + 9.0f * b - 9.0f * c + 3.0f * d;
        _dv2 = 6.0f * a - 12.0f * b + 6.0f * c;
        _dv3 = -3.0f * a + 3.0f * b;
    }

    float increase(float t, float speed)
    {
        return speed / glm::length(t * t * _dv1 + t * _dv2 + _dv3);
    }

    glm::vec2 next(float t)
    {
        return calc(t);
    }

protected:
    glm::vec2 _dv1;
    glm::vec2 _dv2;
    glm::vec2 _dv3;
};

max_stars_repo_name: gpascualg/Shinzui

max_issues_repo_name: gpascualg/Shinzui

max_forks_repo_name: gpascualg/Shinzui


text:
#include <iostream>
#include <boost/thread.hpp>
#include <boost/bind.hpp>
#include <boost/asio.hpp>
#include <vector>
#include <boost/shared_ptr.hpp>
using namespace boost::asio;
io_service service;

struct talk_to_svr {
private:
    ip::tcp::socket sock_;
    enum { max_msg = 1024 };
    int already_read_;
    char buff_[max_msg];
    bool started_;
    std::string username_;

    void write_request() {
        write("ping\n");
    }
    void read_answer() {
        already_read_ = 0;
        read(sock_, buffer(buff_), boost::bind(&talk_to_svr::read_complete, this, _1, _2));
        process_msg();
    }
    void process_msg() {
        std::string msg(buff_, already_read_);
        if ( msg.find("login ") == 0)
            on_login();
        else if ( msg.find("ping") == 0)
            on_ping(msg);
        else if ( msg.find("clients ") == 0)
            on_clients(msg);
    }

    void on_login() {
        std::cout << username_ << " logged in" << std::endl;
        do_ask_clients();
    }
    void on_ping(const std::string & msg) {
        std::istringstream in(msg);
        std::string answer;
        in >> answer >> answer;
        if ( answer == "client_list_changed")
            do_ask_clients();
    }
    void on_clients(const std::string & msg) {
        std::string clients = msg.substr(8);
        std::cout << username_ << ", new client list:" << clients;
    }
    void do_ask_clients() {
        write("clients\n");
        read_answer();
    }

    void write(const std::string & msg) {
        sock_.write_some(buffer(msg));
    }
    size_t read_complete(const boost::system::error_code & err, size_t bytes) {
        if ( err) return 0;
        already_read_ = bytes;
        bool found = std::find(buff_, buff_ + bytes, '\n') < buff_ + bytes;
        return found ? 0 : 1;
    }
public:
    talk_to_svr(const std::string & username) : sock_(service), started_(true), username_(username) {}
    void connect(ip::tcp::endpoint ep) {
        sock_.connect(ep);
    }
    void loop() {
        write("login " + username_ + "\n");
        read_answer();
        while ( started_) {
            write_request();
            read_answer();
            int millis = rand() % 7000;
            std::cout << username_ << " postpone ping " << millis << " ms" << std::endl;
            boost::this_thread::sleep(boost::posix_time::millisec(millis));
        }
    }
    std::string username() const {
        return username_;
    }
};

ip::tcp::endpoint ep( ip::address::from_string("127.0.0.1"), 8001);
void run_client(const std::string & client_name) {
    talk_to_svr client(client_name);
    try {
        client.connect(ep);
        client.loop();
    } catch(boost::system::system_error & err) {
        std::cout << "client terminated " << client.username() << std::endl;
    }
}

int main() {
    std::string names[6] = { "John", "James", "Lucy", "Tracy", "Frank", "Abby"};
    std::vector<boost::thread> threads;
    threads.reserve(6);
    for ( size_t i = 0; i < 6 ; i++) {
        threads.emplace_back(run_client, names[i]);
        boost::this_thread::sleep( boost::posix_time::millisec(100));
    }
    for(boost::thread &thread : threads){
        thread.join();
    }
}


text: #include <boost/accumulators/framework/parameters/weight.hpp>

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


text:
//Copyright (c) 2008-2016 Emil Dotchevski and Reverge Studios, Inc.

//Distributed under the Boost Software License, Version 1.0. (See accompanying
//file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)

#ifndef UUID_49C5A1042AEF11DF9603880056D89593
#define UUID_49C5A1042AEF11DF9603880056D89593

#include <boost/qvm/detail/quat_assign.hpp>
#include <boost/qvm/assert.hpp>
#include <boost/qvm/static_assert.hpp>

namespace
boost
    {
    namespace
    qvm
        {
        template <class T>
        struct
        quat
            {
            T a[4];
            template <class R>
            operator R() const
                {
                R r;
                assign(r,*this);
                return r;
                }
            };

        template <class Q>
        struct quat_traits;

        template <class T>
        struct
        quat_traits< quat<T> >
            {
            typedef quat<T> this_quaternion;
            typedef T scalar_type;

            template <int I>
            static
            BOOST_QVM_INLINE_CRITICAL
            scalar_type
            read_element( this_quaternion const & x )
                {
                BOOST_QVM_STATIC_ASSERT(I>=0);
                BOOST_QVM_STATIC_ASSERT(I<4);
                return x.a[I];
                }

            template <int I>
            static
            BOOST_QVM_INLINE_CRITICAL
            scalar_type &
            write_element( this_quaternion & x )
                {
                BOOST_QVM_STATIC_ASSERT(I>=0);
                BOOST_QVM_STATIC_ASSERT(I<4);
                return x.a[I];
                }
            };
        }
    }

#endif

max_stars_repo_name: fictheader/fcolorwheel

max_issues_repo_name: fictheader/fcolorwheel

max_forks_repo_name: ZeroInfinite/turicreate


text:
/*=============================================================================
    Copyright (c) 2006-2007 Tobias Schwinger

    Use modification and distribution are subject to the Boost Software
    License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
    http://www.boost.org/LICENSE_1_0.txt).
==============================================================================*/

#if !defined(BOOST_FUSION_FUNCTIONAL_HPP_INCLUDED)
#define BOOST_FUSION_FUNCTIONAL_HPP_INCLUDED

#include <boost/fusion/functional/invocation.hpp>
#include <boost/fusion/functional/adapter.hpp>
#include <boost/fusion/functional/generation.hpp>

#endif

max_stars_repo_name: PXLVision/opengv

max_issues_repo_name: isuhao/klib

max_forks_repo_name: isuhao/klib


text:
#ifndef GE_ACTOR_HPP
#define GE_ACTOR_HPP

#pragma once

#include "ge/hash_typeindex.hpp"
#include "ge/transform.hpp"

#include <spdlog/spdlog.h>

#include <memory>

#include <glm/glm.hpp>
#include <glm/gtx/matrix_transform_2d.hpp>
#include <glm/gtx/rotate_vector.hpp>
#include <glm/gtx/norm.hpp>

#include <boost/container/flat_map.hpp>
#include <boost/container/flat_set.hpp>

namespace ge
{
struct runtime;
/// The class that represents anything that can be placed in the world.
class actor : public std::enable_shared_from_this<actor>
{
	// no shared_ptr because that would be a cyclic reference
	actor* m_parent = nullptr;

	transform m_transform;

	boost::container::flat_map<boost::typeindex::type_index, std::shared_ptr<void>> m_interfaces;

protected:
	// called from `factory`
	actor() noexcept {};

	// so we can use make_shared

public:
	// set for find -- we don't care much about insertion speed, but iteration is more important.
	boost::container::flat_set<std::shared_ptr<actor>> m_children;

	/// Creates an actor of type ActorType
	/// \param parent The parent actor, null for a root actor
	/// \param init_params The initialization paramters, will be passed to ActorType::initialize
	template <typename ActorType = actor, typename... InitParams>
	static std::shared_ptr<ActorType> factory(actor* parent, InitParams&&... init_params)
	{
		assert(parent);

		static_assert(std::is_base_of<actor, ActorType>::value,
			"Cannot use actor::factory on non-actor type.");

		auto ret = std::shared_ptr<ActorType>(new ActorType());
		assert(ret);

		ret->set_parent(parent);
		ret->m_runtime = parent->m_runtime;

		// if you get an error here, you passed the wrong parameters to initialize or initialize isn't public
		ret->initialize(std::forward<InitParams>(init_params)...);

		return ret;
	}

	template <typename asset_type>
	auto get_asset(const char* name);

	/// Creates a root actor of type ActorType
	/// \param runtime The runtime object to create it under
	/// \param init_params The initialization paramters, will be passed to ActorType::initialize
	template <typename ActorType = actor, typename... InitParams>
	static std::shared_ptr<ActorType> root_factory(runtime* runtime, InitParams&&... init_params)
	{
		assert(runtime);

		static_assert(std::is_base_of<actor, ActorType>::value,
			"Cannot use actor::factory on non-actor type.");

		auto ret = std::shared_ptr<ActorType>(new ActorType());
		assert(ret);

		ret->m_runtime = runtime;
		ret->initialize(std::forward<InitParams>(init_params)...);

		return ret;
	}

	// no move or copy -- will be in a shared_ptr
	actor(const actor&) = delete;
	actor(actor&&) = delete;

	/// initializes that class--create another version of this in child actors with parameters
	void initialize(){};

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

	virtual ~actor();

	/// Gets a std::shared_ptr<actor> from the actor
	/// \param to_share The actor to turn into a std::shared_ptr
	template <typename ActorType>
	static std::shared_ptr<ActorType> shared(ActorType* to_share) noexcept
	{
		static_assert(std::is_base_of<actor, ActorType>::value,
			"Cannot use actor::shared on a non-actor type");

		return std::static_pointer_cast<ActorType>(to_share->shared_from_this());
	}

	// Interface Interface
	//////////////////////

	/// Adds an iterface to the actor. First template parameter is the actor type, second is the
	/// interface.
	template <typename ActorType, typename Interface, typename... ExtraArgs>
	void add_interface(ExtraArgs&&... extraArgs);

	/// Query if this actor implements a certain interface
	template <typename Interface>
	bool implements_interface() const
	{
		auto iter = m_interfaces.find(boost::typeindex::type_id<Interface>());

		return iter != m_interfaces.end();
	}

	/// Get the storage object for a given interface, nullptr if that interface isn't implemented
	template <typename Interface>
	auto get_interface_storage() -> typename Interface::interface_storage*
	{
		auto iter = m_interfaces.find(boost::typeindex::type_id<Interface>());

		if (iter == m_interfaces.end()) return nullptr;

		return static_cast<typename Interface::interface_storage*>(iter->second.get());
	}

	// transform transformation functions
	/////////////////////////////////////

	/// sets the location relative to the parent, if there is one.
	/// \param new_location the new location
	void set_relative_location(glm::vec2 new_location) noexcept
	{
		m_transform.location = new_location;
	}
	/// Gets the location of the actor relative to the parent
	/// \return The relative location
	glm::vec2 get_relative_location() const noexcept { return m_transform.location; }
	/// Sets the rotation relative to the parent.
	/// \param new_rotation the new rotation to apply, in radians counter-clockwise
	void set_relative_rotation(float new_rotation) noexcept { m_transform.rotation = new_rotation; }
	/// Gets the rotation of the actor relative to the parent
	/// \return The relative rotation, in radians counter-clockwise
	float get_relative_rotation() const noexcept { return m_transform.rotation; }
	/// Sets the scale of the actor relative to the parent
	/// \param new_scale The relative scale
	void set_relative_scale(glm::vec2 new_scale) noexcept { m_transform.scale = new_scale; }
	/// Gets the scale relative to the parent actor
	/// \return The relative scale
	glm::vec2 get_relative_scale() const noexcept { return m_transform.scale; }
	/// Calculates the absolute location of the actor
	/// \return The absolute location
	glm::vec2 calcuate_absolute_location() const noexcept
	{
		if (has_parent()) {
			glm::vec2 parent_loc = get_parent()->calcuate_absolute_location();
			float parent_rot = get_parent()->calcuate_absolute_rotation();
			return parent_loc +
				   glm::rotate(get_relative_location() * get_parent()->calcuate_absolute_scale(),
					   glm::radians(parent_rot));
		}

		return get_relative_location();
	}
	/// Calculates the absolute rotation of the actor
	/// \return The absolute rotation
	float calcuate_absolute_rotation() const noexcept
	{
		if (has_parent()) {
			return get_parent()->calcuate_absolute_rotation() + get_relative_rotation();
		}

		return get_relative_rotation();
	}
	/// Calculates the absolute scale of the actor
	/// \return The absolute scale
	glm::vec2 calcuate_absolute_scale() const noexcept
	{
		if (has_parent()) {
			return get_parent()->calcuate_absolute_scale() * get_relative_scale();
		}
		return get_relative_scale();
	}

	/// Calculates the model matrix for the actor
	/// \return The model matrix
	glm::mat3 calculate_model_matrix() const noexcept;

	// parent manipulation
	//////////////////////

	/// Sets the parent of the actor, unparenting it from the previous parent
	/// \param new_parent The new parent of the actor
	void set_parent(actor* new_parent) noexcept;

	/// Gets the parent actor
	/// \return The parent actor if present, otherwise `nullptr`
	actor* get_parent() const noexcept { return m_parent; }
	/// Gets if the actor has a parent.
	/// \return Has a parent?
	bool has_parent() const noexcept { return m_parent != nullptr; }
	/// Propagates  function to all the children
	/// \param func The function to propagate
	template <typename F>
	void propagate_to_children(F&& func)
	{
		std::forward<F>(func)(*this);

		for (auto child : m_children) {
			if (!child) continue;
			child->propagate_to_children(std::forward<F>(func));
		}
	}

	/// The runtime object that was passed down from the parent actor
	runtime* m_runtime;
};
}  // namespace ge

#include "ge/runtime.hpp"

namespace ge
{
template <typename ActorType, typename Interface, typename... ExtraArgs>
void actor::add_interface(ExtraArgs&&... extraArgs)
{
	using boost::typeindex::type_id;

	static_assert(
		std::is_base_of<actor, ActorType>::value, "Must pass an actor type into add_interface");

	auto* interface = m_runtime->get_interface<Interface>();
	if (!interface) {
		logger->warn("Tried to add interface " + type_id<Interface>().pretty_name() +
					 " that wasn't registered. call runtime::register_interface");
		return;
	}

	// if you get an error here, that means you didn't have the right arguments to
	// actor::add_interface
	m_interfaces.emplace(boost::typeindex::type_id<Interface>(),
		interface->template gen_interface<ActorType>(
			static_cast<ActorType*>(this), std::forward<ExtraArgs>(extraArgs)...));
}

template <typename asset_type>
auto actor::get_asset(const char* name)
{
	return m_runtime->m_asset_manager.get_asset<asset_type>(name);
}

inline glm::vec2 interpolate_to(glm::vec2 start, glm::vec2 dest, glm::vec2 current, float totalSecs, float deltaT) {
	auto distanceToGo = dest - start;

	// we're already there
	if (glm::length2(distanceToGo) <= glm::length2(current - start)) {
		return dest;
	}

	auto distancePerSec = distanceToGo / totalSecs;

	return current + distancePerSec * deltaT;
}

}  // namespace ge

#endif  // GE_ACTOR_HPP

max_stars_repo_name: gentlemans/gentlemanly-engine

max_issues_repo_name: gentlemans/gentlemanly-engine

max_forks_repo_name: gentlemans/gentlemanly-engine