text:
/*
 * Copyright (c) 2011, Peter Thorson. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of the WebSocket++ Project 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 PETER THORSON 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 WEBSOCKET_FRAME_HPP
#define WEBSOCKET_FRAME_HPP

#include "common.hpp"

#include "network_utilities.hpp"
#include "processors/processor.hpp"
#include "utf8_validator/utf8_validator.hpp"

#include <boost/utility.hpp>

#if BEAST_WIN32
#include <winsock2.h>
#else
#include <arpa/inet.h>
#endif

#include <vector>
#include <cstring>
#include <iostream>
#include <algorithm>

namespace websocketpp {
namespace frame {

/* policies to abstract out

 - random number generation
 - utf8 validation

rng
 int32_t gen()

class boost_random {
public:
    boost_random()
    int32_t gen();
private:
 boost::random::random_device m_rng;
 boost::random::variate_generator<boost::random::random_device&,boost::random::uniform_int_distribution<> > m_gen;
 }

 */

template <class rng_policy>
class parser : boost::noncopyable {
public:
    // basic payload byte flags
    static const uint8_t BPB0_OPCODE = 0x0F;
    static const uint8_t BPB0_RSV3 = 0x10;
    static const uint8_t BPB0_RSV2 = 0x20;
    static const uint8_t BPB0_RSV1 = 0x40;
    static const uint8_t BPB0_FIN = 0x80;
    static const uint8_t BPB1_PAYLOAD = 0x7F;
    static const uint8_t BPB1_MASK = 0x80;

    static const uint8_t BASIC_PAYLOAD_16BIT_CODE = 0x7E; // 126
    static const uint8_t BASIC_PAYLOAD_64BIT_CODE = 0x7F; // 127

    static const unsigned int BASIC_HEADER_LENGTH = 2;
    static const unsigned int MAX_HEADER_LENGTH = 14;
    static const uint8_t extended_header_length = 12;
    static const uint64_t max_payload_size = 100000000; // 100MB

    // create an empty frame for writing into
    parser(rng_policy& rng) : m_rng(rng) {
        reset();
    }

    bool ready() const {
        return (m_state == STATE_READY);
    }
    uint64_t get_bytes_needed() const {
        return m_bytes_needed;
    }
    void reset() {
        m_state = STATE_BASIC_HEADER;
        m_bytes_needed = BASIC_HEADER_LENGTH;
        m_degraded = false;
        m_payload.clear();
        std::fill(m_header,m_header+MAX_HEADER_LENGTH,0);
    }

    // Method invariant: One of the following must always be true even in the case
    // of exceptions.
    // - m_bytes_needed > 0
    // - m-state = STATE_READY
    void consume(std::istream &s) {
        try {
            switch (m_state) {
                case STATE_BASIC_HEADER:
                    s.read(&m_header[BASIC_HEADER_LENGTH-m_bytes_needed],m_bytes_needed);

                    m_bytes_needed -= s.gcount();

                    if (m_bytes_needed == 0) {
                        process_basic_header();

                        validate_basic_header();

                        if (m_bytes_needed > 0) {
                            m_state = STATE_EXTENDED_HEADER;
                        } else {
                            process_extended_header();

                            if (m_bytes_needed == 0) {
                                m_state = STATE_READY;
                                process_payload();

                            } else {
                                m_state = STATE_PAYLOAD;
                            }
                        }
                    }
                    break;
                case STATE_EXTENDED_HEADER:
                    s.read(&m_header[get_header_len()-m_bytes_needed],m_bytes_needed);

                    m_bytes_needed -= s.gcount();

                    if (m_bytes_needed == 0) {
                        process_extended_header();
                        if (m_bytes_needed == 0) {
                            m_state = STATE_READY;
                            process_payload();
                        } else {
                            m_state = STATE_PAYLOAD;
                        }
                    }
                    break;
                case STATE_PAYLOAD:
                    s.read(reinterpret_cast<char *>(&m_payload[m_payload.size()-m_bytes_needed]),
                           m_bytes_needed);

                    m_bytes_needed -= s.gcount();

                    if (m_bytes_needed == 0) {
                        m_state = STATE_READY;
                        process_payload();
                    }
                    break;
                case STATE_RECOVERY:
                    // Recovery state discards all bytes that are not the first byte
                    // of a close frame.
                    do {
                        s.read(reinterpret_cast<char *>(&m_header[0]),1);

                        //std::cout << std::hex << int(static_cast<unsigned char>(m_header[0])) << " ";

                        if (int(static_cast<unsigned char>(m_header[0])) == 0x88) {
                            //(BPB0_FIN && CONNECTION_CLOSE)
                            m_bytes_needed--;
                            m_state = STATE_BASIC_HEADER;
                            break;
                        }
                    } while (s.gcount() > 0);

                    //std::cout << std::endl;

                    break;
                default:
                    break;
            }

            /*if (s.gcount() == 0) {
             throw frame_error("consume read zero bytes",FERR_FATAL_SESSION_ERROR);
             }*/
        } catch (const processor::exception& e) {
            // After this point all non-close frames must be considered garbage,
            // including the current one. Reset it and put the reading frame into
            // a recovery state.
            if (m_degraded == true) {
                throw processor::exception("An error occurred while trying to gracefully recover from a less serious frame error.",processor::error::FATAL_ERROR);
            } else {
                reset();
                m_state = STATE_RECOVERY;
                m_degraded = true;

                throw e;
            }
        }
    }

    // get pointers to underlying buffers
    char* get_header() {
        return m_header;
    }
    char* get_extended_header() {
        return m_header+BASIC_HEADER_LENGTH;
    }
    unsigned int get_header_len() const {
        unsigned int temp = 2;

        if (get_masked()) {
            temp += 4;
        }

        if (get_basic_size() == 126) {
            temp += 2;
        } else if (get_basic_size() == 127) {
            temp += 8;
        }

        return temp;
    }

    char* get_masking_key() {
        /*if (m_state != STATE_READY) {
            std::cout << "throw" << std::endl;
            throw processor::exception("attempted to get masking_key before reading full header");
        }*/
        return &m_header[get_header_len()-4];
    }

    // get and set header bits
    bool get_fin() const {
        return ((m_header[0] & BPB0_FIN) == BPB0_FIN);
    }
    void set_fin(bool fin) {
        if (fin) {
            m_header[0] |= BPB0_FIN;
        } else {
            m_header[0] &= (0xFF ^ BPB0_FIN);
        }
    }

    bool get_rsv1() const {
        return ((m_header[0] & BPB0_RSV1) == BPB0_RSV1);
    }
    void set_rsv1(bool b) {
        if (b) {
            m_header[0] |= BPB0_RSV1;
        } else {
            m_header[0] &= (0xFF ^ BPB0_RSV1);
        }
    }

    bool get_rsv2() const {
        return ((m_header[0] & BPB0_RSV2) == BPB0_RSV2);
    }
    void set_rsv2(bool b) {
        if (b) {
            m_header[0] |= BPB0_RSV2;
        } else {
            m_header[0] &= (0xFF ^ BPB0_RSV2);
        }
    }

    bool get_rsv3() const {
        return ((m_header[0] & BPB0_RSV3) == BPB0_RSV3);
    }
    void set_rsv3(bool b) {
        if (b) {
            m_header[0] |= BPB0_RSV3;
        } else {
            m_header[0] &= (0xFF ^ BPB0_RSV3);
        }
    }

    opcode::value get_opcode() const {
        return frame::opcode::value(m_header[0] & BPB0_OPCODE);
    }
    void set_opcode(opcode::value op) {
        if (opcode::reserved(op)) {
            throw processor::exception("reserved opcode",processor::error::PROTOCOL_VIOLATION);
        }

        if (opcode::invalid(op)) {
            throw processor::exception("invalid opcode",processor::error::PROTOCOL_VIOLATION);
        }

        if (is_control() && get_basic_size() > limits::PAYLOAD_SIZE_BASIC) {
            throw processor::exception("control frames can't have large payloads",processor::error::PROTOCOL_VIOLATION);
        }

        m_header[0] &= (0xFF ^ BPB0_OPCODE); // clear op bits
        m_header[0] |= op; // set op bits
    }

    bool get_masked() const {
        return ((m_header[1] & BPB1_MASK) == BPB1_MASK);
    }
    void set_masked(bool masked) {
        if (masked) {
            m_header[1] |= BPB1_MASK;
            generate_masking_key();
        } else {
            m_header[1] &= (0xFF ^ BPB1_MASK);
            clear_masking_key();
        }
    }

    uint8_t get_basic_size() const {
        return m_header[1] & BPB1_PAYLOAD;
    }
    size_t get_payload_size() const {
        if (m_state != STATE_READY && m_state != STATE_PAYLOAD) {
            // TODO: how to handle errors like this?
            throw "attempted to get payload size before reading full header";
        }

        return m_payload.size();
    }

    close::status::value get_close_status() const {
        if (get_payload_size() == 0) {
            return close::status::NO_STATUS;
        } else if (get_payload_size() >= 2) {
            char val[2] = { m_payload[0], m_payload[1] };
            uint16_t code;

            std::copy(val,val+sizeof(code),&code);
            code = ntohs(code);

            return close::status::value(code);
        } else {
            return close::status::PROTOCOL_ERROR;
        }
    }
    std::string get_close_msg() const {
        if (get_payload_size() > 2) {
            uint32_t state = utf8_validator::UTF8_ACCEPT;
            uint32_t codep = 0;
            validate_utf8(&state,&codep,2);
            if (state != utf8_validator::UTF8_ACCEPT) {
                throw processor::exception("Invalid UTF-8 Data",processor::error::PAYLOAD_VIOLATION);
            }
            return std::string(m_payload.begin()+2,m_payload.end());
        } else {
            return std::string();
        }
    }

    std::vector<unsigned char> &get_payload() {
        return m_payload;
    }

    void set_payload(const std::vector<unsigned char>& source) {
        set_payload_helper(source.size());

        std::copy(source.begin(),source.end(),m_payload.begin());
    }
    void set_payload(const std::string& source) {
        set_payload_helper(source.size());

        std::copy(source.begin(),source.end(),m_payload.begin());
    }
    void set_payload_helper(size_t s) {
        if (s > max_payload_size) {
            throw processor::exception("requested payload is over implementation defined limit",processor::error::MESSAGE_TOO_BIG);
        }

        // limits imposed by the websocket spec
        if (is_control() && s > limits::PAYLOAD_SIZE_BASIC) {
            throw processor::exception("control frames can't have large payloads",processor::error::PROTOCOL_VIOLATION);
        }

        bool masked = get_masked();

        if (s <= limits::PAYLOAD_SIZE_BASIC) {
            m_header[1] = s;
        } else if (s <= limits::PAYLOAD_SIZE_EXTENDED) {
            m_header[1] = BASIC_PAYLOAD_16BIT_CODE;

            // this reinterprets the second pair of bytes in m_header as a
            // 16 bit int and writes the payload size there as an integer
            // in network byte order
            *reinterpret_cast<uint16_t*>(&m_header[BASIC_HEADER_LENGTH]) = htons(s);
        } else if (s <= limits::PAYLOAD_SIZE_JUMBO) {
            m_header[1] = BASIC_PAYLOAD_64BIT_CODE;
            *reinterpret_cast<uint64_t*>(&m_header[BASIC_HEADER_LENGTH]) = zsutil::htonll(s);
        } else {
            throw processor::exception("payload size limit is 63 bits",processor::error::PROTOCOL_VIOLATION);
        }

        if (masked) {
            m_header[1] |= BPB1_MASK;
        }

        m_payload.resize(s);
    }

    void set_status(close::status::value status,const std::string message = "") {
        // check for valid statuses
        if (close::status::invalid(status)) {
            std::stringstream err;
            err << "Status code " << status << " is invalid";
            throw processor::exception(err.str());
        }

        if (close::status::reserved(status)) {
            std::stringstream err;
            err << "Status code " << status << " is reserved";
            throw processor::exception(err.str());
        }

        m_payload.resize(2+message.size());

        char val[2];

        *reinterpret_cast<uint16_t*>(&val[0]) = htons(status);

        bool masked = get_masked();

        m_header[1] = message.size()+2;

        if (masked) {
            m_header[1] |= BPB1_MASK;
        }

        m_payload[0] = val[0];
        m_payload[1] = val[1];

        std::copy(message.begin(),message.end(),m_payload.begin()+2);
    }

    bool is_control() const {
        return (opcode::is_control(get_opcode()));
    }

    std::string print_frame() const {
        std::stringstream f;

        unsigned int len = get_header_len();

        f << "frame: ";
        // print header
        for (unsigned int i = 0; i < len; i++) {
            f << std::hex << (unsigned short)m_header[i] << " ";
        }
        // print message
        if (m_payload.size() > 50) {
            f << "[payload of " << m_payload.size() << " bytes]";
        } else {
            std::vector<unsigned char>::const_iterator it;
            for (it = m_payload.begin(); it != m_payload.end(); it++) {
                f << *it;
            }
        }
        return f.str();
    }

    // reads basic header, sets and returns m_header_bits_needed
    void process_basic_header() {
        m_bytes_needed = get_header_len() - BASIC_HEADER_LENGTH;
    }
    void process_extended_header() {
        uint8_t s = get_basic_size();
        uint64_t payload_size;
        int mask_index = BASIC_HEADER_LENGTH;

        if (s <= limits::PAYLOAD_SIZE_BASIC) {
            payload_size = s;
        } else if (s == BASIC_PAYLOAD_16BIT_CODE) {
            // reinterpret the second two bytes as a 16 bit integer in network
            // byte order. Convert to host byte order and store locally.
            payload_size = ntohs(*(
                reinterpret_cast<uint16_t*>(&m_header[BASIC_HEADER_LENGTH])
            ));

            if (payload_size < s) {
                std::stringstream err;
                err << "payload length not minimally encoded. Using 16 bit form for payload size: " << payload_size;
                m_bytes_needed = payload_size;
                throw processor::exception(err.str(),processor::error::PROTOCOL_VIOLATION);
            }

            mask_index += 2;
        } else if (s == BASIC_PAYLOAD_64BIT_CODE) {
            // reinterpret the second eight bytes as a 64 bit integer in
            // network byte order. Convert to host byte order and store.
            payload_size = zsutil::ntohll(*(
                reinterpret_cast<uint64_t*>(&m_header[BASIC_HEADER_LENGTH])
            ));

            if (payload_size <= limits::PAYLOAD_SIZE_EXTENDED) {
                m_bytes_needed = payload_size;
                throw processor::exception("payload length not minimally encoded",
                                processor::error::PROTOCOL_VIOLATION);
            }

            mask_index += 8;
        } else {
            // TODO: shouldn't be here how to handle?
            throw processor::exception("invalid get_basic_size in process_extended_header");
        }

        if (get_masked() == 0) {
            clear_masking_key();
        } else {
            // TODO: this should be removed entirely once it is confirmed to not
            // be used by anything.
            // std::copy(m_header[mask_index],m_header[mask_index+4],m_masking_key);
            /*m_masking_key[0] = m_header[mask_index+0];
            m_masking_key[1] = m_header[mask_index+1];
            m_masking_key[2] = m_header[mask_index+2];
            m_masking_key[3] = m_header[mask_index+3];*/
        }

        if (payload_size > max_payload_size) {
            // TODO: frame/message size limits
            // TODO: find a way to throw a server error without coupling frame
            //       with server
            // throw websocketpp::server_error("got frame with payload greater than maximum frame buffer size.");
            throw "Got frame with payload greater than maximum frame buffer size.";
        }
        m_payload.resize(payload_size);
        m_bytes_needed = payload_size;
    }

    void process_payload() {
        if (get_masked()) {
            char *masking_key = get_masking_key();

            for (uint64_t i = 0; i < m_payload.size(); i++) {
                m_payload[i] = (m_payload[i] ^ masking_key[i%4]);
            }
        }
    }

    // experiment with more efficient masking code.
    void process_payload2() {
        // unmask payload one byte at a time

        //uint64_t key = (*((uint32_t*)m_masking_key;)) << 32;
        //key += *((uint32_t*)m_masking_key);

        // might need to switch byte order
        /*uint32_t key = *((uint32_t*)m_masking_key);

        // 4

        uint64_t i = 0;
        uint64_t s = (m_payload.size() / 4);

        std::cout << "s: " << s << std::endl;

        // chunks of 4
        for (i = 0; i < s; i+=4) {
            ((uint32_t*)(&m_payload[0]))[i] = (((uint32_t*)(&m_payload[0]))[i] ^ key);
        }

        // finish the last few
        for (i = s; i < m_payload.size(); i++) {
            m_payload[i] = (m_payload[i] ^ m_masking_key[i%4]);
        }*/
    }

    void validate_utf8(uint32_t* state,uint32_t* codep,size_t offset = 0) const {
        for (size_t i = offset; i < m_payload.size(); i++) {
            using utf8_validator::decode;

            if (decode(state,codep,m_payload[i]) == utf8_validator::UTF8_REJECT) {
                throw processor::exception("Invalid UTF-8 Data",processor::error::PAYLOAD_VIOLATION);
            }
        }
    }
    void validate_basic_header() const {
        // check for control frame size
        if (is_control() && get_basic_size() > limits::PAYLOAD_SIZE_BASIC) {
            throw processor::exception("Control Frame is too large",processor::error::PROTOCOL_VIOLATION);
        }

        // check for reserved bits
        if (get_rsv1() || get_rsv2() || get_rsv3()) {
            throw processor::exception("Reserved bit used",processor::error::PROTOCOL_VIOLATION);
        }

        // check for reserved opcodes
        if (opcode::reserved(get_opcode())) {
            throw processor::exception("Reserved opcode used",processor::error::PROTOCOL_VIOLATION);
        }

        // check for fragmented control message
        if (is_control() && !get_fin()) {
            throw processor::exception("Fragmented control message",processor::error::PROTOCOL_VIOLATION);
        }
    }

    void generate_masking_key() {
        *(reinterpret_cast<int32_t *>(&m_header[get_header_len()-4])) = m_rng.rand();
    }
    void clear_masking_key() {
        // this is a no-op as clearing the mask bit also changes the get_header_len
        // method to not include these byte ranges. Whenever the masking bit is re-
        // set a new key is generated anyways.
    }

private:
    static const uint8_t STATE_BASIC_HEADER = 1;
    static const uint8_t STATE_EXTENDED_HEADER = 2;
    static const uint8_t STATE_PAYLOAD = 3;
    static const uint8_t STATE_READY = 4;
    static const uint8_t STATE_RECOVERY = 5;

    uint8_t     m_state;
    uint64_t    m_bytes_needed;
    bool        m_degraded;

    char m_header[MAX_HEADER_LENGTH];
    std::vector<unsigned char> m_payload;

    rng_policy& m_rng;
};

}
}

#endif // WEBSOCKET_FRAME_HPP

max_stars_repo_name: Ziftr/rippled

max_issues_repo_name: Ziftr/rippled

max_forks_repo_name: Ziftr/rippled


text:
/**
 * \file
 * \author stvdedal@gmail.com
 *
 * \brief
 * Type declarations
 */
#ifndef GSPAN_TYPES_HPP
#define GSPAN_TYPES_HPP

#include "gspan_edgecode_tree.hpp"
#include "gspan_edgecode_compare.hpp"
#include "gspan_subgraph_tree.hpp"
#include "gspan_subgraph_lists.hpp"

#include <boost/graph/graph_traits.hpp>
#include <boost/graph/properties.hpp>
#include <boost/property_map/property_map.hpp>

#include <map>
#include <unordered_map>
#include <utility>

template <typename IG_, typename VPTag = boost::vertex_bundle_t,
          typename EPTag = boost::edge_bundle_t>
class gspan_traits {
    using vp_ig_pmap = typename boost::property_map<IG_, VPTag>::const_type;
    using ep_ig_pmap = typename boost::property_map<IG_, EPTag>::const_type;
    using vi_ig_pmap = typename
                       boost::property_map<IG_, boost::vertex_index_t>::const_type;
    using ei_ig_pmap = typename
                       boost::property_map<IG_, boost::edge_index_t>::const_type;
public:

    /// type of the Input graph
    using IG = IG_;

    /// properties
    using VI = typename boost::property_traits<vi_ig_pmap>::value_type;
    using EI = typename boost::property_traits<ei_ig_pmap>::value_type;
    using VP = typename boost::property_traits<vp_ig_pmap>::value_type;
    using EP = typename boost::property_traits<ep_ig_pmap>::value_type;

    using directed_category = typename boost::graph_traits<IG>::directed_category;

    /// type of the Mined graph
    using MG = gspan::edgecodetree< VP, EP, directed_category, VI, EI>;

    /// subgraph (SBG)
    using SBG = gspan::subgraph_tree<IG, MG>;

    /// subgraph (SBG) lists
    using SBGS = gspan::subgraph_lists<SBG>;

    /// Edge extentions
    using SG = std::unordered_map<const IG*, SBGS>;
    using RExt = std::map<MG, SG, gspan::edgecode_compare_dfs>;
    using XExt = std::map<MG, SG, gspan::edgecode_compare_lex>;
    //using MinExt = std::map<MG, std::list<SBG>, gspan::edgecode_compare_dfs>;
};

#endif

ext: hpp

max_stars_repo_name: dtchuink/DFG-Pattern-Generator

max_issues_repo_name: dtchuink/DFG-Pattern-Generator

max_forks_repo_name: dtchuink/DFG-Pattern-Generator


text:
#include <boost/swap.hpp>
#include <boost/array.hpp>
#include <iostream>

int main()
{
  char c1 = 'a';
  char c2 = 'b';

  boost::swap(c1, c2);

  std::cout << c1 << c2 << '\n';

  boost::array<int, 1> a1{{1}};
  boost::array<int, 1> a2{{2}};

  boost::swap(a1, a2);

  std::cout << a1[0] << a2[0] << '\n';
}

ext: cpp

max_stars_repo_name: KwangjoJeong/Boost

max_issues_repo_name: KwangjoJeong/Boost

max_forks_repo_name: KwangjoJeong/Boost


text:
/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */

/*
 Copyright (C) 2010 SunTrust Bank
 Copyright (C) 2010 Cavit Hafizoglu

 This file is part of QuantLib, a free-software/open-source library
 for financial quantitative analysts and developers - http://quantlib.org/

 QuantLib is free software: you can redistribute it and/or modify it
 under the terms of the QuantLib license.  You should have received a
 copy of the license along with this program; if not, please email
 <quantlib-dev@lists.sf.net>. The license is also available online at
 <http://quantlib.org/license.shtml>.

 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 license for more details.
*/

/*! \file generalizedornsteinuhlenbeckprocess.hpp
    \brief Ornstein-Uhlenbeck process with piecewise linear coefficients
*/

#ifndef quantlib_generalized_ornstein_uhlenbeck_process_hpp
#define quantlib_generalized_ornstein_uhlenbeck_process_hpp

#include <ql/stochasticprocess.hpp>
#include <boost/function.hpp>

namespace QuantLib {

    //! Piecewise linear Ornstein-Uhlenbeck process class
    /*! This class describes the Ornstein-Uhlenbeck process governed by
        \f[
            dx = a (level - x_t) dt + \sigma dW_t
        \f]

        \ingroup processes

        where the coefficients a and sigma are piecewise linear.
    */
    class GeneralizedOrnsteinUhlenbeckProcess : public StochasticProcess1D {
      public:
        GeneralizedOrnsteinUhlenbeckProcess(
              const boost::function<Real (Time)>& speed,
              const boost::function<Real (Time)>& vol,
              Real x0 = 0.0,
              Real level = 0.0);
        //! \name StochasticProcess1D interface
        //@{
        Real x0() const;

        Real drift(Time t, Real x) const;
        Real diffusion(Time t, Real x) const;

        Real expectation(Time t0, Real x0, Time dt) const;
        Real stdDeviation(Time t0, Real x0, Time dt) const;
        Real variance(Time t0, Real x0, Time dt) const;
        //@}

        Real speed(Time t) const;
        Real volatility(Time t) const;
        Real level() const;

      private:
        Real x0_, level_;
        boost::function<Real (Time)> speed_;
        boost::function<Real (Time)> volatility_;
    };

}

#endif

max_stars_repo_name: grandtiger/quantlib

max_issues_repo_name: grandtiger/quantlib

max_forks_repo_name: grandtiger/quantlib


text:
/** @file pipeline_benchmark.cpp
 *  @brief Test pipeline performance
 */

#include <armadillo>
#include <benchmark/benchmark.h>
#include <load_data.h>
#include <load_json_config.h>
#include <stp.h>

// Cmake variable
#ifndef _PIPELINE_TESTPATH
#define _PIPELINE_TESTPATH 0
#endif

std::string data_path(_PIPELINE_DATAPATH);
std::string input_npz("simdata_nstep10.npz");
std::string config_path(_PIPELINE_CONFIGPATH);
std::string config_file_exact("fastimg_exact_config.json");
std::string config_file_oversampling("fastimg_oversampling_config.json");

stp::SourceFindImage run_pipeline(arma::mat& uvw_lambda, arma::cx_mat& residual_vis, arma::mat& vis_weights, ConfigurationFile& cfg)
{
    stp::PSWF kernel_func(cfg.img_pars.kernel_support);
    std::pair<arma::Mat<real_t>, arma::Mat<real_t>> result = stp::image_visibilities(kernel_func, residual_vis, vis_weights, uvw_lambda, cfg.img_pars);
    result.second.reset();

    return stp::SourceFindImage(std::move(result.first), cfg.detection_n_sigma, cfg.analysis_n_sigma, cfg.estimate_rms,
        cfg.find_negative_sources, cfg.sigma_clip_iters, cfg.median_method, cfg.gaussian_fitting, cfg.ccl_4connectivity,
        cfg.generate_labelmap, cfg.source_min_area, cfg.ceres_diffmethod, cfg.ceres_solvertype);
}

static void pipeline_kernel_exact_benchmark(benchmark::State& state)
{
    int image_size = state.range(0);

    //Load simulated data from input_npz
    arma::mat input_uvw = load_npy_double_array<double>(data_path + input_npz, "uvw_lambda");
    arma::cx_mat input_vis = load_npy_complex_array<double>(data_path + input_npz, "vis");
    arma::mat input_snr_weights = load_npy_double_array<double>(data_path + input_npz, "snr_weights");
    arma::mat skymodel = load_npy_double_array<double>(data_path + input_npz, "skymodel");

    // Generate model visibilities from the skymodel and UVW-baselines
    arma::cx_mat input_model = stp::generate_visibilities_from_local_skymodel(skymodel, input_uvw);

    // Subtract model-generated visibilities from incoming data
    arma::cx_mat residual_vis = input_vis - input_model;

    // Load all configurations from json configuration file
    ConfigurationFile cfg(config_path + config_file_exact);
    cfg.img_pars.image_size = image_size;

    for (auto _ : state) {
        benchmark::DoNotOptimize(run_pipeline(input_uvw, residual_vis, input_snr_weights, cfg));
    }
}

static void pipeline_kernel_oversampling_benchmark(benchmark::State& state)
{
    int image_size = state.range(0);

    //Load simulated data from input_npz
    arma::mat input_uvw = load_npy_double_array<double>(data_path + input_npz, "uvw_lambda");
    arma::cx_mat input_vis = load_npy_complex_array<double>(data_path + input_npz, "vis");
    arma::mat input_snr_weights = load_npy_double_array<double>(data_path + input_npz, "snr_weights");
    arma::mat skymodel = load_npy_double_array<double>(data_path + input_npz, "skymodel");

    // Generate model visibilities from the skymodel and UVW-baselines
    arma::cx_mat input_model = stp::generate_visibilities_from_local_skymodel(skymodel, input_uvw);

    // Load all configurations from json configuration file
    ConfigurationFile cfg(config_path + config_file_oversampling);
    cfg.img_pars.image_size = image_size;

    // Subtract model-generated visibilities from incoming data
    arma::cx_mat residual_vis = input_vis - input_model;

    for (auto _ : state) {
        benchmark::DoNotOptimize(run_pipeline(input_uvw, residual_vis, input_snr_weights, cfg));
    }
}

BENCHMARK(pipeline_kernel_oversampling_benchmark)
    ->RangeMultiplier(2)
    ->Range(1 << 10, 1 << 16)
    ->Unit(benchmark::kMillisecond);

BENCHMARK(pipeline_kernel_exact_benchmark)
    ->RangeMultiplier(2)
    ->Range(1 << 10, 1 << 16)
    ->Unit(benchmark::kMillisecond);

BENCHMARK_MAIN();

max_stars_repo_name: SKA-ScienceDataProcessor/FastImaging

max_issues_repo_name: SKA-ScienceDataProcessor/FastImaging

max_forks_repo_name: SKA-ScienceDataProcessor/FastImaging


text:
#include <boost/test/unit_test.hpp>

#include <scorum/protocol/odds.hpp>

#include "defines.hpp"

#include <scorum/protocol/config.hpp>

#include <limits>

namespace odds_tests {
using namespace scorum;
using namespace scorum::protocol;

BOOST_AUTO_TEST_SUITE(odds_tests)

BOOST_AUTO_TEST_CASE(odds_positive_creation_check)
{
    auto base_fraction = utils::make_fraction(400, 300);
    odds k = base_fraction;

    BOOST_CHECK_EQUAL(k.base(), base_fraction);
    BOOST_CHECK_EQUAL(k.simplified(), utils::make_fraction(4, 3));
    BOOST_CHECK_EQUAL(k.inverted(), utils::make_fraction(4, 1));

    BOOST_CHECK_NO_THROW(odds(utils::make_fraction(std::numeric_limits<int16_t>::max(), 2)));
}

BOOST_AUTO_TEST_CASE(odds_negative_creation_check)
{
    BOOST_REQUIRE_EQUAL(sizeof(odds_value_type), sizeof(uint32_t));

    BOOST_CHECK_NO_THROW(odds(utils::make_fraction(std::numeric_limits<int32_t>::max(), 2)));
    BOOST_CHECK_THROW(odds(utils::make_fraction(std::numeric_limits<uint32_t>::max(), 2)), fc::assert_exception);
    BOOST_CHECK_THROW(odds(utils::make_fraction(std::numeric_limits<int64_t>::max(), 2)), fc::overflow_exception);

    BOOST_CHECK_THROW(odds(utils::make_fraction(-2, 1)), fc::assert_exception);
    BOOST_CHECK_THROW(odds(utils::make_fraction(2, -1)), fc::assert_exception);
    BOOST_CHECK_THROW(odds(utils::make_fraction(-2, -1)), fc::assert_exception);
    BOOST_CHECK_THROW(odds(utils::make_fraction(2, 0)), fc::assert_exception);
    BOOST_CHECK_THROW(odds(utils::make_fraction(0, 1)), fc::assert_exception);
    BOOST_CHECK_THROW(odds(utils::make_fraction(0, 0)), fc::assert_exception);

    BOOST_CHECK_NO_THROW(odds(utils::make_fraction(2, 1)));
}

BOOST_AUTO_TEST_CASE(odds_str_check)
{
    BOOST_CHECK_THROW(odds::from_string(""), fc::exception);
    BOOST_CHECK_THROW(odds::from_string("230"), fc::exception);
    BOOST_CHECK_THROW(odds::from_string("aaaaaaaaa/30"), fc::exception);
    BOOST_CHECK_THROW(odds::from_string("2147483648/1"), fc::exception);
    BOOST_CHECK_THROW(odds::from_string("30/10000000"), fc::exception);

    const std::string str = "30/2";

    odds k = odds::from_string(str);

    BOOST_CHECK_EQUAL(k.simplified(), utils::make_fraction(15, 1));

    BOOST_CHECK_EQUAL(k.to_string(), str);
}

BOOST_AUTO_TEST_CASE(odds_variant_check)
{
    odds k = utils::make_fraction(40, 30);

    fc::variant vk;

    BOOST_REQUIRE_NO_THROW(fc::to_variant(k, vk));

    odds k2;

    BOOST_REQUIRE_NO_THROW(fc::from_variant(vk, k2));

    BOOST_CHECK_EQUAL(k, k2);
}

BOOST_AUTO_TEST_CASE(odds_cast_to_fraction_check)
{
    odds k = utils::make_fraction(40, 30);

    BOOST_CHECK_EQUAL((odds_fraction_type)k, utils::make_fraction(4, 3));
}

BOOST_AUTO_TEST_CASE(odds_empty_check)
{
    odds k;

    BOOST_CHECK(!k);

    BOOST_CHECK_THROW(k.base(), fc::assert_exception);
    BOOST_CHECK_THROW(k.simplified(), fc::assert_exception);
    BOOST_CHECK_THROW(k.inverted(), fc::assert_exception);

    BOOST_CHECK_NE(k, odds(2, 1));
    BOOST_CHECK_EQUAL(k, odds());
}

BOOST_AUTO_TEST_CASE(min_odds_to_string)
{
    odds k = SCORUM_MIN_ODDS;

    BOOST_CHECK_EQUAL("1001/1000", k.to_string());
}

BOOST_AUTO_TEST_CASE(max_odds_to_string)
{
    odds k = SCORUM_MIN_ODDS.inverted();

    BOOST_CHECK_EQUAL("1001/1", k.to_string());
}

BOOST_AUTO_TEST_SUITE_END()
}

max_stars_repo_name: scorum/scorum

max_issues_repo_name: Scorum/Scorum

max_forks_repo_name: Scorum/Scorum


text:
/*
wadlib
Copyright (c) 2011 Bruno Sanches  http://code.google.com/p/wadlib

This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions:

1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/

#include <iostream>

#include <boost/filesystem.hpp>

#include "WadFile.h"
#include "WadLevel.h"

int main(int argc, char **argv)
{
	using namespace std;

	if(argc < 3)
	{
		cerr << "Insuficient parameters, usage: ogreexport <wadname> <levelname> <outputfolder>" << endl;

		return EXIT_FAILURE;
	}

	WadFile_c wad(argv[1]);
	WadLevel_c level;

	try
	{
		wad.LoadLevel(level, argv[2]);
	}
	catch(std::exception &e)
	{
		cerr << "Error: " << e.what() << endl;
		return EXIT_FAILURE;
	}

	return 0;
}

max_stars_repo_name: bcsanches/wadlib

max_issues_repo_name: bcsanches/wadlib

max_forks_repo_name: bcsanches/wadlib


text:
#pragma once
#include <list>
#include <memory>
#include <functional>

#include <boost/asio.hpp>

/**
 * It's guranteed that the tasks will be executed in queue - FIFO.
 * The next task can not start executing earlier
 * than the current's task callback is called.
 *
 * Chain stores all tasks + callbacks
 * Chain is not observed by more than one thread at once
 */
class Chain : public std::enable_shared_from_this<Chain> {
public:
    using Callback = std::function<void()>;
    using Task = std::function<void(Callback)>;

    Chain(std::shared_ptr<boost::asio::io_context> context);

    // NOTE: Here `cb` MUST NOT be async (must not invoke async work)
    Chain& Add(Callback cb);

    Chain& Add(Task task, Callback cb = {});

    void Execute();

private:

    struct Bind {
        Bind(Task task, Callback cb)
            : task { std::move(task) }
            , cb { std::move(cb) }
        {}

        Task task;
        // callback is being passed to task as parameter via std::move
        // and will be destroyed with task.
        Callback cb;
    };

    std::shared_ptr<boost::asio::io_context> context_;
    std::list<Bind> chain_;
};

max_stars_repo_name: Roout/chatterfinity

max_issues_repo_name: Roout/chatterfinity

max_forks_repo_name: Roout/chatterfinity


text:
/****************************************************************

  jjjt_operator.cpp

  Mark A. Caprio, University of Notre Dame.

****************************************************************/

#include <cassert>
#include <cmath>
#include <cstddef>
#include <cstdlib>
#include <iomanip>
#include <ostream>
#include <tuple>
#include <vector>

#include "jjjt_operator.h"

#include "am/halfint.h"
#include <Eigen/Core>
#include "basis.h"
#include "many_body.h"
#include "jjjt_scheme.h"
#include "jt_operator.h"
#include "operator.h"

namespace basis {

  ////////////////////////////////////////////////////////////////
  // two-body JJJT operator -- gather N blocks
  ////////////////////////////////////////////////////////////////

  inline
  void RecastLabelsTwoBodyJJJTToTwoBodyJJJTN(
      const TwoBodySubspaceJJJTLabels& two_body_jjjt_subspace_labels,
      const TwoBodyStateJJJTLabels& two_body_jjjt_state_labels,
      TwoBodySubspaceJJJTNLabels& two_body_jjjtn_subspace_labels,
      TwoBodyStateJJJTNLabels& two_body_jjjtn_state_labels
    )
  // Recast labels for (subspace,state) from TwoBodyJJJT scheme to
  // TwoBodyJJJTN scheme.
  //
  // This direction of conversion (from target labels to source
  // labels) is as needed for looking up the source matrix element.
  //
  // This switches N from being the most-significant state label (that
  // is, least-rapidly-varying in the lexicographic ordering scheme),
  // to being the least-significant subspace label (that is,
  // most-rapidly-varying):
  //
  //   (L,S,J,T,g) : ([N],N1,l1,N2,l2) -> (L,S,J,T,g,N) : (N1,l1,N2,l2)
  //
  // As a state label, N is actually an implicit label, not stored,
  // but effectively the first label for ordering purposes.  Its value
  // may be recovered as N1+N2.
  //
  // Arguments:
  //   two_body_jjjt_subspace_labels (...) : source subspace labels
  //   two_body_jjjt_state_labels (...) : source state labels
  //   two_body_jjjtn_subspace_labels (...,output) : target subspace labels
  //   two_body_jjjtn_state_labels (...,output) : target state labels
  {
    // extract labels
    int J, T, g;
    std::tie(J,T,g) = two_body_jjjt_subspace_labels;
    int N1, l1, N2, l2;
    HalfInt j1, j2;
    std::tie(N1,j1,N2,j2) = two_body_jjjt_state_labels;

    // repackage labels
    int N = N1+N2;
    two_body_jjjtn_subspace_labels = TwoBodySubspaceJJJTNLabels(J,T,g,N);
    two_body_jjjtn_state_labels = two_body_jjjt_state_labels;
  }

  void GatherOperatorTwoBodyJJJTNToTwoBodyJJJT(
      const basis::OperatorLabelsJT& operator_labels,
      const basis::TwoBodySpaceJJJTN& two_body_jjjtn_space,
      const std::array<basis::TwoBodySectorsJJJTN,3>& two_body_jjjtn_component_sectors,
      const std::array<basis::OperatorBlocks<double>,3>& two_body_jjjtn_component_matrices,
      const basis::TwoBodySpaceJJJT& two_body_jjjt_space,
      std::array<basis::TwoBodySectorsJJJT,3>& two_body_jjjt_component_sectors,
      std::array<basis::OperatorBlocks<double>,3>& two_body_jjjt_component_matrices
    )
  {
  for (int T0=operator_labels.T0_min; T0<=operator_labels.T0_max; ++T0)
    // for each isospin component
    {

      // enumerate sectors
      two_body_jjjt_component_sectors[T0]
        = basis::TwoBodySectorsJJJT(two_body_jjjt_space,operator_labels.J0,T0,operator_labels.g0);

      // populate matrices
      two_body_jjjt_component_matrices[T0].resize(two_body_jjjt_component_sectors[T0].size());
      for (std::size_t sector_index=0; sector_index<two_body_jjjt_component_sectors[T0].size(); ++sector_index)
        {
          // retrieve target sector
          const basis::TwoBodySectorsJJJT::SectorType& two_body_jjjt_sector
            = two_body_jjjt_component_sectors[T0].GetSector(sector_index);

          // initialize matrix
          Eigen::MatrixXd& two_body_jjjt_matrix = two_body_jjjt_component_matrices[T0][sector_index];
          two_body_jjjt_matrix = Eigen::MatrixXd::Zero(
              two_body_jjjt_sector.bra_subspace().size(),
              two_body_jjjt_sector.ket_subspace().size()
            );

          // populate matrix elements
          for (std::size_t bra_index = 0; bra_index < two_body_jjjt_sector.bra_subspace().size(); ++bra_index)
            for (std::size_t ket_index = 0; ket_index < two_body_jjjt_sector.ket_subspace().size(); ++ket_index)
              // for each target matrix element
              {

                // ensure canonical matrix element if diagonal sector
                if (two_body_jjjt_sector.IsDiagonal())
                  if (!(bra_index<=ket_index))
                    continue;

                // retrieve target states
                basis::TwoBodyStateJJJT two_body_jjjt_bra(two_body_jjjt_sector.bra_subspace(),bra_index);
                basis::TwoBodyStateJJJT two_body_jjjt_ket(two_body_jjjt_sector.ket_subspace(),ket_index);

                // extract source bra labels
                TwoBodySubspaceJJJTLabels two_body_jjjt_subspace_labels_bra
                  = two_body_jjjt_bra.subspace().labels();
                TwoBodyStateJJJTLabels two_body_jjjt_state_labels_bra
                  = two_body_jjjt_bra.labels();
                TwoBodySubspaceJJJTNLabels two_body_jjjtn_subspace_labels_bra;
                TwoBodyStateJJJTNLabels two_body_jjjtn_state_labels_bra;
                RecastLabelsTwoBodyJJJTToTwoBodyJJJTN(
                    two_body_jjjt_subspace_labels_bra,
                    two_body_jjjt_state_labels_bra,
                    two_body_jjjtn_subspace_labels_bra,
                    two_body_jjjtn_state_labels_bra
                  );

                // extract source bra indices
                std::size_t two_body_jjjtn_subspace_index_bra
                  = two_body_jjjtn_space.LookUpSubspaceIndex(
                      two_body_jjjtn_subspace_labels_bra
                    );
                std::size_t two_body_jjjtn_state_index_bra
                  = two_body_jjjtn_space.GetSubspace(two_body_jjjtn_subspace_index_bra).LookUpStateIndex(
                      two_body_jjjtn_state_labels_bra
                    );

                // extract source ket labels
                TwoBodySubspaceJJJTLabels two_body_jjjt_subspace_labels_ket
                  = two_body_jjjt_ket.subspace().labels();
                TwoBodyStateJJJTLabels two_body_jjjt_state_labels_ket
                  = two_body_jjjt_ket.labels();
                TwoBodySubspaceJJJTNLabels two_body_jjjtn_subspace_labels_ket;
                TwoBodyStateJJJTNLabels two_body_jjjtn_state_labels_ket;
                RecastLabelsTwoBodyJJJTToTwoBodyJJJTN(
                    two_body_jjjt_subspace_labels_ket,
                    two_body_jjjt_state_labels_ket,
                    two_body_jjjtn_subspace_labels_ket,
                    two_body_jjjtn_state_labels_ket
                  );

                // extract source ket indices
                std::size_t two_body_jjjtn_subspace_index_ket
                  = two_body_jjjtn_space.LookUpSubspaceIndex(
                      two_body_jjjtn_subspace_labels_ket
                    );
                std::size_t two_body_jjjtn_state_index_ket
                  = two_body_jjjtn_space.GetSubspace(two_body_jjjtn_subspace_index_ket).LookUpStateIndex(
                      two_body_jjjtn_state_labels_ket
                    );

                // look up matrix element
                std::size_t two_body_jjjtn_sector_index
                  = two_body_jjjtn_component_sectors[T0].LookUpSectorIndex(
                      two_body_jjjtn_subspace_index_bra,
                      two_body_jjjtn_subspace_index_ket
                    );

                const Eigen::MatrixXd& two_body_jjjtn_matrix
                  = two_body_jjjtn_component_matrices[T0][two_body_jjjtn_sector_index];
                double two_body_jjjtn_matrix_element = two_body_jjjtn_matrix(
                    two_body_jjjtn_state_index_bra,two_body_jjjtn_state_index_ket
                  );

                two_body_jjjt_matrix(bra_index,ket_index) = two_body_jjjtn_matrix_element;

              }
        }
    }

  }

  ////////////////////////////////////////////////////////////////
  // two-body JJJT operator output
  ////////////////////////////////////////////////////////////////

  void WriteTwoBodyOperatorComponentJJJT(
      std::ostream& os,
      int T0,
      const TwoBodySectorsJJJT& sectors,
      const OperatorBlocks<double>& matrices,
      basis::NormalizationConversion conversion_mode
    )
  {

    // iterate over sectors
    for (std::size_t sector_index = 0; sector_index < sectors.size(); ++sector_index)
      {

        // extract sector
        const typename TwoBodySectorsJJJT::SectorType& sector = sectors.GetSector(sector_index);
        const typename TwoBodySectorsJJJT::SubspaceType& bra_subspace = sector.bra_subspace();
        const typename TwoBodySectorsJJJT::SubspaceType& ket_subspace = sector.ket_subspace();

        // verify that sector is canonical
        //
        // This is a check that the caller's sector construction
        // followed the specification that only "upper triangle"
        // sectors are stored.
        assert(sector.bra_subspace_index()<=sector.ket_subspace_index());

        // iterate over matrix elements
        for (std::size_t bra_index=0; bra_index<bra_subspace.size(); ++bra_index)
          for (std::size_t ket_index=0; ket_index<ket_subspace.size(); ++ket_index)
            {

              // diagonal sector: restrict to upper triangle
              if (sector.IsDiagonal())
                if (!(bra_index<=ket_index))
                  continue;

              // define states
              const basis::TwoBodyStateJJJT bra(bra_subspace,bra_index);
              const basis::TwoBodyStateJJJT ket(ket_subspace,ket_index);

              // determine matrix element normalization factor
              double conversion_factor = 1.;
              if (conversion_mode == basis::NormalizationConversion::kASToNAS)
                {
                  if ((bra.N1()==bra.N2())&&(bra.l1()==bra.l2())&&(bra.j1()==bra.j2()))
                    conversion_factor *= (1/sqrt(2.));
                  if ((ket.N1()==ket.N2())&&(ket.l1()==ket.l2())&&(ket.j1()==ket.j2()))
                    conversion_factor *= (1/sqrt(2.));
                }
              else if (conversion_mode == basis::NormalizationConversion::kNASToAS)
                {
                  if ((bra.N1()==bra.N2())&&(bra.l1()==bra.l2())&&(bra.j1()==bra.j2()))
                    conversion_factor *= sqrt(2.);
                  if ((ket.N1()==ket.N2())&&(ket.l1()==ket.l2())&&(ket.j1()==ket.j2()))
                    conversion_factor *= sqrt(2.);
                }

              // extract matrix element
              const double matrix_element = conversion_factor*matrices[sector_index](bra_index,ket_index);

              // generate output line
              const int width = 3;
              const int precision = 8;  // for approximately single precision output
              os << std::setprecision(precision);
              os
                << " " << std::setw(width) << T0
                << " " << "  "
                << " " << std::setw(width) << bra.N1()
                << " " << std::setw(width) << bra.l1()
                << " " << std::showpoint << std::fixed << std::setprecision(1) << std::setw(4) << float(bra.j1())
                << " " << std::setw(width) << bra.N2()
                << " " << std::setw(width) << bra.l2()
                << " " << std::showpoint << std::fixed << std::setprecision(1) << std::setw(4) << float(bra.j2())
                << " " << std::setw(width) << bra.J()
                << " " << std::setw(width) << bra.T()
                << " " << std::setw(width) << bra.g()
                << " " << "    "
                << " " << std::setw(width) << ket.N1()
                << " " << std::setw(width) << ket.l1()
                << " " << std::showpoint << std::fixed << std::setprecision(1) << std::setw(4) << float(ket.j1())
                << " " << std::setw(width) << ket.N2()
                << " " << std::setw(width) << ket.l2()
                << " " << std::showpoint << std::fixed << std::setprecision(1) << std::setw(4) << float(ket.j2())
                << " " << std::setw(width) << ket.J()
                << " " << std::setw(width) << ket.T()
                << " " << std::setw(width) << ket.g()
                << " " << "    "
                << " " << std::showpoint << std::scientific << std::setprecision(precision) << matrix_element
                << std::endl;

            }

      }
  }

  ////////////////////////////////////////////////////////////////
  ////////////////////////////////////////////////////////////////
} // namespace

max_stars_repo_name: nd-nuclear-theory/basis

max_issues_repo_name: nd-nuclear-theory/basis

max_forks_repo_name: nd-nuclear-theory/basis


text:
/* This file is part of the dynarmic project.
 * Copyright (c) 2016 MerryMage
 * SPDX-License-Identifier: 0BSD
 */

#include <functional>
#include <memory>

#include <boost/icl/interval_set.hpp>
#include <fmt/format.h>

#include <dynarmic/A32/a32.h>
#include <dynarmic/A32/context.h>

#include "backend/x64/a32_emit_x64.h"
#include "backend/x64/a32_jitstate.h"
#include "backend/x64/block_of_code.h"
#include "backend/x64/callback.h"
#include "backend/x64/devirtualize.h"
#include "backend/x64/jitstate_info.h"
#include "common/assert.h"
#include "common/cast_util.h"
#include "common/common_types.h"
#include "common/llvm_disassemble.h"
#include "common/scope_exit.h"
#include "frontend/A32/translate/translate.h"
#include "frontend/ir/basic_block.h"
#include "frontend/ir/location_descriptor.h"
#include "ir_opt/passes.h"

namespace Dynarmic::A32 {

using namespace Backend::X64;

static RunCodeCallbacks GenRunCodeCallbacks(A32::UserCallbacks* cb, CodePtr (*LookupBlock)(void* lookup_block_arg), void* arg) {
    return RunCodeCallbacks{
        std::make_unique<ArgCallback>(LookupBlock, reinterpret_cast<u64>(arg)),
        std::make_unique<ArgCallback>(Devirtualize<&A32::UserCallbacks::AddTicks>(cb)),
        std::make_unique<ArgCallback>(Devirtualize<&A32::UserCallbacks::GetTicksRemaining>(cb)),
    };
}

static std::function<void(BlockOfCode&)> GenRCP(const A32::UserConfig& conf) {
    return [conf](BlockOfCode& code) {
        if (conf.page_table) {
            code.mov(code.r14, Common::BitCast<u64>(conf.page_table));
        }
        if (conf.fastmem_pointer) {
            code.mov(code.r13, Common::BitCast<u64>(conf.fastmem_pointer));
        }
    };
}

struct Jit::Impl {
    Impl(Jit* jit, A32::UserConfig conf)
            : block_of_code(GenRunCodeCallbacks(conf.callbacks, &GetCurrentBlockThunk, this), JitStateInfo{jit_state}, GenRCP(conf))
            , emitter(block_of_code, conf, jit)
            , conf(std::move(conf))
            , jit_interface(jit)
    {}

    A32JitState jit_state;
    BlockOfCode block_of_code;
    A32EmitX64 emitter;

    A32::UserConfig conf;

    // Requests made during execution to invalidate the cache are queued up here.
    size_t invalid_cache_generation = 0;
    boost::icl::interval_set<u32> invalid_cache_ranges;
    bool invalidate_entire_cache = false;

    void Execute() {
        const CodePtr current_codeptr = [this]{
            // RSB optimization
            const u32 new_rsb_ptr = (jit_state.rsb_ptr - 1) & A32JitState::RSBPtrMask;
            if (jit_state.GetUniqueHash() == jit_state.rsb_location_descriptors[new_rsb_ptr]) {
                jit_state.rsb_ptr = new_rsb_ptr;
                return reinterpret_cast<CodePtr>(jit_state.rsb_codeptrs[new_rsb_ptr]);
            }

            return GetCurrentBlock();
        }();

        block_of_code.RunCode(&jit_state, current_codeptr);
    }

    void Step() {
        block_of_code.StepCode(&jit_state, GetCurrentSingleStep());
    }

    void ExceptionalExit() {
        if (!conf.wall_clock_cntpct) {
            const s64 ticks = jit_state.cycles_to_run - jit_state.cycles_remaining;
            conf.callbacks->AddTicks(ticks);
        }
        PerformCacheInvalidation();
    }

    void ChangeProcessorID(size_t value) {
        conf.processor_id = value;
        emitter.ChangeProcessorID(value);
    }

    void ClearExclusiveState() {
        jit_state.exclusive_state = 0;
    }

    std::string Disassemble(const IR::LocationDescriptor& descriptor) {
        auto block = GetBasicBlock(descriptor);
        std::string result = fmt::format("address: {}\nsize: {} bytes\n", block.entrypoint, block.size);
        result += Common::DisassembleX64(block.entrypoint, reinterpret_cast<const char*>(block.entrypoint) + block.size);
        return result;
    }

    void PerformCacheInvalidation() {
        if (invalidate_entire_cache) {
            jit_state.ResetRSB();
            block_of_code.ClearCache();
            emitter.ClearCache();

            invalid_cache_ranges.clear();
            invalidate_entire_cache = false;
            invalid_cache_generation++;
            return;
        }

        if (invalid_cache_ranges.empty()) {
            return;
        }

        jit_state.ResetRSB();
        emitter.InvalidateCacheRanges(invalid_cache_ranges);
        invalid_cache_ranges.clear();
        invalid_cache_generation++;
    }

    void RequestCacheInvalidation() {
        if (jit_interface->is_executing) {
            jit_state.halt_requested = true;
            return;
        }

        PerformCacheInvalidation();
    }

private:
    Jit* jit_interface;

    static CodePtr GetCurrentBlockThunk(void* this_voidptr) {
        Jit::Impl& this_ = *static_cast<Jit::Impl*>(this_voidptr);
        return this_.GetCurrentBlock();
    }

    IR::LocationDescriptor GetCurrentLocation() const {
        return IR::LocationDescriptor{jit_state.GetUniqueHash()};
    }

    CodePtr GetCurrentBlock() {
        return GetBasicBlock(GetCurrentLocation()).entrypoint;
    }

    CodePtr GetCurrentSingleStep() {
        return GetBasicBlock(A32::LocationDescriptor{GetCurrentLocation()}.SetSingleStepping(true)).entrypoint;
    }

    A32EmitX64::BlockDescriptor GetBasicBlock(IR::LocationDescriptor descriptor) {
        auto block = emitter.GetBasicBlock(descriptor);
        if (block)
            return *block;

        constexpr size_t MINIMUM_REMAINING_CODESIZE = 1 * 1024 * 1024;
        if (block_of_code.SpaceRemaining() < MINIMUM_REMAINING_CODESIZE) {
            invalidate_entire_cache = true;
            PerformCacheInvalidation();
        }

        IR::Block ir_block = A32::Translate(A32::LocationDescriptor{descriptor}, [this](u32 vaddr) { return conf.callbacks->MemoryReadCode(vaddr); }, {conf.define_unpredictable_behaviour, conf.hook_hint_instructions});
        if (conf.HasOptimization(OptimizationFlag::GetSetElimination)) {
            Optimization::A32GetSetElimination(ir_block);
            Optimization::DeadCodeElimination(ir_block);
        }
        if (conf.HasOptimization(OptimizationFlag::ConstProp)) {
            Optimization::A32ConstantMemoryReads(ir_block, conf.callbacks);
            Optimization::ConstantPropagation(ir_block);
            Optimization::DeadCodeElimination(ir_block);
        }
        Optimization::VerificationPass(ir_block);
        return emitter.Emit(ir_block);
    }
};

Jit::Jit(UserConfig conf) : impl(std::make_unique<Impl>(this, std::move(conf))) {}

Jit::~Jit() = default;

void Jit::Run() {
    ASSERT(!is_executing);
    is_executing = true;
    SCOPE_EXIT { this->is_executing = false; };

    impl->jit_state.halt_requested = false;

    impl->Execute();

    impl->PerformCacheInvalidation();
}

void Jit::Step() {
    ASSERT(!is_executing);
    is_executing = true;
    SCOPE_EXIT { this->is_executing = false; };

    impl->jit_state.halt_requested = true;

    impl->Step();

    impl->PerformCacheInvalidation();
}

void Jit::ClearCache() {
    impl->invalidate_entire_cache = true;
    impl->RequestCacheInvalidation();
}

void Jit::InvalidateCacheRange(std::uint32_t start_address, std::size_t length) {
    impl->invalid_cache_ranges.add(boost::icl::discrete_interval<u32>::closed(start_address, static_cast<u32>(start_address + length - 1)));
    impl->RequestCacheInvalidation();
}

void Jit::Reset() {
    ASSERT(!is_executing);
    impl->jit_state = {};
}

void Jit::HaltExecution() {
    impl->jit_state.halt_requested = true;
}

void Jit::ExceptionalExit() {
    impl->ExceptionalExit();
    is_executing = false;
}

void Jit::ClearExclusiveState() {
    impl->ClearExclusiveState();
}

void Jit::ChangeProcessorID(size_t new_processor) {
    impl->ChangeProcessorID(new_processor);
}

std::array<u32, 16>& Jit::Regs() {
    return impl->jit_state.Reg;
}
const std::array<u32, 16>& Jit::Regs() const {
    return impl->jit_state.Reg;
}

std::array<u32, 64>& Jit::ExtRegs() {
    return impl->jit_state.ExtReg;
}

const std::array<u32, 64>& Jit::ExtRegs() const {
    return impl->jit_state.ExtReg;
}

u32 Jit::Cpsr() const {
    return impl->jit_state.Cpsr();
}

void Jit::SetCpsr(u32 value) {
    return impl->jit_state.SetCpsr(value);
}

u32 Jit::Fpscr() const {
    return impl->jit_state.Fpscr();
}

void Jit::SetFpscr(u32 value) {
    return impl->jit_state.SetFpscr(value);
}

std::uint8_t Jit::Asid() const {
    return impl->jit_state.Asid();
}

void Jit::SetAsid(std::uint8_t value) {
    impl->jit_state.SetAsid(value);
}

std::uint8_t Jit::MaxAsidAvailable() const {
    return impl->jit_state.MaxAsidAvailable();
}

Context Jit::SaveContext() const {
    Context ctx;
    SaveContext(ctx);
    return ctx;
}

struct Context::Impl {
    A32JitState jit_state;
    size_t invalid_cache_generation;
};

Context::Context() : impl(std::make_unique<Context::Impl>()) { impl->jit_state.ResetRSB(); }
Context::~Context() = default;
Context::Context(const Context& ctx) : impl(std::make_unique<Context::Impl>(*ctx.impl)) {}
Context::Context(Context&& ctx) noexcept : impl(std::move(ctx.impl)) {}
Context& Context::operator=(const Context& ctx) {
    *impl = *ctx.impl;
    return *this;
}
Context& Context::operator=(Context&& ctx) noexcept {
    impl = std::move(ctx.impl);
    return *this;
}

std::array<std::uint32_t, 16>& Context::Regs() {
    return impl->jit_state.Reg;
}
const std::array<std::uint32_t, 16>& Context::Regs() const {
    return impl->jit_state.Reg;
}
std::array<std::uint32_t, 64>& Context::ExtRegs() {
    return impl->jit_state.ExtReg;
}
const std::array<std::uint32_t, 64>& Context::ExtRegs() const {
    return impl->jit_state.ExtReg;
}

std::uint32_t Context::Cpsr() const {
    return impl->jit_state.Cpsr();
}
void Context::SetCpsr(std::uint32_t value) {
    impl->jit_state.SetCpsr(value);
}

std::uint32_t Context::Fpscr() const {
    return impl->jit_state.Fpscr();
}
void Context::SetFpscr(std::uint32_t value) {
    return impl->jit_state.SetFpscr(value);
}

void Jit::SaveContext(Context& ctx) const {
    ctx.impl->jit_state.TransferJitState(impl->jit_state, false);
    ctx.impl->invalid_cache_generation = impl->invalid_cache_generation;
}

void Jit::LoadContext(const Context& ctx) {
    bool reset_rsb = ctx.impl->invalid_cache_generation != impl->invalid_cache_generation;
    impl->jit_state.TransferJitState(ctx.impl->jit_state, reset_rsb);
}

std::string Jit::Disassemble() const {
    return Common::DisassembleX64(impl->block_of_code.GetCodeBegin(), impl->block_of_code.getCurr());
}

} // namespace Dynarmic::A32


text:
/*ckwg +29
 * Copyright 2014-2015 by Kitware, Inc.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 *  * Redistributions of source code must retain the above copyright notice,
 *    this list of conditions and the following disclaimer.
 *
 *  * Redistributions in binary form must reproduce the above copyright notice,
 *    this list of conditions and the following disclaimer in the documentation
 *    and/or other materials provided with the distribution.
 *
 *  * Neither name of Kitware, Inc. nor the names of any 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 AUTHORS 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.
 */

/**
 * \file
 * \brief Implementation of \link maptk::similarity_ similarity_<T> \endlink
 *        for \c T = { \c float, \c double }
 */

#include "similarity.h"
#include "eigen_io.h"
#include <cmath>
#include <Eigen/LU>

namespace maptk
{

/// Constructor - from a matrix
template <typename T>
similarity_<T>
::similarity_(const Eigen::Matrix<T,4,4>& M)
{
  if (M(3,0) != T(0) || M(3,1) != T(0) || M(3,2) != T(0) || M(3,3) != T(1))
  {
    // not a similarity if bottom row is not [0,0,0,1]
    // TODO throw an exception here
    std::cerr << "third row of similarity matrix must be [0,0,0,1]"<<std::endl;
    return;
  }
  Eigen::Matrix<T,3,3> sr = M.template block<3,3>(0,0);
  this->scale_ = sr.determinant();
  if (this->scale_ <= T(0))
  {
    // similarity must have positive scale
    // TODO throw an exception
    std::cerr << "determinant in upper 3x3 of similarity matrix must be positive"<<std::endl;
    return;
  }
  // take the cube root
  this->scale_ = std::pow(this->scale_, static_cast<T>(1/3.0));
  // factor scale out of sr
  sr /= this->scale_;
  this->rot_ = rotation_<T>(sr);
  assert((Eigen::Matrix<T,3,3>(this->rot_)-sr).norm() < 1e-4);
  this->trans_ = M.template block<3,1>(0,3);
}

/// Convert to a 4x4 matrix
template <typename T>
similarity_<T>
::operator Eigen::Matrix<T,4,4>() const
{
  Eigen::Matrix<T,4,4> mat = Eigen::Matrix<T,4,4>::Zero();
  mat(3,3) = 1;
  mat.template block<3,3>(0,0) = this->scale_ * Eigen::Matrix<T,3,3>(this->rot_);
  mat.template block<3,1>(0,3) = this->trans_;
  return mat;
}

/// Compose two transforms
template <typename T>
similarity_<T>
similarity_<T>
::operator*(const similarity_<T>& rhs) const
{
  return similarity_<T>(this->scale_ * rhs.scale_,
                        this->rot_ * rhs.rot_,
                        *this * rhs.trans_);
}

/// Transform a vector
template <typename T>
Eigen::Matrix<T,3,1>
similarity_<T>
::operator*(const Eigen::Matrix<T,3,1>& rhs) const
{
  return this->scale_ * (this->rot_ * rhs) + this->trans_;
}

/// output stream operator for a similarity transformation
template <typename T>
std::ostream&  operator<<(std::ostream& s, const similarity_<T>& t)
{
  s << t.scale() << ' ' << t.rotation() << ' ' << t.translation();
  return s;
}

/// input stream operator for a similarity transformation
template <typename T>
std::istream&  operator>>(std::istream& s, similarity_<T>& t)
{
  T sc;
  rotation_<T> ro;
  Eigen::Matrix<T,3,1> tr;
  s >> sc >> ro >> tr;
  t = similarity_<T>(sc, ro, tr);
  return s;
}

/// \cond DoxygenSuppress
#define INSTANTIATE_SIMILARITY(T) \
template class MAPTK_LIB_EXPORT similarity_<T>; \
template MAPTK_LIB_EXPORT std::ostream&  operator<<(std::ostream& s, const similarity_<T>& t); \
template MAPTK_LIB_EXPORT std::istream&  operator>>(std::istream& s, similarity_<T>& t)

INSTANTIATE_SIMILARITY(double);
INSTANTIATE_SIMILARITY(float);

#undef INSTANTIATE_SIMILARITY
/// \endcond

} // end namespace maptk

ext: cxx

max_stars_repo_name: efernandez/maptk

max_issues_repo_name: efernandez/maptk

max_forks_repo_name: efernandez/maptk


text:
/*
 * output.cpp
 *
 *  Created on: 11 feb. 2020
 *      Author: scholz
 */

#include<iostream>
#include<vector>
#include <string>
#include <boost/filesystem.hpp>
#include "output.h"

using namespace std;
namespace fs = boost::filesystem;
//deals with output and writes files.

std::vector<std::string> readNm(std::string res)
{
	//gets list of names from a result file
	std::vector<std::string> read(0);
	ifstream data(res);
	if(data)
	{
		std::string line="";
		while(getline(data,line))
		{
			if(line[0] =='>')
			{
				read.push_back(line);
			}
		}
		data.close();
	}
	else
	{
		cout << "No file found at " << res << endl;
	}
	return read;
}

void createDirectory(const std::string& filename)
{
    if (!fs::is_directory(filename) || !fs::exists(filename)) {
        fs::create_directory(filename);
    }
}

void checkFileExists(const std::string& filename)
{
    if (!fs::exists(filename))
    {
        throw std::runtime_error("ERROR! No such file: " + filename);
    }
}

std::string getFileName(const std::string& filename)
{
    boost::filesystem::path path(filename);
	return path.stem().string();
}

void printHead(std::string qfile, char dbtype, double theta, int ws, int cflag, int kflag, std::ofstream* writef)
{
	//prints header of a output file, comtaining informations on the parameters used.
	(*writef) << "# SHERPAS output for queries \"" << qfile << "\"" << endl;
	(*writef) << "#" << endl;
	(*writef) << "# method: " << dbtype << "; threshold: " << theta << "; window: " << ws << endl;
	if(cflag==1)
	{
		(*writef) << "#" << endl << "# circular genome" << endl;
	}
	if(kflag==1)
	{
		(*writef) << "#" << endl << "# no post-treatment of N/A-segments" << endl;
	}
	(*writef) << "#" << endl << endl;
}

std::vector<std::string> printChange(std::vector<std::vector<Arc*>> result, int shift, std::vector<std::string> ref, double thr, std::vector<double> rat, char m)
{
	//from a list of result vectors, the segments with breakpoints and values between (does not print anything, despite the name).
	std::vector<std::string> res(0);
	int s=result.size();
	int rs=ref.size();
	int aref=rs;
	res.push_back("0");
	ref.push_back("N/A");
	for(int i=0; i<s; i++)
	{
		if((ref[(*result[i][0]).getPlace()] != ref[(*result[i][1]).getPlace()] || m=='R') && (i==0 || aref<rs) && rat[i]<thr)
		{
			if(i>0)
			{
				res.push_back(to_string(i+shift));
			}
			aref=rs;
			res.push_back("N/A");
		}
		else if((ref[(*result[i][0]).getPlace()] != ref[aref]) && ((ref[(*result[i][0]).getPlace()] == ref[(*result[i][1]).getPlace()] && m=='F') || rat[i]>=thr))
		{
			if(i>0)
			{
				res.push_back(to_string(i+shift));
			}
			aref=((*result[i][0]).getPlace());
			if(isTop(ref[aref]))
			{
				res.push_back("N/A");
			}
			else
			{
				res.push_back(ref[aref]);
			}
		}
		delete result[i][0];
		delete result[i][1];
	}
	res.push_back(to_string(s+2*shift));
	return res;
}

void mergeNA(std::vector<std::string> read, int circ, int lin, int keep, std::ofstream* write)
{
	//Remove "N/A" section when both adjacent sections are the same.
	int l=0;
	if(keep==0)
	{
		l=3;
		while(l<(read).size()-2)
		{
			if(read[l]=="N/A" && read[l-2]==read[l+2])
			{
				for(int rec=0; rec<4; rec++)
				{
					(read).erase((read).begin()+l-1);
				}
			}
			else if(read[l]=="N/A" && read[l+2]=="N/A")
			{
				for(int rec=0; rec<2; rec++)
				{
					(read).erase((read).begin()+l);
				}
			}
			else
			{
				l+=2;
			}
		}
			if(circ==1)
		{
			if(read[1]=="N/A" && read[(read).size()-2]=="N/A" && read[3]==read[(read).size()-4])
			{
				(read).erase((read).end()-2);
				(read).erase((read).end()-2);
				(read).erase((read).begin()+1);
				(read).erase((read).begin()+1);
			}
		}
	}
	if(lin==1)
	{
		for(int j=0; j<(read).size()-1; j++)
		{
			(*write) << read[j] << ",";
		}
		(*write) << (read).back() << endl;
	}
	else
	{
		(*write) << "1\t";
		for(int j=1; j<(read).size()-2; j+=2)
		{
			(*write) << stoi(read[j+1])-1 << "\t";
			(*write) << read[j] << endl << read[j+1] << "\t";
		}
		(*write) << (read).back()  << "\t" << read[(read).size()-2] << endl << endl;
	}
}


text:
/***************************************************************************
 *   Software License Agreement (BSD License)                              *
 *   Copyright (C) 2014 by Markus Bader <markus.bader@tuwien.ac.at>        *
 *                                                                         *
 *   Redistribution and use in source and binary forms, with or without    *
 *   modification, are permitted provided that the following conditions    *
 *   are met:                                                              *
 *                                                                         *
 *   1. Redistributions of source code must retain the above copyright     *
 *      notice, this list of conditions and the following disclaimer.      *
 *   2. 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.                                                      *
 *   3. Neither the name of the copyright holder 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.                                           *
 ***************************************************************************/

#include "ros/ros.h"
#include <tf/transform_listener.h>
#include <boost/thread.hpp>
#include <shmfw/objects/pose.h>
#include <shmfw/objects/transform2d.h>
#include <shmfw/variable.h>

class Ros2ShmFwTf {
public:
    Ros2ShmFwTf ();
private:
    ros::NodeHandle n_;
    ros::NodeHandle n_param_;
    double frequency_;
    double timeout_signal_;  ///onyl used if frequency_ < 0
    std::string shm_segment_name_;
    int shm_segment_size_;
    std::string target_frame_;
    std::string target_frame_id_;
    std::string source_frame_;
    std::string source_frame_id_;
    std::string tf_prefix_;
    std::string shm_name_pose_;
    std::string shm_name_pose2d_;
    ShmFw::Var<ShmFw::Pose> shm_pose_;
    ShmFw::Var<ShmFw::Pose2D> shm_pose2d_;
    ShmFw::Transform2D tf_offset_;

    tf::TransformListener listener_;
private:
    void loop();
    void read_parameter();
};

int main ( int argc, char **argv ) {
    ros::init ( argc, argv, "shmfw_twist" );
    Ros2ShmFwTf node;
    return 0;
}

Ros2ShmFwTf::Ros2ShmFwTf ()
    : n_ ()
    , n_param_ ( "~" )
    , frequency_ ( 10.0 )
    , shm_segment_name_ ( ShmFw::DEFAULT_SEGMENT_NAME() )
    , shm_segment_size_ ( ShmFw::DEFAULT_SEGMENT_SIZE() )
    , target_frame_ ( "map" )
    , source_frame_ ( "base_link" )
    , tf_prefix_ ()
    , shm_name_pose_ ( "pose3d" )
    , shm_name_pose2d_ ( "pose" )  {

    read_parameter();
    loop();
}

void Ros2ShmFwTf::read_parameter() {
    std::stringstream ss;
    ROS_INFO ( "namespace: %s", n_param_.getNamespace().c_str() );

    n_param_.getParam ( "frequency", frequency_ );
    ROS_INFO ( "frequency: %5.2f", frequency_ );

    n_param_.getParam ( "shm_segment_name", shm_segment_name_ );
    ROS_INFO ( "shm_segment_name: %s", shm_segment_name_.c_str() );

    n_param_.getParam ( "shm_segment_size", shm_segment_size_ );
    ROS_INFO ( "shm_segment_size: %d", shm_segment_size_ );

    n_param_.getParam ( "target_frame", target_frame_ );
    ROS_INFO ( "%s/target_frame: %s", n_param_.getNamespace().c_str(), target_frame_.c_str() );

    n_param_.getParam ( "source_frame", source_frame_ );
    ROS_INFO ( "%s/source_frame: %s", n_param_.getNamespace().c_str(), source_frame_.c_str() );

    n_param_.getParam ( "tf_prefix", tf_prefix_ );
    ROS_INFO ( "%s/tf_prefix: %s", n_param_.getNamespace().c_str(), tf_prefix_.c_str() );

    std::string str_tf("[[ 0.0, 0.0],[ 0.0]]");
    n_param_.getParam ( "offset",  str_tf);
    ROS_INFO ( "%s/offset: %s", n_param_.getNamespace().c_str(), str_tf.c_str() );
    tf_offset_.setFromString(str_tf);

    ShmFw::HandlerPtr shmHdl = ShmFw::Handler::create ( shm_segment_name_, shm_segment_size_, n_.getNamespace() );

    n_param_.getParam ( "shm_name_pose", shm_name_pose_ );
    ROS_INFO ( "%s/shm_name_pose: %s", n_param_.getNamespace().c_str(), shmHdl->resolve_namespace ( shm_name_pose_ ).c_str() );

    target_frame_id_ = tf::resolve ( tf_prefix_, target_frame_ );
    source_frame_id_ = tf::resolve ( tf_prefix_, source_frame_ );
    ROS_INFO ( "Waiting for TF %s -> %s",  target_frame_id_.c_str() ,  source_frame_id_.c_str() );

    shm_pose_.construct ( shm_name_pose_, shmHdl );
    shm_pose_.info_text ( "Pose computed form TF " + target_frame_id_ + " -> " + source_frame_id_ + " frame" );

    n_param_.getParam ( "shm_name_pose2d", shm_name_pose2d_ );
    ROS_INFO ( "%s/shm_name_pose2d: %s", n_param_.getNamespace().c_str(), shmHdl->resolve_namespace ( shm_name_pose2d_ ).c_str() );

    shm_pose2d_.construct ( shm_name_pose2d_, shmHdl );
    shm_pose2d_.info_text ( "Pose computed form TF " + target_frame_id_ + " -> " + source_frame_id_ + " frame" );
}

void Ros2ShmFwTf::loop() {

    ShmFw::Pose pose;
    ShmFw::Pose2D pose2d;
    ros::Rate rate ( frequency_ );
    while ( ros::ok() ) {
        tf::StampedTransform transform;
        tfScalar yaw, pitch, roll;
        try {
            listener_.lookupTransform ( target_frame_id_, source_frame_id_, ros::Time ( 0 ), transform );
            tf::Quaternion q = transform.getRotation();
            tf::Vector3 t = transform.getOrigin();
            pose.orientation.x = q.x();
            pose.orientation.y = q.y();
            pose.orientation.z = q.z();
            pose.orientation.w = q.w();
            pose.position.x = t.x();
            pose.position.y = t.y();
            pose.position.z = t.z();
            shm_pose_.set ( pose );

            pose.getPose2D ( pose2d );
	    pose2d = tf_offset_ * pose2d;
            shm_pose2d_.set ( pose2d );
        } catch ( tf::TransformException ex ) {
            //ROS_ERROR ( "%s",ex.what() );
            ros::Duration ( 1.0 ).sleep();
        }
        ros::spinOnce();
        rate.sleep();
    }
}


text: #include <boost/units/base_units/metric/micron.hpp>

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


text:
/***************************************************************************
   Copyright 2015 Ufora Inc.

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
****************************************************************************/
#include "ChecksummedFile.hpp"

#include <cstdio>
#include <string>
#include <vector>
#include <stdexcept>

#include <boost/crc.hpp>
#include <boost/enable_shared_from_this.hpp>
#include <boost/lexical_cast.hpp>

#include "../Common.hpp"

#include "../KeyState.hppml"
#include "../../../core/math/Nullable.hpp"

using namespace std;

namespace ChecksummedFile {
    namespace detail {

        void onWriteError(const std::string& path)
            {
            if (errno == ENOSPC)
                {
                LOG_CRITICAL << "No Space Left on Disk!";
                throw Ufora::OsError("No space left on SharedState storage device!", int(errno));
                }
            lassert_dump(false, "ChecksummedFile failed to write to " + path)
            }

        uint64_t fileSize(FILE* inFile)
            {
            uint64_t curPos = ftell(inFile);
            fseek(inFile, 0L, SEEK_END);
            uint64_t tr = ftell(inFile);
            fseek(inFile, curPos, SEEK_SET);
            return tr;
            }

        FILE* openFile(const string& fileName, const FileMode::ModeType& mode)
            {
            FILE* tr = fopen(fileName.c_str(), (mode == FileMode::READ ? "r" : "a+"));
            if (tr == nullptr)
                {
                perror("");
                throw std::logic_error("error opening file: " + fileName);
                }
            return tr;
            }
    }

ChecksummedWriter::ChecksummedWriter(string path) :
    mFile(NULL),
    mPath(path),
    mDataError(false),
    mIsDirty(false)
    {
    LOG_INFO << "Checksummed writer opening file " << mPath;

    mFile = detail::openFile(path, FileMode::APPEND);
    }

ChecksummedWriter::~ChecksummedWriter()
    {
    if(mFile != nullptr)
        {
        LOG_INFO << "Checksummed writer closing file " << mPath;
        flush();
        fclose(mFile);
        }
    }

string ChecksummedWriter::path() const
    {
    return mPath;
    }

void ChecksummedWriter::flush()
    {
    // for external flushing
    if (fflush(mFile) != 0) {
        LOG_ERROR << "Checksummed writer failed to flush file. Error:" << ferror(mFile);
        }
    mIsDirty = false;
    }

size_t ChecksummedWriter::written() const
    {
    // return number of bytes written to this file..
    return ftell(mFile);
    }

uint64_t ChecksummedWriter::fileSize() const
    {
    return detail::fileSize(const_cast<FILE*>(mFile));
    }

bool ChecksummedWriter::isDirty() const
    {
    return mIsDirty;
    }

void ChecksummedWriter::writeString(const string& str)
    {
    // write a string to disk as checksum / size / string
    lassert(!mDataError);
    uint64_t size = str.size();

    boost::crc_32_type crc;
    crc.process_bytes(str.data(), str.size());
    uint32_t checksum = crc.checksum();

    if (fwrite(&checksum, sizeof(uint32_t), 1, mFile) != 1)
        detail::onWriteError(mPath);
    if(fwrite(&size, sizeof(uint64_t), 1, mFile) != 1)
        detail::onWriteError(mPath);
    if(fwrite(str.c_str(), sizeof(char), size, mFile) != size)
        detail::onWriteError(mPath);

    mIsDirty = true;
    }

bool readString(FILE* inFile, string& outString, int64_t& remainingBytes)
    {
    // read a string from disk and verify that it matches the checksum.
    // any disk error should result in failure. Any data error should
    // result in mDataError being set to true and null should be returned.
    if(feof(inFile)) // if the file is empty upon opening it will be eof
        return false;

    uint32_t checksum;
    if(fread(&checksum, sizeof(uint32_t), 1, inFile) != 1)
        {
        LOG_ERROR << "unable to read initial hash yet not eof: " <<  endl;
        return false;
        }

    remainingBytes -= sizeof(uint32_t);
    uint64_t size;
    if(fread(&size, sizeof(uint64_t), 1, inFile) != 1)
        {
        LOG_ERROR <<  "unable to read message size from disk";
        return false;
        }

    // ideally we'd use a fixed buffer and avoid malloc here.
    remainingBytes -= sizeof(uint64_t);

    if(size > remainingBytes)
        {
        LOG_ERROR << "message was truncated: should be " <<
            size << " remaining is " << remainingBytes;
        return false;
        }

    vector<char> buff(size);
    if(fread(&buff[0], 1, size, inFile) != size)
        {
        // since we are checking the size above this should never
        // fail!
        LOG_ERROR << "unable to read entire message from disk";
        return false;
        }
    remainingBytes -= size;

    boost::crc_32_type crc;
    crc.process_bytes(&buff[0], size);
    if(crc.checksum() != checksum)
        {
        LOG_ERROR << "message didn't match it's checksum";
        return false;
        }

    outString = string(buff.begin(), buff.end());
    return true;
    }

bool readAllToVector(std::string path, vector<string>& outVector)
    {
    lassert(outVector.size() == 0);
    FILE* file = detail::openFile(path, FileMode::READ);
    int64_t remaining = detail::fileSize(file);

    bool readAgain = true;
    string result;
    while(readAgain)
        {
        bool success = readString(file, result, remaining);
        if(!success)
            {
            if(fclose(file))
                perror("");
            return false;
            }
        outVector.push_back(result);
        readAgain = success && remaining > 0;
        }
    if(fclose(file))
        perror("");
    return true;
    }

}

max_stars_repo_name: ufora/ufora


text:
//  timer, job_timer, and progress_display sample program  -------------------//

//  (C) Copyright Beman Dawes 1998. Permission to copy, use, modify, sell and
//  distribute this software is granted provided this copyright notice appears
//  in all copies. This software is provided "as is" without express or implied
//  warranty, and with no claim as to its suitability for any purpose.

//  Revision History
//  12 Jan 01  Cut time to 1.0 secs to speed regression tests (Beman Dawes)
//  25 Sep 99  added elapsed_min() and elapsed_max() reporting
//  16 Jul 99  Second beta
//   6 Jul 99  Initial boost version

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

using boost::timer;
using boost::progress_timer;
using boost::progress_display;
using std::cout;
using std::endl;

int main() {

  timer t0;  // used only for elapsed_max() and elapsed_min()

  cout << "timer::elapased_min() reports " << t0.elapsed_min() << " seconds\n";
  cout << "timer::elapased_max() reports " << t0.elapsed_max()
       << " seconds, which is " << t0.elapsed_max()/3600.0 << " hours\n";

  cout << "\nverify progress_display(0) doesn't divide by zero" << endl;
  progress_display zero( 0 );  // verify 0 doesn't divide by zero
  ++zero;

  long loops;
  timer loop_timer;
  const double time = 1.0;

  cout << "\ndetermine " << time << " second iteration count" << endl;
  for ( loops = 0; loops < LONG_MAX
     && loop_timer.elapsed() < time; ++loops ) {}
  cout << loops << " iterations"<< endl;

  long i;
  bool time_waster; // defeat [some] optimizers by storing result here

  progress_timer pt;
  timer t1;
  timer t4;
  timer t5;

  cout << "\nburn about " << time << " seconds" << endl;
  progress_display pd( loops );
  for ( i = loops; i--; )
    { time_waster = loop_timer.elapsed() < time; ++pd; }

  timer t2( t1 );
  timer t3;
  t4 = t3;
  t5.restart();

  cout << "\nburn about " << time << " seconds again" << endl;
  pd.restart( loops );
  for ( i = loops; i--; )
    { time_waster = loop_timer.elapsed() < time; ++pd; }

  if ( time_waster ) cout << ' ';  // using time_waster quiets compiler warnings
  progress_display pd2( 50, cout, "\nLead string 1 ", "Lead string 2 ", "Lead string 3 " );
  for ( ; pd2.count() < 50; ++pd2 ) {}

  cout << "\nt1 elapsed: " << t1.elapsed() << '\n';
  cout << "t2 elapsed: " << t2.elapsed() << '\n';
  cout << "t3 elapsed: " << t3.elapsed() << '\n';
  cout << "t4 elapsed: " << t4.elapsed() << '\n';
  cout << "t5 elapsed: " << t5.elapsed() << '\n';
  cout << "t1 and t2 should report the same times (very approximately "
       << 2*time << " seconds).\n";
  cout << "t3, t4 and t5 should report about the same times,\n";
  cout << "and these should be about half the t1 and t2 times.\n";
  cout << "The following elapsed time should be slightly greater than t1."
       << endl;
  return 0;
  } // main


text:
#include <ctime>
#include <iostream>
#include <string>
#include <chrono>
#include <thread>
#include <debug.hpp>
#include <boost/program_options.hpp>
#include <boost/asio.hpp>

#include "client.hpp"
#include "server.hpp"

namespace po = boost::program_options;

using std::thread;
using boost::asio::ip::tcp;

std::string basedir;

void print_help (std::string& binary, po::options_description& desc)
{
	cout << desc << endl;
	cout << "read a file: " << binary << " --operation read --file myfile --server localhost --port 4444" << " - read 1024 bytes from the remote file myfile" << endl;
	cout << "write a file: " << binary << " --operation write --file myfile --server localhost --port 4444" << " - write 2 bytes to the remote file myfile from the standard input" << endl;
}

int main(int ac, char* av[])
{
   debug ("starting server", SEVERITY_INFO);

   po::options_description desc("Available options");

   desc.add_options()
      ("help", "print help message")
      ("basedir", po::value<std::string>(), "directory to serve")
      ("port", po::value<int>(), "port to listen to")
      ;

	std::string binary = av[0];
   po::variables_map vm;
   po::store(po::parse_command_line(ac, av, desc), vm);
   po::notify(vm);

   if (vm.count("port") == 0)
   {
      print_help (binary, desc);
      exit (EXIT_FAILURE);
   }

   if (vm.count("basedir") == 0)
   {
      print_help (binary, desc);
      exit (EXIT_FAILURE);
   }

	basedir = vm["basedir"].as<std::string>();
	int port = vm["port"].as<int>();

   try
   {
      boost::asio::io_service io_service;

      server s(io_service, port);
      s.start();

      io_service.run();
   }
   catch (std::exception& e)
   {
      std::cerr << e.what() << std::endl;
   }

   exit (EXIT_SUCCESS);
}


text:
// Boost.Signals library
//
// Copyright (C) 2001-2002 Doug Gregor (gregod@cs.rpi.edu)
//
// Permission to copy, use, sell and distribute this software is granted
// provided this copyright notice appears in all copies.
// Permission to modify the code and to distribute modified code is granted
// provided this copyright notice appears in all copies, and a notice
// that the code was modified is included with the copyright notice.
//
// This software is provided "as is" without express or implied warranty,
// and with no claim as to its suitability for any purpose.

// For more information, see http://www.boost.org

#ifndef BOOST_SIGNALS_CONNECTION_HPP
#define BOOST_SIGNALS_CONNECTION_HPP

#include <boost/signals/detail/signals_common.hpp>
#include <boost/smart_ptr.hpp>
#include <boost/operators.hpp>
#include <boost/any.hpp>
#include <list>
#include <cassert>
#include <utility>

namespace boost {
  namespace BOOST_SIGNALS_NAMESPACE {
    class trackable;

    namespace detail {
      // Represents an object that has been bound as part of a slot, and how
      // to notify that object of a disconnect
      struct bound_object {
        void* obj;
        void* data;
        void (*disconnect)(void*, void*);

        bool operator==(const bound_object& other) const
          { return obj == other.obj && data == other.data; }
        bool operator<(const bound_object& other) const
          { return obj < other.obj; }
      };

      // Describes the connection between a signal and the objects that are
      // bound for a specific slot. Enables notification of the signal and the
      // slots when a disconnect is requested.
      struct basic_connection {
        void* signal;
        void* signal_data;
        void (*signal_disconnect)(void*, void*);

        std::list<bound_object> bound_objects;
      };
    } // end namespace detail

    // The user may freely pass around the "connection" object and terminate
    // the connection at any time using disconnect().
    class BOOST_SIGNALS_DECL connection :
      private less_than_comparable1<connection>,
      private equality_comparable1<connection>
    {
    public:
      connection();
      connection(const connection&);
      ~connection();

      // Disconnect the signal and slot, if they are connected
      void disconnect() const;

      // Returns true if the signal and slot are connected
      bool connected() const { return con.get() && con->signal_disconnect; }

      // Comparison of connections
      inline bool operator==(const connection& other) const;
      inline bool operator<(const connection& other) const;

      // Connection assignment
      connection& operator=(const connection& other) ;

      // Swap connections
      inline void swap(connection& other);

    public: // TBD: CHANGE THIS
      // Set whether this connection object is controlling or not
      void set_controlling() { controlling_connection = true; }

    private:
      friend class detail::signal_base_impl;
      friend class detail::slot_base;
      friend class trackable;

      // Reset this connection to refer to a different actual connection
      void reset(BOOST_SIGNALS_NAMESPACE::detail::basic_connection*);

      // Add a bound object to this connection (not for users)
      void add_bound_object(const BOOST_SIGNALS_NAMESPACE::detail::bound_object& b);

      friend class BOOST_SIGNALS_NAMESPACE::detail::bound_objects_visitor;

      // Pointer to the actual contents of the connection
      shared_ptr<BOOST_SIGNALS_NAMESPACE::detail::basic_connection> con;

      // True if the destruction of this connection object should disconnect
      bool controlling_connection;
    };

    // Similar to connection, but will disconnect the connection when it is
    // destroyed unless release() has been called.
    class BOOST_SIGNALS_DECL scoped_connection : public connection {
    public:
      scoped_connection() : connection(), released(false) {}
      scoped_connection(const connection&);
      scoped_connection(const scoped_connection&);
      ~scoped_connection();

      connection release();

      inline void swap(scoped_connection&);

      scoped_connection& operator=(const connection&);
      scoped_connection& operator=(const scoped_connection&);

    private:
      bool released;
    };

    inline connection::connection() :
      con(), controlling_connection(false)
    {
    }

    inline connection::connection(const connection& other) :
      con(other.con), controlling_connection(other.controlling_connection)
    {
    }

    inline connection::~connection()
    {
      if (controlling_connection) {
        disconnect();
      }
    }

    inline void
    connection::reset(BOOST_SIGNALS_NAMESPACE::detail::basic_connection* new_con)
    {
      con.reset(new_con);
    }

    inline void
    connection::add_bound_object(const BOOST_SIGNALS_NAMESPACE::detail::bound_object& b)
    {
      assert(con.get() != 0);
      con->bound_objects.push_back(b);
    }

    inline bool connection::operator==(const connection& other) const
    {
      return con.get() == other.con.get();
    }

    inline bool connection::operator<(const connection& other) const
    {
      return con.get() < other.con.get();
    }

    inline connection& connection::operator=(const connection& other)
    {
      connection(other).swap(*this);
      return *this;
    }

    inline void connection::swap(connection& other)
    {
      this->con.swap(other.con);
      std::swap(this->controlling_connection, other.controlling_connection);
    }

    inline void swap(connection& c1, connection& c2)
    {
      c1.swap(c2);
    }

    inline scoped_connection::scoped_connection(const connection& other) :
      connection(other),
      released(false)
    {
    }

    inline
    scoped_connection::scoped_connection(const scoped_connection& other) :
      connection(other),
      released(other.released)
    {
    }

    inline scoped_connection::~scoped_connection()
    {
      if (!released) {
        this->disconnect();
      }
    }

    inline connection scoped_connection::release()
    {
      released = true;
      return *this;
    }

    inline void scoped_connection::swap(scoped_connection& other)
    {
      this->connection::swap(other);
      bool other_released = other.released;
      other.released = this->released;
      this->released = other_released;
    }

    inline void swap(scoped_connection& c1, scoped_connection& c2)
    {
      c1.swap(c2);
    }

    inline scoped_connection&
    scoped_connection::operator=(const connection& other)
    {
      scoped_connection(other).swap(*this);
      return *this;
    }

    inline scoped_connection&
    scoped_connection::operator=(const scoped_connection& other)
    {
      scoped_connection(other).swap(*this);
      return *this;
    }

    namespace detail {
      struct connection_slot_pair {
        connection first;
        any second;

        connection_slot_pair() {}

        connection_slot_pair(const connection& c, const any& a)
          : first(c), second(a)
        {
        }

        // Dummys to allow explicit instantiation to work
        bool operator==(const connection_slot_pair&) const { return false; }
        bool operator<(const connection_slot_pair&) const { return false;}
      };

      // Determines if the underlying connection is disconnected
      struct is_disconnected {
        typedef std::pair<const any, connection_slot_pair> argument_type;
        typedef bool result_type;

        inline bool operator()(const argument_type& c) const
        {
          return !c.second.first.connected();
        }
      };

      // Autodisconnects the bound object when it is destroyed unless the
      // release method is invoked.
      class auto_disconnect_bound_object {
      public:
        auto_disconnect_bound_object(const bound_object& b) :
          binding(b), auto_disconnect(true)
        {
        }

        ~auto_disconnect_bound_object()
        {
          if (auto_disconnect)
            binding.disconnect(binding.obj, binding.data);
        }

        void release() { auto_disconnect = false; }

      private:
        bound_object binding;
        bool auto_disconnect;
      };
    } // end namespace detail
  } // end namespace BOOST_SIGNALS_NAMESPACE
} // end namespace boost

#endif // BOOST_SIGNALS_CONNECTION_HPP