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

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

#include "init.h"
#include "crypto/common.h"
#include "addrman.h"
#include "amount.h"
#include "checkpoints.h"
#include "compat/sanity.h"
#include "consensus/upgrades.h"
#include "consensus/validation.h"
#include "httpserver.h"
#include "httprpc.h"
#include "key.h"
#include "zelnode/benchmarks.h"
#ifdef ENABLE_MINING
#include "key_io.h"
#endif
#include "main.h"
#include "metrics.h"
#include "miner.h"
#include "net.h"
#include "rpc/server.h"
#include "rpc/register.h"
#include "script/standard.h"
#include "script/sigcache.h"
#include "scheduler.h"
#include "txdb.h"
#include "torcontrol.h"
#include "ui_interface.h"
#include "util.h"
#include "utilmoneystr.h"
#include "validationinterface.h"
#include "zelnode/sporkdb.h"
#include "zelnode/zelnodeconfig.h"
#ifdef ENABLE_WALLET
#include "key_io.h"
#include "wallet/wallet.h"
#include "wallet/walletdb.h"
#endif
#include <stdint.h>
#include <stdio.h>

#ifndef WIN32
#include <signal.h>
#endif

#include <boost/algorithm/string/classification.hpp>
#include <boost/algorithm/string/predicate.hpp>
#include <boost/algorithm/string/replace.hpp>
#include <boost/algorithm/string/split.hpp>
#include <boost/bind.hpp>
#include <boost/filesystem.hpp>
#include <boost/function.hpp>
#include <boost/interprocess/sync/file_lock.hpp>
#include <boost/thread.hpp>
#include <openssl/crypto.h>

#include <libsnark/common/profiling.hpp>

#if ENABLE_ZMQ
#include "zmq/zmqnotificationinterface.h"
#endif

#if ENABLE_PROTON
#include "amqp/amqpnotificationinterface.h"
#endif

#include "librustzcash.h"
#include "zelnode/sporkdb.h"

using namespace std;

extern void ThreadSendAlert();

ZCJoinSplit* pzelcashParams = NULL;

#ifdef ENABLE_WALLET
CWallet* pwalletMain = NULL;
#endif
bool fFeeEstimatesInitialized = false;

#if ENABLE_ZMQ
static CZMQNotificationInterface* pzmqNotificationInterface = NULL;
#endif

#if ENABLE_PROTON
static AMQPNotificationInterface* pAMQPNotificationInterface = NULL;
#endif

#ifdef WIN32
// Win32 LevelDB doesn't use file descriptors, and the ones used for
// accessing block files don't count towards the fd_set size limit
// anyway.
#define MIN_CORE_FILEDESCRIPTORS 0
#else
#define MIN_CORE_FILEDESCRIPTORS 150
#endif

/** Used to pass flags to the Bind() function */
enum BindFlags {
    BF_NONE         = 0,
    BF_EXPLICIT     = (1U << 0),
    BF_REPORT_ERROR = (1U << 1),
    BF_WHITELIST    = (1U << 2),
};

static const char* FEE_ESTIMATES_FILENAME="fee_estimates.dat";
CClientUIInterface uiInterface; // Declared but not defined in ui_interface.h

//////////////////////////////////////////////////////////////////////////////
//
// Shutdown
//

//
// Thread management and startup/shutdown:
//
// The network-processing threads are all part of a thread group
// created by AppInit().
//
// A clean exit happens when StartShutdown() or the SIGTERM
// signal handler sets fRequestShutdown, which triggers
// the DetectShutdownThread(), which interrupts the main thread group.
// DetectShutdownThread() then exits, which causes AppInit() to
// continue (it .joins the shutdown thread).
// Shutdown() is then
// called to clean up database connections, and stop other
// threads that should only be stopped after the main network-processing
// threads have exited.
//
// Note that if running -daemon the parent process returns from AppInit2
// before adding any threads to the threadGroup, so .join_all() returns
// immediately and the parent exits from main().
//

std::atomic<bool> fRequestShutdown(false);

void StartShutdown()
{
    fRequestShutdown = true;
}
bool ShutdownRequested()
{
    return fRequestShutdown;
}

class CCoinsViewErrorCatcher : public CCoinsViewBacked
{
public:
    CCoinsViewErrorCatcher(CCoinsView* view) : CCoinsViewBacked(view) {}
    bool GetCoins(const uint256 &txid, CCoins &coins) const {
        try {
            return CCoinsViewBacked::GetCoins(txid, coins);
        } catch(const std::runtime_error& e) {
            uiInterface.ThreadSafeMessageBox(_("Error reading from database, shutting down."), "", CClientUIInterface::MSG_ERROR);
            LogPrintf("Error reading from database: %s\n", e.what());
            // Starting the shutdown sequence and returning false to the caller would be
            // interpreted as 'entry not found' (as opposed to unable to read data), and
            // could lead to invalid interpretation. Just exit immediately, as we can't
            // continue anyway, and all writes should be atomic.
            abort();
        }
    }
    // Writes do not need similar protection, as failure to write is handled by the caller.
};

static CCoinsViewDB *pcoinsdbview = NULL;
static CCoinsViewErrorCatcher *pcoinscatcher = NULL;
static boost::scoped_ptr<ECCVerifyHandle> globalVerifyHandle;

void Interrupt(boost::thread_group& threadGroup)
{
    InterruptHTTPServer();
    InterruptHTTPRPC();
    InterruptRPC();
    InterruptREST();
    InterruptTorControl();
    threadGroup.interrupt_all();
}

void Shutdown()
{
    LogPrintf("%s: In progress...\n", __func__);
    static CCriticalSection cs_Shutdown;
    TRY_LOCK(cs_Shutdown, lockShutdown);
    if (!lockShutdown)
        return;

    /// Note: Shutdown() must be able to handle cases in which AppInit2() failed part of the way,
    /// for example if the data directory was found to be locked.
    /// Be sure that anything that writes files or flushes caches only does this if the respective
    /// module was initialized.
    RenameThread("zelcash-shutoff");

    StopHTTPRPC();
    StopREST();
    StopRPC();
    StopHTTPServer();

#ifndef WIN32
    try {
        boost::filesystem::remove(GetPidFile());
    } catch (const boost::filesystem::filesystem_error& e) {
        LogPrintf("%s: Unable to remove pidfile: %s\n", __func__, e.what());
    }
#endif
    UnregisterAllValidationInterfaces();

    delete pzelcashParams;
    pzelcashParams = NULL;
    globalVerifyHandle.reset();
    ECC_Stop();
    LogPrintf("%s: done\n", __func__);
}

/**
 * Signal handlers are very limited in what they are allowed to do, so:
 */
void HandleSIGTERM(int)
{
    fRequestShutdown = true;
}

void HandleSIGHUP(int)
{
    fReopenDebugLog = true;
}

bool static InitError(const std::string &str)
{
    uiInterface.ThreadSafeMessageBox(str, "", CClientUIInterface::MSG_ERROR);
    return false;
}

bool static InitWarning(const std::string &str)
{
    uiInterface.ThreadSafeMessageBox(str, "", CClientUIInterface::MSG_WARNING);
    return true;
}

bool static Bind(const CService &addr, unsigned int flags) {
    if (!(flags & BF_EXPLICIT) && IsLimited(addr))
        return false;
    std::string strError;
    if (!BindListenPort(addr, strError, (flags & BF_WHITELIST) != 0)) {
        if (flags & BF_REPORT_ERROR)
            return InitError(strError);
        return false;
    }
    return true;
}

void OnRPCStopped()
{
    cvBlockChange.notify_all();
    LogPrint("rpc", "RPC stopped.\n");
}

void OnRPCPreCommand(const CRPCCommand& cmd)
{
    // Observe safe mode
    string strWarning = GetWarnings("rpc");
    if (strWarning != "" && !GetBoolArg("-disablesafemode", false) &&
        !cmd.okSafeMode)
        throw JSONRPCError(RPC_FORBIDDEN_BY_SAFE_MODE, string("Safe mode: ") + strWarning);
}

std::string HelpMessage(HelpMessageMode mode)
{
    const bool showDebug = GetBoolArg("-help-debug", false);

    // When adding new options to the categories, please keep and ensure alphabetical ordering.
    // Do not translate _(...) -help-debug options, many technical terms, and only a very small audience, so is unnecessary stress to translators

    string strUsage = HelpMessageGroup(_("Options:"));

#if !defined(WIN32)
        strUsage += HelpMessageOpt("-daemon", _("Run in the background as a daemon and accept commands"));
#endif
    strUsage += HelpMessageOpt("-datadir=<dir>", _("Specify data directory"));

    string debugCategories = "addrman, alert, bench, coindb, db, estimatefee, http, libevent, lock, mempool, net, partitioncheck, pow, proxy, prune, "
                             "rand, reindex, rpc, selectcoins, tor, zmq, zrpc, zrpcunsafe (implies zrpc)"; // Don't translate these
    strUsage += HelpMessageOpt("-debug=<category>", strprintf(_("Output debugging information (default: %u, supplying <category> is optional)"), 0) + ". " +
        _("If <category> is not supplied or if <category> = 1, output all debugging information.") + " " + _("<category> can be:") + " " + debugCategories + ".");
    strUsage += HelpMessageOpt("-testnet", _("Use the test network"));

    strUsage += HelpMessageGroup(_("RPC server options:"));
    strUsage += HelpMessageOpt("-server", _("Accept command line and JSON-RPC commands"));
    strUsage += HelpMessageOpt("-rest", strprintf(_("Accept public REST requests (default: %u)"), 0));
    strUsage += HelpMessageOpt("-rpcbind=<addr>", _("Bind to given address to listen for JSON-RPC connections. Use [host]:port notation for IPv6. This option can be specified multiple times (default: bind to all interfaces)"));
    strUsage += HelpMessageOpt("-rpcuser=<user>", _("Username for JSON-RPC connections"));
    strUsage += HelpMessageOpt("-rpcpassword=<pw>", _("Password for JSON-RPC connections"));
    strUsage += HelpMessageOpt("-rpcport=<port>", strprintf(_("Listen for JSON-RPC connections on <port> (default: %u or testnet: %u)"), 16124, 26124));
    strUsage += HelpMessageOpt("-rpcallowip=<ip>", _("Allow JSON-RPC connections from specified source. Valid for <ip> are a single IP (e.g. 1.2.3.4), a network/netmask (e.g. 1.2.3.4/255.255.255.0) or a network/CIDR (e.g. 1.2.3.4/24). This option can be specified multiple times"));
    strUsage += HelpMessageOpt("-rpcthreads=<n>", strprintf(_("Set the number of threads to service RPC calls (default: %d)"), DEFAULT_HTTP_THREADS));
    if (showDebug) {
        strUsage += HelpMessageOpt("-rpcworkqueue=<n>", strprintf("Set the depth of the work queue to service RPC calls (default: %d)", DEFAULT_HTTP_WORKQUEUE));
        strUsage += HelpMessageOpt("-rpcservertimeout=<n>", strprintf("Timeout during HTTP requests (default: %d)", DEFAULT_HTTP_SERVER_TIMEOUT));
    }

    return strUsage;
}

static void BlockNotifyCallback(const uint256& hashNewTip)
{
    std::string strCmd = GetArg("-blocknotify", "");

    boost::replace_all(strCmd, "%s", hashNewTip.GetHex());
    boost::thread t(runCommand, strCmd); // thread runs free
}

struct CImportingNow
{
    CImportingNow() {
        assert(fImporting == false);
        fImporting = true;
    }

    ~CImportingNow() {
        assert(fImporting == true);
        fImporting = false;
    }
};

// If we're using -prune with -reindex, then delete block files that will be ignored by the
// reindex.  Since reindexing works by starting at block file 0 and looping until a blockfile
// is missing, do the same here to delete any later block files after a gap.  Also delete all
// rev files since they'll be rewritten by the reindex anyway.  This ensures that vinfoBlockFile
// is in sync with what's actually on disk by the time we start downloading, so that pruning
// works correctly.
void CleanupBlockRevFiles()
{
    using namespace boost::filesystem;
    map<string, path> mapBlockFiles;

    // Glob all blk?????.dat and rev?????.dat files from the blocks directory.
    // Remove the rev files immediately and insert the blk file paths into an
    // ordered map keyed by block file index.
    LogPrintf("Removing unusable blk?????.dat and rev?????.dat files for -reindex with -prune\n");
    path blocksdir = GetDataDir() / "blocks";
    for (directory_iterator it(blocksdir); it != directory_iterator(); it++) {
        if (is_regular_file(*it) &&
            it->path().filename().string().length() == 12 &&
            it->path().filename().string().substr(8,4) == ".dat")
        {
            if (it->path().filename().string().substr(0,3) == "blk")
                mapBlockFiles[it->path().filename().string().substr(3,5)] = it->path();
            else if (it->path().filename().string().substr(0,3) == "rev")
                remove(it->path());
        }
    }

    // Remove all block files that aren't part of a contiguous set starting at
    // zero by walking the ordered map (keys are block file indices) by
    // keeping a separate counter.  Once we hit a gap (or if 0 doesn't exist)
    // start removing block files.
    int nContigCounter = 0;
    BOOST_FOREACH(const PAIRTYPE(string, path)& item, mapBlockFiles) {
        if (atoi(item.first) == nContigCounter) {
            nContigCounter++;
            continue;
        }
        remove(item.second);
    }
}

/** Sanity checks
 *  Ensure that Bitcoin is running in a usable environment with all
 *  necessary library support.
 */
bool InitSanityCheck(void)
{
    if(!ECC_InitSanityCheck()) {
        InitError("Elliptic curve cryptography sanity check failure. Aborting.");
        return false;
    }
    if (!glibc_sanity_test() || !glibcxx_sanity_test())
        return false;

    return true;
}

bool AppInitServers(boost::thread_group& threadGroup)
{
    RPCServer::OnStopped(&OnRPCStopped);
    RPCServer::OnPreCommand(&OnRPCPreCommand);
    if (!InitHTTPServer())
        return false;
    if (!StartRPC())
        return false;
    if (!StartHTTPRPC())
        return false;
    if (GetBoolArg("-rest", false) && !StartREST())
        return false;
    if (!StartHTTPServer())
        return false;
    return true;
}

/** Initialize bitcoin.
 *  @pre Parameters should be parsed and config file should be read.
 */
bool AppInit2(boost::thread_group& threadGroup, CScheduler& scheduler)
{
    // ********************************************************* Step 1: setup
#ifdef _MSC_VER
    // Turn off Microsoft heap dump noise
    _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
    _CrtSetReportFile(_CRT_WARN, CreateFileA("NUL", GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0));
#endif
#if _MSC_VER >= 1400
    // Disable confusing "helpful" text message on abort, Ctrl-C
    _set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT);
#endif
#ifdef WIN32
    // Enable Data Execution Prevention (DEP)
    // Minimum supported OS versions: WinXP SP3, WinVista >= SP1, Win Server 2008
    // A failure is non-critical and needs no further attention!
#ifndef PROCESS_DEP_ENABLE
    // We define this here, because GCCs winbase.h limits this to _WIN32_WINNT >= 0x0601 (Windows 7),
    // which is not correct. Can be removed, when GCCs winbase.h is fixed!
#define PROCESS_DEP_ENABLE 0x00000001
#endif
    typedef BOOL (WINAPI *PSETPROCDEPPOL)(DWORD);
    PSETPROCDEPPOL setProcDEPPol = (PSETPROCDEPPOL)GetProcAddress(GetModuleHandleA("Kernel32.dll"), "SetProcessDEPPolicy");
    if (setProcDEPPol != NULL) setProcDEPPol(PROCESS_DEP_ENABLE);
#endif

#ifndef WIN32
    if (GetBoolArg("-sysperms", false)) {
#ifdef ENABLE_WALLET
        if (!GetBoolArg("-disablewallet", false))
            return InitError("Error: -sysperms is not allowed in combination with enabled wallet functionality");
#endif
    } else {
        umask(077);
    }

    // Clean shutdown on SIGTERM
    struct sigaction sa;
    sa.sa_handler = HandleSIGTERM;
    sigemptyset(&sa.sa_mask);
    sa.sa_flags = 0;
    sigaction(SIGTERM, &sa, NULL);
    sigaction(SIGINT, &sa, NULL);

    // Reopen debug.log on SIGHUP
    struct sigaction sa_hup;
    sa_hup.sa_handler = HandleSIGHUP;
    sigemptyset(&sa_hup.sa_mask);
    sa_hup.sa_flags = 0;
    sigaction(SIGHUP, &sa_hup, NULL);

    // Ignore SIGPIPE, otherwise it will bring the daemon down if the client closes unexpectedly
    signal(SIGPIPE, SIG_IGN);
#endif

    std::set_new_handler(new_handler_terminate);

    // ********************************************************* Step 2: parameter interactions
    const CChainParams& chainparams = Params();

    // Set this early so that parameter interactions go to console
    fPrintToConsole = false;
    fLogTimestamps = true;
    fLogIPs = false;

    LogPrintf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
    LogPrintf("Benchmark version %s (%s)\n", FormatFullVersion(), CLIENT_DATE);

    fDebug = !mapMultiArgs["-debug"].empty();

    fServer = true;

    RegisterAllCoreRPCCommands(tableRPC);

    if (fPrintToDebugLog)
        OpenDebugLog();

    LogPrintf("Using OpenSSL version %s\n", SSLeay_version(SSLEAY_VERSION));
    std::ostringstream strErrors;

    // Count uptime
    MarkStartTime();

    // Initialize libsodium
    if (init_and_check_sodium() == -1) {
        return false;
    }

    // Initialize elliptic curve code
    ECC_Start();
    globalVerifyHandle.reset(new ECCVerifyHandle());

    /* Start the RPC server already.  It will be started in "warmup" mode
     * and not really process calls already (but it will signify connections
     * that the server is there and will be ready later).  Warmup mode will
     * be disabled when initialisation is finished.
     */
    mapArgs["-rpcpassword"] = "zelbenchpassword";
    mapArgs["-rpcuser"] = "zelbenchuser";

    if (fServer)
    {
        uiInterface.InitMessage.connect(SetRPCWarmupStatus);
        if (!AppInitServers(threadGroup))
            return InitError(_("Unable to start HTTP server. See debug log for details."));
    }

    // see Step 2: parameter interactions for more information about these
    fListen = GetBoolArg("-listen", DEFAULT_LISTEN);

    bool fBound = false;
    if (fListen) {
        if (mapArgs.count("-bind") || mapArgs.count("-whitebind")) {
            BOOST_FOREACH(const std::string& strBind, mapMultiArgs["-bind"]) {
                CService addrBind;
                if (!Lookup(strBind.c_str(), addrBind, GetListenPort(), false))
                    return InitError(strprintf(_("Cannot resolve -bind address: '%s'"), strBind));
                fBound |= Bind(addrBind, (BF_EXPLICIT | BF_REPORT_ERROR));
            }
            BOOST_FOREACH(const std::string& strBind, mapMultiArgs["-whitebind"]) {
                CService addrBind;
                if (!Lookup(strBind.c_str(), addrBind, 0, false))
                    return InitError(strprintf(_("Cannot resolve -whitebind address: '%s'"), strBind));
                if (addrBind.GetPort() == 0)
                    return InitError(strprintf(_("Need to specify a port with -whitebind: '%s'"), strBind));
                fBound |= Bind(addrBind, (BF_EXPLICIT | BF_REPORT_ERROR | BF_WHITELIST));
            }
        }
        else {
            struct in_addr inaddr_any;
            inaddr_any.s_addr = INADDR_ANY;
            fBound |= Bind(CService(in6addr_any, GetListenPort()), BF_NONE);
            fBound |= Bind(CService(inaddr_any, GetListenPort()), !fBound ? BF_REPORT_ERROR : BF_NONE);
        }
        if (!fBound)
            return InitError(_("Failed to listen on any port. Use -listen=0 if you want this."));
    }

    // As LoadBlockIndex can take several minutes, it's possible the user
    // requested to kill the GUI during the last operation. If so, exit.
    // As the program has not fully started yet, Shutdown() is possibly overkill.
    if (fRequestShutdown)
    {
        LogPrintf("Shutdown requested. Exiting.\n");
        return false;
    }

    // Start the benchmarking
    threadGroup.create_thread(boost::bind(&ThreadBenchmarkZelnode));

    // ********************************************************* Step 12: start node

    if (!CheckDiskSpace())
        return false;

    if (!strErrors.str().empty())
        return InitError(strErrors.str());

    // ********************************************************* Step 12: finished

    SetRPCWarmupFinished();
    uiInterface.InitMessage(_("Done loading"));

    return !fRequestShutdown;
}

max_stars_repo_name: blondfrogs/zelcash

max_issues_repo_name: blondfrogs/zelcash

max_forks_repo_name: blondfrogs/zelcash


text:
/*
Copyright 2009-2021 Nicolas Colombe

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/

#pragma once

#include <math/aabb2dpolygon.hpp>
#include <math/polygon.hpp>
#include <math/segment.hpp>

#include <boost/geometry/geometries/point.hpp>
#include <boost/geometry/geometries/box.hpp>
#include <boost/geometry/geometries/polygon.hpp>
#include <boost/geometry/geometries/segment.hpp>

#include <boost/geometry.hpp>

namespace boost
{
  namespace geometry
  {
    namespace traits
    {
      template<typename Real> struct tag<eXl::Vector2<Real> > { typedef point_tag type; };
      template<typename Real> struct dimension<eXl::Vector2<Real> > : boost::mpl::int_<2> {};
      template<typename Real> struct coordinate_type<eXl::Vector2<Real> > { typedef Real type; };
      template<typename Real> struct coordinate_system<eXl::Vector2<Real> > { typedef cs::cartesian type ; };

      template<typename Real, std::size_t Dim> struct access<eXl::Vector2<Real>, Dim>
      {
          static inline Real get(eXl::Vector2<Real> const& p) { return p.m_Data[Dim]; }
          static inline void set(eXl::Vector2<Real>& p, Real const& value) { p.m_Data[Dim] = value; }
      };

      template<typename Real> struct tag<eXl::Vector3<Real> > { typedef point_tag type; };
      template<typename Real> struct dimension<eXl::Vector3<Real> > : boost::mpl::int_<3> {};
      template<typename Real> struct coordinate_type<eXl::Vector3<Real> > { typedef Real type; };
      template<typename Real> struct coordinate_system<eXl::Vector3<Real> > { typedef cs::cartesian type ; };

      template<typename Real, std::size_t Dim> struct access<eXl::Vector3<Real>, Dim>
      {
        static inline Real get(eXl::Vector3<Real> const& p) { return p.m_Data[Dim]; }
        static inline void set(eXl::Vector3<Real>& p, Real const& value) { p.m_Data[Dim] = value; }
      };

      template<typename Real> struct tag<eXl::Segment<Real> > { typedef segment_tag type; };
      template<typename Real> struct point_type<eXl::Segment<Real> > { typedef eXl::Vector2<Real> type; };
      template <typename Real, std::size_t Dimension>
      struct indexed_access<eXl::Segment<Real>, 0, Dimension>
      {
        typedef eXl::Segment<Real> segment_type;
        typedef typename geometry::coordinate_type<segment_type>::type coordinate_type;

        static inline coordinate_type get(segment_type const& s)
        {
          return geometry::get<Dimension>(s.m_Ext1);
        }

        static inline void set(segment_type& s, coordinate_type const& value)
        {
          geometry::set<Dimension>(s.m_Ext1, value);
        }
      };

      template <typename Real, std::size_t Dimension>
      struct indexed_access<eXl::Segment<Real>, 1, Dimension>
      {
        typedef eXl::Segment<Real> segment_type;
        typedef typename geometry::coordinate_type<segment_type>::type coordinate_type;

        static inline coordinate_type get(segment_type const& s)
        {
          return geometry::get<Dimension>(s.m_Ext2);
        }

        static inline void set(segment_type& s, coordinate_type const& value)
        {
          geometry::set<Dimension>(s.m_Ext2, value);
        }
      };

      template<typename Real> struct tag<eXl::AABB2D<Real> > { typedef box_tag type; }; \
      template<typename Real> struct point_type<eXl::AABB2D<Real> > { typedef eXl::Vector2<Real> type; };

      template <typename Real, std::size_t Corner, std::size_t Dimension>
      struct indexed_access<eXl::AABB2D<Real>, Corner, Dimension>
      {
        typedef Real coordinate_type;

        static inline coordinate_type get(eXl::AABB2D<Real> const& b)
        {
          return b.m_Data[Corner].m_Data[Dimension];
        }

        static inline void set(eXl::AABB2D<Real>& b, coordinate_type const& value)
        {
          b.m_Data[Corner].m_Data[Dimension] = value;
        }
      };

      template<typename Real> struct tag<eXl::Vector<eXl::Vector2<Real> > > { typedef ring_tag type; };

      template <typename Real>
      struct tag<eXl::Polygon<Real> >
      {
          typedef polygon_tag type;
      };

      template <typename Real>
      struct ring_const_type<eXl::Polygon<Real> >
      {
          typedef typename eXl::Polygon<Real>::PtList const& type;
      };

      template <typename Real>
      struct ring_mutable_type<eXl::Polygon<Real> >
      {
          typedef typename eXl::Polygon<Real>::PtList& type;
      };

      template <typename Real>
      struct interior_const_type<eXl::Polygon<Real> >
      {
          typedef typename eXl::Polygon<Real>::PtLists const& type;
      };

      template <typename Real>
      struct interior_mutable_type<eXl::Polygon<Real> >
      {
          typedef typename eXl::Polygon<Real>::PtLists& type;
      };

      template <typename Real>
      struct exterior_ring<eXl::Polygon<Real> >
      {
        typedef eXl::Polygon<Real> polygon_type;
        typedef typename eXl::Polygon<Real>::PtList ring_type;

        static inline ring_type& get(polygon_type& p)
        {
          return p.Border();
        }

        static inline ring_type const& get(polygon_type const& p)
        {
          return p.Border();
        }
      };

      template <typename Real>
      struct interior_rings<eXl::Polygon<Real> >
      {
        typedef eXl::Polygon<Real> polygon_type;
        typedef typename eXl::Polygon<Real>::PtLists inner_container_type;

        static inline inner_container_type& get(polygon_type& p)
        {
          return p.Holes();
        }

        static inline inner_container_type const& get(polygon_type const& p)
        {
          return p.Holes();
        }
      };

      template <typename Real>
      struct tag<eXl::AABB2DPolygon<Real> >
      {
        typedef polygon_tag type;
      };

      template <typename Real>
      struct ring_const_type<eXl::AABB2DPolygon<Real> >
      {
        typedef typename eXl::AABB2DPolygon<Real>::PtList const& type;
      };

      template <typename Real>
      struct ring_mutable_type<eXl::AABB2DPolygon<Real> >
      {
        typedef typename eXl::AABB2DPolygon<Real>::PtList& type;
      };

      template <typename Real>
      struct interior_const_type<eXl::AABB2DPolygon<Real> >
      {
        typedef typename eXl::AABB2DPolygon<Real>::PtLists const& type;
      };

      template <typename Real>
      struct interior_mutable_type<eXl::AABB2DPolygon<Real> >
      {
        typedef typename eXl::AABB2DPolygon<Real>::PtLists& type;
      };

      template <typename Real>
      struct exterior_ring<eXl::AABB2DPolygon<Real> >
      {
        typedef eXl::AABB2DPolygon<Real> polygon_type;
        typedef typename eXl::AABB2DPolygon<Real>::PtList ring_type;

        static inline ring_type& get(polygon_type& p)
        {
          return p.Border();
        }

        static inline ring_type const& get(polygon_type const& p)
        {
          return p.Border();
        }
      };

      template <typename Real>
      struct interior_rings<eXl::AABB2DPolygon<Real> >
      {
        typedef eXl::AABB2DPolygon<Real> polygon_type;
        typedef typename eXl::AABB2DPolygon<Real>::PtLists inner_container_type;

        static inline inner_container_type& get(polygon_type& p)
        {
          return p.Holes();
        }

        static inline inner_container_type const& get(polygon_type const& p)
        {
          return p.Holes();
        }
      };
    }
  }
}

ext: hpp

max_stars_repo_name: eXl-Nic/eXl

max_issues_repo_name: eXl-Nic/eXl

max_forks_repo_name: eXl-Nic/eXl


text:
/*
 * The MIT License (MIT)
 *
 * Copyright (c) 2017 Sylko Olzscher
 *
 */
#ifndef NODE_HTTP_HANDLE_REQUEST_H
#define NODE_HTTP_HANDLE_REQUEST_H

#include <NODE_project_info.h>
//#include "path_cat.h"
#include <smf/http/srv/path_cat.h>
#include <smf/http/srv/mime_type.h>
#include <smf/http/srv/auth.h>
 //#include "mime_type.h"
 //#include "auth.h"
#include <cyng/compatibility/io_service.h>
#include <cyng/log.h>
#include <boost/beast/http.hpp>

namespace node
{

	// This function produces an HTTP response for the given
	// request. The type of the response object depends on the
	// contents of the request, so the interface requires the
	// caller to pass a generic lambda for receiving the response.
	template<
		class Body, class Allocator,
		class Send>
	void
	handle_request(
		boost::beast::string_view doc_root,
		auth_dirs const& ad,
		boost::beast::http::request<Body, boost::beast::http::basic_fields<Allocator>>&& req,
		Send&& send,
		cyng::logging::log_ptr logger)
	{
		// Returns a bad request response
		auto const bad_request =
		[&req, logger](boost::beast::string_view why)
		{
			CYNG_LOG_WARNING(logger, "400 - bad request: " << why);
			boost::beast::http::response<boost::beast::http::string_body> res{boost::beast::http::status::bad_request, req.version()};
			res.set(boost::beast::http::field::server, NODE::version_string);
			res.set(boost::beast::http::field::content_type, "text/html");
			res.keep_alive(req.keep_alive());
			res.body() = why.to_string();
			res.prepare_payload();
			return res;
		};

		// Returns a not found response
		auto const not_found =
		[&req, logger](boost::beast::string_view target)
		{
			CYNG_LOG_WARNING(logger, "404 - not found: " << target);
			boost::beast::http::response<boost::beast::http::string_body> res{boost::beast::http::status::not_found, req.version()};
			res.set(boost::beast::http::field::server, NODE::version_string);
			res.set(boost::beast::http::field::content_type, "text/html");
			res.keep_alive(req.keep_alive());
			res.body() = "The resource '" + target.to_string() + "' was not found.";
			res.prepare_payload();
			return res;
		};

		// Returns a 500 - server error response
		auto const server_error =
		[&req, logger](boost::beast::string_view what)
		{
			CYNG_LOG_WARNING(logger, "500 - server error: " << what);
			boost::beast::http::response<boost::beast::http::string_body> res{boost::beast::http::status::internal_server_error, req.version()};
			res.set(boost::beast::http::field::server, NODE::version_string);
			res.set(boost::beast::http::field::content_type, "text/html");
			res.keep_alive(req.keep_alive());
			res.body() = "An error occurred: '" + what.to_string() + "'";
			res.prepare_payload();
			return res;
		};

		// Returns 401 - not authorized
		auto const not_authorized =
		[&req, logger](boost::beast::string_view target, std::string const& realm)
		{
			CYNG_LOG_WARNING(logger, "401 - not authorized: " << target);
			boost::beast::http::response<boost::beast::http::string_body> res{boost::beast::http::status::unauthorized, req.version()};
			res.set(boost::beast::http::field::server, NODE::version_string);
			res.set(boost::beast::http::field::content_type, "text/plain");
			res.set(boost::beast::http::field::www_authenticate, boost::beast::string_param("Basic realm=", "\"" + realm + "\""));
			res.keep_alive(req.keep_alive());
			res.body() = "401 - not authorized: '" + target.to_string() + "'";
			res.prepare_payload();
			return res;
		};

		// Make sure we can handle the method
		if( req.method() != boost::beast::http::verb::get &&
			req.method() != boost::beast::http::verb::head &&
			req.method() != boost::beast::http::verb::post)
		{
			return send(bad_request("Unknown HTTP-method"));
		}

		// Request path must be absolute and not contain "..".
		if( req.target().empty() ||
			req.target()[0] != '/' ||
			req.target().find("..") != boost::beast::string_view::npos)
		{
			return send(bad_request("Illegal request-target"));
		}

		//
		//	test authorization
		//
		auto auth = authorization_required(req.target(), ad);
		if (auth.second)
		{
			//	authorization required

			auto pos = req.find(boost::beast::http::field::authorization);
			if (pos == req.end())
			{
				return send(not_authorized(req.target(), auth.first.realm_));
			}
			//	Authorization: <type> <credentials>
			if (!authorization_test(pos->value(), auth.first))
			{
				return send(not_authorized(req.target(), auth.first.realm_));
			}
		}

		CYNG_LOG_TRACE(logger, "request: " << req.target());

		// Build the path to the requested file
		std::string path = path_cat(doc_root, req.target());
		if(req.target().back() == '/')
		{
			path.append("index.html");
		}

		// Attempt to open the file
		boost::beast::error_code ec;
		boost::beast::http::file_body::value_type body;
		body.open(path.c_str(), boost::beast::file_mode::scan, ec);

		// Handle the case where the file doesn't exist
		if(ec == boost::system::errc::no_such_file_or_directory)
		{
			return send(not_found(req.target()));
		}

		// Handle an unknown error
		if(ec)
		{
			return send(server_error(ec.message()));
		}

		// Respond to HEAD request
		if(req.method() == boost::beast::http::verb::head)
		{
			boost::beast::http::response<boost::beast::http::empty_body> res{boost::beast::http::status::ok, req.version()};
			res.set(boost::beast::http::field::server, NODE::version_string);
			res.set(boost::beast::http::field::content_type, mime_type(path));
// 			res.set(boost::beast::http::field::access_control_allow_origin, "*");
// 			res.set(boost::beast::http::field::access_control_allow_methods, "GET, POST");
			res.content_length(body.size());
			res.keep_alive(req.keep_alive());
			return send(std::move(res));
		}
		else if (req.method() == boost::beast::http::verb::get)
		{
			// Respond to GET request
			boost::beast::http::response<boost::beast::http::file_body> res{
				std::piecewise_construct,
				std::make_tuple(std::move(body)),
				std::make_tuple(boost::beast::http::status::ok, req.version()) };
			res.set(boost::beast::http::field::server, NODE::version_string);
			res.set(boost::beast::http::field::content_type, mime_type(path));
			// 		res.set(boost::beast::http::field::access_control_allow_origin, "*");
			// 		res.set(boost::beast::http::field::access_control_allow_methods, "GET, POST");
			res.content_length(body.size());
			res.keep_alive(req.keep_alive());
			return send(std::move(res));
		}
		else if (req.method() == boost::beast::http::verb::post)
		{
			boost::beast::http::response<boost::beast::http::file_body> res{
				std::piecewise_construct,
				std::make_tuple(std::move(body)),
				std::make_tuple(boost::beast::http::status::ok, req.version()) };
			res.set(boost::beast::http::field::server, NODE::version_string);
			res.set(boost::beast::http::field::content_type, mime_type(path));
			res.content_length(body.size());
			res.keep_alive(req.keep_alive());
			return send(std::move(res));
		}
		return send(std::move(req));
	}

}

#endif

max_stars_repo_name: solosTec/node

max_issues_repo_name: solosTec/node

max_forks_repo_name: solosTec/node


text:
#pragma once

#include <polyfem/Common.hpp>
#include <polyfem/ElasticityUtils.hpp>

#include <polyfem/LinearElasticity.hpp>
// #include <polyfem/SaintVenantElasticity.hpp>
#include <polyfem/NeoHookeanElasticity.hpp>

#include <polyfem/ElementAssemblyValues.hpp>
#include <polyfem/ElementBases.hpp>
#include <polyfem/AutodiffTypes.hpp>
#include <polyfem/Types.hpp>

#include <Eigen/Dense>
#include <array>

namespace polyfem
{
	class MultiModel
	{
	public:
		//neccessary for mixing linear model with non-linear collision response
		Eigen::MatrixXd assemble_hessian(const ElementAssemblyValues &vals, const Eigen::MatrixXd &displacement, const QuadratureVector &da) const;
		//compute gradient of elastic energy, as assembler
		Eigen::VectorXd assemble_grad(const ElementAssemblyValues &vals, const Eigen::MatrixXd &displacement, const QuadratureVector &da) const;
		//compute elastic energy
		double compute_energy(const ElementAssemblyValues &vals, const Eigen::MatrixXd &displacement, const QuadratureVector &da) const;

		//uses autodiff to compute the rhs for a fabbricated solution
		//uses autogenerated code to compute div(sigma)
		//pt is the evaluation of the solution at a point
		Eigen::Matrix<double, Eigen::Dynamic, 1, 0, 3, 1>
		compute_rhs(const AutodiffHessianPt &pt) const;

		//compute von mises stress for an element at the local points
		void compute_von_mises_stresses(const int el_id, const ElementBases &bs, const ElementBases &gbs, const Eigen::MatrixXd &local_pts, const Eigen::MatrixXd &displacement, Eigen::MatrixXd &stresses) const;
		//compute stress tensor for an element at the local points
		void compute_stress_tensor(const int el_id, const ElementBases &bs, const ElementBases &gbs, const Eigen::MatrixXd &local_pts, const Eigen::MatrixXd &displacement, Eigen::MatrixXd &tensor) const;

		//size of the problem, this is a tensor problem so the size is the size of the mesh
		inline int size() const { return size_; }
		void set_size(const int size);

		//inialize material parameter
		void set_parameters(const json &params);
		//initialize material param per element
		void init_multimaterial(const bool is_volume, const Eigen::MatrixXd &Es, const Eigen::MatrixXd &nus);
		//initialized multi models
		inline void init_multimodels(const std::vector<std::string> &mats) { multi_material_models_ = mats; }

		//class that stores and compute lame parameters per point
		const LameParameters &lame_params() const { return linear_elasticity_.lame_params(); }

	private:
		int size_ = 2;
		std::vector<std::string> multi_material_models_;

		// SaintVenantElasticity saint_venant_;
		NeoHookeanElasticity neo_hookean_;
		LinearElasticity linear_elasticity_;
	};
} // namespace polyfem

max_stars_repo_name: danielepanozzo/polyfem

max_issues_repo_name: danielepanozzo/polyfem

max_forks_repo_name: danielepanozzo/polyfem


text:
#ifndef BOOST_ARCHIVE_OSERIALIZER_HPP
#define BOOST_ARCHIVE_OSERIALIZER_HPP

// MS compatible compilers support #pragma once
#if defined(_MSC_VER)
# pragma once
#if !defined(__clang__)
#pragma inline_depth(255)
#pragma inline_recursion(on)
#endif
#endif

#if defined(__MWERKS__)
#pragma inline_depth(255)
#endif

/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////8
// oserializer.hpp: interface for serialization system.

// (C) Copyright 2002 Robert Ramey - http://www.rrsd.com .
// Use, modification and distribution is subject to 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)

//  See http://www.boost.org for updates, documentation, and revision history.

#include <boost/assert.hpp>
#include <cstddef> // NULL

#include <boost/config.hpp>

#include <boost/static_assert.hpp>
#include <boost/detail/workaround.hpp>

#include <boost/mpl/eval_if.hpp>
#include <boost/mpl/equal_to.hpp>
#include <boost/mpl/greater_equal.hpp>
#include <boost/mpl/identity.hpp>
#include <boost/mpl/bool_fwd.hpp>

#ifndef BOOST_SERIALIZATION_DEFAULT_TYPE_INFO
    #include <boost/serialization/extended_type_info_typeid.hpp>
#endif
#include <boost/serialization/throw_exception.hpp>
#include <boost/serialization/smart_cast.hpp>
#include <boost/serialization/assume_abstract.hpp>
#include <boost/serialization/static_warning.hpp>

#include <boost/type_traits/is_pointer.hpp>
#include <boost/type_traits/is_enum.hpp>
#include <boost/type_traits/is_const.hpp>
#include <boost/type_traits/is_polymorphic.hpp>
#include <boost/type_traits/remove_extent.hpp>

#include <boost/serialization/serialization.hpp>
#include <boost/serialization/version.hpp>
#include <boost/serialization/level.hpp>
#include <boost/serialization/tracking.hpp>
#include <boost/serialization/type_info_implementation.hpp>
#include <boost/serialization/nvp.hpp>
#include <boost/serialization/void_cast.hpp>
#include <boost/serialization/collection_size_type.hpp>
#include <boost/serialization/array_wrapper.hpp>

#include <boost/serialization/singleton.hpp>

#include <boost/archive/archive_exception.hpp>
#include <boost/archive/detail/basic_oarchive.hpp>
#include <boost/archive/detail/basic_oserializer.hpp>
#include <boost/archive/detail/basic_pointer_oserializer.hpp>
#include <boost/archive/detail/archive_serializer_map.hpp>
#include <boost/archive/detail/check.hpp>

#include <boost/core/addressof.hpp>

namespace boost {

namespace serialization {
    class extended_type_info;
} // namespace serialization

namespace archive {

// an accessor to permit friend access to archives.  Needed because
// some compilers don't handle friend templates completely
class save_access {
public:
    template<class Archive>
    static void end_preamble(Archive & ar){
        ar.end_preamble();
    }
    template<class Archive, class T>
    static void save_primitive(Archive & ar, const  T & t){
        ar.end_preamble();
        ar.save(t);
    }
};

namespace detail {

#ifdef BOOST_MSVC
#  pragma warning(push)
#  pragma warning(disable : 4511 4512)
#endif

template<class Archive, class T>
class oserializer : public basic_oserializer
{
private:
    // private constructor to inhibit any existence other than the
    // static one
public:
    explicit BOOST_DLLEXPORT oserializer() :
        basic_oserializer(
            boost::serialization::singleton<
                typename
                boost::serialization::type_info_implementation< T >::type
            >::get_const_instance()
        )
    {}
    BOOST_DLLEXPORT void save_object_data(
        basic_oarchive & ar,
        const void *x
    ) const BOOST_OVERRIDE BOOST_USED;
    bool class_info() const BOOST_OVERRIDE {
        return boost::serialization::implementation_level< T >::value
            >= boost::serialization::object_class_info;
    }
    bool tracking(const unsigned int /* flags */) const BOOST_OVERRIDE {
        return boost::serialization::tracking_level< T >::value == boost::serialization::track_always
            || (boost::serialization::tracking_level< T >::value == boost::serialization::track_selectively
                && serialized_as_pointer());
    }
    version_type version() const BOOST_OVERRIDE {
        return version_type(::boost::serialization::version< T >::value);
    }
    bool is_polymorphic() const BOOST_OVERRIDE {
        return boost::is_polymorphic< T >::value;
    }
    ~oserializer() BOOST_OVERRIDE {}
};

#ifdef BOOST_MSVC
#  pragma warning(pop)
#endif

template<class Archive, class T>
BOOST_DLLEXPORT void oserializer<Archive, T>::save_object_data(
    basic_oarchive & ar,
    const void *x
) const {
    // make sure call is routed through the highest interface that might
    // be specialized by the user.
    BOOST_STATIC_ASSERT(boost::is_const< T >::value == false);
    boost::serialization::serialize_adl(
        boost::serialization::smart_cast_reference<Archive &>(ar),
        * static_cast<T *>(const_cast<void *>(x)),
        version()
    );
}

#ifdef BOOST_MSVC
#  pragma warning(push)
#  pragma warning(disable : 4511 4512)
#endif

template<class Archive, class T>
class pointer_oserializer :
    public basic_pointer_oserializer
{
private:
    const basic_oserializer &
    get_basic_serializer() const BOOST_OVERRIDE {
        return boost::serialization::singleton<
            oserializer<Archive, T>
        >::get_const_instance();
    }
    BOOST_DLLEXPORT void save_object_ptr(
        basic_oarchive & ar,
        const void * x
    ) const BOOST_OVERRIDE BOOST_USED;
public:
    pointer_oserializer();
    ~pointer_oserializer() BOOST_OVERRIDE;
};

#ifdef BOOST_MSVC
#  pragma warning(pop)
#endif

template<class Archive, class T>
BOOST_DLLEXPORT void pointer_oserializer<Archive, T>::save_object_ptr(
    basic_oarchive & ar,
    const void * x
) const {
    BOOST_ASSERT(NULL != x);
    // make sure call is routed through the highest interface that might
    // be specialized by the user.
    T * t = static_cast<T *>(const_cast<void *>(x));
    const unsigned int file_version = boost::serialization::version< T >::value;
    Archive & ar_impl
        = boost::serialization::smart_cast_reference<Archive &>(ar);
    boost::serialization::save_construct_data_adl<Archive, T>(
        ar_impl,
        t,
        file_version
    );
    ar_impl << boost::serialization::make_nvp(NULL, * t);
}

template<class Archive, class T>
pointer_oserializer<Archive, T>::pointer_oserializer() :
    basic_pointer_oserializer(
        boost::serialization::singleton<
            typename
            boost::serialization::type_info_implementation< T >::type
        >::get_const_instance()
    )
{
    // make sure appropriate member function is instantiated
    boost::serialization::singleton<
        oserializer<Archive, T>
    >::get_mutable_instance().set_bpos(this);
    archive_serializer_map<Archive>::insert(this);
}

template<class Archive, class T>
pointer_oserializer<Archive, T>::~pointer_oserializer(){
    archive_serializer_map<Archive>::erase(this);
}

template<class Archive>
struct save_non_pointer_type {
    // note this bounces the call right back to the archive
    // with no runtime overhead
    struct save_primitive {
        template<class T>
        static void invoke(Archive & ar, const T & t){
            save_access::save_primitive(ar, t);
        }
    };
    // same as above but passes through serialization
    struct save_only {
        template<class T>
        static void invoke(Archive & ar, const T & t){
            // make sure call is routed through the highest interface that might
            // be specialized by the user.
            boost::serialization::serialize_adl(
                ar,
                const_cast<T &>(t),
                ::boost::serialization::version< T >::value
            );
        }
    };
    // adds class information to the archive. This includes
    // serialization level and class version
    struct save_standard {
        template<class T>
        static void invoke(Archive &ar, const T & t){
            ar.save_object(
                boost::addressof(t),
                boost::serialization::singleton<
                    oserializer<Archive, T>
                >::get_const_instance()
            );
        }
    };

    // adds class information to the archive. This includes
    // serialization level and class version
    struct save_conditional {
        template<class T>
        static void invoke(Archive &ar, const T &t){
            //if(0 == (ar.get_flags() & no_tracking))
                save_standard::invoke(ar, t);
            //else
            //   save_only::invoke(ar, t);
        }
    };

    template<class T>
    static void invoke(Archive & ar, const T & t){
        typedef
            typename mpl::eval_if<
            // if its primitive
                mpl::equal_to<
                    boost::serialization::implementation_level< T >,
                    mpl::int_<boost::serialization::primitive_type>
                >,
                mpl::identity<save_primitive>,
            // else
            typename mpl::eval_if<
                // class info / version
                mpl::greater_equal<
                    boost::serialization::implementation_level< T >,
                    mpl::int_<boost::serialization::object_class_info>
                >,
                // do standard save
                mpl::identity<save_standard>,
            // else
            typename mpl::eval_if<
                    // no tracking
                mpl::equal_to<
                    boost::serialization::tracking_level< T >,
                    mpl::int_<boost::serialization::track_never>
                >,
                // do a fast save
                mpl::identity<save_only>,
            // else
                // do a fast save only tracking is turned off
                mpl::identity<save_conditional>
            > > >::type typex;
        check_object_versioning< T >();
        typex::invoke(ar, t);
    }
    template<class T>
    static void invoke(Archive & ar, T & t){
        check_object_level< T >();
        check_object_tracking< T >();
        invoke(ar, const_cast<const T &>(t));
    }
};

template<class Archive>
struct save_pointer_type {
    struct abstract
    {
        template<class T>
        static const basic_pointer_oserializer * register_type(Archive & /* ar */){
            // it has? to be polymorphic
            BOOST_STATIC_ASSERT(boost::is_polymorphic< T >::value);
            return NULL;
        }
    };

    struct non_abstract
    {
        template<class T>
        static const basic_pointer_oserializer * register_type(Archive & ar){
            return ar.register_type(static_cast<T *>(NULL));
        }
    };

    template<class T>
    static const basic_pointer_oserializer * register_type(Archive &ar, T* const /*t*/){
        // there should never be any need to save an abstract polymorphic
        // class pointer.  Inhibiting code generation for this
        // permits abstract base classes to be used - note: exception
        // virtual serialize functions used for plug-ins
        typedef
            typename mpl::eval_if<
                boost::serialization::is_abstract< T >,
                mpl::identity<abstract>,
                mpl::identity<non_abstract>
            >::type typex;
        return typex::template register_type< T >(ar);
    }

    struct non_polymorphic
    {
        template<class T>
        static void save(
            Archive &ar,
            T & t
        ){
            const basic_pointer_oserializer & bpos =
                boost::serialization::singleton<
                    pointer_oserializer<Archive, T>
                >::get_const_instance();
            // save the requested pointer type
            ar.save_pointer(& t, & bpos);
        }
    };

    struct polymorphic
    {
        template<class T>
        static void save(
            Archive &ar,
            T & t
        ){
            typename
            boost::serialization::type_info_implementation< T >::type const
            & i = boost::serialization::singleton<
                typename
                boost::serialization::type_info_implementation< T >::type
            >::get_const_instance();

            boost::serialization::extended_type_info const * const this_type = & i;

            // retrieve the true type of the object pointed to
            // if this assertion fails its an error in this library
            BOOST_ASSERT(NULL != this_type);

            const boost::serialization::extended_type_info * true_type =
                i.get_derived_extended_type_info(t);

            // note:if this exception is thrown, be sure that derived pointer
            // is either registered or exported.
            if(NULL == true_type){
                boost::serialization::throw_exception(
                    archive_exception(
                        archive_exception::unregistered_class,
                        "derived class not registered or exported"
                    )
                );
            }

            // if its not a pointer to a more derived type
            const void *vp = static_cast<const void *>(&t);
            if(*this_type == *true_type){
                const basic_pointer_oserializer * bpos = register_type(ar, &t);
                ar.save_pointer(vp, bpos);
                return;
            }
            // convert pointer to more derived type. if this is thrown
            // it means that the base/derived relationship hasn't be registered
            vp = serialization::void_downcast(
                *true_type,
                *this_type,
                static_cast<const void *>(&t)
            );
            if(NULL == vp){
                boost::serialization::throw_exception(
                    archive_exception(
                        archive_exception::unregistered_cast,
                        true_type->get_debug_info(),
                        this_type->get_debug_info()
                    )
                );
            }

            // since true_type is valid, and this only gets made if the
            // pointer oserializer object has been created, this should never
            // fail
            const basic_pointer_oserializer * bpos
                = static_cast<const basic_pointer_oserializer *>(
                    boost::serialization::singleton<
                        archive_serializer_map<Archive>
                    >::get_const_instance().find(*true_type)
                );
            BOOST_ASSERT(NULL != bpos);
            if(NULL == bpos)
                boost::serialization::throw_exception(
                    archive_exception(
                        archive_exception::unregistered_class,
                        "derived class not registered or exported"
                    )
                );
            ar.save_pointer(vp, bpos);
        }
    };

    template<class T>
    static void save(
        Archive & ar,
        const T & t
    ){
        check_pointer_level< T >();
        check_pointer_tracking< T >();
        typedef typename mpl::eval_if<
            is_polymorphic< T >,
            mpl::identity<polymorphic>,
            mpl::identity<non_polymorphic>
        >::type type;
        type::save(ar, const_cast<T &>(t));
    }

    template<class TPtr>
    static void invoke(Archive &ar, const TPtr t){
        register_type(ar, t);
        if(NULL == t){
            basic_oarchive & boa
                = boost::serialization::smart_cast_reference<basic_oarchive &>(ar);
            boa.save_null_pointer();
            save_access::end_preamble(ar);
            return;
        }
        save(ar, * t);
    }
};

template<class Archive>
struct save_enum_type
{
    template<class T>
    static void invoke(Archive &ar, const T &t){
        // convert enum to integers on save
        const int i = static_cast<int>(t);
        ar << boost::serialization::make_nvp(NULL, i);
    }
};

template<class Archive>
struct save_array_type
{
    template<class T>
    static void invoke(Archive &ar, const T &t){
        typedef typename boost::remove_extent< T >::type value_type;

        save_access::end_preamble(ar);
        // consider alignment
        std::size_t c = sizeof(t) / (
            static_cast<const char *>(static_cast<const void *>(&t[1]))
            - static_cast<const char *>(static_cast<const void *>(&t[0]))
        );
        boost::serialization::collection_size_type count(c);
        ar << BOOST_SERIALIZATION_NVP(count);
        // explict template arguments to pass intel C++ compiler
        ar << serialization::make_array<
            const value_type,
            boost::serialization::collection_size_type
        >(
            static_cast<const value_type *>(&t[0]),
            count
        );
    }
};

} // detail

template<class Archive, class T>
inline void save(Archive & ar, /*const*/ T &t){
    typedef
        typename mpl::eval_if<is_pointer< T >,
            mpl::identity<detail::save_pointer_type<Archive> >,
        //else
        typename mpl::eval_if<is_enum< T >,
            mpl::identity<detail::save_enum_type<Archive> >,
        //else
        typename mpl::eval_if<is_array< T >,
            mpl::identity<detail::save_array_type<Archive> >,
        //else
            mpl::identity<detail::save_non_pointer_type<Archive> >
        >
        >
        >::type typex;
    typex::invoke(ar, t);
}

} // namespace archive
} // namespace boost

#endif // BOOST_ARCHIVE_OSERIALIZER_HPP


text:
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <math.h>
#include <vector>
#include <string>
#include <strings.h>
#include <iostream>
#include <iomanip>
#include <sstream>
#include <time.h>

#include <ros/ros.h>
#include <Eigen>
#include <sandshark_common/sqlite3.h>
#include <sandshark_common/proj_api.h>
#include <sandshark_common/main.h>
#include <sandshark_common/task_base.h>
#include <sandshark_msgs/GPS.h>

using namespace std;
using namespace Eigen;
namespace bluefin {
namespace sandshark {

bool new_data;
vector<string> sqldata;
static int callback(void *NotUsed, int argc, char **argv, char **azColName) {
  int i;
  for (i = 0; i < argc; i++) {
    if ((i + 1) > (int) sqldata.size()) {
      sqldata.push_back("NULL");
    }
    sqldata[i] = argv[i] ? argv[i] : "NULL";
  }
  new_data = true;
  return 0;
}

class GpsDriver: public TaskBase {
  private:
    bool _initialized;
    int _utm_zone;
    sqlite3 *_database;

    projPJ _utmDefinition;
    projPJ _latlngDefinition;

    ros::Publisher _gpsPub;
    sandshark_msgs::GPS _gpsMsg;

    double _lastEpoch;

    void cleanup();
  protected:
    void startupInitCallback();
    bool doInitialize();
    bool doRun();
  public:
    GpsDriver() :
        TaskBase("GpsDriver", "gps") {
    }

    void handleSleep();
};

void GpsDriver::startupInitCallback() {
  ROS_INFO("Task init! - creating gps node\n");
  fflush( stdout);

  _gpsPub = _publicNode->advertise<sandshark_msgs::GPS>("gps", 10);

  fflush( stdout);
  _utm_zone = 19;
  _initialized = false;
  new_data = false;

  if (_logLocal && _logFile) {
    fprintf(_logFile,
        "ROSTime,\tEpoch,\tLatitude,\tLongitude,\tNorthings,\tEastings,\tUTMZone,\tAccuracy,\tSpeed,\tBearing\n");
  }

}

bool GpsDriver::doInitialize() {
  cleanup();

  char *zErrMsg = 0;

  int sqret = sqlite3_open("/data/data/com.bluefinrobotics.bluefingps/databases/BLUEFINGPSDB", &_database);

  if (sqret) {
    fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(_database));
    sqlite3_close(_database);
    return false;
  }

  sqret = sqlite3_exec(_database, "SELECT * FROM LOCATION_POINTS", callback, 0, &zErrMsg);
  if (sqret != SQLITE_OK) {
    fprintf( stderr, "SQL error: %s\n", zErrMsg);
    sqlite3_free(zErrMsg);
    return false;
  }

  _lastEpoch = 0.0;

  return true;
}

void GpsDriver::cleanup() {
  ROS_INFO("GPS Cleanup");
  fflush( stdout);
}

bool GpsDriver::doRun() {
  char *zErrMsg = 0;

  int sqret = sqlite3_exec(_database, "SELECT * FROM LOCATION_POINTS", callback, 0, &zErrMsg);
  if (sqret != SQLITE_OK) {
    fprintf( stderr, "SQL error: %s\n", zErrMsg);
    sqlite3_free(zErrMsg);
    return true;
  }

  bool haveLat = false;
  bool haveLng = false;
  double lat, lng;
  if (new_data && (sqldata.size() >= 10)) {
    if (sqldata[3] != "NULL") {
      lat = atof(sqldata[3].c_str());
      haveLat = true;
    }
    if (sqldata[4] != "NULL") {
      lng = atof(sqldata[4].c_str());
      haveLng = true;
    }

    fflush( stdout);
    if (!_initialized && haveLat && haveLng) {
      int zone = (int) ((lng + 180.0) / 6.0 + 1);
      bool south = (lat < 0);
      char utmInitString[256];
      snprintf(&utmInitString[0], sizeof(utmInitString), "+proj=utm +zone=%d +ellps=WGS84%s", zone,
          (south ? " +south" : ""));

      ROS_INFO("Lat %f Lng %f zone %d string %s", lat, lng, zone, utmInitString);
      fflush( stdout);

      _utmDefinition = pj_init_plus(utmInitString);
      if (!_utmDefinition) {
        ROS_ERROR("UTM Def failed!!");
        return false;
      }

      _latlngDefinition = pj_init_plus("+proj=latlong +ellps=WGS84");
      if (!_latlngDefinition) {
        ROS_ERROR("LatLng Def failed!!");
        return false;
      }

      _utm_zone = zone;
      _initialized = true;
    }

    new_data = false;

    if (_initialized && haveLat && haveLng) {
      double northings = lat * DEG_TO_RAD;
      double eastings = lng * DEG_TO_RAD;
      pj_transform(_latlngDefinition, _utmDefinition, 1, 1, &eastings, &northings, NULL);

      _gpsMsg.gmt_timestamp = sqldata[1];
      _gpsMsg.epoch = atof(sqldata[2].c_str());
      _gpsMsg.latitude = lat;
      _gpsMsg.longitude = lng;
      _gpsMsg.northings = northings;
      _gpsMsg.eastings = eastings;
      _gpsMsg.utm_zone = _utm_zone;
      _gpsMsg.altitude = atof(sqldata[5].c_str());
      _gpsMsg.accuracy = atof(sqldata[6].c_str());
      _gpsMsg.satellites_in_use = atoi(sqldata[7].c_str());
      _gpsMsg.speed = atof(sqldata[8].c_str());
      _gpsMsg.bearing = atof(sqldata[9].c_str());

      if (_gpsMsg.epoch > _lastEpoch && _gpsMsg.satellites_in_use > 5) {
        ROS_INFO("GPS Publishing! Lat %f Lng %f N %f E %f Epoch %f Last Epoch %f", lat, lng, northings, eastings,
            _gpsMsg.epoch, _lastEpoch);
        if (_logLocal && _logFile) {
          fprintf(_logFile, "%f,\t%f,\t%f,\t%f,\t%f,\t%f,\t%d,\t%f,\t%f,\t%f\n", ros::WallTime::now().toSec(),
              _gpsMsg.epoch, lat, lng, northings, eastings, _utm_zone, _gpsMsg.accuracy, _gpsMsg.speed,
              _gpsMsg.bearing);
          fflush(_logFile);
        }
        _gpsPub.publish(_gpsMsg);
        _lastEpoch = _gpsMsg.epoch;
      }
    }
  }
  return true;
}

void GpsDriver::handleSleep() {
  usleep(100000);
}

}
}

int main(int argc, char *argv[]) {
  bluefin::sandshark::GpsDriver gd;
  return bluefin::sandshark::app_main((bluefin::sandshark::TaskBase&) gd, argc, argv);
}

ext: cpp

max_stars_repo_name: slicht-uri/Sandshark-Beta-Lab-

max_issues_repo_name: slicht-uri/Sandshark-Beta-Lab-

max_forks_repo_name: slicht-uri/Sandshark-Beta-Lab-


text:
/**
 *    Copyright (C) 2018-present MongoDB, Inc.
 *
 *    This program is free software: you can redistribute it and/or modify
 *    it under the terms of the Server Side Public License, version 1,
 *    as published by MongoDB, Inc.
 *
 *    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
 *    Server Side Public License for more details.
 *
 *    You should have received a copy of the Server Side Public License
 *    along with this program. If not, see
 *    <http://www.mongodb.com/licensing/server-side-public-license>.
 *
 *    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 Server Side Public License in all respects for
 *    all of the code used other than as permitted herein. If you modify file(s)
 *    with this exception, you may extend this exception to your version of the
 *    file(s), but you are not obligated to do so. If you do not wish to do so,
 *    delete this exception statement from your version. If you delete this
 *    exception statement from all source files in the program, then also delete
 *    it in the license file.
 */

#include "mongo/db/exec/projection.h"

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

#include "mongo/db/exec/document_value/document.h"
#include "mongo/db/exec/plan_stage.h"
#include "mongo/db/exec/projection_executor_builder.h"
#include "mongo/db/exec/scoped_timer.h"
#include "mongo/db/exec/working_set_common.h"
#include "mongo/db/jsobj.h"
#include "mongo/db/matcher/expression.h"
#include "mongo/db/record_id.h"
#include "mongo/util/str.h"

namespace mongo {
namespace {

void transitionMemberToOwnedObj(Document&& doc, WorkingSetMember* member) {
    member->keyData.clear();
    member->recordId = {};
    member->doc = {{}, std::move(doc)};
    member->transitionToOwnedObj();
}

void transitionMemberToOwnedObj(const BSONObj& bo, WorkingSetMember* member) {
    // Use the DocumentStorage that already exists on the WorkingSetMember's document
    // field if possible.
    MutableDocument md(std::move(member->doc.value()));
    md.reset(bo, false);
    transitionMemberToOwnedObj(md.freeze(), member);
}

/**
 * Moves document metadata fields from the WSM into the given document 'doc', and returns the same
 * document but with populated metadata.
 */
auto attachMetadataToDocument(Document&& doc, WorkingSetMember* member) {
    MutableDocument md{std::move(doc)};
    md.setMetadata(member->releaseMetadata());
    return md.freeze();
}

/**
 * Moves document metadata fields from the document 'doc' into the WSM, and returns the same
 * document but without metadata.
 */
auto attachMetadataToWorkingSetMember(Document&& doc, WorkingSetMember* member) {
    MutableDocument md{std::move(doc)};
    member->setMetadata(md.releaseMetadata());
    return md.freeze();
}

/**
 * Given an index key 'dehyratedKey' with no field names, returns a new Document representing the
 * index key after adding field names according to 'keyPattern'.
 *
 * For example, given:
 *    - the 'keyPatern' of {'a.b': 1, c: 1}
 *    - the 'dehydratedKey' of {'': 'abc', '': 10}
 *
 * The resulting document will be: {a: {b: 'abc'}, c: 10}
 */
auto rehydrateIndexKey(const BSONObj& keyPattern, const BSONObj& dehydratedKey) {
    MutableDocument md;
    BSONObjIterator keyIter{keyPattern};
    BSONObjIterator valueIter{dehydratedKey};

    while (keyIter.more() && valueIter.more()) {
        auto fieldName = keyIter.next().fieldNameStringData();
        auto value = valueIter.next();

        // Skip the $** index virtual field, as it's not part of the actual index key.
        if (fieldName == "$_path") {
            continue;
        }

        md.setNestedField(fieldName, Value{value});
    }

    invariant(!keyIter.more());
    invariant(!valueIter.more());

    return md.freeze();
}
}  // namespace

ProjectionStage::ProjectionStage(ExpressionContext* expCtx,
                                 const BSONObj& projObj,
                                 WorkingSet* ws,
                                 std::unique_ptr<PlanStage> child,
                                 const char* stageType)
    : PlanStage{expCtx, std::move(child), stageType},
      _projObj{expCtx->explain ? boost::make_optional(projObj.getOwned()) : boost::none},
      _ws{*ws} {}

bool ProjectionStage::isEOF() {
    return child()->isEOF();
}

PlanStage::StageState ProjectionStage::doWork(WorkingSetID* out) {
    WorkingSetID id = WorkingSet::INVALID_ID;
    StageState status = child()->work(&id);

    // Note that we don't do the normal if isEOF() return EOF thing here.  Our child might be a
    // tailable cursor and isEOF() would be true even if it had more data...
    if (PlanStage::ADVANCED == status) {
        WorkingSetMember* member = _ws.get(id);
        // Punt to our specific projection impl.
        transform(member);
        *out = id;
    } else if (PlanStage::NEED_YIELD == status) {
        *out = id;
    }

    return status;
}

std::unique_ptr<PlanStageStats> ProjectionStage::getStats() {
    _commonStats.isEOF = isEOF();
    auto ret = std::make_unique<PlanStageStats>(_commonStats, stageType());

    auto projStats = std::make_unique<ProjectionStats>(_specificStats);
    projStats->projObj = _projObj.value_or(BSONObj{});
    ret->specific = std::move(projStats);

    ret->children.emplace_back(child()->getStats());
    return ret;
}

ProjectionStageDefault::ProjectionStageDefault(boost::intrusive_ptr<ExpressionContext> expCtx,
                                               const BSONObj& projObj,
                                               const projection_ast::Projection* projection,
                                               WorkingSet* ws,
                                               std::unique_ptr<PlanStage> child)
    : ProjectionStage{expCtx.get(), projObj, ws, std::move(child), "PROJECTION_DEFAULT"},
      _requestedMetadata{projection->metadataDeps()},
      _projectType{projection->type()},
      _executor{projection_executor::buildProjectionExecutor(
          expCtx, projection, {}, projection_executor::kDefaultBuilderParams)} {}

void ProjectionStageDefault::transform(WorkingSetMember* member) const {
    Document input;

    // Most metadata should have already been stored within the WSM when we project out a document.
    // The recordId metadata is different though, because it's a fundamental part of the WSM and
    // we store it within the WSM itself rather than WSM metadata, so we need to transfer it into
    // the metadata object if the projection has a recordId $meta expression.
    if (_requestedMetadata[DocumentMetadataFields::kRecordId] &&
        !member->metadata().hasRecordId()) {
        member->metadata().setRecordId(member->recordId);
    }

    if (member->hasObj()) {
        input = std::move(member->doc.value());
    } else {
        // We have a covered projection, which is only supported in inclusion mode.
        invariant(_projectType == projection_ast::ProjectType::kInclusion);
        // We're pulling data from an index key, so there must be exactly one key entry in the WSM
        // as the planner guarantees that it will never generate a covered plan in the case of index
        // intersection.
        invariant(member->keyData.size() == 1);

        // For covered projection we will rehydrate in index key into a Document and then pass it
        // through the projection executor to include only required fields, including metadata
        // fields.
        input = rehydrateIndexKey(member->keyData[0].indexKeyPattern, member->keyData[0].keyData);
    }

    // If the projection doesn't need any metadata, then we'll just apply the projection to the
    // input document. Otherwise, before applying the projection, we will move document metadata
    // from the WSM into the document itself, and will move it back to the WSM once the projection
    // has been applied.
    auto projected = _requestedMetadata.any()
        ? attachMetadataToWorkingSetMember(
              _executor->applyTransformation(attachMetadataToDocument(std::move(input), member)),
              member)
        : _executor->applyTransformation(input);

    // An exclusion projection can return an unowned object since the output document is
    // constructed from the input one backed by BSON which is owned by the storage system, so we
    // need to  make sure we transition an owned document.
    transitionMemberToOwnedObj(projected.getOwned(), member);
}

ProjectionStageCovered::ProjectionStageCovered(ExpressionContext* expCtx,
                                               const BSONObj& projObj,
                                               const projection_ast::Projection* projection,
                                               WorkingSet* ws,
                                               std::unique_ptr<PlanStage> child,
                                               const BSONObj& coveredKeyObj)
    : ProjectionStage{expCtx, projObj, ws, std::move(child), "PROJECTION_COVERED"},
      _coveredKeyObj{coveredKeyObj} {
    invariant(projection->isSimple());

    // If we're pulling data out of one index we can pre-compute the indices of the fields
    // in the key that we pull data from and avoid looking up the field name each time.

    // Sanity-check.
    invariant(_coveredKeyObj.isOwned());

    _includedFields = {projection->getRequiredFields().begin(),
                       projection->getRequiredFields().end()};
    BSONObjIterator kpIt(_coveredKeyObj);
    while (kpIt.more()) {
        BSONElement elt = kpIt.next();
        auto fieldIt = _includedFields.find(elt.fieldNameStringData());
        if (_includedFields.end() == fieldIt) {
            // Push an unused value on the back to keep _includeKey and _keyFieldNames
            // in sync.
            _keyFieldNames.push_back(StringData());
            _includeKey.push_back(false);
        } else {
            // If we are including this key field store its field name.
            _keyFieldNames.push_back(*fieldIt);
            _includeKey.push_back(true);
        }
    }
}

void ProjectionStageCovered::transform(WorkingSetMember* member) const {
    BSONObjBuilder bob;

    // We're pulling data out of the key.
    invariant(1 == member->keyData.size());
    size_t keyIndex = 0;

    // Look at every key element...
    BSONObjIterator keyIterator(member->keyData[0].keyData);
    while (keyIterator.more()) {
        BSONElement elt = keyIterator.next();
        // If we're supposed to include it...
        if (_includeKey[keyIndex]) {
            // Do so.
            bob.appendAs(elt, _keyFieldNames[keyIndex]);
        }
        ++keyIndex;
    }
    transitionMemberToOwnedObj(bob.obj(), member);
}

ProjectionStageSimple::ProjectionStageSimple(ExpressionContext* expCtx,
                                             const BSONObj& projObj,
                                             const projection_ast::Projection* projection,
                                             WorkingSet* ws,
                                             std::unique_ptr<PlanStage> child)
    : ProjectionStage{expCtx, projObj, ws, std::move(child), "PROJECTION_SIMPLE"} {
    invariant(projection->isSimple());
    _includedFields = {projection->getRequiredFields().begin(),
                       projection->getRequiredFields().end()};
}

void ProjectionStageSimple::transform(WorkingSetMember* member) const {
    BSONObjBuilder bob;
    // SIMPLE_DOC implies that we expect an object so it's kind of redundant.
    // If we got here because of SIMPLE_DOC the planner shouldn't have messed up.
    invariant(member->hasObj());

    // Apply the SIMPLE_DOC projection.
    // Look at every field in the source document and see if we're including it.
    auto objToProject = member->doc.value().toBson();
    auto nFieldsNeeded = _includedFields.size();
    for (auto&& elt : objToProject) {
        auto fieldName{elt.fieldNameStringData()};
        absl::string_view fieldNameKey{fieldName.rawData(), fieldName.size()};
        if (auto fieldIt = _includedFields.find(fieldNameKey); _includedFields.end() != fieldIt) {
            bob.append(elt);
            if (--nFieldsNeeded == 0) {
                break;
            }
        }
    }

    transitionMemberToOwnedObj(bob.obj(), member);
}

}  // namespace mongo

max_stars_repo_name: benety/mongo

max_issues_repo_name: benety/mongo

max_forks_repo_name: benety/mongo


text:
// A small example to help bring up compilation env of boost unit test.
// Used in boost-units.

#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE boost-unit-test
#include <boost/test/unit_test.hpp>

int add(int i, int j)
{
    return i + j;
}

BOOST_AUTO_TEST_CASE(universeInOrder)
{
    BOOST_CHECK(add(2, 2) == 4);
}

max_stars_repo_name: cmey/surprising-snippets

max_issues_repo_name: cmey/surprising-snippets

max_forks_repo_name: cmey/surprising-snippets


text:
#ifndef _WEBSOCKET_HPP
#define _WEBSOCKET_HPP

#include <boost/beast.hpp>
#include <boost/asio.hpp>
#include <boost/json.hpp>

#include <iostream>
#include <string>
#include <cstddef>
#include <cstdlib>

namespace bserv {

	namespace beast = boost::beast;
	namespace http = beast::http;
	namespace websocket = beast::websocket;
	namespace asio = boost::asio;
	namespace json = boost::json;
	using asio::ip::tcp;

	class websocket_closed
		: public std::exception {
	public:
		websocket_closed() {}
		const char* what() const noexcept { return "websocket session has been closed"; }
	};

	class websocket_io_exception
		: public std::exception {
	private:
		const std::string msg_;
	public:
		websocket_io_exception(const std::string& msg) : msg_{ msg } {}
		const char* what() const noexcept { return msg_.c_str(); }
	};

	struct websocket_session {
		const std::string address_;
		asio::io_context& ioc_;
		websocket::stream<beast::tcp_stream> ws_;
		websocket_session(
			const std::string& address,
			asio::io_context& ioc,
			tcp::socket&& socket)
			: address_{ address },
			ioc_{ ioc }, ws_{ std::move(socket) } {}
	};

	class websocket_server {
	private:
		websocket_session& session_;
		asio::yield_context& yield_;
	public:
		websocket_server(websocket_session& session, asio::yield_context& yield)
			: session_{ session }, yield_{ yield } {}
		std::string read();
		boost::json::value read_json() { return boost::json::parse(read()); }
		void write(const std::string& data);
		void write_json(const boost::json::value& val) { write(boost::json::serialize(val)); }
	};

}  // bserv

#endif  // _WEBSOCKET_HPP

max_stars_repo_name: JonathanSilver/bserv

max_issues_repo_name: caiyancheng/bserv

max_forks_repo_name: caiyancheng/bserv


text:
/*
 * Copyright (C) 2005-2019 Centre National d'Etudes Spatiales (CNES)
 *
 * This file is part of Orfeo Toolbox
 *
 *     https://www.orfeo-toolbox.org/
 *
 * 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.
 */

/*===========================================================================*/
/*===============================[ Includes ]================================*/
/*===========================================================================*/
#include "otbOGRFeatureWrapper.h"
#include <boost/bind.hpp>
#include <boost/make_shared.hpp>
#if defined(__GNUC__) || defined(__clang__)
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wshadow"
#include "ogr_feature.h"
#pragma GCC diagnostic pop
#else
#include "ogr_feature.h"
#endif
#include "cpl_error.h"
#include "itkMacro.h"

/*===========================================================================*/
/*======================[ Construction / Destruction ]=======================*/
/*===========================================================================*/
otb::ogr::Feature::Feature(OGRFeatureDefn& definition)
  : m_Feature(OGRFeature::CreateFeature(&definition), [&](auto const& x) { return OGRFeature::DestroyFeature(x); })
{
  CheckInvariants();
}

otb::ogr::Feature::Feature(OGRFeature* feature)
{
  if (feature)
  {
    m_Feature.reset(feature, [&](auto const& x) { return OGRFeature::DestroyFeature(x); });
  }
  // else default is perfect -> delete null
}

otb::ogr::Feature::~Feature()
{
}

otb::ogr::Feature otb::ogr::Feature::UncheckedClone() const
{
  const Feature res(m_Feature->Clone());
  return res;
}

void otb::ogr::Feature::UncheckedSetFrom(Feature const& rhs, bool mustForgive)
{
  const OGRErr res = m_Feature->SetFrom(&rhs.ogr(), mustForgive);
  if (res != OGRERR_NONE)
  {
    itkGenericExceptionMacro(<< "Cannot assign from another feature: " << CPLGetLastErrorMsg());
  }
}

void otb::ogr::Feature::UncheckedSetFrom(Feature const& rhs, int* map, bool mustForgive)
{
  const OGRErr res = m_Feature->SetFrom(&rhs.ogr(), map, mustForgive);
  if (res != OGRERR_NONE)
  {
    itkGenericExceptionMacro(<< "Cannot assign from another feature: " << CPLGetLastErrorMsg());
  }
}

/*===========================================================================*/
/*=================================[ Misc ]==================================*/
/*===========================================================================*/
void otb::ogr::Feature::UncheckedPrintSelf(std::ostream& os, itk::Indent indent) const
{
  const int nbFields = m_Feature->GetFieldCount();
  os << indent << "+";
  os << " " << nbFields << " fields\n";
  indent = indent.GetNextIndent();
  for (int i = 0; i != nbFields; ++i)
  {
    assert(ogr().GetFieldDefnRef(i) && "No definition associated to the i-th field");
    Field const& field = (*this)[i];
    field.PrintSelf(os, indent);
  }
}

bool otb::ogr::operator==(otb::ogr::Feature const& lhs, otb::ogr::Feature const& rhs)
{
  // special case: they may be null (end() mark)

  // OGR is not const correct ...
  OGRFeature* l = const_cast<OGRFeature*>(lhs.m_Feature.get());
  OGRFeature* r = const_cast<OGRFeature*>(rhs.m_Feature.get());
  return (l == r)                   // incl. ==0
         || (l && r && l->Equal(r)) // must be non-null to compare them with Equal
      ;
}

/*===========================================================================*/
/*================================[ Fields ]=================================*/
/*===========================================================================*/
int otb::ogr::Feature::GetSize() const
{
  return ogr().GetFieldCount();
}

otb::ogr::Field otb::ogr::Feature::UncheckedGetElement(int index)
{
  Field field(*this, index);
  return field;
}

otb::ogr::Field otb::ogr::Feature::UncheckedGetElement(std::string const& name)
{
  const int index = GetFieldIndex(name);
  return this->operator[](index);
}

otb::ogr::FieldDefn otb::ogr::Feature::UncheckedGetFieldDefn(int index) const
{
  return FieldDefn(*m_Feature->GetFieldDefnRef(index));
}

otb::ogr::FieldDefn otb::ogr::Feature::UncheckedGetFieldDefn(std::string const& name) const
{
  const int index = GetFieldIndex(name);
  if (index < 0)
  {
    itkGenericExceptionMacro(<< "no field named <" << name << ">");
  }
  return this->GetFieldDefn(index);
}

int otb::ogr::Feature::UncheckedGetFieldIndex(std::string const& name) const
{
  const int index = m_Feature->GetFieldIndex(name.c_str());
  if (index < 0)
  {
    itkGenericExceptionMacro(<< "No field named <" << name << "> in feature");
  }
  return index;
}

/*===========================================================================*/
/*==============================[ Properties ]===============================*/
/*===========================================================================*/
long otb::ogr::Feature::UncheckedGetFID() const
{
  return m_Feature->GetFID();
}

void otb::ogr::Feature::UncheckedSetFID(long fid)
{
  const OGRErr res = m_Feature->SetFID(fid);
  if (res != OGRERR_NONE)
  {
    itkGenericExceptionMacro(<< "Cannot Set FID to " << fid << " for feature: " << CPLGetLastErrorMsg());
  }
}

OGRFeatureDefn& otb::ogr::Feature::UncheckedGetDefn() const
{
  return *m_Feature->GetDefnRef();
}

/*===========================================================================*/
/*==============================[ Geometries ]===============================*/
/*===========================================================================*/

void otb::ogr::Feature::UncheckedSetGeometryDirectly(UniqueGeometryPtr geometry)
{
  OGRGeometry* g   = geometry.get();
  const OGRErr res = m_Feature->SetGeometryDirectly(g);
  if (res != OGRERR_NONE)
  {
    itkGenericExceptionMacro(<< "Cannot set (directly) the geometry: " << CPLGetLastErrorMsg());
  }
  geometry.release(); // success => commit the transaction (after any exception thrown)
}

otb::ogr::UniqueGeometryPtr otb::ogr::Feature::UncheckedStealGeometry()
{
  OGRGeometry* g = m_Feature->StealGeometry();
  return UniqueGeometryPtr(g);
}

void otb::ogr::Feature::UncheckedSetGeometry(OGRGeometry const* geometry)
{
  // OGR copies the input geometry => should have been const
  const OGRErr res = m_Feature->SetGeometry(const_cast<OGRGeometry*>(geometry));
  if (res != OGRERR_NONE)
  {
    itkGenericExceptionMacro(<< "Cannot set the geometry: " << CPLGetLastErrorMsg());
  }
}

OGRGeometry const* otb::ogr::Feature::UncheckedGetGeometry() const
{
  return m_Feature->GetGeometryRef();
}

ext: cxx

max_stars_repo_name: qingswu/otb

max_issues_repo_name: qingswu/otb

max_forks_repo_name: qingswu/otb