text:
/*
 * File:   UCKneeIdentifier.cpp
 * Author: Cara Higgins
 *
 * Created on 20 October 2021, 16:12
 */

#include "UCKneeIdentifier.h"

#include <climits>

#include <boost/bind.hpp>

#include <common/partitionforests/images/GeneralFeature.h>
#include <common/dicom/volumes/DICOMVolume.h>
#include <common/util/ITKImageUtil.h>

namespace mp {

    //#################### CONSTRUCTORS ####################

    UCKneeIdentifier::UCKneeIdentifier(const DICOMVolume_CPtr& dicomVolume, const VolumeIPF_Ptr& volumeIPF)
    : FeatureIdentifier(dicomVolume, volumeIPF) {
    }

    //#################### PUBLIC METHODS ####################

    int UCKneeIdentifier::length() const {
        return 5;
    }

    //#################### PRIVATE METHODS ####################

    std::tuple<std::list<PFNodeID>, int> ucknee;

    // /**
    // @brief	Select region of interest (ROI) by setting window minima and maxima

    // @param[in]	volumeSize	    [x width, y height, z count]
    // @param[in]  distFromEdge    User-selected parameter indicating the minimum distance a node must be from the edge;
    //                             prevents selection of border nodes, which often have very bright values
    // @param[in]  windMinX        Pointer to an integer variable representing the minimum x-value for the ROI
    // @param[in]  windMinY
    // @param[in]  windMaxX
    // @param[in]  windMaxY
    // */
    // void selectROI(itk::Size<3> volumeSize, int distFromEdge, int* windMinX, int* windMinY, int* windMaxX, int* windMaxY) {
    //     int width = volumeSize[0];
    //     int height = volumeSize[1];
    //     float htow = height * 1.0 / width;

    //     *windMinY = distFromEdge;
    //     *windMinX = distFromEdge;
    //     *windMaxX = width-distFromEdge;
    //     *windMaxY = height-distFromEdge;

    //     // TODO: check that distFromEdge <= width / 4, height / 4
    //     // Determine region of focus based on image size
    //     if (0.75 < htow && htow < 1.5) { // Roughly square
    //         *windMinX = width / 4;
    //         *windMaxX = width * 3 / 4;

    //         *windMinY = height / 4;
    //         *windMaxY = height * 3 / 4;
    //     } else if (htow > 1.5) {
    //         *windMinY = height / 4;
    //         *windMaxY = height * 3 / 4;
    //     } else {
    //         *windMinX = width / 4;
    //         *windMaxX = width * 3 / 4;
    //     }

    //     std::cout<<"Height to weight ratio: "<<htow<<std::endl;
    //     std::cout<<"image (height x width) = "<<height<<" x "<<width<<std::endl;
    //     std::cout<<"window = ("<<*windMinX<<", "<<*windMinY<<") -> ("<<*windMaxX<<", "<<*windMaxY<<")"<<std::endl;
    // }

    void UCKneeIdentifier::execute_impl() {
        set_status("Identifying unicompartmental knee...");
        std::cout<<"OnMenuSegmentationSegmentUCKnee reached."<<std::endl;

        int windMinX, windMinY, windMaxX, windMaxY;
        // TODO: only call if ROI is not already initialized
        selectROI(dicom_volume()->size(), 10, &windMinX, &windMinY, &windMaxX, &windMaxY);

        std::vector<int> node_indices = volume_ipf()->node_indices(layerIndex);
        std::cout<<"Nodes in layer "<<layerIndex<<" = "<<node_indices.size()<<std::endl;

        std::tuple<std::list<PFNodeID>, int> nodesWithMaxMeanGray = max_mean_grey_with_filter(
            node_indices, windMinX, windMinY, windMaxX, windMaxY
        );

        std::list<PFNodeID> nodes = std::get<0>(nodesWithMaxMeanGray);
        int maxMeanGrey = std::get<1>(nodesWithMaxMeanGray);

        int threshold = maxMeanGrey - 20;

        std::list<component> connectedComps = connected_components(nodes, threshold);
        connectedComps.sort(compare_components);    // Sort connected components by voxel count

        // Initialize region to store unicompartmental knee nodes
        PartitionForestSelection_Ptr filledRegion(new PartitionForestSelectionT(volume_ipf()));

        // Select the two largest components and set the ucknee variable accordingly
        for (int i = 0; i < 2 && !connectedComps.empty(); i++) {
            component comp = connectedComps.front();
            connectedComps.pop_front();

            std::set<PFNodeID> compNodes(std::get<0>(comp).begin(), std::get<0>(comp).end());

            std::cout<<"calling merge_nonsibling_nodes"<<std::endl;
            compNodes = volume_ipf()->merge_nonsibling_nodes(compNodes, volume_ipf()->CheckPreconditions::CHECK_PRECONDITIONS);
            std::cout<<"merge_nonsibling_nodes executed"<<std::endl;
            PFNodeID compNode = *compNodes.begin();
            // PFNodeID compNode = volume_ipf()->merge_sibling_nodes(compNodes, volume_ipf()->CheckPreconditions::CHECK_PRECONDITIONS);

            ucknee.push_back(compNode);
            filledRegion->select_node(compNode);
        }

        VolumeIPFMultiFeatureSelection_Ptr multiFeatureSelection = get_multi_feature_selection();
        multiFeatureSelection->identify_selection(filledRegion, GeneralFeature::UC_KNEE);
        std::cout<<"Selected top 2 connected components"<<std::endl;
        get_bounding_boxes();
    }

    /**
    @brief	Compares two components based on their associated voxel count.

    @param[in]	first	The first component
    @param[in]  second  The second component

    @return	true if first has a voxel count greater than that of the second component.
    */
    bool UCKneeIdentifier::compare_components(const std::tuple<std::list<PFNodeID>, int>& first, const std::tuple<std::list<PFNodeID>, int>& second)
    {
        return std::get<1>(first) > std::get<1>(second);
    }

    /**
    @brief	Prints the bounding boxes for the two components of the UC knee prosthesis
    */
    void UCKneeIdentifier::get_bounding_boxes()
    {
        for (std::list<PFNodeID>::iterator it = ucknee.begin(); it != ucknee.end(); it++) {
            propertyMap propMap = volume_ipf()->branch_properties(*it).branch_property_map();

            int MinX = std::stoi(propMap.at("X Min"));
            int MinY = std::stoi(propMap.at("Y Min"));
            int MaxX = std::stoi(propMap.at("X Max"));
            int MaxY = std::stoi(propMap.at("Y Max"));

            std::cout<<"Bounding box: ("<<MinX<<", "<<MinY<<") -> ("<<MaxX<<", "<<MaxY<<")"<<std::endl;
        }
    }

    // std::tuple<std::list<PFNodeID>, int> UCKneeIdentifier::max_mean_grey_with_filter(
    //     std::vector<int> node_indices,
    //     int windMinX, int windMinY, int windMaxX, int windMaxY
    // ) {
    //     int meanGrey; int VoxelCount; int MinX; int MinY; int MaxX; int MaxY;
    //     int maxMeanGrey = 0;
    //     std::list<PFNodeID> nodes;

    //     for(std::vector<int>::iterator indexIt = node_indices.begin(); indexIt != node_indices.end(); indexIt++)
    //     {
    //         PFNodeID node = PFNodeID(layerIndex, *indexIt);
    //         propertyMap propMap = volume_ipf()->branch_properties(node).branch_property_map();

    //         meanGrey = std::stof(propMap.at("Mean Grey Value"));
    //         VoxelCount = std::stoi(propMap.at("Voxel Count"));
    //         MinX = std::stoi(propMap.at("X Min"));
    //         MinY = std::stoi(propMap.at("Y Min"));
    //         MaxX = std::stoi(propMap.at("X Max"));
    //         MaxY = std::stoi(propMap.at("Y Max"));

    //         if (
    //             VoxelCount <= 15000 && VoxelCount >= 10 && // Node must contain between 100 and 15,000 voxels
    //             windMinX < MinX && MinX < windMaxX && windMinY < MinY && MinY < windMaxY // Region lies within region of interest (not touching edges)
    //         ) {
    //             nodes.push_back(node);  // Add node to list of filtered nodes

    //             if (meanGrey > maxMeanGrey)
    //                 maxMeanGrey = meanGrey;
    //         }
    //     }

    //     std::cout<<"Max Mean Grey Value = "<<maxMeanGrey<<std::endl;

    //     return std::tuple<std::list<PFNodeID>, int>(nodes, maxMeanGrey);
    // }

    std::list<UCKneeIdentifier::component> UCKneeIdentifier::connected_components(std::list<PFNodeID> nodes, int threshold)
    {
        std::list<component> connectedComps;

        for (std::list<PFNodeID>::iterator it = nodes.begin(); it != nodes.end(); it++) {
            propertyMap propMap = volume_ipf()->branch_properties(*it).branch_property_map();
            int meanGrey = std::stof(propMap.at("Mean Grey Value"));

            if (meanGrey > threshold) { // Check that mean grey value is above the specified threshold
                PFNodeID node = *it;
                component* nodeAddedTo = nullptr; // Pointer to the component the node has been added to

                // Obtain set of adjacent nodes
                std::vector<int> adjNodes = volume_ipf()->adjacent_nodes(node);
                std::set<int> adjNodeSet(adjNodes.begin(), adjNodes.end());

                // Iterate through connected components
                for (std::list<component>::iterator compIt = connectedComps.begin(); compIt != connectedComps.end(); compIt++) {
                    std::list<PFNodeID> compNodes = std::get<0>(*compIt);

                    std::cout<<connectedComps.size()<<" connected components; "<<compNodes.size()<<" nodes in this"<<std::endl;

                    // TODO: use are_connected function
                    // Convert compNodes to a set of node indices
                    std::set<int> nodes;
                    for (std::list<PFNodeID>::iterator nodeIt = compNodes.begin(); nodeIt != compNodes.end(); nodeIt++) {
                        nodes.insert(nodeIt->index());
                    }

                    // Check if the node is adjacent to the component
                    if (volume_ipf()->are_connected(nodes, layerIndex)) {
                        std::cout<<"Connected"<<std::endl;
                        if (!nodeAddedTo) {
                            // If new node is adjacent to the component and hasn't been added to another component,
                            // add it to this component & update voxel count
                            compNodes.push_back(node);
                            std::get<0>(*compIt) = compNodes;
                            std::get<1>(*compIt) += std::stoi(propMap.at("Voxel Count"));
                            nodeAddedTo = &(*compIt);
                            std::cout<<"Node added to existing component."<<std::endl;
                        } else {
                            // Node has already been added to another component, but is also adjacent to this
                            // component, so the components should be merged
                            std::list<PFNodeID> nodeAddedToList = std::get<0>(*nodeAddedTo);
                            nodeAddedToList.splice(nodeAddedToList.begin(), compNodes);
                            std::get<0>(*nodeAddedTo) = nodeAddedToList;
                            std::get<1>(*nodeAddedTo) += std::get<1>(*compIt);

                            // Preserve compIt after erasing component
                            connectedComps.erase(compIt++); // Remove old component, after merging
                            compIt--;
                            std::cout<<"Merging components."<<std::endl;
                        }
                    }
                } // End connected component iteration

                if (!nodeAddedTo) { // If node not adjacent to any connected component, add singleton to connected components
                    component newComp = component(std::list<PFNodeID>(1, node), std::stoi(propMap.at("Voxel Count")));
                    connectedComps.push_back(newComp);
                    std::cout<<"Node added as a singleton component."<<std::endl;
                }
            }
        } // End node iteration

        return connectedComps;
    }

    UCKneeIdentifier::BranchProperties UCKneeIdentifier::calculate_component_properties(int layer, const std::set<int>& indices) const
    {
        std::vector<BranchProperties> nodeProperties;
        nodeProperties.reserve(indices.size());
        for(std::set<int>::const_iterator it=indices.begin(), iend=indices.end(); it!=iend; ++it)
        {
            PFNodeID node(layer, *it);
            nodeProperties.push_back(volume_ipf()->branch_properties(node));
        }
        return BranchProperties::combine_branch_properties(nodeProperties);
    }

    // std::set<PFNodeID> decompose_ucknee()
    // {

    //     // return split_node(const PFNodeID& node, const std::vector<std::set<int> >& groups, CheckPreconditions checkPreconditions = CHECK_PRECONDITIONS)
    // }
}

max_stars_repo_name: cxhiggins/rl-segmentation

max_issues_repo_name: cxhiggins/rl-segmentation

max_forks_repo_name: cxhiggins/rl-segmentation


text:
/*
 * Copyright © 2013 Canonical Ltd.
 *
 * This program is free software: you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License version 3,
 * as published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 * Authored by: Thomas Voß <thomas.voss@canonical.com>
 */

#include <core/posix/child_process.h>

#ifndef ANDROID
#include <boost/iostreams/device/file_descriptor.hpp>
#include <boost/iostreams/stream.hpp>
#endif

#include <atomic>
#include <fstream>
#include <mutex>
#include <unordered_map>

#include <fcntl.h>
#include <poll.h>
#include <unistd.h>

#include <sys/eventfd.h>
#include <sys/signalfd.h>

#include <assert.h>

#include <sys/wait.h>

#ifndef ANDROID
namespace io = boost::iostreams;
#endif

namespace
{

struct DeathObserverImpl : public core::posix::ChildProcess::DeathObserver
{
    DeathObserverImpl(const std::shared_ptr<core::posix::SignalTrap>& trap)
        : on_sig_child_connection
          {
              trap->signal_raised().connect([this](core::posix::Signal signal)
              {
                  switch (signal)
                  {
                  case core::posix::Signal::sig_chld:
                    on_sig_child();
                    break;
                  default:
                    break;
                  }
              })
          }
    {
        if (!trap->has(core::posix::Signal::sig_chld))
            throw std::logic_error(
                    "DeathObserver::DeathObserverImpl: Given SignalTrap"
                    " instance does not trap Signal::sig_chld.");
    }

    bool add(const core::posix::ChildProcess& process) override
    {
        if (process.pid() == -1)
            return false;

        std::lock_guard<std::mutex> lg(guard);

        bool added = false;
        auto new_process = std::make_pair(process.pid(), process);
        std::tie(std::ignore, added) = children.insert(new_process);

        if (added)
        {
            // The process may have died between it's instantiation and it
            // being added to the children map. Check that it's still alive.
            int status{-1};
            if (::waitpid(process.pid(), &status, WNOHANG) != 0) // child no longer alive
            {
                // we missed the SIGCHLD signal so we must now manually
                // inform our subscribers.
                signals.child_died(new_process.second);
                children.erase(new_process.first);
                return false;
            }
        }

        return added;
    }

    bool has(const core::posix::ChildProcess& process) const override
    {
        std::lock_guard<std::mutex> lg(guard);
        return children.count(process.pid()) > 0;
    }

    const core::Signal<core::posix::ChildProcess>& child_died() const override
    {
        return signals.child_died;
    }

    void on_sig_child() override
    {
        pid_t pid{-1}; int status{-1};
        while (true)
        {
            pid = ::waitpid(0, &status, WNOHANG);

            if (pid == -1)
            {
                if (errno == ECHILD)
                {
                    break; // No more children
                }
                continue; // Ignore stray SIGCHLD signals
            }
            else if (pid == 0)
            {
                break; // No more children
            }
            else
            {
                std::lock_guard<std::mutex> lg(guard);
                auto it = children.find(pid);

                if (it != children.end())
                {
                    if (WIFSIGNALED(status) || WIFEXITED(status))
                    {
                        signals.child_died(it->second);
                        children.erase(it);
                    }
                }
            }
        }
    }

    mutable std::mutex guard;
    std::unordered_map<pid_t, core::posix::ChildProcess> children;
    core::ScopedConnection on_sig_child_connection;
    struct
    {
        core::Signal<core::posix::ChildProcess> child_died;
    } signals;
};
}

std::unique_ptr<core::posix::ChildProcess::DeathObserver>
core::posix::ChildProcess::DeathObserver::create_once_with_signal_trap(
        std::shared_ptr<core::posix::SignalTrap> trap)
{
    static std::atomic<bool> has_been_created_once{false};

    if (has_been_created_once.exchange(true))
        throw std::runtime_error
        {
            "DeathObserver::create_once_with_signal_trap: "
            "Cannot create more than one instance."
        };

    try
    {
        std::unique_ptr<core::posix::ChildProcess::DeathObserver> result
        {
            new DeathObserverImpl{trap}
        };

        return result;
    } catch(...)
    {
        // We make sure that a throwing c'tor does not impact our ability to
        // retry creation of a DeathObserver instance.
        has_been_created_once.store(false);

        std::rethrow_exception(std::current_exception());
    }

    assert(false && "We should never reach here.");

    // Silence the compiler.
    return std::unique_ptr<core::posix::ChildProcess::DeathObserver>{};
}

namespace core
{
namespace posix
{
ChildProcess::Pipe ChildProcess::Pipe::invalid()
{
    static Pipe p;
    static std::once_flag flag;

    std::call_once(flag, [&]() { p.close_read_fd(); p.close_write_fd(); });

    return p;
}

ChildProcess::Pipe::Pipe()
{
    int rc = ::pipe(fds);

    if (rc == -1)
        throw std::system_error(errno, std::system_category());
}

ChildProcess::Pipe::Pipe(const ChildProcess::Pipe& rhs) : fds{-1, -1}
{
    if (rhs.fds[0] != -1)
        fds[0] = ::dup(rhs.fds[0]);

    if (rhs.fds[1] != -1)
        fds[1] = ::dup(rhs.fds[1]);
}

ChildProcess::Pipe::~Pipe()
{
    if (fds[0] != -1)
        ::close(fds[0]);
    if (fds[1] != -1)
        ::close(fds[1]);
}

int ChildProcess::Pipe::read_fd() const
{
    return fds[0];
}

void ChildProcess::Pipe::close_read_fd()
{
    if (fds[0] != -1)
    {
        ::close(fds[0]);
        fds[0] = -1;
    }
}

int ChildProcess::Pipe::write_fd() const
{
    return fds[1];
}

void ChildProcess::Pipe::close_write_fd()
{
    if (fds[1] != -1)
    {
        ::close(fds[1]);
        fds[1] = -1;
    }
}

ChildProcess::Pipe& ChildProcess::Pipe::operator=(const ChildProcess::Pipe& rhs)
{
    if (fds[0] != -1)
        ::close(fds[0]);
    if (fds[1] != -1)
        ::close(fds[1]);

    if (rhs.fds[0] != -1)
        fds[0] = ::dup(rhs.fds[0]);
    else
        fds[0] = -1;
    if (rhs.fds[1] != -1)
        fds[1] = ::dup(rhs.fds[1]);
    else
        fds[1] = -1;

    return *this;
}

struct ChildProcess::Private
{
    // stdin and stdout are always "relative" to the childprocess, i.e., we
    // write to stdin of the child process and read from its stdout.
    Private(pid_t pid,
            const ChildProcess::Pipe& stderr,
            const ChildProcess::Pipe& stdin,
            const ChildProcess::Pipe& stdout)
        : pipes{stderr, stdin, stdout},
#ifndef ANDROID
          serr(pipes.stderr.read_fd(), io::never_close_handle),
          sin(pipes.stdin.write_fd(), io::never_close_handle),
          sout(pipes.stdout.read_fd(), io::never_close_handle),
          cerr(&serr),
          cin(&sin),
          cout(&sout),
#endif
          original_parent_pid(::getpid()),
          original_child_pid(pid)
    {
    }

    ~Private()
    {
        // Check if we are in the original parent process.
        if (original_parent_pid == getpid() && !dont_kill_on_cleanup)
        {
            // If so, check if we are considering a valid pid here.
            // If so, we kill the original child.
            if (original_child_pid != -1)
                ::kill(original_child_pid, SIGKILL);
        }
    }

    struct
    {
        ChildProcess::Pipe stdin;
        ChildProcess::Pipe stdout;
        ChildProcess::Pipe stderr;
    } pipes;

#ifndef ANDROID
    io::stream_buffer<io::file_descriptor_source> serr;
    io::stream_buffer<io::file_descriptor_sink> sin;
    io::stream_buffer<io::file_descriptor_source> sout;
    std::istream cerr;
    std::ostream cin;
    std::istream cout;
#endif

    // We need to store the original parent pid as we might have been forked
    // and with our automatic cleanup in place, it might happen that the d'tor
    // is called from the child process.
    pid_t original_parent_pid;
    pid_t original_child_pid;

    bool dont_kill_on_cleanup = false;
};

ChildProcess ChildProcess::invalid()
{
    // We take the init process as child.
    static const pid_t invalid_pid = 1;
    return ChildProcess(invalid_pid, Pipe::invalid(), Pipe::invalid(), Pipe::invalid());
}

ChildProcess::ChildProcess(pid_t pid,
                           const ChildProcess::Pipe& stdin_pipe,
                           const ChildProcess::Pipe& stdout_pipe,
                           const ChildProcess::Pipe& stderr_pipe)
    : Process(pid),
      d(new Private{pid, stdin_pipe, stdout_pipe, stderr_pipe})
{
}

ChildProcess::~ChildProcess()
{
}

wait::Result ChildProcess::wait_for(const wait::Flags& flags)
{
    int status = -1;
    pid_t result_pid = ::waitpid(pid(), std::addressof(status), static_cast<int>(flags));

    if (result_pid == -1)
        throw std::system_error(errno, std::system_category());

    wait::Result result;

    if (result_pid == 0)
    {
        result.status = wait::Result::Status::no_state_change;
        return result;
    }

    if (WIFEXITED(status))
    {
        result.status = wait::Result::Status::exited;
        result.detail.if_exited.status = static_cast<exit::Status>(WEXITSTATUS(status));
    } else if (WIFSIGNALED(status))
    {
        result.status = wait::Result::Status::signaled;
        result.detail.if_signaled.signal = static_cast<Signal>(WTERMSIG(status));
        result.detail.if_signaled.core_dumped = WCOREDUMP(status);
    } else if (WIFSTOPPED(status))
    {
        result.status = wait::Result::Status::stopped;
        result.detail.if_stopped.signal = static_cast<Signal>(WSTOPSIG(status));
    }
#ifndef ANDROID
    else if (WIFCONTINUED(status))
    {
        result.status = wait::Result::Status::continued;
    }
#endif

    return result;
}

void ChildProcess::dont_kill_on_cleanup()
{
  d->dont_kill_on_cleanup = true;
}

#ifndef ANDROID
std::istream& ChildProcess::cerr()
{
    return d->cerr;
}

std::ostream& ChildProcess::cin()
{
    return d->cin;
}

std::istream& ChildProcess::cout()
{
    return d->cout;
}
#endif
}
}

ext: cpp

max_stars_repo_name: akraino-edge-stack/iec

max_issues_repo_name: akraino-edge-stack/iec

max_forks_repo_name: akraino-edge-stack/iec


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
#include <gtest/gtest.h>

#include <boost/algorithm/string.hpp>
#include <boost/filesystem.hpp>
#include <ios>
#include <iosfwd>

#include "presto_cpp/main/common/tests/test_json.h"
#include "presto_cpp/main/types/PrestoToVeloxQueryPlan.h"
#include "presto_cpp/presto_protocol/presto_protocol.h"
#include "velox/exec/Operator.h"
#include "velox/type/Type.h"
#include "velox/vector/FlatVector.h"

namespace fs = boost::filesystem;

using namespace facebook::presto;
using namespace facebook::velox;

namespace {
std::string getDataPath(const std::string& fileName) {
  std::string current_path = fs::current_path().c_str();
  if (boost::algorithm::ends_with(current_path, "fbcode")) {
    return current_path + "/presto_cpp/main/types/tests/data/" + fileName;
  }
  return current_path + "/data/" + fileName;
}
} // namespace

TEST(TestValues, valuesRowVector) {
  std::string str = slurp(getDataPath("ValuesNode.json"));

  json j = json::parse(str);
  std::shared_ptr<protocol::ValuesNode> p = j;

  testJsonRoundtrip(j, p);

  auto scopedPool = memory::getDefaultScopedMemoryPool();
  VeloxQueryPlanConverter converter(scopedPool.get());
  auto values = std::dynamic_pointer_cast<const core::ValuesNode>(
      converter.toVeloxQueryPlan(
          std::dynamic_pointer_cast<protocol::PlanNode>(p),
          nullptr,
          "20201107_130540_00011_wrpkw.1.2.3"));

  ASSERT_NE(values, nullptr);
  ASSERT_EQ(values->values().size(), 1);
  ASSERT_EQ(values->values()[0]->children().size(), 2);
  ASSERT_EQ(values->values()[0]->size(), 3);

  {
    auto v = values->values()[0]->childAt(0)->asFlatVector<int32_t>();
    ASSERT_EQ(v->valueAt(0), 1);
    ASSERT_EQ(v->valueAt(1), 2);
    ASSERT_EQ(v->valueAt(2), 3);
  }

  {
    auto v = values->values()[0]->childAt(1)->asFlatVector<StringView>();
    ASSERT_EQ(v->valueAt(0), StringView("a"));
    ASSERT_EQ(v->valueAt(1), StringView("b"));
    ASSERT_EQ(v->valueAt(2), StringView("c"));
  }
}

TEST(TestValues, valuesPlan) {
  // select a, b from (VALUES (1, 'a'), (2, 'b'), (3, 'c')) as t (a, b) where a
  // = 1;
  //
  std::string str = slurp(getDataPath("ValuesPipeTest.json"));

  json j = json::parse(str);
  std::shared_ptr<protocol::PlanFragment> p = j;

  testJsonRoundtrip(j, p);

  auto scopedPool = memory::getDefaultScopedMemoryPool();
  VeloxQueryPlanConverter converter(scopedPool.get());
  auto values = converter.toVeloxQueryPlan(
      std::dynamic_pointer_cast<protocol::OutputNode>(p->root)->source,
      nullptr,
      "20201107_130540_00011_wrpkw.1.2.3");

  ASSERT_EQ(values->id(), "4");
  ASSERT_EQ(values->sources()[0]->id(), "0");
}

max_stars_repo_name: shrinidhijoshi/presto

max_issues_repo_name: shrinidhijoshi/presto

max_forks_repo_name: shrinidhijoshi/presto


text:
// -*- coding: utf-16 -*-
#pragma once

/** @file include/fractions.hpp
 *  This is a C++ Library header.
 */

// #include <boost/operators.hpp>
// #include <cmath>
#include <numeric>
#include <type_traits>
#include <utility>

#include "common_concepts.h"

namespace fun {

    /**
     * @brief absolute
     *
     * @tparam T
     * @param[in] a
     * @return T
     */
    template <typename T> inline constexpr auto abs(const T& a) -> T {
        if constexpr (std::is_unsigned_v<T>) {
            return a;
        } else {
            return (a < T(0)) ? -a : a;
        }
    }

    /**
     * @brief Greatest common divider
     *
     * @tparam _Mn
     * @param[in] __m
     * @param[in] __n
     * @return _Mn
     */
    template <Integral _Mn> inline constexpr auto gcd_recur(const _Mn& __m, const _Mn& __n) -> _Mn {
        if (__n == 0) {
            return abs(__m);
        }
        return gcd_recur(__n, __m % __n);
    }

    /**
     * @brief Greatest common divider
     *
     * @tparam _Mn
     * @param[in] __m
     * @param[in] __n
     * @return _Mn
     */
    template <Integral _Mn> inline constexpr auto gcd(const _Mn& __m, const _Mn& __n) -> _Mn {
        if (__m == 0) {
            return abs(__n);
        }
        return gcd_recur(__m, __n);
    }

    /**
     * @brief Least common multiple
     *
     * @tparam _Mn
     * @param[in] __m
     * @param[in] __n
     * @return _Mn
     */
    template <Integral _Mn> inline constexpr auto lcm(const _Mn& __m, const _Mn& __n) -> _Mn {
        if (__m == 0 || __n == 0) {
            return 0;
        }
        return (abs(__m) / gcd(__m, __n)) * abs(__n);
    }

    /**
     * @brief Fraction
     *
     * @tparam Z
     */
    template <Integral Z> struct Fraction {
        Z _num;
        Z _den;

        /**
         * @brief Construct a new Fraction object
         *
         * @param[in] num
         * @param[in] den
         */
        constexpr Fraction(Z num, Z den) : _num{std::move(num)}, _den{std::move(den)} {
            this->normalize();
        }

        /**
         * @brief normalize to a canonical form
         *
         * denominator is always non-negative and co-prime with numerator
         */
        constexpr auto normalize() -> Z {
            this->normalize1();
            return this->normalize2();
        }

        /**
         * @brief normalize to a canonical form
         *
         * denominator is always non-negative
         */
        constexpr void normalize1() {
            if (this->_den < Z(0)) {
                this->_num = -this->_num;
                this->_den = -this->_den;
            }
        }

        /**
         * @brief normalize to a canonical form
         *
         * denominator is always co-prime with numerator
         */
        constexpr auto normalize2() -> Z {
            Z common = gcd(this->_num, this->_den);
            if (common == Z(1) || common == Z(0)) {
                return common;
            }
            this->_num /= common;
            this->_den /= common;
            return common;
        }

        /**
         * @brief Construct a new Fraction object
         *
         * @param[in] num
         */
        constexpr explicit Fraction(Z&& num) : _num{std::move(num)}, _den(Z(1)) {}

        /**
         * @brief Construct a new Fraction object
         *
         * @param[in] num
         */
        constexpr explicit Fraction(const Z& num) : _num{num}, _den(1) {}

        /**
         * @brief Construct a new Fraction object
         *
         * @param[in] num
         */
        constexpr Fraction() : _num(0), _den(1) {}

        /**
         * @brief
         *
         * @return const Z&
         */
        [[nodiscard]] constexpr auto num() const noexcept -> const Z& { return _num; }

        /**
         * @brief
         *
         * @return const Z&
         */
        [[nodiscard]] constexpr auto den() const noexcept -> const Z& { return _den; }

        /**
         * @brief cross product
         *
         * @param rhs
         * @return Z
         */
        constexpr auto cross(const Fraction& rhs) const -> Z {
            return this->_num * rhs._den - this->_den * rhs._num;
        }

        /** @name Comparison operators
         *  ==, !=, <, >, <=, >= etc.
         */
        ///@{

        /**
         * @brief Equal to
         *
         * @param[in] lhs
         * @param[in] rhs
         * @return true
         * @return false
         */
        friend constexpr auto operator==(Fraction lhs, Z rhs) -> bool {
            if (lhs._den == Z(1) || rhs == Z(0)) {
                return lhs._num == rhs;
            }
            std::swap(lhs._den, rhs);
            lhs.normalize2();
            return lhs._num == lhs._den * rhs;
        }

        /**
         * @brief Less than
         *
         * @param[in] lhs
         * @param[in] rhs
         * @return true
         * @return false
         */
        friend constexpr auto operator<(Fraction lhs, Z rhs) -> bool {
            if (lhs._den == Z(1) || rhs == Z(0)) {
                return lhs._num == rhs;
            }
            std::swap(lhs._den, rhs._num);
            lhs.normalize2();
            return lhs._num < lhs._den * rhs;
        }

        /**
         * @brief Less than
         *
         * @param[in] lhs
         * @param[in] rhs
         * @return true
         * @return false
         */
        friend constexpr auto operator<(Z lhs, Fraction rhs) -> bool {
            if (rhs._den == Z(1) || lhs == Z(0)) {
                return lhs < rhs._num;
            }
            std::swap(rhs._den, lhs);
            rhs.normalize2();
            return rhs._den * lhs < rhs._num;
        }

        /**
         * @brief Equal to
         *
         * @param[in] lhs
         * @param[in] rhs
         * @return true
         * @return false
         */
        friend constexpr auto operator==(const Z& lhs, const Fraction& rhs) -> bool {
            return rhs == lhs;
        }

        /**
         * @brief Equal to
         *
         * @param[in] rhs
         * @return true
         * @return false
         */

        /**
         * @brief Equal to
         *
         * @param lhs
         * @param rhs
         * @return true
         * @return false
         */
        constexpr friend auto operator==(Fraction lhs, Fraction rhs) -> bool {
            if (lhs._den == rhs._den) {
                return lhs._num == rhs._num;
            }
            std::swap(lhs._den, rhs._num);
            lhs.normalize2();
            rhs.normalize2();
            return lhs._num * rhs._den == lhs._den * rhs._num;
        }

        /**
         * @brief Less than
         *
         * @param lhs
         * @param rhs
         * @return true
         * @return false
         */
        constexpr friend auto operator<(Fraction lhs, Fraction rhs) -> bool {
            if (lhs._den == rhs._den) {
                return lhs._num < rhs._num;
            }
            std::swap(lhs._den, rhs._num);
            lhs.normalize2();
            rhs.normalize2();
            return lhs._num * rhs._den < lhs._den * rhs._num;
        }

        /**
         * @brief
         *
         * @param[in] rhs
         * @return true
         * @return false
         */
        constexpr auto operator!=(const Fraction& rhs) const -> bool { return !(*this == rhs); }

        /**
         * @brief Greater than
         *
         * @param[in] rhs
         * @return true
         * @return false
         */
        constexpr auto operator>(const Fraction& rhs) const -> bool { return rhs < *this; }

        /**
         * @brief Greater than or euqal to
         *
         * @param[in] rhs
         * @return true
         * @return false
         */
        constexpr auto operator>=(const Fraction& rhs) const -> bool { return !(*this < rhs); }

        /**
         * @brief Less than or equal to
         *
         * @param[in] rhs
         * @return true
         * @return false
         */
        constexpr auto operator<=(const Fraction& rhs) const -> bool { return !(rhs < *this); }

        /**
         * @brief Greater than
         *
         * @param[in] rhs
         * @return true
         * @return false
         */
        constexpr auto operator>(const Z& rhs) const -> bool { return rhs < *this; }

        /**
         * @brief Less than or equal to
         *
         * @param[in] rhs
         * @return true
         * @return false
         */
        constexpr auto operator<=(const Z& rhs) const -> bool { return !(rhs < *this); }

        /**
         * @brief Greater than or equal to
         *
         * @param[in] rhs
         * @return true
         * @return false
         */
        constexpr auto operator>=(const Z& rhs) const -> bool { return !(*this < rhs); }

        /**
         * @brief Greater than
         *
         * @param[in] lhs
         * @param[in] rhs
         * @return true
         * @return false
         */
        friend constexpr auto operator>(const Z& lhs, const Fraction& rhs) -> bool {
            return rhs < lhs;
        }

        /**
         * @brief Less than or equal to
         *
         * @param[in] lhs
         * @param[in] rhs
         * @return true
         * @return false
         */
        friend constexpr auto operator<=(const Z& lhs, const Fraction& rhs) -> bool {
            return !(rhs < lhs);
        }

        /**
         * @brief Greater than or euqal to
         *
         * @param[in] lhs
         * @param[in] rhs
         * @return true
         * @return false
         */
        friend constexpr auto operator>=(const Z& lhs, const Fraction& rhs) -> bool {
            return !(lhs < rhs);
        }

        ///@}

        /**
         * @brief reciprocal
         *
         */
        constexpr void reciprocal() noexcept(std::is_nothrow_swappable_v<Z>) {
            std::swap(this->_num, this->_den);
            this->normalize1();
        }

        /**
         * @brief multiply and assign
         *
         * @param rhs
         * @return Fraction&
         */
        constexpr auto operator*=(Fraction rhs) -> Fraction& {
            std::swap(this->_num, rhs._num);
            this->normalize2();
            rhs.normalize2();
            this->_num *= rhs._num;
            this->_den *= rhs._den;
            return *this;
        }

        /**
         * @brief multiply
         *
         * @param lhs
         * @param rhs
         * @return Fraction
         */
        friend constexpr auto operator*(Fraction lhs, const Fraction& rhs) -> Fraction {
            return lhs *= rhs;
        }

        /**
         * @brief multiply and assign
         *
         * @param rhs
         * @return Fraction&
         */
        constexpr auto operator*=(Z rhs) -> Fraction& {
            std::swap(this->_num, rhs);
            this->normalize2();
            this->_num *= rhs;
            return *this;
        }

        /**
         * @brief multiply
         *
         * @param lhs
         * @param rhs
         * @return Fraction
         */
        friend constexpr auto operator*(Fraction lhs, const Z& rhs) -> Fraction {
            return lhs *= rhs;
        }

        /**
         * @brief multiply
         *
         * @param lhs
         * @param rhs
         * @return Fraction
         */
        friend constexpr auto operator*(const Z& lhs, Fraction rhs) -> Fraction {
            return rhs *= lhs;
        }

        /**
         * @brief divide and assign
         *
         * @param rhs
         * @return Fraction&
         */
        constexpr auto operator/=(Fraction rhs) -> Fraction& {
            std::swap(this->_den, rhs._num);
            this->normalize();
            rhs.normalize2();
            this->_num *= rhs._den;
            this->_den *= rhs._num;
            return *this;
        }

        /**
         * @brief divide
         *
         * @param lhs
         * @param rhs
         * @return Fraction
         */
        friend constexpr auto operator/(Fraction lhs, const Fraction& rhs) -> Fraction {
            return lhs /= rhs;
        }

        /**
         * @brief divide and assign
         *
         * @param rhs
         * @return Fraction&
         */
        constexpr auto operator/=(const Z& rhs) -> Fraction& {
            std::swap(this->_den, rhs);
            this->normalize();
            this->_den *= rhs;
            return *this;
        }

        /**
         * @brief divide
         *
         * @param lhs
         * @param rhs
         * @return Fraction
         */
        friend constexpr auto operator/(Fraction lhs, const Z& rhs) -> Fraction {
            return lhs /= rhs;
        }

        /**
         * @brief divide
         *
         * @param lhs
         * @param rhs
         * @return Fraction
         */
        friend constexpr auto operator/(const Z& lhs, Fraction rhs) -> Fraction {
            rhs.reciprocal();
            return rhs *= lhs;
        }

        /**
         * @brief Negate
         *
         * @return Fraction
         */
        constexpr auto operator-() const -> Fraction {
            auto res = Fraction(*this);
            res._num = -res._num;
            return res;
        }

        /**
         * @brief Add
         *
         * @param rhs
         * @return Fraction
         */
        constexpr auto operator+(const Fraction& rhs) const -> Fraction {
            if (this->_den == rhs._den) {
                return Fraction(this->_num + rhs._num, this->_den);
            }
            const auto common = gcd(this->_den, rhs._den);
            if (common == Z(0)) {
                return Fraction(rhs._den * this->_num + this->_den * rhs._num, Z(0));
            }
            const auto l = this->_den / common;
            const auto r = rhs._den / common;
            auto d = this->_den * r;
            auto n = r * this->_num + l * rhs._num;
            return Fraction(std::move(n), std::move(d));
        }

        /**
         * @brief Subtract
         *
         * @param[in] frac
         * @return Fraction
         */
        constexpr auto operator-(const Fraction& frac) const -> Fraction { return *this + (-frac); }

        /**
         * @brief Add
         *
         * @param[in] frac
         * @param[in] i
         * @return Fraction
         */
        friend constexpr auto operator+(Fraction frac, const Z& i) -> Fraction { return frac += i; }

        /**
         * @brief Add
         *
         * @param[in] i
         * @param[in] frac
         * @return Fraction
         */
        friend constexpr auto operator+(const Z& i, Fraction frac) -> Fraction { return frac += i; }

        /**
         * @brief
         *
         * @param[in] i
         * @return Fraction
         */
        constexpr auto operator-(const Z& i) const -> Fraction { return *this + (-i); }

        /**
         * @brief
         *
         * @param[in] rhs
         * @return Fraction
         */
        constexpr auto operator+=(const Fraction& rhs) -> Fraction& { return *this -= (-rhs); }

        /**
         * @brief
         *
         * @param[in] rhs
         * @return Fraction
         */
        constexpr auto operator-=(const Fraction& rhs) -> Fraction& {
            if (this->_den == rhs._den) {
                this->_num -= rhs._num;
                this->normalize2();
                return *this;
            }

            auto other{rhs};
            std::swap(this->_den, other._num);
            auto common_n = this->normalize2();
            auto common_d = other.normalize2();
            std::swap(this->_den, other._num);
            this->_num = this->cross(other);
            this->_den *= other._den;
            std::swap(this->_den, common_d);
            this->normalize2();
            this->_num *= common_n;
            this->_den *= common_d;
            this->normalize2();
            return *this;
        }

        /**
         * @brief
         *
         * @param[in] i
         * @return Fraction
         */
        constexpr auto operator+=(const Z& i) -> Fraction& { return *this -= (-i); }

        /**
         * @brief
         *
         * @param[in] rhs
         * @return Fraction
         */
        constexpr auto operator-=(const Z& rhs) -> Fraction& {
            if (this->_den == Z(1)) {
                this->_num -= rhs;
                return *this;
            }

            auto other{rhs};
            std::swap(this->_den, other);
            auto common_n = this->normalize2();
            std::swap(this->_den, other);
            this->_num -= other * this->_den;
            this->_num *= common_n;
            this->normalize2();
            return *this;
        }

        /**
         * @brief
         *
         * @param[in] c
         * @param[in] frac
         * @return Fraction
         */
        friend constexpr auto operator-(const Z& c, const Fraction& frac) -> Fraction {
            return c + (-frac);
        }

        /**
         * @brief
         *
         * @param[in] c
         * @param[in] frac
         * @return Fraction
         */
        friend constexpr auto operator+(int&& c, const Fraction& frac) -> Fraction {
            return frac + Z(c);
        }

        /**
         * @brief
         *
         * @param[in] c
         * @param[in] frac
         * @return Fraction
         */
        friend constexpr auto operator-(int&& c, const Fraction& frac) -> Fraction {
            return (-frac) + Z(c);
        }

        /**
         * @brief
         *
         * @param[in] c
         * @param[in] frac
         * @return Fraction<Z>
         */
        friend constexpr auto operator*(int&& c, const Fraction& frac) -> Fraction {
            return frac * Z(c);
        }

        /**
         * @brief
         *
         * @tparam _Stream
         * @tparam Z
         * @param[in] os
         * @param[in] frac
         * @return _Stream&
         */
        template <typename _Stream> friend auto operator<<(_Stream& os, const Fraction& frac)
            -> _Stream& {
            os << "(" << frac.num() << "/" << frac.den() << ")";
            return os;
        }
    };

    // For template deduction
    // Integral{Z} Fraction(const Z &, const Z &) noexcept -> Fraction<Z>;

}  // namespace fun

ext: hpp


text:
/* file_output.cc
   Jeremy Barnes, 29 May 2011
   Copyright (c) 2011 Datacratic.  All rights reserved.

*/

#include "file_output.h"
#include "jml/utils/parse_context.h"
#include <boost/tuple/tuple.hpp>

#define BOOST_SYSTEM_NO_DEPRECATED

#include <boost/filesystem.hpp>

using namespace std;
using namespace boost::filesystem;
using namespace ML;

namespace Datacratic {

/*****************************************************************************/
/* FILE OUTPUT                                                               */
/*****************************************************************************/

NamedOutput::
NamedOutput(size_t ringBufferSize)
    : CompressingOutput(ringBufferSize)
{
}

NamedOutput::
~NamedOutput()
{
    close();
}

void
NamedOutput::
open(const std::string & filename,
     const std::string & compression,
     int level)
{
    close();
    switchFile(filename, compression, level);
    startWorkerThread();
}

void
NamedOutput::
closeFile()
{
    if (!sink) return;

    //if (onPreFileClose)
    //    onPreFileClose(currentFilename);

    closeCompressor();
    sink->close();

    //if (onPostFileClose)
    //    onPostFileClose(currentFilename);
}

void
NamedOutput::
rotate(const std::string & newFilename,
       const std::string & newCompression,
       int newLevel)
{
    auto op = [=] ()
        {
            this->switchFile(newFilename, newCompression, newLevel);
        };

    pushOperation(op);
}

void
NamedOutput::
close()
{
    WorkerThreadOutput::stopWorkerThread();
    closeFile();
}

void
NamedOutput::
switchFile(const std::string & filename,
           const std::string & compression_,
           int level)
{

    closeCompressor();
    closeFile();

    string compression = compression_;
    if (compression == "")
        compression = Compressor::filenameToCompression(filename);

    string fn = filename;

    bool append = false;
    if (filename.length() > 0 && filename[filename.length() - 1] == '+') {
        fn = string(filename, 0, filename.length() - 2);
        append = true;
    }

    if (onPreFileOpen)
        onPreFileOpen(fn);

    // todo - fix this by saving the output of createSink and getting
    // the new uri if there is one
    std::shared_ptr<CompressingOutput::Sink> theSink = createSink(fn, append);
    CompressingOutput::open(theSink, compression, level);

    if (onPostFileOpen)
    {
//        cerr << "NamedOutput::switchfile: calling on postfile open with " <<
//            theSink->currentUri << endl;
        onPostFileOpen(theSink->currentUri);
    }
}

/*****************************************************************************/
/* FILE SINK                                                                 */
/*****************************************************************************/

FileSink::
FileSink(const std::string & filename, bool append, bool disambiguate)
    : fd(-1)
{
    if (filename != "")
        open(filename, append, disambiguate);
}

FileSink::
~FileSink()
{
    close();
}

void
FileSink::
open(const std::string & filename, bool append, bool disambiguate)
{
    close();

    string fn = filename;

    path p = filename;
    path d = p;  d.remove_filename();

    string e = p.extension().string();
    path s = p.stem();
    while (s.extension() != "") {
        e = s.extension().string() + e;
        s = s.stem();
    }

    //cerr << "dir " << d << " ext " << e << " stem " << s << endl;

    if (!exists(d)) {
        //cerr << "creating directory " << d << endl;
        create_directories(d);
    }

    if (disambiguate) {
        string base = (d/s).string();
        string disamb = "";
        int n = 0;

        while (exists((fn = base + disamb + e))) {
            cerr << "file " + (base + disamb + e) + " exists; disambiguating"
                 << endl;
            disamb = ML::format(".%d", ++n);
        }

    }

    cerr << "opening file " << fn << " with append " << append << endl;

    fd = ::open(fn.c_str(),
                O_WRONLY | O_CREAT | O_EXCL | (append ? O_APPEND : 0),
                00664);

    if (fd == -1)
        throw ML::Exception(errno, "open of " + filename);

    currentUri = fn;

}

void
FileSink::
close()
{
    //cerr << "closing file " << currentUri << endl;

    if (fd != -1) {
        int r = fdatasync(fd);
        if (r == -1)
            throw ML::Exception(errno, "fdatasync " + currentUri);

        int res = ::close(fd);
        if (res == -1)
            throw ML::Exception(errno, "close " + currentUri);
        fd = -1;

        currentUri = "";
    }
}

size_t
FileSink::
write(const char * data, size_t size)
{
    size_t done = 0;

    while (done < size) {
        ssize_t res = ::write(fd, data + done, size - done);
        if (res == -1)
            throw ML::Exception(errno, "write to FileSink for "
                                + currentUri);
        done += res;
    }

    return done;
}

size_t
FileSink::
flush(FileFlushLevel flushLevel)
{
    switch (flushLevel) {

    case FLUSH_NONE:
        return 0;

    case FLUSH_TO_OS:
        return 0;   // we call write() straight away, so ther is no internal
                    // buffering and nothing to do here

    case FLUSH_TO_DISK: {
        int r = fdatasync(fd);
        if (r == -1)
            throw ML::Exception(errno, "fdatasync for " + currentUri);
        return 0;
    }

    default:
        throw ML::Exception("FileSink::flush(): unknown flush level");
    }
}

/*****************************************************************************/
/* FILE OUTPUT                                                               */
/*****************************************************************************/

FileOutput::
FileOutput(const std::string & filename, size_t ringBufferSize)
    : NamedOutput(ringBufferSize)
{
    if (filename != "")
        open(filename);
}

FileOutput::
~FileOutput()
{
    close();
}

std::shared_ptr<CompressingOutput::Sink>
FileOutput::
createSink(const std::string & filename, bool append)
{
    return std::make_shared<FileSink>(filename, append);
}

/*****************************************************************************/
/* ROTATING FILE OUTPUT                                                      */
/*****************************************************************************/

RotatingFileOutput::
RotatingFileOutput()
    : RotatingOutputAdaptor(std::bind(&RotatingFileOutput::createFile,
                                      this,
                                      std::placeholders::_1))
{
}

RotatingFileOutput::
~RotatingFileOutput()
{
    close();
}

void
RotatingFileOutput::
open(const std::string & filenamePattern,
     const std::string & periodPattern,
     const std::string & compression,
     int level)
{
    this->compression = compression;
    this->level = level;

    RotatingOutputAdaptor::open(filenamePattern, periodPattern);
}

FileOutput *
RotatingFileOutput::
createFile(const std::string & filename)
{
    std::unique_ptr<FileOutput> result(new FileOutput());

    result->onPreFileOpen = [=] (const string & fn)
        { if (this->onPreFileOpen) this->onPreFileOpen(fn); };
    result->onPostFileOpen = [=] (const string & fn)
        { if (this->onPostFileOpen) this->onPostFileOpen(fn); };
    result->onPreFileClose = [=] (const string & fn)
        { if (this->onPreFileClose) this->onPreFileClose(fn); };
    result->onPostFileClose = [=] (const string & fn)
        { if (this->onPostFileClose) this->onPostFileClose(fn); };
    result->onFileWrite = [=] (const string& channel, const std::size_t bytes)
	{ if (this->onFileWrite) this->onFileWrite(channel, bytes); };

    result->open(filename, compression, level);

    return result.release();
}

} // namespace Datacratic

ext: cc

max_stars_repo_name: etnrlz/rtbkit

max_issues_repo_name: leobispo/soa

max_forks_repo_name: leobispo/soa


text:
/**
 * @file quic_svd_test.cpp
 * @author Siddharth Agrawal
 *
 * Test file for QUIC-SVD class.
 */

#include <mlpack/core.hpp>
#include <mlpack/methods/quic_svd/quic_svd.hpp>

#include <boost/test/unit_test.hpp>
#include "old_boost_test_definitions.hpp"

BOOST_AUTO_TEST_SUITE(QUICSVDTest);

using namespace mlpack;
using namespace mlpack::svd;

/**
 * The reconstruction error of the obtained SVD should be small.
 */
BOOST_AUTO_TEST_CASE(QUICSVDReconstructionError)
{
  // Load the dataset.
  arma::mat dataset;
  data::Load("test_data_3_1000.csv", dataset);

  // Obtain the SVD using default parameters.
  arma::mat u, v, sigma;
  QUIC_SVD quicsvd(dataset, u, v, sigma);

  // Reconstruct the matrix using the SVD.
  arma::mat reconstruct;
  reconstruct = u * sigma * v.t();

  // The relative reconstruction error should be small.
  double relativeError = arma::norm(dataset - reconstruct, "frob") /
                         arma::norm(dataset, "frob");
  BOOST_REQUIRE_SMALL(relativeError, 1e-5);
}

BOOST_AUTO_TEST_SUITE_END();

max_stars_repo_name: vj-ug/Contribution-to-mlpack

max_issues_repo_name: vj-ug/Contribution-to-mlpack

max_forks_repo_name: vj-ug/Contribution-to-mlpack


text:
// Copyright Abel Sinkovics (abel@sinkovics.hu)  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)

#include <boost/metaparse/string.hpp>
#include <boost/metaparse/sequence_apply.hpp>
#include <boost/metaparse/last_of.hpp>
#include <boost/metaparse/int_.hpp>
#include <boost/metaparse/token.hpp>
#include <boost/metaparse/lit_c.hpp>
#include <boost/metaparse/one_of.hpp>
#include <boost/metaparse/empty.hpp>
#include <boost/metaparse/entire_input.hpp>
#include <boost/metaparse/build_parser.hpp>

#include <boost/rational.hpp>

#include <boost/config.hpp>

#include <boost/mpl/int.hpp>

#include <iostream>

using boost::metaparse::sequence_apply2;
using boost::metaparse::last_of;
using boost::metaparse::int_;
using boost::metaparse::token;
using boost::metaparse::lit_c;
using boost::metaparse::one_of;
using boost::metaparse::empty;
using boost::metaparse::entire_input;
using boost::metaparse::build_parser;

template <class Num, class Denom>
struct rational
{
  typedef rational type;

  static boost::rational<int> run()
  {
    return boost::rational<int>(Num::type::value, Denom::type::value);
  }
};

typedef
  sequence_apply2<
    rational,

    token<int_>,
    one_of<
      last_of<lit_c<'/'>, token<int_> >,
      empty<boost::mpl::int_<1> >
    >
  >
  rational_grammar;

typedef build_parser<entire_input<rational_grammar> > rational_parser;

#ifdef RATIONAL
#  error RATIONAL already defined
#endif
#define RATIONAL(s) \
  (::rational_parser::apply<BOOST_METAPARSE_STRING(s)>::type::run())

#if BOOST_METAPARSE_STD < 2011

int main()
{
  std::cout << "Please use a compiler that supports constexpr" << std::endl;
}

#else

int main()
{
  const boost::rational<int> r1 = RATIONAL("1/3");
  const boost::rational<int> r2 = RATIONAL("4/4");
  const boost::rational<int> r3 = RATIONAL("1");
  const boost::rational<int> r4 = RATIONAL("13/11");

  // Uncommenting the following line generates a compilation error. On a
  // number of platforms the error report contains the following (or something
  // similar):
  // x__________________PARSING_FAILED__________________x<1, 3, digit_expected>
  // where 1, 3 is the location of the error inside the string literal.
//  const boost::rational<int> r5 = RATIONAL("7/");

  std::cout
    << r1 << std::endl
    << r2 << std::endl
    << r3 << std::endl
    << r4 << std::endl;
}

#endif


text:
//
// Created by janw on 02.06.2020.
//

// STL
#include <iostream>
#include <algorithm>
#include <sstream>
#include <string>

#include <boost/iostreams/copy.hpp>
#include <boost/iostreams/filtering_streambuf.hpp>
#include <boost/iostreams/filter/zlib.hpp>

#include <pcl/point_cloud.h>
#include <pcl/point_types.h>

#include "laser_slam_ros/visual_view.hpp"

#define PRINT(x) std::cout << #x << " = " << x << std::endl

using std::cout;
using std::endl;

#include <signal.h>
#include <termios.h>
#include <stdio.h>
int getch()
{
  static struct termios oldt, newt;
  tcgetattr( STDIN_FILENO, &oldt);           // save old settings
  newt = oldt;
  newt.c_lflag &= ~(ICANON);                 // disable buffering
  tcsetattr( STDIN_FILENO, TCSANOW, &newt);  // apply new settings

  int c = getchar();  // read character (non-blocking)

  tcsetattr( STDIN_FILENO, TCSANOW, &oldt);  // restore old settings
  return c;
}

namespace laser_slam_ros {

VisualView::VisualView()
  : isCompressedFlag(false)
{
  // ++ids;
  // LOG(INFO) << "allocated " << ids;
}

VisualView::VisualView(const laser_slam::LaserScan &iscan,
                       const laser_slam::Pose &ipose,
                       const int &ihorRes,
                       const int &ivertRes,
                       bool iorganized)
  : isCompressedFlag(false),
    horRes(ihorRes),
    vertRes(ivertRes),
    organized(iorganized),
    pixelOffsets{0, 6, 12, 18},
    // MulRan
    // vertAngles{-15.654, -15.062, -14.497, -13.947, -13.489, -12.908, -12.337, -11.803,
    //           -11.347, -10.78, -10.224, -9.675, -9.239, -8.664, -8.118, -7.574,
    //           -7.131, -6.575, -6.019, -5.47, -5.037, -4.478, -3.921, -3.382,
    //           -2.938, -2.274, -1.84, -1.282, -0.842, -0.29, 0.262, 0.805,
    //           1.246, 1.799, 2.346, 2.894, 3.338, 3.891, 4.442, 4.989,
    //           5.443, 5.977, 6.535, 7.079, 7.54, 8.086, 8.63, 9.189,
    //           9.633, 10.182, 10.734, 11.309, 11.751, 12.305, 12.852, 13.442,
    //           13.91, 14.444, 15.012, 15.615, 16.073, 16.629, 17.217, 17.84}
    // KITTI
    vertAngles{-24.8       , -24.37460317, -23.94920635, -23.52380952,
               -23.0984127 , -22.67301587, -22.24761905, -21.82222222,
               -21.3968254 , -20.97142857, -20.54603175, -20.12063492,
               -19.6952381 , -19.26984127, -18.84444444, -18.41904762,
               -17.99365079, -17.56825397, -17.14285714, -16.71746032,
               -16.29206349, -15.86666667, -15.44126984, -15.01587302,
               -14.59047619, -14.16507937, -13.73968254, -13.31428571,
               -12.88888889, -12.46349206, -12.03809524, -11.61269841,
               -11.18730159, -10.76190476, -10.33650794,  -9.91111111,
               -9.48571429,  -9.06031746,  -8.63492063,  -8.20952381,
               -7.78412698,  -7.35873016,  -6.93333333,  -6.50793651,
               -6.08253968,  -5.65714286,  -5.23174603,  -4.80634921,
               -4.38095238,  -3.95555556,  -3.53015873,  -3.1047619 ,
               -2.67936508,  -2.25396825,  -1.82857143,  -1.4031746 ,
               -0.97777778,  -0.55238095,  -0.12698413,   0.2984127 ,
               0.72380952,   1.14920635,   1.57460317,   2.        }
{
    pose = ipose;
    time_ns = iscan.time_ns;

    intensity.resize(vertRes, horRes);
    intensity.setZero();
    range.resize(vertRes, horRes);
    range.setZero();
    count.resize(vertRes, horRes);
    count.setZero();
    dirs.resize(vertRes * horRes, Eigen::Vector3f::Zero());

    unsigned intDim = 0;
    if(iscan.scan.descriptorExists("intensity")){
        intDim = iscan.scan.getDescriptorDimension("intensity");
        // cout << "intDim = " << intDim << endl;
    }
    else{
        LOG(ERROR) << "No intensity data in laser scan";
    }
    // cout << "iscan.scan.getNbPoints() = " << iscan.scan.getNbPoints() << endl;
    if (organized) {
      for (size_t i = 0u; i < iscan.scan.getNbPoints(); ++i) {
        float x = iscan.scan.features(0, i);
        float y = iscan.scan.features(1, i);
        float z = iscan.scan.features(2, i);

        float intVal = iscan.scan.descriptors(intDim, i);
        float rangeVal = std::sqrt(x * x + y * y + z * z);

        if (rangeVal > rangeThresh) {
          int vertCoord = i / horRes;
          int horCoord = (i - pixelOffsets[vertCoord % 4] + horRes) % horRes;

          // int horCoord = getHorCoord(x, y, z);
          // int vertCoord = getVertCoord(x, y, z);
          // if(horCoord < 0 || horRes <= horCoord || vertCoord < 0 || vertRes <= vertCoord) {
          //   cout << i << ": (" << x << ", " << y << ", " << z << ")" << endl;
          //   // cout << "horAngle = " << horAngle << "\tvertAngle = " << vertAngle << "\tintensity = " << intVal << endl;
          //   cout << "horCoord = " << horCoord << "\tvertCoord = " << vertCoord << endl;
          //
          //   LOG(ERROR) << "Wrong image coordinates";
          //   throw "Wrong image coordinates";
          // }

          Eigen::Vector3f dir = Eigen::Vector3f(x, y, z).normalized();
          intensity(vertCoord, horCoord) = intVal;
          range(vertCoord, horCoord) = rangeVal;
          count(vertCoord, horCoord) += 1;
          dirs[vertCoord * horRes + horCoord] = dir;
        }
      }
    }
    // do interpolation
    else {
      // std::cout << "interpolating intensity image" << std::endl;
      // std::cout << "binning" << std::endl;
      std::vector<std::vector<std::vector<int>>> bins(vertRes,
                                                     std::vector<std::vector<int>>(horRes, std::vector<int>()));
      for (size_t i = 0u; i < iscan.scan.getNbPoints(); ++i) {
        float x = iscan.scan.features(0, i);
        float y = iscan.scan.features(1, i);
        float z = iscan.scan.features(2, i);

        float intVal = iscan.scan.descriptors(intDim, i);
        float rangeVal = std::sqrt(x * x + y * y + z * z);

        if (rangeVal > rangeThresh) {
          int horCoord = getHorCoordLow(x, y, z);
          int vertCoord = getVertCoordLow(x, y, z);

          if(0 <= horCoord && horCoord < horRes && 0 <= vertCoord && vertCoord < vertRes) {
            // std::cout << "adding to bin (" << vertCoord << ", " << horCoord << ")" << std::endl;
            bins[vertCoord][horCoord].push_back(i);
          }
        }
      }

      // std::cout << "interpolating" << std::endl;
      for(int r = 0; r < vertRes; ++r) {
        for (int c = 0; c < horRes; ++c) {
          // PRINT(r);
          // PRINT(c);
          Eigen::Vector3f dir = getDir(r, c);
          float horAngle = getHorAngle(dir(0), dir(1), dir(2));
          float vertAngle = getVertAngle(dir(0), dir(1), dir(2));
          // PRINT(dir.transpose());
          // PRINT(horAngle);
          // PRINT(vertAngle);

          int nh00 = getClosest(iscan, bins[r][c], dir);
          int nh10 = -1;
          if (r > 0) {
            nh10 = getClosest(iscan, bins[r - 1][c], dir);
          }
          // there is always a neighboring column
          int nh01 = getClosest(iscan, bins[r][(c - 1 + horRes) % horRes], dir);
          int nh11 = -1;
          if (r > 0) {
            nh11 = getClosest(iscan, bins[r - 1][(c - 1 + horRes) % horRes], dir);
          }

          // PRINT(nh00);
          // PRINT(nh10);
          // PRINT(nh01);
          // PRINT(nh11);
          Eigen::Vector4f pt = Eigen::Vector4f::Zero();
          if (nh00 >= 0 && nh10 >= 0 && nh01 >= 0 && nh11 >= 0) {
            Eigen::Vector4f pt00 = getPoint(iscan, nh00, intDim);
            Eigen::Vector4f pt10 = getPoint(iscan, nh10, intDim);
            Eigen::Vector4f pt01 = getPoint(iscan, nh01, intDim);
            Eigen::Vector4f pt11 = getPoint(iscan, nh11, intDim);

            // first interpolate horizontally
            Eigen::Vector4f pt0 = interpolateHor(pt01, pt00, horAngle);
            Eigen::Vector4f pt1 = interpolateHor(pt11, pt10, horAngle);
            // then vertically
            pt = interpolateVert(pt0, pt1, vertAngle);
            // {
            //   PRINT(r);
            //   PRINT(c);
            //   PRINT(dir.transpose());
            //   PRINT(horAngle);
            //   PRINT(vertAngle);
            //   PRINT(getHorAngle(pt01(0), pt01(1), pt01(2)));
            //   PRINT(getHorAngle(pt00(0), pt00(1), pt00(2)));
            //   PRINT(nh00);
            //   PRINT(nh10);
            //   PRINT(nh01);
            //   PRINT(nh11);
            //   PRINT(pt00.transpose());
            //   PRINT(pt10.transpose());
            //   PRINT(pt01.transpose());
            //   PRINT(pt11.transpose());
            //   PRINT(pt0.transpose());
            //   PRINT(pt1.transpose());
            //   PRINT(pt.transpose());
            //   while (getch() != 'n') {
            //
            //   }
            // }
          }
          else if (nh00 >= 0 && nh10 >= 0) {
            Eigen::Vector4f pt00 = getPoint(iscan, nh00, intDim);
            Eigen::Vector4f pt10 = getPoint(iscan, nh10, intDim);

            // PRINT(pt00.transpose());
            // PRINT(pt10.transpose());
            pt = interpolateVert(pt00, pt10, vertAngle);
          }
          else if (nh01 >= 0 && nh11 >= 0) {
            Eigen::Vector4f pt01 = getPoint(iscan, nh01, intDim);
            Eigen::Vector4f pt11 = getPoint(iscan, nh11, intDim);

            // PRINT(pt01.transpose());
            // PRINT(pt11.transpose());
            // interpolate vertically
            pt = interpolateVert(pt01, pt11, vertAngle);
          }
          else if (nh00 >= 0 && nh01 >= 0) {
            Eigen::Vector4f pt00 = getPoint(iscan, nh00, intDim);
            Eigen::Vector4f pt01 = getPoint(iscan, nh01, intDim);

            // PRINT(pt00.transpose());
            // PRINT(pt01.transpose());
            // interpolate horizontally
            pt = interpolateHor(pt01, pt00, horAngle);
          }
          else if (nh10 >= 0 && nh11 >= 0) {
            Eigen::Vector4f pt10 = getPoint(iscan, nh10, intDim);
            Eigen::Vector4f pt11 = getPoint(iscan, nh11, intDim);

            // PRINT(pt10.transpose());
            // PRINT(pt11.transpose());
            // interpolate horizontally
            pt = interpolateHor(pt11, pt10, horAngle);
          }
          else {
            // chose the closest
            int nh = getClosest(iscan, std::vector<int>{nh00, nh10, nh01, nh11}, dir);
            if (nh >= 0) {
              pt = getPoint(iscan, nh, intDim);
            }
          }
          // PRINT(pt.transpose());
          if (pt != Eigen::Vector4f::Zero()) {
            Eigen::Vector3f dir = pt.head<3>().normalized();
            intensity(r, c) = pt(3);
            range(r, c) = pt.head<3>().norm();
            dirs[r * horRes + c] = dir;
            count(r, c) += 1;
          }
        }
      }
    }

    // buildKdtree();

    ++ids;
    // LOG(INFO) << "allocated " << ids;
}

// VisualView::VisualView(VisualView &&other) :
//     pixelOffsets(std::move(other.pixelOffsets)),
//     vertAngles(std::move(other.vertAngles)),
//     pose(std::move(other.pose)),
//     time_ns(std::move(other.time_ns)),
//     intensity(std::move(other.intensity)),
//     range(std::move(other.range)),
//     count(std::move(other.count)),
//     dirs(std::move(other.dirs)) {
//   ++ids;
// }

// VisualView::VisualView(const VisualView &other) :
//     pixelOffsets(other.pixelOffsets),
//     vertAngles(other.vertAngles),
//     pose(other.pose),
//     time_ns(other.time_ns),
//     intensity(other.intensity),
//     range(other.range),
//     count(other.count),
//     dirs(other.dirs) {
//   ++ids;
//   // LOG(INFO) << "allocated " << ids;
// }

// VisualView::~VisualView(){
//   --ids;
//   // LOG(INFO) << "allocated " << ids;
// }

float VisualView::angDiff(const float &a1, const float &a2) const {
  float d = a1 - a2;
  if (d < -M_PI) {
    d += 2 * M_PI;
  }
  else if(M_PI < d) {
    d -= 2 * M_PI;
  }
  return d;
}

float VisualView::getHorAngle(const float &x, const float &y, const float &z) const {
  float horAngle = atan2(-y, x);
  if (horAngle < 0) {
    horAngle += 2.0 * M_PI;
  }

  return horAngle;
}

float VisualView::getVertAngle(const float &x, const float &y, const float &z) const {
  float horRange = std::sqrt(x*x + y*y);
  float vertAngle = atan2(z, horRange);

  return vertAngle;
}

int VisualView::getHorCoord(const float &x, const float &y, const float &z) const {
  float horAngle = getHorAngle(x, y, z);

  // round to nearest integer
  int horCoord = int(horAngle / (2 * M_PI) * horRes + 0.5);

  return horCoord;
}

int VisualView::getVertCoord(const float &x, const float &y, const float &z) const {
  float vertAngle = getVertAngle(x, y, z);

  auto it = std::lower_bound(vertAngles.begin(), vertAngles.end(), vertAngle * 180.0 / M_PI);
  if (it != vertAngles.begin()){
    if(std::abs(*(it-1) - vertAngle * 180.0 / M_PI) < std::abs(*it - vertAngle * 180.0 / M_PI)){
      --it;
    }
  }
  // int vertCoord = int((vertRange / 2.0 - vertAngle) / vertRange * (vertRes - 1));
  int vertCoord = vertAngles.end() - it - 1;

  return vertCoord;
}

int VisualView::getHorCoordLow(const float &x, const float &y, const float &z) const {
  float horAngle = getHorAngle(x, y, z);

  // round to nearest integer
  int horCoord = int(horAngle / (2 * M_PI) * horRes);

  return horCoord;
}

int VisualView::getVertCoordLow(const float &x, const float &y, const float &z) const {
  float vertAngle = getVertAngle(x, y, z);

  auto it = std::lower_bound(vertAngles.begin(), vertAngles.end(), vertAngle * 180.0 / M_PI);

  // int vertCoord = int((vertRange / 2.0 - vertAngle) / vertRange * (vertRes - 1));
  int vertCoord = vertAngles.end() - it - 1;

  return vertCoord;
}

Eigen::Vector3f VisualView::getDir(const int &r, const int &c) const {
  float horAngle = c * 2 * M_PI / horRes;
  float vertAngle = vertAngles[vertAngles.size() - r - 1] * M_PI / 180.0;

  Eigen::Quaternionf q = Eigen::AngleAxisf(-horAngle, Eigen::Vector3f::UnitZ())
                        * Eigen::AngleAxisf(-vertAngle, Eigen::Vector3f::UnitY());
  Eigen::Vector3f dir = q * Eigen::Vector3f::UnitX();
  return dir;
}

int VisualView::getClosest(const laser_slam::LaserScan &scan,
                           const std::vector<int> &nhs,
                           const Eigen::Vector3f &dir) const {
  int bestNh = -1;
  float bestW = 0.0f;
  for (const int &nh : nhs) {
    if (nh >= 0) {
      float x = scan.scan.features(0, nh);
      float y = scan.scan.features(1, nh);
      float z = scan.scan.features(2, nh);

      Eigen::Vector3f nhDir = Eigen::Vector3f(x, y, z).normalized();
      float curW = dir.dot(nhDir);
      if (curW > bestW) {
        bestNh = nh;
        bestW = curW;
      }
    }
  }
  return bestNh;
}

Eigen::Vector4f VisualView::getPoint(const laser_slam::LaserScan &scan, const int &idx, const int &intDim) const {
  return Eigen::Vector4f(scan.scan.features(0, idx),
                        scan.scan.features(1, idx),
                        scan.scan.features(2, idx),
                        scan.scan.descriptors(intDim, idx));
}

Eigen::Vector4f VisualView::interpolateVert(const Eigen::Vector4f &pt1,
                                            const Eigen::Vector4f &pt2,
                                            const float &vertAngle) const {
  float pt1ang = getVertAngle(pt1(0), pt1(1), pt1(2));
  float pt2ang = getVertAngle(pt2(0), pt2(1), pt2(2));
  float w2 = (vertAngle - pt1ang) / (pt2ang - pt1ang);
  float w1 = (pt2ang - vertAngle) / (pt2ang - pt1ang);

  if (abs(w1 + w2 - 1.0f) > 1e-5) {
    std::cout << "abs(w1 + w2 - 1.0f) > 1e-5" << std::endl;
  }
  if (vertAngle < pt1ang || pt2ang < vertAngle) {
    std::cout << "vertAngle < pt1ang || pt2ang < vertAngle" << std::endl;
  }

  // {
  //   PRINT(pt1.transpose());
  //   PRINT(pt2.transpose());
  //   PRINT(pt1ang);
  //   PRINT(vertAngle);
  //   PRINT(pt2ang);
  //   PRINT(w1);
  //   PRINT(w2);
  //   while (getch() != 'm') {
  //
  //   }
  // }

  return (w1 * pt1 + w2 * pt2) / (w1 + w2);
}

Eigen::Vector4f VisualView::interpolateHor(const Eigen::Vector4f &pt1,
                                           const Eigen::Vector4f &pt2,
                                           const float &horAngle) const {
  float pt1ang = getHorAngle(pt1(0), pt1(1), pt1(2));
  float pt2ang = getHorAngle(pt2(0), pt2(1), pt2(2));
  float w2 = angDiff(horAngle, pt1ang) / angDiff(pt2ang, pt1ang);
  float w1 = angDiff(pt2ang, horAngle) / angDiff(pt2ang, pt1ang);

  // if (abs(w1 + w2 - 1.0f) > 1e-5 || w1 < 0.0f || w2 < 0.0f) {
  //   std::cout << "abs(w1 + w2 - 1.0f) > 1e-5 || w1 < 0.0f || w2 < 0.0f" << std::endl;
  //
  //   {
  //     PRINT(pt1.transpose());
  //     PRINT(pt2.transpose());
  //     PRINT(pt1ang);
  //     PRINT(horAngle);
  //     PRINT(pt2ang);
  //     PRINT(w1);
  //     PRINT(w2);
  //     while (getch() != 'm') {
  //
  //     }
  //   }
  // }
  // if (horAngle < pt1ang || pt2ang < horAngle) {
  //   std::cout << "horAngle < pt1ang || pt2ang < horAngle" << std::endl;
  // }

  return (w1 * pt1 + w2 * pt2) / (w1 + w2);
}

std::pair<int, int> VisualView::getClosestDir(const float &x, const float &y, const float &z,
                                              const int &r1,
                                              const int &c1,
                                              const int &r2,
                                              const int &c2) const {
  Eigen::Vector3f dir(x, y, z);
  dir.normalize();
  std::pair<int, int> bestCoord(-1, -1);
  float bestDiff = std::numeric_limits<float>::max();

  // std::vector<int> idxs;
  // std::vector<float> dists;
  // kdtree->nearestKSearch(pcl::PointXYZ(dir(0), dir(1), dir(2)), 4, idxs, dists);
  //
  // for (auto &idx : idxs) {
  //   int r = idxToCoord.at(idx).first;
  //   int c = idxToCoord.at(idx).second;
  //
  //   if(range(r, c) > rangeThresh) {
  //     float diff = 1.0f - dir.dot(dirs[r * horRes + c]);
  //     if ((diff < 1.0f - cos(dirThresh * M_PI / 180.0)) && diff < bestDiff) {
  //       bestCoord.first = r;
  //       bestCoord.second = c;
  //       bestDiff = diff;
  //     }
  //   }
  // }

  for(int r = r1; r < r2; ++r){
    for(int c = c1; c < c2; ++c){
      if(range(r, c) > rangeThresh) {
        // 1 - cosine(alpha)
        float diff = 1.0f - dir.dot(dirs[r * horRes + c]);
        if ((diff < 1.0f - cos(dirThresh * M_PI / 180.0)) && diff < bestDiff) {
          bestCoord.first = r;
          bestCoord.second = c;
          bestDiff = diff;
        }
      }
    }
  }
  // if(bestCoord.first == -1 && bestCoord.second == -1){
  //   cout << "bestDiff = " << acos(1.0 - bestDiffAll) * 180.0 / M_PI << endl;
  // }

  return bestCoord;
}

VisualView::MatrixInt
VisualView::getMask(const laser_slam_ros::PointCloud &point_cloud) const {
  MatrixInt mask;
  mask.resize(vertRes, horRes);
  mask.setZero();

  for(int p = 0; p < point_cloud.size(); ++p) {
    Eigen::Vector3d ptSensor = pose.T_w.inverseTransform(point_cloud.at(p).getVector3fMap().cast<double>());

    // narrowing down search area
    int horCoordComp = getHorCoord(ptSensor(0), ptSensor(1), ptSensor(2));
    int vertCoordComp = getVertCoord(ptSensor(0), ptSensor(1), ptSensor(2));
    int r1 = std::max(0, vertCoordComp - 16);
    int r2 = std::min(vertRes, vertCoordComp + 16);
    int c1 = std::max(0, horCoordComp - 32);
    int c2 = std::min(horRes, horCoordComp + 32);

    std::pair<int, int> coord = getClosestDir(ptSensor(0), ptSensor(1), ptSensor(2),
                                              r1, c1, r2, c2);
    int horCoord = coord.second;
    int vertCoord = coord.first;

    // {
    //   Eigen::Vector3f dir = ptSensor.normalized().cast<float>();
    //   std::vector<int> idxs;
    //   std::vector<float> dists;
    //   kdtree.nearestKSearch(pcl::PointXYZ(dir(0), dir(1), dir(2)), 4, idxs, dists);
    //
    //   std::pair<int, int> coordComp(-1, -1);
    //
    //   float bestDiff = std::numeric_limits<float>::max();
    //   for (int i = 0; i < idxs.size(); ++i){
    //     int r = idxToCoord.at(idxs[i]).first;
    //     int c = idxToCoord.at(idxs[i]).second;
    //
    //     if(range(r, c) > rangeThresh) {
    //       float diff = 1.0f - dir.dot(dirs[r * horRes + c]);
    //       if ((diff < 1.0f - cos(dirThresh * M_PI / 180.0)) && diff < bestDiff) {
    //         coordComp.first = r;
    //         coordComp.second = c;
    //         bestDiff = diff;
    //       }
    //     }
    //   }
    //
    //   if (coordComp.first != coord.first || coordComp.second != coord.second) {
    //       LOG(INFO) << "coord = (" << coord.first << ", " << coord.second << "), coordComp = ("
    //                 << coordComp.first << ", " << coordComp.second << "), coordProj = ("
    //                 << vertCoordComp << ", " << horCoordComp << ")";
    //       LOG(INFO) << "diff = " << 1.0f - dir.dot(dirs[coord.first * horRes + coord.second])
    //                 << ", diffComp = " << 1.0f - dir.dot(dirs[coordComp.first * horRes + coordComp.second]);
    //     }
    // }
    // {
    //   int r1 = std::max(0, vertCoordComp - 12);
    //   int r2 = std::min(vertRes - 1, vertCoordComp + 12);
    //   int c1 = std::max(0, horCoordComp - 28);
    //   int c2 = std::min(horRes - 1, horCoordComp + 28);
    //
    //   std::pair<int, int> coordComp = getClosestDir(ptSensor(0), ptSensor(1), ptSensor(2),
    //                                             r1, c1, r2, c2);
    //   if (coordComp.first != coord.first || coordComp.second != coord.second) {
    //     LOG(INFO) << "coord = (" << coord.first << ", " << coord.second << "), coordComp = ("
    //               << coordComp.first << ", " << coordComp.second << "), coordProj = ("
    //               << vertCoordComp << ", " << horCoordComp << ")";
    //   }
    // }

    // cout << p << ": (" << ptSensor(0) << ", " << ptSensor(1) << ", " << ptSensor(2) << ")" << endl;
    // cout << "horCoord1 = " << horCoord << "\tvertCoord1 = " << vertCoord << endl;
    // cout << "horCoord2 = " << horCoordComp << "\tvertCoord2 = " << vertCoordComp << endl;

    if(0 <= horCoord && horCoord < horRes && 0 <= vertCoord && vertCoord < vertRes) {
      if(ptSensor.norm() < range(vertCoord, horCoord) + occlusionThresh) {
        mask(vertCoord, horCoord) += 1;
      }
    }
    // else{
    //   cout << "horCoord1 = " << horCoord << "\tvertCoord1 = " << vertCoord << endl;
    //   cout << "horCoord2 = " << horCoordComp << "\tvertCoord2 = " << vertCoordComp << endl;
    // }
  }
  return mask;
}

std::vector<uint8_t> VisualView::compressData(const std::vector<uint8_t> &data) {
  std::stringstream compressed;
  std::stringstream decompressed;
  decompressed << std::string((char*)data.data(), data.size());
  boost::iostreams::filtering_streambuf<boost::iostreams::input> out;
  out.push(boost::iostreams::zlib_compressor());
  out.push(decompressed);
  boost::iostreams::copy(out, compressed);
  std::string compressedStr = compressed.str();
  return std::vector<uint8_t>(compressedStr.begin(), compressedStr.end());
}

std::vector<uint8_t> VisualView::decompressData(const std::vector<uint8_t> &dataComp) {
  std::stringstream compressed;
  std::stringstream decompressed;
  compressed << std::string((char*)dataComp.data(), dataComp.size());
  boost::iostreams::filtering_streambuf<boost::iostreams::input> in;
  in.push(boost::iostreams::zlib_decompressor());
  in.push(compressed);
  boost::iostreams::copy(in, decompressed);
  std::string decompressedStr = decompressed.str();
  return std::vector<uint8_t>(decompressedStr.begin(), decompressedStr.end());
}

void VisualView::compress() {
  if(intensity.size() > 0){
    std::vector<uint8_t> data((uint8_t*)intensity.data(), (uint8_t*)intensity.data() + intensity.size() * sizeof(float));
    intensityComp = compressData(data);
    intensity.resize(0, 0);
    // cout << "data.size() = " << data.size() << endl;
    // std::vector<uint8_t> dataComp = compressData(data);
    // cout << "dataComp.size() = " << dataComp.size() << endl;
    // std::vector<uint8_t> data2 = decompressData(dataComp);
    // cout << "data2.size() = " << data2.size() << endl;
    // Matrix intensity2 = Eigen::Map<Matrix>((float*)data2.data(), vertRes, horRes);
    // if(intensity != intensity2) {
    //   cout << endl << "Matrices dont match" << endl << endl;
    //   cout << intensity << endl;
    //   cout << intensity2 << endl;
    // }
    // else{
    //   cout << endl << "Matrices match :)" << endl << endl;
    // }
  }
  if(range.size() > 0){
    std::vector<uint8_t> data((uint8_t*)range.data(), (uint8_t*)range.data() + range.size() * sizeof(float));
    rangeComp = compressData(data);
    range.resize(0, 0);
  }
  if(count.size() > 0){
    std::vector<uint8_t> data((uint8_t*)count.data(), (uint8_t*)count.data() + count.size() * sizeof(int));
    countComp = compressData(data);
    count.resize(0, 0);
  }
  if(dirs.size() > 0){
    std::vector<uint8_t> data((uint8_t*)dirs.data(), (uint8_t*)dirs.data() + dirs.size() * sizeof(Eigen::Vector3f));
    dirsComp = compressData(data);
    dirs.clear();
  }
  // kdtree.reset();
  // idxToCoord.clear();
  isCompressedFlag = true;
}

void VisualView::decompress() {
  if(intensityComp.size() > 0) {
    std::vector<uint8_t> data = decompressData(intensityComp);
    intensity = Eigen::Map<Matrix>((float*)data.data(), vertRes, horRes);
    intensityComp.clear();
    // cout << "intensity decompressed" << endl;
  }
  if(rangeComp.size() > 0) {
    std::vector<uint8_t> data = decompressData(rangeComp);
    range = Eigen::Map<Matrix>((float*)data.data(), vertRes, horRes);
    rangeComp.clear();
    // cout << "range decompressed" << endl;
  }
  if(countComp.size() > 0) {
    std::vector<uint8_t> data = decompressData(countComp);
    count = Eigen::Map<MatrixInt>((int*)data.data(), vertRes, horRes);
    countComp.clear();
    // cout << "count decompressed" << endl;
  }
  if(dirsComp.size() > 0) {
    std::vector<uint8_t> data = decompressData(dirsComp);
    dirs = std::vector<Eigen::Vector3f>((Eigen::Vector3f*)data.data(), (Eigen::Vector3f*)data.data() + vertRes * horRes);
    dirsComp.clear();
    // cout << "dirs decompressed" << endl;
  }
  // buildKdtree();

  isCompressedFlag = false;
}

// void VisualView::buildKdtree() {
//   LOG(INFO) << "Building kdtree";
//
//   idxToCoord.clear();
//   kdtree.reset(new pcl::KdTreeFLANN<pcl::PointXYZ>());
//
//   pcl::PointCloud<pcl::PointXYZ>::Ptr dirsPointCloud(new pcl::PointCloud<pcl::PointXYZ>());
//   for(int r = 0; r < vertRes; ++r) {
//     for (int c = 0; c < horRes; ++c) {
//       if (count(r, c) > 0) {
//         idxToCoord[dirsPointCloud->size()] = std::make_pair(r, c);
//         dirsPointCloud->push_back(pcl::PointXYZ(dirs[r * horRes + c](0),
//                                                 dirs[r * horRes + c](1),
//                                                 dirs[r * horRes + c](2)));
//       }
//     }
//   }
//
//   kdtree->setInputCloud(dirsPointCloud);
// }

int VisualView::ids = 0;

}


text:
//
// Copyright (c) 2016 Marat Abrarov (abrarov@gmail.com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE or copy at http://www.boost.org/LICENSE_1_0.txt)
//

#include <cstddef>
#include <iterator>
#include <stdexcept>
#include <boost/asio.hpp>
#include <gtest/gtest.h>
#include <ma/cyclic_buffer.hpp>

namespace ma {
namespace test {
namespace cyclic_buffer_test {

class generic_test : public testing::TestWithParam<std::size_t>
{
}; // class generic_test

INSTANTIATE_TEST_CASE_P(buffer_size, generic_test,
    testing::Values(0, 1, 2, 3, 5, 128));

TEST_P(generic_test, size)
{
  const std::size_t buffer_size = GetParam();
  const ma::cyclic_buffer buffer(buffer_size);
  ASSERT_EQ(buffer_size, buffer.size());
}

TEST_P(generic_test, free_size_of_empty)
{
  typedef ma::cyclic_buffer::mutable_buffers_type mutable_buffers_type;
  const std::size_t buffer_size = GetParam();
  const ma::cyclic_buffer buffer(buffer_size);
  const mutable_buffers_type free_space = buffer.prepared();
  ASSERT_EQ(buffer_size, boost::asio::buffer_size(free_space));
}

TEST_P(generic_test, filled_size_of_empty)
{
  typedef ma::cyclic_buffer::const_buffers_type const_buffers_type;
  const std::size_t buffer_size = GetParam();
  const ma::cyclic_buffer buffer(buffer_size);
  const const_buffers_type filled_space = buffer.data();
  ASSERT_EQ(0U, boost::asio::buffer_size(filled_space));
}

TEST_P(generic_test, free_size_of_full)
{
  typedef ma::cyclic_buffer::mutable_buffers_type mutable_buffers_type;
  const std::size_t buffer_size = GetParam();
  ma::cyclic_buffer buffer(buffer_size);
  buffer.consume(buffer_size);
  const mutable_buffers_type free_space = buffer.prepared();
  ASSERT_EQ(0U, boost::asio::buffer_size(free_space));
}

TEST_P(generic_test, filled_size_of_full)
{
  typedef ma::cyclic_buffer::const_buffers_type const_buffers_type;
  const std::size_t buffer_size = GetParam();
  ma::cyclic_buffer buffer(buffer_size);
  buffer.consume(buffer_size);
  const const_buffers_type filled_space = buffer.data();
  ASSERT_EQ(buffer_size, boost::asio::buffer_size(filled_space));
}

TEST_P(generic_test, filled_size_limited)
{
  typedef ma::cyclic_buffer::const_buffers_type const_buffers_type;
  const std::size_t buffer_size = GetParam();
  const std::size_t size_limit = buffer_size / 2;
  ma::cyclic_buffer buffer(buffer_size);
  buffer.consume(buffer_size);
  const const_buffers_type filled_space = buffer.data(size_limit);
  ASSERT_EQ(size_limit, boost::asio::buffer_size(filled_space));
}

TEST_P(generic_test, filled_size_limited_with_too_large_value)
{
  typedef ma::cyclic_buffer::const_buffers_type const_buffers_type;
  const std::size_t buffer_size = GetParam();
  const std::size_t size_limit = buffer_size + 1;
  ma::cyclic_buffer buffer(buffer_size);
  buffer.consume(buffer_size);
  const const_buffers_type filled_space = buffer.data(size_limit);
  ASSERT_EQ(buffer_size, boost::asio::buffer_size(filled_space));
}

TEST_P(generic_test, free_size_limited)
{
  typedef ma::cyclic_buffer::mutable_buffers_type mutable_buffers_type;
  const std::size_t buffer_size = GetParam();
  const std::size_t size_limit = buffer_size / 2;
  const ma::cyclic_buffer buffer(buffer_size);
  const mutable_buffers_type free_space = buffer.prepared(size_limit);
  ASSERT_EQ(size_limit, boost::asio::buffer_size(free_space));
}

TEST_P(generic_test, free_size_limited_with_too_large_value)
{
  typedef ma::cyclic_buffer::mutable_buffers_type mutable_buffers_type;
  const std::size_t buffer_size = GetParam();
  const std::size_t size_limit = buffer_size + 1;
  const ma::cyclic_buffer buffer(buffer_size);
  const mutable_buffers_type free_space = buffer.prepared(size_limit);
  ASSERT_EQ(buffer_size, boost::asio::buffer_size(free_space));
}

TEST_P(generic_test, reset)
{
  typedef ma::cyclic_buffer::mutable_buffers_type mutable_buffers_type;
  const std::size_t buffer_size = GetParam();
  ma::cyclic_buffer buffer(buffer_size);
  // Consume all free space
  buffer.consume(buffer_size);
  buffer.reset();
  // Check that buffer is all free again
  const mutable_buffers_type free_space = buffer.prepared();
  ASSERT_EQ(buffer_size, boost::asio::buffer_size(free_space));
}

TEST_P(generic_test, empty_mutable_buffers)
{
  typedef ma::cyclic_buffer::mutable_buffers_type mutable_buffers_type;
  const std::size_t buffer_size = GetParam();
  ma::cyclic_buffer buffer(buffer_size);
  const mutable_buffers_type zero_buffers = buffer.prepared(0);
  ASSERT_TRUE(zero_buffers.empty());
}

TEST_P(generic_test, empty_const_buffers)
{
  typedef ma::cyclic_buffer::const_buffers_type const_buffers_type;
  const std::size_t buffer_size = GetParam();
  ma::cyclic_buffer buffer(buffer_size);
  const const_buffers_type zero_buffers = buffer.data();
  ASSERT_TRUE(zero_buffers.empty());
}

TEST_P(generic_test, consume_more_than_available)
{
  const std::size_t buffer_size = GetParam();
  ma::cyclic_buffer buffer(buffer_size);
  ASSERT_THROW(buffer.consume(buffer_size + 1), std::length_error);
}

TEST_P(generic_test, commit_more_than_allocated)
{
  const std::size_t buffer_size = GetParam();
  ma::cyclic_buffer buffer(buffer_size);
  ASSERT_THROW(buffer.commit(1), std::length_error);
}

TEST(complex_test, looping_free_space)
{
  typedef ma::cyclic_buffer::mutable_buffers_type mutable_buffers_type;
  ma::cyclic_buffer buffer(16);
  buffer.consume(8);
  buffer.commit(4);
  const mutable_buffers_type free_space = buffer.prepared();
  // 2 buffers should be provided
  ASSERT_EQ(2U, std::distance(free_space.begin(), free_space.end()));
  // Check the size of free space
  ASSERT_EQ(12U, boost::asio::buffer_size(free_space));
}

TEST(complex_test, commit_after_fragmentation)
{
  typedef ma::cyclic_buffer::mutable_buffers_type mutable_buffers_type;
  ma::cyclic_buffer buffer(16);
  buffer.consume(buffer.size());
  buffer.commit(12);
  buffer.consume(4);
  buffer.commit(8);
  const mutable_buffers_type free_space = buffer.prepared();
  // 2 buffers should be provided
  ASSERT_EQ(2U, std::distance(free_space.begin(), free_space.end()));
  // Check the size of free space
  ASSERT_EQ(buffer.size(), boost::asio::buffer_size(free_space));
}

TEST(complex_test, looping_filled_space)
{
  typedef ma::cyclic_buffer::const_buffers_type const_buffers_type;
  ma::cyclic_buffer buffer(16);
  buffer.consume(buffer.size());
  buffer.commit(12);
  buffer.consume(4);
  const const_buffers_type filled_space = buffer.data();
  // 2 buffers should be provided
  ASSERT_EQ(2U, std::distance(filled_space.begin(), filled_space.end()));
  // Check the size of free space
  ASSERT_EQ(8U, boost::asio::buffer_size(filled_space));
}

} // namespace cyclic_buffer_test
} // namespace test
} // namespace ma


text:
/**************************************************************************
** Copyright (C) 2015 Christian Manning
**
** This software may be modified and distributed under the terms
** of the MIT license.  See the LICENSE file for details.
**************************************************************************/

#ifndef LASTFM_MBID
#define LASTFM_MBID

#include <boost/uuid/uuid.hpp>

namespace lastfmpp {

using mbid_t = boost::uuids::uuid;

} // namespace lastfm

#endif // LASTFM_MBID

max_stars_repo_name: chrismanning/lastfmpp

max_issues_repo_name: chrismanning/lastfmpp

max_forks_repo_name: chrismanning/lastfmpp


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

#include "utils/misc.hpp"
#include "pokedex_gbimpl.hpp"

#include "database/database_common.hpp"
#include "database/id_to_string.hpp"
#include "pksav/pksav_call.hpp"

#include <pkmn/exception.hpp>

#include <pksav/common/pokedex.h>

#include <boost/thread/lock_guard.hpp>

#ifndef PKMN_POKEDEX_GBIMPL_IPP
#define PKMN_POKEDEX_GBIMPL_IPP

namespace pkmn
{
    template <typename pksav_type>
    pokedex_gbimpl<pksav_type>::pokedex_gbimpl(
        int game_id,
        pksav_type* p_native
    ): pokedex_impl(game_id)
    {
        const size_t num_bytes = (_generation == 1) ? PKSAV_GEN1_POKEDEX_BUFFER_SIZE_BYTES
                                                    : PKSAV_GEN2_POKEDEX_BUFFER_SIZE_BYTES;
        _seen_buffer.resize(num_bytes, 0);
        _owned_buffer.resize(num_bytes, 0);

        if(p_native != nullptr)
        {
            BOOST_ASSERT(p_native->p_seen != nullptr);
            BOOST_ASSERT(p_native->p_owned != nullptr);

            std::memcpy(
                _seen_buffer.data(),
                p_native->p_seen,
                num_bytes
            );
            std::memcpy(
                _owned_buffer.data(),
                p_native->p_owned,
                num_bytes
            );
        }

        _pksav_pokedex.p_seen  = _seen_buffer.data();
        _pksav_pokedex.p_owned = _owned_buffer.data();

        _p_native = &_pksav_pokedex;
    }

    template <typename pksav_type>
    bool pokedex_gbimpl<pksav_type>::has_seen(
        pkmn::e_species species
    )
    {
        boost::lock_guard<pokedex_gbimpl> lock(*this);

        bool has_seen = false;

        PKSAV_CALL(
            pksav_get_pokedex_bit(
                _pksav_pokedex.p_seen,
                uint16_t(species),
                &has_seen
            );
        )

        return has_seen;
    }

    template <typename pksav_type>
    bool pokedex_gbimpl<pksav_type>::has_caught(
        pkmn::e_species species
    )
    {
        boost::lock_guard<pokedex_gbimpl> lock(*this);

        bool has_caught = false;

        PKSAV_CALL(
            pksav_get_pokedex_bit(
                _pksav_pokedex.p_owned,
                uint16_t(species),
                &has_caught
            );
        )

        return has_caught;
    }

    template <typename pksav_type>
    void pokedex_gbimpl<pksav_type>::_set_has_seen(
        int species_id,
        bool has_seen_value
    )
    {
        PKSAV_CALL(
            pksav_set_pokedex_bit(
                _pksav_pokedex.p_seen,
                uint16_t(species_id),
                has_seen_value
            );
        )
    }

    template <typename pksav_type>
    void pokedex_gbimpl<pksav_type>::_set_has_caught(
        int species_id,
        bool has_caught_value
    )
    {
        PKSAV_CALL(
            pksav_set_pokedex_bit(
                _pksav_pokedex.p_owned,
                uint16_t(species_id),
                has_caught_value
            );
        )
    }

    template <typename pksav_type>
    void pokedex_gbimpl<pksav_type>::_update_all_seen()
    {
        _update_member_vector_with_pksav(
            _pksav_pokedex.p_seen,
            _all_seen
        );
    }

    template <typename pksav_type>
    void pokedex_gbimpl<pksav_type>::_update_all_caught()
    {
        _update_member_vector_with_pksav(
            _pksav_pokedex.p_owned,
            _all_caught
        );
    }
}

#endif /* PKMN_POKEDEX_GBIMPL_IPP */

ext: ipp

max_stars_repo_name: ncorgan/libpkmn

max_issues_repo_name: PMArkive/libpkmn

max_forks_repo_name: PMArkive/libpkmn


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.

#pragma once
#ifndef _POOLMGMT_HH_
#define _POOLMGMT_HH_

#include <string>
#include <unordered_set>
#include <boost/pool/pool_alloc.hpp>
#include <iostream>

class PoolMgmt
{
public:
	typedef std::basic_string<char, std::char_traits<char>, boost::fast_pool_allocator<char>> PoolString;

	struct PoolStringHasher
  	{
      	std::size_t operator()(const PoolString& k) const
      	{
         	size_t h = std::hash<std::string>()(k.data());
         	return h;
      	}
  	};

	struct PoolStringEqualTo
	{
	    bool operator()(const PoolString& p1, const PoolString& p2) const
	    {
	        return (0 == std::strcmp(p1.data(), p2.data()));
	    }
	};

	// This will release all memory blocks that aren’t used at the moment.
	// The memory will be returned to OS.
	static void ReleaseMemory()
	{
		boost::singleton_pool<boost::fast_pool_allocator_tag, sizeof(char)>::release_memory();
		boost::singleton_pool<boost::fast_pool_allocator_tag, sizeof(int)>::release_memory();
		boost::singleton_pool<boost::fast_pool_allocator_tag, sizeof(PoolString)>::release_memory();
	}

	// This will release all memory blocks including those currently used.
	// The memory will be returned to OS.
	static void PurgeMemory()
	{
		boost::singleton_pool<boost::fast_pool_allocator_tag, sizeof(char)>::purge_memory();
		boost::singleton_pool<boost::fast_pool_allocator_tag, sizeof(int)>::purge_memory();
		boost::singleton_pool<boost::fast_pool_allocator_tag, sizeof(PoolString)>::purge_memory();
	}
};

typedef std::unordered_set<PoolMgmt::PoolString, PoolMgmt::PoolStringHasher, PoolMgmt::PoolStringEqualTo, boost::fast_pool_allocator<PoolMgmt::PoolString>> PoolStringUnorderedSet;

#endif

// vim: se sw=8 :

ext: hh

max_stars_repo_name: shridpant/azure-linux-extensions

max_issues_repo_name: shridpant/azure-linux-extensions

max_forks_repo_name: shridpant/azure-linux-extensions