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

#ifndef LIBP2P_PROTOCOL_KADEMLIA_CONTENTROUTINGIMPL
#define LIBP2P_PROTOCOL_KADEMLIA_CONTENTROUTINGIMPL

#include <libp2p/protocol/kademlia/impl/content_routing_table.hpp>

#include <boost/multi_index/hashed_index_fwd.hpp>
#include <boost/multi_index/member.hpp>
#include <boost/multi_index/ordered_index_fwd.hpp>
#include <boost/multi_index_container_fwd.hpp>

#include <libp2p/protocol/common/scheduler.hpp>
#include <libp2p/protocol/kademlia/common.hpp>
#include <libp2p/protocol/kademlia/config.hpp>

namespace libp2p::protocol::kademlia {

  struct ByKey;
  struct ByExpireTime;

  namespace {

    namespace mi = boost::multi_index;

    struct Record {
      ContentId key;
      peer::PeerId peer;
      scheduler::Ticks expire_time = scheduler::Ticks{};
    };

    /// Table of Record with 2 indices (by key and expire time)
    using Table = boost::multi_index_container<
        Record,
        mi::indexed_by<
            // hashed_non_unique by key means unordered index, non-unique
            mi::hashed_non_unique<mi::tag<ByKey>,
                                  mi::member<Record, ContentId, &Record::key>,
                                  std::hash<ContentId>>,
            // ordered_non_unique by expire time means accending order
            mi::ordered_non_unique<
                mi::tag<ByExpireTime>,
                mi::member<Record, scheduler::Ticks, &Record::expire_time>>>>;

  }  // namespace

  class ContentRoutingTableImpl
      : public ContentRoutingTable,
        public std::enable_shared_from_this<ContentRoutingTableImpl> {
   public:
    using Ticks = scheduler::Ticks;
    using AbsTime = Ticks;

    ContentRoutingTableImpl(const Config &config, Scheduler &scheduler,
                            std::shared_ptr<event::Bus> bus);

    ~ContentRoutingTableImpl() override;

    std::vector<PeerId> getProvidersFor(const ContentId &key,
                                        size_t limit = 0) const override;

    void addProvider(const ContentId &key, const peer::PeerId &peer) override;

   private:
    void onCleanupTimer();

    const Config& config_;
    Scheduler &scheduler_;
    std::shared_ptr<event::Bus> bus_;
    std::unique_ptr<Table> table_;
    Scheduler::Handle cleanup_timer_;
  };

}  // namespace libp2p::protocol::kademlia

#endif  // LIBP2P_KAD_CONTENT_PROVIDERS_STORE_HPP

ext: hpp


text:
/**
 * Copyright (c) 2017 Melown Technologies SE
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * *  Redistributions of source code must retain the above copyright notice,
 *    this list of conditions and the following disclaimer.
 *
 * *  Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */
/**
 * \file vts/tileset.hpp
 * \author Vaclav Blazek <vaclav.blazek@citationtech.net>
 *
 * Tile set access.
 */

#ifndef vtslibs_vts_tileset_hpp_included_
#define vtslibs_vts_tileset_hpp_included_

#include <memory>
#include <cmath>
#include <list>
#include <string>
#include <array>

#include <boost/optional.hpp>
#include <boost/noncopyable.hpp>
#include <boost/filesystem/path.hpp>

#include "utility/runnable.hpp"

#include "../storage/lod.hpp"
#include "../storage/range.hpp"
#include "../storage/resources.hpp"

#include "basetypes.hpp"
#include "types.hpp"
#include "mesh.hpp"
#include "metatile.hpp"
#include "atlas.hpp"
#include "tileset/properties.hpp"
#include "mapconfig.hpp"
#include "tileindex.hpp"
#include "tilesource.hpp"
#include "options.hpp"

namespace vtslibs { namespace vts {

/** Driver that implements physical aspects of tile set.
 */
class Driver;

/** TileSet interface.
 */
class TileSet {
public:
    ~TileSet();

    /** Get tile set propeties.
     * \return tile set properties
     */
    TileSetProperties getProperties() const;

    /** Sets new position.
     */
    void setPosition(const registry::Position &position);

    /** Adds given credits into list of credits used by this tileset.
     */
    void addCredits(const registry::IdSet &credits);

    /** Adds given bound layers into list of bound layers used by this tileset.
     */
    void addBoundLayers(const registry::IdSet &boundLayers);

    /** Generates map configuration for this single tile set.
     * \param includeExtra include extra configuration in the output.
     * \return map configuration
     */
    MapConfig mapConfig(bool includeExtra = true) const;

    /** Generates meshTiles configutation
     */
    MeshTilesConfig meshTilesConfig(bool includeExtra = true) const;

    /** Returns tile's mesh.
     */
    Mesh getMesh(const TileId &tileId) const;

    /** Returns stured tile's mesh mask unless generate is set to true. In that case,
     *  fresh mesh mask is generated from mesh data.
     */
    MeshMask getMeshMask(const TileId &tileId, bool generate = false) const;

    /** Returns tiles' atlas.
     */
    void getAtlas(const TileId &tileId, Atlas &atlas) const;

    /** Set tile content.
     *  \param tileId tile identifier
     *  \param tile tile content
     */
    void setTile(const TileId &tileId, const Tile &tile);

    /** Set tile content.
     *
     * Supplied nodeInfo must be correct!
     *
     *  \param tileId tile identifier
     *  \param tile tile content
     *  \param nodeInfo information about node
     */
    void setTile(const TileId &tileId, const Tile &tile
                 , const NodeInfo &nodeInfo);

    /** Set tile content.
     *  \param tileId tile identifier
     *  \param tile tile content source
     */
    void setTile(const TileId &tileId, const TileSource &tile);

    /** Set tile content.
     *
     * Supplied nodeInfo must be correct!
     *
     *  \param tileId tile identifier
     *  \param tile tile content source
     *  \param nodeInfo information about node
     */
    void setTile(const TileId &tileId, const TileSource &tile
                 , const NodeInfo &nodeInfo);

    /** Marks tile as influenced tile.
     *  Fails if tile is already a valid tile.
     */
    void markInfluencedTile(const TileId &tileId);

    /** Sets tile's navtile. Tile must already have mesh.
     *  Only navtile is stored.
     */
    void setNavTile(const TileId &tileId, const NavTile &navtile);

    /** Returns tile's navtile.
     */
    void getNavTile(const TileId &tileId, NavTile &navtile) const;

    /** Set's tile's surrogate value (i.e. representative height).
     */
    void setSurrogateValue(const TileId &tileId, float value);

    /** Returns tile's metanode.
     */
    MetaNode getMetaNode(const TileId &tileId) const;

    /** Returns tile's metanode.
     */
    const MetaNode* getMetaNode(const TileId &tileId, const std::nothrow_t&)
        const;

    /** Returns metatile.
     */
    MetaTile getMetaTile(const TileId &metaId) const;

    /** Shows metatile version.
     */
    int getMetaTileVersion(const TileId &metaId) const;

    /** Returns ID of metatile tileId belongs to.
     */
    TileId metaId(const TileId &tileId) const;

    /** Returns tile's content source.
     */
    TileSource getTileSource(const TileId &tileId) const;

    /** Returns reference for given tile.
     *  Reference is number > 0. 0 means no reference.
     */
    int getReference(const TileId &tileId) const;

    /** Checks whether tile exist.
     */
    bool exists(const TileId &tileId) const;

    /** Get source reference. Returns zero if tile does not exist. For tileset
     *  without stored tileset reference always returns 1 for existing tile.
     */
    int sourceReference(const TileId &tileId) const;

    /** Checks whether tile extist and covers whole tile.
     */
    bool fullyCovered(const TileId &tileId) const;

    /** Flushes tileset.
     *
     * Must be called before close otherwise tileset is useless.
     */
    void flush();

    /** Empties any cached content at once. Fails if there are any modified data.
     */
    void emptyCache() const;

    /** Starts watching runnable without entering a transaction.
     */
    void watch(utility::Runnable *runnable);

    /** Is the tile set empty (i.e. has it no tile?)
     */
    bool empty() const;

    /** Remove storage.
     */
    void drop();

    /** Returns lod range covered by tiles.
     */
    LodRange lodRange() const;

    /** Returns lod range at given lod. Calculated on the fly.
     */
    TileRange tileRange(Lod lod) const;

    /** Referce frame in charge.
     */
    const registry::ReferenceFrame& referenceFrame() const;

    /** Returns constant driver. Used in delivery system.
     */
    const Driver& driver() const;

    /** Root path of this tileset.
     */
    boost::filesystem::path root() const;

    /** Get tileset's ID.
     */
    std::string id() const { return getProperties().id; }

    /** Returns tile index.
     */
    const TileIndex& tileIndex() const;

    /** Returns tile index in given lod range
     */
    TileIndex tileIndex(const LodRange &lodRange) const;

    /** Derives metatile index from tile index
     */
    TileIndex metaIndex() const;

    /** Returns sphere of influence of this tileset.
     *
     *  SoI are all tiles that have giventype and also tiles above and below
     *  them.
     *
     * \param range optional LOD range in which to generate the SoI;
     *              defaults to tileset's LOD range
     * \param type type of tile to check
     * \return SoI where only influenced tile has non-zero value
     */
    TileIndex sphereOfInfluence(const LodRange &range = LodRange::emptyRange()
                                , TileIndex::Flag::value_type type
                                = TileIndex::Flag::mesh)
        const;

    typedef std::vector<const TileSet*> const_ptrlist;

    typedef std::vector<TileSet> list;

    bool externallyChanged() const;

    /** Returns time of last modification. Recorded at read-only open.
     */
    std::time_t lastModified() const;

    /** Returns information about used resources.
     */
    storage::Resources resources() const;

    /** Tells caller whether this tileset can contain given tile set.
     */
    bool canContain(const NodeInfo &nodeInfo) const;

    /** Pastes other tileset into this one.
     */
    void paste(const TileSet &src
               , const boost::optional<LodRange> &lodRange = boost::none);

    /** Returns type information.
     */
    std::string typeInfo() const;

    /** Get node info for given tile.
     */
    NodeInfo nodeInfo(const TileId &tileId) const;

    /** Returns representative texel size. Computed on the fly from most
     *  detailed LOD's metanodes.
     */
    double texelSize() const;

    /** Returns root node.
     */
    NodeInfo rootNode() const;

    /** Returns mapConfig for given path.
     *
     * \param root root path of all datasets (surfaces and glues)
     * \param includeExtra include extra configuration in the output.
     * \return map configuration
     */
    static MapConfig mapConfig(const boost::filesystem::path &root
                               , bool includeExtra = true);

    /** Returns mapConfig for given driver.
     *
     * \param driver data source
     * \param includeExtra include extra configuration in the output.
     * \return map configuration
     */
    static MapConfig mapConfig(const Driver &driver, bool includeExtra);

    /** Returns meshTiles config for given path.
     *
     * \param root root path of all datasets (surfaces and glues)
     * \return map configuration
     */
    static MeshTilesConfig meshTilesConfig(const boost::filesystem::path &root
                                           , bool includeExtra = true);

    /** Returns meshTiles config for given driver.
     *
     * \param driver data source
     * \return map configuration
     */
    static MeshTilesConfig meshTilesConfig(const Driver &driver
                                           , bool includeExtra);

    /** Check for tileset at given path.
     */
    static bool check(const boost::filesystem::path &root);

    /** Check for tileset at given path.
     */
    static bool check(const boost::filesystem::path &root
                      , const std::string &mime);

    /** Low level access: open driver directly.
     *  You need to include tileset/driver.hpp to access it.
     */
    static std::shared_ptr<Driver>
    openDriver(const boost::filesystem::path &root
               , const OpenOptions &openOptions = OpenOptions());

    static void relocate(const boost::filesystem::path &root
                         , const RelocateOptions &options
                         , const std::string &prefix = "");

    /** Recursively reencode datasets:
     *  plain: reencoded
     *  local: recursive reencode, revision bump on success
     *  remote: revision bump
     *  local: recursive reencode, revision bump on success
     */
    static void reencode(const boost::filesystem::path &root
                         , const ReencodeOptions &options
                         , const std::string &prefix = "");

    /** Creates glue from given sets.
     *
     * \param glue output tileset for glue tiles
     * \param sets input tilesets
     * \param options glue creation options
     *
     *  Priority grows from left to right.
     *
     */
    static void createGlue(TileSet &glue, const list &sets
                           , const GlueCreationOptions &options);

    /** Glue statistics returned by analyzeGlue.
     */
    struct GlueStatistics {
        std::size_t tilesToGenerate;

        GlueStatistics() : tilesToGenerate() {}
    };

    /** Updates revision to be at least equal to the provided number.
     */
    unsigned int ensureRevision(unsigned int revision);

    /** Tries to get revision from other tileset. If such revision can be read
     *  then calls ensureRevision(oldRevision + 1).
     */
    unsigned int ensureRevision(const boost::filesystem::path &root);

    /** Analyze glue from given sets.
     *
     * \param sets input tilesets
     * \param options glue creation options
     *
     *  Priority grows from left to right.
     *
     */
    static GlueStatistics analyzeGlue(const list &sets
                                      , const GlueCreationOptions &options);

    /** Internals. Public to ease library developers' life, not to allow users
     *  to put their dirty hands in the tileset's guts!
     */
    struct Detail;

    /** Full tileset properties.
     */
    typedef FullTileSetProperties Properties;

private:
    TileSet(const std::shared_ptr<Driver> &driver
            , const TileSet::Properties &properties);
    TileSet(const std::shared_ptr<Driver> &driver);

    std::shared_ptr<Detail> detail_;

public:
    Detail& detail() { return *detail_; }
    const Detail& detail() const { return *detail_; }

    /** Needed to instantiate.
     */
    class Factory; friend class Factory;

    /** Driver helper.
     */
    friend class Driver;
};

/** Low-level create operation.
 */
TileSet createTileSet(const boost::filesystem::path &path
                      , const TileSet::Properties &properties
                      , CreateMode mode);

} } // namespace vtslibs::vts

#endif // vtslibs_vts_tileset_hpp_included_

max_stars_repo_name: melowntech/vts-libs

max_issues_repo_name: HanochZhu/vts-browser-unity-plugin

max_forks_repo_name: HanochZhu/vts-browser-unity-plugin


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

#include <boost/interprocess/sync/file_lock.hpp>
#include <boost/interprocess/sync/named_recursive_mutex.hpp>
#include <cstdint>
#include <ctime>
#include <ipmid/api.hpp>
#include <sdbusplus/bus.hpp>
#include <variant>

namespace ipmi
{

using DbusUserPropVariant =
    std::variant<std::vector<std::string>, std::string, bool>;

using DbusUserObjPath = sdbusplus::message::object_path;

using DbusUserObjProperties =
    std::vector<std::pair<std::string, DbusUserPropVariant>>;

using DbusUserObjValue = std::map<std::string, DbusUserObjProperties>;

/**
 * @enum User update events.
 */
enum class UserUpdateEvent
{
    reservedEvent,
    userCreated,
    userDeleted,
    userRenamed,
    userGrpUpdated,
    userPrivUpdated,
    userStateUpdated
};

/** @struct UserPrivAccess
 *
 *  Structure for user privilege access (refer spec sec 22.22)
 */
struct UserPrivAccess
{
    uint8_t privilege;
    bool ipmiEnabled;
    bool linkAuthEnabled;
    bool accessCallback;
};

/** @struct UserInfo
 *
 *  Structure for user related information
 */
struct UserInfo
{
    uint8_t userName[ipmiMaxUserName];
    UserPrivAccess userPrivAccess[ipmiMaxChannels];
    bool userEnabled;
    bool userInSystem;
    bool fixedUserName;
    PayloadAccess payloadAccess[ipmiMaxChannels];
};

/** @struct UsersTbl
 *
 *  Structure for array of user related information
 */
struct UsersTbl
{
    //+1 to map with UserId directly. UserId 0 is reserved.
    UserInfo user[ipmiMaxUsers + 1];
};

/** @brief PAM User Authentication check
 *
 *  @param[in] username - username in string
 *  @param[in] password	- password in string
 *
 *  @return status
 */
bool pamUserCheckAuthenticate(std::string_view username,
                              std::string_view password);

class UserAccess;

UserAccess& getUserAccessObject();

class UserAccess
{
  public:
    UserAccess(const UserAccess&) = delete;
    UserAccess& operator=(const UserAccess&) = delete;
    UserAccess(UserAccess&&) = delete;
    UserAccess& operator=(UserAccess&&) = delete;

    ~UserAccess();
    UserAccess();

    /** @brief determines valid channel
     *
     *  @param[in] chNum - channel number
     *
     *  @return true if valid, false otherwise
     */
    static bool isValidChannel(const uint8_t chNum);

    /** @brief determines valid userId
     *
     *  @param[in] userId - user id
     *
     *  @return true if valid, false otherwise
     */
    static bool isValidUserId(const uint8_t userId);

    /** @brief determines valid user privilege
     *
     *  @param[in] priv - Privilege
     *
     *  @return true if valid, false otherwise
     */
    static bool isValidPrivilege(const uint8_t priv);

    /** @brief determines sync index to be mapped with common-user-management
     *
     *  @return Index which will be used as sync index
     */
    static uint8_t getUsrMgmtSyncIndex();

    /** @brief Converts system privilege to IPMI privilege
     *
     *  @param[in] value - Privilege in string
     *
     *  @return CommandPrivilege - IPMI privilege type
     */
    static CommandPrivilege convertToIPMIPrivilege(const std::string& value);

    /** @brief Converts IPMI privilege to system privilege
     *
     *  @param[in] value - IPMI privilege
     *
     *  @return System privilege in string
     */
    static std::string convertToSystemPrivilege(const CommandPrivilege& value);

    /** @brief determines whether user name is valid
     *
     *  @param[in] userNameInChar - user name
     *
     *  @return true if valid, false otherwise
     */
    bool isValidUserName(const std::string& userName);

    /** @brief determines whether ipmi is in available groups list
     *
     * @return true if ipmi group is present, false otherwise
     */
    bool isIpmiInAvailableGroupList();

    /** @brief provides user id of the user
     *
     *  @param[in] userName - user name
     *
     *  @return user id of the user, else invalid user id (0xFF), if user not
     * found
     */
    uint8_t getUserId(const std::string& userName);

    /** @brief provides user information
     *
     *  @param[in] userId - user id
     *
     *  @return UserInfo for the specified user id
     */
    UserInfo* getUserInfo(const uint8_t userId);

    /** @brief sets user information
     *
     *  @param[in] userId - user id
     *  @param[in] userInfo - user information
     *
     */
    void setUserInfo(const uint8_t userId, UserInfo* userInfo);

    /** @brief provides user name
     *
     *  @param[in] userId - user id
     *  @param[out] userName - user name
     *
     *  @return ccSuccess for success, others for failure.
     */
    Cc getUserName(const uint8_t userId, std::string& userName);

    /** @brief to set user name
     *
     *  @param[in] userId - user id
     *  @param[in] userName - user name
     *
     *  @return ccSuccess for success, others for failure.
     */
    Cc setUserName(const uint8_t userId, const std::string& userName);

    /** @brief to set user enabled state
     *
     *  @param[in] userId - user id
     *  @param[in] enabledState - enabled state of the user
     *
     *  @return ccSuccess for success, others for failure.
     */
    Cc setUserEnabledState(const uint8_t userId, const bool& enabledState);

    /** @brief to set user password
     *
     *  @param[in] userId - user id
     *  @param[in] userPassword  - new password of the user
     *
     *  @return ccSuccess for success, others for failure.
     */
    Cc setUserPassword(const uint8_t userId, const char* userPassword);

    /** @brief to set special user password
     *
     *  @param[in] userName - user name
     *  @param[in] userPassword  - new password of the user
     *
     *  @return ccSuccess for success, others for failure.
     */
    Cc setSpecialUserPassword(const std::string& userName,
                              const std::string& userPassword);

    /** @brief to set user privilege and access details
     *
     *  @param[in] userId - user id
     *  @param[in] chNum - channel number
     *  @param[in] privAccess - privilege access
     *  @param[in] otherPrivUpdates - other privilege update flag to update ipmi
     * enable, link authentication and access callback
     *
     *  @return ccSuccess for success, others for failure.
     */
    Cc setUserPrivilegeAccess(const uint8_t userId, const uint8_t chNum,
                              const UserPrivAccess& privAccess,
                              const bool& otherPrivUpdates);

    /** @brief to get user payload access details from userInfo entry.
     *
     *  @param[in] userInfo    - userInfo entry in usersTbl.
     *  @param[out] stdPayload - stdPayloadEnables1 in a 2D-array.
     *  @param[out] oemPayload - oemPayloadEnables1 in a 2D-array.
     *
     *  @details Update the given 2D-arrays using the payload access details
     *  available in the given userInfo entry (from usersTbl).
     *  This 2D-array will be mapped to a JSON object (which will be written to
     *  a JSON file subsequently).
     */
    void readPayloadAccessFromUserInfo(
        const UserInfo& userInfo,
        std::array<std::array<bool, ipmiMaxChannels>, payloadsPerByte>&
            stdPayload,
        std::array<std::array<bool, ipmiMaxChannels>, payloadsPerByte>&
            oemPayload);

    /** @brief to update user payload access details in userInfo entry.
     *
     *  @param[in] stdPayload - stdPayloadEnables1 in a 2D-array.
     *  @param[in] oemPayload - oemPayloadEnables1 in a 2D-array.
     *  @param[out] userInfo  - userInfo entry in usersTbl.
     *
     *  @details Update user payload access details of a given userInfo
     *  entry (in usersTbl) with the information provided in given 2D-arrays.
     *  This 2D-array was created out of a JSON object (which was created by
     *  parsing a JSON file).
     */
    void updatePayloadAccessInUserInfo(
        const std::array<std::array<bool, ipmiMaxChannels>, payloadsPerByte>&
            stdPayload,
        const std::array<std::array<bool, ipmiMaxChannels>, payloadsPerByte>&
            oemPayload,
        UserInfo& userInfo);

    /** @brief to set user payload access details
     *
     *  @param[in] chNum - channel number
     *  @param[in] operation - Enable / Disable
     *  @param[in] userId - user id
     *  @param[in] payloadAccess - payload access
     *
     *  @return ccSuccess for success, others for failure.
     */
    Cc setUserPayloadAccess(const uint8_t chNum, const uint8_t operation,
                            const uint8_t userId,
                            const PayloadAccess& payloadAccess);

    /** @brief reads user management related data from configuration file
     *
     */
    void readUserData();

    /** @brief writes user management related data to configuration file
     *
     */
    void writeUserData();

    /** @brief Funtion which checks and reload configuration file data if
     * needed.
     *
     */
    void checkAndReloadUserData();

    /** @brief provides user details from D-Bus user property data
     *
     *  @param[in] properties - D-Bus user property
     *  @param[out] usrGrps - user group details
     *  @param[out] usrPriv - user privilege
     *  @param[out] usrEnabled - enabled state of the user.
     *
     *  @return 0 for success, -errno for failure.
     */
    void getUserProperties(const DbusUserObjProperties& properties,
                           std::vector<std::string>& usrGrps,
                           std::string& usrPriv, bool& usrEnabled);

    /** @brief provides user details from D-Bus user object data
     *
     *  @param[in] userObjs - D-Bus user object
     *  @param[out] usrGrps - user group details
     *  @param[out] usrPriv - user privilege
     *  @param[out] usrEnabled - enabled state of the user.
     *
     *  @return 0 for success, -errno for failure.
     */
    int getUserObjProperties(const DbusUserObjValue& userObjs,
                             std::vector<std::string>& usrGrps,
                             std::string& usrPriv, bool& usrEnabled);

    /** @brief function to add user entry information to the configuration
     *
     *  @param[in] userName - user name
     *  @param[in] priv - privilege of the user
     *  @param[in] enabled - enabled state of the user
     *
     *  @return true for success, false for failure
     */
    bool addUserEntry(const std::string& userName, const std::string& priv,
                      const bool& enabled);

    /** @brief function to delete user entry based on user index
     *
     *  @param[in] usrIdx - user index
     *
     */
    void deleteUserIndex(const size_t& usrIdx);

    /** @brief function to get users table
     *
     */
    UsersTbl* getUsersTblPtr();

    std::unique_ptr<boost::interprocess::named_recursive_mutex> userMutex{
        nullptr};

  private:
    UsersTbl usersTbl;
    std::vector<std::string> availablePrivileges;
    std::vector<std::string> availableGroups;
    sdbusplus::bus::bus bus;
    std::time_t fileLastUpdatedTime;
    bool signalHndlrObject = false;
    boost::interprocess::file_lock sigHndlrLock;
    boost::interprocess::file_lock mutexCleanupLock;

    /** @brief function to get user configuration file timestamp
     *
     *  @return time stamp or -EIO for failure
     */
    std::time_t getUpdatedFileTime();

    /** @brief function to available system privileges and groups
     *
     */
    void getSystemPrivAndGroups();

    /** @brief function to init user data from configuration & D-Bus objects
     * and to register for signals
     *
     */
    void cacheUserDataFile();
};

} // namespace ipmi

max_stars_repo_name: cjcain/phosphor-host-ipmid

max_issues_repo_name: cjcain/phosphor-host-ipmid

max_forks_repo_name: cjcain/phosphor-host-ipmid


text:
#define BOOST_TEST_MODULE task
#include <boost/test/unit_test.hpp>

#include <bunsan/broker/task/stream_channel.hpp>

#include <bunsan/crypto/base64.hpp>
#include <bunsan/protobuf/binary.hpp>

#include <sstream>

namespace broker = bunsan::broker;
namespace task = broker::task;

BOOST_AUTO_TEST_SUITE(task_)

struct stream_channel_fixture {
  std::ostringstream sout;
  task::stream_channel channel{sout};

  template <typename Message>
  Message check_command(const std::string &command) {
    BOOST_REQUIRE(!sout.str().empty());
    BOOST_TEST_MESSAGE("[" << sout.str() << "]");
    BOOST_CHECK_EQUAL(sout.str().find('\n'), sout.str().size() - 1);
    std::istringstream sin(sout.str());
    std::string cmd;
    BOOST_CHECK(sin >> cmd);
    BOOST_CHECK_EQUAL(cmd, command);
    std::string data;
    BOOST_CHECK(sin >> data);
    std::string empty;
    BOOST_CHECK(!(sin >> empty));
    return bunsan::protobuf::binary::parse_make<Message>(
        bunsan::crypto::base64::decode(data));
  }
};

BOOST_FIXTURE_TEST_SUITE(stream_channel, stream_channel_fixture)

BOOST_AUTO_TEST_CASE(send_status) {
  broker::Status status;
  status.set_code(123);
  status.set_reason("test reason");
  status.set_data("test data");
  channel.send_status(status);
  const auto status_ = check_command<broker::Status>("status");
  BOOST_CHECK_EQUAL(status_.code(), status.code());
  BOOST_CHECK_EQUAL(status_.reason(), status.reason());
  BOOST_CHECK_EQUAL(status_.data(), status.data());
}

BOOST_AUTO_TEST_CASE(send_result) {
  broker::Result result;
  result.set_status(broker::Result::ERROR);
  result.set_reason("test reason");
  result.set_data("test data");
  channel.send_result(result);
  const auto result_ = check_command<broker::Result>("result");
  BOOST_CHECK_EQUAL(result_.status(), result.status());
  BOOST_CHECK_EQUAL(result_.reason(), result.reason());
  BOOST_CHECK_EQUAL(result_.data(), result.data());
}

BOOST_AUTO_TEST_SUITE_END()  // stream_channel

BOOST_AUTO_TEST_SUITE_END()  // task_

ext: cpp

max_stars_repo_name: bunsanorg/broker

max_issues_repo_name: bunsanorg/broker

max_forks_repo_name: bunsanorg/broker


text:
#include "qnodedialog.h"
#include "ui_qnodedialog.h"
#include <boost/make_shared.hpp>
#include <QSettings>
#include <QMessageBox>

std::string getDefaultMasterURI()
{
    if(  qgetenv("ROS_MASTER_URI").isEmpty() )
    {
      QMessageBox msgBox;
      msgBox.setText("WARNINGS: the ROS_MASTER_URI is not defined in your environment\n"
                     "Using the default value [http://localhost:11311]\n");
      msgBox.exec();
      return "http://localhost:11311";
    }
    else{
      auto master_uri = ( qgetenv("ROS_MASTER_URI"));
      return std::string( master_uri.data() );
    }
}

QNodeDialog::QNodeDialog( QWidget *parent) :
  QDialog(parent),
  ui(new Ui::QNodeDialog)
{
  ui->setupUi(this);

  QSettings settings( "IcarusTechnology", "PlotJuggler");

  auto master_ui = settings.value("QNode.master_uri", tr("http://localhost:11311")).toString();
  auto host_ip   = settings.value("QNode.host_ip", tr("localhost")).toString();

  ui->lineEditMaster->setText( master_ui );
  ui->lineEditHost->setText( host_ip );
}

namespace ros {
    namespace master {
        void init(const M_string& remappings);
    }
}

bool QNodeDialog::Connect(const std::string& ros_master_uri,
                          const std::string& hostname)
{
  std::map<std::string,std::string> remappings;
  remappings["__master"] = ros_master_uri;
  remappings["__hostname"] = hostname;

  static bool first_time = true;
  if( first_time)
  {
      ros::init(remappings,"PlotJugglerListener");
      first_time = false;
  }
  else{
      ros::master::init(remappings);
  }

  bool connected = ros::master::check();
  if ( ! connected ) {
      QMessageBox msgBox;
      msgBox.setText( QString("Could not connect to the ros master [%1]").
                      arg(QString::fromStdString(ros_master_uri)));
      msgBox.exec();
  }
  return connected;
}

QNodeDialog::~QNodeDialog()
{
  QSettings settings( "IcarusTechnology", "PlotJuggler");
  settings.setValue ("QNode.master_uri",  ui->lineEditMaster->text() );
  settings.setValue("QNode.host_ip",      ui->lineEditHost->text() );
  delete ui;
}

void QNodeDialog::on_pushButtonConnect_pressed()
{
    bool connected = false;
    if( ui->checkBoxUseEnvironment->isChecked() )
    {
        const std::string master_uri = getDefaultMasterURI();
        connected = QNodeDialog::Connect(master_uri, "localhost" );
    }
    else{
        std::string ros_master_uri = ui->lineEditMaster->text().toStdString();
        std::string hostname       = ui->lineEditHost->text().toStdString();
        connected = QNodeDialog::Connect(ros_master_uri, hostname);
    }
    if( connected ) {
        this->close();
    }
    else{

    }
}

void QNodeDialog::on_checkBoxUseEnvironment_toggled(bool checked)
{
    ui->lineEditMaster->setEnabled( !checked );
    ui->lineEditHost->setEnabled( !checked );
}

void QNodeDialog::on_pushButtonCancel_pressed()
{
    this->close();
}

RosManager &RosManager::get()
{
    static RosManager manager;
    return manager;
}

void RosManager::stopROS()
{
    if(ros::isStarted() )
    {
        ros::shutdown(); // explicitly needed since we use ros::start();;
        ros::waitForShutdown();
    }
}

RosManager::~RosManager()
{

}

ros::NodeHandlePtr RosManager::getNode()
{
    RosManager& manager = RosManager::get();

    if(!ros::isInitialized() || !ros::master::check() )
    {
        bool connected = QNodeDialog::Connect(getDefaultMasterURI(), "localhost" );
        if ( ! connected )
        {
            //as a fallback strategy, launch the QNodeDialog
            QNodeDialog dialog;
            dialog.exec();
        }
    }
    if ( ros::master::check() && ros::isInitialized())
    {
        if( !manager._node ){
            manager._node = ros::NodeHandlePtr(new ros::NodeHandle, [](ros::NodeHandle* node)
            {
                    RosManager::get().stopROS();
            }  );
        }
        ros::start();
    }
    return manager._node;
}


text:
//          Copyright Gavin Band 2008 - 2012.
// Distributed under the Boost Software License, Version 1.0.
//    (See accompanying file LICENSE_1_0.txt or copy at
//          http://www.boost.org/LICENSE_1_0.txt)

#ifndef COMPONENTS_SNPOUTPUTCOMPONENT_SNPOUTPUTCOMPONENT_HPP
#define COMPONENTS_SNPOUTPUTCOMPONENT_SNPOUTPUTCOMPONENT_HPP

#include <Eigen/Core>
#include "genfile/CohortIndividualSource.hpp"
#include "genfile/SNPDataSourceProcessor.hpp"
#include "genfile/SNPDataSink.hpp"
#include "genfile/VariantIdentifyingData.hpp"
#include "genfile/VariantDataReader.hpp"
#include "qcdb/DBOutputter.hpp"
#include "appcontext/OptionProcessor.hpp"
#include "appcontext/UIContext.hpp"

namespace impl {

	struct SNPDataSourceIndex {
		typedef std::auto_ptr< SNPDataSourceIndex > UniquePtr ;
		virtual ~SNPDataSourceIndex() {}
		virtual void add_index_entry( genfile::VariantIdentifyingData const& snp, genfile::SNPDataSink& sink ) = 0 ;
		virtual void finalise() = 0 ;
	} ;

	struct SNPOutputter: public genfile::SNPDataSourceProcessor::Callback {
	public:
		typedef std::auto_ptr< SNPOutputter > UniquePtr ;
		static UniquePtr create( genfile::CohortIndividualSource const& samples, genfile::SNPDataSink& sink ) ;
	public:
		SNPOutputter( genfile::CohortIndividualSource const& samples, genfile::SNPDataSink& sink ) ;
		~SNPOutputter() ;

		void begin_processing_snps( std::size_t number_of_samples, genfile::SNPDataSource::Metadata const& metadata ) ;
		void processed_snp( genfile::VariantIdentifyingData const&, genfile::VariantDataReader& data_reader ) ;
		void end_processing_snps() ;

		typedef boost::function< void ( genfile::VariantIdentifyingData const& snp, genfile::SNPDataSink& sink ) > IndexCallback ;
		void send_index_to( impl::SNPDataSourceIndex::UniquePtr index ) ;

	private:
		genfile::CohortIndividualSource const& m_samples ;
		bool m_manage ;
		genfile::SNPDataSink* m_sink ;
		impl::SNPDataSourceIndex::UniquePtr m_index ;
		Eigen::MatrixXd m_genotypes ;

	} ;
}

struct SNPOutputComponent: public boost::noncopyable {
	static void declare_options( appcontext::OptionProcessor& options ) ;

	SNPOutputComponent(
		genfile::CohortIndividualSource const& samples,
		appcontext::OptionProcessor const& options,
		appcontext::UIContext& ui_context
	) ;

	void setup( genfile::SNPDataSink& sink, genfile::SNPDataSourceProcessor& processor ) ;

	private:
		genfile::CohortIndividualSource const& m_samples ;
		appcontext::OptionProcessor const& m_options ;
} ;

#endif

max_stars_repo_name: CreRecombinase/qctool

max_issues_repo_name: CreRecombinase/qctool

max_forks_repo_name: gavinband/qctool


text:
// Copyright (C) Vladimir Prus 2003. Permission to copy, use,
// modify, sell and distribute this software is granted provided this
// copyright notice appears in all copies. This software is provided
// "as is" without express or implied warranty, and with no claim as
// to its suitability for any purpose.

#include <boost/graph/adjacency_list.hpp>
#include <boost/graph/copy.hpp>

using namespace boost;

class copier {
public:
    template<class V1, class V2>
    void operator()(const V1&, const V2&) const {}
};

int main()
{
    adjacency_list<vecS, vecS, directedS, property<vertex_root_t, int> > g1, g2;
    adjacency_list<vecS, setS, directedS, property<vertex_index_t, int> > g3;

    copy_graph(g1, g2);
    copier c;
    copy_graph(g3, g1, vertex_copy(c));
}


text:
#pragma once

#include "search/result.hpp"
#include "search/search_quality/assessment_tool/context.hpp"
#include "search/search_quality/assessment_tool/edits.hpp"
#include "search/search_quality/sample.hpp"

#include "geometry/point2d.hpp"
#include "geometry/rect2d.hpp"

#include <cstddef>
#include <string>
#include <vector>

#include <boost/optional.hpp>

class ResultsEdits;
class Model;

class View
{
public:
  enum class ResultType
  {
    Found,
    NonFound
  };

  virtual ~View() = default;

  void SetModel(Model & model) { m_model = &model; }

  virtual void SetSamples(ContextList::SamplesSlice const & samples) = 0;
  virtual void OnSearchStarted() = 0;
  virtual void OnSearchCompleted() = 0;
  virtual void ShowSample(size_t index, search::Sample const & sample,
                          boost::optional<m2::PointD> const & position, bool isUseless,
                          bool hasEdits) = 0;

  virtual void AddFoundResults(search::Results::ConstIter begin,
                               search::Results::ConstIter end) = 0;
  virtual void ShowNonFoundResults(std::vector<search::Sample::Result> const & results,
                                   std::vector<ResultsEdits::Entry> const & entries) = 0;

  virtual void ShowMarks(Context const & context) = 0;
  virtual void ShowFoundResultsMarks(search::Results::ConstIter begin,
                                     search::Results::ConstIter end) = 0;
  virtual void ShowNonFoundResultsMarks(std::vector<search::Sample::Result> const & results,
                                        std::vector<ResultsEdits::Entry> const & entries) = 0;
  virtual void ClearSearchResultMarks() = 0;

  virtual void MoveViewportToResult(search::Result const & result) = 0;
  virtual void MoveViewportToResult(search::Sample::Result const & result) = 0;
  virtual void MoveViewportToRect(m2::RectD const & rect) = 0;

  virtual void OnResultChanged(size_t sampleIndex, ResultType type,
                               ResultsEdits::Update const & update) = 0;
  virtual void SetResultsEdits(size_t index, ResultsEdits & foundResultsEdits,
                               ResultsEdits & nonFoundResultsEdits) = 0;
  virtual void OnSampleChanged(size_t sampleIndex, bool isUseless, bool hasEdits) = 0;
  virtual void OnSamplesChanged(bool hasEdits) = 0;

  virtual void ShowError(std::string const & msg) = 0;

  virtual void Clear() = 0;

protected:
  Model * m_model = nullptr;
};

inline std::string DebugPrint(View::ResultType type)
{
  switch (type)
  {
  case View::ResultType::Found: return "Found";
  case View::ResultType::NonFound: return "NonFound";
  }
  return "Unknown";
}

max_stars_repo_name: letko-dmitry/omim

max_issues_repo_name: Mahmoudabdelmobdy/omim

max_forks_repo_name: vmihaylenko/omim


text:
#ifndef STOCK_UPDATE_WORKER_HPP
#define STOCK_UPDATE_WORKER_HPP

#include <memory>
#include <mutex>
#include <string>
#include <boost/thread/thread.hpp>

namespace StockMarket {
    class StockUpdateWorker;
}

class StockMarket::StockUpdateWorker
{
public:
    typedef boost::int_least64_t Interval_t;

private:
    struct Impl;
    std::unique_ptr<Impl> m_pimpl;

public:
    StockUpdateWorker();
    StockUpdateWorker(const std::string &sourceURL,
                      const StockUpdateWorker::Interval_t interval,
                      const std::string &tempFile,
                      bool startImmediately = false);
    ~StockUpdateWorker();

public:
    std::string GetSourceURL();
    boost::int_least64_t GetInterval();
    std::string GetTempFile();

    void SetSourceURL(const std::string &sourceFile);
    void SetInterval(boost::int_least64_t interval);
    void SetTempFile(const std::string &tempFile);

public:
    bool IsRunning();
    void Start();
    void Stop();
};

#endif /* STOCK_UPDATE_WORKER_HPP */

max_stars_repo_licenses: Unlicense MIT

max_issues_repo_licenses: Unlicense MIT

max_forks_repo_licenses: Unlicense MIT


text: #include <boost/numeric/odeint/external/vexcl/vexcl_abs.hpp>

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


text:
#ifndef SERVER_HPP
#define SERVER_HPP

#include <string>
#include <boost/bind.hpp>
#include <boost/function.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/thread/mutex.hpp>
#include <boost/thread.hpp>
#include <zmq.hpp>

namespace ULogger {
    class Server;
}

class ULogger::Server
{
private:
    typedef boost::shared_ptr<boost::thread> ThreadPtr;
    typedef boost::shared_ptr<zmq::context_t> ContextPtr;
    typedef boost::shared_ptr<zmq::socket_t> SocketPtr;

private:
    static const std::string MSG_RECEIVED;
    static const std::string MSG_INVALID;

public:
    boost::function<void(const std::string &, const std::string &)> OnMessageReceived;

private:
	bool m_running;
	size_t m_port;

    ThreadPtr m_workerThread;
    boost::mutex m_workerMutex;

    ContextPtr m_context;
    SocketPtr m_socket;

public:
    Server();
    Server(size_t port);
    ~Server();

public:
    void SetPort(const size_t port);

    bool IsRunning();
	void Start();
	void Stop();

private:
	void Listen();
	std::string GetMessage(const zmq::message_t &msg);
    bool SendResponse(const std::string &str);
};

#endif /* SERVER_HPP */


text:
/*
 * Copyright (c) 2014, Stanislav Vorobiov
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice, this
 *    list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 *    this list of conditions and the following disclaimer in the documentation
 *    and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "TentacleAttractComponent.h"
#include "SceneObject.h"
#include "SceneObjectFactory.h"
#include "Scene.h"
#include "Utils.h"
#include "Settings.h"
#include "af/Utils.h"
#include <boost/make_shared.hpp>

namespace af
{
    TentacleAttractComponent::TentacleAttractComponent(float frequency, float dampingRatio)
    : TargetableComponent(phaseThink),
      bone_(-1),
      frequency_(frequency),
      dampingRatio_(dampingRatio)
    {
    }

    TentacleAttractComponent::~TentacleAttractComponent()
    {
    }

    void TentacleAttractComponent::accept(ComponentVisitor& visitor)
    {
        visitor.visitPhasedComponent(shared_from_this());
    }

    void TentacleAttractComponent::update(float dt)
    {
        if (!target()) {
            if (joint_) {
                joint_->remove();
                joint_.reset();
            }
            return;
        }

        if (!joint_) {
            assert(bone_ < static_cast<int>(tentacle_->objects().size()));

            dummy_->setTransform(target()->getTransform());
            joint_ = scene()->addDistanceJoint(tentacle_->objects()[bone_], dummy_,
                b2Vec2_zero, b2Vec2_zero, 0.0f,
                frequency_, dampingRatio_, false);
        }

        dummy_->setLinearVelocity((1.0f / settings.physics.fixedTimestep) * (target()->pos() - dummy_->pos()));
        dummy_->setAngularVelocity((1.0f / settings.physics.fixedTimestep) * normalizeAngle(target()->angle() - dummy_->angle()));
    }

    void TentacleAttractComponent::onRegister()
    {
        tentacle_ = parent()->findComponent<RenderTentacleComponent>();

        dummy_ = sceneObjectFactory.createDummy();
        scene()->addObject(dummy_);

        if (bone_ == -1) {
            bone_ = tentacle_->objects().size() - 1;
        }

        assert(bone_ < static_cast<int>(tentacle_->objects().size()));

        if (target()) {
            dummy_->setTransform(target()->getTransform());
            joint_ = scene()->addDistanceJoint(tentacle_->objects()[bone_], dummy_,
                b2Vec2_zero, b2Vec2_zero, 0.0f,
                frequency_, dampingRatio_, false);
        }
    }

    void TentacleAttractComponent::onUnregister()
    {
        setTarget(SceneObjectPtr());
        dummy_->removeFromParent();
        dummy_.reset();
    }
}

max_stars_repo_name: Sheph/TriggerTime

max_issues_repo_name: Sheph/TriggerTime

max_forks_repo_name: Sheph/TriggerTime


text:
#pragma once

#include <memory>
#include <utility>

#include <boost/operators.hpp>

#include <elle/attribute.hh>
#include <elle/operator.hh>
#include <elle/serialization.hh>

#include <elle/cryptography/fwd.hh>
#include <elle/cryptography/types.hh>
#include <elle/cryptography/Oneway.hh>
#include <elle/cryptography/Cipher.hh>
#if defined(ELLE_CRYPTOGRAPHY_ROTATION)
# include <elle/cryptography/rsa/Seed.hh>
#endif
#include <elle/cryptography/rsa/Padding.hh>
#include <elle/cryptography/rsa/defaults.hh>

namespace elle
{
  namespace cryptography
  {
    namespace rsa
    {
      /// Represent a public key in the RSA asymmetric cryptosystem.
      class PublicKey
        : public elle::Printable
        , public std::enable_shared_from_this<PublicKey>
        , private boost::totally_ordered<PublicKey>
      {
      /*-------------.
      | Construction |
      `-------------*/
      public:
        /// Construct a public key out of its private counterpart.
        explicit
        PublicKey(PrivateKey const& k);
        /// Construct a public key based on the given EVP_PKEY key whose
        /// ownership is transferred.
        explicit
        PublicKey(::EVP_PKEY* key);
        /// Construct a public key based on the given RSA key whose
        /// ownership is transferred to the public key.
        explicit
        PublicKey(::RSA* rsa);
        PublicKey(PublicKey const& other);
        PublicKey(PublicKey&& other);
        virtual
        ~PublicKey() = default;

        /*--------.
        | Methods |
        `--------*/
      private:
        /// Check that the key is valid.
        void
        _check() const;
      public:
        /// Encrypt the plain text and return the ciphered text in an envelope.
        virtual
        elle::Buffer
        seal(elle::ConstWeakBuffer const& plain,
             Cipher const cipher = defaults::envelope_cipher,
             Mode const mode = defaults::envelope_mode) const;
        /// Encrypt the stream-based plain text and seal it in an envelope.
        void
        seal(std::istream& plain,
             std::ostream& code,
             Cipher const cipher = defaults::envelope_cipher,
             Mode const mode = defaults::envelope_mode) const;
        /// Encrypt a plain text using the raw public key.
        ///
        /// WARNING: This method cannot be used to encrypt large amount of
        ///          data as constrained by the key's modulus. Please refer
        ///          to the seal()/open() methods.
        virtual
        elle::Buffer
        encrypt(elle::ConstWeakBuffer const& plain,
                Padding const padding = defaults::encryption_padding) const;
        /// Verify the given signature against the original plain text.
        bool
        verify(elle::ConstWeakBuffer const& signature,
               elle::ConstWeakBuffer const& plain,
               Padding const padding = defaults::signature_padding,
               Oneway const oneway = defaults::oneway) const;
        /// Verify the given signature against the object
        template <typename T>
        bool
        verify(elle::ConstWeakBuffer const& signature, T const& o) const;
        template <typename T>
        std::function<bool ()>
        verify_async(elle::ConstWeakBuffer const& signature, T const& o) const;
      private:
        virtual
        bool
        _verify(elle::ConstWeakBuffer const& signature,
                elle::ConstWeakBuffer const& plain,
                Padding const padding = defaults::signature_padding,
                Oneway const oneway = defaults::oneway) const;
        template <typename T>
        std::pair<elle::Buffer, elle::Buffer>
        _verify_data(elle::ConstWeakBuffer const& signature,
                     T const& o) const;
      public:
        /// Whether the given signature matches the stream-based plain.
        bool
        verify(elle::ConstWeakBuffer const& signature,
               std::istream& plain,
               Padding const padding = defaults::signature_padding,
               Oneway const oneway = defaults::oneway) const;
        /// Return the public key's size in bytes.
        uint32_t
        size() const;
        /// Return the public key's length in bits.
        uint32_t
        length() const;
      private:
        bool
        _verify(elle::ConstWeakBuffer const& signature,
                std::istream& plain,
                Padding const padding = defaults::signature_padding,
                Oneway const oneway = defaults::oneway) const;

# if defined(ELLE_CRYPTOGRAPHY_ROTATION)
        /*---------.
        | Rotation |
        `---------*/
      public:
        /// Construct a public key based on a given seed i.e in a deterministic
        /// way.
        explicit
        PublicKey(Seed const& seed);
        /// Return the seed once unrotated by the public key.
        Seed
        unrotate(Seed const& seed) const;
# endif

        /*----------.
        | Operators |
        `----------*/
      public:
        bool
        operator ==(PublicKey const& other) const;
        bool
        operator <(PublicKey const& other) const;
        PublicKey&
        operator =(PublicKey&& other) = default;

        /*----------.
        | Printable |
        `----------*/
      public:
        void
        print(std::ostream& stream) const override;

        /*--------------.
        | Serialization |
        `--------------*/
      public:
        PublicKey(elle::serialization::SerializerIn& serializer);
        void
        serialize(elle::serialization::Serializer& serializer);
        using serialization_tag = elle::serialization_tag;

        /*-----------.
        | Attributes |
        `-----------*/
      public:
        ELLE_ATTRIBUTE_R(types::EVP_PKEY, key);
      };

      namespace _details
      {
        void
        raise(std::string const& message);
        types::EVP_PKEY
        build_evp(::RSA* rsa);
      }
    }
  }
}

//
// ---------- DER -------------------------------------------------------------
//

namespace elle
{
  namespace cryptography
  {
    namespace rsa
    {
      namespace publickey
      {
        namespace der
        {
          /*----------.
          | Functions |
          `----------*/

          /// Encode the public key in DER.
          elle::Buffer
          encode(PublicKey const& K);
          /// Decode the public key from a DER representation.
          PublicKey
          decode(elle::ConstWeakBuffer const& buffer);
        }
      }
    }
  }
}

namespace std
{
  template <>
  struct hash<elle::cryptography::rsa::PublicKey>
  {
    size_t
    operator ()(elle::cryptography::rsa::PublicKey const& value) const;
  };
}

#include <elle/cryptography/rsa/PublicKey.hxx>

ext: hh

max_stars_repo_name: infinitio/elle

max_issues_repo_name: infinitio/elle

max_forks_repo_name: infinitio/elle


text:
//  (C) Copyright Raffi Enficiaud 2017.
//  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)

//  See http://www.boost.org/libs/test for the library home page.

//[example_code
#define BOOST_TEST_MODULE fixture_04
#include <boost/test/included/unit_test.hpp>

struct MyGlobalFixture {
  MyGlobalFixture() {
      BOOST_TEST_MESSAGE( "ctor fixture i=" << i );
  }
  void setup() {
      BOOST_TEST_MESSAGE( "setup fixture i=" << i );
      i++;
  }
  void teardown() {
      BOOST_TEST_MESSAGE( "teardown fixture i=" << i );
      i += 2;
  }
  ~MyGlobalFixture() {
      BOOST_TEST_MESSAGE( "dtor fixture i=" << i );
  }
  static int i;
};
int MyGlobalFixture::i = 0;

BOOST_TEST_GLOBAL_FIXTURE( MyGlobalFixture );

BOOST_AUTO_TEST_CASE(test_case1)
{
  BOOST_TEST_MESSAGE("running test_case1");
  BOOST_TEST(MyGlobalFixture::i == 1);
}

BOOST_AUTO_TEST_CASE(test_case2)
{
  BOOST_TEST_MESSAGE("running test_case2");
  BOOST_TEST(MyGlobalFixture::i == 3);
}
//]


text:
#include "../src/FindHome.hxx"
#include <boost/format.hpp>
#include <iostream>

int main(int argc, char * argv[])
{
  (void) argc; (void) argv;
  std::string myhome = findHome();

  std::cerr << "My home is [" << myhome << "]" << std::endl;
}

ext: cxx


text:
#include <boost/python.hpp>
#include <boost/cstdint.hpp>

#include <Magick++/Include.h>

using namespace boost::python;

void __RenderingIntent()
{
    enum_< Magick::RenderingIntent >("RenderingIntent")
        .value("UndefinedIntent", Magick::UndefinedIntent)
        .value("SaturationIntent", Magick::SaturationIntent)
        .value("PerceptualIntent", Magick::PerceptualIntent)
        .value("AbsoluteIntent", Magick::AbsoluteIntent)
        .value("RelativeIntent", Magick::RelativeIntent)
    ;
}

max_stars_repo_name: veryhappythings/pgmagick

max_issues_repo_name: veryhappythings/pgmagick

max_forks_repo_name: veryhappythings/pgmagick


text:
#include "engine/core/app.h"

#include <boost/log/core.hpp>
#include <boost/log/trivial.hpp>
#include <boost/log/utility/setup/console.hpp>
#include <SDL2/SDL_ttf.h>

#include "engine/core/logging.h"
#include "engine/core/rtclock.h"
#include "engine/core/audio.h"

engine::App::App():
  _desc("Options"),
  _graphics(false),
  _audio(false),
  _asio(false),
  _resX(0),
  _resY(0),
  _nbAsioThreads(0),
  _clock(std::make_shared<RtClock>()),
  _window(nullptr, SDL_DestroyWindow),
  _glContext(nullptr, SDL_GL_DeleteContext),
  _alcDevice(nullptr, alcCloseDevice),
  _alcContext(nullptr, alcDestroyContext)
{
  _desc.add_options()
    ("help", "Displays help")
    ("verbose,v", "Verbose logging");
}

engine::App::~App()
{
  if(TTF_WasInit())
  {
    TTF_Quit();
  }

  stopAsio();
}

engine::App & engine::App::enableGraphics()
{
  _graphics = true;

  _desc.add_options()
    ("x", po::value<int>(&_resX)->default_value(1280), "X resolution")
    ("y", po::value<int>(&_resY)->default_value(1024), "Y resolution")
    ("full-screen", "Full screen")
    ("vsync", "Enable vertical synchronization");

  return *this;
}

engine::App & engine::App::enableAudio()
{
  _audio = true;

  return *this;
}

engine::App & engine::App::enableAsio()
{
  _asio = true;

  _desc.add_options()
    ("threads", po::value<unsigned int>(&_nbAsioThreads)->default_value(4), "Number of working threads");

  return *this;
}

po::options_description_easy_init engine::App::add_options()
{
  return _desc.add_options();
}

bool engine::App::run(int argc, char ** argv)
{
  po::store(po::parse_command_line(argc, argv, _desc), _vm);

  if (_vm.count("help"))
  {
    std::cout << _desc << std::endl;
    return false;
  }
  else
  {
    po::notify(_vm);

    // Logging
    BOOST_LOG_TRIVIAL(info) << "Init logging";
    engine::setLogLevel(_vm.count("verbose"));

    // Asio
    if(_asio)
    {
      initAsio();
    }

    // Graphics
    if(_graphics)
    {
      initGraphics();
    }

    // Fonts
    initTTF();

    // Audio
    if(_audio)
    {
      initAudio();
    }

    return true;
  }
}

bool engine::App::has(const std::string & option)
{
  return _vm.count(option);
}

engine::Clock * engine::App::clock()
{
  return _clock.get();
}

SDL_Window * engine::App::window()
{
  return _window.get();
}

int engine::App::resX() const
{
  return _resX;
}

int engine::App::resY() const
{
  return _resY;
}

ALCdevice * engine::App::audioDevice()
{
  return _alcDevice.get();
}

ALCcontext * engine::App::audioContext()
{
  return _alcContext.get();
}

boost::asio::io_context * engine::App::asioContext()
{
  return _asioContext.get();
}

void engine::App::stopAsio()
{
  if(_asio)
  {
    asioContext()->stop();
    for(auto && thread : _asioThreads)
    {
      thread.join();
    }
    _asioThreads.clear();
  }
}

void engine::App::initAsio()
{
  BOOST_LOG_TRIVIAL(info) << "Init threads";

  _asioContext = std::make_shared<boost::asio::io_context>();
  _workGuard = std::make_shared<work_guard>(_asioContext->get_executor());

  for (unsigned int index = 0; index < _nbAsioThreads; ++index)
  {
    _asioThreads.push_back(std::thread([this](){ _asioContext->run(); }));
    pthread_setname_np(_asioThreads.back().native_handle(), "asio");
  }

  BOOST_LOG_TRIVIAL(info) << "Created " << _nbAsioThreads << " work threads";
}

void engine::App::initGraphics()
{
  BOOST_LOG_TRIVIAL(info) << "Init graphics";

  if(SDL_Init(SDL_INIT_VIDEO) < 0)
    throw std::runtime_error(std::string("Failed to init SDL : ") + SDL_GetError());

  unsigned int videoFlags = SDL_WINDOW_OPENGL;
  if(has("full-screen"))
  {
    SDL_DisplayMode displayMode;
    if(SDL_GetDesktopDisplayMode(0, &displayMode) < 0)
      throw std::runtime_error(std::string("Failed to get display mode : ") + SDL_GetError());
    _resX = displayMode.w;
    _resY = displayMode.h;
    videoFlags |= SDL_WINDOW_FULLSCREEN;
  }

  BOOST_LOG_TRIVIAL(info) << "Setting up video mode to " << _resX << "x" << _resY;

  SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);

  _window.reset(SDL_CreateWindow("Viewer",
                                 SDL_WINDOWPOS_UNDEFINED,
                                 SDL_WINDOWPOS_UNDEFINED,
                                 _resX,
                                 _resY,
                                 videoFlags));

  _glContext.reset(SDL_GL_CreateContext(_window.get()));

  SDL_GL_SetSwapInterval(has("vsync") ? 1 : 0);
}

void engine::App::initTTF()
{
  if(TTF_Init() != 0)
  {
    throw std::runtime_error(std::string("Failed to initialise TTF : ") + TTF_GetError());
  }
}

void engine::App::initAudio()
{
  BOOST_LOG_TRIVIAL(info) << "Init audio";

  const char * deviceName = alcGetString(nullptr, ALC_DEFAULT_DEVICE_SPECIFIER);
  if(alcGetError(nullptr) != ALC_NO_ERROR)
    throw std::runtime_error(std::string("Failed to get default audio device : ")
                             + getAlcErrorString());

  BOOST_LOG_TRIVIAL(info) << "Default audio device is " << deviceName;

  _alcDevice.reset(alcOpenDevice(deviceName));
  if(alcGetError(nullptr) != ALC_NO_ERROR)
    throw std::runtime_error(std::string("Failed to initialise audio : ")
                             + getAlcErrorString());

  _alcContext.reset(alcCreateContext(_alcDevice.get(), nullptr));
  if(alcGetError(nullptr) != ALC_NO_ERROR)
    throw std::runtime_error(std::string("Failed to initialise audio : ")
                             + getAlcErrorString());

  if(!alcMakeContextCurrent(audioContext()))
    throw std::runtime_error(std::string("Failed to make audio context current : ")
                             + getAlcErrorString());
}

max_stars_repo_name: smallduckinette/engine

max_issues_repo_name: smallduckinette/engine

max_forks_repo_name: smallduckinette/engine


text: #include <boost/container/pmr/monotonic_buffer_resource.hpp>


text:
//
// Copyright Jason Rice 2016
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
#ifndef NBDL_MPDEF_SHOW_IF_HPP
#define NBDL_MPDEF_SHOW_IF_HPP

#include <boost/hana.hpp>

namespace mpdef {

namespace hana = boost::hana;

struct ShowIf
{
  template<typename ...T>
  struct Show { };

  struct DontShow { using foo = void; };

  template<typename Cond, typename ...T>
  constexpr void operator()(Cond, T&&...) const
  {
     using Foo = typename decltype(hana::if_(Cond{}, Show<T...>{}, DontShow{}))::foo;
  }
};
constexpr ShowIf show_if{};

}//mpdef
#endif

max_stars_repo_name: ricejasonf/nbdl

max_issues_repo_name: ricejasonf/nbdl

max_forks_repo_name: ricejasonf/nbdl


text:
//  (C) Copyright Gennadiy Rozental 2001.
//  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)

//  See http://www.boost.org/libs/test for the library home page.
//
//  File        : $RCSfile$
//
//  Version     : $Revision$
//
//  Description : implements fetching absent parameter athuments from environment
// ***************************************************************************

#ifndef BOOST_TEST_UTILS_RUNTIME_ENV_FETCH_HPP
#define BOOST_TEST_UTILS_RUNTIME_ENV_FETCH_HPP

// Boost.Test Runtime parameters
#include <boost/test/utils/runtime/parameter.hpp>
#include <boost/test/utils/runtime/argument.hpp>

#include <boost/test/detail/suppress_warnings.hpp>

// C Runtime
#include <stdlib.h>

namespace network_boost {
namespace runtime {
namespace env {

namespace env_detail {

#ifndef UNDER_CE

#ifdef BOOST_MSVC
#pragma warning(push)
#pragma warning(disable:4996) // getenv
#endif

inline std::pair<cstring,bool>
sys_read_var( cstring var_name )
{
    using namespace std;
    char const* res = getenv( var_name.begin() );

    return std::make_pair( cstring(res), res != NULL );
}

#ifdef BOOST_MSVC
#pragma warning(pop)
#endif

#else

inline std::pair<cstring,bool>
sys_read_var( cstring var_name )
{
    return std::make_pair( cstring(), false );
}

#endif

//____________________________________________________________________________//

template<typename ReadFunc>
inline void
fetch_absent( parameters_store const& params, runtime::arguments_store& args, ReadFunc read_func )
{
    BOOST_TEST_FOREACH( parameters_store::storage_type::value_type const&, v, params.all() ) {
        basic_param_ptr param = v.second;

        if( args.has( param->p_name ) || param->p_env_var.empty() )
            continue;

        std::pair<cstring,bool> value = read_func( param->p_env_var );

        if( !value.second )
            continue;

        // Validate against unexpected empty value
        BOOST_TEST_I_ASSRT( !value.first.is_empty() || param->p_has_optional_value,
            format_error( param->p_name )
                << "Missing an argument value for the parameter " << param->p_name
                << " in the environment." );

        // Produce argument value
        param->produce_argument( value.first, false, args );

    }
}

//____________________________________________________________________________//

} // namespace env_detail

inline void
fetch_absent( parameters_store const& params, runtime::arguments_store& args )
{
    env_detail::fetch_absent( params, args, &env_detail::sys_read_var );
}

} // namespace env
} // namespace runtime
} // namespace network_boost

#include <boost/test/detail/enable_warnings.hpp>

#endif // BOOST_TEST_UTILS_RUNTIME_ENV_FETCH_HPP

max_stars_repo_name: Liastre/uri

max_issues_repo_name: Liastre/uri

max_forks_repo_name: Liastre/uri


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

#include <algorithm>
#include <cstdarg>
#include <stack>
#include <string>
#include <utility>

#include <boost/format.hpp>

#include "Attributes.hpp"
#include "CodeGenerator.hpp"
#include "FieldParser.hpp"
#include "Util.hpp"

// Code that will be embedded to generated output
#include "lib/LibCommonDef.hpp"

using namespace std;
using boost::format;

struct Variable
{
	string cppName;
	string jsonName;

	VariableTypeDef type;

	bool skipNull = false;
	bool isReservable = false;

	int reservableFieldTag = -1;

	explicit Variable(const VariableDef &var)
	  : cppName(var.name)
	  , jsonName(var.name)
	  , type(var.type)
	{
		if (var.attributes.find(VarAttributes::JsonFieldName.name) != var.attributes.end())
		{
			this->jsonName = var.attributes.at(VarAttributes::JsonFieldName.name).args[0];
		}

		if (var.attributes.find(VarAttributes::OnNull.name) != var.attributes.end() &&
		    var.attributes.at(VarAttributes::OnNull.name).args[0] == "skip")
		{
			this->skipNull = true;
		}

		isReservable = ( type.typeName != "int"
		              && type.typeName != "double"
		              && type.typeName != "bool" );
	}

	bool operator<(const Variable &o) const
	{
		return jsonName < o.jsonName;
	}
	bool operator==(const Variable &o) const
	{
		return jsonName == o.jsonName;
	}
};

struct Struct
{
	Struct(const StructDef &structDef)
	   : name(structDef.name)
	   , inNamespace(structDef.inNamespace)
	{
		int reservableFieldTag = 0;
		for (const VariableDef &vDef : structDef.variables)
		{
			Variable v(vDef);
			if (v.isReservable)
			{
				v.reservableFieldTag = (++reservableFieldTag);
			}

			allVars.push_back(v);
		}
	}

	string name;
	vector<Variable> allVars;
	vector<string> inNamespace;
};

void GenerateParserForStruct(CodeFormatter &code, const Struct &s);
void GenerateAllocatorForStruct(CodeFormatter &code, const Struct &s);
void GenerateReserverForStruct(CodeFormatter &code, const Struct &s);

void GenerateHeaderForFile(CodeFormatter &code, const ParsedFile &file)
{
	vector<Struct> allStructs;
	for (const StructDef &s : file.structs)
	{
		allStructs.emplace_back(s);
	}

	// TODO provide an option to generate #ifndef style guards
	code.EmitLine("#pragma once");

	code.EmitCode( string(reinterpret_cast<const char *>(&libCommonData[0]), libCommonData.size()) );

	// Header declerations
	for (const Struct &s : allStructs)
	{
		// Begin namespaces
		for (auto it = s.inNamespace.begin(); it != s.inNamespace.end(); ++it)
		{
			code.EmitLine("namespace %s {", it->c_str());
		}

		code.EmitLine("struct %s", s.name.c_str());
		code.EmitLine("{");
		code.EmitLine("%s() = default;", s.name.c_str());
		code.EmitLine("%s(const %s &) = default;", s.name.c_str(), s.name.c_str());
		code.EmitLine("%s(%s &&) = default;", s.name.c_str(), s.name.c_str());
		code.EmitLine("");
		code.EmitLine("%s& operator=(const %s &) = default;", s.name.c_str(), s.name.c_str());
		code.EmitLine("");

		code.EmitLine("// Field tag numbers");
		code.EmitLine("enum class __QuantumJsonFieldTag");
		code.EmitLine("{");
		for (const Variable &var : s.allVars)
		{
			if (var.isReservable)
			{
				code.EmitLine("__QUANTUMJSON_FIELD_TAG_%s = %d,",
				    var.cppName.c_str(), var.reservableFieldTag);
			}
			else
			{
				code.EmitLine("// Skipped non-reservable field %s", var.cppName.c_str());
			}
		}
		code.EmitLine("};");

		// Member fields
		for (const Variable &var : s.allVars)
		{
			code.EmitLine("%s %s;", var.type.Render().c_str(), var.cppName.c_str());
		}

		code.EmitLine("// Parsing functions");

		code.EmitLine("void MergeFromJson(const std::string &json)");
		code.EmitLine("{");
			code.EmitLine("MergeFromJson(json.begin(), json.end());");
		code.EmitLine("}");

		code.EmitLine("template <typename InputIteratorType>");
		code.EmitLine("void MergeFromJson(InputIteratorType it, InputIteratorType end);");

		code.EmitLine("// Serialization functions");

		code.EmitLine("template <typename OutputIteratorType>");
		code.EmitLine("void SerializeTo(OutputIteratorType out) const");
		code.EmitLine("{");
			code.EmitLine("QuantumJsonImpl__::Serializer<OutputIteratorType> s(out);");
			code.EmitLine("this->SerializeTo(s);");
		code.EmitLine("}");

		code.EmitLine("template <typename OutputIteratorType>");
		code.EmitLine("void SerializeTo(QuantumJsonImpl__::Serializer<OutputIteratorType> &s) const;");

		code.EmitLine("private:");
		code.EmitLine("// Private methods that are called by parser");

		code.EmitLine("// Function that parses one field only");
		code.EmitLine("// If the object is as follows:");
		code.EmitLine("// {\"a\": \"sadsadsa\", \"b\": 123}");
		code.EmitLine("//  <------------->  <------>");
		code.EmitLine("// marked regions would map to ParseNextField calls.");
		code.EmitLine("template <typename InputIteratorType>");
		code.EmitLine("void ParseNextField(QuantumJsonImpl__::Parser<InputIteratorType> &parser);");

		code.EmitLine("// Allocator that works on random access input, not to rely on string/vector");
		code.EmitLine("// growth performance");
		code.EmitLine("template <typename InputIteratorType>");
		code.EmitLine("static");
		code.EmitLine("// TODO rename this function to something more descriptive");
		code.EmitLine("void ReserveNextField(QuantumJsonImpl__::PreAllocator<InputIteratorType> &allocator);");

		code.EmitLine("template <typename InputIteratorType>");
		code.EmitLine("void ReserveCalculatedSpace(QuantumJsonImpl__::PreAllocator<InputIteratorType> &allocator);");

		code.EmitLine("template <typename T> friend struct QuantumJsonImpl__::Parser;");
		code.EmitLine("template <typename T> friend struct QuantumJsonImpl__::PreAllocator;");
		code.EmitLine("};");

		// End namespaces
		for (auto it = s.inNamespace.rbegin(); it != s.inNamespace.rend(); ++it)
		{
			code.EmitLine("} // namespace %s", it->c_str());
		}
	}

	// Function definitions
	for (const Struct &s : allStructs)
	{
		// Begin namespaces
		for (auto it = s.inNamespace.begin(); it != s.inNamespace.end(); ++it)
		{
			code.EmitLine("namespace %s {", it->c_str());
		}

		GenerateParserForStruct(code, s);
		GenerateAllocatorForStruct(code, s);
		GenerateReserverForStruct(code, s);

		code.EmitLine("template <typename InputIteratorType>");
		code.EmitLine("inline");
		code.EmitLine("void %s::MergeFromJson(InputIteratorType it,", s.name.c_str());
		code.EmitLine("     %s                InputIteratorType end)", string(s.name.size(), ' ').c_str());
		code.EmitLine("{");
			code.EmitLine("QuantumJsonImpl__::Parser<InputIteratorType> parser(it, end);");
			code.EmitLine("parser.ParseObject(*this);");
			code.EmitLine("");
			code.EmitLine("// Throw when parsing fails");
			code.EmitLine("if (parser.errorCode != QuantumJsonImpl__::ErrorCode::NoError)");
			code.EmitLine("{");
				code.EmitLine("throw QuantumJsonImpl__::JsonError(parser.errorCode);");
			code.EmitLine("}");
		code.EmitLine("}");

		code.EmitLine("template <typename OutputIteratorType>");
		code.EmitLine("void %s::SerializeTo(", s.name.c_str());
		code.EmitLine("    QuantumJsonImpl__::Serializer<OutputIteratorType> &s");
		code.EmitLine("    ) const");
		code.EmitLine("{");
			code.EmitLine("*(s.out++) = '{';");

		bool putSeparator = false;
		for (const Variable &v : s.allVars)
		{
			code.EmitLine("");
			code.EmitLine("// Render field %s", v.cppName.c_str());

			if (putSeparator)
			{
				code.EmitLine("*(s.out++) = ',';");
			}
			putSeparator = true;

			code.EmitLine("*(s.out++) = '\"';");
			for (char c : v.jsonName)
			{
				code.EmitLine("*(s.out++) = '%c';", c);
			}
			code.EmitLine("*(s.out++) = '\"';");
			code.EmitLine("*(s.out++) = ':';");

			code.EmitLine("s.SerializeValue(this->%s);", v.cppName.c_str());
		}

			code.EmitLine("*(s.out++) = '}';");
		code.EmitLine("}");

		// End namespaces
		for (auto it = s.inNamespace.rbegin(); it != s.inNamespace.rend(); ++it)
		{
			code.EmitLine("} // namespace %s", it->c_str());
		}
	}
}

void GenerateParserForStruct(CodeFormatter &code, const Struct &s)
{
	FieldParser fp;
	for (const Variable &var : s.allVars)
	{
		CodeFormatter action;
		if (var.skipNull)
		{
			action.EmitLine("// Skip null values for this field.");
			action.EmitLine("{");
				action.EmitLine("bool skipped = false;");
				action.EmitLine("parser.MaybeSkipNull(&skipped);");
				action.EmitLine("if (skipped)");
				action.EmitLine("{");
					action.EmitLine("return;");
				action.EmitLine("}");
			action.EmitLine("}");
		}
		action.EmitLine("parser.ParseValueInto(this->%s);", var.cppName.c_str());
		fp.addField(var.jsonName, action.getFormattedCode());
	}

	code.EmitLine("template <typename InputIteratorType>");
	code.EmitLine("inline");
	code.EmitLine("void %s::ParseNextField(QuantumJsonImpl__::Parser<InputIteratorType> &parser)", s.name.c_str());
	code.EmitLine("{");
	fp.generateFieldParserCode(code);
	code.EmitLine("}");
}

void GenerateAllocatorForStruct(CodeFormatter &code, const Struct &s)
{
	FieldParser fp;
	for (const Variable &var : s.allVars)
	{
		if (var.isReservable)
		{
			CodeFormatter action;
			action.EmitLine("// Reserve space in field");
			action.EmitLine("{");
				action.EmitLine("size_t fieldSizeIdx = parser.VisitingField(");
				action.EmitLine("    static_cast<int>(__QuantumJsonFieldTag::__QUANTUMJSON_FIELD_TAG_%s));", var.cppName.c_str());
				action.EmitLine("parser.CalculateSpaceToReserveIn(fieldSizeIdx,");
				action.EmitLine("    static_cast<decltype(%s::%s)*>(nullptr));", s.name.c_str(), var.cppName.c_str());
				action.EmitLine("return;");
			action.EmitLine("}");

			fp.addField(var.jsonName, action.getFormattedCode());
		}
	}

	code.EmitLine("template <typename InputIteratorType>");
	code.EmitLine("inline");
	code.EmitLine("void %s::ReserveNextField(QuantumJsonImpl__::PreAllocator<InputIteratorType> &parser)",
	     s.name.c_str());
	code.EmitLine("{");
	fp.generateFieldParserCode(code);
	code.EmitLine("}");
}

void GenerateReserverForStruct(CodeFormatter &code, const Struct &s)
{
	code.EmitLine("template <typename InputIteratorType>");
	code.EmitLine("inline");
	code.EmitLine("void %s::ReserveCalculatedSpace(QuantumJsonImpl__::PreAllocator<InputIteratorType> &allocator)", s.name.c_str());
	code.EmitLine("{");
		code.EmitLine("size_t objectFieldsEnd = allocator.GetObjectSize();");
		code.EmitLine("allocator.PopObject();");
		code.EmitLine("while (allocator.GetCurIdx() != objectFieldsEnd)");
		code.EmitLine("{");
			code.EmitLine("int fieldTag = allocator.GetFieldTag();");
			code.EmitLine("switch(static_cast<__QuantumJsonFieldTag>(fieldTag))");
			code.EmitLine("{");

	for (const Variable &var : s.allVars)
	{
		if (var.isReservable)
		{
			code.EmitLine("case __QuantumJsonFieldTag::__QUANTUMJSON_FIELD_TAG_%s:", var.cppName.c_str());
			code.EmitLine("{");
				code.EmitLine("allocator.ReserveCalculatedSpaceIn(this->%s);", var.cppName.c_str());
				code.EmitLine("break;");
			code.EmitLine("}");
		}
	}

				code.EmitLine("default:");
				code.EmitLine("; // Should not happen");
			code.EmitLine("}");
		code.EmitLine("}");
	code.EmitLine("}");
}

max_stars_repo_name: mserdarsanli/QuantumJson

max_issues_repo_name: mserdarsanli/QuantumJson

max_forks_repo_name: mserdarsanli/QuantumJson


text:
/*
  Copyright (c) 2020, Robin Zimmeck <robin@robin-zimmeck.de>

  Redistribution and use in source and binary forms, with or without
  modification, are permitted provided that the following conditions are met:

  1. Redistributions of source code must retain the above copyright notice, this
     list of conditions and the following disclaimer.

  2. Redistributions in binary form must reproduce the above copyright notice,
     this list of conditions and the following disclaimer in the documentation
     and/or other materials provided with the distribution.

  3. Neither the name of the copyright holder nor the names of its contributors
     may be used to endorse or promote products derived from this software
     without specific prior written permission.

  This software is provided by the copyright holders and contributors "as is"
  and any express or implied warranties, including, but not limited to, the
  implied warranties of merchantability and fitness for a particular purpose are
  disclaimed. In no event shall the copyright holder or contributors be liable
  for any direct, indirect, incidental, special, exemplary, or consequential
  damages (including, but not limited to, procurement of substitute goods or
  services; loss of use, data, or profits; or business interruption) however
  caused and on any theory of liability, whether in contract, strict liability,
  or tort (including negligence or otherwise) arising in any way out of the use
  of this software, even if advised of the possibility of such damage.
*/

#define BOOST_TEST_MAIN
#include <boost/test/unit_test.hpp>

#include "minisi/literals.h"
#include "minisi/io.h"

using namespace minisi;

BOOST_AUTO_TEST_CASE(literals_test)
{
  using namespace minisi::literals;
  BOOST_CHECK_EQUAL( 10.0_m, 10.0 * metre );
  BOOST_CHECK_EQUAL( 10.0_m², 10.0 * metre * metre );
  BOOST_CHECK_EQUAL( 10.0_s, 10.0 * second );
  BOOST_CHECK_EQUAL( 100.0_kg, 100.0 * kilogram );
  BOOST_CHECK_EQUAL( 1.0_N, 1.0 * newton );
  BOOST_CHECK_EQUAL( 543.0_J, 543.0 * joule );
  BOOST_CHECK_EQUAL( 100.0_W, 100.0 * watt );
  BOOST_CHECK_EQUAL( 3.6_mps, 3.6 * metre / second );
  BOOST_CHECK_EQUAL( 9.81_mps², 9.81 * metre / (second * second) );
  BOOST_CHECK_EQUAL( 6.53_mps³, 6.53 * metre / second / second / second );
  BOOST_CHECK_EQUAL( 70.0_kmph, 70.0 * kilometre / hour );
}

max_stars_repo_name: jhunold/minisi

max_issues_repo_name: jhunold/minisi

max_forks_repo_name: jhunold/minisi


text:
/*
 * Copyright (c) 2017-2018
 *
 *  Dmytro Iakovliev daemondzk@gmail.com
 *  Oleksii Kogutenko https://github.com/oleksii-kogutenko
 *
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *     * Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 *     * Neither the name of the <organization> nor the
 *     names of its contributors may be used to endorse or promote products
 *     derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY Dmytro Iakovliev daemondzk@gmail.com ''AS IS'' AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL Dmytro Iakovliev daemondzk@gmail.com BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 */

#include <ctime>
#include <iostream>
#include <iomanip>
#include <cstdlib>
#include <vector>

#include <gavccache.h>
#include <gavccacheinit.h>
#include "gavcconstants.h"

#include <logging.h>

#include <properties.h>

#include <boost/bind.hpp>
#include <boost_property_tree_ext.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/algorithm/string/predicate.hpp>

#include <ctime>

namespace al = art::lib;
namespace pl = piel::lib;
namespace fs = boost::filesystem;
namespace pt = boost::property_tree;
namespace po = boost::program_options;

namespace piel { namespace cmd {

GAVCCacheInit::GAVCCacheInit(const std::string &cache_path)
    : pl::IOstreamsHolder()
    , cache_path_(cache_path)
{
}

GAVCCacheInit::~GAVCCacheInit()
{
}

void GAVCCacheInit::operator()()
{
    if (!GAVCCache::validate(cache_path_)) {
        fs::remove_all(cache_path_);
        GAVCCache::init(cache_path_);
    }
}

} } // namespace piel::cmd

max_stars_repo_name: diakovliev/pie

max_issues_repo_name: diakovliev/pie

max_forks_repo_name: diakovliev/pie


text: #include <boost/bimap/relation/support/pair_by.hpp>


text:
#include <astar_planner/simple_svg.h>
#include <astar_planner/visualisation.h>
#include <boost/function.hpp>
#include <boost/graph/adjacency_list.hpp>
#include <boost/graph/graph_utility.hpp>
#include <boost/graph/graphviz.hpp>
#include <boost/property_map/function_property_map.hpp>
#include <opencv2/highgui.hpp>
#include <opencv2/imgproc.hpp>

#include <fstream>

namespace astar_planner
{

cv::Mat visualise(const Costmap& costmap, const PathResult& astar_result)
{
    cv::Mat disp;
    costmap.distance_to_collision.convertTo(disp, CV_8U, 1.0, 0);
    cv::cvtColor(disp, disp, cv::COLOR_GRAY2BGR);
    return visualise(disp, costmap, astar_result);
}

cv::Mat visualise(cv::Mat& disp, const Costmap& costmap, const PathResult& astar_result)
{

    // draw the 2d heuristic cost values
    // draw as a blue gradient
    {
        double max_cost_so_far = 0;
        for (const auto& node : astar_result.explore_cache.explore_2d)
        {
            if (node.second.cost_so_far < std::numeric_limits<double>::max())
                max_cost_so_far = std::max(node.second.cost_so_far, max_cost_so_far);
        }

        for (const auto& node : astar_result.explore_cache.explore_2d)
        {
            const unsigned char c =
                static_cast<unsigned char>(255.0 - 255.0 * node.second.cost_so_far / max_cost_so_far);
            disp.at<cv::Vec3b>(node.second.state.y, node.second.state.x) = cv::Vec3b(c, c, 0);
        }
    }

    // Count how often a cell is visited during 3d exploration
    std::size_t max_count = 0;
    std::unordered_map<size_t, size_t> counts;
    for (auto node : astar_result.explore_3d)
    {
        const Eigen::Array2i cell = costmap.getCellIndex({node.second->state.x, node.second->state.y});
        const std::size_t idx = costmap.to2DGridIndex({cell.x(), cell.y()});
        counts[idx]++;
        if (counts[idx] > max_count)
            max_count = counts[idx];
    }

    // visualise 3d exploration
    for (auto node : astar_result.explore_3d)
    {
        if (!node.second->parent)
            continue;

        const Eigen::Array2i cell = costmap.getCellIndex({node.second->state.x, node.second->state.y});
        const std::size_t idx = costmap.to2DGridIndex({cell.x(), cell.y()});

        const unsigned char c = static_cast<unsigned char>(
            std::max(0.0, 255.0 * static_cast<double>(counts[idx]) / static_cast<double>(max_count)));

        disp.at<cv::Vec3b>(cell.y(), cell.x()) = cv::Vec3b(0, c, 0);
    }

    // super sample the image
    const int scale = 4;
    cv::resize(disp, disp, cv::Size(0, 0), scale, scale, cv::INTER_CUBIC);

    // visualise 3d exploration connections
    cv::Mat overlay;
    disp.copyTo(overlay);
    for (auto node : astar_result.explore_3d)
    {
        if (!node.second->parent)
            continue;

        const Eigen::Array2i cell = costmap.getCellIndex({node.second->state.x, node.second->state.y}) * scale;
        const Eigen::Array2i parent_cell =
            costmap.getCellIndex({node.second->parent->state.x, node.second->parent->state.y}) * scale;

        cv::line(overlay, cv::Point(parent_cell.x(), parent_cell.y()), cv::Point(cell.x(), cell.y()),
                 cv::Scalar(0, 255, 255), 1);
    }
    const double alpha = 0.3;
    cv::addWeighted(overlay, alpha, disp, 1 - alpha, 0, disp);

    // draw the start
    {
        const Eigen::Rotation2Dd rotation(astar_result.start.linear());
        const Eigen::Array2i start_cell = costmap.getCellIndex(astar_result.start.translation()) * scale;

        const Eigen::Vector2d x_end = Eigen::Vector2d(start_cell.x(), start_cell.y()) +
                                      Eigen::Vector2d(rotation * Eigen::Vector2d(10 * scale, 0));
        const Eigen::Vector2d y_end = Eigen::Vector2d(start_cell.x(), start_cell.y()) +
                                      Eigen::Vector2d(rotation * Eigen::Vector2d(0, 10 * scale));

        cv::line(disp, cv::Point(start_cell.x(), start_cell.y()), cv::Point(x_end.x(), x_end.y()),
                 cv::Scalar(0, 0, 255), 2);
        cv::line(disp, cv::Point(start_cell.x(), start_cell.y()), cv::Point(y_end.x(), y_end.y()),
                 cv::Scalar(0, 255, 0), 2);
    }

    // draw the goal
    {
        const Eigen::Rotation2Dd rotation(astar_result.goal.linear());
        const Eigen::Array2i start_cell = costmap.getCellIndex(astar_result.goal.translation()) * scale;

        const Eigen::Vector2d x_end = Eigen::Vector2d(start_cell.x(), start_cell.y()) +
                                      Eigen::Vector2d(rotation * Eigen::Vector2d(10 * scale, 0));
        const Eigen::Vector2d y_end = Eigen::Vector2d(start_cell.x(), start_cell.y()) +
                                      Eigen::Vector2d(rotation * Eigen::Vector2d(0, 10 * scale));

        cv::line(disp, cv::Point(start_cell.x(), start_cell.y()), cv::Point(x_end.x(), x_end.y()),
                 cv::Scalar(0, 0, 255), 2);
        cv::line(disp, cv::Point(start_cell.x(), start_cell.y()), cv::Point(y_end.x(), y_end.y()),
                 cv::Scalar(0, 255, 0), 2);
    }

    // trace out the resulting path
    if (astar_result.success)
    {
        for (size_t i = 0; i < astar_result.path.size(); i++)
        {
            auto& node = astar_result.path[i];

            const Eigen::Vector2d position(node->state.x, node->state.y);
            const Eigen::Rotation2Dd rotation(node->state.theta);

            const Eigen::Array2i start_cell = costmap.getCellIndex(position) * scale;

            const Eigen::Vector2d x_end = Eigen::Vector2d(start_cell.x(), start_cell.y()) +
                                          Eigen::Vector2d(rotation * Eigen::Vector2d(10 * scale, 0));
            const Eigen::Vector2d y_end = Eigen::Vector2d(start_cell.x(), start_cell.y()) +
                                          Eigen::Vector2d(rotation * Eigen::Vector2d(0, 10 * scale));

            cv::line(disp, cv::Point(start_cell.x(), start_cell.y()), cv::Point(x_end.x(), x_end.y()),
                     cv::Scalar(0, 0, 255), 2);
            cv::line(disp, cv::Point(start_cell.x(), start_cell.y()), cv::Point(y_end.x(), y_end.y()),
                     cv::Scalar(0, 255, 0), 2);
        }
    }

    // draw the 2d heuristic shortest path
    // draw as a blue line
    if (!astar_result.path.empty())
    {
        auto first_node = astar_result.path.back();
        const Eigen::Array2i start_cell = costmap.getCellIndex({first_node->state.x, first_node->state.y});
        const std::size_t start_index = costmap.to2DGridIndex({start_cell.x(), start_cell.y()});
        auto node_it = astar_result.explore_cache.explore_2d.find(start_index);
        if (node_it != astar_result.explore_cache.explore_2d.end())
        {
            auto node = &node_it->second;
            do
            {
                cv::circle(disp, cv::Point(node->state.x * scale, node->state.y * scale), 2, cv::Scalar(255, 0, 0), -1);
                node = node->parent;
            } while (node);
        }
    }

    return disp;
}

// cppcheck-suppress unusedFunction
void drawDot(const Costmap& costmap, const PathResult& astar_result, const Eigen::Isometry2d& goal,
             const std::string& graph_path, const double linear_resolution, const double angular_resolution)
{
    typedef boost::property<boost::edge_weight_t, double> EdgeProperties;

    struct VertexProperties
    {
        std::string tag;
        std::string location;
        // cppcheck-suppress unusedStructMember
        Node3D* node;
    };

    struct GraphProperties
    {
    };

    typedef boost::adjacency_list<boost::vecS, boost::vecS, boost::directedS, VertexProperties, EdgeProperties,
                                  GraphProperties>
        Explore3dGraph;
    typedef boost::graph_traits<Explore3dGraph>::vertex_descriptor vertex_descriptor;

    Explore3dGraph graph;

    std::unordered_map<uint64_t, vertex_descriptor> node_to_vertex_map;

    const State3D goal_state{goal.translation().x(), goal.translation().y(),
                             Eigen::Rotation2Dd(goal.linear()).smallestAngle()};

    const auto goal_index = StateToIndex(goal_state, linear_resolution, angular_resolution);
    const auto goal_key = IndexToKey(goal_index);

    for (auto node : astar_result.explore_3d)
    {
        std::string tag = "START";
        if (node.second->parent)
        {
            const double angle = node.second->parent->state.theta - node.second->state.theta;

            const auto node_index = StateToIndex(node.second->state, linear_resolution, angular_resolution);
            const auto node_key = IndexToKey(node_index);

            if (node_key == goal_key)
                tag = "GOAL";
            else if (std::abs(angle) < 1e-3)
                tag = "S";
            else if (angle < 0)
                tag = "L";
            else
                tag = "R";
        }
        const std::string location = std::to_string(node.second->state.x / costmap.resolution) + "," +
                                     std::to_string(-node.second->state.y / costmap.resolution) + "!";
        node_to_vertex_map[node.first] = boost::add_vertex({tag, location, node.second}, graph);
    }

    for (auto node : astar_result.explore_3d)
    {
        if (!node.second->parent)
            continue;

        const double cost = node.second->cost_so_far - node.second->parent->cost_so_far;

        const auto node_index = StateToIndex(node.second->state, linear_resolution, angular_resolution);
        const auto node_key = IndexToKey(node_index);

        const auto parent_index = StateToIndex(node.second->parent->state, linear_resolution, angular_resolution);
        const auto parent_key = IndexToKey(parent_index);

        boost::add_edge(node_to_vertex_map[parent_key], node_to_vertex_map[node_key], cost, graph);
    }

    std::ofstream dotfile(graph_path.c_str());

    boost::dynamic_properties dp;
    dp.property("node_id", boost::get(boost::vertex_index, graph));
    dp.property("label", boost::get(&VertexProperties::tag, graph));
    dp.property("pos", boost::get(&VertexProperties::location, graph));

    boost::write_graphviz_dp(dotfile, graph, dp);
}

// cppcheck-suppress unusedFunction
bool drawPathSVG(const PathResult& astar_result, const std::string& svg_path)
{
    ROS_ASSERT(astar_result.success);

    const auto layout = std::make_shared<svg::Layout>(svg::Dimensions(0, 0), svg::Layout::Origin::TopLeft);
    const auto viewbox = std::make_shared<svg::ViewBox>(-10000, -10000, 20000, 20000);
    svg::Document doc(layout, viewbox);

    for (size_t i = 0; i < astar_result.path.size(); i++)
    {
        auto& node = astar_result.path[i];

        const Eigen::Vector2d position(node->state.x, node->state.y);
        const Eigen::Rotation2Dd rotation(node->state.theta);

        const Eigen::Vector2d x_dir = Eigen::Rotation2Dd(node->state.theta) * Eigen::Vector2d::UnitX();
        const Eigen::Vector2d y_dir = Eigen::Rotation2Dd(node->state.theta) * Eigen::Vector2d::UnitY();

        svg::Polyline x_path(svg::Stroke(3, svg::Color::Red()));
        x_path << svg::Point(node->state.x * 1000, node->state.y * 1000);
        x_path << svg::Point(node->state.x * 1000 + x_dir[0] * 0.04 * 1000,
                             node->state.y * 1000 + x_dir[1] * 0.04 * 1000);
        doc << x_path;

        svg::Polyline y_path(svg::Stroke(3, svg::Color::Green()));
        y_path << svg::Point(node->state.x * 1000, node->state.y * 1000);
        y_path << svg::Point(node->state.x * 1000 + y_dir[0] * 0.04 * 1000,
                             node->state.y * 1000 + y_dir[1] * 0.04 * 1000);
        doc << y_path;
    }

    return doc.save(svg_path);
}

}  // namespace astar_planner


text:
#include <boost/test/unit_test.hpp>
#include "algorithms/data_structures/bt/find_duplicate_subtrees.hpp"
#include <limits>

using Types::DS::NodeBT;
using Algo::DS::BT::FindDuplicateSubtrees;

std::string traverse(NodeBT<int>* head, const int& null_value) {
    if (head == nullptr) { return std::to_string(null_value); }

    auto pattern = traverse(head->left, null_value);
    pattern += std::to_string(head->value);
    pattern += traverse(head->right, null_value);
    return pattern;
}

BOOST_AUTO_TEST_SUITE(BTFindDuplicateSubtrees)

    BOOST_AUTO_TEST_CASE(empty_bt)
    {
        NodeBT<int>* bt = nullptr;
        const std::vector<NodeBT<int>*> expected;
        FindDuplicateSubtrees finder;
        BOOST_CHECK(expected == finder.find(bt));
        DeleteBT(&bt);
    }

    BOOST_AUTO_TEST_CASE(bt_with_one_node)
    {
        NodeBT<int>* bt = Types::DS::CreateBT({{5}}, std::numeric_limits<int>::min());
        const std::vector<NodeBT<int>*> expected;
        FindDuplicateSubtrees finder;
        BOOST_CHECK(expected == finder.find(bt));
        DeleteBT(&bt);
    }

    BOOST_AUTO_TEST_CASE(bt_default_test_case)
    {
        const auto nv = 0;
        const std::vector<std::vector<int>> tree_levels = {
            {1},
            {2, 3},
            {4, nv, 2, 4},
            {nv, nv, nv, nv, 4, nv, nv, nv}
        };

        NodeBT<int>* bt = Types::DS::CreateBT(tree_levels, nv);
        FindDuplicateSubtrees finder;
        const auto result = finder.find(bt);

        std::vector<std::string> result_patterns;
        for (const auto& node : result) {
            result_patterns.push_back(traverse(node, nv));
        }

        std::vector<std::string> expected_patterns = {"040", "04020"};

        std::sort(result_patterns.begin(), result_patterns.end());
        std::sort(expected_patterns.begin(), expected_patterns.end());
        BOOST_CHECK(expected_patterns == result_patterns);
        DeleteBT(&bt);
    }

    BOOST_AUTO_TEST_CASE(bt_3_level_tree_no_duplicates)
    {
        const auto nv = 0;
        const std::vector<std::vector<int>> tree_levels = {
            {1},
            {2, 3},
            {4, 5, 6, 7},
            {8, 9, 10, 11, 12, 13, 14, 15}
        };

        NodeBT<int>* bt = Types::DS::CreateBT(tree_levels, nv);
        FindDuplicateSubtrees finder;
        BOOST_CHECK(finder.find(bt).empty());
        DeleteBT(&bt);
    }

    BOOST_AUTO_TEST_CASE(bt_test_case_140)
    {
        // [0,0,0,0,null,null,0,null,null,null,0]
        const auto nv = -1;
        const std::vector<std::vector<int>> tree_levels = {
            {0},
            {0, 0},
            {0, nv, nv, 0},
            {nv, nv, nv, nv, nv, nv, nv, 0}
        };

        NodeBT<int>* bt = Types::DS::CreateBT(tree_levels, nv);
        FindDuplicateSubtrees finder;
        const auto result = finder.find(bt);

        std::vector<std::string> result_patterns;
        for (const auto& node : result) {
            result_patterns.push_back(traverse(node, nv));
        }

        std::vector<std::string> expected_patterns = {"-10-1"};

        std::sort(result_patterns.begin(), result_patterns.end());
        std::sort(expected_patterns.begin(), expected_patterns.end());
        BOOST_CHECK(expected_patterns == result_patterns);
        DeleteBT(&bt);
    }

BOOST_AUTO_TEST_SUITE_END()

max_stars_repo_name: iamantony/CppNotes

max_issues_repo_name: iamantony/CppNotes

max_forks_repo_name: iamantony/CppNotes