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
//

#include <boost/beast/http/basic_parser.hpp>

namespace boost {
namespace beast {
namespace http {

//[code_http_10_custom_parser

template<bool isRequest>
class custom_parser : public basic_parser<isRequest>
{
private:
    /** Called after receiving the request-line.

        This virtual function is invoked after receiving a request-line
        when parsing HTTP requests.
        It can only be called when `isRequest == true`.

        @param method The verb enumeration. If the method string is not
        one of the predefined strings, this value will be @ref verb::unknown.

        @param method_str The unmodified string representing the verb.

        @param target The request-target.

        @param version The HTTP-version. This will be 10 for HTTP/1.0,
        and 11 for HTTP/1.1.

        @param ec An output parameter which the function may set to indicate
        an error. The error will be clear before this function is invoked.
    */
    void
    on_request_impl(
        verb method,                // The method verb, verb::unknown if no match
        string_view method_str,     // The method as a string
        string_view target,         // The request-target
        int version,                // The HTTP-version
        error_code& ec) override;   // The error returned to the caller, if any

    /** Called after receiving the status-line.

        This virtual function is invoked after receiving a status-line
        when parsing HTTP responses.
        It can only be called when `isRequest == false`.

        @param code The numeric status code.

        @param reason The reason-phrase. Note that this value is
        now obsolete, and only provided for historical or diagnostic
        purposes.

        @param version The HTTP-version. This will be 10 for HTTP/1.0,
        and 11 for HTTP/1.1.

        @param ec An output parameter which the function may set to indicate
        an error. The error will be clear before this function is invoked.
    */
    void
    on_response_impl(
        int code,                   // The status-code
        string_view reason,         // The obsolete reason-phrase
        int version,                // The HTTP-version
        error_code& ec) override;   // The error returned to the caller, if any

    /** Called once for each complete field in the HTTP header.

        This virtual function is invoked for each field that is received
        while parsing an HTTP message.

        @param name The known field enum value. If the name of the field
        is not recognized, this value will be @ref field::unknown.

        @param name_string The exact name of the field as received from
        the input, represented as a string.

        @param value A string holding the value of the field.

        @param ec An output parameter which the function may set to indicate
        an error. The error will be clear before this function is invoked.
    */
    void
    on_field_impl(
        field f,                    // The known-field enumeration constant
        string_view name,           // The field name string.
        string_view value,          // The field value
        error_code& ec) override;   // The error returned to the caller, if any

    /** Called once after the complete HTTP header is received.

        This virtual function is invoked once, after the complete HTTP
        header is received while parsing a message.

        @param ec An output parameter which the function may set to indicate
        an error. The error will be clear before this function is invoked.
    */
    void
    on_header_impl(
        error_code& ec) override;   // The error returned to the caller, if any

    /** Called once before the body is processed.

        This virtual function is invoked once, before the content body is
        processed (but after the complete header is received).

        @param content_length A value representing the content length in
        bytes if the length is known (this can include a zero length).
        Otherwise, the value will be `boost::none`.

        @param ec An output parameter which the function may set to indicate
        an error. The error will be clear before this function is invoked.
    */
    void
    on_body_init_impl(
        boost::optional<
            std::uint64_t> const&
                content_length,     // Content length if known, else `boost::none`
        error_code& ec) override;   // The error returned to the caller, if any

    /** Called each time additional data is received representing the content body.

        This virtual function is invoked for each piece of the body which is
        received while parsing of a message. This function is only used when
        no chunked transfer encoding is present.

        @param body A string holding the additional body contents. This may
        contain nulls or unprintable characters.

        @param ec An output parameter which the function may set to indicate
        an error. The error will be clear before this function is invoked.

        @see on_chunk_body_impl
    */
    std::size_t
    on_body_impl(
        string_view s,              // A portion of the body
        error_code& ec) override;   // The error returned to the caller, if any

    /** Called each time a new chunk header of a chunk encoded body is received.

        This function is invoked each time a new chunk header is received.
        The function is only used when the chunked transfer encoding is present.

        @param size The size of this chunk, in bytes.

        @param extensions A string containing the entire chunk extensions.
        This may be empty, indicating no extensions are present.

        @param ec An output parameter which the function may set to indicate
        an error. The error will be clear before this function is invoked.
    */
    void
    on_chunk_header_impl(
        std::uint64_t size,         // The size of the upcoming chunk,
                                    // or zero for the last chunk
        string_view extension,      // The chunk extensions (may be empty)
        error_code& ec) override;   // The error returned to the caller, if any

    /** Called each time additional data is received representing part of a body chunk.

        This virtual function is invoked for each piece of the body which is
        received while parsing of a message. This function is only used when
        no chunked transfer encoding is present.

        @param remain The number of bytes remaining in this chunk. This includes
        the contents of passed `body`. If this value is zero, then this represents
        the final chunk.

        @param body A string holding the additional body contents. This may
        contain nulls or unprintable characters.

        @param ec An output parameter which the function may set to indicate
        an error. The error will be clear before this function is invoked.

        @return This function should return the number of bytes actually consumed
        from the `body` value. Any bytes that are not consumed on this call
        will be presented in a subsequent call.

        @see on_body_impl
    */
    std::size_t
    on_chunk_body_impl(
        std::uint64_t remain,       // The number of bytes remaining in the chunk,
                                    // including what is being passed here.
                                    // or zero for the last chunk
        string_view body,           // The next piece of the chunk body
        error_code& ec) override;   // The error returned to the caller, if any

    /** Called once when the complete message is received.

        This virtual function is invoked once, after successfully parsing
        a complete HTTP message.

        @param ec An output parameter which the function may set to indicate
        an error. The error will be clear before this function is invoked.
    */
    void
    on_finish_impl(
        error_code& ec) override;   // The error returned to the caller, if any

public:
    custom_parser() = default;
};

//]

// Definitions are not part of the docs but necessary to link

template<bool isRequest>
void custom_parser<isRequest>::
on_request_impl(verb method, string_view method_str,
    string_view path, int version, error_code& ec)
{
    boost::ignore_unused(method, method_str, path, version);
    ec = {};
}

template<bool isRequest>
void custom_parser<isRequest>::
on_response_impl(
    int status,
    string_view reason,
    int version,
    error_code& ec)
{
    boost::ignore_unused(status, reason, version);
    ec = {};
}

template<bool isRequest>
void custom_parser<isRequest>::
on_field_impl(
    field f,
    string_view name,
    string_view value,
    error_code& ec)
{
    boost::ignore_unused(f, name, value);
    ec = {};
}

template<bool isRequest>
void custom_parser<isRequest>::
on_header_impl(error_code& ec)
{
    ec = {};
}

template<bool isRequest>
void custom_parser<isRequest>::
on_body_init_impl(
    boost::optional<std::uint64_t> const& content_length,
    error_code& ec)
{
    boost::ignore_unused(content_length);
    ec = {};
}

template<bool isRequest>
std::size_t custom_parser<isRequest>::
on_body_impl(string_view body, error_code& ec)
{
    boost::ignore_unused(body);
    ec = {};
    return body.size();
}

template<bool isRequest>
void custom_parser<isRequest>::
on_chunk_header_impl(
    std::uint64_t size,
    string_view extension,
    error_code& ec)
{
    boost::ignore_unused(size, extension);
    ec = {};
}

template<bool isRequest>
std::size_t custom_parser<isRequest>::
on_chunk_body_impl(
    std::uint64_t remain,
    string_view body,
    error_code& ec)
{
    boost::ignore_unused(remain);
    ec = {};
    return body.size();
}

template<bool isRequest>
void custom_parser<isRequest>::
on_finish_impl(error_code& ec)
{
    ec = {};
}

template class custom_parser<true>;
template class custom_parser<false>;

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


text:
/**
 * Copyright Soramitsu Co., Ltd. All Rights Reserved.
 * SPDX-License-Identifier: Apache-2.0
 */

#include <gtest/gtest.h>

#include <boost/algorithm/string/join.hpp>
#include "common/blob.hpp"
#include "common/buffer.hpp"
#include "crypto/bip39/impl/bip39_provider_impl.hpp"
#include "crypto/bip39/mnemonic.hpp"
#include "crypto/pbkdf2/impl/pbkdf2_provider_impl.hpp"
#include "testutil/outcome.hpp"

using namespace kagome;
using namespace crypto;
using namespace bip39;

struct Bip39EntropyTest : public ::testing::Test {
  void SetUp() override {
    auto pbkdf2_provider = std::make_shared<Pbkdf2ProviderImpl>();
    bip39_provider = std::make_shared<Bip39ProviderImpl>(pbkdf2_provider);
    phrase =
        "legal winner thank year wave sausage worth useful legal winner "
        "thank yellow";
    entropy_hex = "7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f";
    seed_hex =
        "4313249608fe8ac10fd5886c92c4579007272cb77c21551ee5b8d60b780416850"
        "f1e26c1f4b8d88ece681cb058ab66d6182bc2ce5a03181f7b74c27576b5c8bf";
  }

  std::string_view phrase;
  std::string_view entropy_hex;
  std::string_view seed_hex;

  std::shared_ptr<Bip39Provider> bip39_provider;
};

/**
 * @given valid mnemonic, entropy and seed values
 * @when entropy is calculated by mnemonic
 * @and seed is calculated by entropy
 * @then entropy and seed come up with predefined values
 */
TEST_F(Bip39EntropyTest, DecodeSuccess) {
  EXPECT_OUTCOME_TRUE(mnemonic, Mnemonic::parse(phrase));
  auto joined_words = boost::algorithm::join(mnemonic.words, " ");
  ASSERT_EQ(joined_words, phrase);

  EXPECT_OUTCOME_TRUE(entropy,
                      bip39_provider->calculateEntropy(mnemonic.words));
  ASSERT_EQ(common::Buffer(entropy).toHex(), entropy_hex);

  EXPECT_OUTCOME_TRUE(seed, bip39_provider->makeSeed(entropy, "Substrate"));
  ASSERT_EQ(seed.toHex(), seed_hex);
}

ext: cpp

max_stars_repo_name: FlorianFranzen/kagome

max_issues_repo_name: FlorianFranzen/kagome

max_forks_repo_name: FlorianFranzen/kagome


text:
#define BOOST_TEST_MODULE "C++ Unit Tests for Scylla BLAS"
#include <boost/test/included/unit_test.hpp>

ext: cc

max_stars_repo_name: scylla-zpp-blas/linear-algebra

max_issues_repo_name: scylla-zpp-blas/linear-algebra

max_forks_repo_name: scylla-zpp-blas/linear-algebra


text:
//
//  string.hpp
//
//  Created by Anton Leuski on 7/22/14.
//  Copyright (c) 2015 Anton Leuski & ICT/USC. All rights reserved.
//
//  This file is part of Jerome.
//
//  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.
//

#ifndef __jerome_type_string_hpp__
#define __jerome_type_string_hpp__

#include <string>
#include <jerome/type/optional.hpp>

#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdocumentation"
#include <boost/algorithm/string.hpp>
#pragma clang diagnostic pop

#if defined(__ANDROID__)
// Android NDK doesn't support these C++ functions. Thus we just
// implement them here to avoid compiling errors.
#include <sstream>
#include <cstdlib>
namespace std
{
	template <typename T>
	inline std::string to_string(T value)
	{
		std::ostringstream os ;
		os << value ;
		return os.str() ;
	}
	int			stoi(const string& str, size_t* idx = 0, int base = 10) { return atoi(str.c_str()); }
	long		stol(const string& str, size_t* idx = 0, int base = 10) { return atol(str.c_str()); }
	float		stof(const string& str, size_t* idx = 0) { return atof(str.c_str()); }
	double	stod(const string& str, size_t* idx = 0) { return atof(str.c_str()); }
}
#endif

namespace jerome {

  typedef std::string		String;
  typedef boost::optional<String>	OptionalString;

  inline String trim(const String &s)
  {
    auto wsfront=std::find_if_not(s.begin(),s.end(),[](int c){return std::isspace(c);});
    auto wsback=std::find_if_not(s.rbegin(),s.rend(),[](int c){return std::isspace(c);}).base();
    return (wsback<=wsfront ? std::string() : std::string(wsfront,wsback));
  }

  bool 	hasSuffix(const String& inS, const String& inSuffix);
  String 	dropSuffix(const String& inS, const String& inSuffix);
  void 	replaceAll(String& ioString, const String& inOld, const String& inNew);

  template<typename ... Args>
  String string_format(const String& format, Args ... args)
  {
    size_t size = snprintf(nullptr, 0, format.c_str(), args ...) + 1; // Extra space for '\0'
    std::unique_ptr<char[]> buf(new char[size]);
    snprintf(buf.get(), size, format.c_str(), args ...);
    return String(buf.get(), buf.get() + size - 1); // We don't want the '\0' inside
  }

  inline String to_lower(const String& inString)
  {
    return boost::algorithm::to_lower_copy(inString);
  }

  inline bool stob(const String& inString)
  {
    if (to_lower(inString) == "true") { return true; }
    if (to_lower(inString) == "false") { return false; }
    try {
      return stoi(inString) != 0;
    } catch (std::exception&) {
      return false;
    }
  }
}

#endif // defined __jerome_type_string_hpp__

ext: hpp

max_stars_repo_name: leuski-ict/jerome

max_issues_repo_name: leuski-ict/jerome

max_forks_repo_name: leuski-ict/jerome


text: #include <boost/mpl/aux_/preprocessed/msvc70/greater_equal.hpp>

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


text:
#include "kmeans.h"

#include <boost/test/unit_test.hpp>

using namespace memb;

BOOST_AUTO_TEST_SUITE(kMeans)

BOOST_AUTO_TEST_CASE(kMeansWork)
{
    std::vector<float> data;
    std::vector<uint8_t> expectedClusterIds;

    const size_t MIDDLE_CLUSTER_SIZE = 8;
    const size_t FIRST_CLUSTER_SIZE = 16;
    const size_t LAST_CLUSTER_SIZE = 4;

    for (size_t i = 0; i < MIDDLE_CLUSTER_SIZE; ++i) {
        data.push_back(-0.5 + i * 0.125);
        expectedClusterIds.push_back(1);
    }

    for (size_t i = 0; i < FIRST_CLUSTER_SIZE; ++i) {
        data.push_back(-9 + i * 0.125);
        expectedClusterIds.push_back(0);
    }

    for (size_t i = 0; i < LAST_CLUSTER_SIZE; ++i) {
        data.push_back(11.75 + i * 0.125);
        expectedClusterIds.push_back(2);
    }

    KMeansClusterizer clusterizer(3);
    clusterizer.fit(data);

    auto clusterIds = clusterizer.predict(data);
    BOOST_REQUIRE(clusterIds == expectedClusterIds);
}

BOOST_AUTO_TEST_SUITE_END()

max_stars_repo_name: thousandvoices/memb

max_issues_repo_name: thousandvoices/memb

max_forks_repo_name: thousandvoices/memb


text:
// -*- coding: utf-8 -*-
// Copyright (C) 2006-2009 Rosen Diankov (rdiankov@cs.cmu.edu)
//
// This file is part of OpenRAVE.
// OpenRAVE is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.

#ifdef _WIN32
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#endif

#include "libopenrave-core/openrave-core.h"
#include <set>

using namespace OpenRAVE;
using namespace std;

#include <stdio.h>
#include <boost/shared_ptr.hpp>
#include <boost/thread/thread.hpp>
#include <boost/array.hpp>
#include <boost/bind.hpp>
#include <boost/algorithm/string.hpp>

#include <signal.h>
void sigint_handler(int sig);
void MainOpenRAVEThread();

#ifdef _WIN32
#define usleep(micro) Sleep((micro)/1000)
#else
#define _strnicmp strncasecmp
#define _stricmp strcasecmp
#include <sys/time.h>
#endif

#define FORIT(it, v) for(it = (v).begin(); it != (v).end(); (it)++)

static bool bDisplayGUI = true, bShowGUI = true;

static EnvironmentBasePtr s_penv;
//static boost::shared_ptr<boost::thread> s_mainThread;
static string s_sceneFile;
static string s_saveScene; // if not NULL, saves the scene and exits
static boost::shared_ptr<string> s_viewerName;

static list< pair<string, string> > s_listModules; // modules to initially create
static vector<string> vResourceFiles; // xml files to open
static int s_WindowWidth = 1024, s_WindowHeight = 768;
static int s_WindowPosX, s_WindowPosY;
static bool s_bSetWindowPosition = false;
int g_argc;
char** g_argv;
static bool s_bThreadDestroyed = false;
static const char* s_geometryextentsions[] = { "iv","vrml","wrl","stl","blend","3ds","ase","obj","ply","dxf","lwo","lxo","ac","ms3d","x","mesh.xml","irrmesh","irr","nff","off","raw"};
#ifndef _WIN32
#include <sys/stat.h>
#include <sys/types.h>
#endif

int main(int argc, char ** argv)
{
    g_argc = argc;
    g_argv = argv;

    int nServPort = 4765;

    DebugLevel debuglevel = Level_Info;
    list<string> listLoadPlugins;
    string collisionchecker, physicsengine, servername="textserver";
    bool bListPlugins = false;

    std::set<std::string> geometryextensions;
    for(size_t iext = 0; iext < sizeof(s_geometryextentsions)/sizeof(s_geometryextentsions[0]); ++iext) {
        geometryextensions.insert(s_geometryextentsions[iext]);
    }

    // parse command line arguments
    int i = 1;
    while(i < argc) {
        if((_stricmp(argv[i], "-h") == 0)||(_stricmp(argv[i], "-?") == 0)||(_stricmp(argv[i], "/?") == 0)||(_stricmp(argv[i], "--help") == 0)||(_stricmp(argv[i], "-help") == 0)) {
            RAVELOG_INFO("OpenRAVE Usage\n"
                         "--nogui             Run without a GUI (does not initialize the graphics engine nor communicate with any window manager)\n"
                         "--hidegui           Run with a hidden GUI, this allows 3D rendering and images to be captured\n"
                         "--listplugins       List all plugins and the interfaces they provide\n"
                         "--loadplugin [path] load a plugin at the following path\n"
                         "--serverport [port] start up the server on a specific port (default is 4765)\n"
                         "--collision [name]  Default collision checker to use\n"
                         "--viewer [name]     Default viewer to use\n"
                         "--server [name]     Default server to use\n"
                         "--physics [name]    Default physics engine to use\n"
                         "-d [debug-level]   start up OpenRAVE with the specified debug level (higher numbers print more).\n"
                         "                   Default level is 2 for release builds, and 4 for debug builds.\n"
                         "-wdims [width] [height] start up the GUI window with these dimensions\n"
                         "-wpos x y set the position of the GUI window\n"
                         "--module [modulename] [args] Start openrave with a module. If args involves spaces, surround it with double quotes. args is optional.\n"
                         "--version          Output the current openrave version\n\n"
                         "-f [scene]         Load a openrave environment file\n\n");
            return 0;
        }
        else if((_stricmp(argv[i], "--loadplugin") == 0)||(_stricmp(argv[i], "-loadplugin") == 0)) {
            listLoadPlugins.push_back(argv[i+1]);
            i += 2;
        }
        else if((_stricmp(argv[i], "--listplugins") == 0)||(_stricmp(argv[i], "-listplugins") == 0)) {
            bListPlugins = true;
            i++;
        }
        else if( _stricmp(argv[i], "--version") == 0 ) {
            printf("%s\n",OPENRAVE_VERSION_STRING);
            return 0;
        }
        else if( _stricmp(argv[i], "-f") == 0 ) {
            s_sceneFile = argv[i+1];
            i += 2;
        }
        else if( _stricmp(argv[i], "-save") == 0 ) {
            s_saveScene = argv[i+1];
            i += 2;
        }
        else if((_stricmp(argv[i], "--collision") == 0)||(_stricmp(argv[i], "-collision") == 0)) {
            collisionchecker = argv[i+1];
            i += 2;
        }
        else if((_stricmp(argv[i], "--viewer") == 0)||(_stricmp(argv[i], "-viewer") == 0)) {
            s_viewerName.reset(new string(argv[i+1]));
            i += 2;
        }
        else if((_stricmp(argv[i], "--physics") == 0)||(_stricmp(argv[i], "-physics") == 0)) {
            physicsengine = argv[i+1];
            i += 2;
        }
        else if((_stricmp(argv[i],"--server") == 0)||(_stricmp(argv[i],"-server") == 0)) {
            servername = argv[i+1];
            i += 2;
        }
        else if((_stricmp(argv[i], "--module") == 0)||(_stricmp(argv[i], "-problem") == 0)) {
            s_listModules.push_back(pair<string, string>(argv[i+1], ""));
            i += 2;

            if((i < argc)&&(argv[i][0] != '-')) {
                // set the args
                s_listModules.back().second = argv[i];
                i++;
            }
        }
        else if((_stricmp(argv[i], "--nogui") == 0)||(_stricmp(argv[i], "-nogui") == 0)) {
            bDisplayGUI = false;
            i++;
        }
        else if((_stricmp(argv[i], "--hidegui") == 0)||(_stricmp(argv[i], "-hidegui") == 0)) {
            bShowGUI = false;
            i++;
        }
        else if( _stricmp(argv[i], "-d") == 0 ) {
            debuglevel = (DebugLevel)atoi(argv[i+1]);
            i += 2;
        }
        else if( _stricmp(argv[i], "-wdims") == 0 ) {
            s_WindowWidth = atoi(argv[i+1]);
            s_WindowHeight = atoi(argv[i+2]);
            i += 3;
        }
        else if( _stricmp(argv[i], "-wpos") == 0 ) {
            s_WindowPosX = atoi(argv[i+1]);
            s_WindowPosY = atoi(argv[i+2]);
            s_bSetWindowPosition = true;
            i += 3;
        }
        else if((_stricmp(argv[i], "--serverport") == 0)||(_stricmp(argv[i], "-serverport") == 0)) {
            nServPort = atoi(argv[i+1]);
            i += 2;
        }
        else {
            // try to load as xml files
            vResourceFiles.push_back(argv[i]);
            i++;
        }
    }

    RaveInitialize(true);

    // create environment and start a command-line controlled simulation
    RaveSetDebugLevel(debuglevel);
    s_penv = RaveCreateEnvironment();
    RaveSetDebugLevel(debuglevel);
    for(list<string>::iterator it = listLoadPlugins.begin(); it != listLoadPlugins.end(); ++it) {
        RaveLoadPlugin(*it);
    }

    // add a signal handler
    signal(SIGINT,sigint_handler); // control C

    if( bListPlugins ) {

        std::list< std::pair<std::string, PLUGININFO> > plugins;
        std::list< std::pair<std::string, PLUGININFO> >::iterator itplugin;
        RaveGetPluginInfo(plugins);

        // output all the plugins and exit
        vector<string>::const_iterator itnames;

        vector<string>::iterator itname;
        stringstream ss;

        ss << endl << "Number of plugins: " << plugins.size() << endl;

        stringstream buf;
        std::map<InterfaceType,std::string>::const_iterator ittype;
        FORIT(ittype,RaveGetInterfaceNamesMap()) {
            vector<string> names;
            FORIT(itplugin, plugins) {
                FORIT(itnames, itplugin->second.interfacenames[ittype->first]) {
                    buf.str("");
#ifdef _WIN32
                    buf << "  " << *itnames << " - " << itplugin->first;
#else
                    buf << "  " << ChangeTextColor(0,OPENRAVECOLOR_DEBUGLEVEL) << *itnames << ResetTextColor() << " - " << itplugin->first;
#endif
                    names.push_back(buf.str());
                }
            }
            sort(names.begin(), names.end());
#ifdef _WIN32
            ss << ittype->second << ": " << names.size() << endl;
#else
            ss << ChangeTextColor(0,OPENRAVECOLOR_WARNLEVEL) << ittype->second << ": " << ResetTextColor() << names.size() << endl;
#endif
            FORIT(itname, names) {
                ss << itname->c_str() << endl;
            }
        }
        printf("%s",ss.str().c_str());
        s_penv->Destroy();
        return 0;
    }

    if((servername.size() > 0)&&(nServPort > 0)) {
        ModuleBasePtr pserver = RaveCreateModule(s_penv, servername);
        if( !!pserver ) {
            stringstream ss;
            ss << nServPort;
            if( s_penv->AddModule(pserver,ss.str()) != 0 )
                RAVELOG_WARN("failed to load server\n");
        }
    }

    if( collisionchecker.size() > 0 ) {
        CollisionCheckerBasePtr p = RaveCreateCollisionChecker(s_penv, collisionchecker);
        if( !!p ) {
            s_penv->SetCollisionChecker(p);
        }
    }
    if( physicsengine.size() > 0 ) {
        PhysicsEngineBasePtr p = RaveCreatePhysicsEngine(s_penv, physicsengine);
        if( !!p ) {
            s_penv->SetPhysicsEngine(p);
        }
    }

    // mac osx requires the main thread to be the gui thread...
    //s_bThreadDestroyed = false;
    //s_mainThread.reset(new boost::thread(boost::bind(MainOpenRAVEThread)));
    //s_mainThread->join();
    MainOpenRAVEThread();
    s_penv.reset();
    RaveDestroy();
    return 0;
}

// use to control openrave
void MainOpenRAVEThread()
{
    EnvironmentBasePtr penv = s_penv; // need to do this since s_penv can be reset at any time
    ViewerBasePtr pviewer;
    if( bDisplayGUI && (!s_viewerName ||s_viewerName->size()>0) ) {
        // find a viewer
        if( !!s_viewerName &&(s_viewerName->size() > 0)) {
            pviewer = RaveCreateViewer(penv, *s_viewerName);
        }
        if( !pviewer ) {
            boost::array<string,1> viewer_prefs = { { "qtcoin"}};
            for(size_t i = 0; i < viewer_prefs.size(); ++i) {
                pviewer = RaveCreateViewer(penv, viewer_prefs[i]);
                if( !!pviewer ) {
                    break;
                }
            }
        }

        if( !pviewer ) { // take any viewer
            std::map<InterfaceType, std::vector<std::string> > interfacenames;
            RaveGetLoadedInterfaces(interfacenames);
            std::vector<std::string>::const_iterator itname;
            FORIT(itname, interfacenames[PT_Viewer]) {
                pviewer = RaveCreateViewer(penv, *itname);
                if( !!pviewer ) {
                    break;
                }
            }
        }

        if( !pviewer ) {
            RAVELOG_WARN("failed to find an OpenRAVE viewer.\n");
        }
        else {
            RAVELOG_DEBUG("using %s viewer\n", pviewer->GetXMLId().c_str());
            pviewer->SetSize(s_WindowWidth, s_WindowHeight);
            if( s_bSetWindowPosition ) {
                pviewer->Move(s_WindowPosX,s_WindowPosY);
            }
            penv->AddViewer(pviewer);
        }
    }

    {
        EnvironmentMutex::scoped_lock lock(penv->GetMutex());

        if( s_sceneFile.size() > 0 ) {
            if( !penv->Load(s_sceneFile) ) {
                penv->LoadURI(s_sceneFile);
            }
        }
        vector<string>::iterator it;
        FORIT(it, vResourceFiles) {
            if( !penv->Load(*it) ) {
                penv->LoadURI(*it);
            }
        }
        list< pair<string, string> >::iterator itprob;
        FORIT(itprob, s_listModules) {
            ModuleBasePtr prob = RaveCreateModule(penv, itprob->first);
            if( !!prob ) {
                penv->AddModule(prob, itprob->second);
            }
        }

        if( s_saveScene.size() > 0 ) {
            penv->Save(s_saveScene);
            s_bThreadDestroyed = true;
            return;
        }
    }

    // need to keep a local pointer around to guarantee destruction order
    if( !!pviewer ) {
        pviewer->main(bShowGUI);
        s_bThreadDestroyed = true;
    }
    else {
        while(!s_bThreadDestroyed) {
            usleep(10000);
        }
    }
    if( !!penv ) {
        penv->Remove(pviewer);
        penv.reset();
        s_penv.reset();
        int iter = 0;
        while(pviewer.use_count() > 1 && iter < 200) {
            RAVELOG_DEBUG("viewer use count > 1, waiting for others to release viewer so can guarantee destruction in correct thread\n");
            usleep(10000);
            ++iter;
        }
    }
}

void sigint_handler(int sig)
{
    // if signal comes from viewer thread, then this could freeze openrave since this function
    // will call the viewer to exit, but it will be blocked waiting for this function to finish
    s_bThreadDestroyed = true;
    RaveDestroy();
    s_penv.reset();
#ifndef _WIN32
    // have to let the default sigint properly shutdown the program
    signal(SIGINT, SIG_DFL);
    kill(0 /*getpid()*/, SIGINT);
#endif
}

max_issues_repo_name: jdsika/holy

max_forks_repo_name: jdsika/holy


text:
#include <iostream>
#include <fstream>
#include <boost/math/constants/constants.hpp>
#include <boost/algorithm/searching/knuth_morris_pratt.hpp>
#include <boost/multiprecision/cpp_dec_float.hpp>
#include <boost/multiprecision/cpp_int.hpp>

using namespace std;

int main(int argc,char ** argv)
{

    //input file
    std::ifstream piDumpFile("big_pi_test_with_pi_test");
    if(piDumpFile.fail())
    {
        std::cout << "Sorry, no file to process." << std::endl;
        return 0;
    }

    //piDumpFile >> piDump;
    //

    piDumpFile.seekg(0, piDumpFile.end);
    std::streampos lengthToRead = piDumpFile.tellg();
    piDumpFile.seekg(0, piDumpFile.beg);

    std::string piDump(lengthToRead, '\0');

    piDumpFile.read(const_cast<char*>(piDump.data()), lengthToRead);

    std::cout << "piDump.size() " << piDump.size() << std::endl;

    //get PI constant
    boost::multiprecision::cpp_dec_float_50 piPrecise =
            boost::math::constants::pi<boost::multiprecision::cpp_dec_float_50>();
    //round it
    piPrecise = round(piPrecise * 10e18);
    //get pattern
    std::string piStrRound20 = piPrecise.str();
    std::cout << "Searching for rounded PI:" << piStrRound20 << std::endl;

    //perform KMP algorithm
    std::string::iterator piIterator = boost::algorithm::knuth_morris_pratt_search(
            piDump.begin(),piDump.end(), piStrRound20.begin(), piStrRound20.end());

    if(piIterator == piDump.end())
    {
        std::cout << "Could not find PI !" << std::endl;
    }else
    {
        std::cout << "Found PI at position n=" << std::distance(piDump.begin(),piIterator)+1 << std::endl;
    }

	return 0;
}


text: #include <boost/core/ref.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_LOGICAL_OR_HPP_INCLUDED
#define BOOST_SIMD_ARCH_COMMON_SIMD_FUNCTION_LOGICAL_OR_HPP_INCLUDED

#include <boost/simd/detail/overload.hpp>
#include <boost/simd/detail/traits.hpp>
#include <boost/simd/function/mask2logical.hpp>
#include <boost/simd/function/bitwise_or.hpp>
#include <boost/simd/function/genmask.hpp>
#include <boost/simd/meta/hierarchy/simd.hpp>
#include <boost/simd/meta/as_logical.hpp>

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

  BOOST_DISPATCH_OVERLOAD_IF(logical_or_
                            , (typename A0,typename A1,typename X)
                            , (nsm::and_< detail::same_size<A0,A1>, detail::is_native<X>>)
                            , bd::cpu_
                            , bs::pack_<bd::fundamental_<A0>,X>
                            , bs::pack_<bd::fundamental_<A1>,X>
                            )

  {
    BOOST_FORCEINLINE
    bs::as_logical_t<A0> operator()(const A0& a0, const A1& a1) const BOOST_NOEXCEPT
    {
      return mask2logical(bitwise_or(genmask(a0), genmask(a1)));
    }
  };
} } }

#endif

max_stars_repo_name: SylvainCorlay/pythran

max_issues_repo_name: SylvainCorlay/pythran

max_forks_repo_name: SylvainCorlay/pythran


text:
/**
 * @file torres_etal_2016.hpp
 * @brief Header file for torres_etal_2016.cpp
 * @author Takaki Ueno
 */

/*
 * Copyright (c) 2017 Takaki Ueno
 * Released under the MIT license
 */

#ifndef INCLUDED_torres_etal_2016_hpp_
#define INCLUDED_torres_etal_2016_hpp_

// cgutil
#include <cgutil.hpp>

// cpp standard libraries
#include <array>
#include <string>
#include <unordered_map>

// Boost
#include <boost/range/adaptor/indexed.hpp>
#include <boost/range/adaptor/reversed.hpp>

// std_msgs
#include <std_msgs/Float64.h>

// geometry_msgs
#include <geometry_msgs/Point32.h>
#include <geometry_msgs/Polygon.h>

// Service
#include "cpp_uav/Torres16.h"

/**
 * @struct Direction
 * @brief Storage for line sweep direction
 *
 * Sweep direction is from edge to vertex
 */
struct Direction
{
  LineSegment baseEdge;
  geometry_msgs::Point opposedVertex;
};

/**
 * @brief Checks if given path is clockwise (the first turn made to the left) or not
 * @param path
 * @return bool True if path is clockwise
 * @details the definition of "clockwise" is based on Fig.8 in Torres et al. 2016
 */
inline bool isClockWise(const PointVector& path)
{
  return path.at(0).x < path.at(1).x ? true : false;
}

/**
 * @brief Calculates line sweep direction for given polygon
 * @param polygon Line sweep direction is calculated on this region
 * @return direction Struct containing edge and vertex
 */
Direction identifyOptimalSweepDir(const PointVector& polygon)
{
  Direction sweepDirection;

  PointVector convexHull = computeConvexHull(polygon);

  // Edges of polygon
  LineSegmentVector edges;

  // Make a list of edges of polygon
  for (std::size_t i = 0; i < convexHull.size(); ++i)
  {
    LineSegment ar;

    ar.at(0) = convexHull.at(i);

    // if vertex is the last one,
    // that vertex makes an edge whose end is the first vertex
    if (i == convexHull.size() - 1)
    {
      ar.at(1) = convexHull.at(0);
    }
    else
    {
      ar.at(1) = convexHull.at(i + 1);
    }
    edges.push_back(ar);
  }

  double optimalDistance = 0;

  // Calculate line sweep direction
  // Algorithm 1 in Torres et al, 2016
  for (const auto& edge : edges | boost::adaptors::indexed())
  {
    double edgeMaxDistance = 0;
    geometry_msgs::Point opposedVertex;

    for (const geometry_msgs::Point& vertex : convexHull)
    {
      // calculateDistance() function returns distance
      // between given edge and vertex
      double distance = calculateDistance(edge.value(), vertex);

      if (distance > edgeMaxDistance)
      {
        edgeMaxDistance = distance;
        opposedVertex = vertex;
      }
    }

    if ((edgeMaxDistance < optimalDistance) or edge.index() == 0)
    {
      optimalDistance = edgeMaxDistance;
      sweepDirection.baseEdge = edge.value();
      sweepDirection.opposedVertex = opposedVertex;
    }
  }

  return sweepDirection;
}

/**
 * @brief Reshape given path
 * @param path The sweep lines of path should be horizontal about x axis
 * @param padding
 * @return PointVector
 * @details Reshape given path so that generated path becomes the sequence of "C" shapes and add padding
 */
PointVector reshapePath(const PointVector& path, double padding)
{
  PointVector zigzagPath;

  // reshape every traverse
  for (int i = 0; i < std::round(path.size() / 2); ++i)
  {
    // even-numbered traverse
    if (i % 2 == 0)
    {
      try
      {
        // in case that the first point of the traverse is located on LEFT side
        if (path.at(2 * i).x < path.at(2 * i + 1).x)
        {
          geometry_msgs::Point p1 = path.at(2 * i);
          geometry_msgs::Point p2 = path.at(2 * i + 1);

          // add padding
          p1.x += padding;
          p2.x -= padding;

          // be careful with the order of points
          zigzagPath.push_back(p1);
          zigzagPath.push_back(p2);
        }
        // in case that the first point of the traverse is located on RIGHT side
        else
        {
          geometry_msgs::Point p1 = path.at(2 * i);
          geometry_msgs::Point p2 = path.at(2 * i + 1);

          // add padding
          p1.x -= padding;
          p2.x += padding;

          // be careful with the order of points
          zigzagPath.push_back(p2);
          zigzagPath.push_back(p1);
        }
      }
      // in case that the traverse has only one vertex
      catch (std::out_of_range& ex)
      {
        geometry_msgs::Point p = path.at(2 * i);
        if (isClockWise(path))
        {
          // the first vertex of even-numbered traverse of clockwise path is located on RIGHT side of polygon
          p.x += padding;
          zigzagPath.push_back(p);
        }
        else
        {
          // the first vertex of even-numbered traverse of counterclockwise path is located on LEFT side of polygon
          p.x -= padding;
          zigzagPath.push_back(p);
        }
        ROS_ERROR("%s", ex.what());
      }
    }
    // odd-numbered traverse
    else
    {
      try
      {
        // in case that the first point of the traverse is located on RIGHT side
        if (path.at(2 * i).x > path.at(2 * i + 1).x)
        {
          geometry_msgs::Point p1 = path.at(2 * i);
          geometry_msgs::Point p2 = path.at(2 * i + 1);

          // add padding
          p1.x -= padding;
          p2.x += padding;

          // be careful with the order of points
          zigzagPath.push_back(p1);
          zigzagPath.push_back(p2);
        }
        // in case that the first point of the traverse is located on LEFT side
        else
        {
          geometry_msgs::Point p1 = path.at(2 * i);
          geometry_msgs::Point p2 = path.at(2 * i + 1);

          // add padding
          p1.x += padding;
          p2.x -= padding;

          // be careful with the order of points
          zigzagPath.push_back(p2);
          zigzagPath.push_back(p1);
        }
      }
      // in case that the traverse has only one vertex
      catch (std::out_of_range& ex)
      {
        geometry_msgs::Point p = path.at(2 * i);
        if (isClockWise(path))
        {
          // the first vertex of odd-numbered traverse of clockwise path is located on LEFT side of polygon
          p.x -= padding;
          zigzagPath.push_back(p);
        }
        else
        {
          // the first vertex of odd-numbered traverse of clockwise path is located on RIGHT side of polygon
          p.x += padding;
          zigzagPath.push_back(p);
        }
        ROS_ERROR("%s", ex.what());
      }
    }
  }
  return zigzagPath;
}

/**
 * @brief Compute coverage path for convex polygon
 * @param polygon Coverage path is calculated on this region
 * @param footprintWidth Width of the area taken by one sweep
 * @param horizontalOverwrap Horizontal overwrap of each sweep
 * @param sweepDirection
 * @param path Path of coverage path
 * @return bool True if path does not intersect with polygon
 */
bool computeConvexCoverage(const PointVector& polygon, double footprintWidth, double horizontalOverwrap,
                           const Direction& sweepDirection, PointVector& path)
{
  // Unable to make polygon with less than 3 points
  if (polygon.size() < 3)
  {
    return false;
  }

  // TODO: Change to configurable
  const double padding = footprintWidth/2.0;

  // rotate input polygon so that baseEdge become horizontal
  double rotationAngle = calculateHorizontalAngle(sweepDirection.baseEdge.front(), sweepDirection.baseEdge.back());
  PointVector rotatedPolygon = rotatePoints(polygon, -rotationAngle);

  // find x coordinate of most left and most right point
  double minX(0), maxX(0);
  for (const auto& vertex : rotatedPolygon)
  {
    if (vertex.x < minX)
    {
      minX = vertex.x;
    }
    else if (vertex.x > maxX)
    {
      maxX = vertex.x;
    }
  }

  double stepWidth = footprintWidth * (1 - horizontalOverwrap);

  // calculate sweep direction of rotated polygon
  PointVector dir{ sweepDirection.opposedVertex, sweepDirection.baseEdge.front(), sweepDirection.baseEdge.back() };
  dir = rotatePoints(dir, -rotationAngle);
  Direction rotatedDir;
  rotatedDir.opposedVertex = dir.at(0);
  rotatedDir.baseEdge.front() = dir.at(1);
  rotatedDir.baseEdge.back() = dir.at(2);

  int stepNum = std::ceil(calculateDistance(rotatedDir.baseEdge, rotatedDir.opposedVertex) / stepWidth);

  LineSegmentVector sweepLines;

  // generate list of sweep lines which is horizontal against the base edge
  for (int i = 0; i < stepNum; ++i)
  {
    LineSegment ar;
    geometry_msgs::Point p1, p2;
    p1.x = minX;
    p1.y = rotatedDir.baseEdge.at(0).y + (i * stepWidth) + padding;
    p2.x = maxX;
    p2.y = rotatedDir.baseEdge.at(1).y + (i * stepWidth) + padding;

    ar.at(0) = p1;
    ar.at(1) = p2;

    sweepLines.push_back(ar);
  }

  // Localize intersections of sweeplines and edges of rotated polygon
  LineSegmentVector rotatedEdges = generateEdgeVector(rotatedPolygon, true);

  PointVector intersections;

  for (const auto& sweepLine : sweepLines)
  {
    int intersectionCount = 0;
    for (const auto& edge : rotatedEdges)
    {
      if (hasIntersection(sweepLine, edge))
      {
        intersections.push_back(localizeIntersection(edge, sweepLine));
        ++intersectionCount;
      }

      // sweep line in optimal path does not have more than 2 intersections
      if (intersectionCount >= 3)
      {
        return false;
      }
    }
  }

  // sort points by y coordinate in ascending order
  std::stable_sort(intersections.begin(), intersections.end(),
                   [](const geometry_msgs::Point& p1, const geometry_msgs::Point& p2) { return p1.y < p2.y; });

  PointVector rotatedPath = reshapePath(intersections, padding);

  path = rotatePoints(rotatedPath, rotationAngle);

  if (hasIntersection(generateEdgeVector(polygon, true), generateEdgeVector(path, false)) == true)
  {
    return false;
  }

  return true;
}

/**
 * @brief Compute coverage path for convex polygon
 * @param polygon Coverage path is calculated on this region
 * @param footprintWidth Width of the area taken by one sweep
 * @param horizontalOverwrap Horizontal overwrap of each sweep
 * @param path Path of coverage path
 * @return bool True if path does not intersect with polygon
 */
bool computeConvexCoverage(const PointVector& polygon, double footprintWidth, double horizontalOverwrap,
                           PointVector& path)
{
  Direction sweepDirection = identifyOptimalSweepDir(polygon);
  return computeConvexCoverage(polygon, footprintWidth, horizontalOverwrap, sweepDirection, path);
}

/**
 * @brief Calculates length of path
 * @param path
 * @return double Length of path
 */
double calculatePathLength(const PointVector& path)
{
  if (path.size() < 2)
  {
    return 0;
  }

  double pathLength = 0;
  for (int i = 0; i < path.size() - 1; ++i)
  {
    pathLength += calculateDistance(path.at(i), path.at(i + 1));
  }
  return pathLength;
}

/**
 * @brief Return counter clock wise-ed path of given path
 * @param path Clockwise path
 * @return PointVector Counter clock wise version of given path
 */
PointVector computeCCWPath(PointVector path)
{
  for (int i = 0; i < std::round(path.size() / 2); ++i)
  {
    // swap the first point and the last point in each sweep line
    geometry_msgs::Point tmp = path.at(2 * i);

    path.at(2 * i) = path.at(2 * i + 1);
    try
    {
      path.at(2 * i + 1) = tmp;
    }
    catch (std::out_of_range& ex)
    {
      ROS_ERROR("%s", ex.what());
    }
  }
  return path;
}

/**
 * @brief Return opposite path of given path
 * @param path
 * @return PointVector Path with points of reversed order of given path
 */
PointVector computeOppositePath(const PointVector& path)
{
  PointVector oppositePath;

  // inversely iterate given points
  for (int i = path.size() - 1; i >= 0; --i)
  {
    oppositePath.push_back(path.at(i));
  }

  return oppositePath;
}

/**
 * @brief Identify optimal path from 4 coverage alternatives
 * @param polygon
 * @param path
 * @param start Start point
 * @param end End point
 * @return PointVector Optimal path that minimizes the length of path
 * @details The naming of the following variable follows torres et al. 2016
 */
PointVector identifyOptimalAlternative(const PointVector& polygon, const PointVector& path,
                                       const geometry_msgs::Point& start, const geometry_msgs::Point& end)
{
  // The naming of the following variable follows torres et al. 2016
  std::unordered_map<int, std::unordered_map<std::string, geometry_msgs::Point>> coverageAlternatives;
  std::unordered_map<std::string, geometry_msgs::Point> a1, a2, a3, a4;

  PointVector pathCW = isClockWise(path) ? path : computeCCWPath(path);
  PointVector pathCCW = isClockWise(path) ? computeCCWPath(path) : path;

  // a1: clockwise current path
  a1["SP"] = pathCW.front();
  a1["EP"] = pathCW.back();

  // a2: counterclockwise current path
  a2["SP"] = pathCCW.front();
  a2["EP"] = pathCCW.back();

  // a3: clockwise opposite path
  a3["SP"] = pathCW.back();
  a3["EP"] = pathCW.front();

  // a4: counterclockwise opposite path
  a4["SP"] = pathCCW.back();
  a4["EP"] = pathCCW.front();

  coverageAlternatives[1] = a1;
  coverageAlternatives[2] = a2;
  coverageAlternatives[3] = a3;
  coverageAlternatives[4] = a4;

  bool hasIntersectionCW = hasIntersection(generateEdgeVector(polygon, true), generateEdgeVector(pathCW, false));
  bool hasIntersectionCCW = hasIntersection(generateEdgeVector(polygon, true), generateEdgeVector(pathCCW, false));

  double minDistance;
  int optimalPath;

  // check which coverage alternative has the shortest path
  for (const auto& coverage : coverageAlternatives | boost::adaptors::indexed())
  {
    // skip calculating length if the path has intersections
    if ((hasIntersectionCW and coverage.index() % 2 == 0) or (hasIntersectionCCW and coverage.index() % 2 != 0))
    {
      continue;
    }

    // only length of transition need to be considered because the length of coverage is almost same
    double distance = calculateDistance(coverage.value().second.at("SP"), start) +
                      calculateDistance(end, coverage.value().second.at("EP"));

    if (distance < minDistance or coverage.index() == 0)
    {
      minDistance = distance;
      optimalPath = coverage.value().first;
    }
  }

  switch (optimalPath)
  {
    case 1:
    {
      return pathCW;
    }
    case 2:
    {
      return pathCCW;
    }
    case 3:
    {
      return computeOppositePath(pathCW);
    }
    default:
    {
      return computeOppositePath(pathCCW);
    }
  }
}

/**
 * @brief Identify optimal path from 4 coverage alternatives
 * @param polygon
 * @param path
 * @param start Start point
 * @return PointVector Optimal path that minimizes the length of path
 * @details The naming of the following variable follows torres et al. 2016
 */
PointVector identifyOptimalAlternative(const PointVector& polygon, const PointVector& path,
                                       const geometry_msgs::Point& start)
{
  return identifyOptimalAlternative(polygon, path, start, start);
}

/**
 * @brief Find second optimal path
 * @param polygon
 * @param footprintWidth
 * @param horizontalOverwrap
 * @param path
 * @return bool True if second optimal path exists
 */
bool findSecondOptimalPath(const PointVector& polygon, double footprintWidth, double horizontalOverwrap,
                           PointVector& path)
{
  std::vector<Direction> sweepDirections;
  PointVector convexHull = computeConvexHull(polygon);
  LineSegmentVector edges = generateEdgeVector(convexHull, true);

  // compute optimal sweep directions for each edge
  for (const auto& edge : edges)
  {
    double maxDistance = 0;
    Direction direction;
    direction.baseEdge = edge;
    for (const auto& vertex : convexHull)
    {
      double distance = calculateDistance(edge, vertex);

      // optimal sweep direction for a edge is the direction with the largest distance
      if (distance > maxDistance)
      {
        maxDistance = distance;
        direction.opposedVertex = vertex;
      }
    }
    sweepDirections.push_back(direction);
  }

  // compute second optimal path which has the shortest coverage path
  double pathLength = 0;
  PointVector tempPath;
  for (const auto& sweepDirection : sweepDirections)
  {
    PointVector p;

    // isValidPath is true if computed coverage does not have intersection
    bool isValidPath = computeConvexCoverage(polygon, footprintWidth, horizontalOverwrap, sweepDirection, p);

    // second optimal path is the shortest path without intersection
    if (isValidPath and ((calculatePathLength(tempPath) < pathLength) or (pathLength == 0)))
    {
      tempPath = p;
      pathLength = calculatePathLength(tempPath);
    }
  }

  if (tempPath.size() <= 1)
  {
    return false;
  }
  else
  {
    path = tempPath;
    return true;
  }
}

/**
 * @brief Check if given two polygons are adjacent
 * @param polygon1
 * @param polygon2
 * @return True if given two polygons are adjacent
 */
bool isAdjacent(const PointVector& polygon1, const PointVector& polygon2)
{
  for (const auto& vertex1 : polygon1)
  {
    for (const auto& vertex2 : polygon2)
    {
      // consider that two polygons are adjacent if they have at least one point in common
      if (vertex1 == vertex2)
      {
        return true;
      }
    }
  }
  return false;
}

/**
 * @brief Compute coverage path for multiple convex polygons
 * @param subPolygons
 * @param footprintWidth
 * @param horizontalOverwrap
 * @param adjacencyCriteria Ignore paths which have less adjacent polygons than this number
 * @return PointVector Computed Path
 * @details See section 6.2 of torres et al. 2016 for the detail
 */
PointVector computeMultiplePolygonCoverage(std::vector<PointVector> subPolygons, double footprintWidth,
                                           double horizontalOverwrap, int adjacencyCriteria = 1)
{
  PointVector path;

  std::vector<int> permutation(subPolygons.size());
  std::iota(permutation.begin(), permutation.end(), 0);

  double minPathLength = -1;
  bool hasIntersection = false;

  int numPermutation = 0;
  int numIntersectSets = 0;

  do
  {
    // ignore permutations which do not start from the same polygon as the first one of given subpolygons
    if (permutation.front() != 0)
    {
      continue;
    }

    // count adjacent polygons
    int adjacencyCount = 0;
    for (auto itr = permutation.begin(); itr != permutation.end() - 1; ++itr)
    {
      if (isAdjacent(subPolygons.at(*itr), subPolygons.at(*(itr + 1))) == true)
      {
        ++adjacencyCount;
      }
    }

    // ignore if enough number of polygons do not exist
    if (adjacencyCount < adjacencyCriteria)
    {
      continue;
    }

    double pathLength = 0;
    std::vector<PointVector> candidatePath;

    // computes coverage path for each polygons and connect them
    for (auto itr = permutation.begin(); itr != permutation.end(); ++itr)
    {
      PointVector partPath, optimalAlternative;
      // first polygon of given subpolygon
      if (itr == permutation.begin())
      {
        try
        {
          // start point and end point of first subpolygon are ...
          //    start point: the last point of coverage of the last subpolygon
          //    end point  : the first point of coverage of the second subpolygon
          geometry_msgs::Point start = subPolygons.at(*(permutation.end() - 1)).back();
          geometry_msgs::Point end;
          PointVector polygon = subPolygons.at(*itr);
          if (permutation.size() == 1)
          {
            // end point is the same as start point if subPolygons.at(*(itr+1)) is out of range
            end = start;
          }
          else
          {
            end = subPolygons.at(*(itr + 1)).front();
          }

          // break if computed path has intersections
          if (computeConvexCoverage(polygon, footprintWidth, horizontalOverwrap, partPath) == false)
          {
            hasIntersection = true;
            break;
          }

          // set optimal alternative as candidate
          optimalAlternative = identifyOptimalAlternative(polygon, partPath, start, end);
          candidatePath.push_back(optimalAlternative);

          // calculate the length of candidate path
          pathLength += calculatePathLength(optimalAlternative);
        }
        catch (std::out_of_range& ex)
        {
          ROS_ERROR("%s", ex.what());
        }
      }
      // the last polygon of the given subpolygons
      else if (itr == permutation.end() - 1)
      {
        try
        {
          // start point and end point of the last subpolygon are ...
          //    start point: the last point of coverage of the previous subpolygon
          //    end point  : the first point of coverage of the first subpolygon
          geometry_msgs::Point start = subPolygons.at(*(itr - 1)).back();
          geometry_msgs::Point end = subPolygons.at(*permutation.begin()).front();
          PointVector polygon = subPolygons.at(*itr);

          // break if computed path has intersections
          if (computeConvexCoverage(polygon, footprintWidth, horizontalOverwrap, partPath) == false)
          {
            hasIntersection = true;
            break;
          }

          // set optimal alternative as candidate
          optimalAlternative = identifyOptimalAlternative(polygon, partPath, start, end);
          candidatePath.push_back(optimalAlternative);

          // calculate the length of candidate path
          pathLength += calculatePathLength(optimalAlternative);
        }
        catch (std::out_of_range& ex)
        {
          ROS_ERROR("%s", ex.what());
        }
      }
      // middle polygons
      else
      {
        try
        {
          // start point and end point of middle subpolygons are ...
          //    start point: the last point of coverage of the previous subpolygon
          //    end point  : the first point of coverage of the next subpolygon
          geometry_msgs::Point start = subPolygons.at(*(itr - 1)).back();
          geometry_msgs::Point end = subPolygons.at(*(itr + 1)).front();
          PointVector polygon = subPolygons.at(*itr);

          // break if computed path has intersections
          if (computeConvexCoverage(polygon, footprintWidth, horizontalOverwrap, partPath) == false)
          {
            hasIntersection = true;
            break;
          }

          // set optimal alternative as candidate
          optimalAlternative = identifyOptimalAlternative(polygon, partPath, start, end);
          candidatePath.push_back(optimalAlternative);

          // calculate the length of candidate path
          pathLength += calculatePathLength(optimalAlternative);
        }
        catch (std::out_of_range& ex)
        {
          ROS_ERROR("%s", ex.what());
        }
      }
    }

    numPermutation++;

    if(hasIntersection)
    {
      numIntersectSets++;
      hasIntersection = false;
      break;
    }

    // update coverage path and minimum path length
    if (minPathLength < 0 or pathLength < minPathLength)
    {
      minPathLength = pathLength;

      if (not path.empty())
      {
        path.clear();
      }

      // insert coverages of subpolygons
      for (const auto& part : candidatePath)
      {
        path.insert(path.begin(), part.begin(), part.end());
      }
    }

  } while (next_permutation(permutation.begin(), permutation.end()));

  if(minPathLength<0)
  {
    ROS_ERROR("Unable to generate path.");
  }

  return path;
}

#endif


text:
#include <utility>

//
// Created by redra on 21.07.17.
//

#include <boost/asio/io_service.hpp>
#include <iostream>
#include <icc/Component.hpp>
#include <icc/Event.hpp>
#include <icc/Timer.hpp>
#include <icc/command/Builder.hpp>
#include <icc/command/Command.hpp>
#include <icc/command/CommandLoop.hpp>
#include <icc/Context.hpp>

namespace icc {

template <>
class Context<boost::asio::io_service>
    : public std::enable_shared_from_this<Context<boost::asio::io_service>>
    , public IContext {
 public:
  class Channel : public IContext::IChannel {
   public:
    explicit Channel(std::shared_ptr<Context> context)
        : context_{std::move(context)} {
    }

    void push(Action _action) override {
      if (context_) {
        context_->push(std::move(_action));
      }
    }

    void invoke(Action _action) override {
      if (context_) {
        context_->invoke(std::move(_action));
      }
    }

    [[nodiscard]]
    IContext & getContext() const override {
      return *context_;
    }

   private:
    std::shared_ptr<Context> context_;
  };

  Context(boost::asio::io_service *_service)
    : service_(std::shared_ptr<boost::asio::io_service>(_service,
      [=](boost::asio::io_service *) {
        // NOTE(redra): Nothing need to do. Owner of this pointer is not us
      }))
    , worker_(new boost::asio::io_service::work(*service_)) {
  }

  Context(std::shared_ptr<boost::asio::io_service> _service)
    : service_(std::move(_service))
    , worker_(new boost::asio::io_service::work(*service_)) {
  }

  void push(Action _action) {
    if (service_) {
      service_->post(std::move(_action));
    }
  }

  void invoke(Action _action) {
    if (service_) {
      service_->dispatch(_action);
    }
  }

  std::unique_ptr<IChannel> createChannel() override {
    return std::unique_ptr<Channel>(new Channel{shared_from_this()});
  }

 private:
  std::shared_ptr<boost::asio::io_service> service_;
  std::unique_ptr<boost::asio::io_service::work> worker_;
};

}

class ConnectionHFP
    : public icc::command::Command {
 public:
  virtual void processStartCommand() override {
    std::cout << "ConnectionHFP is started" << std::endl;
    finished(icc::command::CommandResult::FAILED);
  }
};

class ConnectionA2DP
    : public icc::command::Command {
 public:
  virtual void processStartCommand() override {
    std::cout << "ConnectionA2DP is started" << std::endl;
    finished(icc::command::CommandResult::SUCCESS);
  }
};

class ConnectionBTProfiles
  : public icc::command::CommandLoop {
 private:
  friend class icc::command::Builder;
  ConnectionBTProfiles(boost::asio::io_service *_eventLoop)
    : icc::Component(_eventLoop) {
    setMode(icc::command::LoopMode::MultiCommand |
            icc::command::LoopMode::Transaction);
    pushBack(std::make_shared<ConnectionHFP>());
    pushBack(std::make_shared<ConnectionA2DP>());
  }

  virtual void processStartCommand() override {
    std::cout << "ConnectionBTProfiles is started" << std::endl;
    icc::command::CommandLoop::processStartCommand();
  }

 public:
  void processEvent(const CommandData & _data) override {
    icc::command::CommandLoop::processEvent(_data);
    switch (_data.result_) {
      case icc::command::CommandResult::SUCCESS:
        std::cout << "ConnectionBTProfiles::CommandEvent::SUCCESS" << std::endl;
        break;
      case icc::command::CommandResult::FAILED:
        std::cout << "ConnectionBTProfiles::CommandEvent::FAILED" << std::endl;
        break;
      case icc::command::CommandResult::ABORTED:
        std::cout << "ConnectionBTProfiles::CommandEvent::ABORTED" << std::endl;
        break;
    }
  }
};

class Connect
  : public icc::command::CommandLoop {
 private:
  friend class icc::command::Builder;
  Connect(boost::asio::io_service *_eventLoop)
    : icc::Component(_eventLoop) {
  }

 public:
  void processEvent(const CommandData & _data) override {
    icc::command::CommandLoop::processEvent(_data);
    switch (_data.result_) {
      case icc::command::CommandResult::SUCCESS:
        std::cout << "Connect::CommandEvent::SUCCESS" << std::endl;
        break;
      case icc::command::CommandResult::FAILED:
        std::cout << "Connect::CommandEvent::FAILED" << std::endl;
        break;
      case icc::command::CommandResult::ABORTED:
        std::cout << "Connect::CommandEvent::ABORTED" << std::endl;
        break;
    }
    std::cout << "Connect::Command is finished" << std::endl;
  }
};

int main() {
  try {
    using icc::command::Builder;
    boost::asio::io_service service_;
    auto mainLoop = Builder::buildCommandLoop<Connect>(&service_);
    mainLoop->pushBack(Builder::buildCommandLoop<ConnectionBTProfiles>(&service_));
    mainLoop->startCommand();
    // Start event loop
    service_.run();
  } catch (icc::command::CommandStateAssert & ex) {
    std::cout << "ex is " << ex.what() << std::endl;
    std::cout << "command is " << ex.getCommand()->getCommandType() << std::endl;
  }
  return 0;
}

max_stars_repo_name: redradist/Inter-Component-Communication

max_issues_repo_name: redradist/Inter-Component-Communication

max_forks_repo_name: redradist/Inter-Component-Communication


text:
//==-------------------------------------------------------------*- C++ -*--==//
//
// Copyright 2019 Contributors to the Gazer project
//
// 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.
//
//===----------------------------------------------------------------------===//
///
/// \file This file defines the FoldingExprBuilder class, an implementation of
/// the expression builder interface. It aims to fold constant expressions and
/// perform some basic formula simplification.
///
//===----------------------------------------------------------------------===//
#include "gazer/Core/Expr/ExprBuilder.h"
#include "gazer/Core/ExprTypes.h"
#include "gazer/Core/LiteralExpr.h"
#include "gazer/Core/Expr/Matcher.h"
#include "gazer/ADT/Algorithm.h"

#include <llvm/ADT/DenseMap.h>
#include <llvm/ADT/DenseSet.h>
#include <llvm/Support/raw_ostream.h>

#include <boost/container/flat_set.hpp>

#include <unordered_set>
#include <variant>

using namespace gazer;
using namespace gazer::PatternMatch;

using llvm::isa;
using llvm::cast;
using llvm::dyn_cast;

namespace
{

class FoldingExprBuilder : public ExprBuilder
{
public:
    FoldingExprBuilder(GazerContext& context)
        : ExprBuilder(context)
    {}

private:
    ExprPtr foldBinaryExpr(Expr::ExprKind kind, const ExprPtr& left, const ExprPtr& right);
    ExprPtr foldBinaryCompare(Expr::ExprKind kind, const ExprPtr& left, const ExprPtr& right);
    ExprPtr simplifyLtEq(const ExprPtr& left, const ExprPtr& right);

public:
    ExprPtr Not(const ExprPtr& op) override
    {
        if (auto boolLit = dyn_cast<BoolLiteralExpr>(op.get())) {
            return BoolLiteralExpr::Get(op->getContext(), !boolLit->getValue());
        }

        ExprPtr x, y;

        // Not(Or(Not(X), Y)) --> And(X, Not(Y))
        if (match(op, m_Or(m_Not(m_Expr(x)), m_Expr(y)))) {
            return this->And({x, this->Not(y)});
        }

        return NotExpr::Create(op);
    }

    ExprPtr ZExt(const ExprPtr& op, BvType& type) override
    {
        if (auto bvLit = dyn_cast<BvLiteralExpr>(op.get())) {
            return BvLiteralExpr::Get(type, bvLit->getValue().zext(type.getWidth()));
        }

        return ZExtExpr::Create(op, type);
    }

    ExprPtr SExt(const ExprPtr& op, BvType& type) override
    {
        if (auto bvLit = dyn_cast<BvLiteralExpr>(op.get())) {
            return BvLiteralExpr::Get(type, bvLit->getValue().sext(type.getWidth()));
        }

        return SExtExpr::Create(op, type);
    }

    ExprPtr Extract(const ExprPtr& op, unsigned offset, unsigned width) override
    {
        if (auto bvLit = dyn_cast<BvLiteralExpr>(op)) {
            return BvLiteralExpr::Get(
                BvType::Get(op->getContext(), width),
                bvLit->getValue().extractBits(width, offset)
            );
        }

        if (op->isUndef()) {
            // Extracting from and undef results in an undef
            return UndefExpr::Get(BvType::Get(getContext(), width));
        }

        return ExtractExpr::Create(op, offset, width);
    }

    #define FOLD_BINARY_ARITHMETIC(KIND)                                    \
    ExprPtr KIND(const ExprPtr& left, const ExprPtr& right) override {      \
        ExprPtr folded = this->foldBinaryExpr(Expr::KIND, left, right);   \
        if (folded != nullptr) { return folded; }                           \
        return KIND##Expr::Create(left, right);                             \
    }

    FOLD_BINARY_ARITHMETIC(Add)
    FOLD_BINARY_ARITHMETIC(Sub)
    FOLD_BINARY_ARITHMETIC(Mul)
    FOLD_BINARY_ARITHMETIC(BvSDiv)
    FOLD_BINARY_ARITHMETIC(BvUDiv)
    FOLD_BINARY_ARITHMETIC(BvSRem)
    FOLD_BINARY_ARITHMETIC(BvURem)
    FOLD_BINARY_ARITHMETIC(Shl)
    FOLD_BINARY_ARITHMETIC(LShr)
    FOLD_BINARY_ARITHMETIC(AShr)
    FOLD_BINARY_ARITHMETIC(BvAnd)
    FOLD_BINARY_ARITHMETIC(BvOr)
    FOLD_BINARY_ARITHMETIC(BvXor)

    #undef FOLD_BINARY_ARITHMETIC

    ExprPtr BvConcat(const ExprPtr& left, const ExprPtr& right) override
    {
        unsigned width = cast<BvType>(left->getType()).getWidth() + cast<BvType>(right->getType()).getWidth();

        if (auto lhsLit = llvm::dyn_cast<BvLiteralExpr>(left)) {
            if (auto rhsLit = llvm::dyn_cast<BvLiteralExpr>(right)) {
                llvm::APInt result = lhsLit->getValue().zext(width).shl(rhsLit->getType().getWidth());
                result = result | rhsLit->getValue().zext(width);

                return this->BvLit(result);
            }
        }

        if (left->isUndef() && right->isUndef()) {
            // We do not want to simplify partially undef cases.
            return this->Undef(BvType::Get(getContext(), width));
        }

        return BvConcatExpr::Create(left, right);
    }

    ExprPtr And(const ExprVector& vector) override
    {
        ExprVector newOps;

        for (const ExprPtr& op : vector) {
            if (auto lit = dyn_cast<BoolLiteralExpr>(op)) {
                // We are not adding unnecessary true literals
                if (lit->isFalse()) {
                    return this->False();
                }
            } else if (auto andExpr = dyn_cast<AndExpr>(op)) {
                // For AndExpr operands, we flatten the expression
                newOps.insert(newOps.end(), andExpr->op_begin(), andExpr->op_end());
            } else {
                newOps.push_back(op);
            }
        }

        if (newOps.empty()) {
            // If we eliminated all operands
            return this->True();
        }

        if (newOps.size() == 1) {
            return *newOps.begin();
        }

        return AndExpr::Create(newOps);
    }

    ExprPtr Or(const ExprVector& vector) override
    {
        ExprVector newOps;

        for (const ExprPtr& op : vector) {
            if (auto lit = dyn_cast<BoolLiteralExpr>(op)) {
                if (lit->isTrue()) {
                    return this->True();
                } else {
                    // We are not adding unnecessary false literals
                }
            } else if (auto orExpr = dyn_cast<OrExpr>(op)) {
                // For OrExpr operands, we try to flatten the expression
                newOps.insert(newOps.end(), orExpr->op_begin(), orExpr->op_end());
            } else {
                newOps.push_back(op);
            }
        }

        if (newOps.empty()) {
            // If we eliminated all operands
            return this->False();
        }

        if (newOps.size() == 1) {
            return *newOps.begin();
        }

        return OrExpr::Create(newOps);
    }

    ExprPtr Imply(const ExprPtr& left, const ExprPtr& right) override
    {
        // True  => X --> X
        // False => X --> True
        if (auto bl = llvm::dyn_cast<BoolLiteralExpr>(left)) {
            if (bl->isTrue()) {
                return right;
            }

            return this->True();
        }

        // X => True  --> True
        // X => False --> not X
        if (auto br = llvm::dyn_cast<BoolLiteralExpr>(right)) {
            if (br->isTrue()) {
                return this->True();
            }

            return this->Not(left);
        }

        return ImplyExpr::Create(left, right);
    }

    ExprPtr Eq(const ExprPtr& left, const ExprPtr& right) override
    {
        if (left == right) {
            return this->True();
        }

        if (isa<LiteralExpr>(left) && isa<LiteralExpr>(right) && left != right) {
            return this->False();
        }

        if (ExprPtr folded = this->foldBinaryCompare(Expr::Eq, left, right)) {
            return folded;
        }

        ExprRef<BoolLiteralExpr> b1 = nullptr;
        ExprPtr c1 = nullptr;
        ExprRef<LiteralExpr> l1 = nullptr, l2 = nullptr;

        // Eq(Select(C1, L1, L2), L1) --> C1
        if (unord_match(left, right, m_Select(m_Expr(c1), m_Literal(l1), m_Literal(l2)), m_Specific(l1))) {
            return c1;
        }

        // Eq(Select(C1, L1, L2), L2) --> Not(C1)
        if (unord_match(left, right, m_Select(m_Expr(c1), m_Literal(l1), m_Literal(l2)), m_Specific(l2))) {
            return this->Not(c1);
        }

        return EqExpr::Create(left, right);
    }

    ExprPtr NotEq(const ExprPtr& left, const ExprPtr& right) override
    {
        return this->Not(this->Eq(left, right));
    }

    // Comparison operators
    //===------------------------------------------------------------------===//
    // Apart from folding, we shall also normalize everything here
    // into a LtEq expression.

    ExprPtr Lt(const ExprPtr& left, const ExprPtr& right) override
    {
        // Lt(X, Y) --> Not(LtEq(Y, X))
        return this->Not(this->LtEq(right, left));
    }

    ExprPtr LtEq(const ExprPtr& left, const ExprPtr& right) override
    {
        if (ExprPtr folded = this->foldBinaryCompare(Expr::LtEq, left, right)) {
            return folded;
        }

        return this->simplifyLtEq(left, right);
    }

    ExprPtr Gt(const ExprPtr& left, const ExprPtr& right) override
    {
        if (ExprPtr folded = this->foldBinaryCompare(Expr::Gt, left, right)) {
            return folded;
        }

        // Gt(C, X) --> LtEq(X, C - 1) if C is Int
        IntLiteralExpr::ValueTy intVal;
        ExprPtr x;
        if (match(left, right, m_Int(&intVal), m_Expr(x))) {
            return LtEqExpr::Create(x, this->IntLit(intVal - 1));
        }

        // Gt(X, Y) --> Not(LtEq(X, Y))
        return this->Not(this->LtEq(left, right));
    }

    ExprPtr GtEq(const ExprPtr& left, const ExprPtr& right) override
    {
        // GtEq(X, Y) --> LtEq(Y, X)
        return this->LtEq(right, left);
    }

    ExprPtr BvSLt(const ExprPtr& left, const ExprPtr& right) override
    {
        return BvSLtExpr::Create(left, right);
    }

    ExprPtr BvSLtEq(const ExprPtr& left, const ExprPtr& right) override
    {
        return BvSLtEqExpr::Create(left, right);
    }

    ExprPtr BvSGt(const ExprPtr& left, const ExprPtr& right) override
    {
        return BvSGtExpr::Create(left, right);
    }

    ExprPtr BvSGtEq(const ExprPtr& left, const ExprPtr& right) override
    {
        return BvSGtEqExpr::Create(left, right);
    }

    ExprPtr BvULt(const ExprPtr& left, const ExprPtr& right) override
    {
        return BvULtExpr::Create(left, right);
    }

    ExprPtr BvULtEq(const ExprPtr& left, const ExprPtr& right) override
    {
        return BvULtEqExpr::Create(left, right);
    }

    ExprPtr BvUGt(const ExprPtr& left, const ExprPtr& right) override
    {
        return BvUGtExpr::Create(left, right);
    }

    ExprPtr BvUGtEq(const ExprPtr& left, const ExprPtr& right) override
    {
        return BvUGtEqExpr::Create(left, right);
    }

    // Floating-point
    //===------------------------------------------------------------------===//

    ExprPtr FIsNan(const ExprPtr& op) override
    {
        if (auto fpLit = dyn_cast<FloatLiteralExpr>(op)) {
            return this->BoolLit(fpLit->getValue().isNaN());
        }

        return FIsNanExpr::Create(op);
    }

    ExprPtr FIsInf(const ExprPtr& op) override
    {
        if (auto fpLit = dyn_cast<FloatLiteralExpr>(op)) {
            return this->BoolLit(fpLit->getValue().isInfinity());
        }

        return FIsInfExpr::Create(op);
    }

    ExprPtr FCast(const ExprPtr& op, FloatType& type, llvm::APFloat::roundingMode rm) override
    {
        return FCastExpr::Create(op, type, rm);
    }

    ExprPtr SignedToFp(const ExprPtr& op, FloatType& type, llvm::APFloat::roundingMode rm) override {
        return SignedToFpExpr::Create(op, type, rm);
    }

    ExprPtr UnsignedToFp(const ExprPtr& op, FloatType& type, llvm::APFloat::roundingMode rm) override {
        return UnsignedToFpExpr::Create(op, type, rm);
    }

    ExprPtr FpToSigned(const ExprPtr& op, BvType& type, llvm::APFloat::roundingMode rm) override {
        return FpToSignedExpr::Create(op, type, rm);
    }

    ExprPtr FpToUnsigned(const ExprPtr& op, BvType& type, llvm::APFloat::roundingMode rm) override {
        return FpToUnsignedExpr::Create(op, type, rm);
    }

    ExprPtr FAdd(const ExprPtr& left, const ExprPtr& right, llvm::APFloat::roundingMode rm) override
    {
        return FAddExpr::Create(left, right, rm);
    }

    ExprPtr FSub(const ExprPtr& left, const ExprPtr& right, llvm::APFloat::roundingMode rm) override
    {
        return FSubExpr::Create(left, right, rm);
    }

    ExprPtr FMul(const ExprPtr& left, const ExprPtr& right, llvm::APFloat::roundingMode rm) override
    {
        return FMulExpr::Create(left, right, rm);
    }

    ExprPtr FDiv(const ExprPtr& left, const ExprPtr& right, llvm::APFloat::roundingMode rm) override
    {
        return FDivExpr::Create(left, right, rm);
    }

    ExprPtr FEq(const ExprPtr& left, const ExprPtr& right) override
    {
        return FEqExpr::Create(left, right);
    }
    ExprPtr FGt(const ExprPtr& left, const ExprPtr& right) override
    {
        return FGtExpr::Create(left, right);
    }
    ExprPtr FGtEq(const ExprPtr& left, const ExprPtr& right) override
    {
        return FGtEqExpr::Create(left, right);
    }
    ExprPtr FLt(const ExprPtr& left, const ExprPtr& right) override
    {
        return FLtExpr::Create(left, right);
    }
    ExprPtr FLtEq(const ExprPtr& left, const ExprPtr& right) override
    {
        return FLtEqExpr::Create(left, right);
    }

    ExprPtr Select(const ExprPtr& condition, const ExprPtr& then, const ExprPtr& elze) override
    {
        // Select(True, E1, E2) --> E1
        // Select(False, E1, E2) --> E2
        if (auto condLit = dyn_cast<BoolLiteralExpr>(condition.get())) {
            return condLit->isTrue() ? then : elze;
        }

        ExprPtr c1 = nullptr, c2 = nullptr;
        ExprPtr e1 = nullptr, e2 = nullptr;

        // Select(C, E, E) --> E
        if (then == elze) {
            return then;
        }

        // Select(C, E, False) --> And(C, E)
        if (elze == this->False()) {
            return this->And({ condition, then });
        }

        // Select(C, E, True) --> Or(not C, E)
        if (elze == this->True()) {
            return this->Or({ this->Not(condition), then });
        }

        // Select(C, True, E) --> Or(C, E)
        if (then == this->True()) {
            return this->Or({ condition, elze });
        }

        // Select(C, False, E) --> And(not C, E)
        if (then == this->False()) {
            return this->And({ this->Not(condition), elze });
        }

        // Select(not C, E1, E2) --> Select(C, E2, E1)
        if (match(condition, then, elze, m_Not(m_Expr(c1)), m_Expr(e1), m_Expr(e2))) {
            return SelectExpr::Create(c1, elze, then);
        }

        // Select(C1, Select(C1, E1, E'), E2) --> Select(C1, E1, E2)
        if (match(condition, then, elze, m_Expr(c1), m_Select(m_Specific(c1), m_Expr(e1), m_Expr()), m_Expr(e2))) {
            return SelectExpr::Create(c1, e1, e2);
        }

        // Select(C1, E1, Select(C1, E', E2)) --> Select(C1, E1, E2)
        if (match(condition, then, elze, m_Expr(c1), m_Expr(e1), m_Select(m_Specific(c1), m_Expr(), m_Expr(e2)))) {
            return SelectExpr::Create(c1, e1, e2);
        }

        // Select(C1, Select(C2, E1, E2), E1) --> Select(C1 and not C2, E2, E1)
        if (match(condition, then, elze, m_Expr(c1), m_Select(m_Expr(c2), m_Expr(e1), m_Expr(e2)), m_Specific(e1))) {
            return SelectExpr::Create(this->And({c1, this->Not(c2)}), e1, e2);
        }

        // Select(C1, Select(C2, E1, E2), E2) --> Select(C1 and C2, E1, E2)
        if (match(condition, then, elze, m_Expr(c1), m_Select(m_Expr(c2), m_Expr(e1), m_Expr(e2)), m_Specific(e2))) {
            return SelectExpr::Create(AndExpr::Create({c1, c2}), e1, e2);
        }

        // Select(C1, E1, Select(C2, E1, E2)) --> Select(C1 or C2, E1, E2)
        if (match(condition, then, elze, m_Expr(c1), m_Expr(e1), m_Select(m_Expr(c2), m_Specific(e1), m_Expr(e2)))) {
            return SelectExpr::Create(OrExpr::Create({c1, c2}), e1, e2);
        }

        return SelectExpr::Create(condition, then, elze);
    }

    ExprPtr Write(const ExprPtr& array, const ExprPtr& index, const ExprPtr& value) override
    {
        if (auto lit = llvm::dyn_cast<ArrayLiteralExpr>(array)) {
            if (lit->getMap().empty() && lit->getDefault() == value) {
                return lit;
            }
        }

        return ArrayWriteExpr::Create(array, index, value);
    }

    ExprPtr Read(const ExprPtr& array, const ExprPtr& index) override
    {
        if (auto lit = llvm::dyn_cast<ArrayLiteralExpr>(array)) {
            if (lit->getMap().empty()) {
                return lit->getDefault();
            }
        }

        return ArrayReadExpr::Create(array, index);
    }
};

} // end anonymous namespace

ExprPtr FoldingExprBuilder::foldBinaryExpr(Expr::ExprKind kind, const ExprPtr& left, const ExprPtr& right)
{
    if (auto rhs = dyn_cast<IntLiteralExpr>(right)) {
        // If the right side is an integer literal
        switch (kind) {
            case Expr::Add:
            case Expr::Sub:
                if (rhs->isZero()) { return left; }
                break;
            case Expr::Mul:
                if (rhs->isZero()) { return right; }
                if (rhs->isOne()) { return left; }
                break;
            case Expr::Div:
                if (rhs->isOne()) { return left; }
                break;
            case Expr::Mod:
            case Expr::Rem:
                if (rhs->isOne()) { return this->IntLit(0); }
                break;
            default:
                break;
        }
    } else if (auto rhs = dyn_cast<BvLiteralExpr>(right)) {
        // Alternatively, it can be a bit-vector literal
        switch (kind) {
            case Expr::Add:
            case Expr::Sub:
                if (rhs->isZero()) { return left; }
                break;
            case Expr::Mul:
                if (rhs->isZero()) { return right; }
                if (rhs->isOne())  { return left; }
                break;
            case Expr::BvUDiv:
            case Expr::BvSDiv:
                if (rhs->isOne()) { return left; }                          // X div 1 == X
                break;
            case Expr::BvURem:
            case Expr::BvSRem:
                if (rhs->isOne()) { return BvLiteralExpr::Get(rhs->getType(), 0); }   // X rem 1 == 0
                break;
            case Expr::BvAnd:
                if (rhs->isZero()) { return rhs; }                          // X and 0 == 0
                if (rhs->isAllOnes()) { return left; }                      // X and 1..1 == X
                break;
            case Expr::BvOr:
                if (rhs->isZero()) { return left; }                         // X or 0 == X
                if (rhs->isAllOnes()) { return rhs; }                       // X and 1..1 == 1..1
            case Expr::BvXor:
                if (rhs->isZero()) { return left; }                         // X xor 0 == X
                break;
            default:
                break;
        }
    } else if (llvm::isa<LiteralExpr>(left) && Expr::isCommutative(kind)) {
        // If LHS is constant while RHS is not, retry with swapped operands
        return foldBinaryExpr(kind, right, left);
    }

    // See if both of them are literals
    if (auto lhs = dyn_cast<IntLiteralExpr>(left)) {
        if (auto rhs = dyn_cast<IntLiteralExpr>(right)) {
            auto l = lhs->getValue();
            auto r = rhs->getValue();

            switch (kind) {
                case Expr::Add: return this->IntLit(l + r);
                case Expr::Sub: return this->IntLit(l - r);
                case Expr::Mul: return this->IntLit(l * r);
                case Expr::Div: return this->IntLit(l / r);
                case Expr::Mod:
                case Expr::Rem:
                // FIXME
                default:
                    break;
            }
        }
    } else if (auto lhs = dyn_cast<BvLiteralExpr>(left)) {
        if (auto rhs = dyn_cast<BvLiteralExpr>(right)) {
            auto l = lhs->getValue();
            auto r = rhs->getValue();

            switch (kind) {
                case Expr::Add: return this->BvLit(l + r);
                case Expr::Sub: return this->BvLit(l - r);
                case Expr::Mul: return this->BvLit(l * r);
                case Expr::BvUDiv: return this->BvLit(l.udiv(r));
                case Expr::BvSDiv: return this->BvLit(l.sdiv(r));
                case Expr::BvURem: return this->BvLit(l.urem(r));
                case Expr::BvSRem: return this->BvLit(l.srem(r));
                case Expr::BvAnd: return this->BvLit(l & r);
                case Expr::BvOr: return this->BvLit(l | r);
                case Expr::BvXor: return this->BvLit(l ^ r);
                // FIXME: This is problematic if shift width exceeds the size
                case Expr::Shl: return this->BvLit(l.shl(r));
                case Expr::LShr: return this->BvLit(l.lshr(r));
                case Expr::AShr: return this->BvLit(l.ashr(r));
                default:
                    llvm_unreachable("Unknown binary BV expression!");
            }
        }

        switch (kind) {
            case Expr::BvSDiv:
            case Expr::BvUDiv:
            case Expr::BvSRem:
            case Expr::BvURem:
            case Expr::LShr:
            case Expr::AShr:
            case Expr::Shl:
                if (lhs->isZero()) { return lhs; }
                break;
            default:
                break;
        }
    }

    // Give up, cannot fold.
    return nullptr;
}

ExprPtr FoldingExprBuilder::foldBinaryCompare(Expr::ExprKind kind, const ExprPtr& left, const ExprPtr& right)
{
    if (isa<BoolLiteralExpr>(right)) {
        switch (kind) {
            case Expr::Eq:
                // Eq(X, True) --> X
                // Eq(X, False) --> Not(X)
                if (auto blit = dyn_cast<BoolLiteralExpr>(right)) {
                    if (blit->isTrue()) {
                        return left;
                    }

                    return this->Not(left);
                }
                break;
            case Expr::NotEq:
                // NotEq(X, True) --> Not(X)
                // NotEq(X, False) --> X
                if (auto blit = dyn_cast<BoolLiteralExpr>(right)) {
                    if (blit->isTrue()) {
                        return this->Not(left);
                    }

                    return left;
                }
                break;
            default:
                break;
        }
    } else if (isa<BoolLiteralExpr>(left)) {
        // If LHS is a literal, swap the operands around and check through the other way
        return foldBinaryCompare(kind, right, left);
    }

    if (isa<BvLiteralExpr>(left) && isa<BvLiteralExpr>(right)) {
        auto lv = cast<BvLiteralExpr>(left)->getValue();
        auto rv = cast<BvLiteralExpr>(right)->getValue();

        switch (kind) {
            case Expr::BvSLt:   return this->BoolLit(lv.slt(rv));
            case Expr::BvSLtEq: return this->BoolLit(lv.sle(rv));
            case Expr::BvSGt:   return this->BoolLit(lv.sgt(rv));
            case Expr::BvSGtEq: return this->BoolLit(lv.sge(rv));
            case Expr::BvULt:   return this->BoolLit(lv.ult(rv));
            case Expr::BvULtEq: return this->BoolLit(lv.ule(rv));
            case Expr::BvUGt:   return this->BoolLit(lv.ugt(rv));
            case Expr::BvUGtEq: return this->BoolLit(lv.uge(rv));
            case Expr::Eq:      return this->BoolLit(lv == rv);
            case Expr::NotEq:   return this->BoolLit(lv != rv);
            default:
                llvm_unreachable("Unknown bit-vector comparison!");
        }
    } else if (isa<IntLiteralExpr>(left) && isa<IntLiteralExpr>(right)) {
        auto lv = cast<IntLiteralExpr>(left)->getValue();
        auto rv = cast<IntLiteralExpr>(right)->getValue();

        switch (kind) {
            case Expr::Eq:      return this->BoolLit(lv == rv);
            case Expr::NotEq:   return this->BoolLit(lv != rv);
            case Expr::Lt:      return this->BoolLit(lv < rv);
            case Expr::LtEq:    return this->BoolLit(lv <= rv);
            case Expr::Gt:      return this->BoolLit(lv > rv);
            case Expr::GtEq:    return this->BoolLit(lv >= rv);
            default:
                llvm_unreachable("Unknown integer comparison!");
        }
    }

    return nullptr;
}

ExprPtr FoldingExprBuilder::simplifyLtEq(const ExprPtr& left, const ExprPtr& right)
{
    ExprPtr x, other;
    IntLiteralExpr::ValueTy c1;
    IntLiteralExpr::ValueTy c2;

    if (auto rhs = dyn_cast<IntLiteralExpr>(right)) {
        c2 = rhs->getValue();
        other = left;
    } else if (auto lhs = dyn_cast<IntLiteralExpr>(left)) {
        c2 = lhs->getValue();
        other = right;
    } else {
        return LtEqExpr::Create(left, right);
    }

    #define CREATE_RESULT(VAR, LIT)                                                         \
        (other == left ? LtEqExpr::Create((VAR), (LIT)) : LtEqExpr::Create((LIT), (VAR)))

    // X + C1 <= C2 --> X <= C2 - C1
    // C2 <= X + C1 --> C2 - C1 <= X
    if (match(other, m_Add(m_Int(&c1), m_Expr(x)))) {
        return CREATE_RESULT(x, this->IntLit(c2 - c1));
    }

    // X - C1 <= C2 --> X <= C1 + C2
    // C2 <= X - C1 --> C2 + C1 <= X
    if (match(other, m_Sub(m_Expr(x), m_Int(&c1)))) {
        return CREATE_RESULT(x, this->IntLit(c2 + c1));
    }

    return LtEqExpr::Create(left, right);
}

std::unique_ptr<ExprBuilder> gazer::CreateFoldingExprBuilder(GazerContext& context) {
    return std::unique_ptr<ExprBuilder>(new FoldingExprBuilder(context));
}

max_stars_repo_name: ftsrg/gazer

max_issues_repo_name: FTSRG/gazer

max_forks_repo_name: ftsrg/gazer


text:
/**
 *    Copyright (C) 2014 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 <boost/lexical_cast.hpp>
#include <string>

#include "mongo/db/concurrency/fast_map_noalloc.h"
#include "mongo/db/concurrency/lock_mgr_defs.h"
#include "mongo/unittest/unittest.h"

namespace mongo {

    struct TestStruct {

        void initNew(int newId, const std::string& newValue) {
            id = newId;
            value = newValue;
        }

        int id;
        std::string value;
    };

    typedef class FastMapNoAlloc<ResourceId, TestStruct, 6> TestFastMapNoAlloc;

    TEST(FastMapNoAlloc, Empty) {
        TestFastMapNoAlloc map;
        ASSERT(map.empty());

        TestFastMapNoAlloc::Iterator it = map.begin();
        ASSERT(it.finished());
    }

    TEST(FastMapNoAlloc, NotEmpty) {
        TestFastMapNoAlloc map;

        map.insert(ResourceId(RESOURCE_DOCUMENT, 1))->initNew(101, "Item101");
        map.insert(ResourceId(RESOURCE_DOCUMENT, 2))->initNew(102, "Item102");
        ASSERT(!map.empty());

        TestFastMapNoAlloc::Iterator it = map.begin();
        ASSERT(!it.finished());
        ASSERT(!!it);

        ASSERT(it->id == 101);
        ASSERT(it->value == "Item101");

        it.next();
        ASSERT(!it.finished());
        ASSERT(!!it);

        ASSERT(it->id == 102);
        ASSERT(it->value == "Item102");

        // We are at the last element
        it.next();
        ASSERT(it.finished());
        ASSERT(!it);
    }

    TEST(FastMapNoAlloc, FindNonExisting) {
        TestFastMapNoAlloc map;

        ASSERT(!map.find(ResourceId(RESOURCE_DOCUMENT, 0)));
    }

    TEST(FastMapNoAlloc, FindAndRemove) {
        TestFastMapNoAlloc map;

        for (int i = 0; i < 6; i++) {
            map.insert(ResourceId(RESOURCE_DOCUMENT, i))->initNew(
                                                i, "Item" + boost::lexical_cast<std::string>(i));
        }

        for (int i = 0; i < 6; i++) {
            ASSERT(!map.find(ResourceId(RESOURCE_DOCUMENT, i)).finished());

            ASSERT_EQUALS(i, map.find(ResourceId(RESOURCE_DOCUMENT, i))->id);

            ASSERT_EQUALS("Item" + boost::lexical_cast<std::string>(i),
                          map.find(ResourceId(RESOURCE_DOCUMENT, i))->value);
        }

        // Remove a middle entry
        map.find(ResourceId(RESOURCE_DOCUMENT, 2)).remove();
        ASSERT(!map.find(ResourceId(RESOURCE_DOCUMENT, 2)));

        // Remove entry after first
        map.find(ResourceId(RESOURCE_DOCUMENT, 1)).remove();
        ASSERT(!map.find(ResourceId(RESOURCE_DOCUMENT, 1)));

        // Remove entry before last
        map.find(ResourceId(RESOURCE_DOCUMENT, 4)).remove();
        ASSERT(!map.find(ResourceId(RESOURCE_DOCUMENT, 4)));

        // Remove first entry
        map.find(ResourceId(RESOURCE_DOCUMENT, 0)).remove();
        ASSERT(!map.find(ResourceId(RESOURCE_DOCUMENT, 0)));

        // Remove last entry
        map.find(ResourceId(RESOURCE_DOCUMENT, 5)).remove();
        ASSERT(!map.find(ResourceId(RESOURCE_DOCUMENT, 5)));

        // Remove final entry
        map.find(ResourceId(RESOURCE_DOCUMENT, 3)).remove();
        ASSERT(!map.find(ResourceId(RESOURCE_DOCUMENT, 3)));
    }

    TEST(FastMapNoAlloc, RemoveAll) {
        TestFastMapNoAlloc map;
        unordered_map<ResourceId, TestStruct> checkMap;

        for (int i = 1; i <= 6; i++) {
            map.insert(ResourceId(RESOURCE_DOCUMENT, i))->initNew(
                                                i, "Item" + boost::lexical_cast<std::string>(i));

            checkMap[ResourceId(RESOURCE_DOCUMENT, i)].initNew(
                                                i, "Item" + boost::lexical_cast<std::string>(i));
        }

        TestFastMapNoAlloc::Iterator it = map.begin();
        while (!it.finished()) {
            ASSERT_EQUALS(it->id, checkMap[it.key()].id);
            ASSERT_EQUALS(
                "Item" + boost::lexical_cast<std::string>(it->id), checkMap[it.key()].value);

            checkMap.erase(it.key());
            it.remove();
        }

        ASSERT(map.empty());
        ASSERT(checkMap.empty());
    }

} // namespace mongo

max_stars_repo_name: joprice/mongo

max_issues_repo_name: liuaiping/mongo

max_forks_repo_name: liuaiping/mongo