text:
//  Copyright (c) 2011-present, Facebook, Inc.  All rights reserved.
//  This source code is licensed under both the GPLv2 (found in the
//  COPYING file in the root directory) and Apache 2.0 License
//  (found in the LICENSE.Apache file in the root directory).

#include "monitoring/instrumented_mutex.h"

#include "monitoring/perf_context_imp.h"
#include "monitoring/thread_status_util.h"
#include "util/sync_point.h"
#include "util/util.h"

#if MUTEX_DEBUG_MILLISECONDS
#include <boost/stacktrace.hpp>
#endif

namespace rocksdb {
namespace {
Statistics* stats_for_report(Env* env, Statistics* stats) {
  if (env != nullptr && stats != nullptr &&
      stats->stats_level_ > kExceptTimeForMutex) {
    return stats;
  } else {
    return nullptr;
  }
}
}  // namespace

void InstrumentedMutex::Lock() {
#if MUTEX_DEBUG_MILLISECONDS
  auto start = std::chrono::high_resolution_clock::now();
  auto stacktrace = new boost::stacktrace::stacktrace();
#endif
  PERF_CONDITIONAL_TIMER_FOR_MUTEX_GUARD(
      db_mutex_lock_nanos, stats_code_ == DB_MUTEX_WAIT_MICROS,
      stats_for_report(env_, stats_), stats_code_);
  LockInternal();
#if MUTEX_DEBUG_MILLISECONDS
  assert(start_stacktrace_ == nullptr);
  start_stacktrace_ = stacktrace;
  wait_start_ = start;
  lock_start_ = std::chrono::high_resolution_clock::now();
#endif
}

void InstrumentedMutex::Unlock() {
#if MUTEX_DEBUG_MILLISECONDS
  int64_t lock_dur =
      std::chrono::duration_cast<std::chrono::microseconds>(
          std::chrono::high_resolution_clock::now() - lock_start_)
          .count();
  assert(start_stacktrace_ != nullptr);
  auto stacktrace =
      static_cast<boost::stacktrace::stacktrace*>(start_stacktrace_);
  start_stacktrace_ = nullptr;
#endif
  AssertHeld();
  mutex_.Unlock();
#if MUTEX_DEBUG_MILLISECONDS
  if (lock_dur > MUTEX_DEBUG_MILLISECONDS * 1000) {
    int64_t wait_dur = std::chrono::duration_cast<std::chrono::microseconds>(
                           lock_start_ - wait_start_)
                           .count();
    fprintf(
        stderr,
        "InstrumentedMutex Trace: Lock = %" PRIi64 "us Wait = %" PRIi64
        "us\n--------\n%s--------\n%s--------\n",
        lock_dur, wait_dur, boost::stacktrace::to_string(*stacktrace).c_str(),
        boost::stacktrace::to_string(boost::stacktrace::stacktrace()).c_str());
  }
  delete stacktrace;
#endif
}

void InstrumentedMutex::LockInternal() {
#ifndef NDEBUG
  ThreadStatusUtil::TEST_StateDelay(ThreadStatus::STATE_MUTEX_WAIT);
#endif
  mutex_.Lock();
}

void InstrumentedCondVar::Wait() {
  PERF_CONDITIONAL_TIMER_FOR_MUTEX_GUARD(
      db_condition_wait_nanos, stats_code_ == DB_MUTEX_WAIT_MICROS,
      stats_for_report(env_, stats_), stats_code_);
  WaitInternal();
}

void InstrumentedCondVar::WaitInternal() {
#if MUTEX_DEBUG_MILLISECONDS
  int64_t lock_dur = std::chrono::duration_cast<std::chrono::microseconds>(
                         std::chrono::high_resolution_clock::now() -
                         instrumented_mutex_->lock_start_)
                         .count();
  assert(instrumented_mutex_->start_stacktrace_ != nullptr);
  auto stacktrace = static_cast<boost::stacktrace::stacktrace*>(
      instrumented_mutex_->start_stacktrace_);
  instrumented_mutex_->start_stacktrace_ = nullptr;
  if (lock_dur > MUTEX_DEBUG_MILLISECONDS * 1000) {
    int64_t wait_dur =
        std::chrono::duration_cast<std::chrono::microseconds>(
            instrumented_mutex_->lock_start_ - instrumented_mutex_->wait_start_)
            .count();
    fprintf(
        stderr,
        "InstrumentedMutex Trace: Lock = %" PRIi64 "us Wait = %" PRIi64
        "us\n--------\n%s--------\n%s--------\n",
        lock_dur, wait_dur, boost::stacktrace::to_string(*stacktrace).c_str(),
        boost::stacktrace::to_string(boost::stacktrace::stacktrace()).c_str());
  }
  call_destructor(stacktrace);
#endif
#ifndef NDEBUG
  ThreadStatusUtil::TEST_StateDelay(ThreadStatus::STATE_MUTEX_WAIT);
#endif
  cond_.Wait();
#if MUTEX_DEBUG_MILLISECONDS
  auto start = std::chrono::high_resolution_clock::now();
  call_constructor(stacktrace);
  assert(instrumented_mutex_->start_stacktrace_ == nullptr);
  instrumented_mutex_->start_stacktrace_ = stacktrace;
  instrumented_mutex_->wait_start_ = start;
  instrumented_mutex_->lock_start_ = std::chrono::high_resolution_clock::now();
#endif
}

bool InstrumentedCondVar::TimedWait(uint64_t abs_time_us) {
  PERF_CONDITIONAL_TIMER_FOR_MUTEX_GUARD(
      db_condition_wait_nanos, stats_code_ == DB_MUTEX_WAIT_MICROS,
      stats_for_report(env_, stats_), stats_code_);
  return TimedWaitInternal(abs_time_us);
}

bool InstrumentedCondVar::TimedWaitInternal(uint64_t abs_time_us) {
#if MUTEX_DEBUG_MILLISECONDS
  int64_t lock_dur = std::chrono::duration_cast<std::chrono::microseconds>(
                         std::chrono::high_resolution_clock::now() -
                         instrumented_mutex_->lock_start_)
                         .count();
  assert(instrumented_mutex_->start_stacktrace_ != nullptr);
  auto stacktrace = static_cast<boost::stacktrace::stacktrace*>(
      instrumented_mutex_->start_stacktrace_);
  instrumented_mutex_->start_stacktrace_ = nullptr;
  if (lock_dur > MUTEX_DEBUG_MILLISECONDS * 1000) {
    int64_t wait_dur =
        std::chrono::duration_cast<std::chrono::microseconds>(
            instrumented_mutex_->lock_start_ - instrumented_mutex_->wait_start_)
            .count();
    fprintf(
        stderr,
        "InstrumentedMutex Trace: Lock = %" PRIi64 "us Wait = %" PRIi64
        "us\n--------\n%s--------\n%s--------\n",
        lock_dur, wait_dur, boost::stacktrace::to_string(*stacktrace).c_str(),
        boost::stacktrace::to_string(boost::stacktrace::stacktrace()).c_str());
  }
  call_destructor(stacktrace);
#endif
#ifndef NDEBUG
  ThreadStatusUtil::TEST_StateDelay(ThreadStatus::STATE_MUTEX_WAIT);
#endif
  TEST_SYNC_POINT_CALLBACK("InstrumentedCondVar::TimedWaitInternal",
                           &abs_time_us);

  bool r = cond_.TimedWait(abs_time_us);
#if MUTEX_DEBUG_MILLISECONDS
  auto start = std::chrono::high_resolution_clock::now();
  call_constructor(stacktrace);
  assert(instrumented_mutex_->start_stacktrace_ == nullptr);
  instrumented_mutex_->start_stacktrace_ = stacktrace;
  instrumented_mutex_->wait_start_ = start;
  instrumented_mutex_->lock_start_ = std::chrono::high_resolution_clock::now();
#endif
  return r;
}

}  // namespace rocksdb

ext: cc


text:
#include "judge_daemon.h"
#include "config/config_item.h"
#include "sandboxing/sandbox.h"
#include <iostream>
#include <fstream>
#include <string.h>
#include <dirent.h>
#include <sys/param.h>
#include <sstream>
#include <algorithm>

#include <boost/format.hpp>

// from Stack Overflow:
//     https://stackoverflow.com/questions/35007134/c-boost-undefined-reference-to-boostfilesystemdetailcopy-file
// #define BOOST_NO_CXX11_SCOPED_ENUMS
#include <boost/filesystem.hpp>
#include <boost/filesystem/fstream.hpp>
// #undef BOOST_NO_CXX11_SCOPED_ENUMS

using namespace std;
using namespace boost::filesystem;
using boost::format;

#ifdef __MINGW32__
#include <windows.h>
#include <boost/thread.hpp>
namespace std
{
using boost::mutex;
using boost::lock_guard;
using boost::unique_lock;
}
#else

#endif

//#define USE_CENA_VALIDATOR

enum {
    CMP_tra, CMP_float, CMP_int, CMP_spj
};

bool clean_files() throw() {
    int ret;
#ifdef _WIN32
    ret = system("del /f /q /s *");
#else
    ret = system("rm -f -r *");
#endif
    return ret == 0;
}

solution::solution() {
    TargetPath = getTargetPath();
    QueryMutex = new std::mutex;
    ProblemFK = ComparisonMode = LanguageType = TimeLimit = MemoryLimit = SolutionScore = ErrorCode = 0;
    IsCodeOpenSourced = 0;
    TimeStamp = 0;
    SolutionType = JUDGE_ACTION_NORMAL;
}

solution::~solution() {
    delete QueryMutex;
}

void solution::CloneFrom(const solution &from) throw() {
    ProblemFK = from.ProblemFK;
    ComparisonMode = from.ComparisonMode;
    LanguageType = from.LanguageType;
    TimeLimit = from.TimeLimit;
    MemoryLimit = from.MemoryLimit;
    SolutionScore = from.SolutionScore;
    SolutionType = from.SolutionType;
    TargetPath = from.TargetPath;
}

const string TargetName("target");
const string InputName("user.in");
const string OutputName("user.out");

bool solution::Compile() throw(const char *) {
    puts("compile");
    if (!SystemConf.IsLanguageExists(LanguageType)) {
        throw "Language doesn't exist";
    }
    path sourceCodeFile(TargetName);
    sourceCodeFile = SystemConf.TempDirectory / sourceCodeFile;
    sourceCodeFile.replace_extension(SystemConf.FindLanguage(LanguageType)->FileExtension);

    path targetFile(TargetName);
    targetFile = SystemConf.TempDirectory / targetFile;

    boost::filesystem::ofstream ofs(sourceCodeFile);
    ofs << SourceCode;
    ofs.close();

    /*FILE *code_file = fopen(source.c_str(), "wb");
    if (code_file == NULL) {
        throw "Write code file failed";
    }

    int size = SourceCode.size();
    fwrite(SourceCode.c_str(), 1, size, code_file);
    fclose(code_file);*/

    remove(targetFile);
    path errFile = SystemConf.TempDirectory / "err.out";
    string command = str(format(SystemConf.FindLanguage(LanguageType)->CompilationExec) % sourceCodeFile % targetFile);
    command += (format(" >%1% 2>&1 && echo @~good~@ >%1%") % errFile).str();
    std::cerr << "Executing " << command << endl;
    system(command.c_str());

    FILE *output = fopen(errFile.string().c_str(), "r");
    if (!output) {
        throw "Can't open compiler output";
    }
    char *buffer = new char[65536];
    if (!buffer) {
        throw "FAILED to allocate buffer.";
    }
    int read_size = fread(buffer, 1, 65400, output);
    buffer[read_size] = '\0';
    fclose(output);

    if (exists(targetFile)) {
        if (strstr(buffer, "@~good~@") == NULL) {
            OutputLog("Info: Execute file exists, but compiler doesn't return 0.");
        }
        delete[] buffer;
    } else {
        if (strstr(buffer, "@~good~@") != NULL) {
            delete[] buffer;
            throw "Compiler returned 0, but execute file doesn't exist.";
        } else {
            LastState = buffer;
            SolutionScore = TimeLimit = MemoryLimit = 0;
            ErrorCode = SOLUTION_COMPILATION_ERROR;
            puts("Compile Error");
            delete[] buffer;

            OutputLog("LastState = " + LastState);

            std::unique_lock<std::mutex> Lock(*(std::mutex *) QueryMutex);
            TestCaseDetail.push_back({SOLUTION_COMPILATION_ERROR, 0, 0, LastState, 0});

            return false;
        }
    }
    remove(errFile);
    return true;
}

void solution::Judge() throw(const char *) {
    // Test Code Start -- Yoto
    string testOut;
    testOut += "ProblemFK = " + to_string(ProblemFK) + "\n";
    testOut += "ComparisonMode = " + to_string(ComparisonMode) + "\n";
    testOut += "LanguageType = " + to_string(LanguageType) + "\n";
    testOut += "MemoryLimit = " + to_string(MemoryLimit) + "\n";
    testOut += "SolutionScore = " + to_string(SolutionScore) + "\n";
    testOut += "ErrorCode = " + to_string(ErrorCode) + "\n";
    testOut += "IsCodeOpenSourced = " + to_string(IsCodeOpenSourced) + "\n";
    testOut += "SolutionType = " + to_string(SolutionType) + "\n";
    testOut += "UserName = " + UserName + "\n";
    testOut += "Key = " + Key + "\n";
    testOut += "LastState = " + LastState + "\n";
    testOut += "TimeStamp = " + to_string(TimeStamp) + "\n";
    testOut += "TargetPath = " + string(TargetPath) + "\n";

    int counter = 0;
    for (SingleTestCaseReport &tc : TestCaseDetail) {
        testOut += "TestCaseDetails[" + to_string(counter) + "] = { ";
        testOut += "ErrorCode = " + to_string(tc.ErrorCode) + ", ";
        testOut += "TimeProfile = " + to_string(tc.TimeProfile) + ", ";
        testOut += "MemoryProfile = " + to_string(tc.MemoryProfile) + ", ";
        testOut += "AdditionalInformation" + tc.AdditionalInformation + ", ";
        testOut += "CaseScore" + to_string(tc.CaseScore) + " }\n";
        counter++;
    }

    testOut += "UserCode = " + to_string(ProblemFK) + "\n";
    OutputLog(testOut.c_str());
    // FIXME Test Code End -- Yoto

    char dir_name[MAXPATHLEN + 16], input_filename[MAXPATHLEN + 16];
    char buffer[MAXPATHLEN * 2 + 16];
    puts("judge");

    sprintf(dir_name, "%s/%d", SystemConf.DataDir.c_str(), ProblemFK);
    DIR *dp = opendir(dir_name);
    if (dp == NULL) {
        ErrorCode = SOLUTION_SYSTEM_ERROR;
        LastState = "No data files";
        throw "Can't open data dir";
    }
    std::vector<std::string> in_files;
    struct dirent *ep;
    ep = readdir(dp);
    while (ep) {
        int len = strlen(ep->d_name);
        if (len > 3 && 0 == strcasecmp(ep->d_name + len - 3, ".in")) {
            in_files.push_back(std::string(ep->d_name));
        }
        ep = readdir(dp);
    }
    closedir(dp);
    if (in_files.empty()) {
        ErrorCode = SOLUTION_SYSTEM_ERROR;
        LastState = "No data files";
        throw "Data folder is empty";
    }
    std::sort(in_files.begin(), in_files.end());

    int total_score = 0, total_time = 0, max_memory = 0, dir_len = strlen(dir_name);
    const int full_score = 100;
    int case_score = full_score / in_files.size();
    if (case_score <= 0)
        case_score = 1;

    int status;

    path tempDirectory(SystemConf.TempDir), dataDirectory(dir_name);
    for (std::string &d_name : in_files) {
        std::string tips;
        path inputFile, tempInputFile, outputFile, answerFile;

        inputFile = dataDirectory / d_name;
        tempInputFile = tempDirectory / InputName;
        outputFile = tempDirectory / OutputName;
        answerFile = inputFile;
        answerFile.replace_extension("out");

        try {
            copy_file(inputFile, tempInputFile, copy_option::overwrite_if_exists);
            OutputLog("Temp file created.");
        } catch (filesystem_error &ex) {
            OutputLog("FAILED to create temp file.", ex.what());
            throw ex.what();
        }

        ExecutionResult result;
        int get_score = case_score;

        result = RunSandbox(tempDirectory, TargetName, InputName, OutputName, TimeLimit,
                            (SystemConf.FindLanguage(LanguageType)->ExtraMemory + MemoryLimit) /*to byte*/);
        if (result.Status == EXITED) {
            cerr << "Answer file is: " << answerFile.string() << endl;
            FILE *fanswer = fopen(answerFile.string().c_str(), "rb");
            if (fanswer) {
                FILE *foutput = fopen(outputFile.string().c_str(), "rb"), *finput;
                if (foutput) {
                    ValidatorInfo info;

                    switch (ComparisonMode >> 16) {
                        case CMP_tra:
#ifdef USE_CENA_VALIDATOR
                            info = validator_cena(fanswer, foutput);
#else
                            info = validator(fanswer, foutput);//traditional OI comparison (Ignore trailing space)
#endif
                            break;
                        case CMP_float:
                            info = validator_float(fanswer, foutput, (ComparisonMode & 0xffff)); //precision comparison
                            break;
                        case CMP_int:
                            info = validator_int(fanswer, foutput);
                            break;
                        case CMP_spj:
                            sprintf(input_filename, "%s/%s", dir_name, d_name.c_str());
                            // info = run_spj(buffer, input_filename, &get_score, dir_name);//in call_ruc.cpp
                            break;
                        default:
                            info.Result = -1; //validator error
                    }
                    fclose(foutput);

                    int s = info.Result;
                    if (!s) {
                        status = SOLUTION_ACCEPT;
                        tips = "Good Job!";
                        total_score += get_score;
                    } else if (s == -1) {
                        status = SOLUTION_VALIDATOR_ERROR;
                        tips = "Please contact administrator.";
                        get_score = 0;
                    } else if (s == 4)     // for spj
                    {
                        status = (get_score == case_score) ? SOLUTION_ACCEPT : SOLUTION_WRONG_ANSWER;
                        total_score += get_score;
                        tips = info.UserMismatch;
                        free(info.UserMismatch);
                    } else {
                        status = SOLUTION_WRONG_ANSWER;
                        get_score = 0;
                        if (s == 1) {
                            tips = "Output mismatch.\nYours: ";
                            tips += info.UserMismatch;
                            tips += "\nAnswer: ";
                            tips += info.StandardMismatch;
                            free(info.UserMismatch);
                            free(info.StandardMismatch);
                        } else if (s == 2)
                            tips = "Your output is longer than standard output.";
                        else if (s == 3)
                            tips = "Your output is shorter than standard output.";
                        else //unknown result
                            tips = "";
                    }
                } else {
                    status = SOLUTION_WRONG_ANSWER;
                    get_score = 0;
                    tips = "Cannot find output file.";
                }
                fclose(fanswer);
            } else {
                int err = errno;
                cerr << "Errno is " << errno << endl;
                OutputLog((std::string("Info: No answer file ") + buffer).c_str());
                get_score = 0;
                tips = "No answer file";
                status = SOLUTION_WRONG_ANSWER;
            }
        } else     //RE,TLE,MLE
        {
            get_score = 0;

            /*status = result.State;
            if (status == SOLUTION_RUNTIME_ERROR)
                tips = result.Info;
            else
                tips = "";
                */
            switch (result.Status) {
                case TIME_LIMIT_EXCEEDED:
                    status = SOLUTION_TIME_LIMIT_EXCEEDED;
                    break;
                case MEMORY_LIMIT_EXCEEDED:
                    status = SOLUTION_MEMORY_LIMIT_EXCEEDED;
                    break;
                case BAD_SYSTEM_CALL:
                case SIGNALED:
                    status = SOLUTION_RUNTIME_ERROR;
                    tips = result.Message;
                    break;
                case FAILED:
                    status = SOLUTION_SYSTEM_ERROR;
                    tips = string("System Error.");
                    break;
            }
        }
        total_time += result.Time;
        if (result.Memory > max_memory)
            max_memory = result.Memory;

        printf("status %d %s\n", status, tips.c_str());
        if (ErrorCode == -1 && status != SOLUTION_ACCEPT)  //only store the first error infomation
        {
            ErrorCode = status;
            LastState = tips;
        }

        remove(tempInputFile);
        // remove(outputFile);

        std::unique_lock<std::mutex> Lock(*(std::mutex *) QueryMutex);
        TestCaseDetail.push_back({status, result.Time, result.Memory, tips, get_score});
    }

    if (ErrorCode == -1) //No error
        ErrorCode = SOLUTION_ACCEPT;

    //use score,mem_limit,time_limit to store result
    SolutionScore = total_score / double(case_score * in_files.size()) * full_score + 0.500001;
    MemoryLimit = max_memory;
    TimeLimit = total_time;
    printf("error_code %d, time %dms, memory %dkB, score %d\n", ErrorCode, TimeLimit, MemoryLimit, SolutionScore);
}

void solution::WriteDatabase() throw(const char *) {
    int id = get_next_solution_id();
    printf("solution_id: %d\n", id);
    if (this->UserName.size() == 0)
        throw "User id is empty";
    write_result_to_database(id, this);
}

ext: cpp


text:
/**
 * @file client.hpp
 * @author Marcus Edel
 *
 * Miscellaneous client routines.
 */
#ifndef GYM_CLIENT_HPP
#define GYM_CLIENT_HPP

#include <string>
#include <sstream>

#include <boost/bind.hpp>
#include <boost/asio.hpp>
#include <boost/asio/deadline_timer.hpp>
#include <boost/lambda/lambda.hpp>
#include <boost/lambda/bind.hpp>
#include <boost/iostreams/filtering_stream.hpp>
#include <boost/iostreams/filter/zlib.hpp>
#include <boost/iostreams/copy.hpp>

namespace gym {

using boost::asio::ip::tcp;
using boost::asio::deadline_timer;
using boost::lambda::_1;
using boost::lambda::var;
using boost::lambda::bind;

/**
 * Implementation of the Client.
 */
class Client
{
 public:
  static void async_read_handler(const boost::system::error_code& err,
                                 boost::system::error_code* err_out,
                                 std::size_t bytes_transferred,
                                 std::size_t* bytes_out)
  {
    *err_out = err;
    *bytes_out = bytes_transferred;
  }

  /**
   * Create the Client object using the given host and port.
   *
   * @param host The hostname to connect.
   * @param port The port used for the connection.
   */
  Client() :
      s(io_service),
      deadline(io_service),
      compressionLevel(0)
  {
    deadline.expires_at(boost::posix_time::pos_infin);

    // Start the persistent actor that checks for deadline expiry.
    check_deadline();
  }

  ~Client()
  {
    // The socket is closed so that any outstanding asynchronous operations are
    // cancelled. This allows the blocked connect(), read_line() or write_line()
    // functions to return.
    boost::system::error_code ignored_ec;
    s.close(ignored_ec);
  }

  void connect(const std::string& host, const std::string& port)
  {
    tcp::resolver resolver(io_service);
    tcp::resolver::query query(tcp::v4(), host, port);
    tcp::resolver::iterator iterator = resolver.resolve(query);

    // Set a deadline for the asynchronous operation.
    deadline.expires_from_now(boost::posix_time::seconds(10));

    // Set up the variable that receives the result of the asynchronous
    // operation.
    boost::system::error_code ec = boost::asio::error::would_block;

    // Start the asynchronous operation.
    boost::asio::async_connect(s, iterator, var(ec) = _1);

    // Block until the asynchronous operation has completed.
    do io_service.run_one(); while (ec == boost::asio::error::would_block);

    // Determine whether a connection was successfully established.
    if (ec || !s.is_open())
    {
      throw boost::system::system_error(
          ec ? ec : boost::asio::error::operation_aborted);
    }
  }

  /**
   * Receive a message using the currently open socket.
   *
   * @param data The received data.
   */
  void receive(std::string& data)
  {
    // Set a deadline for the asynchronous operation.
    deadline.expires_from_now(boost::posix_time::seconds(10));

    // Set up the variable that receives the result of the asynchronous
    // operation.
    boost::system::error_code ec = boost::asio::error::would_block;

    boost::asio::streambuf response;
    size_t reply_length;

    boost::asio::async_read_until(s, response, "\r\n\r\n",
        boost::bind(async_read_handler, boost::asio::placeholders::error, &ec,
        boost::asio::placeholders::bytes_transferred, &reply_length));

    // Block until the asynchronous operation has completed.
    do io_service.run_one(); while (ec == boost::asio::error::would_block);

    if (ec)
    {
      throw boost::system::system_error(ec);
    }

    data = std::string(
        boost::asio::buffers_begin(response.data()),
        boost::asio::buffers_begin(response.data()) + reply_length);

    if (compressionLevel > 0)
    {
      boost::iostreams::filtering_streambuf<boost::iostreams::input> in;
      in.push( boost::iostreams::zlib_decompressor());
      in.push(boost::iostreams::array_source(data.data(), data.size()));

      std::stringstream ss;
      boost::iostreams::copy(in, ss);
      data = ss.str();
    }
  }

  /**
   * Send a message using the currently open socket.
   *
   * @param data The data to be send.
   */
  void send(const std::string& data)
  {
    // Set a deadline for the asynchronous operation.
    deadline.expires_from_now(boost::posix_time::seconds(10));

    // Set up the variable that receives the result of the asynchronous
    // operation.
    boost::system::error_code ec = boost::asio::error::would_block;

    std::string d = data  + "\r\n";

    boost::asio::async_write(s, boost::asio::buffer(d),
        boost::asio::transfer_exactly(d.size()), var(ec) = _1);

    // Block until the asynchronous operation has completed.
    do io_service.run_one(); while (ec == boost::asio::error::would_block);

    if (ec)
    {
      throw boost::system::system_error(ec);
    }
  }

  /*
   * The compression level in range [0, 9] where 0 means no compression used for
   * receiving data.
   *
   * @param compression The compression level.
   */
  void compression(const size_t compression)
  {
    compressionLevel = compression;
  }

 private:
  void check_deadline()
  {
    // Check whether the deadline has passed. We compare the deadline against
    // the current time since a new asynchronous operation may have moved the
    // deadline before this actor had a chance to run.
    if (deadline.expires_at() <= deadline_timer::traits_type::now())
    {
      // There is no longer an active deadline. The expiry is set to positive
      // infinity so that the actor takes no action until a new deadline is set.
      deadline.expires_at(boost::posix_time::pos_infin);
    }

    // Put the actor back to sleep.
    deadline.async_wait(bind(&Client::check_deadline, this));
  }

  //! Locally stored io service.
  boost::asio::io_service io_service;

  //! Locally stored socket object.
  tcp::socket s;

  //! Object to control connection timeouts.
  deadline_timer deadline;

  //! Locally-stored compression parameter.
  size_t compressionLevel;
}; // class Client

} // namespace gym

#endif

ext: hpp

max_stars_repo_name: zsogitbe/models

max_issues_repo_name: zsogitbe/models

max_forks_repo_name: zsogitbe/models


text:
/*
 * Copyright (C) 2019 Intel Corporation
 *
 * SPDX-License-Identifier: MIT
 *
 */

#ifndef COMPUTE_SAMPLES_VME_SEARCH_HPP
#define COMPUTE_SAMPLES_VME_SEARCH_HPP

#include <vector>

#include <boost/compute/core.hpp>

#include "application/application.hpp"
#include "yuv_utils/yuv_utils.hpp"

namespace compute_samples {
class VmeSearchApplication : public Application {
private:
  Status run_implementation(std::vector<std::string> &command_line) override;
  struct Arguments {
    bool output_bmp = false;
    std::string sub_test = "";
    std::string input_yuv_path = "";
    std::string output_yuv_path = "";
    int qp = 0;
    int width = 0;
    int height = 0;
    int frames = 0;
    bool help = false;
  };

  void run_vme_search(const VmeSearchApplication::Arguments &args,
                      boost::compute::context &context,
                      boost::compute::command_queue &queue,
                      boost::compute::kernel &kernel, YuvCapture &capture,
                      PlanarImage &src_planar_image,
                      boost::compute::image2d &src_image,
                      boost::compute::image2d &ref_image, int frame_idx) const;
  Arguments parse_command_line(const std::vector<std::string> &command_line);
};
} // namespace compute_samples

#endif


text:
#include "RooRealVar.h"
#include "RooRealConstant.h"
#include "RooGaussian.h"
#include "RooExponential.h"
#include "RooAddPdf.h"
#include "RooAddition.h"
#include "RooDataSet.h"
#include "RooDataHist.h"
#include "RooHistPdf.h"
#include "RooChebychev.h"
#include "RooExponential.h"
#include "RooProdPdf.h"
#include "RooChi2Var.h"
#include "RooGlobalFunc.h"
#include "RooPlot.h"
#include "RooMinuit.h"
#include "RooFitResult.h"
#include "RooFormulaVar.h"
#include "RooGenericPdf.h"
#include "RooExtendPdf.h"
#include "TCanvas.h"
#include "TROOT.h"
#include "TFile.h"
#include "TH1.h"
#include "RooNLLVar.h"
#include "RooRandom.h"
#include "TRandom3.h"
#include <iostream>
#include <fstream>
#include <boost/program_options.hpp>
using namespace boost;
namespace po = boost::program_options;
#include <vector>

using namespace std;
using namespace RooFit;

// A function that get histogram, restricting it on fit range  and sets contents to 0.0 if entries are too small

TH1F *getHisto(TFile *file, const char *name, double fMin, double fMax, unsigned int rebin) {
  TObject *h = file->Get(name);
  if (h == nullptr)
    cout << "Can't find object " << name << "\n";
  TH1F *histo = dynamic_cast<TH1F *>(h);
  if (histo == nullptr)
    cout << "Object " << name << " is of type " << h->ClassName() << ", not TH1\n";
  TH1F *new_histo = new TH1F(name, name, (int)(fMax - fMin), fMin, fMax);
  int bin_num = 0;
  for (int i = (int)fMin; i <= (int)fMax; ++i) {
    bin_num = (i - (int)fMin + 1);
    new_histo->SetBinContent(bin_num, histo->GetBinContent(i));
  }
  delete histo;
  new_histo->Sumw2();
  new_histo->Rebin(rebin);
  for (int i = 1; i <= new_histo->GetNbinsX(); ++i) {
    if (new_histo->GetBinContent(i) == 0.00) {
      cout << " WARNING: histo " << name << " has 0 enter in bin number " << i << endl;
    }
    if (new_histo->GetBinContent(i) < 0.1) {
      new_histo->SetBinContent(i, 0.0);
      new_histo->SetBinError(i, 0.0);
      cout << " WARNING: setting value 0.0 to histo " << name << " for bin number " << i << endl;
    }
  }

  return new_histo;
}

// a function that create fromm a model pdf a toy RooDataHist

RooDataHist *genHistFromModelPdf(
    const char *name, RooAbsPdf *model, RooRealVar *var, double ScaleLumi, int range, int rebin, int seed) {
  double genEvents = model->expectedEvents(*var);
  TRandom3 *rndm = new TRandom3();
  rndm->SetSeed(seed);
  double nEvt = rndm->PoissonD(genEvents);
  int intEvt = ((nEvt - (int)nEvt) >= 0.5) ? (int)nEvt + 1 : int(nEvt);
  RooDataSet *data = model->generate(*var, intEvt);
  cout << " expected events for " << name << " = " << genEvents << endl;
  cout << " data->numEntries() for name " << name << " == " << data->numEntries() << endl;
  // cout<< " nEvt from PoissonD for" << name << " == " << nEvt<< endl;
  //cout<< " cast of nEvt  for" << name << " == " << intEvt<< endl;
  RooAbsData *binned_data = data->binnedClone();
  TH1 *toy_hist = binned_data->createHistogram(name, *var, Binning(range / rebin));
  for (int i = 1; i <= toy_hist->GetNbinsX(); ++i) {
    toy_hist->SetBinError(i, sqrt(toy_hist->GetBinContent(i)));
    if (toy_hist->GetBinContent(i) == 0.00) {
      cout << " WARNING: histo " << name << " has 0 enter in bin number " << i << endl;
    }
    if (toy_hist->GetBinContent(i) < 0.1) {
      toy_hist->SetBinContent(i, 0.0);
      toy_hist->SetBinError(i, 0.0);
      cout << " WARNING: setting value 0.0 to histo " << name << " for bin number " << i << endl;
    }
  }
  RooDataHist *toy_rooHist = new RooDataHist(name, name, RooArgList(*var), toy_hist);
  return toy_rooHist;
}

// a function to create the pdf used for the fit, need the histo model, should be zmm except for zmusta case.....

RooHistPdf *createHistPdf(const char *name, TH1F *model, RooRealVar *var, int rebin) {
  TH1F *model_clone = new TH1F(*model);
  model_clone->Sumw2();
  model_clone->Rebin(rebin);
  RooDataHist *model_dataHist = new RooDataHist(name, name, RooArgList(*var), model_clone);
  RooHistPdf *HistPdf = new RooHistPdf(name, name, *var, *model_dataHist, 0);
  delete model_clone;
  return HistPdf;
}

void fit(RooAbsReal &chi2, int numberOfBins, const char *outFileNameWithFitResult) {
  TFile *out_root_file = new TFile(outFileNameWithFitResult, "recreate");
  RooMinuit m_tot(chi2);
  m_tot.migrad();
  // m_tot.hesse();
  RooFitResult *r_chi2 = m_tot.save();
  cout << "==> Chi2 Fit results " << endl;
  r_chi2->Print("v");
  //  r_chi2->floatParsFinal().Print("v") ;
  int NumberOfFreeParameters = r_chi2->floatParsFinal().getSize();
  for (int i = 0; i < NumberOfFreeParameters; ++i) {
    r_chi2->floatParsFinal()[i].Print();
  }
  cout << "chi2:" << chi2.getVal() << ", numberOfBins: " << numberOfBins
       << ", NumberOfFreeParameters: " << NumberOfFreeParameters << endl;
  cout << "Normalized Chi2   = " << chi2.getVal() / (numberOfBins - NumberOfFreeParameters) << endl;
  r_chi2->Write();
  delete out_root_file;
}

int main(int argc, char **argv) {
  gROOT->SetStyle("Plain");
  double fMin, fMax, lumi, scaleLumi = 1;
  int seed;
  Bool_t toy = kFALSE;
  Bool_t fitFromData = kFALSE;
  string infile, outfile;
  int rebinZMuMu = 1, rebinZMuSa = 1, rebinZMuTk = 1, rebinZMuMuNoIso = 1, rebinZMuMuHlt = 1;
  po::options_description desc("Allowed options");
  desc.add_options()("help,h", "produce help message")("toy,t", "toy enabled")(
      "seed,s", po::value<int>(&seed)->default_value(34567), "seed value for toy")(
      "luminosity,l", po::value<double>(&lumi)->default_value(45.), "luminosity value for toy ")(
      "fit,f", "fit from data enabled")(
      "rebin,r", po::value<vector<int> >(), "rebin value: r_mutrk r mumuNotIso r_musa r _muhlt")(
      "input-file,i", po::value<string>(&infile), "input file")(
      "output-file,o", po::value<string>(&outfile), "output file with fit results")(
      "min,m", po::value<double>(&fMin)->default_value(60), "minimum value for fit range")(
      "max,M", po::value<double>(&fMax)->default_value(120), "maximum value for fit range");
  po::positional_options_description p;
  p.add("rebin", -1);
  po::variables_map vm;
  po::store(po::command_line_parser(argc, argv).options(desc).positional(p).run(), vm);
  po::notify(vm);
  if (vm.count("help")) {
    cout << "Usage: options_description [options]\n";
    cout << desc;
    return 0;
  }

  if (vm.count("toy")) {
    cout << "toy enabled with seed " << seed << "\n";
    toy = kTRUE;
    //RooRandom::randomGenerator()->SetSeed(seed) ;
    // lumi should be intented as pb-1 and passed from outside
    scaleLumi = lumi / 45.0;  // 45 is the current lumi correspondent to the histogram.....
  }
  if (vm.count("fit")) {
    cout << "fit from data enabled \n";
    fitFromData = kTRUE;
  }

  if (!vm.count("toy") && !vm.count("fit")) {
    cerr << "Choose one beetween  fitting form data or with a toy MC \n";
    return 1;
  }

  if (toy == fitFromData) {
    cerr << "Choose if fit from data or with a toy MC \n";
    return 1;
  }

  if (vm.count("rebin")) {
    vector<int> v_rebin = vm["rebin"].as<vector<int> >();
    if (v_rebin.size() != 4) {
      cerr << " please provide 4 numbers in the given order:r_mutrk r mumuNotIso r_musa r _muhlt \n";
      return 1;
    }
    rebinZMuTk = v_rebin[0];
    rebinZMuMuNoIso = v_rebin[1];
    rebinZMuSa = v_rebin[2];
    rebinZMuMuHlt = v_rebin[3];
  }

  RooRealVar *mass = new RooRealVar("mass", "mass (GeV/c^{2})", fMin, fMax);
  TFile *root_file = new TFile(infile.c_str(), "read");
  int range = (int)(fMax - fMin);
  int numberOfBins = range / rebinZMuSa + range / rebinZMuTk + range / rebinZMuMuNoIso + 2 * range / rebinZMuMuHlt;
  // zmm histograms used for pdf
  TH1F *zmm = getHisto(root_file, "goodZToMuMuPlots/zMass", fMin, fMax, rebinZMuMu);
  // zmsta used for pdf
  TH1F *zmsta = getHisto(root_file, "zmumuSaMassHistogram/zMass", fMin, fMax, 1);  // histogramms to fit.....
  TH1F *zmmsta = getHisto(root_file, "goodZToMuMuOneStandAloneMuonPlots/zMass", fMin, fMax, rebinZMuSa / rebinZMuMu);
  TH1F *zmt = getHisto(root_file, "goodZToMuMuOneTrackPlots/zMass", fMin, fMax, rebinZMuTk / rebinZMuMu);
  TH1F *zmmNotIso = getHisto(root_file, "nonIsolatedZToMuMuPlots/zMass", fMin, fMax, rebinZMuMuNoIso / rebinZMuMu);
  TH1F *zmm1hlt = getHisto(root_file, "goodZToMuMu1HLTPlots/zMass", fMin, fMax, rebinZMuMuHlt / rebinZMuMu);
  TH1F *zmm2hlt = getHisto(root_file, "goodZToMuMu2HLTPlots/zMass", fMin, fMax, rebinZMuMuHlt / rebinZMuMu);

  // creating a pdf for Zmt

  RooHistPdf *ZmtPdf = createHistPdf("ZmtPdf", zmm, mass, rebinZMuTk / rebinZMuMu);
  // creating a pdf for Zmm not iso
  RooHistPdf *ZmmNoIsoPdf = createHistPdf("ZmmNoIsoPdf", zmm, mass, rebinZMuMuNoIso / rebinZMuMu);
  // creating a pdf for Zms from zmsta!!!
  RooHistPdf *ZmsPdf = createHistPdf("ZmsPdf", zmsta, mass, rebinZMuSa / rebinZMuMu);
  // creating a pdf for Zmmhlt
  RooHistPdf *ZmmHltPdf = createHistPdf("ZmmHltPdf", zmm, mass, rebinZMuMuHlt / rebinZMuMu);

  // creating the variable with random init values

  RooRealVar Yield("Yield", "Yield", 15000., 345., 3567890.);
  RooRealVar nbkg_mutrk("nbkg_mutrk", "background _mutrk fraction", 500, 0., 100000.);
  RooRealVar nbkg_mumuNotIso("nbkg_mumuNotIso", "background fraction", 500, 0., 100000.);
  RooRealVar nbkg_musa("nbkg_musa", "background fraction", 50, 0., 100000.);
  RooRealVar eff_tk("eff_tk", "signal _mutrk fraction", .99, 0.8, 1.0);
  RooRealVar eff_sa("eff_sa", "eff musta", 0.99, 0.8, 1.0);
  RooRealVar eff_iso("eff_iso", "eff mumuNotIso", .99, 0.8, 1.0);
  RooRealVar eff_hlt("eff_hlt", "eff 1hlt", 0.99, 0.8, 1.0);
  RooRealVar alpha("alpha", "coefficient alpha", -0.01, -1000, 1000.);
  RooRealVar a0("a0", "coefficient 0", 1, -1000., 1000.);
  RooRealVar a1("a1", "coefficient 1", -0.001, -1000, 1000.);
  RooRealVar a2("a2", "coefficient 2", 0.0, -1000., 1000.);
  RooRealVar beta("beta", "coefficient beta", -0.01, -1000, 1000.);
  RooRealVar b0("b0", "coefficient 0", 1, -1000., 1000.);
  RooRealVar b1("b1", "coefficient 1", -0.001, -1000, 1000.);
  RooRealVar b2("b2", "coefficient 2", 0.0, -1000., 1000.);
  RooRealVar gamma("gamma", "coefficient gamma", -0.01, -1000, 1000.);
  RooRealVar c0("c0", "coefficient 0", 1, -1000., 1000.);
  RooRealVar c1("c1", "coefficient 1", -0.001, -1000, 1000.);
  // fit parameters setted from datacard
  filebuf fb;
  fb.open("zMuMuRooFit.txt", ios::in);
  istream is(&fb);
  char line[1000];

  Yield.readFromStream(is.getline(line, 1000), kFALSE);
  nbkg_mutrk.readFromStream(is.getline(line, 1000), kFALSE);
  nbkg_mumuNotIso.readFromStream(is.getline(line, 1000), kFALSE);
  nbkg_musa.readFromStream(is.getline(line, 1000), kFALSE);
  eff_tk.readFromStream(is.getline(line, 1000), kFALSE);
  eff_sa.readFromStream(is.getline(line, 1000), kFALSE);
  eff_iso.readFromStream(is.getline(line, 1000), kFALSE);
  eff_hlt.readFromStream(is.getline(line, 1000), kFALSE);
  alpha.readFromStream(is.getline(line, 1000), kFALSE);
  a0.readFromStream(is.getline(line, 1000), kFALSE);
  a1.readFromStream(is.getline(line, 1000), kFALSE);
  a2.readFromStream(is.getline(line, 1000), kFALSE);
  beta.readFromStream(is.getline(line, 1000), kFALSE);
  b0.readFromStream(is.getline(line, 1000), kFALSE);
  b1.readFromStream(is.getline(line, 1000), kFALSE);
  b2.readFromStream(is.getline(line, 1000), kFALSE);
  gamma.readFromStream(is.getline(line, 1000), kFALSE);
  c0.readFromStream(is.getline(line, 1000), kFALSE);
  c1.readFromStream(is.getline(line, 1000), kFALSE);
  fb.close();

  // scaling to lumi if toy is enabled...
  if (vm.count("toy")) {
    Yield.setVal(scaleLumi * (Yield.getVal()));
    nbkg_mutrk.setVal(scaleLumi * (nbkg_mutrk.getVal()));
    nbkg_mumuNotIso.setVal(scaleLumi * (nbkg_mumuNotIso.getVal()));
  }

  //efficiency term

  //zMuMuEff1HLTTerm = _2 * (effTk ^ _2) *  (effSa ^ _2) * (effIso ^ _2) * effHLT * (_1 - effHLT);
  RooFormulaVar zMuMu1HLTEffTerm(
      "zMuMu1HLTEffTerm",
      "Yield * (2.* (eff_tk)^2 * (eff_sa)^2 * (eff_iso)^2 * eff_hlt *(1.- eff_hlt))",
      RooArgList(eff_tk,
                 eff_sa,
                 eff_iso,
                 eff_hlt,
                 Yield));  //zMuMuEff2HLTTerm = (effTk ^ _2) *  (effSa ^ _2) * (effIso ^ _2) * (effHLT ^ _2) ;
  RooFormulaVar zMuMu2HLTEffTerm("zMuMu2HLTEffTerm",
                                 "Yield * ((eff_tk)^2 * (eff_sa)^2 * (eff_iso)^2 * (eff_hlt)^2)",
                                 RooArgList(eff_tk, eff_sa, eff_iso, eff_hlt, Yield));
  //zMuMuNoIsoEffTerm = (effTk ^ _2) * (effSa ^ _2) * (_1 - (effIso ^ _2)) * (_1 - ((_1 - effHLT)^_2));
  RooFormulaVar zMuMuNoIsoEffTerm("zMuMuNoIsoEffTerm",
                                  "Yield * ((eff_tk)^2 * (eff_sa)^2 * (1.- (eff_iso)^2) * (1.- ((1.-eff_hlt)^2)))",
                                  RooArgList(eff_tk, eff_sa, eff_iso, eff_hlt, Yield));
  //zMuTkEffTerm = _2 * (effTk ^ _2) * effSa * (_1 - effSa) * (effIso ^ _2) * effHLT;
  RooFormulaVar zMuTkEffTerm("zMuTkEffTerm",
                             "Yield * (2. *(eff_tk)^2 * eff_sa * (1.-eff_sa)* (eff_iso)^2 * eff_hlt)",
                             RooArgList(eff_tk, eff_sa, eff_iso, eff_hlt, Yield));
  //zMuSaEffTerm = _2 * (effSa ^ _2) * effTk * (_1 - effTk) * (effIso ^ _2) * effHLT;
  RooFormulaVar zMuSaEffTerm("zMuSaEffTerm",
                             "Yield * (2. *(eff_sa)^2 * eff_tk * (1.-eff_tk)* (eff_iso)^2 * eff_hlt)",
                             RooArgList(eff_tk, eff_sa, eff_iso, eff_hlt, Yield));

  // creating model for the  fit
  // z mu track

  RooGenericPdf *bkg_mutrk = new RooGenericPdf("bkg_mutrk",
                                               "zmt bkg_model",
                                               "exp(alpha*mass) * ( a0 + a1 * mass + a2 * mass^2 )",
                                               RooArgSet(*mass, alpha, a0, a1, a2));
  // RooFormulaVar fracSigMutrk("fracSigMutrk", "@0 / (@0 + @1)", RooArgList(zMuTkEffTerm, nbkg_mutrk ));
  RooAddPdf *model_mutrk = new RooAddPdf(
      "model_mutrk", "model_mutrk", RooArgList(*ZmtPdf, *bkg_mutrk), RooArgList(zMuTkEffTerm, nbkg_mutrk));
  // z mu mu not Iso

  // creating background pdf for zmu mu not Iso
  RooGenericPdf *bkg_mumuNotIso = new RooGenericPdf("bkg_mumuNotIso",
                                                    "zmumuNotIso bkg_model",
                                                    "exp(beta * mass) * (b0 + b1 * mass + b2 * mass^2)",
                                                    RooArgSet(*mass, beta, b0, b1, b2));
  // RooFormulaVar fracSigMuMuNoIso("fracSigMuMuNoIso", "@0 / (@0 + @1)", RooArgList(zMuMuNoIsoEffTerm, nbkg_mumuNotIso ));
  RooAddPdf *model_mumuNotIso = new RooAddPdf("model_mumuNotIso",
                                              "model_mumuNotIso",
                                              RooArgList(*ZmmNoIsoPdf, *bkg_mumuNotIso),
                                              RooArgList(zMuMuNoIsoEffTerm, nbkg_mumuNotIso));
  // z mu sta

  // RooGenericPdf model_musta("model_musta",  " ZmsPdf * zMuSaEffTerm ", RooArgSet( *ZmsPdf, zMuSaEffTerm)) ;
  RooGenericPdf *bkg_musa = new RooGenericPdf(
      "bkg_musa", "zmusa bkg_model", "exp(gamma * mass) * (c0 + c1 * mass )", RooArgSet(*mass, gamma, c0, c1));
  // RooAddPdf * eZmsSig= new RooAddPdf("eZmsSig","eZmsSig",RooArgList(*,*bkg_mumuNotIso), RooArgList(zMuMuNoIsoEffTerm, nbkg_mumuNotIso));
  RooAddPdf *eZmsSig =
      new RooAddPdf("eZmsSig", "eZmsSig", RooArgList(*ZmsPdf, *bkg_musa), RooArgList(zMuSaEffTerm, nbkg_musa));

  //RooExtendPdf * eZmsSig= new RooExtendPdf("eZmsSig","extended signal p.d.f for zms ",*ZmsPdf,  zMuSaEffTerm ) ;

  // z mu mu HLT

  // count ZMuMu Yield
  double nZMuMu = 0.;
  double nZMuMu1HLT = 0.;
  double nZMuMu2HLT = 0.;
  unsigned int nBins = zmm->GetNbinsX();
  double xMin = zmm->GetXaxis()->GetXmin();
  double xMax = zmm->GetXaxis()->GetXmax();
  double deltaX = (xMax - xMin) / nBins;
  for (unsigned int i = 0; i < nBins; ++i) {
    double x = xMin + (i + .5) * deltaX;
    if (x > fMin && x < fMax) {
      nZMuMu += zmm->GetBinContent(i + 1);
      nZMuMu1HLT += zmm1hlt->GetBinContent(i + 1);
      nZMuMu2HLT += zmm2hlt->GetBinContent(i + 1);
    }
  }

  cout << ">>> count of ZMuMu yield in the range [" << fMin << ", " << fMax << "]: " << nZMuMu << endl;
  cout << ">>> count of ZMuMu (1HLT) yield in the range [" << fMin << ", " << fMax << "]: " << nZMuMu1HLT << endl;
  cout << ">>> count of ZMuMu (2HLT) yield in the range [" << fMin << ", " << fMax << "]: " << nZMuMu2HLT << endl;
  // we set eff_hlt
  //eff_hlt.setVal( 1. / (1. + (nZMuMu1HLT/ (2 * nZMuMu2HLT))) ) ;
  // creating the pdf for z mu mu 1hlt

  RooExtendPdf *eZmm1hltSig =
      new RooExtendPdf("eZmm1hltSig", "extended signal p.d.f for zmm 1hlt", *ZmmHltPdf, zMuMu1HLTEffTerm);
  // creating the pdf for z mu mu 2hlt
  RooExtendPdf *eZmm2hltSig =
      new RooExtendPdf("eZmm2hltSig", "extended signal p.d.f for zmm 2hlt", *ZmmHltPdf, zMuMu2HLTEffTerm);

  // getting the data if fit otherwise constructed the data for model if toy....

  RooDataHist *zmtMass, *zmmNotIsoMass, *zmsMass, *zmm1hltMass, *zmm2hltMass;

  if (toy) {
    zmtMass = genHistFromModelPdf("zmtMass", model_mutrk, mass, scaleLumi, range, rebinZMuTk, seed);
    zmmNotIsoMass =
        genHistFromModelPdf("zmmNotIsoMass", model_mumuNotIso, mass, scaleLumi, range, rebinZMuMuNoIso, seed);
    zmsMass = genHistFromModelPdf("zmsMass", eZmsSig, mass, scaleLumi, range, rebinZMuSa, seed);
    zmm1hltMass = genHistFromModelPdf("zmm1hltMass", eZmm1hltSig, mass, scaleLumi, range, rebinZMuMuHlt, seed);
    zmm2hltMass = genHistFromModelPdf("zmm2hltMass", eZmm2hltSig, mass, scaleLumi, range, rebinZMuMuHlt, seed);
  } else {  // if  fit from data....
    zmtMass = new RooDataHist("zmtMass", "good z mu track", RooArgList(*mass), zmt);
    zmmNotIsoMass = new RooDataHist("ZmmNotIso", "good z mu mu not isolated", RooArgList(*mass), zmmNotIso);
    zmsMass = new RooDataHist("zmsMass", "good z mu sta mass", RooArgList(*mass), zmmsta);
    zmm1hltMass = new RooDataHist("zmm1hltMass", "good Z mu mu 1hlt", RooArgList(*mass), zmm1hlt);
    zmm2hltMass = new RooDataHist("zmm2hltMass", "good Z mu mu 2hlt", RooArgList(*mass), zmm2hlt);
  }

  // creting the chi2s
  RooChi2Var *chi2_mutrk =
      new RooChi2Var("chi2_mutrk", "chi2_mutrk", *model_mutrk, *zmtMass, Extended(kTRUE), DataError(RooAbsData::SumW2));
  RooChi2Var *chi2_mumuNotIso = new RooChi2Var("chi2_mumuNotIso",
                                               "chi2_mumuNotIso",
                                               *model_mumuNotIso,
                                               *zmmNotIsoMass,
                                               Extended(kTRUE),
                                               DataError(RooAbsData::SumW2));

  RooChi2Var *chi2_musta =
      new RooChi2Var("chi2_musta", "chi2_musta", *eZmsSig, *zmsMass, Extended(kTRUE), DataError(RooAbsData::SumW2));
  // uncomment this line if you want to use logLik for mu sta
  // RooNLLVar *chi2_musta = new RooNLLVar("chi2_musta","chi2_musta",*eZmsSig, *zmsMass,  Extended(kTRUE), DataError(RooAbsData::SumW2) ) ;
  RooChi2Var *chi2_mu1hlt = new RooChi2Var(
      "chi2_mu1hlt", "chi2_mu1hlt", *eZmm1hltSig, *zmm1hltMass, Extended(kTRUE), DataError(RooAbsData::SumW2));
  RooChi2Var *chi2_mu2hlt = new RooChi2Var(
      "chi2_mu2hlt", "chi2_mu2hlt", *eZmm2hltSig, *zmm2hltMass, Extended(kTRUE), DataError(RooAbsData::SumW2));

  // adding the chi2
  RooAddition totChi2("totChi2",
                      "chi2_mutrk + chi2_mumuNotIso  + chi2_musta   + chi2_mu1hlt  +  chi2_mu2hlt ",
                      RooArgSet(*chi2_mutrk, *chi2_mumuNotIso, *chi2_musta, *chi2_mu1hlt, *chi2_mu2hlt));

  // printing out the model integral befor fitting
  double N_zMuMu1hlt = eZmm1hltSig->expectedEvents(*mass);
  double N_bkgTk = bkg_mutrk->expectedEvents(*mass);
  double N_bkgIso = bkg_mumuNotIso->expectedEvents(*mass);

  double N_zMuTk = zMuTkEffTerm.getVal();

  double e_hlt = eff_hlt.getVal();
  double e_tk = eff_tk.getVal();
  double e_sa = eff_sa.getVal();
  double e_iso = eff_iso.getVal();
  double Y_hlt = N_zMuMu1hlt / ((2. * (e_tk * e_tk) * (e_sa * e_sa) * (e_iso * e_iso) * e_hlt * (1. - e_hlt)));
  double Y_mutk = N_zMuTk / ((2. * (e_tk * e_tk) * e_sa * (1. - e_sa) * (e_iso * e_iso) * e_hlt));

  cout << "Yield prediction from mumu1hlt integral befor fitting: " << Y_hlt << endl;
  cout << "Yield prediction from mutk integral befor fitting: " << Y_mutk << endl;
  cout << "Bkg for mutk prediction from mutk integral after fitting: " << N_bkgTk << endl;
  cout << "Bkg for mumuNotIso prediction from mumuNotIso integral after fitting: " << N_bkgIso << endl;

  fit(totChi2, numberOfBins, outfile.c_str());
  N_zMuMu1hlt = eZmm1hltSig->expectedEvents(*mass);
  N_zMuTk = zMuTkEffTerm.getVal();
  double N_zMuMuNoIso = zMuMuNoIsoEffTerm.getVal();
  double N_Tk = model_mutrk->expectedEvents(*mass);
  double N_Iso = model_mumuNotIso->expectedEvents(*mass);
  e_hlt = eff_hlt.getVal();
  e_tk = eff_tk.getVal();
  e_sa = eff_sa.getVal();
  e_iso = eff_iso.getVal();
  Y_hlt = N_zMuMu1hlt / ((2. * (e_tk * e_tk) * (e_sa * e_sa) * (e_iso * e_iso) * e_hlt * (1. - e_hlt)));
  Y_mutk = N_zMuTk / ((2. * (e_tk * e_tk) * e_sa * (1. - e_sa) * (e_iso * e_iso) * e_hlt));

  cout << "Yield prediction from mumu1hlt integral after fitting: " << Y_hlt << endl;
  //cout << "Yield prediction from mutk integral after fitting: " <<  Y_mutk << endl;
  cout << "N + B  prediction from mutk integral after fitting: " << N_Tk << endl;
  cout << "zMuTkEffTerm " << N_zMuTk << endl;
  cout << "N + B  prediction from mumuNotIso integral after fitting: " << N_Iso << endl;
  cout << "zMuMuNoIsoEffTerm " << N_zMuMuNoIso << endl;

  cout << "chi2_mutrk:" << chi2_mutrk->getVal() << endl;
  cout << "chi2_mumuNotIso:" << chi2_mumuNotIso->getVal() << endl;
  cout << "chi2_musta:" << chi2_musta->getVal() << endl;
  cout << "chi2_mumu1hlt:" << chi2_mu1hlt->getVal() << endl;
  cout << "chi2_mumu2hlt:" << chi2_mu2hlt->getVal() << endl;

  //plotting
  RooPlot *massFrame_mutrk = mass->frame();
  RooPlot *massFrame_mumuNotIso = mass->frame();
  RooPlot *massFrame_musta = mass->frame();
  RooPlot *massFrame_mumu1hlt = mass->frame();
  RooPlot *massFrame_mumu2hlt = mass->frame();

  TCanvas *canv1 = new TCanvas("canvas");
  TCanvas *canv2 = new TCanvas("new_canvas");
  canv1->Divide(2, 3);
  canv1->cd(1);
  canv1->SetLogy(kTRUE);
  zmtMass->plotOn(massFrame_mutrk, LineColor(kBlue));
  model_mutrk->plotOn(massFrame_mutrk, LineColor(kRed));
  model_mutrk->plotOn(massFrame_mutrk, Components(*bkg_mutrk), LineColor(kGreen));
  massFrame_mutrk->SetTitle("Z -> #mu track");
  // massFrame_mutrk->GetYaxis()->SetLogScale();
  massFrame_mutrk->Draw();
  gPad->SetLogy(1);

  canv2->cd();
  canv2->SetLogy(kTRUE);
  massFrame_mutrk->Draw();
  canv2->SaveAs("LogZMuTk.eps");
  canv2->SetLogy(kFALSE);
  canv2->SaveAs("LinZMuTk.eps");

  canv1->cd(2);
  zmmNotIsoMass->plotOn(massFrame_mumuNotIso, LineColor(kBlue));
  model_mumuNotIso->plotOn(massFrame_mumuNotIso, LineColor(kRed));
  model_mumuNotIso->plotOn(massFrame_mumuNotIso, Components(*bkg_mumuNotIso), LineColor(kGreen));
  massFrame_mumuNotIso->SetTitle("Z -> #mu #mu not isolated");
  massFrame_mumuNotIso->Draw();
  gPad->SetLogy(1);

  canv2->cd();
  canv2->Clear();
  canv2->SetLogy(kTRUE);
  massFrame_mumuNotIso->Draw();
  canv2->SaveAs("LogZMuMuNotIso.eps");
  canv2->SetLogy(kFALSE);
  canv2->SaveAs("LinZMuMuNotIso.eps");

  canv1->cd(3);
  zmsMass->plotOn(massFrame_musta, LineColor(kBlue));
  eZmsSig->plotOn(massFrame_musta, Components(*bkg_musa), LineColor(kGreen));
  eZmsSig->plotOn(massFrame_musta, LineColor(kRed));
  massFrame_musta->SetTitle("Z -> #mu sta");
  massFrame_musta->Draw();

  canv2->cd();
  canv2->Clear();
  canv2->SetLogy(kTRUE);
  massFrame_musta->Draw();
  canv2->SaveAs("LogZMuSa.eps");
  canv2->SetLogy(kFALSE);
  canv2->SaveAs("LinZMuSa.eps");

  canv1->cd(4);
  zmm1hltMass->plotOn(massFrame_mumu1hlt, LineColor(kBlue));
  eZmm1hltSig->plotOn(massFrame_mumu1hlt, LineColor(kRed));
  massFrame_mumu1hlt->SetTitle("Z -> #mu #mu 1hlt");
  massFrame_mumu1hlt->Draw();
  canv2->cd();
  canv2->Clear();
  canv2->SetLogy(kTRUE);
  massFrame_mumu1hlt->Draw();
  canv2->SaveAs("LogZMuMu1Hlt.eps");
  canv2->SetLogy(kFALSE);
  canv2->SaveAs("LinZMuMu1Hlt.eps");

  canv1->cd(5);
  zmm2hltMass->plotOn(massFrame_mumu2hlt, LineColor(kBlue));
  eZmm2hltSig->plotOn(massFrame_mumu2hlt, LineColor(kRed));
  massFrame_mumu2hlt->SetTitle("Z -> #mu #mu 2hlt");
  massFrame_mumu2hlt->Draw();

  canv1->SaveAs("mass.eps");

  canv2->cd();
  canv2->Clear();
  canv2->SetLogy(kTRUE);
  massFrame_mumu2hlt->Draw();
  canv2->SaveAs("LogZMuMu2Hlt.eps");
  canv2->SetLogy(kFALSE);
  canv2->SaveAs("LinZMuMu2Hlt.eps");

  /* how to read the fit result in root
     TH1D h_Yield("h_Yield", "h_Yield", 100, 10000, 30000)
     for (int i =0: i < 100; i++){
     RooFitResult* r = gDirectory->Get(Form("toy_totChi2;%d)",i)
     //r->floatParsFinal().Print("s");
     // without s return a list,  can we get the number?
     RooFitResult* r = gDirectory->Get("toy_totChi2;1")
     // chi2
     r->minNll();
     //distamce form chi2.....
     //r->edm();
     // yield
     r->floatParsFinal()[0]->Print();
     //RooAbsReal * l = r->floatParsFinal()->first()
     RooAbsReal * y = r->floatParsFinal()->find("Yield");
     h_Yield->Fill(y->getVal());
     }

  */

  delete root_file;
  //delete out_root_file;
  return 0;
}

max_stars_repo_name: SWuchterl/cmssw

max_issues_repo_name: SWuchterl/cmssw

max_forks_repo_name: SWuchterl/cmssw


text: #include <boost/fusion/container/vector.hpp>

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


text:
#include "CalibrationHelpers.h"

#include <iostream>
#include <fstream>
#include <string>
#include <Eigen/Dense>

namespace romocc
{

std::vector<Transform3d> invert_matrices(std::vector<Transform3d> matrices)
{
    std::vector<Transform3d> invertedMatrices;

    for(int i = 0; i<matrices.size(); i++)
    {
        invertedMatrices.push_back(matrices.at(i).inverse());
    }
    return invertedMatrices;
}

double compute_average(std::vector<double> const &v)
{
    double sum = 0;
    for(int i=0; i<v.size(); i++)
        sum += v[i];
    return sum/v.size();
}

double compute_variance(std::vector<double> const &v, double mean)
{
    double sum = 0.0;
    double temp =0.0;
    double var =0.0;

    for ( int j =0; j <= v.size()-1; j++)
    {
        temp = std::pow(v[j]-mean,2);
        sum += temp;
    }

    return var = sum/(v.size()-2);
}

std::vector<double> compute_linspace(double a, double b, int n)
{
    std::vector<double> array;
    double step = (b-a) / (n-1);

    while(a <= b) {
        array.push_back(a);
        a += step;
    }
    return array;
}

double sgn(double val)
{
    return (double(0) < val) - (val < double(0));
}

Transform3d load_calibration_file(std::string filepath){
    auto calMat = Eigen::Affine3d::Identity();
    std::ifstream inFile;
    inFile.open(filepath);

    if(inFile.is_open())
    {
        for(int row = 0; row < calMat.rows(); row++){
            for(int col = 0; col < calMat.cols(); col++)
            {
                double item = 0;
                inFile >> item;
                calMat(row, col) = item;
            }
        }
        inFile.close();
    }
    return calMat;
}

void save_calibration_file(std::string path, Eigen::Affine3d calMat) {
    std::ofstream outFile;
    outFile.open(path);

    if(outFile.is_open()){
        outFile << calMat.matrix();
        outFile.close();
    }
}

}

max_stars_repo_name: SINTEFMedtek/libromocc

max_issues_repo_name: SINTEFMedtek/libromocc

max_forks_repo_name: SINTEFMedtek/libromocc


text:
#ifndef __LOG_HPP__
#define __LOG_HPP__
/* Usage:
 * 1. include "log.hpp"
 * 2. call loginit() in the very beginning
 * 3. LOG(trace/debug/info/warning/error/fatal)<< "log message";
 */
#include <string>
#ifdef DEBUGLOG
	#include <boost/log/trivial.hpp>
	#define LOG(x) BOOST_LOG_TRIVIAL(x)
#else /* DEBUGLOG */
	#include <ostream>
	#ifdef LOG_DEFINE_VAR
		std::ostream _NullLog_(0);
	#else /* LOG_DEFINE_VAR */
		extern std::ostream _NullLog_;
	#endif /* LOG_DEFINE_VAR */
	#define LOG(x) _NullLog_
#endif /* DEBUGLOG */

enum E_LOGLEVEL
{
	LEVEL_TRACE,
	LEVEL_DEBUG,
	LEVEL_INFO,
	LEVEL_WARNING,
	LEVEL_ERROR,
	LEVEL_FATAL
};

void loginit(E_LOGLEVEL eloglevel=LEVEL_TRACE, std::string filename="", bool console=true);
#endif


text:
/*
 * This file is part of the DUDS project. It is subject to the BSD-style
 * license terms in the LICENSE file found in the top-level directory of this
 * distribution and at https://github.com/jjackowski/duds/blob/master/LICENSE.
 * No part of DUDS, including this file, may be copied, modified, propagated,
 * or distributed except according to the terms contained in the LICENSE file.
 *
 * Copyright (C) 2017  Jeff Jackowski
 */
#ifndef EXTENDEDUNIT_HPP
#define EXTENDEDUNIT_HPP

#include <duds/general/Errors.hpp>
#include <duds/data/Unit.hpp>
#include <boost/serialization/split_member.hpp>

namespace duds { namespace data {

// needed for celsius, liter

/**
 * redo: Use floats for scale and offset. Use 32-bits for 10 3-bit and 1 2-bit
 *       additional unit flags (put relative humidity there?), and a Unit.
 *       Should be 16 bytes, 128-bits. Include in GenericValue.
 */
class ExtendedUnit {
	Unit unit;
	union {
		/**
		 * A scaling and offset value packed into four bytes. The scalar works
		 * for most of the metric prefixes. The offset works for 273.15. All this
		 * fits in the space of a single float. The offset needs more precision
		 * than a half (from IEEE 754).
		 */
		std::uint32_t scaloff;
		struct {
			/**
			 * The mantissa, save for the impled leading bit.
			 */
			unsigned int mant  : 20;
			/**
			 * The exponent as a signed integer rather than unsigned with bias.
			 */
			int exp            : 7;
			/**
			 * The sign flag.
			 */
			int sign           : 1;
			/**
			 * A value used to represnt most SI prefixes. The prefixes
			 * represent a scalar value. To produce this prefix scalar,
			 * multiply @a scale by three, then rasie ten to the power of
			 * the product. Kilograms has a prefix built into the base unit
			 * resulting in inconsistency. This scalar modifies kilo in
			 * kilograms. Thus, if @a unit is Kilogram, then a @a scale of -1
			 * produces the unit gram.
			 */
			int scale : 4;
		};
	};
	// serialization support
	friend class boost::serialization::access;
	template <class A>
	void save(A &a, const unsigned int) const {
		a & BOOST_SERIALIZATION_NVP(unit);
		// prevent differences in bitfields across platforms from causing
		// different values for scaloff; assume for now that the archive will
		// handle endianness differences
		std::uint32_t packed = mant | (exp << 20) | (sign << 27) | (scale << 28);
		a & BOOST_SERIALIZATION_NVP(packed);
	}
	template <class A>
	void load(A &a, const unsigned int) {
		a & BOOST_SERIALIZATION_NVP(unit);
		std::uint32_t packed;
		a & BOOST_SERIALIZATION_NVP(packed);
		// prevent differences in bitfields across platforms from causing
		// different values for scaloff; assume for now that the archive will
		// handle endianness differences
		mant = packed & 0xFFFFF;
		exp = (packed >> 20) & 0x7F;
		sign = (packed >> 27) & 1;
		scale = packed >> 28;
	}
	BOOST_SERIALIZATION_SPLIT_MEMBER();
	/**
	 * An simple internal constructor that takes the values of it members.
	 * @todo  Maybe make this public along with some macro to set @a s? Doing
	 *        so would allow easy creation of constant ExtendedUnit objects,
	 *        like the Units in Units.hpp. May have to specify the offset it
	 *        pieces, though.
	 */
	constexpr ExtendedUnit(Unit u, std::uint32_t s) : unit(u), scaloff(s) { }
public:
	/**
	 * Makes an uninitialized ExtendedUnit.
	 */
	ExtendedUnit() = default;
	/**
	 * Makes a copy.
	 */
	ExtendedUnit(const ExtendedUnit &) = default;
	/**
	 * Makes an ExtendedUnit that is equivalent to the given base Unit.
	 * @param u  The base unit.
	 */
	constexpr ExtendedUnit(Unit u) : unit(u), scaloff(0) { }
	/**
	 * Constructs an ExtendedUnit with the given values.
	 * @tparam O  The offset type; must be either @a float or @a double. In most
	 *            cases, the compiler should deduce this type.
	 * @param  u  The initial Unit value.
	 * @param  o  The initial offset value.
	 * @param  s  The initial scalar value.
	 * @todo   Document the offset and scalar better.
	 * @throw  UnitRangeError  Either the scalar or offset value is beyond the
	 *                         bounds of the internal storage.
	 */
	template <typename O>
	ExtendedUnit(Unit u, O o, int s) : unit(u), scale(s) {
		if ((s > 7) || (s < -8)) {
			DUDS_THROW_EXCEPTION(UnitRangeError());
		}
		offset(o);
	}
	/**
	 * True if the unit represented by this object can also be represented by
	 * a Unit object.
	 */
	bool canConvertToUnit() const;
	/**
	 * Change the offset.
	 * @param o  The new offset. Is must not be subnormal, infinite, or NaN.
	 * @throw  UnitRangeError  The offset value is beyond the bounds of the
	 *                         internal storage.
	 */
	void offset(float o);
	/**
	 * Query the offset as a float.
	 */
	float offsetf() const;
	/**
	 * Change the offset.
	 * @param o  The new offset. Is must not be subnormal, infinite, or NaN.
	 * @throw  UnitRangeError  The offset value is beyond the bounds of the
	 *                         internal storage.
	 */
	void offset(double o);
	/**
	 * Query the offset as a double.
	 */
	double offset() const;
	/**
	 * Returns the base unit as a Unit object.
	 */
	const Unit &base() const {
		return unit;
	}
	/**
	 * Returns the exponent for the ampere (current) dimension.
	 */
	int ampere() const {
		return unit.ampere();
	}
	/**
	 * Returns the exponent for the candela (luminous intensity) dimension.
	 */
	int candela() const {
		return unit.candela();
	}
	/**
	 * Returns the exponent for the kelvin (thermodynamic temperature) dimension.
	 */
	int kelvin() const {
		return unit.kelvin();
	}
	/**
	 * Returns the exponent for the kilogram (mass) dimension.
	 */
	int kilogram() const {
		return unit.kilogram();
	}
	/**
	 * Returns the exponent for the meter (distance) dimension.
	 */
	int meter() const {
		return unit.meter();
	}
	/**
	 * Returns the exponent for the mole (amount of substance) dimension.
	 */
	int mole() const {
		return unit.mole();
	}
	/**
	 * Returns the exponent for the second (time) dimension.
	 */
	int second() const {
		return unit.second();
	}
	/**
	 * Returns the exponent for radians (angle).
	 */
	int radian() const {
		return unit.radian();
	}
	/**
	 * Returns the exponent for steradians (solid angle).
	 */
	int steradian() const {
		return unit.steradian();
	}
	/**
	 * Returns the exponent for the ampere (current) dimension.
	 */
	int amp() const {
		return unit.ampere();
	}
	/**
	 * Returns the exponent for the meter (distance) dimension.
	 */
	int metre() const {
		return unit.meter();
	}
	/**
	 * Returns the exponent for the ampere (current) dimension.
	 */
	int A() const {
		return unit.ampere();
	}
	/**
	 * Returns the exponent for the candela (luminous intensity) dimension.
	 */
	int cd() const {
		return unit.candela();
	}
	/**
	 * Returns the exponent for the kelvin (thermodynamic temperature) dimension.
	 */
	int K() const {
		return unit.kelvin();
	}
	/**
	 * Returns the exponent for the kilogram (mass) dimension.
	 */
	int kg() const {
		return unit.kilogram();
	}
	/**
	 * Returns the exponent for the meter (distance) dimension.
	 */
	int m() const {
		return unit.meter();
	}
	/**
	 * Returns the exponent for the mole (amount of substance) dimension.
	 */
	int mol() const {
		return unit.mole();
	}
	/**
	 * Returns the exponent for the second (time) dimension.
	 */
	int s() const {
		return unit.second();
	}
	/**
	 * Returns the exponent for radians (angle).
	 */
	int rad() const {
		return unit.radian();
	}
	/**
	 * Returns the exponent for steradians (solid angle).
	 */
	int sr() const {
		return unit.steradian();
	}
	/**
	 * Sets the exponent for the ampere (current) dimension without range
	 * checking.
	 * @param e  The exponent in a range between -8 to 7, inclusive.
	 */
	void ampere(int e) {
		unit.ampere(e);
	}
	/**
	 * Sets the exponent for the candela (luminous intensity) dimension without
	 * range checking.
	 * @param e  The exponent in a range between -8 to 7, inclusive.
	 */
	void candela(int e) {
		unit.candela(e);
	}
	/**
	 * Sets the exponent for the kelvin (thermodynamic temperature) dimension
	 * without range checking.
	 * @param e  The exponent in a range between -8 to 7, inclusive.
	 */
	void kelvin(int e) {
		unit.kelvin(e);
	}
	/**
	 * Sets the exponent for the ampere (current)kilogram (mass) dimension without
	 * range checking.
	 * @param e  The exponent in a range between -8 to 7, inclusive.
	 */
	void kilogram(int e) {
		unit.kilogram(e);
	}
	/**
	 * Sets the exponent for the meter (distance) dimension without range
	 * checking.
	 * @param e  The exponent in a range between -8 to 7, inclusive.
	 */
	void meter(int e) {
		unit.meter(e);
	}
	/**
	 * Sets the exponent for the mole (amount of substance) dimension without
	 * range checking.
	 * @param e  The exponent in a range between -8 to 7, inclusive.
	 */
	void mole(int e) {
		unit.mole(e);
	}
	/**
	 * Sets the exponent for the second (time) dimension without range
	 * checking.
	 * @param e  The exponent in a range between -8 to 7, inclusive.
	 */
	void second(int e) {
		unit.second(e);
	}
	/**
	 * Sets the exponent for radians (angle) without range checking.
	 * @param e  The exponent in a range between -2 to 1, inclusive.
	 */
	void radian(int e) {
		unit.radian(e);
	}
	/**
	 * Sets the exponent for steradians (solid angle) without range checking.
	 * @param e  The exponent in a range between -2 to 1, inclusive.
	 */
	void steradian(int e) {
		unit.steradian(e);
	}
	/**
	 * Sets the exponent for the ampere (current) dimension without range
	 * checking.
	 * @param e  The exponent in a range between -8 to 7, inclusive.
	 */
	void amp(int e) {
		unit.ampere(e);
	}
	/**
	 * Sets the exponent for the meter (distance) dimension without range
	 * checking.
	 * @param e  The exponent in a range between -8 to 7, inclusive.
	 */
	void metre(int e) {
		unit.meter(e);
	}
	/**
	 * Sets the exponent for the ampere (current) dimension without range
	 * checking.
	 * @param e  The exponent in a range between -8 to 7, inclusive.
	 */
	void A(int e) {
		unit.ampere(e);
	}
	/**
	 * Sets the exponent for the candela (luminous intensity) dimension without
	 * range checking.
	 * @param e  The exponent in a range between -8 to 7, inclusive.
	 */
	void cd(int e) {
		unit.candela(e);
	}
	/**
	 * Sets the exponent for the kelvin (thermodynamic temperature) dimension
	 * without range checking.
	 * @param e  The exponent in a range between -8 to 7, inclusive.
	 */
	void K(int e) {
		unit.kelvin(e);
	}
	/**
	 * Sets the exponent for the kilogram (mass) dimension without range
	 * checking.
	 * @param e  The exponent in a range between -8 to 7, inclusive.
	 */
	void kg(int e) {
		unit.kilogram(e);
	}
	/**
	 * Sets the exponent for the meter (distance) dimension without range
	 * checking.
	 * @param e  The exponent in a range between -8 to 7, inclusive.
	 */
	void m(int e) {
		unit.meter(e);
	}
	/**
	 * Sets the exponent for the mole (amount of substance) dimension without
	 * range checking.
	 * @param e  The exponent in a range between -8 to 7, inclusive.
	 */
	void mol(int e) {
		unit.mole(e);
	}
	/**
	 * Sets the exponent for the second (time) dimension without range
	 * checking.
	 * @param e  The exponent in a range between -8 to 7, inclusive.
	 */
	void s(int e) {
		second(e);
	}
	/**
	 * Sets the exponent for radians (angle) without range checking.
	 * @param e  The exponent in a range between -2 to 1, inclusive.
	 */
	void rad(int e) {
		unit.radian(e);
	}
	/**
	 * Sets the exponent for steradians (solid angle) without range checking.
	 * @param e  The exponent in a range between -2 to 1, inclusive.
	 */
	void sr(int e) {
		unit.steradian(e);
	}
	/**
	 * Sets the exponent for the ampere (current) dimension.
	 * @param e  The exponent in a range between -8 to 7, inclusive.
	 * @throw UnitRangeError  The exponent @a e is out of range.
	 */
	void setAmpere(int e) {
		unit.setAmpere(e);
	}
	/**
	 * Sets the exponent for the candela (luminous intensity) dimension.
	 * @param e  The exponent in a range between -8 to 7, inclusive.
	 * @throw UnitRangeError  The exponent @a e is out of range.
	 */
	void setCandela(int e) {
		unit.setCandela(e);
	}
	/**
	 * Sets the exponent for the kelvin (thermodynamic temperature) dimension.
	 * @param e  The exponent in a range between -8 to 7, inclusive.
	 * @throw UnitRangeError  The exponent @a e is out of range.
	 */
	void setKelvin(int e) {
		unit.setKelvin(e);
	}
	/**
	 * Sets the exponent for the kilogram (mass) dimension.
	 * @param e  The exponent in a range between -8 to 7, inclusive.
	 * @throw UnitRangeError  The exponent @a e is out of range.
	 */
	void setKilogram(int e) {
		unit.setKilogram(e);
	}
	/**
	 * Sets the exponent for the meter (distance) dimension.
	 * @param e  The exponent in a range between -8 to 7, inclusive.
	 * @throw UnitRangeError  The exponent @a e is out of range.
	 */
	void setMeter(int e) {
		unit.setMeter(e);
	}
	/**
	 * Sets the exponent for the mole (amount of substance) dimension.
	 * @param e  The exponent in a range between -8 to 7, inclusive.
	 * @throw UnitRangeError  The exponent @a e is out of range.
	 */
	void setMole(int e) {
		unit.setMole(e);
	}
	/**
	 * Sets the exponent for the second (time) dimension.
	 * @param e  The exponent in a range between -8 to 7, inclusive.
	 * @throw UnitRangeError  The exponent @a e is out of range.
	 */
	void setSecond(int e) {
		unit.setSecond(e);
	}
	/**
	 * Sets the exponent for radians (angle).
	 * @param e  The exponent in a range between -2 to 1, inclusive.
	 * @throw UnitRangeError  The exponent @a e is out of range.
	 */
	void setRadian(int e) {
		unit.setRadian(e);
	}
	/**
	 * Sets the exponent for steradians (solid angle).
	 * @param e  The exponent in a range between -2 to 1, inclusive.
	 * @throw UnitRangeError  The exponent @a e is out of range.
	 */
	void setSteradian(int e) {
		unit.setSteradian(e);
	}
	/**
	 * Sets the exponent for the ampere (current) dimension.
	 * @param e  The exponent in a range between -8 to 7, inclusive.
	 * @throw UnitRangeError  The exponent @a e is out of range.
	 */
	void setAmp(int e) {
		unit.setAmpere(e);
	}
	/**
	 * Sets the exponent for the meter (distance) dimension.
	 * @param e  The exponent in a range between -8 to 7, inclusive.
	 * @throw UnitRangeError  The exponent @a e is out of range.
	 */
	void setMetre(int e) {
		unit.setMeter(e);
	}
	/**
	 * Returns true if the object represents no units. This is normal for some
	 * values, such as ratios.
	 */
	bool unitless() const {
		return unit.unitless();
	}
	/**
	 * Combines two units into a new unit.
	 * @throw UnitRangeError  A resulting exponent is out of range.
	 */
	const ExtendedUnit operator * (const Unit &U) const;
	/**
	 * Combines two units into a new unit.
	 * @throw UnitRangeError  A resulting exponent is out of range.
	 */
	const ExtendedUnit operator / (const Unit &U) const;
	/**
	 * Combines two units into a new unit.
	 * @throw UnitRangeError  A resulting exponent is out of range. All
	 *                           work is done on a temporary so that if an
	 *                           exception is thrown only the temporary is
	 *                           modified.
	 */
	ExtendedUnit &operator *= (const Unit &U);
	/**
	 * Combines two units into a new unit.
	 * @throw UnitRangeError  A resulting exponent is out of range. All
	 *                           work is done on a temporary so that if an
	 *                           exception is thrown only the temporary is
	 *                           modified.
	 */
	ExtendedUnit &operator /= (const Unit &U);
	/**
	 * Makes this extended unit equivalent to the given Unit object.
	 */
	ExtendedUnit &operator = (const Unit &U);
	/**
	 * Unit objects are compared using the @a u member.
	 */
	bool operator < (const ExtendedUnit &U) const {
		return ((unit == U.unit) && (scaloff < U.scaloff)) || (unit < U.unit);
	}
	/**
	 * Unit objects are compared using the @a u member.
	 */
	bool operator > (const ExtendedUnit &U) const {
		return ((unit == U.unit) && (scaloff > U.scaloff)) || (unit > U.unit);
	}
	/**
	 * Unit objects are compared using the @a u member.
	 */
	bool operator <= (const ExtendedUnit &U) const {
		return ((unit == U.unit) && (scaloff <= U.scaloff)) || (unit <= U.unit);
	}
	/**
	 * Unit objects are compared using the @a u member.
	 */
	bool operator >= (const ExtendedUnit &U) const {
		return ((unit == U.unit) && (scaloff >= U.scaloff)) || (unit >= U.unit);
	}
	/**
	 * Unit objects are compared using the @a u member.
	 */
	bool operator == (const ExtendedUnit &U) const {
		return (unit == U.unit) && (scaloff == U.scaloff);
	}
	/**
	 * Unit objects are compared using the @a u member.
	 */
	bool operator != (const ExtendedUnit &U) const {
		return (unit != U.unit) || (scaloff != U.scaloff);
	}
};

/**
 * An idea that is not yet implemented; <b>DO NOT USE</b>.
 */
template <class Q = double>
struct ExtendedQuantity {
	Q value;
	ExtendedUnit unit;
private:
	// serialization support
	friend class boost::serialization::access;
	template <class A>
	void serialize(A &a, const unsigned int) {
		a & BOOST_SERIALIZATION_NVP(value);
		a & BOOST_SERIALIZATION_NVP(unit);
	}
};

} }

#endif        //  #ifndef EXTENDEDUNIT_HPP

max_stars_repo_name: jjackowski/duds

max_issues_repo_name: jjackowski/duds

max_forks_repo_name: jjackowski/duds