text:
/*-------------------------------------------------------------------------
This source file is a part of Whisperwind.(GameEngine + GamePlay + GameTools)
For the latest info, see http://lisuyong.com

Copyright (c) 2012 Suyong Li (79481268@qq.com)

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

#define BOOST_ALL_NO_LIB /// Don't use boost lib.
#include <boost/date_time/posix_time/posix_time.hpp>

#include "DebugDefine.h"
#include "StringConverter.h"
#include "LogManager.h"

namespace Util
{
	//---------------------------------------------------------------------
	LogManager LogManager::mSingleton;
	LogManager & LogManager::getSingleton()
	{
		return mSingleton;
	}
	//---------------------------------------------------------------------
	LogManager::LogManager()
	{
		/// As global initialise is random,I put this string here.
		static const String LOG_PATH("../Whisperwind.log");

		mStream.open(LOG_PATH, std::ios::out | std::ios::trunc);
		WHISPERWIND_ASSERT(mStream.is_open());
	}
	//---------------------------------------------------------------------
	LogManager::~LogManager()
	{
		mStream.close();
	}
	//---------------------------------------------------------------------
	void LogManager::log(const Wstring & event)
	{
		/// I don't know why this has nothing effect to me...
		//std::locale::global(std::locale(""));

		/// So finally I just choose the common way to handle this with ANSI format.
		/// NOTE:I'll fix it.
		/// TODO:Fix it.

		String strTime = boost::posix_time::to_iso_extended_string(
			boost::posix_time::second_clock::local_time());
		strTime[10] = ' ';

		mStream  << (strTime + " : " + WstringToString(event)).c_str() << std::endl;
		mStream.flush();

		DEBUG_PRINT(event);
	}
}


text:
// some "useful" typedefs and simple classes
//

#ifndef INCLUDED_types_HH
#define INCLUDED_types_HH

// #include <boost/foreach.hpp>
// #include <boost/algorithm/string.hpp>

#include <iostream>
#include <fstream>
#include <sstream>
// #include <iterator>
#include <algorithm>
#include <string>
#include <map>
#include <vector>
#include <cassert>

#include <math.h>

using namespace std;

#define foreach_ BOOST_FOREACH

typedef std::size_t  Size;
typedef double  Real;
typedef std::pair< Size, Size > SizePair;

typedef vector< SizePair > SizePairs;
typedef vector< string > strings;
typedef vector< Size > Sizes;
typedef vector< bool > bools;
typedef vector< Real > Reals;

struct Feature {
	string name;
	Sizes poslist;
	Sizes neglist;
};

typedef vector< Feature > Features;

#endif

ext: hh

max_stars_repo_name: phbradley/repdist

max_issues_repo_name: phbradley/repdist

max_forks_repo_name: phbradley/repdist


text:
#ifndef BOOST_ARCHIVE_ITERATORS_OSTREAM_ITERATOR_HPP
#define BOOST_ARCHIVE_ITERATORS_OSTREAM_ITERATOR_HPP

// MS compatible compilers support #pragma once
#if defined(_MSC_VER)
#pragma once
#endif

/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////8
// ostream_iterator.hpp

// (C) Copyright 2002 Robert Ramey - http://www.rrsd.com .
// Use, modification and distribution is subject to the Boost Software
// License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)

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

// note: this is a custom version of the standard ostream_iterator.
// This is necessary as the standard version doesn't work as expected
// for wchar_t based streams on systems for which wchar_t not a true
// type but rather a synonym for some integer type.

#include <boost/iterator/iterator_facade.hpp>
#include <ostream>

namespace boost {
namespace archive {
namespace iterators {

// given a type, make an input iterator based on a pointer to that type
template <class Elem>
class ostream_iterator
    : public boost::iterator_facade<ostream_iterator<Elem>, Elem,
                                    std::output_iterator_tag,
                                    ostream_iterator<Elem> &> {
  friend class boost::iterator_core_access;
  typedef ostream_iterator this_t;
  typedef Elem char_type;
  typedef std::basic_ostream<char_type> ostream_type;

  // emulate the behavior of std::ostream
  ostream_iterator &dereference() const {
    return const_cast<ostream_iterator &>(*this);
  }
  bool equal(const this_t &rhs) const { return m_ostream == rhs.m_ostream; }
  void increment() {}

protected:
  ostream_type *m_ostream;
  void put_val(char_type e) {
    if (NULL != m_ostream) {
      m_ostream->put(e);
      if (!m_ostream->good())
        m_ostream = NULL;
    }
  }

public:
  this_t &operator=(char_type c) {
    put_val(c);
    return *this;
  }
  ostream_iterator(ostream_type &os) : m_ostream(&os) {}
  ostream_iterator() : m_ostream(NULL) {}
  ostream_iterator(const ostream_iterator &rhs) : m_ostream(rhs.m_ostream) {}
};

} // namespace iterators
} // namespace archive
} // namespace boost

#endif // BOOST_ARCHIVE_ITERATORS_OSTREAM_ITERATOR_HPP

ext: hpp

max_stars_repo_name: henrywarhurst/matrix

max_issues_repo_name: henrywarhurst/matrix

max_forks_repo_name: henrywarhurst/matrix


text:
//
// Copyright (c) 2020 Vinnie Falco (vinnie.falco@gmail.com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
// Official repository: https://github.com/madmongo1/webclient
//

// Test that header file is self-contained.
#include "test_suite.hpp"

#include <boost/webclient/forty_two.hpp>

namespace boost {
namespace webclient {

class forty_two_test
{
  public:
    void run()
    {
        BOOST_TEST(forty_two() == 42);
    }
};

TEST_SUITE(forty_two_test, "boost.webclient.forty_two");

}   // namespace webclient
}   // namespace boost

ext: cpp


text:
/**************************************************************
 *
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 *
 *************************************************************/

#ifndef _SAX_FS_HELPER_HXX_
#define _SAX_FS_HELPER_HXX_

#include <com/sun/star/uno/XReference.hpp>
#include <com/sun/star/io/XOutputStream.hpp>
#include <com/sun/star/xml/sax/XFastTokenHandler.hpp>
#include <stdarg.h>
#include <boost/shared_ptr.hpp>
#include <sax/fastattribs.hxx>
#include "sax/dllapi.h"

#define FSNS(namespc, element) ((namespc << 16) | element)
const sal_Int32 FSEND = -1; // same as XML_TOKEN_INVALID

namespace sax_fastparser {

enum MergeMarksEnum { MERGE_MARKS_APPEND = 0, MERGE_MARKS_PREPEND = 1, MERGE_MARKS_POSTPONE = 2 };

typedef ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XFastAttributeList > XFastAttributeListRef;

class FastSaxSerializer;

class SAX_DLLPUBLIC FastSerializerHelper
{
public:

    FastSerializerHelper( const ::com::sun::star::uno::Reference< ::com::sun::star::io::XOutputStream >& xOutputStream );

	~FastSerializerHelper();

	void startElement(const char* elementName, ...);
	void singleElement(const char* elementName, ...);
	void endElement(const char* elementName);

	void startElementV(sal_Int32 elementTokenId, va_list args);
	void singleElementV(sal_Int32 elementTokenId, va_list args);

	inline void startElement(sal_Int32 elementTokenId, ...)
		{ va_list args; va_start( args, elementTokenId ); startElementV( elementTokenId, args ); va_end( args ); }
	inline void singleElement(sal_Int32 elementTokenId, ...)
		{ va_list args; va_start( args, elementTokenId ); singleElementV( elementTokenId, args ); va_end( args ); }
	inline void startElementNS(sal_Int32 namespaceTokenId, sal_Int32 elementTokenId, ...)
		{ va_list args; va_start( args, elementTokenId ); startElementV( FSNS( namespaceTokenId, elementTokenId), args ); va_end( args ); }
	inline void singleElementNS(sal_Int32 namespaceTokenId, sal_Int32 elementTokenId, ...)
		{ va_list args; va_start( args, elementTokenId ); singleElementV( FSNS( namespaceTokenId, elementTokenId), args ); va_end( args ); }
	void endElement(sal_Int32 elementTokenId);
	inline void endElementNS(sal_Int32 namespaceTokenId, sal_Int32 elementTokenId)
		{ endElement( FSNS( namespaceTokenId, elementTokenId ) ); }

	void singleElement(const char* elementName, XFastAttributeListRef xAttrList);
	inline void singleElement(sal_Int32 elementTokenId, XFastAttributeListRef xAttrList)
		{ singleElementV(elementTokenId, xAttrList); }
	void singleElementV(sal_Int32 elementTokenId, XFastAttributeListRef xAttrList);
	inline void singleElementNS(sal_Int32 namespaceTokenId, sal_Int32 elementTokenId, XFastAttributeListRef xAttrList)
		{ singleElementV(FSNS( namespaceTokenId, elementTokenId), xAttrList); }

    void startElementV(sal_Int32 elementTokenId, XFastAttributeListRef xAttrList);
    inline void startElementNS(sal_Int32 namespaceTokenId, sal_Int32 elementTokenId, XFastAttributeListRef xAttrList)
        { startElementV( FSNS( namespaceTokenId, elementTokenId ), xAttrList ); }

	FastSerializerHelper* write(const char* value);
	FastSerializerHelper* write(const rtl::OUString& value);
	FastSerializerHelper* write(sal_Int32 value);
	FastSerializerHelper* write(sal_Int64 value);
	FastSerializerHelper* write(float value);
	FastSerializerHelper* write(double value);

	FastSerializerHelper* writeEscaped(const char* value);
	FastSerializerHelper* writeEscaped(const rtl::OUString& value);

	FastSerializerHelper* writeId(sal_Int32 tokenId);

	::com::sun::star::uno::Reference< ::com::sun::star::io::XOutputStream > getOutputStream();

	FastAttributeList *createAttrList();

    void mark();
    void mergeTopMarks( MergeMarksEnum eMergeType = MERGE_MARKS_APPEND );

private:

    FastSaxSerializer* mpSerializer;
	com::sun::star::uno::Reference<com::sun::star::xml::sax::XFastTokenHandler> mxTokenHandler;

};

typedef boost::shared_ptr< FastSerializerHelper > FSHelperPtr;

}

#endif // _SAX_FS_HELPER_HXX_

ext: hxx

max_stars_repo_name: Grosskopf/openoffice

max_issues_repo_name: Grosskopf/openoffice

max_forks_repo_name: Grosskopf/openoffice


text:
/*
 * Sarus
 *
 * Copyright (c) 2018-2022, ETH Zurich. All rights reserved.
 *
 * Please, refer to the LICENSE file in the root directory.
 * SPDX-License-Identifier: BSD-3-Clause
 *
 */

#include "Lockfile.hpp"

#include <chrono>
#include <thread>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

#include <boost/format.hpp>

#include "common/Error.hpp"
#include "common/Logger.hpp"

namespace sarus {
namespace common {

Lockfile::Lockfile()
    : logger(&common::Logger::getInstance())
{}

Lockfile::Lockfile(const boost::filesystem::path& file, unsigned int timeoutMs)
    : logger(&common::Logger::getInstance())
    , lockfile{convertToLockfile(file)}
{
    auto message = boost::format("acquiring lock on file %s") % file;
    logger->log(message.str(), loggerSubsystemName, common::LogLevel::DEBUG);

    unsigned int elapsedTimeMs = 0;
    while(!createLockfileAtomically()) {
        if(timeoutMs != noTimeout && elapsedTimeMs >= timeoutMs) {
            message = boost::format("failed to acquire lock on file %s (expired timeout of %d milliseconds)") % *lockfile % timeoutMs;
            SARUS_THROW_ERROR(message.str());
        }
        const int backoffTimeMs = 100;
        std::this_thread::sleep_for(std::chrono::milliseconds(backoffTimeMs));
        elapsedTimeMs += backoffTimeMs;
    }

    logger->log("successfully acquired lock", loggerSubsystemName, common::LogLevel::DEBUG);
}

Lockfile::Lockfile(Lockfile&& rhs)
    : logger{rhs.logger}
    , lockfile{rhs.lockfile}
{
    logger->log("move constructing lock", loggerSubsystemName, common::LogLevel::DEBUG);
    rhs.lockfile.reset();
    logger->log("successfully move constructed lock", loggerSubsystemName, common::LogLevel::DEBUG);
}

Lockfile& Lockfile::operator=(Lockfile&& rhs) {
    logger->log("move assigning lock", loggerSubsystemName, common::LogLevel::DEBUG);
    if(lockfile) {
        boost::filesystem::remove(*lockfile);
    }
    lockfile = rhs.lockfile;
    rhs.lockfile.reset();
    logger->log("successfully move assigned lock", loggerSubsystemName, common::LogLevel::DEBUG);
    return *this;
}

Lockfile::~Lockfile() {
    logger->log("destroying lockfile", loggerSubsystemName, common::LogLevel::DEBUG);
    if(lockfile) {
        auto message = boost::format("removing lockfile %s") % *lockfile;
        logger->log(message.str(), loggerSubsystemName, common::LogLevel::DEBUG);
        boost::filesystem::remove(*lockfile);
    }
    logger->log("successfully destroyed lockfile", loggerSubsystemName, common::LogLevel::DEBUG);
}

boost::filesystem::path Lockfile::convertToLockfile(const boost::filesystem::path& file) const {
    auto lockfileLeaf = file.leaf().string() + ".lock";
    auto lockfile = file;
    lockfile.remove_leaf();
    lockfile /= lockfileLeaf;

    auto message = boost::format("converted filename %s to lockfile %s") % file % lockfile;
    logger->log(message.str(), loggerSubsystemName, common::LogLevel::DEBUG);

    return lockfile;
}

bool Lockfile::createLockfileAtomically() const {
    auto message = boost::format("creating lockfile %s") % *lockfile;
    logger->log(message.str(), loggerSubsystemName, common::LogLevel::DEBUG);

    auto fd = open(lockfile->string().c_str(), O_CREAT | O_EXCL, O_RDONLY);
    if(fd == -1) {
        message = boost::format("failed to create lockfile %s") % *lockfile;
        logger->log(message.str(), loggerSubsystemName, common::LogLevel::DEBUG);
        return false;
    }

    logger->log("successfully created lockfile", loggerSubsystemName, common::LogLevel::DEBUG);

    if(close(fd) != 0) {
        message = boost::format("failed to close file descriptor of lockfile %s") % *lockfile;
        SARUS_THROW_ERROR(message.str());
    }
    return true;
}

} // namespace
} // namespace

max_stars_repo_name: rayrayson/sarus

max_issues_repo_name: rayrayson/sarus

max_forks_repo_name: rayrayson/sarus


text:
#ifndef UUID_9AE0723F_DD0B_434B_8880_D7981FAF1F20
#define UUID_9AE0723F_DD0B_434B_8880_D7981FAF1F20
#pragma once

#include <iosfwd>
#include <boost/filesystem/path.hpp>
#include "except.hpp"
#include "nonowning_string.hpp"

namespace Neptools
{

using Byte = unsigned char;

// if you want to change it to 64-bit: change FileMemSize to size_t,
// #define _FILE_OFFSET_BITS 64
// to the beginning of source.cpp, and fix braindead winapi
using FilePosition = uint32_t;
using FileMemSize = uint32_t; // min(FilePos, size_t)

template <typename T, typename U>
T asserted_cast(U* ptr)
{
    NEPTOOLS_ASSERT_MSG(
        dynamic_cast<T>(ptr) == static_cast<T>(ptr), "U is not T");
    return static_cast<T>(ptr);
}

template <typename T, typename U>
T asserted_cast(U& ref)
{
#ifndef NDEBUG // gcc shut up about unused typedef
    using raw_t = std::remove_reference_t<T>;
    NEPTOOLS_ASSERT_MSG(
        dynamic_cast<raw_t*>(&ref) == static_cast<raw_t*>(&ref), "U is not T");
#endif
    return static_cast<T>(ref);
}

template <typename T>
constexpr size_t EmptySizeof = std::is_empty<T>::value ? 0 : sizeof(T);

std::ofstream OpenOut(const boost::filesystem::path& pth);
std::ifstream OpenIn(const boost::filesystem::path& pth);

void DumpBytes(std::ostream& os, StringView data);

#define NEPTOOLS_STATIC_ASSERT(...) static_assert(__VA_ARGS__, #__VA_ARGS__)

}
#endif

max_stars_repo_name: clienthax/neptools

max_issues_repo_name: clienthax/neptools

max_forks_repo_name: clienthax/neptools


text:
#pragma once

#include <roerei/uri.hpp>

#include <roerei/generic/sparse_matrix.hpp>
#include <roerei/generic/create_map.hpp>
#include <roerei/generic/encapsulated_vector.hpp>
#include <roerei/generic/id_t.hpp>

#include <boost/fusion/include/adapt_struct.hpp>

#include <vector>
#include <set>

namespace roerei
{

struct dataset_t
{
	typedef uint16_t value_t;
	typedef sparse_matrix_t<object_id_t, feature_id_t, value_t> feature_matrix_t;
	typedef sparse_matrix_t<object_id_t, dependency_id_t, value_t> dependency_matrix_t;

	encapsulated_vector<object_id_t, uri_t> objects;
	encapsulated_vector<feature_id_t, uri_t> features;
	encapsulated_vector<dependency_id_t, uri_t> dependencies;
	feature_matrix_t feature_matrix;
	dependency_matrix_t dependency_matrix;

	std::set<object_id_t> prior_objects;

public:
	dataset_t(dataset_t&&) = default;
	dataset_t(dataset_t const&) = delete;
	dataset_t(
			std::remove_const<decltype(objects)>::type&& _objects,
			std::remove_const<decltype(features)>::type&& _features,
			std::remove_const<decltype(dependencies)>::type&& _dependencies,
			feature_matrix_t&& _feature_matrix,
			dependency_matrix_t&& _dependency_matrix,
			std::remove_const<decltype(prior_objects)>::type&& _prior_objects
	);

	template<typename CONTAINER>
	dataset_t(CONTAINER&& _objects, CONTAINER&& _features, CONTAINER&& _dependencies);

	std::map<dependency_id_t, object_id_t> create_dependency_map() const;
	std::map<object_id_t, dependency_id_t> create_dependency_revmap() const;
};

namespace detail
{
	template<typename ID, typename B>
	static inline encapsulated_vector<ID, uri_t> construct_move_elements(B&& ys)
	{
		encapsulated_vector<ID, uri_t> xs;
		xs.reserve(ys.size());
		for(auto&& y : ys)
			xs.emplace_back(std::move(y));

		return xs;
	}
}

inline std::map<dependency_id_t, object_id_t> dataset_t::create_dependency_map() const
{
	std::map<uri_t, object_id_t> object_map;
	objects.iterate([&](object_id_t id, uri_t const& u) {
		object_map.emplace(std::make_pair(u, id));
	});

	std::map<dependency_id_t, object_id_t> dependency_map;
	dependencies.iterate([&](dependency_id_t id, uri_t const& u) {
		auto it = object_map.find(u);
		if(it == object_map.end())
			return;

		dependency_map.emplace(std::make_pair(id, it->second));
	});
	return dependency_map;
}

inline std::map<object_id_t, dependency_id_t> dataset_t::create_dependency_revmap() const
{
	std::map<uri_t, dependency_id_t> dependency_urimap;
	dependencies.iterate([&](dependency_id_t id, uri_t const& u) {
		dependency_urimap.emplace(std::make_pair(u, id));
	});

	std::map<object_id_t, dependency_id_t> dependency_revmap;
	objects.iterate([&](object_id_t id, uri_t const& u) {
		auto it = dependency_urimap.find(u);
		if(it == dependency_urimap.end())
			return;

		dependency_revmap.emplace(std::make_pair(id, it->second));
	});
	return dependency_revmap;
}

template<typename CONTAINER>
dataset_t::dataset_t(CONTAINER&& _objects, CONTAINER&& _features, CONTAINER&& _dependencies)
	: objects(detail::construct_move_elements<object_id_t>(_objects))
	, features(detail::construct_move_elements<feature_id_t>(_features))
	, dependencies(detail::construct_move_elements<dependency_id_t>(_dependencies))
	, feature_matrix(objects.size(), features.size())
	, dependency_matrix(objects.size(), dependencies.size())
	, prior_objects()
{}

inline dataset_t::dataset_t(
		std::remove_const<decltype(objects)>::type&& _objects,
		std::remove_const<decltype(features)>::type&& _features,
		std::remove_const<decltype(dependencies)>::type&& _dependencies,
		feature_matrix_t&& _feature_matrix,
		dependency_matrix_t&& _dependency_matrix,
		std::remove_const<decltype(prior_objects)>::type&& _prior_objects
)
	: objects(std::move(_objects))
	, features(std::move(_features))
	, dependencies(std::move(_dependencies))
	, feature_matrix(std::move(_feature_matrix))
	, dependency_matrix(std::move(_dependency_matrix))
	, prior_objects(std::move(_prior_objects))
{}

}

BOOST_FUSION_ADAPT_STRUCT(
		roerei::dataset_t,
		(decltype(roerei::dataset_t::objects), objects)
		(decltype(roerei::dataset_t::features), features)
		(decltype(roerei::dataset_t::dependencies), dependencies)
		(roerei::dataset_t::feature_matrix_t, feature_matrix)
		(roerei::dataset_t::dependency_matrix_t, dependency_matrix)
		(decltype(roerei::dataset_t::prior_objects), prior_objects)
)

max_stars_repo_name: Wassasin/roerei

max_issues_repo_name: Wassasin/roerei

max_forks_repo_name: Wassasin/roerei


text:
#include <vector>
#include <list>
#include <map>
#include <set>

#include <queue>
#include <deque>
#include <stack>
#include <bitset>
#include <algorithm>
#include <functional>
#include <numeric>
#include <utility>
#include <sstream>
#include <iostream>
#include <fstream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <ctime>
#include <cstring>
#include <assert.h>
#include <boost/lexical_cast.hpp>

#define INF 1023123123
#define EPS 1e-11
#define LSOne(S) (S & (-S))

#define M_PI           3.14159265358979323846  /* pi */

#define FORN(X,Y) for (int (X) = 0;(X) < (Y);++(X))
#define FORB(X,Y) for (int (X) = (Y);(X) >= 0;--(X))
#define REP(X,Y,Z) for (int (X) = (Y);(X) < (Z);++(X))
#define REPB(X,Y,Z) for (int (X) = (Y);(X) >= (Z);--(X))

#define SZ(Z) ((int)(Z).size())
#define ALL(W) (W).begin(), (W).end()
#define PB push_back

#define MP make_pair
#define A first
#define B second

#define FORIT(X,Y) for(typeof((Y).begin()) X = (Y).begin();X!=(Y).end();X++)

using namespace std;

typedef long long ll;
typedef double db;
typedef vector<int> vi;
typedef pair<int, int> ii;
typedef vector<ii> vii;

void print_case(int i)
{
   cout << "Case #" << i + 1 << ": ";
}

bool myfunction(pair<ll, pair<ll, int>> i, pair<ll, pair<ll, int>> j) { return (i>j); }

int main()
{
   cout.precision(12);
   int ntc;
   cin >> ntc;

   FORN(kk, ntc)
   {
      print_case(kk);
      int n, k;
      cin >> n >> k;
      vector<pair<ll, pair<ll, int>>> hs(n);
      vector<pair<ll, pair<ll, int>>> rs(n);
      vector<pair<ll, ll>> all(n);
      vi nn;
      FORN(i, n)
      {
         hs[i].second.second = i;
         rs[i].second.second = i;
         cin >> rs[i].first;
         cin >> hs[i].first;
         hs[i].second.first = rs[i].first;
         rs[i].second.first = hs[i].first;
         all[i].first = rs[i].first;
         all[i].second = hs[i].first;
         hs[i].first *= rs[i].first;
      }
      sort(hs.begin(), hs.end(), myfunction);
      sort(rs.begin(), rs.end(), myfunction);

      double maxArea = -1;
      FORN(i, n)
      {
         auto top = rs[i];
         int toChoose = k - 1;
         int hIndex = 0;
         double area = M_PI * top.first * top.first + 2 * M_PI * all[top.second.second].second * top.first;
         while (hIndex < n && toChoose > 0)
         {
            if (hs[hIndex].second.second != top.second.second && all[hs[hIndex].second.second].first <= top.first)
            {
               area += 2 * M_PI * hs[hIndex].first;
               toChoose--;
            }
            hIndex++;
         }
         if (toChoose == 0 && area > maxArea)
         {
            maxArea = area;
         }
      }

      cout << maxArea << endl;
   }
}

max_stars_repo_name: fvannee/competitive-coding

max_issues_repo_name: fvannee/competitive-coding

max_forks_repo_name: fvannee/competitive-coding


text:
/*
 * Copyright (c) 2018-2019, Eberty Alves, Pedro Raimundo
 */

// C++ standard library
#include <bits/stdc++.h>

// Kinect
#include <libfreenect/libfreenect_sync.h>

// OpenCV
#include <opencv2/core.hpp>
#include <opencv2/highgui.hpp>
#include <opencv2/imgcodecs.hpp>
#include <opencv2/imgproc.hpp>

// Boost library
#include <boost/program_options.hpp>

// Escape closes the application
#define CLOSE 27

// Image capture keys
#define DEPTH 'd'
#define COLOR 'c'
#define BURST 'b'

// Mesh capture key
#define DEPTH_MESH 'm'

// Perform all captures
#define ALL 'a'

// SR Size
static unsigned int sr_size;

// ENUM viewers
enum { TOP = 1, FRONT = 0, BOTTOM = -1 };
static int type_of_view = FRONT;

// Counters
static unsigned int count_depth = 0;
static unsigned int count_burst = 0;
static unsigned int count_color = 0;
static unsigned int count_depth_mesh = 0;

// Captures settings
static std::string capture_name;
static unsigned int capture_step;

// Depth thresholds in mm
int depth_min;
int depth_max;
int left_plane;
int right_plane;
int top_plane;
int bottom_plane;

// OpenCV variables
static cv::Size kinect_size;

// ---------------------------------------------------------
// Name: lerp
// ---------------------------------------------------------
// Description: Make a linear interpolation between two
//              variables a and b given fraction f
// ---------------------------------------------------------

inline double lerp(double a, double b, double f) {
  return (a * (1.0 - f)) + (b * f);
}

// ---------------------------------------------------------
// Name: view_type_str
// ---------------------------------------------------------
// Description: Convert the view type into a string
// ---------------------------------------------------------

std::string view_type_str(int value) {
  if (type_of_view == TOP) {
    return "top";
  }
  if (type_of_view == BOTTOM) {
    return "bottom";
  }
  return std::to_string(value % 360);
}

// ---------------------------------------------------------
// Name: show_depth
// ---------------------------------------------------------
// Description: Transform a depth frame information into color
//              and show as a video
// ---------------------------------------------------------

void show_depth(uint16_t *depth) {
  cv::Mat depth_mat = cv::Mat(kinect_size, CV_16UC1, depth);
  cv::Mat depth_mat_tmp = cv::Mat(kinect_size, CV_8UC3);
  int i, j;
  for (i = 0; i < kinect_size.height; i++) {
    for (j = 0; j < kinect_size.width; j++) {
      uint16_t depth_in_mm = depth_mat.at<uint16_t>(i, j);
      if (depth_in_mm != 0 && depth_in_mm >= depth_min && depth_in_mm <= depth_max && i >= top_plane &&
          i <= bottom_plane && j >= left_plane && j <= right_plane) {
        uint16_t color = (uint16_t)lerp(255.0, 32.0, (double)depth_in_mm / FREENECT_DEPTH_MM_MAX_VALUE);
        cv::Vec3b &pixel_color = depth_mat_tmp.at<cv::Vec3b>(i, j);
        pixel_color[0] = color;
        pixel_color[1] = color;
        pixel_color[2] = color;
      } else {
        cv::Vec3b &pixel_color = depth_mat_tmp.at<cv::Vec3b>(i, j);
        pixel_color[0] = 0;
        pixel_color[1] = 0;
        pixel_color[2] = 0;
      }
    }
  }
  cv::imshow("DEPTH", depth_mat_tmp);
}

// ---------------------------------------------------------
// Name: show_rgb
// ---------------------------------------------------------
// Description: show rgb frame as a video
// ---------------------------------------------------------

void show_rgb(uchar *rgb) {
  cv::Mat img_bgr_mat;
  cv::Mat img_rgb_mat = cv::Mat(kinect_size, CV_8UC3, rgb);
  cvtColor(img_rgb_mat, img_bgr_mat, cv::COLOR_RGB2BGR);
  imshow("RGB", img_bgr_mat);
}

// ---------------------------------------------------------
// Name: clean_image
// ---------------------------------------------------------
// Description: manually treshold a CV_16UC1 image, since
// the chances of opencv working for this are kind hit-or-miss
// between versions and operating systems
// ---------------------------------------------------------

cv::Mat clean_image(cv::Mat input_image, int near, int far, int left, int right, int top, int bottom) {
  cv::Mat output_image;
  input_image.copyTo(output_image);
  for (int i = 0; i < output_image.size().height; i++) {
    for (int j = 0; j < output_image.size().width; j++) {
      uint16_t &pixel = output_image.at<uint16_t>(i, j);
      if (pixel > far || pixel < near || i < top || i > bottom || j < left || j > right) {
        pixel = 0;
      }
    }
  }
  return output_image;
}

// ---------------------------------------------------------
// Name: save_depth
// ---------------------------------------------------------
// Description: create a file and save one depth frame
// ---------------------------------------------------------

int save_depth(uint16_t *depth) {
  cv::Mat depth_mat = cv::Mat(kinect_size, CV_16UC1, depth);
  std::ostringstream oss;
  oss << capture_name << "_depth_" << view_type_str(count_depth * capture_step) << ".png";
  depth_mat = clean_image(depth_mat, depth_min, depth_max, left_plane, right_plane, top_plane, bottom_plane);
  imwrite(oss.str(), depth_mat);
  printf("%s saved!\n", oss.str().c_str());
  fflush(stdout);
  return 1;
}

// ---------------------------------------------------------
// Name: save_depth_burst
// ---------------------------------------------------------
// Description: create a file and save one depth frame from
//              a burst sequence
// ---------------------------------------------------------

int save_depth_burst(uint16_t *depth, unsigned int frame_count) {
  cv::Mat depth_mat = cv::Mat(kinect_size, CV_16UC1, depth);
  std::ostringstream oss;
  oss << capture_name << "_burst_" << view_type_str(count_burst * capture_step) << "_" << frame_count << ".png";
  depth_mat = clean_image(depth_mat, depth_min, depth_max, left_plane, right_plane, top_plane, bottom_plane);
  imwrite(oss.str(), depth_mat);
  printf("%s saved!\n", oss.str().c_str());
  fflush(stdout);
  return 1;
}

// ---------------------------------------------------------
// Name: save_rgb
// ---------------------------------------------------------
// Description: create a file and save one rgb frame
// ---------------------------------------------------------

int save_rgb(uchar *rgb) {
  cv::Mat img_rgb_mat = cv::Mat(kinect_size, CV_8UC3, rgb);
  cv::Mat img_bgr_mat;
  std::ostringstream oss;
  oss << capture_name << "_color_" << view_type_str(count_color * capture_step) << ".png";
  cvtColor(img_rgb_mat, img_bgr_mat, cv::COLOR_RGB2BGR);
  imwrite(oss.str(), img_bgr_mat);
  printf("%s saved!\n", oss.str().c_str());
  fflush(stdout);
  return 1;
}

// ---------------------------------------------------------
// Name: save_ply
// ---------------------------------------------------------
// Description: create a file and save a .ply point cloud
//              with both depth and color information.
// ---------------------------------------------------------

int save_ply(cv::Mat depth_mat, cv::Mat color_mat, int count) {
  std::ostringstream oss;
  oss << capture_name << "_mesh_" << view_type_str(count * capture_step) << ".ply";

  FILE *fp;

  if ((fp = fopen(oss.str().c_str(), "w")) == NULL) {
    printf("Error: while creating file %s\n", oss.str().c_str());
    return 0;
  }

  // Bilateral filtering of the depth image disabled for now
  // because super resolution ends up smoothing out the noise

  // Normals via cross-product
  cv::Mat normal_mat = cv::Mat(depth_mat.size(), CV_32FC3);
  for (int i = 0; i < depth_mat.size().height; i++) {
    for (int j = 0; j < depth_mat.size().width; j++) {
      uint16_t right = 0, left = 0, down = 0, up = 0;

      if (i > 0 && j > 0 && i < depth_mat.size().height - 1 && j < depth_mat.size().width - 1) {
        right = depth_mat.at<uint16_t>(i + 1, j);
        left = depth_mat.at<uint16_t>(i - 1, j);
        down = depth_mat.at<uint16_t>(i, j + 1);
        up = depth_mat.at<uint16_t>(i, j - 1);
      }

      // Threshold (as per Hinterstoisser et al (2011))
      if (abs(depth_mat.at<uint16_t>(i, j) - right) > 20) {
        right = 0;
      }
      if (abs(depth_mat.at<uint16_t>(i, j) - left) > 20) {
        left = 0;
      }
      if (abs(depth_mat.at<uint16_t>(i, j) - down) > 20) {
        down = 0;
      }
      if (abs(depth_mat.at<uint16_t>(i, j) - up) > 20) {
        up = 0;
      }

      double dzdx = (right - left) / 2.0;
      double dzdy = (down - up) / 2.0;

      cv::Vec3d d(-dzdx, -dzdy, 1.0);
      cv::Vec3d n = normalize(d);

      normal_mat.at<cv::Vec3f>(i, j) = n;
    }
  }

  uint32_t num_vertices = 0;
  // Iterate to count the number of vertices, needed for .ply header
  for (int i = 0; i < depth_mat.size().height; i++) {
    for (int j = 0; j < depth_mat.size().width; j++) {
      uint16_t z_in_mm = depth_mat.at<uint16_t>(i, j);

      if (z_in_mm != 0 && z_in_mm >= depth_min && z_in_mm <= depth_max && i >= top_plane && i <= bottom_plane &&
          j >= left_plane && j <= right_plane) {
        num_vertices++;
      }
    }
  }

  // then a second time to write the geometry into the .ply file
  fprintf(fp, "ply\n");
  fprintf(fp, "format ascii 1.0\n");
  fprintf(fp, "element vertex %d\n", num_vertices);
  fprintf(fp, "property float x\n");
  fprintf(fp, "property float y\n");
  fprintf(fp, "property float z\n");
  fprintf(fp, "property float nx\n");
  fprintf(fp, "property float ny\n");
  fprintf(fp, "property float nz\n");
  fprintf(fp, "property uchar red\n");
  fprintf(fp, "property uchar green\n");
  fprintf(fp, "property uchar blue\n");
  fprintf(fp, "end_header\n");
  for (int i = 0; i < depth_mat.size().height; i++) {
    for (int j = 0; j < depth_mat.size().width; j++) {
      uint16_t z_in_mm = depth_mat.at<uint16_t>(i, j);
      double fx = 572.882768, fy = 542.739980, cx = 314.649173, cy = 240.160459;
      if (z_in_mm != 0 && z_in_mm >= depth_min && z_in_mm <= depth_max && i >= top_plane && i <= bottom_plane &&
          j >= left_plane && j <= right_plane) {
        double vx = z_in_mm * (j - cx) * (1 / fx);
        double vy = -z_in_mm * (i - cy) * (1 / fy);
        cv::Vec3b color = color_mat.at<cv::Vec3b>(i, j);
        cv::Vec3f normal = normal_mat.at<cv::Vec3f>(i, j);
        fprintf(fp, "%.6lf %.6lf %.6lf %.6lf %.6lf %.6lf %d %d %d\n", (double)vx, (double)vy, (double)-z_in_mm,
                (double)normal[0], (double)normal[1], (double)normal[2], color[0], color[1], color[2]);
      }
    }
  }

  fclose(fp);
  fflush(fp);

  printf("%s saved!\n", oss.str().c_str());
  fflush(stdout);

  return 1;
}

int main(int argc, char **argv) {
  try {
    // Parse command-line options
    namespace po = boost::program_options;

    // Define command-line options
    po::options_description desc("Options");
    desc.add_options()
    ("help,h", "Print help message")
    ("capture_name,n", po::value<std::string>(&capture_name)->default_value("artefact"), "Name for saved files")
    ("capture_step,s", po::value<unsigned int>(&capture_step)->default_value(20), "Angles (degrees) for each capture")
    ("sr_size,z", po::value<unsigned int>(&sr_size)->default_value(16), "Number of sr images for each capture")
    ("depth_min,m", po::value<int>(&depth_min)->default_value(0), "Minimum value for depth (threshold)")
    ("depth_max,M", po::value<int>(&depth_max)->default_value(790), "Maximum value for depth (threshold)")
    ("left_plane,l", po::value<int>(&left_plane)->default_value(0), "Left plane threshold in mm")
    ("right_plane,r", po::value<int>(&right_plane)->default_value(640), "Right plane threshold in mm")
    ("top_plane,t", po::value<int>(&top_plane)->default_value(0), "Top plane threshold in mm")
    ("bottom_plane,b", po::value<int>(&bottom_plane)->default_value(480), "Bottom plane threshold in mm");

    // Use a parser to evaluate the command line
    po::variables_map vm;
    po::store(po::parse_command_line(argc, argv, desc), vm);

    // Store the command-line options evaluated by the parser
    if (vm.count("help")) {
      std::cout
          << "Connect the Kinect on the laptop, launch this depth acquisition tool and configure the bounding box of "
          << "the reconstruction volume to minimize the amount of extraneous information captured. Acquire the depth "
          << "and color images corresponding to each lateral view. Manually position the Kinect to "
          << "acquire views from the top and bottom of the object, when necessary." << std::endl
          << std::endl;
      std::cout << desc << std::endl;
      std::cout << std::endl << "Values: " << std::endl;
      std::cout << "  Image capture keys:    " << std::endl;
      std::cout << "              Depth      " << DEPTH << std::endl;
      std::cout << "              Color      " << COLOR << std::endl;
      std::cout << "              Burst      " << BURST << std::endl;
      std::cout << "              Depth mesh " << DEPTH_MESH << std::endl;
      std::cout << "  Perform all captures:  " << ALL << std::endl;
      std::cout << "  View type:             "
                << "Top(8), Front(*), Bottom(2)" << std::endl;
      std::cout << "  Close the application: " << CLOSE << std::endl;
      return 0;
    }

    capture_name = vm["capture_name"].as<std::string>();

    capture_step = vm["capture_step"].as<unsigned int>();
    if (capture_step <= 0 || capture_step >= 360) {
      std::cout << "capture_step must be in (0, 360) range, the value will be setting to 1." << std::endl;
      capture_step = 1;
    }

    sr_size = vm["sr_size"].as<unsigned int>();
    depth_min = vm["depth_min"].as<int>();
    depth_max = vm["depth_max"].as<int>();
    left_plane = vm["left_plane"].as<int>();
    right_plane = vm["right_plane"].as<int>();
    top_plane = vm["top_plane"].as<int>();
    bottom_plane = vm["bottom_plane"].as<int>();

    std::cout << "Capture name: " << capture_name << " | Steps: " << capture_step << std::endl;

    // Set Windows
    cv::namedWindow("RGB", cv::WINDOW_AUTOSIZE);
    cv::namedWindow("DEPTH", cv::WINDOW_AUTOSIZE);

    // Set kinect_size settings
    kinect_size.width = 640;
    kinect_size.height = 480;

    // Trackbar
    cv::createTrackbar("Near Plane (mm)\t", "DEPTH", &depth_min, 4000, NULL);
    cv::createTrackbar("Far Plane (mm)\t", "DEPTH", &depth_max, 4000, NULL);
    cv::createTrackbar("Left Plane (px)\t", "DEPTH", &left_plane, kinect_size.width - 1, NULL);
    cv::createTrackbar("Right Plane (px)\t", "DEPTH", &right_plane, kinect_size.width - 1, NULL);
    cv::createTrackbar("Top Plane (px)\t", "DEPTH", &top_plane, kinect_size.height - 1, NULL);
    cv::createTrackbar("Bottom Plane (px)", "DEPTH", &bottom_plane, kinect_size.height - 1, NULL);

    int key = 0;
    if (freenect_sync_set_tilt_degs(0, 0)) {  // Returns nonzero on error
      throw std::runtime_error("No device found");
    }

    // Loop to get captures
    while ((key = cv::waitKey(1))) {
      // Opencv apparently cant decide whether 'no key' is -1 or 255.
      if (key == 255 || key == -1) {
        uint32_t timestamp;
        uint32_t timestamp_depth;
        unsigned char *data;
        uint16_t *depth_data;

        freenect_sync_get_video((void **)(&data), &timestamp, 0, FREENECT_VIDEO_RGB);
        show_rgb(data);
        freenect_sync_get_depth((void **)(&depth_data), &timestamp_depth, 0, FREENECT_DEPTH_REGISTERED);
        show_depth(depth_data);
      } else {
        if (key == CLOSE) {
          break;
        }

        if (key >= '0' && key <= '9') {
          if (key == '8') {
            type_of_view = TOP;
            std::cout << "View: TOP" << std::endl;
          } else if (key == '2') {
            type_of_view = BOTTOM;
            std::cout << "View: BOTTOM" << std::endl;
          } else {
            type_of_view = FRONT;
            std::cout << "View: FRONT " << (count_depth * capture_step) << std::endl;
          }
        }

        if (key == ALL && type_of_view == FRONT) {
          std::vector<unsigned int> v = {count_depth, count_burst, count_color, count_depth_mesh};
          unsigned int min_value = *std::min_element(v.begin(), v.end());
          count_depth = count_burst = count_color = count_depth_mesh = min_value;
        }

        if (key == DEPTH || key == ALL) {
          uint32_t timestamp_depth;
          uint16_t *depth_data;
          freenect_sync_get_depth((void **)(&depth_data), &timestamp_depth, 0, FREENECT_DEPTH_REGISTERED);
          save_depth(depth_data);
          if (type_of_view == FRONT) count_depth++;
        }

        if (key == BURST || key == ALL) {
          uint32_t timestamp_depth;
          uint16_t *depth_data;
          for (unsigned int i = 0; i < sr_size; i++) {
            freenect_sync_get_depth((void **)(&depth_data), &timestamp_depth, 0, FREENECT_DEPTH_REGISTERED);
            save_depth_burst(depth_data, i);
          }
          if (type_of_view == FRONT) count_burst++;
        }

        if (key == COLOR || key == ALL) {
          uint32_t timestamp;
          unsigned char *data;
          freenect_sync_get_video((void **)(&data), &timestamp, 0, FREENECT_VIDEO_RGB);
          save_rgb(data);
          if (type_of_view == FRONT) count_color++;
        }

        if (key == DEPTH_MESH || key == ALL) {
          uint32_t timestamp_depth;
          uint16_t *depth_data;
          freenect_sync_get_depth((void **)(&depth_data), &timestamp_depth, 0, FREENECT_DEPTH_REGISTERED);
          uint32_t timestamp_color;
          unsigned char *color_data;
          freenect_sync_get_video((void **)(&color_data), &timestamp_color, 0, FREENECT_VIDEO_RGB);
          save_ply(cv::Mat(kinect_size, CV_16UC1, depth_data), cv::Mat(kinect_size, CV_8UC3, color_data), count_depth_mesh);
          if (type_of_view == FRONT) count_depth_mesh++;
        }
      }
    }

    return 0;
  } catch (const std::exception &e) {
    std::cerr << e.what() << std::endl;
  } catch (...) {
    std::cerr << "An unknown error has occurred." << std::endl;
  }

  return -1;
}


text:
#include <iostream>
#include <cmath>
#include <algorithm>
#include <vector>
#include <boost/multiprecision/cpp_int.hpp>
using namespace boost::multiprecision;
using namespace std;
int main() {
    cpp_int s, p; cin >> s >> p;
    for (cpp_int i = 1; i <= sqrt(p); i++) {
        if (p % i == 0) {
            if (i + p / i == s) {
                cout << "Yes" << endl;
                return 0;
            }
        }
    }
    cout << "No" << endl;
    return 0;
}


text:
#include "numpy_utils.hpp"
#include <boost/foreach.hpp>
#include <boost/python.hpp>
#include <Eigen/Core>
#include <Eigen/Core>
#include <Eigen/Dense>
#include <Eigen/SVD>
#include <iostream>
#include <iostream>
#include <vector>

using namespace Eigen;
using namespace std;
namespace py = boost::python;

/////////////////

// http://en.wikipedia.org/wiki/Axis_angle#Log_map_from_SO.283.29_to_so.283.29
Vector3d LogMap(const Matrix3d& m) {
  double cosarg = (m.trace() - 1)/2;
  cosarg = fmin(cosarg, 1);
  cosarg = fmax(cosarg, -1);
  double theta = acos( cosarg );
  if (theta==0) return Vector3d::Zero();
  else return theta*(1/(2*sin(theta))) * Vector3d(m(2,1) - m(1,2), m(0,2)-m(2,0), m(1,0)-m(0,1));
}

double RotReg(const Matrix3d& b, const Vector3d& rot_coeffs, double scale_coeff) {
  // regularize rotation using polar decomposition
  JacobiSVD<Matrix3d> svd(b.transpose(), ComputeFullU | ComputeFullV);
  Vector3d s = svd.singularValues();
  if (b.determinant() <= 0) return INFINITY;
  return LogMap(svd.matrixU() * svd.matrixV().transpose()).cwiseAbs().dot(rot_coeffs) + s.array().log().square().sum()*scale_coeff;
}

Matrix3d RotRegGrad(const Matrix3d& b, const Vector3d& rot_coeffs, double scale_coeff) {
  Matrix3d out;
  double y0 = RotReg(b, rot_coeffs, scale_coeff);
  Matrix3d xpert = b;
  double epsilon = 1e-5;
  for (int i=0; i < 3; ++i) {
    for (int j=0; j < 3; ++j) {
      xpert(i,j) = b(i,j) + epsilon;
      out(i,j) = (RotReg(xpert, rot_coeffs, scale_coeff) - y0)/epsilon;
      xpert(i,j) = b(i,j);
    }
  }
  return out;
}

Vector3d gRotCoeffs;
double gScaleCoeff;

void PySetCoeffs(py::object rot_coeffs, py::object scale_coeff) {
  gRotCoeffs = Vector3d(py::extract<double>(rot_coeffs[0]), py::extract<double>(rot_coeffs[1]), py::extract<double>(rot_coeffs[2]));
  gScaleCoeff = py::extract<double>(scale_coeff);
}

double PyRotReg(const py::object& m ){
  const double* data = getPointer<double>(m);
  return RotReg( Map< const Matrix<double,3,3,RowMajor> >(data), gRotCoeffs, gScaleCoeff);
}

py::object PyRotRegGrad(const py::object& m) {
  static py::object np_mod = py::import("numpy");
  py::object out = np_mod.attr("empty")(py::make_tuple(3,3));
  const double* data = getPointer<double>(m);
  Matrix<double,3,3,RowMajor> g = RotRegGrad( Map< const Matrix<double,3,3,RowMajor> >(data), gRotCoeffs, gScaleCoeff);
  memcpy(getPointer<double>(out), g.data(), sizeof(double)*9);
  return out;
}

////////////////

void Interp(float x0, float x1, const VectorXf& y0, const VectorXf& y1, const VectorXf& newxs, MatrixXf& newys) {
  float dx = x1 - x0;
  for (int i=0; i < newxs.size(); ++i) {
    newys.row(i) = ((x1 - newxs[i])/dx) * y0 + ((newxs[i] - x0)/dx) * y1;
  }
}

vector<int> Resample(const MatrixXf& x, const VectorXf& _t, float max_err, float max_dx, float max_dt) {
  int N = x.rows(); // number of timesteps
  VectorXf t;
  if (_t.size() == 0){
    t.resize(N);
    for (int i=0; i < N; ++i) t[i] = i;
  }
  else t=_t;
  VectorXi cost(N); // shortest path cost
  VectorXi pred(N); // shortest path predecessor

  MatrixXf q(20, x.cols()); // scratch space for interpolation
  q.setConstant(-666);

  const int NOPRED = -666;
  const int BIGINT = 999999;

  pred.setConstant(NOPRED);
  cost.setConstant(BIGINT);
  cost(0) = 0;
  pred(0) = NOPRED;
  for (int iSrc = 0; iSrc < N; ++iSrc) {
    for (int iTarg = iSrc+1; iTarg < N; ++iTarg) {
      float dx = (x.row(iTarg) - x.row(iSrc)).maxCoeff();
      float dt = t(iTarg) - t(iSrc);
      int seglen = iTarg - iSrc + 1;
      if (q.rows() < seglen) q.resize(2*q.rows(), q.cols());
      Interp(t(iSrc), t(iTarg), x.row(iSrc), x.row(iTarg), t.middleRows(iSrc, seglen), q);
      float err = (q.block(0,0,seglen, x.cols()) - x.middleRows(iSrc, seglen)).cwiseAbs().maxCoeff();
      if ((dx <= max_dx) && (dt <= max_dt || iTarg == iSrc+1) && (err <= max_err)) {
        int newcost = cost(iSrc) + 1;
        if (newcost < cost(iTarg)) {
          cost(iTarg) = newcost;
          pred(iTarg) = iSrc;
        }
      }
      else break;
    }
  }

  int i=N-1;
  vector<int> revpath;
  while (i > 0) {
    revpath.push_back(i);
    i = pred(i);
  }
  revpath.push_back(0);
  std::reverse(revpath.begin(), revpath.end());
  return revpath;
}

py::object pyResample(py::object x, py::object t, float max_err, float max_dx, float max_dt) {
  x = np_mod.attr("array")(x, "float32");
  int xdim0 = py::extract<int>(x.attr("shape")[0]);
  int xdim1 = py::extract<int>(x.attr("shape")[1]);
  float* xdata = getPointer<float>(x);
  t = np_mod.attr("array")(t, "float32");
  int tdim0 = py::extract<int>(t.attr("__len__")());
  float* tdata = getPointer<float>(t);
  vector<int> inds = Resample(Map<MatrixXf>(xdata, xdim0, xdim1), Map<VectorXf>(tdata, tdim0), max_err, max_dx, max_dt);
  return toNdarray1<int>(inds.data(), inds.size());
}
//BOOST_PYTHON_FUNCTION_OVERLOADS(resample_overloads, pyResample, 3, 5);

///////////////////

BOOST_PYTHON_MODULE(fastrapp) {

  np_mod = py::import("numpy");

  py::def("resample", &pyResample, (py::arg("x"), py::arg("t"), py::arg("max_err"),   py::arg("max_dx")=INFINITY, py::arg("max_dt")=INFINITY));

  py::def("set_coeffs", &PySetCoeffs, (py::arg("rot_coeffs"), py::arg("scale_coeff")));
  py::def("rot_reg", &PyRotReg, (py::arg("B")));
  py::def("rot_reg_grad", &PyRotRegGrad, (py::arg("B")));

}


text:
//
// Copyright (c) 2016-2017 Kris Jusiak (kris at jusiak dot net)
//
// 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)
//
#include <boost/sml.hpp>
#include <string>
#include <type_traits>
#include <utility>

namespace sml = boost::sml;

struct e1 {};
struct e2 {};
struct e3 {};
struct e4 {};
struct e5 {};
struct e6 {};

const auto idle = sml::state<class idle>;

test minimal_with_dependency = [] {
  struct c {
    auto operator()() noexcept {
      using namespace sml;
      return make_transition_table(*idle + event<e1> / [](int i) { expect(42 == i); });
    }
  };

  sml::sm<c> sm{42};
  expect(sm.is(idle));
  sm.process_event(e1{});
  expect(sm.is(idle));
};

test dependencies = [] {
  struct c {
    auto operator()() noexcept {
      using namespace sml;

      auto guard = [](int i) {
        expect(42 == i);
        return true;
      };

      auto action = [](double d, e1) { expect(d == 87.0); };

      // clang-format off
      return make_transition_table(
         *idle + event<e1> [ guard ] / (action, [](const auto& e, int i) -> void {
            (void)e;
            expect(std::is_same<decltype(e), const e1&>::value);
            expect(42 == i);
          }) = X
      );
      // clang-format on
    }
  };

  {
    sml::sm<c> sm{42, 87.0};
    sm.process_event(e1{});
    expect(sm.is(sml::X));
  }

  {
    sml::sm<c> sm{87.0, 42};
    sm.process_event(e1{});
    expect(sm.is(sml::X));
  }
};

test dependencies_with_const = [] {
  struct dep {
    int i = 7;
  };

  struct c {
    auto operator()() noexcept {
      using namespace sml;

      auto guard = [](int i, dep& dependency) {
        expect(7 == dependency.i);
        expect(42 == i);
        return true;
      };

      auto const_guard = [](dep const& dependency, int const i) {
        expect(7 == dependency.i);
        expect(42 == i);
        return true;
      };

      auto action = [](int i, dep& dependency, e1) {
        expect(7 == dependency.i);
        expect(42 == i);
      };

      auto const_action = [](dep const& dependency, int const i, e1) {
        expect(7 == dependency.i);
        expect(42 == i);
      };

      // clang-format off
      return make_transition_table(
         *idle + event<e1> [ guard && const_guard ] / (action, const_action) = X
      );
      // clang-format on
    }
  };

  {
    dep dependency;
    sml::sm<c> sm{dependency, 42};
    sm.process_event(e1{});
    expect(sm.is(sml::X));
  }
};

max_stars_repo_name: krzysztof-jusiak/sml

max_issues_repo_name: krzysztof-jusiak/sml

max_forks_repo_name: krzysztof-jusiak/sml


text:
//
// This node stop the Autonomous Life and, then, wake up the robot.
// It's written to be included in pepper_bringup.launch.
// To operate with Autonomous Life and Rest, use enable_pepper instead.
//

// Naoqi
#include <qi/applicationsession.hpp>

// ROS
#include <ros/ros.h>

// PepperTools Class
#include <pepper_lib_developed/pepper_tools.hpp>

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

int main(int argc, char** argv) {
	ros::init(argc, argv, "start_pepper");
	ros::NodeHandle nh;

	ROS_INFO_STREAM("Going to initialize...");

	// Launch naoqi service
	qi::ApplicationSession app(argc, argv);
	app.startSession();

	// Create pepper tools object
	boost::shared_ptr <pepper_tools::PepperTools> obj = boost::shared_ptr<pepper_tools::PepperTools>(new pepper_tools::PepperTools(app.session()));
	// pepper_tools::PepperTools obj = pepper_tools::PepperTools(app.session());

	// Stop autonomous life and wake up
	obj->alStop();
	obj->wakeUp();
	obj->resetPosture();

	return 0;
}


text:
#ifndef _LIBRE_SHEET_IMPL_HPP
#define _LIBRE_SHEET_IMPL_HPP

//          Copyright Anurag Ghosh 2015.
// 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)

#include <string>

#include <boost/shared_ptr.hpp>
#include <boost/pointer_cast.hpp>
#include <boost/make_shared.hpp>
#include <boost/filesystem.hpp>

#include <boost/document/detail/document_exception.hpp>

#include <boost/document/detail/sheet_interface.hpp>
#include <boost/document/detail/cell_interface.hpp>
#include <boost/document/detail/chart_interface.hpp>

#include <boost/document/detail/libre_api/libre_sheet_func.hpp>
#include <boost/document/detail/libre_api/libre_cell_func.hpp>

#include <boost/document/detail/libre_api/libre_chart_func.hpp>

#include "cell_impl.hpp"
#include "chart_impl.hpp"

namespace boost { namespace detail {

class libre_sheet: public sheet_interface {

protected:
	::com::sun::star::uno::Reference < com::sun::star::lang::XComponent > xComponent_;
	::com::sun::star::uno::Reference< com::sun::star::sheet::XSpreadsheet > xSheet_;
	std::size_t index;
	std::string name;

public:
	libre_sheet(const ::com::sun::star::uno::Reference < com::sun::star::lang::XComponent >& xComponent,
		const ::com::sun::star::uno::Reference< com::sun::star::sheet::XSpreadsheet >& xSheet, std::size_t index) {
		this->xComponent_ = xComponent;
		this->xSheet_ = xSheet;
		this->index = index;
		this->name = boost::doc::libre_sheet_func::get_sheet_name(this->xSheet_);
	}

	libre_sheet(const ::com::sun::star::uno::Reference < com::sun::star::lang::XComponent >& xComponent,
		const ::com::sun::star::uno::Reference< com::sun::star::sheet::XSpreadsheet >& xSheet,const std::string& str) {
		this->xComponent_ = xComponent;
		this->xSheet_ = xSheet;
		this->index = (std::size_t)boost::doc::libre_sheet_func::get_sheet_index(this->xSheet_);
		this->name = str;
	}

	std::string sheet_name() {
		return this->name;
	}

	std::size_t sheet_index() {
		return this->index;
	}

	void rename_sheet(const std::string& str) {
		if(str.empty()) {
			boost::throw_exception(document_exception("Error: String Passed is Empty."));
   		}
	 	boost::doc::libre_sheet_func::rename_sheet(this->xSheet_,str);
		this->name = str;
	}

	//Refer to https://simple.wikipedia.org/wiki/OpenOffice_Calc
	std::size_t max_row() {
		return 1048576;
	}

	std::size_t max_column() {
		return 1024;
	}

	boost::cell get_cell(std::size_t row, std::size_t column) {
		if( row > max_row() || column > max_column() ) {
			boost::throw_exception(document_exception("Error: Invalid Indices Provided."));
		}
		::com::sun::star::uno::Reference< com::sun::star::table::XCell > xCell = boost::doc::libre_cell_func::get_cell(this->xSheet_,(int)row,(int)column);
		return boost::cell(boost::dynamic_pointer_cast<cell_interface>(boost::make_shared<boost::detail::libre_cell>(xCell,row,column)));
	}

	boost::cell get_cell_unchecked(std::size_t row, std::size_t column) {
		::com::sun::star::uno::Reference< com::sun::star::table::XCell > xCell = this->xSheet_->getCellByPosition((int)row, (int)column);
		return boost::cell(boost::dynamic_pointer_cast<cell_interface>(boost::make_shared<boost::detail::libre_cell>(xCell,row,column)));
	}

	boost::chart add_chart(const std::string& name, const std::string& cell_range, std::size_t left, std::size_t top, std::size_t width, std::size_t height) {
		::com::sun::star::uno::Reference < com::sun::star::chart::XChartDocument > xChart = boost::doc::libre_chart_func::add_chart(this->xSheet_, name, cell_range, (int)left, (int)top, (int)width, (int)height);
		return boost::chart(boost::dynamic_pointer_cast<chart_interface>(boost::make_shared<boost::detail::libre_chart>(xChart, this->xSheet_, name, cell_range, left, top, width, height)));
	}

	boost::chart get_chart(const std::string& name) {
		::com::sun::star::uno::Reference < com::sun::star::chart::XChartDocument > xChart = boost::doc::libre_chart_func::get_chart(this->xSheet_, name);
		return boost::chart(boost::dynamic_pointer_cast<chart_interface>(boost::make_shared<boost::detail::libre_chart>(xChart, this->xSheet_, name, "", 0, 0, 0, 0)));
	}

	void delete_chart(const std::string& name) {
		boost::doc::libre_chart_func::delete_chart(this->xSheet_, name);
	}

 	~libre_sheet() {
 	}

};

}} // namespace boost::detail

#endif

max_stars_repo_name: anuragxel/generic-document-library

max_issues_repo_name: anuragxel/generic-document-library

max_forks_repo_name: anuragxel/generic-document-library


text:
#pragma once

#include <boost/cstdint.hpp>

using boost::uint8_t;
using boost::uint16_t;
using boost::uint32_t;
using boost::uint64_t;

using boost::int8_t;
using boost::int16_t;;
using boost::int32_t;
using boost::int64_t;

max_stars_repo_name: hindsights/xul

max_issues_repo_name: hindsights/xul

max_forks_repo_name: hindsights/xul


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

#include "goughcompile.h"
#include "goughcompile_dump.h"
#include "goughcompile_internal.h"
#include "gough_internal.h"
#include "grey.h"
#include "util/container.h"
#include "util/flat_containers.h"
#include "util/graph.h"
#include "util/graph_range.h"
#include "util/order_check.h"

#include "ue2common.h"

#include <algorithm>
#include <boost/graph/depth_first_search.hpp>
#include <boost/range/adaptor/map.hpp>

using namespace std;
using boost::adaptors::map_values;

namespace ue2 {

template<typename VarP, typename VarQ>
void emplace_back_all_raw(vector<VarP> *out, const vector<VarQ> &in) {
    for (const auto &var : in) {
        out->emplace_back(var.get());
    }
}

static
void all_vars(const GoughGraph &g, vector<GoughSSAVar *> *out) {
    for (auto v : vertices_range(g)) {
        emplace_back_all_raw(out, g[v].vars);
    }
    for (const auto &e : edges_range(g)) {
        emplace_back_all_raw(out, g[e].vars);
    }
}

namespace {
struct GoughGraphAux {
    map<const GoughSSAVar *, GoughVertex> containing_v;
    map<const GoughSSAVar *, GoughEdge> containing_e;
    map<const GoughSSAVar *, set<GoughVertex> > reporters;
};
}

static never_inline
void fill_aux(const GoughGraph &g, GoughGraphAux *aux) {
    for (auto v : vertices_range(g)) {
        for (const auto &var : g[v].vars) {
            aux->containing_v[var.get()] = v;
            DEBUG_PRINTF("%u is on vertex %u\n", var->slot, g[v].state_id);
        }

        for (GoughSSAVar *var : g[v].reports | map_values) {
            aux->reporters[var].insert(v);
        }

        for (GoughSSAVar *var : g[v].reports_eod | map_values) {
            aux->reporters[var].insert(v);
        }
    }
    for (const auto &e : edges_range(g)) {
        for (const auto &var : g[e].vars) {
            aux->containing_e[var.get()] = e;
            DEBUG_PRINTF("%u is on edge %u->%u\n", var->slot,
                         g[source(e, g)].state_id, g[target(e, g)].state_id);
        }
    }
}

static
bool is_block_local(const GoughGraph &cfg, GoughSSAVar *var,
                    const GoughGraphAux &aux) {
    /* if var used as a report, it cannot be considered block local */
    if (contains(aux.reporters, var)) {
        return false;
    }

    /* (useful) vertex/join vars never local - they are terminal in blocks
     * and so should be read by another block. */
    if (!contains(aux.containing_e, var)) {
        return false;
    }

    /* for other cases, require that all uses of var are later in the same edge
     * or on the target AND if on target it is sole on flow coming from the
     * edge in question. */
    const GoughEdge &e = aux.containing_e.at(var);
    GoughVertex t = target(e, cfg);

    size_t seen_outputs = 0;
    const flat_set<GoughSSAVarWithInputs *> &out = var->get_outputs();
    bool seen_var = false;
    for (const auto &e_var : cfg[e].vars) {
        if (seen_var) {
            GoughSSAVarWithInputs *w
                = dynamic_cast<GoughSSAVarWithInputs *>(e_var.get());
            if (contains(out, w)) {
                seen_outputs++;
            }
        } else {
            seen_var = var == e_var.get();
        }
    }
    assert(seen_var);

    for (const auto &t_var : cfg[t].vars) {
        if (contains(out, t_var.get())) {
            seen_outputs++;
            const flat_set<GoughEdge> &flow = t_var->get_edges_for_input(var);
            if (flow.size() != 1 || *flow.begin() != e) {
                /* this var is used by the target join var BUT on a different
                 * flow, so this is not a block local variable */
                return false;
            }
        }
    }

    assert(seen_outputs <= out.size());
    return seen_outputs == out.size();
}

static
void handle_pending_edge(const GoughGraph &g, const GoughEdge &e,
                         GoughSSAVar *start, set<GoughVertex> &pending_vertex,
                         set<const GoughSSAVar *> &rv) {
    const vector<shared_ptr<GoughSSAVar> > &vars = g[e].vars;
    bool marking = !start;
    DEBUG_PRINTF("  ---checking edge %u->%u %s %zu\n", g[source(e, g)].state_id,
                 g[target(e, g)].state_id, marking ? "full" : "partial",
                 vars.size());
    for (auto it = vars.rbegin(); it != vars.rend(); ++it) {
        GoughSSAVar *var = it->get();
        if (contains(rv, var)) {
            DEBUG_PRINTF("somebody has already processed this vertex [%u]\n",
                         var->slot);
            return;
        }
        if (var == start) {
            assert(!marking);
            marking = true;
            continue;
        }
        if (marking) {
            rv.insert(var);
        }
    }
    assert(marking);
    GoughVertex s = source(e, g);
    for (const auto &var : g[s].vars) {
        DEBUG_PRINTF("interferes %u\n", var->slot);
        rv.insert(var.get());
    }
    pending_vertex.insert(s);
}

static
void handle_pending_vars(GoughSSAVar *def, const GoughGraph &g,
                         const GoughGraphAux &aux,
                         const flat_set<GoughSSAVarWithInputs *> &pending_var,
                         set<GoughVertex> &pending_vertex,
                         set<const GoughSSAVar *> &rv) {
    for (GoughSSAVarWithInputs *var : pending_var) {
        if (contains(aux.containing_v, var)) {
            /* def is used by join vertex, value only needs to be live on some
             * incoming edges */
            GoughSSAVarJoin *vj = (GoughSSAVarJoin *)var;
            const flat_set<GoughEdge> &live_edges
                = vj->get_edges_for_input(def);
            for (const auto &e : live_edges) {
                handle_pending_edge(g, e, nullptr, pending_vertex, rv);
            }
            continue;
        }
        const GoughEdge &e = aux.containing_e.at(var);
        handle_pending_edge(g, e, var, pending_vertex, rv);
    }
}

static
void handle_pending_vertex(GoughVertex def_v, const GoughGraph &g,
                           GoughVertex current,
                           set<GoughVertex> &pending_vertex,
                           set<const GoughSSAVar *> &rv) {
    DEBUG_PRINTF("---checking vertex %u\n", g[current].state_id);
    if (def_v == current) {
        DEBUG_PRINTF("contains target vertex\n");
        return; /* we have reached def */
    }
    for (const auto &e : in_edges_range(current, g)) {
        handle_pending_edge(g, e, nullptr, pending_vertex, rv);
    }
}

static
void handle_pending_vertices(GoughSSAVar *def, const GoughGraph &g,
                             const GoughGraphAux &aux,
                             set<GoughVertex> &pending_vertex,
                             set<const GoughSSAVar *> &rv) {
    if (pending_vertex.empty()) {
        return;
    }

    GoughVertex def_v = GoughGraph::null_vertex();
    if (contains(aux.containing_v, def)) {
        def_v = aux.containing_v.at(def);
    }
    unordered_set<GoughVertex> done;
    while (!pending_vertex.empty()) {
        GoughVertex current = *pending_vertex.begin();
        pending_vertex.erase(current);
        if (contains(done, current)) {
            continue;
        }
        done.insert(current);
        handle_pending_vertex(def_v, g, current, pending_vertex, rv);
    }
}

/* returns set of labels that the given def is live at */
static never_inline
set<const GoughSSAVar *> live_during(GoughSSAVar *def, const GoughGraph &g,
                                     const GoughGraphAux &aux) {
    DEBUG_PRINTF("checking who is defined during %u lifetime\n", def->slot);
    set<GoughVertex> pending_vertex;

    set<const GoughSSAVar *> rv;
    rv.insert(def);

    if (contains(aux.reporters, def)) {
        DEBUG_PRINTF("--> gets reported\n");
        const set<GoughVertex> &reporters = aux.reporters.at(def);
        for (auto v : reporters) {
            pending_vertex.insert(v);
            for (const auto &var : g[v].vars) {
                DEBUG_PRINTF("interferes %u\n", var->slot);
                rv.insert(var.get());
            }
        }
    }

    handle_pending_vars(def, g, aux, def->get_outputs(), pending_vertex, rv);
    handle_pending_vertices(def, g, aux, pending_vertex, rv);

    rv.erase(def);
    return rv;
}

template<typename VarP>
void set_initial_slots(const vector<VarP> &vars, u32 *next_slot) {
    for (auto &var : vars) {
        assert(var->slot == INVALID_SLOT);
        var->slot = (*next_slot)++;
    }
}

/* crude, deterministic assignment of symbolic register slots.
 * returns number of slots given out
 */
static
u32 initial_slots(const GoughGraph &g) {
    u32 next_slot = 0;
    for (auto v : vertices_range(g)) {
        set_initial_slots(g[v].vars, &next_slot);
    }
    for (const auto &e : edges_range(g)) {
        set_initial_slots(g[e].vars, &next_slot);
    }

    return next_slot;
}

#define NO_COLOUR (~0U)

static
u32 available_colour(const flat_set<u32> &bad_colours) {
    u32 rv = 0;
    for (const u32 &colour : bad_colours) {
        if (colour != rv) {
            assert(colour > rv);
            break;
        }
        rv = colour + 1;
    }

    assert(rv != NO_COLOUR);
    return rv;
}

static
void poison_colours(const set<const GoughSSAVar *> &live, u32 c,
                    const vector<u32> &colour_map,
                    vector<flat_set<u32> > *bad_colour) {
    for (const GoughSSAVar *var : live) {
        u32 var_index = var->slot;
        if (colour_map[var_index] != NO_COLOUR) {
            assert(c != colour_map[var_index]);
        } else {
            (*bad_colour)[var_index].insert(c);
        }
    }
}

static
void find_bad_due_to_live(const set<const GoughSSAVar *> &live,
                          const vector<u32> &colour_map, flat_set<u32> *out) {
    for (const GoughSSAVar *var : live) {
        u32 var_index = var->slot;
        if (colour_map[var_index] != NO_COLOUR) {
            out->insert(colour_map[var_index]);
        }
    }
}

static
void sequential_vertex_colouring(const GoughGraph &g, const GoughGraphAux &aux,
                                 const vector<GoughSSAVar *> &order,
                                 vector<u32> &colour_map) {
    assert(order.size() < NO_COLOUR);
    colour_map.clear();
    colour_map.resize(order.size(), NO_COLOUR);
    vector<u32> temp(order.size(), ~0U);
    vector<flat_set<u32> > bad_colour(order.size());

    for (GoughSSAVar *var : order) {
        u32 var_index = var->slot;
        if (is_block_local(g, var, aux)) {
            DEBUG_PRINTF("%u is block local\n", var_index);
            /* ignore variable whose lifetime is limited to their local block
             * there is no need to assign stream state to these variables */
            continue;
        }
        assert(colour_map[var_index] == NO_COLOUR);
        set<const GoughSSAVar *> live = live_during(var, g, aux);
        flat_set<u32> &local_bad = bad_colour[var_index];
        find_bad_due_to_live(live, colour_map, &local_bad);
        DEBUG_PRINTF("colouring %u\n", var_index);
        u32 c = available_colour(local_bad);
        colour_map[var_index] = c;
        assert(!contains(bad_colour[var_index], c));
        poison_colours(live, c, colour_map, &bad_colour);

        flat_set<u32> temp_set;
        local_bad.swap(temp_set);
        DEBUG_PRINTF("    %u coloured %u\n", var_index, c);
    }
}

template<typename VarP>
void add_to_dom_ordering(const vector<VarP> &vars,
                         vector<GoughSSAVar *> *out) {
    for (const auto &var : vars) {
        out->emplace_back(var.get());
    }
}

namespace {
class FinishVisitor : public boost::default_dfs_visitor {
public:
    explicit FinishVisitor(vector<GoughVertex> *o) : out(o) {}
    void finish_vertex(const GoughVertex v, const GoughGraph &) {
        out->emplace_back(v);
    }
    vector<GoughVertex> *out;
};
}

static
void find_dom_ordering(const GoughGraph &cfg, vector<GoughSSAVar *> *out) {
    vector<GoughVertex> g_order;

    /* due to construction quirks, default vertex order provides entry points */
    depth_first_search(cfg, visitor(FinishVisitor(&g_order))
                        .root_vertex(cfg[boost::graph_bundle].initial_vertex));

    for (auto it = g_order.rbegin(); it != g_order.rend(); ++it) {
        add_to_dom_ordering(cfg[*it].vars, out);
        for (const auto &e : out_edges_range(*it, cfg)) {
            add_to_dom_ordering(cfg[e].vars, out);
        }
    }
}

static
void create_slot_mapping(const GoughGraph &cfg, UNUSED u32 old_slot_count,
                         vector<u32> *old_new) {
    /* Interference graphs from SSA form are chordal -> optimally colourable in
     * poly time.
     *
     * Chordal graphs can be coloured by walking in perfect elimination order.
     * If the SSA CFG is iterated over in a way that respects dominance
     * relationship, the interference graph will be iterated in a perfect
     * elimination order.
     *
     * We can avoid creating the full interference graph and use liveness
     * information as we iterate over the definitions to perform the colouring.
     *
     * See S Hack various 2006-
     */
    vector<GoughSSAVar *> dom_order;

    GoughGraphAux aux;
    fill_aux(cfg, &aux);

    find_dom_ordering(cfg, &dom_order);
    assert(dom_order.size() == old_slot_count);
    sequential_vertex_colouring(cfg, aux, dom_order, *old_new);
}

static
void update_local_slots(GoughGraph &g, set<GoughSSAVar *> &locals,
                        u32 local_base) {
    DEBUG_PRINTF("%zu local variables\n", locals.size());
    /* local variables only occur on edges (joins are never local) */

    u32 allocated_count = 0;
    for (const auto &e : edges_range(g)) {
        u32 next_slot = local_base;
        for (auto &var : g[e].vars) {
            if (contains(locals, var.get())) {
                DEBUG_PRINTF("updating slot %u using local %u\n", var->slot,
                             next_slot);
                var->slot = next_slot++;
                allocated_count++;
            }
        }
    }

    assert(allocated_count == locals.size());
}

static never_inline
u32 update_slots(GoughGraph &g, const vector<u32> &old_new,
                 UNUSED u32 old_slot_count) {
    vector<GoughSSAVar *> vars;
    set<GoughSSAVar *> locals;
    all_vars(g, &vars);
    u32 slot_count = 0;
    for (GoughSSAVar *v : vars) {
        assert(v->slot < old_new.size());
        DEBUG_PRINTF("updating slot %u to %u\n", v->slot, old_new[v->slot]);
        if (old_new[v->slot] != NO_COLOUR) { /* not local, assign final slot */
            v->slot = old_new[v->slot];
            ENSURE_AT_LEAST(&slot_count, v->slot + 1);
        } else {
            locals.insert(v);
        }
    }
    assert(slot_count <= old_slot_count);
    DEBUG_PRINTF("reduce stream slots from %u to %u\n", old_slot_count,
                 slot_count);
    update_local_slots(g, locals, slot_count);

    return slot_count;
}

u32 assign_slots(GoughGraph &cfg, const Grey &grey) {
    u32 slot_count = initial_slots(cfg);

    if (!grey.goughRegisterAllocate) {
        return slot_count;
    }
    dump(cfg, "slots_pre", grey);

    vector<u32> old_new;
    create_slot_mapping(cfg, slot_count, &old_new);
    slot_count = update_slots(cfg, old_new, slot_count);

    return slot_count;
}

} // namespace ue2


text:
#include <stdio.h>
#include <sys/stat.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <time.h>
#include <assert.h>
#include <boost/property_tree/ini_parser.hpp>
#include <boost/property_tree/ptree.hpp>
#include <rte_launch.h>
#include <rte_malloc.h>

#include <vector>

#include "../core/logging.hpp"
#include "../core/clock.hpp"
#include "../core/libcyclone.hpp"
#include "pmemkv.hpp"

unsigned long tx_wr_block_cnt = 0UL;
unsigned long tx_ro_block_cnt = 0UL;
unsigned long tx_failed_cnt = 0UL;
unsigned long total_latency = 0UL;
unsigned long tx_begin_time = 0UL;
std::vector<struct cb_st *> *timeout_vector;
pthread_mutex_t vlock = PTHREAD_MUTEX_INITIALIZER;
volatile int64_t timedout_msgs = 0;
int driver(void *arg);

#define TIMEOUT_VECTOR_THRESHOLD 32
/* callback context */
typedef struct cb_st
{
	uint8_t request_type;
	unsigned long request_id;
} cb_t;

void async_callback(void *args, int code, unsigned long msg_latency)
{
	struct cb_st *cb_ctxt = (struct cb_st *)args;
	if(code == REP_SUCCESS){
		//BOOST_LOG_TRIVIAL(info) << "received message " << cb_ctxt->request_id;
		cb_ctxt->request_type == OP_PUT ? tx_wr_block_cnt++ : tx_ro_block_cnt++;
		rte_free(cb_ctxt);
	}else if (timedout_msgs < TIMEOUT_VECTOR_THRESHOLD){
		__sync_synchronize();
		//BOOST_LOG_TRIVIAL(info) << "timed-out message " << cb_ctxt->request_id;
		tx_failed_cnt++;
		pthread_mutex_lock(&vlock);
		timeout_vector->push_back(cb_ctxt);
		timedout_msgs++;
		//__sync_fetch_and_add(&timedout_msgs, 1);
		pthread_mutex_unlock(&vlock);
	}

	total_latency += msg_latency;
	if ((tx_wr_block_cnt + tx_ro_block_cnt) >= 5000)
	{
		unsigned long total_elapsed_time = (rtc_clock::current_time() - tx_begin_time);
		BOOST_LOG_TRIVIAL(info) << "LOAD = "
			<< ((double)1000000 * (tx_wr_block_cnt + tx_ro_block_cnt)) / total_elapsed_time
			<< " tx/sec "
			<< "LATENCY = "
			<< ((double)total_latency) / (tx_wr_block_cnt + tx_ro_block_cnt)
			<< " us "
			<< "wr/rd = "
			<<((double)tx_wr_block_cnt/tx_ro_block_cnt);
		tx_wr_block_cnt   = 0;
		tx_ro_block_cnt   = 0;
		tx_failed_cnt  = 0;
		total_latency  = 0;
		tx_begin_time = rtc_clock::current_time();
	}else if(tx_failed_cnt >= 5000){
		unsigned long total_elapsed_time = (rtc_clock::current_time() - tx_begin_time);
		BOOST_LOG_TRIVIAL(info) << "Ecsessive message timing out "
			<< " timedout count "
			<< tx_failed_cnt
			<< " success count "
			<< tx_wr_block_cnt + tx_ro_block_cnt
			<< " elpsd time "
			<< total_elapsed_time;
		tx_wr_block_cnt   = 0;
		tx_ro_block_cnt   = 0;
		tx_failed_cnt  = 0;
		total_latency  = 0;
		tx_begin_time = rtc_clock::current_time();
	}
}

typedef struct driver_args_st
{
	int leader;
	int me;
	int mc;
	int replicas;
	int clients;
	int partitions;
	void **handles;
	void operator() ()
	{
		(void)driver((void *)this);
	}
} driver_args_t;

int driver(void *arg)
{
	unsigned long request_id = 0UL; // wrap around at MAX
	driver_args_t *dargs = (driver_args_t *)arg;
	int me = dargs->me;
	int mc = dargs->mc;
	int replicas = dargs->replicas;
	int clients = dargs->clients;
	int partitions = dargs->partitions;
	void **handles = dargs->handles;
	char *buffer = new char[DISP_MAX_MSGSIZE];
	//struct proposal *prop = (struct proposal *)buffer;
	srand(time(NULL));
	int ret;
	int rpc_flags;
	int my_core;

	pmemkv_t *kv = (pmemkv_t *)buffer;

	double frac_read = 0.5;
	const char *frac_read_env = getenv("KV_FRAC_READ");
	if (frac_read_env != NULL)
	{
		frac_read = atof(frac_read_env);
	}
	BOOST_LOG_TRIVIAL(info) << "FRAC_READ = " << frac_read;

	unsigned long keys = pmemkv_keys;
	const char *keys_env = getenv("KV_KEYS");
	if (keys_env != NULL)
	{
		keys = atol(keys_env);
	}
	BOOST_LOG_TRIVIAL(info) << "KEYS = " << keys;

	srand(rtc_clock::current_time());
	struct cb_st *cb_ctxt;
	for( ; ; ){
		if(timedout_msgs > 0){ // re-try timedout messages
			__sync_synchronize();
			pthread_mutex_lock(&vlock);
			if(timeout_vector->size() > 0){
				cb_ctxt = timeout_vector->at(0);
				timeout_vector->erase(timeout_vector->begin());
				//__sync_fetch_and_sub(&timedout_msgs, 1);
				timedout_msgs--;
			}
			pthread_mutex_unlock(&vlock);

		}else{
			double coin = ((double)rand()) / RAND_MAX;
			if (coin > frac_read){
				rpc_flags = 0;
				kv->op    = OP_PUT;
			}
			else{
				rpc_flags = RPC_FLAG_RO;
				kv->op    = OP_GET;
			}

			kv->key   = rand() % keys;
			my_core = kv->key % executor_threads;

			cb_ctxt = (struct cb_st *)rte_malloc("callback_ctxt", sizeof(struct cb_st), 0);
			cb_ctxt->request_type = rpc_flags;
		}
		cb_ctxt->request_id = request_id++;
		// BOOST_LOG_TRIVIAL(info) << "sent message id  " << cb_ctxt->request_id;
		do{
			ret = make_rpc_async(handles[0],
					buffer,
					sizeof(pmemkv_t),
					async_callback,
					(void *)cb_ctxt,
					1UL << my_core,
					rpc_flags);
			if(ret == EMAX_INFLIGHT){
				//sleep a bit
				continue;
			}
		}while(ret);
	}
	return 0;
}

int main(int argc, const char *argv[])
{
	if (argc != 11)
	{
		printf("Usage: %s client_id_start client_id_stop mc replicas clients partitions cluster_config quorum_config_prefix server_ports inflight_cap\n", argv[0]);
		exit(-1);
	}

	int client_id_start = atoi(argv[1]);
	int client_id_stop  = atoi(argv[2]);
	driver_args_t *dargs;
	void **prev_handles;
	timeout_vector = new std::vector<struct cb_st *>();
	cyclone_network_init(argv[7], 1, atoi(argv[3]), 2 + client_id_stop - client_id_start);
	driver_args_t ** dargs_array =
		(driver_args_t **)malloc((client_id_stop - client_id_start) * sizeof(driver_args_t *));
	for (int me = client_id_start; me < client_id_stop; me++)
	{
		dargs = (driver_args_t *) malloc(sizeof(driver_args_t));
		dargs_array[me - client_id_start] = dargs;
		if (me == client_id_start)
		{
			dargs->leader = 1;
		}
		else
		{
			dargs->leader = 0;
		}
		dargs->me = me;
		dargs->mc = atoi(argv[3]);
		dargs->replicas = atoi(argv[4]);
		dargs->clients  = atoi(argv[5]);
		dargs->partitions = atoi(argv[6]);
		dargs->handles = new void *[dargs->partitions];
		char fname_server[50];
		char fname_client[50];
		for (int i = 0; i < dargs->partitions; i++){
			sprintf(fname_server, "%s", argv[7]);
			sprintf(fname_client, "%s%d.ini", argv[8], i);
			dargs->handles[i] = cyclone_client_init(dargs->me,
					dargs->mc,
					1 + me - client_id_start,
					fname_server,
					atoi(argv[9]),
					fname_client,
					CLIENT_ASYNC,
					atoi(argv[10]));
		}
	}
	for (int me = client_id_start; me < client_id_stop; me++){
		cyclone_launch_clients(dargs_array[me-client_id_start]->handles[0],driver, dargs_array[me-client_id_start], 1+  me-client_id_start);
	}
	rte_eal_mp_wait_lcore();
}


text:
/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */

/*
 Copyright (C) 2015 Peter Caspers

 This file is part of QuantLib, a free-software/open-source library
 for financial quantitative analysts and developers - http://quantlib.org/

 QuantLib is free software: you can redistribute it and/or modify it
 under the terms of the QuantLib license.  You should have received a
 copy of the license along with this program; if not, please email
 <quantlib-dev@lists.sf.net>. The license is also available online at
 <http://quantlib.org/license.shtml>.

 This program is distributed in the hope that it will be useful, but WITHOUT
 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 FOR A PARTICULAR PURPOSE.  See the license for more details.
*/

#include <ql/exercise.hpp>
#include <ql/pricingengines/blackformula.hpp>
#include <ql/experimental/models/fxoptionhelper.hpp>
#include <ql/time/calendars/nullcalendar.hpp>

#include <boost/make_shared.hpp>

namespace QuantLib {

FxOptionHelper::FxOptionHelper(
    const Period &maturity, const Calendar &calendar, const Real strike,
    const Handle<Quote> fxSpot, const Handle<Quote> volatility,
    const Handle<YieldTermStructure> &domesticYield,
    const Handle<YieldTermStructure> &foreignYield,
    CalibrationHelper::CalibrationErrorType errorType)
    : CalibrationHelper(volatility, domesticYield, errorType),
      hasMaturity_(true), maturity_(maturity), calendar_(calendar),
      strike_(strike), fxSpot_(fxSpot), foreignYield_(foreignYield) {
    registerWith(fxSpot_);
    registerWith(foreignYield_);
}

FxOptionHelper::FxOptionHelper(
    const Date &exerciseDate, const Real strike, const Handle<Quote> fxSpot,
    const Handle<Quote> volatility,
    const Handle<YieldTermStructure> &domesticYield,
    const Handle<YieldTermStructure> &foreignYield,
    CalibrationHelper::CalibrationErrorType errorType)
    : CalibrationHelper(volatility, domesticYield, errorType),
      hasMaturity_(false), exerciseDate_(exerciseDate), strike_(strike),
      fxSpot_(fxSpot), foreignYield_(foreignYield) {
    registerWith(fxSpot_);
    registerWith(foreignYield_);
}

void FxOptionHelper::performCalculations() const {
    if (hasMaturity_)
        exerciseDate_ =
            calendar_.advance(termStructure_->referenceDate(), maturity_);
    tau_ = termStructure_->timeFromReference(exerciseDate_);
    atm_ = fxSpot_->value() * foreignYield_->discount(tau_) /
           termStructure_->discount(tau_);
    effStrike_ = strike_;
    if(effStrike_ == Null<Real>())
        effStrike_ = atm_;
    type_ = effStrike_ >= atm_ ? Option::Call : Option::Put;
    boost::shared_ptr<StrikedTypePayoff> payoff(
        new PlainVanillaPayoff(type_, effStrike_));
    boost::shared_ptr<Exercise> exercise =
        boost::make_shared<EuropeanExercise>(exerciseDate_);
    option_ =
        boost::shared_ptr<VanillaOption>(new VanillaOption(payoff, exercise));
    CalibrationHelper::performCalculations();
}

Real FxOptionHelper::modelValue() const {
    calculate();
    option_->setPricingEngine(engine_);
    return option_->NPV();
}

Real FxOptionHelper::blackPrice(Real volatility) const {
    calculate();
    const Real stdDev = volatility * std::sqrt(tau_);
    return blackFormula(type_, strike_, atm_, stdDev, termStructure_->discount(tau_));
}

} // namespace QuantLib

max_forks_repo_name: pcaspers/quantlib


text: #include <boost/graph/graph_traits.hpp>

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


text:
/******************************************************************************
 * $Id$
 *
 * Project:  libLAS - http://liblas.org - A BSD library for LAS format data.
 * Purpose:  Point Writer implementation for C++ libLAS
 * Author:   Howard Butler, hobu.inc@gmail.com
 *
 ******************************************************************************
 * Copyright (c) 2010, Howard Butler
 *
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following
 * conditions are met:
 *
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in
 *       the documentation and/or other materials provided
 *       with the distribution.
 *     * Neither the name of the Martin Isenburg or Iowa Department
 *       of Natural Resources nor the names of its contributors may be
 *       used to endorse or promote products derived from this software
 *       without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
 * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
 * OF SUCH DAMAGE.
 ****************************************************************************/

#include <liblas/header.hpp>
#include <liblas/variablerecord.hpp>
#include <liblas/schema.hpp>
#include <liblas/detail/writer/writer.hpp>
#include <liblas/detail/writer/point.hpp>
#include <liblas/detail/private_utility.hpp>
// boost
#include <boost/cstdint.hpp>
// std
#include <cmath>
#include <sstream>

using namespace boost;

namespace liblas { namespace detail { namespace writer {

Point::Point(std::ostream& ofs, boost::uint32_t& count, HeaderPtr header)
    : m_ofs(ofs)
    , m_header(header)
    , m_format(header->GetSchema())
    , m_pointCount(count)
{
    setup();
}

Point::~Point()
{

}

void Point::setup()
{
    // If we have extra data on each point by virtue of the
    // base size of the format being smaller than the total byte
    // size of the format, we should make a buffer of blank data
    // that we can write into the file as necessary.  We make it
    // here instead of at each ::write() invocation to save the
    // allocation and writing of the array
    if (m_format.GetByteSize() != m_format.GetBaseByteSize())
	{
        std::size_t const size = m_format.GetByteSize() - m_format.GetBaseByteSize();

        m_blanks.resize(size);
        m_blanks.assign(size, 0);
    }
}

void Point::write(const liblas::Point& point)
{

    std::vector<boost::uint8_t> const& data = point.GetData();
    detail::write_n(m_ofs, data.front(), m_header->GetDataRecordLength());

    m_pointCount++;

    // write in our extra data that the user set on the
    // point up to the header's specified DataRecordLength
    // if (m_format.GetByteSize() != m_format.GetBaseByteSize()) {
    //     std::vector<uint8_t> const& data = point.GetExtraData();
    //
    //     std::size_t size = m_format.GetByteSize() - m_format.GetBaseByteSize();
    //
    //     if (size < 0) {
    //         throw std::runtime_error("ByteSize of format was less than BaseByteSize, this cannot happen!");
    //     }
    //
    //     if (data.size() == 0) {
    //
    //         detail::write_n(GetStream(), m_blanks.front(), static_cast<std::streamsize>(size));
    //
    //     } else if (data.size() < size){
    //         // size can be casted now that we have already checked if it is less than 0
    //         int16_t difference = static_cast<uint16_t>(size) - static_cast<uint16_t>(data.size());
    //         detail::write_n(GetStream(), data.front(), data.size());
    //         detail::write_n(GetStream(), m_blanks.front(), static_cast<std::streamsize>(difference));
    //
    //     } else {
    //         detail::write_n(GetStream(), data.front(), static_cast<std::streamsize>(size));
    //     }
    // }
}

}}} // namespace liblas::detail::reader

max_stars_repo_name: marisn/libLAS

max_issues_repo_name: marisn/libLAS

max_forks_repo_name: marisn/libLAS


text:
/**
 * @file crypto.hpp
 * @author Bensuperpc (bensuperpc@gmail.com)
 * @brief
 * @version 1.0.0
 * @date 2021-04-01
 *
 * MIT License
 *
 */

/*
** Source:
https://stackoverflow.com/questions/178265/what-is-the-most-hard-to-understand-piece-of-c-code-you-know
https://cs.uwaterloo.ca/~m32rober/rsqrt.pdf
https://github.com/bavlayan/Encrypt-Decrypt-with-OpenSSL---RSA
*/

#ifndef CRYPTO_HPP_
#define CRYPTO_HPP_

#define BUFFSIZE 16384

#include <cstring>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <sstream>
#include <string>

// For MD5 and SHA
#include <boost/crc.hpp> //CRC32
#include <openssl/md5.h>
#include <openssl/sha.h>
#include <string_view>

//#include "openssl_rsa.h"

extern "C" {
#include "banned.h"
};

#define BUFFSIZE 16384

namespace my {
namespace crypto {
/**
 * @brief Get the md5hash object
 *
 * @param str
 * @return std::string
 */
std::string get_md5hash(const std::string &str);
// void get_md5hash_from_string(const unsigned char *, size_t &);
/**
 * @brief Get the md5hash from string object
 *
 * @param str
 * @return std::string
 */
std::string get_md5hash_from_string(const std::string &str);

/**
 * @brief Get the sha1hash object
 *
 * @param str
 * @return std::string
 */
std::string get_sha1hash(const std::string &str);
// void get_sha1hash_from_string(const unsigned char *, size_t &);

/**
 * @brief Get the sha1hash from string object
 *
 * @param str
 * @return std::string
 */
std::string get_sha1hash_from_string(const std::string &str);

/**
 * @brief Get the sha224hash object
 *
 * @param str
 * @return std::string
 */
std::string get_sha224hash(const std::string &str);
// void get_sha224hash_from_string(const unsigned char *, size_t &);

/**
 * @brief Get the sha224hash from string object
 *
 * @param str
 * @return std::string
 */
std::string get_sha224hash_from_string(const std::string &str);

/**
 * @brief Get the sha256hash object
 *
 * @param str
 * @return std::string
 */
std::string get_sha256hash(const std::string &str);
// void get_sha256hash_from_string(const unsigned char *, size_t &);

/**
 * @brief Get the sha256hash from string object
 *
 * @param str
 * @return std::string
 */
std::string get_sha256hash_from_string(const std::string &str);

/**
 * @brief Get the sha384hash object
 *
 * @param str
 * @return std::string
 */
std::string get_sha384hash(const std::string &str);
// void get_sha384hash_from_string(const unsigned char *, size_t &);

/**
 * @brief Get the sha384hash from string object
 *
 * @param str
 * @return std::string
 */
std::string get_sha384hash_from_string(const std::string &str);

/**
 * @brief Get the sha512hash object
 *
 * @param str
 * @return std::string
 */
std::string get_sha512hash(const std::string &str);
// void get_sha512hash_from_string(const unsigned char *, size_t &);
/**
 * @brief Get the sha512hash from string object
 *
 * @param str
 * @return std::string
 */
std::string get_sha512hash_from_string(const std::string &str);
} // namespace crypto
} // namespace my
// https://www.quora.com/How-can-I-get-the-MD5-or-SHA-hash-of-a-file-in-C

std::string my::crypto::get_md5hash(const std::string &fname) {

  char buffer[BUFFSIZE];
  unsigned char digest[MD5_DIGEST_LENGTH]; // == 16

  std::stringstream ss;
  std::string md5string;

  std::ifstream ifs(fname, std::ifstream::binary);

  MD5_CTX md5Context;

  MD5_Init(&md5Context);

  while (ifs.good()) {
    ifs.read(buffer, BUFFSIZE);
    MD5_Update(&md5Context, buffer, static_cast<size_t>(ifs.gcount()));
  }

  ifs.close();

  auto &&res = MD5_Final(digest, &md5Context);

  if (res == 0) // hash failed
    return {};  // or raise an exception

  // ss << std::hex << std::uppercase << std::setfill('0');
  ss << std::hex << std::setfill('0');
  for (unsigned char uc : digest)
    ss << std::setw(2) << (int)uc;

  md5string = ss.str();

  return md5string;
}

std::string my::crypto::get_md5hash_from_string(const std::string &str) {
  unsigned char result[MD5_DIGEST_LENGTH];
  MD5((const unsigned char *)str.c_str(), str.size(), result);

  std::ostringstream sout;
  sout << std::hex << std::setfill('0');
  for (long long c : result) {
    sout << std::setw(2) << (long long)c;
  }
  return sout.str();
}

std::string my::crypto::get_sha1hash(const std::string &fname) {

  char buffer[BUFFSIZE];
  unsigned char digest[SHA_DIGEST_LENGTH];

  std::stringstream ss;
  std::string sha1string;

  std::ifstream ifs(fname, std::ifstream::binary);

  SHA_CTX sha1Context;

  SHA1_Init(&sha1Context);

  while (ifs.good()) {
    ifs.read(buffer, BUFFSIZE);
    SHA1_Update(&sha1Context, buffer, static_cast<size_t>(ifs.gcount()));
  }

  ifs.close();

  auto &&res = SHA1_Final(digest, &sha1Context);

  if (res == 0) // hash failed
    return {};  // or raise an exception

  // ss << std::hex << std::uppercase << std::setfill('0');
  ss << std::hex << std::setfill('0');
  for (unsigned char uc : digest)
    ss << std::setw(2) << (int)uc;

  sha1string = ss.str();

  return sha1string;
}

std::string my::crypto::get_sha1hash_from_string(const std::string &str) {
  unsigned char result[SHA_DIGEST_LENGTH];
  SHA1((const unsigned char *)str.c_str(), str.size(), result);

  std::ostringstream sout;
  sout << std::hex << std::setfill('0');
  for (long long c : result) {
    sout << std::setw(2) << (long long)c;
  }
  return sout.str();
}

std::string my::crypto::get_sha224hash(const std::string &fname) {

  char buffer[BUFFSIZE];
  unsigned char digest[SHA224_DIGEST_LENGTH];

  std::stringstream ss;
  std::string sha224string;

  std::ifstream ifs(fname, std::ifstream::binary);

  SHA256_CTX sha224Context;

  SHA224_Init(&sha224Context);

  while (ifs.good()) {
    ifs.read(buffer, BUFFSIZE);
    SHA256_Update(&sha224Context, buffer, static_cast<size_t>(ifs.gcount()));
  }

  ifs.close();

  auto &&res = SHA256_Final(digest, &sha224Context);

  if (res == 0) // hash failed
    return {};  // or raise an exception

  // ss << std::hex << std::uppercase << std::setfill('0');
  ss << std::hex << std::setfill('0');
  for (unsigned char uc : digest)
    ss << std::setw(2) << (int)uc;

  sha224string = ss.str();

  return sha224string;
}

std::string my::crypto::get_sha224hash_from_string(const std::string &str) {
  unsigned char result[SHA224_DIGEST_LENGTH];
  SHA224((const unsigned char *)str.c_str(), str.size(), result);

  std::ostringstream sout;
  sout << std::hex << std::setfill('0');
  for (long long c : result) {
    sout << std::setw(2) << (long long)c;
  }
  return sout.str();
}

std::string my::crypto::get_sha256hash(const std::string &fname) {

  char buffer[BUFFSIZE];
  unsigned char digest[SHA256_DIGEST_LENGTH];

  std::stringstream ss;
  std::string sha256string;

  std::ifstream ifs(fname, std::ifstream::binary);

  SHA256_CTX sha256Context;

  SHA256_Init(&sha256Context);

  while (ifs.good()) {
    ifs.read(buffer, BUFFSIZE);
    SHA256_Update(&sha256Context, buffer, static_cast<size_t>(ifs.gcount()));
  }

  ifs.close();

  auto &&res = SHA256_Final(digest, &sha256Context);

  if (res == 0) // hash failed
    return {};  // or raise an exception

  // ss << std::hex << std::uppercase << std::setfill('0');
  ss << std::hex << std::setfill('0');
  for (unsigned char uc : digest)
    ss << std::setw(2) << (int)uc;

  sha256string = ss.str();

  return sha256string;
}

std::string my::crypto::get_sha256hash_from_string(const std::string &str) {
  unsigned char result[SHA256_DIGEST_LENGTH];
  SHA256((const unsigned char *)str.c_str(), str.size(), result);

  std::ostringstream sout;
  sout << std::hex << std::setfill('0');
  for (long long c : result) {
    sout << std::setw(2) << (long long)c;
  }
  return sout.str();
}

std::string my::crypto::get_sha384hash(const std::string &fname) {

  char buffer[BUFFSIZE];
  unsigned char digest[SHA384_DIGEST_LENGTH];

  std::stringstream ss;
  std::string sha384string;

  std::ifstream ifs(fname, std::ifstream::binary);

  SHA512_CTX sha384Context;

  SHA384_Init(&sha384Context);

  while (ifs.good()) {
    ifs.read(buffer, BUFFSIZE);
    SHA384_Update(&sha384Context, buffer, static_cast<size_t>(ifs.gcount()));
  }

  ifs.close();

  auto &&res = SHA384_Final(digest, &sha384Context);

  if (res == 0) // hash failed
    return {};  // or raise an exception

  // ss << std::hex << std::uppercase << std::setfill('0');
  ss << std::hex << std::setfill('0');
  for (unsigned char uc : digest)
    ss << std::setw(2) << (int)uc;

  sha384string = ss.str();

  return sha384string;
}

std::string my::crypto::get_sha384hash_from_string(const std::string &str) {
  unsigned char result[SHA384_DIGEST_LENGTH];
  SHA384((const unsigned char *)str.c_str(), str.size(), result);

  std::ostringstream sout;
  sout << std::hex << std::setfill('0');
  for (long long c : result) {
    sout << std::setw(2) << (long long)c;
  }
  return sout.str();
}

std::string my::crypto::get_sha512hash(const std::string &fname) {

  char buffer[BUFFSIZE];
  unsigned char digest[SHA512_DIGEST_LENGTH];

  std::stringstream ss;
  std::string sha512string;

  std::ifstream ifs(fname, std::ifstream::binary);

  SHA512_CTX sha512Context;

  SHA512_Init(&sha512Context);

  while (ifs.good()) {
    ifs.read(buffer, BUFFSIZE);
    SHA512_Update(&sha512Context, buffer, static_cast<size_t>(ifs.gcount()));
  }

  ifs.close();

  auto &&res = SHA512_Final(digest, &sha512Context);

  if (res == 0) // hash failed
    return {};  // or raise an exception

  // ss << std::hex << std::uppercase << std::setfill('0');
  ss << std::hex << std::setfill('0');
  for (unsigned char uc : digest)
    ss << std::setw(2) << (int)uc;

  sha512string = ss.str();

  return sha512string;
}

std::string my::crypto::get_sha512hash_from_string(const std::string &str) {
  unsigned char result[SHA512_DIGEST_LENGTH];
  SHA512((const unsigned char *)str.c_str(), str.size(), result);

  std::ostringstream sout;
  sout << std::hex << std::setfill('0');
  for (long long c : result) {
    sout << std::setw(2) << (long long)c;
  }
  return sout.str();
}
/*
void my::crypto::get_sha512hash_from_string(const unsigned char *cstr, unsigned
char *out, size_t &size)
{
    unsigned char digest[SHA512_DIGEST_LENGTH];
    MD5Context context;
    MD5Init(&context);
    MD5Update(&context, string, strlen(string));
    MD5Final(digest, &context);

    unsigned char hash[SHA512_DIGEST_LENGTH]; // == 16
    SHA512(cstr, sizeof(*cstr) - 1, hash);
    unsigned char * hash_ptr = hash;
}
*/

#endif

max_stars_repo_name: bensuperpc/BenCrypto

max_issues_repo_name: bensuperpc/BenCrypto

max_forks_repo_name: bensuperpc/BenCrypto