text:
//
// Book:      OpenCL(R) Programming Guide
// Authors:   Aaftab Munshi, Benedict Gaster, Timothy Mattson, James Fung, Dan Ginsburg
// ISBN-10:   0-321-74964-2
// ISBN-13:   978-0-321-74964-2
// Publisher: Addison-Wesley Professional
// URLs:      http://safari.informit.com/9780132488006/
//            http://www.openclprogrammingguide.com
//

//
//  Description:
//      Implementation of Dijkstra's Single-Source Shortest Path (SSSP) algorithm on the GPU.
//      The basis of this implementation is the paper:
//
//          "Accelerating large graph algorithms on the GPU using CUDA" by
//          Parwan Harish and P.J. Narayanan
//
//      This file is the main driver to test the OpenCL Dijkstra implementation either with
//      randomly generated graph data or pre-canned city data.
//
//  Author:
//      Dan Ginsburg
//      <daniel.ginsburg@childrens.harvard.edu>
//
//  Children's Hospital Boston
//
#include <sstream>
#include <iostream>
#include <boost/program_options.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <stdio.h>
#include "oclDijkstraKernel.h"

///
//  Namespaces
//
namespace po = boost::program_options;
namespace pt = boost::posix_time;

////////////////////////////////////////////////////////////////////////////////
// Helper functions
////////////////////////////////////////////////////////////////////////////////

///
//  Generate a random graph
//
void generateRandomGraph(GraphData *graph, int numVertices, int neighborsPerVertex)
{
    graph->vertexCount = numVertices;
    graph->vertexArray = (int*) malloc(graph->vertexCount * sizeof(int));
    graph->edgeCount = numVertices * neighborsPerVertex;
    graph->edgeArray = (int*)malloc(graph->edgeCount * sizeof(int));
    graph->weightArray = (float*)malloc(graph->edgeCount * sizeof(float));

    for(int i = 0; i < graph->vertexCount; i++)
    {
        graph->vertexArray[i] = i * neighborsPerVertex;
    }

    for(int i = 0; i < graph->edgeCount; i++)
    {
        graph->edgeArray[i] = (rand() % graph->vertexCount);
        graph->weightArray[i] = (float)(rand() % 1000) / 1000.0f;
    }
}

///
//  Parse command line arguments
//
void parseCommandLineArgs(int argc, char **argv, bool &doCPU, bool &doGPU,
                          bool &doMultiGPU, bool &doCPUGPU, bool &doRef,
                          int *sourceVerts,
                          int *generateVerts, int *generateEdgesPerVert)
{
    po::options_description desc("Allowed options");
    desc.add_options()
        ("help",    "Produce help message")
        ("cpu",     "Run CPU version of algorithm")
        ("gpu",     "Run single GPU version of algorithm")
        ("multigpu","Run multi GPU version of algorithm")
        ("cpugpu",  "Run multi GPU+CPU version of algorithm")
        ("ref",     "Run reference version of algorithm")
        ("sources", po::value<int>(), "Number of source vertices to search from (default: 100)")
        ("verts",   po::value<int>(), "Number of vertices in randomly generated graph (default: 100000)")
        ("edges",   po::value<int>(), "Number of edges per vertex in randomly generated graph (default: 10)");

    po::variables_map vm;
    po::store(po::parse_command_line(argc, argv, desc), vm);
    po::notify(vm);

    if (vm.count("help") || argc == 1)
    {
        std::cout << desc << "\n";
        exit(1);
    }

    // Parse options
    if (vm.count("cpu"))
    {
        doCPU = true;
    }

    if (vm.count("gpu"))
    {
        doGPU = true;
    }

    if (vm.count("multigpu"))
    {
        doMultiGPU = true;
    }

    if (vm.count("cpugpu"))
    {
        doCPUGPU = true;
    }

    if (vm.count("ref"))
    {
        doRef = true;
    }

    if (vm.count("sources"))
    {
        *sourceVerts = vm["sources"].as<int>();
    }

    if (vm.count("verts"))
    {
        *generateVerts = vm["verts"].as<int>();
    }

    if (vm.count("edges"))
    {
        *generateEdgesPerVert = vm["edges"].as<int>();
    }
}

///
/// Gets the id of device with maximal FLOPS from the context (from NVIDIA SDK)
///
static cl_device_id getMaxFlopsDev(cl_context cxGPUContext)
{
    size_t szParmDataBytes;
    cl_device_id* cdDevices;

    // get the list of GPU devices associated with context
    clGetContextInfo(cxGPUContext, CL_CONTEXT_DEVICES, 0, NULL,
            &szParmDataBytes);
    cdDevices = (cl_device_id*) malloc(szParmDataBytes);
    size_t device_count = szParmDataBytes / sizeof(cl_device_id);

    clGetContextInfo(cxGPUContext, CL_CONTEXT_DEVICES, szParmDataBytes,
            cdDevices, NULL);

    cl_device_id max_flops_device = cdDevices[0];
    int max_flops = 0;

    size_t current_device = 0;

    // CL_DEVICE_MAX_COMPUTE_UNITS
    cl_uint compute_units;
    clGetDeviceInfo(cdDevices[current_device], CL_DEVICE_MAX_COMPUTE_UNITS,
            sizeof(compute_units), &compute_units, NULL);

    // CL_DEVICE_MAX_CLOCK_FREQUENCY
    cl_uint clock_frequency;
    clGetDeviceInfo(cdDevices[current_device], CL_DEVICE_MAX_CLOCK_FREQUENCY,
            sizeof(clock_frequency), &clock_frequency, NULL);

    max_flops = compute_units * clock_frequency;
    ++current_device;

    while (current_device < device_count)
    {
        // CL_DEVICE_MAX_COMPUTE_UNITS
        cl_uint compute_units;
        clGetDeviceInfo(cdDevices[current_device], CL_DEVICE_MAX_COMPUTE_UNITS,
                sizeof(compute_units), &compute_units, NULL);

        // CL_DEVICE_MAX_CLOCK_FREQUENCY
        cl_uint clock_frequency;
        clGetDeviceInfo(cdDevices[current_device],
                CL_DEVICE_MAX_CLOCK_FREQUENCY, sizeof(clock_frequency),
                &clock_frequency, NULL);

        int flops = compute_units * clock_frequency;
        if (flops > max_flops)
        {
            max_flops = flops;
            max_flops_device = cdDevices[current_device];
        }
        ++current_device;
    }

    free(cdDevices);

    return max_flops_device;
}

////////////////////////////////////////////////////////////////////////////////
// Program main
////////////////////////////////////////////////////////////////////////////////
int main(int argc, char **argv)
{
    bool doCPU = false;
    bool doGPU = false;
    bool doMultiGPU = false;
    bool doCPUGPU = false;
    bool doRef = false;
    int numSources = 100;
    int generateVerts = 100000;
    int generateEdgesPerVert = 10;

    parseCommandLineArgs(argc, argv, doCPU, doGPU,
                         doMultiGPU, doCPUGPU, doRef,
                         &numSources, &generateVerts, &generateEdgesPerVert);

    cl_platform_id platform;
    cl_context gpuContext;
    cl_context cpuContext;
    cl_int errNum;

    // First, select an OpenCL platform to run on.  For this example, we
    // simply choose the first available platform.  Normally, you would
    // query for all available platforms and select the most appropriate one.
    cl_uint numPlatforms;
    errNum = clGetPlatformIDs(1, &platform, &numPlatforms);
    printf("Number of OpenCL Platforms: %d\n", numPlatforms);
    if (errNum != CL_SUCCESS || numPlatforms <= 0)
    {
        printf("Failed to find any OpenCL platforms.\n");
        return 1;
    }

    // create the OpenCL context on available GPU devices
    gpuContext = clCreateContextFromType(0, CL_DEVICE_TYPE_GPU, NULL, NULL, &errNum);
    if (errNum != CL_SUCCESS)
    {
        printf("No GPU devices found.\n");
    }

    // Create an OpenCL context on available CPU devices
    cpuContext = clCreateContextFromType(0, CL_DEVICE_TYPE_CPU, NULL, NULL, &errNum);
    if (errNum != CL_SUCCESS)
    {
        printf("No CPU devices found.\n");
    }

    // Allocate memory for arrays
    GraphData graph;
    generateRandomGraph(&graph, generateVerts, generateEdgesPerVert);

    printf("Vertex Count: %d\n", graph.vertexCount);
    printf("Edge Count: %d\n", graph.edgeCount);

    std::vector<int> sourceVertices;

    for(int source = 0; source < numSources; source++)
    {
        sourceVertices.push_back(source % graph.vertexCount);
    }

    int *sourceVertArray = (int*) malloc(sizeof(int) * sourceVertices.size());
    std::copy(sourceVertices.begin(), sourceVertices.end(), sourceVertArray);

    float *results = (float*) malloc(sizeof(float) * sourceVertices.size() * graph.vertexCount);

    // Run Dijkstra's algorithm
    pt::ptime startTimeCPU = pt::microsec_clock::local_time();
    if (doCPU)
    {
        runDijkstra(cpuContext, getMaxFlopsDev(cpuContext), &graph, sourceVertArray,
                    results, sourceVertices.size() );
    }
    pt::time_duration timeCPU = pt::microsec_clock::local_time() - startTimeCPU;

    pt::ptime startTimeGPU = pt::microsec_clock::local_time();
    if (doGPU)
    {
        runDijkstra(gpuContext, getMaxFlopsDev(gpuContext), &graph, sourceVertArray,
                    results, sourceVertices.size() );
    }
    pt::time_duration timeGPU = pt::microsec_clock::local_time() - startTimeGPU;

    pt::ptime startTimeMultiGPU = pt::microsec_clock::local_time();
    if (doMultiGPU)
    {
        runDijkstraMultiGPU(gpuContext, &graph, sourceVertArray,
                            results, sourceVertices.size() );
    }
    pt::time_duration timeMultiGPU = pt::microsec_clock::local_time() - startTimeMultiGPU;

    pt::ptime startTimeGPUCPU = pt::microsec_clock::local_time();
    if (doCPUGPU)
    {
        runDijkstraMultiGPUandCPU(gpuContext, cpuContext, &graph, sourceVertArray,
                                  results, sourceVertices.size() );
    }
    pt::time_duration timeGPUCPU = pt::microsec_clock::local_time() - startTimeGPUCPU;

    pt::ptime startTimeRef = pt::microsec_clock::local_time();
    if (doRef)
    {
        runDijkstraRef( &graph, sourceVertArray,
                        results, sourceVertices.size() );
    }
    pt::time_duration timeRef = pt::microsec_clock::local_time() - startTimeRef;

    if (doCPU)
    {
        printf("\nrunDijkstra - CPU Time:               %f s\n", (float)timeCPU.total_milliseconds() / 1000.0f);
    }

    if (doGPU)
    {
        printf("\nrunDijkstra - Single GPU Time:        %f s\n", (float)timeGPU.total_milliseconds() / 1000.0f);
    }

    if (doMultiGPU)
    {
        printf("\nrunDijkstra - Multi GPU Time:         %f s\n", (float)timeMultiGPU.total_milliseconds() / 1000.0f);
    }

    if (doCPUGPU)
    {
        printf("\nrunDijkstra - Multi GPU and CPU Time: %f s\n", (float)timeGPUCPU.total_milliseconds() / 1000.0f);
    }

    if (doRef)
    {
        printf("\nrunDijkstra - Reference (CPU):        %f s\n", (float)timeRef.total_milliseconds() / 1000.0f);
    }

    free(sourceVertArray);
    free(results);

    clReleaseContext(gpuContext);

    // finish
    //shrEXIT(argc, argv);
 }


text:
//          Copyright Gavin Band 2008 - 2012.
// 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 BINGWA_BINGWA_COMPUTATION_HPP
#define BINGWA_BINGWA_COMPUTATION_HPP

#include <memory>
#include <string>
#include <vector>
#include <map>
#include <boost/function.hpp>
#include <boost/noncopyable.hpp>
#include <Eigen/Core>
#include "genfile/VariantIdentifyingData.hpp"
#include "genfile/VariantEntry.hpp"
#include "EffectParameterNamePack.hpp"
#include "appcontext/OptionProcessor.hpp"

namespace bingwa {
	struct BingwaComputation: public boost::noncopyable {
		typedef std::auto_ptr< BingwaComputation > UniquePtr ;
		static UniquePtr create(
			std::string const& name,
			std::vector< std::string > const& cohort_names,
			appcontext::OptionProcessor const&
		) ;
		virtual ~BingwaComputation() {}
		typedef genfile::VariantIdentifyingData VariantIdentifyingData ;
		typedef boost::function< void ( std::string const& value_name, genfile::VariantEntry const& value ) > ResultCallback ;

		struct DataGetter: public boost::noncopyable {
			virtual ~DataGetter() {} ;
			virtual std::size_t get_number_of_cohorts() const = 0 ;
			virtual bool is_non_missing( std::size_t i ) const = 0 ;
			virtual bool is_trusted( std::size_t i ) const = 0 ;
			virtual void get_counts( std::size_t, Eigen::VectorXd* result ) const = 0 ;
			virtual void get_betas( std::size_t i, Eigen::VectorXd* result ) const = 0 ;
			virtual void get_ses( std::size_t i, Eigen::VectorXd* result  ) const = 0 ;
			virtual void get_covariance_upper_triangle( std::size_t i, Eigen::VectorXd* result  ) const = 0 ;
			virtual void get_pvalue( std::size_t i, double* result ) const = 0 ;
			virtual void get_info( std::size_t i, double* result ) const = 0 ;
			virtual void get_variable( std::string const& variable, std::size_t i, std::string* result ) const = 0 ;
		} ;

		typedef boost::function< bool ( DataGetter const&, int i ) > Filter ;

		virtual void set_effect_parameter_names( EffectParameterNamePack const& names ) = 0 ;
		virtual void get_variables( boost::function< void ( std::string, std::string ) > ) const = 0 ;
		virtual void operator()(
			VariantIdentifyingData const&,
			DataGetter const& data_getter,
			ResultCallback callback
		) = 0 ;
		virtual std::string get_summary( std::string const& prefix = "", std::size_t column_width = 20 ) const = 0 ;
		virtual std::string get_spec() const = 0 ;
	} ;
}

#endif

ext: hpp

max_stars_repo_name: gavinband/bingwa

max_issues_repo_name: gavinband/bingwa

max_forks_repo_name: gavinband/bingwa


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

#include <armadillo2_services/torso.h>

Torso::Torso(ros::NodeHandle &nh, const JointStateReader &joints_state)
{
    joints_state_ = &joints_state;
    nh_ = &nh;
    torso_pub_ = nh_->advertise<std_msgs::Float64>("/torso_effort_controller/command", 10);
}

bool Torso::command(float position)
{
    if (torso_pub_.getNumSubscribers() > 0)
    {
        std_msgs::Float64 cmd_msg;
        cmd_msg.data = position;
        torso_pub_.publish(cmd_msg);
        return true;
    }
    return false;
}

bool Torso::commandCurrentPos()
{
    return command(joints_state_->getJointsState().torso);
}

ext: cpp

max_stars_repo_name: aosbgu/ROSPlan-ExperimentPDDL

max_issues_repo_name: aosbgu/ROSPlan-ExperimentPDDL

max_forks_repo_name: aosbgu/ROSPlan-ExperimentPDDL


text:
/***********************************************************************************************************************
 *  OpenStudio(R), Copyright (c) 2008-2018, Alliance for Sustainable Energy, LLC. All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
 *  following conditions are met:
 *
 *  (1) Redistributions of source code must retain the above copyright notice, this list of conditions and the following
 *  disclaimer.
 *
 *  (2) Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
 *  following disclaimer in the documentation and/or other materials provided with the distribution.
 *
 *  (3) Neither the name of the copyright holder nor the names of any contributors may be used to endorse or promote
 *  products derived from this software without specific prior written permission from the respective party.
 *
 *  (4) Other than as required in clauses (1) and (2), distributions in any form of modifications or other derivative
 *  works may not use the "OpenStudio" trademark, "OS", "os", or any other confusingly similar designation without
 *  specific prior written permission from Alliance for Sustainable Energy, LLC.
 *
 *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
 *  INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 *  DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER, THE UNITED STATES GOVERNMENT, OR ANY CONTRIBUTORS BE LIABLE FOR
 *  ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 *  PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
 *  AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 *  ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 **********************************************************************************************************************/

#ifndef OPENSTUDIO_MAINRIGHTCOLUMNCONTROLLER_HPP
#define OPENSTUDIO_MAINRIGHTCOLUMNCONTROLLER_HPP

#include "../shared_gui_components/OSQObjectController.hpp"
#include <boost/smart_ptr.hpp>
#include "../model/Model.hpp"
#include "../shared_gui_components/EditController.hpp"
#include "../shared_gui_components/LocalLibraryController.hpp"

#include <QSharedPointer>

class QStackedWidget;

namespace openstudio {

class EditController;
class HorizontalTabWidget;
class InspectorController;
class LocalLibraryController;
class SystemItem;
class OSItem;

class MainRightColumnController : public OSQObjectController
{
  Q_OBJECT

  public:

  MainRightColumnController(const model::Model & model, const openstudio::path &resourcesPath);

  virtual ~MainRightColumnController() {};

  HorizontalTabWidget * mainRightColumnView() const;

  QSharedPointer<LocalLibraryController> measureLibraryController();

  void hideMyModelTab(bool hide);

  bool isMyModelTabHidden(){return m_myModelTabIsHidden;}

  std::shared_ptr<InspectorController> inspectorController() { return m_inspectorController; };

  enum RightColumnTabID
  {
    MY_MODEL,
    LIBRARY,
    EDIT
  };

  // Methods to store and retrieve SystemItem objects.
  // These are used to get plenum colors and potentially other tasks.
  void registerSystemItem(const Handle & systemHandle, SystemItem * systemItem);
  void unregisterSystemItem(const Handle & systemHandle);
  SystemItem * systemItem(const Handle & systemHandle) const;

  signals:

  void toggleUnitsClicked(bool displayIP);

  void itemRemoveClicked(OSItem *);

  public slots:

  void configureForSiteSubTab(int subTabID);

  void configureForSchedulesSubTab(int subTabID);

  void configureForConstructionsSubTab(int subTabID);

  void configureForGeometrySubTab(int subTabID);

  void configureForLoadsSubTab(int subTabID);

  void configureForSpaceTypesSubTab(int subTabID);

  void configureForFacilitySubTab(int subTabID);

  void configureForSpacesSubTab(int subTabID);

  void configureForThermalZonesSubTab(int subTabID);

  void configureForHVACSystemsSubTab(int subTabID);

  void configureForBuildingSummarySubTab(int subTabID);

  void configureForOutputVariablesSubTab(int subTabID);

  void configureForSimulationSettingsSubTab(int subTabID);

  void configureForScriptsSubTab(int subTabID);

  void configureForRunSimulationSubTab(int subTabID);

  void configureForResultsSummarySubTab(int subTabID);

  void inspectModelObject(model::OptionalModelObject & modelObject, bool readOnly);

  void inspectModelObjectByItem(OSItem * item, bool readOnly);

  void toggleUnits(bool displayIP);

  void chooseEditTab();

  QSharedPointer<LocalLibraryController> measuresLibraryController();

  QSharedPointer<EditController> measuresEditController();

  private:

  REGISTER_LOGGER("openstudio.openstudio_lib.MainRightColumnController");

  void setMyModelView(QWidget * widget);

  void setLibraryView(QWidget * widget);

  void setEditView(QWidget * widget);

  HorizontalTabWidget * m_horizontalTabWidget;

  std::shared_ptr<InspectorController> m_inspectorController;

  QStackedWidget * m_myModelView;

  QStackedWidget * m_libraryView;

  QStackedWidget * m_editView;

  std::map<Handle,SystemItem *> m_systemItemMap;

  model::Model m_model;

  openstudio::path m_resourcesPath;

  QSharedPointer<LocalLibraryController> m_measureLibraryController;

  QSharedPointer<EditController> m_measureEditController;

  bool m_myModelTabIsHidden;

  OSItem * m_item = nullptr;

  private slots:

  void onItemRemoveClicked(OSItem *);

  void emitItemRemoveClicked(OSItem *);

  void onRemoveButtonClicked(bool checked);

  void onWorkspaceObjectRemoved();
};

} // openstudio

#endif // OPENSTUDIO_MAINRIGHTCOLUMNCONTROLLER_HPP

max_stars_repo_name: hongyuanjia/OpenStudio

max_issues_repo_name: hongyuanjia/OpenStudio

max_forks_repo_name: hongyuanjia/OpenStudio


text:
#ifndef BOOST_ARCHIVE_ITERATORS_BINARY_FROM_BASE64_HPP
#define BOOST_ARCHIVE_ITERATORS_BINARY_FROM_BASE64_HPP

// MS compatible compilers support #pragma once
#if defined(_MSC_VER) && (_MSC_VER >= 1020)
# pragma once
#endif

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

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

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

#include <cassert>

#include <boost/config.hpp> // for BOOST_DEDUCED_TYPENAME
#include <boost/serialization/throw_exception.hpp>
#include <boost/serialization/pfto.hpp>
#include <boost/static_assert.hpp>

#include <boost/iterator/transform_iterator.hpp>
#include <boost/archive/iterators/dataflow_exception.hpp>

namespace boost {
namespace archive {
namespace iterators {

/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////8
// convert base64 characters to binary data

namespace detail {

template<class CharType>
struct to_6_bit {
    typedef CharType result_type;
    CharType operator()(CharType t) const{
        const char lookup_table[] = {
            -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
            -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
            -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,62,-1,-1,-1,63,
            52,53,54,55,56,57,58,59,60,61,-1,-1,-1,-1,-1,-1,
            -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10,11,12,13,14,
            15,16,17,18,19,20,21,22,23,24,25,-1,-1,-1,-1,-1,
            -1,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,
            41,42,43,44,45,46,47,48,49,50,51,-1,-1,-1,-1,-1
        };
        // metrowerks trips this assertion - how come?
        #if ! defined(__MWERKS__)
        BOOST_STATIC_ASSERT(128 == sizeof(lookup_table));
        #endif
        signed char value = -1;
        if((unsigned)t <= 127)
            value = lookup_table[(unsigned)t];
        if(-1 == value)
            boost::serialization::throw_exception(
                dataflow_exception(dataflow_exception::invalid_base64_character)
            );
        return value;
    }
};

} // namespace detail

// note: what we would like to do is
// template<class Base, class CharType = BOOST_DEDUCED_TYPENAME Base::value_type>
//  typedef transform_iterator<
//      from_6_bit<CharType>,
//      transform_width<Base, 6, sizeof(Base::value_type) * 8, CharType>
//  > base64_from_binary;
// but C++ won't accept this.  Rather than using a "type generator" and
// using a different syntax, make a derivation which should be equivalent.
//
// Another issue addressed here is that the transform_iterator doesn't have
// a templated constructor.  This makes it incompatible with the dataflow
// ideal.  This is also addressed here.

template<
    class Base,
    class CharType = BOOST_DEDUCED_TYPENAME boost::iterator_value<Base>::type
>
class binary_from_base64 : public
    transform_iterator<
        detail::to_6_bit<CharType>,
        Base
    >
{
    friend class boost::iterator_core_access;
    typedef transform_iterator<
        detail::to_6_bit<CharType>,
        Base
    > super_t;
public:
    // make composible buy using templated constructor
    template<class T>
    binary_from_base64(BOOST_PFTO_WRAPPER(T)  start) :
        super_t(
            Base(BOOST_MAKE_PFTO_WRAPPER(static_cast< T >(start))),
            detail::to_6_bit<CharType>()
        )
    {}
    // intel 7.1 doesn't like default copy constructor
    binary_from_base64(const binary_from_base64 & rhs) :
        super_t(
            Base(rhs.base_reference()),
            detail::to_6_bit<CharType>()
        )
    {}
//    binary_from_base64(){};
};

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

#endif // BOOST_ARCHIVE_ITERATORS_BINARY_FROM_BASE64_HPP

max_stars_repo_name: zorbathut/glorp

max_issues_repo_name: zorbathut/glorp


text:
//
// Copyright Jason Rice 2017
// 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 NBDL_FWD_SQL_DB_UPDATE_HPP
#define NBDL_FWD_SQL_DB_UPDATE_HPP

#include <boost/hana/core/when.hpp>

namespace nbdl::sql_db
{
  namespace hana = boost::hana;

  template<typename T, typename = void>
  struct update_impl : update_impl<T, hana::when<true>> { };

  struct update_fn
  {
    template<typename DbInsert, typename Entity, typename Keys>
    void operator()(DbInsert, Entity&&, Keys&&) const;
  };

  constexpr update_fn update{};
}

#endif

max_stars_repo_name: ricejasonf/nbdl

max_issues_repo_name: ricejasonf/nbdl

max_forks_repo_name: ricejasonf/nbdl


text:
// Copyright MetaCommunications, Inc. 2003-2005.
// Copyright Steven Watanabe 2010
//
// 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 "common.hpp"
#include "xml.hpp"
#include "html.hpp"

#include <boost/regex.hpp>
#include <boost/foreach.hpp>
#include <boost/algorithm/string/split.hpp>
#include <boost/algorithm/string/classification.hpp>
#include <boost/date_time/posix_time/posix_time_io.hpp>
#include <algorithm>
#include <set>

using namespace boost::regression;

std::string boost::regression::alternate_mode(const std::string& mode) {
    if(mode == "user") {
        return "developer";
    } else {
        return "user";
    }
}

std::string boost::regression::release_postfix(bool is_release) {
    if(is_release) {
        return "_release";
    } else {
        return "";
    }
}

// safe
void boost::regression::get_libraries(const test_structure_t& test_structure, std::set<std::string>& out) {
    typedef boost::unordered_map<std::string, test_structure_t::platform_t>::const_reference outer_elem;
    BOOST_FOREACH(outer_elem platform, test_structure.platforms) {
        BOOST_FOREACH(test_structure_t::platform_t::const_reference run, platform.second) {
            BOOST_FOREACH(test_structure_t::toolset_group_t::const_reference toolset, run.toolsets) {
                BOOST_FOREACH(test_structure_t::toolset_t::const_reference library, toolset.second) {
                    out.insert(library.first);
                }
            }
        }
    }
}

#if 0

    <func:function name="meta:test_case_status">
        <xsl:param name="explicit_markup"/>
        <xsl:param name="test_log"/>

        <xsl:variable name="status">
            <xsl:choose>
                 <xsl:when test="meta:is_unusable( $explicit_markup, $test_log/@library, $test_log/@toolset )">
                     <xsl:text>unusable</xsl:text>
                 </xsl:when>
                 <xsl:when test="$test_log/@result='fail' and  $test_log/@status='unexpected' and $test_log/@is-new='no'">
                     <xsl:text>fail-unexpected</xsl:text>
                 </xsl:when>
                 <xsl:when test="$test_log/@result='fail' and  $test_log/@status='unexpected' and $test_log/@is-new='yes'">
                     <xsl:text>fail-unexpected-new</xsl:text>
                 </xsl:when>
                 <xsl:when test="$test_log/@result='success' and  $test_log/@status='unexpected'">
                     <xsl:text>success-unexpected</xsl:text>
                 </xsl:when>
                 <xsl:when test="$test_log/@status='expected'">
                     <xsl:text>expected</xsl:text>
                 </xsl:when>
                 <xsl:otherwise>
                     <xsl:text>other</xsl:text>
                 </xsl:otherwise>
             </xsl:choose>
         </xsl:variable>
         <func:result select="$status"/>
     </func:function>

    <func:function name="meta:is_toolset_required">
        <xsl:param name="toolset"/>
        <func:result select="count( $explicit_markup/explicit-failures-markup/mark-toolset[ @name = $toolset and @status='required' ] ) > 0"/>
    </func:function>

#endif

bool boost::regression::is_library_beta(const failures_markup_t& explicit_markup, const std::string& library) {
    boost::unordered_map<std::string, node_ptr>::const_iterator pos = explicit_markup.libraries.find(library);
    if(pos != explicit_markup.libraries.end()) {
        return check_attr(pos->second, "status", "beta");
    }
    return false;
}

bool boost::regression::is_test_log_a_test_case(const test_structure_t::test_log_t& test_log) {
    const std::string& type = test_log.test_type;
    return type == "compile" || type == "compile_fail" || type == "link" || type == "link_fail" ||
        type == "run" || type == "run_fail" || type == "run_pyd" || type == "run_mpi";
}

// Does not assume any constraints on contents of the strings
bool boost::regression::is_unusable(const failures_markup_t& markup, const std::string& library, const std::string& toolset) {
    boost::unordered_map<std::string, node_ptr>::const_iterator pos = markup.libraries.find(library);
    if(pos != markup.libraries.end()) {
        FOR_EACH_ELEMENT(mark_unusable, pos->second) {
            if(check_name(mark_unusable, "mark-unusable")) {
                FOR_EACH_ELEMENT(toolset_node, mark_unusable) {
                    std::string name;
                    if(lookup_attr(toolset_node, "name", name) && re_match(name, toolset)) {
                        return true;
                    }
                }
            }
        }
    }
    return false;
}

void boost::regression::get_unusable(const failures_markup_t& markup,
                                     const std::string& library,
                                     const test_structure_t& test_structure,
                                     boost::unordered_map<std::string, std::size_t>& out,
                                     std::vector<node_ptr>& notes) {
    boost::unordered_map<std::string, node_ptr>::const_iterator pos = markup.libraries.find(library);
    if(pos != markup.libraries.end()) {
        FOR_EACH_ELEMENT(mark_unusable, pos->second) {
            if(check_name(mark_unusable, "mark-unusable")) {
                node_ptr note = 0;
                std::vector<std::string> toolsets;
                FOR_EACH_ELEMENT(toolset_node, mark_unusable) {
                    std::string name;
                    if(check_name(toolset_node, "toolset") && lookup_attr(toolset_node, "name", name)) {
                        BOOST_FOREACH(test_structure_t::platform_group_t::const_reference platform, test_structure.platforms) {
                            BOOST_FOREACH(test_structure_t::platform_t::const_reference run, platform.second) {
                                BOOST_FOREACH(test_structure_t::toolset_group_t::const_reference toolset, run.toolsets) {
                                    if(re_match(name, toolset.first)) {
                                        toolsets.push_back(toolset.first);
                                    }
                                }
                            }
                        }
                    } else if(check_name(toolset_node, "note")) {
                        note = toolset_node;
                    }
                }
                if(note != 0 && !toolsets.empty()) {
                    notes.push_back(note);
                    BOOST_FOREACH(const std::string& toolset, toolsets) {
                        out[toolset] = notes.size();
                    }
                }
            }
        }
    }
}

// There are no restrictions on the pattern or the
// string.  The only special character in the pattern
// is '*', which matches any number of consecutive characters.
bool boost::regression::re_match(const std::string& pattern, const std::string& text) {
    std::size_t pattern_start = 0;
    std::size_t pattern_end = 0;
    std::size_t text_start = 0;
    // check that the leading portion of the string matches
    std::size_t first = pattern.find('*');
    if(first == std::string::npos) return pattern == text;
    if(pattern.substr(0, first) != text.substr(0, first)) return false;
    text_start = first;
    pattern_start = pattern_end = first + 1;
    for(; pattern_end != pattern.size(); ++pattern_end) {
        // split into blocks at '*'
        if(pattern[pattern_end] == '*') {
            // and search for each block
            std::size_t size = pattern_end - pattern_start;
            std::size_t off = text.find(pattern.data() + pattern_start, text_start, size);
            // if not found, the pattern doesn't match
            if(off == std::string::npos) return false;
            text_start = off + size;
            pattern_start = pattern_end + 1; // skip past the '*'
        }
    }
    // check that the tails of the strings are the same
    std::size_t tail_size = pattern_end - pattern_start;
    return tail_size <= text.size() - text_start &&
        pattern.substr(pattern_start, tail_size) == text.substr(text.size() - tail_size, tail_size);
}

// date-time

// The result is clamped to the range [0,30]
int boost::regression::timestamp_difference(const boost::posix_time::ptime& x, const boost::posix_time::ptime& y) {
    boost::posix_time::time_duration diff = y - x;
    int result = diff.hours() / 24;
    if(result < 0) return 0;
    else if(result > 30) return 30;
    else return result;
}

std::string boost::regression::format_timestamp(const boost::posix_time::ptime& timestamp) {
    std::ostringstream stream;
    stream.imbue(std::locale(std::locale::classic(), new boost::posix_time::time_facet("%a, %d %b %Y %H:%M:%S +0000")));
    stream << timestamp;
    return stream.str();
}

// path

// FIXME: The result MUST be a valid filesystem path.
std::string boost::regression::encode_path(const std::string& path) {
    std::string result;
    BOOST_FOREACH(char ch, path) {
        if(ch == '.' || ch == '/') {
            ch = '-';
        }
        // FIXME: allow only characters from the following set:
        // "[a-z][A-Z][0-9][-+_. ,()$!~?]...
        result += ch;
    }
    return result;
}

std::string boost::regression::escape_uri(const std::string& path) {
    std::string result;
    BOOST_FOREACH(char ch, path) {
        if (('a' <= ch && ch <= 'z') ||
            ('A' <= ch && ch <= 'Z') ||
            ('0' <= ch && ch <= '9') ||
            ch == '-' || ch == '_' || ch == '~' || ch == '.' ||
            // We're intentionally allowing '/' to go through.
            // to escape it as well, use escape_literal_uri
            ch == '/' ||
            // FIXME: reserved characters
            ch == '+')
            result += ch;
        else {
            unsigned digit = ch;
            ch &= 0xFF;
            const char * xdigits = "0123456789ABCDEF";
            result += '%';
            result += xdigits[digit >> 4];
            result += xdigits[digit & 0xF];
        }
    }
    return result;
}

std::string boost::regression::escape_literal_uri(const std::string& path) {
    std::string result;
    BOOST_FOREACH(char ch, path) {
        // FIXME: Assumes UTF-8
        if (('a' <= ch && ch <= 'z') ||
            ('A' <= ch && ch <= 'Z') ||
            ('0' <= ch && ch <= '9') ||
            ch == '-' || ch == '_' || ch == '~' || ch == '.')
            result += ch;
        else {
            unsigned digit = ch;
            ch &= 0xFF;
            const char * xdigits = "0123456789ABCDEF";
            result += '%';
            result += xdigits[digit >> 4];
            result += xdigits[digit & 0xF];
        }
    }
    return result;
}

// okay
std::string boost::regression::output_file_path(const std::string& path) {
    return("output/" + (encode_path(path) + ".html"));
}

// okay
std::string boost::regression::log_file_path(
    const failures_markup_t& explicit_markup,
    const test_structure_t::test_log_t& test_log,
    const std::string& runner,
    const std::string& release_postfix)
{
    if(show_output(explicit_markup, test_log)) {
        return output_file_path(runner + "-" + test_log.target_directory + release_postfix);
    } else {
        return "";
    }
}

bool boost::regression::show_library(const failures_markup_t& explicit_markup, const std::string& library, bool release) {
    return !release || !is_library_beta(explicit_markup, library);
}

bool boost::regression::show_output(const failures_markup_t& explicit_markup, const test_structure_t::test_log_t& test_log) {
    return ((!test_log.result || test_log.show_run_output) ||
        (test_log.result && !test_log.status))
        && !(is_unusable(explicit_markup, test_log.library, test_log.toolset));
}

bool boost::regression::show_toolset(const failures_markup_t& explicit_markup, const std::string& toolset, bool release) {
    return !release || explicit_markup.required_toolsets.find(toolset) != explicit_markup.required_toolsets.end();
}

// safe: no assumptions, enumerated result
std::string boost::regression::result_cell_class(const failures_markup_t& explicit_markup,
                                                 const std::string& library,
                                                 const std::string& toolset,
                                                 const test_log_group_t& test_logs) {
    if(is_unusable(explicit_markup, library, toolset)) {
        return "unusable";
    }
    if(test_logs.empty()) {
        return "missing";
    }
    BOOST_FOREACH(test_log_group_t::value_type log, test_logs) {
        if(!log->result && log->expected_result && !log->is_new) {
            return "fail-unexpected";
        }
    }
    BOOST_FOREACH(test_log_group_t::value_type log, test_logs) {
        if(!log->result && log->expected_result && log->is_new) {
            return "fail-unexpected-new";
        }
    }
    BOOST_FOREACH(test_log_group_t::value_type log, test_logs) {
        if(!log->result && log->expected_reason != "") {
            return "fail-expected-unreasearched";
        }
    }
    BOOST_FOREACH(test_log_group_t::value_type log, test_logs) {
        if(!log->result) {
            return "fail-expected";
        }
    }
    BOOST_FOREACH(test_log_group_t::value_type log, test_logs) {
        if(log->result && !log->expected_result) {
            return "success-unexpected";
        }
    }
    BOOST_FOREACH(test_log_group_t::value_type log, test_logs) {
        if(log->result && log->expected_result) {
            return "success-expected";
        }
    }
    return "unknown";
}
// safe
std::string boost::regression::result_cell_class(const failures_markup_t& explicit_markup,
                                                 const std::string& library,
                                                 const std::string& toolset,
                                                 const test_structure_t::library_t& test_logs)
{
    test_log_group_t tmp;
    BOOST_FOREACH(test_structure_t::library_t::const_reference test_case, test_logs) {
        BOOST_FOREACH(test_structure_t::test_case_t::const_reference log, test_case.second) {
            tmp.push_back(&log);
        }
    }
    return result_cell_class(explicit_markup, library, toolset, tmp);
}

// requires: purpose must be well-formed html
void boost::regression::insert_report_header(
    html_writer& document,
    const boost::posix_time::ptime& run_date,
    const std::vector<std::string>& warnings,
    const std::string& purpose)
{
    document << "
\n";
    document << "
\n";
    document << "        Report Time:  " << format_timestamp(run_date) << "\n";
    document << "
\n";

    if(!purpose.empty()) {
        document << "
\n";
        document << "        Purpose:  " << purpose << "\n";
        document << "
\n";
    }

    BOOST_FOREACH(const std::string& warning, warnings) {
        document << "
\n";
        document << "        Warning: \n";
        document << "        <a href=\"mailto:boost-testing@lists.boost.org?subject=[Report Pages]%20" << escape_literal_uri(warning) << " (" << format_timestamp(run_date) << ")\" class=\"warning-link\">\n";
        document << "            " << escape_xml(warning) << "\n";
        document << "        \n";
        document << "
\n";
    }

    document << "
\n";
}

// requires class_ is enumerated
void boost::regression::insert_view_link(html_writer& out, const std::string& page, const std::string& class_, bool release) {
    if(release) {
        out << "<a href=\"" << escape_uri(page) << ".html\" class=\"" << class_ << "\" target=\"_top\">"
               "Full View"
               "\n";
    } else {
        out << "<a href=\"" << escape_uri(page) << "_release.html\" class=\"" << class_ << "\" target=\"_top\">"
               "Release View"
               "";
    }

}

// requires: mode = developer | user (Should be the opposite of the current page)
// requires: page is the base name of the current page.  It should be valid
//           according to encode_path, but should not be URI escaped.
void boost::regression::insert_page_links(html_writer& document,
                                          const std::string& page,
                                          bool release,
                                          const std::string& mode) {
    document << "
\n";

    // yes, really.  The class is set to ""
    insert_view_link(document, page, "", release);

    std::string release_postfix(release? "_release" : "");

    document << " | "
                "<a href=\"../" << mode << "/" << escape_uri(page) << release_postfix << ".html\" class=\"view-link\" target=\"_top\">"
             << mode << " View"
                ""
                " | "
                "<a href=\"" << escape_uri(page) << release_postfix << "_.html#legend\">Legend\n"

                "
\n";

}

// requires: mode = summary | details
// requires: top_or_bottom = top | bottom
void boost::regression::insert_runners_rows(html_writer& document,
                                            const std::string& mode,
                                            const std::string& top_or_bottom,
                                            const test_structure_t& test_structure,
                                            const boost::posix_time::ptime& run_date) {
    std::string colspan = (mode == "summary") ? "1" : "2";

    if(top_or_bottom == "top") {
        document << "
\n"
                    "    <td colspan=\"" << colspan << "\"> 	\n";
        BOOST_FOREACH(test_structure_t::platform_group_t::const_reference platform, test_structure.platforms) {
            std::size_t count = 0;
            BOOST_FOREACH(test_structure_t::platform_t::const_reference run, platform.second) {
                count += run.toolsets.size();
            }
            if(count > 0) {
                document << "    <td colspan=\"" << count << "\" class=\"runner\">\n"
                            "        " << escape_xml(platform.first) << "\n"
                            "    	\n";
            }
        }
        document << "    <td colspan=\"" << colspan << "\"> 	\n"
                    "
\n";
    }

    document << "
\n"
                "    <td colspan=\"" << colspan << "\"> 	\n";
    BOOST_FOREACH(test_structure_t::platform_group_t::const_reference platform, test_structure.platforms) {
        BOOST_FOREACH(test_structure_t::platform_t::const_reference run, platform.second) {
            if(run.toolsets.size() > 0) {
                document << "    <td colspan=\"" << run.toolsets.size() << "\" class=\"runner\">\n"
                            "        <a href=\"../" << escape_uri(encode_path(run.runner)) << ".html\">\n"
                            "            " << escape_xml(run.runner) << "\n"
                            "        \n"
                            "    	\n";
            }
        }
    }
    document << "    <td colspan=\"" << colspan << "\"> 	\n"
                "
\n";

    document << "
\n"
                "<td colspan=\"" << colspan << "\"> 	\n";
    BOOST_FOREACH(test_structure_t::platform_group_t::const_reference platform, test_structure.platforms) {
        BOOST_FOREACH(test_structure_t::platform_t::const_reference run, platform.second) {
            if(run.toolsets.size() > 0) {
                document << "    <td colspan=\"" << run.toolsets.size() << "\" class=\"revision\">\n"
                            "         rev " << run.revision << "\n"
                            "    	\n";
            }
        }
    }
    document << "    <td colspan=\"" << colspan << "\"> 	\n"
                "
\n";

    document << "
\n"
                "    <td colspan=\"" << colspan << "\"> 	\n";
    BOOST_FOREACH(test_structure_t::platform_group_t::const_reference platform, test_structure.platforms) {
        BOOST_FOREACH(test_structure_t::platform_t::const_reference run, platform.second) {
            if(run.toolsets.size() > 0) {
                int age = timestamp_difference(run.timestamp, run_date);
                document << "    <td colspan=\"" << run.toolsets.size() << "\" class=\"timestamp\">\n"
                            "        <span class=\"timestamp-" << age << "\">" << format_timestamp(run.timestamp) << "";
                if(run.run_type != "full") {
                    document << "<span class=\"run-type-" << run.run_type << "\">" << run.run_type[0] << "\n";
                }
                document << "    	\n";
            }
        }
    }
    document << "    <td colspan=\"" << colspan << "\"> 	\n"
                "
\n";

    if(top_or_bottom == "bottom") {
        document << "
\n"
                    "    <td colspan=\"" << colspan << "\"> 	\n";
        BOOST_FOREACH(test_structure_t::platform_group_t::const_reference platform, test_structure.platforms) {
            std::size_t count = 0;
            BOOST_FOREACH(test_structure_t::platform_t::const_reference run, platform.second) {
                count += run.toolsets.size();
            }
            if(count > 0) {
                document << "    <td colspan=\"" << count << "\" class=\"runner\">\n"
                            "        " << escape_xml(platform.first) << "\n"
                            "    	\n";
            }
        }
        document << "    <td colspan=\"" << colspan << "\"> 	\n"
                    "
\n";
    }
}

// requires mode = summary | details
void boost::regression::insert_toolsets_row(html_writer& document,
                                            const test_structure_t& test_structure,
                                            const failures_markup_t& explicit_markup,
                                            const std::string& mode,
                                            const boost::posix_time::ptime& run_date,
                                            const std::string& library,
                                            const boost::unordered_map<std::string, std::size_t>& library_marks) {

    document << "
\n";

    std::string colspan = (mode == "summary") ? "1" : "2";
    std::string title = (mode == "summary") ?
        " library / toolset " :
        " test / toolset ";

    document << "    <td class=\"head\" colspan=\"" << colspan << "\" width=\"1%\">" << title << "	\n";
    BOOST_FOREACH(const test_structure_t::platform_group_t::const_reference platform, test_structure.platforms) {
        BOOST_FOREACH(const test_structure_t::platform_t::const_reference run, platform.second) {
            BOOST_FOREACH(const test_structure_t::toolset_group_t::const_reference toolset, run.toolsets) {
                std::string name = toolset.first;
                std::string class_ = (explicit_markup.required_toolsets.find(name) != explicit_markup.required_toolsets.end())?
                    "required-toolset-name" :
                    "toolset-name";

                document << "<td class=\"" << class_ << "\">\n";
                int age = timestamp_difference(run.timestamp, run_date);

                document <<    "<span class=\"timestamp-" << age << "\">\n";

                // break toolset names into words
                BOOST_FOREACH(char ch, name) {
                    document << ch;
                    if(ch == '-') {
                        document << ' ';
                    }
                }

                if(mode == "details") {
                    //
                    std::set<std::size_t> toolset_notes;
                    typedef boost::unordered_map<std::string, std::size_t>::const_reference ref_type;
                    BOOST_FOREACH(ref_type toolset_markup, library_marks.equal_range(name)) {
                        toolset_notes.insert(toolset_markup.second);
                    }
                    if(!toolset_notes.empty()) {
                        document << "\n";
                        bool first = true;
                        BOOST_FOREACH(std::size_t note_index, toolset_notes) {
                            if(!first) document << ", "; else first = false;
                            document << "<a href=\"#" << escape_uri(library) << "-note-" << note_index << "\" title=\"Note " << note_index << "\">\n"
                                        "    " << note_index << "\n"
                                        "\n";
                        }
                        document << "\n";
                    }
                }

                document << "\n"
                            "	\n";
            }
        }
    }
    document << "" << title << "	\n"
                "
\n";
}

namespace {

std::string get_note_attr(const test_structure_t::note_t& note, const std::string& name) {
    if(const node_ptr* node = boost::get<node_ptr>(&note)) {
        std::string result;
        lookup_attr(*node, name, result);
        return result;
    } else {
        return std::string();
    }
}

}

// requires: if note is a string, it is well-formed html
void boost::regression::show_note(
    html_writer& document,
    const test_structure_t::note_t& note,
    const std::string& references,
    const failures_markup_t& explicit_markup)
{
    document << "
\n";

    std::string author = get_note_attr(note, "author");
    std::string date = get_note_attr(note, "date");

    document << "    \n";

    if(author != "" && date != "") {
        document << "        [ " << escape_xml(author) << " " << escape_xml(date) << " ]\n";
    } else if(author != "") {
        document << "        [ " << escape_xml(author) << " ]\n";
    } else if(date != "") {
        document << "        [ " << escape_xml(date) << " ]\n";
    }

    document << "    \n";

    if(references != "") {
        // lookup references (refid="17,18")
        std::vector<std::string> refs;
        boost::algorithm::split(refs, references, boost::is_any_of(","));
        BOOST_FOREACH(const std::string& refid, refs) {
            boost::unordered_map<std::string, node_ptr>::const_iterator pos = explicit_markup.notes.find(refid);
            if(pos != explicit_markup.notes.end()) {
                write_contents(document, pos->second);
            } else {
                document << "    " << escape_xml(refid) << "\n";
            }
        }
    }
    if(const node_ptr* node_note = boost::get<node_ptr>(&note)) {
        write_contents(document, *node_note);
    } else if(const std::string* string_note = boost::get<std::string>(&note)) {
        document << *string_note; // not escaped--can contain html markup
    }

    document << "
\n";
}

// requires: any note that is a string contains well-formed html
void boost::regression::show_notes(html_writer& document,
                                   const std::vector<test_structure_t::note_t>& notes,
                                   const failures_markup_t& explicit_markup)
{
    document << "
\n";

    BOOST_FOREACH(const test_structure_t::note_t& note, notes) {

        document << "
\n";

        std::string refid = get_note_attr(note, "refid");
        ::show_note(document, note, refid, explicit_markup);

        document << "
\n";

    }

    document << "
\n";
}

max_stars_repo_name: ballisticwhisper/boost

max_issues_repo_name: ballisticwhisper/boost

max_forks_repo_name: ballisticwhisper/boost


text:
/*
 * Application.cpp
 *
 *  Created on: 10.06.2015
 *      Author: marius
 */

#include "../../include/gerbil/Application.h"
#include <boost/regex.hpp>
#include <boost/lexical_cast.hpp>

#ifdef __linux__
#include <sys/sysinfo.h>
#elif _WIN32
#include <windows.h>
#else
// is there another OS?
#endif

#ifdef GPU
#include <cuda_runtime.h>
#endif

/**
 * Detect the total amount of memory at the system.
 * @return
 */
unsigned long long getTotalSystemMemory()  {
#ifdef __linux__
	struct sysinfo info;
	if(sysinfo(&info) == -1)
		return DEF_MEMORY_SIZE;
	return info.totalram;
#elif _WIN32
	MEMORYSTATUSEX status;
    status.dwLength = sizeof(status);
    GlobalMemoryStatusEx(&status);
    return status.ullTotalPhys;
#else
	return DEF_MEMORY_SIZE;
#endif
}

/**
 * Detect the amount of free memory at the system.
 * @return
 */
unsigned long long getFreeSystemMemory()  {
#ifdef __linux__
	struct sysinfo info;
	if(sysinfo(&info) == -1)
		return DEF_MEMORY_SIZE;
	return info.freeram;
#elif _WIN32
	MEMORYSTATUSEX status;
    status.dwLength = sizeof(status);
    GlobalMemoryStatusEx(&status);
    return status.ullAvailPhys;
#else
	return DEF_MEMORY_SIZE;
#endif
}

/*
 * Constructor
 * default for params
 */
// TODO: Reorder attributes
gerbil::Application::Application() :
		_k(0), _m(0), _tempFilesNumber(0), _sequenceSplitterThreadsNumber(0),
		_superSplitterThreadsNumber(0), _hasherThreadsNumber(0), _thresholdMin(0), _memSize(0),
		_threadsNumber(0), _norm(DEF_NORM),
		_fastFileName(""), _tempFolderName(""), _kmcFileName(""), _tempFiles(NULL),
		_rtRun1(0.0), _rtRun2(0.0), _memoryUsage1(0), _memoryUsage2(0),
		_readerParserThreadsNumber(1), _numGPUs(0),
		_singleStep(0), _leaveBinStat(false), _histogram(0), _outputFormat(of_gerbil)
{

}

gerbil::Application::~Application() {
#ifdef GPU
	cudaDeviceReset();
#endif
}

void gerbil::Application::parseParams(const int &argc, char** argv) {
	uint i;
	for (i = 1; i < argc && argv[i][0] == '-'; i++) {
		switch (argv[i][1]) {
		case 'k':
			_k = atoi(argv[++i]);
			break;
		case 'm':
			_m = atoi(argv[++i]);
			break;
		case 'f':
			_tempFilesNumber = atoi(argv[++i]);
			break;
		case 'l':
			_thresholdMin = atoi(argv[++i]);
			break;
		case 't':
			_threadsNumber = atoi(argv[++i]);
			break;
		case 'e': {
			std::string s(argv[++i]);
			boost::regex rgx("(0*[1-9][0-9]*)(M|G)B?");
			boost::smatch match;
			if (!boost::regex_match(s, match, rgx)) {
				std::cout
						<< "invalid value for parameter -e\nuse -h for help\n";
				exit(0);
			}
			_memSize = atoi(match.str(1).c_str());
			if (match.str(2) == "G")
				_memSize *= 1024;
			break;
		}
		case 'd':
			_norm = false;
			break;
		case 'i':
			verbose = true;
			break;
		case 'o': {
			std::string s(argv[++i]);
			if (s == "fasta")
				_outputFormat = of_fasta;
			else if (s == "none")
				_outputFormat = of_none;
			else
				_outputFormat = of_gerbil;
			break;
		}
		case 'x':
			switch(argv[++i][0]) {
			case '1': _singleStep = 1; break;
			case '2': _singleStep = 2; break;
			case 'b': _leaveBinStat = true; break;
			case 'h': _histogram = true; break;
			}
			break;
#ifdef GPU
		case 'g': {
			// determine number of gpus to use
			int num;
			auto err = cudaGetDeviceCount(&num);
			if (err != cudaSuccess) {
				std::cerr << "Error while searching for GPU's: " << cudaGetErrorString(err) << std::endl;
				std::cerr << "Disabling GPU support." << std::endl;
				_numGPUs = 0;
			} else {
				_numGPUs = (uint8_t) std::min(num, 2);
			}
			break;
		}
#endif
		case 's':
			checkSystem();
			exit(0);
		case 'v':
			std::cout << VERSION_MAJOR << "." << VERSION_MINOR << std::endl;
			exit(0);
		case 'h':
			printf("_________________________________________________________________\n");
			printf("Gerbil version %i.%i\n", VERSION_MAJOR, VERSION_MINOR);
			printf("-----------------------------------------------------------------\n");
			printf("usage: gerbil [<option>|<flag>]* <input> <temp> <output>\n");
			printf("<option>:\n");
			printf("  -k <size>             size of kmers (default: 28)\n");
			printf("  -m <size>             size of minimizers (default: auto)\n");
			printf("  -e <size>(M|G)B       size of ram usage (default: auto)\n");
			printf("  -f <number>           number of temporary files (default: %u)\n",
					DEF_TEMPFILES_NUMBER);
			printf("  -t <number>           number of threads (default: auto)\n");
			printf("  -l <count>            minimal count of k-mers (default: %u)\n",
					DEF_THRESHOLD_MIN);
			printf("<flag>:\n");
			printf("  -h                    show help\n");
			printf("  -v                    version\n");
			printf("  -h                    help\n");
			printf("  -d                    disable normalization\n");
			printf("  -i                    verbose output\n");
			printf("  -s                    system check\n");
			printf("  -o <outputFormat>     output format\n");
			printf("      outputFormat:\n");
			printf("         gerbil         gerbil format\n");
			printf("         fasta          fasta format\n");
			printf("         none           no output\n");
#ifdef GPU
			printf("  -g                    enable gpu\n");
#endif
			printf("  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  \n");
			printf("  -x <mode>             Debugging and testing purposes\n");
			printf("                        (can be specified multiple times)\n");
			printf("     modes:\n");
			printf("        1               only step 1, leaves temporary files and a\n");
			printf("                        binStatFile (with statistical stuff)\n");
			printf("                        !Watch out: no <output>\n");
			printf("        2               only step 2, requires temporary files and\n");
			printf("                        the binStatFile\n");
			printf("                        !Watch out: no <input>\n");
			printf("        b               leaves the binStatFile\n");
			printf("        h               saves the data for a histogram of the\n");
			printf("                        uk-mers in the output folder\n");
			printf("-----------------------------------------------------------------\n");
			exit(0);
		}
	}
	IF_REL(if (argc < 4) {
		std::cout << "missing parameters\nuse -h for help\n"
		;
		exit(0)
		;
	});

	if (i + (_singleStep ? 2 : 3) <= argc) {
		if (_singleStep != 2)
			_fastFileName = std::string(argv[i++]);
		_tempFolderName = std::string(argv[i++]);
		if(_singleStep != 1)
			_kmcFileName = std::string(argv[i++]);
	}
		IF_REL(
				else { std::cerr << "missing parameters (-h for help)\n"; exit(1); })

	autocompleteParams();
	if (verbose)
		printParamsInfo();
	checkParams();
}

void gerbil::Application::process(const int &argc, char** argv) {

	parseParams(argc, argv);

	ReadBundle::setK(_k);

	if (_singleStep != 2)
		run1();
	else
		loadBinStat();

	if (_singleStep != 1)
		run2();

	if(_singleStep != 1 && !_leaveBinStat)
		std::remove((_tempFolderName + "binStatFile.txt").c_str());
}

void gerbil::Application::run1() {
	// no buffer for output stream
	setbuf(stdout, NULL);

	// time
	StopWatch sw(CLOCK_REALTIME);
	sw.start();

	// calculate memory
	uint32 frBlocksNumber, readBundlesNumber, superBundlesNumber;
	uint64 superWriterBufferSize;
	distributeMemory1(frBlocksNumber, readBundlesNumber, superBundlesNumber,
			superWriterBufferSize);

	// init pipeline
	FastReader fastReader(frBlocksNumber, _fastFileName,
			_readerParserThreadsNumber);
	FastParser fastParser(readBundlesNumber, fastReader.getFileType(), st_reads,
			fastReader.getSyncSwapQueues(), _readerParserThreadsNumber);
	SequenceSplitter sequenceSplitter(superBundlesNumber,
			fastParser.getSyncQueue(), _sequenceSplitterThreadsNumber, _k, _m,
			_tempFilesNumber, _norm);
	SuperWriter superWriter(_tempFolderName,
			sequenceSplitter.getSuperBundleQueues(), _tempFilesNumber,
			superWriterBufferSize);

	// start pipepline
	fastReader.process();
	fastParser.process();
	sequenceSplitter.process();
	superWriter.process();

	// join all
	fastReader.join();
	fastParser.join();
	sequenceSplitter.join();
	superWriter.join();

	// save bin statistic
	_tempFiles = superWriter.getTempFiles();
	saveBinStat();

	sw.stop();
	_rtRun1 = sw.get_s();

	// verbose output
	if (verbose) {
		printf("================== STAGE 1 ==================\n");
		fastReader.print();
		fastParser.print();
		sequenceSplitter.print();
		superWriter.print();
		printf("memory usage           : %12lu MB\n", B_TO_MB(_memoryUsage1));
		printf("---------------------------------------------\n");
	}
}

void gerbil::Application::run2() {
	// no buffer for output stream
	setbuf(stdout, NULL);

	// time
	StopWatch sw(CLOCK_REALTIME);
	sw.start();

	// calculate statistic for tempFiles
	TempFileStatistic tempFileStatistic(_tempFiles, _tempFilesNumber);

	// distribute number of hashers to number of gpu and cpu hashers
	uint8_t hasherThreadsGPU = std::min(_numGPUs, _hasherThreadsNumber);
	uint8_t hasherThreadsCPU = std::max(0,_hasherThreadsNumber-hasherThreadsGPU);

	// calculate memory
	uint32 superBundlesNumber, kmcBundlesNumber, kMerBundlesNumber;
	uint64 maxKmcHashtableSize;
	distributeMemory2(&tempFileStatistic, superBundlesNumber, kmcBundlesNumber,
			maxKmcHashtableSize, kMerBundlesNumber);

	// init distributor
	KmerDistributer distributor(hasherThreadsCPU, hasherThreadsGPU, _tempFilesNumber);

	// init pipeline
	SuperReader superReader(superBundlesNumber, _tempFiles, _tempFilesNumber, &distributor);
	KmerHasher kmerHasher(_k, kmcBundlesNumber, superReader.getSuperBundleQueue(),
			_superSplitterThreadsNumber, hasherThreadsCPU, hasherThreadsGPU,
			_tempFiles, _tempFilesNumber, _thresholdMin, _norm, _tempFolderName,
			maxKmcHashtableSize, kMerBundlesNumber,
			superReader.getTempFilesOrder(), &distributor);
	KmcWriter kmcWriter(_kmcFileName, kmerHasher.getKmcSyncSwapQueue(), _k, _outputFormat);

	// start pipeline
	superReader.process();
	kmerHasher.process();
	kmcWriter.process();

	// join all
	superReader.join();
	kmerHasher.join();
	kmcWriter.join();

	sw.stop();
	_rtRun2 = sw.get_s();

	// save bin statistic
	saveBinStat();

	if(_histogram)
		kmerHasher.saveHistogram();

	// verbose output
	if (verbose) {
		printf("================== STAGE 2 ==================\n");
		kmerHasher.print();
		kmcWriter.print();
		printf("memory usage    : %12lu MB\n", B_TO_MB(_memoryUsage2));
		printf("---------------------------------------------\n");
		printSummary();
	}
}

/*
 * private
 */

void gerbil::Application::distributeMemory1(uint32 &fastBundlesNumber,
		uint32 &readBundlesNumber, uint32 &superBundlesNumber,
		uint64 &superWriterBufferSize) {
	// some space for general consumption
	uint64 base_memory_B = RUN1_MEMORY_GENERAL_B;

	// const memory for SequenceSplitter
	base_memory_B += (_tempFilesNumber * _sequenceSplitterThreadsNumber)
			* SUPER_BUNDLE_DATA_SIZE_B;

	_memoryUsage1 = base_memory_B;

	// FastReader
	fastBundlesNumber = MIN_FASTBUNDLEBUFFER_SIZE_B / FAST_BUNDLE_DATA_SIZE_B;
	_memoryUsage1 += fastBundlesNumber * FAST_BUNDLE_DATA_SIZE_B;

	// FastParser
	readBundlesNumber = MIN_READBUNDLEBUFFER_SIZE_B / READ_BUNDLE_SIZE_B;
	_memoryUsage1 += readBundlesNumber * READ_BUNDLE_SIZE_B;

	// SequenceSplitter
	superBundlesNumber =
	MIN_SUPERBUNDLEBUFFER_SIZE_B / SUPER_BUNDLE_DATA_SIZE_B;
	_memoryUsage1 += superBundlesNumber * SUPER_BUNDLE_DATA_SIZE_B;

	// SuperWriter
	_memoryUsage1 += MIN_SUPERWRITERBUFFER_SIZE_B;

	// check minimal memory
	if (_memoryUsage1 > MB_TO_B(_memSize)) {
		std::cerr
				<< "Not enough memory!\n\t Reduced number of temporary files/ the Number of SequenceSplitters or increasing the amount of memory."
				<< std::endl;
		exit(1);
	}

	// compute memory for buffers

	// memory for FastBundles
	uint64 optFastBundlesNumber = MAX_FASTBUNDLEBUFFER_SIZE_B
			/ FAST_BUNDLE_DATA_SIZE_B;
	uint64 memOptFastBundles = 0;
	if (optFastBundlesNumber > fastBundlesNumber) {
		optFastBundlesNumber -= fastBundlesNumber; // already assured
		memOptFastBundles = optFastBundlesNumber * FAST_BUNDLE_DATA_SIZE_B;
	} else
		optFastBundlesNumber = 0;

	// memory for ReadBundles
	uint64 optReadBundlesNumber = MAX_READBUNDLEBUFFER_SIZE_B
			/ READ_BUNDLE_SIZE_B;
	uint64 memOptReadBundles = 0;
	if (optReadBundlesNumber > readBundlesNumber) {
		optReadBundlesNumber -= readBundlesNumber; // already assured
		memOptReadBundles = optReadBundlesNumber * READ_BUNDLE_SIZE_B;
	} else
		optReadBundlesNumber = 0;

	// memory for SuperBundles
	uint64 optSuperBundlesNumber = MAX_SUPERBUNDLEBUFFER_SIZE_B
			/ SUPER_BUNDLE_DATA_SIZE_B;
	uint64 memOptSuperBundles = 0;
	if (optSuperBundlesNumber > superBundlesNumber) {
		optSuperBundlesNumber -= superBundlesNumber; // already assured
		memOptSuperBundles = optSuperBundlesNumber * SUPER_BUNDLE_DATA_SIZE_B;
	} else
		optSuperBundlesNumber = 0;

	uint64 availableMemory_B = (MB_TO_B(_memSize) - _memoryUsage1) * 0.5; // assure 50% memory for SuperWriterBuffer

	// assure memory
	uint64 sumOptMem = memOptFastBundles + memOptReadBundles
			+ optSuperBundlesNumber;
	if (sumOptMem <= availableMemory_B) {
		fastBundlesNumber += optFastBundlesNumber;
		readBundlesNumber += optReadBundlesNumber;
		superBundlesNumber += optSuperBundlesNumber;
	} else {
		fastBundlesNumber += (double) availableMemory_B
				/ FAST_BUNDLE_DATA_SIZE_B
				* ((double) memOptFastBundles / sumOptMem);
		readBundlesNumber += (double) availableMemory_B / READ_BUNDLE_SIZE_B
				* ((double) memOptReadBundles / sumOptMem);
		superBundlesNumber += (double) availableMemory_B
				/ SUPER_BUNDLE_DATA_SIZE_B
				* ((double) memOptSuperBundles / sumOptMem);
	}

	_memoryUsage1 = base_memory_B;
	_memoryUsage1 += fastBundlesNumber * FAST_BUNDLE_DATA_SIZE_B;
	_memoryUsage1 += readBundlesNumber * READ_BUNDLE_SIZE_B;
	_memoryUsage1 += superBundlesNumber * SUPER_BUNDLE_DATA_SIZE_B;

	availableMemory_B = MB_TO_B(_memSize) - _memoryUsage1;

	superWriterBufferSize = availableMemory_B
			/ (SUPER_BUNDLE_DATA_SIZE_B + sizeof(SuperBundleStackItem));

	_memoryUsage1 += superWriterBufferSize
			* (SUPER_BUNDLE_DATA_SIZE_B + sizeof(SuperBundleStackItem));
}

void gerbil::Application::distributeMemory2(
		TempFileStatistic* tempFileStatistic, uint32 &superBundlesNumber,
		uint32 &kmcBundlesNumber, uint64 &maxKmcHashtableSize,
		uint32 &kMerBundlesNumber) {
	uint64 bytesPerHashEntry = getKMerByteNumbers(_k) + sizeof(uint_cv);

	// some space for general consumption
	uint64 base_memory_B = RUN2_MEMORY_GENERAL_B;

	// const memory consumption
	base_memory_B += _numGPUs * GPU_COPY_BUFFER_SIZE;

	base_memory_B += _superSplitterThreadsNumber * _hasherThreadsNumber
			* KMER_BUNDLE_DATA_SIZE_B;
	base_memory_B += 2 * (_hasherThreadsNumber + _numGPUs) * KMER_BUNDLE_DATA_SIZE_B;
	base_memory_B += 2 * (_hasherThreadsNumber + _numGPUs)
			* (1 + FAILUREBUFFER_KMER_BUNDLES_NUMBER_PER_THREAD)
			* KMER_BUNDLE_DATA_SIZE_B;
	base_memory_B += (_hasherThreadsNumber + _numGPUs) * KMC_BUNDLE_DATA_SIZE_B;

	_memoryUsage2 = base_memory_B;
	uint64 availableMemory_B = MB_TO_B(_memSize) - _memoryUsage2;

	// compute minimum sizes
	superBundlesNumber = MIN_SUPERBUNDLEBUFFER2_SIZE_B
			/ SUPER_BUNDLE_DATA_SIZE_B;
	kMerBundlesNumber = MIN_KMERBUNDLEBUFFER_SIZE_B / KMER_BUNDLE_DATA_SIZE_B;
	kmcBundlesNumber = MIN_KMCBUNDLEBUFFER_SIZE_B / KMC_BUNDLE_DATA_SIZE_B;
	maxKmcHashtableSize = MIN_KMCHASHTABLE_SIZE_B / bytesPerHashEntry;

	// update memory usage for step 2
	_memoryUsage2 += (uint64) superBundlesNumber * SUPER_BUNDLE_DATA_SIZE_B;
	_memoryUsage2 += (uint64) kMerBundlesNumber * KMER_BUNDLE_DATA_SIZE_B;
	_memoryUsage2 += (uint64) kmcBundlesNumber * KMC_BUNDLE_DATA_SIZE_B;
	_memoryUsage2 += maxKmcHashtableSize * bytesPerHashEntry;
	availableMemory_B = MB_TO_B(_memSize) - _memoryUsage2;
	//printf("%u\t\t%u\t\t%u\t\t%lu\n", superBundlesNumber, kMerBundlesNumber, kmcBundlesNumber, maxKmcHashtableSize);

	// compute memory for hashtable
	uint64 maxUKMersNumber = std::min(tempFileStatistic->getMaxKMersNumber(),
			tempFileStatistic->getAvg2SdKMersNumber());
	if (maxUKMersNumber > maxKmcHashtableSize) {
		maxUKMersNumber -= maxKmcHashtableSize; // already assured
		uint64 extraSize;
		if (maxUKMersNumber
				* bytesPerHashEntry<= availableMemory_B * MEM_KEY_HT)
			extraSize = maxUKMersNumber;
		else
			extraSize = availableMemory_B * MEM_KEY_HT / bytesPerHashEntry;
		maxKmcHashtableSize += extraSize;
		_memoryUsage2 += extraSize * bytesPerHashEntry;
		availableMemory_B = MB_TO_B(_memSize) - _memoryUsage2;
	}

	// compute memory for buffers
	uint64 optSuperBundlesNumber =
			tempFileStatistic->getAvg2SdSize() / SUPER_BUNDLE_DATA_SIZE_B;
	uint64 memOptSuperBundles = 0;
	if (optSuperBundlesNumber > superBundlesNumber) {
		optSuperBundlesNumber -= superBundlesNumber; // already assured
		memOptSuperBundles = optSuperBundlesNumber * SUPER_BUNDLE_DATA_SIZE_B;
	} else
		optSuperBundlesNumber = 0;

	uint64 optKMerBundlesNumber = tempFileStatistic->getAvg2SdKMersNumber()
			* getKMerByteNumbers(_k) / KMER_BUNDLE_DATA_SIZE_B;
	//printf("optkmer: %lu\n", optKMerBundlesNumber * KMER_BUNDLE_DATA_SIZE_B);
	uint64 memOptKMerBundles = 0;
	if (optKMerBundlesNumber > kMerBundlesNumber) {
		optKMerBundlesNumber -= kMerBundlesNumber; // already assured
		memOptKMerBundles = optKMerBundlesNumber * KMER_BUNDLE_DATA_SIZE_B;
	} else
		optKMerBundlesNumber = 0;

	uint64 optKmcBundlesNumber = tempFileStatistic->getAvgKMersNumber()
			/ (1 + 2 * log((uint64) _thresholdMin))
			* getKMerByteNumbers(_k) / KMC_BUNDLE_DATA_SIZE_B; // should be: number of uk-Mers
			//printf("optkmc: %lu\n", optKmcBundlesNumber* KMC_BUNDLE_DATA_SIZE_B);
	uint64 memOptKmcBundles = 0;
	if (optKmcBundlesNumber > kmcBundlesNumber) {
		optKmcBundlesNumber -= kmcBundlesNumber; // already assured
		memOptKmcBundles = optKmcBundlesNumber * KMC_BUNDLE_DATA_SIZE_B;
	} else
		optKmcBundlesNumber = 0;

	// assure memory
	uint64 sumOptMem = memOptSuperBundles + memOptKMerBundles
			+ memOptKmcBundles;
	if (sumOptMem <= availableMemory_B) {
		superBundlesNumber += optSuperBundlesNumber;
		kMerBundlesNumber += optKMerBundlesNumber;
		kmcBundlesNumber += optKmcBundlesNumber;
	} else {
		superBundlesNumber += (double) availableMemory_B
				/ SUPER_BUNDLE_DATA_SIZE_B
				* ((double) memOptSuperBundles / sumOptMem);
		kMerBundlesNumber += (double) availableMemory_B
				/ KMER_BUNDLE_DATA_SIZE_B
				* ((double) memOptKMerBundles / sumOptMem);
		kmcBundlesNumber += (double) availableMemory_B / KMC_BUNDLE_DATA_SIZE_B
				* ((double) memOptKmcBundles / sumOptMem);
	}

	// update memory usage for step 2
	_memoryUsage2 = base_memory_B;
	_memoryUsage2 += superBundlesNumber * SUPER_BUNDLE_DATA_SIZE_B;
	_memoryUsage2 += kMerBundlesNumber * KMER_BUNDLE_DATA_SIZE_B;
	_memoryUsage2 += kmcBundlesNumber * KMC_BUNDLE_DATA_SIZE_B;
	_memoryUsage2 += maxKmcHashtableSize * bytesPerHashEntry;
	availableMemory_B = MB_TO_B(_memSize) - _memoryUsage2;
	//printf("%u\t\t%u\t\t%u\t\t%lu\n", superBundlesNumber, kMerBundlesNumber, kmcBundlesNumber, maxKmcHashtableSize);
	/*printf("%lu MB\t\t%lu MB\t\t%lu MB\t\t%lu MB\n",
	 B_TO_MB(superBundlesNumber * SUPER_BUNDLE_DATA_SIZE_B),
	 B_TO_MB(kMerBundlesNumber * KMER_BUNDLE_DATA_SIZE_B),
	 B_TO_MB(kmcBundlesNumber * KMC_BUNDLE_DATA_SIZE_B),
	 B_TO_MB(maxKmcHashtableSize * bytesPerHashEntry));*/

	//printf("avg Size     = %12lu\n", tempFileStatistic->getAvgKMersNumber());
	//printf("stabw        = %12lu\n", tempFileStatistic->getSdKMersNumber());
	//printf("max Size     = %12lu\n", tempFileStatistic->getMaxKMersNumber());
	//printf("avg+2Sd Size = %12lu\n", tempFileStatistic->getAvg2SdKMersNumber());
}

void gerbil::Application::checkSystem() {
	printf("check System...\n");
	printf("supports lockfree\n");
	printf("\tuint64 : ");
	if (__atomic_always_lock_free(sizeof(uint64), 0))
		printf("yes\n");
	else
		printf("no\n");
	printf("\tuint32 : ");
	if (__atomic_always_lock_free(sizeof(uint32), 0))
		printf("yes\n");
	else
		printf("no\n");
	printf("\tuint16 : ");
	if (__atomic_always_lock_free(sizeof(uint16), 0))
		printf("yes\n");
	else
		printf("no\n");
	printf("\tuint8  : ");
	if (__atomic_always_lock_free(sizeof(uint8), 0))
		printf("yes\n");
	else
		printf("no\n");
	unsigned concurentThreadsSupported = std::thread::hardware_concurrency();
	printf("supported threads: %u\n", concurentThreadsSupported);
	//int sysinfo(struct sysinfo *info);
	/*printf("total-ram: %lu\n", (size_t)sysconf( _SC_PHYS_PAGES ) *
	 (size_t)sysconf( _SC_PAGESIZE ));*/

	//struct sysinfo info;
	//sysinfo(&info);
	uint64_t totalram = getTotalSystemMemory();
	uint64_t freeram = getFreeSystemMemory();
	printf("total-ram: %2.3f GB\n",
			(double) totalram / 1024 / 1024 / 1024);
	printf("free-ram: %2.3f GB\n", (double) freeram / 1024 / 1024 / 1024);

	/*struct stat64 stat_buf;
	if (!_fastFileName.empty() && !stat64(_fastFileName.c_str(), &stat_buf)) {
		printf("file size: %f GB\n",
				(double) stat_buf.st_size / 1024 / 1024 / 1024);

	}*/
}

void gerbil::Application::autocompleteParams() {
#define SET_DEFAULT(x, d) if(!x) x = d

	// set to default values
	SET_DEFAULT(_k, DEF_KMER_SIZE);
	SET_DEFAULT(_threadsNumber,
			std::thread::hardware_concurrency() < MIN_THREADS_NUMBER ? DEF_THREADS_NUMBER : std::thread::hardware_concurrency());
	if (_threadsNumber < 4)
		_threadsNumber = 4;
	SET_DEFAULT(_sequenceSplitterThreadsNumber,
			_threadsNumber <= 4 ? 2 : _threadsNumber - 3);

#if false
	SET_DEFAULT(_superSplitterThreadsNumber, 1 + (_threadsNumber - 1) * 4 / 10);
	SET_DEFAULT(_hasherThreadsNumber, 1 + (_threadsNumber - 1) * 8 / 10);
#endif

	SET_DEFAULT(_superSplitterThreadsNumber, 1 + (_threadsNumber - 1) * 5 / 10);
	SET_DEFAULT(_hasherThreadsNumber, _numGPUs + 1 + (_threadsNumber - 1) * 6 / 10);

	SET_DEFAULT(_tempFilesNumber, DEF_TEMPFILES_NUMBER);
	SET_DEFAULT(_thresholdMin, DEF_THRESHOLD_MIN);

	// set size of available memory
	if (!_memSize) {
		//struct sysinfo info;
		//if (!sysinfo(&info)) {
		uint64_t totalram = getTotalSystemMemory();
			_memSize = totalram / 1024 / 1024;
			if (_memSize > 1024)				// for system and file buffers
				_memSize -= 1024;
			else
				_memSize = 0;					// no auto setup
		//} else
		//	_memSize = DEF_MEMORY_SIZE;
	}

	if (!_sequenceSplitterThreadsNumber)
		_sequenceSplitterThreadsNumber = 1;
	if (!_superSplitterThreadsNumber)
		_superSplitterThreadsNumber = 1;
	if (!_hasherThreadsNumber)
		_hasherThreadsNumber = 1;

	// set size of minimizers
	if (!_m) {
		uint_tfn x = _tempFilesNumber;
		while (x) {
			x >>= 2;
			++_m;
		}
		// for balanced distribution of file sizes
		if (_m < MAX_MINIMIZER_SIZE)
			++_m;
		if (_m < MAX_MINIMIZER_SIZE)
			++_m;

		if (_m < MIN_MINIMIZER_SIZE)
			_m = MIN_MINIMIZER_SIZE;

	}
}

void gerbil::Application::checkParams() {
#define CHECK_PARAM_IN_RANGE(x, min, max, s1, s2)																			\
		if (x < min) {																											\
			std::cerr << s1 << " (" << (uint64)x << ") " << " is too small (should be: " << s2 << " >= " << min << ")" << std::endl;		\
			exit(1);																											\
		}																														\
		else if (x > max) {																										\
			std::cerr << s1 << " (" << (uint64)x << ") " << " is too large (should be: " << s2 << " <= " << max << ")" << std::endl;		\
			exit(1);																											\
		}

	// check file paths
	if (_fastFileName.empty() && _singleStep != 2) {
		printf("input file is unknown\n");
		exit(1);
	}
	if (_tempFolderName.empty()) {
		printf("temp folder is unknown\n");
		exit(1);
	}
	if (_kmcFileName.empty() && _singleStep != 1) {
		printf("output file is unknown\n");
		exit(1);
	}

	// check parameter ranges
	CHECK_PARAM_IN_RANGE(_memSize, MIN_MEMORY_SIZE, MAX_MEMORY_SIZE,
			"size e of memory", "e");
	CHECK_PARAM_IN_RANGE(_tempFilesNumber, MIN_TEMPFILES_NUMBER,
			MAX_TEMPFILES_NUMBER, "number n of temp files", "n");
	CHECK_PARAM_IN_RANGE(_m, MIN_MINIMIZER_SIZE, MAX_MINIMIZER_SIZE,
			"size m of minimizers", "m");
	CHECK_PARAM_IN_RANGE(_k, MIN_KMER_SIZE, MAX_KMER_SIZE, "size k of k-mers",
			"k");
	CHECK_PARAM_IN_RANGE(_thresholdMin, MIN_THRESHOLD_MIN, MAX_THRESHOLD_MIN,
			"minimum counts l of k-mer", "l");

	CHECK_PARAM_IN_RANGE(_threadsNumber, MIN_THREADS_NUMBER, MAX_THREADS_NUMBER,
			"number t of threads", "t");

	// check additional conditions
	if (_m > _k) {
		std::cerr
				<< "size m of minimizers is too large, size of k-mers k is too small (should be: m <= k)\n";
		exit(1);
	}
	if ((((uint64) 4) << (2 * _m)) < _tempFilesNumber) {
		std::cerr
				<< "number n of temp files is too large, size of minimizers m is too small (should be: n <= 4^m)\n";
		exit(1);
	}
}

void gerbil::Application::printParamsInfo() {
	printf("______________________________________________\n");
	printf("Gerbil version %i.%i\n", VERSION_MAJOR, VERSION_MINOR);
	printf("================= PARAMETERS =================\n");
	printf("size of k-mers          : %5u\n", _k);
	printf("size of minimizers      : %5u\n", _m);
	printf("threshold min           : %5u\n", _thresholdMin);
	printf("normalized kmers        : ");
	_norm ? printf(" true\n") : printf("false\n");
	printf("number of temp-files    : %5lu\n", _tempFilesNumber);
	printf("total number of threads : %5u\n", _threadsNumber);
	printf("number of splitters     : %5u\n", _sequenceSplitterThreadsNumber);
	printf("number of hashers       : %5u\n", _hasherThreadsNumber);
	printf("input                   :       %s\n", _fastFileName.c_str());
	printf("temp                    :       %s\n", _tempFolderName.c_str());
	printf("output                  :       %s\n", _kmcFileName.c_str());
	printf("size of memory          : %5lu MB\n", _memSize);
	printf("number of gpu's         : %5u\n", _numGPUs);
	printf("---------------------------------------------\n");
}

void gerbil::Application::printSummary() {
	printf("===================================================\n");
	printf("================== S U M M A R Y ==================\n");
	printf("===================================================\n");
	printf("time (real) for stage1    :  % 5.3f s\n", _rtRun1);
	printf("time (real) for stage2    :  % 5.3f s\n", _rtRun2);
	printf("time (real) total (1 + 2) :  % 5.3f s\n", _rtRun1 + _rtRun2);
	printf("---------------------------------------------------\n");
}

void gerbil::Application::saveBinStat() {
	std::string binStatFileName(_tempFolderName);
	binStatFileName += "binStatFile.txt";
	FILE* binStatFile = fopen(binStatFileName.c_str(), "wb+");
	for (uint_tfn tempFileId(0); tempFileId < _tempFilesNumber; ++tempFileId)
		_tempFiles[tempFileId].fprintStat(binStatFile);
	fclose(binStatFile);
}

void gerbil::Application::loadBinStat() {
	if (_tempFiles)
		return;
	std::string binStatFileName(_tempFolderName);
	binStatFileName += "binStatFile.txt";
	FILE* binStatFile = fopen(binStatFileName.c_str(), "rb");
	_tempFiles = new TempFile[_tempFilesNumber];
	for (uint_tfn tempFileId(0); tempFileId < _tempFilesNumber; ++tempFileId) {
		_tempFiles[tempFileId].loadStats(_tempFolderName, binStatFile);
	}
	fclose(binStatFile);
}

max_stars_repo_name: danflomin/gerbil

max_issues_repo_name: danflomin/gerbil

max_forks_repo_name: danflomin/gerbil


text:
/*  $Id: vecscreen_run_unit_test.cpp 191065 2010-05-07 15:27:55Z madden $
* ===========================================================================
*
*                            PUBLIC DOMAIN NOTICE
*               National Center for Biotechnology Information
*
*  This software/database is a "United States Government Work" under the
*  terms of the United States Copyright Act.  It was written as part of
*  the author's official duties as a United States Government employee and
*  thus cannot be copyrighted.  This software/database is freely available
*  to the public for use. The National Library of Medicine and the U.S.
*  Government have not placed any restriction on its use or reproduction.
*
*  Although all reasonable efforts have been taken to ensure the accuracy
*  and reliability of the software and data, the NLM and the U.S.
*  Government do not and cannot warrant the performance or results that
*  may be obtained by using this software or data. The NLM and the U.S.
*  Government disclaim all warranties, express or implied, including
*  warranties of performance, merchantability or fitness for any particular
*  purpose.
*
*  Please cite the author in any work or product based on this material.
*
* ===========================================================================
*
* Author:  Tom Madden
*
* File Description:
*   Unit test module to test CVecscreenRun class.
*
* ===========================================================================
*/

#include <ncbi_pch.hpp>
#include <corelib/ncbiexpt.hpp>
#include <corelib/ncbiutil.hpp>
#include <corelib/ncbistre.hpp>

#include <objmgr/object_manager.hpp>
#include <objmgr/scope.hpp>
#include <objtools/data_loaders/genbank/gbloader.hpp>
#include <objmgr/util/sequence.hpp>
#include <objects/seqloc/Seq_id.hpp>

#include <algo/blast/api/blast_exception.hpp>
#include <algo/blast/blastinput/blast_scope_src.hpp>

#include <algo/blast/format/vecscreen_run.hpp>

#define NCBI_BOOST_NO_AUTO_TEST_MAIN
#include <corelib/test_boost.hpp>
#include <boost/test/auto_unit_test.hpp>
#include <boost/test/floating_point_comparison.hpp>

using namespace ncbi;
using namespace ncbi::blast;
using namespace ncbi::objects;

BOOST_AUTO_TEST_SUITE(vecscreen_run)

BOOST_AUTO_TEST_CASE(VecscreenRunWithHits)
{
    const bool is_prot = false;
    SDataLoaderConfig config(is_prot, SDataLoaderConfig::eUseGenbankDataLoader);

    CBlastScopeSource ss(config);
    CRef<CScope> scope = ss.NewScope();

    CRef<CSeq_loc> query_loc(new CSeq_loc());
    query_loc->SetWhole().SetGi(555);

    CVecscreenRun vs_run(query_loc, scope);

    list<CVecscreenRun::SVecscreenSummary> vs_list = vs_run.GetList();

    CVecscreenRun::SVecscreenSummary& match = vs_list.front();

    BOOST_REQUIRE(vs_list.size() == 1);
    BOOST_REQUIRE(match.range.GetFrom() == 588);
    BOOST_REQUIRE(match.range.GetTo() == 623);

    CRef<CSeq_align_set> seqalign_set = vs_run.GetSeqalignSet();
    BOOST_REQUIRE(seqalign_set->Size() == 1);
}

BOOST_AUTO_TEST_CASE(VecscreenRunWithNoHits)
{
    const bool is_prot = false;
    SDataLoaderConfig config(is_prot, SDataLoaderConfig::eUseGenbankDataLoader);

    CBlastScopeSource ss(config);
    CRef<CScope> scope = ss.NewScope();

    CRef<CSeq_loc> query_loc(new CSeq_loc());
    query_loc->SetWhole().SetGi(405832);

    CVecscreenRun vs_run(query_loc, scope);

    list<CVecscreenRun::SVecscreenSummary> vs_list = vs_run.GetList();

    BOOST_REQUIRE(vs_list.size() == 0);

    CRef<CSeq_align_set> seqalign_set = vs_run.GetSeqalignSet();
    BOOST_REQUIRE(seqalign_set->Size() == 0);
}

BOOST_AUTO_TEST_CASE(VecscreenRunWithNoDataLoader)
{
    // Data loader is intentionally missing, so as to provoke constructor exception
    CRef<CObjectManager> object_manager = CObjectManager::GetInstance();
    CRef<CScope> scope(new CScope(*object_manager));

    CRef<CSeq_loc> query_loc(new CSeq_loc());
    query_loc->SetWhole().SetGi(555);

    BOOST_REQUIRE_THROW(CVecscreenRun vs_run(query_loc, scope), blast::CBlastException);
}

BOOST_AUTO_TEST_SUITE_END()

max_stars_repo_name: OpenHero/gblastn

max_issues_repo_name: OpenHero/gblastn

max_forks_repo_name: OpenHero/gblastn


text:
/*
 * Copyright (C) 2009-2012, Gostai S.A.S.
 *
 * This software is provided "as is" without warranty of any kind,
 * either expressed or implied, including but not limited to the
 * implied warranties of fitness for a particular purpose.
 *
 * See the LICENSE file for more information.
 */

#include <boost/date_time/local_time/local_time.hpp>

#include <urbi/object/symbols.hh>
#include <urbi/object/date.hh>
#include <urbi/object/duration.hh>
#include <urbi/object/global.hh>

namespace urbi
{
  namespace object
  {
    /*---------------.
    | Construction.  |
    `---------------*/

    Date::Date()
      : time_(boost::posix_time::microsec_clock::local_time())
    {
      proto_add(proto ? rObject(proto) : Object::proto);
    }

    Date::Date(const value_type& t)
      : time_(t)
    {
      proto_add(proto ? rObject(proto) : Object::proto);
    }

    Date::Date(rDate time)
      : time_(time->time_)
    {
      CAPTURE_GLOBAL(Orderable);
      proto_add(Orderable);
      proto_add(proto);
    }

    // FIXME: kill this when overloading is fully supported
    OVERLOAD_TYPE_3(
      MINUS_overload, 1, 1,
      Date,
      (rDuration (Date::*)(rDate) const)                      &Date::operator-,
      Duration,
      (rDate     (Date::*)(const Date::duration_type&) const) &Date::operator-,
      Float,
      (rDate     (Date::*)(const Date::duration_type&) const) &Date::operator-)

    // FIXME: kill this when overloading is fully supported
    static rObject MINUS(const objects_type& args)
    {
      check_arg_count(args, 0, 1);
      static rPrimitive actual = new Primitive(MINUS_overload);
      return (*actual)(args);
    }

    URBI_CXX_OBJECT_INIT(Date)
      : time_(boost::posix_time::microsec_clock::local_time())
    {
      bind_variadic(SYMBOL(MINUS), MINUS);

#define DECLARE(Unit)                        \
      bind(#Unit,       &Date::Unit ## _get, \
           &Date::Unit ## _set)

      DECLARE(day);
      DECLARE(hour);
      DECLARE(microsecond);
      DECLARE(minute);
      DECLARE(month);
      DECLARE(second);
      DECLARE(us);
      DECLARE(year);

#undef DECLARE

      bind(SYMBOL(LT), (bool (Date::*)(rDate rhs) const)&Date::operator <);

      BIND(EQ_EQ, operator ==);
      BIND(PLUS, operator +);
      BIND(asFloat, as_float);
      BIND(asString, as_string);
      BINDG(epoch);
      BINDG(now);
      bind_variadic(SYMBOL(init), &Date::init);
    }

    void
    Date::init(const objects_type& args)
    {
      check_arg_count(args.size(), 0, 1);

      if (args.empty())
        time_ = boost::posix_time::microsec_clock::local_time();
      else
      {
        const std::string& s = from_urbi<std::string>(args[0]);
        try
        {
          time_ = boost::posix_time::time_from_string(s);
        }
        catch (const boost::bad_lexical_cast&)
        {
          FRAISE("cannot convert to date: %s", s);
        }
      }
    }

    /*-------------.
    | Comparison.  |
    `-------------*/

    bool
    Date::operator ==(rDate rhs) const
    {
      return time_ == rhs->time_;
    }

    bool
    Date::operator <(rDate rhs) const
    {
      return time_ < rhs->time_;
    }

    /*-------------.
    | Operations.  |
    `-------------*/

    Date&
    Date::operator += (const duration_type& rhs)
    {
      time_ += rhs;
      return *this;
    }

    rDate
    Date::operator + (const duration_type& rhs) const
    {
      rDate res = new Date(time_);
      *res += rhs;
      return res;
    }

    Date&
    Date::operator -= (const duration_type& rhs)
    {
      time_ -= rhs;
      return *this;
    }

    rDate
    Date::operator - (const duration_type& rhs) const
    {
      rDate res = new Date(time_);
      *res -= rhs;
      return res;
    }

    rDuration
    Date::operator - (rDate rhs) const
    {
      return new Duration(time_ - rhs->time_);
    }

    /*----------------.
    | Modifications.  |
    `----------------*/

#define TIME_GETTER(Unit)                        \
  Date::Unit ## _type Date::Unit ## _get() const \
  {                                              \
    return time_.time_of_day().Unit ## s();      \
  }                                              \

#define TIME_SETTER(Unit)                               \
  void Date::Unit ## _set(Date::Unit ## _type value)    \
  {                                                     \
    Date::duration_type td = time_.time_of_day();       \
    td -= boost::posix_time::Unit ## s(td.Unit ## s()); \
    td += boost::posix_time::Unit ## s(value);          \
    time_ = Date::value_type(time_.date(), td);         \
  }                                                     \

#define TIME_MODIFIERS(Unit) \
  TIME_GETTER(Unit)          \
  TIME_SETTER(Unit)          \

  TIME_MODIFIERS(hour)
  TIME_MODIFIERS(minute)
  TIME_MODIFIERS(second)

#undef TIME_GETTER
#undef TIME_SETTER
#undef TIME_MODIFIERS

#define MILLION 1000000L

  Date::us_type Date::us_get() const
  {
    return time_.time_of_day().total_microseconds();
  }

  void Date::us_set(Date::us_type value)
  {
    Date::duration_type td = time_.time_of_day();
    td -= boost::posix_time::microseconds(td.total_microseconds());
    td += boost::posix_time::microseconds(value);
    time_ = Date::value_type(time_.date(), td);
  }

  Date::microsecond_type Date::microsecond_get() const
  {
    return us_get() % MILLION;
  }

  void Date::microsecond_set(Date::microsecond_type value)
  {
    Date::duration_type td = time_.time_of_day();
    td -= boost::posix_time::microseconds(td.total_microseconds() % MILLION);
    td += boost::posix_time::microseconds(value);
    time_ = Date::value_type(time_.date(), td);
  }

#define DATE_GETTER(Unit)                        \
  Date::Unit ## _type Date::Unit ## _get() const \
  {                                              \
    return time_.date().Unit();                  \
  }                                              \

#define DATE_SETTER(Unit, Y, M, D)                            \
  void Date::Unit ## _set(Date::Unit ## _type Unit ## _given) \
  {                                                           \
    try                                                       \
    {                                                         \
      time_ = Date::value_type(Date::date_type(Y, M, D),      \
                               time_.time_of_day());          \
    }                                                         \
    catch(std::exception& e)                                  \
    {                                                         \
      runner::raise_primitive_error(e.what());                \
    }                                                         \
  }                                                           \

#define DATE_MODIFIERS(Unit, Y, M, D) \
  DATE_GETTER(Unit)                   \
  DATE_SETTER(Unit, Y, M, D)          \

  DATE_MODIFIERS(year,  year_given, time_.date().month(), time_.date().day())
  DATE_MODIFIERS(month, time_.date().year(), month_given, time_.date().day())
  DATE_MODIFIERS(day,   time_.date().year(), time_.date().month(), day_given)

#undef DATE_GETTER
#undef DATE_SETTER
#undef DATE_MODIFIERS

    /*--------------.
    | Conversions.  |
    `--------------*/

    Date::value_type
    Date::as_boost() const
    {
      return time_;
    }

    std::string
    Date::as_string() const
    {
      Date::duration_type td = time_.time_of_day();
      return
        libport::format("%04s-%02s-%02s %02s:%02s:%02s.%06s",
                        time_.date().year(),
                        // Otherwise we get "Jan", "Feb", etc.
                        int(time_.date().month()),
                        time_.date().day(),
                        td.hours(),
                        td.minutes(),
                        td.seconds(),
                        td.total_microseconds() % MILLION);
    }

    Date::duration_type
    Date::as_float() const
    {
      return time_ - epoch();
    }

    /*--------.
    | Dates.  |
    `--------*/

    rDate
    Date::now()
    {
      return new Date();
    }

    Date::value_type
    Date::epoch()
    {
      value_type abs(boost::gregorian::date(1970, 1, 1));
      return abs + local_time_offset();
    }

    Date::duration_type
    Date::local_time_offset()
    {
      // FIXME: Crappy way to find the local time offset, but AFAICT,
      // Boost provides no way to get the current timezone :-(
      using namespace boost::posix_time;
      static Date::duration_type offset =
        seconds((microsec_clock::local_time()
                 - microsec_clock::universal_time()).total_seconds());
      return offset;
    }
  }
}

ext: cc

max_stars_repo_name: jcbaillie/urbi

max_issues_repo_name: jcbaillie/urbi

max_forks_repo_name: jcbaillie/urbi