text:
#include "StdInc.h"
#include "ToolComponentHelpers.h"

#include <ShaderInfo.h>

#include "IteratorView.h"

#include <boost/filesystem.hpp>

static void HandleArguments(boost::program_options::wcommand_line_parser& parser, std::function<void()> cb)
{
	boost::program_options::options_description desc;

	desc.add_options()
		("filename", boost::program_options::value<std::vector<boost::filesystem::path>>()->required(), "The path of the file to convert.");

	boost::program_options::positional_options_description positional;
	positional.add("filename", -1);

	parser.options(desc).
		positional(positional);

	cb();
}

static void Run(const boost::program_options::variables_map& map)
{
	if (map.count("filename") == 0)
	{
		printf("Usage:\n\n   fivem formats:exportShaders *.fxc...\n");
		return;
	}

	auto& entries = map["filename"].as<std::vector<boost::filesystem::path>>();

	for (auto& filePath : entries)
	{
		auto shaderFile = fxc::ShaderFile::Load(filePath.wstring());

		/*
		for (auto& shaderPair : shaderFile->GetVertexShaders())
		{
			const auto& name = shaderPair->GetName();
			const auto& data = shaderPair->GetShaderData();

			if (name.find("VS_TransformDeferred") == 0)
			{
				FILE* f = fopen("replace_vs.cso", "rb");
				fseek(f, 0, SEEK_END);

				int l = ftell(f);

				fseek(f, 0, SEEK_SET);

				std::vector<uint8_t> d(l);
				fread(d.data(), 1, d.size(), f);

				fclose(f);

				shaderPair->SetShaderData(d);
			}
		}
		*/

		for (auto& shaderPair : shaderFile->GetPixelShaders())
		{
			const auto& name = shaderPair->GetName();
			const auto& data = shaderPair->GetShaderData();

			FILE* f = fopen(va("%s.cso", name), "wb");
			fwrite(data.data(), 1, data.size(), f);
			fclose(f);
		}

		//shaderFile->Save(filePath.wstring() + L"_edited");
	}
}

static FxToolCommand command("formats:exportShaders", HandleArguments, Run);

max_stars_repo_name: thorium-cfx/fivem

max_issues_repo_name: thorium-cfx/fivem

max_forks_repo_name: thorium-cfx/fivem


text:
//
// Copyright (c) 2016-2017 Vinnie Falco (vinnie dot falco at gmail dot com)
//
// 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)
//
// Official repository: https://github.com/boostorg/beast
//

#ifndef BOOST_BEAST_HTTP_DETAIL_CHUNK_ENCODE_HPP
#define BOOST_BEAST_HTTP_DETAIL_CHUNK_ENCODE_HPP

#include <boost/beast/core/type_traits.hpp>
#include <boost/beast/http/type_traits.hpp>
#include <boost/asio/buffer.hpp>
#include <algorithm>
#include <array>
#include <cstddef>

namespace boost {
namespace beast {
namespace http {
namespace detail {

struct chunk_extensions
{
    virtual ~chunk_extensions() = default;
    virtual boost::asio::const_buffers_1 str() = 0;
};

template<class ChunkExtensions>
struct chunk_extensions_impl : chunk_extensions
{
    ChunkExtensions ext_;

    chunk_extensions_impl(ChunkExtensions&& ext)
        : ext_(std::move(ext))
    {
    }

    chunk_extensions_impl(ChunkExtensions const& ext)
        : ext_(ext)
    {
    }

    boost::asio::const_buffers_1
    str() override
    {
        auto const s = ext_.str();
        return {s.data(), s.size()};
    }
};

template<class T, class = void>
struct is_chunk_extensions : std::false_type {};

template<class T>
struct is_chunk_extensions<T, beast::detail::void_t<decltype(
    std::declval<string_view&>() = std::declval<T&>().str(),
        (void)0)>> : std::true_type
{
};

//------------------------------------------------------------------------------

/** A buffer sequence containing a chunk-encoding header
*/
class chunk_size
{
public:
    // Storage for the longest hex string we might need
    class value_type
    {
        friend class chunk_size;

        // First byte holds the length
        char buf_[1 + 2 * sizeof(std::size_t)];

        template<class = void>
        void
        prepare(std::size_t n);

        template<class OutIter>
        static
        OutIter
        to_hex(OutIter last, std::size_t n)
        {
            if(n == 0)
            {
                *--last = '0';
                return last;
            }
            while(n)
            {
                *--last = "0123456789abcdef"[n&0xf];
                n>>=4;
            }
            return last;
        }
    public:
        operator
        boost::asio::const_buffer() const
        {
            return {
                buf_ + sizeof(buf_) - buf_[0],
                static_cast<unsigned>(buf_[0])};
        }
    };

    using const_iterator = value_type const*;

    chunk_size(chunk_size const& other) = default;

    /** Construct a chunk header

        @param n The number of octets in this chunk.
    */
    chunk_size(std::size_t n)
    {
        value_.prepare(n);
    }

    const_iterator
    begin() const
    {
        return &value_;
    }

    const_iterator
    end() const
    {
        return begin() + 1;
    }

private:
    value_type value_;
};

template<class>
void
chunk_size::
value_type::
prepare(std::size_t n)
{
    auto const last = &buf_[sizeof(buf_)];
    auto it = to_hex(last, n);
    buf_[0] = static_cast<char>(last - it);
}

//------------------------------------------------------------------------------

/// Returns a buffer sequence holding a CRLF for chunk encoding
inline
boost::asio::const_buffers_1
chunk_crlf()
{
    return {"\r\n", 2};
}

/// Returns a buffer sequence holding a final chunk header
inline
boost::asio::const_buffers_1
chunk_last()
{
    return {"0\r\n", 3};
}

//------------------------------------------------------------------------------

template<class = void>
struct chunk_crlf_iter_type
{
    class value_type
    {
        char const s[2] = {'\r', '\n'};

    public:
        value_type() = default;

        operator
        boost::asio::const_buffer() const
        {
            return {s, sizeof(s)};
        }
    };
    static value_type value;
};

template<class T>
typename chunk_crlf_iter_type<T>::value_type
chunk_crlf_iter_type<T>::value;

using chunk_crlf_iter = chunk_crlf_iter_type<void>;

//------------------------------------------------------------------------------

template<class = void>
struct chunk_size0_iter_type
{
    class value_type
    {
        char const s[3] = {'0', '\r', '\n'};

    public:
        value_type() = default;

        operator
        boost::asio::const_buffer() const
        {
            return {s, sizeof(s)};
        }
    };
    static value_type value;
};

template<class T>
typename chunk_size0_iter_type<T>::value_type
chunk_size0_iter_type<T>::value;

using chunk_size0_iter = chunk_size0_iter_type<void>;

struct chunk_size0
{
    using value_type = chunk_size0_iter::value_type;

    using const_iterator = value_type const*;

    const_iterator
    begin() const
    {
        return &chunk_size0_iter::value;
    }

    const_iterator
    end() const
    {
        return begin() + 1;
    }
};

//------------------------------------------------------------------------------

template<class T,
    bool = is_fields<T>::value>
struct buffers_or_fields
{
    using type = typename
        T::reader::const_buffers_type;
};

template<class T>
struct buffers_or_fields<T, false>
{
    using type = T;
};

} // detail
} // http
} // beast
} // boost

#endif

ext: hpp

max_stars_repo_name: Voultapher/Presentations

max_issues_repo_name: HowardHinnant/beast


text:
//
// Created by tudom on 2019-12-28.
//

#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wused-but-marked-unused"
#pragma once

#pragma clang diagnostic push
#pragma ide diagnostic ignored "MemberFunctionCanBeStaticInspection"
#pragma ide diagnostic ignored "cert-err58-cpp"

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

#include <liblucent/lucent.hpp>

BOOST_AUTO_TEST_SUITE(Demangler)
  using namespace liblucent;

  BOOST_AUTO_TEST_CASE(Demangle_shouldReturnSameString_ifNotMangledNameIsGiven) {
      std::string inp{"SomeNonMangledName"};
      auto ret = Demangle(inp);

      BOOST_CHECK_EQUAL(ret, inp);
  }

  BOOST_AUTO_TEST_CASE(Demangle_shouldReturnCorrectlyDemangledName) {
      std::string inp{
#ifdef LIBLUCENT_MSABI_MANGING_SCHEME
             "??$func@H@@YAXHPEAH$$QEAHP6AXXZA6AHH@Z@Z"
#else
             "_Z2iiiOPiKRKiPFviE"
#endif
      };

      BOOST_CHECK_EQUAL(Demangle(inp), "ii(int, int*&&, int const& const, void (*)(int))");
  }

BOOST_AUTO_TEST_SUITE_END()

#pragma clang diagnostic pop

#pragma clang diagnostic pop

max_stars_repo_name: isbodand/InfoDynamite

max_issues_repo_name: isbodand/InfoDynamite

max_forks_repo_name: isbodand/InfoDynamite


text:
#ifndef EXPSUM_KERNEL_FUNCTIONS_BESSEL_KERNEL_HPP
#define EXPSUM_KERNEL_FUNCTIONS_BESSEL_KERNEL_HPP

#include <cassert>
#include <cmath>

#include <armadillo>

namespace expsum
{

template <typename T>
struct bessel_j_kernel
{
public:
    using size_type   = arma::uword;
    using real_type   = T;
    using vector_type = arma::Col<T>;
    using matrix_type = arma::Mat<T>;

private:
    vector_type exponent_;
    vector_type weight_;
    real_type v_;   // order of Bessel function Jv(x)
    real_type eps_; // tolerance

public:
    void compute(real_type v, real_type eps);

    size_type size() const
    {
        return exponent_.size();
    }

    const vector_type& exponents() const
    {
        return exponent_;
    }

    const vector_type& weights() const
    {
        return weight_;
    }

private:
};

template <typename T>
void bessel_j_kernel<T>::compute(real_type v, real_type eps)
{
}

} // namespace: expsum

#endif /* EXPSUM_KERNEL_FUNCTIONS_BESSEL_KERNEL_HPP */

max_stars_repo_name: hide-ikeno/expsum

max_issues_repo_name: hide-ikeno/expsum

max_forks_repo_name: hide-ikeno/expsum


text:
/**
 *  @copyright Copyright 2018 The J-PET Framework Authors. All rights reserved.
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may find a copy of the License in the LICENCE file.
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 *  @file JPetPMTest.cpp
 */

#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE JPetPMTest

#include "JPetPM/JPetPM.h"
#include "JPetPM/JPetPMFactory.h"

#include <boost/test/unit_test.hpp>

BOOST_AUTO_TEST_SUITE(FirstSuite)

BOOST_AUTO_TEST_CASE(default_constructor)
{
  JPetPM pm;
  float epsilon = 0.0001;
  BOOST_REQUIRE_EQUAL(pm.getSide(), JPetPM::SideA);
  BOOST_REQUIRE_EQUAL(pm.getID(), 0);
  BOOST_REQUIRE_EQUAL(pm.getHVset(), 0);
  BOOST_REQUIRE_EQUAL(pm.getHVopt(), 0);
  BOOST_REQUIRE_CLOSE(pm.getHVgain(JPetPM::kFirst), 0, epsilon);
  BOOST_REQUIRE_CLOSE(pm.getHVgain(JPetPM::kSecond), 0, epsilon);
  BOOST_REQUIRE_EQUAL(pm.getDescription(), "");
  BOOST_CHECK_EQUAL(pm.isNullObject(), false);
  BOOST_REQUIRE(!pm.hasFEB());
}

BOOST_AUTO_TEST_SUITE_END()

BOOST_AUTO_TEST_SUITE(FactorySuite)

class TestParamGetter : public JPetParamGetter
{
  ParamObjectsDescriptions getAllBasicData(ParamObjectType type, const int runId)
  {
    ParamObjectsDescriptions result;
    switch (type)
    {
    case ParamObjectType::kPM:
      switch (runId)
      {
      case 0: // No PMs
        break;
      case 1: // Simple single object
      case 5: // Wrong FEB relation
      case 6: // Wrong scin relation
      case 7: // Wrong barrel slot relation
        result = {{1, {{"id", "1"}, {"is_right_side", "1"}, {"description", "no writing"}}}};
        break;
      case 2: // Simple two objects
        result = {{1, {{"id", "1"}, {"is_right_side", "1"}, {"description", "no writing"}}},
                  {5, {{"id", "5"}, {"is_right_side", "0"}, {"description", "some writing"}}}};
        break;
      case 3: // Object with missing field
        result = {{1, {{"id", "1"}, {"description", "some writing"}}}};
        break;
      case 4: // Object with wrong field
        result = {{1, {{"id", "1"}, {"is_right_side", "probably"}, {"description", "some writing"}}}};
        break;
      }
      break;
    case ParamObjectType::kFEB:
      result = {{1,
                 {{"id", "1"},
                  {"active", "1"},
                  {"status", "healthy"},
                  {"description", "tall"},
                  {"version", "27"},
                  {"creator_id", "44"},
                  {"time_outputs_per_input", "2"},
                  {"no_time_outputs_per_input", "3"}}}};
      break;
    case ParamObjectType::kTRB:
      result = {{1, {{"id", "1"}, {"type", "1"}, {"channel", "224"}}}};
      break;
    case ParamObjectType::kScintillator:
      result = {{1, {{"id", "1"}, {"attenuation_length", "10.34"}, {"length", "100"}, {"width", "4.5"}, {"height", "2.5"}}}};
      break;
    case ParamObjectType::kBarrelSlot:
      result = {{1, {{"id", "1"}, {"active", "1"}, {"name", "pepe"}, {"theta1", "5.5"}, {"frame_id", "6"}}}};
      break;
    case ParamObjectType::kLayer:
      result = {{1, {{"id", "1"}, {"active", "1"}, {"name", "ala"}, {"radius", "10.5"}}}};
      break;
    case ParamObjectType::kFrame:
      result = {{1, {{"id", "1"}, {"active", "1"}, {"status", "ok"}, {"description", "descr1"}, {"version", "2"}, {"creator_id", "1"}}}};
      break;
    default: // Other cases not needed.
      break;
    }
    return result;
  }
  ParamRelationalData getAllRelationalData(ParamObjectType type1, ParamObjectType type2, const int runId)
  {
    ParamRelationalData result;
    switch (type1)
    {
    case ParamObjectType::kPM:
      switch (runId)
      {
      case 0: // No relations
        break;
      case 1: // Simple single object
        result = {{1, 1}};
        break;
      case 2: // Simple two objects
        result = {{1, 1}, {5, 1}};
        break;
      case 5: // Wrong FEB relation
        switch (type2)
        {
        case ParamObjectType::kFEB:
          result = {{1, 43}};
          break;
        default:
          result = {{1, 1}};
          break;
        }
      case 6: // Wrong scin relation
        switch (type2)
        {
        case ParamObjectType::kScintillator:
          result = {{1, 43}};
          break;
        default:
          result = {{1, 1}};
          break;
        }
      case 7: // Wrong barrel slot relation
        switch (type2)
        {
        case ParamObjectType::kBarrelSlot:
          result = {{1, 43}};
          break;
        default:
          result = {{1, 1}};
          break;
        }
      }
      break;
    default:
      result = {{1, 1}};
      break;
    }
    return result;
  }
};

TestParamGetter paramGetter;

BOOST_AUTO_TEST_CASE(no_pms)
{
  JPetTRBFactory trbFactory(paramGetter, 0);
  JPetFEBFactory febFactory(paramGetter, 0, trbFactory);
  JPetFrameFactory frameFactory(paramGetter, 0);
  JPetLayerFactory layerFactory(paramGetter, 0, frameFactory);
  JPetBarrelSlotFactory barrelSlotFactory(paramGetter, 0, layerFactory);
  JPetScinFactory scinFactory(paramGetter, 0, barrelSlotFactory);
  JPetPMFactory factory(paramGetter, 0, febFactory, scinFactory, barrelSlotFactory);
  auto& pms = factory.getPMs();
  BOOST_REQUIRE_EQUAL(pms.size(), 0u);
}

BOOST_AUTO_TEST_CASE(single_object)
{
  JPetTRBFactory trbFactory(paramGetter, 1);
  JPetFEBFactory febFactory(paramGetter, 1, trbFactory);
  JPetFrameFactory frameFactory(paramGetter, 1);
  JPetLayerFactory layerFactory(paramGetter, 1, frameFactory);
  JPetBarrelSlotFactory barrelSlotFactory(paramGetter, 1, layerFactory);
  JPetScinFactory scinFactory(paramGetter, 1, barrelSlotFactory);
  JPetPMFactory factory(paramGetter, 1, febFactory, scinFactory, barrelSlotFactory);
  auto& pms = factory.getPMs();
  BOOST_REQUIRE_EQUAL(pms.size(), 1u);
  auto pm = pms[1];
  BOOST_REQUIRE_EQUAL(pm->getID(), 1);
  BOOST_REQUIRE_EQUAL(pm->getSide(), JPetPM::SideB);
  BOOST_REQUIRE(pm->hasFEB());
  BOOST_REQUIRE_EQUAL(pm->getFEB().getID(), febFactory.getFEBs().at(1)->getID());
  BOOST_REQUIRE_EQUAL(pm->getScin().getID(), scinFactory.getScins().at(1)->getID());
  BOOST_REQUIRE_EQUAL(pm->getBarrelSlot().getID(), barrelSlotFactory.getBarrelSlots().at(1)->getID());
}

BOOST_AUTO_TEST_CASE(two_objects)
{
  JPetTRBFactory trbFactory(paramGetter, 2);
  JPetFEBFactory febFactory(paramGetter, 2, trbFactory);
  JPetFrameFactory frameFactory(paramGetter, 2);
  JPetLayerFactory layerFactory(paramGetter, 2, frameFactory);
  JPetBarrelSlotFactory barrelSlotFactory(paramGetter, 2, layerFactory);
  JPetScinFactory scinFactory(paramGetter, 2, barrelSlotFactory);
  JPetPMFactory factory(paramGetter, 2, febFactory, scinFactory, barrelSlotFactory);
  auto& pms = factory.getPMs();
  BOOST_REQUIRE_EQUAL(pms.size(), 2u);
  auto pm = pms[1];
  BOOST_REQUIRE_EQUAL(pm->getID(), 1);
  BOOST_REQUIRE_EQUAL(pm->getSide(), JPetPM::SideB);
  BOOST_REQUIRE(pm->hasFEB());
  BOOST_REQUIRE_EQUAL(pm->getFEB().getID(), febFactory.getFEBs().at(1)->getID());
  BOOST_REQUIRE_EQUAL(pm->getScin().getID(), scinFactory.getScins().at(1)->getID());
  BOOST_REQUIRE_EQUAL(pm->getBarrelSlot().getID(), barrelSlotFactory.getBarrelSlots().at(1)->getID());
  pm = pms[5];
  BOOST_REQUIRE_EQUAL(pm->getID(), 5);
  BOOST_REQUIRE_EQUAL(pm->getSide(), JPetPM::SideA);
  BOOST_REQUIRE(pm->hasFEB());
  BOOST_REQUIRE_EQUAL(pm->getFEB().getID(), febFactory.getFEBs().at(1)->getID());
  BOOST_REQUIRE_EQUAL(pm->getScin().getID(), scinFactory.getScins().at(1)->getID());
  BOOST_REQUIRE_EQUAL(pm->getBarrelSlot().getID(), barrelSlotFactory.getBarrelSlots().at(1)->getID());
}

BOOST_AUTO_TEST_CASE(missing_field)
{
  JPetTRBFactory trbFactory(paramGetter, 3);
  JPetFEBFactory febFactory(paramGetter, 3, trbFactory);
  JPetFrameFactory frameFactory(paramGetter, 3);
  JPetLayerFactory layerFactory(paramGetter, 3, frameFactory);
  JPetBarrelSlotFactory barrelSlotFactory(paramGetter, 3, layerFactory);
  JPetScinFactory scinFactory(paramGetter, 3, barrelSlotFactory);
  JPetPMFactory factory(paramGetter, 3, febFactory, scinFactory, barrelSlotFactory);
  BOOST_REQUIRE_THROW(factory.getPMs(), std::out_of_range);
}

BOOST_AUTO_TEST_CASE(wrong_field)
{
  JPetTRBFactory trbFactory(paramGetter, 4);
  JPetFEBFactory febFactory(paramGetter, 4, trbFactory);
  JPetFrameFactory frameFactory(paramGetter, 4);
  JPetLayerFactory layerFactory(paramGetter, 4, frameFactory);
  JPetBarrelSlotFactory barrelSlotFactory(paramGetter, 4, layerFactory);
  JPetScinFactory scinFactory(paramGetter, 4, barrelSlotFactory);
  JPetPMFactory factory(paramGetter, 4, febFactory, scinFactory, barrelSlotFactory);
  BOOST_REQUIRE_THROW(factory.getPMs(), std::bad_cast);
}

BOOST_AUTO_TEST_CASE(wrong_feb_relation)
{
  JPetTRBFactory trbFactory(paramGetter, 5);
  JPetFEBFactory febFactory(paramGetter, 5, trbFactory);
  JPetFrameFactory frameFactory(paramGetter, 5);
  JPetLayerFactory layerFactory(paramGetter, 5, frameFactory);
  JPetBarrelSlotFactory barrelSlotFactory(paramGetter, 5, layerFactory);
  JPetScinFactory scinFactory(paramGetter, 5, barrelSlotFactory);
  JPetPMFactory factory(paramGetter, 5, febFactory, scinFactory, barrelSlotFactory);
  BOOST_REQUIRE_THROW(factory.getPMs(), std::out_of_range);
}

BOOST_AUTO_TEST_CASE(wrong_scin_relation)
{
  JPetTRBFactory trbFactory(paramGetter, 6);
  JPetFEBFactory febFactory(paramGetter, 6, trbFactory);
  JPetFrameFactory frameFactory(paramGetter, 6);
  JPetLayerFactory layerFactory(paramGetter, 6, frameFactory);
  JPetBarrelSlotFactory barrelSlotFactory(paramGetter, 6, layerFactory);
  JPetScinFactory scinFactory(paramGetter, 6, barrelSlotFactory);
  JPetPMFactory factory(paramGetter, 6, febFactory, scinFactory, barrelSlotFactory);
  BOOST_REQUIRE_THROW(factory.getPMs(), std::out_of_range);
}

BOOST_AUTO_TEST_CASE(wrong_barrelSlot_relation)
{
  JPetTRBFactory trbFactory(paramGetter, 7);
  JPetFEBFactory febFactory(paramGetter, 7, trbFactory);
  JPetFrameFactory frameFactory(paramGetter, 7);
  JPetLayerFactory layerFactory(paramGetter, 7, frameFactory);
  JPetBarrelSlotFactory barrelSlotFactory(paramGetter, 7, layerFactory);
  JPetScinFactory scinFactory(paramGetter, 7, barrelSlotFactory);
  JPetPMFactory factory(paramGetter, 7, febFactory, scinFactory, barrelSlotFactory);
  BOOST_REQUIRE_THROW(factory.getPMs(), std::out_of_range);
}

BOOST_AUTO_TEST_SUITE_END()

ext: cpp

max_stars_repo_name: BlurredChoise/j-pet-framework

max_issues_repo_name: BlurredChoise/j-pet-framework

max_forks_repo_name: BlurredChoise/j-pet-framework


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

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

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

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

 /*!

    @ingroup group-arithmetic
    Function object implementing remainder capabilities

    Computes the remainder of division.
    The return value is x-n*y, where n is the value x/y,
    rounded to the nearest integer (using round2even).

    @par semantic:
    For any given value @c x, @c y of type @c T:

    @code
    T r = remainder(x, y);
    @endcode

    For floating point values the code is similar to:

    @code
    T r = x-divround2even(x, y)*y;
    @endcode

    @par Note:

    As r can be negative, @c remainder is not defined for unsigned types.

    For floating entries:
       -  if x is +/-inf , Nan is returned
       -  If y is +/-0   , Nan is returned
       -  If either argument is NaN, Nan is returned
       -  If the returned value is 0, it will have the same sign as x.

    If correct values for these limit cases do not matter for you, using the fast_ decorator
    can gain some cycles.

    @see mod, rem, modulo

    @par Alias

    @c drem

    @par Decorators

    fast_ for floating entries

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

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

#endif


text:
#ifndef STAN_MATH_PRIM_PROB_SCALED_INV_CHI_SQUARE_RNG_HPP
#define STAN_MATH_PRIM_PROB_SCALED_INV_CHI_SQUARE_RNG_HPP

#include <stan/math/prim/meta.hpp>
#include <stan/math/prim/err.hpp>
#include <stan/math/prim/fun/max_size.hpp>
#include <boost/random/chi_squared_distribution.hpp>
#include <boost/random/variate_generator.hpp>

namespace stan {
namespace math {

/** \ingroup prob_dists
 * Return a scaled chi square random variate for the given
 * number of degrees of freedom and scale using the specified random
 * number generator.
 *
 * nu and sigma can each be a scalar or a one-dimensional container. Any
 * non-scalar inputs must be the same size.
 *
 * @tparam T_deg type of degrees of freedom parameter
 * @tparam T_scale type of scale parameter
 * @tparam RNG type of random number generator
 * @param nu (Sequence of) positive degrees of freedom parameter(s)
 * @param s (Sequence of) positive scale parameter(s)
 * @param rng random number generator
 * @return (Sequence of) scaled chi square random variate(s)
 * @throw std::domain_error if nu or sigma are nonpositive
 * @throw std::invalid_argument if non-scalar arguments are of different
 * sizes
 */
template <typename T_deg, typename T_scale, class RNG>
inline typename VectorBuilder<true, double, T_deg, T_scale>::type
scaled_inv_chi_square_rng(const T_deg& nu, const T_scale& s, RNG& rng) {
  using boost::variate_generator;
  using boost::random::chi_squared_distribution;
  static const char* function = "scaled_inv_chi_square_rng";
  check_positive_finite(function, "Degrees of freedom parameter", nu);
  check_positive_finite(function, "Scale parameter", s);
  check_consistent_sizes(function, "Location parameter", nu, "Scale Parameter",
                         s);

  scalar_seq_view<T_deg> nu_vec(nu);
  scalar_seq_view<T_scale> s_vec(s);
  size_t N = max_size(nu, s);
  VectorBuilder<true, double, T_deg, T_scale> output(N);

  for (size_t n = 0; n < N; ++n) {
    variate_generator<RNG&, chi_squared_distribution<> > chi_square_rng(
        rng, chi_squared_distribution<>(nu_vec[n]));
    output[n] = nu_vec[n] * s_vec[n] * s_vec[n] / chi_square_rng();
  }

  return output.data();
}

}  // namespace math
}  // namespace stan
#endif

max_stars_repo_name: HaoZeke/math

max_issues_repo_name: HaoZeke/math

max_forks_repo_name: SteveBronder/math


text:
#ifndef RICPAD_DIFFERENTIATE
#define RICPAD_DIFFERENTIATE

#include <Eigen/Dense>

namespace solver {

template <typename T, int N>
T differentiate(
        // A function which takes an Eigen Matrix
        const std::function<T(Eigen::Matrix<T,N,1>&)>& f,
        // The variables contained in an Eigen matrix
        const Eigen::Matrix<T, N, 1>& x,
        // With respect to which variable we differentiate
        const int k,
        // Step size
        const T& h
      )
{
    Eigen::Matrix<T, N, 1> xp(x), xm(x);

    xp(k) += h;
    xm(k) -= h;

    T ans = f(xp) - f(xm);
    ans /= (h*T(2));

    return ans;
};

}; // namespace differentiate
#endif

max_stars_repo_name: javierelpianista/solver

max_issues_repo_name: javierelpianista/solver

max_forks_repo_name: javierelpianista/solver


text:
/*
 * Copyright 2019-2021 Azavea
 *
 * 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.
 */

#define BOOST_TEST_MODULE Token Unit Tests
#include <boost/test/included/unit_test.hpp>

#include "bindings.h"
#include "tokens.hpp"

#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wwrite-strings"
const char *options1[] = {
    "-of", "MEM",
    "-tap", "-tr", "7", "11",
    "-r", "bilinear",
    "-t_srs", "epsg:3857",
    nullptr};
const char *options2[] = {
    "-of", "MEM",
    "-tap", "-tr", "7", "11",
    "-t_srs", "epsg:3857",
    nullptr};
const char *uri1 = "geo.tif";
const char *uri2 = "geo2.tif";
#pragma GCC diagnostic pop

BOOST_AUTO_TEST_CASE(get_unique_token_test)
{
    token_init(16);
    auto token = get_token(uri1, options1);

    BOOST_TEST(token == static_cast<token_t>(33));
    token_deinit();
}

BOOST_AUTO_TEST_CASE(get_same_token_test)
{
    token_init(16);
    auto token1 = get_token(uri1, options1);
    auto token2 = get_token(uri1, options1);

    BOOST_TEST(token1 == static_cast<token_t>(33));
    BOOST_TEST(token1 != token2);
    token_deinit();
}

BOOST_AUTO_TEST_CASE(get_different_uri_tokens_test)
{
    token_init(16);
    auto token1 = get_token(uri1, options1);
    auto token2 = get_token(uri2, options1);

    BOOST_TEST(token1 == static_cast<token_t>(33));
    BOOST_TEST(token1 != token2);
    token_deinit();
}

BOOST_AUTO_TEST_CASE(get_different_options_tokens_test)
{
    token_init(16);
    auto token1 = get_token(uri1, options1);
    auto token2 = get_token(uri1, options2);

    BOOST_TEST(token1 == static_cast<token_t>(33));
    BOOST_TEST(token1 != token2);
    token_deinit();
}

BOOST_AUTO_TEST_CASE(token_eviction_test)
{
    token_init(3);
    auto token1 = get_token(uri1, options1);
    auto token2 = get_token(uri1, options2);
    auto token3 = get_token(uri2, options1);
    auto token4 = get_token(uri2, options2);

    BOOST_TEST(query_token(token1).is_initialized() == false);
    BOOST_TEST(query_token(token2).is_initialized() == true);
    BOOST_TEST(query_token(token3).is_initialized() == true);
    BOOST_TEST(query_token(token4).is_initialized() == true);
}

BOOST_AUTO_TEST_CASE(token_lru_eviction_test)
{
    token_init(3);
    auto token1 = get_token(uri1, options1);
    auto token2 = get_token(uri1, options2);
    auto token3 = get_token(uri2, options1);
    query_token(token1);
    auto token4 = get_token(uri2, options2);

    BOOST_TEST(query_token(token1).is_initialized() == true);
    BOOST_TEST(query_token(token2).is_initialized() == false);
    BOOST_TEST(query_token(token3).is_initialized() == true);
    BOOST_TEST(query_token(token4).is_initialized() == true);
}

namespace std
{
std::ostream &operator<<(std::ostream &out, const uri_options_t &rhs)
{
    return (out << rhs.first << " " << rhs.second.size());
}
} // namespace std

BOOST_AUTO_TEST_CASE(query_test)
{
    token_init(16);

    auto token1 = static_cast<uint64_t>(42);
    auto actual1 = query_token(token1).is_initialized();
    auto expected1 = false;
    BOOST_TEST(actual1 == expected1);

    auto token2 = get_token(uri1, options1);
    auto actual2 = query_token(token2).value();
    auto expected2 = uri_options_t{uri_t{uri1}, options_t{}};
    for (auto p = options1; *p != nullptr; ++p)
    {
        expected2.second.push_back(*p);
    }
    BOOST_TEST(actual2 == expected2);

    auto token3 = get_token(uri1, options2);
    auto actual3 = query_token(token3).value();
    auto expected3 = std::make_pair(uri_t{uri1}, options_t{});
    for (auto p = options2; *p != nullptr; ++p)
    {
        expected3.second.push_back(*p);
    }
    BOOST_TEST(actual3 == expected3);

    token_deinit();
}

max_stars_repo_name: jamesmcclain/gdal-warp-bindings

max_issues_repo_name: geotrellis/gdal-warp-bindings

max_forks_repo_name: geotrellis/gdal-warp-bindings


text:
/**
 *   Copyright (C) 2012 - 2013 ciere consulting, ciere.com
 *   Copyright (C) 2011, 2012  Object Modeling Designs
 *
 *   Distributed under the Boost Software License, Version 1.0. (See accompanying
 *   file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
 */

#ifndef CIERE_JSON_DETAIL_IO_IMPL_HPP
#define CIERE_JSON_DETAIL_IO_IMPL_HPP

#include "../exception.hpp"
#include "../parser/grammar.hpp"

#include <boost/foreach.hpp>
#include <boost/spirit/include/qi_expect.hpp>
#include <boost/spirit/include/qi_char_class.hpp>
#include <boost/spirit/include/qi_parse_attr.hpp>
#include <boost/spirit/include/support_istream_iterator.hpp>
#include <boost/variant/static_visitor.hpp>

#include <ios>
#include <istream>
#include <string>

namespace ciere { namespace json
{
   namespace spirit = boost::spirit;

   namespace detail
   {
      struct printer : public boost::static_visitor<>
      {
         printer(std::ostream& s) : stream(s) {}

         void operator()(string_t const & utf) const
         {
            stream << '"';

            typedef ::boost::uint32_t ucs4_char;
            typedef boost::u8_to_u32_iterator<std::string::const_iterator> iter_t;
            iter_t f = utf.begin();
            iter_t l = utf.end();

            for(iter_t i = f; i != l; ++i)
            {
               ucs4_char c = *i;
               switch (c)
               {
                  case '"':   stream << "\\\""; break;
                  case '\\':  stream << "\\\\"; break;
                  case '/':   stream << "\\/";  break;
                  case '\b':  stream << "\\b";  break;
                  case '\f':  stream << "\\f";  break;
                  case '\n':  stream << "\\n";  break;
                  case '\r':  stream << "\\r";  break;
                  case '\t':  stream << "\\t";  break;

                  default:    stream << boost::spirit::to_utf8(c);
               }
            }

            stream << '"';
         }

         template< typename T >
         void operator()(T const & v) const
         {
            stream << v;
         }

         void operator()(double d) const
         {
            // javascript's handling of NaN and +/-Infinity
            // isn't so great. JSON simply follows the javascript
            // standard. We can output nan and infinity; however,
            // we cannot actually parse it back in afaict because
            // the javascript side is generating a null?
            //
            // TODO: clear this up with something definitive
            if(boost::math::isnan(d))
            {
               stream << "NaN";
               return;
            }
            if(boost::math::isinf(d))
            {
               if(d < 0.0) { stream << '-'; }
               stream << "Infinity";
               return;
            }
            stream << d;
         }

         void operator()(bool_t v) const
         {
            stream << (v?"true":"false");
         }

         void operator()(null_t) const
         {
            stream << "null";
         }

         void operator()(object_t const & obj) const
         {
            stream << "{";
            bool first = true;

            BOOST_FOREACH( object_t::value_type const & v, obj )
            {
               if( first ) { first = false;  }
               else        { stream << ", "; }

               stream << '"' << v.first << "\":";
               boost::apply_visitor( *this,v.second);
            }

            stream << "}";
         }

         void operator()(array_t const & arr) const
         {
            stream << "[";
            bool first = true;

            BOOST_FOREACH( value const & v, arr )
            {
               if( first ) { first = false;  }
               else        { stream << ", "; }

               boost::apply_visitor(*this,v);
            }
            stream << "]";
         }

         std::ostream& stream;
      };
   }

   inline std::ostream & operator<<(std::ostream & stream, null_t)
   {
      stream << "null";
      return stream;
   }

   inline std::ostream & operator<<(std::ostream & stream, value const & v)
   {
      boost::apply_visitor(detail::printer(stream),v);
      return stream;
   }

   inline std::istream & operator>>(std::istream & stream, value & object)
   {
      if( !json::construct( stream, object ) )
      {
         stream.setstate( std::ios_base::failbit );
      }

      return stream;
   }

   inline bool construct(std::istream & input, value & v)
   {
      typedef spirit::istream_iterator iterator_t;
      typedef parser::grammar<iterator_t> grammar_t;

      bool skipws_was_set = input.flags() & std::ios::skipws;
      input.unsetf(std::ios::skipws);

      iterator_t iterator(input), end;

      grammar_t grammar;
      bool parse_success = false;
      try
      {
         parse_success = spirit::qi::phrase_parse( iterator, end
                                                 , grammar
                                                 , spirit::ascii::space_type()
                                                 , v );
      }
      catch(spirit::qi::expectation_failure<iterator_t> const &){}

      if(skipws_was_set)
      {
         input.unsetf(std::ios::skipws);
      }

      return parse_success;
   }

   inline value construct(std::istream & input)
   {
      value v;

      if(construct(input, v) == false)
      {
         throw parse_error();
      }

      return v;
   }

   template<typename Iterator>
   bool construct(Iterator & iter, Iterator const & iter_end, value & v)
   {
      typedef parser::grammar<Iterator> grammar_t;
      grammar_t grammar;

      bool parse_success = false;
      try
      {
         parse_success = spirit::qi::phrase_parse( iter, iter_end
                                                 , grammar
                                                 , spirit::ascii::space_type()
                                                 , v );
      }
      catch(spirit::qi::expectation_failure<Iterator> const &){}

      return parse_success;
   }

   template<typename Iterator>
   value construct(Iterator & iter, Iterator const & iter_end)
   {
      value v;

      if(construct(iter, iter_end, v) == false)
      {
         throw parse_error();
      }

      return v;
   }

   inline bool construct(std::string const & input, value & v, bool parse_complete)
   {
      typedef std::string::const_iterator iterator_t;
      iterator_t iter     = input.begin();
      iterator_t iter_end = input.end();

      bool parse_success = construct(iter, iter_end, v);

      return ( parse_success
               &&
               ( !parse_complete || iter == iter_end ) );
   }

   inline value construct(std::string const & input, bool parse_complete)
   {
      value v;

      if(construct(input, v, parse_complete) == false)
      {
         throw parse_error();
      }

      return v;
   }
}}

#endif // CIERE_JSON_DETAIL_IO_IMPL_HPP


text:
/**
 *    Copyright (C) 2016 MongoDB, Inc.
 *
 *    This program is free software: you can redistribute it and/or  modify
 *    it under the terms of the GNU Affero General Public License, version 3,
 *    as published by the Free Software Foundation.
 *
 *    This program is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *    GNU Affero General Public License for more details.
 *
 *    You should have received a copy of the GNU Affero General Public License
 *    along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 *    As a special exception, the copyright holders give permission to link the
 *    code of portions of this program with the OpenSSL library under certain
 *    conditions as described in each individual source file and distribute
 *    linked combinations including the program with the OpenSSL library. You
 *    must comply with the GNU Affero General Public License in all respects for
 *    all of the code used other than as permitted herein. If you modify file(s)
 *    with this exception, you may extend this exception to your version of the
 *    file(s), but you are not obligated to do so. If you do not wish to do so,
 *    delete this exception statement from your version. If you delete this
 *    exception statement from all source files in the program, then also delete
 *    it in the license file.
 */

#include "mongo/platform/basic.h"

#include "mongo/db/pipeline/parsed_aggregation_projection.h"

#include <boost/optional.hpp>
#include <string>

#include "mongo/bson/bsonelement.h"
#include "mongo/bson/bsonobj.h"
#include "mongo/db/matcher/expression_algo.h"
#include "mongo/db/pipeline/field_path.h"
#include "mongo/db/pipeline/parsed_exclusion_projection.h"
#include "mongo/db/pipeline/parsed_inclusion_projection.h"
#include "mongo/stdx/unordered_set.h"
#include "mongo/util/assert_util.h"
#include "mongo/util/mongoutils/str.h"

namespace mongo {
namespace parsed_aggregation_projection {

using expression::isPathPrefixOf;

//
// ProjectionSpecValidator
//

Status ProjectionSpecValidator::validate(const BSONObj& spec) {
    return ProjectionSpecValidator(spec).validate();
}

Status ProjectionSpecValidator::ensurePathDoesNotConflictOrThrow(const std::string& path) {
    auto result = _seenPaths.emplace(path);
    auto pos = result.first;

    // Check whether the path was a duplicate of an existing path.
    auto conflictingPath = boost::make_optional(!result.second, *pos);

    // Check whether the preceding path prefixes this path.
    if (!conflictingPath && pos != _seenPaths.begin()) {
        conflictingPath =
            boost::make_optional(isPathPrefixOf(*std::prev(pos), path), *std::prev(pos));
    }

    // Check whether this path prefixes the subsequent path.
    if (!conflictingPath && std::next(pos) != _seenPaths.end()) {
        conflictingPath =
            boost::make_optional(isPathPrefixOf(path, *std::next(pos)), *std::next(pos));
    }

    if (conflictingPath) {
        return Status(ErrorCodes::FailedToParse,
                      str::stream() << "specification contains two conflicting paths. "
                                       "Cannot specify both '"
                                    << path
                                    << "' and '"
                                    << *conflictingPath
                                    << "': "
                                    << _rawObj.toString(),
                      40176);
    }
    return Status::OK();
}

Status ProjectionSpecValidator::validate() {
    if (_rawObj.isEmpty()) {
        return Status(
            ErrorCodes::FailedToParse, "specification must have at least one field", 40177);
    }
    for (auto&& elem : _rawObj) {
        Status status = parseElement(elem, FieldPath(elem.fieldName()));
        if (!status.isOK())
            return status;
    }
    return Status::OK();
}

Status ProjectionSpecValidator::parseElement(const BSONElement& elem, const FieldPath& pathToElem) {
    if (elem.type() == BSONType::Object) {
        return parseNestedObject(elem.Obj(), pathToElem);
    }
    return ensurePathDoesNotConflictOrThrow(pathToElem.fullPath());
}

Status ProjectionSpecValidator::parseNestedObject(const BSONObj& thisLevelSpec,
                                                  const FieldPath& prefix) {
    if (thisLevelSpec.isEmpty()) {
        return Status(ErrorCodes::FailedToParse,
                      str::stream()
                          << "an empty object is not a valid value. Found empty object at path "
                          << prefix.fullPath(),
                      40180);
    }
    for (auto&& elem : thisLevelSpec) {
        auto fieldName = elem.fieldNameStringData();
        if (fieldName[0] == '$') {
            // This object is an expression specification like {$add: [...]}. It will be parsed
            // into an Expression later, but for now, just track that the prefix has been
            // specified and skip it.
            if (thisLevelSpec.nFields() != 1) {
                return Status(ErrorCodes::FailedToParse,
                              str::stream() << "an expression specification must contain exactly "
                                               "one field, the name of the expression. Found "
                                            << thisLevelSpec.nFields()
                                            << " fields in "
                                            << thisLevelSpec.toString()
                                            << ", while parsing object "
                                            << _rawObj.toString(),
                              40181);
            }
            Status status = ensurePathDoesNotConflictOrThrow(prefix.fullPath());
            if (!status.isOK())
                return status;
            continue;
        }
        if (fieldName.find('.') != std::string::npos) {
            return Status(ErrorCodes::FailedToParse,
                          str::stream() << "cannot use dotted field name '" << fieldName
                                        << "' in a sub object: "
                                        << _rawObj.toString(),
                          40183);
        }
        Status status =
            parseElement(elem, FieldPath::getFullyQualifiedPath(prefix.fullPath(), fieldName));
        if (!status.isOK())
            return status;
    }
    return Status::OK();
}

namespace {

/**
 * This class is responsible for determining what type of $project stage it specifies.
 */
class ProjectTypeParser {
public:
    /**
     * Parses 'spec' to determine whether it is an inclusion or exclusion projection. 'Computed'
     * fields (ones which are defined by an expression or a literal) are treated as inclusion
     * projections for in this context of the$project stage.
     */
    static ProjectionType parse(const BSONObj& spec) {
        ProjectTypeParser parser(spec);
        parser.parse();
        invariant(parser._parsedType);
        return *(parser._parsedType);
    }

private:
    ProjectTypeParser(const BSONObj& spec) : _rawObj(spec) {}

    /**
     * Traverses '_rawObj' to determine the type of projection, populating '_parsedType' in the
     * process.
     */
    void parse() {
        size_t nFields = 0;
        for (auto&& elem : _rawObj) {
            parseElement(elem, FieldPath(elem.fieldName()));
            nFields++;
        }

        // Check for the case where we only exclude '_id'.
        if (nFields == 1) {
            BSONElement elem = _rawObj.firstElement();
            if (elem.fieldNameStringData() == "_id" && (elem.isBoolean() || elem.isNumber()) &&
                !elem.trueValue()) {
                _parsedType = ProjectionType::kExclusion;
            }
        }

        // Default to inclusion if nothing (except maybe '_id') is explicitly included or excluded.
        if (!_parsedType) {
            _parsedType = ProjectionType::kInclusion;
        }
    }

    /**
     * Parses a single BSONElement. 'pathToElem' should include the field name of 'elem'.
     *
     * Delegates to parseSubObject() if 'elem' is an object. Otherwise updates '_parsedType' if
     * appropriate.
     *
     * Throws a UserException if this element represents a mix of projection types.
     */
    void parseElement(const BSONElement& elem, const FieldPath& pathToElem) {
        if (elem.type() == BSONType::Object) {
            return parseNestedObject(elem.Obj(), pathToElem);
        }

        if ((elem.isBoolean() || elem.isNumber()) && !elem.trueValue()) {
            // A top-level exclusion of "_id" is allowed in either an inclusion projection or an
            // exclusion projection, so doesn't affect '_parsedType'.
            if (pathToElem.fullPath() != "_id") {
                uassert(40178,
                        str::stream() << "Bad projection specification, cannot exclude fields "
                                         "other than '_id' in an inclusion projection: "
                                      << _rawObj.toString(),
                        !_parsedType || (*_parsedType == ProjectionType::kExclusion));
                _parsedType = ProjectionType::kExclusion;
            }
        } else {
            // A boolean true, a truthy numeric value, or any expression can only be used with an
            // inclusion projection. Note that literal values like "string" or null are also treated
            // as expressions.
            uassert(40179,
                    str::stream() << "Bad projection specification, cannot include fields or "
                                     "add computed fields during an exclusion projection: "
                                  << _rawObj.toString(),
                    !_parsedType || (*_parsedType == ProjectionType::kInclusion));
            _parsedType = ProjectionType::kInclusion;
        }
    }

    /**
     * Traverses 'thisLevelSpec', parsing each element in turn.
     *
     * Throws a UserException if 'thisLevelSpec' represents an invalid mix of projections.
     */
    void parseNestedObject(const BSONObj& thisLevelSpec, const FieldPath& prefix) {

        for (auto&& elem : thisLevelSpec) {
            auto fieldName = elem.fieldNameStringData();
            if (fieldName[0] == '$') {
                // This object is an expression specification like {$add: [...]}. It will be parsed
                // into an Expression later, but for now, just track that the prefix has been
                // specified and skip it.
                uassert(40182,
                        str::stream() << "Bad projection specification, cannot include fields or "
                                         "add computed fields during an exclusion projection: "
                                      << _rawObj.toString(),
                        !_parsedType || _parsedType == ProjectionType::kInclusion);
                _parsedType = ProjectionType::kInclusion;
                continue;
            }
            parseElement(elem, FieldPath::getFullyQualifiedPath(prefix.fullPath(), fieldName));
        }
    }

    // The original object. Used to generate more helpful error messages.
    const BSONObj& _rawObj;

    // This will be populated during parse().
    boost::optional<ProjectionType> _parsedType;
};

}  // namespace

std::unique_ptr<ParsedAggregationProjection> ParsedAggregationProjection::create(
    const boost::intrusive_ptr<ExpressionContext>& expCtx, const BSONObj& spec) {
    // Check that the specification was valid. Status returned is unspecific because validate()
    // is used by the $addFields stage as well as $project.
    // If there was an error, uassert with a $project-specific message.
    Status status = ProjectionSpecValidator::validate(spec);
    if (!status.isOK()) {
        uasserted(status.location(),
                  str::stream() << "Invalid $project specification: " << status.reason());
    }

    // Check for any conflicting specifications, and determine the type of the projection.
    auto projectionType = ProjectTypeParser::parse(spec);
    // kComputed is a projection type reserved for $addFields, and should never be detected by the
    // ProjectTypeParser.
    invariant(projectionType != ProjectionType::kComputed);

    // We can't use make_unique() here, since the branches have different types.
    std::unique_ptr<ParsedAggregationProjection> parsedProject(
        projectionType == ProjectionType::kInclusion
            ? static_cast<ParsedAggregationProjection*>(new ParsedInclusionProjection())
            : static_cast<ParsedAggregationProjection*>(new ParsedExclusionProjection()));

    // Actually parse the specification.
    parsedProject->parse(expCtx, spec);
    return parsedProject;
}

}  // namespace parsed_aggregation_projection
}  // namespace mongo


text:
/*
 *  Copyright 2021 (c) Microsoft Corporation.
 *
 *  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.
 */

/*
 * linkMgrdMain.cpp
 *
 *  Created on: Oct 23, 2020
 *      Author: Tamer Ahmed Ahmed
 */

#include <iostream>

#include <boost/lexical_cast.hpp>
#include <boost/program_options.hpp>

#include "MuxManager.h"
#include "MuxPort.h"
#include "common/MuxConfig.h"
#include "common/MuxLogger.h"
#include "link_manager/LinkManagerStateMachineActiveStandby.h"
#include "link_prober/LinkProberStateMachineActiveActive.h"
#include "link_prober/LinkProberStateMachineActiveStandby.h"
#include "link_prober/LinkProber.h"
#include "link_prober/IcmpPayload.h"

// Private namespace for this module
namespace {
    // Some namespace and type aliases...
    namespace program_options = boost::program_options;

    static auto DEFAULT_LOGGING_FILTER_LEVEL = boost::log::trivial::debug;

    void InitializeLogger(std::string execName, boost::log::trivial::severity_level level, bool extraLogFile)
    {
        std::string progName = execName.substr(execName.find_last_of('/') + 1);
        std::string logFile = "/var/log/mux/" + progName + ".log";

        common::MuxLogger::getInstance()->initialize(progName, logFile, level, extraLogFile);
    }

} // end namespace

//
// Main program entry point for Gemini MUX Manager (aka linkmgrd).
//
int main(int argc, const char* argv[])
{
    int retValue = EXIT_SUCCESS;

    //
    // Constants for command line argument strings:
    //
    boost::log::trivial::severity_level level;
    bool extraLogFile = false;
    bool measureSwitchover = false;
    bool defaultRoute = false;

    program_options::options_description description("linkmgrd options");
    description.add_options()
        ("help,h",
         "Print usage information.")
        ("verbosity,v",
         program_options::value<boost::log::trivial::severity_level>(&level)->value_name("<severity_level>")->
         default_value(DEFAULT_LOGGING_FILTER_LEVEL),
         "Logging verbosity level.")
        ("extra_log_file,e",
         program_options::bool_switch(&extraLogFile)->default_value(false),
         "Store logs in an extra log file")
         ("measure_switchover_overhead,m",
         program_options::bool_switch(&measureSwitchover)->default_value(false),
         "Decrease link prober interval after switchover to better measure switchover overhead")
         ("default_route,d",
         program_options::bool_switch(&defaultRoute)->default_value(false),
         "Disable heartbeat sending and avoid switching to active when default route is missing"
         )
    ;

    //
    // Actually parse options, print verbose usage when it fails
    //
    program_options::variables_map variableMap;
    try {
        store(parse_command_line(argc, argv, description), variableMap);
        program_options::notify(variableMap);
    }
    catch (program_options::error_with_option_name& e) {
        std::cerr << "Command Line Syntax Error: " << e.what() << std::endl;
        std::cout << description << "\n";
        retValue = EXIT_FAILURE;
    }
    catch (program_options::error& e) {
        std::cerr << "Command Line Error: " << e.what() << std::endl;
        std::cout << description << "\n";
        retValue = EXIT_FAILURE;
    }

    if (retValue == EXIT_SUCCESS && variableMap.count("help")) {
        std::cout << description << "\n";

        retValue = EXIT_FAILURE;
    }

    if (retValue == EXIT_SUCCESS) {
        InitializeLogger(argv[0], level, extraLogFile);
        std::stringstream ss;
        ss << "level: " << level;
        MUXLOGINFO(ss.str());

        // initialize static data
        link_prober::IcmpPayload::generateGuid();

        std::shared_ptr<mux::MuxManager> muxManagerPtr = std::make_shared<mux::MuxManager> ();
        muxManagerPtr->initialize(measureSwitchover, defaultRoute);
        muxManagerPtr->run();
        muxManagerPtr->deinitialize();
    }

    return retValue;
}

max_stars_repo_name: lolyu/sonic-linkmgrd

max_issues_repo_name: lolyu/sonic-linkmgrd

max_forks_repo_name: lolyu/sonic-linkmgrd


text:
#include <bunsan/test/filesystem/write_data.hpp>

#include <boost/filesystem/operations.hpp>
#include <boost/filesystem/fstream.hpp>
#include <boost/test/unit_test.hpp>

namespace bunsan::test::filesystem {

void write_data(const boost::filesystem::path &path, const std::string &data) {
  BOOST_TEST_CHECKPOINT(BOOST_CURRENT_FUNCTION);
  BOOST_TEST_MESSAGE("Attempt to write to " << path << ".");
  boost::filesystem::ofstream fout(path);
  BOOST_REQUIRE(fout.is_open());
  fout << data << std::flush;
  BOOST_REQUIRE(fout);
  fout.close();
  BOOST_REQUIRE(fout);
}

}  // namespace bunsan::test::filesystem

max_stars_repo_name: bacsorg/bacs

max_issues_repo_name: bacsorg/bacs

max_forks_repo_name: bacsorg/bacs


text:
#include<am/concurrent/slfvector.h>
#include <boost/test/unit_test.hpp>
#include <boost/thread.hpp>
#include<iostream>
#include<stdexcept>
#include <boost/archive/text_oarchive.hpp>
#include <boost/archive/text_iarchive.hpp>
#include<fstream>

using namespace std;
using namespace izenelib::am::concurrent;

BOOST_AUTO_TEST_SUITE( t_concurrent_read_vector_suite )

BOOST_AUTO_TEST_CASE(push_back){
    slfvector<int> vc;
    for(int i = 0; i < 100; ++i){
        vc.push_back(i);
    }
    BOOST_CHECK(vc.size() == 100);
}

BOOST_AUTO_TEST_CASE(at){
    slfvector<int> vc;
    std::cout<<time(NULL)<<std::endl;
    for(int i = 0; i < 100000000; ++i){
        vc.push_back(i);
    }
    std::cout<<time(NULL)<<std::endl;
    for(int j = 0; j < 10; ++j)
    for(int i = 0; i < 100000000; ++i){
        vc.at(i);
        vc[i];
    }
    std::cout<<time(NULL)<<std::endl;
}

BOOST_AUTO_TEST_CASE(resize){
    slfvector<int> vc(0);
    vc.clear();
    for(int i = 0; i < 100; ++i){
        vc.push_back(i);
    }
    vc.resize(10);
    BOOST_CHECK(vc.size() == 10);
    vc.resize(200);
    BOOST_CHECK(vc.size() == 200);
    vc.resize(0);
    BOOST_CHECK(vc.size() == 0);
    vc.clear();
    vc.resize(1);
    BOOST_CHECK(vc.size() == 1);
}

BOOST_AUTO_TEST_CASE(copy_constructor){
    slfvector<int> vc;
    for(int i = 0; i < 20; ++i){
        vc.push_back(i);
    }
    {
        slfvector<int>vc2(vc);
        for(uint32_t idx = 0; idx < 20; ++idx)
            BOOST_CHECK(vc.at(idx) == vc2.at(idx));
        vc = vc2;
    }
    BOOST_CHECK(vc.size() == 20);
    vc.clear();
}

BOOST_AUTO_TEST_CASE(swap){
    slfvector<int> vec1, vec2;
    for(int i = 0; i < 10; ++i){
        vec1.push_back(i);
        vec2.push_back(100 + i);
    }
    vec1.swap(vec2);
    for(int i = 0; i < 10; ++i){
        std::cout<<"Swap: "<<vec1[i]<<endl;
    }
    for(int i = 0; i < 10; ++i){
        std::cout<<"Swap 2: "<<vec2[i]<<endl;
    }
}

BOOST_AUTO_TEST_CASE(serialize){
    std::ofstream ofs("filename");
    slfvector<int> vec;
    for(int i = 0; i < 10; ++i)
        vec.push_back(i);
    {
        boost::archive::text_oarchive oa(ofs);
        oa << vec;
    }
    std::cout<<"Serialized!"<<std::endl;
    slfvector<int> vec2;
    {
        std::ifstream ifs("filename");
        boost::archive::text_iarchive ia(ifs);
        ia >> vec2;
    }
    std::cout<<"Deserialized!"<<std::endl;
    std::cout<<"Test serialize, size: "<<vec2.size()<<std::endl;
    for(int i = 1; i < 10; ++i)
        std::cout<<"Test serialize: "<<vec2.at(i)<<endl;
}

slfvector<int> vcbench;
void push(){
    for(int i = 0; i < 100000; ++i){
        vcbench.push_back(i);
    }
}

void read(){
    for(int i = 0; i < 10000; ++i){
        try{
            vcbench.at((i * 97) % (vcbench.size() + 1) - 1);
        }catch(const std::out_of_range& e){
        }
    }
}

BOOST_AUTO_TEST_CASE(Bench){
slfvector<int> vcbench;
    boost::thread push_t1(boost::bind(&push));
    boost::thread read_t2(boost::bind(&read));
    boost::thread read_t3(boost::bind(&read));
    boost::thread read_t4(boost::bind(&read));
    boost::thread read_t5(boost::bind(&read));
    boost::thread read_t6(boost::bind(&read));
    boost::thread read_t7(boost::bind(&read));
    boost::thread read_t8(boost::bind(&read));
    boost::thread read_t9(boost::bind(&read));
    boost::thread read_t10(boost::bind(&read));

    push_t1.join();
    read_t2.join();
    read_t3.join();
    read_t4.join();
    read_t5.join();
    read_t6.join();
    read_t7.join();
    read_t8.join();
    read_t9.join();
    read_t10.join();
}

BOOST_AUTO_TEST_SUITE_END()

max_stars_repo_name: izenecloud/izenelib

max_issues_repo_name: izenecloud/izenelib

max_forks_repo_name: izenecloud/izenelib