text:
#ifndef SPARSETENSOR_HYPERTRIE_POSCALC_HPP
#define SPARSETENSOR_HYPERTRIE_POSCALC_HPP

#include <cstdint>
#include <boost/container/flat_map.hpp>
#include <vector>
#include <memory>
#include <itertools.hpp>

namespace hypertrie::internal::util {
	/**
	 * Provides translation between position in superkeys with subkeys. (1,2,4) for example is a subkey of (1,2,3,4).
	 * And the other way around.
	 */
	// TODO: make threadsafe
	class PosCalc {
		template<typename key, typename value>
		using flat_map = ::boost::container::flat_map<key, value>;
	public:
		using key_pos_t = uint8_t;
		using subkey_mask_t = ::std::vector<bool>;
	private:
		/**
		 * Stores for superkey positions to which subkey positions they map.
		 */
		const std::vector<key_pos_t> key_to_subkey;

		/**
		 * Stores for subkey positions to which superkey positions they map. So this is also a list of all currently relevant superkey pos.
		 */
		const std::vector<key_pos_t> subkey_to_key;

		/**
		 * removed_positions bit vector of positions removed from superkey to subkey.
		 */
		const subkey_mask_t removed_positions;

		/**
		 * Cache for PosCalcs of subkeys that are 1 shorter.
		 */
		mutable std::vector<PosCalc const *> next_pos_calcs;

		PosCalc(std::vector<key_pos_t> &&keyToSubkey,
		        std::vector<key_pos_t> &&subkeyToKey,
		        subkey_mask_t removedPositions) :
				key_to_subkey{keyToSubkey},
				subkey_to_key{subkeyToKey},
				removed_positions{std::move(removedPositions)},
				next_pos_calcs(this->keyLength()) {}

	public:

		key_pos_t keyLength() const {
			return key_to_subkey.size();
		}

		key_pos_t subkeyLength() const {
			return subkey_to_key.size();
		}

		/**
		 * Convert a superkey position to a subkey key position.
		 * @param key_pos superkey position
		 * @return subkey position
		 */
		key_pos_t key_to_subkey_pos(key_pos_t key_pos) const {
			return key_to_subkey[key_pos];
		}

		/**
		 * Convert a subkey position to a superkey position.
		 * @param subkey_pos subkey position
		 * @return superkey position
		 */
		key_pos_t subkey_to_key_pos(key_pos_t subkey_pos) const {
			return subkey_to_key[subkey_pos];
		}

		/**
		 * Get all keypositions that this subkey contains.
		 * @return vector of key positions.
		 */
		const std::vector<key_pos_t> &getKeyPoss() const {
			return subkey_to_key;
		}

		/**
		 * bit vector of positions removed from superkey to subkey.
		 * @return bit vector
		 */
		const subkey_mask_t &getSubKeyMask() const {
			return removed_positions;
		}

		/**
		 * PosCalcs of subkeys that has one position less.
		 * @param key_pos position of superkey to be removed.
		 * @return PosCalc like this but without position key_pos.
		 */
		PosCalc const *use(const key_pos_t &key_pos) const {
			PosCalc const *child = next_pos_calcs.at(key_pos);
			if (child == nullptr) {
				std::vector<bool> used_pos_mask(this->keyLength(), true);
				for (auto subkey_pos : this->subkey_to_key)
					used_pos_mask[subkey_pos] = false;
				used_pos_mask[key_pos] = true;

				child = getInstance(used_pos_mask);
				next_pos_calcs[key_pos] = child;
			}
			return child;
		}

		/**
		 * Holds all instances.
		 */
		inline static flat_map<std::vector<bool>, std::unique_ptr<PosCalc const>> instances{};

		/**
		 * Get an instance for a vector of used positions.
		 * @param removed_positions bit vector of positions removed from superkey to subkey.
		 * @return an instance
		 */
		static PosCalc const *getInstance(const std::vector<bool> &removed_positions) {
			auto instance_ = instances.find(removed_positions);
			if (instance_ != instances.end()) {
				// if an instance already exists return it
				return instance_->second.get();
			} else {
				// else create it and store it for reuse
				auto key_length = key_pos_t(removed_positions.size());

				key_pos_t subkey_length = std::count(removed_positions.begin(), removed_positions.end(), false);

				subkey_mask_t next_removed_positions(key_length);
				std::vector<key_pos_t> next_key_to_subkey(key_length);
				std::vector<key_pos_t> next_subkey_to_key(subkey_length);

				key_pos_t offset = 0;

				for (auto key_pos : iter::range(key_length)) {

					if (removed_positions[key_pos]) {
						offset++;
					} else {
						const key_pos_t subkey_pos = key_pos - offset;

						next_key_to_subkey[key_pos] = subkey_pos;
						next_subkey_to_key[subkey_pos] = key_pos;
					}
				}

				instances[removed_positions] = std::unique_ptr<PosCalc const>{new PosCalc{
						std::move(next_key_to_subkey), std::move(next_subkey_to_key), removed_positions}};
				return instances[removed_positions].get();
			}
		}

		/**
		 * Get an instance for a empty vector of used positions of given length.
		 * @param removed_positions length of the empty vector.
		 * @return an instance
		 */
		static PosCalc const *getInstance(const size_t &length) {
			subkey_mask_t key_mask(length);
			return getInstance(key_mask);
		}

	};

}

#endif //SPARSETENSOR_HYPERTRIE_POSCALC_HPP

max_stars_repo_name: lennartaustenfeld/hypertrie

max_issues_repo_name: lennartaustenfeld/hypertrie

max_forks_repo_name: lennartaustenfeld/hypertrie


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

  Basic N-dimensional topology.

  Copyright (c) 2013
  Dzmitry Hlindzich <hlindzich@gmail.com>
  All rights reserved.

  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.

  THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR OR CONTRIBUTORS BE LIABLE
  FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
  OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
  OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  SUCH DAMAGE.

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

#ifndef TOPOLOGY_HPP_79A57FE0_9EFD_11E2_9E96_0800200C9A66_
#define TOPOLOGY_HPP_79A57FE0_9EFD_11E2_9E96_0800200C9A66_

#include <vector>
#include <utility>
#include <set>
#include <boost/static_assert.hpp>

#include "bo/core/vector.hpp"

namespace bo {
namespace math {

// Basic N-dimensional hyperrectangle (N-orthotope) geometry.
template <typename RealType, std::size_t N>
class OrthotopeTopology
{
private:
    BOOST_STATIC_ASSERT(N > 0);

public:
    typedef Vector<RealType, N> Point;
    typedef std::pair<Point, Point> Edge;
    typedef std::vector<Edge> Edges;

    // Returns all the edges of a unit N-orthotope.
    static Edges edges()
    {
        // Initialize the source of the edge traverse.
        PointSet in_vertices;
        in_vertices.insert(Point(0));

        // Traverse the edges.
        Edges e;
        traverse_edges(in_vertices, e);

        return e;
    }

    // Returns the number of edges in a N-orthotope.
    static std::size_t edge_count()
    {
        return (1 << (N - 1)) * N;
    }

    // Returns the number of vertices in a N-orthotope.
    static std::size_t vertex_count()
    {
        return 1 << N;
    }

    // Returns the number of facets ((N-1)-dimensional faces) in a N-othotope.
    static std::size_t facet_count()
    {
        return 2 * N;
    }

private:

    typedef std::set<Point> PointSet;

    // Recursively traverses the edges of a N-orthotope starting from the given set
    // of vertices in ascending order and pushes the edges into the given container.
    static void traverse_edges(const PointSet &in_vertices, Edges &edges)
    {
        if (in_vertices.size() == 1 && *in_vertices.begin() == Point(1))
            return;

        PointSet out_vertices;

        for (typename PointSet::const_iterator it = in_vertices.begin(); it != in_vertices.end(); ++it)
        {
            Point edge_begin = *it;

            // Find all adjacent vertices for the current one.
            for (std::size_t k = 0; k < N; ++k)
            {
                if (edge_begin[k] == 1)
                    continue;

                // An adjacent vertex differs only in one dimension.
                Point edge_end = edge_begin;
                edge_end[k] = 1;

                // Insert the edge into the collection.
                edges.push_back(Edge(edge_begin, edge_end));

                // Save the end vertex.
                out_vertices.insert(edge_end);
            }
        }

        traverse_edges(out_vertices, edges);
    }

};

} // namespace math
} // namespace bo

#endif // TOPOLOGY_HPP_79A57FE0_9EFD_11E2_9E96_0800200C9A66_

ext: hpp

max_stars_repo_name: rukletsov/bo

max_issues_repo_name: rukletsov/bo

max_forks_repo_name: rukletsov/bo


text:
/*
 * Copyright (c) 2014 Juniper Networks, Inc. All rights reserved.
 */

#include <boost/uuid/uuid_io.hpp>
#include <vnc_cfg_types.h>
#include <cmn/agent_cmn.h>

#include <net/if.h>
#include <ifmap/ifmap_node.h>
#include <cfg/cfg_init.h>
#include <cfg/cfg_listener.h>
#include <oper/agent_sandesh.h>
#include <oper/ifmap_dependency_manager.h>
#include <oper/interface_common.h>
#include <oper/physical_device.h>
#include <oper/nexthop.h>
#include <oper/config_manager.h>

#include <vector>
#include <string>

using std::string;

/////////////////////////////////////////////////////////////////////////////
// PhysicalInterface routines
/////////////////////////////////////////////////////////////////////////////
PhysicalInterface::PhysicalInterface(const std::string &name,
                           const boost::uuids::uuid &logical_router_uuid) :
    Interface(Interface::PHYSICAL, nil_uuid(), name, NULL, true,
              logical_router_uuid),
    persistent_(false), subtype_(INVALID), physical_device_(NULL) {
}

PhysicalInterface::~PhysicalInterface() {
}

PhysicalDevice *PhysicalInterface::physical_device() const {
    return physical_device_.get();
}

string PhysicalInterface::ToString() const {
    return "PORT <" + name() + ">";
}

bool PhysicalInterface::CmpInterface(const DBEntry &rhs) const {
    const PhysicalInterface &a = static_cast<const PhysicalInterface &>(rhs);
    return name() < a.name();
}

DBEntryBase::KeyPtr PhysicalInterface::GetDBRequestKey() const {
    InterfaceKey *key = new PhysicalInterfaceKey(name());
    return DBEntryBase::KeyPtr(key);
}

bool PhysicalInterface::OnChange(const InterfaceTable *table,
                                 const PhysicalInterfaceData *data) {
    bool ret = false;

    // Handle VRF Change
    VrfKey key(data->vrf_name_);
    VrfEntry *new_vrf = static_cast<VrfEntry *>
        (table->agent()->vrf_table()->FindActiveEntry(&key));
    if (new_vrf != vrf_.get()) {
        vrf_.reset(new_vrf);
        ret = true;
    }

    PhysicalDevice *dev =
        table->agent()->physical_device_table()->Find(data->device_uuid_);
    if (dev != physical_device_.get()) {
        physical_device_.reset(dev);
        ret = true;
    }

    return ret;
}

bool PhysicalInterface::Delete(const DBRequest *req) {
    flow_key_nh_.reset();
    InterfaceNH::DeletePhysicalInterfaceNh(name(), mac());
    return true;
}

std::string PhysicalInterface::GetPhysicalInterfaceName() const {
    std::size_t pos = name().find_last_of(":");
    if (pos != string::npos) {
        return name().substr(pos + 1);
    }
    return name();
}

void PhysicalInterface::PostAdd() {
    InterfaceNH::CreatePhysicalInterfaceNh(name(), mac());

    InterfaceTable *table = static_cast<InterfaceTable *>(get_table());
    Agent *agent = table->agent();

    InterfaceNHKey key(new PhysicalInterfaceKey(name()), false, InterfaceNHFlags::INET4, mac());
    flow_key_nh_ = static_cast<InterfaceNH *>
        (agent->nexthop_table()->FindActiveEntry(&key));
    assert(flow_key_nh_);

    if (table->agent()->test_mode()) {
        return;
    }

    std::string interface_name = name();
    // Interfaces in VMWARE mode and having remote VMs
    // must be put into promiscuous mode
    if (subtype_ != VMWARE) {
        if (!table->agent()->server_gateway_mode() ||
            subtype_ == PhysicalInterface::FABRIC) {
            return;
        } else {
            interface_name = GetPhysicalInterfaceName();
        }
    }

// Not yet supported on Windows
#ifndef _WIN32
    int fd = socket(AF_LOCAL, SOCK_STREAM, 0);
    assert(fd >= 0);

    struct ifreq ifr;
    memset(&ifr, 0, sizeof(ifr));
    strncpy(ifr.ifr_name, interface_name.c_str(), IF_NAMESIZE);

    if (ioctl(fd, SIOCGIFFLAGS, (void *)&ifr) < 0) {
        LOG(ERROR, "Error <" << errno << ": " << strerror(errno) <<
            "> setting promiscuous flag for interface <" << interface_name << ">");
        close(fd);
        return;
    }

    ifr.ifr_flags |= IFF_PROMISC;
    if (ioctl(fd, SIOCSIFFLAGS, (void *)&ifr) < 0) {
        LOG(ERROR, "Error <" << errno << ": " << strerror(errno) <<
            "> setting promiscuous flag for interface <" << interface_name << ">");
        close(fd);
        return;
    }

    close(fd);
#endif

}

/////////////////////////////////////////////////////////////////////////////
// PhysicalInterfaceKey routines
/////////////////////////////////////////////////////////////////////////////
PhysicalInterfaceKey::PhysicalInterfaceKey(const std::string &name) :
    InterfaceKey(AgentKey::ADD_DEL_CHANGE, Interface::PHYSICAL, nil_uuid(),
                 name, false) {
}

PhysicalInterfaceKey::~PhysicalInterfaceKey() {
}

Interface *PhysicalInterfaceKey::AllocEntry(const InterfaceTable *table) const {
    return new PhysicalInterface(name_, nil_uuid());
}

Interface *PhysicalInterfaceKey::AllocEntry(const InterfaceTable *table,
                                            const InterfaceData *data) const {
    PhysicalInterface *intf = new PhysicalInterface(name_,
                                                    data->logical_router_uuid_);
    const PhysicalInterfaceData *phy_data =
        static_cast<const PhysicalInterfaceData *>(data);
    intf->encap_type_ = phy_data->encap_type_;
    intf->no_arp_ = phy_data->no_arp_;
    intf->subtype_ = phy_data->subtype_;
    intf->display_name_ = phy_data->display_name_;
    if (intf->subtype_ == PhysicalInterface::VMWARE ||
        intf->subtype_ == PhysicalInterface::CONFIG) {
        intf->persistent_ = true;
    }

    intf->OnChange(table, phy_data);
    return intf;
}

InterfaceKey *PhysicalInterfaceKey::Clone() const {
    return new PhysicalInterfaceKey(name_);
}

/////////////////////////////////////////////////////////////////////////////
// PhysicalInterfaceData routines
/////////////////////////////////////////////////////////////////////////////
PhysicalInterfaceData::PhysicalInterfaceData(Agent *agent, IFMapNode *node,
                                             const string &vrf_name,
                                             PhysicalInterface::SubType subtype,
                                             PhysicalInterface::EncapType encap,
                                             bool no_arp,
                                             const uuid &device_uuid,
                                             const string &display_name,
                                             const Ip4Address &ip,
                                             Interface::Transport transport) :
    InterfaceData(agent, node, transport), subtype_(subtype), encap_type_(encap),
    no_arp_(no_arp), device_uuid_(device_uuid), display_name_(display_name),
    ip_(ip) {
    EthInit(vrf_name);
}

/////////////////////////////////////////////////////////////////////////////
// Config handling routines
/////////////////////////////////////////////////////////////////////////////
static PhysicalInterfaceKey *BuildKey(const std::string &name) {
    return new PhysicalInterfaceKey(name);
}

bool InterfaceTable::PhysicalInterfaceIFNodeToReq(IFMapNode *node,
                                                  DBRequest &req,
                                                  const boost::uuids::uuid &u) {

    // Enqueue request to config-manager if add/change
    if ((req.oper != DBRequest::DB_ENTRY_DELETE) &&
                            (node->IsDeleted() == false)) {
        agent()->config_manager()->AddPhysicalInterfaceNode(node);
        return false;
    }

    autogen::PhysicalInterface *port =
        static_cast <autogen::PhysicalInterface *>(node->GetObject());
    assert(port);

    // Get the physical-router from FQDN
    string device = "";
    vector<string> elements;
    split(elements, node->name(), boost::is_any_of(":"), boost::token_compress_on);
    if (elements.size() == 3) {
        device = elements[1];
    }

    if (elements.size() == 3 && device != agent()->agent_name()) {
        if (RemotePhysicalInterfaceIFNodeToReq(node, req, u)) {
            Enqueue(&req);
        }
        return false;
    }

    req.key.reset(BuildKey(node->name()));
    req.oper = DBRequest::DB_ENTRY_DELETE;
    return true;
}

bool InterfaceTable::PhysicalInterfaceProcessConfig(IFMapNode *node,
        DBRequest &req, const boost::uuids::uuid &u) {

    if (node->IsDeleted()) {
        return false;
    }

    autogen::PhysicalInterface *port =
        static_cast <autogen::PhysicalInterface *>(node->GetObject());
    assert(port);

    // Get the physical-router from FQDN
    string device = "";
    vector<string> elements;
    split(elements, node->name(), boost::is_any_of(":"), boost::token_compress_on);
    if (elements.size() == 3) {
        device = elements[1];
    }

    // If physical-router does not match agent_name, treat as remote interface
    if (elements.size() == 3 && device != agent()->agent_name()) {
        return RemotePhysicalInterfaceIFNodeToReq(node, req, u);
    }

    req.key.reset(BuildKey(node->name()));

    boost::uuids::uuid dev_uuid = nil_uuid();
    // Find link with physical-router adjacency
    IFMapNode *adj_node = NULL;
    adj_node = agent()->config_manager()->FindAdjacentIFMapNode(node,
                                                            "physical-router");
    if (adj_node) {
        autogen::PhysicalRouter *router =
            static_cast<autogen::PhysicalRouter *>(adj_node->GetObject());
        autogen::IdPermsType id_perms = router->id_perms();
        CfgUuidSet(id_perms.uuid.uuid_mslong, id_perms.uuid.uuid_lslong,
                   dev_uuid);
    }
    req.oper = DBRequest::DB_ENTRY_ADD_CHANGE;
    req.data.reset(new PhysicalInterfaceData(agent(), node,
                                             agent()->fabric_vrf_name(),
                                             PhysicalInterface::CONFIG,
                                             PhysicalInterface::ETHERNET,
                                             false, dev_uuid,
                                             port->display_name(),
                                             Ip4Address(0),
                                             Interface::TRANSPORT_ETHERNET));
    pi_ifnode_to_req_++;
    Enqueue(&req);
    return false;
}

/////////////////////////////////////////////////////////////////////////////
// Utility methods
/////////////////////////////////////////////////////////////////////////////
// Enqueue DBRequest to create a Host Interface
void PhysicalInterface::CreateReq(InterfaceTable *table, const string &ifname,
                                  const string &vrf_name, SubType subtype,
                                  EncapType encap, bool no_arp,
                                  const uuid &device_uuid,
                                  const Ip4Address &ip,
                                  Interface::Transport transport) {
    DBRequest req(DBRequest::DB_ENTRY_ADD_CHANGE);
    req.key.reset(new PhysicalInterfaceKey(ifname));
    req.data.reset(new PhysicalInterfaceData(NULL, NULL, vrf_name, subtype,
                                             encap, no_arp, device_uuid,
                                             ifname, ip, transport));
    table->Enqueue(&req);
}

void PhysicalInterface::Create(InterfaceTable *table, const string &ifname,
                               const string &vrf_name, SubType subtype,
                               EncapType encap, bool no_arp,
                               const uuid &device_uuid,
                               const Ip4Address &ip,
                               Interface::Transport transport) {
    DBRequest req(DBRequest::DB_ENTRY_ADD_CHANGE);
    req.key.reset(new PhysicalInterfaceKey(ifname));
    req.data.reset(new PhysicalInterfaceData(NULL, NULL, vrf_name, subtype,
                                             encap, no_arp, device_uuid,
                                             ifname, ip, transport));
    table->Process(req);
}

// Enqueue DBRequest to delete a Host Interface
void PhysicalInterface::DeleteReq(InterfaceTable *table, const string &ifname) {
    DBRequest req(DBRequest::DB_ENTRY_DELETE);
    req.key.reset(new PhysicalInterfaceKey(ifname));
    req.data.reset(NULL);
    table->Enqueue(&req);
}

void PhysicalInterface::Delete(InterfaceTable *table, const string &ifname) {
    DBRequest req(DBRequest::DB_ENTRY_DELETE);
    req.key.reset(new PhysicalInterfaceKey(ifname));
    req.data.reset(NULL);
    table->Process(req);
}

ext: cc

max_stars_repo_name: kaweue/contrail-controller

max_issues_repo_name: kaweue/contrail-controller

max_forks_repo_name: kaweue/contrail-controller


text:
#include <Eigen/Dense>
#include <Eigen/SVD>
#include <cmath>
#include "metrics.h"
#include <iostream>

using namespace Eigen;

namespace dmaps
{
	f_type rmsd(const vector_t& ri, const vector_t& rj, const vector_t& w)
	{
		// Copy vectors for manipulation.
		vector_t r1 = ri, r2 = rj;

		// Get subset of weights just to make sure the size is proper.
		const vector_t& ws = w.segment(0, ri.size()/3);

		// Maps for ease of use.
		Map<matrix3_t> xi(r1.data(), r1.size()/3, 3);
		Map<matrix3_t> xj(r2.data(), r2.size()/3, 3);

		// Subtract out centers of mass.
		f_type wtot = ws.sum();
		vector3_t comi = (ws.asDiagonal()*xi).colwise().sum()/wtot;
		vector3_t comj = (ws.asDiagonal()*xj).colwise().sum()/wtot;
		xi.rowwise() -= comi.transpose();
		xj.rowwise() -= comj.transpose();

		// SVD of covariance matrix.
		matrix_t cov = xi.transpose()*ws.asDiagonal()*xj;
		JacobiSVD<matrix_t> svd(cov, ComputeThinU | ComputeThinV);

		// Find rotation.
		f_type d = (svd.matrixV()*svd.matrixU().transpose()).determinant() > 0 ? 1 : -1;

		matrix33_t eye = matrix33_t::Identity(3, 3);
		eye(2, 2) = d;
		matrix33_t R = svd.matrixV()*eye*svd.matrixU().transpose();

		// Return rmsd.
		return std::sqrt((ws.asDiagonal()*(xi - xj*R).array().square().matrix()).sum()/wtot);
	}

	f_type euclidean(const vector_t& ri, const vector_t& rj, const vector_t& w)
	{
		return std::sqrt((w.array()*(ri-rj).array().square()).sum());
	}

	f_type contact_map(const vector_t& ri, const vector_t& rj, const vector_t&)
	{
		Map<const matrix3_t> xi(ri.data(), ri.size()/3, 3);
		Map<const matrix3_t> xj(rj.data(), rj.size()/3, 3);

		int irows = xi.rows(), jrows = xj.rows();
		vector_t dxi(irows*irows/2 - irows/2), dxj(jrows*jrows/2 - jrows/2);

		// Compute pairwise distances.
		int k = 0;
		for(int i = 0; i < irows - 1; ++i)
		{
			int nrows = irows - i - 1;
			dxi.segment(k, nrows) = (xi.bottomRows(nrows).rowwise() - xi.row(i)).matrix().rowwise().norm();
			k += nrows;
		}

		k = 0;
		for(int i = 0; i < jrows - 1; ++i)
		{
			int nrows = jrows - i - 1;
			dxj.segment(k, nrows) = (xj.bottomRows(nrows).rowwise() - xj.row(i)).matrix().rowwise().norm();
			k += nrows;
		}

		// Calculate distance metric normalization constants.
		f_type r0 = 0.35, n = 8, m = 12;

		dxi.array() = (1. - (dxi.array()/r0).pow(n))/(1. - (dxi.array()/r0).pow(m));
		dxj.array() = (1. - (dxj.array()/r0).pow(n))/(1. - (dxj.array()/r0).pow(m));

		f_type norm = std::sqrt(dxi.sum()*dxj.sum());

		return std::sqrt(1.0/norm*(dxi - dxj).array().square().sum());
	}
}

ext: cpp

max_stars_repo_name: hsidky/dmaps

max_issues_repo_name: hsidky/dmaps

max_forks_repo_name: hsidky/dmaps


text:
#ifdef WIN32
#define BOOST_ASIO_ERROR_CATEGORY_NOEXCEPT noexcept(true)
#endif

#include <thread>
#include <boost/bind.hpp>
#include <boost/log/core.hpp>
#include <boost/log/trivial.hpp>
#include "lowlevel_producer.h"

namespace csi {
namespace kafka {
lowlevel_producer::lowlevel_producer(boost::asio::io_service& io_service, const std::string& topic, int32_t partition, int32_t required_acks, int32_t timeout, int32_t max_packet_size)
  : _ios(io_service)
  , _client(io_service)
  , _topic(topic)
  , _partition_id(partition)
  , _required_acks(required_acks)
  , _tx_timeout(timeout)
  , _max_packet_size(max_packet_size)
  , _tx_queue_byte_size(0)
  , _tx_in_progress(false)
  , _try_send_posted(false)
  , _metrics_timer(io_service)
  , _metrics_timeout(boost::posix_time::milliseconds(100))
  , __metrics_total_tx_bytes(0)
  , __metrics_total_tx_msg(0) {
  if (required_acks < -1 || required_acks > 1) {
    BOOST_LOG_TRIVIAL(error) << "lowlevel_producer required_acks invalid value: " << required_acks;
  }
  if (_max_packet_size < 0)
    _max_packet_size = (csi::kafka::basic_call_context::MAX_BUFFER_SIZE - 1000);
  if (_max_packet_size > (csi::kafka::basic_call_context::MAX_BUFFER_SIZE - 1000))
    _max_packet_size = (csi::kafka::basic_call_context::MAX_BUFFER_SIZE - 1000);

  _metrics_timer.expires_from_now(_metrics_timeout);
  _metrics_timer.async_wait([this](const boost::system::error_code& ec) { handle_metrics_timer(ec); });
}

lowlevel_producer::~lowlevel_producer() {
  _metrics_timer.cancel();
  _client.close();
}

void  lowlevel_producer::close() {
  _client.close();
}

void lowlevel_producer::handle_metrics_timer(const boost::system::error_code& ec) {
  if (ec)
    return;
  _metrics_timer.expires_from_now(_metrics_timeout);
  _metrics_timer.async_wait([this](const boost::system::error_code& ec) { handle_metrics_timer(ec); });

  _try_send();
}

void lowlevel_producer::connect_async(const broker_address& address, int32_t timeout, connect_callback cb) {
  _client.connect_async(address, timeout, cb);
}

boost::system::error_code lowlevel_producer::connect(const broker_address& address, int32_t timeout) {
  return _client.connect(address, timeout);
}

void lowlevel_producer::connect_async(const boost::asio::ip::tcp::resolver::query& query, int32_t timeout, connect_callback cb) {
  _client.connect_async(query, 1000, cb);
}

boost::system::error_code lowlevel_producer::connect(const boost::asio::ip::tcp::resolver::query& query, int32_t timeout) {
  return _client.connect(query, 1000);
}

void lowlevel_producer::send_async(std::shared_ptr<basic_message> message, tx_ack_callback cb) {
  {
    csi::spinlock::scoped_lock xxx(_spinlock);
    _tx_queue_byte_size += message ? message->size() : 0; // callback markers
    _tx_queue.push_front(tx_item(message, cb));
  }

  if (_tx_in_progress || _try_send_posted)
    return;

  _try_send_posted = true;
  _ios.post([this]() {_try_send(); });
}

int32_t lowlevel_producer::send_sync(std::shared_ptr<basic_message> message) {
  std::promise<int32_t> p;
  std::future<int32_t>  f = p.get_future();
  send_async(message, [&p](int32_t result) {
    p.set_value(result);
  });
  f.wait();
  return f.get();
}

void lowlevel_producer::_try_send() {
  _try_send_posted = false;

  if (_tx_in_progress || !_client.is_connected())
    return;
  _tx_in_progress = true;

  std::vector<std::shared_ptr<basic_message>> v;

  // we might have NULL data with callbacks in this stream - it's a callback marker after the last inserted batch
  // it should be included in the nr of items sent so we can remove it after completion
  size_t items_in_batch = 0;
  {
    csi::spinlock::scoped_lock xxx(_spinlock);
    size_t remaining = _max_packet_size;
    {
      std::deque<tx_item> ::reverse_iterator cursor = _tx_queue.rbegin();
      while (cursor != _tx_queue.rend()) {
        size_t item_size = (*cursor).msg ? (*cursor).msg->size() : 0;
        if (remaining < item_size)
          break;
        ++items_in_batch;
        remaining -= item_size;
        if ((*cursor).msg)
          v.push_back((*cursor).msg);
        cursor++;
      }
      assert(_tx_queue.size() >= v.size());
    }
  }

  if (items_in_batch > 0) {
    //auto tick = boost::posix_time::microsec_clock::local_time();
    _client.send_produce_async(_topic, _partition_id, _required_acks, _tx_timeout, v, [this, items_in_batch](rpc_result<produce_response> result) {
      //auto now = boost::posix_time::microsec_clock::local_time();
      //boost::posix_time::time_duration diff = now - tick;
      //_metrics_tx_roundtrip((double) diff.total_milliseconds());

      if (result) {
        BOOST_LOG_TRIVIAL(error) << "kafka lowlevel_producer (" << _topic << ":" << _partition_id << ") _try_send send_produce_async failed, required acks: " << _required_acks << ", ec: " << csi::kafka::to_string(result.ec);
        _tx_in_progress = false;
        _client.close();
        //_try_send();
        return;
      }

      //TODO PARSE THE RESULT DEEP - WE MIGHT HAVE GOTTEN AN ERROR INSIDE
      //IF SO WE SHOULD PROBASBLY CLOSE THE CONNECTION
      for (std::vector<produce_response::topic_data>::const_iterator i = result->topics.begin(); i != result->topics.end(); ++i) {
        for (std::vector<produce_response::topic_data::partition_data>::const_iterator j = i->partitions.begin(); j != i->partitions.end(); ++j) {
        }
      }

      std::vector<tx_ack_callback> callbacks; // we cant run the callbacks when the spinlock is locked so copy those and run them after
      {
        csi::spinlock::scoped_lock xxx(_spinlock);
        {
          assert(_tx_queue.size() >= items_in_batch);
          size_t tx_size = 0;
          for (size_t i = 0; i != items_in_batch; ++i) {
            const tx_item& item = *(_tx_queue.end() - 1);
            if (item.msg) // we might have a callback marker (NULL message)
            {
              tx_size += item.msg->size();
              ++__metrics_total_tx_msg;
            }
            if (item.cb)
              callbacks.push_back(item.cb);
            _tx_queue.pop_back();
          }
          _tx_queue_byte_size -= tx_size;
          __metrics_total_tx_bytes += tx_size;
        }
      }
      for (std::vector<tx_ack_callback>::const_iterator i = callbacks.begin(); i != callbacks.end(); ++i)
        (*i)(0); // no error?

      _tx_in_progress = false; // here is a small gap where an external enqueu would trigger a post(_try_send()) - thus callinmg twice but it should be harmless
      _try_send();
    });
  } else {
    _tx_in_progress = false; // here is a small gap where an external enqueu would trigger a post(_try_send()) - thus callinmg twice but it should be harmless
  }
}
} // kafka
}; // csi

max_stars_repo_name: bitbouncer/csi-kafka

max_issues_repo_name: bitbouncer/csi-kafka

max_forks_repo_name: bitbouncer/csi-kafka


text:
/*
 *          Copyright Andrey Semashev 2007 - 2015.
 * Distributed under the Boost Software License, Version 1.0.
 *    (See accompanying file LICENSE_1_0.txt or copy at
 *          http://www.boost.org/LICENSE_1_0.txt)
 */
/*!
 * \file   attr_attribute_set_ticket11106.cpp
 * \author Andrey Semashev
 * \date   15.03.2015
 *
 * \brief  This header contains a test for the fix for https://svn.boost.org/trac/boost/ticket/11106.
 */

#define BOOST_TEST_MODULE attr_attribute_set_ticket11106

#include <string>
#include <sstream>
#include <utility>
#include <boost/test/unit_test.hpp>
#include <boost/log/attributes/constant.hpp>
#include <boost/log/attributes/attribute_set.hpp>

// The test checks that insertion does not invalidate existing elements in the container
BOOST_AUTO_TEST_CASE(ticket11106)
{
    boost::log::attribute_set set;

    unsigned int i = 0;
    while (i < 100)
    {
        std::ostringstream strm;
        strm << "Attr" << i;
        boost::log::attribute_name name = strm.str();

        std::pair< boost::log::attribute_set::iterator, bool > res = set.insert(name, boost::log::attributes::make_constant(5));
        ++i;

        BOOST_CHECK(res.second); // check that insertion succeeded
        BOOST_CHECK(set.find(res.first->first) != set.end()); // check that lookup works

        // Now check that all previously inserted elements are still findable
        unsigned int j = 0;
        for (boost::log::attribute_set::const_iterator it = set.begin(), end = set.end(); it != end; ++it, ++j)
        {
            boost::log::attribute_name key = it->first;
            BOOST_CHECK(set.find(key) != set.end());
        }
        BOOST_CHECK_EQUAL(j, i);
    }
}


text:
#define BOOST_TEST_MODULE COMMON_TEST
#include <boost/test/included/unit_test.hpp>
#include <../common-cpp/include/http.h>
BOOST_AUTO_TEST_CASE(movebycmd_test)
{
    try
    {

        common::movebycmd("test/common_test.cpp", "test/common_test.cpp/1");
        BOOST_FAIL("it should have failed,but not");
    }
    catch (const std::exception &e)
    {
        common::print_info(common::string_format("it's expect to failed:%s", e.what()));
    }
    BOOST_ASSERT(!std::filesystem::exists("test/common_test.cpp1"));
    common::movebycmd("test/common_test.cpp", "test/common_test.cpp${a}");
    BOOST_ASSERT(std::filesystem::exists("test/common_test.cpp${a}"));
    common::movebycmd("test/common_test.cpp${a}", "test/common_test.cpp");
    BOOST_ASSERT(!std::filesystem::exists("test/common_test.cpp${a}"));
    common::print_info("PASS");
}
BOOST_AUTO_TEST_CASE(free_test_function)
/* Compare with void free_test_function() */
{
    common::http_client c{"blog.swish-cloud.com", 443};
    for (int i = 0; i < 5; i++)
    {
        c.GET();
        common::print_info(c.error.message());
        common::print_info(c.resp_text);
#ifndef __linux__
        common::GetLastErrorMsg(NULL);
        bool res = !c.error && !c.resp_text.empty();
        if (!res)
        {
            BOOST_FAIL(c.error.message());
            return;
        }
#endif
    }
}

max_stars_repo_name: swishcloud/common-cpp

max_issues_repo_name: swishcloud/common-cpp

max_forks_repo_name: swishcloud/common-cpp


text:
#pragma once
#ifndef _FTL_RGBD_FRAME_HPP_
#define _FTL_RGBD_FRAME_HPP_

#include <ftl/configuration.hpp>
#include <ftl/exception.hpp>
#include <opencv2/core.hpp>
#include <opencv2/core/cuda.hpp>
#include <opencv2/core/cuda_stream_accessor.hpp>

#include <ftl/data/new_frame.hpp>

#include <ftl/codecs/channels.hpp>
#include <ftl/rgbd/format.hpp>
#include <ftl/rgbd/camera.hpp>
#include <ftl/codecs/codecs.hpp>
#include <ftl/codecs/packet.hpp>
#include <ftl/utility/vectorbuffer.hpp>
#include <ftl/cuda_common.hpp>
#include <ftl/rgbd/capabilities.hpp>

#include <type_traits>
#include <array>
#include <list>

#include <Eigen/Eigen>

namespace ftl {
namespace calibration {
struct CalibrationData;
}

namespace rgbd {

//typedef ftl::data::Frame Frame;

/*inline const ftl::rgbd::Camera &getLeftCamera(const Frame &f) { return f.get<ftl::rgbd::Camera>(ftl::codecs::Channel::Calibration); }
inline const ftl::rgbd::Camera &getRightCamera(const Frame &f) { return f.get<ftl::rgbd::Camera>(ftl::codecs::Channel::Calibration2); }
inline const ftl::rgbd::Camera &getLeft(const Frame &f) { return f.get<ftl::rgbd::Camera>(ftl::codecs::Channel::Calibration); }
inline const ftl::rgbd::Camera &getRight(const Frame &f) { return f.get<ftl::rgbd::Camera>(ftl::codecs::Channel::Calibration2); }
inline const Eigen::Matrix4d &getPose(const Frame &f) { return f.get<Eigen::Matrix4d>(ftl::codecs::Channel::Pose); }*/

class VideoFrame {
	public:
	VideoFrame() {}

	// Manually add copy constructor since default is removed
	VideoFrame(const VideoFrame &);
	VideoFrame &operator=(const VideoFrame &);

	template <typename T>
	ftl::cuda::TextureObject<T> &createTexture(const ftl::rgbd::Format<T> &f, bool interpolated);

	template <typename T>
	ftl::cuda::TextureObject<T> &createTexture(bool interpolated=false) const;

	cv::cuda::GpuMat &createGPU();
	cv::cuda::GpuMat &createGPU(const ftl::rgbd::FormatBase &f);

	template <typename T> ftl::cuda::TextureObject<T> &getTexture(ftl::codecs::Channel) const;

	cv::Mat &createCPU();
	cv::Mat &createCPU(const ftl::rgbd::FormatBase &f);

	const cv::Mat &getCPU() const;
	const cv::cuda::GpuMat &getGPU() const;

	/// gets cv::Mat for
	cv::Mat &setCPU();
	cv::cuda::GpuMat &setGPU();

	inline bool isGPU() const { return isgpu; };

	inline bool hasOpenGL() const { return opengl_id != 0; }
	inline void setOpenGL(unsigned int id) { opengl_id = id; }
	inline unsigned int getOpenGL() const { return opengl_id; }

	private:
	mutable ftl::cuda::TextureObjectBase tex;
	cv::cuda::GpuMat gpu;
	mutable cv::Mat host;
	unsigned int opengl_id=0;
	bool isgpu=false;
	mutable bool validhost=false;
};

class Frame : public ftl::data::Frame {
	public:
	const ftl::rgbd::Camera &getLeftCamera() const;
	const ftl::rgbd::Camera &getRightCamera() const;
	inline const ftl::rgbd::Camera &getLeft() const { return getLeftCamera(); }
	inline const ftl::rgbd::Camera &getRight() const { return getRightCamera(); }
	const Eigen::Matrix4d &getPose() const;
	ftl::rgbd::Camera &setLeft();
	ftl::rgbd::Camera &setRight();
	Eigen::Matrix4d &setPose();

	cv::Size getSize(ftl::codecs::Channel c=ftl::codecs::Channel::Left) const;

	ftl::calibration::CalibrationData& setCalibration();
	const ftl::calibration::CalibrationData& getCalibration() const;

	std::string serial() const;
	std::string device() const;

	/** Note, this throws exception if channel is missing */
	const std::unordered_set<ftl::rgbd::Capability> &capabilities() const;

	/** Does not throw exception */
	bool hasCapability(ftl::rgbd::Capability) const;

	inline bool isLive() const { return hasCapability(ftl::rgbd::Capability::LIVE); }
	inline bool isVirtual() const { return hasCapability(ftl::rgbd::Capability::VIRTUAL); }
	inline bool isMovable() const { return hasCapability(ftl::rgbd::Capability::MOVABLE); }
	inline bool isTouchable() const { return hasCapability(ftl::rgbd::Capability::TOUCH); }
	inline bool isVR() const { return hasCapability(ftl::rgbd::Capability::VR); }
	inline bool is360() const { return hasCapability(ftl::rgbd::Capability::EQUI_RECT); }
	inline bool isSideBySideStereo() const { return hasCapability(ftl::rgbd::Capability::STEREO); }

	void upload(ftl::codecs::Channel c);

	bool isGPU(ftl::codecs::Channel c) const;
	bool hasOpenGL(ftl::codecs::Channel c) const;
	unsigned int getOpenGL(ftl::codecs::Channel c) const;

	template <typename T>
	ftl::cuda::TextureObject<T> &getTexture(ftl::codecs::Channel c) { return this->get<VideoFrame>(c).getTexture<T>(c); }

	template <typename T>
	ftl::cuda::TextureObject<T> &createTexture(ftl::codecs::Channel c, bool interpolated=false) { return this->get<VideoFrame>(c).createTexture<T>(interpolated); }

	template <typename T>
	ftl::cuda::TextureObject<T> &createTexture(ftl::codecs::Channel c, const ftl::rgbd::Format<T> &fmt, bool interpolated=false) { return this->create<VideoFrame>(c).createTexture<T>(fmt, interpolated); }

};

template <typename T>
ftl::cuda::TextureObject<T> &VideoFrame::getTexture(ftl::codecs::Channel c) const {
	if (!isgpu) throw FTL_Error("Texture channel is not on GPU");

	if (tex.cvType() != ftl::traits::OpenCVType<T>::value || tex.width() != static_cast<size_t>(gpu.cols) || tex.height() != static_cast<size_t>(gpu.rows) || gpu.type() != tex.cvType()) {
		throw FTL_Error("Texture has not been created properly " << int(c));
	}

	return ftl::cuda::TextureObject<T>::cast(tex);
}

template <typename T>
ftl::cuda::TextureObject<T> &VideoFrame::createTexture(const ftl::rgbd::Format<T> &f, bool interpolated) {
	createGPU();

	if (f.empty()) {
		throw FTL_Error("createTexture needs a non-empty format");
	} else {
		gpu.create(f.size(), f.cvType);
	}

	if (gpu.type() != ftl::traits::OpenCVType<T>::value) {
		throw FTL_Error("Texture type mismatch: " << gpu.type() << " != " << ftl::traits::OpenCVType<T>::value);
	}

	// TODO: Check tex cvType

	if (tex.devicePtr() == nullptr) {
		//LOG(INFO) << "Creating texture object";
		tex = ftl::cuda::TextureObject<T>(gpu, interpolated);
	} else if (tex.cvType() != ftl::traits::OpenCVType<T>::value || tex.width() != static_cast<size_t>(gpu.cols) || tex.height() != static_cast<size_t>(gpu.rows)) {
		//LOG(INFO) << "Recreating texture object for '" << ftl::codecs::name(c) << "'";
		tex.free();
		tex = ftl::cuda::TextureObject<T>(gpu, interpolated);
	}

	return ftl::cuda::TextureObject<T>::cast(tex);
}

template <typename T>
ftl::cuda::TextureObject<T> &VideoFrame::createTexture(bool interpolated) const {
	if (!isgpu && !host.empty()) {
		//gpu.create(host.size(), host.type());
		// TODO: Should this upload to GPU or not?
		//gpu_ += c;
		throw FTL_Error("Cannot create a texture on a host frame");
	} else if (!isgpu || (isgpu && gpu.empty())) {
		throw FTL_Error("createTexture needs a format if no memory is allocated");
	}

	if (gpu.type() != ftl::traits::OpenCVType<T>::value) {
		throw FTL_Error("Texture type mismatch: " << gpu.type() << " != " << ftl::traits::OpenCVType<T>::value);
	}

	// TODO: Check tex cvType

	if (tex.devicePtr() == nullptr) {
		//LOG(INFO) << "Creating texture object";
		tex = ftl::cuda::TextureObject<T>(gpu, interpolated);
	} else if (tex.cvType() != ftl::traits::OpenCVType<T>::value || tex.width() != static_cast<size_t>(gpu.cols) || tex.height() != static_cast<size_t>(gpu.rows) || tex.devicePtr() != gpu.data) {
		//LOG(INFO) << "Recreating texture object for '" << ftl::codecs::name(c) << "'.";
		tex.free();
		tex = ftl::cuda::TextureObject<T>(gpu, interpolated);
	}

	return ftl::cuda::TextureObject<T>::cast(tex);
}

}
}

template <>
cv::Mat &ftl::data::Frame::create<cv::Mat, 0>(ftl::codecs::Channel c);

template <>
cv::cuda::GpuMat &ftl::data::Frame::create<cv::cuda::GpuMat, 0>(ftl::codecs::Channel c);

template <>
const cv::Mat &ftl::data::Frame::get<cv::Mat>(ftl::codecs::Channel c) const;

template <>
const cv::cuda::GpuMat &ftl::data::Frame::get<cv::cuda::GpuMat>(ftl::codecs::Channel c) const;

template <>
cv::Mat &ftl::data::Frame::set<cv::Mat, 0>(ftl::codecs::Channel c);

template <>
cv::cuda::GpuMat &ftl::data::Frame::set<cv::cuda::GpuMat, 0>(ftl::codecs::Channel c);

template <>
inline bool ftl::data::make_type<ftl::rgbd::VideoFrame>() {
	return false;
}

template <>
inline bool ftl::data::decode_type<ftl::rgbd::VideoFrame>(std::any &a, const std::vector<uint8_t> &data) {
	return false;
}

#endif // _FTL_RGBD_FRAME_HPP_

max_stars_repo_name: knicos/voltu

max_issues_repo_name: knicos/voltu

max_forks_repo_name: knicos/voltu


text:
// Copyright (c) 2013, Thomas Goyne <plorkyeran@aegisub.org>
//
// Permission to use, copy, modify, and distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
// OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
//
// Aegisub Project http://www.aegisub.org/

#include "config.h"

#include "video_provider_cache.h"

#include "options.h"
#include "video_frame.h"

#include <algorithm>
#include <boost/version.hpp>

#if BOOST_VERSION <= 105200
// Compilation fails without this with boost 1.52. I have no idea why.
static bool operator==(VideoFrame const& a, VideoFrame const& b) {
	return a.width == b.width
		&& a.height == b.height
		&& a.pitch == b.pitch
		&& a.flipped == b.flipped
		&& a.data == b.data;
}
#endif

/// A video frame and its frame number
struct CachedFrame : public VideoFrame {
	int frame_number;

	CachedFrame(int frame_number, VideoFrame const& frame)
	: VideoFrame(frame.data.data(), frame.width, frame.height, frame.pitch, frame.flipped)
	, frame_number(frame_number)
	{
	}
};

VideoProviderCache::VideoProviderCache(std::unique_ptr<VideoProvider> parent)
: master(std::move(parent))
, max_cache_size(OPT_GET("Provider/Video/Cache/Size")->GetInt() << 20) // convert MB to bytes
{
}

VideoProviderCache::~VideoProviderCache() {
}

std::shared_ptr<VideoFrame> VideoProviderCache::GetFrame(int n) {
	size_t total_size = 0;

	for (auto cur = cache.begin(); cur != cache.end(); ++cur) {
		if (cur->frame_number == n) {
			cache.splice(cache.begin(), cache, cur); // Move to front
			return std::make_shared<VideoFrame>(cache.front());
		}

		total_size += cur->data.size();
	}

	auto frame = master->GetFrame(n);

	if (total_size >= max_cache_size)
		cache.pop_back();
	cache.emplace_front(n, *frame);

	return frame;
}

max_stars_repo_name: rcombs/Aegisub

max_issues_repo_name: rcombs/Aegisub

max_forks_repo_name: rcombs/Aegisub


text:
#include "./../../header/tarjan.h"

//STL
#include <iostream>
#include <vector>
#include <string>
#include <fstream>
#include <sstream>
#include <iterator>
//Boost
#include <boost/config.hpp>
#include <boost/graph/adjacency_list.hpp>
#include <boost/graph/graphviz.hpp>
#include <boost/graph/graph_utility.hpp>
#include <boost/graph/adjacency_list_io.hpp>
#include <boost/graph/property_iter_range.hpp>
#include <boost/graph/copy.hpp>
#include <boost/property_map/property_map.hpp>

using namespace boost;

void Tarjan::print_graph(){
    GraphComponent::print_graph_file(t);
}

void Tarjan::ApplyDFS() {
    typedef boost::graph_traits<theGraph>::vertex_descriptor Vertex;
    v_p id = get(&VertexProperty::index, t);
    typedef boost::graph_traits<theGraph>::vertex_iterator vertex_iter;
    std::pair<vertex_iter, vertex_iter> vp;
    Vertex_t theFirst = *(vertices(t).first);
    int Counter = 0;
    int SizeOfGraph = num_vertices(t);
    std::vector<int> visited(SizeOfGraph,666);
    DepthFirstSearch(theFirst, Counter, visited);
    std::cout << "\nTarjan Depth First Search Exited Successfully." << std::endl;
    std::cout << "Discovery Order is: " << std::endl;
     for(vp=vertices(t); vp.first != vp.second; vp.first++){
        Vertex_t v = *vp.first;
        std::cout << "Node(" << id[v] << ") --> " << visited[id[v]] << std::endl;
    }

}

void Tarjan::DepthFirstSearch( Vertex_t &v, int &Counter,std::vector<int> &visited) {
    v_p id = get(&VertexProperty::index, t);
    e_p arch_type =get(&EdgeProperty::name, t);
    Counter++;
    visited[id[v]] = static_cast<unsigned long>(Counter);
 //   std::cout << "Node(" << id[v] << ") --> " << visited[id[v]] << std::endl;
    typedef boost::graph_traits<theGraph>::edge_descriptor Edge;
    boost::graph_traits<theGraph>::out_edge_iterator out_i, out_end;
    for (boost::tie(out_i, out_end) = out_edges(v, t); out_i != out_end; ++out_i) {
        Edge e = *out_i;
        Vertex_t w = target(e, t);
        if (visited[id[w]] == 666) {
            arch_type[e] = "forward";
            //std::cout << "Node(" <<id[w] << ") --> " << visited[w] << std::endl;
            DepthFirstSearch(w, Counter,visited);
        } else if (visited[id[w]] < visited[id[v]]) {
            arch_type[e] = "backward";
        }
    }
}

bool Tarjan::isReachable(Vertex_t &source, Vertex_t &Target) {
    typedef graph_traits<theGraph>::vertices_size_type size_type;
    size_type n_vertices;
    n_vertices = num_vertices(t);
    v_p id = get(&VertexProperty::index, t);
    std::vector<bool> Visited(n_vertices, false);
    std::deque<Vertex_t> Checks;
    Visited[id[source]] = true;
    Checks.push_back(source);
    while (!Checks.empty()) {
        Vertex_t v = Checks.front();
        Checks.pop_front();
        boost::graph_traits<theGraph>::out_edge_iterator out_i, out_end;
        for (boost::tie(out_i, out_end) = out_edges(v, t); out_i != out_end; ++out_i) {
            Vertex_t w = target(*out_i, t);
            if (id[w] == id[Target]) {
                return true;
            } else if (!Visited[id[w]]) {
                Visited[id[w]] = true;
                Checks.push_back(w);
            }
        }
    }
    return false;
}
UtilityStructs::StorageItems Tarjan::applyBiconnectivity(){
    float ms_duration = 0;
    v_p id = get(&VertexProperty::index, t);
    typedef boost::graph_traits<theGraph>::vertex_descriptor Vertex_t;
    typedef boost::graph_traits<theGraph>::edge_descriptor Edge_t;
    typedef boost::graph_traits<theGraph>::vertex_iterator vertex_iter;
    std::pair<vertex_iter, vertex_iter> vp;
    std::vector<Edge_t> edges;
    std::vector<std::vector<Edge_t> > components;
    int Counter = 0;
    int sizeOfGraph = num_vertices(t);
    std::vector<int> visited(sizeOfGraph,999999);
    std::vector<int> lowPt(sizeOfGraph,999999);
    int stackCount = 0;
    {
        UtilityStructs::Timer timer;
        for(vp = vertices(t); vp.first != vp.second; vp.first++){
            Vertex_t v = *vp.first;
            if(visited[id[v]] == 999999) {
                biconnect(v, edges, Counter,components, visited, lowPt, stackCount);
            }
        }
        ms_duration = timer.stop();
    }
    size_t total_bytes = 0;
    total_bytes += sizeof(visited[0]) * visited.size();
    total_bytes += sizeof(lowPt[0]) * lowPt.size();
    total_bytes +=sizeof(edges[0]) * stackCount;
    UtilityStructs::StorageItems s;
    s.vertexCount = num_vertices(t);
    s.edgeCount = num_edges(t);
    s.duration = ms_duration;
    s.total_bytes = total_bytes;

    return s;
}

void Tarjan::biconnect(Vertex_t &v,
                  std::vector<Edge_t> &edges,
                  int &Counter,
                  std::vector<std::vector<Edge_t> > &components,
                  std::vector<int> &visited,
                  std::vector<int> &lowPt,
                  int &stackCount){
    v_p id = get(&VertexProperty::index,t);
    Counter++;
    visited[id[v]] = Counter;
    lowPt[id[v]] = Counter;
    typedef boost::graph_traits<theGraph>::edge_descriptor Edge;
    boost::graph_traits<theGraph>::out_edge_iterator out_i, out_end;
    for( boost::tie(out_i,out_end) = out_edges(v,t); out_i != out_end; ++out_i){
        Edge e = *out_i;
        Vertex_t w = target(e,t);
        if(visited[id[w]] == 999999){
            edges.push_back(e);
            biconnect(w,edges,Counter,components, visited,lowPt,stackCount);
            lowPt[id[v]] = lowPt[id[v]] < lowPt[id[w]]?lowPt[id[v]]:lowPt[id[w]];
            if(lowPt[id[w]] > lowPt[id[v]]){
                std::vector<Edge_t> temp;
                std::vector<Edge_t>::iterator it;
                for(it = edges.begin();it != edges.end(); it++){
                    Edge e2 = *it;
                    Vertex_t w2 = target(e2,t);
                    if(visited[id[w2]] > visited[id[v]]){
                        temp.push_back(e2);
                        edges.erase(std::remove(edges.begin(), edges.end(), e2), edges.end());
                    }
                }
                temp.push_back(e);
                edges.erase(std::remove(edges.begin(), edges.end(), e), edges.end());
                components.push_back(temp);
            }
        }else if(visited[id[w]] < visited[id[v]] & w != v){
            edges.push_back(e);
            lowPt[id[v]] = lowPt[id[v]] < lowPt[id[w]]?lowPt[id[v]]:visited[id[w]];
        }
    }
}

UtilityStructs::StorageItems Tarjan::ApplySCC(bool debugMode) {
    float ms_duration = 0;
    v_p id = get(&VertexProperty::index, t);
    typedef boost::graph_traits<theGraph>::vertex_descriptor Vertex_t;
    typedef boost::graph_traits<theGraph>::vertex_iterator vertex_iter;
    std::pair<vertex_iter, vertex_iter> vp;
    std::vector<Vertex_t> Points;
    int Counter = 0;
    int SizeOfGraph = num_vertices(t);
    std::vector<int> visited(SizeOfGraph,999999);
    std::vector<int> lowPt(SizeOfGraph,999999);
    std::vector<int> lowVine(SizeOfGraph,999999);
    int stackCount = 0;
   // std::cout << "\nTarjan version of the SCC Algorithm has processed the graph" << std::endl;
    //TIMER
    {
        UtilityStructs::Timer timer;
    for (vp = vertices(t); vp.first != vp.second; vp.first++) {
        Vertex_t v = *vp.first;
        if (visited[id[v]] == 999999) {
            StrongConnect(v,Points, Counter,visited,lowPt,lowVine,stackCount,debugMode);
        }
    }
    ms_duration = timer.stop();
    }
    //TIMER end
    //Storage info collection
    size_t total_bytes = 0;
    total_bytes += sizeof(visited[0]) * visited.size();
    total_bytes += sizeof(lowPt[0]) * lowPt.size();
    total_bytes += sizeof(lowVine[0]) * lowVine.size();
    total_bytes +=sizeof(Points[0]) * stackCount;
    UtilityStructs::StorageItems s;
    s.vertexCount = num_vertices(t);
    s.edgeCount = num_edges(t);
    s.duration = ms_duration;
    s.total_bytes = total_bytes;
    Visualize vis;
    if(debugMode){
        vis.printProgramBottom();
         std::stringstream buffer3;
        buffer3 << std::setw(40) << std::left <<"Completion Time" ;
        buffer3 << ": " << s.duration << " miliseconds" ;
        std::stringstream buffer4;
        buffer4 << std::setw(40)<< std::left << "Total Execution Size";
        buffer4 << ": " << s.total_bytes / 1024.f << " KBs";
        vis.printLine(buffer3.str());
        vis.printLine(buffer4.str());
}
    return s;
}

void Tarjan::StrongConnect(Vertex_t &v,
                            std::vector<Vertex_t> &Points,
                            int &Counter,
                            std::vector<int> &visited,
                            std::vector<int> &lowPt,
                            std::vector<int> &lowVine,
                            int &stackCount,
                            bool debugMode) {
    e_p arch_type = get(&EdgeProperty::name, t);
    v_p id = get(&VertexProperty::index,t);
    Visualize vis;
    Counter++;
    visited[id[v]]= Counter;
    lowPt[id[v]]= Counter;
    lowVine[id[v]] = Counter;
    Points.push_back(v);
    stackCount++;
    typedef boost::graph_traits<theGraph>::edge_descriptor Edge;
    boost::graph_traits<theGraph>::out_edge_iterator out_i, out_end;
    for (boost::tie(out_i, out_end) = out_edges(v, t); out_i != out_end; ++out_i) {
        Edge e = *out_i;
        Vertex_t w = target(e, t);
        if (visited[id[w]] == 999999) {
            arch_type[e] = "tree"; // like in tarjan's algorithm
            StrongConnect(w,Points, Counter,visited,lowPt,lowVine,stackCount,debugMode);
            lowPt[id[v]] = lowPt[id[v]]< lowPt[id[w]]?lowPt[id[v]]:lowPt[id[w]];
            lowVine[id[v]] = lowVine[id[v]]< lowVine[id[w]]?lowVine[id[v]]:lowVine[id[w]];
        } else if (!isReachable( w, v)) {
            if (visited[id[w]] < visited[id[v]]) {
                arch_type[e] = "vine";
                if (std::find(Points.begin(), Points.end(), w) != Points.end()) {
                    lowVine[id[v]] = lowVine[id[v]] < visited[id[w]] ? lowVine[id[v]] : visited[id[w]];
                }
            }
        } else {
            arch_type[e] = "frond";
            lowPt[id[v]] = lowPt[id[v]] < visited[id[w]] ? lowPt[id[v]] : visited[id[w]];
        }
    }
    if (lowPt[id[v]] == visited[id[v]] && lowVine[id[v]] == visited[id[v]]) {
            int count_component = 0;
            std::stringstream buffer ;
            if(debugMode){
                vis.printLine("");
                buffer << std::setw(40) << std::left << "The Strongly Connected Component is" ;
                 buffer << ": ";
                 count_component++;
            }

        while(!Points.empty() && visited[id[Points.back()]] >= visited[id[v]]){
            Vertex_t x = Points.back();
            Points.pop_back();
            buffer << id[x]+1 <<  " " ;
        }
       if(debugMode){
        vis.printLine(buffer.str());
        std::stringstream buffer2;
        buffer2 << std::setw(40) << std::left << "Number of elements in the component is" ;
        buffer2 << ": "<< count_component ;
        vis.printLine(buffer2.str());
       }
    }

}


text:
#pragma once

#include <vector>
#include <string>
#include <array>
#include <algorithm>
#include <memory>
#include <boost/filesystem.hpp>
#include <boost/dll.hpp>

#include "ICardDetector.hpp"
#include "ContourFinder.hpp"
#include "CardIdentifier.hpp"
#include "PerspectiveCorrector.hpp"
#include "CardAssigner.hpp"
#include "ImProcSettings.hpp"
#include "DataDetect.hpp"
#include "Card.hpp"
#include "Image.hpp"
#include "IDetectionDataHandler.hpp"
#include "BufferManager.hpp"

namespace fs = boost::filesystem;

namespace detect
{
	/**
	 * \ingroup detection
	 * @class CardDetector
	 * @author Julian Massing (julimassing@gmail.com)
	 * @brief Detects Cards in the live image.
	 *
	 * @version 1.0
	 * @date 2020-11-21
	 *
	 * @copyright Copyright (c) 2020
	 *
	 */

	class CardDetector: public ICardDetector
	{
		private:
			enum Filter { LARGEST_AREA, SMALLEST_AREA, LE_AREA, GE_AREA };
			const int perspective_transform_offset_ = 5;
			// Parameters used for filtering Card Contours
			const int max_card_size_ = 500000;
			const int min_card_size_ = 8000;
			// Parameters for Card Image size.
			const int card_width_ = 301;
			const double card_aspect_ratio_ = 1.4;

			Image live_frame_;
			std::vector<Card> cards_;
			int frame_nr_;
			ImProcSettings settings_;
			std::unique_ptr<IDetectionDataHandler> data_handler_;
			PerspectiveCorrector perspective_corrector_;
			BufferManager buffer_manager_;

		public:

			DataDetect data_;
			int game_phase_;

			void detectCards() override;
			/**
			 * @brief Updates the frame that is being processed with current live frame
			 *
			 *
			 */
			void updateFrame() override;
			const std::vector<Card> getCards() override { return this->cards_; }
			void attachDataHandler(std::unique_ptr<IDetectionDataHandler> handler)
			{
				this->data_handler_.swap(handler);
			}
			int get_frame_nr()
			{
				return this->frame_nr_;
			}
			/**
			 * @brief Construct a new Card Detector object
			 *
			 * @param initial_settings Initial processing settings, e.g. binary thresholds etc.
			 */
			CardDetector(ImProcSettings& initial_settings):
			live_frame_{},
			cards_{},
			buffer_manager_{},
			frame_nr_(0),
			data_{},
			settings_(initial_settings),
			game_phase_{0},
			data_handler_{nullptr}
			{};
			~CardDetector(){};

			// Using default copy and move constructors.
			CardDetector(const CardDetector& other) = default;
			CardDetector& operator=(const CardDetector& other) = default;
			CardDetector(CardDetector&& other) noexcept = default;
			CardDetector& operator=(CardDetector&& other) noexcept = default;
	};
}//namespace detect

max_stars_repo_name: JMassing/Pokerbot

max_issues_repo_name: JMassing/Pokerbot

max_forks_repo_name: JMassing/Pokerbot


text:
/*=============================================================================
    Copyright (c) 2001-2011 Joel de Guzman

    Distributed under the Boost Software License, Version 1.0. (See accompanying
    file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
=============================================================================*/
#if !defined(SPIRIT_SEQUENTIAL_OR_MARCH_12_2007_1130PM)
#define SPIRIT_SEQUENTIAL_OR_MARCH_12_2007_1130PM

#if defined(_MSC_VER)
#pragma once
#endif

#include <boost/fusion/include/as_vector.hpp>
#include <boost/fusion/include/for_each.hpp>
#include <boost/spirit/home/qi/detail/attributes.hpp>
#include <boost/spirit/home/qi/detail/pass_function.hpp>
#include <boost/spirit/home/qi/meta_compiler.hpp>
#include <boost/spirit/home/support/algorithm/any_if_ns_so.hpp>
#include <boost/spirit/home/support/detail/what_function.hpp>
#include <boost/spirit/home/support/handles_container.hpp>

namespace boost {
namespace spirit {
///////////////////////////////////////////////////////////////////////////
// Enablers
///////////////////////////////////////////////////////////////////////////
template <>
struct use_operator<qi::domain, proto::tag::logical_or> // enables ||
    : mpl::true_ {};

template <>
struct flatten_tree<qi::domain, proto::tag::logical_or> // flattens ||
    : mpl::true_ {};
} // namespace spirit
} // namespace boost

namespace boost {
namespace spirit {
namespace qi {
template <typename Elements>
struct sequential_or : nary_parser<sequential_or<Elements>> {
  template <typename Context, typename Iterator> struct attribute {
    // Put all the element attributes in a tuple,
    // wrapping each element in a boost::optional
    typedef typename traits::build_attribute_sequence<
        Elements, Context, traits::sequential_or_attribute_transform, Iterator,
        qi::domain>::type all_attributes;

    // Now, build a fusion vector over the attributes. Note
    // that build_fusion_vector 1) removes all unused attributes
    // and 2) may return unused_type if all elements have
    // unused_type(s).
    typedef typename traits::build_fusion_vector<all_attributes>::type type;
  };

  sequential_or(Elements const &elements_) : elements(elements_) {}

  template <typename Iterator, typename Context, typename Skipper,
            typename Attribute>
  bool parse(Iterator &first, Iterator const &last, Context &context,
             Skipper const &skipper, Attribute &attr_) const {
    typedef traits::attribute_not_unused<Context, Iterator> predicate;
    detail::pass_function<Iterator, Context, Skipper> f(first, last, context,
                                                        skipper);

    // wrap the attribute in a tuple if it is not a tuple
    typename traits::wrap_if_not_tuple<Attribute>::type attr_local(attr_);

    // return true if *any* of the parsers succeed
    // (we use the non-short-circuiting and strict order version:
    // any_if_ns_so to force all the elements to be tested and
    // in the defined order: first is first, last is last)
    return spirit::any_if_ns_so(elements, attr_local, f, predicate());
  }

  template <typename Context> info what(Context &context) const {
    info result("sequential-or");
    fusion::for_each(elements,
                     spirit::detail::what_function<Context>(result, context));
    return result;
  }

  Elements elements;
};

///////////////////////////////////////////////////////////////////////////
// Parser generators: make_xxx function (objects)
///////////////////////////////////////////////////////////////////////////
template <typename Elements, typename Modifiers>
struct make_composite<proto::tag::logical_or, Elements, Modifiers>
    : make_nary_composite<Elements, sequential_or> {};
} // namespace qi
} // namespace spirit
} // namespace boost

namespace boost {
namespace spirit {
namespace traits {
///////////////////////////////////////////////////////////////////////////
// We specialize this for sequential_or (see support/attributes.hpp).
// For sequential_or, we only wrap the attribute in a tuple IFF
// it is not already a fusion tuple.
template <typename Elements, typename Attribute>
struct pass_attribute<qi::sequential_or<Elements>, Attribute>
    : wrap_if_not_tuple<Attribute> {};

///////////////////////////////////////////////////////////////////////////
template <typename Elements>
struct has_semantic_action<qi::sequential_or<Elements>>
    : nary_has_semantic_action<Elements> {};

///////////////////////////////////////////////////////////////////////////
template <typename Elements, typename Attribute, typename Context,
          typename Iterator>
struct handles_container<qi::sequential_or<Elements>, Attribute, Context,
                         Iterator>
    : nary_handles_container<Elements, Attribute, Context, Iterator> {};
} // namespace traits
} // namespace spirit
} // namespace boost

#endif

max_stars_repo_name: henrywarhurst/matrix

max_issues_repo_name: henrywarhurst/matrix

max_forks_repo_name: henrywarhurst/matrix


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

#if defined(HAVE_CONFIG_H)
#include "config/bitcoin-config.h"
#endif

#include "chainparamsbase.h"
#include "clientversion.h"
#include "fs.h"
#include "rpc/client.h"
#include "rpc/protocol.h"
#include "sync.h"
#include "util.h"
#include "utilstrencodings.h"

#include <stdio.h>

#include <event2/buffer.h>
#include <event2/event.h>
#include <event2/http.h>
#include <event2/keyvalq_struct.h>

#include <univalue.h>

using namespace std;

#ifdef DEBUG_LOCKORDER
#include <boost/thread/tss.hpp>
// BU add lockstack stuff here for bitcoin-cli, because I need to carefully
// order it in globals.cpp for bitcoind and bitcoin-qt
boost::mutex dd_mutex;
std::map<std::pair<void *, void *>, LockStack> lockorders;
boost::thread_specific_ptr<LockStack> lockstack;
#endif

int CommandLineRPC(int argc, char *argv[])
{
    string strPrint;
    int nRet = 0;
    try
    {
        // Skip switches
        while (argc > 1 && IsSwitchChar(argv[1][0]))
        {
            argc--;
            argv++;
        }
        std::vector<std::string> args = std::vector<std::string>(&argv[1], &argv[argc]);
        if (GetBoolArg("-stdin", false))
        {
            // Read one arg per line from stdin and append
            std::string line;
            while (std::getline(std::cin, line))
                args.push_back(line);
        }
        if (args.size() < 1)
            throw runtime_error("too few parameters (need at least command)");
        std::string strMethod = args[0];
        UniValue params(UniValue::VARR);
        for (unsigned int idx = 1; idx < args.size(); idx++)
        {
            const std::string &strVal = args[idx];
            params.push_back(strVal);
        }

        // Execute and handle connection failures with -rpcwait
        const bool fWait = GetBoolArg("-rpcwait", false);
        do
        {
            try
            {
                const UniValue reply = CallRPC(strMethod, params);

                // Parse reply
                const UniValue &result = find_value(reply, "result");
                const UniValue &error = find_value(reply, "error");

                if (!error.isNull())
                {
                    // Error
                    int code = error["code"].get_int();
                    if (fWait && code == RPC_IN_WARMUP)
                        throw CConnectionFailed("server in warmup");
                    strPrint = "error: " + error.write();
                    nRet = abs(code);
                    if (error.isObject())
                    {
                        UniValue errCode = find_value(error, "code");
                        UniValue errMsg = find_value(error, "message");
                        strPrint = errCode.isNull() ? "" : "error code: " + errCode.getValStr() + "\n";

                        if (errMsg.isStr())
                            strPrint += "error message:\n" + errMsg.get_str();
                    }
                }
                else
                {
                    // Result
                    if (result.isNull())
                        strPrint = "";
                    else if (result.isStr())
                        strPrint = result.get_str();
                    else
                        strPrint = result.write(2);
                }
                // Connection succeeded, no need to retry.
                break;
            }
            catch (const CConnectionFailed &)
            {
                if (fWait)
                    MilliSleep(1000);
                else
                    throw;
            }
        } while (fWait);
    }
    catch (const boost::thread_interrupted &)
    {
        throw;
    }
    catch (const std::exception &e)
    {
        strPrint = string("error: ") + e.what();
        nRet = EXIT_FAILURE;
    }
    catch (...)
    {
        PrintExceptionContinue(nullptr, "CommandLineRPC()");
        throw;
    }

    if (strPrint != "")
    {
        fprintf((nRet == 0 ? stdout : stderr), "%s\n", strPrint.c_str());
    }
    return nRet;
}

int main(int argc, char *argv[])
{
    SetupEnvironment();
    if (!SetupNetworking())
    {
        fprintf(stderr, "Error: Initializing networking failed\n");
        exit(1);
    }

    try
    {
        std::string appname("bitcoin-cli");
        std::string usage = "\n" + _("Usage:") + "\n" + "  " + appname + " [options] " +
                            strprintf(_("Send command to %s"), _(PACKAGE_NAME)) + "\n" + "  " + appname +
                            " [options] help                " + _("List commands") + "\n" + "  " + appname +
                            " [options] help <command>      " + _("Get help for a command") + "\n";

        int ret = AppInitRPC(usage, AllowedArgs::BitcoinCli(), argc, argv);
        if (ret != CONTINUE_EXECUTION)
            return ret;
    }
    catch (const std::exception &e)
    {
        PrintExceptionContinue(&e, "AppInitRPC()");
        return EXIT_FAILURE;
    }
    catch (...)
    {
        PrintExceptionContinue(nullptr, "AppInitRPC()");
        return EXIT_FAILURE;
    }

    int ret = EXIT_FAILURE;
    try
    {
        ret = CommandLineRPC(argc, argv);
    }
    catch (const std::exception &e)
    {
        PrintExceptionContinue(&e, "CommandLineRPC()");
    }
    catch (...)
    {
        PrintExceptionContinue(nullptr, "CommandLineRPC()");
    }
    return ret;
}

max_stars_repo_name: cculianu/BitcoinUnlimited

max_issues_repo_name: cculianu/BitcoinUnlimited

max_forks_repo_name: cculianu/BitcoinUnlimited


text:
// Copyright (c) by respective owners including Yahoo!, Microsoft, and
// individual contributors. All rights reserved. Released under a BSD (revised)
// license as described in the file LICENSE.

#include <boost/test/unit_test.hpp>
#include <boost/test/test_tools.hpp>

#include "test_common.h"

#include <vector>
#include "parser/flatbuffer/parse_example_flatbuffer.h"
#include "constant.h"
#include "feature_group.h"

flatbuffers::Offset<void> get_label(flatbuffers::FlatBufferBuilder& builder, VW::parsers::flatbuffer::Label label_type)
{
  flatbuffers::Offset<void> label;
  if (label_type == VW::parsers::flatbuffer::Label_SimpleLabel)
    label = VW::parsers::flatbuffer::CreateSimpleLabel(builder, 0.0, 1.0).Union();

  return label;
}

flatbuffers::Offset<VW::parsers::flatbuffer::ExampleRoot> sample_flatbuffer_collection(
    flatbuffers::FlatBufferBuilder& builder, VW::parsers::flatbuffer::Label label_type)
{
  std::vector<flatbuffers::Offset<VW::parsers::flatbuffer::Example>> examples;
  std::vector<flatbuffers::Offset<VW::parsers::flatbuffer::Namespace>> namespaces;
  std::vector<flatbuffers::Offset<VW::parsers::flatbuffer::Feature>> fts;

  auto label = get_label(builder, label_type);

  fts.push_back(VW::parsers::flatbuffer::CreateFeatureDirect(builder, "hello", 2.23f, constant));
  namespaces.push_back(VW::parsers::flatbuffer::CreateNamespaceDirect(builder, nullptr, constant_namespace, &fts, 128));
  examples.push_back(VW::parsers::flatbuffer::CreateExampleDirect(builder, &namespaces, label_type, label));

  auto eg_collection = VW::parsers::flatbuffer::CreateExampleCollectionDirect(builder, &examples);
  return CreateExampleRoot(builder, VW::parsers::flatbuffer::ExampleType_ExampleCollection, eg_collection.Union());
}

flatbuffers::Offset<VW::parsers::flatbuffer::ExampleRoot> sample_flatbuffer(
    flatbuffers::FlatBufferBuilder& builder, VW::parsers::flatbuffer::Label label_type)
{
  std::vector<flatbuffers::Offset<VW::parsers::flatbuffer::Namespace>> namespaces;
  std::vector<flatbuffers::Offset<VW::parsers::flatbuffer::Feature>> fts;

  auto label = get_label(builder, label_type);

  fts.push_back(VW::parsers::flatbuffer::CreateFeatureDirect(builder, "hello", 2.23f, constant));
  namespaces.push_back(VW::parsers::flatbuffer::CreateNamespaceDirect(builder, nullptr, constant_namespace, &fts, 128));
  auto example = VW::parsers::flatbuffer::CreateExampleDirect(builder, &namespaces, label_type, label);

  return CreateExampleRoot(builder, VW::parsers::flatbuffer::ExampleType_Example, example.Union());
}

BOOST_AUTO_TEST_CASE(test_flatbuffer_standalone_example)
{
  auto all = VW::initialize("--no_stdin --quiet --flatbuffer", nullptr, false, nullptr, nullptr);

  flatbuffers::FlatBufferBuilder builder;

  auto root = sample_flatbuffer(builder, VW::parsers::flatbuffer::Label_SimpleLabel);
  builder.FinishSizePrefixed(root);

  uint8_t* buf = builder.GetBufferPointer();
  int size = builder.GetSize();

  VW::v_array<example*> examples;
  examples.push_back(&VW::get_unused_example(all));
  io_buf unused_buffer;
  all->flat_converter->parse_examples(all, unused_buffer, examples, buf);

  auto example = all->flat_converter->data()->example_obj_as_Example();
  BOOST_CHECK_EQUAL(example->namespaces()->size(), 1);
  BOOST_CHECK_EQUAL(example->namespaces()->Get(0)->features()->size(), 1);
  BOOST_CHECK_CLOSE(example->label_as_SimpleLabel()->label(), 0.0, FLOAT_TOL);
  BOOST_CHECK_CLOSE(example->label_as_SimpleLabel()->weight(), 1.0, FLOAT_TOL);
  BOOST_CHECK_EQUAL(example->namespaces()->Get(0)->hash(), constant_namespace);
  BOOST_CHECK_EQUAL(example->namespaces()->Get(0)->full_hash(), constant_namespace);
  BOOST_CHECK_EQUAL(example->namespaces()->Get(0)->features()->Get(0)->name()->c_str(), "hello");
  BOOST_CHECK_EQUAL(example->namespaces()->Get(0)->features()->Get(0)->hash(), constant);
  BOOST_CHECK_CLOSE(example->namespaces()->Get(0)->features()->Get(0)->value(), 2.23, FLOAT_TOL);

  // Check vw example
  BOOST_CHECK_EQUAL(examples.size(), 1);
  BOOST_CHECK_CLOSE(examples[0]->l.simple.label, 0.f, FLOAT_TOL);
  const auto& red_features = examples[0]->_reduction_features.template get<simple_label_reduction_features>();
  BOOST_CHECK_CLOSE(red_features.weight, 1.f, FLOAT_TOL);

  BOOST_CHECK_EQUAL(examples[0]->indices[0], constant_namespace);
  BOOST_CHECK_CLOSE(examples[0]->feature_space[examples[0]->indices[0]].values[0], 2.23f, FLOAT_TOL);
  BOOST_CHECK_EQUAL(examples[0]->feature_space[examples[0]->indices[0]].namespace_extents.size(), 1);
  BOOST_CHECK_EQUAL(examples[0]->feature_space[examples[0]->indices[0]].namespace_extents[0],
      (VW::namespace_extent{0, 1, constant_namespace}));

  VW::finish_example(*all, *examples[0]);
  VW::finish(*all);
}

BOOST_AUTO_TEST_CASE(test_flatbuffer_collection)
{
  auto all = VW::initialize("--no_stdin --quiet --flatbuffer", nullptr, false, nullptr, nullptr);

  flatbuffers::FlatBufferBuilder builder;

  auto root = sample_flatbuffer_collection(builder, VW::parsers::flatbuffer::Label_SimpleLabel);
  builder.FinishSizePrefixed(root);

  uint8_t* buf = builder.GetBufferPointer();
  int size = builder.GetSize();

  VW::v_array<example*> examples;
  examples.push_back(&VW::get_unused_example(all));
  io_buf unused_buffer;
  all->flat_converter->parse_examples(all, unused_buffer, examples, buf);

  auto collection_examples = all->flat_converter->data()->example_obj_as_ExampleCollection()->examples();
  BOOST_CHECK_EQUAL(collection_examples->size(), 1);
  BOOST_CHECK_EQUAL(collection_examples->Get(0)->namespaces()->size(), 1);
  BOOST_CHECK_EQUAL(collection_examples->Get(0)->namespaces()->Get(0)->features()->size(), 1);
  BOOST_CHECK_CLOSE(collection_examples->Get(0)->label_as_SimpleLabel()->label(), 0.0, FLOAT_TOL);
  BOOST_CHECK_CLOSE(collection_examples->Get(0)->label_as_SimpleLabel()->weight(), 1.0, FLOAT_TOL);
  BOOST_CHECK_EQUAL(collection_examples->Get(0)->namespaces()->Get(0)->hash(), constant_namespace);
  BOOST_CHECK_EQUAL(collection_examples->Get(0)->namespaces()->Get(0)->full_hash(), constant_namespace);
  BOOST_CHECK_EQUAL(collection_examples->Get(0)->namespaces()->Get(0)->features()->Get(0)->name()->c_str(), "hello");
  BOOST_CHECK_EQUAL(collection_examples->Get(0)->namespaces()->Get(0)->features()->Get(0)->hash(), constant);
  BOOST_CHECK_CLOSE(collection_examples->Get(0)->namespaces()->Get(0)->features()->Get(0)->value(), 2.23, FLOAT_TOL);

  // check vw example
  BOOST_CHECK_EQUAL(examples.size(), 1);
  BOOST_CHECK_CLOSE(examples[0]->l.simple.label, 0.f, FLOAT_TOL);
  const auto& red_features = examples[0]->_reduction_features.template get<simple_label_reduction_features>();
  BOOST_CHECK_CLOSE(red_features.weight, 1.f, FLOAT_TOL);

  BOOST_CHECK_EQUAL(examples[0]->indices[0], constant_namespace);
  BOOST_CHECK_CLOSE(examples[0]->feature_space[examples[0]->indices[0]].values[0], 2.23f, FLOAT_TOL);
  BOOST_CHECK_EQUAL(examples[0]->feature_space[examples[0]->indices[0]].namespace_extents.size(), 1);
  BOOST_CHECK_EQUAL(examples[0]->feature_space[examples[0]->indices[0]].namespace_extents[0],
      (VW::namespace_extent{0, 1, constant_namespace}));

  VW::finish_example(*all, *examples[0]);
  VW::finish(*all);
}


text:
//
// Created by christoph on 04.06.19.
//

#define _FILE_OFFSET_BITS 64

#include <cstdio>
#include <boost/algorithm/string/case_conv.hpp>
#include <boost/algorithm/string/predicate.hpp>
#include <Utils/File/Logfile.hpp>
#include <Math/Geometry/AABB3.hpp>
#include <Utils/Events/Stream/Stream.hpp>
#include "NetCDFConverter.hpp"
#include "TrajectoryFile.hpp"
#include <iostream>

Trajectories loadTrajectoriesFromFile(const std::string &filename, TrajectoryType trajectoryType)
{
    Trajectories trajectories;

    std::string lowerCaseFilename = boost::to_lower_copy(filename);
    if (boost::ends_with(lowerCaseFilename, ".obj")) {
        trajectories = loadTrajectoriesFromObj(filename, trajectoryType);
    } else if (boost::ends_with(lowerCaseFilename, ".nc")) {
        trajectories = loadTrajectoriesFromNetCdf(filename, trajectoryType);
    } else if (boost::ends_with(lowerCaseFilename, ".binlines")) {
        trajectories = loadTrajectoriesFromBinLines(filename, trajectoryType);
    }

    sgl::AABB3 boundingBox;
    for (Trajectory &trajectory : trajectories) {
        for (glm::vec3 &position : trajectory.positions) {
            boundingBox.combine(position);
        }
    }

    bool isConvectionRolls = trajectoryType == TRAJECTORY_TYPE_CONVECTION_ROLLS_NEW;
    bool isUCLA = trajectoryType == TRAJECTORY_TYPE_UCLA;
    bool isRings = trajectoryType == TRAJECTORY_TYPE_RINGS;
    bool isCfdData = trajectoryType == TRAJECTORY_TYPE_CFD;

    glm::vec3 minVec(boundingBox.getMinimum());
    glm::vec3 maxVec(boundingBox.getMaximum());

    float minAttr = std::numeric_limits<float>::max();
    float maxAttr = std::numeric_limits<float>::lowest();

    if (isConvectionRolls) {
        minVec = glm::vec3(0);
        maxVec = glm::vec3(0.5);
    } else if (isUCLA)
    {
        minVec = glm::vec3(glm::min(boundingBox.getMinimum().x, std::min(boundingBox.getMinimum().y, boundingBox.getMinimum().z)));
        maxVec = glm::vec3(glm::max(boundingBox.getMaximum().x, std::max(boundingBox.getMaximum().y, boundingBox.getMaximum().z)));

        for(const Trajectory& traj : trajectories)
        {
            for (const float& attr : traj.attributes[0])
            {
                minAttr = std::min(minAttr, attr);
                maxAttr = std::max(maxAttr, attr);
            }
        }

    } else {
        // Normalize data for rings
        float minValue = glm::min(boundingBox.getMinimum().x, std::min(boundingBox.getMinimum().y, boundingBox.getMinimum().z));
        float maxValue = glm::max(boundingBox.getMaximum().x, std::max(boundingBox.getMaximum().y, boundingBox.getMaximum().z));
        minVec = glm::vec3(minValue);
        maxVec = glm::vec3(maxValue);
    }

    if (isRings || isConvectionRolls || isCfdData || isUCLA) {
        for (Trajectory &trajectory : trajectories) {
            for (glm::vec3 &position : trajectory.positions) {
                position = (position - minVec) / (maxVec - minVec);
                if (isConvectionRolls || isCfdData) {
                    glm::vec3 dims = glm::vec3(1);
                    dims.y = boundingBox.getDimensions().y;
                    position -= dims;
                }
            }
        }
    }

    // if UCLA --> normalize attributes
    if (isUCLA)
    {
        for(Trajectory& traj : trajectories)
        {
            for (float& attr : traj.attributes[0])
            {
                attr = (attr - minAttr) / (maxAttr - minAttr);
            }
        }
    }

    return trajectories;
}

Trajectories loadTrajectoriesFromObj(const std::string &filename, TrajectoryType trajectoryType)
{
    bool isConvectionRolls = trajectoryType == TRAJECTORY_TYPE_CONVECTION_ROLLS_NEW;
    bool isRings = trajectoryType == TRAJECTORY_TYPE_RINGS;
    bool isUCLA = trajectoryType == TRAJECTORY_TYPE_UCLA;
    Trajectories trajectories;

    std::vector<glm::vec3> globalLineVertices;
    std::vector<float> globalLineVertexAttributes;

    FILE *file = fopen64(filename.c_str(), "r");
    if (!file) {
        sgl::Logfile::get()->writeError(std::string() + "Error in convertObjTrajectoryDataToBinaryLineMesh: File \""
                                        + filename + "\" does not exist.");
        return trajectories;
    }
#if defined(_WIN32) && !defined(__MINGW32__)
    _fseeki64(file, 0, SEEK_END);
    size_t length = _ftelli64(file);
    _fseeki64(file, 0, SEEK_SET);
#else
    fseeko(file, 0, SEEK_END);
    size_t length = ftello(file);
    fseeko(file, 0, SEEK_SET);
#endif

    char *fileBuffer = new char[length];
    fread(fileBuffer, 1, length, file);
    fclose(file);
    std::string lineBuffer;
    std::string numberString;

    for (size_t charPtr = 0; charPtr < length; ) {
        while (charPtr < length) {
            char currentChar = fileBuffer[charPtr];
            if (currentChar == '\n' || currentChar == '\r') {
                charPtr++;
                break;
            }
            lineBuffer.push_back(currentChar);
            charPtr++;
        }

        if (lineBuffer.size() == 0) {
            continue;
        }

        char command = lineBuffer.at(0);
        char command2 = ' ';
        if (lineBuffer.size() > 1) {
            command2 = lineBuffer.at(1);
        }

        if (command == 'g') {
            // New path
            /*static int ctr = 0;
            if (ctr >= 999) {
                Logfile::get()->writeInfo(std::string() + "Parsing trajectory line group " + line.at(1) + "...");
            }
            ctr = (ctr + 1) % 1000;*/
        } else if (command == 'v' && command2 == 't') {
            // Path line vertex attribute
            float attr = 0.0f;
            sscanf(lineBuffer.c_str()+2, "%f", &attr);
            globalLineVertexAttributes.push_back(attr);
        } else if (command == 'v' && command2 == 'n') {
            // Not supported so far
        } else if (command == 'v') {
            // Path line vertex position
            glm::vec3 position;
            if (isUCLA)
            {
                sscanf(lineBuffer.c_str()+2, "%f %f %f", &position.x, &position.y, &position.z);
            }
            else if (isConvectionRolls) {
                sscanf(lineBuffer.c_str()+2, "%f %f %f", &position.x, &position.z, &position.y);
            } else {
                sscanf(lineBuffer.c_str()+2, "%f %f %f", &position.x, &position.y, &position.z);
            }
            globalLineVertices.push_back(position);
        } else if (command == 'l') {
            // Get indices of current path line
            std::vector<uint32_t> currentLineIndices;
            for (size_t linePtr = 2; linePtr < lineBuffer.size(); linePtr++) {
                char currentChar = lineBuffer.at(linePtr);
                bool isWhitespace = currentChar == ' ' || currentChar == '\t';
                if (isWhitespace && numberString.size() != 0) {
                    currentLineIndices.push_back(atoi(numberString.c_str()) - 1);
                    numberString.clear();
                } else if (!isWhitespace) {
                    numberString.push_back(currentChar);
                }
            }
            if (numberString.size() != 0) {
                currentLineIndices.push_back(atoi(numberString.c_str()) - 1);
                numberString.clear();
            }

            Trajectory trajectory;

            std::vector<float> pathLineVorticities;
            trajectory.positions.reserve(currentLineIndices.size());
            pathLineVorticities.reserve(currentLineIndices.size());
            for (size_t i = 0; i < currentLineIndices.size(); i++) {
                glm::vec3 pos = globalLineVertices.at(currentLineIndices.at(i));

                // Remove invalid line points (used in many scientific datasets to indicate invalid lines).
                const float MAX_VAL = 1e10f;
                if (std::fabs(pos.x) > MAX_VAL || std::fabs(pos.y) > MAX_VAL || std::fabs(pos.z) > MAX_VAL) {
                    continue;
                }

                trajectory.positions.push_back(globalLineVertices.at(currentLineIndices.at(i)));
                pathLineVorticities.push_back(globalLineVertexAttributes.at(currentLineIndices.at(i)));
            }

            // Compute importance criteria
            computeTrajectoryAttributes(
                    trajectoryType, trajectory.positions, pathLineVorticities, trajectory.attributes);

            // Line filtering for WCB trajectories
            //if (trajectoryType == TRAJECTORY_TYPE_WCB) {
            //  if (importanceCriteriaIn.at(3).size() > 0 && importanceCriteriaIn.at(3).at(0) < 500.0f) {
            //      continue;
            //  }
            //}

            trajectories.push_back(trajectory);
        } else if (command = '#') {
            // Ignore comments
        } else {
            //Logfile::get()->writeError(std::string() + "Error in parseObjMesh: Unknown command \"" + command + "\".");
        }

        lineBuffer.clear();
    }

    // compute byte size of raw representation with 1 attribute for paper
    uint64_t byteSize = 0;
    for (const auto& traj : trajectories)
    {
        byteSize += traj.positions.size() * sizeof(float) * 3;
        byteSize += traj.attributes[0].size() * sizeof(float);
    }

    byteSize = byteSize / 1024 / 1024;
    std::cout << "Raw byte size of obj file: " << byteSize << "MB" << std::endl << std::flush;

    return trajectories;
}

Trajectories loadTrajectoriesFromNetCdf(const std::string &filename, TrajectoryType trajectoryType) {
    Trajectories trajectories = loadNetCdfFile(filename);

    for (Trajectory &trajectory : trajectories) {
        // Compute importance criteria
        std::vector<float> oldAttributes = trajectory.attributes.at(0);
        trajectory.attributes.clear();
        computeTrajectoryAttributes(
                trajectoryType, trajectory.positions, oldAttributes, trajectory.attributes);
    }

    return trajectories;
}

Trajectories loadTrajectoriesFromBinLines(const std::string &filename, TrajectoryType trajectoryType) {
    Trajectories trajectories;

    std::ifstream file(filename.c_str(), std::ifstream::binary);
    if (!file.is_open()) {
        sgl::Logfile::get()->writeError(std::string() + "Error in loadTrajectoriesFromBinLines: File \""
                + filename + "\" not found.");
        return trajectories;
    }

    file.seekg(0, file.end);
    size_t size = file.tellg();
    file.seekg(0);
    char *buffer = new char[size];
    file.read(buffer, size);

    // Read format version
    sgl::BinaryReadStream stream(buffer, size);
    const uint32_t LINE_FILE_FORMAT_VERSION = 1u;
    uint32_t versionNumber;
    stream.read(versionNumber);
    if (versionNumber != LINE_FILE_FORMAT_VERSION) {
        sgl::Logfile::get()->writeError(std::string()
                + "Error in loadTrajectoriesFromBinLines: Invalid magic number in file \"" + filename + "\".");
        return trajectories;
    }

    // Rest of header after format version
    uint32_t numTrajectories, numAttributes, trajectoryNumPoints;
    stream.read(numTrajectories);
    stream.read(numAttributes);
    trajectories.resize(numTrajectories);

    for (uint32_t trajectoryIndex = 0; trajectoryIndex < numTrajectories; trajectoryIndex++) {
        Trajectory &currentTrajectory = trajectories.at(trajectoryIndex);
        stream.read(trajectoryNumPoints);
        currentTrajectory.positions.resize(trajectoryNumPoints);
        stream.read((void*)&currentTrajectory.positions.front(), sizeof(glm::vec3)*trajectoryNumPoints);
        currentTrajectory.attributes.resize(numAttributes);
        for (uint32_t attributeIndex = 0; attributeIndex < numAttributes; attributeIndex++) {
            std::vector<float> &currentAttribute = currentTrajectory.attributes.at(attributeIndex);
            currentAttribute.resize(trajectoryNumPoints);
            stream.read((void*)&currentAttribute.front(), sizeof(float)*trajectoryNumPoints);
        }
    }

    return trajectories;
}

max_stars_repo_name: chrismile/PixelSyncOIT

max_issues_repo_name: chrismile/PixelSyncOIT

max_forks_repo_name: chrismile/PixelSyncOIT


text:
#define BOOST_TEST_MODULE CsvWriteImplTestSuite
#define BOOST_TEST_DYN_LINK

#include <boost/test/included/unit_test.hpp>
#include <Eigen/Core>
#include <hops/hops.hpp>

BOOST_AUTO_TEST_SUITE(CsvWriterImpl)

    BOOST_AUTO_TEST_CASE( writeInts) {
        std::vector<int> data{-525, 0, 35};
        std::string expectedOutput = "-525\n0\n35\n";

        std::ostringstream actualOutput;
        hops::internal::CsvWriterImpl::writeOneDimensionalRecords(actualOutput, data);

        BOOST_CHECK(actualOutput.str() == expectedOutput);
    }

    BOOST_AUTO_TEST_CASE( writeLongs) {
        std::vector<long> data{-525, 0, 35};
        std::string expectedOutput = "-525\n0\n35\n";

        std::ostringstream actualOutput;
        hops::internal::CsvWriterImpl::writeOneDimensionalRecords(actualOutput, data);

        BOOST_CHECK(actualOutput.str() == expectedOutput);
    }

    BOOST_AUTO_TEST_CASE( writeFloats) {
        std::vector<float> data{1.25f, 5.513f, 8.35f};
        std::string expectedOutput = "1.25\n5.513\n8.35\n";

        std::ostringstream actualOutput;
        hops::internal::CsvWriterImpl::writeOneDimensionalRecords(actualOutput, data);

        BOOST_CHECK(actualOutput.str() == expectedOutput);
    }

    BOOST_AUTO_TEST_CASE( writeDoubles) {
        std::vector<double> data{1.25, 5.513, 8.35};
        std::string expectedOutput = "1.25\n5.513\n8.35\n";

        std::ostringstream actualOutput;
        hops::internal::CsvWriterImpl::writeOneDimensionalRecords(actualOutput, data);

        BOOST_CHECK(actualOutput.str() == expectedOutput);
    }

    BOOST_AUTO_TEST_CASE( writeStrings) {
        std::vector<std::string> data{"test1", "test2"};
        std::string expectedOutput = "test1\ntest2\n";

        std::ostringstream actualOutput;
        hops::internal::CsvWriterImpl::writeOneDimensionalRecords(actualOutput, data);

        BOOST_CHECK(actualOutput.str() == expectedOutput);
    }

    BOOST_AUTO_TEST_CASE( writeEigenFloatVectors) {
        std::vector<Eigen::VectorXf> data;
        Eigen::VectorXf v1(3);
        v1 << 1.1f,5.6f,3.14f;
        data.emplace_back(v1);
        Eigen::VectorXf v2(1);
        v2 << -1.1f;
        data.emplace_back(v2);
        std::string expectedOutput = "1.1,5.6,3.14\n-1.1\n";

        std::ostringstream actualOutput;
        hops::internal::CsvWriterImpl::writeEigenVectorRecords(actualOutput, data);

        BOOST_CHECK(actualOutput.str() == expectedOutput);
    }

    BOOST_AUTO_TEST_CASE( writeEigenDoubleVectors) {
        std::vector<Eigen::VectorXd> data;
        Eigen::VectorXd v1(3);
        v1 << 1.1,5.6,3.14;
        data.emplace_back(v1);
        Eigen::VectorXd v2(1);
        v2 << -1.1;
        data.emplace_back(v2);
        std::string expectedOutput = "1.1,5.6,3.14\n-1.1\n";

        std::ostringstream actualOutput;
        hops::internal::CsvWriterImpl::writeEigenVectorRecords(actualOutput, data);

        BOOST_CHECK(actualOutput.str() == expectedOutput);
    }

BOOST_AUTO_TEST_SUITE_END()

max_stars_repo_name: modsim/hops

max_issues_repo_name: modsim/hops

max_forks_repo_name: modsim/hops


text:
// Copyright: 2014 Steven Lamerton
// License: MIT, see LICENSE

#include <boost/filesystem.hpp>
#include "callbacks.h"

void Callbacks::InclusionDirective(
    clang::SourceLocation hash_loc,
    const clang::Token&,
    llvm::StringRef,
    bool,
    clang::CharSourceRange,
    const clang::FileEntry*,
    llvm::StringRef search_path,
    llvm::StringRef relative_path,
    const clang::Module*) {
  if (pp_.getSourceManager().getFileCharacteristic(hash_loc) ==
      clang::SrcMgr::C_User) {
    // Normalise the file paths before adding the relationship
    llvm::StringRef current_file_ref =
        pp_.getSourceManager().getFilename(hash_loc);
    boost::filesystem::path current_file(
        current_file_ref.begin(),
        current_file_ref.end());

    boost::filesystem::path included_file(std::string(search_path) +
        "/" + std::string(relative_path));

    map_generator_->AddInclusion(std::make_pair(
        boost::filesystem::canonical(current_file).string(),
        boost::filesystem::canonical(included_file).string()));
  }
}

void Callbacks::FileChanged(
      clang::SourceLocation loc,
      clang::PPCallbacks::FileChangeReason,
      clang::SrcMgr::CharacteristicKind file_type,
      clang::FileID) {
  if (file_type != clang::SrcMgr::CharacteristicKind::C_User) {
    llvm::StringRef loc_ref = pp_.getSourceManager().getFilename(loc);
    boost::filesystem::path current_file(
        loc_ref.begin(),
        loc_ref.end());
    map_generator_->AddSystemFile(
        boost::filesystem::canonical(current_file).string());
  }
}

Consumer::Consumer(
    clang::Preprocessor &pp,
    std::shared_ptr<MapGenerator> map_generator) {
  pp.addPPCallbacks(llvm::make_unique<Callbacks>(pp, map_generator));
}

std::unique_ptr<clang::ASTConsumer> Action::CreateASTConsumer(
    clang::CompilerInstance &ci,
    llvm::StringRef) {
  return llvm::make_unique<Consumer>(ci.getPreprocessor(), map_generator_);
}

Action* FrontendActionFactory::create() {
  return new Action(map_generator_);
}

max_stars_repo_name: sjlamerton/inclusion-mapper

max_issues_repo_name: steve-lamerton/inclusion-mapper

max_forks_repo_name: steve-lamerton/inclusion-mapper


text:
/**
 *  @copyright Copyright 2019 The J-PET Framework Authors. All rights reserved.
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may find a copy of the License in the LICENCE file.
 *
 *  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.
 *
 *  @file JPetUnpackTaskTest.cpp
 */

#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE JPetUnpackTaskTest

#include "JPetOptionsGenerator/JPetOptionsGeneratorTools.h"
#include "JPetUnpackTask/JPetUnpackTask.h"
#include <boost/test/unit_test.hpp>
#include <boost/filesystem.hpp>

BOOST_AUTO_TEST_SUITE(UnpackTaskSuite)

BOOST_AUTO_TEST_CASE(wrong_init_test)
{
  std::string fileNameWithPath = "bla.hld";
  std::string xmlConfig = "bli.xml";
  std::string totCalib = "blu.root";
  std::string tdcCalib = "blo.root";

  BOOST_REQUIRE(!JPetUnpackTask::validateFiles(
    fileNameWithPath,  xmlConfig, totCalib, true, tdcCalib, true
  ));
}

BOOST_AUTO_TEST_CASE(no_calib_init_test)
{
  std::string fileNameWithPath = "unitTestData/JPetUnpackerTest/xx14099113231.hld";
  std::string xmlConfig = "unitTestData/JPetUnpackerTest/conf_trb3.xml";
  std::string totCalib = "blu.root";
  std::string tdcCalib = "blo.root";

  BOOST_REQUIRE(JPetUnpackTask::validateFiles(
    fileNameWithPath,  xmlConfig, totCalib, false, tdcCalib, false
  ));
}

BOOST_AUTO_TEST_CASE(good_init_test)
{
  std::string fileNameWithPath = "unitTestData/JPetUnpackerTest/xx14099113231.hld";
  std::string xmlConfig = "unitTestData/JPetUnpackerTest/conf_trb3.xml";
  std::string totCalib = "unitTestData/JPetUnpackerTest/calib.root";
  std::string tdcCalib = "unitTestData/JPetUnpackerTest/tdccalib.root";

  BOOST_REQUIRE(JPetUnpackTask::validateFiles(
    fileNameWithPath,  xmlConfig, totCalib, true, tdcCalib, true
  ));
}

BOOST_AUTO_TEST_SUITE_END()

max_stars_repo_name: BlurredChoise/j-pet-framework

max_issues_repo_name: BlurredChoise/j-pet-framework

max_forks_repo_name: BlurredChoise/j-pet-framework


text:
#include <boost/optional/optional_io.hpp>

#include "nmea.h"

// define custom stream operators

// first a helper: a custom manipulator for skipping commas
std::istream& comma(std::istream& is) {
    char ch;
    is >> ch;
    if (ch != ',') {
        is.setstate(std::ios_base::failbit);
    }
    return is;
}

std::istream&
operator>>(std::istream& is, gga_t& g) {
    using namespace std;

    // define some temporaries
    char ch;
    string str;

    // a failure in one of the operator>> execution will cause all later ones to fail
    // so we don't need to do early exits

    while (!is.fail() && str.length() < 6) {
        is >> ch;
        str += ch;
    }
    if (str != "$GPGGA") {
        is.setstate(ios_base::failbit);
    }
    comma(is);

    is >> g.timestamp >> comma >> g.latitude >> comma;

    is >> g.lat_hemi;
    if ((g.lat_hemi != 'N') && (g.lat_hemi != 'S')) {
        is.setstate(ios_base::failbit);
    }
    comma(is);

    is >> g.longitude >> comma;

    is >> g.long_hemi;
    if ((g.long_hemi != 'E') && (g.long_hemi != 'W')) {
        is.setstate(ios_base::failbit);
    }
    comma(is);

    is >> g.quality >> comma >> g.sat_count >> comma >> g.dilution >> comma >> g.altitude >> comma;
    is >> g.alt_units >> comma >> g.sea_level >> comma >> g.sea_level_units >> comma;

    // handle optional values
    if (is.peek() != ',') {
        is >> g.time_since_dgps;
    }
    comma(is);

    if (is.peek() != ',') {
        is >> g.dgps_station_id;
    }
    comma(is);

    is >> ch;
    if (ch != '*') {
        is.setstate(ios_base::failbit);
    }
    is >> g.checksum;

    return is;
}

std::ostream& operator<<(std::ostream& os, gga_t const& g) {
    os << '(' << g.latitude << g.lat_hemi << ',' << g.longitude << g.long_hemi << ')';
    return os;
}

max_stars_repo_name: jefftrull/SequencesFromStreams

max_issues_repo_name: jefftrull/SequencesFromStreams

max_forks_repo_name: jefftrull/SequencesFromStreams