text:
/* CirKit: A circuit toolkit
 * Copyright (C) 2009-2015  University of Bremen
 * Copyright (C) 2015-2017  EPFL
 *
 * Permission is hereby granted, free of charge, to any person
 * obtaining a copy of this software and associated documentation
 * files (the "Software"), to deal in the Software without
 * restriction, including without limitation the rights to use,
 * copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following
 * conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
 * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
 * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
 * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 * OTHER DEALINGS IN THE SOFTWARE.
 */

#include "mig_rewrite.hpp"

#include <boost/graph/topological_sort.hpp>

#include <core/utils/timer.hpp>
#include <classical/mig/mig_utils.hpp>

namespace cirkit
{

/******************************************************************************
 * Types                                                                      *
 ******************************************************************************/

/******************************************************************************
 * Private functions                                                          *
 ******************************************************************************/

std::map<mig_node, mig_function> init_visited_table( const mig_graph& mig, mig_graph& mig_new )
{
  std::map<mig_node, mig_function> old_to_new;

  old_to_new[0] = mig_get_constant( mig_new, false );
  for ( const auto& pi : mig_info( mig ).inputs )
  {
    old_to_new[pi] = mig_create_pi( mig_new, mig_info( mig ).node_names.at( pi ) );
  }

  return old_to_new;
}

mig_function mig_rewrite_top_down_rec( const mig_graph& mig, mig_node node,
                                       mig_graph& mig_new,
                                       const mig_maj_rewrite_func_t& on_maj,
                                       std::map<mig_node, mig_function>& old_to_new )
{
  /* visited */
  const auto it = old_to_new.find( node );
  if ( it != old_to_new.end() )
  {
    return it->second;
  }

  const auto c = get_children( mig, node );
  const auto f = on_maj( mig_new,
                         mig_rewrite_top_down_rec( mig, c[0].node, mig_new, on_maj, old_to_new ) ^ c[0].complemented,
                         mig_rewrite_top_down_rec( mig, c[1].node, mig_new, on_maj, old_to_new ) ^ c[1].complemented,
                         mig_rewrite_top_down_rec( mig, c[2].node, mig_new, on_maj, old_to_new ) ^ c[2].complemented );

  old_to_new.insert( {node, f} );
  return f;
}

/******************************************************************************
 * Public functions                                                           *
 ******************************************************************************/

mig_function mig_rewrite_default_maj( mig_graph& mig_new, const mig_function& a, const mig_function& b, const mig_function& c )
{
  return mig_create_maj( mig_new, a, b, c );
}

mig_graph mig_rewrite_top_down( const mig_graph& mig,
                                const mig_maj_rewrite_func_t& on_maj,
                                const properties::ptr& settings,
                                const properties::ptr& statistics )
{
  /* settings */
  const auto prefill = get( settings, "prefill", prefill_func_t() );

  /* statistics */
  properties_timer t( statistics );

  mig_graph mig_new;
  mig_initialize( mig_new, mig_info( mig ).model_name );

  /* create constant and PIs */
  auto old_to_new = init_visited_table( mig, mig_new );

  /* prefill */
  if ( prefill )
  {
    prefill( mig_new, old_to_new );
  }

  /* map nodes */
  for ( const auto& po : mig_info( mig ).outputs )
  {
    mig_create_po( mig_new, mig_rewrite_top_down_rec( mig, po.first.node, mig_new, on_maj, old_to_new ) ^ po.first.complemented, po.second );
  }

  return mig_new;
}

mig_graph mig_rewrite_bottom_up( const mig_graph& mig,
                                 const mig_maj_rewrite_func_t& on_maj,
                                 const properties::ptr& settings,
                                 const properties::ptr& statistics )
{
  /* statistics */
  properties_timer t( statistics );

  mig_graph mig_new;
  mig_initialize( mig_new, mig_info( mig ).model_name );

  /* create constant and PIs */
  auto old_to_new = init_visited_table( mig, mig_new );

  /* map nodes */
  std::vector<mig_node> top( num_vertices( mig ) );
  boost::topological_sort( mig, top.begin() );
  for ( auto node : top )
  {
    if ( out_degree( node, mig ) == 0u ) { continue; }

    const auto c = get_children( mig, node );
    old_to_new[node] = on_maj( mig_new,
                               old_to_new[c[0].node] ^ c[0].complemented,
                               old_to_new[c[1].node] ^ c[1].complemented,
                               old_to_new[c[2].node] ^ c[2].complemented );
  }

  for ( const auto& po : mig_info( mig ).outputs )
  {
    mig_create_po( mig_new, old_to_new[po.first.node] ^ po.first.complemented, po.second );
  }

  return mig_new;
}

}

// Local Variables:
// c-basic-offset: 2
// eval: (c-set-offset 'substatement-open 0)
// eval: (c-set-offset 'innamespace 0)
// End:

max_stars_repo_name: eletesta/cirkit

max_issues_repo_name: eletesta/cirkit

max_forks_repo_name: eletesta/cirkit


text:
//
// ExpansionHunter
// Copyright 2016-2021 Illumina, Inc.
// All rights reserved.
//
// Author: Egor Dolzhenko <edolzhenko@illumina.com>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
//

#include "locus/LocusAnalyzer.hh"

#include <boost/smart_ptr/make_unique.hpp>

#include "locus/LocusAligner.hh"
#include "locus/RepeatAnalyzer.hh"
#include "locus/SmallVariantAnalyzer.hh"

using boost::make_unique;
using boost::optional;
using graphtools::AlignmentWriter;
using graphtools::GraphAlignment;
using graphtools::NodeId;
using std::string;
using std::vector;

namespace ehunter
{
namespace locus
{

LocusAnalyzer::LocusAnalyzer(LocusSpecification locusSpec, const HeuristicParameters& params, AlignWriterPtr writer)
    : locusSpec_(std::move(locusSpec))
    , aligner_(locusSpec_.locusId(), &locusSpec_.regionGraph(), params, std::move(writer))
    , statsCalc_(locusSpec_.typeOfChromLocusLocatedOn(), locusSpec_.regionGraph())
{
    for (const auto& variantSpec : locusSpec_.variantSpecs())
    {
        if (variantSpec.classification().type == VariantType::kRepeat)
        {
            const auto& graph = locusSpec_.regionGraph();
            const int repeatNodeId = static_cast<int>(variantSpec.nodes().front());
            const auto& motif = graph.nodeSeq(repeatNodeId);

            if (variantSpec.classification().subtype == VariantSubtype::kRareRepeat)
            {
                if (irrPairFinder())
                {
                    const string message
                        = "Region " + locusSpec_.locusId() + " must not have more than one rare repeat";
                    throw std::logic_error(message);
                }
                addIrrPairFinder(motif);
            }

            addRepeatAnalyzer(variantSpec.id(), repeatNodeId);
        }
        else if (variantSpec.classification().type == VariantType::kSmallVariant)
        {
            addSmallVariantAnalyzer(
                variantSpec.id(), variantSpec.classification().subtype, variantSpec.nodes(),
                variantSpec.optionalRefNode());
        }
        else
        {
            std::stringstream encoding;
            encoding << variantSpec.classification().type << "/" << variantSpec.classification().subtype;
            throw std::logic_error("Missing logic to create an analyzer for " + encoding.str());
        }
    }
}

void LocusAnalyzer::processMates(
    Read& read, Read* mate, RegionType regionType, graphtools::AlignerSelector& alignerSelector)
{
    if (regionType == RegionType::kTarget)
    {
        processOntargetMates(read, mate, alignerSelector);
    }
    else if (mate)
    {
        processOfftargetMates(read, *mate);
    }
}

void LocusAnalyzer::processOntargetMates(Read& read, Read* mate, graphtools::AlignerSelector& alignerSelector)
{
    auto alignedPair = aligner_.align(read, mate, alignerSelector);

    const bool neitherMateAligned = !alignedPair.first && !alignedPair.second;
    const bool bothMatesAligned = alignedPair.first && alignedPair.second;

    if (irrPairFinder_ && neitherMateAligned && mate)
    {
        processOfftargetMates(read, *mate);
        return;
    }

    if (bothMatesAligned)
    {
        statsCalc_.inspect(*alignedPair.first, *alignedPair.second);
        runVariantAnalysis(read, *alignedPair.first, *mate, *alignedPair.second);
    }
    else
    {
        if (alignedPair.first) {
            statsCalc_.inspectRead(*alignedPair.first);
        }
        if (alignedPair.second) {
            statsCalc_.inspectRead(*alignedPair.second);
        }
    }
}

void LocusAnalyzer::processOfftargetMates(const Read& read, const Read& mate)
{
    if (!irrPairFinder_)
    {
        const string message = "Locus " + locusSpec_.locusId() + " is not supposed to have offtarget read pairs";
        throw std::logic_error(message);
    }

    if (irrPairFinder_->check(read.sequence(), mate.sequence()))
    {
        int numAnalyzersFound = 0;
        for (auto& variantAnalyzer : variantAnalyzers_)
        {
            auto repeatAnalyzer = dynamic_cast<RepeatAnalyzer*>(variantAnalyzer.get());
            if (repeatAnalyzer != nullptr && repeatAnalyzer->repeatUnit() == irrPairFinder_->targetMotif())
            {
                numAnalyzersFound++;
                repeatAnalyzer->addInrepeatReadPair();
            }
        }

        if (numAnalyzersFound != 1)
        {
            const string message = "Locus " + locusSpec_.locusId() + " must have exactly one rare motif";
            throw std::logic_error(message);
        }
    }
}

LocusFindings LocusAnalyzer::analyze(Sex sampleSex, boost::optional<double> genomeWideDepth)
{
    LocusFindings locusFindings(statsCalc_.estimate(sampleSex));
    if (genomeWideDepth && locusSpec_.requiresGenomeWideDepth())
    {
        locusFindings.stats.setDepth(*genomeWideDepth);
    }

    for (auto& variantAnalyzer : variantAnalyzers_)
    {
        std::unique_ptr<VariantFindings> variantFindingsPtr = variantAnalyzer->analyze(locusFindings.stats);
        const string& variantId = variantAnalyzer->variantId();
        locusFindings.findingsForEachVariant.emplace(variantId, std::move(variantFindingsPtr));
    }

    return locusFindings;
}

void LocusAnalyzer::addIrrPairFinder(std::string motif) { irrPairFinder_ = IrrPairFinder(std::move(motif)); }

void LocusAnalyzer::addRepeatAnalyzer(std::string variantId, graphtools::NodeId nodeId)
{
    variantAnalyzers_.emplace_back(make_unique<RepeatAnalyzer>(
        std::move(variantId), locusSpec_.regionGraph(), nodeId, locusSpec_.genotyperParameters()));
}

void LocusAnalyzer::addSmallVariantAnalyzer(
    string variantId, VariantSubtype subtype, vector<NodeId> nodes, optional<NodeId> refNode)
{
    variantAnalyzers_.emplace_back(make_unique<SmallVariantAnalyzer>(
        std::move(variantId), subtype, locusSpec_.regionGraph(), std::move(nodes), refNode,
        locusSpec_.genotyperParameters()));
}

void LocusAnalyzer::runVariantAnalysis(
    const Read& read, const LocusAnalyzer::Align& readAlign, const Read& mate, const LocusAnalyzer::Align& mateAlign)
{
    for (auto& analyzer : variantAnalyzers_)
    {
        analyzer->processMates(read, readAlign, mate, mateAlign);
    }
}

}
}

ext: cpp


text:
#include "HpsValidator.h"
#include "HttpRecConfig.h"
#include "HpsLogHelper.h"

#include <vector>
#include <algorithm>
#include <boost/algorithm/string.hpp>
#include <boost/regex.hpp>

using std::vector;

bool CHpsValidator::IsNeedToValidate(const string &strUrlPath)
{
    HP_XLOG(XLOG_DEBUG, "CHpsValidator::%s urlPath[%s]\n", __FUNCTION__, strUrlPath.c_str());
    const vector<string> vecWhiteValidateList = CHttpRecConfig::GetInstance()->GetWhiteValidateList();
    return !std::binary_search(vecWhiteValidateList.begin(), vecWhiteValidateList.end(), strUrlPath);
}

bool CHpsValidator::ValidateHttpParams(const char *pStrKeyValues)
{
    HP_XLOG(XLOG_DEBUG, "CHpsValidator::%s StrKeyValues[%s]\n", __FUNCTION__, pStrKeyValues);
    if (NULL != pStrKeyValues)
    {
        vector<string> vecKeyValue;
        boost::algorithm::split(vecKeyValue, pStrKeyValues, boost::algorithm::is_any_of("&"), boost::algorithm::token_compress_on);
        for (vector<string>::iterator iter = vecKeyValue.begin(); iter != vecKeyValue.end(); ++iter)
        {
            const char *pEqualitySign = strstr(iter->c_str(), "=");
            if (NULL != pEqualitySign)
            {
                if (!ValidateHttpParamValue(pEqualitySign + 1))
                {
                    return false;
                }
            }
        }
    }

    return true;
}

bool CHpsValidator::ValidateHttpParamValue(const char *pStrValue)
{
    HP_XLOG(XLOG_DEBUG, "CHpsValidator::%s Value[%s]\n", __FUNCTION__, pStrValue);
    //Validate for injection attack
    const static boost::regex reg("\\b(and|or)\\b.{1,6}?(=|>|<|\\bin\\b|\\blike\\b)|\\/\\*.+?\\*\\/|<\\s*script\\b|\\bEXEC\\b|UNION.+?Select|Update.+?SET|Insert\\s+INTO.+?VALUES|(Select|Delete).+?FROM|(Create|Alter|Drop|TRUNCATE)\\s+(TABLE|DATABASE)");
    if (NULL != pStrValue)
    {
        if (boost::regex_match(pStrValue, reg))
        {
            return false;
        }
    }

    return true;
}

max_stars_repo_name: shrewdlin/BPE

max_issues_repo_name: shrewdlin/BPE

max_forks_repo_name: shrewdlin/BPE


text:
#include <boost/di.hpp>
namespace di = boost::di;

#include <string>
using namespace std;

// Interface
class IFuel
{
    public:
    virtual ~IFuel() noexcept = default;
    virtual string FillUp() = 0;
    virtual string Status() = 0;
};

// Petrol Fuel Tank implementation of IFuel
class FuelTank : public IFuel
{
    private:
    bool isFull = false;
    public:
    string FillUp() override { this->isFull = true; return "Filling up!";  }
    string Status() override { return (this->isFull)? "Full" : "Empty"; }
};

// A car that can have diferent types of fuel storage technologie!
class Car
{
    private:
    IFuel &fuel;

    public:
    Car (IFuel &f):fuel(f){}

    void Run()
    {
        printf("%s\n", fuel.Status().c_str());
        printf("%s\n", fuel.FillUp().c_str());
        printf("%s", fuel.Status().c_str());
    }
};

int main()
{
    const auto carFactory = di::make_injector
            (di::bind<IFuel>().to<FuelTank>());

    auto car = carFactory.create<Car>();

    car.Run();

    return 0;
}

max_stars_repo_name: joserossini/cpp-playground

max_issues_repo_name: joserossini/cpp-playground

max_forks_repo_name: joserossini/cpp-playground


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)

#include <string>
#include <vector>
#include <boost/function.hpp>
#include <boost/bind.hpp>
#include <boost/math/distributions/chi_squared.hpp>
#include "genfile/Error.hpp"
#include "metro/likelihood/Multinomial.hpp"
#include "components/SNPSummaryComponent/SNPHWE.hpp"
#include "components/SNPSummaryComponent/HWEComputation.hpp"
#include "metro/likelihood/Multinomial.hpp"
#include "metro/likelihood/ProductOfMultinomials.hpp"
#include "metro/FishersExactTest.hpp"

// #define DEBUG_HWE_COMPUTATION 1

namespace stats {
	HWEComputation::HWEComputation():
		m_threshhold( 0.9 ),
		m_chi_squared_1df( 1.0 ),
		m_chi_squared_2df( 2.0 )
	{}

	void HWEComputation::operator()(
		VariantIdentifyingData const& snp,
		Genotypes const& genotypes,
		Ploidy const& ploidy,
		genfile::VariantDataReader&,
		ResultCallback callback
	) {
		genfile::Chromosome const& chromosome = snp.get_position().chromosome() ;
		if( snp.number_of_alleles() == 2 ) {
			if( chromosome.is_sex_determining() ) {
				X_chromosome_test( snp, genotypes, ploidy, callback ) ;
			} else {
				autosomal_test( snp, genotypes, callback ) ;
			}
		}
	}

	std::string HWEComputation::get_summary( std::string const& prefix, std::size_t column_width ) const { return prefix + "HWEComputation" ; }

	void HWEComputation::autosomal_test( VariantIdentifyingData const& snp, Genotypes const& genotypes, ResultCallback callback ) {
		Eigen::VectorXd genotype_counts = Eigen::VectorXd::Zero( 3 ) ;
		for( int g = 0; g < 3; ++g ) {
			genotype_counts( g ) = std::floor( genotypes.col(g).sum() + 0.5 ) ;
		}
		autosomal_exact_test( snp, genotype_counts, callback ) ;
		autosomal_multinomial_test( snp, genotype_counts, callback ) ;
	}

	void HWEComputation::autosomal_exact_test( VariantIdentifyingData const& snp, Eigen::VectorXd const& genotype_counts, ResultCallback callback ) {
		if( genotype_counts.array().maxCoeff() > 0.5 ) {
			double HWE_pvalue = SNPHWE( genotype_counts(1), genotype_counts(0), genotype_counts(2) ) ;
			callback( "HW_exact_p_value", HWE_pvalue ) ;
		}
		else {
			callback( "HW_exact_p_value", genfile::MissingValue() ) ;
		}
	}

	void HWEComputation::autosomal_multinomial_test( VariantIdentifyingData const& snp, Eigen::VectorXd const& genotype_counts, ResultCallback callback ) {
		metro::likelihood::Multinomial< double, Eigen::VectorXd, Eigen::MatrixXd > hw_model( genotype_counts ) ;
		{
			// compute MLE under assumption of hardy-weinberg.
			double p = 2.0 * genotype_counts( 2 ) + genotype_counts( 1 ) ;
			p /= 2.0 * genotype_counts.sum() ;
			Eigen::VectorXd a = Eigen::VectorXd::Zero( 3 ) ;
			a( 0 ) = ( 1 - p ) * ( 1 - p ) ;
			a( 1 ) = 2.0 * p * ( 1 - p ) ;
			a( 2 ) = p * p ;
			hw_model.evaluate_at( a ) ;
		}

		metro::likelihood::Multinomial< double, Eigen::VectorXd, Eigen::MatrixXd > full_model( genotype_counts ) ;
		full_model.evaluate_at( full_model.get_MLE() ) ;

#if DEBUG_HWE_COMPUTATION
		std::cerr << std::fixed << std::setprecision( 5 );
		std::cerr << "table = " << genotype_counts.transpose() << "...\n" ;
		std::cerr << std::resetiosflags( std::ios::floatfield ) ;
		std::cerr << "hw_model.MLE = " << hw_model.get_parameters().transpose() << ", loglikelihood = " << hw_model.get_value_of_function() << "...\n" ;
		std::cerr << "full_model.MLE = " << full_model.get_parameters().transpose() << ", loglikelihood = " << full_model.get_value_of_function() << "...\n" ;
#endif

		double likelihood_ratio_statistic = 2.0 * ( full_model.get_value_of_function() - hw_model.get_value_of_function() ) ;
		double p_value = std::numeric_limits< double >::quiet_NaN() ;
		if( likelihood_ratio_statistic != likelihood_ratio_statistic || likelihood_ratio_statistic < 0.0 ) {
			likelihood_ratio_statistic = std::numeric_limits< double >::quiet_NaN() ;
		}
		else {
			p_value = boost::math::cdf(
				boost::math::complement(
					m_chi_squared_1df,
					likelihood_ratio_statistic
				)
			) ;
		}

		callback( "HW_lrt_p_value", p_value ) ;
	}

	void HWEComputation::X_chromosome_test( VariantIdentifyingData const& snp, Genotypes const& genotypes, Ploidy const& ploidy, ResultCallback callback ) {
		// We look at three models and perform two LR tests.
		// model1: full model, males and females may have different frequencies and no assumption of HW in females.  (3 parameters)
		// model2: HWE holds in females, but males and females may have different frequencies. (2 parameters)
		// model3: HWE holds in females and males and females have the same frequency. (1 parameter)
		//
		// test1: test that males and females have the same allele frequency
		// test2: test HWE in females.
		//
		// Note: males will be called as 0/1 on the X and Y chromosomes.
		Eigen::MatrixXd genotype_counts = Eigen::MatrixXd::Zero( 2, 3 ) ; // first row is males, second row is females.  Last column will be zero for males.
		Eigen::MatrixXd allele_counts = Eigen::MatrixXd::Zero( 2, 2 ) ; // first row is males, second row is females.

		typedef Eigen::VectorXd Vector ;

		int const HAPLOID = 0 ;
		int const DIPLOID = 1 ;

		for( int i = 0; i < genotypes.rows(); ++i ) {
			if( ploidy(i) == 1 || ploidy(i) == 2 ) {
				int const index = ploidy(i) - 1 ;
				for( int g = 0; g < 3; ++g ) {
					if( genotypes( i, g ) > m_threshhold ) {
						++genotype_counts( index, g ) ;
						break ;
					}
				}
			}
		}
		for( int g = 0; g < 2; ++g ) {
			allele_counts( 0, g ) = genotype_counts( 0, g ) ;
			allele_counts( 1, g ) = genotype_counts( 1, 1 ) + 2.0 * genotype_counts( 1, 2.0 * g ) ;
		}

		if( genotype_counts.maxCoeff() == 0 ) {
				callback( "HW_females_exact_pvalue", genfile::MissingValue() ) ;
				callback( "HW_females_lrt_pvalue", genfile::MissingValue()) ;
				callback( "male_female_exact_pvalue", genfile::MissingValue() ) ;
				callback( "male_female_lrt_pvalue", genfile::MissingValue() ) ;
				callback( "male_female_and_HW_lrt_pvalue", genfile::MissingValue() ) ;

		} else {
			typedef metro::likelihood::Multinomial< double, Eigen::VectorXd, Eigen::MatrixXd > Multinomial ;
			typedef metro::likelihood::ProductOfMultinomials< double, Eigen::VectorXd, Eigen::MatrixXd > ProductOfIndependentMultinomials ;
			// In model 1 each genotype is allowed to have its own frequency.
			// Morever males and females may have different frequencies
			ProductOfIndependentMultinomials full_model( genotype_counts ) ;
			full_model.evaluate_at( full_model.get_MLE() ) ;

			// In model2 alleles are independent (HWE) in females, but males and females may differ.
			ProductOfIndependentMultinomials model2( genotype_counts ) ;
			{
				double const p_females = ( 2 * genotype_counts( DIPLOID, 0 ) + genotype_counts( DIPLOID, 1 ) ) / (2 * genotype_counts.row( DIPLOID ).sum() ) ;
				double const p_males = genotype_counts( HAPLOID, 0 ) / genotype_counts.row( HAPLOID ).sum() ;
				Vector params( 6 ) ;
				params( 0 ) = p_males ;
				params( 1 ) = 1-p_males ;
				params( 2 ) = 0 ;
				params( 3 ) = p_females * p_females ;
				params( 4 ) = 2 * p_females * (1-p_females) ;
				params( 5 ) = (1-p_females) * (1-p_females) ;
				model2.evaluate_at( params ) ;
			}

			// In model3, the NULL model, alleles are independent (HWE) and males and females must agree.
			ProductOfIndependentMultinomials model3( genotype_counts ) ;
			{
				double const p = ( 2 * genotype_counts( DIPLOID, 0 ) + genotype_counts( HAPLOID, 0 ) + genotype_counts( DIPLOID, 1 ) )
					/ ( 2 * genotype_counts.row( DIPLOID ).sum() + genotype_counts.row( HAPLOID ).sum() ) ;

				Vector params( 6 ) ;
				params( 0 ) = p ;
				params( 1 ) = (1-p) ;
				params( 2 ) = 0 ;
				params( 3 ) = p * p ;
				params( 4 ) = 2 * p * (1-p) ;
				params( 5 ) = (1-p) * (1-p) ;
				model3.evaluate_at( params ) ;
			}

#if DEBUG_HWE_COMPUTATION
			std::cerr << "Genotype counts:\n" << genotype_counts << "\n" ;
			std::cerr << "Allele counts:\n" << allele_counts << "\n" ;
			std::cerr << "Model 1 params: " << full_model.get_parameters().transpose() << ".\n" ;
			std::cerr << "Model 2 params: " << model2.get_parameters().transpose() << ".\n" ;
			std::cerr << "Model 3 params: " << model3.get_parameters().transpose() << ".\n" ;
#endif
			double const NaN = std::numeric_limits< double >::quiet_NaN() ;

			using boost::math::cdf ;
			using boost::math::complement ;

			if( genotype_counts.row( DIPLOID ).array().maxCoeff() > 0.5 ) {
				double exact_HWE_pvalue = SNPHWE( genotype_counts( DIPLOID, 1 ), genotype_counts( DIPLOID, 0 ), genotype_counts( DIPLOID, 2 ) ) ;
				callback( "HW_females_exact_pvalue", exact_HWE_pvalue ) ;
			} else {
				callback( "HW_females_exact_pvalue", genfile::MissingValue() ) ;
			}

			double const lr_stat_12 = 2.0 * ( full_model.get_value_of_function() - model2.get_value_of_function() ) ;
			double p_value_12 = NaN ;
			if( lr_stat_12 == lr_stat_12 && lr_stat_12 > 0 && lr_stat_12 != std::numeric_limits< double >::infinity() ) {
				p_value_12 = cdf( complement( m_chi_squared_1df, lr_stat_12 ) ) ;
				callback( "HW_females_lrt_pvalue", p_value_12 ) ;
			} else {
				callback( "HW_females_lrt_pvalue", genfile::MissingValue()) ;
			}

			// Also get exact male/female p-value
			{
				Eigen::Matrix2d A = allele_counts ;
				A(0,0) = std::floor( A(0,0) + 0.5 ) ;
				A(0,1) = std::floor( A(0,1) + 0.5 ) ;
				A(1,0) = std::floor( A(1,0) + 0.5 ) ;
				A(1,1) = std::floor( A(1,1) + 0.5 ) ;
				double const male_female_pvalue = metro::FishersExactTest( A ).get_pvalue( metro::FishersExactTest::eTwoSided ) ;
				if( male_female_pvalue == male_female_pvalue ) {
					callback( "male_female_exact_pvalue", male_female_pvalue ) ;
				} else {
					callback( "male_female_exact_pvalue", genfile::MissingValue() ) ;
				}
			}

			double const lr_stat_23 = 2.0 * ( model2.get_value_of_function() - model3.get_value_of_function() ) ;
			double p_value_23 = NaN ;
			if( lr_stat_23 == lr_stat_23 && lr_stat_23 > 0 && lr_stat_23 != std::numeric_limits< double >::infinity() ) {
				p_value_23 = cdf( complement( m_chi_squared_1df, lr_stat_23 ) ) ;
				callback( "male_female_lrt_pvalue", p_value_23 ) ;
			} else {
				callback( "male_female_lrt_pvalue", genfile::MissingValue() ) ;
			}

			double const lr_stat_13 = 2.0 * ( full_model.get_value_of_function() - model3.get_value_of_function() ) ;
			double p_value_13 = NaN ;
			if( lr_stat_13 == lr_stat_13 && lr_stat_13 > 0 && lr_stat_13 != std::numeric_limits< double >::infinity() ) {
				p_value_13 = cdf( complement( m_chi_squared_2df, lr_stat_13 ) ) ;
				callback( "male_female_and_HW_lrt_pvalue", p_value_13 ) ;
			} else {
				callback( "male_female_and_HW_lrt_pvalue", genfile::MissingValue() ) ;
			}
		}
	}
}

max_stars_repo_name: gavinband/qctool

max_issues_repo_name: gavinband/qctool

max_forks_repo_name: gavinband/qctool


text:
// Boost.Geometry (aka GGL, Generic Geometry Library)
// Unit Test

// Copyright (c) 2007-2012 Barend Gehrels, Amsterdam, the Netherlands.
// Copyright (c) 2008-2012 Bruno Lalande, Paris, France.
// Copyright (c) 2009-2012 Mateusz Loskot, London, UK.

// Parts of Boost.Geometry are redesigned from Geodan's Geographic Library
// (geolib/GGL), copyright (c) 1995-2010 Geodan, Amsterdam, the Netherlands.

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

#include <algorithm>
#include <iterator>
#include <sstream>
#include <string>

#include <geometry_test_common.hpp>

#include <boost/geometry/iterators/closing_iterator.hpp>

#include <boost/geometry/core/coordinate_type.hpp>
#include <boost/geometry/io/wkt/read.hpp>
#include <boost/geometry/geometries/geometries.hpp>
#include <boost/geometry/geometries/point_xy.hpp>

// The closing iterator should also work on normal std:: containers
void test_non_geometry()
{
    std::vector<int> v;
    v.push_back(1);
    v.push_back(2);
    v.push_back(3);

    typedef bg::closing_iterator
        <
            std::vector<int> const
        > closing_iterator;

    closing_iterator it(v);
    closing_iterator end(v, true);

    std::ostringstream out;
    for (; it != end; ++it)
    {
        out << *it;
    }
    BOOST_CHECK_EQUAL(out.str(), "1231");
}

template <typename Geometry>
void test_geometry(std::string const& wkt)
{
    Geometry geometry;
    bg::read_wkt(wkt, geometry);
    typedef bg::closing_iterator<Geometry const> closing_iterator;

    // 1. Test normal behaviour
    {
        closing_iterator it(geometry);
        closing_iterator end(geometry, true);

        std::ostringstream out;
        for (; it != end; ++it)
        {
            out << " " << bg::get<0>(*it) << bg::get<1>(*it);
        }
        BOOST_CHECK_EQUAL(out.str(), " 11 14 44 41 11");

        // Check compilations, it is (since Oct 2010) random access
        it--;
        --it;
        it += 2;
        it -= 2;
    }

    // 2: check copy behaviour
    {
        typedef typename boost::range_iterator<Geometry const>::type normal_iterator;
        Geometry copy;

        std::copy<closing_iterator>(
            closing_iterator(geometry),
            closing_iterator(geometry, true),
            std::back_inserter(copy));

        std::ostringstream out;
        for (normal_iterator cit = boost::begin(copy); cit != boost::end(copy); ++cit)
        {
                out << " " << bg::get<0>(*cit) << bg::get<1>(*cit);
        }
        BOOST_CHECK_EQUAL(out.str(), " 11 14 44 41 11");
    }
}

template <typename P>
void test_all()
{
    test_non_geometry();
    test_geometry<bg::model::ring<P> >("POLYGON((1 1,1 4,4 4,4 1))");
}

int test_main(int, char* [])
{
    test_all<bg::model::d2::point_xy<double> >();

    return 0;
}

max_stars_repo_name: randolphwong/mcsema

max_issues_repo_name: randolphwong/mcsema

max_forks_repo_name: randolphwong/mcsema


text:
// MIT License
//
// Copyright (c) 2018 Michal Siedlaczek
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.

//! \file
//! \author     Michal Siedlaczek
//! \copyright  MIT License

#include <iostream>

#include <CLI/CLI.hpp>
#include <boost/filesystem.hpp>
#include <spdlog/sinks/stdout_color_sinks.h>
#include <spdlog/spdlog.h>

#include <irkit/coding/hutucker.hpp>
#include <irkit/compacttable.hpp>
#include <irkit/index.hpp>
#include <irkit/index/source.hpp>
#include <irkit/io.hpp>
#include <irkit/lexicon.hpp>
#include <irkit/memoryview.hpp>
#include "cli.hpp"

using boost::filesystem::path;
using irk::index::document_t;
using std::uint32_t;

void build_shard_map(
    const std::vector<std::string>& shards,
    const irk::lexicon<irk::hutucker_codec<char>, irk::memory_view>& titles,
    const path& output_file)
{
    auto log = spdlog::stderr_color_mt("stderr");
    log->info("Building shard map");
    auto last_shard = shards.size() - 1;
    std::vector<uint32_t> map(titles.size(), last_shard);
    int mapped_documents(0);
    int missing_documents(0);
    int shard_id(0);
    for (const auto& shard_file : shards) {
        log->info("Mapping shard {0}", shard_id);
        for (const std::string& title : irk::io::lines(shard_file)) {
            if (auto id = titles.index_at(title); id.has_value()) {
                map[id.value()] = shard_id;
                mapped_documents += 1;
            } else {
                missing_documents += 1;
            }
        }
        shard_id += 1;
    }
    log->info(
        "Mapped {}; missing in index: {}; defaulted to last: {}",
        mapped_documents,
        missing_documents,
        titles.size() - mapped_documents);
    log->info("Writing shard map");
    auto table = irk::build_compact_table<uint32_t>(map);
    irk::io::dump(table, output_file);
}

int main(int argc, char** argv)
{
    std::string mapping_name;
    std::vector<std::string> shard_files;

    auto [app, args] = irk::cli::app(
        "Build mapping from document to shard",
        irk::cli::index_dir_opt{});
    app->add_option(
           "-n,--name",
           mapping_name,
           "Name of the mapping",
           false)
        ->required();
    app->add_option(
           "shards",
           shard_files,
           "Files describing shards:\t"
           "The files must contain a whitespace-delimited list of TREC IDs. "
           "The documents in the first file will be assigned to shard 0, "
           "the second file to shard 1, and so on. "
           "If a given document repeats, it will be overwritten. "
           "Documents that don't exist in the index will be ignored. "
           "Documents in the index not present in any input file will be "
           "appended to the last shard.",
           false)
        ->required();
    CLI11_PARSE(*app, argc, argv);

    path dir(args->index_dir);
    irk::inverted_index_view index(irtl::value(irk::Inverted_Index_Mapped_Source::from(dir)));
    build_shard_map(shard_files, index.titles(), dir / (mapping_name + ".shardmap"));
    return 0;
}

max_stars_repo_name: elshize/irkit

max_issues_repo_name: elshize/irkit

max_forks_repo_name: elshize/irkit


text:
/**
 *  @file
 *  @author     2012-2013 Stefan Radomski (stefan.radomski@cs.tu-darmstadt.de)
 *  @copyright  Simplified BSD
 *
 *  @cond
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the FreeBSD license as published by the FreeBSD
 *  project.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 *
 *  You should have received a copy of the FreeBSD license along with this
 *  program. If not, see <http://www.opensource.org/licenses/bsd-license>.
 *  @endcond
 */

#include "uscxml/Common.h"

#include "uscxml/plugins/ioprocessor/basichttp/BasicHTTPIOProcessor.h"
#include "uscxml/Message.h"
#include "uscxml/DOMUtils.h"
#include <iostream>
#include <event2/dns.h>
#include <event2/buffer.h>
#include <event2/keyvalq_struct.h>

#include <string.h>

#include <io/uri.hpp>
#include <glog/logging.h>
#include <boost/algorithm/string.hpp>

#ifdef _WIN32
#include <winsock2.h>
#include <windows.h>
#endif

#ifndef _WIN32
#include <netdb.h>
#include <arpa/inet.h>
#endif

#ifdef BUILD_AS_PLUGINS
#include <Pluma/Connector.hpp>
#endif

namespace uscxml {

#ifndef ioprocessor_scxml_EXPORTS
#	ifdef BUILD_AS_PLUGINS
PLUMA_CONNECTOR
bool pluginConnect(pluma::Host& host) {
	host.add( new BasicHTTPIOProcessorProvider() );
	return true;
}
#	endif
#endif

// see http://www.w3.org/TR/scxml/#BasicHTTPEventProcessor

BasicHTTPIOProcessor::BasicHTTPIOProcessor() {
}

BasicHTTPIOProcessor::~BasicHTTPIOProcessor() {
	HTTPServer* httpServer = HTTPServer::getInstance();
	httpServer->unregisterServlet(this);
}

boost::shared_ptr<IOProcessorImpl> BasicHTTPIOProcessor::create(InterpreterImpl* interpreter) {
	boost::shared_ptr<BasicHTTPIOProcessor> io = boost::shared_ptr<BasicHTTPIOProcessor>(new BasicHTTPIOProcessor());
	io->_interpreter = interpreter;

	// register at http server
	std::string path = interpreter->getName();
	int i = 2;
	while (!HTTPServer::registerServlet(path + "/basichttp", io.get())) {
		std::stringstream ss;
		ss << interpreter->getName() << i++;
		path = ss.str();
	}

	return io;
}

Data BasicHTTPIOProcessor::getDataModelVariables() {
	Data data;

	// we are not connected!
	if(_url.length() == 0)
		return data;

	data.compound["location"] = Data(_url, Data::VERBATIM);

	URL url(_url);
	data.compound["host"] = Data(url.host(), Data::VERBATIM);
	data.compound["port"] = Data(url.port(), Data::VERBATIM);
	data.compound["path"] = Data(url.path(), Data::VERBATIM);
	data.compound["scheme"] = Data(url.scheme(), Data::VERBATIM);

	std::vector<std::string> pathComps = url.pathComponents();
	std::vector<std::string>::const_iterator pathCompIter = pathComps.begin();
	while(pathCompIter != pathComps.end()) {
		data.compound["pathComponens"].array.push_back(Data(*pathCompIter, Data::VERBATIM));
		pathCompIter++;
	}

	return data;
}

bool BasicHTTPIOProcessor::httpRecvRequest(const HTTPServer::Request& req) {
	Event reqEvent = req;
	reqEvent.eventType = Event::EXTERNAL;

//	std::cout << req.raw << std::endl;

	/**
	 * If a single instance of the parameter '_scxmleventname' is present, the
	 * SCXML Processor must use its value as the name of the SCXML event that it
	 * raises.
	 */

    { // if we sent ourself an event it will end up here
        // this will call the const subscript operator
        if (req.data.at("content").hasKey("_scxmleventname")) {
            reqEvent.name = req.data.at("content").at("_scxmleventname").atom;
        }
        if (req.data.at("content").hasKey("content")) {
            reqEvent.content = req.data.at("content").at("content").atom;
        }
    }

    // if we used wget, it will end up here - unify?
	if (req.data.hasKey("content")) {
		const Data& data = req.data["content"];
		for(std::map<std::string, Data>::const_iterator compIter = data.compound.begin();
		        compIter!= data.compound.end(); compIter++) {
			if (compIter->first == "content") {
				reqEvent.content = compIter->second.atom;
			} else {
				reqEvent.data[compIter->first] = compIter->second;
			}
		}
	}

    if (req.data.hasKey("header")) {
        const Data& data = req.data["header"];
        for(std::map<std::string, Data>::const_iterator compIter = data.compound.begin();
            compIter!= data.compound.end(); compIter++) {
            if (compIter->first == "_scxmleventname") {
                reqEvent.name = compIter->second.atom;
            }
        }
    }

	// check whether we can parse it as XML
	if (reqEvent.content.length() > 0) {
		NameSpacingParser parser = NameSpacingParser::fromXML(reqEvent.content);
		if (!parser.errorsReported()) {
			reqEvent.dom = parser.getDocument();
		}
	}

	/// test532
	if (reqEvent.name.length() == 0)
		reqEvent.name = "http." + req.data.compound.at("type").atom;

	returnEvent(reqEvent);
	evhttp_send_reply(req.evhttpReq, 200, "OK", NULL);
	return true;
}

void BasicHTTPIOProcessor::send(const SendRequest& req) {

	if (req.target.length() == 0) {
		_interpreter->receiveInternal(Event("error.communication", Event::PLATFORM));
		return;
	}

	bool isLocal = false;
	std::string target;
	if (!boost::equals(req.target, _url)) {
		target = req.target;
	} else {
		isLocal = true;
		target = _url;
	}
	URL targetURL(target);
	std::stringstream kvps;
	std::string kvpSeperator;

	// event name
	if (req.name.size() > 0) {
		char* eventNameCStr = evhttp_encode_uri("_scxmleventname");
		char* eventValueCStr = evhttp_encode_uri(req.name.c_str());
		kvps << kvpSeperator << eventNameCStr << "=" << eventValueCStr;
		kvpSeperator = "&";
		free(eventNameCStr);
		free(eventValueCStr);
//		targetURL.addOutHeader("_scxmleventname", evhttp_encode_uri(req.name.c_str()));
	}

	// event namelist
	if (req.namelist.size() > 0) {
		std::map<std::string, Data>::const_iterator namelistIter = req.namelist.begin();
		while (namelistIter != req.namelist.end()) {
			char* keyCStr = evhttp_encode_uri(namelistIter->first.c_str());
			// this is simplified - Data might be more elaborate than a simple string atom
			char* valueCStr = evhttp_encode_uri(namelistIter->second.atom.c_str());
			kvps << kvpSeperator << keyCStr << "=" << valueCStr;
			free(keyCStr);
			free(valueCStr);
			kvpSeperator = "&";
//			targetURL.addOutHeader(namelistIter->first, namelistIter->second);
			namelistIter++;
		}
	}

	// event params
	if (req.params.size() > 0) {
		std::multimap<std::string, Data>::const_iterator paramIter = req.params.begin();
		while (paramIter != req.params.end()) {
			char* keyCStr = evhttp_encode_uri(paramIter->first.c_str());
			// this is simplified - Data might be more elaborate than a simple string atom
			char* valueCStr = evhttp_encode_uri(paramIter->second.atom.c_str());
			kvps << kvpSeperator << keyCStr << "=" << valueCStr;
			free(keyCStr);
			free(valueCStr);
			kvpSeperator = "&";
//			targetURL.addOutHeader(paramIter->first, paramIter->second);
			paramIter++;
		}
	}

	// try hard to find actual content
	char* keyCStr = evhttp_encode_uri("content");
	if (req.content.size() > 0) {
		char* valueCStr = evhttp_encode_uri(req.content.c_str());
		kvps << kvpSeperator << keyCStr << "=" << valueCStr;
		free(valueCStr);
		kvpSeperator = "&";
	} else if (req.dom) {
		std::stringstream xmlStream;
		xmlStream << req.dom;
		char* valueCStr = evhttp_encode_uri(xmlStream.str().c_str());
		kvps << kvpSeperator << keyCStr << "=" << valueCStr;
		free(valueCStr);
		kvpSeperator = "&";
	} else if (!req.data.empty()) {
		char* valueCStr = NULL;
		if (req.data.atom.length() || req.data.array.size() || req.data.compound.size()) {
			valueCStr = evhttp_encode_uri(Data::toJSON(req.data).c_str());
		} else if(req.data.node) {
			std::stringstream xmlStream;
			xmlStream << req.data.node;
			valueCStr = evhttp_encode_uri(xmlStream.str().c_str());
		} else if(req.data.binary) {
			valueCStr = evhttp_encode_uri(req.data.binary.base64().c_str());
		}
		if (valueCStr != NULL) {
			kvps << kvpSeperator << keyCStr << "=" << valueCStr;
			free(valueCStr);
			kvpSeperator = "&";
		}
	}
	free(keyCStr);

	targetURL.setOutContent(kvps.str());

//	targetURL.addOutHeader("Content-Type", "application/x-www-form-urlencoded");

	targetURL.setRequestType("post");
	targetURL.addMonitor(this);

	_sendRequests[req.sendid] = std::make_pair(targetURL, req);
	if (isLocal) {
		// test201 use a blocking request with local communication
		targetURL.download(true);
	} else {
		URLFetcher::fetchURL(targetURL);
	}
}

void BasicHTTPIOProcessor::downloadStarted(const URL& url) {}

void BasicHTTPIOProcessor::downloadCompleted(const URL& url) {
	std::map<std::string, std::pair<URL, SendRequest> >::iterator reqIter = _sendRequests.begin();
	while(reqIter != _sendRequests.end()) {
		if (reqIter->second.first == url) {
			// test513
			std::string statusCode = url.getStatusCode();
			if (statusCode.length() > 0) {
				std::string statusPrefix = statusCode.substr(0,1);
				std::string statusRest = statusCode.substr(1);
				Event event;
				event.data = url;
				event.name = "HTTP." + statusPrefix + "." + statusRest;
//				returnEvent(event);
			}
			_sendRequests.erase(reqIter);
			return;
		}
		reqIter++;
	}
	assert(false);
}

void BasicHTTPIOProcessor::downloadFailed(const URL& url, int errorCode) {

	std::map<std::string, std::pair<URL, SendRequest> >::iterator reqIter = _sendRequests.begin();
	while(reqIter != _sendRequests.end()) {
		if (reqIter->second.first == url) {
			Event failEvent;
			failEvent.name = "error.communication";
			returnEvent(failEvent);

			_sendRequests.erase(reqIter);
			return;
		}
		reqIter++;
	}
	assert(false);

}

}

max_stars_repo_name: sradomski/uscxml

max_issues_repo_name: sradomski/uscxml

max_forks_repo_name: sradomski/uscxml


text:
#include <chrono>
#include <cstdlib>
#include <iostream>
#include <string>
#include <boost/asio.hpp>
#include <asio-zmq.hpp>
#include "helper.hpp"

int main(int argc, char* argv[])
{
    if (argc != 4) {
        std::cerr << "usage: local_lat <bind-to> <message-size> "
                  << "<roundtrip-count>\n";
        return 1;
    }

    std::string const ep = argv[1];
    int message_size = std::atoi(argv[2]);
    int roundtrip_count = std::atoi(argv[3]);

    boost::asio::io_service ios;
    boost::asio::zmq::context ctx;

    boost::asio::zmq::test::perf::requester requester(ios, ctx, roundtrip_count, message_size, ep);

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

    ios.run();

    auto elapsed = std::chrono::system_clock::now() - watch;
    double latency = static_cast<double>(
                         std::chrono::duration_cast<std::chrono::microseconds>(elapsed).count()) /
                     (roundtrip_count * 2);
    std::cout << "message size: " << message_size << " [B]\n";
    std::cout << "roundtrip count: " << roundtrip_count << "\n";
    std::cout << "average latency: " << latency << " [us]\n";
}

max_stars_repo_name: yayj/asio-zmq

max_issues_repo_name: yayj/asio-zmq

max_forks_repo_name: yayj/asio-zmq


text:
#include <gtest/gtest.h>

#include <boost/system/error_code.hpp>
#include <string>
#include <vector>

#include "compiler/compiler.hpp"

extern std::string parser(std::string sInputFile);

bool check_compile_function() { return (parser("ut_example.rql") == "OK"); }

TEST(xcompiler, check_compile) { ASSERT_TRUE(check_compile_function()); }

max_stars_repo_name: michalwidera/abracadabradb

max_issues_repo_name: michalwidera/abracadabradb

max_forks_repo_name: michalwidera/abracadabradb


text:
//
// Copyright (c) 2016-2019 Vinnie Falco (vinnie dot falco at gmail dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
// Official repository: https://github.com/boostorg/beast
//

#include "snippets.hpp"

#include <boost/beast/_experimental/unit_test/suite.hpp>
#include <boost/beast/_experimental/test/stream.hpp>
#include <boost/beast/core/async_base.hpp>
#include <boost/beast/core/buffers_prefix.hpp>
#include <boost/beast/core/error.hpp>
#include <boost/beast/core/flat_buffer.hpp>
#include <boost/beast/core/stream_traits.hpp>
#include <boost/beast/core/tcp_stream.hpp>
#include <boost/beast/http.hpp>
#include <boost/beast/ssl/ssl_stream.hpp>
#include <boost/asio/buffer.hpp>
#include <boost/asio/read.hpp>
#include <boost/asio/spawn.hpp>
#include <cstdlib>
#include <utility>
#include <string>

namespace boost {
namespace beast {

namespace {

struct handler_type
{
    template<class... Args>
    void operator()(Args&&...)
    {
    }
};

void
core_3_timeouts_snippets()
{
    handler_type handler;

    #include "snippets.ipp"

    {
    //[code_core_3_timeouts_1

        // `ioc` will be used to dispatch completion handlers
        tcp_stream stream(ioc);

    //]
    }

    {
    //[code_core_3_timeouts_2

        // The resolver is used to look up the IP addresses for a domain name
        net::ip::tcp::resolver resolver(ioc);

        // The stream will use the same executor as the resolver
        tcp_stream stream(resolver.get_executor());

    //]
    }

    {
    //[code_core_3_timeouts_3

        // The strand will be used to invoke all completion handlers
        tcp_stream stream(net::make_strand(ioc));

    //]

        net::ip::tcp::resolver resolver(ioc);

    //[code_core_3_timeouts_4

        // Set the logical operation timer to 30 seconds
        stream.expires_after (std::chrono::seconds(30));

        // If the connection is not established within 30 seconds,
        // the operation will be canceled and the handler will receive
        // error::timeout as the error code.

        stream.async_connect(resolver.resolve("www.example.com", "http"),
            [](error_code ec, net::ip::tcp::endpoint ep)
            {
                if(ec == error::timeout)
                    std::cerr << "async_connect took too long\n";
                else if(! ec)
                    std::cout << "Connected to " << ep << "\n";
            }
        );

        // The timer is still running. If we don't want the next
        // operation to time out 30 seconds relative to the previous
        // call  to `expires_after`, we need to turn it off before
        // starting another asynchronous operation.

        stream.expires_never();

    //]
    }

    {
    //[code_core_3_timeouts_5

        // The acceptor is used to listen and accept incoming connections.
        // We construct the acceptor to use a new strand, and listen
        // on the loopback address with an operating-system assigned port.

        net::ip::tcp::acceptor acceptor(net::make_strand(ioc));
        acceptor.bind(net::ip::tcp::endpoint(net::ip::make_address_v4("127.0.0.1"), 0));
        acceptor.listen(0);

        // This blocks until a new incoming connection is established.
        // Upon success, the function returns a new socket which is
        // connected to the peer. The socket will have its own executor,
        // which in the call below is a new strand for the I/O context.

        net::ip::tcp::socket s = acceptor.accept(net::make_strand(ioc));

        // Construct a new tcp_stream from the connected socket.
        // The stream will use the strand created when the connection
        // was accepted.

        tcp_stream stream(std::move(s));
    //]
    }

    {
        tcp_stream stream(ioc);

    //[code_core_3_timeouts_6

        std::string s;

        // Set the logical operation timer to 30 seconds.
        stream.expires_after (std::chrono::seconds(30));

        // Read a line from the stream into the string.
        net::async_read_until(stream, net::dynamic_buffer(s), '\n',
            [&s, &stream](error_code ec, std::size_t bytes_transferred)
            {
                if(ec)
                    return;

                // read_until can read past the '\n', these will end up in
                // our buffer but we don't want to echo those extra received
                // bytes. `bytes_transferred` will be the number of bytes
                // up to and including the '\n'. We use `buffers_prefix` so
                // that extra data is not written.

                net::async_write(stream, buffers_prefix(bytes_transferred, net::buffer(s)),
                    [&s](error_code ec, std::size_t bytes_transferred)
                    {
                        // Consume the line from the buffer
                        s.erase(s.begin(), s.begin() + bytes_transferred);

                        if(ec)
                            std::cerr << "Error: " << ec.message() << "\n";
                    });
            });
    //]
    }

    {
        tcp_stream stream(ioc);

    //[code_core_3_timeouts_7

        std::string s1;
        std::string s2;

        // Set the logical operation timer to 15 seconds.
        stream.expires_after (std::chrono::seconds(15));

        // Read another line from the stream into our dynamic buffer.
        // The operation will time out after 15 seconds.

        net::async_read_until(stream, net::dynamic_buffer(s1), '\n', handler);

        // Set the logical operation timer to 30 seconds.
        stream.expires_after (std::chrono::seconds(30));

        // Write the contents of the other buffer.
        // This operation will time out after 30 seconds.

        net::async_write(stream, net::buffer(s2), handler);

    //]
    }

    {
    //[code_core_3_timeouts_8

        // To declare a stream with a rate policy, it is necessary to
        // write out all of the template parameter types.
        //
        // `simple_rate_policy` is default constructible, but
        // if the choice of RatePolicy is not DefaultConstructible,
        // an instance of the type may be passed to the constructor.

        basic_stream<net::ip::tcp, net::executor, simple_rate_policy> stream(ioc);

        // The policy object, which is default constructed, or
        // decay-copied upon construction, is attached to the stream
        // and may be accessed through the function `rate_policy`.
        //
        // Here we set individual rate limits for reading and writing

        stream.rate_policy().read_limit(10000); // bytes per second

        stream.rate_policy().write_limit(850000); // bytes per second
    //]
    }
}

//[code_core_3_timeouts_1f

/** This function echoes back received lines from a peer, with a timeout.

    The algorithm terminates upon any error (including timeout).
*/
template <class Protocol, class Executor>
void do_async_echo (basic_stream<Protocol, Executor>& stream)
{
    // This object will hold our state when reading the line.

    struct echo_line
    {
        basic_stream<Protocol, Executor>& stream;

        // The shared pointer is used to extend the lifetime of the
        // string until the last asynchronous operation completes.
        std::shared_ptr<std::string> s;

        // This starts a new operation to read and echo a line
        void operator()()
        {
            // If a line is not sent and received within 30 seconds, then
            // the connection will be closed and this algorithm will terminate.

            stream.expires_after(std::chrono::seconds(30));

            // Read a line from the stream into our dynamic buffer, with a timeout
            net::async_read_until(stream, net::dynamic_buffer(*s), '\n', std::move(*this));
        }

        // This function is called when the read completes
        void operator()(error_code ec, std::size_t bytes_transferred)
        {
            if(ec)
                return;

            net::async_write(stream, buffers_prefix(bytes_transferred, net::buffer(*s)),
                [this](error_code ec, std::size_t bytes_transferred)
                {
                    s->erase(s->begin(), s->begin() + bytes_transferred);

                    if(! ec)
                    {
                        // Run this algorithm again
                        echo_line{stream, std::move(s)}();
                    }
                    else
                    {
                        std::cerr << "Error: " << ec.message() << "\n";
                    }
                });
        }
    };

    // Create the operation and run it
    echo_line{stream, std::make_shared<std::string>()}();
}

//]

//[code_core_3_timeouts_2f

/** Request an HTTP resource from a TLS host and return it as a string, with a timeout.

    This example uses fibers (stackful coroutines) and its own I/O context.
*/
std::string
https_get (std::string const& host, std::string const& target, error_code& ec)
{
    // It is the responsibility of the algorithm to clear the error first.
    ec = {};

    // We use our own I/O context, to make this function blocking.
    net::io_context ioc;

    // This context is used to hold client and server certificates.
    // We do not perform certificate verification in this example.

    net::ssl::context ctx(net::ssl::context::tlsv12);

    // This string will hold the body of the HTTP response, if any.
    std::string result;

    // Note that Networking TS does not come with spawn. This function
    // launches a "fiber" which is a coroutine that has its own separately
    // allocated stack.

    boost::asio::spawn(ioc,
    [&](boost::asio::yield_context yield)
    {
        // We use the Beast ssl_stream wrapped around a beast tcp_stream.
        ssl_stream<tcp_stream> stream(ioc, ctx);

        // The resolver will be used to look up the IP addresses for the host name
        net::ip::tcp::resolver resolver(ioc);

        // First, look up the name. Networking has its own timeout for this.
        // The `yield` object is a CompletionToken which specializes the
        // `net::async_result` customization point to make the fiber work.
        //
        // This call will appear to "block" until the operation completes.
        // It isn't really blocking. Instead, the fiber implementation saves
        // the call stack and suspends the function until the asynchronous
        // operation is complete. Then it restores the call stack, and resumes
        // the function to the statement following the async_resolve. This
        // allows an asynchronous algorithm to be expressed synchronously.

        auto const endpoints = resolver.async_resolve(host, "https", {}, yield[ec]);
        if(ec)
            return;

        // The function `get_lowest_layer` retrieves the "bottom most" object
        // in the stack of stream layers. In this case it will be the tcp_stream.
        // This timeout will apply to all subsequent operations collectively.
        // That is to say, they must all complete within the same 30 second
        // window.

        get_lowest_layer(stream).expires_after(std::chrono::seconds(30));

        // `tcp_stream` range connect algorithms are member functions, unlike net::
        get_lowest_layer(stream).async_connect(endpoints, yield[ec]);
        if(ec)
            return;

        // Perform the TLS handshake
        stream.async_handshake(net::ssl::stream_base::client, yield[ec]);
        if(ec)
            return;

        // Send an HTTP GET request for the target
        {
            http::request<http::empty_body> req;
            req.method(http::verb::get);
            req.target(target);
            req.version(11);
            req.set(http::field::host, host);
            req.set(http::field::user_agent, "Beast");
            http::async_write(stream, req, yield[ec]);
            if(ec)
                return;
        }

        // Now read the response
        flat_buffer buffer;
        http::response<http::string_body> res;
        http::async_read(stream, buffer, res, yield[ec]);
        if(ec)
            return;

        // Try to perform the TLS shutdown handshake
        stream.async_shutdown(yield[ec]);

        // `net::ssl::error::stream_truncated`, also known as an SSL "short read",
        // indicates the peer closed the connection without performing the
        // required closing handshake (for example, Google does this to
        // improve performance). Generally this can be a security issue,
        // but if your communication protocol is self-terminated (as
        // it is with both HTTP and WebSocket) then you may simply
        // ignore the lack of close_notify:
        //
        // https://github.com/boostorg/beast/issues/38
        //
        // https://security.stackexchange.com/questions/91435/how-to-handle-a-malicious-ssl-tls-shutdown
        //
        // When a short read would cut off the end of an HTTP message,
        // Beast returns the error beast::http::error::partial_message.
        // Therefore, if we see a short read here, it has occurred
        // after the message has been completed, so it is safe to ignore it.

        if(ec == net::ssl::error::stream_truncated)
            ec = {};
        else if(ec)
            return;

        // Set the string to return to the caller
        result = std::move(res.body());
    });

    // `run` will dispatch completion handlers, and block until there is
    // no more "work" remaining. When this call returns, the operations
    // are complete and we can give the caller the result.
    ioc.run();

    return result;
}

//]

//[code_core_3_timeouts_3f

class window
{
    std::size_t value_ = 0;

    // The size of the exponential window, in seconds.
    // This should be a power of two.

    static std::size_t constexpr Window = 4;

public:
    /** Returns the number of elapsed seconds since the given time, and adjusts the time.

        This function returns the number of elapsed seconds since the
        specified time point, rounding down. It also moves the specified
        time point forward by the number of elapsed seconds.

        @param since The time point from which to calculate elapsed time.
        The function will modify the value, by adding the number of elapsed
        seconds to it.

        @return The number of elapsed seconds.
    */
    template<class Clock, class Duration>
    static
    std::chrono::seconds
    get_elapsed(std::chrono::time_point<Clock, Duration>& since) noexcept
    {
        auto const elapsed = std::chrono::duration_cast<
            std::chrono::seconds>(Clock::now() - since);
        since += elapsed;
        return elapsed;
    }

    /// Returns the current value, after adding the given sample.
    std::size_t
    update(std::size_t sample, std::chrono::seconds elapsed) noexcept
    {
        // Apply exponential decay.
        //
        // This formula is fast (no division or multiplication) but inaccurate.
        // It overshoots by `n*(1-a)/(1-a^n), where a=(window-1)/window`.
        // Could be good enough for a rough approximation, but if relying
        // on this for production please perform tests!

        auto count = elapsed.count();
        while(count--)
            value_ -= (value_ + Window - 1) / Window;
        value_ += sample;
        return value_ / Window;
    }
    /// Returns the current value
    std::size_t
    value() const noexcept
    {
        return value_ / Window;
    }
};

//]

//[code_core_3_timeouts_4f

/** A RatePolicy to measure instantaneous throughput.

    This measures the rate of transfer for reading and writing
    using a simple exponential decay function.
*/
class rate_gauge
{
    // The clock used to measure elapsed time
    using clock_type = std::chrono::steady_clock;

    // This implements an exponential smoothing window function.
    // The value `Seconds` is the size of the window in seconds.

    clock_type::time_point when_;
    std::size_t read_bytes_ = 0;
    std::size_t write_bytes_ = 0;
    window read_window_;
    window write_window_;

    // Friending this type allows us to mark the
    // member functions required by RatePolicy as private.
    friend class rate_policy_access;

    // Returns the number of bytes available to read currently
    // Required by RatePolicy
    std::size_t
    available_read_bytes() const noexcept
    {
        // no limit
        return (std::numeric_limits<std::size_t>::max)();
    }

    // Returns the number of bytes available to write currently
    // Required by RatePolicy
    std::size_t
    available_write_bytes() const noexcept
    {
        // no limit
        return (std::numeric_limits<std::size_t>::max)();
    }

    // Called every time bytes are read
    // Required by RatePolicy
    void
    transfer_read_bytes(std::size_t n) noexcept
    {
        // Add this to our running total of bytes read
        read_bytes_ += n;
    }

    // Called every time bytes are written
    // Required by RatePolicy
    void
    transfer_write_bytes(std::size_t n) noexcept
    {
        // Add this to our running total of bytes written
        write_bytes_ += n;
    }

    // Called approximately once per second
    // Required by RatePolicy
    void
    on_timer()
    {
        // Calculate elapsed time in seconds, and adjust our time point
        auto const elapsed = window::get_elapsed(when_);

        // Skip the update when elapsed==0,
        // otherwise the measurement will have jitter
        if(elapsed.count() == 0)
            return;

        // Add our samples and apply exponential decay
        read_window_.update(read_bytes_, elapsed);
        write_window_.update(write_bytes_, elapsed);

        // Reset our counts of bytes transferred
        read_bytes_ = 0;
        write_bytes_ = 0;
    }

public:
    rate_gauge()
        : when_(clock_type::now())
    {
    }

    /// Returns the current rate of reading in bytes per second
    std::size_t
    read_bytes_per_second() const noexcept
    {
        return read_window_.value();
    }

    /// Returns the current rate of writing in bytes per second
    std::size_t
    write_bytes_per_second() const noexcept
    {
        return write_window_.value();
    }
};

//]

void
core_3_timeouts_snippets2()
{
    #include "snippets.ipp"

    {
    //[code_core_3_timeouts_9

        // This stream will use our new rate_gauge policy
        basic_stream<net::ip::tcp, net::executor, rate_gauge> stream(ioc);

        //...

        // Print the current rates
        std::cout <<
            stream.rate_policy().read_bytes_per_second() << " bytes/second read\n" <<
            stream.rate_policy().write_bytes_per_second() << " bytes/second written\n";
    //]
    }
}

} // (anon)

template class basic_stream<net::ip::tcp, net::executor, rate_gauge>;

struct core_3_timeouts_test
    : public beast::unit_test::suite
{
    void
    testWindow()
    {
        window w;
        std::size_t v0 = w.value();
        std::size_t const N = 100000;
        for(std::size_t n = 1; n <= 2; ++n)
        {
            for(std::size_t i = 0;;++i)
            {
                auto const v = w.update(n * N, std::chrono::seconds(n));
                if(v == v0)
                {
                    BEAST_PASS();
                #if 0
                    log <<
                        "update(" << n*N << ", " << n <<
                        ") converged to " << w.value() <<
                        " in " << i << std::endl;
                #endif
                    break;
                }
                if(i > 1000)
                {
                    BEAST_FAIL();
                    break;
                }
                v0 = v;
            }
        }
    }

    void
    run() override
    {
        testWindow();

        BEAST_EXPECT(&core_3_timeouts_snippets);
        BEAST_EXPECT(&core_3_timeouts_snippets2);
        BEAST_EXPECT((&do_async_echo<net::ip::tcp, net::io_context::executor_type>));
        BEAST_EXPECT(&https_get);
    }
};

BEAST_DEFINE_TESTSUITE(beast,doc,core_3_timeouts);

} // beast
} // boost

max_stars_repo_name: grisumbras/beast

max_issues_repo_name: qingkouwei/mediaones

max_forks_repo_name: qingkouwei/mediaones


text:
/// HEADER
#include <csapex/factory/message_factory.h>

/// COMPONENT
#include <csapex/utility/assert.h>
#include <csapex/utility/yaml_node_builder.h>
#include <csapex/serialization/message_serializer.h>
#include <csapex/serialization/serialization_buffer.h>
#include <csapex/core/settings.h>

/// SYSTEM
#include <fstream>
#include <boost/iostreams/filtering_stream.hpp>
#include <boost/iostreams/copy.hpp>
#include <boost/iostreams/filter/gzip.hpp>
#include <iostream>
#define BOOST_NO_CXX11_SCOPED_ENUMS
#include <boost/filesystem.hpp>
#undef BOOST_NO_CXX11_SCOPED_ENUMS
#include <boost/version.hpp>

#if (BOOST_VERSION / 100000) >= 1 && (BOOST_VERSION / 100 % 1000) >= 54
namespace bf3 = boost::filesystem;
#else
namespace bf3 = boost::filesystem3;
#endif

using namespace csapex;

MessageFactory::MessageFactory()
{
}

void MessageFactory::shutdown()
{
    type_to_constructor.clear();
}

TokenData::Ptr MessageFactory::createMessage(const std::string& type)
{
    MessageFactory& i = instance();

    if (i.type_to_constructor.empty()) {
        throw std::runtime_error("no connection types registered!");
    }

    if (i.type_to_constructor.find(type) == i.type_to_constructor.end()) {
        throw std::runtime_error(std::string("cannot create message, no such type (") + type + ")");
    }

    return i.type_to_constructor[type]();
}

TokenData::Ptr MessageFactory::readFile(const std::string& file)
{
    std::string ext = file.substr(file.rfind("."));

    if (ext == Settings::message_extension_binary) {
        return readBinaryFile(file);
    } else {
        return readYamlFile(file);
    }

    return nullptr;
}

int MessageFactory::writeFile(const std::string& path, const std::string& base, const int suffix, const TokenData& msg, serialization::Format format)
{
    int next_free_suffix = suffix;

    // make sure the target directory exists
    bf3::path dir(path);
    if (!bf3::exists(dir)) {
        bf3::create_directories(dir);
    }

    if (format == serialization::Format::NATIVE) {
        msg.writeNative(path, base, std::to_string(next_free_suffix));
        return next_free_suffix + 1;
    }

    // generate a unique file name
    std::string file_name;
    bool file_exists = false;
    do {
        std::stringstream file_s;
        switch (format) {
            case serialization::Format::APEX_YAML:
                file_s << path << "/" << base << "_" << next_free_suffix << Settings::message_extension;
                break;
            case serialization::Format::APEX_BINARY:
                file_s << path << "/" << base << "_" << next_free_suffix << Settings::message_extension_binary;
                break;
            case serialization::Format::NATIVE:
                break;
        }
        file_name = file_s.str();

        if (bf3::exists((file_name))) {
            ++next_free_suffix;
        }
    } while (file_exists);

    switch (format) {
        case serialization::Format::APEX_YAML:
            writeYamlFile(file_name, msg);
            break;
        case serialization::Format::APEX_BINARY:
            writeBinaryFile(file_name, msg);
            break;
        case serialization::Format::NATIVE:
            // DO NOTHING
            break;
    }

    return next_free_suffix;
}

TokenData::Ptr MessageFactory::readYamlFile(const std::string& path)
{
    YAML::Node node;
    if (path.substr(path.size() - Settings::message_extension_compressed.size()) == Settings::message_extension_compressed) {
        std::ifstream in(path, std::ios_base::in | std::ios_base::binary);
        boost::iostreams::filtering_istream zipped_in;
        zipped_in.push(boost::iostreams::gzip_decompressor());
        zipped_in.push(in);
        node = YAML::Load(zipped_in);
    } else {
        node = YAML::LoadFile(path);
    }
    return MessageSerializer::instance().readYaml(node);
}

void MessageFactory::writeYamlFile(const std::string& path, const TokenData& msg)
{
    std::ofstream out(path.c_str());

    YAML::Emitter yaml;
    yaml << MessageSerializer::instance().serializeYamlMessage(msg);
    out << yaml.c_str();
}

TokenData::Ptr MessageFactory::readBinaryFile(const std::string& path)
{
    auto file = std::fopen(path.c_str(), "rb");
    if (!file) {
        throw std::runtime_error("cannot open file " + path + " for reading");
    }

    std::fseek(file, 0, SEEK_END);
    std::size_t n = std::ftell(file);
    std::rewind(file);

    SerializationBuffer buffer;
    buffer.resize(n);

    std::fread(buffer.data(), 1, n, file);

    return MessageSerializer::instance().deserializeBinaryMessage(buffer);
}

void MessageFactory::writeBinaryFile(const std::string& path, const TokenData& msg)
{
    auto file = std::fopen(path.c_str(), "wb");
    if (!file) {
        throw std::runtime_error("cannot open file " + path + " for writing");
    }

    SerializationBuffer buffer;
    MessageSerializer::serializeBinaryMessage(msg, buffer);
    buffer.finalize();

    std::fwrite(buffer.data(), sizeof(uint8_t), buffer.size(), file);
}

bool MessageFactory::isMessageRegistered(const std::string& type) const
{
    std::map<std::string, Constructor>::const_iterator it = type_to_constructor.find(type);
    return it != type_to_constructor.end();
}

void MessageFactory::registerMessage(std::string type, std::type_index typeindex, Constructor constructor)
{
    MessageFactory& i = instance();

    std::map<std::string, Constructor>::const_iterator it = i.type_to_constructor.find(type);

    apex_assert_hard_msg(it == i.type_to_constructor.end() || i.type_to_type_index.at(type) == typeindex, std::string("there are two or more messages of type '") + type + "' registered");

    i.type_to_constructor.insert(std::make_pair(type, constructor));
    i.type_to_type_index.insert(std::make_pair(type, typeindex));
}


text:
/****************************************************************************
**
** Copyright (C) 2017 TU Wien, ACIN, Vision 4 Robotics (V4R) group
** Contact: v4r.acin.tuwien.ac.at
**
** This file is part of V4R
**
** V4R is distributed under dual licenses - GPLv3 or closed source.
**
** GNU General Public License Usage
** V4R is free software: you can redistribute it and/or modify
** it under the terms of the GNU General Public License as published
** by the Free Software Foundation, either version 3 of the License, or
** (at your option) any later version.
**
** V4R is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
** GNU General Public License for more details.
**
** Please review the following information to ensure the GNU General Public
** License requirements will be met: https://www.gnu.org/licenses/gpl-3.0.html.
**
**
** Commercial License Usage
** If GPL is not suitable for your project, you must purchase a commercial
** license to use V4R. Licensees holding valid commercial V4R licenses may
** use this file in accordance with the commercial license agreement
** provided with the Software or, alternatively, in accordance with the
** terms contained in a written agreement between you and TU Wien, ACIN, V4R.
** For licensing terms and conditions please contact office<at>acin.tuwien.ac.at.
**
**
** The copyright holder additionally grants the author(s) of the file the right
** to use, copy, modify, merge, publish, distribute, sublicense, and/or
** sell copies of their contributions without any restrictions.
**
****************************************************************************/

/**
 * @file main.cpp
 * @author Johann Prankl (prankl@acin.tuwien.ac.at)
 * @date 2017
 * @brief
 *
 */

#include <v4r/features/ImGradientDescriptor.h>
#include <Eigen/Dense>
#include <opencv2/imgproc/imgproc.hpp>

//#define IMGD_INTERPOLATED

namespace v4r {

using namespace std;

/************************************************************************************
 * Constructor/Destructor
 */
ImGradientDescriptor::ImGradientDescriptor(const Parameter &p) : param(p) {
  // param.computeRootGD = false;
}

ImGradientDescriptor::~ImGradientDescriptor() {}

/**
 * ComputeGradients
 */
void ImGradientDescriptor::ComputeGradients(const cv::Mat_<unsigned char> &im) {
  if (param.smooth)
    cv::blur(im, im_smooth, cv::Size(3, 3));
  else
    im_smooth = im;

  cv::Sobel(im_smooth, im_dx, CV_16S, 1, 0, 3, 1, 0, cv::BORDER_DEFAULT);
  cv::Sobel(im_smooth, im_dy, CV_16S, 0, 1, 3, 1, 0, cv::BORDER_DEFAULT);
}

/**
 * ComputeDescriptor
 */
void ImGradientDescriptor::ComputeDescriptor(std::vector<float> &desc, const cv::Mat_<float> &weight) {
  int h;
  short *ptr_dx, *ptr_dy;

  desc.clear();
  desc.resize(128, 0);

  int dv = (im_dx.rows - 2) / 4;
  int du = (im_dx.cols - 2) / 4;

  for (int v = 1; v < im_dx.rows - 1; v++) {
    ptr_dx = &im_dx(v, 1);
    ptr_dy = &im_dy(v, 1);

    for (int u = 1; u < im_dx.cols - 1; u++, ptr_dx++, ptr_dy++) {
      if (*ptr_dx > 0 && *ptr_dy > 0) {
        if (*ptr_dx > *ptr_dy)
          h = 0;
        else
          h = 1;
      } else if (*ptr_dx < 0 && *ptr_dy > 0) {
        if ((-*ptr_dx) < *ptr_dy)
          h = 2;
        else
          h = 3;
      } else if (*ptr_dx < 0 && *ptr_dy < 0) {
        if ((*ptr_dx) < *ptr_dy)
          h = 4;
        else
          h = 5;
      } else {
        if ((*ptr_dx) < (-*ptr_dy))
          h = 6;
        else
          h = 7;
      }

      // desc[(((v-1)/dv*4 + (u-1)/du))*8 + h] += float(sqrt(*ptr_dx * *ptr_dx + *ptr_dy * *ptr_dy)) * weight(v,u);
      desc[(((v - 1) / dv * 4 + (u - 1) / du)) * 8 + h] += float(fabs(*ptr_dx) + fabs(*ptr_dy)) * weight(v, u);
      // desc[(v-1)/dv*4*8 + (u-1)/du*8 + h] += float(fabs(*ptr_dx)+fabs(*ptr_dy)) * weight(v,u);

      // cout<<sqrt(*ptr_dx * *ptr_dx + *ptr_dy * *ptr_dy)<<" ";
    }
  }
}

/**
 * ComputeDescriptorInterpolate
 */
void ImGradientDescriptor::ComputeDescriptorInterpolate(std::vector<float> &desc, const cv::Mat_<float> &weight) {
  int h;
  // short *ptr_dx, *ptr_dy;

  desc.clear();
  desc.resize(128, 0);

  int dv = (im_dx.rows - 2) / 4;
  int du = (im_dx.cols - 2) / 4;
  float du_2 = float(du) / 2.;
  float dv_2 = float(dv) / 2.;
  float wx, wy, wx2, wy2;

  for (int v = 0; v < 4; v++) {
    for (int u = 0; u < 4; u++) {
      for (int y = 0; y < dv; y++) {
        for (int x = 0; x < du; x++) {
          int ug = u * du + x + 1;
          int vg = v * dv + y + 1;
          const float &dx = im_dx(vg, ug);
          const float &dy = im_dy(vg, ug);

          if (dx > 0 && dy > 0) {
            if (dx > dy)
              h = 0;
            else
              h = 1;
          } else if (dx < 0 && dy > 0) {
            if ((-dx) < dy)
              h = 2;
            else
              h = 3;
          } else if (dx < 0 && dy < 0) {
            if (dx < dy)
              h = 4;
            else
              h = 5;
          } else {
            if (dx < -dy)
              h = 6;
            else
              h = 7;
          }

          wx = 0.5 + .5 * (1. - (float(x) - du_2) / du_2);
          wy = 0.5 + .5 * (1. - (float(y) - dv_2) / dv_2);

          desc[(v * 4 + u) * 8 + h] += float(fabs(dx) + fabs(dy)) * weight(vg, ug) * fabs(wx) * fabs(wy);

          wx2 = 1. - fabs(wx);
          wy2 = 1. - fabs(wy);
          int u2 = u + sign(wx);
          int v2 = v + sign(wy);

          if (u2 >= 0 && u2 < 4) {
            desc[(v * 4 + u2) * 8 + h] += float(fabs(dx) + fabs(dy)) * weight(vg, ug) * fabs(wx2) * fabs(wy);
          }
          if (v2 >= 0 && v2 < 4) {
            desc[(v2 * 4 + u) * 8 + h] += float(fabs(dx) + fabs(dy)) * weight(vg, ug) * fabs(wx) * fabs(wy2);
          }
          if (u2 >= 0 && u2 < 4 && v2 >= 0 && v2 < 4) {
            desc[(v * 4 + u2) * 8 + h] += float(fabs(dx) + fabs(dy)) * weight(vg, ug) * fabs(wx2) * fabs(wy2);
          }
        }
      }
    }
  }
}

/**
 * ComputeLTGauss
 */
void ImGradientDescriptor::ComputeLTGauss(const cv::Mat_<unsigned char> &im) {
  if (lt_gauss.rows != im.rows || lt_gauss.cols != im.cols) {
    if (param.gauss_lin)
      ComputeLTGaussLin(im);
    else
      ComputeLTGaussCirc(im);
  }
}

/**
 * ComputeLTGaussCirc
 */
void ImGradientDescriptor::ComputeLTGaussCirc(const cv::Mat_<unsigned char> &im) {
  if (im.rows != im.cols || (im.rows - 2) % 4 != 0)
    throw std::runtime_error("[ImGradientDescriptor::ComputeLTGaussCirc] Invalid patch size!");

  lt_gauss = cv::Mat_<float>(im.rows, im.cols);

  float h_size = im.rows / 2;
  float invSqrSigma;

  invSqrSigma = param.sigma * (float)(h_size - 1);
  invSqrSigma = -1. / (invSqrSigma * invSqrSigma);

  for (int v = -h_size; v < h_size; v++) {
    for (int u = -h_size; u < h_size; u++) {
      lt_gauss(v + h_size, u + h_size) = exp(invSqrSigma * (u * u + v * v));
    }
  }

  /*cv::Mat_<unsigned char> tmp(im.rows,im.cols);
  for (int v=0; v<im.rows; v++)
    for (int u=0; u<im.cols; u++)
      tmp(v,u) = lt_gauss(v,u)*255;
  cv::imshow("image",tmp);
  cv::waitKey(0);*/
}

/**
 * ComputeLTGaussLin
 */
void ImGradientDescriptor::ComputeLTGaussLin(const cv::Mat_<unsigned char> &im) {
  if ((im.cols - 2) % 4 != 0 || (im.rows - 2) % 4 != 0)
    throw std::runtime_error("[ImGradientDescriptor::ComputeLTGaussLin] Invalid patch size!");

  lt_gauss.resize(im.rows, im.cols);

  float h_size = im.rows / 2;
  float invSqrSigma;

  invSqrSigma = param.sigma * (float)(h_size - 1);
  invSqrSigma = -1. / (invSqrSigma * invSqrSigma);

  for (int v = -h_size; v < h_size; v++) {
    for (int u = 0; u < im.cols; u++) {
      lt_gauss(v + h_size, u) = exp(invSqrSigma * (u * u));
    }
  }
}

/**
 * Normalize
 */
void ImGradientDescriptor::Normalize(std::vector<float> &desc) {
  float norm = 0;

  float *ptr = &desc[0];
  for (unsigned i = 0; i < desc.size(); i++, ptr++)
    norm += (*ptr * *ptr);

  if (norm > numeric_limits<float>::epsilon()) {
    norm = 1. / sqrt(norm);

    for (unsigned i = 0; i < desc.size(); i++)
      desc[i] *= norm;
  }
}

/**
 * Normalize
 */
void ImGradientDescriptor::Cut(std::vector<float> &desc) {
  float *ptr = &desc[0];
  float *ptr_end = &desc.back();
  ptr_end++;

  for (; ptr != ptr_end; ptr++)
    if (*ptr > param.thrCutDesc)
      *ptr = param.thrCutDesc;
}

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

/**
 * compute gradient descriptor of center point (sift like)
 * we use a 3x3 sobel kernel
 * @param im image patch to compute the descriptor (min. 18x18 = 16x16 + 1px boarder)
 */
void ImGradientDescriptor::compute(const cv::Mat_<unsigned char> &im, std::vector<float> &desc) {
  ComputeLTGauss(im);

  ComputeGradients(im);

#ifdef IMGD_INTERPOLATED
  ComputeDescriptorInterpolate(desc, lt_gauss);
#else
  ComputeDescriptor(desc, lt_gauss);
#endif

  if (param.normalize) {
    Normalize(desc);  // to 1
    Cut(desc);        // cut 0.2
    Normalize(desc);  // renormalize to 1
  }

  if (param.computeRootGD) {
    Eigen::Map<Eigen::VectorXf> eig_desc(&desc[0], desc.size());
    float norm = eig_desc.lpNorm<1>();
    eig_desc.array() /= norm;
    eig_desc.array() = eig_desc.array().sqrt();
  }
}

/**
 * compute gradient descriptor of center point (sift like)
 * we use a 3x3 sobel kernel
 * @param im image patch to compute the descriptor (min. 18x18 = 16x16 + 1px boarder)
 */
void ImGradientDescriptor::compute(const cv::Mat_<unsigned char> &im, const cv::Mat_<float> &weight,
                                   std::vector<float> &desc) {
  ComputeGradients(im);

#ifdef IMGD_INTERPOLATED
  ComputeDescriptorInterpolate(desc, weight);
#else
  ComputeDescriptor(desc, weight);
#endif

  if (param.normalize) {
    Normalize(desc);  // to 1
    Cut(desc);        // cut 0.2
    Normalize(desc);  // renormalize to 1
  }

  if (param.computeRootGD) {
    Eigen::Map<Eigen::VectorXf> eig_desc(&desc[0], desc.size());
    float norm = eig_desc.lpNorm<1>();
    eig_desc.array() /= norm;
    eig_desc.array() = eig_desc.array().sqrt();
  }
}
}  // namespace v4r


text:
#ifndef DUMP_FOREST_HPP
#define DUMP_FOREST_HPP

#include "dump/x3_support.hpp"

#include <boost/algorithm/string/replace.hpp>
#include <boost/container/small_vector.hpp>
#include <boost/multi_index_container.hpp>
#include <boost/optional.hpp>
#include <boost/type_index.hpp>
#include <boost/variant.hpp>

#include <array>
#include <map>
#include <memory>
#include <ostream>
#include <set>
#include <sstream>
#include <string>
#include <vector>

namespace dump {

    /**
     * Struct that keeps the state of the forest_dumper.
     */
    struct forest_state {
        std::ostream& out;
        unsigned int level;

        forest_state(std::ostream& out)
            : out(out), level(0) {}
    };

    /**
     * Base class for data structure dumpers.
     *
     * We use the Curiously recurring template pattern here to be able
     * to call method's of the derived class.
     */
    template <typename Derived>
    struct forest_dumper {
        typedef forest_dumper<Derived> Self;

        const std::string black = "\\textcolor{black}{";
        const std::string red = "\\textcolor{red}{";
        const std::string green = "\\textcolor{green}{";
        const std::string yellow = "\\textcolor{orange}{";
        const std::string blue = "\\textcolor{blue}{";
        const std::string magenta = "\\textcolor{magenta}{";
        const std::string cyan = "\\textcolor{cyan}{";
        const std::string white = "\\textcolor{white}{";

        const std::string violet = "\\textcolor{violet}{";

        const std::string bold = "\\textbf{";

        const std::string reset = "}";

        forest_state state;
        std::string label;
        bool last_child;
        bool inlined;

        forest_dumper(std::ostream& out)
            : state(out), label(""), last_child(true),
              inlined(false) {
            print_prefix();
        }

        forest_dumper(forest_state state, std::string label,
                      bool last_child, bool inlined)
            : state(state), label(label), last_child(last_child),
              inlined(inlined) {
            this->state.level++;
            print_prefix();
        }

        ~forest_dumper() {
            print_postfix();
        }

        Derived &getDerived() {
            return static_cast<Derived&>(*this);
        }

        const Derived &getDerived() const {
            return static_cast<const Derived&>(*this);
        }

        inline
        std::string escape(std::string text) {
            boost::replace_all(text, "_", "\\_");
            boost::replace_all(text, "&", "\\&");
            boost::replace_all(text, "#", "\\#");
            /* Commas are replaced because of their syntactical meaning in LaTeX
             * forest package as they are used to configure additional settings
             * inside a node or subtree.
             */
            boost::replace_all(text, "{", "\\{");
            boost::replace_all(text, "}", "\\}");
            boost::replace_all(text, ",", "{,}");
            boost::replace_all(text, "[", "{[}");
            boost::replace_all(text, "]", "{]}");
            boost::replace_all(text, "=", "{=}");
            return text;
        }

        void print_prefix() {
            if(state.level == 0) {
                state.out << "\\begin{forest}" << std::endl;
                state.out << "  for tree={" << std::endl;
                state.out << "    font=\\ttfamily," << std::endl;
                state.out << "    grow'=0," << std::endl;
                state.out << "    child anchor=west," << std::endl;
                state.out << "    parent anchor=south," << std::endl;
                state.out << "    anchor=west," << std::endl;
                state.out << "    calign=first," << std::endl;
                state.out << "    edge path={" << std::endl;
                state.out << "      \\noexpand\\path [draw, \\forestoption{edge}]" << std::endl;
                state.out << "      (!u.south west) +(7.5pt,0) |- node[fill,inner sep=1.25pt] {} (.child anchor)\\forestoption{edge label};" << std::endl;
                state.out << "    }," << std::endl;
                state.out << "    before typesetting nodes={" << std::endl;
                state.out << "      if n=1" << std::endl;
                state.out << "        {insert before={[,phantom]}}" << std::endl;
                state.out << "        {}" << std::endl;
                state.out << "    }," << std::endl;
                state.out << "    fit=band," << std::endl;
                state.out << "    before computing xy={l=15pt}," << std::endl;
                state.out << "  }" << std::endl;
            }
            if(!inlined) {
                state.out << std::string(state.level, ' ');
                state.out << "[";
            } else {
                state.out << ' ';
            }
            if(label.length() > 0) {
                state.out << escape(label) << ' ';
            }
        }

        void print_postfix() {
            if(!inlined) {
                state.out << "]";
                state.out << std::endl;
            } else {
                state.out << ' ';
            }
            if(state.level == 0) {
                state.out << "\\end{forest}" << std::endl;
            }
        }

        template <typename Node>
        void cNode(Node const& node, std::string const& text) {
            state.out << bold << magenta << escape(text) << reset << reset;
        }

        template <typename Dumper, typename Parent, typename Child>
        void cAttr(Parent const& parent, std::string const& label,
                   Child const& child, bool last_child,
                   bool inlined = false) {
            Dumper{state, label, last_child, inlined}(child);
        }

        template <typename Parent, typename Child>
        void cAttr(Parent const& parent, std::string const& label,
                   Child const& child, bool last_child,
                   bool inlined = false) {
            Derived{state, label, last_child, inlined}(child);
        }

        template <typename T, std::size_t N>
        void cList(std::array<T, N> const& ops, std::string const& text) {
            cNode(ops, text);
            (*this)(ops);
        }

        template <typename T>
        void cList(std::vector<T> const& ops, std::string const& text) {
            cNode(ops, text);
            (*this)(ops);
        }

        template <typename T, typename Compare, typename Allocator>
        void cList(std::set<T, Compare, Allocator> const& ops,
                   std::string const& text) {
            cNode(ops, text);
            (*this)(ops);
        }

        template <typename Key, typename T, typename Compare, typename Allocator>
        void cList(std::map<Key, T, Compare, Allocator> const& ops,
                   std::string const& text) {
            cNode(ops, text);
            (*this)(ops);
        }

        template <typename... _Args>
        void cList(boost::multi_index_container<_Args...> const& ops,
                   std::string const& text) {
            cNode(ops, text);
            (*this)(ops);
        }

        template <typename T, std::size_t A>
        void cList(boost::container::small_vector<T, A> const& ops,
                   std::string const& text) {
            cNode(ops, text);
            (*this)(ops);
        }

        template <typename T>
        void cAddr(T const& obj) {
            state.out << ' ' << cyan << std::addressof(obj) << reset;
        }

        template <typename T>
        void cType(T const& obj) {
            // alternatively use typeid(T).name() which is not
            // required to be human readable
            state.out << ' '
                      << yellow
                      << escape(boost::typeindex::type_id<T>().pretty_name())
                      << reset;
        }

        template <typename T>
        void cTypeAddr(T const& obj) {
            cType(obj);
            cAddr(obj);
        }

        void cEnum(std::string const& text) {
            state.out << yellow << escape(text) << reset;
        }

        void cValue(std::string const& text) {
            if(text.find("\n") == std::string::npos) {
                state.out << green << " " << escape(text) << " " << reset;
            } else {
                cBlock(text);
            }
        }

        void cBlock(std::string const& text) {
            std::string t =
                boost::replace_all_copy(escape(text),
                                        "\n",
                                        "\\\\\n  ");
            boost::replace_all(t, " ", "\\ ");
            boost::replace_all(t, "/home/chris/projects/thesis/code/umbrella/", "");
            boost::replace_all(t, "lib-udf-clang-sdf-sdf-col/test/src/", "");
            state.out << "\\\\\n\\ \\ " << t << ", align=left";
        }

        void cErr(std::string const& text) {
            state.out << bold << red << escape(text) << reset;
        }

        template <typename T>
        void cErrTypeAddr(std::string const& text, T const& obj) {
            cErr(text);
            cTypeAddr(obj);
        }

        void cUndefined() {
            state.out << violet << "undefined" << reset;
        }

        void operator()(bool const& value)
        {
            cValue((value ? "true" : "false"));
        }

        void operator()(char const& value)
        {
            cValue(std::to_string(value));
        }

        void operator()(unsigned char const& value)
        {
            cValue(std::to_string(value));
        }

        void operator()(short const& value)
        {
            cValue(std::to_string(value));
        }

        void operator()(unsigned short const& value)
        {
            cValue(std::to_string(value));
        }

        void operator()(int const& value)
        {
            cValue(std::to_string(value));
        }

        void operator()(unsigned int const& value)
        {
            cValue(std::to_string(value));
        }

        void operator()(long const& value)
        {
            cValue(std::to_string(value));
        }

        void operator()(unsigned long const& value)
        {
            cValue(std::to_string(value));
        }

        void operator()(float const& value)
        {
            cValue(std::to_string(value));
        }

        void operator()(double const& value)
        {
            cValue(std::to_string(value));
        }

        void operator()(std::string const& value)
        {
            // TODO: Support multi line strings as in `console_dumper`
            cValue(value);
        }

        template <typename T>
        void operator()(std::shared_ptr<T> const& op) {
            if(op != nullptr) {
                getDerived()(*op);
            } else {
                cUndefined();
            }
        }

        template <typename... _Args>
        void operator()(boost::variant<_Args...> const& op) {
            return boost::apply_visitor(getDerived(), op);
        }

        template <typename T>
        void operator()(boost::optional<T> const& op) {
            if(op) {
                getDerived()(op.get());
            } else {
                cUndefined();
            }
        }

        // Boost Spirit X3 variant type
        template <typename T,
              typename std::enable_if<is_variant<T>::value, bool>::type = false>
        void operator()(T const& ast) {
            boost::apply_visitor(getDerived(), ast);
        }

        template <typename T>
        void operator()(boost::spirit::x3::forward_ast<T> const& ast) {
            getDerived()(ast.get());
        }

        template <typename T, std::size_t N>
        void operator()(std::array<T, N> const& ops) {
            auto s = ops.size();
            cAttr<Derived>(ops, "size", s, false, true);
            for(auto const& op : ops) {
                cAttr<Derived>(ops, "item", op, --s==0);
            }
        }

        template <typename T>
        void operator()(std::vector<T> const& ops) {
          auto s = ops.size();
          cAttr<Derived>(ops, "size", s, false, true);
          for(auto const& op : ops) {
              cAttr<Derived>(ops, "item", op, --s==0);
          }
        }

        template <typename Key, typename Compare, typename Allocator>
        void operator()(std::set<Key, Compare, Allocator> const& ops) {
            auto s = ops.size();
            cAttr<Derived>(ops, "size", s, false, true);
            for(auto const& op : ops) {
                cAttr<Derived>(ops, "item", op, --s==0);
            }
        }

        template <typename Key, typename T, typename Compare, typename Allocator>
        void operator()(std::map<Key, T, Compare, Allocator> const& ops) {
            auto s = ops.size();
            cAttr<Derived>(ops, "size", s, false, true);
            for(auto const& op : ops) {
                cAttr<Derived>(ops, "item", op, --s==0);
            }
        }

        template <typename Key, typename T, typename Compare, typename Allocator>
        void operator()(typename std::map<Key, T, Compare, Allocator>::value_type const& op) {
            cNode("Item", op);
            cAttr<Derived>(op, "key", op.first, false);
            cAttr<Derived>(op, "value", op.second, true);
        }

        template <typename... _Args>
        void operator()(boost::multi_index_container<_Args...>
                        const& ops) {
          auto s = ops.size();
          cAttr<Derived>(ops, "size", s, false, true);
          for(auto const& op : ops) {
              cAttr<Derived>(ops, "item", op, --s==0);
          }
        }

        template <typename T, std::size_t N, typename Allocator>
        void operator()(boost::container::small_vector<T, N, Allocator> const& ops) {
            auto s = ops.size();
            cAttr<Derived>(ops, "size", s, false, true);
            for(auto const& op : ops) {
                cAttr<Derived>(ops, "item", op, --s==0);
            }
        }

        template <typename T,
              typename std::enable_if<!is_variant<T>::value, bool>::type = false>
        void operator()(T const& ast) {
            cErrTypeAddr("not implemented", ast);
        }
    };

}

#endif //DUMP_FOREST_HPP

ext: hpp

max_stars_repo_name: cviebig/lib-dump

max_issues_repo_name: cviebig/lib-dump

max_forks_repo_name: cviebig/lib-dump


text:
/* Copyright 2003-2013 Joaquin M Lopez Munoz.
 * 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)
 *
 * See http://www.boost.org/libs/multi_index for library home page.
 */

#ifndef BOOST_MULTI_INDEX_DETAIL_INVARIANT_ASSERT_HPP
#define BOOST_MULTI_INDEX_DETAIL_INVARIANT_ASSERT_HPP

#if defined(_MSC_VER)
#pragma once
#endif

#if !defined(BOOST_MULTI_INDEX_INVARIANT_ASSERT)
#include <boost/assert.hpp>
#define BOOST_MULTI_INDEX_INVARIANT_ASSERT BOOST_ASSERT
#endif

#endif

max_stars_repo_name: sbrown-uhd/hazelcast-cpp-client

max_issues_repo_name: sbrown-uhd/hazelcast-cpp-client

max_forks_repo_name: sbrown-uhd/hazelcast-cpp-client


text:
#ifndef __ENV_METHOD_H__
#define __ENV_METHOD_H__

#include <vector>
#include <string>

#include <armadillo>

#include <plink/snp_row.hpp>
#include <shared_ptr/shared_ptr.hpp>
#include <besiq/method/method.hpp>

class genotype_matrix;
typedef shared_ptr<genotype_matrix> genotype_matrix_ptr;

class method_env_type
{
public:
    /**
     * Constructor.
     */
    method_env_type(method_data_ptr data)
        : m_data( data )
    {
    }

    /**
     * Returns the additional data.
     */
    method_data_ptr get_data()
    {
        return m_data;
    }

    virtual size_t num_usable_samples(const snp_row &row1)
    {
        unsigned int n = 0;
        for(int i = 0; i < row1.size( ); i++)
        {
            if( row1[ i ] != 3 && m_data->missing[ i ] == 0 )
            {
                n++;
            }
        }

        return n;
    }

    /**
     * Outputs the column names that will be
     * outputted by this method separated by '\t'.
     */
    virtual void init(std::ostream &output) = 0;

    /**
     * @param row The first genotype.
     * @param output The output stream
     */
    virtual void run(const snp_row &row, std::ostream &output) = 0;

private:
    /**
     * Additional data required by the method.
     */
    method_data_ptr m_data;
};

/**
 * Runs the given method on the genotype file, traversing
 * the given list of SNPs.
 *
 * @param method A method to run.
 * @param genotyeps Genotypes for all SNPs.
 */
void run_env_method(method_env_type &method, genotype_matrix_ptr genotypes);

#endif /* End of __ENV_METHOD_H__ */

max_stars_repo_name: hoehleatsu/besiq

max_issues_repo_name: hoehleatsu/besiq

max_forks_repo_name: hoehleatsu/besiq