text:
#include "nmos/mdns_api.h"

#include <boost/range/adaptor/filtered.hpp>
#include <boost/range/adaptor/transformed.hpp>
#include "mdns/service_discovery.h"
#include "nmos/api_utils.h"
#include "nmos/mdns.h"
#include "nmos/mdns_versions.h"
#include "nmos/model.h"

namespace nmos
{
    namespace experimental
    {
        web::http::experimental::listener::api_router make_unmounted_mdns_api(nmos::base_model& model, slog::base_gate& gate);

        web::http::experimental::listener::api_router make_mdns_api(nmos::base_model& model, slog::base_gate& gate)
        {
            using namespace web::http::experimental::listener::api_router_using_declarations;

            api_router mdns_api;

            mdns_api.support(U("/?"), methods::GET, [](http_request req, http_response res, const string_t&, const route_parameters&)
            {
                set_reply(res, status_codes::OK, nmos::make_sub_routes_body({ U("x-dns-sd/") }, req, res));
                return pplx::task_from_result(true);
            });

            mdns_api.support(U("/") + nmos::experimental::patterns::mdns_api.pattern + U("/?"), methods::GET, [](http_request req, http_response res, const string_t&, const route_parameters&)
            {
                set_reply(res, status_codes::OK, nmos::make_sub_routes_body(nmos::make_api_version_sub_routes(mdns_versions::all), req, res));
                return pplx::task_from_result(true);
            });

            mdns_api.mount(U("/") + nmos::experimental::patterns::mdns_api.pattern + U("/") + nmos::patterns::version.pattern, make_unmounted_mdns_api(model, gate));

            return mdns_api;
        }

        web::json::value make_mdns_result(const nmos::api_version& version, const ::mdns::browse_result& browsed, const ::mdns::resolve_result& resolved)
        {
            using web::json::value;

            value result;

            result[U("name")] = value::string(utility::s2us(browsed.name));
            // from v1.1, the service domain is included in the response
            if (nmos::experimental::mdns_versions::v1_1 <= version)
            {
                result[U("domain")] = value::string(utility::s2us(browsed.domain));
            }
            result[U("host_target")] = value::string(utility::s2us(resolved.host_name));
            value& addresses = result[U("addresses")] = value::array();
            for (const auto& ip_address : resolved.ip_addresses)
            {
                web::json::push_back(addresses, value::string(utility::s2us(ip_address)));
            }
            result[U("port")] = resolved.port;

            value& txt = result[U("txt")];

            auto records = ::mdns::parse_txt_records(resolved.txt_records);
            for (const auto& record : records)
            {
                txt[utility::s2us(record.first)] = value::string(utility::s2us(record.second));
            }

            return result;
        }

        namespace fields
        {
            const web::json::field_as_string_or query_domain{ U("query.domain"), {} };
        }

        namespace details
        {
            unsigned int get_request_timeout(const web::http::http_headers& headers)
            {
                // hm, ought to use the "wait" preference instead really
                // see https://tools.ietf.org/html/rfc7240#section-4.3
                auto header = headers.find(U("Request-Timeout"));
                return headers.end() != header
                    ? utility::conversions::details::scan_string(header->second, mdns::default_timeout_seconds)
                    : mdns::default_timeout_seconds;
            }

            // from v1.1, the browse domain is specified in the path
            // in v1.0, the browse domain may be specified as a query parameter
            utility::string_t get_domain(const web::uri& request_uri, const web::http::experimental::listener::route_parameters& parameters)
            {
                const auto mdnsBrowseDomain = parameters.find(nmos::experimental::patterns::mdnsBrowseDomain.name);
                if (parameters.end() != mdnsBrowseDomain)
                {
                    return web::uri::decode(mdnsBrowseDomain->second);
                }
                else
                {
                    auto flat_query_params = web::json::value_from_query(request_uri.query());
                    nmos::details::decode_elements(flat_query_params);
                    return nmos::experimental::fields::query_domain(flat_query_params);
                }
            }
        }

        web::http::experimental::listener::api_router make_unmounted_mdns_domain_api(nmos::base_model& model, slog::base_gate& gate);

        web::http::experimental::listener::api_router make_unmounted_mdns_api(nmos::base_model& model, slog::base_gate& gate)
        {
            using namespace web::http::experimental::listener::api_router_using_declarations;

            api_router mdns_api;

            // check for supported API version
            mdns_api.support(U(".*"), nmos::details::make_api_version_handler(nmos::experimental::mdns_versions::all, gate));

            // from v1.1, the top level provides a list of available browse domains
            mdns_api.support(U("/?"), methods::GET, [&model](http_request req, http_response res, const string_t&, const route_parameters& parameters)
            {
                const nmos::api_version version = nmos::parse_api_version(parameters.at(nmos::patterns::version.name));

                if (nmos::experimental::mdns_versions::v1_1 > version)
                {
                    return pplx::task_from_result(true);
                }

                // hm, should use DNSServiceEnumerateDomains here
                set_reply(res, status_codes::OK, nmos::make_sub_routes_body({ U("local./") }, req, res));

                throw nmos::details::to_api_finally_handler{}; // in order to skip other route handlers and then send the response
            });

            // from v1.1, the browse domain is specified in the path (and the next level provides the list of available service types)
            mdns_api.mount(U("/") + nmos::experimental::patterns::mdnsBrowseDomain.pattern, make_unmounted_mdns_domain_api(model, gate));

            // in v1.0, the browse domain may be specified as a query parameter (and the top level provides the list of available service types)
            // from v1.1, this is deprecated
            mdns_api.mount({}, make_unmounted_mdns_domain_api(model, gate));

            return mdns_api;
        }

        web::http::experimental::listener::api_router make_unmounted_mdns_domain_api(nmos::base_model& model, slog::base_gate& gate_)
        {
            using namespace web::http::experimental::listener::api_router_using_declarations;

            api_router mdns_api;

            mdns_api.support(U("/?"), methods::GET, [&model, &gate_](http_request req, http_response res, const string_t&, const route_parameters& parameters)
            {
                // hmmm, fragile; make shared, and capture into continuation below, in order to extend lifetime until after discovery
                std::shared_ptr<nmos::api_gate> gate(new nmos::api_gate(gate_, req, parameters));

                const std::chrono::seconds timeout(details::get_request_timeout(req.headers()));

                // get the browse domain from the path, query parameters or settings
                const auto query_domain = details::get_domain(req.request_uri(), parameters);
                const auto browse_domain = utility::us2s(!query_domain.empty() ? query_domain : with_read_lock(model.mutex, [&] { return nmos::get_domain(model.settings); }));

                std::shared_ptr<::mdns::service_discovery> discovery(new ::mdns::service_discovery(*gate));

                // note, only the list of available service types that are explicitly being advertised is returned by "_services._dns-sd._udp"
                // see https://tools.ietf.org/html/rfc6763#section-9
                return discovery->browse("_services._dns-sd._udp", browse_domain, 0, timeout).then([req, res, gate](std::vector<::mdns::browse_result> browsed) mutable
                {
                    auto results = boost::copy_range<std::set<utility::string_t>>(browsed | boost::adaptors::transformed([](const ::mdns::browse_result& br)
                    {
                        // results for this query seem to be e.g. name = "_nmos-query", type = "_tcp.local."
                        return utility::s2us(br.name + '.' + br.type.substr(0, br.type.find('.')) + '/');
                    }));
                    res.headers().add(U("X-Total-Count"), results.size());
                    set_reply(res, status_codes::OK, nmos::make_sub_routes_body(std::move(results), req, res));
                    return true;
                });
            });

            mdns_api.support(U("/") + nmos::experimental::patterns::mdnsServiceType.pattern + U("/?"), methods::GET, [&model, &gate_](http_request req, http_response res, const string_t&, const route_parameters& parameters)
            {
                // hmmm, fragile; make shared, and capture into continuation below, in order to extend lifetime until after discovery
                std::shared_ptr<nmos::api_gate> gate(new nmos::api_gate(gate_, req, parameters));

                const nmos::api_version version = nmos::parse_api_version(parameters.at(nmos::patterns::version.name));
                // hmm, something to think about... the regex patterns are presumably being used on encoded paths?
                const std::string serviceType = utility::us2s(web::uri::decode(parameters.at(nmos::experimental::patterns::mdnsServiceType.name)));

                const std::chrono::seconds timeout(details::get_request_timeout(req.headers()));

                // get the browse domain from the path, query parameters or settings
                const auto query_domain = details::get_domain(req.request_uri(), parameters);
                const auto browse_domain = utility::us2s(!query_domain.empty() ? query_domain : with_read_lock(model.mutex, [&] { return nmos::get_domain(model.settings); }));

                std::shared_ptr<::mdns::service_discovery> discovery(new ::mdns::service_discovery(*gate));

                // hmm, how to add cancellation on shutdown to the browse and resolve operations?
                return discovery->browse(serviceType, browse_domain, 0, timeout).then([res, version, discovery, timeout, gate](std::vector<::mdns::browse_result> browsed) mutable
                {
                    if (!browsed.empty())
                    {
                        typedef std::pair<::mdns::browse_result, std::vector<::mdns::resolve_result>> mdns_result;
                        std::vector<pplx::task<mdns_result>> tasks;
                        for (const auto& browsed1 : browsed)
                        {
                            tasks.push_back(discovery->resolve(browsed1.name, browsed1.type, browsed1.domain, browsed1.interface_id, timeout)
                                .then([browsed1, gate](std::vector<::mdns::resolve_result> resolved)
                            {
                                return mdns_result(browsed1, resolved);
                            }));
                        }
                        return pplx::when_all(tasks.begin(), tasks.end()).then([res, version, tasks](pplx::task<std::vector<mdns_result>> finally) mutable
                        {
                            // to ensure an exception from one doesn't leave other tasks' exceptions unobserved
                            for (auto& task : tasks)
                            {
                                try { task.wait(); } catch (...) {}
                            }

                            // merge results that have the same host_target, port and txt records
                            // and only differ in the resolved addresses

                            std::map<value, std::set<std::string>> results;
                            for (auto& result : finally.get())
                            {
                                auto& browsed1 = result.first;
                                for (auto& resolved1 : result.second)
                                {
                                    auto ip_addresses = resolved1.ip_addresses;
                                    resolved1.ip_addresses.clear();
                                    auto instance = make_mdns_result(version, browsed1, resolved1);
                                    results[instance].insert(ip_addresses.begin(), ip_addresses.end());
                                }
                            }

                            set_reply(res, status_codes::OK,
                                web::json::serialize_array(results | boost::adaptors::transformed([](const std::map<value, std::set<std::string>>::value_type& result)
                                {
                                    auto instance = result.first;
                                    for (const auto& address : result.second)
                                    {
                                        web::json::push_back(instance[U("addresses")], web::json::value::string(utility::s2us(address)));
                                    }
                                    return instance;
                                })),
                                web::http::details::mime_types::application_json);
                            res.headers().add(U("X-Total-Count"), results.size());
                            return true;
                        });
                    }
                    else
                    {
                        return pplx::create_task([] {}).then([res]() mutable
                        {
                            set_reply(res, status_codes::OK, value::array());
                            res.headers().add(U("X-Total-Count"), 0);
                            return true;
                        });
                    }
                });
            });

            mdns_api.support(U("/") + nmos::experimental::patterns::mdnsServiceType.pattern + U("/") + nmos::experimental::patterns::mdnsServiceName.pattern + U("/?"), methods::GET, [&model, &gate_](http_request req, http_response res, const string_t&, const route_parameters& parameters)
            {
                // hmmm, fragile; make shared, and capture into continuation below, in order to extend lifetime until after discovery
                std::shared_ptr<nmos::api_gate> gate(new nmos::api_gate(gate_, req, parameters));

                const nmos::api_version version = nmos::parse_api_version(parameters.at(nmos::patterns::version.name));
                const std::string serviceType = utility::us2s(web::uri::decode(parameters.at(nmos::experimental::patterns::mdnsServiceType.name)));
                const std::string serviceName = utility::us2s(web::uri::decode(parameters.at(nmos::experimental::patterns::mdnsServiceName.name)));

                const std::chrono::seconds timeout(details::get_request_timeout(req.headers()));

                // get the browse domain from the path, query parameters or settings
                const auto query_domain = details::get_domain(req.request_uri(), parameters);
                const auto service_domain = utility::us2s(!query_domain.empty() ? query_domain : with_read_lock(model.mutex, [&] { return nmos::get_domain(model.settings); }));

                std::shared_ptr<::mdns::service_discovery> discovery(new ::mdns::service_discovery(*gate));

                // When browsing, we resolve using the browse results' domain and interface
                // so this can give different results...
                const ::mdns::browse_result browsed1(serviceName, serviceType, service_domain);
                return discovery->resolve(browsed1.name, browsed1.type, browsed1.domain, browsed1.interface_id, timeout)
                    .then([res, version, browsed1, gate](std::vector<::mdns::resolve_result> resolved) mutable
                {
                    // merge results that have the same host_target, port and txt records
                    // and only differ in the resolved addresses

                    std::map<value, std::set<std::string>> results;
                    for (auto& resolved1 : resolved)
                    {
                        auto ip_addresses = resolved1.ip_addresses;
                        resolved1.ip_addresses.clear();
                        auto instance = make_mdns_result(version, browsed1, resolved1);
                        results[instance].insert(ip_addresses.begin(), ip_addresses.end());
                    }

                    if (!results.empty())
                    {
                        // for now, pick one of the merged results, even though there conceivably may be one per interface
                        const auto& result = *results.begin();

                        auto instance = result.first;
                        for (const auto& address : result.second)
                        {
                            web::json::push_back(instance[U("addresses")], web::json::value::string(utility::s2us(address)));
                        }
                        set_reply(res, status_codes::OK, instance);
                    }
                    else
                    {
                        set_reply(res, status_codes::NotFound);
                    }

                    return true;
                });
            });

            return mdns_api;
        }
    }
}

max_stars_repo_name: rayli-hlit/nmos-cpp

max_issues_repo_name: rayli-hlit/nmos-cpp

max_forks_repo_name: alanb-sony/nmos-cpp


text:
//==============================================================================
//         Copyright 2003 - 2012   LASMEA UMR 6602 CNRS/Univ. Clermont II
//         Copyright 2009 - 2012   LRI    UMR 8623 CNRS/Univ Paris Sud XI
//
//          Distributed under the Boost Software License, Version 1.0.
//                 See accompanying file LICENSE.txt or copy at
//                     http://www.boost.org/LICENSE_1_0.txt
//==============================================================================
#ifndef BOOST_SIMD_SDK_SIMD_PACK_META_MODEL_OF_HPP_INCLUDED
#define BOOST_SIMD_SDK_SIMD_PACK_META_MODEL_OF_HPP_INCLUDED

#include <boost/dispatch/meta/model_of.hpp>
#include <boost/simd/sdk/simd/pack/forward.hpp>

namespace boost { namespace dispatch { namespace meta
{
  template< class Type
          , std::size_t Cardinal
          >
  struct model_of< boost::simd::pack<Type, Cardinal> >
  {
    struct type
    {
      template<typename T>
      struct apply
      {
          typedef boost::simd::pack<T, Cardinal> type;
      };
    };
  };
} } }

#endif

ext: hpp


text:
//==================================================================================================
/**
  Copyright 2016 NumScale SAS

  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_ARCH_COMMON_SIMD_FUNCTION_CORRECT_FMA_HPP_INCLUDED
#define BOOST_SIMD_ARCH_COMMON_SIMD_FUNCTION_CORRECT_FMA_HPP_INCLUDED

#include <boost/simd/detail/overload.hpp>
#include <boost/simd/function/bitwise_cast.hpp>
#include <boost/simd/function/group.hpp>
#include <boost/simd/function/split.hpp>
#include <boost/simd/function/two_add.hpp>
#include <boost/simd/function/two_prod.hpp>
#include <boost/simd/detail/dispatch/meta/as_integer.hpp>
#include <boost/simd/function/pedantic.hpp>

#ifndef BOOST_SIMD_DONT_CARE_FMA_OVERFLOW
#include <boost/simd/function/exponent.hpp>
#include <boost/simd/function/ldexp.hpp>
#include <boost/simd/function/maxmag.hpp>
#include <boost/simd/function/minmag.hpp>
#endif

namespace boost { namespace simd { namespace ext
{
   namespace bd = boost::dispatch;
   namespace bs = boost::simd;

   BOOST_DISPATCH_OVERLOAD_IF(fma_
                             , (typename A0, typename X)
                             , (detail::is_native<X>)
                             , bd::cpu_
                             , bs::pedantic_tag
                             , bs::pack_<bd::single_<A0>, X>
                             , bs::pack_<bd::single_<A0>, X>
                             , bs::pack_<bd::single_<A0>, X>
                             )
   {
      BOOST_FORCEINLINE A0 operator()( const pedantic_tag &
                                     , const A0& a0, const A0& a1, const A0& a2) const BOOST_NOEXCEPT
      {
        auto s0 = split(a0);
        auto s1 = split(a1);
        auto s2 = split(a2);
        return group(s0[0]*s1[0]+s2[0], s0[1]*s1[1]+s2[1]);
      }
   };

   BOOST_DISPATCH_OVERLOAD_IF(fma_
                          , (typename A0, typename X)
                          , (detail::is_native<X>)
                          , bd::cpu_
                          , bs::pedantic_tag
                          , bs::pack_<bd::floating_<A0>, X>
                          , bs::pack_<bd::floating_<A0>, X>
                          , bs::pack_<bd::floating_<A0>, X>
                          )
   {
      BOOST_FORCEINLINE A0 operator()( const pedantic_tag &
                                     , const A0& a0, const A0& a1, const A0& a2) const BOOST_NOEXCEPT
      {
        A0 p, rp, s, rs;
  #ifndef BOOST_SIMD_DONT_CARE_FMA_OVERFLOW
        using iA0 = bd::as_integer_t<A0>;
        A0 amax =  a0; maxmag(a0, a1);
        A0 amin =  a1; minmag(a0, a1);
        iA0 e0 = -shift_right(exponent(amax), 1);
        amax = pedantic_(ldexp)(amax, e0);
        A0 a02 = pedantic_(ldexp)(a2, e0);
        std::tie(p, rp) = two_prod(amax, amin);
        std::tie(s, rs) = two_add(p, a02);
        return pedantic_(ldexp)(s+(rp+rs), -e0);
  #else
        std::tie(p, rp) = two_prod(a0, a1);
        std::tie(s, rs) = two_add(p, a2);
        return s+(rp+rs);
 #endif
      }
   };

   BOOST_DISPATCH_OVERLOAD_IF(fma_
                          , (typename A0, typename X)
                          , (detail::is_native<X>)
                          , bd::cpu_
                          , bs::pedantic_tag
                          , bs::pack_<bd::int_<A0>, X>
                          , bs::pack_<bd::int_<A0>, X>
                          , bs::pack_<bd::int_<A0>, X>
                          )
   {
      BOOST_FORCEINLINE A0 operator()( const pedantic_tag &
                                     , const A0& a0, const A0& a1, const A0& a2) const BOOST_NOEXCEPT
      {
        // correct fma has to ensure "no intermediate overflow".
        // This is done in the case of signed integers by transtyping to unsigned type
        // to perform the computations in a guaranteed 2-complement environment
        // since signed integer overflow in C++ produces "undefined results"
        using utype =  bd::as_integer_t<A0>;
        return bitwise_cast<A0>(fma(bitwise_cast<utype>(a0), bitwise_cast<utype>(a1), bitwise_cast<utype>(a2)));
      }
   };

   BOOST_DISPATCH_OVERLOAD_IF(fma_
                          , (typename A0, typename X)
                          , (detail::is_native<X>)
                          , bd::cpu_
                          , bs::pedantic_tag
                          , bs::pack_<bd::uint_<A0>, X>
                          , bs::pack_<bd::uint_<A0>, X>
                          , bs::pack_<bd::uint_<A0>, X>
                          )
   {
      BOOST_FORCEINLINE A0 operator()( const pedantic_tag &
                                     , const A0& a0, const A0& a1, const A0& a2) const BOOST_NOEXCEPT
      {
        return a0*a1+a2;
      }
   };
} } }

#endif

max_stars_repo_name: SylvainCorlay/pythran

max_issues_repo_name: SylvainCorlay/pythran

max_forks_repo_name: SylvainCorlay/pythran


text:
//
// Copyright (c) 2019-2020 Kris Jusiak (kris at jusiak dot net)
//
// 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/ut.hpp>

int main() {
  using namespace boost::ut::literals;
  using namespace boost::ut::operators::terse;
  using namespace boost::ut::bdd;

  "Scenario"_test = [] {
    given("I have...") = [] {
      when("I run...") = [] {
        then("I should have...") = [] { 1_u == 1u; };
        then("I should have...") = [] { 1u == 1_u; };
      };
    };
  };

  feature("Calculator") = [] {
    scenario("Addition") = [] {
      given("I have number 40") = [] {
        auto number = 40;
        when("I add 2 to number") = [&number] { number += 2; };
        then("I expect number to be 42") = [&number] { 42_i == number; };
      };
    };
  };

  scenario("Addition");
    given("I have number 40");
      auto number = 40;

    when("I add 2 to number");
      number += 2;

    then("I expect number to be 42");
      42_i == number;
}

ext: cpp

max_stars_repo_name: jasondegraw/ut

max_issues_repo_name: jasondegraw/ut

max_forks_repo_name: jasondegraw/ut


text:
#include "PCAPSpeedupPlugin.h"
#include "search_common.h"
#include <boost/algorithm/string.hpp>
#include <boost/foreach.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/tokenizer.hpp>

static bool withParallelRegions = false;
static bool withUserRegion      = true;

/**
 * custom compare function for sorting the pair of vectors
 **/
static bool pairCompare( const std::pair<string, double> firstPair,
                         const std::pair<string, double> secondPair ) {
    return firstPair.second > secondPair.second;
}

/** Calculates the metric to be minimized. */
static double objectiveExecTime( int scenario_id, ScenarioResultsPool* srp ) {
    std::list<MetaProperty> properties = srp->getScenarioResultsByID( scenario_id );
    return properties.front().getSeverity();
}

PCAPSpeedupPlugin::PCAPSpeedupPlugin() : app( Application::instance() ) {
}

/*
 * Parse options passed to the pcap plugin
 */
void PCAPSpeedupPlugin::parse_opts( int argc, char* argv[] ) {
    const struct option long_opts[] = {
        { "pcap-config", required_argument, 0, 'W' },
        0
    };

    optind = 1;
    while( optind < argc ) {
        int index = -1;
        opterr = 0;
        int result = getopt_long( argc, argv, "", long_opts, &index );

        if( result == -1 ) {
            psc_errmsg( "Error parsing command line parameters.\n" );
        }

        switch( result ) {
        case 'W':
            has_pcap_config  = true;
            pcap_config_file = optarg;
            break;
        default:
            psc_errmsg( "Unrecognized option passed to the compiler flags plugin.\n" );
            break;
        }
    }
}

/*
 * Parse configuration file
 */
void PCAPSpeedupPlugin::parseConfigFile() {
    psc_dbgmsg( PSC_SELECTIVE_DEBUG_LEVEL( AutotunePlugins ), "PCAPSpeedupPlugin: call to parseConfigFile()\n" );
    ifstream inputFile( pcap_config_file.c_str() );
    if( inputFile.is_open() ) {
        string line;
        while( getline( inputFile, line ) ) {
            // if line starts with a comment, ignore the line
            boost::algorithm::trim( line );
            if( line.length() > 2 && line.substr( 0, 2 ) == "//" )
                continue;
            if( line.find( '=' ) == std::string::npos )
                continue;

            boost::char_separator<char>                    sep( "=" );
            boost::tokenizer<boost::char_separator<char> > tokens( line, sep );
            int                                            tokenNo = 0;
            string                                         key     = "", value = "";
            BOOST_FOREACH( const string &t, tokens ) {
                if( tokenNo == 0 ) {
                    key = t;
                }
                else {
                    value = t;
                    break;
                }
                tokenNo++;
            }

            // now we have the key and value, try to make sense of it
            boost::algorithm::trim( key );
            boost::algorithm::trim( value );
            if( value[ value.length() - 1 ] == ';' ) {
                value =  value.substr( 0, value.length() - 1 );
            }

            if( key.empty() || value.empty() ) {
                continue;
            }
            // ignore comments if any
            if( value.find( "//" ) != std::string::npos ) {
                value = value.substr( 0, value.find( "//" ) );
            }

            if( value[ 0 ] == '\"' && value[ value.length() - 1 ] == '\"' ) {
                if( value.length() >= 3 ) {
                    value = value.substr( 1, value.length() - 2 );
                }
                else {
                    continue;
                }
            }

            if( key == "search_algorithm" ) {
                // such if-else structures will make sure that invalid values are not set
                if( value == "gde3" ) {
                    searchAlgorithmName = "gde3";
                    psc_dbgmsg( PSC_SELECTIVE_DEBUG_LEVEL( AutotunePlugins ), "PCAPSpeedupPlugin: search algorithm to be loaded changed to gde3\n" );
                }
                else if( value == "individual" ) {
                    searchAlgorithmName = "individual";
                    psc_dbgmsg( PSC_SELECTIVE_DEBUG_LEVEL( AutotunePlugins ), "PCAPSpeedupPlugin: search algorithm to be loaded changed to individual\n" );
                }
                else if( value == "random" ) {
                    searchAlgorithmName = "random";
                    psc_dbgmsg( PSC_SELECTIVE_DEBUG_LEVEL( AutotunePlugins ), "PCAPSpeedupPlugin: search algorithm to be loaded changed to random\n" );
                }
                else if( value == "exhaustive" ) {
                    searchAlgorithmName = "exhaustive";
                    psc_dbgmsg( PSC_SELECTIVE_DEBUG_LEVEL( AutotunePlugins ), "PCAPSpeedupPlugin: search algorithm to be loaded changed to exhaustive\n" );
                }
                else {
                    psc_dbgmsg( PSC_SELECTIVE_DEBUG_LEVEL( AutotunePlugins ), "PCAPSpeedupPlugin: Invalid options for search algorithm. Valid options are \"exhaustive\",\"gde3\",\"individual\" & \"random\".\n" );
                }
            }
            else if( key == "parallelRegions" ) {
                if( value == "true" ) {
                    withParallelRegions = true;
                    psc_dbgmsg( PSC_SELECTIVE_DEBUG_LEVEL( AutotunePlugins ), "PCAPSpeedupPlugin: parallel regions will be used for tuning\n" );
                }
                else if( value == "false" ) {
                    withParallelRegions = false;
                    psc_dbgmsg( PSC_SELECTIVE_DEBUG_LEVEL( AutotunePlugins ), "PCAPSpeedupPlugin: parallel regions will NOT be used for tuning\n" );
                }
                else {
                    psc_dbgmsg( PSC_SELECTIVE_DEBUG_LEVEL( AutotunePlugins ), "PCAPSpeedupPlugin: Invalid options for parallel regions. Valid options are \"true\" or \"false\"\n" );
                }
            }
            else if( key == "userRegion" ) {
                if( value == "true" ) {
                    withUserRegion = true;
                    psc_dbgmsg( PSC_SELECTIVE_DEBUG_LEVEL( AutotunePlugins ), "PCAPSpeedupPlugin: User region will be used for tuning\n" );
                }
                else if( value == "false" ) {
                    withUserRegion = false;
                    psc_dbgmsg( PSC_SELECTIVE_DEBUG_LEVEL( AutotunePlugins ), "PCAPSpeedupPlugin: User region will NOT be used for tuning\n" );
                }
                else {
                    psc_dbgmsg( PSC_SELECTIVE_DEBUG_LEVEL( AutotunePlugins ), "PCAPSpeedupPlugin: Invalid options for user regions. Valid options are \"true\" or \"false\"\n" );
                }
            }
            else if( key == "minRegionsToConsider" ) {
                try{
                    int noRegions = boost::lexical_cast<int>( value );
                    if( noRegions > 0 ) {
                        minNoRegions = noRegions;
                        psc_dbgmsg( PSC_SELECTIVE_DEBUG_LEVEL( AutotunePlugins ), "PCAPSpeedupPlugin: At least %d parallel regions will be considered for tuning\n", minNoRegions );
                    }
                    else {
                        psc_dbgmsg( PSC_SELECTIVE_DEBUG_LEVEL( AutotunePlugins ), "PCAPSpeedupPlugin: Invalid option for minRegionsToConsider. Valid option is a integer value > 0\n", minNoRegions );
                    }
                }
                catch( const boost::bad_lexical_cast& ) {
                    psc_dbgmsg( PSC_SELECTIVE_DEBUG_LEVEL( AutotunePlugins ), "Invalid option for noRegionsToConsider\n" );
                    continue;
                }
            }
            else if( key == "maxRegionsToConsider" ) {
                try{
                    int noRegions = boost::lexical_cast<int>( value );
                    if( noRegions > 0 ) {
                        maxNoRegions = noRegions;
                        psc_dbgmsg( PSC_SELECTIVE_DEBUG_LEVEL( AutotunePlugins ), "PCAPSpeedupPlugin: At most %d parallel regions will be considered for tuning\n", maxNoRegions );
                    }
                    else {
                        psc_dbgmsg( PSC_SELECTIVE_DEBUG_LEVEL( AutotunePlugins ), "PCAPSpeedupPlugin: Invalid option for maxRegionsToConsider. Valid option is a integer value > 0\n", minNoRegions );
                    }
                }
                catch( const boost::bad_lexical_cast& ) {
                    psc_dbgmsg( PSC_SELECTIVE_DEBUG_LEVEL( AutotunePlugins ), "Invalid option for noRegionsToConsider\n" );
                    continue;
                }
            }
            else if( key == "cutoff1" ) {
                try{
                    double cutoff = boost::lexical_cast<double>( value );
                    if( cutoff > 0 && cutoff < 1 ) {
                        firstCutOff = cutoff;
                        psc_dbgmsg( PSC_SELECTIVE_DEBUG_LEVEL( AutotunePlugins ), "PCAPSpeedupPlugin: firstCutOff set to %.2lf.\n", firstCutOff );
                        psc_dbgmsg( PSC_SELECTIVE_DEBUG_LEVEL( AutotunePlugins ), "PCAPSpeedupPlugin: parallel regions with exec time >= %.2lf will be considered for tuning until max limit is reached.\n", firstCutOff );
                    }
                    else {
                        psc_dbgmsg( PSC_SELECTIVE_DEBUG_LEVEL( AutotunePlugins ), "PCAPSpeedupPlugin: Invalid value for cutoff1. Valid option is a float value between 0 and 1.\n" );
                    }
                }
                catch( const boost::bad_lexical_cast& ) {
                    psc_dbgmsg( PSC_SELECTIVE_DEBUG_LEVEL( AutotunePlugins ), "invalid option for cutoff1\n" );
                    continue;
                }
            }
            else if( key == "cutoff2" ) {
                try{
                    double cutoff = boost::lexical_cast<double>( value );
                    if( cutoff > 0 && cutoff < 1 ) {
                        secondCutOff = cutoff;
                        psc_dbgmsg( PSC_SELECTIVE_DEBUG_LEVEL( AutotunePlugins ), "PCAPSpeedupPlugin: secondCutOff set to %.2lf.\n", secondCutOff );
                        psc_dbgmsg( PSC_SELECTIVE_DEBUG_LEVEL( AutotunePlugins ), "PCAPSpeedupPlugin: parallel regions with exec time >= %.2lf will be considered depending on number of regions already considered.\n", secondCutOff );
                    }
                    else {
                        psc_dbgmsg( PSC_SELECTIVE_DEBUG_LEVEL( AutotunePlugins ), "PCAPSpeedupPlugin: Invalid value for cutoff2. Valid option is a float value between 0 and 1.\n" );
                    }
                }
                catch( const boost::bad_lexical_cast& ) {
                    psc_dbgmsg( PSC_SELECTIVE_DEBUG_LEVEL( AutotunePlugins ), "invalid option for cutoff2\n" );
                    continue;
                }
            }
        }

        // check for no of regions consistency
        if( maxNoRegions < minNoRegions ) {
            psc_dbgmsg( PSC_SELECTIVE_DEBUG_LEVEL( AutotunePlugins ), "PCAPSpeedupPlugin: Maximum no of regions (%d) cannot be less than minimum no of regions (%d).\n", maxNoRegions, minNoRegions );
            maxNoRegions = minNoRegions;
            psc_dbgmsg( PSC_SELECTIVE_DEBUG_LEVEL( AutotunePlugins ), "PCAPSpeedupPlugin: Setting maximum no of regions to be equal as minimum no of regions (%d).\n", minNoRegions );
        }

        psc_dbgmsg( PSC_SELECTIVE_DEBUG_LEVEL( AutotunePlugins ), "PCAPSpeedupPlugin: completed reading the configuration file.\n" );
    }
    else {
        psc_dbgmsg( PSC_SELECTIVE_DEBUG_LEVEL( AutotunePlugins ), "PCAPSpeedupPlugin: could not open configuration file.\n" );
    }
}

/*
 * Initialize the plugin's data structures.
 *
 * The tuning parameter list needs to be created.
 *
 * Search algorithms are loaded here when required. This can be done as follows:
 *
 *    searchAlgorithm = loadSearchAlgorithm("name");
 *
 * where "name" refers to one of the available search algorithms (currently only exhaustive).
 *
 */
void PCAPSpeedupPlugin::initialize( DriverContext*   context,
                                    ScenarioPoolSet* pool_set ) {
    psc_dbgmsg( PSC_SELECTIVE_DEBUG_LEVEL( AutotunePlugins ), "PCAPSpeedupPlugin: call to initialize()\n" );
    this->context  = context;
    this->pool_set = pool_set;

    has_pcap_config = false;
    parse_opts( context->getArgc(), context->getArgv() );

    if( app.get_regions().empty() )
        psc_abort( "PCAPSpeedupPlugin : No Region found. Exiting.\n" );

    numberOfThreadsTP = new TuningParameter();
    numberOfThreadsTP->setId( 0 );
    numberOfThreadsTP->setName( "NUMTHREADS" );
    numberOfThreadsTP->setPluginType( PCAP );
    numberOfThreadsTP->setRange( 1, context->getOmpnumthreads(), 1 );
    Restriction* r = new Restriction();
    for( int i = 1; i <= context->getOmpnumthreads(); i = i * 2 ) {
        r->addElement( i );
    }
    r->setRegion( NULL );
    r->setType( 2 );
    numberOfThreadsTP->setRestriction( r );
    numberOfThreadsTP->setRuntimeActionType( TUNING_ACTION_FUNCTION_POINTER );

    string results = numberOfThreadsTP->toString();
    psc_dbgmsg( PSC_SELECTIVE_DEBUG_LEVEL( AutotunePlugins ), "PCAPSpeedupPlugin: Before exiting to initialize, string is: %s\n\n", results.c_str() );

    // initializing variables to default value
    //  for preanalysis & region selection
    firstTuningStep     = true;
    firstCutOff         = 0.2;
    secondCutOff        = 0.1;
    minNoRegions        = 3;
    maxNoRegions        = 3;
    searchAlgorithmName = "exhaustive";

    if( has_pcap_config )
        parseConfigFile(); // might override some defaults
}

/*
 * Defines a pre-analysis strategy.
 *
 * Found properties of the pre-analysis strategy are stored in the arp.
 *
 */
bool PCAPSpeedupPlugin::analysisRequired( StrategyRequest** strategy ) {
    StrategyRequestGeneralInfo*         analysisStrategyGeneralInfo = new StrategyRequestGeneralInfo;
    std::map<string, Region*>::iterator region;

    analysisStrategyGeneralInfo->strategy_name     = "ConfigAnalysis";
    analysisStrategyGeneralInfo->pedantic          = 0;
    analysisStrategyGeneralInfo->delay_phases      = 0;
    analysisStrategyGeneralInfo->delay_seconds     = 0;
    analysisStrategyGeneralInfo->analysis_duration = 1;

    PropertyRequest* req = new PropertyRequest();

    req->addPropertyID( EXECTIME );
    for( region = code_region_candidates.begin(); region != code_region_candidates.end(); region++ ) {
        req->addRegion( region->second );
    }
    req->addAllProcesses();

    std::list<PropertyRequest*>* reqList = new list<PropertyRequest*>;
    reqList->push_back( req );

    *strategy = new StrategyRequest( reqList, analysisStrategyGeneralInfo );
    return true;
}

/*
 * Operations to be done at the start of a tuning step.
 *
 * The tuning parameters that were created at initialization are used to create a variant space.
 * The variant space and the regions are then used to create a search space that is passed to the
 * search algorithm.
 *
 */
void PCAPSpeedupPlugin::startTuningStep() {
    psc_dbgmsg( PSC_SELECTIVE_DEBUG_LEVEL( AutotunePlugins ), "PCAPSpeedupPlugin: call to startTuningStep()\n" );
    std::list<Region*> code_regions;
    code_regions = appl->get_regions();
    std::list<Region*>::iterator region;

    // iterating over all regions & adding to code_region_candidates for preanalysis
    int parallel_regions = 0, parallel_do_regions = 0;
    psc_dbgmsg( PSC_SELECTIVE_DEBUG_LEVEL( AutotunePlugins ), "Searching all available regions...\n" );
    for( region = code_regions.begin(); region != code_regions.end(); region++ ) {
        /*
         * Only parallel regions should be considered for tuning, since we can not set num threads for
         * individual for loops in the same parallel section
         */
        if( ( *region )->get_type() == PARALLEL_REGION ) {
            if( ( *region )->get_type() == PARALLEL_REGION ) {
                parallel_regions++;
                psc_dbgmsg( PSC_SELECTIVE_DEBUG_LEVEL( AutotunePlugins ), "Parallel region found:\n" );
            }
            else {
                parallel_do_regions++;
                psc_dbgmsg( PSC_SELECTIVE_DEBUG_LEVEL( AutotunePlugins ), "Parallel do region found:\n" );
            }
            psc_dbgmsg( PSC_SELECTIVE_DEBUG_LEVEL( AutotunePlugins ), "\tFile name: %s\n", ( *region )->getFileName().c_str() );
            psc_dbgmsg( PSC_SELECTIVE_DEBUG_LEVEL( AutotunePlugins ), "\tFirst line: %d\n", ( *region )->getFirstLine() );
            psc_dbgmsg( PSC_SELECTIVE_DEBUG_LEVEL( AutotunePlugins ), "\tLast line: %d\n", ( *region )->getLastLine() );
            psc_dbgmsg( PSC_SELECTIVE_DEBUG_LEVEL( AutotunePlugins ), "\tMatcher key: %s\n", ( *region )->getIdForPropertyMatching().c_str() );
            code_region_candidates[ ( *region )->getIdForPropertyMatching() ] = *region;
        }
    }
    psc_dbgmsg( PSC_SELECTIVE_DEBUG_LEVEL( AutotunePlugins ), "PCAP PLUGIN: found %d parallel & parallel_do regions.\n", ( parallel_regions + parallel_do_regions ) );

    psc_dbgmsg( PSC_SELECTIVE_DEBUG_LEVEL( AutotunePlugins ), "obtain getSearchInstance\n" );
    int    major, minor;
    string name, description;

    char const* selected_search = getenv( "PSC_SEARCH_ALGORITHM" );
    if( selected_search != NULL ) {
        psc_dbgmsg( PSC_SELECTIVE_DEBUG_LEVEL( AutotunePlugins ), "User specified search algorithm: %s\n", selected_search );
        string selected_search_string = string( selected_search );
        context->loadSearchAlgorithm( selected_search_string, &major, &minor, &name, &description );
        searchAlgorithm = context->getSearchAlgorithmInstance( selected_search_string );
    }
    else {
        psc_dbgmsg( PSC_SELECTIVE_DEBUG_LEVEL( AutotunePlugins ), "Selecting default search algorithm: %s\n ", searchAlgorithmName.c_str() );
        context->loadSearchAlgorithm( searchAlgorithmName, &major, &minor, &name, &description );
        searchAlgorithm = context->getSearchAlgorithmInstance( searchAlgorithmName );
        searchAlgorithm->addObjectiveFunction( new TimeObjective("") );
    }

    if( searchAlgorithm != NULL ) {
        print_loaded_search( major, minor, name, description );
        searchAlgorithm->initialize( context, pool_set );
    }
    else {
        perror( "NULL pointer in searchAlgorithm\n" );
        throw PTF_PLUGIN_ERROR( NULL_REFERENCE );
    }

    psc_dbgmsg( PSC_SELECTIVE_DEBUG_LEVEL( AutotunePlugins ), "searchAlgorithm instance obtained\n" );
}

/*
 * The Created Scenario Pool (csp) is populated here.
 *
 * The scenarios need to be created and added to the first pool. To create the scenarios, a
 * search algorithm can be used or it can be done directly by the plugin.
 *
 * After this step, the Periscope will verify that scenarios were added to the csp.
 *
 */
void PCAPSpeedupPlugin::createScenarios() {
    psc_dbgmsg( PSC_SELECTIVE_DEBUG_LEVEL( AutotunePlugins ), "PCAPSpeedupPlugin: call to createScenarios()\n" );
    if( !searchAlgorithm )
        psc_abort("Error: The search algorithm is set to a nullptr.");

    // while createScenarios may be called multiple times, we should add the searchspace only once
    if( firstTuningStep ) {
        firstTuningStep = false;

        if( withParallelRegions ) {
            // sorting and arranging prenanalysis result
            list<MetaProperty> found_properties = pool_set->arp->getPreAnalysisProperties( 0 );
            double             totalExecTime    = 0;

            BOOST_FOREACH( MetaProperty& property, found_properties ) {
                regionExectimeMap.push_back( make_pair( property.getRegionId(), property.getSeverity() ) );
                psc_dbgmsg( PSC_SELECTIVE_DEBUG_LEVEL( AutotunePlugins ),
                            "PCAPSpeedupPlugin: Severity (%f) in region: %d added to vector\n",
                            property.getSeverity(), static_cast<int>( property.getRegionType() ) );
                totalExecTime += property.getSeverity();
            }

            // sort the vector according to decreasing execution time
            std::sort( regionExectimeMap.begin(), regionExectimeMap.end(), pairCompare );

            /*
             *  Using heuristic to find out important regions
             *  - first add regions with >= firstCutOff % (e.g. 20%) exectime unitl maxNoRegions
             *  - if no of regions are less than minNoRegions, add regions with  with
             *    exectime < firstCutoff & >=secondCutOff % (e.g. between 20% & 10%) exectime
             */

            int noRegionsAdded = 0;
            // initially collect regions that are above first cutoff
            for( int i = 0; i < regionExectimeMap.size(); i++ ) {
                double execTime = regionExectimeMap[ i ].second;
                if( execTime < ( firstCutOff * totalExecTime ) ) {
                    break;
                }

                noRegionsAdded++;
                selected_region = code_region_candidates[ regionExectimeMap[ i ].first ];
                addRegionToSearchAlgorithm( regionExectimeMap[ i ].second );
                if( noRegionsAdded == maxNoRegions ) {
                    break;
                }
            }

            if( noRegionsAdded < minNoRegions ) { // utilize second cutoff
                for( int i = 0; i < regionExectimeMap.size(); i++ ) {
                    double execTime = regionExectimeMap[ i ].second;
                    if( execTime < ( secondCutOff * totalExecTime ) ) {
                        break;
                    }

                    if( execTime >= ( firstCutOff * totalExecTime ) ) {
                        continue;
                    }

                    noRegionsAdded++;
                    selected_region = code_region_candidates[ regionExectimeMap[ i ].first ];
                    addRegionToSearchAlgorithm( regionExectimeMap[ i ].second );
                    if( noRegionsAdded == minNoRegions ) {
                        break;
                    }
                }
            }

            // if no regions added, add first few regions in decreasing order of their execTime
            if( noRegionsAdded == 0 ) {
                for( int i = 0; i < regionExectimeMap.size(); i++ ) {
                    noRegionsAdded++;
                    selected_region = code_region_candidates[ regionExectimeMap[ 0 ].first ];
                    addRegionToSearchAlgorithm( regionExectimeMap[ 0 ].second );
                    if( noRegionsAdded == minNoRegions ) {
                        break;
                    }
                }
            }
        }

        if( !withParallelRegions || withUserRegion ) {
            psc_dbgmsg( PSC_SELECTIVE_DEBUG_LEVEL( AutotunePlugins ),
                        "PCAPSpeedupPlugin: Creating search space for the USER region\n" );
            SearchSpace*  searchspace  = new SearchSpace();
            VariantSpace* variantSpace = new VariantSpace();
            variantSpace->addTuningParameter( numberOfThreadsTP );
            searchspace->setVariantSpace( variantSpace );
            searchspace->addRegion( app.get_phase_region() );
            searchAlgorithm->addSearchSpace( searchspace );
        }
    }

    searchAlgorithm->createScenarios();
    psc_dbgmsg( PSC_SELECTIVE_DEBUG_LEVEL( AutotunePlugins ), "PCAPSpeedupPlugin: call to createScenarios() completed\n" );
}

/*
 * Preparatory steps for the scenarios are done here.
 *
 * If there are any preparatory steps required by some or all scenarios in the csp (for example:
 * the project may need to be re-compiled), then they are to be performed here. After each
 * scenario is prepared, they are migrated from the csp to the Prepared Scenario Pool (psp).
 *
 * In some cases, no preparation may be necessary and the plugin can simply move all scenarios
 * from the csp to the psp.
 *
 * After this step, the Periscope will verify that scenarios were added to the psp.
 *
 */
void PCAPSpeedupPlugin::prepareScenarios() {
    psc_dbgmsg( PSC_SELECTIVE_DEBUG_LEVEL( AutotunePlugins ), "PCAPSpeedupPlugin: call to prepareScenarios()\n" );

    if( !pool_set->csp->empty() ) {
        Scenario* scenario;
        scenario = pool_set->csp->pop();
        pool_set->psp->push( scenario );
    }
}

/*
 * Populate the Experiment Scenario Pool (esp) for the next experiment.
 *
 * This is the final step before the experiments are executed. Scenarios are moved from the
 * psp to the esp, depending on the number of processes and whether they can be executed
 * in parallel.
 *
 * After this step, the Periscope will verify that scenarios were added to the esp.
 *
 */
void PCAPSpeedupPlugin::defineExperiment( int               numprocs,
                                          bool&             analysisRequired,
                                          StrategyRequest** strategy ) {
    psc_dbgmsg( PSC_SELECTIVE_DEBUG_LEVEL( AutotunePlugins ), "PCAPSpeedupPlugin: call to defineExperiment()\n" );

    int i = 0;
    Scenario* scenario;
    for( ; !pool_set->psp->empty() && i < numprocs; i++ ) {
        scenario = pool_set->psp->pop();

        std::list<PropertyRequest*>* propertyRequestList = new list<PropertyRequest*>();
        std::list<int>*              propertyIds         = new list<int>;

        propertyIds->push_back( EXECTIME );
        propertyRequestList->push_back( new PropertyRequest( propertyIds ) );
        scenario->setPropertyRequests( propertyRequestList );
        scenario->setTunedRegion( app.get_phase_region() );

        pool_set->esp->push( scenario );
    }

    psc_dbgmsg( PSC_SELECTIVE_DEBUG_LEVEL( AutotunePlugins ), "PCAPSpeedupPlugin: Added %d scenario in the experiment.\n", i );
    StrategyRequestGeneralInfo* strategyRequestGeneralInfo = new StrategyRequestGeneralInfo;

    strategyRequestGeneralInfo->strategy_name     = "OMP";
    strategyRequestGeneralInfo->pedantic          = 1;
    strategyRequestGeneralInfo->delay_phases      = 0;
    strategyRequestGeneralInfo->delay_seconds     = 0;
    strategyRequestGeneralInfo->analysis_duration = 1;

    *strategy = NULL;
}

/*
 * Return true if a restart of the application is required for the next experiment,
 * false otherwise.
 */
bool PCAPSpeedupPlugin::restartRequired( std::string& env,
                                         int&         numprocs,
                                         std::string& command,
                                         bool&        is_instrumented ) {
    return false; // restart not required to change the number of threads
}

/*
 * Return true if if the current search iteration is finished (by either the plugin itself or as
 * a result of the search algorithm), false otherwise.
 */
bool PCAPSpeedupPlugin::searchFinished() {
    psc_dbgmsg( PSC_SELECTIVE_DEBUG_LEVEL( AutotunePlugins ), "PCAPSpeedupPlugin: call to searchFinished()\n" );
    return searchAlgorithm->searchFinished();
}

/*
 * Final operation of a tuning step.
 *
 * If any post-processing is necessary before entering the next tuning iteration, it is to be
 * done here.
 */
void PCAPSpeedupPlugin::finishTuningStep() {
}

/*
 * Returns true if the plugin finished the tuning process, false otherwise.
 */
bool PCAPSpeedupPlugin::tuningFinished() {
    psc_dbgmsg( PSC_SELECTIVE_DEBUG_LEVEL( AutotunePlugins ), "PCAPSpeedupPlugin: call to tuningFinished()\n" );
    return true;
}

/*
 * Prints to the screen (and to a file, where necessary) the tuning advice.
 */
Advice* PCAPSpeedupPlugin::getAdvice() {
    psc_dbgmsg( PSC_SELECTIVE_DEBUG_LEVEL( AutotunePlugins ), "PCAPSpeedupPlugin: call to getAdvice()\n" );
    if( !searchAlgorithm )
        psc_abort("Error: The search algorithm is set to a nullptr.");

    Scenario* scenario;
    for( int scenario_id = 0; scenario_id < pool_set->fsp->size(); scenario_id++ ) {
        scenario = ( *pool_set->fsp->getScenarios() )[ scenario_id ];
        std::list<MetaProperty> properties = pool_set->srp->getScenarioResultsByID( scenario_id );

        BOOST_FOREACH( MetaProperty& prop, properties )
            scenario->addResult( "Time", prop.getSeverity() );
    }

    writePCAPresults();

    Scenario* best_scenario = ( *pool_set->fsp->getScenarios() )[ searchAlgorithm->getOptimum() ];
    if( !best_scenario )
        psc_abort( "Error: Best scenario cannot be NULL at this point." );

    return new Advice( getName(), best_scenario, searchAlgorithm->getSearchPath(), "Time", pool_set->fsp->getScenarios() );
}

/*
 * Finalize the plugin normally.
 *
 * Remove any allocated memory, objects, file descriptors, etc.
 *
 */
void PCAPSpeedupPlugin::finalize() {
    psc_dbgmsg( PSC_SELECTIVE_DEBUG_LEVEL( AutotunePlugins ), "PCAPSpeedupPlugin: call to finalize()\n" );
    terminate();
}

/*
 * Terminate the plugin due to error.
 *
 * Safely remove any allocated memory, objects, file descriptors, etc. This method should
 * be able to be executed safely at any point.
 *
 */
void PCAPSpeedupPlugin::terminate() {
    psc_dbgmsg( PSC_SELECTIVE_DEBUG_LEVEL( AutotunePlugins ), "PCAPSpeedupPlugin: call to terminate()\n" );

    if( searchAlgorithm ) {
        searchAlgorithm->finalize();
        delete searchAlgorithm;
    }

    context->unloadSearchAlgorithms();
}

/**
 * @brief Returns an instance of this particular plugin implementation.
 *
 * @ingroup PCAPSpeedupPlugin
 *
 * @return A pointer to an instance of this particular plugin implementation.
 */
IPlugin* getPluginInstance() {
    psc_dbgmsg( PSC_SELECTIVE_DEBUG_LEVEL( AutotunePlugins ), "PCAPSpeedupPlugin: call to getComponentInstance()\n" );
    return new PCAPSpeedupPlugin();
}

/**
 * @brief Returns the major plugin interface version used by this plugin (example: the 1 in 1.0).
 *
 * @ingroup PCAPSpeedupPlugin
 *
 * @return The major plugin interface version used by the plugin
 */
int getVersionMajor() {
    psc_dbgmsg( PSC_SELECTIVE_DEBUG_LEVEL( AutotunePlugins ), "PCAPSpeedupPlugin: call to getInterfaceVersionMajor()\n" );
    return 1;
}

/**
 * @brief Returns the minor plugin interface version used by this plugin (example: the 0 in 1.0).
 *
 * @ingroup PCAPSpeedupPlugin
 *
 * @return The minor plugin interface version used by the plugin
 *
 */
int getVersionMinor() {
    psc_dbgmsg( PSC_SELECTIVE_DEBUG_LEVEL( AutotunePlugins ), "PCAPSpeedupPlugin: call to getInterfaceVersionMinor()\n" );
    return 0;
}

/**
 * @brief Returns a string with the name of the plugin.
 *
 * @ingroup PCAPSpeedupPlugin
 *
 * @return A string with the name of the plugin
 *
 */
std::string getName() {
    psc_dbgmsg( PSC_SELECTIVE_DEBUG_LEVEL( AutotunePlugins ), "PCAPSpeedupPlugin: call to getName()\n" );
    return "PCAP plugin";
}

/**
 * @brief Returns a string with a short description of the plugin.
 *
 * @ingroup PCAPSpeedupPlugin
 *
 * @return A string with a short description of the plugin
 *
 */
std::string getShortSummary() {
    psc_dbgmsg( PSC_SELECTIVE_DEBUG_LEVEL( AutotunePlugins ), "PCAPSpeedupPlugin: call to getShortSummary()\n" );
    return "Tunes the Energy Delay Product of OMP applications.";
}

void PCAPSpeedupPlugin::addRegionToSearchAlgorithm(double  execTime) {
    psc_dbgmsg( PSC_SELECTIVE_DEBUG_LEVEL( AutotunePlugins ), "PCAPSpeedupPlugin: selected region with: runtime: %f; ID: %s; file: %s; first line: %d; last line: %d;\n", execTime, selected_region->getIdForPropertyMatching().c_str(), selected_region->getFileName().c_str(), selected_region->getFirstLine(), selected_region->getLastLine() );

    SearchSpace*  searchspace  = new SearchSpace();
    VariantSpace* variantSpace = new VariantSpace();

    variantSpace->addTuningParameter( numberOfThreadsTP );
    searchspace->setVariantSpace( variantSpace );

    selected_region->print();
    printf( "\n" );
    searchspace->addRegion( selected_region );
    searchAlgorithm->addSearchSpace( searchspace );
}

void PCAPSpeedupPlugin::writePCAPresults() {
    const int num_scenarios = pool_set->fsp->size();

    std::ostringstream result_oss;
    result_oss << "\nAutoTune Results:" << std::endl;
    result_oss << "-----------------------\n\n";

    result_oss << "\nAll Results:\n";
    result_oss << "Scenario                            |   Threads   |   Execution Time\n";
    std::ofstream result_file( "pcap_results.txt" );
    result_file << "Scenario ID;Threads;Time\n";
    for( int scenario_id = 0; scenario_id < num_scenarios; ++scenario_id ) {
        Scenario* scenario = ( *pool_set->fsp->getScenarios() )[ scenario_id ];
        result_oss <<  std::setw( 3 )  <<  scenario_id  <<  "    ";
        result_file << scenario_id << "; ";

        BOOST_FOREACH( TuningSpecification* ts, *scenario->getTuningSpecifications() ) {
            typedef std::map<TuningParameter*, int>::const_iterator Iterator;
            int nthr = 0;

            // the variant is a list of parameters and values
            for( Iterator iter = ts->getVariant()->getValue().begin(); iter != ts->getVariant()->getValue().end(); ++iter )
                nthr = iter->second;

            BOOST_FOREACH( const std::string& region_iter, *ts->getVariantContext().context_union.entity_list ) {
                std::ostringstream temp;
                temp <<  "("  <<  region_iter  <<  "):";
                std::string tempStr = temp.str();
                result_oss <<  std::setw( 24 )  <<  std::left  <<  tempStr  <<  std::setw( 3 )  <<  std::right  <<  nthr  <<  "  ";
                result_file <<  tempStr;
            }
        }

        result_file << ";";

        typedef std::map<string, double>::const_iterator Iterator;
        std::map<string, double> results = scenario->getResults();
        for( Iterator i = results.begin(); i != results.end(); i++ ) {
            result_oss << std::setw( 14 ) <<  std::right  << i->second;
            result_file << i->second << ";";
        }

        result_oss << std::endl;
        result_file << std::endl;
    }
    result_oss << std::endl;

    // print best scenario
    Scenario* best_scenario = ( *pool_set->fsp->getScenarios() )[ searchAlgorithm->getOptimum() ];
    if( !best_scenario )
        psc_abort( "Error: Best scenario cannot be NULL at this point." );
    assert( best_scenario );
    result_oss << "=> Best scenario: " << best_scenario->getID() << std::endl;

    // print all the generated output
    std::cout << result_oss.str();
}

ext: cc

max_stars_repo_name: readex-eu/readex-ptf

max_issues_repo_name: readex-eu/readex-ptf

max_forks_repo_name: readex-eu/readex-ptf


text:
/*
 * Score a grammar in striped format
 * ./score_grammar <alignment> < filtered.grammar > scored.grammar
 */
#include <iostream>
#include <string>
#include <map>
#include <vector>
#include <utility>
#include <cstdlib>
#include <fstream>
#include <tr1/unordered_map>

#include "sentence_pair.h"
#include "extract.h"
#include "fdict.h"
#include "tdict.h"
#include "lex_trans_tbl.h"
#include "filelib.h"

#include <boost/functional/hash.hpp>
#include <boost/program_options.hpp>
#include <boost/program_options/variables_map.hpp>

using namespace std;
using namespace std::tr1;

static const size_t MAX_LINE_LENGTH = 64000000;

typedef unordered_map<vector<WordID>, RuleStatistics, boost::hash<vector<WordID> > > ID2RuleStatistics;

namespace {
  inline bool IsWhitespace(char c) { return c == ' ' || c == '\t'; }
  inline bool IsBracket(char c){return c == '[' || c == ']';}
  inline void SkipWhitespace(const char* buf, int* ptr) {
    while (buf[*ptr] && IsWhitespace(buf[*ptr])) { ++(*ptr); }
  }
}

int ReadPhraseUntilDividerOrEnd(const char* buf, const int sstart, const int end, vector<WordID>* p) {
  static const WordID kDIV = TD::Convert("|||");
  int ptr = sstart;
  while(ptr < end) {
    while(ptr < end && IsWhitespace(buf[ptr])) { ++ptr; }
    int start = ptr;
    while(ptr < end && !IsWhitespace(buf[ptr])) { ++ptr; }
    if (ptr == start) {cerr << "Warning! empty token.\n"; return ptr; }
    const WordID w = TD::Convert(string(buf, start, ptr - start));

    if((IsBracket(buf[start]) and IsBracket(buf[ptr-1])) or( w == kDIV))
      p->push_back(1 * w);
    else {
      if (w == kDIV) return ptr;
      p->push_back(w);
    }
  }
  return ptr;
}

void ParseLine(const char* buf, vector<WordID>* cur_key, ID2RuleStatistics* counts) {
  static const WordID kDIV = TD::Convert("|||");
  counts->clear();
  int ptr = 0;
  while(buf[ptr] != 0 && buf[ptr] != '\t') { ++ptr; }
  if (buf[ptr] != '\t') {
    cerr << "Missing tab separator between key and value!\n INPUT=" << buf << endl;
    exit(1);
  }
  cur_key->clear();
  // key is: "[X] ||| word word word"
  int tmpp = ReadPhraseUntilDividerOrEnd(buf, 0, ptr, cur_key);
  cur_key->push_back(kDIV);
  ReadPhraseUntilDividerOrEnd(buf, tmpp, ptr, cur_key);
  ++ptr;
  int start = ptr;
  int end = ptr;
  int state = 0; // 0=reading label, 1=reading count
  vector<WordID> name;
  while(buf[ptr] != 0) {
    while(buf[ptr] != 0 && buf[ptr] != '|') { ++ptr; }
    if (buf[ptr] == '|') {
      ++ptr;
      if (buf[ptr] == '|') {
        ++ptr;
        if (buf[ptr] == '|') {
          ++ptr;
          end = ptr - 3;
          while (end > start && IsWhitespace(buf[end-1])) { --end; }
          if (start == end) {
            cerr << "Got empty token!\n  LINE=" << buf << endl;
            exit(1);
          }
          switch (state) {
            case 0: ++state; name.clear(); ReadPhraseUntilDividerOrEnd(buf, start, end, &name); break;
            case 1: --state; (*counts)[name].ParseRuleStatistics(buf, start, end); break;
            default: cerr << "Can't happen\n"; abort();
          }
          SkipWhitespace(buf, &ptr);
          start = ptr;
        }
      }
    }
  }
  end=ptr;
  while (end > start && IsWhitespace(buf[end-1])) { --end; }
  if (end > start) {
    switch (state) {
      case 0: ++state; name.clear(); ReadPhraseUntilDividerOrEnd(buf, start, end, &name); break;
      case 1: --state; (*counts)[name].ParseRuleStatistics(buf, start, end); break;
      default: cerr << "Can't happen\n"; abort();
    }
  }
}

void LexTranslationTable::createTTable(const char* buf){

  bool DEBUG = false;

  AnnotatedParallelSentence sent;

  sent.ParseInputLine(buf);

  //iterate over the alignment to compute aligned words

  for(int i =0;i<sent.aligned.width();i++)
    {
      for (int j=0;j<sent.aligned.height();j++)
	{
	  if (DEBUG) cerr << sent.aligned(i,j) << " ";
	  if( sent.aligned(i,j))
	    {
	      if (DEBUG) cerr << TD::Convert(sent.f[i])  << " aligned to " << TD::Convert(sent.e[j]);
	      ++word_translation[pair<WordID,WordID> (sent.f[i], sent.e[j])];
	      ++total_foreign[sent.f[i]];
	      ++total_english[sent.e[j]];
	    }
	}
      if (DEBUG)  cerr << endl;
    }
  if (DEBUG) cerr << endl;

  static const WordID NULL_ = TD::Convert("NULL");
  //handle unaligned words - align them to null
  for (int j =0; j < sent.e_len; j++)
    {
      if (sent.e_aligned[j]) continue;
      ++word_translation[pair<WordID,WordID> (NULL_, sent.e[j])];
      ++total_foreign[NULL_];
      ++total_english[sent.e[j]];
    }

  for (int i =0; i < sent.f_len; i++)
    {
      if (sent.f_aligned[i]) continue;
      ++word_translation[pair<WordID,WordID> (sent.f[i], NULL_)];
      ++total_english[NULL_];
      ++total_foreign[sent.f[i]];
    }

}

inline float safenlog(float v) {
  if (v == 1.0f) return 0.0f;
  float res = -log(v);
  if (res > 100.0f) res = 100.0f;
  return res;
}

int main(int argc, char** argv){
  bool DEBUG= false;
  if (argc != 2) {
    cerr << "Usage: " << argv[0] << " corpus.al < filtered.grammar\n";
    return 1;
  }
  ifstream alignment (argv[1]);
  istream& unscored_grammar = cin;
  ostream& scored_grammar = cout;

  //create lexical translation table
  cerr << "Creating table..." << endl;
  char* buf = new char[MAX_LINE_LENGTH];

  LexTranslationTable table;

  while(!alignment.eof())
    {
      alignment.getline(buf, MAX_LINE_LENGTH);
      if (buf[0] == 0) continue;

      table.createTTable(buf);
    }

  bool PRINT_TABLE=false;
  if (PRINT_TABLE)
    {
      ofstream trans_table;
      trans_table.open("lex_trans_table.out");
      for(map < pair<WordID,WordID>,int >::iterator it = table.word_translation.begin(); it != table.word_translation.end(); ++it)
      {
	trans_table <<  TD::Convert(it->first.first) <<  "|||" << TD::Convert(it->first.second) << "==" << it->second << "//" << table.total_foreign[it->first.first] << "//" << table.total_english[it->first.second] << endl;
      }

      trans_table.close();
    }

  //score unscored grammar
  cerr <<"Scoring grammar..." << endl;

  ID2RuleStatistics acc, cur_counts;
  vector<WordID> key, cur_key,temp_key;
  vector< pair<short,short> > al;
  vector< pair<short,short> >::iterator ita;
  int line = 0;

  static const int kCF = FD::Convert("CF");
  static const int kCE = FD::Convert("CE");
  static const int kCFE = FD::Convert("CFE");

  while(!unscored_grammar.eof())
    {
      ++line;
      unscored_grammar.getline(buf, MAX_LINE_LENGTH);
      if (buf[0] == 0) continue;
      ParseLine(buf, &cur_key, &cur_counts);

      //loop over all the Target side phrases that this source aligns to
      for (ID2RuleStatistics::const_iterator it = cur_counts.begin(); it != cur_counts.end(); ++it)
	{

	 /*Compute phrase translation prob.
	   Print out scores in this format:
	   Phrase trnaslation prob P(F|E)
	   Phrase translation prob P(E|F)
	   Lexical weighting prob lex(F|E)
	   Lexical weighting prob lex(E|F)
	 */

	  float pEF_ = it->second.counts.value(kCFE) / it->second.counts.value(kCF);
	  float pFE_ = it->second.counts.value(kCFE) / it->second.counts.value(kCE);

	  map <WordID, pair<int, float> > foreign_aligned;
	  map <WordID, pair<int, float> > english_aligned;

	  //Loop over all the alignment points to compute lexical translation probability
	  al = it->second.aligns;
	  for(ita = al.begin(); ita != al.end(); ++ita)
	    {

	      if (DEBUG)
		{
		  cerr << "\nA:" << ita->first << "," << ita->second << "::";
		  cerr <<  TD::Convert(cur_key[ita->first + 2]) << "-" << TD::Convert(it->first[ita->second]);
		}

	      //Lookup this alignment probability in the table
	      int temp = table.word_translation[pair<WordID,WordID> (cur_key[ita->first+2],it->first[ita->second])];
	      float f2e=0, e2f=0;
	      if ( table.total_foreign[cur_key[ita->first+2]] != 0)
		f2e = (float) temp / table.total_foreign[cur_key[ita->first+2]];
	      if ( table.total_english[it->first[ita->second]] !=0 )
		e2f = (float) temp / table.total_english[it->first[ita->second]];
	      if (DEBUG) printf (" %d %E %E\n", temp, f2e, e2f);

	      //local counts to keep track of which things haven't been aligned, to later compute their null alignment
	      if (foreign_aligned.count(cur_key[ita->first+2]))
		{
		  foreign_aligned[ cur_key[ita->first+2] ].first++;
		  foreign_aligned[ cur_key[ita->first+2] ].second += e2f;
		}
	      else
		foreign_aligned [ cur_key[ita->first+2] ] = pair<int,float> (1,e2f);

	      if (english_aligned.count( it->first[ ita->second] ))
		{
		  english_aligned[ it->first[ ita->second ]].first++;
		  english_aligned[  it->first[ ita->second] ].second += f2e;
		}
	      else
		english_aligned [ it->first[ ita->second] ] = pair<int,float> (1,f2e);

	    }

	  float final_lex_f2e=1, final_lex_e2f=1;
	  static const WordID NULL_ = TD::Convert("NULL");

	  //compute lexical weight P(F|E) and include unaligned foreign words
	   for(int i=0;i<cur_key.size(); i++)
	     {

	       if (!table.total_foreign.count(cur_key[i])) continue;      //if we dont have it in the translation table, we won't know its lexical weight

	       if (foreign_aligned.count(cur_key[i]))
		 {
		   pair<int, float> temp_lex_prob = foreign_aligned[cur_key[i]];
		   final_lex_e2f *= temp_lex_prob.second / temp_lex_prob.first;
		 }
	       else //dealing with null alignment
		 {
		   int temp_count = table.word_translation[pair<WordID,WordID> (cur_key[i],NULL_)];
		   float temp_e2f = (float) temp_count / table.total_english[NULL_];
		   final_lex_e2f *= temp_e2f;
		 }

	     }

	   //compute P(E|F) unaligned english words
	   for(int j=0; j< it->first.size(); j++)
	     {
	       if (!table.total_english.count(it->first[j])) continue;

	       if (english_aligned.count(it->first[j]))
		 {
		   pair<int, float> temp_lex_prob = english_aligned[it->first[j]];
		   final_lex_f2e *= temp_lex_prob.second / temp_lex_prob.first;
		 }
	       else //dealing with null
		 {
		   int temp_count = table.word_translation[pair<WordID,WordID> (NULL_,it->first[j])];
		   float temp_f2e = (float) temp_count / table.total_foreign[NULL_];
		   final_lex_f2e *= temp_f2e;
		 }
	     }

       scored_grammar << TD::GetString(cur_key);
       string lhs = TD::Convert(cur_key[0]);
	   scored_grammar << " " << TD::GetString(it->first) << " |||";
	   if(lhs.find('_')!=string::npos) {
	       scored_grammar << " Bkoff=" << safenlog(3.0f);
	   } else {
	       scored_grammar << " FGivenE=" << safenlog(pFE_) << " EGivenF=" << safenlog(pEF_);
	       scored_grammar << " LexE2F=" << safenlog(final_lex_e2f) << " LexF2E=" << safenlog(final_lex_f2e);
	   }
	   scored_grammar << endl;
	}
    }
}

max_stars_repo_name: agesmundo/FasterCubePruning

max_issues_repo_name: jhclark/cdec

max_forks_repo_name: jhclark/cdec


text:
/*******************************************************************************
*
* MIT License
*
* Copyright (c) 2019 Advanced Micro Devices, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*******************************************************************************/

#include <miopen/config.h>
#include <miopen/hip_build_utils.hpp>
#include <miopen/stringutils.hpp>
#include <miopen/exec_utils.hpp>
#include <miopen/logger.hpp>
#include <miopen/env.hpp>
#include <miopen/target_properties.hpp>
#include <boost/optional.hpp>
#include <sstream>
#include <string>

MIOPEN_DECLARE_ENV_VAR(MIOPEN_DEBUG_HIP_ENFORCE_COV3)
MIOPEN_DECLARE_ENV_VAR(MIOPEN_DEBUG_HIP_VERBOSE)
MIOPEN_DECLARE_ENV_VAR(MIOPEN_DEBUG_HIP_DUMP)

namespace miopen {

bool IsHccCompiler()
{
    static const auto isHcc = EndsWith(MIOPEN_HIP_COMPILER, "hcc");
    return isHcc;
}

bool IsHipClangCompiler()
{
    static const auto isClangXX = EndsWith(MIOPEN_HIP_COMPILER, "clang++");
    return isClangXX;
}

namespace {

inline bool ProduceCoV3()
{
    // If env.var is set, then let's follow it.
    if(IsEnabled(MIOPEN_DEBUG_HIP_ENFORCE_COV3{}))
        return true;
    if(IsDisabled(MIOPEN_DEBUG_HIP_ENFORCE_COV3{}))
        return false;
    // Otherwise, let's enable CO v3 for HIP kernels since ROCm 3.0.
    return (HipCompilerVersion() >= external_tool_version_t{3, 0, -1});
}

/// Returns option for enabling/disabling CO v3 generation for the compiler
/// that builds HIP kernels, depending on compiler version etc.
inline const std::string& GetCoV3Option(const bool enable)
{
    /// \note PR #2166 uses the "--hcc-cov3" option when isHCC is true.
    /// It's unclear why... HCC included in ROCm 2.8 does not support it,
    /// perhaps it suits for some older HCC?
    ///
    /// These options are Ok for ROCm 3.0:
    static const std::string option_enable{"-mcode-object-v3"};
    static const std::string no_option{};
    if(enable)
        return option_enable;
    else
        return no_option;
}
} // namespace

struct LcOptionTargetStrings
{
    const std::string& device;
    const std::string xnack;
    const std::string sramecc;
    LcOptionTargetStrings(const TargetProperties& target)
        : device(target.Name()),
          xnack(std::string{":xnack"} + (target.Xnack() ? "+" : "-")),
          sramecc(std::string{":sramecc"} + (target.Sramecc() ? "+" : "-"))
    {
    }
};

static boost::filesystem::path HipBuildImpl(boost::optional<TmpDir>& tmp_dir,
                                            const std::string& filename,
                                            std::string src,
                                            std::string params,
                                            const TargetProperties& target,
                                            const bool testing_mode)
{
#ifdef __linux__
    // Write out the include files
    // Let's assume includes are overkill for feature tests & optimize'em out.
    if(!testing_mode)
    {
        auto inc_list = GetKernelIncList();
        auto inc_path = tmp_dir->path;
        boost::filesystem::create_directories(inc_path);
        for(auto inc_file : inc_list)
        {
            auto inc_src = GetKernelInc(inc_file);
            WriteFile(inc_src, inc_path / inc_file);
        }
    }
    src += "\nint main() {}\n";
    WriteFile(src, tmp_dir->path / filename);

    // cppcheck-suppress unreadVariable
    const LcOptionTargetStrings lots(target);

    auto env = std::string("");
    if(IsHccCompiler())
    {
        params += " -amdgpu-target=" + target.Name();
        params += " " + GetCoV3Option(ProduceCoV3());
    }
    else if(IsHipClangCompiler())
    {
        if(params.find("-std=") == std::string::npos)
            params += " --std=c++11";

        if(HipCompilerVersion() < external_tool_version_t{4, 1, 0})
            params += " --cuda-gpu-arch=" + lots.device;
        else
            params += " --cuda-gpu-arch=" + lots.device + lots.xnack;

        params += " --cuda-device-only";
        params += " -c";
        params += " -O3 ";
    }

    params += " -Wno-unused-command-line-argument -I. ";
    params += MIOPEN_STRINGIZE(HIP_COMPILER_FLAGS);
    if(IsHccCompiler())
    {
        env += std::string("KMOPTLLC=\"-mattr=+enable-ds128 ");
        if(HipCompilerVersion() >= external_tool_version_t{2, 8, 0})
            env += " --amdgpu-spill-vgpr-to-agpr=0";
        env += '\"';
    }
    else if(IsHipClangCompiler())
    {
        params += " -mllvm --amdgpu-spill-vgpr-to-agpr=0";
    }

#if MIOPEN_BUILD_DEV
    if(miopen::IsEnabled(MIOPEN_DEBUG_HIP_VERBOSE{}))
    {
        params += " -v";
    }

    if(miopen::IsEnabled(MIOPEN_DEBUG_HIP_DUMP{}))
    {
        if(IsHccCompiler())
        {
            params += " -gline-tables-only";
            env += " KMDUMPISA=1";
            env += " KMDUMPLLVM=1";
        }
        else if(IsHipClangCompiler())
        {
            params += " -gline-tables-only";
            params += " -save-temps";
        }
    }
#endif

    // hip version
    params +=
        std::string(" -DHIP_PACKAGE_VERSION_FLAT=") + std::to_string(HIP_PACKAGE_VERSION_FLAT);

    params += " ";
    auto bin_file = tmp_dir->path / (filename + ".o");

    // compile
    const std::string redirector = testing_mode ? " 1>/dev/null 2>&1" : "";
    tmp_dir->Execute(env + std::string(" ") + MIOPEN_HIP_COMPILER,
                     params + filename + " -o " + bin_file.string() + redirector);
    if(!boost::filesystem::exists(bin_file))
        MIOPEN_THROW(filename + " failed to compile");
#ifdef EXTRACTKERNEL_BIN
    if(IsHccCompiler())
    {
        // call extract kernel
        tmp_dir->Execute(EXTRACTKERNEL_BIN, " -i " + bin_file.string());
        auto hsaco =
            std::find_if(boost::filesystem::directory_iterator{tmp_dir->path},
                         {},
                         [](auto entry) { return (entry.path().extension() == ".hsaco"); });

        if(hsaco == boost::filesystem::directory_iterator{})
        {
            MIOPEN_LOG_E("failed to find *.hsaco in " << hsaco->path().string());
        }

        return hsaco->path();
    }
#endif
#if defined(MIOPEN_OFFLOADBUNDLER_BIN) && !MIOPEN_BACKEND_HIP
    // Unbundling is not required for HIP runtime && hip-clang
    if(IsHipClangCompiler())
    {
        tmp_dir->Execute(MIOPEN_OFFLOADBUNDLER_BIN,
                         "--type=o --targets=hip-amdgcn-amd-amdhsa-" +
                             (HipCompilerVersion() < external_tool_version_t{4, 1, 0}
                                  ? lots.device
                                  : (std::string{'-'} + lots.device + lots.xnack)) +
                             " --inputs=" + bin_file.string() + " --outputs=" + bin_file.string() +
                             ".hsaco --unbundle");

        auto hsaco =
            std::find_if(boost::filesystem::directory_iterator{tmp_dir->path},
                         {},
                         [](auto entry) { return (entry.path().extension() == ".hsaco"); });

        if(hsaco == boost::filesystem::directory_iterator{})
        {
            MIOPEN_LOG_E("failed to find *.hsaco in " << hsaco->path().string());
        }
        return hsaco->path();
    }
    else
#endif
    {
        return bin_file;
    }
#else
    (void)filename;
    (void)params;
    MIOPEN_THROW("HIP kernels are only supported in Linux");
#endif
}

static bool
HipBuildTest(const std::string& program_name, std::string params, const TargetProperties& target)
{
    boost::optional<miopen::TmpDir> dir(program_name);
    std::string source = miopen::GetKernelSrc(program_name);
    try
    {
        std::ignore = HipBuildImpl(dir, program_name, source, params, target, true);
    }
    catch(...)
    {
        return false;
    }
    return true;
}

static bool DetectIfBufferAtomicFaddReturnsFloatImpl(const TargetProperties& target)
{
    const std::string program_name("detect_llvm_amdgcn_buffer_atomic_fadd_f32_float.cpp");
    std::string params;

    if(HipBuildTest(program_name, params, target))
    {
        MIOPEN_LOG_NQI("Yes");
        return true;
    }
    MIOPEN_LOG_NQI("No");
    return false;
}

static bool DetectIfBufferAtomicFaddReturnsFloat(const TargetProperties& target)
{
    static const bool once = DetectIfBufferAtomicFaddReturnsFloatImpl(target);
    return once;
}

boost::filesystem::path HipBuild(boost::optional<TmpDir>& tmp_dir,
                                 const std::string& filename,
                                 std::string src,
                                 std::string params,
                                 const TargetProperties& target)
{
    if(target.Name() == "gfx908")
        if(DetectIfBufferAtomicFaddReturnsFloat(target))
            params += " -DCK_AMD_BUFFER_ATOMIC_FADD_RETURNS_FLOAT=1";
    return HipBuildImpl(tmp_dir, filename, src, params, target, false);
}

void bin_file_to_str(const boost::filesystem::path& file, std::string& buf)
{
    std::ifstream bin_file_ptr(file.string().c_str(), std::ios::binary);
    std::ostringstream bin_file_strm;
    bin_file_strm << bin_file_ptr.rdbuf();
    buf = bin_file_strm.str();
}

static external_tool_version_t HipCompilerVersionImpl()
{
    external_tool_version_t version;
    if(IsHccCompiler())
    {
        const std::string path(MIOPEN_HIP_COMPILER);
        const std::string mandatory_prefix("(based on HCC ");
        do
        {
            if(path.empty() || !std::ifstream(path).good())
                break;

            std::stringstream out;
            MIOPEN_LOG_NQI2("Running: " << '\'' << path << " --version" << '\'');
            if(miopen::exec::Run(path + " --version", nullptr, &out) != 0)
                break;

            std::string line;
            while(!out.eof())
            {
                std::getline(out, line);
                MIOPEN_LOG_NQI2(line);
                auto begin = line.find(mandatory_prefix);
                if(begin == std::string::npos)
                    continue;

                begin += mandatory_prefix.size();
                int v3, v2, v1 = v2 = v3 = -1;
                char c2, c1 = c2 = 'X';
                std::istringstream iss(line.substr(begin));
                iss >> v1 >> c1 >> v2 >> c2 >> v3;
                if(!iss.fail() && v1 >= 0)
                {
                    version.major = v1;
                    if(c1 == '.' && v2 >= 0)
                    {
                        version.minor = v2;
                        if(c2 == '.' && v3 >= 0)
                            version.patch = v3;
                    }
                }
                break;
            }
        } while(false);
    }
    else
    {
#ifdef HIP_PACKAGE_VERSION_MAJOR
        MIOPEN_LOG_NQI2("Read version information from HIP package...");
        version.major = HIP_PACKAGE_VERSION_MAJOR;
#ifdef HIP_PACKAGE_VERSION_MINOR
        version.minor = HIP_PACKAGE_VERSION_MINOR;
#else
        version.minor = 0;
#endif
#ifdef HIP_PACKAGE_VERSION_PATCH
        version.patch = HIP_PACKAGE_VERSION_PATCH;
#else
        version.patch = 0;
#endif
#else // HIP_PACKAGE_VERSION_MAJOR is not defined. CMake failed to find HIP package.
        MIOPEN_LOG_NQI2("...assuming 3.2.0 (hip-clang RC)");
        version.major = 3;
        version.minor = 2;
        version.patch = 0;
#endif
    }
    MIOPEN_LOG_NQI(version.major << '.' << version.minor << '.' << version.patch);
    return version;
}

external_tool_version_t HipCompilerVersion()
{
    static auto once = HipCompilerVersionImpl();
    return once;
}

bool operator>(const external_tool_version_t& lhs, const external_tool_version_t& rhs)
{
    if(lhs.major > rhs.major)
        return true;
    else if(lhs.major == rhs.major)
    {
        if(lhs.minor > rhs.minor)
            return true;
        else if(lhs.minor == rhs.minor)
            return (lhs.patch > rhs.patch);
        else
            return false;
    }
    else
        return false;
}

bool operator<(const external_tool_version_t& lhs, const external_tool_version_t& rhs)
{
    return rhs > lhs;
}
bool operator>=(const external_tool_version_t& lhs, const external_tool_version_t& rhs)
{
    return !(lhs < rhs);
}

bool operator<=(const external_tool_version_t& lhs, const external_tool_version_t& rhs)
{
    return !(lhs > rhs);
}

} // namespace miopen


text:
#include <stdlib.h>
#include <math.h>
#include <stdio.h>

#include <NTL/config.h>

#ifndef NTL_GMP_LIP

int main()
{
   fprintf(stderr, "NTL_GMP_LIP flag not set\n");

   return 0;
}

#else

#include <gmp.h>
#include <NTL/mach_desc.h>

void print2k(FILE *f, long k, long bpl)
{
   long m, l;
   long first;

   if (k <= 0) {
      fprintf(f, "((double) 1.0)");
      return;
   }

   m = bpl - 2;
   first = 1;

   fprintf(f, "(");

   while (k > 0) {
      if (k > m)
         l = m;
      else
         l = k;

      k = k - l;

      if (first)
         first = 0;
      else
         fprintf(f, "*");

      fprintf(f, "((double)(1L<<%ld))", l);
   }

   fprintf(f, ")");
}

void Error(const char *s)
{
   fprintf(stderr, "%s\n", s);
   abort();
}

int main()
{
   long bpl;
   long ntl_zz_nbits, ntl_wsp_nbits, ntl_sp_nbits;

   fprintf(stderr, "NTL_GMP_LIP flag set\n");

   bpl = NTL_BITS_PER_LONG;

   /*
    * We require that the number of bits per limb quantity correspond to the
    * number of bits of a long, or possibly a "long long" that is twice as wide
    * as a long.  These restrictions will almost certainly be satisfied, unless
    * GMP is installed using the newly proposed "nail" option.
    */

   ntl_zz_nbits = 0;

   if (sizeof(mp_limb_t) == sizeof(long) && mp_bits_per_limb == bpl)
      ntl_zz_nbits = bpl;
   else if (sizeof(mp_limb_t) == 2*sizeof(long) && mp_bits_per_limb == 2*bpl)
      ntl_zz_nbits = 2*bpl;
   else
      Error("sorry...this is a funny gmp");

   if (sizeof(mp_size_t) != sizeof(long) &&
       sizeof(mp_size_t) != sizeof(int))

   Error("sorry...this is a funny gmp");

   ntl_wsp_nbits = bpl - 2;

   ntl_sp_nbits = NTL_NBITS_MAX;

   if (sizeof(mp_size_t) < sizeof(long)) {
      printf("#define NTL_SMALL_MP_SIZE_T\n");
      fprintf(stderr, "setting NTL_SMALL_MP_SIZE_T\n");
   }

   fprintf(stderr, "NTL_ZZ_NBITS = %ld\n", ntl_zz_nbits);
   fprintf(stderr, "NTL_WSP_NBITS = %ld\n", ntl_wsp_nbits);
   fprintf(stderr, "NTL_SP_NBITS = %ld\n", ntl_sp_nbits);

   printf("#define NTL_ZZ_NBITS (%ld)\n",  ntl_zz_nbits);

   printf("#define NTL_ZZ_FRADIX ");
   print2k(stdout, ntl_zz_nbits, bpl);
   printf("\n");

   return 0;
}

#endif

max_stars_repo_name: vshesh/RUNEtag

max_issues_repo_name: vshesh/RUNEtag

max_forks_repo_name: vshesh/RUNEtag


text:
#ifndef NETWORKS_HPP
#define NETWORKS_HPP

#include <utility>
// For External Library
#include <torch/torch.h>
#include <boost/program_options.hpp>

// Define Namespace
namespace nn = torch::nn;
namespace po = boost::program_options;

// Function Prototype
void weights_init(nn::Module &m);
void DownSampling(nn::Sequential &sq, const size_t in_nc, const size_t out_nc, const bool BN, const bool ReLU, const bool bias=false);
void UpSampling(nn::Sequential &sq, const size_t in_nc, const size_t out_nc, const bool BN, const bool ReLU, const bool bias=false);

// -------------------------------------------------
// struct{UNet_GeneratorImpl}(nn::Module)
// -------------------------------------------------
struct UNet_GeneratorImpl : nn::Module{
private:
    nn::Sequential model;
public:
    UNet_GeneratorImpl(){}
    UNet_GeneratorImpl(po::variables_map &vm);
    torch::Tensor forward(torch::Tensor x);
};

// -------------------------------------------------
// struct{UNetBlockImpl}(nn::Module)
// -------------------------------------------------
struct UNetBlockImpl : nn::Module{
private:
    bool outermost;
    nn::Sequential model;
public:
    UNetBlockImpl(){}
    UNetBlockImpl(const std::pair<size_t, size_t> outside_nc, const size_t inside_nc, UNetBlockImpl &submodule, bool outermost_=false, bool innermost=false, bool use_dropout=false);
    torch::Tensor forward(torch::Tensor x);
};

// ----------------------------------------------------------
// struct{GAN_DiscriminatorImpl}(nn::Module)
// ----------------------------------------------------------
struct GAN_DiscriminatorImpl : nn::Module{
private:
    nn::Sequential down, features, classifier;
public:
    GAN_DiscriminatorImpl(){}
    GAN_DiscriminatorImpl(po::variables_map &vm);
    std::pair<torch::Tensor, torch::Tensor> forward(torch::Tensor x);
};

TORCH_MODULE(UNet_Generator);
TORCH_MODULE(UNetBlock);
TORCH_MODULE(GAN_Discriminator);

#endif


text:
#ifndef _jsc_bioinfo_bartxt_hpp_included_
#define _jsc_bioinfo_bartxt_hpp_included_

#include <boost/config.hpp>

#include <math.h>

#include <iostream>
#include <map>
#include <set>
#include <sstream>
#include <vector>

#include <boost/lambda/bind.hpp>
#include <boost/lambda/lambda.hpp>
#include <boost/shared_ptr.hpp>

#include "jsc/util/interval_list.hpp"

using namespace std;
using namespace boost;
using namespace boost::lambda;

using namespace jsc::util;

namespace jsc
{

namespace bioinfo
{

//! Defines the format of a bar entry, without strand information.
class bar_entry
{
public:
	long pos;
	double sig;
};

//! A shared_ptr to bar_entry.
typedef shared_ptr<bar_entry> bar_ptr;
//! A vector of jsc::bioinfo::bar_ptr.
typedef vector<bar_ptr> vec_barp;
//! A map of (chrName, vector of bar_entries).
typedef map<string, vec_barp> map_chr_barps;

//! Loads map_chr_barps from an istream (w/o the header).
map_chr_barps load_barps(istream & is)
{
	string line;
	/* read content */
	map_chr_barps chr_barps_map;
	string chrName = "";
	string prefix = "# Name";
	while (getline(is, line) && !is.eof())
	{
		if (line.length() == 0)
		{
			continue;
		}
		else if (line.compare(0, prefix.size(), prefix) == 0)
		{
			// load chrName
			istringstream iss(line);
			string s1, s2; //``#" and ``Name"
			iss >> s1
				>> s2
				>> chrName;
		}
		else if (line[0] == '#')
		{
			continue;
		}
		else
		{
			// load bar_entry
			bar_ptr barp(new bar_entry());
			istringstream iss(line);
			iss >> barp->pos
				>> barp->sig;
			chr_barps_map[chrName].push_back(barp);
		}
	}

	// sort all the vectors in the map
	map_chr_barps::iterator cbm_itr;
	for (cbm_itr = chr_barps_map.begin(); cbm_itr != chr_barps_map.end(); ++cbm_itr)
	{
		sort((*cbm_itr).second.begin(), (*cbm_itr).second.end(),
				bind(&bar_entry::pos, *_1) < bind(&bar_entry::pos, *_2));
	}
	return chr_barps_map;
}

} /* end of bioinfo */

} /* end of jsc */

#endif

max_stars_repo_name: gersteinlab/LESSeq

max_issues_repo_name: gersteinlab/LESSeq

max_forks_repo_name: gersteinlab/LESSeq


text:
#ifndef __FOLDING_CONTROL_ALGORITHM__
#define __FOLDING_CONTROL_ALGORITHM__

#include <ros/ros.h>
#include <Eigen/Dense>
#include <math.h>
#include <pr2_algorithms/algorithm_base.hpp>
#include <limits>
#include <stdexcept>

namespace manipulation_algorithms{

  /**
    Class that implements the (master-slave) folding assembly control algorithm.
  **/
  class FoldingAssemblyController : public AlgorithmBase
  {
  public:
    FoldingAssemblyController();
    ~FoldingAssemblyController();

    void control(const Eigen::Vector3d &p_d, const double theta_d, const double f_d, const Eigen::Vector3d &surface_tangent, const Eigen::Vector3d &surface_normal, const Eigen::Vector3d &r, const Eigen::Vector3d &p_1, const Eigen::Vector3d &f_c, Eigen::Vector3d &v_out, Eigen::Vector3d &w_out, const double d_t);
    virtual bool getParams(const ros::NodeHandle &n);
  protected:
    double k_v_, k_omega_, k_force_;
  };
}
#endif