text:
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <assert.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_integration.h>
#include <gsl/gsl_spline.h>
#include <gsl/gsl_sort.h>
#include <gsl/gsl_roots.h>
#include <gsl/gsl_sf_bessel.h>

#include "cosmocalc.h"
#include "weaklens.h"

double chiLim;

static void comp_lens_power_spectrum(lensPowerSpectra lps);

double lens_power_spectrum(double ell, lensPowerSpectra lps)
{
  if(lps->initFlag == 1 || lps->currCosmoNum != cosmoData.cosmoNum || lps->currWLNum != wlData.wlNum)
    {
      lps->initFlag = 0;
      lps->currCosmoNum = cosmoData.cosmoNum;
      lps->currWLNum = wlData.wlNum;

      comp_lens_power_spectrum(lps);
    }

  return exp(gsl_spline_eval(lps->spline,log(ell),lps->accel));
}

double nonlinear_powspec_for_lens(double k, double a)
{
  return nonlinear_powspec(k,a);
}

static double lenskern(double chi, double chis)
{
  if(chi > chis)
    return 0.0;
  else
    return 1.5*cosmoData.OmegaM*(100.0/CSOL)*(100.0/CSOL)/acomvdist(chi)*(chis-chi)/chis;
}

static double lenspk_integrand(double chi, void *p)
{
  lensPowerSpectra lps = (lensPowerSpectra) p;
  double sn = lps->sn;

  if(chi == 0.0 || chi < chiLim)
    return 0.0;
  else
    return lenskern(chi,lps->chis1)*lenskern(chi,lps->chis2)*(nonlinear_powspec_for_lens(lps->ell/chi,acomvdist(chi)) + sn);
}

static void comp_lens_power_spectrum(lensPowerSpectra lps)
{
#define WORKSPACE_NUM 100000
#define ABSERR 1e-12
#define RELERR 1e-12
#define TABLE_LENGTH 1000

  gsl_integration_workspace *workspace;
  gsl_function F;
  double result,abserr;
  double logltab[TABLE_LENGTH];
  double logpkltab[TABLE_LENGTH];
  double chimax;
  int i;

  //fill in bin information
  chiLim = lps->chiLim;
  if(lps->chis1 > lps->chis2)
    chimax = lps->chis1;
  else
    chimax = lps->chis2;

  fprintf(stderr,"doing lens pk - chiLim = %lf, chiMax = %lf\n",chiLim,chimax);

  //init
  workspace = gsl_integration_workspace_alloc((size_t) WORKSPACE_NUM);
  F.function = &lenspk_integrand;
  F.params = lps;

  //make table
  double lnlmin = log(wlData.lmin);
  double lnlmax = log(wlData.lmax);
  for(i=0;i<TABLE_LENGTH;++i)
    {
      logltab[i] = i*(lnlmax-lnlmin)/(TABLE_LENGTH-1) + lnlmin;

      lps->ell = exp(logltab[i]);
      gsl_integration_qag(&F,0.0,chimax,ABSERR,RELERR,(size_t) WORKSPACE_NUM,GSL_INTEG_GAUSS51,workspace,&result,&abserr);

      logpkltab[i] = log(result);
    }

  //free
  gsl_integration_workspace_free(workspace);

  //init splines and accels
  if(lps->spline != NULL)
    gsl_spline_free(lps->spline);
  lps->spline = gsl_spline_alloc(gsl_interp_akima,(size_t) (TABLE_LENGTH));
  gsl_spline_init(lps->spline,logltab,logpkltab,(size_t) (TABLE_LENGTH));
  if(lps->accel != NULL)
    gsl_interp_accel_reset(lps->accel);
  else
    lps->accel = gsl_interp_accel_alloc();

#undef TABLE_LENGTH
#undef ABSERR
#undef RELERR
#undef WORKSPACE_NUM
}

lensPowerSpectra init_lens_power_spectrum(double zs1, double zs2)
{
  lensPowerSpectra lps;

  lps = (lensPowerSpectra)malloc(sizeof(_lensPowerSpectra));
  assert(lps != NULL);

  lps->initFlag = 1;
  lps->zs1 = zs1;
  lps->zs2 = zs2;
  lps->chis1 = comvdist(1.0/(1.0 + zs1));
  lps->chis2 = comvdist(1.0/(1.0 + zs2));
  lps->spline = NULL;
  lps->accel = NULL;

  return lps;
}

void free_lens_power_spectrum(lensPowerSpectra lps)
{
  if(lps->spline != NULL)
    gsl_spline_free(lps->spline);
  if(lps->accel != NULL)
    gsl_interp_accel_free(lps->accel);
  free(lps);
}

////////////////////////////////////////
// corr. funcs!
//////////////////////////////////////

static double lenscfp_integrand(double ell, void *p)
{
  lensCorrFunc lcf = (lensCorrFunc) p;

  return ell/2.0/M_PI*lens_power_spectrum(ell,lcf->lps)*gsl_sf_bessel_J0(ell*lcf->theta/60.0/180.0*M_PI);

}

static double lenscfm_integrand(double ell, void *p)
{
  lensCorrFunc lcf = (lensCorrFunc) p;

  return ell/2.0/M_PI*lens_power_spectrum(ell,lcf->lps)*gsl_sf_bessel_Jn(4,ell*lcf->theta/60.0/180.0*M_PI);
}

static void comp_lens_corr_funcs(lensCorrFunc lcf)
{
#define WORKSPACE_NUM 100000
#define ABSERR 1e-12
#define RELERR 1e-12
#define TABLE_LENGTH 1000

  gsl_integration_workspace *workspace;
  gsl_function F;
  double result,abserr;
  double logttab[TABLE_LENGTH];
  double logcfptab[TABLE_LENGTH];
  double logcfmtab[TABLE_LENGTH];
  int i;
  double lntmin;
  double lntmax;

  //init
  workspace = gsl_integration_workspace_alloc((size_t) WORKSPACE_NUM);
  F.params = lcf;
  lntmin = log(wlData.tmin);
  lntmax = log(wlData.tmax);

  //make tables
  F.function = &lenscfp_integrand;
  for(i=0;i<TABLE_LENGTH;++i)
    {
      logttab[i] = i*(lntmax-lntmin)/(TABLE_LENGTH-1) + lntmin;

      lcf->theta = exp(logttab[i]);
      gsl_integration_qag(&F,wlData.lmin,wlData.lmax,ABSERR,RELERR,(size_t) WORKSPACE_NUM,GSL_INTEG_GAUSS51,workspace,&result,&abserr);

      logcfptab[i] = log(result);
    }

  F.function = &lenscfm_integrand;
  for(i=0;i<TABLE_LENGTH;++i)
    {
      logttab[i] = i*(lntmax-lntmin)/(TABLE_LENGTH-1) + lntmin;

      lcf->theta = exp(logttab[i]);
      gsl_integration_qag(&F,wlData.lmin,wlData.lmax,ABSERR,RELERR,(size_t) WORKSPACE_NUM,GSL_INTEG_GAUSS51,workspace,&result,&abserr);

      logcfmtab[i] = log(result);
    }

  //free
  gsl_integration_workspace_free(workspace);

  //init splines and accels
  if(lcf->splineP != NULL)
    gsl_spline_free(lcf->splineP);
  lcf->splineP = gsl_spline_alloc(gsl_interp_akima,(size_t) (TABLE_LENGTH));
  gsl_spline_init(lcf->splineP,logttab,logcfptab,(size_t) (TABLE_LENGTH));
  if(lcf->accelP != NULL)
    gsl_interp_accel_reset(lcf->accelP);
  else
    lcf->accelP = gsl_interp_accel_alloc();

  if(lcf->splineM != NULL)
    gsl_spline_free(lcf->splineM);
  lcf->splineM = gsl_spline_alloc(gsl_interp_akima,(size_t) (TABLE_LENGTH));
  gsl_spline_init(lcf->splineM,logttab,logcfmtab,(size_t) (TABLE_LENGTH));
  if(lcf->accelM != NULL)
    gsl_interp_accel_reset(lcf->accelM);
  else
    lcf->accelM = gsl_interp_accel_alloc();

#undef TABLE_LENGTH
#undef ABSERR
#undef RELERR
#undef WORKSPACE_NUM
}

double lens_corr_func_minus(double theta, lensCorrFunc lcf)
{
  if(lcf->initFlag == 1 || lcf->currCosmoNum != cosmoData.cosmoNum || lcf->currWLNum != wlData.wlNum)
    {
      lcf->initFlag = 0;
      lcf->currCosmoNum = cosmoData.cosmoNum;
      lcf->currWLNum = wlData.wlNum;

      comp_lens_corr_funcs(lcf);
    }

  return exp(gsl_spline_eval(lcf->splineM,log(theta),lcf->accelM));
}

double lens_corr_func_plus(double theta, lensCorrFunc lcf)
{
  if(lcf->initFlag == 1 || lcf->currCosmoNum != cosmoData.cosmoNum || lcf->currWLNum != wlData.wlNum)
    {
      lcf->initFlag = 0;
      lcf->currCosmoNum = cosmoData.cosmoNum;
      lcf->currWLNum = wlData.wlNum;

      comp_lens_corr_funcs(lcf);
    }

  return exp(gsl_spline_eval(lcf->splineP,log(theta),lcf->accelP));
}

lensCorrFunc init_lens_corr_func(lensPowerSpectra lps)
{
  lensCorrFunc lcf;

  lcf = (lensCorrFunc)malloc(sizeof(_lensCorrFunc));
  assert(lcf != NULL);

  lcf->initFlag = 1;
  lcf->lps = lps;
  lcf->splineM = NULL;
  lcf->accelM = NULL;
  lcf->splineP = NULL;
  lcf->accelP = NULL;

  return lcf;
}

void free_lens_corr_func(lensCorrFunc lcf)
{
  if(lcf->splineM != NULL)
    gsl_spline_free(lcf->splineM);
  if(lcf->accelM != NULL)
    gsl_interp_accel_free(lcf->accelM);

  if(lcf->splineP != NULL)
    gsl_spline_free(lcf->splineP);
  if(lcf->accelP != NULL)
    gsl_interp_accel_free(lcf->accelP);

  free(lcf);
}

ext: c

max_stars_repo_name: beckermr/cosmocalc

max_issues_repo_name: beckermr/cosmocalc

max_forks_repo_name: beckermr/cosmocalc


text:
/**
 *
 * @file qwrapper_spotrf.c
 *
 *  PLASMA core_blas quark wrapper
 *  PLASMA is a software package provided by Univ. of Tennessee,
 *  Univ. of California Berkeley and Univ. of Colorado Denver
 *
 * @version 2.6.0
 * @author Hatem Ltaief
 * @author Mathieu Faverge
 * @author Jakub Kurzak
 * @date 2010-11-15
 * @generated s Tue Jan  7 11:44:56 2014
 *
 **/
#include <lapacke.h>
#include "common.h"

/***************************************************************************//**
 *
 **/
void QUARK_CORE_slauum(Quark *quark, Quark_Task_Flags *task_flags,
                       PLASMA_enum uplo, int n, int nb,
                       float *A, int lda)
{
    DAG_CORE_LAUUM;
    QUARK_Insert_Task(quark, CORE_slauum_quark, task_flags,
        sizeof(PLASMA_enum),                &uplo,  VALUE,
        sizeof(int),                        &n,     VALUE,
        sizeof(float)*nb*nb,    A,             INOUT,
        sizeof(int),                        &lda,   VALUE,
        0);
}

/***************************************************************************//**
 *
 **/
#if defined(PLASMA_HAVE_WEAK)
#pragma weak CORE_slauum_quark = PCORE_slauum_quark
#define CORE_slauum_quark PCORE_slauum_quark
#endif
void CORE_slauum_quark(Quark *quark)
{
    PLASMA_enum uplo;
    int N;
    float *A;
    int LDA;

    quark_unpack_args_4(quark, uplo, N, A, LDA);
    LAPACKE_slauum_work(LAPACK_COL_MAJOR, lapack_const(uplo), N, A, LDA);
}


text:
#ifndef AMICI_MISC_H
#define AMICI_MISC_H

#include "amici/defines.h"
#include <sunmatrix/sunmatrix_sparse.h> // SUNMatrixContent_Sparse

#include <algorithm>
#include <vector>
#include <memory>
#include <regex>

#include <gsl/gsl-lite.hpp>

namespace amici {

/**
 * @brief creates a slice from existing data
 *
 * @param data to be sliced
 * @param index slice index
 * @param size slice size
 * @return span of the slice
 */

 gsl::span<realtype> slice(std::vector<realtype> &data, int index,
                           unsigned size);

/**
  * @brief Remove parameter scaling according to the parameter scaling in pscale
  *
  * All vectors must be of same length.
  *
  * @param bufferScaled scaled parameters
  * @param pscale parameter scaling
  * @param bufferUnscaled unscaled parameters are written to the array
  */
void unscaleParameters(gsl::span<const realtype> bufferScaled,
                       gsl::span<const ParameterScaling> pscale,
                       gsl::span<realtype> bufferUnscaled);

/**
  * @brief Remove parameter scaling according to `scaling`
  *
  * @param scaledParameter scaled parameter
  * @param scaling parameter scaling
  *
  * @return Unscaled parameter
  */
double getUnscaledParameter(double scaledParameter, ParameterScaling scaling);

/**
 * @brief Apply parameter scaling according to `scaling`
 * @param unscaledParameter
 * @param scaling parameter scaling
 * @return Scaled parameter
 */
double getScaledParameter(double unscaledParameter, ParameterScaling scaling);

/**
 * @brief Apply parameter scaling according to `scaling`
 * @param bufferUnscaled
 * @param pscale parameter scaling
 * @param bufferScaled destination
 */
void scaleParameters(gsl::span<const realtype> bufferUnscaled,
                     gsl::span<const ParameterScaling> pscale,
                     gsl::span<realtype> bufferScaled);

/**
 * @brief Returns the current backtrace as std::string
 * @param maxFrames Number of frames to include
 * @return Backtrace
 */
std::string backtraceString(int maxFrames);

/**
 * @brief Convert std::regex_constants::error_type to string
 * @param err_type error type
 * @return Error type as string
 */
std::string regexErrorToString(std::regex_constants::error_type err_type);

/**
 * @brief Format printf-style arguments to std::string
 * @param fmt Format string
 * @param ap Argument list pointer
 * @return Formatted String
 */
std::string printfToString(const char *fmt, va_list ap);

} // namespace amici

#ifndef __cpp_lib_make_unique
// custom make_unique while we are still using c++11
namespace std {
template<typename T, typename... Args>
std::unique_ptr<T> make_unique(Args&&... args)
{
    return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
}
}
#endif

#endif // AMICI_MISC_H

ext: h

max_stars_repo_name: paszkow/AMICI

max_issues_repo_name: paszkow/AMICI

max_forks_repo_name: paszkow/AMICI


text:
#if !defined(FINDFILEEXT_H_INCLUDED)
#define FINDFILEEXT_H_INCLUDED

#include "FileEnumerator.h"
#include "Utils.h"

#include <filesystem>
#include <gsl/gsl>
#include <iosfwd>
#include <map>
#include <string>
#include <vector>

class FindFileExt
{
public:
	static int usage(::std::ostream& strm, const ::std::string& progName,
		const char* pMsg);

	FindFileExt(::gsl::span<const char*const> args);
	int run();

	FindFileExt(const FindFileExt&) = delete;
	FindFileExt& operator=(const FindFileExt&) = delete;
	FindFileExt(FindFileExt&&) = delete;
	FindFileExt& operator=(FindFileExt&&) = delete;

PRIVATE_EXCEPT_IN_TEST:
	using Path = ::std::filesystem::path;
	using StrToCountMap = ::std::map< ::std::string, size_t >;
	using PathList = ::std::vector<Path>;

	void countFiles();
	void reportExtension(const StrToCountMap::value_type& extToCountMapping);

	bool				m_includeCounts;
	bool				m_outputAsWildcards;
	FileEnumerator	m_fileEnumerator;
	StrToCountMap	m_extToCountMap;
	PathList			m_noExtList;
};

#endif // FINDFILEEXT_H_INCLUDED

max_stars_repo_name: IanEmmons/CmdLineUtil

max_issues_repo_name: IanEmmons/CmdLineUtil

max_forks_repo_name: IanEmmons/CmdLineUtil


text:
/* min/convergence.c
 *
 * Copyright (C) 1996, 1997, 1998, 1999, 2000 Brian Gough
 *
 * This program 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 2 of the License, or (at
 * your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 */

#include <config.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_min.h>

int
gsl_min_test_interval (double x_lower, double x_upper, double epsabs, double epsrel)
{
  const double lower = x_lower;
  const double upper = x_upper;

  const double abs_lower = fabs(lower) ;
  const double abs_upper = fabs(upper) ;

  double min_abs, tolerance;

  if (epsrel < 0.0)
    GSL_ERROR ("relative tolerance is negative", GSL_EBADTOL);

  if (epsabs < 0.0)
    GSL_ERROR ("absolute tolerance is negative", GSL_EBADTOL);

  if (lower > upper)
    GSL_ERROR ("lower bound larger than upper_bound", GSL_EINVAL);

  if ((lower > 0 && upper > 0) || (lower < 0 && upper < 0))
    {
      min_abs = GSL_MIN_DBL(abs_lower, abs_upper) ;
    }
  else
    {
      min_abs = 0;
    }

  tolerance = epsabs + epsrel * min_abs  ;

  if (fabs(upper - lower) < tolerance)
    return GSL_SUCCESS;

  return GSL_CONTINUE ;
}

max_stars_repo_name: manggoguy/parsec-modified

max_issues_repo_name: manggoguy/parsec-modified

max_forks_repo_name: manggoguy/parsec-modified


text:
// Copyright (C) 2021 Intel Corporation
// SPDX-License-Identifier: Apache-2.0

#ifndef _HEBench_ClearText_EltMult_H_7e5fa8c2415240ea93eff148ed73539b
#define _HEBench_ClearText_EltMult_H_7e5fa8c2415240ea93eff148ed73539b

#include <gsl/gsl>

#include "hebench/api_bridge/cpp/hebench.hpp"

#include "clear_benchmark.h"

template <class T>
class EltMult_Benchmark : public ClearTextBenchmark
{
private:
    HEBERROR_DECLARE_CLASS_NAME(EltMult_Benchmark)

public:
    EltMult_Benchmark(hebench::cpp::BaseEngine &engine,
                      const hebench::APIBridge::BenchmarkDescriptor &bench_desc,
                      const hebench::APIBridge::WorkloadParams &bench_params);
    ~EltMult_Benchmark() override;

    hebench::APIBridge::Handle encode(const hebench::APIBridge::DataPackCollection *p_parameters) override;
    void decode(hebench::APIBridge::Handle encoded_data, hebench::APIBridge::DataPackCollection *p_native) override;

    hebench::APIBridge::Handle load(const hebench::APIBridge::Handle *p_local_data, std::uint64_t count) override;
    void store(hebench::APIBridge::Handle remote_data,
               hebench::APIBridge::Handle *p_local_data, std::uint64_t count) override;

    hebench::APIBridge::Handle operate(hebench::APIBridge::Handle h_remote_packed,
                                       const hebench::APIBridge::ParameterIndexer *p_param_indexers) override;

protected:
    std::uint64_t m_vector_size;

private:
    static void eltMult(gsl::span<T> &result,
                        const gsl::span<const T> &V0, const gsl::span<const T> &V1,
                        std::size_t element_count);
};

#include "inl/bench_eltmult.inl"

#endif // defined _HEBench_ClearText_EltMult_H_7e5fa8c2415240ea93eff148ed73539b

max_stars_repo_name: hebench/backend-cpu-cleartext

max_issues_repo_name: hebench/backend-cpu-cleartext

max_forks_repo_name: hebench/backend-cpu-cleartext


text:
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <string.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_spline.h>

int i;
int max_lines=30;
double xi, yi, x[30], y[30];

const char* getfield(char* line, int num)
{
    const char* tok;
    for (tok = strtok(line, ",");
            tok && *tok;
            tok = strtok(NULL, ";\n"))
    {
        if (!--num)
            return tok;
    }
    return NULL;
}

void read_csv(char* filename, int max_lines){
  FILE * f = fopen(filename, "r");
  char line[1024];
  int l = 0;
  fgets(line, 1024, f);
  while(fgets(line, 1024, f)){
    char* tmp = strdup(line);
    double y_tmp = atof(getfield(tmp, 2));
    double x_tmp = atof(getfield(tmp, 1));
    if(l < max_lines){
      x[l] = x_tmp;
      y[l] = y_tmp;
    }
    l++;

    free(tmp);
  }
}

int
main (void)
{
  read_csv("secret_fun.csv", max_lines);

  // printf ("#m=0,S=17\n");
  //
  // for (i = 0; i < max_lines; i++)
  //   {
  //     // x[i] = i + 0.5 * sin (i);
  //     // y[i] = i + cos (i * i);
  //     printf ("%f %f \n", x[i], y[i]);
  //   }

  // printf ("#m=1,S=0\n");
  //
  {
    gsl_interp_accel *acc
      = gsl_interp_accel_alloc ();
    gsl_spline *spline
      = gsl_spline_alloc (gsl_interp_cspline, 30);

    gsl_spline_init (spline, x, y, 30);

    printf("x,y\n" );
    for (xi = x[0]; xi < x[29]; xi += 0.01)
      {
        printf("%g, ", xi);
        yi = gsl_spline_eval (spline, xi, acc);
        printf ("%g\n", yi);
      }
    gsl_spline_free (spline);
    gsl_interp_accel_free (acc);
  }
  return 0;
}


text:
#include "../EngineTest.h"

#include <Catch2>

#include <gsl/gsl_math.h>

TEST_CASE("Skew Function Evaluation Tests", "[skew]") {

    // SECTION("Empty Test"){
    //     requireIsEqual("skew()", "Insufficient Number of Arguments for Function: skew");
    // }

    SECTION("`skew` Test 1"){
        requireIsEqual("skew(-7.48, 1.3, -6.68, 7.61, -3.75)", 0.4478899957);
    }

    SECTION("`skew` Test 2"){
        requireIsEqual("skew(-9.79, 6.39, -2.51, 5.03, -7.83, -5.82, 5.14)", 0.0115605537);
    }

    SECTION("`skew` Test 3"){
        requireIsEqual("skew(-8.75, -8.67, 6.72, -4.01, -0.14, -2.32, 7.62, -7.36, 9.19)", 0.2380296624);
    }

    SECTION("`skew` Test 4"){
        requireIsEqual("skew(8.28, -5.77, -5.76)", 0.3848995209);
    }

    SECTION("`skew` Test 5"){
        requireIsEqual("skew(-7.03, 4.48, -2.21, 6.56, -3.27, 6.23, -3.57, 9.99, 0.48)", 0.0727451398);
    }

    SECTION("`skew` Test 6"){
        requireIsEqual("skew(-5.52, -5.18, -0.97, -0.07)", 0.0281579987);
    }

    SECTION("`skew` Test 7"){
        requireIsEqual("skew(5.24, -9.46, 1.35, -5.8, 4.4, 3.6)", -0.5210503622);
    }

    SECTION("`skew` Test 8"){
        requireIsEqual("skew(4.94, -2.29, 7.81, 8.51, -5.59, -6.55, 5.24)", -0.2249073199);
    }

    SECTION("`skew` Test 9"){
        requireIsEqual("skew(-3.73, -9.06, -4.36, 6.63, -4.59)", 0.6907748203);
    }

    SECTION("`skew` Test 10"){
        requireIsEqual("skew(-5.79, -1.84, -6.12, -5.07, -2.07, -3.48, 9.85, -6.41)", 1.4695482561);
    }

}

max_stars_repo_name: antoniojkim/CalcPlusPlus

max_issues_repo_name: antoniojkim/CalcPlusPlus

max_forks_repo_name: antoniojkim/CalcPlusPlus


text:
#pragma once

#include <gsl/span>

namespace CesiumUtility {
/**
 * @brief This function converts between span types. This function
 * has the same rules with C++ reintepret_cast
 * https://en.cppreference.com/w/cpp/language/reinterpret_cast. So please use it
 * carefully
 */
template <typename To, typename From>
gsl::span<To> reintepretCastSpan(const gsl::span<From>& from) noexcept {
  return gsl::span<To>(
      reinterpret_cast<To*>(from.data()),
      from.size() * sizeof(From) / sizeof(To));
}
} // namespace CesiumUtility

max_stars_repo_name: yieryi/cesium-native

max_issues_repo_name: yieryi/cesium-native

max_forks_repo_name: yieryi/cesium-native


text:
#pragma once
#include "iparamlist.h"
#include "optioninfo.h"
#include "configaccess.h"
#include "format.h"
#include "streamreader.h"
#include <sfun/string_utils.h>
#include <cmdlime/errors.h>
#include <cmdlime/customnames.h>
#include <gsl/gsl>
#include <vector>
#include <sstream>
#include <functional>
#include <memory>

namespace cmdlime::detail{
namespace str = sfun::string_utils;

template <typename T>
class ParamList : public IParamList{
public:
    ParamList(std::string name,
              std::string shortName,
              std::string type,
              std::function<std::vector<T>&()> paramListGetter)
        : info_(std::move(name), std::move(shortName), std::move(type))
        , paramListGetter_(std::move(paramListGetter))
    {
    }

    void setDefaultValue(const std::vector<T>& value)
    {
        hasValue_ = true;
        defaultValue_ = value;
    }

    OptionInfo& info() override
    {
        return info_;
    }

    const OptionInfo& info() const override
    {
        return info_;
    }

private:
    bool read(const std::string& data) override
    {
        if (!isDefaultValueOverwritten_){
            paramListGetter_().clear();
            isDefaultValueOverwritten_ = true;
        }

        const auto dataParts = str::split(data, ",");
        for (const auto& part : dataParts){
            auto stream = std::stringstream{part};
            paramListGetter_().emplace_back();
            if (!readFromStream(stream, paramListGetter_().back()))
                return false;
        }
        hasValue_ = true;
        return true;
    }

    bool hasValue() const override
    {
        return hasValue_;
    }

    bool isOptional() const override
    {
        return defaultValue_.has_value();
    }

    std::string defaultValue() const override
    {
        if (!defaultValue_.has_value())
            return {};
        auto stream = std::stringstream{};
        stream << "{";
        auto firstVal = true;
        for (auto& val : defaultValue_.value()){
            if (firstVal)
                stream << val;
            else
                stream << ", " << val;
            firstVal = false;
        }
        stream << "}";
        return stream.str();
    }

private:
    OptionInfo info_;
    std::function<std::vector<T>&()> paramListGetter_;
    bool hasValue_ = false;
    std::optional<std::vector<T>> defaultValue_;
    bool isDefaultValueOverwritten_ = false;
};

template <>
inline bool ParamList<std::string>::read(const std::string& data)
{
    const auto dataParts = str::split(data, ",");
    for (const auto& part : dataParts){
        paramListGetter_().push_back(part);
    }
    hasValue_ = true;
    return true;
}

template<typename T, typename TConfig>
class ParamListCreator{
    using NameProvider = typename Format<ConfigAccess<TConfig>::format()>::nameProvider;

public:
    ParamListCreator(TConfig& cfg,
                   const std::string& varName,
                   const std::string& type,
                   std::function<std::vector<T>&()> paramListGetter)
        : cfg_(cfg)
    {
        Expects(!varName.empty());
        Expects(!type.empty());
        paramList_ = std::make_unique<ParamList<T>>(NameProvider::name(varName),
                                                    NameProvider::shortName(varName),
                                                    NameProvider::valueName(type),
                                                    std::move(paramListGetter));
    }

    ParamListCreator<T, TConfig>& operator<<(const std::string& info)
    {
        paramList_->info().addDescription(info);
        return *this;
    }

    ParamListCreator<T, TConfig>& operator<<(const Name& customName)
    {
        paramList_->info().resetName(customName.value());
        return *this;
    }

    ParamListCreator<T, TConfig>& operator<<(const ShortName& customName)
    {
        static_assert(Format<ConfigAccess<TConfig>::format()>::shortNamesEnabled,
                      "Current command line format doesn't support short names");
        paramList_->info().resetShortName(customName.value());
        return *this;
    }

    ParamListCreator<T, TConfig>& operator<<(const WithoutShortName&)
    {
        static_assert(Format<ConfigAccess<TConfig>::format()>::shortNamesEnabled,
                      "Current command line format doesn't support short names");
        paramList_->info().resetShortName({});
        return *this;
    }

    ParamListCreator<T, TConfig>& operator<<(const ValueName& valueName)
    {
        paramList_->info().resetValueName(valueName.value());
        return *this;
    }

    ParamListCreator<T, TConfig>& operator()(std::vector<T> defaultValue = {})
    {
        defaultValue_ = std::move(defaultValue);
        paramList_->setDefaultValue(defaultValue_);
        return *this;
    }

    operator std::vector<T>()
    {
        ConfigAccess<TConfig>{cfg_}.addParamList(std::move(paramList_));
        return defaultValue_;
    }

private:
    std::unique_ptr<ParamList<T>> paramList_;
    std::vector<T> defaultValue_;
    TConfig& cfg_;
};

template <typename T, typename TConfig>
ParamListCreator<T, TConfig> makeParamListCreator(TConfig& cfg,
                                                  const std::string& varName,
                                                  const std::string& type,
                                                  std::function<std::vector<T>&()> paramListGetter)
{
    return ParamListCreator<T, TConfig>{cfg, varName, type, std::move(paramListGetter)};
}

}

max_stars_repo_name: GerHobbelt/hypertextcpp

max_issues_repo_name: GerHobbelt/hypertextcpp

max_forks_repo_name: GerHobbelt/hypertextcpp