text:
/* $Id: aspect.hpp 48153 2011-01-01 15:57:50Z mordante $ */
/*
   Copyright (C) 2009 - 2011 by Yurii Chernyi <terraninfo@terraninfo.net>
   Part of the Battle for Wesnoth Project http://www.wesnoth.org/

   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation; either version 2 of the License, or
   (at your option) any later version.
   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY.

   See the COPYING file for more details.
*/

/**
 * @file
 */

#ifndef AI_COMPOSITE_ASPECT_HPP_INCLUDED
#define AI_COMPOSITE_ASPECT_HPP_INCLUDED

#include "property_handler.hpp"
#include "value_translator.hpp"

#include "../../log.hpp"

#include <boost/bind.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/pointer_cast.hpp>

#ifdef _MSC_VER
#pragma warning(push)
//silence "inherits via dominance" warnings
#pragma warning(disable:4250)
#endif

namespace ai {

class aspect : public readonly_context_proxy, public events::observer, public component {
public:
	aspect(readonly_context &context, const config &cfg, const std::string &id);

	virtual ~aspect();

	void invalidate() const
	{
		valid_ = false;
		valid_variant_ = false;
	}

	virtual const variant& get_variant() const = 0;

	virtual boost::shared_ptr<variant> get_variant_ptr() const = 0;

	virtual void recalculate() const = 0;

	virtual void on_create();

	virtual bool redeploy(const config &cfg, const std::string & id);

	virtual config to_config() const;

	virtual bool delete_all_facets();

	void handle_generic_event(const std::string &/*event_name*/)
	{
		invalidate();
	}

	virtual bool active() const
	{
		return true;
	}

	virtual std::string get_name() const
	{ return name_; }

	virtual std::string get_id() const
	{ return id_; }

	virtual std::string get_engine() const
	{ return engine_; }

	static lg::log_domain& log();

protected:
	mutable bool valid_;
	mutable bool valid_variant_;

	config cfg_;
	bool invalidate_on_turn_start_;
	bool invalidate_on_tod_change_;
	bool invalidate_on_gamestate_change_;
	bool invalidate_on_minor_gamestate_change_;
	std::string engine_;
	std::string name_;
	std::string id_;

};

template<typename T>
class typesafe_aspect : public aspect {
public:
	typesafe_aspect(readonly_context &context, const config &cfg, const std::string &id)
		: aspect(context,cfg,id)
		, value_()
		, value_variant_()
	{
	}

	virtual ~typesafe_aspect()
	{
	}

	virtual const T& get() const
	{
		return *get_ptr();
	}

	virtual const variant& get_variant() const
	{
		return *get_variant_ptr();
	}

	virtual boost::shared_ptr<variant> get_variant_ptr() const
	{
		if (!valid_variant_) {
			if (!valid_) {
				recalculate();
			}

			if (!valid_variant_ && valid_ ) {
				value_variant_ = boost::shared_ptr<variant>(new variant(variant_value_translator<T>::value_to_variant(this->get())));
				valid_variant_ = true;
			} else {
				assert(valid_variant_);
			}
		}
		return value_variant_;
	}

	virtual void recalculate() const = 0;

	virtual boost::shared_ptr<T> get_ptr() const
	{
		if (!valid_) {
			if (!valid_variant_) {
				recalculate();
			}

			if (!valid_ && valid_variant_) {
				value_ = boost::shared_ptr<T>(new T(variant_value_translator<T>::variant_to_value(get_variant())));
				valid_ = true;
			} else {
				assert(valid_);
			}
		}
		return value_;
	}

protected:
	mutable boost::shared_ptr<T> value_;
	mutable boost::shared_ptr<variant> value_variant_;
};

class known_aspect {
public:
	known_aspect(const std::string &name);

	virtual ~known_aspect();

	virtual void set(aspect_ptr a) = 0;

	virtual void add_facet(const config &cfg) = 0;

	const std::string& get_name() const;

protected:
	const std::string name_;
};

template<class T>
class composite_aspect;

template<typename T>
class typesafe_known_aspect : public known_aspect {
public:
	typesafe_known_aspect(const std::string &name, boost::shared_ptr< typesafe_aspect<T> > &where, aspect_map &aspects)
	: known_aspect(name), where_(where), aspects_(aspects)
	{
	}

	void set(aspect_ptr a)
	{
		boost::shared_ptr< typesafe_aspect <T> > c = boost::dynamic_pointer_cast< typesafe_aspect<T> >(a);
		if (c) {
			assert (c->get_id()== this->get_name());
			where_ = c;
			aspects_.insert(make_pair(this->get_name(),c));
		} else {
			LOG_STREAM(debug, aspect::log()) << "typesafe_known_aspect [" << this->get_name() << "] : while setting aspect, got null. this might be caused by invalid [aspect] WML" << std::endl;
		}
	}

	virtual void add_facet(const config &cfg)
	{
		boost::shared_ptr< composite_aspect <T> > c = boost::dynamic_pointer_cast< composite_aspect<T> >(where_);
		if (c) {
			assert (c->get_id()==this->get_name());
			c->add_facet(-1, cfg);
			c->invalidate();
		} else {
			LOG_STREAM(debug, aspect::log()) << "typesafe_known_aspect [" << this->get_name() << "] : while adding facet to aspect, got null. this might be caused by target [aspect] being not composite" << std::endl;
		}
	}

protected:
	boost::shared_ptr<typesafe_aspect <T> > &where_;
	aspect_map &aspects_;

};

template<typename T>
class composite_aspect : public typesafe_aspect<T> {
public:

	composite_aspect(readonly_context &context, const config &cfg, const std::string &id)
		: typesafe_aspect<T>(context, cfg, id)
		, facets_()
		, default_()
	{
		foreach (const config &cfg_element, this->cfg_.child_range("facet") ){
			add_facet(-1,cfg_element);
		}

		const config &_default = this->cfg_.child("default");
		if (_default) {
			std::vector< aspect_ptr > default_aspects;
			engine::parse_aspect_from_config(*this,_default,this->get_id(),std::back_inserter(default_aspects));
			if (!default_aspects.empty()) {
				typename aspect_type<T>::typesafe_ptr b = boost::dynamic_pointer_cast< typesafe_aspect<T> >(default_aspects.front());
				default_ = b;
			}
		}

		boost::function2<void, typename aspect_type<T>::typesafe_ptr_vector&, const config&> factory_facets =
                        boost::bind(&ai::composite_aspect<T>::create_facet,*this,_1,_2);

                register_vector_property(this->property_handlers(),"facet",facets_, factory_facets);

	}

	void create_facet(  typename aspect_type<T>::typesafe_ptr_vector &facets, const config &cfg)
        {
		std::vector<aspect_ptr> facets_base;
		engine::parse_aspect_from_config(*this,cfg,this->get_id(),std::back_inserter(facets_base));
		foreach (aspect_ptr a, facets_base ){
			typename aspect_type<T>::typesafe_ptr b = boost::dynamic_pointer_cast< typesafe_aspect<T> > (a);
			facets.push_back(b);
		}
        }

	virtual void recalculate() const
	{
		///@todo 1.9 optimize in case of an aspect which returns variant
		foreach (const typename aspect_type<T>::typesafe_ptr &f, make_pair(facets_.rbegin(),facets_.rend())) {
			if (f->active()) {
				this->value_ = boost::shared_ptr<T>(f->get_ptr());
				this->valid_ = true;
				return;
			}
		}
		this->value_ = boost::shared_ptr<T>(default_->get_ptr());
		this->valid_ = true;
	}

	virtual config to_config() const
	{
		config cfg = aspect::to_config();
		foreach (const typename aspect_type<T>::typesafe_ptr f, facets_) {
			cfg.add_child("facet",f->to_config());
		}
		if (default_) {
			cfg.add_child("default",default_->to_config());
		}
		return cfg;
	}

	virtual bool add_facet(int pos, const config &cfg)
	{
		if (pos<0) {
			pos = facets_.size();
		}
		std::vector< aspect_ptr > facets;
		engine::parse_aspect_from_config(*this,cfg,this->get_id(),std::back_inserter(facets));
		int j=0;
		foreach (aspect_ptr a, facets ){
			typename aspect_type<T>::typesafe_ptr b = boost::dynamic_pointer_cast< typesafe_aspect<T> > (a);
			facets_.insert(facets_.begin()+pos+j,b);
			j++;
		}
		return (j>0);
	}

	virtual bool delete_all_facets()
	{
		bool b = !facets_.empty();
		facets_.clear();
		return b;
	}

protected:
	typename aspect_type<T>::typesafe_ptr_vector facets_;
	typename aspect_type<T>::typesafe_ptr default_;

};

template<typename T>
class standard_aspect : public typesafe_aspect<T> {
public:
	standard_aspect(readonly_context &context, const config &cfg, const std::string &id)
		: typesafe_aspect<T>(context, cfg, id), time_of_day_(cfg["time_of_day"]),turns_(cfg["turns"])
	{
		boost::shared_ptr<T> value(new T(config_value_translator<T>::cfg_to_value(this->cfg_)));
		this->value_= value;
		LOG_STREAM(debug, aspect::log()) << "standard aspect has time_of_day=["<<time_of_day_<<"], turns=["<<turns_<<"], and value: "<< std::endl << config_value_translator<T>::value_to_cfg(this->get()) << std::endl;
	}

	virtual bool active() const
	{
		return this->is_active(time_of_day_,turns_);
	}

	void recalculate() const
	{
		//nothing to recalculate
		this->valid_ = true;
	}

	config to_config() const
	{
		config cfg = aspect::to_config();
		config_value_translator<T>::value_to_cfg(this->get(),cfg);
		cfg["time_of_day"] = time_of_day_;
		cfg["turns"] = turns_;
		return cfg;
	}

protected:
	std::string time_of_day_;
	std::string turns_;

};

class aspect_factory{
public:
	typedef boost::shared_ptr< aspect_factory > factory_ptr;
	typedef std::map<std::string, factory_ptr> factory_map;
	typedef std::pair<const std::string, factory_ptr> factory_map_pair;

	static factory_map& get_list() {
		static factory_map *aspect_factories;
		if (aspect_factories==NULL) {
			aspect_factories = new factory_map;
		}
		return *aspect_factories;
	}

	virtual aspect_ptr get_new_instance( readonly_context &context, const config &cfg, const std::string &id) = 0;

	aspect_factory( const std::string &name )
	{
		factory_ptr ptr_to_this(this);
		get_list().insert(make_pair(name,ptr_to_this));
	}

	virtual ~aspect_factory() {}
};

template<class ASPECT>
class register_aspect_factory : public aspect_factory {
public:
	register_aspect_factory( const std::string &name )
		: aspect_factory( name )
	{
	}

	virtual aspect_ptr get_new_instance( readonly_context &context, const config &cfg, const std::string &id){
		boost::shared_ptr<ASPECT> _a(new ASPECT(context,cfg,id));
		aspect_ptr a = _a;
		a->on_create();
		return a;
	}
};

} //end of namespace ai

#ifdef _MSC_VER
#pragma warning(pop)
#endif

#endif

ext: hpp

max_stars_repo_name: blackberry/Wesnoth

max_issues_repo_name: blackberry/Wesnoth

max_forks_repo_name: blackberry/Wesnoth


text:
/*
 * Copyright (c) 2015 Cryptonomex, Inc., and contributors.
 *
 * The MIT License
 *
 * 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 <bitset>
#include <iostream>

#include <boost/test/unit_test.hpp>

#include <graphene/chain/database.hpp>
#include <graphene/chain/protocol/protocol.hpp>
#include <graphene/chain/account_object.hpp>
#include <graphene/chain/proposal_object.hpp>
#include <graphene/chain/vesting_balance_object.hpp>

#include <fc/crypto/digest.hpp>

#include "../common/database_fixture.hpp"

using namespace graphene::chain;

BOOST_AUTO_TEST_SUITE(block_tests)

BOOST_FIXTURE_TEST_CASE( update_account_keys, database_fixture )
{
   try
   {
       account_uid_type sam_account_id = graphene::chain::calc_account_uid( 2018001 );
       account_uid_type alice_account_id = graphene::chain::calc_account_uid( 2018002 );

      const asset_object& core = db.get_core_asset();
      uint32_t skip_flags =
          database::skip_transaction_dupe_check
        | database::skip_witness_signature
        | database::skip_transaction_signatures
        | database::skip_authority_check
        ;

      // Sam is the creator of accounts
      private_key_type committee_key = init_account_priv_key;
      private_key_type sam_key = generate_private_key("sam");

      //
      // A = old key set
      // B = new key set
      //
      // we measure how many times we test following four cases:
      //
      //                                     A-B        B-A
      // alice     case_count[0]   A == B    empty      empty
      // bob       case_count[1]   A  < B    empty      nonempty
      // charlie   case_count[2]   B  < A    nonempty   empty
      // dan       case_count[3]   A nc B    nonempty   nonempty
      //
      // and assert that all four cases were tested at least once
      //
      account_object sam_account_object = create_account(sam_account_id "sam", sam_key );

      //Get a sane head block time
      generate_block( skip_flags );

      db.modify(db.get_global_properties(), [](global_property_object& p) {
         p.parameters.committee_proposal_review_period = fc::hours(1).to_seconds();
      });

      transaction tx;
      processed_transaction ptx;

      account_object committee_account_object = db.get_account_by_uid( committee_account );
      // transfer from committee account to Sam account
      transfer(committee_account_object, sam_account_object, core.amount(100000));

      const int num_keys = 5;
      vector< private_key_type > numbered_private_keys;
      vector< vector< public_key_type > > numbered_key_id;
      numbered_private_keys.reserve( num_keys );
      numbered_key_id.push_back( vector<public_key_type>() );
      numbered_key_id.push_back( vector<public_key_type>() );

      for( int i=0; i<num_keys; i++ )
      {
         private_key_type privkey = generate_private_key(
            std::string("key_") + std::to_string(i));
         public_key_type pubkey = privkey.get_public_key();
         address addr( pubkey );

         numbered_private_keys.push_back( privkey );
         numbered_key_id[0].push_back( pubkey );
         //numbered_key_id[1].push_back( addr );
      }

      // each element of possible_key_sched is a list of exactly num_keys
      // indices into numbered_key_id[use_address].  they are defined
      // by repeating selected elements of
      // numbered_private_keys given by a different selector.
      vector< vector< int > > possible_key_sched;
      const int num_key_sched = (1 << num_keys)-1;
      possible_key_sched.reserve( num_key_sched );

      for( int s=1; s<=num_key_sched; s++ )
      {
         vector< int > v;
         int i = 0;
         v.reserve( num_keys );
         while( v.size() < num_keys )
         {
            if( s & (1 << i) )
               v.push_back( i );
            i++;
            if( i >= num_keys )
               i = 0;
         }
         possible_key_sched.push_back( v );
      }

      // we can only undo in blocks
      generate_block( skip_flags );

      std::cout << "update_account_keys:  this test will take a few minutes...\n";
      for( int use_addresses=0; use_addresses<2; use_addresses++ )
      {
         vector< public_key_type > key_ids = numbered_key_id[ use_addresses ];
         for( int num_owner_keys=1; num_owner_keys<=2; num_owner_keys++ )
         {
            for( int num_active_keys=1; num_active_keys<=2; num_active_keys++ )
            {
               std::cout << use_addresses << num_owner_keys << num_active_keys << "\n";
               for( const vector< int >& key_sched_before : possible_key_sched )
               {
                  auto it = key_sched_before.begin();
                  vector< const private_key_type* > owner_privkey;
                  vector< const public_key_type* > owner_keyid;
                  owner_privkey.reserve( num_owner_keys );

                  trx.clear();
                  account_create_operation create_op;
                  create_op.uid = alice_account_id;
                  create_op.name = "alice";

                  for( int owner_index=0; owner_index<num_owner_keys; owner_index++ )
                  {
                     int i = *(it++);
                     create_op.owner.key_auths[ key_ids[ i ] ] = 1;
                     owner_privkey.push_back( &numbered_private_keys[i] );
                     owner_keyid.push_back( &key_ids[ i ] );
                  }
                  // size() < num_owner_keys is possible when some keys are duplicates
                  create_op.owner.weight_threshold = create_op.owner.key_auths.size();

                  for( int active_index=0; active_index<num_active_keys; active_index++ )
                     create_op.active.key_auths[ key_ids[ *(it++) ] ] = 1;
                  // size() < num_active_keys is possible when some keys are duplicates
                  create_op.active.weight_threshold = create_op.active.key_auths.size();

                  create_op.memo_key = key_ids[ *(it++) ] ;

                  account_reg_info reg;

                  reg.allowance_per_article = asset(10000);
                  reg.max_share_per_article = asset(5000);
                  reg.max_share_total = asset(1000);
                  reg.registrar = committee_account;
                  create_op.reg_info = reg;

                  trx.operations.push_back( create_op );
                  // trx.sign( sam_key );
                  wdump( (trx) );

                  processed_transaction ptx_create = db.push_transaction( trx,
                     database::skip_transaction_dupe_check |
                     database::skip_transaction_signatures |
                     database::skip_authority_check
                      );

                  generate_block( skip_flags );
                  for( const vector< int >& key_sched_after : possible_key_sched )
                  {
                     auto it = key_sched_after.begin();

                     trx.clear();
                     account_update_operation update_op;
                     update_op.account = alice_account_id;
                     update_op.owner = authority();
                     update_op.active = authority();
                     update_op.secondary = authority();

                     for( int owner_index=0; owner_index<num_owner_keys; owner_index++ )
                        update_op.owner->key_auths[ key_ids[ *(it++) ] ] = 1;
                     // size() < num_owner_keys is possible when some keys are duplicates
                     update_op.owner->weight_threshold = update_op.owner->key_auths.size();
                     for( int active_index=0; active_index<num_active_keys; active_index++ )
                        update_op.active->key_auths[ key_ids[ *(it++) ] ] = 1;
                     // size() < num_active_keys is possible when some keys are duplicates
                     update_op.active->weight_threshold = update_op.active->key_auths.size();
                     FC_ASSERT( update_op.new_options.valid() );
                     update_op.memo_key = key_ids[ *(it++) ] ;

                     trx.operations.push_back( update_op );
                     for( int i=0; i<int(create_op.owner.weight_threshold); i++)
                     {
                        sign( trx, *owner_privkey[i] );
                        if( i < int(create_op.owner.weight_threshold-1) )
                        {
                           GRAPHENE_REQUIRE_THROW(db.push_transaction(trx), fc::exception);
                        }
                        else
                        {
                           db.push_transaction( trx,
                           database::skip_transaction_dupe_check |
                           database::skip_transaction_signatures );
                        }
                     }
                     verify_account_history_plugin_index();
                     generate_block( skip_flags );

                     verify_account_history_plugin_index();
                     db.pop_block();
                     verify_account_history_plugin_index();
                  }
                  db.pop_block();
                  verify_account_history_plugin_index();
               }
            }
         }
      }
   }
   catch( const fc::exception& e )
   {
      edump( (e.to_detail_string()) );
      throw;
   }
}

BOOST_FIXTURE_TEST_CASE( tapos_rollover, database_fixture )
{
   try
   {
      ACTORS((2018003)(2018004));

      BOOST_TEST_MESSAGE( "Give Alice some money" );
      transfer(committee_account, u_2018003_id, asset(10000));
      generate_block();

      BOOST_TEST_MESSAGE( "Generate up to block 0xFF00" );
      generate_blocks( 0xFF00 );
      signed_transaction xfer_tx;

      BOOST_TEST_MESSAGE( "Transfer money at/about 0xFF00" );
      transfer_operation xfer_op;
      xfer_op.from = u_2018003_id;
      xfer_op.to = u_2018004_id;
      xfer_op.amount = asset(1000);

      xfer_tx.operations.push_back( xfer_op );
      xfer_tx.set_expiration( db.head_block_time() + fc::seconds( 0x1000 * db.get_global_properties().parameters.block_interval ) );
      xfer_tx.set_reference_block( db.head_block_id() );

      sign( xfer_tx, alice_private_key );
      PUSH_TX( db, xfer_tx, 0 );
      generate_block();

      BOOST_TEST_MESSAGE( "Sign new tx's" );
      xfer_tx.set_expiration( db.head_block_time() + fc::seconds( 0x1000 * db.get_global_properties().parameters.block_interval ) );
      xfer_tx.set_reference_block( db.head_block_id() );
      xfer_tx.signatures.clear();
      sign( xfer_tx, alice_private_key );

      BOOST_TEST_MESSAGE( "Generate up to block 0x10010" );
      generate_blocks( 0x110 );

      BOOST_TEST_MESSAGE( "Transfer at/about block 0x10010 using reference block at/about 0xFF00" );
      PUSH_TX( db, xfer_tx, 0 );
      generate_block();
   }
   catch (fc::exception& e)
   {
      edump((e.to_detail_string()));
      throw;
   }
}

BOOST_AUTO_TEST_SUITE_END()

ext: cpp

max_stars_repo_name: abitmore/yoyow-core

max_issues_repo_name: yoyow-org/bitshares-core

max_forks_repo_name: yoyow-org/bitshares-core


text:
#ifndef AIRTRAFFICSCREEN_H
#define AIRTRAFFICSCREEN_H

#include <SFML/Graphics.hpp>
#include <SFML/Audio.hpp>
#include <map>
#include <boost/ptr_container/ptr_list.hpp>
#include <boost/ptr_container/ptr_map.hpp>
#include <boost/property_tree/ptree.hpp>
#include "Screen.hpp"
#include "Aircraft.hpp"
#include "Runway.hpp"
#include "Explosion.hpp"
#include "Scenery.hpp"
#include "Surface.hpp"
#include "Networker.hpp"

using namespace std;

class AirTrafficScreen : public Screen
{
    public:
        AirTrafficScreen(sf::RenderWindow &NewApp);
        ~AirTrafficScreen();

        virtual ScreenType Run(const ScreenType &OldScreen);

        void Reset();
        bool SetupClient(const string &Host);
        bool SetupServer();
        void KillNet();
        bool IsNetActive();

        void StepNet();
        void Draw();
    private:
        bool Running;
        sf::Clock FrameTimer;

        void LoadResources();
        void HandleEvents();
        void Step();

        void Pause(bool Status);

        Networker Net;
        void HandleNet();
        void SendGameData(const sf::Uint32 Id = 0);

        boost::property_tree::ptree Data;

        map<string, AircraftTemplate> AircraftTemplates;
        map<string, RunwayTemplate> RunwayTemplates;
        map<string, ExplosionTemplate> ExplosionTemplates;
        map<string, SceneryTemplate> SceneryTemplates;
        map<string, SurfaceTemplate> SurfaceTemplates;

        boost::ptr_map<sf::Uint32, Aircraft> Aircrafts;
        sf::Uint32 AidNext;
        boost::ptr_list<Runway> Runways;
        boost::ptr_list<Explosion> Explosions;
        boost::ptr_list<Scenery> Sceneries;

        sf::ConvexShape AirportArea;

        Surface *Background;
        sf::Sound AlarmSound;

        map<sf::Uint32, sf::Vector2i> Pointers;

        Aircraft *Pathing;
        sf::Uint32 PathingAid;
        void PathingFinish(Aircraft *Ac);

        int Score;
        int HighScore;

        sf::Font Font;
        sf::Text ScoreText;
        sf::Text HighScoreText;

        sf::Text ChatText;
        vector<sf::String> ChatLines;
        sf::String UserChatLine;
        void AddChatLine(const sf::String &Line);

        float Spawner;
        float PlayTime;

        sf::Vector2f Wind;
        float WindTime;

        float NetUpdateTime;

        void LoadTexture(const string& FileName);
        map<string, sf::Texture> Textures;
        void LoadSound(const string& FileName);
        map<string, sf::SoundBuffer> Sounds;

        void SpawnRunway();
        void SpawnAircraft();
        void SpawnExplosion(sf::Vector2f);
        void SpawnScenery();
        void PickSurface();
        void CalculateHull();

        class
        {
            public:
                int operator() (const int &n)
                {
                    return rand() % n;
                }
        } Shuffler;
};

#endif // AIRTRAFFICSCREEN_H


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

#include "math/point_typed.h" // header to test

using namespace biosim;

BOOST_AUTO_TEST_SUITE(suite_point_typed)

BOOST_AUTO_TEST_CASE(point_typed_ctor) {
  math::point p_data({1.0, 2.0, 3.0});
  math::point_typed p(p_data);
  BOOST_CHECK(p.get_type() == math::point_typed::coordinate_type::cartesian);
  BOOST_CHECK(p.get_point() == p_data);

  p = math::point_typed(p_data, math::point_typed::coordinate_type::cylindrical);
  BOOST_CHECK(p.get_type() == math::point_typed::coordinate_type::cylindrical);
  BOOST_CHECK(p.get_point() == p_data);
}

BOOST_AUTO_TEST_CASE(point_typed_cmp_operator) {
  math::point p_cart({3.0, 4.0, 5.0});
  math::point p_cart2({3.0, 4.0, 6.0});
  math::point p_cyl = math::point_typed(p_cart).to_type(math::point_typed::coordinate_type::cylindrical);
  math::point p_cart_again = math::point_typed(p_cyl, math::point_typed::coordinate_type::cylindrical)
                                 .to_type(math::point_typed::coordinate_type::cartesian);
  BOOST_CHECK(p_cart == p_cart);
  BOOST_CHECK(p_cart == p_cart_again);
  BOOST_CHECK(p_cart != p_cart2);
  BOOST_CHECK(p_cart != p_cyl);
}

BOOST_AUTO_TEST_CASE(point_typed_convert) {
  math::point p_cart({3.0, 4.0, 5.0});
  math::point p_cyl = math::point_typed(p_cart).to_type(math::point_typed::coordinate_type::cylindrical);
  BOOST_CHECK(p_cyl[0] == 5.0);
  BOOST_CHECK_CLOSE(p_cyl[1], 0.927295, 1e-3);
  BOOST_CHECK(p_cyl[2] == 5.0);
  math::point p_cart2 = math::point_typed(p_cyl, math::point_typed::coordinate_type::cylindrical)
                            .to_type(math::point_typed::coordinate_type::cartesian);
  BOOST_CHECK_CLOSE(p_cart2[0], 3.0, 1e-3);
  BOOST_CHECK_CLOSE(p_cart2[1], 4.0, 1e-3);
  BOOST_CHECK(p_cart2[2] == 5.0);

  p_cart = math::point({-3.0, 4.0, 5.0});
  p_cyl = math::point_typed(p_cart).to_type(math::point_typed::coordinate_type::cylindrical);
  BOOST_CHECK(p_cyl[0] == 5.0);
  BOOST_CHECK_CLOSE(p_cyl[1], 2.214297, 1e-3);
  BOOST_CHECK(p_cyl[2] == 5.0);
  p_cart2 = math::point_typed(p_cyl, math::point_typed::coordinate_type::cylindrical)
                .to_type(math::point_typed::coordinate_type::cartesian);
  BOOST_CHECK_CLOSE(p_cart2[0], -3.0, 1e-3);
  BOOST_CHECK_CLOSE(p_cart2[1], 4.0, 1e-3);
  BOOST_CHECK(p_cart2[2] == 5.0);

  p_cart = math::point({-3.0, -4.0, 5.0});
  p_cyl = math::point_typed(p_cart).to_type(math::point_typed::coordinate_type::cylindrical);
  BOOST_CHECK(p_cyl[0] == 5.0);
  BOOST_CHECK_CLOSE(p_cyl[1], -2.214297, 1e-3);
  BOOST_CHECK(p_cyl[2] == 5.0);
  p_cart2 = math::point_typed(p_cyl, math::point_typed::coordinate_type::cylindrical)
                .to_type(math::point_typed::coordinate_type::cartesian);
  BOOST_CHECK_CLOSE(p_cart2[0], -3.0, 1e-3);
  BOOST_CHECK_CLOSE(p_cart2[1], -4.0, 1e-3);
  BOOST_CHECK(p_cart2[2] == 5.0);

  p_cart = math::point({3.0, -4.0, 5.0});
  p_cyl = math::point_typed(p_cart).to_type(math::point_typed::coordinate_type::cylindrical);
  BOOST_CHECK(p_cyl[0] == 5.0);
  BOOST_CHECK_CLOSE(p_cyl[1], -0.927295, 1e-3);
  BOOST_CHECK(p_cyl[2] == 5.0);
  p_cart2 = math::point_typed(p_cyl, math::point_typed::coordinate_type::cylindrical)
                .to_type(math::point_typed::coordinate_type::cartesian);
  BOOST_CHECK_CLOSE(p_cart2[0], 3.0, 1e-3);
  BOOST_CHECK_CLOSE(p_cart2[1], -4.0, 1e-3);
  BOOST_CHECK(p_cart2[2] == 5.0);

  p_cart = math::point({0.0, 4.0, 5.0});
  p_cyl = math::point_typed(p_cart).to_type(math::point_typed::coordinate_type::cylindrical);
  BOOST_CHECK(p_cyl[0] == 4.0);
  BOOST_CHECK_CLOSE(p_cyl[1], 1.5708, 1e-3);
  BOOST_CHECK(p_cyl[2] == 5.0);
  p_cart2 = math::point_typed(p_cyl, math::point_typed::coordinate_type::cylindrical)
                .to_type(math::point_typed::coordinate_type::cartesian);
  BOOST_CHECK_SMALL(p_cart2[0], 1e-5);
  BOOST_CHECK_CLOSE(p_cart2[1], 4.0, 1e-3);
  BOOST_CHECK(p_cart2[2] == 5.0);

  p_cart = math::point({0.0, -4.0, 5.0});
  p_cyl = math::point_typed(p_cart).to_type(math::point_typed::coordinate_type::cylindrical);
  BOOST_CHECK(p_cyl[0] == 4.0);
  BOOST_CHECK_CLOSE(p_cyl[1], -1.5708, 1e-3);
  BOOST_CHECK(p_cyl[2] == 5.0);
  p_cart2 = math::point_typed(p_cyl, math::point_typed::coordinate_type::cylindrical)
                .to_type(math::point_typed::coordinate_type::cartesian);
  BOOST_CHECK_SMALL(p_cart2[0], 1e-5);
  BOOST_CHECK_CLOSE(p_cart2[1], -4.0, 1e-3);
  BOOST_CHECK(p_cart2[2] == 5.0);

  p_cart = math::point({0.0, 0.0, 5.0});
  p_cyl = math::point_typed(p_cart).to_type(math::point_typed::coordinate_type::cylindrical);
  BOOST_CHECK(p_cyl[0] == 0.0);
  BOOST_CHECK(p_cyl[1] == 0.0);
  BOOST_CHECK(p_cyl[2] == 5.0);
  p_cart2 = math::point_typed(p_cyl, math::point_typed::coordinate_type::cylindrical)
                .to_type(math::point_typed::coordinate_type::cartesian);
  BOOST_CHECK_SMALL(p_cart2[0], 1e-5);
  BOOST_CHECK_SMALL(p_cart2[1], 1e-5);
  BOOST_CHECK(p_cart2[2] == 5.0);
}

BOOST_AUTO_TEST_SUITE_END()

max_stars_repo_name: shze/biosim

max_issues_repo_name: shze/biosim

max_forks_repo_name: shze/biosim


text:
#define BOOST_TEST_MODULE "test_util_file_extension"

#ifdef UNITTEST_FRAMEWORK_LIBRARY_EXIST
#include <boost/test/unit_test.hpp>
#else
#define BOOST_TEST_NO_LIB
#include <boost/test/included/unit_test.hpp>
#endif

#include <mill/util/file_extension.hpp>

BOOST_AUTO_TEST_CASE(test_extension)
{
    using namespace std::literals::string_view_literals;

    BOOST_TEST(mill::extension_of("hoge.txt"sv)  == ".txt"sv);
    BOOST_TEST(mill::extension_of("piyo.dat"sv)  == ".dat"sv);
    BOOST_TEST(mill::extension_of("fuga.xlsx"sv) == ".xlsx"sv);
}

max_stars_repo_name: ToruNiina/Coffee-mill

max_issues_repo_name: ToruNiina/Coffee-mill

max_forks_repo_name: ToruNiina/Coffee-mill


text:
//-----------------------------------------------------------------------------
// Copyright (c) 2015-2018 Benjamin Buch
//
// https://github.com/bebuch/disposer-cli
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at https://www.boost.org/LICENSE_1_0.txt)
//-----------------------------------------------------------------------------
#include "log.hpp"

#include <disposer/disposer.hpp>

#include <logsys/log.hpp>
#include <logsys/stdlogb_factory_object.hpp>

#include <io_tools/name_generator.hpp>
#include <io_tools/time_to_dir_string.hpp>

#include <cxxopts.hpp>

#include <boost/filesystem.hpp>
#include <boost/stacktrace.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/dll.hpp>

#include <regex>
#include <iostream>
#include <future>
#include <csignal>
#include <condition_variable>

namespace disposer_cli{

	auto const program_start_time = io_tools::time_to_dir_string();

	void signal_handler(int signum){
		std::signal(signum, SIG_DFL);
		{
			std::ofstream os(program_start_time + "_stacktrace.dump");
			if(os) os << boost::stacktrace::stacktrace();
		}
		std::cerr << boost::stacktrace::stacktrace();
		std::raise(SIGABRT);
	}

	std::mutex server_stop_mutex;
	auto server_stop_ready = false;
	std::condition_variable server_stop;

	void signal_stop(int signum){
		{
			std::unique_lock<std::mutex> lock(server_stop_mutex);
			server_stop_ready = true;
		}
		server_stop.notify_one();
		std::signal(signum, SIG_DFL);
	}

	std::unique_ptr< logsys::stdlog_base > log_factory()noexcept try{
		return std::make_unique< disposer_cli::stdlog >();
	}catch(std::exception const& e){
		std::cerr << "terminate with exception in stdlogb factory: "
			<< e.what() << '\n';
		std::terminate();
	}catch(...){
		std::cerr << "terminate with unknown exception in stdlogb factory\n";
		std::terminate();
	}

}

int main(int argc, char** argv){
	using namespace std::literals::string_literals;
	using namespace std::literals::string_view_literals;
	namespace fs = boost::filesystem;

	// Set signal handler
	std::signal(SIGSEGV, &disposer_cli::signal_handler);
	std::signal(SIGABRT, &disposer_cli::signal_handler);

	logsys::stdlogb_factory_object = &disposer_cli::log_factory;

	cxxopts::Options option_config(argv[0], "disposer module system");

	option_config.add_options()
		("components-and-modules-dirs", "directories that containe "
			"components and modules to be loaded by the disposer",
			cxxopts::value< std::vector< std::string > >()
			->default_value({"components-and-modules"}), "Directory")
		("c,config", "Configuration file", cxxopts::value< std::string >(),
			"config.ini")
		("l,log", "Filename of the logfile; use ${date_time} as placeholder, "
			"depending on your operating system you might have to mask "
			"$ as \\$",
			cxxopts::value< std::string >()
				->default_value("${date_time}_disposer.log"),
			"disposer.log")
		("no-log", "Don't create a log file")
		("s,server", "Run until the enter key is pressed")
		("b,background", "If server mode run in background without waiting "
			"on keypress")
		("m,multithreading",
			"All N executions of a chain are stated instantly")
		("chain", "Execute a chain",
			cxxopts::value< std::vector< std::string > >(), "Name")
		("n,count", "Count of chain executions",
			cxxopts::value< std::vector< std::size_t > >()
			->default_value({"1"}), "Count")
		("list-components", "Print all component names")
		("list-modules", "Print all module names")
		("component-help", "Print the help text of the given component",
			cxxopts::value< std::vector< std::string > >(), "Component Name")
		("module-help", "Print the help text of the given module",
			cxxopts::value< std::vector< std::string > >(), "Module Name")
		("components-and-modules-help",
			"Print the help text of all modules and components");

	auto options = [&]{
			try{
				auto options = option_config.parse(argc, argv);
				if(
					options["list-components"].count() == 0 &&
					options["list-modules"].count() == 0 &&
					options["component-help"].count() == 0 &&
					options["module-help"].count() == 0 &&
					options["components-and-modules-help"].count() == 0
				){
					if(options["config"].count() == 0){
						throw std::logic_error("Need option ‘config‘");
					}
					bool const server = options["server"].count() > 0;
					bool const chain = options["chain"].count() > 0;
					if(!server && !chain){
						throw std::logic_error(
							"Need at least option ‘server‘ or option ‘chain‘");
					}
				}
				return options;
			}catch(std::exception const& e){
				std::cerr << e.what() << "\n\n";
				std::cout << option_config.help();
				std::exit(-1);
			}
		}();

	// defines the livetime of the logfile
	std::shared_ptr< std::ostream > logfile;
	if(options["no-log"].count() == 0){
		auto const filename_pattern = options["log"].as< std::string >();
		auto generator = io_tools::make_name_generator(
			filename_pattern, {false},
			std::make_pair("date_time"s,
				[](std::string const& str){ return str; }));

		auto const filename = generator(disposer_cli::program_start_time);
		logfile = std::make_shared< std::ofstream >(filename);
		if(!*logfile){
			throw std::runtime_error("Can not open log-file: " + filename);
		}

		// add the log file to the log system
		disposer_cli::stdlog::weak_file_ptr = logfile;
	}

	// modules must be deleted last, to access the destructors in shared libs
	std::list< boost::dll::shared_library > libraries;
	disposer::system system;

	if(!logsys::exception_catching_log([](
		logsys::stdlogb& os){ os << "loading modules"; },
	[&system, &libraries, mc_dirs =
		options["components-and-modules-dirs"]
			.as< std::vector< std::string > >()
	]{
		for(auto& mc_dir: mc_dirs){
			std::cout << "Search for DLLs in '" << mc_dir << "'" << std::endl;

			std::regex regex("lib.*\\.so");
			for(auto const& file: fs::directory_iterator(mc_dir)){
				if(
					!is_regular_file(file) ||
					!std::regex_match(file.path().filename().string(), regex)
				) continue;

				auto const lib_name = file.path().stem().string().substr(3);

				logsys::log([&lib_name](logsys::stdlogb& os){
					os << "load shared library '" << lib_name << "'";
				}, [&]{
					auto& library = libraries.emplace_back(file.path().string(),
						boost::dll::load_mode::rtld_deepbind);

					if(library.has("init")){
						library.get_alias<
								void(
									std::string const&,
									disposer::declarant&
								)
							>("init")(lib_name, system.directory().declarant());
					}else{
						logsys::log([&lib_name](logsys::stdlogb& os){
							os << "shared library '" << lib_name
								<< "' is nighter a component nor a module";
						});
					}
				});
			}
		}
	})) return 1;

	if(options["components-and-modules-help"].count() > 0){
		logsys::exception_catching_log(
			[](logsys::stdlogb& os){ os << "print help"; },
			[&system]{
				std::cout << system.directory().help();
			});

		return 0;
	}else if(
		options["list-components"].count() > 0 ||
		options["list-modules"].count() > 0
	){
		if(options["list-components"].count() > 0){
			auto components = system.directory().component_names();
			std::cout << "  * Components:\n";
			for(auto const& component: components){
				std::cout << "    * " << component << '\n';
			}
		}

		if(options["list-modules"].count() > 0){
			auto modules = system.directory().module_names();
			std::cout << "  * Modules:\n";
			for(auto const& module: modules){
				std::cout << "    * " << module << '\n';
			}
		}

		return 0;
	}else if(
		options["component-help"].count() > 0 ||
		options["module-help"].count() > 0
	){
		logsys::exception_catching_log(
			[](logsys::stdlogb& os){ os << "print help"; },
			[&system, &options]{
				if(options["component-help"].count() > 0){
					for(auto component: options["component-help"]
						.as< std::vector< std::string > >()
					){
						std::cout <<
							system.directory().component_help(component);
					}
				}

				if(options["module-help"].count() > 0){
					for(auto module: options["module-help"]
						.as< std::vector< std::string > >()
					){
						std::cout << system.directory().module_help(module);
					}
				}
			});

		return 0;
	}

	auto const config = options["config"].as< std::string >();

	if(!logsys::exception_catching_log(
		[](logsys::stdlogb& os){ os << "loading config"; },
		[&system, &config]{
			system.load_config_file(config);
		})) return -1;

	if(options["chain"].count() > 0){
		logsys::exception_catching_log(
			[](logsys::stdlogb& os){ os << "exec chains"; },
			[&system, &options]{
				auto const multithreading =
					options["multithreading"].count() > 0;
				auto const exec_chains =
					options["chain"].as< std::vector< std::string > >();
				auto const exec_counts =
					options["count"].as< std::vector< std::size_t > >();
				for(std::size_t i = 0; i < exec_chains.size(); ++i){
					auto const exec_count =
						exec_counts.size() > i ? exec_counts[i] : 1;

					disposer::enabled_chain chain(system, exec_chains[i]);

					if(!multithreading){
						// single thread version
						for(std::size_t j = 0; j < exec_count; ++j){
							chain.exec();
						}
					}else{
						// multi threaded version
						std::vector< std::future< void > > tasks;
						tasks.reserve(exec_count);

						for(std::size_t j = 0; j < exec_count; ++j){
							tasks.push_back(std::async([&chain]{
									chain.exec();
								}));
						}

						for(auto& task: tasks){
							task.get();
						}
					}
				}
			});
	}

	if(options["server"].count() > 0){
		if(options["background"].count() == 0){
			// Wait on CTRL-C
			std::signal(SIGINT, &disposer_cli::signal_stop);
		}else{
			// Wait on terminate signal
			std::signal(SIGTERM, &disposer_cli::signal_stop);
		}

		std::unique_lock< std::mutex > lock(disposer_cli::server_stop_mutex);
		if(options["background"].count() == 0){
			std::cout << "Press CTRL-C to exit!" << std::endl;
		}
		disposer_cli::server_stop.wait(lock,
			[]{return disposer_cli::server_stop_ready;});
	}
}

max_stars_repo_name: bebuch/disposer-cli

max_issues_repo_name: bebuch/disposer-cli

max_forks_repo_name: bebuch/disposer-cli


text:
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation.  All rights reserved.
// Licensed under the MIT License (MIT). See License.txt in the repo root for license information.
// ------------------------------------------------------------

#include "stdafx.h"

#include <boost/test/unit_test.hpp>
#include "Common/boost-taef.h"

#include "Hosting2/FabricNodeHost.Test.h"

using namespace std;
using namespace Common;
using namespace Hosting2;
using namespace ServiceModel;
using namespace Management;
using namespace ImageModel;

const StringLiteral TraceType("FabricUpgradeTest");

class DummyFabricUpgradeImpl : public IFabricUpgradeImpl
{
    Common::AsyncOperationSPtr BeginDownload(
        Common::FabricVersion const & fabricVersion,
        Common::AsyncCallback const & callback,
        Common::AsyncOperationSPtr const & parent)
    {
        UNREFERENCED_PARAMETER(fabricVersion);
        return AsyncOperation::CreateAndStart<CompletedAsyncOperation>(
            ErrorCodeValue::Success,
            callback,
            parent);
    }

    Common::ErrorCode EndDownload(
        Common::AsyncOperationSPtr const & operation)
    {
        return CompletedAsyncOperation::End(operation);
    }

    Common::AsyncOperationSPtr BeginValidateAndAnalyze(
        Common::FabricVersionInstance const & currentFabricVersionInstance,
        ServiceModel::FabricUpgradeSpecification const & fabricUpgradeSpec,
        Common::AsyncCallback const & callback,
        Common::AsyncOperationSPtr const & parent)
    {
        UNREFERENCED_PARAMETER(currentFabricVersionInstance);
        UNREFERENCED_PARAMETER(fabricUpgradeSpec);
        return AsyncOperation::CreateAndStart<CompletedAsyncOperation>(
            ErrorCodeValue::Success,
            callback,
            parent);
    }

    Common::ErrorCode EndValidateAndAnalyze(
        __out bool & shouldCloseReplica,
        Common::AsyncOperationSPtr const & operation)
    {
        shouldCloseReplica = false;
        return CompletedAsyncOperation::End(operation);
    }

    Common::AsyncOperationSPtr BeginUpgrade(
        Common::FabricVersionInstance const & currentFabricVersionInstance,
        ServiceModel::FabricUpgradeSpecification const & fabricUpgradeSpec,
        Common::AsyncCallback const & callback,
        Common::AsyncOperationSPtr const & parent)
    {
        UNREFERENCED_PARAMETER(currentFabricVersionInstance);
        UNREFERENCED_PARAMETER(fabricUpgradeSpec);
        return AsyncOperation::CreateAndStart<CompletedAsyncOperation>(
            ErrorCodeValue::Success,
            callback,
            parent);
    }

    Common::ErrorCode EndUpgrade(
        Common::AsyncOperationSPtr const & operation)
    {
        return CompletedAsyncOperation::End(operation);
    }
};

class FabricUpgradeTest
{
protected:
	FabricUpgradeTest() : fabricNodeHost_(make_shared<TestFabricNodeHost>()) { BOOST_REQUIRE(Setup()); }
    TEST_METHOD_SETUP(Setup);
    ~FabricUpgradeTest() { BOOST_REQUIRE(Cleanup()); }
    TEST_METHOD_CLEANUP(Cleanup);

    ConfigSettings GetDefaultConfigSettings();

	shared_ptr<TestFabricNodeHost> fabricNodeHost_;
    shared_ptr<ConfigSettingsConfigStore> configStore_;
};

BOOST_FIXTURE_TEST_SUITE(FabricUpgradeTestSuite,FabricUpgradeTest)

BOOST_AUTO_TEST_CASE(TestValidate)
{
    FabricConfigVersion configVersion;
    auto error = configVersion.FromString(L"V2");
    VERIFY_IS_TRUE(error.IsSuccess());

    ManualResetEvent validateDone;
    FabricVersion targetFabricVersion(
        FabricCodeVersion::Default,
        configVersion);

    FabricUpgradeSpecification fabricUpgradeSpec(targetFabricVersion, 5, UpgradeType::Rolling_NotificationOnly, true, false);

    fabricNodeHost_->GetHosting().BeginValidateFabricUpgrade(
        fabricUpgradeSpec,
        [this, &validateDone](AsyncOperationSPtr const & operation)
    {
        bool shouldRestartReplica;
        auto error = fabricNodeHost_->GetHosting().EndValidateFabricUpgrade(shouldRestartReplica, operation);
        VERIFY_IS_FALSE(shouldRestartReplica);
        VERIFY_IS_TRUE_FMT(error.IsSuccess(), "ValidateFabricUpgrade returned %d", error.ReadValue());
        validateDone.Set();
    },
        AsyncOperationSPtr());

    VERIFY_IS_TRUE(validateDone.WaitOne(10000), L"TestValidate completed before timeout.");
}

BOOST_AUTO_TEST_CASE(TestUpgrade)
{
    FabricConfigVersion configVersion;
    auto error = configVersion.FromString(L"V2");
    VERIFY_IS_TRUE(error.IsSuccess());

    ManualResetEvent upgradeDone;
    FabricVersion targetFabricVersion(
        FabricCodeVersion::Default,
        configVersion);

    FabricUpgradeSpecification fabricUpgradeSpec(targetFabricVersion, 5, UpgradeType::Rolling_NotificationOnly, true, false);

    fabricNodeHost_->GetHosting().BeginFabricUpgrade(
        fabricUpgradeSpec,
        false, /* TODO: Update with fix for #1405455 */
        [this, &upgradeDone](AsyncOperationSPtr const & operation)
    {
        auto error = fabricNodeHost_->GetHosting().EndFabricUpgrade(operation);
        VERIFY_IS_TRUE_FMT(error.IsSuccess(), "FabricUpgrade returned %d", error.ReadValue());
        upgradeDone.Set();
    },
        AsyncOperationSPtr());

    ConfigSettings updatedConfigSettings = GetDefaultConfigSettings();
    updatedConfigSettings.Sections[L"FabricNode"].Parameters[L"NodeVersion"].Value = FabricVersionInstance(fabricUpgradeSpec.Version, fabricUpgradeSpec.InstanceId).ToString();

    configStore_->Update(updatedConfigSettings);

    VERIFY_IS_TRUE(upgradeDone.WaitOne(10000), L"TestUpgrade completed before timeout.");
}

BOOST_AUTO_TEST_CASE(TestParallelOperations)
{
    ManualResetEvent upgradeDone;
    ManualResetEvent parallelUpgradeDone;
    ManualResetEvent parallelValidateDone;

    FabricConfigVersion configVersion;
    auto error = configVersion.FromString(L"V2");
    VERIFY_IS_TRUE(error.IsSuccess());

    FabricVersion targetFabricVersion(
        FabricCodeVersion::Default,
        configVersion);

    FabricUpgradeSpecification fabricUpgradeSpec(targetFabricVersion, 5, UpgradeType::Rolling_NotificationOnly, true, false);

    fabricNodeHost_->GetHosting().BeginFabricUpgrade(
        fabricUpgradeSpec,
        false, /* TODO: Update with fix for #1405455 */
        [this, &upgradeDone](AsyncOperationSPtr const & operation)
    {
        auto error = fabricNodeHost_->GetHosting().EndFabricUpgrade(operation);
        VERIFY_IS_TRUE_FMT(error.IsSuccess(), "FabricUpgrade returned %d", error.ReadValue());
        upgradeDone.Set();
    },
        AsyncOperationSPtr());

    fabricNodeHost_->GetHosting().BeginFabricUpgrade(
        fabricUpgradeSpec,
        false, /* TODO: Update with fix for #1405455 */
        [this, &parallelUpgradeDone](AsyncOperationSPtr const & operation)
    {
        auto error = fabricNodeHost_->GetHosting().EndFabricUpgrade(operation);
        VERIFY_IS_TRUE_FMT(!error.IsSuccess(), "Parallel FabricUpgrade returned %d", error.ReadValue());
        parallelUpgradeDone.Set();
    },
        AsyncOperationSPtr());

    VERIFY_IS_TRUE(parallelUpgradeDone.WaitOne(10000), L"ParallelUpgrade completed before timeout.");

    fabricNodeHost_->GetHosting().BeginValidateFabricUpgrade(
        fabricUpgradeSpec,
        [this, &parallelValidateDone](AsyncOperationSPtr const & operation)
    {
        bool shouldRestartReplica;;
        auto error = fabricNodeHost_->GetHosting().EndValidateFabricUpgrade(shouldRestartReplica, operation);
        VERIFY_IS_TRUE_FMT(!error.IsSuccess(), "Parallel ValidateFabricUpgrade returned %d", error.ReadValue());
        parallelValidateDone.Set();
    },
        AsyncOperationSPtr());

    VERIFY_IS_TRUE(parallelValidateDone.WaitOne(10000), L"ParallelValidate completed before timeout.");

    ConfigSettings updatedConfigSettings = GetDefaultConfigSettings();
    updatedConfigSettings.Sections[L"FabricNode"].Parameters[L"NodeVersion"].Value = FabricVersionInstance(fabricUpgradeSpec.Version, fabricUpgradeSpec.InstanceId).ToString();

    configStore_->Update(updatedConfigSettings);

    VERIFY_IS_TRUE(upgradeDone.WaitOne(10000), L"TestParallelOperations completed before timeout.");
}

BOOST_AUTO_TEST_CASE(TestCloseDuringUpgrade)
{
    FabricConfigVersion configVersion;
    auto error = configVersion.FromString(L"V2");
    VERIFY_IS_TRUE(error.IsSuccess());

    ManualResetEvent upgradeDone;
    FabricVersion targetFabricVersion(
        FabricCodeVersion::Default,
        configVersion);

    FabricUpgradeSpecification fabricUpgradeSpec(targetFabricVersion, 5, UpgradeType::Rolling_NotificationOnly, true, false);

    fabricNodeHost_->GetHosting().BeginFabricUpgrade(
        fabricUpgradeSpec,
        false, /* TODO: Update with fix for #1405455 */
        [this, &upgradeDone](AsyncOperationSPtr const & operation)
    {
        auto error = fabricNodeHost_->GetHosting().EndFabricUpgrade(operation);
        VERIFY_IS_TRUE_FMT(!error.IsSuccess(), "FabricUpgrade returned %d", error.ReadValue());
        upgradeDone.Set();
    },
        AsyncOperationSPtr());

    this->fabricNodeHost_->Close();

    VERIFY_IS_TRUE(upgradeDone.WaitOne(10000), L"TestParallelOperations completed before timeout.");
}

BOOST_AUTO_TEST_SUITE_END()

ConfigSettings FabricUpgradeTest::GetDefaultConfigSettings()
{
    FabricNodeConfigSPtr defaultConfig = std::make_shared<FabricNodeConfig>();

    ConfigParameter nodeId;
    nodeId.Name = defaultConfig->NodeIdEntry.Key;
    nodeId.Value = defaultConfig->NodeId;

    ConfigParameter nodeAddress;
    nodeAddress.Name = defaultConfig->NodeAddressEntry.Key;
    nodeAddress.Value = defaultConfig->NodeAddress;

    ConfigParameter leaseAgentAddress;
    leaseAgentAddress.Name = defaultConfig->LeaseAgentAddressEntry.Key;
    leaseAgentAddress.Value = defaultConfig->LeaseAgentAddress;

    ConfigParameter runtimeServiceAddress;
    runtimeServiceAddress.Name = defaultConfig->RuntimeServiceAddressEntry.Key;
    runtimeServiceAddress.Value = defaultConfig->RuntimeServiceAddress;

    ConfigParameter clientConnectionAddress;
    clientConnectionAddress.Name = defaultConfig->ClientConnectionAddressEntry.Key;
    clientConnectionAddress.Value = defaultConfig->ClientConnectionAddress;

    ConfigParameter workingDir;
    workingDir.Name = defaultConfig->WorkingDirEntry.Key;
    workingDir.Value = defaultConfig->WorkingDir;

    ConfigParameter nodeVersion;
    nodeVersion.Name = defaultConfig->NodeVersionEntry.Key;
    nodeVersion.Value = defaultConfig->NodeVersion.ToString();

    ConfigSection fabricNodeSection;
    fabricNodeSection.Name = L"FabricNode";
    fabricNodeSection.Parameters.insert(make_pair(nodeId.Name, nodeId));
    fabricNodeSection.Parameters.insert(make_pair(nodeAddress.Name, nodeAddress));
    fabricNodeSection.Parameters.insert(make_pair(leaseAgentAddress.Name, leaseAgentAddress));
    fabricNodeSection.Parameters.insert(make_pair(runtimeServiceAddress.Name, runtimeServiceAddress));
    fabricNodeSection.Parameters.insert(make_pair(clientConnectionAddress.Name, clientConnectionAddress));
    fabricNodeSection.Parameters.insert(make_pair(workingDir.Name, workingDir));
    fabricNodeSection.Parameters.insert(make_pair(nodeVersion.Name, nodeVersion));

    ConfigSettings configSettings;
    configSettings.Sections.insert(make_pair(L"FabricNode", fabricNodeSection));

    return configSettings;
}

bool FabricUpgradeTest::Setup()
{
    ConfigSettings configSettings = GetDefaultConfigSettings();
    configStore_ = make_shared<ConfigSettingsConfigStore>(configSettings);

	return fabricNodeHost_->Open(make_shared<FabricNodeConfig>(configStore_), make_shared<DummyFabricUpgradeImpl>());
}

bool FabricUpgradeTest::Cleanup()
{
    auto retval = fabricNodeHost_->Close();
    if (!retval)
    {
        // wait for the update operations to finish, this is a bug in the upgrade path
        // that needs to be fixed
        Sleep(5000);
    }

    return retval;
}

max_stars_repo_name: gridgentoo/ServiceFabricAzure

max_issues_repo_name: gridgentoo/ServiceFabricAzure

max_forks_repo_name: gridgentoo/ServiceFabricAzure