text:
#include <StdInc.h>

#include <CoreConsole.h>

#include <HttpClient.h>

#include <ResourceEventComponent.h>
#include <ResourceManager.h>

#include <ServerInstanceBase.h>
#include <ServerInstanceBaseRef.h>

#include <TcpListenManager.h>
#include <ReverseTcpServer.h>

#include <MonitorInstance.h>

#include <json.hpp>

#include <boost/random/random_device.hpp>
#include <boost/uuid/random_generator.hpp>
#include <boost/uuid/uuid_io.hpp>

extern fwEvent<fx::MonitorInstance*> OnMonitorTick;

inline auto msec()
{
	return std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::high_resolution_clock::now().time_since_epoch());
}

static InitFunction initFunction([]()
{
	static auto httpClient = new HttpClient();

	using namespace std::chrono_literals;

	static bool setNucleus = false;
	static bool setNucleusSuccess = false;
	static std::chrono::milliseconds setNucleusTimeout;

	OnMonitorTick.Connect([](fx::MonitorInstance* instance)
	{
		if (!setNucleusSuccess && (!setNucleus || (msec() > setNucleusTimeout)))
		{
			std::string nucleusToken = "anonymous";
			std::string extToken;

			{
				char tokenData[64] = { 0 };
				fwPlatformString tokenPath = MakeRelativeCitPath("server-monitor-token.key");

				if (auto f = _pfopen(tokenPath.c_str(), _P("rb")))
				{
					fgets(tokenData, std::size(tokenData), f);
					fclose(f);
				}

				if (!tokenData[0])
				{
					std::string token = boost::uuids::to_string(boost::uuids::basic_random_generator<boost::random_device>()());

					if (auto f = _pfopen(tokenPath.c_str(), _P("wb")))
					{
						fmt::fprintf(f, "%s", token);
						fclose(f);
					}

					extToken = token;
				}
				else
				{
					extToken = tokenData;
				}
			}

			static ConVar<std::string> serverProfile("serverProfile", ConVar_None, "default");
			extToken += "_" + serverProfile.GetValue();

			if (!nucleusToken.empty())
			{
				auto tlm = instance->GetComponent<fx::TcpListenManager>();

				auto jsonData = nlohmann::json::object({
					{ "token", nucleusToken },
					{ "tokenEx", extToken },
					{ "port", fmt::sprintf("%d", tlm->GetPrimaryPort()) },
				});

				static auto authDelay = 15s;

				setNucleusTimeout = msec() + authDelay;

				HttpRequestOptions opts;
				opts.ipv4 = true;

				httpClient->DoPostRequest("https://cfx.re/api/register/?v=2", jsonData.dump(), opts, [instance, tlm](bool success, const char* data, size_t length)
				{
					if (!success)
					{
						if (authDelay < 15min)
						{
							authDelay *= 2;
						}

						setNucleusTimeout = msec() + authDelay;
					}
					else
					{
						auto jsonData = nlohmann::json::parse(std::string(data, length));

						fwRefContainer<net::ReverseTcpServer> rts = new net::ReverseTcpServer();
						rts->Listen("users.cfx.re:30130", jsonData.value("rpToken", ""));

						tlm->AddExternalServer(rts);

						instance->GetComponent<fx::ResourceManager>()
							->GetComponent<fx::ResourceEventManagerComponent>()
							->QueueEvent2(
								"_cfx_internal:nucleusConnected",
								{},
								fmt::sprintf("https://%s/", jsonData.value("host", ""))
							);

						static auto webVar = instance->AddVariable<std::string>("web_baseUrl", ConVar_None, jsonData.value("host", ""));

						setNucleusSuccess = true;
					}
				});
			}

			setNucleus = true;
		}
	});
});

max_stars_repo_name: thorium-cfx/fivem

max_issues_repo_name: thorium-cfx/fivem

max_forks_repo_name: thorium-cfx/fivem


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

#include "io/DataMatrix.hpp" // TODO don't cross namespace!
#include "it/EntropyCalculator.hpp"

using namespace mist;

io::DataMatrix::data_t test_data[12] = { 0, 1, 0, 0, 0, 1, 1, 0, 1, 1, 1, 0 };

BOOST_AUTO_TEST_CASE(EntropyCalculator_constructor_default)
{
  int n = 3;
  int m = 4;
  io::DataMatrix test_matrix(test_data, n, m);
  it::EntropyCalculator ec(
      it::EntropyCalculator::variables_ptr(test_matrix.variables()));
}

BOOST_AUTO_TEST_CASE(EntropyCalculator_entropy_bounds)
{
  int n = 3;
  int m = 4;
  io::DataMatrix test_matrix(test_data, n, m);

  it::EntropyCalculator ec(
      it::EntropyCalculator::variables_ptr(test_matrix.variables()));

  // run through some entropies
  for (Variable::index_t i = 0; i < n; i++) {
    ec.entropy({ i });
  }
  ec.entropy({ 0, 1 });
  ec.entropy({ 0, 2 });
  ec.entropy({ 1, 0 });
  ec.entropy({ 1, 2 });
  ec.entropy({ 0, 1, 2 });

  // XXX: memory error, doesn't throw because counters don't check variable
  // indexes impossible in practice because indexes are deterministic & safe
  // BOOST_CHECK_THROW(
  //    ec.entropy({6}), std::exception
  //);
}

BOOST_AUTO_TEST_CASE(EntropyCalculator_entropy_correct1)
{
  int n = 3;
  int m = 4;
  io::DataMatrix test_matrix(test_data, n, m);

  it::EntropyCalculator ec(
      it::EntropyCalculator::variables_ptr(test_matrix.variables()));

  BOOST_TEST(ec.entropy({ 0 }) == 0.8112781244591328);
  BOOST_TEST(ec.entropy({ 1 }) == 1);
  BOOST_TEST(ec.entropy({ 2 }) == 0.8112781244591328);
  BOOST_TEST(ec.entropy({ 0, 1 }) == 1.5);
  BOOST_TEST(ec.entropy({ 0, 2 }) == 1.5);
  BOOST_TEST(ec.entropy({ 1, 2 }) == 1.5);
  BOOST_TEST(ec.entropy({ 0, 1, 2 }) == 2);
}

BOOST_AUTO_TEST_CASE(EntropyCalculator_entropy_correct_d4)
{
  int n = 4;
  int m = 3;
  io::DataMatrix test_matrix(test_data, n, m);

  it::EntropyCalculator ec(
      it::EntropyCalculator::variables_ptr(test_matrix.variables()));

  // 1.58496250072115
  BOOST_TEST(ec.entropy({ 0, 1, 2, 3 }) == 1.5849625007211561);
}

ext: cpp

max_stars_repo_name: andbanman/mist

max_issues_repo_name: andbanman/mist

max_forks_repo_name: andbanman/mist


text:
// Copyright (c) 2009-2013 The Dacrs developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include "crypter.h"

//#include "script.h"
#include "util.h"
#include <string>
#include <vector>
#include <boost/foreach.hpp>
#include <openssl/aes.h>
#include <openssl/evp.h>

bool CCrypter::SetKeyFromPassphrase(const SecureString& strKeyData, const vector<unsigned char>& vchSalt,
		const unsigned int unRounds, const unsigned int unDerivationMethod) {
	if (unRounds < 1 || vchSalt.size() != g_kWalletCryptoSaltSize) {
		return false;
	}
	int i = 0;
	if (unDerivationMethod == 0) {
		i = EVP_BytesToKey(EVP_aes_256_cbc(), EVP_sha512(), &vchSalt[0], (unsigned char *) &strKeyData[0],
						strKeyData.size(), unRounds, m_chKey, m_chIV);
	}
	if (i != (int) g_kWalletCryptoKeySize) {
		OPENSSL_cleanse(m_chKey, sizeof(m_chKey));
		OPENSSL_cleanse(m_chIV, sizeof(m_chIV));
		return false;
	}
	m_bKeySet = true;

	return true;
}

bool CCrypter::SetKey(const CKeyingMaterial& vchNewKey, const vector<unsigned char>& vchNewIV) {
	if (vchNewKey.size() != g_kWalletCryptoKeySize || vchNewIV.size() != g_kWalletCryptoKeySize) {
		return false;
	}
	memcpy(&m_chKey[0], &vchNewKey[0], sizeof m_chKey);
	memcpy(&m_chIV[0], &vchNewIV[0], sizeof m_chIV);
	m_bKeySet = true;

	return true;
}

bool CCrypter::Encrypt(const CKeyingMaterial& vchPlaintext, vector<unsigned char> &vchCiphertext) {
	if (!m_bKeySet) {
		return false;
	}
	// max ciphertext len for a n bytes of plaintext is
	// n + AES_BLOCK_SIZE - 1 bytes
	int nLen = vchPlaintext.size();
	int nCLen = nLen + AES_BLOCK_SIZE, nFLen = 0;
	vchCiphertext = vector<unsigned char>(nCLen);

	EVP_CIPHER_CTX sEvpCipherCtx;

	bool bOk = true;

	EVP_CIPHER_CTX_init(&sEvpCipherCtx);
	if (bOk) {
		bOk = EVP_EncryptInit_ex(&sEvpCipherCtx, EVP_aes_256_cbc(), NULL, m_chKey, m_chIV);
	}
	if (bOk) {
		bOk = EVP_EncryptUpdate(&sEvpCipherCtx, &vchCiphertext[0], &nCLen, &vchPlaintext[0], nLen);
	}
	if (bOk) {
		bOk = EVP_EncryptFinal_ex(&sEvpCipherCtx, (&vchCiphertext[0]) + nCLen, &nFLen);
	}

	EVP_CIPHER_CTX_cleanup(&sEvpCipherCtx);

	if (!bOk) {
		return false;
	}
	vchCiphertext.resize(nCLen + nFLen);

	return true;
}

bool CCrypter::Decrypt(const vector<unsigned char>& vchCiphertext, CKeyingMaterial& vchPlaintext) {
	if (!m_bKeySet) {
		return false;
	}
	// plaintext will always be equal to or lesser than length of ciphertext
	int nLen = vchCiphertext.size();
	int nPLen = nLen, nFLen = 0;

	vchPlaintext = CKeyingMaterial(nPLen);
	EVP_CIPHER_CTX sEvpCipherCtx;
	bool bOk = true;

	EVP_CIPHER_CTX_init(&sEvpCipherCtx);
	if (bOk) {
		bOk = EVP_DecryptInit_ex(&sEvpCipherCtx, EVP_aes_256_cbc(), NULL, m_chKey, m_chIV);
	}
	if (bOk) {
		bOk = EVP_DecryptUpdate(&sEvpCipherCtx, &vchPlaintext[0], &nPLen, &vchCiphertext[0], nLen);
	}
	if (bOk) {
		bOk = EVP_DecryptFinal_ex(&sEvpCipherCtx, (&vchPlaintext[0]) + nPLen, &nFLen);
	}

	EVP_CIPHER_CTX_cleanup(&sEvpCipherCtx);

	if (!bOk) {
		return false;
	}
	vchPlaintext.resize(nPLen + nFLen);

	return true;
}

bool EncryptSecret(const CKeyingMaterial& vMasterKey, const CKeyingMaterial &vPlaintext, const uint256& cIV,
		vector<unsigned char> &vchCiphertext) {
	CCrypter cKeyCrypter;
	vector<unsigned char> vchIV(g_kWalletCryptoKeySize);
	memcpy(&vchIV[0], &cIV, g_kWalletCryptoKeySize);
	if (!cKeyCrypter.SetKey(vMasterKey, vchIV)) {
		return false;
	}

	return cKeyCrypter.Encrypt(*((const CKeyingMaterial*) &vPlaintext), vchCiphertext);
}

bool DecryptSecret(const CKeyingMaterial& vMasterKey, const vector<unsigned char>& vchCiphertext, const uint256& cIV,
		CKeyingMaterial& vPlaintext) {
	CCrypter cKeyCrypter;
	vector<unsigned char> vchIV(g_kWalletCryptoKeySize);
	memcpy(&vchIV[0], &cIV, g_kWalletCryptoKeySize);
	if (!cKeyCrypter.SetKey(vMasterKey, vchIV)) {
		return false;
	}

	return cKeyCrypter.Decrypt(vchCiphertext, *((CKeyingMaterial*) &vPlaintext));
}

bool CCryptoKeyStore::SetCrypted() {
	LOCK(cs_KeyStore);
	if (m_bUseCrypto) {
		return true;
	}
	if (IsContainMainKey()) {
		return false;
	}
	m_bUseCrypto = true;

	return true;
}

bool CCryptoKeyStore::Lock() {
	if (!SetCrypted()) {
		return false;
	}
	{
		LOCK(cs_KeyStore);
		m_vMasterKey.clear();
	}
	g_pUIInterface->NotifyMessage("Lock");
	NotifyStatusChanged(this);

	return true;
}

bool CCryptoKeyStore::Unlock(const CKeyingMaterial& vMasterKeyIn) {
	{
		LOCK(cs_KeyStore);
		if (!SetCrypted()) {
			return false;
		}
		CryptedKeyMap::const_iterator mi = m_mapCryptedKeys.begin();
		for (; mi != m_mapCryptedKeys.end(); ++mi) {
			const CPubKey &cPubKey = (*mi).second.first;
			const vector<unsigned char> &vchCryptedSecret = (*mi).second.second;
			CKeyingMaterial vSecret;
			if (!DecryptSecret(vMasterKeyIn, vchCryptedSecret, cPubKey.GetHash(), vSecret)) {
				return false;
			}
			if (vSecret.size() != 32) {
				return false;
			}
			CKey cKey;
			cKey.Set(vSecret.begin(), vSecret.end(), cPubKey.IsCompressed());
			if (cKey.GetPubKey() == cPubKey) {
				break;
			}

			return false;
		}
		m_vMasterKey = vMasterKeyIn;
	}
	g_pUIInterface->NotifyMessage("UnLock");
	NotifyStatusChanged(this);

	return true;
}

bool CCryptoKeyStore::AddKeyCombi(const CKeyID & cKeyId, const CKeyCombi &cKeyCombi) {
	{
		LOCK(cs_KeyStore);

		if (!IsCrypted()) {
			return CBasicKeyStore::AddKeyCombi(cKeyId, cKeyCombi);
		}
		if (IsLocked()) {
			return false;
		}
		CKey cMainKey;
		cKeyCombi.GetCKey(cMainKey, false);
		CKeyCombi newkeyCombi = cKeyCombi;
		newkeyCombi.CleanMainKey();
		CBasicKeyStore::AddKeyCombi(cKeyId, cKeyCombi);

		vector<unsigned char> vchCryptedSecret;
		CKeyingMaterial vchSecret(cMainKey.begin(), cMainKey.end());
		CPubKey cPubKey;
		cPubKey = cMainKey.GetPubKey();
		if (!EncryptSecret(m_vMasterKey, vchSecret, cPubKey.GetHash(), vchCryptedSecret)) {
			return false;
		}
		if (!AddCryptedKey(cPubKey, vchCryptedSecret)) {
			return false;
		}
	}

	return true;
}

bool CCryptoKeyStore::AddCryptedKey(const CPubKey &cPubKey, const vector<unsigned char> &vchCryptedSecret) {
	{
		LOCK(cs_KeyStore);
		if (!SetCrypted()) {
			return false;
		}
		m_mapCryptedKeys[cPubKey.GetKeyID()] = make_pair(cPubKey, vchCryptedSecret);
	}

	return true;
}

bool CCryptoKeyStore::GetKey(const CKeyID &cAddress, CKey& ckeyOut, bool bIsMine) const {
	{
		LOCK(cs_KeyStore);
		if (bIsMine) {
			return CBasicKeyStore::GetKey(cAddress, ckeyOut, bIsMine);
		} else {
			if (!IsCrypted()) {
				return CBasicKeyStore::GetKey(cAddress, ckeyOut);
			}
			CryptedKeyMap::const_iterator mi = m_mapCryptedKeys.find(cAddress);
			if (mi != m_mapCryptedKeys.end()) {
				const CPubKey &cPubKey = (*mi).second.first;
				const vector<unsigned char> &vchCryptedSecret = (*mi).second.second;
				CKeyingMaterial vSecret;
				if (!DecryptSecret(m_vMasterKey, vchCryptedSecret, cPubKey.GetHash(), vSecret)) {
					return false;
				}
				if (vSecret.size() != 32) {
					return false;
				}
				ckeyOut.Set(vSecret.begin(), vSecret.end(), cPubKey.IsCompressed());
				return true;
			}
		}
	}

	return false;
}

bool CCryptoKeyStore::GetPubKey(const CKeyID &cAddress, CPubKey& cPubKeyOut, bool bIsMine) const {
	{
		LOCK(cs_KeyStore);
		if (bIsMine) {
			return CKeyStore::GetPubKey(cAddress, cPubKeyOut, bIsMine);
		} else {
			if (!IsCrypted()) {
				return CKeyStore::GetPubKey(cAddress, cPubKeyOut, bIsMine);
			}
			CryptedKeyMap::const_iterator mi = m_mapCryptedKeys.find(cAddress);
			if (mi != m_mapCryptedKeys.end()) {
				cPubKeyOut = (*mi).second.first;
				return true;
			}
		}
	}

	return false;
}

bool CCryptoKeyStore::GetKeyCombi(const CKeyID & cAddress, CKeyCombi & cKeyCombiOut) const {
	CBasicKeyStore::GetKeyCombi(cAddress, cKeyCombiOut);
	if (!IsCrypted()) {
		return true;
	}
	CKey cKeyOut;
	if (!IsLocked()) {
		if (!GetKey(cAddress, cKeyOut)) {
			return false;
		}
		cKeyCombiOut.SetMainKey(cKeyOut);
	}

	return true;
}

bool CCryptoKeyStore::EncryptKeys(CKeyingMaterial& vMasterKeyIn) {
	{
		LOCK(cs_KeyStore);
		if (!m_mapCryptedKeys.empty() || IsCrypted()) {
			return false;
		}
		m_bUseCrypto = true;
		for (auto& mKey : mapKeys) {
			CKey cMainKey;
			mKey.second.GetCKey(cMainKey, false);
			CPubKey cPubKey = cMainKey.GetPubKey();
			CKeyingMaterial vSecret(cMainKey.begin(), cMainKey.end());
			vector<unsigned char> vchCryptedSecret;
			if (!EncryptSecret(vMasterKeyIn, vSecret, cPubKey.GetHash(), vchCryptedSecret)) {
				return false;
			}
			if (!AddCryptedKey(cPubKey, vchCryptedSecret)) {
				return false;
			}

			mKey.second.CleanMainKey();
		}
	}

	return true;
}

max_stars_repo_name: SoyPay/dacrs

max_issues_repo_name: SoyPay/dacrs

max_forks_repo_name: SoyPay/dacrs


text:
//  (C) Copyright John Maddock 2006.
//  Use, modification and distribution are subject to the
//  Boost Software License, Version 1.0. (See accompanying file
//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)

#ifndef BOOST_MATH_SQRT1PM1
#define BOOST_MATH_SQRT1PM1

#ifdef _MSC_VER
#pragma once
#endif

#include <boost/math/special_functions/math_fwd.hpp>
#include <boost/math/special_functions/log1p.hpp>
#include <boost/math/special_functions/expm1.hpp>

//
// This algorithm computes sqrt(1+x)-1 for small x:
//

namespace boost{ namespace math{

template <class T, class Policy>
inline typename tools::promote_args<T>::type sqrt1pm1(const T& val, const Policy& pol)
{
   typedef typename tools::promote_args<T>::type result_type;
   BOOST_MATH_STD_USING

   if(fabs(result_type(val)) > 0.75)
      return sqrt(1 + result_type(val)) - 1;
   return boost::math::expm1(boost::math::log1p(val, pol) / 2, pol);
}

template <class T>
inline typename tools::promote_args<T>::type sqrt1pm1(const T& val)
{
   return sqrt1pm1(val, policies::policy<>());
}

} // namespace math
} // namespace boost

#endif // BOOST_MATH_SQRT1PM1

ext: hpp


text:
/*
 * Deadlocks
 */
#include <iostream>
#include <sys/types.h>

#include <boost/iterator/counting_iterator.hpp>

#include <seastar/core/app-template.hh>
#include <seastar/core/reactor.hh>
#include <seastar/core/sleep.hh>
#include <seastar/core/when_all.hh>

seastar::future<> WorkingFiber(int id, seastar::semaphore& limit) {
    using namespace std::chrono_literals;
    auto fut = id == 2 ? seastar::make_ready_future<>() : seastar::sleep(1s);
    std::cerr << "Fiber " << id << " waits on " << (&limit) << "... waiters:" << limit.waiters() << std::endl;
    return fut.then([&limit] {
        return limit.wait(3);
    }).then([&limit, id] {
        std::cerr << "Fiber " << id << " sleeps: " << (&limit) << " waiters:" << limit.waiters() << std::endl;
        return seastar::sleep(1ms);
    }).then([&limit, id] {
        std::cerr << "Fiber " << id << " waits again..." << (&limit) << " :" << limit.waiters() << std::endl;
        return limit.wait(3);
    }).then([id] {
        std::cerr << "Fiber " << id << " finishes." << std::endl;
        return seastar::sleep(2s);
    });
}

seastar::future<> WorkInLoop(int id, seastar::semaphore& limit) {
    return seastar::do_for_each(boost::counting_iterator(0), boost::counting_iterator(1), [&limit, id](int) {
        return WorkingFiber(id, limit).finally([&limit] {
            limit.signal(6);
        });
    });
}

int main(int argc, char** argv) {
    seastar::app_template app;
    app.run(argc, argv, [] {
        return seastar::do_with(seastar::semaphore(6), [](auto& limit) {
            std::cerr << "tid: " << gettid() << "\n";
            std::cerr << "semaphore address: " << (void*)(&limit) << "\n";
            return seastar::when_all(WorkInLoop(1, limit), WorkInLoop(2, limit)).discard_result();
        });
    });
}

ext: cc

max_stars_repo_name: haaawk/seastar

max_issues_repo_name: haaawk/seastar

max_forks_repo_name: haaawk/seastar


text:
#pragma once
#include <string>
#include <map>
#include <mdw/formula/Grammar.hpp>
#include <mdw/formula/Expression.hpp>
#include <mdw/formula/IContext.hpp>
#include <mdw/formula/Any.hpp>
#include <mdw/formula/ValueException.hpp>
#include <boost/unordered_map.hpp>

namespace mdw { namespace formula {

  template <class FactT> class CachableFact
  {
  public:
    typedef typename __TypeTraits<FactT>::actual_type OutputType;
    typedef typename TypeTraits<OutputType>::ReturnType ReturnType;

    class DefaultResolver: public TypedExpression<OutputType>
    {
    public:
      DefaultResolver(const Grammar& iGrammar, const std::string& iName):
        TypedExpression<OutputType>(iGrammar), _name(iName),
        _latestContextId(-1), _factContainer(NULL), _constFactContainer(NULL)
      {}

      ReturnType evaluate(IContext& ioContext) const
      {
        if (ioContext.getUniqueId() != _latestContextId)
        {
          _factContainer = NULL;
          _constFactContainer = NULL;
          _latestContextId = ioContext.getUniqueId();
        }
        if (_factContainer)
        {
          return _factContainer->get();
        } else if (_constFactContainer) {
          return  _constFactContainer->get();
        } else {
          const TypedFact<OutputType> *aCont =
            ioContext.getFactContainer<OutputType>(_name);
          if (aCont)
          {
            _factContainer = aCont;
            return aCont->get();
          } else {
            const TypedFact<const OutputType> *aConstCont =
              ioContext.getFactContainer<const OutputType>(_name);
            if (aConstCont)
            {
              _constFactContainer = aConstCont;
              return aConstCont->get();
            } else {
              throw ValueException(_name.c_str());
            }
          }
        }
      }

      size_t complexity() const
      {
        return 2;
      }

      std::string toString() const
      {
        return "$" + _name;
      }

    private:
      const std::string& _name;
      mutable int _latestContextId;
      mutable const TypedFact<OutputType> *_factContainer;
      mutable const TypedFact<const OutputType> *_constFactContainer;
    };

    class Instantiator: public FactInstantiator
    {
    public:
      Instantiator(const Grammar& iGrammar):
        _grammar(iGrammar)
      {}

      Expression& instantiate(ArenaAllocator& ioAllocator,
                              const Grammar& iGrammar,
                              const std::string& iName) const
      {
        DefaultResolver& anExpr = ioAllocator.create<DefaultResolver>(_grammar, iName);
        return anExpr;
      }

    private:
      const Grammar& _grammar;
    };

    static void RegisterMe(ArenaAllocator& ioAllocator, Grammar& ioGrammar, const std::string& iName)
    {
      Instantiator& anInstantiator = ioAllocator.create<Instantiator>(ioGrammar);

      ioGrammar.registerFactResolver<Instantiator>(iName, anInstantiator);
    }
  };

}}

max_stars_repo_name: AmadeusITGroup/Formula

max_issues_repo_name: AmadeusITGroup/Formula

max_forks_repo_name: AmadeusITGroup/Formula


text:
/*
 For more information, please see: http://software.sci.utah.edu

 The MIT License

 Copyright (c) 2015 Scientific Computing and Imaging Institute,
 University of Utah.

 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 <Interface/Modules/Math/CreateStandardMatrixDialog.h>
#include <Core/Algorithms/Base/AlgorithmVariableNames.h>
#include <Core/Algorithms/Math/CreateStandardMatrixAlgo.h>
#include <boost/shared_ptr.hpp>
#include <Dataflow/Network/ModuleStateInterface.h>
#include <QtGui>

using namespace SCIRun::Gui;
using namespace SCIRun::Core::Algorithms;
using namespace SCIRun::Dataflow::Networks;
using namespace SCIRun::Core::Algorithms::Math;

CreateStandardMatrixDialog::CreateStandardMatrixDialog(const std::string& name, ModuleStateHandle state,
                                                       QWidget* parent /* = 0 */)
: ModuleDialogGeneric(state, parent)
{
    setupUi(this);
    setWindowTitle(QString::fromStdString(name));
    fixSize();

    addComboBoxManager(matrixType_, Parameters::MatrixType);
    addSpinBoxManager(noOfRows_, Parameters::Rows);
    addSpinBoxManager(noOfColumns_, Parameters::Columns);
    addDoubleSpinBoxManager(sizeOfStep_,Parameters::Size);
    addDoubleSpinBoxManager(startPointer_,Parameters::StartPointer);

    connect(matrixType_, SIGNAL(activated(const QString&)), this, SLOT(enableWidgets(const QString&)));
}

void CreateStandardMatrixDialog::enableWidgets(const QString& mode)
{
    sizeOfStep_->setReadOnly(mode!="Series");
    startPointer_->setReadOnly(mode!="Series");
}

void CreateStandardMatrixDialog::pullSpecial()
{
    enableWidgets(QString::fromStdString(state_->getValue(Parameters::MatrixType).toString()));
}

max_stars_repo_name: Nahusa/SCIRun


text:
/*!
  @author Shin'ichiro Nakaoka
*/

#include "VRMLSceneLoader.h"
#include "SceneLoader.h"
#include "VRMLParser.h"
#include "VRMLToSGConverter.h"
#include "EasyScanner.h"
#include "NullOut.h"
#include <boost/format.hpp>
#include "gettext.h"

using namespace std;
using namespace cnoid;
using boost::format;

namespace {

struct Registration {
    Registration(){
        SceneLoader::registerLoader(
            "wrl",
            []() -> shared_ptr<AbstractSceneLoader> { return std::make_shared<VRMLSceneLoader>(); });
    }
} registration;

}

namespace cnoid {

class VRMLSceneLoaderImpl
{
public:
    VRMLParser parser;
    VRMLToSGConverter converter;
    ostream* os_;

    VRMLSceneLoaderImpl();
    ostream& os() { return *os_; }
    SgNode* load(const std::string& filename);
};

}

VRMLSceneLoader::VRMLSceneLoader()
{
    impl = new VRMLSceneLoaderImpl;
}

VRMLSceneLoaderImpl::VRMLSceneLoaderImpl()
{
    os_ = &nullout();
}

VRMLSceneLoader::~VRMLSceneLoader()
{
    delete impl;
}

void VRMLSceneLoader::setMessageSink(std::ostream& os)
{
    impl->os_ = &os;
    impl->parser.setMessageSink(os);
    impl->converter.setMessageSink(os);
}

SgNode* VRMLSceneLoader::load(const std::string& filename)
{
    return impl->load(filename);
}

SgNode* VRMLSceneLoaderImpl::load(const std::string& filename)
{
    converter.clearConvertedNodeMap();

    SgGroupPtr top = new SgGroup;

    try {
        parser.load(filename);

        while(VRMLNodePtr vrml = parser.readNode()){
            SgNodePtr node = converter.convert(vrml);
            if(node){
                top->addChild(node);
            }
        }
        parser.checkEOF();

    } catch(EasyScanner::Exception& ex){
        os() << ex.getFullMessage() << endl;
        return 0;
    }

    if(top->empty()){
        os() << (format(_("VRML file \"%1%\" does not have any valid entity.")) % filename) << endl;
        return 0;
    }

    if(top->numChildren() == 1){
        return top->child(0);
    }

    return top.retn();
}


text:
#include <boost/function.hpp>
typedef boost::function<void(int)> fobject_t;

// Now this function may accept functional objects
void process_integers(const fobject_t& f);

void my_ints_function(int i);

int main() {
   process_integers(&my_ints_function);
}

void my_ints_function(int /*i*/) {}
void process_integers(const fobject_t& f) { f(10); }


text: #include <boost/property_tree/stream_translator.hpp>

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


text:
#include <pbcopper/poa/PoaGraph.h>

#include <cstddef>

#include <limits>
#include <sstream>

#include <boost/foreach.hpp>
#include <boost/graph/topological_sort.hpp>
#include <boost/unordered_set.hpp>

#include "PoaGraphImpl.h"
#include "VectorL.h"

namespace PacBio {
namespace Poa {
namespace detail {

std::string sequenceAlongPath(const BoostGraph& /*unused*/, const VertexInfoMap& vertexInfoMap,
                              const std::vector<VD>& path)
{
    std::ostringstream ss;
    for (const VD v : path) {
        ss << vertexInfoMap[v].Base;
    }
    return ss.str();
}

boost::unordered_set<VD> SpanningDFS(const VD start, const VD end, const BoostGraph& g)
{
    std::vector<VD> stack;
    boost::unordered_set<VD> fwd;
    boost::unordered_set<VD> rev;
    // find all vertices reachable from start
    stack.push_back(start);
    do {
        VD v = stack.back();
        stack.pop_back();
        // mark those we've already visited,
        //   if so, skip
        if (fwd.find(v) != fwd.end()) {
            continue;
        }
        fwd.insert(v);
        BOOST_FOREACH (const ED& e, out_edges(v, g)) {
            stack.push_back(target(e, g));
        }
    } while (!stack.empty());
    // find all vertices that can reach end
    //   FROM start
    stack.push_back(end);
    do {
        VD v = stack.back();
        stack.pop_back();
        // if it's not been visited in the forward pass,
        //   or we've already visited it here, skip
        if (fwd.find(v) == fwd.end() || rev.find(v) != rev.end()) {
            continue;
        }
        rev.insert(v);
        BOOST_FOREACH (const ED& e, in_edges(v, g)) {
            stack.push_back(source(e, g));
        }
    } while (!stack.empty());
    return rev;
}

std::vector<VD> PoaGraphImpl::sortedVertices() const
{
    std::vector<VD> sv(num_vertices(g_));
    topological_sort(g_, sv.rbegin());
    return sv;
}

void PoaGraphImpl::tagSpan(VD start, VD end)
{
    boost::unordered_set<VD> vertices = SpanningDFS(start, end, g_);
    for (const VD v : vertices) {
        vertexInfoMap_[v].SpanningReads++;
    }
}

std::vector<VD> PoaGraphImpl::consensusPath(Align::AlignMode mode, int minCoverage) const
{
    // Pat's note on the approach here:
    //
    // "A node gets a score of NumReads if all reads go through
    //  it, and a score of -NumReads if no reads go through it The
    //  shift of -0.0001 breaks ties in favor of skipping
    //  half-full nodes.  In the 2 reads case this will get rid of
    //  insertions which are the more common error."
    //
    // The interpretation of minCoverage (which is applicable only
    // for LOCAL, SEMIGLOBAL modes) is that it represents
    // application-specific knowledge of the basal coverage level
    // of reads in the template, such that if a node is contained
    // in fewer than minCoverage reads, it will be penalized
    // against inclusion in the consensus.
    int totalReads = NumReads();

    std::list<VD> path;
    std::list<VD> sortedVerticesLocal(num_vertices(g_));
    topological_sort(g_, sortedVerticesLocal.rbegin());
    boost::unordered_map<VD, VD> bestPrevVertex;

    // ignore ^ and $
    // TODO(dalexander): find a cleaner way to do this
    vertexInfoMap_[sortedVerticesLocal.front()].ReachingScore = 0;
    sortedVerticesLocal.pop_back();
    sortedVerticesLocal.pop_front();

    VD bestVertex = null_vertex;
    float bestReachingScore = -FLT_MAX;
    for (const VD v : sortedVerticesLocal) {
        PoaNode& vInfo = vertexInfoMap_[v];
        int containingReads = vInfo.Reads;
        int spanningReads = vInfo.SpanningReads;
        float score =
            (mode != Align::AlignMode::GLOBAL)
                ? (2 * containingReads - 1 * std::max(spanningReads, minCoverage) - 0.0001F)
                : (2 * containingReads - 1 * totalReads - 0.0001F);
        vInfo.Score = score;
        vInfo.ReachingScore = score;
        bestPrevVertex[v] = null_vertex;
        for (const ED& e : inEdges(v, g_)) {
            VD sourceVertex = source(e, g_);
            float rsc = score + vertexInfoMap_[sourceVertex].ReachingScore;
            if (rsc > vInfo.ReachingScore) {
                vInfo.ReachingScore = rsc;
                bestPrevVertex[v] = sourceVertex;
            }
            if (rsc > bestReachingScore) {
                bestVertex = v;
                bestReachingScore = rsc;
            }
            // if the score is the same, the order we've encountered vertices
            //   might not be deterministic. Fix this by comparing on
            //   vertex_index
            else if ((rsc == bestReachingScore) &&
                     (get(boost::vertex_index, g_, v) < get(boost::vertex_index, g_, bestVertex))) {
                bestVertex = v;
            }
        }
    }
    assert(bestVertex != null_vertex);

    // trace back from best-scoring vertex
    VD v = bestVertex;
    while (v != null_vertex) {
        path.push_front(v);
        v = bestPrevVertex[v];
    }
    return std::vector<VD>(path.begin(), path.end());
}

void PoaGraphImpl::threadFirstRead(std::string sequence, std::vector<Vertex>* outputPath)
{
    // first sequence in the alignment
    VD u = null_vertex;
    VD v;
    VD startSpanVertex = null_vertex;
    VD endSpanVertex;
    int readPos = 0;

    if (outputPath) {
        outputPath->clear();
    }

    for (const char base : sequence) {
        v = addVertex(base);
        if (outputPath) {
            outputPath->push_back(externalize(v));
        }
        if (readPos == 0) {
            add_edge(enterVertex_, v, g_);
            startSpanVertex = v;
        } else {
            add_edge(u, v, g_);
        }
        u = v;
        readPos++;
    }
    assert(startSpanVertex != null_vertex);
    assert(u != null_vertex);
    endSpanVertex = u;
    add_edge(u, exitVertex_, g_);  // terminus -> $
    tagSpan(startSpanVertex, endSpanVertex);
}

void PoaGraphImpl::tracebackAndThread(std::string sequence,
                                      const AlignmentColumnMap& alignmentColumnForVertex,
                                      Align::AlignMode alignMode, std::vector<Vertex>* outputPath)
{
    const int I = sequence.length();

    // perform traceback from (I,$), threading the new sequence into
    // the graph as we go.
    int i = I;
    VD v = null_vertex;
    VD forkVertex = null_vertex;
    VD u = exitVertex_;
    int span = 0;
    VD startSpanVertex;
    VD endSpanVertex = alignmentColumnForVertex.at(exitVertex_)->PreviousVertex[I];

    if (outputPath) {
        outputPath->resize(I);
        std::fill(outputPath->begin(), outputPath->end(), std::numeric_limits<size_t>::max());
    }

#define READPOS (i - 1)
#define VERTEX_ON_PATH(readPos, v)                 \
    if (outputPath) {                              \
        (*outputPath)[(readPos)] = externalize(v); \
    }

    while (!(u == enterVertex_ && i == 0)) {
        // u -> v
        // u: current vertex
        // v: vertex last visited in traceback (could be == u)
        // forkVertex: the vertex that will be the target of a new edge

        /* Vertex uExt = */ this->externalize(u);  // DEBUGGING
        /* Vertex vExt = */ this->externalize(v);  // DEBUGGING

        const AlignmentColumn* const curCol = alignmentColumnForVertex.at(u).get();
        assert(curCol != nullptr);
        PoaNode& curNodeInfo = vertexInfoMap_[u];
        VD prevVertex = curCol->PreviousVertex[i];
        MoveType reachingMove = curCol->ReachingMove[i];

        if (reachingMove == StartMove) {
            assert(v != null_vertex);

            if (forkVertex == null_vertex) {
                forkVertex = v;
            }
            // In local model thread read bases, adjusting i (should stop at 0)
            while (i > 0) {
                assert(alignMode == Align::AlignMode::LOCAL);
                VD newForkVertex = addVertex(sequence[READPOS], 1, span);
                add_edge(newForkVertex, forkVertex, g_);
                VERTEX_ON_PATH(READPOS, newForkVertex);
                forkVertex = newForkVertex;
                i--;
            }
        } else if (reachingMove == EndMove) {
            assert(forkVertex == null_vertex && u == exitVertex_ && v == null_vertex);

            forkVertex = exitVertex_;

            if (alignMode == Align::AlignMode::LOCAL) {
                // Find the row # we are coming from, walk
                // back to there, threading read bases onto
                // graph via forkVertex, adjusting i.
                const AlignmentColumn* const prevCol =
                    alignmentColumnForVertex.at(prevVertex).get();
                int prevRow = ArgMax(prevCol->Score);

                while (i > prevRow) {
                    VD newForkVertex = addVertex(sequence[READPOS], 1, span);
                    add_edge(newForkVertex, forkVertex, g_);
                    VERTEX_ON_PATH(READPOS, newForkVertex);
                    forkVertex = newForkVertex;
                    i--;
                }
            }
        } else if (reachingMove == MatchMove) {
            VERTEX_ON_PATH(READPOS, u);
            // if there is an extant forkVertex, join it
            if (forkVertex != null_vertex) {
                add_edge(u, forkVertex, g_);
                forkVertex = null_vertex;
            }
            // add to existing node
            curNodeInfo.Reads++;
            i--;
        } else if (reachingMove == DeleteMove) {
            if (forkVertex == null_vertex) {
                forkVertex = v;
            }
        } else if (reachingMove == ExtraMove || reachingMove == MismatchMove) {
            // begin a new arc with this read base
            VD newForkVertex = addVertex(sequence[READPOS], 1, span);
            if (forkVertex == null_vertex) {
                forkVertex = v;
            }
            add_edge(newForkVertex, forkVertex, g_);
            VERTEX_ON_PATH(READPOS, newForkVertex);
            forkVertex = newForkVertex;
            i--;
        } else {
            throw std::runtime_error("unreachable");
        }

        v = u;
        u = prevVertex;
        span = curNodeInfo.SpanningReads;
    }
    startSpanVertex = v;

    // if there is an extant forkVertex, join it to enterVertex
    if (forkVertex != null_vertex) {
        add_edge(enterVertex_, forkVertex, g_);
        startSpanVertex = forkVertex;
        forkVertex = null_vertex;
    }

    if (startSpanVertex != exitVertex_) {
        tagSpan(startSpanVertex, endSpanVertex);
    }

    // all filled in?
    assert(outputPath == nullptr ||
           std::find(outputPath->begin(), outputPath->end(), std::numeric_limits<size_t>::max()) ==
               outputPath->end());

#undef READPOS
#undef VERTEX_ON_PATH
}

}  // namespace detail
}  // namespace Poa
}  // namespace PacBio

max_stars_repo_name: PacificBiosciences/pbcopper

max_issues_repo_name: PacificBiosciences/pbcopper

max_forks_repo_name: PacificBiosciences/pbcopper


text:
#ifndef STAN_MATH_PRIM_SCAL_PROB_EXPONENTIAL_RNG_HPP
#define STAN_MATH_PRIM_SCAL_PROB_EXPONENTIAL_RNG_HPP

#include <stan/math/prim/meta.hpp>
#include <stan/math/prim/scal/err/check_positive_finite.hpp>
#include <boost/random/exponential_distribution.hpp>
#include <boost/random/variate_generator.hpp>

namespace stan {
namespace math {

/**
 * Return a exponential random variate with inverse scale beta
 * using the specified random number generator.
 *
 * beta can be a scalar or a one-dimensional container.
 *
 * @tparam T_inv Type of inverse scale parameter
 * @tparam RNG class of random number generator
 * @param beta (Sequence of) positive inverse scale parameter(s)
 * @param rng random number generator
 * @return (Sequence of) exponential random variate(s)
 * @throw std::domain_error if beta is nonpositive
 */
template <typename T_inv, class RNG>
inline typename VectorBuilder<true, double, T_inv>::type exponential_rng(
    const T_inv& beta, RNG& rng) {
  using boost::exponential_distribution;
  using boost::variate_generator;

  static const char* function = "exponential_rng";

  check_positive_finite(function, "Inverse scale parameter", beta);

  scalar_seq_view<T_inv> beta_vec(beta);
  size_t N = length(beta);
  VectorBuilder<true, double, T_inv> output(N);

  for (size_t n = 0; n < N; ++n) {
    variate_generator<RNG&, exponential_distribution<> > exp_rng(
        rng, exponential_distribution<>(beta_vec[n]));
    output[n] = exp_rng();
  }

  return output.data();
}

}  // namespace math
}  // namespace stan
#endif

max_stars_repo_name: alashworth/stan-monorepo

max_issues_repo_name: alashworth/stan-monorepo

max_forks_repo_name: alashworth/stan-monorepo


text:
/**********************************************************************
*  Copyright (c) 2008-2016, Alliance for Sustainable Energy.
*  All rights reserved.
*
*  This library is free software; you can redistribute it and/or
*  modify it under the terms of the GNU Lesser General Public
*  License as published by the Free Software Foundation; either
*  version 2.1 of the License, or (at your option) any later version.
*
*  This library is distributed in the hope that it will be useful,
*  but WITHOUT ANY WARRANTY; without even the implied warranty of
*  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
*  Lesser General Public License for more details.
*
*  You should have received a copy of the GNU Lesser General Public
*  License along with this library; if not, write to the Free Software
*  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
**********************************************************************/

#ifndef UTILITIES_TIME_DATE_HPP
#define UTILITIES_TIME_DATE_HPP

#include "../UtilitiesAPI.hpp"

#include "Time.hpp"
#include "../core/Macro.hpp"
#include "../core/Logger.hpp"

#include <ostream>
#include <vector>

#include <boost/optional.hpp>
#include <boost/date_time/gregorian/gregorian.hpp>
#include <boost/date_time/date_defs.hpp>
#include <boost/date_time/gregorian/greg_calendar.hpp>
#include "../core/Enum.hpp"

namespace openstudio{

  /** \class DayOfWeek
   *  \brief DayOfWeek is an enumeration of the days of the week: Sunday, Monday, Tuesday,
   *  Wednesday, Thursday, Friday, Saturday.
   *  \details See the OPENSTUDIO_ENUM documentation in utilities/core/Enum.hpp. The actual
   *  macro call is:
   *  \code
  OPENSTUDIO_ENUM(DayOfWeek,
      ((Sunday)(Sunday)(boost::date_time::Sunday))
      ((Monday)(Monday)(boost::date_time::Monday))
      ((Tuesday)(Tuesday)(boost::date_time::Tuesday))
      ((Wednesday)(Wednesday)(boost::date_time::Wednesday))
      ((Thursday)(Thursday)(boost::date_time::Thursday))
      ((Friday)(Friday)(boost::date_time::Friday))
      ((Saturday)(Saturday)(boost::date_time::Saturday))
  );
   *  \endcode */
  OPENSTUDIO_ENUM(DayOfWeek,
      ((Sunday)(Sunday)(boost::date_time::Sunday))
      ((Monday)(Monday)(boost::date_time::Monday))
      ((Tuesday)(Tuesday)(boost::date_time::Tuesday))
      ((Wednesday)(Wednesday)(boost::date_time::Wednesday))
      ((Thursday)(Thursday)(boost::date_time::Thursday))
      ((Friday)(Friday)(boost::date_time::Friday))
      ((Saturday)(Saturday)(boost::date_time::Saturday))
  );

  /// Convert string to DayOfWeek. Accepts full string or first three letters.
  UTILITIES_API DayOfWeek dayOfWeek(const std::string& day);

  /** \class MonthOfYear
   *  \brief MonthOfYear is an enumeration of months: January, February, March,
   *  April, May, June, July, August, September, October, November, December.
   *  \details See the OPENSTUDIO_ENUM documentation in utilities/core/Enum.hpp. The actual
   *  macro call is:
   *  \code
  OPENSTUDIO_ENUM(MonthOfYear,
      ((Jan)(January)(boost::date_time::Jan))
      ((Feb)(February)(boost::date_time::Feb))
      ((Mar)(March)(boost::date_time::Mar))
      ((Apr)(April)(boost::date_time::Apr))
      ((May)(May)(boost::date_time::May))
      ((Jun)(June)(boost::date_time::Jun))
      ((Jul)(July)(boost::date_time::Jul))
      ((Aug)(August)(boost::date_time::Aug))
      ((Sep)(September)(boost::date_time::Sep))
      ((Oct)(October)(boost::date_time::Oct))
      ((Nov)(November)(boost::date_time::Nov))
      ((Dec)(December)(boost::date_time::Dec))
      ((NotAMonth)(Not a month)(boost::date_time::NotAMonth))
      ((NumMonths)(Number of months)(boost::date_time::NumMonths))
  );
   *  \endcode */
  OPENSTUDIO_ENUM(MonthOfYear,
      ((Jan)(January)(boost::date_time::Jan))
      ((Feb)(February)(boost::date_time::Feb))
      ((Mar)(March)(boost::date_time::Mar))
      ((Apr)(April)(boost::date_time::Apr))
      ((May)(May)(boost::date_time::May))
      ((Jun)(June)(boost::date_time::Jun))
      ((Jul)(July)(boost::date_time::Jul))
      ((Aug)(August)(boost::date_time::Aug))
      ((Sep)(September)(boost::date_time::Sep))
      ((Oct)(October)(boost::date_time::Oct))
      ((Nov)(November)(boost::date_time::Nov))
      ((Dec)(December)(boost::date_time::Dec))
      ((NotAMonth)(Not a month)(boost::date_time::NotAMonth))
      ((NumMonths)(Number of months)(boost::date_time::NumMonths))
  );

  /// Converts string to MonthOfYear. Accepts full string or first three letters.
  UTILITIES_API MonthOfYear monthOfYear(const std::string& month);

  /// convert unsigned to MonthOfYear
  UTILITIES_API MonthOfYear monthOfYear(unsigned month);

  /// convert MonthOfYear to unsigned
  UTILITIES_API unsigned month(MonthOfYear monthOfYear);

  /** \class NthDayOfWeekInMonth
   *  \brief NthDayOfWeekInMonth is an enum for the nth DayOfWeek in MonthOfYear
   *  (e.g. first Saturday in January).
   *  \details The fifth NthDayOfWeekInMonth is equivalent to the last DayOfWeek in
   *  MonthOfYear. See the OPENSTUDIO_ENUM documentation in utilities/core/Enum.hpp
   *  for documentation of the class structure. The actual macro call is:
   *  \code
  OPENSTUDIO_ENUM( NthDayOfWeekInMonth,
      ((first)(first)(boost::gregorian::nth_day_of_the_week_in_month::first))
      ((second)(second)(boost::gregorian::nth_day_of_the_week_in_month::second))
      ((third)(third)(boost::gregorian::nth_day_of_the_week_in_month::third))
      ((fourth)(fourth)(boost::gregorian::nth_day_of_the_week_in_month::fourth))
      ((fifth)(fifth)(boost::gregorian::nth_day_of_the_week_in_month::fifth))
  );
   *  \endcode */
  OPENSTUDIO_ENUM( NthDayOfWeekInMonth,
      ((first)(first)(boost::gregorian::nth_day_of_the_week_in_month::first))
      ((second)(second)(boost::gregorian::nth_day_of_the_week_in_month::second))
      ((third)(third)(boost::gregorian::nth_day_of_the_week_in_month::third))
      ((fourth)(fourth)(boost::gregorian::nth_day_of_the_week_in_month::fourth))
      ((fifth)(fifth)(boost::gregorian::nth_day_of_the_week_in_month::fifth))
  );

  /// Convert string to NthDayOfWeekInMonth. Accepts full string, also accepts 1, 1st, 2, 2nd, etc.
  UTILITIES_API NthDayOfWeekInMonth nthDayOfWeekInMonth(const std::string& nth);

  /// YearDescription describes a year with several optional parameters
  struct UTILITIES_API YearDescription{

    /// constructor
    YearDescription();

    /// get the assumed year
    int assumedYear() const;

    /// is the year a leap year, defaults to false
    bool isLeapYear;

    /// first day of the year, defaults to not set
    boost::optional<DayOfWeek> yearStartsOnDayOfWeek;

    /// look for year in future, defaults to false
    bool lookInFuture;
  };

  class DateTime;

  /// Date is an absolute unit of time, resolution to the day
  /// Date is simple wrapper around boost::gregorian::date
  class UTILITIES_API Date
  {
  public:

    friend UTILITIES_API std::ostream& operator<<(std::ostream& os, const Date& date);
    friend UTILITIES_API std::ostream& operator<<(std::ostream& os, const DateTime& dateTime);
    friend class DateTime;

    /// impl type is boost::gregorian::date
    typedef boost::gregorian::date ImplType;
    //typedef std::shared_ptr<ImplType> ImplPtr;

    REGISTER_LOGGER("utilities.time.Date");

    /// nth weekday of month generators
    static Date fromNthDayOfMonth(NthDayOfWeekInMonth n, DayOfWeek dayOfWeek, MonthOfYear monthOfYear);
    static Date fromNthDayOfMonth(NthDayOfWeekInMonth n, DayOfWeek dayOfWeek, MonthOfYear monthOfYear, int year);

    /// Day of year generators
    static Date fromDayOfYear(unsigned dayOfYear);
    static Date fromDayOfYear(unsigned dayOfYear, int year);
    static Date fromDayOfYear(unsigned dayOfYear, const YearDescription& yearDescription);

    /// is year a leap year
    static bool isLeapYear(int year);

    /// get current Date
    static Date currentDate();

    /// default constructor
    Date();

    /// destructor
    ~Date(){}

    /// from impl
    Date(const ImplType& impl);

    /// Date from month, day of month
    Date(MonthOfYear monthOfYear, unsigned dayOfMonth);

    /// Date from month, day of month, year
    Date(MonthOfYear monthOfYear, unsigned dayOfMonth, int year);

    /// Date from YearDescription, month, and day of month
    Date(MonthOfYear monthOfYear, unsigned dayOfMonth, const YearDescription& yearDescription);

    /// constructor from string
    Date(const std::string& string);

    /// Date from a system tm structure
    Date(tm t_tm);

    /// copy constructor
    Date(const Date& other);

    /// addition operator
    Date operator+ (const Time& time) const;

    /// assignment by addition operator
    Date& operator+= (const Time& time);

    /// difference operator
    Date operator- (const Time& time) const;

    /// assignment by difference operator
    Date& operator-= (const Time& time);

    /// time duration
    Time operator- (const Date& date) const;

    /// equality operator
    bool operator== (const Date& other) const;

    /// non-equality operator
    bool operator!= (const Date& other) const;

    /// less than operator
    bool operator< (const Date& rhs) const;

    /// less than equals operator
    bool operator<= (const Date& rhs) const;

    /// greater than operator
    bool operator> (const Date& rhs) const;

    /// greater than equals operator
    bool operator>= (const Date& rhs) const;

    /// assignment operator
    Date &operator=(const Date &other);

    /// user provided base year
    boost::optional<int> baseYear() const;

    /// set base year
    void baseYear(int baseYear);

    /// assumed base year
    int assumedBaseYear() const;

    /// year
    int year() const;

    /// month of year
    MonthOfYear monthOfYear() const;

    /// day of month
    unsigned dayOfMonth() const;

    /// day of year
    unsigned dayOfYear() const;

    /// is assumed year a leap year
    bool isLeapYear() const;

    /// day of the week
    DayOfWeek dayOfWeek() const;

  protected:

    // reference to impl
    const ImplType impl() const;

  private:

    // initFromYearMonthDay
    void initFromYearMonthDay(int year, MonthOfYear monthOfYear, unsigned dayOfMonth);

    // initFromYearDayOfYear
    void initFromYearDayOfYear(int year, unsigned dayOfYear);

    ImplType m_impl;

    // user provided base year is optional
    boost::optional<int> m_baseYear;

    // always have assumed base year
    int m_assumedBaseYear;
  };

  /// optional Date
  typedef boost::optional<Date> OptionalDate;

  /// vector of Date
  typedef std::vector<Date> DateVector;

  // std::ostream operator<<
  UTILITIES_API std::ostream& operator<<(std::ostream& os, const Date& date);

  /// DateCompare compares two dates, returns true if lhs is less than rhs
  class UTILITIES_API DateCompare{
  public:
    /// operator()
    bool operator()(const Date& lhs, const Date& rhs) const;
  };

  /// return nthDayOfWeekInMonth for given date
  UTILITIES_API NthDayOfWeekInMonth nthDayOfWeekInMonth(const Date& date);

} // openstudio

#endif // UTILITIES_TIME_DATE_HPP

max_stars_repo_name: jasondegraw/OpenStudio

max_issues_repo_name: jasondegraw/OpenStudio

max_forks_repo_name: jasondegraw/OpenStudio


text: #include <boost/interprocess/smart_ptr/shared_ptr.hpp>


text:
//  Boost string_algo library find_iterator.hpp header file  ---------------------------//

//  Copyright Pavol Droba 2002-2004. Use, modification and
//  distribution is subject to the Boost Software License, Version
//  1.0. (See accompanying file LICENSE_1_0.txt or copy at
//  http://www.boost.org/LICENSE_1_0.txt)
//  See http://www.boost.org for updates, documentation, and revision history.

#ifndef BOOST_STRING_FIND_ITERATOR_HPP
#define BOOST_STRING_FIND_ITERATOR_HPP

#include <boost/algorithm/string/config.hpp>
#include <boost/algorithm/string/collection_traits.hpp>
#include <boost/algorithm/string/iterator_range.hpp>
#include <boost/algorithm/string/detail/find_iterator.hpp>
#include <boost/iterator/iterator_facade.hpp>
#include <boost/iterator/iterator_categories.hpp>

/*! \file
    Defines find iterator classes. Find iterator repeatly applies a Finder
    to the specified input string to search for matches. Dereferencing
    the iterator yields the current match or a range between the last and the current
    match depending on the iterator used.
*/

namespace boost {
    namespace algorithm {

//  find_iterator -----------------------------------------------//

        //! find_iterator
        /*!
            Find iterator encapsulates a Finder and allows
            for incremental searching in a string.
            Each increment moves the iterator to the next match.

            Find iterator is a readable forward traversal iterator.

            Dereferencing the iterator yields an iterator_range delimiting
            the current match.
        */
        template<typename IteratorT>
        class find_iterator :
            public iterator_facade<
                find_iterator<IteratorT>,
                const iterator_range<IteratorT>,
                forward_traversal_tag >,
            private detail::find_iterator_base<IteratorT>
        {
        private:
            // facade support
            friend class ::boost::iterator_core_access;

            // base type
            typedef iterator_facade<
                find_iterator<IteratorT>,
                const iterator_range<IteratorT>,
                forward_traversal_tag> facade_type;

        private:
        // typedefs

            typedef detail::find_iterator_base<IteratorT> base_type;
            typedef BOOST_STRING_TYPENAME
                base_type::input_iterator_type input_iterator_type;
            typedef BOOST_STRING_TYPENAME
                base_type::match_type match_type;

        public:
            //! Default constructor
            /*!
                Construct null iterator. All null iterators are equal.

                \post eof()==true
            */
            find_iterator() {}

            //! Copy constructor
            /*!
                Construct a copy of the find_iterator
            */
            find_iterator( const find_iterator& Other ) :
                base_type(Other),
                m_Match(Other.m_Match),
                m_End(Other.m_End) {}

            //! Constructor
            /*!
                Construct new find_iterator for a given finder
                and a range.
            */
            template<typename FinderT>
            find_iterator(
                    IteratorT Begin,
                    IteratorT End,
                    FinderT Finder ) :
                detail::find_iterator_base<IteratorT>(Finder,0),
                m_Match(Begin,Begin),
                m_End(End)
            {
                increment();
            }

            //! Constructor
            /*!
                Construct new find_iterator for a given finder
                and a collection.
            */
            template<typename FinderT, typename CollectionT>
            find_iterator(
                    CollectionT& Col,
                    FinderT Finder ) :
                detail::find_iterator_base<IteratorT>(Finder,0),
                m_Match(begin(Col),begin(Col)),
                m_End(end(Col))
            {
                increment();
            }

        private:
        // iterator operations

            // dereference
            const match_type& dereference() const
            {
                return m_Match;
            }

            // increment
            void increment()
            {
                m_Match=this->do_find(m_Match.end(),m_End);
            }

            // comparison
            bool equal( const find_iterator& Other ) const
            {
                bool bEof=eof();
                bool bOtherEof=Other.eof();

                return bEof || bOtherEof ? bEof==bOtherEof :
                    (
                        m_Match==Other.m_Match &&
                        m_End==Other.m_End
                    );
            }

        public:
        // operations

            //! Eof check
            /*!
                Check the eof condition. Eof condition means that
                there is nothing more to be searched i.e. find_iterator
                is after the last match.
            */
            bool eof() const
            {
                return
                    this->is_null() ||
                    (
                        m_Match.begin() == m_End &&
                        m_Match.end() == m_End
                    );
            }

        private:
        // Attributes
            match_type m_Match;
            input_iterator_type m_End;
        };

        //! find iterator construction helper
        /*!
         *    Construct a find iterator to iterate through the specified string
         */
        template<typename CollectionT, typename FinderT>
        inline find_iterator<
            BOOST_STRING_TYPENAME result_iterator_of<CollectionT>::type>
        make_find_iterator(
            CollectionT& Collection,
            FinderT Finder)
        {
            return find_iterator<BOOST_STRING_TYPENAME result_iterator_of<CollectionT>::type>(
                begin(Collection), end(Collection), Finder);
        }

//  split iterator -----------------------------------------------//

        //! split_iterator
        /*!
            Split iterator encapsulates a Finder and allows
            for incremental searching in a string.
            Unlike the find iterator, split iterator iterates
            through gaps between matches.

            Find iterator is a readable forward traversal iterator.

            Dereferencing the iterator yields an iterator_range delimiting
            the current match.
        */
        template<typename IteratorT>
        class split_iterator :
            public iterator_facade<
                split_iterator<IteratorT>,
                const iterator_range<IteratorT>,
                forward_traversal_tag >,
            private detail::find_iterator_base<IteratorT>
        {
        private:
            // facade support
            friend class ::boost::iterator_core_access;

            // base type
            typedef iterator_facade<
                find_iterator<IteratorT>,
                iterator_range<IteratorT>,
                forward_traversal_tag> facade_type;

        private:
        // typedefs

            typedef detail::find_iterator_base<IteratorT> base_type;
            typedef BOOST_STRING_TYPENAME
                base_type::input_iterator_type input_iterator_type;
            typedef BOOST_STRING_TYPENAME
                base_type::match_type match_type;

        public:
            //! Default constructor
            /*!
                Construct null iterator. All null iterators are equal.

                \post eof()==true
            */
            split_iterator() {}
            //! Copy constructor
            /*!
                Construct a copy of the split_iterator
            */
            split_iterator( const split_iterator& Other ) :
                base_type(Other),
                m_Match(Other.m_Match),
                m_Next(Other.m_Next),
                m_End(Other.m_End) {}

            //! Constructor
            /*!
                Construct new split_iterator for a given finder
                and a range.
            */
            template<typename FinderT>
            split_iterator(
                    IteratorT Begin,
                    IteratorT End,
                    FinderT Finder ) :
                detail::find_iterator_base<IteratorT>(Finder,0),
                m_Match(Begin,Begin),
                m_Next(Begin),
                m_End(End)
            {
                increment();
            }
            //! Constructor
            /*!
                Construct new split_iterator for a given finder
                and a collection.
            */
            template<typename FinderT, typename CollectionT>
            split_iterator(
                    CollectionT& Col,
                    FinderT Finder ) :
                detail::find_iterator_base<IteratorT>(Finder,0),
                m_Match(begin(Col),begin(Col)),
                m_Next(begin(Col)),
                m_End(end(Col))
            {
                increment();
            }

        private:
        // iterator operations

            // dereference
            const match_type& dereference() const
            {
                return m_Match;
            }

            // increment
            void increment()
            {
                match_type FindMatch=this->do_find( m_Next, m_End );
                m_Match=match_type( m_Next, FindMatch.begin() );
                m_Next=FindMatch.end();
            }

            // comparison
            bool equal( const split_iterator& Other ) const
            {
                bool bEof=eof();
                bool bOtherEof=Other.eof();

                return bEof || bOtherEof ? bEof==bOtherEof :
                    (
                        m_Match==Other.m_Match &&
                        m_Next==Other.m_Next &&
                        m_End==Other.m_End
                    );
            }

        public:
        // operations

            //! Eof check
            /*!
                Check the eof condition. Eof condition means that
                there is nothing more to be searched i.e. find_iterator
                is after the last match.
            */
            bool eof() const
            {
                return
                    this->is_null() ||
                    (
                        m_Match.begin() == m_End &&
                        m_Match.end() == m_End
                    );
            }

        private:
        // Attributes
            match_type m_Match;
            input_iterator_type m_Next;
            input_iterator_type m_End;
        };

        //! split iterator construction helper
        /*!
         *    Construct a split iterator to iterate through the specified collection
         */
        template<typename CollectionT, typename FinderT>
        inline split_iterator<
            BOOST_STRING_TYPENAME result_iterator_of<CollectionT>::type>
        make_split_iterator(
            CollectionT& Collection,
            FinderT Finder)
        {
            return split_iterator<BOOST_STRING_TYPENAME result_iterator_of<CollectionT>::type>(
                begin(Collection), end(Collection), Finder);
        }

    } // namespace algorithm

    // pull names to the boost namespace
    using algorithm::find_iterator;
    using algorithm::make_find_iterator;
    using algorithm::split_iterator;
    using algorithm::make_split_iterator;

} // namespace boost

#endif  // BOOST_STRING_FIND_ITERATOR_HPP

max_stars_repo_name: macaurther/DOCUSA

max_issues_repo_name: macaurther/DOCUSA

max_forks_repo_name: dguenms/Dawn-of-Civilization


text:
#include "unittest.h"
#include "OpcUaStackCore/BuildInTypes/OpcUaNumber.h"
#include "OpcUaStackCore/Base/Utility.h"
#include <sstream>
#include <boost/iostreams/stream.hpp>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>

using namespace OpcUaStackCore;

void writeDocument(boost::property_tree::ptree& pt)
{
#if 0
	std::cout << "READ" << std::endl;

	std::stringstream ss1;
	boost::property_tree::ptree js;
	ss1 << "{ \"Value\": \"123\" }";
	boost::property_tree::json_parser::read_json(ss1, js);

	std::cout << "WRITE:" << std::endl;
#endif

	boost::property_tree::ptree xx;
	xx.add_child("AAA", pt);

	std::stringstream ss2;
	boost::property_tree::json_parser::write_json(ss2, xx);
	std::cout << "Document: " << ss2.str() << std::endl;
}

BOOST_AUTO_TEST_SUITE(OpcUaNumber_)

BOOST_AUTO_TEST_CASE(OpcUaNumber_)
{
	std::cout << "OpcUaNumber_t" << std::endl;
}

BOOST_AUTO_TEST_CASE(OpcUaNumber_OpcUaBoolean)
{
	std::stringstream ss;
	OpcUaBoolean value1, value2;

	value1 = true;
	OpcUaNumber::opcUaBinaryEncode(ss, value1);
	OpcUaNumber::opcUaBinaryDecode(ss, value2);
	BOOST_REQUIRE(value2 == true);

	OpcUaNumber::opcUaBinaryEncode(ss, false);
	OpcUaNumber::opcUaBinaryDecode(ss, value2);
	BOOST_REQUIRE(value2 == false);
}

BOOST_AUTO_TEST_CASE(OpcUaNumber_OpcUaBoolean_ptree)
{
	boost::property_tree::ptree pt;
	OpcUaBoolean value1, value2;

	value1 = true;
	OpcUaNumber::encode(pt, value1);
	OpcUaNumber::decode(pt, value2);
	BOOST_REQUIRE(value2 == true);

	OpcUaNumber::encode(pt, false);
	OpcUaNumber::decode(pt, value2);
	BOOST_REQUIRE(value2 == false);
}

BOOST_AUTO_TEST_CASE(OpcUaNumber_OpcUaBooleanArray)
{
	std::stringstream ss;
	OpcUaBooleanArray value1, value2;

	value1.resize(3);
	value1.set(0, true);
	value1.set(1, false);
	value1.set(2, true);

	OpcUaNumber::opcUaBinaryEncode(ss, value1);
	OpcUaNumber::opcUaBinaryDecode(ss, value2);

	bool result;
	BOOST_REQUIRE(value2.get(0, result) == true);
	BOOST_REQUIRE(result == true);
	BOOST_REQUIRE(value2.get(1, result) == true);
	BOOST_REQUIRE(result == false);
	BOOST_REQUIRE(value2.get(2, result) == true);
	BOOST_REQUIRE(result == true);
	BOOST_REQUIRE(value2.get(3, result) == false);
}

BOOST_AUTO_TEST_CASE(OpcUaNumber_OpcUaBooleanArray_ptree)
{
	boost::property_tree::ptree pt;
	OpcUaBooleanArray value1, value2;

	value1.resize(3);
	value1.set(0, true);
	value1.set(1, false);
	value1.set(2, true);

	OpcUaNumber::encode(pt, value1);
	OpcUaNumber::decode(pt, value2);

	bool result;
	BOOST_REQUIRE(value2.get(0, result) == true);
	BOOST_REQUIRE(result == true);
	BOOST_REQUIRE(value2.get(1, result) == true);
	BOOST_REQUIRE(result == false);
	BOOST_REQUIRE(value2.get(2, result) == true);
	BOOST_REQUIRE(result == true);
	BOOST_REQUIRE(value2.get(3, result) == false);
}

BOOST_AUTO_TEST_CASE(OpcUaNumber_OpcUaBooleanArraySPtr)
{
	std::stringstream ss;
	OpcUaBooleanArray::SPtr value1, value2;

	value1 = constructSPtr<OpcUaBooleanArray>();
	value2 = constructSPtr<OpcUaBooleanArray>();

	value1->resize(3);
	value1->set(0, true);
	value1->set(1, false);
	value1->set(2, true);

	OpcUaNumber::opcUaBinaryEncode(ss, value1);
	OpcUaNumber::opcUaBinaryDecode(ss, value2);

	bool result;
	BOOST_REQUIRE(value2->get(0, result) == true);
	BOOST_REQUIRE(result == true);
	BOOST_REQUIRE(value2->get(1, result) == true);
	BOOST_REQUIRE(result == false);
	BOOST_REQUIRE(value2->get(2, result) == true);
	BOOST_REQUIRE(result == true);
	BOOST_REQUIRE(value2->get(3, result) == false);
}

BOOST_AUTO_TEST_CASE(OpcUaNumber_OpcUaBooleanArraySPtr_ptree)
{
	boost::property_tree::ptree pt;
	OpcUaBooleanArray::SPtr value1, value2;

	value1 = constructSPtr<OpcUaBooleanArray>();
	value2 = constructSPtr<OpcUaBooleanArray>();

	value1->resize(3);
	value1->set(0, true);
	value1->set(1, false);
	value1->set(2, true);

	OpcUaNumber::encode(pt, value1);
	OpcUaNumber::decode(pt, value2);

	bool result;
	BOOST_REQUIRE(value2->get(0, result) == true);
	BOOST_REQUIRE(result == true);
	BOOST_REQUIRE(value2->get(1, result) == true);
	BOOST_REQUIRE(result == false);
	BOOST_REQUIRE(value2->get(2, result) == true);
	BOOST_REQUIRE(result == true);
	BOOST_REQUIRE(value2->get(3, result) == false);
}

BOOST_AUTO_TEST_CASE(OpcUaNumber_OpcUaSByte)
{
	std::stringstream ss;
	OpcUaSByte value1, value2;

	value1 = -128;
	OpcUaNumber::opcUaBinaryEncode(ss, value1);
	OpcUaNumber::opcUaBinaryDecode(ss, value2);
	BOOST_REQUIRE(value2 == -128);

	value1 = -1;
	OpcUaNumber::opcUaBinaryEncode(ss, value1);
	OpcUaNumber::opcUaBinaryDecode(ss, value2);
	BOOST_REQUIRE(value2 == -1);

	value1 = 0;
	OpcUaNumber::opcUaBinaryEncode(ss, value1);
	OpcUaNumber::opcUaBinaryDecode(ss, value2);
	BOOST_REQUIRE(value2 == 0);

	value1 = 1;
	OpcUaNumber::opcUaBinaryEncode(ss, value1);
	OpcUaNumber::opcUaBinaryDecode(ss, value2);
	BOOST_REQUIRE(value2 == 1);

	value1 = 127;
	OpcUaNumber::opcUaBinaryEncode(ss, value1);
	OpcUaNumber::opcUaBinaryDecode(ss, value2);
	BOOST_REQUIRE(value2 == 127);
}

BOOST_AUTO_TEST_CASE(OpcUaNumber_OpcUaSByte_ptree)
{
	boost::property_tree::ptree pt;
	OpcUaSByte value1, value2;

	value1 = -128;
	OpcUaNumber::encode(pt, value1);
	writeDocument(pt);
	OpcUaNumber::decode(pt, value2);
	BOOST_REQUIRE(value2 == -128);

	value1 = -1;
	OpcUaNumber::encode(pt, value1);
	OpcUaNumber::decode(pt, value2);
	BOOST_REQUIRE(value2 == -1);

	value1 = 0;
	OpcUaNumber::encode(pt, value1);
	OpcUaNumber::decode(pt, value2);
	BOOST_REQUIRE(value2 == 0);

	value1 = 1;
	OpcUaNumber::encode(pt, value1);
	OpcUaNumber::decode(pt, value2);
	BOOST_REQUIRE(value2 == 1);

	value1 = 127;
	OpcUaNumber::encode(pt, value1);
	OpcUaNumber::decode(pt, value2);
	BOOST_REQUIRE(value2 == 127);
}

BOOST_AUTO_TEST_CASE(OpcUaNumber_OpcUaByte)
{
	std::stringstream ss;
	OpcUaByte value1, value2;

	value1 = 0;
	OpcUaNumber::opcUaBinaryEncode(ss, value1);
	OpcUaNumber::opcUaBinaryDecode(ss, value2);
	BOOST_REQUIRE(value2 == 0);

	value1 = 1;
	OpcUaNumber::opcUaBinaryEncode(ss, value1);
	OpcUaNumber::opcUaBinaryDecode(ss, value2);
	BOOST_REQUIRE(value2 == 1);

	value1 = 255;
	OpcUaNumber::opcUaBinaryEncode(ss, value1);
	OpcUaNumber::opcUaBinaryDecode(ss, value2);
	BOOST_REQUIRE(value2 == 255);
}

BOOST_AUTO_TEST_CASE(OpcUaNumber_OpcUaByte_ptree)
{
	boost::property_tree::ptree pt;
	OpcUaByte value1, value2;

	value1 = 0;
	OpcUaNumber::encode(pt, value1);
	OpcUaNumber::decode(pt, value2);
	BOOST_REQUIRE(value2 == 0);

	value1 = 1;
	OpcUaNumber::encode(pt, value1);
	OpcUaNumber::decode(pt, value2);
	BOOST_REQUIRE(value2 == 1);

	value1 = 255;
	OpcUaNumber::encode(pt, value1);
	OpcUaNumber::decode(pt, value2);
	BOOST_REQUIRE(value2 == 255);
}

BOOST_AUTO_TEST_CASE(OpcUaNumber_OpcUaInt16)
{
	std::stringstream ss;
	OpcUaInt16 value1, value2;

	value1 = -0x7FFF;
	OpcUaNumber::opcUaBinaryEncode(ss, value1);
	OpcUaNumber::opcUaBinaryDecode(ss, value2);
	BOOST_REQUIRE(value2 == -0x7FFF);

	value1 = -1;
	OpcUaNumber::opcUaBinaryEncode(ss, value1);
	OpcUaNumber::opcUaBinaryDecode(ss, value2);
	BOOST_REQUIRE(value2 == -1);

	value1 = 0;
	OpcUaNumber::opcUaBinaryEncode(ss, value1);
	OpcUaNumber::opcUaBinaryDecode(ss, value2);
	BOOST_REQUIRE(value2 == 0);

	value1 = 1;
	OpcUaNumber::opcUaBinaryEncode(ss, value1);
	OpcUaNumber::opcUaBinaryDecode(ss, value2);
	BOOST_REQUIRE(value2 == 1);

	value1 = 0x7FFE;
	OpcUaNumber::opcUaBinaryEncode(ss, value1);
	OpcUaNumber::opcUaBinaryDecode(ss, value2);
	BOOST_REQUIRE(value2 == 0x7FFE);
}

BOOST_AUTO_TEST_CASE(OpcUaNumber_OpcUaInt16_ptree)
{
	boost::property_tree::ptree pt;
	OpcUaInt16 value1, value2;

	value1 = -0x7FFF;
	OpcUaNumber::encode(pt, value1);
	OpcUaNumber::decode(pt, value2);
	BOOST_REQUIRE(value2 == -0x7FFF);

	value1 = -1;
	OpcUaNumber::encode(pt, value1);
	OpcUaNumber::decode(pt, value2);
	BOOST_REQUIRE(value2 == -1);

	value1 = 0;
	OpcUaNumber::encode(pt, value1);
	OpcUaNumber::decode(pt, value2);
	BOOST_REQUIRE(value2 == 0);

	value1 = 1;
	OpcUaNumber::encode(pt, value1);
	OpcUaNumber::decode(pt, value2);
	BOOST_REQUIRE(value2 == 1);

	value1 = 0x7FFE;
	OpcUaNumber::encode(pt, value1);
	OpcUaNumber::decode(pt, value2);
	BOOST_REQUIRE(value2 == 0x7FFE);
}

BOOST_AUTO_TEST_CASE(OpcUaNumber_OpcUaUInt16)
{
	std::stringstream ss;
	OpcUaUInt16 value1, value2;

	value1 = 0;
	OpcUaNumber::opcUaBinaryEncode(ss, value1);
	OpcUaNumber::opcUaBinaryDecode(ss, value2);
	BOOST_REQUIRE(value2 == 0);

	value1 = 1;
	OpcUaNumber::opcUaBinaryEncode(ss, value1);
	OpcUaNumber::opcUaBinaryDecode(ss, value2);
	BOOST_REQUIRE(value2 == 1);

	value1 = 0xFFFF;
	OpcUaNumber::opcUaBinaryEncode(ss, value1);
	OpcUaNumber::opcUaBinaryDecode(ss, value2);
	BOOST_REQUIRE(value2 == 0xFFFF);
}

BOOST_AUTO_TEST_CASE(OpcUaNumber_OpcUaUInt16_ptree)
{
	boost::property_tree::ptree pt;
	OpcUaUInt16 value1, value2;

	value1 = 0;
	OpcUaNumber::encode(pt, value1);
	OpcUaNumber::decode(pt, value2);
	BOOST_REQUIRE(value2 == 0);

	value1 = 1;
	OpcUaNumber::encode(pt, value1);
	OpcUaNumber::decode(pt, value2);
	BOOST_REQUIRE(value2 == 1);

	value1 = 0xFFFF;
	OpcUaNumber::encode(pt, value1);
	OpcUaNumber::decode(pt, value2);
	BOOST_REQUIRE(value2 == 0xFFFF);
}

BOOST_AUTO_TEST_CASE(OpcUaNumber_OpcUaInt32)
{
	std::stringstream ss;
	OpcUaInt32 value1, value2;

	value1 = -0x7FFFFFFF;
	OpcUaNumber::opcUaBinaryEncode(ss, value1);
	OpcUaNumber::opcUaBinaryDecode(ss, value2);
	BOOST_REQUIRE(value2 == -0x7FFFFFFF);

	value1 = -1;
	OpcUaNumber::opcUaBinaryEncode(ss, value1);
	OpcUaNumber::opcUaBinaryDecode(ss, value2);
	BOOST_REQUIRE(value2 == -1);

	value1 = 0;
	OpcUaNumber::opcUaBinaryEncode(ss, value1);
	OpcUaNumber::opcUaBinaryDecode(ss, value2);
	BOOST_REQUIRE(value2 == 0);

	value1 = 1;
	OpcUaNumber::opcUaBinaryEncode(ss, value1);
	OpcUaNumber::opcUaBinaryDecode(ss, value2);
	BOOST_REQUIRE(value2 == 1);

	value1 = 0x7FFFFFFE;
	OpcUaNumber::opcUaBinaryEncode(ss, value1);
	OpcUaNumber::opcUaBinaryDecode(ss, value2);
	BOOST_REQUIRE(value2 == 0x7FFFFFFE);
}

BOOST_AUTO_TEST_CASE(OpcUaNumber_OpcUaInt32_ptree)
{
	boost::property_tree::ptree pt;
	OpcUaInt32 value1, value2;

	value1 = -0x7FFFFFFF;
	OpcUaNumber::encode(pt, value1);
	OpcUaNumber::decode(pt, value2);
	BOOST_REQUIRE(value2 == -0x7FFFFFFF);

	value1 = -1;
	OpcUaNumber::encode(pt, value1);
	OpcUaNumber::decode(pt, value2);
	BOOST_REQUIRE(value2 == -1);

	value1 = 0;
	OpcUaNumber::encode(pt, value1);
	OpcUaNumber::decode(pt, value2);
	BOOST_REQUIRE(value2 == 0);

	value1 = 1;
	OpcUaNumber::encode(pt, value1);
	OpcUaNumber::decode(pt, value2);
	BOOST_REQUIRE(value2 == 1);

	value1 = 0x7FFFFFFE;
	OpcUaNumber::encode(pt, value1);
	OpcUaNumber::decode(pt, value2);
	BOOST_REQUIRE(value2 == 0x7FFFFFFE);
}

BOOST_AUTO_TEST_CASE(OpcUaNumber_OpcUaUInt32)
{
	std::stringstream ss;
	OpcUaUInt32 value1, value2;

	value1 = 0;
	OpcUaNumber::opcUaBinaryEncode(ss, value1);
	OpcUaNumber::opcUaBinaryDecode(ss, value2);
	BOOST_REQUIRE(value2 == 0);

	value1 = 1;
	OpcUaNumber::opcUaBinaryEncode(ss, value1);
	OpcUaNumber::opcUaBinaryDecode(ss, value2);
	BOOST_REQUIRE(value2 == 1);

	value1 = 0xFFFFFFFF;
	OpcUaNumber::opcUaBinaryEncode(ss, value1);
	OpcUaNumber::opcUaBinaryDecode(ss, value2);
	BOOST_REQUIRE(value2 == 0xFFFFFFFF);
}

BOOST_AUTO_TEST_CASE(OpcUaNumber_OpcUaUInt32_ptree)
{
	boost::property_tree::ptree pt;
	OpcUaUInt32 value1, value2;

	value1 = 0;
	OpcUaNumber::encode(pt, value1);
	OpcUaNumber::decode(pt, value2);
	BOOST_REQUIRE(value2 == 0);

	value1 = 1;
	OpcUaNumber::encode(pt, value1);
	OpcUaNumber::decode(pt, value2);
	BOOST_REQUIRE(value2 == 1);

	value1 = 0xFFFFFFFF;
	OpcUaNumber::encode(pt, value1);
	OpcUaNumber::decode(pt, value2);
	BOOST_REQUIRE(value2 == 0xFFFFFFFF);
}

BOOST_AUTO_TEST_CASE(OpcUaNumber_OpcUaInt64)
{
	std::stringstream ss;
	OpcUaInt64 value1, value2;

	value1 = -0x7FFFFFFFFFFFFFFF;
	OpcUaNumber::opcUaBinaryEncode(ss, value1);
	OpcUaNumber::opcUaBinaryDecode(ss, value2);
	BOOST_REQUIRE(value2 == -0x7FFFFFFFFFFFFFFF);

	value1 = -1;
	OpcUaNumber::opcUaBinaryEncode(ss, value1);
	OpcUaNumber::opcUaBinaryDecode(ss, value2);
	BOOST_REQUIRE(value2 == -1);

	value1 = 0;
	OpcUaNumber::opcUaBinaryEncode(ss, value1);
	OpcUaNumber::opcUaBinaryDecode(ss, value2);
	BOOST_REQUIRE(value2 == 0);

	value1 = 1;
	OpcUaNumber::opcUaBinaryEncode(ss, value1);
	OpcUaNumber::opcUaBinaryDecode(ss, value2);
	BOOST_REQUIRE(value2 == 1);

	value1 = 0x7FFFFFFE;
	OpcUaNumber::opcUaBinaryEncode(ss, value1);
	OpcUaNumber::opcUaBinaryDecode(ss, value2);
	BOOST_REQUIRE(value2 == 0x7FFFFFFE);
}

BOOST_AUTO_TEST_CASE(OpcUaNumber_OpcUaInt64_ptree)
{
	boost::property_tree::ptree pt;
	OpcUaInt64 value1, value2;

	value1 = -0x7FFFFFFFFFFFFFFF;
	OpcUaNumber::encode(pt, value1);
	OpcUaNumber::decode(pt, value2);
	BOOST_REQUIRE(value2 == -0x7FFFFFFFFFFFFFFF);

	value1 = -1;
	OpcUaNumber::encode(pt, value1);
	OpcUaNumber::decode(pt, value2);
	BOOST_REQUIRE(value2 == -1);

	value1 = 0;
	OpcUaNumber::encode(pt, value1);
	OpcUaNumber::decode(pt, value2);
	BOOST_REQUIRE(value2 == 0);

	value1 = 1;
	OpcUaNumber::encode(pt, value1);
	OpcUaNumber::decode(pt, value2);
	BOOST_REQUIRE(value2 == 1);

	value1 = 0x7FFFFFFE;
	OpcUaNumber::encode(pt, value1);
	OpcUaNumber::decode(pt, value2);
	BOOST_REQUIRE(value2 == 0x7FFFFFFE);
}

BOOST_AUTO_TEST_CASE(OpcUaNumber_OpcUaUInt64)
{
	std::stringstream ss;
	OpcUaUInt64 value1, value2;

	value1 = 0;
	OpcUaNumber::opcUaBinaryEncode(ss, value1);
	OpcUaNumber::opcUaBinaryDecode(ss, value2);
	BOOST_REQUIRE(value2 == 0);

	value1 = 1;
	OpcUaNumber::opcUaBinaryEncode(ss, value1);
	OpcUaNumber::opcUaBinaryDecode(ss, value2);
	BOOST_REQUIRE(value2 == 1);

	value1 = 0xFFFFFFFFFFFFFFFF;
	OpcUaNumber::opcUaBinaryEncode(ss, value1);
	OpcUaNumber::opcUaBinaryDecode(ss, value2);
	BOOST_REQUIRE(value2 == 0xFFFFFFFFFFFFFFFF);
}

BOOST_AUTO_TEST_CASE(OpcUaNumber_OpcUaUInt64_ptree)
{
	boost::property_tree::ptree pt;
	OpcUaUInt64 value1, value2;

	value1 = 0;
	OpcUaNumber::encode(pt, value1);
	OpcUaNumber::decode(pt, value2);
	BOOST_REQUIRE(value2 == 0);

	value1 = 1;
	OpcUaNumber::encode(pt, value1);
	OpcUaNumber::decode(pt, value2);
	BOOST_REQUIRE(value2 == 1);

	value1 = 0xFFFFFFFFFFFFFFFF;
	OpcUaNumber::encode(pt, value1);
	OpcUaNumber::decode(pt, value2);
	BOOST_REQUIRE(value2 == 0xFFFFFFFFFFFFFFFF);
}

BOOST_AUTO_TEST_CASE(OpcUaNumber_OpcUaFloat)
{
	std::stringstream ss;
	OpcUaFloat value1, value2;

	value1 = (float)-1234.56;
	OpcUaNumber::opcUaBinaryEncode(ss, value1);
	OpcUaNumber::opcUaBinaryDecode(ss, value2);
	BOOST_REQUIRE((float)value2 == (float)-1234.56);

	value1 = -1;
	OpcUaNumber::opcUaBinaryEncode(ss, value1);
	OpcUaNumber::opcUaBinaryDecode(ss, value2);
	BOOST_REQUIRE(value2 == -1);

	value1 = 0;
	OpcUaNumber::opcUaBinaryEncode(ss, value1);
	OpcUaNumber::opcUaBinaryDecode(ss, value2);
	BOOST_REQUIRE(value2 == 0);

	value1 = 1;
	OpcUaNumber::opcUaBinaryEncode(ss, value1);
	OpcUaNumber::opcUaBinaryDecode(ss, value2);
	BOOST_REQUIRE(value2 == 1);

	value1 = (float)1234.56;
	OpcUaNumber::opcUaBinaryEncode(ss, value1);
	OpcUaNumber::opcUaBinaryDecode(ss, value2);
	BOOST_REQUIRE((float)value2 == (float)1234.56);
}

BOOST_AUTO_TEST_CASE(OpcUaNumber_OpcUaFloat_ptree)
{
	boost::property_tree::ptree pt;
	OpcUaFloat value1, value2;

	value1 = (float)-1234.56;
	OpcUaNumber::encode(pt, value1);
	OpcUaNumber::decode(pt, value2);
	BOOST_REQUIRE((float)value2 == (float)-1234.56);

	value1 = -1;
	OpcUaNumber::encode(pt, value1);
	OpcUaNumber::decode(pt, value2);
	BOOST_REQUIRE(value2 == -1);

	value1 = 0;
	OpcUaNumber::encode(pt, value1);
	OpcUaNumber::decode(pt, value2);
	BOOST_REQUIRE(value2 == 0);

	value1 = 1;
	OpcUaNumber::encode(pt, value1);
	OpcUaNumber::decode(pt, value2);
	BOOST_REQUIRE(value2 == 1);

	value1 = (float)1234.56;
	OpcUaNumber::encode(pt, value1);
	OpcUaNumber::decode(pt, value2);
	BOOST_REQUIRE((float)value2 == (float)1234.56);
}

BOOST_AUTO_TEST_CASE(OpcUaNumber_OpcUaDouble)
{
	std::stringstream ss;
	OpcUaDouble value1, value2;

	value1 = -1234.56;
	OpcUaNumber::opcUaBinaryEncode(ss, value1);
	OpcUaNumber::opcUaBinaryDecode(ss, value2);
	BOOST_REQUIRE(value2 == -1234.56);

	value1 = -1;
	OpcUaNumber::opcUaBinaryEncode(ss, value1);
	OpcUaNumber::opcUaBinaryDecode(ss, value2);
	BOOST_REQUIRE(value2 == -1);

	value1 = 0;
	OpcUaNumber::opcUaBinaryEncode(ss, value1);
	OpcUaNumber::opcUaBinaryDecode(ss, value2);
	BOOST_REQUIRE(value2 == 0);

	value1 = 1;
	OpcUaNumber::opcUaBinaryEncode(ss, value1);
	OpcUaNumber::opcUaBinaryDecode(ss, value2);
	BOOST_REQUIRE(value2 == 1);

	value1 = 1234.56;
	OpcUaNumber::opcUaBinaryEncode(ss, value1);
	OpcUaNumber::opcUaBinaryDecode(ss, value2);
	BOOST_REQUIRE(value2 == 1234.56);
}

BOOST_AUTO_TEST_CASE(OpcUaNumber_OpcUaDouble_ptree)
{
	boost::property_tree::ptree pt;
	OpcUaDouble value1, value2;

	value1 = -1234.56;
	OpcUaNumber::encode(pt, value1);
	OpcUaNumber::decode(pt, value2);
	BOOST_REQUIRE(value2 == -1234.56);

	value1 = -1;
	OpcUaNumber::encode(pt, value1);
	OpcUaNumber::decode(pt, value2);
	BOOST_REQUIRE(value2 == -1);

	value1 = 0;
	OpcUaNumber::encode(pt, value1);
	OpcUaNumber::decode(pt, value2);
	BOOST_REQUIRE(value2 == 0);

	value1 = 1;
	OpcUaNumber::encode(pt, value1);
	OpcUaNumber::decode(pt, value2);
	BOOST_REQUIRE(value2 == 1);

	value1 = 1234.56;
	OpcUaNumber::encode(pt, value1);
	OpcUaNumber::decode(pt, value2);
	BOOST_REQUIRE(value2 == 1234.56);
}

BOOST_AUTO_TEST_SUITE_END()

max_stars_repo_name: gianricardo/OpcUaStack

max_issues_repo_name: gianricardo/OpcUaStack

max_forks_repo_name: gianricardo/OpcUaStack


text:
#include <iostream>
#include <fstream>
#include <iomanip>
#include <random>
#include <chrono>
#include "program_config.hpp"
#include "fileset.hpp"
#include "nntp/message.hpp"
#include "nntp/usenet.hpp"
#include <boost/algorithm/string/replace.hpp>

const int NONCE_LENGTH = 16;
using msgid_exceptions_map = std::map<filepiece_key, std::string>;

static std::mt19937 rng{static_cast<std::mt19937::result_type>(
            std::chrono::system_clock::now().time_since_epoch().count())};

static std::string get_run_nonce(size_t length)
{
    static const char choices[] = "abcdefghijklmnopqrstuvwxyz1234567890";
    std::ostringstream stream;

    for (size_t i = 0; i < length; ++i)
    {
        stream << choices[rng() % (sizeof(choices) - 1)];
    }

    return stream.str();
}

std::string ghetto_xml_escape(const std::string& str)
{
    auto escaped = str;
    boost::algorithm::replace_all(escaped, "\"", """);
    boost::algorithm::replace_all(escaped, "'", "'");
    boost::algorithm::replace_all(escaped, "<", "<");
    boost::algorithm::replace_all(escaped, ">", ">");
    boost::algorithm::replace_all(escaped, ">", "&");
    return escaped;
}

using piece_size_map = std::map<size_t, size_t>;

void write_nzb(std::ostream& stream, const fileset& files, const prog_config& cfg, const std::vector<piece_size_map>& piece_sizes, const std::string& nonce, const msgid_exceptions_map& exceptions)
{
    auto epoch_time = std::chrono::system_clock::now().time_since_epoch().count();

    stream << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" << std::endl;
    stream << "<!DOCTYPE nzb PUBLIC \"-//newzBin//DTD NZB 1.1//END\" \"http://www.newzbin.com/DTD/nzb/nzb-1.1.dtd\">" << std::endl;
    stream << "<nzb xmlns=\"http://www.newzbin.com/DTD/2003/nzb\">" << std::endl;
    stream << std::endl;

    for (size_t i = 0; i < files.get_num_files(); ++i)
    {
        stream << "<file poster=\"" << ghetto_xml_escape(cfg.from)
            << "\" date=\"" << epoch_time
            << "\" subject=\""
            << ghetto_xml_escape(files.get_usenet_subject(cfg.subject, i, 0)) << "\">" << std::endl;

        stream << "<groups>" << std::endl;
        for (const auto& group : cfg.groups)
        {
            stream << "<group>" << group << "</group>" << std::endl;
        }
        stream << "</groups>" << std::endl;

        stream << "<segments>" << std::endl;
        for (size_t pieceIndex = 0; pieceIndex < files.get_num_pieces(i); ++pieceIndex)
        {
            auto it = piece_sizes[i].find(pieceIndex);

            auto exception_it = exceptions.find({i, pieceIndex});
            const auto& actual_nonce = exception_it == exceptions.end() ? nonce : exception_it->second;
            auto msg_id = fileset::get_usenet_message_id(actual_nonce, cfg.msgiddomain, i, pieceIndex);
            boost::algorithm::replace_all(msg_id, "<", "");
            boost::algorithm::replace_all(msg_id, ">", "");

            stream << "<segment bytes=\"" << it->second
                << "\" number=\"" << pieceIndex + 1
                << "\">" << msg_id
                << "</segment>" << std::endl;
        }

        stream << "</segments>" << std::endl;
        stream << "</file>" << std::endl;
    }

    stream << "</nzb>" << std::endl;
}

int main(int argc, const char* argv[])
{
    namespace fs = boost::filesystem;

    prog_config cfg;
    if (!load_program_config(argc, argv, cfg))
    {
        return 1;
    }

    if (cfg.subject.empty())
    {
        // If there is only a single file, we just use the file as the subject
        if (cfg.files.size() == 1)
        {
            cfg.subject = cfg.files[0].filename().generic_string();
        }
        else
        {
            std::cout << "You are attempting to posting multiple files. Please specify a subject to identify this grouping of files" << std::endl;
            return 1;
        }
    }

    if (!cfg.nzboutput.empty())
    {
        fs::path p{cfg.nzboutput};
        if (boost::filesystem::is_directory(p))
        {
            fs::path file_out{cfg.subject + ".nzb"};
            cfg.nzboutput = (p / file_out).generic_string();
        }
    }

    fileset postitems{cfg.article_size};
    uint64_t total_bytes = 0;

    auto add_postitem = [&postitems, &total_bytes](const boost::filesystem::path& path)
    {
        postitems.add_file(path);
        total_bytes += boost::filesystem::file_size(path);
    };

    for (auto& path : cfg.files)
    {
        if (fs::is_directory(path))
        {
            for (auto it = fs::recursive_directory_iterator{path}; it != fs::recursive_directory_iterator{}; ++it)
            {
                if (fs::is_regular_file(it->path()))
                {
                    add_postitem(it->path());
                }
            }
        }
        else if (fs::is_regular_file(path))
        {
            add_postitem(path);
        }
        else
        {
            std::cerr << "[WARN] Ignoring " << path << " since it is neither a file nor a directory!" << std::endl;
        }
    }

    p2u::nntp::usenet usenet{cfg.io_threads, cfg.queue_size};
    usenet.set_operation_timeout(cfg.operation_timeout);
    for (const auto& p : cfg.servers)
    {
        usenet.add_connections(p.first, p.second);
    }

    std::string run_nonce = get_run_nonce(NONCE_LENGTH);

    size_t num_total_files = postitems.get_num_files();
    size_t total_parts = postitems.get_total_pieces();
    size_t num_posted = 0;
    uint64_t bytes_posted = 0;

    auto post_start = std::chrono::system_clock::now();

    // TODO: We are only dealing with 1 IO thread right now. Guard this in the future
    msgid_exceptions_map msgid_exceptions;
    std::map<filepiece_key, int> msgid_retries;

    usenet.set_stat_finished_callback([&](const std::string& msgid, p2u::nntp::stat_result result)
            {
                // TODO: Resubmit appropriate piece when stat result fails.
                std::cout << "HEADER CHECK> " << msgid << " - " << (result == p2u::nntp::stat_result::ARTICLE_EXISTS ? "OK" : "FAIL") << std::endl;
            });

    usenet.set_post_failed_callback([&](const std::shared_ptr<p2u::nntp::article>& article)
            {
                auto key = fileset::get_key_from_message_id(article->get_header().msgid);
                auto it = msgid_retries.find(key);
                if (it == msgid_retries.end())
                {
                    auto inserted = msgid_retries.insert(std::make_pair(key, 1));
                    it = inserted.first;
                }
                else
                {
                    it->second++;
                    if (it->second >= 3)
                    {
                        std::cerr << "[FATAL] Too many retries while posting " << article->get_header().msgid << ". Aborting program!" << std::endl;
                        std::ostringstream dumpfile;
                        dumpfile << article->get_header().msgid << ".dump";
                        std::ofstream dump{dumpfile.str().c_str(), std::ofstream::binary};
                        if (!dump.is_open())
                        {
                            std::cerr << "[FATAL] Could not open dump file. Discarding.." << std::endl;
                            std::exit(1);
                        }

                        std::ostringstream header;
                        article->get_header().write_to(header);

                        std::string headerstr = header.str();
                        dump.write(headerstr.c_str(), headerstr.length());
                        dump.write("\r\n", 2);

                        std::vector<boost::asio::const_buffer> buffers;
                        article->write_payload_asio_buffers(std::back_inserter(buffers));
                        assert(buffers.size() > 0);
                        for (auto& p : buffers)
                        {
                            const char* buf = boost::asio::buffer_cast<const char*>(p);
                            size_t bufsize = boost::asio::buffer_size(p);
                            dump.write(buf, bufsize);
                        }

                        dump.write("\r\n.\r\n", 5);
                        dump.close();
                        std::exit(1);
                    }
                }

                std::cerr << "[WARN] Posting " << article->get_header().subject << " failed. Retry #" << it->second << std::endl;
                // Try changing the message id and restarting

                auto& header = const_cast<p2u::nntp::header&>(article->get_header());

                // Add some random data to the header to be sent.
                //
                // Why you ask? For some reason, certain news providers (ahem highwinds) have
                // this stupid bug where if you try to post a certain message, it will *always* timeout
                //
                // Like, not even fail to post, just time out.
                //
                // This makes it *extremely* annoying to deal with (and it is the entire reason why I have
                // logic that "times out" a news post")
                //
                // And even worse, when they time out, *even* after I change the message ID to avoid a possibility
                // of duping a previous post, it *still* fails to post. The one method I found to seemingly work is
                // to append some random data in the header.
                std::string random_data_header_key{"X-Random-"};
                random_data_header_key += get_run_nonce(10);
                header.additional.push_back({random_data_header_key, get_run_nonce(5)});

                // Change the message ID of this part
                msgid_exceptions[key] = get_run_nonce(NONCE_LENGTH);
                header.msgid = fileset::get_usenet_message_id(msgid_exceptions[key], cfg.msgiddomain, key.file_index, key.piece_index);

                // Enqueue it back on
                usenet.enqueue_post(article, true);

                std::cerr << "[INFO] Requeued post " << article->get_header().subject << " with message id " << article->get_header().msgid << std::endl;
            });

    usenet.set_post_finished_callback([&](const std::shared_ptr<p2u::nntp::article>& article)
            {
                ++num_posted;
                bytes_posted += article->get_payload_size();

                auto seconds_elapsed = std::chrono::duration_cast<std::chrono::seconds>(std::chrono::system_clock::now() - post_start).count();
                uint64_t speed_kb = 0;
                if (seconds_elapsed != 0)
                {
                    speed_kb = (bytes_posted / seconds_elapsed) / 1024;
                }

                int percentage_complete = static_cast<int>((static_cast<float>(num_posted) / total_parts) * 100);

                size_t pieces_remaining = total_parts - num_posted;
                if (percentage_complete > 100 || pieces_remaining == 0)
                {
                    percentage_complete = 100;
                }
                std::cout << "STATUS> " << percentage_complete << "% - Pieces Remaining: " << pieces_remaining << " - Average Speed: " << speed_kb << " KB/s" << std::endl;
            });

    usenet.start();

    std::vector<piece_size_map> piece_sizes;

    for (size_t fileIndex = 0; fileIndex < num_total_files; ++fileIndex)
    {
        size_t num_pieces = postitems.get_num_pieces(fileIndex);
        auto cur_file_name = postitems.get_file_name(fileIndex);
        piece_sizes.emplace_back();

        for (size_t pieceIndex = 0; pieceIndex < num_pieces; ++pieceIndex)
        {
            // Body
            auto chunk = postitems.get_chunk(fileIndex, pieceIndex);

            piece_sizes[fileIndex][pieceIndex] = chunk.size();

            // Header
            p2u::nntp::header header;

            header.from = cfg.from;
            header.subject = postitems.get_usenet_subject(cfg.subject, fileIndex, pieceIndex);
            header.msgid = postitems.get_usenet_message_id(run_nonce, cfg.msgiddomain, fileIndex, pieceIndex);
            std::copy(cfg.groups.begin(), cfg.groups.end(), std::back_inserter(header.newsgroups));

            auto article = std::make_shared<p2u::nntp::article>(header);
            article->add_payload_piece(std::move(chunk));
            usenet.enqueue_post(article);
        }
    }

    // TODO: Somehow figure out to validate the right posts. (When we retry, we generate a new message id)
    if (cfg.validate_posts)
    {
        for (size_t fileIndex = 0; fileIndex < num_total_files; ++fileIndex)
        {
            size_t num_pieces = postitems.get_num_pieces(fileIndex);
            for (size_t pieceIndex = 0; pieceIndex < num_pieces; ++pieceIndex)
            {
                usenet.enqueue_stat(postitems.get_usenet_message_id(run_nonce, cfg.msgiddomain, fileIndex, pieceIndex));
            }
        }
    }

    usenet.stop();
    usenet.join();

    // If we've reached here without fully dispensing all items in our queue, this means that the program
    // prematurely stopped.
    if (usenet.get_queue_size() == 0)
    {
        if (!cfg.nzboutput.empty())
        {
            std::ofstream nzboutstream;
            nzboutstream.open(cfg.nzboutput.c_str());
            if (!nzboutstream.is_open())
            {
                std::cout << "ERROR: Cannot open " << cfg.nzboutput << " for writing. Nzb output discarded." << std::endl;
            }
            else
            {
                write_nzb(nzboutstream, postitems, cfg, piece_sizes, run_nonce, msgid_exceptions);
            }
        }
        return 0;
    }
    else
    {
        std::cout << "[ERROR] Workers died when there was still work for them to do!. " << std::endl;
        return 1;
    }

}


text:
//
// Created by odderikf on 11/10/18.
//

#ifndef OVING12_CONSTANTS_HPP
#define OVING12_CONSTANTS_HPP

#include <boost/filesystem.hpp>

const int BYTE_SIZE = 256;
const int BLOCK_SIZE = 8192;

const boost::filesystem::path test_in("test_in");
const boost::filesystem::path test_out("test_out");
const boost::filesystem::path test_huff("test_huff");
const boost::filesystem::path huff("huff");
const boost::filesystem::path dot(".");

const bool verbose = false;

#endif //OVING12_CONSTANTS_HPP

max_stars_repo_name: odderikf/algdat

max_issues_repo_name: odderikf/algdat

max_forks_repo_name: odderikf/algdat


text:
//  Copyright (c) 2014 Thomas Heller
//
//  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)

// hpxinspect:nodeprecatedinclude:boost/shared_ptr.hpp
// hpxinspect:nodeprecatedname:boost::shared_ptr

#include <hpx/runtime/serialization/serialize.hpp>
#include <hpx/runtime/serialization/shared_ptr.hpp>
#include <hpx/runtime/serialization/unique_ptr.hpp>
#include <hpx/runtime/serialization/intrusive_ptr.hpp>

#include <hpx/runtime/serialization/input_archive.hpp>
#include <hpx/runtime/serialization/output_archive.hpp>

#include <hpx/util/lightweight_test.hpp>

#include <boost/intrusive_ptr.hpp>
#include <boost/shared_ptr.hpp>

#include <memory>
#include <vector>

void test_boost_shared()
{
    boost::shared_ptr<int> ip(new int(7));
    boost::shared_ptr<int> op1;
    boost::shared_ptr<int> op2;
    {
        std::vector<char> buffer;
        hpx::serialization::output_archive oarchive(buffer);
        oarchive << ip << ip;

        hpx::serialization::input_archive iarchive(buffer);
        iarchive >> op1;
        iarchive >> op2;
    }
    HPX_TEST_NEQ(op1.get(), ip.get());
    HPX_TEST_NEQ(op2.get(), ip.get());
    HPX_TEST_EQ(op1.get(), op2.get());
    HPX_TEST_EQ(*op1, *ip);
    op1.reset();
    HPX_TEST_EQ(*op2, *ip);
}

void test_shared()
{
    std::shared_ptr<int> ip(new int(7));
    std::shared_ptr<int> op1;
    std::shared_ptr<int> op2;
    {
        std::vector<char> buffer;
        hpx::serialization::output_archive oarchive(buffer);
        oarchive << ip << ip;

        hpx::serialization::input_archive iarchive(buffer);
        iarchive >> op1;
        iarchive >> op2;
    }
    HPX_TEST_NEQ(op1.get(), ip.get());
    HPX_TEST_NEQ(op2.get(), ip.get());
    HPX_TEST_EQ(op1.get(), op2.get());
    HPX_TEST_EQ(*op1, *ip);
    op1.reset();
    HPX_TEST_EQ(*op2, *ip);
}

void test_unique()
{
    std::unique_ptr<int> ip(new int(7));
    std::unique_ptr<int> op1;
    std::unique_ptr<int> op2;
    {
        std::vector<char> buffer;
        hpx::serialization::output_archive oarchive(buffer);
        oarchive << ip << ip;

        hpx::serialization::input_archive iarchive(buffer);
        iarchive >> op1;
        iarchive >> op2;
    }
    HPX_TEST_NEQ(op1.get(), ip.get());
    HPX_TEST_NEQ(op2.get(), ip.get());
    HPX_TEST_NEQ(op1.get(), op2.get()); //untracked
    HPX_TEST_EQ(*op1, *ip);
    HPX_TEST_EQ(*op2, *ip);
}

struct A
{
    A() : i(7), count(0) {}
    int i;

    int count;

    template <typename Archive>
    void serialize(Archive & ar, unsigned)
    {
        ar & i;
    }
};

void intrusive_ptr_add_ref(A* a)
{
    ++a->count;
}

void intrusive_ptr_release(A* a)
{
    if(--a->count == 0)
    {
        delete a;
    }
}

void test_intrusive()
{
    boost::intrusive_ptr<A> ip(new A());
    boost::intrusive_ptr<A> op1;
    boost::intrusive_ptr<A> op2;
    {
        std::vector<char> buffer;
        hpx::serialization::output_archive oarchive(buffer);
        oarchive << ip << ip;

        hpx::serialization::input_archive iarchive(buffer);
        iarchive >> op1;
        iarchive >> op2;
    }
    HPX_TEST_EQ(ip->count, 1);
    HPX_TEST_NEQ(op1.get(), ip.get());
    HPX_TEST_NEQ(op2.get(), ip.get());
    HPX_TEST_EQ(op1.get(), op2.get());
    HPX_TEST_EQ(op1->i, ip->i);
    HPX_TEST_EQ(op1->count, 2);
    HPX_TEST_EQ(op2->count, 2);
    op1.reset();
    HPX_TEST_EQ(op2->count, 1);
    HPX_TEST_EQ(op2->i, ip->i);
}

int main()
{
    test_boost_shared();
    test_shared();
    test_unique();
    test_intrusive();

    return hpx::util::report_errors();
}

max_forks_repo_name: biddisco/hpx