text:
// Copyright (c) 2017-2018, Karbo developers
// Copyright (c) 2017-2019, The CROAT.community developers
//
// This file is part of Bytecoin.
//
// Bytecoin is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Bytecoin is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with Bytecoin. If not, see <http://www.gnu.org/licenses/>.

#include <condition_variable>
#include <future>
#include <memory>
#include <mutex>
#include <sstream>
#include <functional>
#include <iostream>
#include <cstring>
#include <string>
#include <map>
#include <boost/program_options/variables_map.hpp>
#include <iostream>
#ifdef _WIN32
#include <Windows.h>
#include <io.h>
//#include <crtdbg.h>
//#include <winsock2.h>
#include <windns.h>
#include <Rpc.h>
#else
#include <arpa/nameser.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <resolv.h>
#include <netdb.h>
#include <unistd.h>
#endif
#include "DnsTools.h"

namespace Common {

#ifndef __ANDROID__

	bool fetch_dns_txt(const std::string domain, std::vector<std::string>&records) {

#ifdef _WIN32
		using namespace std;

#pragma comment(lib, "Ws2_32.lib")
#pragma comment(lib, "Dnsapi.lib")

		PDNS_RECORD pDnsRecord;          //Pointer to DNS_RECORD structure.

		{
			WORD type = DNS_TYPE_TEXT;

			if (0 != DnsQuery_A(domain.c_str(), type, DNS_QUERY_BYPASS_CACHE, NULL, &pDnsRecord, NULL))
			{
				cerr << "Error querying: '" << domain << "'" << endl;
				return false;
			}
		}

		PDNS_RECORD it;
		map<WORD, function<void(void)>> callbacks;

		callbacks[DNS_TYPE_TEXT] = [&it, &records](void) -> void {
			std::stringstream stream;
			for (DWORD i = 0; i < it->Data.TXT.dwStringCount; i++) {
				stream << RPC_CSTR(it->Data.TXT.pStringArray[i]) << endl;;
			}
			records.push_back(stream.str());
		};

		for (it = pDnsRecord; it != NULL; it = it->pNext) {
			if (callbacks.count(it->wType)) {
				callbacks[it->wType]();
			}
		}
		DnsRecordListFree(pDnsRecord, DnsFreeRecordListDeep);
#else
		using namespace std;

		res_init();
		ns_msg nsMsg;
		int response;
		unsigned char query_buffer[4096];
		{
			ns_type type = ns_t_txt;

			const char * c_domain = (domain).c_str();
			response = res_query(c_domain, 1, type, query_buffer, sizeof(query_buffer));

			if (response < 0)
				return false;
		}

		ns_initparse(query_buffer, response, &nsMsg);

		map<ns_type, function<void(const ns_rr &rr)>> callbacks;

		callbacks[ns_t_txt] = [&nsMsg, &records](const ns_rr &rr) -> void {
			int txt_len = *(unsigned char *) ns_rr_rdata(rr);
			char txt[256];
			memset(txt, 0, 256);
			if (txt_len <= 255){
				memcpy(txt, ns_rr_rdata(rr) + 1, txt_len);
				records.push_back(txt);
			}
		};

		for (int x = 0; x < ns_msg_count(nsMsg, ns_s_an); x++) {
			ns_rr rr;
			ns_parserr(&nsMsg, ns_s_an, x, &rr);
			ns_type type = ns_rr_type(rr);
			if (callbacks.count(type)) {
				callbacks[type](rr);
			}
		}

#endif
		if (records.empty())
			return false;

		return true;
	}

#endif

bool processServerAliasResponse(const std::string& s, std::string& address) {
  try {
    // Courtesy of Monero Project
    // make sure the txt record has "oa1:croat" and find it
    auto pos = s.find("oa1:croat");
    if (pos == std::string::npos)
      return false;
    // search from there to find "recipient_address="
    pos = s.find("recipient_address=", pos);
    if (pos == std::string::npos)
      return false;
    pos += 18; // move past "recipient_address="
    // find the next semicolon
    auto pos2 = s.find(";", pos);
    if (pos2 != std::string::npos)
    {
      // length of address == 95, we can at least validate that much here
      if (pos2 - pos == 95)
      {
        address = s.substr(pos, 95);
      }
      else {
        return false;
      }
    }
  }
  catch (std::exception&) {
    return false;
  }

  return true;
}

std::string resolveAlias(const std::string& aliasUrl) {
  std::string host;
  std::string uri;
  std::vector<std::string> records;
  std::string address;

  if (!Common::fetch_dns_txt(aliasUrl, records)) {
    throw std::runtime_error("Failed to lookup DNS record");
  }

  for (const auto& record : records) {
    if (Common::processServerAliasResponse(record, address)) {
      return address;
    }
  }
  throw std::runtime_error("Failed to parse server response");
}

std::vector<std::string> resolveAliases(const std::string& aliasUrl) {
  std::string host;
  std::string uri;
  std::vector<std::string> records;
  std::vector<std::string> addresses;

  if (!Common::fetch_dns_txt(aliasUrl, records)) {
    throw std::runtime_error("Failed to lookup DNS record");
  }

  for (const auto& record : records) {
    std::string address;
    if (Common::processServerAliasResponse(record, address)) {
      addresses.push_back(address);
    }
  }

  if (!addresses.empty()) {
    return addresses;
  }

  throw std::runtime_error("Failed to parse server response");
}

}

max_stars_repo_name: CroatApps/CROAT-Node

max_issues_repo_name: CroatApps/CROAT-Node

max_forks_repo_name: CroatApps/CROAT-Node


text:
/*
 * Copyright (C) 2005-2020 Centre National d'Etudes Spatiales (CNES)
 *
 * This file is part of Orfeo Toolbox
 *
 *     https://www.orfeo-toolbox.org/
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#define BOOST_TEST_MODULE "SarSensorModel unit testing"
#define BOOST_TEST_DYN_LINK
#if defined(__GNUC__) || defined(__clang__)
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunused-parameter"
#pragma GCC diagnostic ignored "-Woverloaded-virtual"
#include <boost/test/unit_test.hpp>
#pragma GCC diagnostic pop
#else
#include <boost/test/unit_test.hpp>
#endif

#include "otbSarSensorModel.h"
#include "otbImageFileReader.h"

using namespace boost::unit_test;

BOOST_AUTO_TEST_CASE(SARSensorModel_parameters)
{
  BOOST_TEST_REQUIRE( framework::master_test_suite().argc == 8);
  // filename lon lat height lineTol sampleTol sqResTol
  //BOOST_TEST_MESSAGE( "'argv[0]' contains " << framework::master_test_suite().argv[0] );
  //BOOST_TEST_REQUIRE( framework::master_test_suite().argv[1] == "--input" );
  std::cout << "argv[1] " << framework::master_test_suite().argv[1] << std::endl;

}

BOOST_AUTO_TEST_CASE(SARSensorModel_WorldToLineSample)
{
  using ImageType = otb::VectorImage<unsigned int, 2>;
  using ReaderType = otb::ImageFileReader<ImageType>;

  auto reader = ReaderType::New();
  reader->SetFileName(framework::master_test_suite().argv[1]);
  reader->GenerateOutputInformation();
  const auto & imd = reader->GetOutput()->GetImageMetadata();

  otb::SarSensorModel model(imd);

  otb::SarSensorModel::Point3DType inWorldPoint;

  inWorldPoint[0] = std::stod(framework::master_test_suite().argv[2]);
  inWorldPoint[1] = std::stod(framework::master_test_suite().argv[3]);
  inWorldPoint[2] = std::stod(framework::master_test_suite().argv[4]);

  otb::SarSensorModel::Point2DType outLineSampleOssim;

  std::cout << "Direct test with otb" << std::endl;
  otb::SarSensorModel::Point2DType outLineSampleOtb;
  model.WorldToLineSample(inWorldPoint, outLineSampleOtb);
}

BOOST_AUTO_TEST_CASE(SARSensorModel_auto_validate_inverse_transform )
{
  double lineTol = std::stod(framework::master_test_suite().argv[5]);
  double sampleTol = std::stod(framework::master_test_suite().argv[6]);

  using ImageType = otb::VectorImage<unsigned int, 2>;
  using ReaderType = otb::ImageFileReader<ImageType>;

  auto reader = ReaderType::New();
  reader->SetFileName(framework::master_test_suite().argv[1]);
  reader->GenerateOutputInformation();

  if (reader->GetOutput()->GetGCPCount() == 0)
  {
    otbLogMacro(Info, << "Input product has no gcp, skipping gcp inverse transform validation.");
    return;
  }

  const auto & imd = reader->GetOutput()->GetImageMetadata();

  otb::SarSensorModel model(imd);

  for (const auto & gcp : imd.GetGCPParam().GCPs)
  {
    itk::Point<double, 3> geoPoint;
    geoPoint[0] = gcp.m_GCPX;
    geoPoint[1] = gcp.m_GCPY;
    geoPoint[2] = gcp.m_GCPZ;

    itk::Point<double, 2> lineSampleBaseline;
    lineSampleBaseline[0] = gcp.m_GCPCol;
    lineSampleBaseline[1] = gcp.m_GCPRow;

    itk::Point<double, 2> lineSample;

    model.WorldToLineSample(geoPoint, lineSample);

    BOOST_TEST(std::abs(lineSample[0] - lineSampleBaseline[0]) < lineTol);
    BOOST_TEST(std::abs(lineSample[1] - lineSampleBaseline[1]) < sampleTol);
  }
}

BOOST_AUTO_TEST_CASE(SARSensorModel_auto_validate_forward_transform)
{
  double sqResTol = std::stod(framework::master_test_suite().argv[7]);;

  using ImageType = otb::VectorImage<unsigned int, 2>;
  using ReaderType = otb::ImageFileReader<ImageType>;

  auto reader = ReaderType::New();
  reader->SetFileName(framework::master_test_suite().argv[1]);
  reader->GenerateOutputInformation();

  if (reader->GetOutput()->GetGCPCount() <= 1)
  {
    otbLogMacro(Info, << "Input product has not enough gcp, at least two are "
                         "required for this test. Skipping gcp forward transform validation.");
    return;
  }

  auto & imd = reader->GetOutput()->m_Imd;
  auto & GCPParam = imd.GetGCPParam();

  std::vector<otb::GCP> testGCPs;
  otb::Projection::GCPParam productGCPs;

  bool odd = false;

  for (auto gcp: GCPParam.GCPs)
  {
    if (odd)
    {
      productGCPs.GCPs.push_back(gcp);
    }
    else
    {
      testGCPs.push_back(gcp);
    }
    odd = !odd;
  }

  imd.Add(otb::MDGeom::GCP, productGCPs);

  otb::SarSensorModel model(imd);

  for (const auto & gcp : testGCPs)
  {
    itk::Point<double, 2> sensorPoint;
    sensorPoint[0] = gcp.m_GCPCol;
    sensorPoint[1] = gcp.m_GCPRow;

    itk::Point<double, 3> geoPointBaseline;
    geoPointBaseline[0] = gcp.m_GCPX;
    geoPointBaseline[1] = gcp.m_GCPY;
    geoPointBaseline[2] = gcp.m_GCPZ;

    itk::Point<double, 3> geoPoint;

    model.LineSampleHeightToWorld(sensorPoint, gcp.m_GCPZ, geoPoint);
    BOOST_TEST(geoPoint.SquaredEuclideanDistanceTo(geoPointBaseline) < sqResTol);
  }

}

ext: cxx

max_stars_repo_name: orfeotoolbox/OTB

max_issues_repo_name: guandd/OTB

max_forks_repo_name: guandd/OTB


text:
#ifndef __IRODS_BUFFER_ENCRYPTION_HPP__
#define __IRODS_BUFFER_ENCRYPTION_HPP__

// =-=-=-=-=-=-=-
// irods includes
#include "irods/rodsDef.h"

// =-=-=-=-=-=-=-
#include "irods/irods_error.hpp"

// =-=-=-=-=-=-=-
// boost includes
#include <boost/numeric/ublas/storage.hpp>

// =-=-=-=-=-=-=-
// ssl includes
#include <openssl/evp.h>

namespace irods {

/// =-=-=-=-=-=-=-
/// @brief functor which manages buffer encryption
///        used for parallel transfers.  based on
///        SSL EVP library
    class buffer_crypt {

        public:
            // =-=-=-=-=-=-=-
            // typedef for bounded array
            typedef std::vector< unsigned char > array_t;

            // =-=-=-=-=-=-=-
            // con/de structors
            buffer_crypt();
            buffer_crypt(
                int,           // key size in bytes
                int,           // salt size in bytes
                int,           // num hash rounds
                const char* ); // algorithm
            ~buffer_crypt();

            /// =-=-=-=-=-=-=-
            /// @brief given a string, encrypt it
            irods::error encrypt(
                const array_t&, // key
                const array_t&, // initialization vector
                const array_t&, // plaintext buffer
                array_t& );     // encrypted buffer

            /// =-=-=-=-=-=-=-
            /// @brief given a string, decrypt it
            irods::error decrypt(
                const array_t&, // key
                const array_t&, // initialization vector
                const array_t&, // encrypted buffer
                array_t& );     // plaintext buffer

            /// =-=-=-=-=-=-=-
            /// @brief given a key, create a hashed key and IV
            irods::error initialization_vector(
                array_t& );     // initialization vector

            /// =-=-=-=-=-=-=-
            /// @brief generate a random byte key
            static irods::error generate_key(
                array_t&,       // random byte key
                int );          // key size in bytes

            /// =-=-=-=-=-=-=-
            /// @brief hex encode buffer_crypt::array_t
            static irods::error hex_encode(
                const array_t&,     // bytes to encode
                std::string& );     // hex encoded bytes

            /// =-=-=-=-=-=-=-
            /// @brief accessors for attributes
            int         key_size()        {
                return key_size_;
            };
            int         salt_size()       {
                return salt_size_;
            };
            int         num_hash_rounds() {
                return num_hash_rounds_;
            };
            std::string algorithm()       {
                return algorithm_;
            };

            static std::string gen_hash( unsigned char*, int );

        private:
            // =-=-=-=-=-=-=-
            // attributes
            int         key_size_;
            int         salt_size_;
            int         num_hash_rounds_;
            std::string algorithm_;

    }; // class buffer_crypt

}; // namespace irods

#endif // __IRODS_BUFFER_ENCRYPTION_HPP__

ext: hpp

max_stars_repo_name: aghsmith/irods

max_issues_repo_name: selroc/irods

max_forks_repo_name: selroc/irods


text:
#pragma once

#include "telnetpp/server_option.hpp"
#include <boost/optional.hpp>
#include <map>

namespace telnetpp { namespace options { namespace new_environ {

//* =========================================================================
/// \brief An implementation of the server side of the Telnet New-Environ
/// option.
//* =========================================================================
class TELNETPP_EXPORT server : public server_option
{
public :
    //* =====================================================================
    /// \brief Constructor
    //* =====================================================================
    server();

    //* =====================================================================
    /// \brief Sets a "VAR" type variable in the environment.
    //* =====================================================================
    std::vector<telnetpp::token> set_variable(
        std::string const &name, std::string const &value);

    //* =====================================================================
    /// \brief Deletes a "VAR" type variable from the environment.
    //* =====================================================================
    std::vector<telnetpp::token> delete_variable(std::string const &name);

    //* =====================================================================
    /// \brief Sets a "USERVAR" type variable in the environment.
    //* =====================================================================
    std::vector<telnetpp::token> set_user_variable(
        std::string const &name, std::string const &value);

    //* =====================================================================
    /// \brief Deletes a "USERVAR" type variable from the environment.
    //* =====================================================================
    std::vector<telnetpp::token> delete_user_variable(std::string const &name);

private :
    //* =====================================================================
    /// \brief Handle a negotiation that has been received in the active
    /// state.
    //* =====================================================================
    std::vector<telnetpp::token> handle_subnegotiation(u8stream const &content);

    std::map<std::string, std::string> variables_;
    std::map<std::string, std::string> user_variables_;
};

}}}

max_stars_repo_name: CalielOfSeptem/septem

max_issues_repo_name: HoraceWeebler/septem

max_forks_repo_name: HoraceWeebler/septem


text:
//
// sp_constexpr_test2.cpp
//
// Copyright 2017 Peter Dimov
//
// 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/config.hpp>
#include <boost/detail/workaround.hpp>

#define HAVE_CONSTEXPR_INIT

#if defined( BOOST_NO_CXX11_CONSTEXPR )
# undef HAVE_CONSTEXPR_INIT
#endif

#if BOOST_WORKAROUND( BOOST_MSVC, < 1920 )
# undef HAVE_CONSTEXPR_INIT
#endif

#if defined(__clang__) && defined( BOOST_NO_CXX14_CONSTEXPR )
# undef HAVE_CONSTEXPR_INIT
#endif

#if !defined( HAVE_CONSTEXPR_INIT )

int main()
{
}

#else

#include <boost/shared_ptr.hpp>
#include <boost/weak_ptr.hpp>
#include <boost/enable_shared_from_this.hpp>
#include <boost/core/lightweight_test.hpp>

struct X: public boost::enable_shared_from_this<X>
{
    int v_;

    constexpr X() BOOST_NOEXCEPT: v_( 1 )
    {
    }
};

struct Z
{
    Z();
};

static Z z;
static X x;

Z::Z()
{
    BOOST_TEST_EQ( x.v_, 1 );
}

int main()
{
    return boost::report_errors();
}

#endif // #if defined( BOOST_NO_CXX11_CONSEXPR )

ext: cpp


text:
/*
 * \file DQMEventInfo.h
 *
 * \author M. Zanetti - INFN Padova
 *
*/
#include <DQMServices/Core/interface/DQMOneEDAnalyzer.h>

#include "FWCore/Framework/interface/LuminosityBlock.h"
#include "FWCore/Version/interface/GetReleaseVersion.h"
#include <FWCore/Framework/interface/Event.h>
#include <FWCore/Framework/interface/Run.h>
#include <FWCore/Framework/interface/MakerMacros.h>
#include <FWCore/ParameterSet/interface/ParameterSet.h>

#include <algorithm>
#include <iostream>
#include <sstream>
#include <fstream>
#include <string>
#include <vector>
#include <memory>
#include <cstdio>
#include <cmath>
#include <map>

#include <sys/time.h>
#include <TSystem.h>

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

class DQMEventInfo : public DQMOneEDAnalyzer<> {
public:
  /// Constructor
  DQMEventInfo(const edm::ParameterSet& ps);

  /// Destructor
  ~DQMEventInfo() override;

protected:
  /// Analyze
  void analyze(const edm::Event& e, const edm::EventSetup& c) override;
  void bookHistograms(DQMStore::IBooker&, edm::Run const&, edm::EventSetup const&) override;

private:
  std::string eventInfoFolder_;
  std::string subsystemname_;

  double currentTime_, lastUpdateTime_, lastAvgTime_;
  double runStartTime_;
  double evtRateWindow_;
  int64_t evtRateCount_;
  int64_t pEvent_;

  //////////////////////////////////////////////////////////////////
  ///These MEs are filled with the info from the most recent event
  ///   by the module
  //////////////////////////////////////////////////////////////////
  MonitorElement* runId_;
  MonitorElement* runStartTimeStamp_;  ///UTC time of the run start
  MonitorElement* eventId_;
  MonitorElement* lumisecId_;
  MonitorElement* eventTimeStamp_;

  //////////////////////////////////////////////////////////////////
  ///These MEs are either static or updated upon each analyze() call
  //////////////////////////////////////////////////////////////////
  MonitorElement* nUpdates_;               ///Number of collector updates (TBD)
  MonitorElement* processId_;              ///The PID associated with this job
  MonitorElement* processStartTimeStamp_;  ///The UTC time of the first event processed
  MonitorElement* processTimeStamp_;       ///The UTC time of the last event
  MonitorElement* processLatency_;         ///Time elapsed since the last event
  MonitorElement* processEventRate_;       ///Avg # of events in programmable window (default: 5 min)
  MonitorElement* processEvents_;          ///# of event processed so far
  MonitorElement* hostName_;               ///Hostname of the local machine
  MonitorElement* processName_;            ///DQM "name" of the job (eg, Hcal or DT)
  MonitorElement* workingDir_;             ///Current working directory of the job
  MonitorElement* cmsswVer_;               ///CMSSW version run for this job
  MonitorElement* dqmPatch_;               ///DQM patch version for this job
  MonitorElement* errSummary_;             ///Subdetector-specific error summary (float)
  MonitorElement* errSummaryEtaPhi_;       ///Subdetector-specific etaPhi summary (float)
  MonitorElement* errSummarySegment_[10];
};

static inline double stampToReal(edm::Timestamp time) {
  return (time.value() >> 32) + 1e-6 * (time.value() & 0xffffffff);
}

static inline double stampToReal(const timeval& time) { return time.tv_sec + 1e-6 * time.tv_usec; }

DQMEventInfo::DQMEventInfo(const edm::ParameterSet& ps) {
  struct timeval now;
  gettimeofday(&now, nullptr);

  pEvent_ = 0;
  evtRateCount_ = 0;
  lastAvgTime_ = currentTime_ = stampToReal(now);

  // read config parms
  std::string folder = ps.getUntrackedParameter<std::string>("eventInfoFolder", "EventInfo");
  subsystemname_ = ps.getUntrackedParameter<std::string>("subSystemFolder", "YourSubsystem");

  eventInfoFolder_ = subsystemname_ + "/" + folder;
  evtRateWindow_ = ps.getUntrackedParameter<double>("eventRateWindow", 0.5);
  if (evtRateWindow_ <= 0.15)
    evtRateWindow_ = 0.15;
}

DQMEventInfo::~DQMEventInfo() = default;

void DQMEventInfo::bookHistograms(DQMStore::IBooker& ibooker,
                                  edm::Run const& iRun,
                                  edm::EventSetup const& /* iSetup */) {
  ibooker.setCurrentFolder(eventInfoFolder_);

  //Event specific contents
  runId_ = ibooker.bookInt("iRun");
  runId_->Fill(iRun.id().run());
  lumisecId_ = ibooker.bookInt("iLumiSection");
  lumisecId_->Fill(-1);
  eventId_ = ibooker.bookInt("iEvent");
  eventId_->Fill(-1);
  eventTimeStamp_ = ibooker.bookFloat("eventTimeStamp");

  ibooker.setCurrentFolder(eventInfoFolder_);
  //Process specific contents
  processTimeStamp_ = ibooker.bookFloat("processTimeStamp");
  processTimeStamp_->Fill(currentTime_);
  processLatency_ = ibooker.bookFloat("processLatency");
  processTimeStamp_->Fill(-1);
  processEvents_ = ibooker.bookInt("processedEvents");
  processEvents_->Fill(pEvent_);
  processEventRate_ = ibooker.bookFloat("processEventRate");
  processEventRate_->Fill(-1);
  nUpdates_ = ibooker.bookInt("processUpdates");
  nUpdates_->Fill(-1);

  //Static Contents
  processId_ = ibooker.bookInt("processID");
  processId_->Fill(getpid());
  processStartTimeStamp_ = ibooker.bookFloat("processStartTimeStamp");
  processStartTimeStamp_->Fill(currentTime_);
  runStartTimeStamp_ = ibooker.bookFloat("runStartTimeStamp");
  runStartTimeStamp_->Fill(stampToReal(iRun.beginTime()));
  char hostname[65];
  gethostname(hostname, 64);
  hostname[64] = 0;
  hostName_ = ibooker.bookString("hostName", hostname);
  processName_ = ibooker.bookString("processName", subsystemname_);
  char* pwd = getcwd(nullptr, 0);
  workingDir_ = ibooker.bookString("workingDir", pwd);
  free(pwd);
  cmsswVer_ = ibooker.bookString("CMSSW_Version", edm::getReleaseVersion());

  // Folder to be populated by sub-systems' code
  std::string subfolder = eventInfoFolder_ + "/reportSummaryContents";
  ibooker.setCurrentFolder(subfolder);

  //Online static histograms
  const edm::ParameterSet& sourcePSet =
      edm::getProcessParameterSetContainingModule(moduleDescription()).getParameterSet("@main_input");

  if (sourcePSet.getParameter<std::string>("@module_type") == "DQMStreamerReader") {
    std::string evSelection;
    std::vector<std::string> evSelectionList;
    std::string delimiter(", ");
    evSelectionList = sourcePSet.getUntrackedParameter<std::vector<std::string> >("SelectEvents");
    // add single quotes inline in the vector of HLT paths:
    // we do copy assignment, and getUntrackedParameter returns
    // a by-value copy of the vector of strings
    std::for_each(evSelectionList.begin(), evSelectionList.end(), [](std::string& s) {
      std::string squote("'");
      s = squote + s + squote;
    });
    evSelection = boost::algorithm::join(evSelectionList, delimiter);
    // if no HLT paths are specified, no selections are performed:
    // we mark this with an asterisk.
    if (evSelection.empty()) {
      evSelection = std::string("'*'");
    }
    ibooker.setCurrentFolder(eventInfoFolder_);
    ibooker.bookString("eventSelection", evSelection);
  }
}

void DQMEventInfo::analyze(const edm::Event& e, const edm::EventSetup& c) {
  //Filling lumi here guarantees that the lumi number corresponds to the event when
  // using multiple concurrent lumis in a job
  lumisecId_->Fill(e.id().luminosityBlock());
  eventId_->Fill(e.id().event());  // Handing edm::EventNumber_t to Fill method which will handle further casting
  eventTimeStamp_->Fill(stampToReal(e.time()));

  pEvent_++;
  evtRateCount_++;
  processEvents_->Fill(pEvent_);

  struct timeval now;
  gettimeofday(&now, nullptr);
  lastUpdateTime_ = currentTime_;
  currentTime_ = stampToReal(now);

  processTimeStamp_->Fill(currentTime_);
  processLatency_->Fill(currentTime_ - lastUpdateTime_);

  double delta = currentTime_ - lastAvgTime_;
  if (delta >= (evtRateWindow_ * 60.0)) {
    processEventRate_->Fill(evtRateCount_ / delta);
    evtRateCount_ = 0;
    lastAvgTime_ = currentTime_;
  }

  return;
}

#include "FWCore/Framework/interface/MakerMacros.h"
DEFINE_FWK_MODULE(DQMEventInfo);

ext: cc

max_stars_repo_name: PKUfudawei/cmssw

max_issues_repo_name: PKUfudawei/cmssw

max_forks_repo_name: PKUfudawei/cmssw


text:
/* Siconos is a program dedicated to modeling, simulation and control
 * of non smooth dynamical systems.
 *
 * Copyright 2021 INRIA.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
*/

#ifndef SiconosPointers_hpp
#define SiconosPointers_hpp

/*! \file SiconosPointers.hpp
  Siconos interface to reference-counting pointers

 Siconos pointers are reference counting pointers. Memory pointed by a
 Siconos pointer is automaticaly deallocated.

 Basic usage :

 - to declare a Siconos pointer on a Siconos Object:

 \verbatim
 SP::<Siconos Object> myobject;
 \endverbatim

 - to set a Siconos pointer :

 \verbatim
 myobject.reset(new <Siconos Object>(...));
 \endverbatim

Siconos pointers are boost smart pointers.

More documentation on smart pointers and reference counting:

 - http://en.wikipedia.org/wiki/Smart_pointer

 - http://en.wikipedia.org/wiki/Reference_counting

 - http://www.boost.org/doc/libs/release/libs/smart_ptr

 */

#include <memory> // Def of std::shared_ptr

// boost shared_arrays : at the time required
// only in HEM5 and LSodar
#include <boost/shared_array.hpp>

namespace SP {}
namespace SPC {}
namespace SA {}

/** \namespace SP Namespace for Siconos smart pointers : memory
    pointed by a Siconos smart pointers is automaticaly
    deallocated */
namespace SharedPointer = SP;

/** \namespace SA Namespace for Siconos shared arrays : Siconos shared
    arrays are automaticaly deallocated */
namespace SharedArray = SA;

/** \namespace SPC Namespace for const shared pointers : memory
    pointed by a const shared pointers is automaticaly deallocated */
namespace SharedPointerConst = SPC;

/** Using a shared_ptr to hold a pointer to a statically allocated
   object
   use create<type>SPtr(<type> &x)
   cf http://www.boost.org/doc/
*/
struct nullDeleter
{
  void operator()(void const *) const {}
};

/* template namespace : no */

#define NAME_SPACE_SPTR(X) \
  namespace SP \
  { \
    typedef SPtr##X X; \
  } \
  namespace SPC \
  { \
    typedef SPtrConst##X X;\
  }

#define NAME_SPACE_SAPTR(X)                     \
  namespace SA \
  { \
    typedef X##SAPtr X; \
  }

/* template typedef : no */

#define TYPEDEF_SPTR(X) \
  typedef std::shared_ptr<X> SPtr##X; \
  typedef std::shared_ptr<const X> SPtrConst##X; \
  inline SPtr##X create##SPtr##X(X &x) \
  { \
    std::shared_ptr<X> px(&x, nullDeleter()); \
    return px; \
  } \
  inline SPtrConst##X create##SPtrConst##X(const X &x) \
  { \
    std::shared_ptr<const X> px(&x, nullDeleter()); \
    return px; \
  } \
  NAME_SPACE_SPTR(X)

#define TYPEDEF_SAPTR(X)                        \
  typedef boost::shared_array<X> X##SAPtr ;     \
  NAME_SPACE_SAPTR(X)

#define DEFINE_SPTR(X)                          \
  class X; \
  TYPEDEF_SPTR(X)

#define DEFINE_SPTR_STRUCT(X) \
  struct X; \
  TYPEDEF_SPTR(X)

#define DEFINE_SAPTR(X) \
  class X; \
  TYPEDEF_SAPTR(X)

/* template with one argument */

#define NAME_SPACE_TPL1_SPTR(N,X,Y)              \
  namespace SP                                   \
  {                                              \
    typedef SPtr##N N;                           \
  }                                              \
  namespace SPC                                  \
  {                                              \
    typedef SPtrConst##N N;                      \
  }

#define TYPEDEF_TPL1_SPTR(N,X,Y)                           \
  typedef std::shared_ptr<X<Y> > SPtr##N;                \
  typedef std::shared_ptr<const X<Y> > SPtrConst##N;     \
  inline SPtr##N create##SPtr##N(X<Y> &x)                  \
  {                                                        \
    std::shared_ptr<X<Y> > px(&x, nullDeleter());        \
    return px;                                             \
  }                                                        \
  inline SPtrConst##N create##SPtrConst##N(const X<Y> &x)  \
  {                                                        \
    std::shared_ptr<const X<Y> > px(&x, nullDeleter());  \
    return px;                                             \
  }                                                        \
  NAME_SPACE_TPL1_SPTR(N,X,Y)

#endif /* SiconosPointers_hpp */

max_stars_repo_name: BuildJet/siconos

max_issues_repo_name: BuildJet/siconos

max_forks_repo_name: BuildJet/siconos


text:
/*
	This file is part of solidity.

	solidity is free software: you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation, either version 3 of the License, or
	(at your option) any later version.

	solidity is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with solidity.  If not, see <http://www.gnu.org/licenses/>.
*/

#include <test/yulPhaser/TestHelpers.h>

#include <tools/yulPhaser/SimulationRNG.h>

#include <boost/test/unit_test.hpp>

#include <cassert>

using namespace std;

namespace solidity::phaser::test
{

BOOST_AUTO_TEST_SUITE(Phaser)
BOOST_AUTO_TEST_SUITE(RandomTest)

BOOST_AUTO_TEST_CASE(bernoulliTrial_should_produce_samples_with_right_expected_value_and_variance)
{
	SimulationRNG::reset(1);
	constexpr size_t numSamples = 10000;
	constexpr double successProbability = 0.4;
	constexpr double relativeTolerance = 0.05;

	// For bernoulli distribution with success probability p: EX = p, VarX = p(1 - p)
	constexpr double expectedValue = successProbability;
	constexpr double variance = successProbability * (1 - successProbability);

	vector<uint32_t> samples;
	for (uint32_t i = 0; i < numSamples; ++i)
		samples.push_back(static_cast<uint32_t>(SimulationRNG::bernoulliTrial(successProbability)));

	BOOST_TEST(abs(mean(samples) - expectedValue) < expectedValue * relativeTolerance);
	BOOST_TEST(abs(meanSquaredError(samples, expectedValue) - variance) < variance * relativeTolerance);
}

BOOST_AUTO_TEST_CASE(bernoulliTrial_can_be_reset)
{
	constexpr size_t numSamples = 10;
	constexpr double successProbability = 0.4;

	SimulationRNG::reset(1);
	vector<uint32_t> samples1;
	for (uint32_t i = 0; i < numSamples; ++i)
		samples1.push_back(static_cast<uint32_t>(SimulationRNG::bernoulliTrial(successProbability)));

	vector<uint32_t> samples2;
	for (uint32_t i = 0; i < numSamples; ++i)
		samples2.push_back(static_cast<uint32_t>(SimulationRNG::bernoulliTrial(successProbability)));

	SimulationRNG::reset(1);
	vector<uint32_t> samples3;
	for (uint32_t i = 0; i < numSamples; ++i)
		samples3.push_back(static_cast<uint32_t>(SimulationRNG::bernoulliTrial(successProbability)));

	SimulationRNG::reset(2);
	vector<uint32_t> samples4;
	for (uint32_t i = 0; i < numSamples; ++i)
		samples4.push_back(static_cast<uint32_t>(SimulationRNG::bernoulliTrial(successProbability)));

	BOOST_TEST(samples1 != samples2);
	BOOST_TEST(samples1 == samples3);
	BOOST_TEST(samples1 != samples4);
	BOOST_TEST(samples2 != samples3);
	BOOST_TEST(samples2 != samples4);
	BOOST_TEST(samples3 != samples4);
}

BOOST_AUTO_TEST_CASE(uniformInt_returns_different_values_when_called_multiple_times)
{
	SimulationRNG::reset(1);
	constexpr size_t numSamples = 1000;
	constexpr uint32_t minValue = 50;
	constexpr uint32_t maxValue = 80;
	constexpr double relativeTolerance = 0.05;

	// For uniform distribution from range a..b: EX = (a + b) / 2, VarX = ((b - a + 1)^2 - 1) / 12
	constexpr double expectedValue = (minValue + maxValue) / 2.0;
	constexpr double variance = ((maxValue - minValue + 1) * (maxValue - minValue + 1) - 1) / 12.0;

	vector<uint32_t> samples;
	for (uint32_t i = 0; i < numSamples; ++i)
		samples.push_back(SimulationRNG::uniformInt(minValue, maxValue));

	BOOST_TEST(abs(mean(samples) - expectedValue) < expectedValue * relativeTolerance);
	BOOST_TEST(abs(meanSquaredError(samples, expectedValue) - variance) < variance * relativeTolerance);
}

BOOST_AUTO_TEST_CASE(uniformInt_can_be_reset)
{
	constexpr size_t numSamples = 10;
	constexpr uint32_t minValue = 50;
	constexpr uint32_t maxValue = 80;

	SimulationRNG::reset(1);
	vector<uint32_t> samples1;
	for (uint32_t i = 0; i < numSamples; ++i)
		samples1.push_back(SimulationRNG::uniformInt(minValue, maxValue));

	vector<uint32_t> samples2;
	for (uint32_t i = 0; i < numSamples; ++i)
		samples2.push_back(SimulationRNG::uniformInt(minValue, maxValue));

	SimulationRNG::reset(1);
	vector<uint32_t> samples3;
	for (uint32_t i = 0; i < numSamples; ++i)
		samples3.push_back(SimulationRNG::uniformInt(minValue, maxValue));

	SimulationRNG::reset(2);
	vector<uint32_t> samples4;
	for (uint32_t i = 0; i < numSamples; ++i)
		samples4.push_back(SimulationRNG::uniformInt(minValue, maxValue));

	BOOST_TEST(samples1 != samples2);
	BOOST_TEST(samples1 == samples3);
	BOOST_TEST(samples1 != samples4);
	BOOST_TEST(samples2 != samples3);
	BOOST_TEST(samples2 != samples4);
	BOOST_TEST(samples3 != samples4);
}

BOOST_AUTO_TEST_CASE(binomialInt_should_produce_samples_with_right_expected_value_and_variance)
{
	SimulationRNG::reset(1);
	constexpr size_t numSamples = 1000;
	constexpr uint32_t numTrials = 100;
	constexpr double successProbability = 0.2;
	constexpr double relativeTolerance = 0.05;

	// For binomial distribution with n trials and success probability p: EX = np, VarX = np(1 - p)
	constexpr double expectedValue = numTrials * successProbability;
	constexpr double variance = numTrials * successProbability * (1 - successProbability);

	vector<uint32_t> samples;
	for (uint32_t i = 0; i < numSamples; ++i)
		samples.push_back(SimulationRNG::binomialInt(numTrials, successProbability));

	BOOST_TEST(abs(mean(samples) - expectedValue) < expectedValue * relativeTolerance);
	BOOST_TEST(abs(meanSquaredError(samples, expectedValue) - variance) < variance * relativeTolerance);
}

BOOST_AUTO_TEST_CASE(binomialInt_can_be_reset)
{
	constexpr size_t numSamples = 10;
	constexpr uint32_t numTrials = 10;
	constexpr double successProbability = 0.6;

	SimulationRNG::reset(1);
	vector<uint32_t> samples1;
	for (uint32_t i = 0; i < numSamples; ++i)
		samples1.push_back(SimulationRNG::binomialInt(numTrials, successProbability));

	vector<uint32_t> samples2;
	for (uint32_t i = 0; i < numSamples; ++i)
		samples2.push_back(SimulationRNG::binomialInt(numTrials, successProbability));

	SimulationRNG::reset(1);
	vector<uint32_t> samples3;
	for (uint32_t i = 0; i < numSamples; ++i)
		samples3.push_back(SimulationRNG::binomialInt(numTrials, successProbability));

	SimulationRNG::reset(2);
	vector<uint32_t> samples4;
	for (uint32_t i = 0; i < numSamples; ++i)
		samples4.push_back(SimulationRNG::binomialInt(numTrials, successProbability));

	BOOST_TEST(samples1 != samples2);
	BOOST_TEST(samples1 == samples3);
	BOOST_TEST(samples1 != samples4);
	BOOST_TEST(samples2 != samples3);
	BOOST_TEST(samples2 != samples4);
	BOOST_TEST(samples3 != samples4);
}

BOOST_AUTO_TEST_SUITE_END()
BOOST_AUTO_TEST_SUITE_END()

}

max_stars_repo_name: MrChico/solidity

max_issues_repo_name: MrChico/solidity


text:
#include <boost/version.hpp>
#include <iostream>
#include <iomanip>

int main()
{
	std::cout << "Boost version: "
		<< BOOST_VERSION / 100000
		<< "."
		<< BOOST_VERSION / 100 % 1000
		<< "."
		<< BOOST_VERSION % 100
		<< std::endl;
	return 0;
}

max_stars_repo_name: khairulislam/phys

max_issues_repo_name: khairulislam/phys

max_forks_repo_name: khairulislam/phys


text:
/*
    Copyright 2013 Adobe
    Distributed under the Boost Software License, Version 1.0.
    (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*/
/**************************************************************************************************/

#ifndef ADOBE_ALGORITHM_FIND_HPP
#define ADOBE_ALGORITHM_FIND_HPP

#include <adobe/config.hpp>

#include <algorithm>
#include <functional>
#include <utility>

#include <boost/next_prior.hpp>
#include <boost/range/begin.hpp>
#include <boost/range/end.hpp>

/**************************************************************************************************/

namespace adobe {

/**************************************************************************************************/
/*!
\defgroup find find
\ingroup non_mutating_algorithm

\see
    - STL documentation for \ref stldoc_find
    - STL documentation for \ref stldoc_find_if
    - STL documentation for \ref stldoc_find_end
    - STL documentation for \ref stldoc_find_first_of
    - STL documentation for \ref stldoc_adjacent_find
*/

/**************************************************************************************************/

/*!
\defgroup find_not find_not
\ingroup find

\c find_not is similar to \c find, except \c find_not will return the first iterator
\c i in the range [first, last) for which \c *i is not equal to \c value. Returns \c
last if no such iterator exists.

\requirements
    - Same as for find_if

\complexity
    - Same as for find_if
*/

/**************************************************************************************************/

/**************************************************************************************************/
/*!
\defgroup find_if_not find_if_not
\ingroup find

\c find_if_not is similar to \c find_if, except \c find_if_not will return the first
iterator \c i in the range [first, last) for which \c pred(*i) is \c false.
Returns \c last if no such iterator exists.

\requirements
    - Same as for find_if

\complexity
    - Same as for find_if
*/
/**************************************************************************************************/
/*!
    \ingroup find_if_not

    \brief find_if_not implementation
*/
template <class InputIterator, class Predicate>
inline InputIterator find_if_not(InputIterator first, InputIterator last, Predicate pred) {
    return std::find_if_not(first, last, std::bind(pred, std::placeholders::_1));
}

/*!
    \ingroup find_if_not

    \brief find_if_not implementation
*/
template <class InputRange, class Predicate>
inline typename boost::range_iterator<InputRange>::type find_if_not(InputRange& range,
                                                                    Predicate pred) {
    return adobe::find_if_not(boost::begin(range), boost::end(range), pred);
}

/*!
    \ingroup find_if_not

    \brief find_if_not implementation
*/
template <class InputRange, class Predicate>
inline typename boost::range_const_iterator<InputRange>::type find_if_not(const InputRange& range,
                                                                          Predicate pred) {
    return adobe::find_if_not(boost::begin(range), boost::end(range), pred);
}

/**************************************************************************************************/

/*!
    \ingroup find_not
*/
template <class InputIterator, class T>
inline InputIterator find_not(InputIterator first, InputIterator last, const T& value) {
    return std::find_if_not(first, last,
                            std::bind(std::equal_to<T>(), value, std::placeholders::_1));
}

/*!
    \ingroup find_not

    \brief find_not implementation
*/
template <class InputRange, class T>
inline typename boost::range_iterator<InputRange>::type find_not(InputRange& range,
                                                                 const T& value) {
    return adobe::find_not(boost::begin(range), boost::end(range), value);
}

/*!
    \ingroup find_not

    \brief find_not implementation
*/
template <class InputRange, class T>
inline typename boost::range_const_iterator<InputRange>::type find_not(const InputRange& range,
                                                                       const T& value) {
    return adobe::find_not(boost::begin(range), boost::end(range), value);
}

/*!
    \ingroup find
    \brief find implementation
*/
template <class InputRange, class T>
inline typename boost::range_iterator<InputRange>::type find(InputRange& range, const T& value) {
    return std::find(boost::begin(range), boost::end(range), value);
}

/*!
    \ingroup find

    \brief find implementation
*/
template <class InputRange, class T>
inline typename boost::range_const_iterator<InputRange>::type find(const InputRange& range,
                                                                   const T& value) {
    return std::find(boost::begin(range), boost::end(range), value);
}

/*!
    \ingroup find

    \brief find implementation
*/
template <class InputIterator, class Predicate>
inline InputIterator find_if(InputIterator first, InputIterator last, Predicate pred) {
    return std::find_if(first, last, std::bind(pred, std::placeholders::_1));
}

/*!
    \ingroup find

    \brief find implementation
*/
template <class InputRange, class Predicate>
inline typename boost::range_iterator<InputRange>::type find_if(InputRange& range, Predicate pred) {
    return adobe::find_if(boost::begin(range), boost::end(range), pred);
}

/*!
    \ingroup find

    \brief find implementation
*/
template <class InputRange, class Predicate>
inline typename boost::range_const_iterator<InputRange>::type find_if(const InputRange& range,
                                                                      Predicate pred) {
    return adobe::find_if(boost::begin(range), boost::end(range), pred);
}

/*!
    \ingroup find
*/

template <typename I, // I models ForwardIterator
          typename T>
// T is value_type(I)
std::pair find_range(I f, I l, const T& x) {
    f = std::find(f, l, x);
    if (f != l)
        l = find_not(boost::next(f), l, x);
    return std::make_pair(f, l);
}

/*!
    \ingroup find
*/

template <typename I, // I models ForwardIterator
          typename P>
// P models UnaryPredicate(value_type(I))
std::pair find_range_if(I f, I l, P p) {
    f = adobe::find_if(f, l, p);
    if (f != l)
        l = adobe::find_if_not(boost::next(f), l, p);
    return std::make_pair(f, l);
}

/*!
    \ingroup find

    \brief find implementation
*/
template <class ForwardRange1, class ForwardRange2>
inline typename boost::range_iterator<ForwardRange1>::type find_end(ForwardRange1& range1,
                                                                    const ForwardRange2& range2) {
    return std::find_end(boost::begin(range1), boost::end(range1), boost::begin(range2),
                         boost::end(range2));
}

/*!
    \ingroup find

    \brief find implementation
*/
template <class ForwardRange1, class ForwardRange2>
inline typename boost::range_const_iterator<ForwardRange1>::type
find_end(const ForwardRange1& range1, const ForwardRange2& range2) {
    return std::find_end(boost::begin(range1), boost::end(range1), boost::begin(range2),
                         boost::end(range2));
}

/*!
    \ingroup find

    \brief find implementation
*/
template <class ForwardIterator1, class ForwardIterator2, class BinaryPredicate>
inline ForwardIterator1 find_end(ForwardIterator1 first1, ForwardIterator1 last1,
                                 ForwardIterator2 first2, ForwardIterator2 last2,
                                 BinaryPredicate comp) {
    return std::find_end(first1, last1, first2, last2,
                         std::bind(comp, std::placeholders::_1, std::placeholders::_2));
}

/*!
    \ingroup find

    \brief find implementation
*/
template <class ForwardRange1, class ForwardRange2, class BinaryPredicate>
inline typename boost::range_iterator<ForwardRange1>::type
find_end(ForwardRange1& range1, const ForwardRange2& range2, BinaryPredicate comp) {
    return adobe::find_end(boost::begin(range1), boost::end(range1), boost::begin(range2),
                           boost::end(range2), comp);
}

/*!
    \ingroup find

    \brief find implementation
*/
template <class ForwardRange1, class ForwardRange2, class BinaryPredicate>
inline typename boost::range_const_iterator<ForwardRange1>::type
find_end(const ForwardRange1& range1, const ForwardRange2& range2, BinaryPredicate comp) {
    return adobe::find_end(boost::begin(range1), boost::end(range1), boost::begin(range2),
                           boost::end(range2), comp);
}

#if 0

// find_first_of is a bad algorithm. Use find_first_of_set until we provide a better predicate.

/*!
    \ingroup find

    \brief find implementation
*/
template <class InputRange, class ForwardRange>
inline typename boost::range_iterator<InputRange>::type
find_first_of(InputRange& range1, const ForwardRange& range2)
{
    return std::find_first_of(boost::begin(range1), boost::end(range1),
                              boost::begin(range2), boost::end(range2));
}

/*!
    \ingroup find

    \brief find implementation
*/
template <class InputRange, class ForwardRange>
inline typename boost::range_const_iterator<InputRange>::type
find_first_of(const InputRange& range1, const ForwardRange& range2)
{
    return std::find_first_of(boost::begin(range1), boost::end(range1),
                              boost::begin(range2), boost::end(range2));
}

/*!
    \ingroup find

    \brief find implementation
*/
template <class InputIterator, class ForwardIterator, class BinaryPredicate>
inline InputIterator find_first_of(InputIterator first1, InputIterator last1,
                                   ForwardIterator first2, ForwardIterator last2,
                                   BinaryPredicate comp)

{
    return std::find_first_of(first1, last1, first2, last2, std::bind(comp, std::placeholders::_1, std::placeholders::_2));
}

/*!
    \ingroup find

    \brief find implementation
*/
template <class InputRange, class ForwardRange, class BinaryPredicate>
inline typename boost::range_iterator<InputRange>::type
find_first_of(InputRange& range1, const ForwardRange& range2, BinaryPredicate comp)
{
    return adobe::find_first_of(boost::begin(range1), boost::end(range1),
                                boost::begin(range2), boost::end(range2),
                                comp);
}

/*!
    \ingroup find

    \brief find implementation
*/
template <class InputRange, class ForwardRange, class BinaryPredicate>
inline typename boost::range_const_iterator<InputRange>::type
find_first_of(const InputRange& range1, const ForwardRange& range2, BinaryPredicate comp)
{
    return adobe::find_first_of(boost::begin(range1), boost::end(range1),
                                boost::begin(range2), boost::end(range2),
                                comp);
}

#endif

/*!
    \ingroup find

    \brief find implementation
*/
template <class ForwardRange>
inline typename boost::range_iterator<ForwardRange>::type adjacent_find(ForwardRange& range) {
    return std::adjacent_find(boost::begin(range), boost::end(range));
}

/*!
    \ingroup find

    \brief find implementation
*/
template <class ForwardRange>
inline typename boost::range_const_iterator<ForwardRange>::type
adjacent_find(const ForwardRange& range) {
    return std::adjacent_find(boost::begin(range), boost::end(range));
}

/*!
    \ingroup find

    \brief find implementation
*/
template <class ForwardIterator, class BinaryPredicate>
inline ForwardIterator adjacent_find(ForwardIterator first, ForwardIterator last,
                                     BinaryPredicate pred) {
    return std::adjacent_find(first, last,
                              std::bind(pred, std::placeholders::_1, std::placeholders::_2));
}

/*!
    \ingroup find

    \brief find implementation
*/
template <class ForwardRange, class BinaryPredicate>
inline typename boost::range_iterator<ForwardRange>::type adjacent_find(ForwardRange& range,
                                                                        BinaryPredicate pred) {
    return adobe::adjacent_find(boost::begin(range), boost::end(range), pred);
}

/*!
    \ingroup find

    \brief find implementation
*/
template <class ForwardRange, class BinaryPredicate>
inline typename boost::range_const_iterator<ForwardRange>::type
adjacent_find(const ForwardRange& range, BinaryPredicate pred) {
    return adobe::adjacent_find(boost::begin(range), boost::end(range), pred);
}

/**************************************************************************************************/

} // namespace adobe

/**************************************************************************************************/

#endif

/**************************************************************************************************/


text:
#include <cassert>
#include <cmath>
#include <algorithm>
#include <boost/functional/hash.hpp>

#include "fin.hh"

using namespace std;

Fin::Fin( const Fin & other )
  : Action( other ),
    _lambda( other._lambda )
{
}

Fin::Fin( const RemyBuffers::Fin & dna )
  : Action ( dna.domain() ),
    _lambda( dna.lambda() )
{
}

RemyBuffers::Fin Fin::DNA( void ) const
{
  RemyBuffers::Fin ret;

  ret.set_lambda( _lambda );
  ret.mutable_domain()->CopyFrom( _domain.DNA() );

  return ret;
}

vector< Fin > Fin::next_generation( void ) const
{
  vector< Fin> ret;

  auto lambda_alternatives = get_optimizer().lambda.alternatives( _lambda, true );

  printf("Alternatives: lambda %f to %f\n",
         *(min_element(lambda_alternatives.begin(), lambda_alternatives.end())),
         *(max_element(lambda_alternatives.begin(), lambda_alternatives.end()))
  );

  for ( const auto & alt_lambda : lambda_alternatives ) {
        Fin new_fin{ *this };
        new_fin._generation++;

        new_fin._lambda = alt_lambda;
        new_fin.round();

        ret.push_back( new_fin );
  }

  return ret;
}

string Fin::str( const unsigned int total ) const
{
  char tmp[ 256 ];
  snprintf( tmp, 256, "{%s} gen=%u usage=%.4f => (lambda=%f)",
            _domain.str().c_str(), _generation, double( _domain.count() ) / double( total ), _lambda );
  return tmp;
}

void Fin::round( void )
{
  _lambda = (1.0/10000.0) * int( 10000 * _lambda );
}

size_t hash_value( const Fin & fin )
{
  size_t seed = 0;
  boost::hash_combine( seed, fin._lambda );
  boost::hash_combine( seed, fin._domain );

  return seed;
}

max_stars_repo_name: CN-TU/remy

max_issues_repo_name: CN-TU/remy

max_forks_repo_name: CN-TU/remy


text:
/*
  Copyright (c) 2015 DataStax

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

  http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
*/

#define BOOST_TEST_DYN_LINK
#ifdef STAND_ALONE
#   define BOOST_TEST_MODULE cassandra
#endif

#include "address.hpp"
#include "md5.hpp"
#include "murmur3.hpp"
#include "token_map.hpp"

#include <boost/scoped_ptr.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/multiprecision/cpp_int.hpp>
#include <boost/test/unit_test.hpp>
#include <boost/random/mersenne_twister.hpp>

#include <limits>

cass::SharedRefPtr<cass::Host> create_host(const std::string& ip) {
  return cass::SharedRefPtr<cass::Host>(new cass::Host(cass::Address(ip, 4092), false));
}

template <class HashType>
struct TestTokenMap {
  typedef HashType(HashFunc)(const std::string& s);
  typedef std::map<HashType, cass::SharedRefPtr<cass::Host> > TokenHostMap;

  TokenHostMap tokens;
  cass::TokenMap token_map;
  cass::SharedRefPtr<cass::ReplicationStrategy> strategy;

  void build(const std::string& partitioner,
             const std::string& ks_name) {
    token_map.set_partitioner(partitioner);

    if (!strategy) {
      strategy =  cass::SharedRefPtr<cass::ReplicationStrategy>(
                    new cass::NonReplicatedStrategy(""));
    }

    token_map.set_replication_strategy(ks_name, strategy);

    for (typename TokenHostMap::iterator i = tokens.begin(); i != tokens.end(); ++i) {
      cass::TokenStringList tokens;
      tokens.push_back(boost::lexical_cast<std::string>(i->first));
      token_map.update_host(i->second, tokens);
    }

    token_map.build();
  }

  void verify(HashFunc hash_func, const std::string& ks_name) {
    for (int i = 0; i < 24; ++i) {
      std::string value(1, 'a' + i);
      const cass::CopyOnWriteHostVec& replicas
          = token_map.get_replicas(ks_name, value);

      HashType hash = hash_func(value);
      typename TokenHostMap::iterator token = tokens.upper_bound(hash);

      if (token != tokens.end()) {
        BOOST_CHECK(replicas->front() == token->second);
      } else {
        BOOST_CHECK(replicas->front() == tokens.begin()->second);
      }
    }
  }
};

BOOST_AUTO_TEST_SUITE(token_map)

int64_t murmur3_hash(const std::string& s) {
  return cass::MurmurHash3_x64_128(s.data(), s.size(), 0);
}

BOOST_AUTO_TEST_CASE(murmur3)
{
  TestTokenMap<int64_t> test_murmur3;

  test_murmur3.tokens[std::numeric_limits<int64_t>::min() / 2] = create_host("1.0.0.1");
  test_murmur3.tokens[0] = create_host("1.0.0.2");
  test_murmur3.tokens[std::numeric_limits<int64_t>::max() / 2] = create_host("1.0.0.3");
  // Anything greater than the last host should be wrapped around to host1

  test_murmur3.build(cass::Murmur3Partitioner::PARTITIONER_CLASS, "test");
  test_murmur3.verify(murmur3_hash, "test");
}

BOOST_AUTO_TEST_CASE(murmur3_multiple_tokens_per_host)
{
  TestTokenMap<int64_t> test_murmur3;

  const size_t tokens_per_host = 256;

  cass::HostVec hosts;
  hosts.push_back(create_host("1.0.0.1"));
  hosts.push_back(create_host("1.0.0.2"));
  hosts.push_back(create_host("1.0.0.3"));
  hosts.push_back(create_host("1.0.0.4"));

  boost::mt19937_64 ng;

  for (cass::HostVec::iterator i = hosts.begin(); i != hosts.end(); ++i) {
    for (size_t j = 0; j < tokens_per_host; ++j) {
      int64_t t = static_cast<int64_t>(ng());
      test_murmur3.tokens[t] = *i;
    }
  }

  test_murmur3.build(cass::Murmur3Partitioner::PARTITIONER_CLASS, "test");
  test_murmur3.verify(murmur3_hash, "test");
}

boost::multiprecision::int128_t random_hash(const std::string& s) {
  cass::Md5 m;
  m.update(reinterpret_cast<const uint8_t*>(s.data()), s.size());
  uint8_t h[16];
  m.final(h);
  std::string hex("0x");
  for (int i = 0; i < 16; ++i) {
    char buf[4];
    sprintf(buf, "%02X", h[i]);
    hex.append(buf);
  }
  return boost::multiprecision::int128_t(hex);
}

BOOST_AUTO_TEST_CASE(random)
{
  TestTokenMap<boost::multiprecision::int128_t> test_random;

  test_random.tokens[boost::multiprecision::int128_t("42535295865117307932921825928971026432")] = create_host("1.0.0.1");  // 2^127 / 4
  test_random.tokens[boost::multiprecision::int128_t("85070591730234615865843651857942052864")] = create_host("1.0.0.2");  // 2^127 / 2
  test_random.tokens[boost::multiprecision::int128_t("1605887595351923798765477786913079296")] = create_host("1.0.0.3"); // 2^127 * 3 / 4
  // Anything greater than the last host should be wrapped around to host1

  test_random.build(cass::RandomPartitioner::PARTITIONER_CLASS, "test");
  test_random.verify(random_hash, "test");
}

std::string byte_ordered_hash(const std::string& s) {
  return s;
}

BOOST_AUTO_TEST_CASE(byte_ordered)
{
  TestTokenMap<std::string> test_byte_ordered;

  test_byte_ordered.tokens["g"] = create_host("1.0.0.1");
  test_byte_ordered.tokens["m"] = create_host("1.0.0.2");
  test_byte_ordered.tokens["s"] = create_host("1.0.0.3");
  // Anything greater than the last host should be wrapped around to host1

  test_byte_ordered.build(cass::ByteOrderedPartitioner::PARTITIONER_CLASS, "test");
  test_byte_ordered.verify(byte_ordered_hash, "test");
}

BOOST_AUTO_TEST_CASE(remove_host)
{
  TestTokenMap<int64_t> test_remove_host;

  test_remove_host.strategy =
      cass::SharedRefPtr<cass::ReplicationStrategy>(new cass::SimpleStrategy("", 2));

  test_remove_host.tokens[std::numeric_limits<int64_t>::min() / 2] = create_host("1.0.0.1");
  test_remove_host.tokens[0] = create_host("1.0.0.2");
  test_remove_host.tokens[std::numeric_limits<int64_t>::max() / 2] = create_host("1.0.0.3");

  test_remove_host.build(cass::Murmur3Partitioner::PARTITIONER_CLASS, "test");

  cass::TokenMap& token_map = test_remove_host.token_map;

  {
    const cass::CopyOnWriteHostVec& replicas
        = token_map.get_replicas("test", "abc");

    BOOST_REQUIRE(replicas->size() == 2);
    BOOST_CHECK((*replicas)[0]->address() == cass::Address("1.0.0.1", 9042));
    BOOST_CHECK((*replicas)[1]->address() == cass::Address("1.0.0.2", 9042));
  }

  TestTokenMap<int64_t>::TokenHostMap::iterator host_to_remove_it = test_remove_host.tokens.begin();

  token_map.remove_host(host_to_remove_it->second);

  {
    const cass::CopyOnWriteHostVec& replicas
        = token_map.get_replicas("test", "abc");

    BOOST_REQUIRE(replicas->size() == 2);
    BOOST_CHECK((*replicas)[0]->address() == cass::Address("1.0.0.2", 9042));
    BOOST_CHECK((*replicas)[1]->address() == cass::Address("1.0.0.3", 9042));
  }

  ++host_to_remove_it;
  token_map.remove_host(host_to_remove_it->second);

  {
    const cass::CopyOnWriteHostVec& replicas
        = token_map.get_replicas("test", "abc");

    BOOST_REQUIRE(replicas->size() == 1);
    BOOST_CHECK((*replicas)[0]->address() == cass::Address("1.0.0.3", 9042));
  }

  ++host_to_remove_it;
  token_map.remove_host(host_to_remove_it->second);

  {
    const cass::CopyOnWriteHostVec& replicas = token_map.get_replicas("test", "abc");

    BOOST_REQUIRE(replicas->size() == 0);
  }
}

BOOST_AUTO_TEST_CASE(drop_keyspace)
{
  TestTokenMap<int64_t> test_drop_keyspace;

  test_drop_keyspace.strategy =
      cass::SharedRefPtr<cass::ReplicationStrategy>(new cass::SimpleStrategy("", 2));

  test_drop_keyspace.tokens[std::numeric_limits<int64_t>::min() / 2] = create_host("1.0.0.1");
  test_drop_keyspace.tokens[0] = create_host("1.0.0.2");
  test_drop_keyspace.tokens[std::numeric_limits<int64_t>::max() / 2] = create_host("1.0.0.3");

  test_drop_keyspace.build(cass::Murmur3Partitioner::PARTITIONER_CLASS, "test");

  cass::TokenMap& token_map = test_drop_keyspace.token_map;

  {
    const cass::CopyOnWriteHostVec& replicas
        = token_map.get_replicas("test", "abc");

    BOOST_REQUIRE(replicas->size() == 2);
    BOOST_CHECK((*replicas)[0]->address() == cass::Address("1.0.0.1", 9042));
    BOOST_CHECK((*replicas)[1]->address() == cass::Address("1.0.0.2", 9042));
  }

  token_map.drop_keyspace("test");

  {
    const cass::CopyOnWriteHostVec& replicas
        = token_map.get_replicas("test", "abc");

    BOOST_REQUIRE(replicas->size() == 0);
  }
}

BOOST_AUTO_TEST_SUITE_END()

max_stars_repo_name: planetbeing/cpp-driver

max_issues_repo_name: planetbeing/cpp-driver

max_forks_repo_name: planetbeing/cpp-driver


text:
#include "hash.h"
#include <boost/crc.hpp>
extern "C" {
    #include <librdkafka/rdmurmur2.h>
    #include <librdkafka/xxhash.h>
}

namespace flame::hash {

    template <typename INTEGER_TYPE>
    static php::string dec2hex(INTEGER_TYPE dec) {
        php::string hex(sizeof(INTEGER_TYPE) * 2);
        sprintf(hex.data(), "%0*lx", sizeof(INTEGER_TYPE) * 2, dec);
        return std::move(hex);
    }

    static php::value murmur2(php::parameters& params) {
        php::string data = params[0].to_string();
        std::uint32_t raw = rd_murmur2(data.c_str(), data.size());
        if (params.size() > 1 && params[1].to_boolean()) return raw;
        return dec2hex<std::uint32_t>(raw);
    }

    static php::value xxh64(php::parameters& params) {
        php::string data = params[0].to_string();
        unsigned long long seed = 0;
        if (params.size() > 1) {
            seed = params[1].to_integer();
        }
        std::uint64_t raw = XXH64(data.c_str(), data.size(), seed);
        if (params.size() > 2 && params[2].to_boolean()) return raw;
        return dec2hex<std::uint64_t>(raw);
    }

    static php::value crc64(php::parameters& params) {
        php::string data = params[0].to_string();
        boost::crc_optimal<64, 0x42F0E1EBA9EA3693, 0xFFFFFFFFFFFFFFFF, 0xFFFFFFFFFFFFFFFF, true, true>  crc64;
        crc64.process_bytes(data.c_str(), data.size());
        std::uint64_t raw = crc64.checksum();
        if (params.size() > 1 && params[1].to_boolean()) return raw;
        return dec2hex<std::uint64_t>(raw);
    }

    void declare(php::extension_entry &ext) {
        ext
            .function<murmur2>("flame\\hash\\murmur2", {
                {"data", php::TYPE::STRING},
            })
            .function<xxh64>("flame\\hash\\xxh64", {
                {"data", php::TYPE::STRING},
                {"seed", php::TYPE::INTEGER, false, true},
            })
            .function<crc64>("flame\\hash\\crc64", {
                {"data", php::TYPE::STRING},
            });
    }
}

max_stars_repo_name: terrywh/php-mill

max_issues_repo_name: terrywh/php-mill

max_forks_repo_name: terrywh/php-mill


text:
/*
 * Copyright (c) DTAI - KU Leuven – All rights reserved.
 * Proprietary, do not copy or distribute without permission.
 * Written by Pieter Robberechts, 2019
 */

#ifndef DECISIONTREE_CALCULATIONS_HPP
#define DECISIONTREE_CALCULATIONS_HPP

#include <tuple>
#include <vector>
#include <string>
#include <unordered_map>
#include <boost/timer/timer.hpp>
#include "Question.hpp"
#include "Utils.hpp"

using ClassCounter = std::unordered_map<std::string, int>;

namespace Calculations {

std::tuple<const std::vector<size_t>, const std::vector<size_t>> partition(const Data &data, const Question &q, const std::vector<size_t>& indexes); // changed so that it partitions indexes instead the data

const double gini(const ClassCounter& counts, double N);

std::tuple<const double, const Question> find_best_split(const Data &rows, const MetaData &meta, const std::vector<size_t>& indexes);

std::tuple<std::string, double> determine_best_threshold(const Data &data, int col, const std::vector<size_t>& indexes, const ClassCounter& counter);

const ClassCounter copy(const ClassCounter &counter); //used to make a copy of class counter

const ClassCounter empty(const ClassCounter &counter); // used to make an empty copy of class counter

const ClassCounter classCounts(const Data &data, const std::vector<size_t>& indexes);

} // namespace Calculations

#endif //DECISIONTREE_CALCULATIONS_HPP

max_stars_repo_name: ilovrencic/CART-Algorithm

max_issues_repo_name: ilovrencic/CART-Algorithm

max_forks_repo_name: ilovrencic/CART-Algorithm


text:
#ifndef UTILMM_SOCKET_HH
#define UTILMM_SOCKET_HH

#include <boost/noncopyable.hpp>
#include <string>
#include <vector>
#include <sys/types.h>
#include <stdint.h>

namespace utilmm
{
    /** Base class for sockets
     *
     * @ingroup system
     */
    class base_socket : boost::noncopyable
    {
    public:
	enum Domain { Unix, Inet };
	enum Type { Stream, Datagram };
	enum Wait { WaitRead = 1, WaitWrite = 2, WaitException = 4};

    private:
	static int to_unix(Domain d);
	static int to_unix(Type t);

	struct bad_address : public std::exception { };

	int	m_fd;
	Domain	m_domain;
	Type	m_type;

	int wait(int what, timeval* tv) const;

    protected:
	std::vector<uint8_t> to_sockaddr(std::string const& to) const;

    public:
	base_socket(int fd);
	base_socket(Domain domain, Type type);

	/** Closes the socket */
	~base_socket();

	/** Get the socket file descriptor */
	int fd() const;

	/** Non-blocking version of \c wait
	 *
	 * @param what an OR-ed field of values in the Wait enum
	 * @return true if the event was present and false otherwise
	 */
	bool try_wait(int what) const;

	/** Blocks until one of the specified events is detected on this socket
	 *
	 * @param what an OR-ed field of values in the Wait enum
	 */
	void wait(int what) const;

	/** Flush all buffers related to this socket */
	void flush() const;
    };

    /** A socket connected to a remote peer
     *
     * @ingroup system
     */
    class socket : public base_socket
    {
	friend class server_socket;

    public:
	/** Creates a socket object from an already existing file descriptor */
	socket(int fd);

	/** Opens a new socket in the specified domain and of the specified type,
	 * and connect it to \c connect_to. \c connect_to is either an IP address
	 * of the form \c a.b.c.d:port if \c domain is Inet, or a Unix socket name
	 * otherwise.
	 */
	socket(Domain domain, Type type, std::string const& connect_to);

	/** Connects or reconnects this socket to the specified peer. \c
	 * to is either an IP address of the form \c a.b.c.d:port if \c
	 * domain is Inet, or a Unix socket name otherwise.
	 */
	void connect(std::string const& to);

	/** Reads at most \c size bytes in the specified buffer and returns the
	 * count of bytes actually read.
	 *
	 * @exception unix_error raised if an error occured
	 */
	int read(void* buf, size_t size) const;

	/** Writes at most \c size bytes in the specified buffer and returns
	 * the count of bytes actually written.
	 *
	 * @exception unix_error raised if an error occured
	 */
	int write(void const* buf, size_t size) const;
    };

    /** A socket class holding servers (i.e. listening sockets)
     *
     * @ingroup system
     */
    class server_socket : public base_socket
    {
    public:
	server_socket(Domain domain, Type type, std::string const& bind_to, int backlog = 256);

	void bind(std::string const& to);

	/** Waits for an incoming connection
	 * If block is true, wait for a connection. If it is false, do not block
	 * and return NULL if there is no connection available
	 */
	socket* accept() const;

	/** Checks if there is an incoming connection in the connection queue.
	 * @return true if it is the case (i.e. accept() will return a socket)
	 * and false otherwise */
	bool try_wait() const;

	/** Waits for an incoming connection */
	void wait() const;
    };
}

#endif

ext: hh

max_stars_repo_name: annaborn/utilmm

max_issues_repo_name: annaborn/utilmm

max_forks_repo_name: annaborn/utilmm


text:
// Copyright 2020 The Defold Foundation
// Licensed under the Defold License version 1.0 (the "License"); you may not use
// this file except in compliance with the License.
//
// You may obtain a copy of the License, together with FAQs at
// https://www.defold.com/license
//
// 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.

#include <dlib/math.h>
#include <dlib/array.h>

#include <graphics/glfw/glfw_native.h>
#include <android_native_app_glue.h>

#include "../graphics_vulkan_defines.h"
#include "../../graphics.h"
#include "../graphics_vulkan_private.h"

extern struct android_app* __attribute__((weak)) g_AndroidApp;

namespace dmGraphics
{
    VkResult CreateWindowSurface(VkInstance vkInstance, VkSurfaceKHR* vkSurfaceOut, const bool enableHighDPI)
    {
        PFN_vkCreateAndroidSurfaceKHR vkCreateAndroidSurfaceKHR = (PFN_vkCreateAndroidSurfaceKHR)
            vkGetInstanceProcAddr(vkInstance, "vkCreateAndroidSurfaceKHR");

        if (!vkCreateAndroidSurfaceKHR)
        {
            return VK_ERROR_EXTENSION_NOT_PRESENT;
        }

        VkAndroidSurfaceCreateInfoKHR vk_surface_create_info = {};
        vk_surface_create_info.sType  = VK_STRUCTURE_TYPE_ANDROID_SURFACE_CREATE_INFO_KHR;
        vk_surface_create_info.window = g_AndroidApp->window;

        return vkCreateAndroidSurfaceKHR(vkInstance, &vk_surface_create_info, 0, vkSurfaceOut);
    }
}

max_stars_repo_name: Krzlfx/defold

max_issues_repo_name: Krzlfx/defold

max_forks_repo_name: Krzlfx/defold


text:
//
// Copyright (C) 2009-2013 King Luo (home_king@163.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)
//

#include <iostream>
using namespace std;

#include <boost/config.hpp>

#if defined(BOOST_WINDOWS)
#include <Windows.h>
#else
#include <dlfcn.h>
#endif

#include <boost/test/minimal.hpp>

// include the test case
#include "test_reflection.hpp"

int test_main(int argc, char* argv[])
{
    const char* library = argv[1];
    try {
        //dynamic load the sample classes
#if defined(BOOST_WINDOWS)
        HMODULE libHandle = LoadLibraryA (library);
#else
        void* libHandle = dlopen(library, RTLD_NOW);
#endif

        test_reflection();

#if defined(BOOST_WINDOWS)
        FreeLibrary(libHandle);
#else
        dlclose(libHandle);
#endif

        try {
            Class t = Class::forName("test.AccountImpl");
            BOOST_FAIL("test.AccountImpl should be non-exist");
        }
        catch(ClassNotFoundException&) {
            //correct branch
        }
    }
    catch(std::exception& exc) {
        std::cerr << exc.what() << std::endl;
        throw;
    }

    return 0;
}

max_stars_repo_name: jackfive/boost-reflection

max_issues_repo_name: jackfive/boost-reflection

max_forks_repo_name: jackfive/boost-reflection


text: #include <boost/qvm/gen/mat_operations4.hpp>

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


text:
#include "base_algorithm.h"

#include <Eigen/Dense>
#include <memory>
#include <vector>

#include "algorithm_params.pb.h"
#include "algorithm_state.pb.h"
#include "lib/progressbar/progressbar.h"
#include "mixing_state.pb.h"
#include "src/algorithms/neal8_algorithm.h"
#include "src/collectors/base_collector.h"
#include "src/utils/eigen_utils.h"
#include "src/utils/rng.h"

Eigen::MatrixXd BaseAlgorithm::eval_lpdf(
    BaseCollector *const collector, const Eigen::MatrixXd &grid,
    const Eigen::RowVectorXd &hier_covariate /*= Eigen::RowVectorXd(0)*/,
    const Eigen::RowVectorXd &mix_covariate /*= Eigen::RowVectorXd(0)*/) {
  std::deque<Eigen::VectorXd> lpdf;
  bool keep = true;
  progresscpp::ProgressBar *bar = nullptr;
  if (verbose) {
    bar = new progresscpp::ProgressBar(collector->get_size(), 60);
  }
  while (keep) {
    keep = update_state_from_collector(collector);
    if (!keep) {
      break;
    }
    lpdf.push_back(lpdf_from_state(grid, hier_covariate, mix_covariate));
    if (verbose) {
      ++(*bar);
      bar->display();
    }
  }
  collector->reset();
  if (verbose) {
    bar->done();
    delete bar;
    print_ending_message();
  }
  return bayesmix::stack_vectors(lpdf);
}

void BaseAlgorithm::read_params_from_proto(
    const bayesmix::AlgorithmParams &params) {
  // Generic parameters
  maxiter = params.iterations();
  burnin = params.burnin();
  init_num_clusters = params.init_num_clusters();
  auto &rng = bayesmix::Rng::Instance().get();
  rng.seed(params.rng_seed());
}

void BaseAlgorithm::initialize() {
  if (verbose) {
    std::cout << "Initializing... " << std::flush;
  }
  // Perform checks
  if (data.rows() == 0) {
    throw std::invalid_argument("Data was not provided to algorithm");
  }
  // Hierarchy checks
  if (unique_values.size() == 0) {
    throw std::invalid_argument("Hierarchy was not provided to algorithm");
  }
  if (unique_values[0]->is_conjugate() == false and
      requires_conjugate_hierarchy()) {
    std::string msg = "Algorithm \"" + bayesmix::AlgorithmId_Name(get_id()) +
                      "\"  only supports conjugate hierarchies";
    throw std::invalid_argument(msg);
  }
  if (unique_values[0]->is_multivariate() == false && data.cols() > 1) {
    throw std::invalid_argument(
        "Multivariate data supplied to univariate hierarchy");
  }
  if (hier_covariates.rows() != 0) {
    if (unique_values[0]->is_dependent() == false) {
      throw std::invalid_argument(
          "Covariates supplied to non-dependent hierarchy");
    }
    if (data.rows() != hier_covariates.rows()) {
      throw std::invalid_argument(
          "Sizes of data and hierarchy covariates do not match");
    }
  } else {
    // Create empty covariates vector
    hier_covariates = Eigen::MatrixXd::Zero(data.rows(), 0);
  }
  // Mixing checks
  if (mixing == nullptr) {
    throw std::invalid_argument("Mixing was not provided to algorithm");
  }
  if (this->is_conditional() != mixing->is_conditional()) {
    throw std::invalid_argument(
        "Algorithm and mixing must be either both "
        "marginal or both conditional");
  }
  if (mix_covariates.rows() != 0) {
    if (mixing->is_dependent() == false) {
      throw std::invalid_argument(
          "Covariates supplied to non-dependent mixing");
    }
    if (data.rows() != mix_covariates.rows()) {
      throw std::invalid_argument(
          "Sizes of data and mixing covariates do not match");
    }
  } else {
    // Create empty covariates vector
    mix_covariates = Eigen::MatrixXd::Zero(data.rows(), 0);
  }
  mixing->set_covariates(&mix_covariates);
  // Initialize mixing
  mixing->set_num_components(init_num_clusters);
  mixing->initialize();
  // Interpet default number of clusters
  if (mixing->get_num_components() == 0) {
    mixing->set_num_components(data.rows());
  }
  // Initialize hierarchies
  unique_values[0]->initialize();
  unsigned int num_components = mixing->get_num_components();

  for (size_t i = 0; i < num_components - 1; i++) {
    unique_values.push_back(unique_values[0]->clone());
    unique_values[i]->sample_prior();

  }
  // Build uniform probability on clusters, given their initial number
  std::default_random_engine generator;
  std::uniform_int_distribution<int> distro(0, num_components - 1);
  // Allocate one datum per cluster first, and update cardinalities
  allocations.clear();
  for (size_t i = 0; i < num_components; i++) {
    allocations.push_back(i);
    unique_values[i]->add_datum(i, data.row(i), update_hierarchy_params(),
                                hier_covariates.row(i));
  }

  // Randomly allocate all remaining data, and update cardinalities
  for (size_t i = num_components; i < data.rows(); i++) {
    unsigned int clust = distro(generator);
    allocations.push_back(clust);
    unique_values[clust]->add_datum(i, data.row(i), update_hierarchy_params(),
                                    hier_covariates.row(i));
  }
  if (verbose) {
    std::cout << "Done" << std::endl;
  }
}

void BaseAlgorithm::update_hierarchy_hypers() {
  bayesmix::AlgorithmState::ClusterState clust;
  std::vector<bayesmix::AlgorithmState::ClusterState> states;
  // Build vector of states associated to non-empty clusters
  for (auto &un : unique_values) {
    if (un->get_card() > 0) {
      un->write_state_to_proto(&clust);
      states.push_back(clust);
    }
  }
  unique_values[0]->update_hypers(states);
}

bayesmix::AlgorithmState BaseAlgorithm::get_state_as_proto(unsigned int iter) {
  bayesmix::AlgorithmState iter_out;
  // Transcribe iteration number, allocations, and cardinalities
  iter_out.set_iteration_num(iter);
  *iter_out.mutable_cluster_allocs() = {allocations.begin(),
                                        allocations.end()};
  // Transcribe unique values vector
  for (size_t i = 0; i < unique_values.size(); i++) {
    bayesmix::AlgorithmState::ClusterState clusval;
    unique_values[i]->write_state_to_proto(&clusval);
    iter_out.add_cluster_states()->CopyFrom(clusval);
  }

  // Transcribe the hyperparameters of the hyerarchy
  bayesmix::AlgorithmState::HierarchyHypers hyper_state;
  unique_values[0]->write_hypers_to_proto(&hyper_state);
  iter_out.mutable_hierarchy_hypers()->CopyFrom(hyper_state);

  // Transcribe mixing state
  bayesmix::MixingState mixstate;
  mixing->write_state_to_proto(&mixstate);
  iter_out.mutable_mixing_state()->CopyFrom(mixstate);

  return iter_out;
}

bool BaseAlgorithm::update_state_from_collector(BaseCollector *coll) {
  bool success = coll->get_next_state(&curr_state);
  return success;
}

max_stars_repo_name: edoardopalli/bayesmix

max_issues_repo_name: edoardopalli/bayesmix

max_forks_repo_name: edoardopalli/bayesmix


text:
#include "StdAfx.h"
#include "DlgPackageInstall.h"
#include "L3dPackageInstaller.h"
#include "FileDlgHelper.h"
#include "InstallerException.h"
#include "DlgInstallSelectFiles.h"

#include <Strsafe.h>
#include <string>
#include <vector>
#include <memory>
#include <algorithm>

#include <boost/filesystem.hpp>
#include <lhWinAPI.h>

#include "DBHelper.h"

namespace l3d
{
namespace packageinstaller
{
namespace ui
{

using namespace std;
using namespace db;

DlgPackageInstall::DlgPackageInstall(const std::wstring& l3dPath, const std::vector<std::wstring>& packagesToInstall) :
	curListSel(-1), installationStarted(false), hListPackages(nullptr),
	dropTarget{ { L".zip", L".l3dpack" } }, argPackagesToInstall(packagesToInstall)

{
	bool disableTransactions = DBHelper::instance().GetPreferenceValue(DBHelper::PREF_DISABLE_TRANSACTIONS, false);
	installManager = std::make_unique<InstallManager>(l3dPath, disableTransactions);
	dropTarget.SetOnDropNotify(this);
}

DlgPackageInstall::~DlgPackageInstall(void)
{
	if (hListPackages != nullptr)
	{
		RevokeDragDrop(hListPackages);
	}
}

//INT_PTR DlgPackageInstall::Show(HINSTANCE hInstance, HWND hWndParent)
//{
//	return Dialog::Show(hInstance, MAKEINTRESOURCE(IDD_INSTALLPACKAGES), hWndParent);
//}

HWND DlgPackageInstall::CreateModeless(HINSTANCE hInstance, HWND hWndParent)
{
	return Dialog::CreateModeless(hInstance, MAKEINTRESOURCE(IDD_INSTALLPACKAGES), hWndParent);
}

void DlgPackageInstall::OnFilesDrop()
{
	DoAddFiles(dropTarget.getFilenames());
}

void DlgPackageInstall::DoAddFilesDlg()
{
	unique_ptr<OpenFileDlg> dlg = GetOpenFileDlg();

	dlg->SetAllowMultiSelect(true);
	vector<COMDLG_FILTERSPEC> filter(1);
	std::wstring filterName = strTable.LoadS(IDS_INSTALLPKGFILEFILTERDESC);
	std::wstring filterExt = strTable.LoadS(IDS_INSTALLPKGFILEFILTEREXT);
	filter[0].pszName = filterName.c_str();
	filter[0].pszSpec = filterExt.c_str();

	static const GUID dlgGuid =	{ 0x21f280a6, 0x5d5b, 0x44c0, { 0x97, 0x67, 0x2, 0x30, 0x94, 0xed, 0x9c, 0xbb } };
	dlg->SetClientGuid(dlgGuid);

	dlg->SetFileTypes(filter);
	if (SUCCEEDED(dlg->Show(GetHwnd())))
	{
		DoAddFiles(dlg->GetResults());
	}
}

void DlgPackageInstall::DoAddFiles(const vector<wstring>& filenames)
{
	LVITEM lvI;

	// Initialize LVITEM members that are common to all items.
	lvI.pszText   = LPSTR_TEXTCALLBACK; // Sends an LVN_GETDISPINFO message.
	lvI.mask      = LVIF_TEXT | LVIF_IMAGE | LVIF_STATE;
	lvI.stateMask = 0;
	lvI.iSubItem  = 0;
	lvI.state     = 0;

	for (auto file = begin(filenames); file != end(filenames); ++file)
	{
		boost::filesystem::path p = *file;
		if (boost::filesystem::exists(p) && installManager->AddPackageToInstall(*file))
		{
			selectedPackages.emplace_back(PkgDispInfo(*file, p.filename().wstring()));
			size_t ind = selectedPackages.size() - 1;
			lvI.iItem  = ind;
			lvI.iImage = ind;

			ListView_InsertItem(hListPackages, &lvI);
		}
	}
	if (selectedPackages.size() > 1 && SendDlgItemMessage(GetHwnd(), IDC_CHECKBOXASKALWAYS, BM_GETCHECK, 0, 0) == BST_CHECKED)
	{
		SendDlgItemMessage(GetHwnd(), IDC_CHECKBOXASKALWAYS, BM_SETCHECK, BST_UNCHECKED, 0);
		MessageBox(GetHwnd(), strTable.Load(IDS_ALWAYSASKNOTPOSSIBLE), strTable.Load(IDS_FENCY_APP_TITLE), MB_OK | MB_ICONINFORMATION);
	}
	SetInstallBtnState();
}

void DlgPackageInstall::SetInstallBtnState()
{
	EnableWindow(GetDlgItem(GetHwnd(), IDC_BUTTONSTARTINSTALLATION), !selectedPackages.empty());
	EnableWindow(GetDlgItem(GetHwnd(), IDC_CHECKBOXASKALWAYS), selectedPackages.empty() || selectedPackages.size() == 1);
}

void DlgPackageInstall::SetUpDownBtnState()
{
	EnableWindow(GetDlgItem(GetHwnd(), IDC_BUTTONUP), curListSel > 0 && selectedPackages.size() > 0);
	EnableWindow(GetDlgItem(GetHwnd(), IDC_BUTTONDOWN), curListSel >= 0 && curListSel < static_cast<int>(selectedPackages.size()) - 1);
}

INT_PTR DlgPackageInstall::OnInitDlg(WPARAM wParam, LPARAM lParam)
{
	hListPackages = GetDlgItem(GetHwnd(), IDC_LISTPACKAGES);
	hTextBoxReadme = GetDlgItem(GetHwnd(), IDC_EDITPACKAGEINFO);

	RegisterDragDrop(hListPackages, &dropTarget);
	SetTimer(GetHwnd(), 0, 1000, nullptr);

	SendDlgItemMessage(GetHwnd(), IDC_CHECKBOXONLYOLDER, BM_SETCHECK, BST_CHECKED, 0);

	SendDlgItemMessage(GetHwnd(), IDC_BUTTONUP, BM_SETIMAGE, IMAGE_ICON, reinterpret_cast<LPARAM>(LoadIcon(GetHInstance(), MAKEINTRESOURCE(IDI_GOUP))));
	SendDlgItemMessage(GetHwnd(), IDC_BUTTONDOWN, BM_SETIMAGE, IMAGE_ICON, reinterpret_cast<LPARAM>(LoadIcon(GetHInstance(), MAKEINTRESOURCE(IDI_GODOWN))));

	/*installManager->AddPackageToInstall(L"D:\\new_inst_pkg.l3dpack");
	boost::filesystem::path p(L"D:\\new_inst_pkg.l3dpack");
	selectedPackages.emplace_back(PkgDispInfo(L"D:\\new_inst_pkg.l3dpack", p.filename().wstring()));
	size_t ind = selectedPackages.size() - 1;
	LVITEM lvI;
	// Initialize LVITEM members that are common to all items.
	lvI.pszText   = LPSTR_TEXTCALLBACK; // Sends an LVN_GETDISPINFO message.
	lvI.mask      = LVIF_TEXT | LVIF_IMAGE | LVIF_STATE;
	lvI.stateMask = 0;
	lvI.iSubItem  = 0;
	lvI.state     = 0;
	lvI.iItem  = ind;
	lvI.iImage = ind;
	ListView_InsertItem(hListPackages, &lvI);*/
	SetInstallBtnState();
	SetUpDownBtnState();

	SendDlgItemMessage(GetHwnd(), IDC_CHECKBOXASKALWAYS, BM_SETCHECK,
		DBHelper::instance().GetPreferenceValue(DBHelper::PREF_INSTALL_ALWAYS_ASK, false) ? BST_CHECKED : BST_UNCHECKED, 0);
	SendDlgItemMessage(GetHwnd(), IDC_CHECKBOXONLYOLDER, BM_SETCHECK,
		DBHelper::instance().GetPreferenceValue(DBHelper::PREF_INSTALL_ONLY_OLDER, true) ? BST_CHECKED : BST_UNCHECKED, 0);

	DoAddFiles(argPackagesToInstall);

	using resizeabledlghelper::ANCHOR;
	AddAnchor(ANCHOR(IDC_BUTTONADDPACKAGES,		resizeabledlghelper::AF_TOP | resizeabledlghelper::AF_LEFT));
	AddAnchor(ANCHOR(IDC_STATICPKGINFO,			resizeabledlghelper::AF_TOP | resizeabledlghelper::AF_LEFT));

	AddAnchor(ANCHOR(IDC_BUTTONDOWN,			resizeabledlghelper::AF_TOP | resizeabledlghelper::AF_LEFT));
	AddAnchor(ANCHOR(IDC_BUTTONUP,				resizeabledlghelper::AF_TOP | resizeabledlghelper::AF_LEFT));

	AddAnchor(ANCHOR(IDC_LISTPACKAGES,			resizeabledlghelper::AF_TOP_AND_BOTTOM | resizeabledlghelper::AF_LEFT));
	AddAnchor(ANCHOR(IDC_EDITPACKAGEINFO,		resizeabledlghelper::AF_TOP_AND_BOTTOM | resizeabledlghelper::AF_LEFT_AND_RIGHT));

	AddAnchor(ANCHOR(IDC_BUTTONREMOVEPACKAGE,	resizeabledlghelper::AF_BOTTOM | resizeabledlghelper::AF_LEFT));
	AddAnchor(ANCHOR(IDC_CHECKBOXONLYOLDER,		resizeabledlghelper::AF_BOTTOM | resizeabledlghelper::AF_LEFT));
	AddAnchor(ANCHOR(IDC_CHECKBOXASKALWAYS,		resizeabledlghelper::AF_BOTTOM | resizeabledlghelper::AF_LEFT));

	AddAnchor(ANCHOR(IDC_STATICPROGRESSINSTALL,	resizeabledlghelper::AF_BOTTOM | resizeabledlghelper::AF_LEFT));
	AddAnchor(ANCHOR(IDC_PROGRESSINSTALL,		resizeabledlghelper::AF_BOTTOM | resizeabledlghelper::AF_LEFT_AND_RIGHT));

	AddAnchor(ANCHOR(IDC_BUTTONSTARTINSTALLATION,	resizeabledlghelper::AF_BOTTOM | resizeabledlghelper::AF_RIGHT));
	AddAnchor(ANCHOR(IDC_BUTTONCANCELINSTALLATION,	resizeabledlghelper::AF_BOTTOM | resizeabledlghelper::AF_RIGHT));

	return ResizeableDialog::OnInitDlg(wParam, lParam);
}

INT_PTR DlgPackageInstall::OnSize(WPARAM wParam, LPARAM lParam)
{
	return ResizeableDialog::OnSize(wParam, lParam);
}

void DlgPackageInstall::CloseDlg(bool reuseSelectedPackages /*=false*/)
{
	installManager->CancelAndWaitForTasks();
	SetTimer(GetHwnd(), 0, 1000, nullptr);

	std::wstring p = installManager->GetL3dPath().wstring();
	installManager.reset(new InstallManager(p));

	ListView_DeleteAllItems(hListPackages);
	SetWindowText(hTextBoxReadme, L"");

	EnableWindow(GetDlgItem(GetHwnd(), IDC_BUTTONSTARTINSTALLATION), TRUE);
	EnableWindow(GetDlgItem(GetHwnd(), IDC_CHECKBOXASKALWAYS), TRUE);
	EnableWindow(GetDlgItem(GetHwnd(), IDC_CHECKBOXONLYOLDER), TRUE);
	EnableWindow(GetDlgItem(GetHwnd(), IDC_BUTTONREMOVEPACKAGE), FALSE);
	EnableWindow(GetDlgItem(GetHwnd(), IDC_BUTTONADDPACKAGES), TRUE);
	EnableWindow(GetDlgItem(GetHwnd(), IDC_BUTTONCANCELINSTALLATION), FALSE);
	installationStarted = false;

	if (reuseSelectedPackages)
	{
		vector<wstring> files;
		transform(	begin(selectedPackages),
					end(selectedPackages),
					back_inserter(files),
					[] (const PkgDispInfo& disp) { return disp.completePath; });
		selectedPackages.clear();
		DoAddFiles(files);
	}
	else
	{
		selectedPackages.clear();
	}

	SendDlgItemMessage(GetHwnd(), IDC_PROGRESSINSTALL, PBM_SETPOS, 0, 0);
	SetDlgItemText(GetHwnd(), IDC_STATICPROGRESSINSTALL, L"");

	//EndDialog(GetHwnd(), 0);

}

INT_PTR DlgPackageInstall::OnCommand(WPARAM wParam, LPARAM lParam)
{
	switch (LOWORD(wParam))
	{
	case IDC_BUTTONADDPACKAGES:
		DoAddFilesDlg();
		break;

	case IDC_BUTTONSTARTINSTALLATION:
		if (!installationStarted)
		{
			SetTimer(GetHwnd(), 0, 500, nullptr);
			installManager->SetAlwaysAskBeforeOverwrite(SendDlgItemMessage(GetHwnd(), IDC_CHECKBOXASKALWAYS, BM_GETCHECK, 0, 0) == BST_CHECKED);
			installManager->SetReplaceOnlyOlder(SendDlgItemMessage(GetHwnd(), IDC_CHECKBOXONLYOLDER, BM_GETCHECK, 0, 0) == BST_CHECKED);
			installManager->StartInstallation();
			EnableWindow(GetDlgItem(GetHwnd(), IDC_BUTTONSTARTINSTALLATION), FALSE);
			EnableWindow(GetDlgItem(GetHwnd(), IDC_CHECKBOXASKALWAYS), FALSE);
			EnableWindow(GetDlgItem(GetHwnd(), IDC_CHECKBOXONLYOLDER), FALSE);
			EnableWindow(GetDlgItem(GetHwnd(), IDC_BUTTONREMOVEPACKAGE), FALSE);
			EnableWindow(GetDlgItem(GetHwnd(), IDC_BUTTONADDPACKAGES), FALSE);
			EnableWindow(GetDlgItem(GetHwnd(), IDC_BUTTONCANCELINSTALLATION), TRUE);
			installationStarted = true;
		}
		break;

	case IDC_BUTTONCANCELINSTALLATION:
		SoftCancel();
		break;

	case IDC_BUTTONREMOVEPACKAGE:
		if (!installationStarted && curListSel >= 0 && curListSel < static_cast<int>(selectedPackages.size()))
		{
			if (installManager->RemovePackageToInstall(selectedPackages[curListSel].completePath))
			{
				selectedPackages.erase(selectedPackages.begin() + curListSel);
				ListView_DeleteItem(hListPackages, curListSel);
				SetInstallBtnState();
				SetUpDownBtnState();
			}
		}
		break;

	case IDC_BUTTONUP:
		if (!installationStarted && curListSel > 0 && curListSel < static_cast<int>(selectedPackages.size()))
		{
			int sel = curListSel;
			swap(selectedPackages[curListSel], selectedPackages[curListSel - 1]);
			vector<wstring>& v = installManager->GetSelectedFilesToInstall();
			swap(v[curListSel], v[curListSel - 1]);
			ListView_SetItemText(hListPackages, curListSel, 0, LPSTR_TEXTCALLBACK);
			ListView_SetItemText(hListPackages, curListSel - 1, 0, LPSTR_TEXTCALLBACK);
			ListView_SetItemState(hListPackages, curListSel, 0, 0x000F);
			curListSel = sel - 1;
			ListView_SetItemState(hListPackages, curListSel, LVIS_SELECTED | LVIS_FOCUSED, 0x000F);
			ListView_SetSelectionMark(hListPackages, curListSel);
			OnSelectionChanged();
		}
		break;

	case IDC_BUTTONDOWN:
		if (!installationStarted && curListSel >= 0 && curListSel < static_cast<int>(selectedPackages.size()) - 1)
		{
			int sel = curListSel;
			swap(selectedPackages[curListSel], selectedPackages[curListSel + 1]);
			vector<wstring>& v = installManager->GetSelectedFilesToInstall();
			swap(v[curListSel], v[curListSel + 1]);
			ListView_SetItemText(hListPackages, curListSel, 0, LPSTR_TEXTCALLBACK);
			ListView_SetItemText(hListPackages, curListSel + 1, 0, LPSTR_TEXTCALLBACK);
			ListView_SetItemState(hListPackages, curListSel, 0, 0x000F);
			curListSel = sel + 1;
			ListView_SetItemState(hListPackages, curListSel, LVIS_SELECTED | LVIS_FOCUSED, 0x000F);
			ListView_SetSelectionMark(hListPackages, curListSel);
			OnSelectionChanged();
		}
		break;
	}
	return Dialog::OnCommand(wParam,lParam);
}

void DlgPackageInstall::OnSelectionChanged()
{
	if (curListSel >= 0 && curListSel < static_cast<int>(selectedPackages.size()))
	{
		PkgDispInfo& inf = selectedPackages[curListSel];
		if (!inf.finishedPreInstall)
		{
			inf.finishedPreInstall = installManager->IsPreInstallFinished(inf.completePath);
		}
		if (inf.finishedPreInstall)
		{
			const std::wstring r = installManager->GetReadmeForPackage(inf.completePath);
			SetWindowText(hTextBoxReadme, r.c_str());
		}
		else
		{
			SetWindowText(hTextBoxReadme, strTable.Load(IDS_LOADING_README));
		}
		if (!installationStarted)
		{
			EnableWindow(GetDlgItem(GetHwnd(), IDC_BUTTONREMOVEPACKAGE), TRUE);
		}
		SetUpDownBtnState();
	}
	else
	{
		EnableWindow(GetDlgItem(GetHwnd(), IDC_BUTTONREMOVEPACKAGE), FALSE);
		SetWindowText(hTextBoxReadme, L"");
		SetUpDownBtnState();
	}
}

INT_PTR DlgPackageInstall::OnNotify(WPARAM wParam, LPARAM lParam)
{
	switch (((LPNMHDR) lParam)->code)
	{
	case LVN_GETDISPINFO:
		{
			NMLVDISPINFO *plvdi = reinterpret_cast<NMLVDISPINFO*>(lParam);

			try
			{
				if (plvdi->hdr.hwndFrom == hListPackages && (plvdi->item.mask & LVIF_TEXT) != 0)
				{
					const wstring& txt = selectedPackages.at(plvdi->item.iItem).dispName;
					StringCchCopy(plvdi->item.pszText, plvdi->item.cchTextMax, txt.c_str());
				}
			} catch (const std::out_of_range&)
			{
			}
		}
		break;
	case LVN_ITEMCHANGED:
		{
			int newSel = (int)SendMessage(hListPackages, LVM_GETNEXTITEM, -1, LVNI_FOCUSED);
			//if (newSel != curListSel)
			{
				curListSel = newSel;
				OnSelectionChanged();
			}
			/*
			LPNMLISTVIEW pnmv = reinterpret_cast<LPNMLISTVIEW>(lParam);
			if (pnmv->iItem >= 0 && pnmv->iItem < static_cast<int>(selectedPackages.size()) &&
				(pnmv->uNewState & LVIS_SELECTED) != 0 && (pnmv->uChanged & LVIF_STATE) != 0)
			{
				curListSel = pnmv->iItem;
				OnSelectionChanged();
			}
			else if ((pnmv->uNewState & LVIS_SELECTED) == 0 && (pnmv->uChanged & LVIF_STATE) != 0)
			{
				curListSel = -1;
				OnSelectionChanged();
			}
			*/
		}
	}
	return Dialog::OnNotify(wParam, lParam);
}

bool DlgPackageInstall::SoftCancel()
{
	if (installationStarted)
	{
		if (installManager->IsUsingTransaction() || MessageBox(GetHwnd(), strTable.LoadS(IDS_WARNINGCANCEL).c_str(),
			strTable.LoadS(IDS_WARNINGCANCELTITLE).c_str(), MB_ICONWARNING | MB_YESNO) == IDYES)
		{
			installManager->CancelInstallation();
			EnableWindow(GetDlgItem(GetHwnd(), IDCANCEL), FALSE);
		}
		else
		{
			return false;
		}
	}
	return true;
}

INT_PTR DlgPackageInstall::OnTimer(WPARAM wParam, LPARAM lParam)
{
	if (curListSel >= 0 && curListSel < static_cast<int>(selectedPackages.size()))
	{
		PkgDispInfo& inf = selectedPackages[curListSel];
		if (!inf.finishedPreInstall)
		{
			inf.finishedPreInstall = installManager->IsPreInstallFinished(inf.completePath);
			if (inf.finishedPreInstall)
			{
				ListView_SetItemText(hListPackages, curListSel, 0, LPSTR_TEXTCALLBACK);
			}
		}
	}
	if (installationStarted)
	{
		size_t cur, total;
		SendDlgItemMessage(GetHwnd(), IDC_PROGRESSINSTALL, PBM_SETPOS, installManager->GetInstallationProgress(&cur, &total), 0);
		TCHAR buf[260];
		swprintf_s(buf, strTable.Load(IDS_INSTALLPROGTXT), cur, total);
		SetDlgItemText(GetHwnd(), IDC_STATICPROGRESSINSTALL, buf);
		if (installManager->IsInstallFinished())
		{
			KillTimer(GetHwnd(), 0);
			InstallManager::InstallManagerState st = installManager->GetInstallerState();

			if (st == InstallManager::InstallSuccessfullyFinished || st == InstallManager::InstallPassOneFinished)
			{
				std::unique_ptr<DlgInstallSelectFiles> dlg;
				if (st == InstallManager::InstallPassOneFinished)
				{
					dlg = std::unique_ptr<DlgInstallSelectFiles>(
						new DlgInstallSelectFiles(installManager->GetInstallInformation(), installManager->GetFilesToDeinstall(), true));
				}
				else if (installManager->IsAlwaysAsk())
				{
					dlg = std::unique_ptr<DlgInstallSelectFiles>(
						new DlgInstallSelectFiles(installManager->GetInstallInformation(), installManager->GetDeinstalledFiles(), false, installManager->GetUserSelection()));
				}
				else
				{
					dlg = std::unique_ptr<DlgInstallSelectFiles>(
						new DlgInstallSelectFiles(installManager->GetInstallInformation(), installManager->GetDeinstalledFiles(), false));
				}
				dlg->SetL3dPath(installManager->GetL3dPath());
				if (dlg->Show(GetHInstance(), GetHwnd()) == IDOK && st == InstallManager::InstallPassOneFinished)
				{
					installManager->StartInstallUserSelection(dlg->GetSelectedFiles());
					SetTimer(GetHwnd(), 0, 500, nullptr);
				}
				else
				{
					CloseDlg();
				}
			}
			else if (st == InstallManager::InstallCancelled)
			{
				std::wstring msg = strTable.LoadS(IDS_INSTALLCANCELLED).append(L"\n");
				if (installManager->IsUsingTransaction())
				{
					msg.append(strTable.LoadS(IDS_INSTALLROLLEDBACK));
					MessageBox(GetHwnd(), msg.c_str(), strTable.Load(IDS_INSTALLCANCELLEDTITLE), MB_OK | MB_ICONINFORMATION);
				}
				else
				{
					msg.append(strTable.LoadS(IDS_INSTALLPARTIAL));
					MessageBox(GetHwnd(), msg.c_str(), strTable.Load(IDS_INSTALLCANCELLEDTITLE), MB_OK | MB_ICONWARNING);
				}
				CloseDlg();
			}
			else
			{
				const InstallerException *pEx = installManager->GetInstallerException();
				std::wstring msg;
				if (pEx != nullptr)
				{
					const InstallerErrorInformation& inf = pEx->GetErrorInfo();
					boost::filesystem::path pkgPath;
					if (inf.currentPackage.packageName.length() > 0)
					{
						pkgPath = inf.currentPackage.parentPackageName.length() > 0 ?
							inf.currentPackage.parentPackageName : pEx->GetErrorInfo().currentPackage.packageName;
						msg.append(pkgPath.filename().wstring());
						msg.append(L": ");

						// Lösche das Package welches den Fehler verursacht hat
						selectedPackages.erase(remove_if(begin(selectedPackages), end(selectedPackages),
							[&pkgPath](const PkgDispInfo& disp) { return disp.completePath == pkgPath.wstring(); } ), end(selectedPackages));
					}

					switch (inf.kindOfError)
					{
					case InstallerErrorInformation::InstallErrorFileSystemOccurred:
						msg.append(strTable.LoadS(IDS_INSTALLERRORFS));
						break;
					case InstallerErrorInformation::InstallErrorTxFsOccurred:
						msg.append(strTable.LoadS(IDS_INSTALLERRORTXFS));
						break;
					case InstallerErrorInformation::InstallErrorZipOccurred:
						msg.append(strTable.LoadS(IDS_INSTALLERRORZIP));
						break;
					case InstallerErrorInformation::InstallErrorPkgVersionNewer:
						msg.append(strTable.LoadS(IDS_PKGVERSIONNEWER));
						break;
					case InstallerErrorInformation::InstallErrorDeinstall:
						msg.append(strTable.LoadS(IDS_DEINSTALLERRORUNKWOWN));
						break;
					}
					if (!inf.currentFile.empty())
					{
						msg.append(L"\n").append(inf.currentFile).append(L"\n");
					}
					if (inf.errorMsg.length() > 0)
					{
						msg.append(inf.errorMsg).append(L"\n");
					}
				}
				else
				{
					msg = strTable.LoadS(IDS_INSTALLERROR);
				}
				if (installManager->IsUsingTransaction())
				{
					msg.append(strTable.LoadS(IDS_INSTALLROLLEDBACK));
				}
				else
				{
					msg.append(strTable.LoadS(IDS_INSTALLPARTIAL));
				}
				MessageBox(GetHwnd(), msg.c_str(), strTable.Load(IDS_INSTALLERRORHEADER), MB_OK | MB_ICONERROR);
				CloseDlg(true);
			}
		}
	}
	return Dialog::OnTimer(wParam, lParam);
}

}
}
}


text:
#ifndef HITTABLE_HH
#define HITTABLE_HH

#include <Eigen/Dense>

#include "ray.hh"

namespace hittable
{

struct hitRecord
{
    bool didHit{false};
    double t{0};
    Eigen::Vector3d p;
    Eigen::Vector3d norm;
    bool frontFace{false};

    inline void setFaceNormal(const ray::Ray& ray,
                              const Eigen::Vector3d& outwardNormal)
    {
        frontFace = ray.direction().dot(outwardNormal) < 0;
        norm = frontFace ? outwardNormal : -outwardNormal;
    }
};

class Hittable
{
  public:
    virtual ~Hittable();

    [[nodiscard]] virtual auto
    hit(const ray::Ray& r, double t_min = 0,
        double t_max = std::numeric_limits<double>::infinity()) const
        -> hitRecord = 0;
};

} // namespace hittable

#endif // HITTABLE_HH

max_stars_repo_name: AlexanderDavid/inOneWeekend

max_issues_repo_name: AlexanderDavid/inOneWeekend

max_forks_repo_name: AlexanderDavid/inOneWeekend