text:
#ifndef _TEST_H_
#define _TEST_H_

#define _GNU_SOURCE

#include <time.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <float.h>
#include <string.h>
#include <omp.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_spline.h>
#include <gsl/gsl_interp2d.h>
#include <gsl/gsl_spline2d.h>
#include <gsl/gsl_sf_bessel.h>
#include <gsl/gsl_sf_legendre.h>
#include <gsl/gsl_integration.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_linalg.h>
#include <gsl/gsl_blas.h>
#include <gsl/gsl_monte.h>
#include <gsl/gsl_monte_vegas.h>
#include <gsl/gsl_odeiv2.h>
#include <gsl/gsl_roots.h>
#include <gsl/gsl_sf_expint.h>
#include <ctype.h>
#include "cuba.h"

#define PSC             101L
#define ST              102L
#define TK              103L

#define CO10            131L
#define CO21            132L
#define CO32            133L
#define CO43            134L
#define CO54            135L
#define CO65            136L
#define CII             137L

#define NPARS     6

extern struct globals gb;

#include "../Class/include/class.h"
#include "global_structs.h"
#include "cosmology.h"

typedef struct initialize_struct{
      double Mh_min;
      long   mode_mf;
      size_t ninterp;
      int    nlines;
      int    lines[7];
}initialize_struct;

void initialize(char *argv[], struct initialize_struct *init_struct);
void  cleanup();

int Cosmology_init(struct Cosmology *Cx, double pk_kmax, double pk_zmax,
            int nlines, int * line_types, size_t npoints_interp, double M_min, long mode_mf);

double PS_line_HM(struct Cosmology *Cx, double k, double z, double M_min, long mode_mf,  long line_type, int line_id);
double PS_shot_HM(struct Cosmology *Cx, double k, double z, double M_min, double *input, long mode_mf, long line_type, int line_id);
double b22_ls(struct Cosmology *Cx, double z);

double PS_shot(struct Cosmology *Cx, double z, size_t line_id);
double Tbar_line(struct Cosmology *Cx, size_t line_id, double z);
void   line_bias(struct Line *Lx, double z, double *result);

double rhoc(struct Cosmology *Cx, double z);

#endif

max_stars_repo_name: amoradinejad/limHaloPT

max_issues_repo_name: amoradinejad/limHaloPT

max_forks_repo_name: amoradinejad/limHaloPT


text:
/** \file
 * Analyze CSA output traces responding to pulses for ENC evaluation.
 */
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <math.h>
#include <string.h>
#include <unistd.h>

#include <gsl/gsl_histogram2d.h>

#include "common.h"
#include "filters.h"
#include "hdf5rawWaveformIo.h"
typedef SCOPE_DATA_TYPE IN_WFM_BASE_TYPE;
typedef SCOPE_DATA_TYPE OUT_WFM_BASE_TYPE;

/** Parameters settable from commandline */
typedef struct param
{
    size_t diffSep;  //!< rise-time in samples for pulse finding
    double riseFrac; //!< fraction of max pulse height for pulse edge location
    double fltM;     //!< exp decay constant for Trapezoidal filter
    size_t sPre;     //!< samples before rising edge
    size_t sLen;     //!< total number of samples of a pulse
    size_t sHscale;  //!< histogram sample scaling factor
} param_t;

param_t param_default = {
    .diffSep = 150,
    .riseFrac = 0.5,
    .fltM = -1.0,
    .sPre = 1000,
    .sLen = 4000,
    .sHscale = 4
};

void print_usage(const param_t *pm)
{
    printf("Usage:\n");
    printf("      -r rise time in samples[%zd]\n", pm->diffSep);
    printf("      -f riseFrac[%g]\n", pm->riseFrac);
    printf("      -m fltM[%g]\n", pm->fltM);
    printf("      -p sPre[%zd]\n", pm->sPre);
    printf("      -l sLen[%zd]\n", pm->sLen);
    printf("      -s iStart[0] -e iStop[-1] starting and stopping(+1) eventid\n");
    printf("      inFileName(.h5) outFileName\n");
}

/** Find pulses by their rising edges.
 *
 * @param[out] npulse number of pulses found
 * @param[in] fltH input waveform should be loaded into it already
 * @param[in] diffSep basically the rise time in samples
 * @param[in] riseFrac fraction of max pulse height to set pulse edge location
 * @param[in] M exp decay constant for Trapezoidal filter
 * @return the list of rising edge positions (times)
 */
size_t *find_pulses(size_t *npulse, filters_t *fltH, size_t diffSep, double riseFrac, double M)
{

    size_t n, nc = 1024;
    size_t *pulseRiseT = NULL, *pulseRiseT1;

    size_t flt_k = 2*diffSep, flt_l = 2*flt_k;
    double flt_M = M, max, dV;
    ssize_t i, j, sep, prev;

    if((pulseRiseT = calloc(nc, sizeof(size_t))) == NULL) {
        error_printf("calloc failed for pulseRiseT in %s()\n", __FUNCTION__);
        return NULL;
    }

    filters_trapezoidal(fltH, flt_k, flt_l, flt_M);

    max = 0.0;
    for(i=0; i<fltH->wavLen; i++)
        if(fltH->outWav[i] > max) max = fltH->outWav[i];

    sep = flt_k + flt_l;
    prev = 0;
    n = 0;
    for(i=0; i<fltH->wavLen; i++) {
        j = ((i+diffSep)>=fltH->wavLen)?(fltH->wavLen-1):(i+diffSep);
        dV = fltH->inWav[j] - fltH->inWav[i];
        if(dV > max * riseFrac) {
            if(i-prev > sep) {
                pulseRiseT[n] = j; n++;
                if(n >= nc) {
                    nc *= 2;
                    if((pulseRiseT1 = realloc(pulseRiseT, nc * sizeof(size_t))) == NULL) {
                        error_printf("realloc failed for pulseRiseT in %s()\n", __FUNCTION__);
                        *npulse = n;
                        return pulseRiseT;
                    }
                    pulseRiseT = pulseRiseT1;
                }
                prev = i;
            }
        }
    }
    *npulse = n;
    return pulseRiseT;
}

int main(int argc, char **argv)
{
    int optC = 0;
    param_t pm;

    char *inFileName, *outFileName;
    struct hdf5rawWaveformIo_waveform_file *inWfmFile;
    struct waveform_attribute inWfmAttr;
    struct hdf5rawWaveformIo_waveform_event inWfmEvent;
    IN_WFM_BASE_TYPE *inWfmBuf;
    // OUT_WFM_BASE_TYPE *outWfmBuf;
    filters_t *fltHdl;

    ssize_t iStart=0, iStop=-1, i, j, k, iCh;
    size_t nEventsInFile, chGrpLen, npulse, *pulseRiseT, nSep;
    unsigned int v, c;
    size_t chGrpIdx[SCOPE_NCH] = {0};
    double frameSize, val, sep, sepMu, sepSigma;

    gsl_histogram2d *wav2H, *flt2H;

    memcpy(&pm, &param_default, sizeof(pm));
    // parse switches
    while((optC = getopt(argc, argv, "e:f:l:m:p:r:s:")) != -1) {
        switch(optC) {
        case 'e':
            iStop = atoll(optarg);
            break;
        case 'f':
            pm.riseFrac = atof(optarg);
            break;
        case 'l':
            pm.sLen = atoll(optarg);
            break;
        case 'm':
            pm.fltM = atof(optarg);
            break;
        case 'p':
            pm.sPre = atoll(optarg);
            break;
        case 'r':
            pm.diffSep = atoll(optarg);
            break;
        case 's':
            iStart = atoll(optarg);
            break;
        default:
            print_usage(&pm);
            return EXIT_FAILURE;
            break;
        }
    }

    argc -= optind;
    argv += optind;
    if(argc<2 || argc>=3) {
        print_usage(&pm);
        return EXIT_FAILURE;
    }

    inFileName = argv[0];
    outFileName = argv[1];

    inWfmFile = hdf5rawWaveformIo_open_file_for_read(inFileName);
    hdf5rawWaveformIo_read_waveform_attribute_in_file_header(inWfmFile, &inWfmAttr);

    fprintf(stderr, "waveform_attribute:\n"
            "     chMask  = 0x%04x\n"
            "     nPt     = %zd\n"
            "     nFrames = %zd\n"
            "     dt      = %g\n"
            "     t0      = %g\n"
            "     ymult   = %g %g %g %g\n"
            "     yoff    = %g %g %g %g\n"
            "     yzero   = %g %g %g %g\n",
            inWfmAttr.chMask, inWfmAttr.nPt, inWfmAttr.nFrames, inWfmAttr.dt,
            inWfmAttr.t0, inWfmAttr.ymult[0], inWfmAttr.ymult[1], inWfmAttr.ymult[2],
            inWfmAttr.ymult[3], inWfmAttr.yoff[0], inWfmAttr.yoff[1],
            inWfmAttr.yoff[2], inWfmAttr.yoff[3], inWfmAttr.yzero[0],
            inWfmAttr.yzero[1], inWfmAttr.yzero[2], inWfmAttr.yzero[3]);

    nEventsInFile = hdf5rawWaveformIo_get_number_of_events(inWfmFile);
    fprintf(stderr, "Number of events in file: %zd\n", nEventsInFile);
    if(iStart < 0) iStart = 0;
    if(iStart >= nEventsInFile) iStart = nEventsInFile - 1;
    if(iStop < 0) iStop = nEventsInFile;
    if(iStop <= iStart) iStop = iStart + 1;

    if(inWfmAttr.nFrames > 0) {
        frameSize = inWfmAttr.nPt / (double)inWfmAttr.nFrames;
    } else {
        frameSize = (double)inWfmAttr.nPt;
    }

    v = inWfmAttr.chMask;
    for(c=0; v; c++) v &= v - 1;
    /* Brian Kernighan's way of counting bits */
    chGrpLen = inWfmFile->nCh / c;
    i=0;
    for(v=0; v<SCOPE_NCH; v++)
        if((inWfmAttr.chMask >> v) & 0x01) {
            chGrpIdx[i] = v;
            i++;
        }
    inWfmBuf = (IN_WFM_BASE_TYPE*)malloc(inWfmFile->nPt * inWfmFile->nCh * sizeof(IN_WFM_BASE_TYPE));
    inWfmEvent.wavBuf = inWfmBuf;

    fltHdl = filters_init(NULL, inWfmFile->nPt);
    wav2H = gsl_histogram2d_alloc(pm.sLen/pm.sHscale, 128);
    gsl_histogram2d_set_ranges_uniform(wav2H, -0.5 * inWfmAttr.dt, (pm.sLen+0.5) * inWfmAttr.dt,
        inWfmAttr.yzero[chGrpIdx[0]] + (-128.5 - inWfmAttr.yoff[chGrpIdx[0]]) * inWfmAttr.ymult[chGrpIdx[0]],
        inWfmAttr.yzero[chGrpIdx[0]] + ( 127.5 - inWfmAttr.yoff[chGrpIdx[0]]) * inWfmAttr.ymult[chGrpIdx[0]]);

    flt2H = gsl_histogram2d_alloc(pm.sLen/pm.sHscale, 256);
    gsl_histogram2d_set_ranges_uniform(flt2H, -0.5 * inWfmAttr.dt, (pm.sLen+0.5) * inWfmAttr.dt, -0.01, -0.01 + 256 * inWfmAttr.ymult[chGrpIdx[0]]);

    nSep = 0; sepMu = 0.0; sepSigma = 0.0;
    for(inWfmEvent.eventId = iStart; inWfmEvent.eventId < iStop; inWfmEvent.eventId++) {
        hdf5rawWaveformIo_read_event(inWfmFile, &inWfmEvent);
        for(iCh=0; iCh < 1 /* inWfmFile->nCh */; iCh++) {
            for(i=0; i<inWfmFile->nPt; i++) {
                val = (inWfmBuf[(size_t)(iCh * inWfmFile->nPt + i)]
                       - inWfmAttr.yoff[chGrpIdx[iCh]])
                    * inWfmAttr.ymult[chGrpIdx[iCh]]
                    + inWfmAttr.yzero[chGrpIdx[iCh]];

                fltHdl->inWav[i] = val;
            }
        }
        pulseRiseT = find_pulses(&npulse, fltHdl,
                                 pm.diffSep, pm.riseFrac, pm.fltM);
        fprintf(stderr, "eventId = %zd, npulse = %zd, first at %zd\n",
               inWfmEvent.eventId, npulse, pulseRiseT[0]);
        for(i=0; i<npulse-1; i++) {
            sep = pulseRiseT[i+1] - pulseRiseT[i];
            sepMu += sep;
            sepSigma += sep * sep;
            nSep++;
        }

        for(i=1; i<npulse-1; i++) {
            for(j=0; j<pm.sLen; j++) {
                k = pulseRiseT[i]-pm.sPre + j;
                gsl_histogram2d_increment(wav2H, j*inWfmAttr.dt, fltHdl->inWav[k]);
                gsl_histogram2d_increment(flt2H, j*inWfmAttr.dt, fltHdl->outWav[k]);
            }
        }
        free(pulseRiseT);
    }
    sepMu /= (double)nSep;
    sepSigma = sqrt(1.0/(double)(nSep-1) * (sepSigma - nSep * sepMu * sepMu));

    printf("nSep = %zd, sepMu = %g, sepSigma = %g\n", nSep, sepMu, sepSigma);

    FILE *ofp;
    if((ofp = fopen(outFileName, "w"))==NULL) {
        perror(outFileName);
        goto Exit;
    }
    gsl_histogram2d_fprintf(ofp, wav2H, "%24.16e", "%g");
    fprintf(ofp, "\n\n");
    gsl_histogram2d_fprintf(ofp, flt2H, "%24.16e", "%g");
    fprintf(ofp, "\n\n");

    fprintf(ofp, "# baseline distribution");
    double yl, yu;
    for(i=0; i<gsl_histogram2d_ny(wav2H); i++) {
        gsl_histogram2d_get_yrange(wav2H, i, &yl, &yu);
        fprintf(ofp, "%24.16e, %g\n", yl, gsl_histogram2d_get(wav2H, 0, i));
    }
    fprintf(ofp, "\n\n");

    fprintf(ofp, "# filtered distribution");
    for(i=0; i<gsl_histogram2d_ny(flt2H); i++) {
        gsl_histogram2d_get_yrange(flt2H, i, &yl, &yu);
        fprintf(ofp, "%24.16e, %g\n", yl,
                gsl_histogram2d_get(flt2H, (pm.sPre+3*pm.diffSep)/pm.sHscale, i));
    }

    fclose(ofp);

Exit:
    free(inWfmBuf); inWfmBuf = NULL;
    gsl_histogram2d_free(wav2H);
    gsl_histogram2d_free(flt2H);
    filters_close(fltHdl);
    hdf5rawWaveformIo_close_file(inWfmFile);

    return EXIT_SUCCESS;
}

ext: c


text:
/**
 * \author Sylvain Marsat, University of Maryland - NASA GSFC
 *
 * \brief C header for functions computing coeffcients of Not-A-Knot and Quadratic splines in matrix form.
 *
 */

#ifndef _FRESNEL_H
#define _FRESNEL_H

#define _XOPEN_SOURCE 500

#ifdef __GNUC__
#define UNUSED __attribute__ ((unused))
#else
#define UNUSED
#endif

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <complex.h>
#include <time.h>
#include <unistd.h>
#include <getopt.h>
#include <stdbool.h>
#include <string.h>

#include <gsl/gsl_errno.h>
#include <gsl/gsl_bspline.h>
#include <gsl/gsl_blas.h>
#include <gsl/gsl_min.h>
#include <gsl/gsl_spline.h>
#include <gsl/gsl_complex.h>

#include "constants.h"
#include "struct.h"

#if defined(__cplusplus)
#define complex _Complex
extern "C" {
#elif 0
} /* so that editors will match preceding brace */
#endif

double complex ComputeInt(
  gsl_matrix* splinecoeffsAreal,         /*  */
  gsl_matrix* splinecoeffsAimag,         /*  */
  gsl_matrix* splinecoeffsphase);        /*  */

double complex ComputeIntCase1a(
  const double complex* coeffsA,         /* */
  const double p1,                       /* */
  const double p2,                       /* */
  const double scale);                   /* */
double complex ComputeIntCase1b(
  const double complex* coeffsA,         /* */
  const double p1,                       /* */
  const double p2,                       /* */
  const double scale);                   /* */
double complex ComputeIntCase2(
  const double complex* coeffsA,         /* */
  const double p1,                       /* */
  const double p2);                      /* */
double complex ComputeIntCase3(
  const double complex* coeffsA,         /* */
  const double p1,                       /* */
  const double p2);                      /* */
double complex ComputeIntCase4(
  const double complex* coeffsA,         /* */
  const double p1,                       /* */
  const double p2);                      /* */

#if 0
{ /* so that editors will match succeeding brace */
#elif defined(__cplusplus)
}
#endif

#endif /* _FRESNEL_H */

ext: h

max_stars_repo_name: titodalcanton/flare

max_issues_repo_name: titodalcanton/flare

max_forks_repo_name: titodalcanton/flare


text:
#pragma once
// support functions for TString & c-string handling...
// v1.17

#include <tchar.h>
#include <cstdlib>
#include <codecvt>

#ifdef max
#undef max
#endif
#ifdef min
#undef min
#endif

#include <concepts>

#include <gsl/gsl>

// determine whether _Ty is a Number type (excluding char / wchar)
template<class _Ty>
struct is_Numeric
	: std::integral_constant<bool,
	(std::is_arithmetic_v<_Ty> || std::is_same_v<_Ty, std::byte> || std::is_enum_v<_Ty>)
	&& !std::is_same_v<_Ty, wchar_t>
	&& !std::is_same_v<_Ty, char>
	&& !std::is_pointer_v<_Ty>
	>
{
};

// determine whether T is a Number type (excluding char / wchar), same as is_Numeric<T>::value
template <typename T>
constexpr bool is_Numeric_v = is_Numeric<T>::value;

namespace std
{
	inline string to_string(const wstring& wstr)
	{
		//string str;
		//str.assign(wstr.begin(), wstr.end());
		//return str;

		using convert_type = std::codecvt_utf8<wchar_t>;
		std::wstring_convert<convert_type, wchar_t> converter;

		//use converter (.to_bytes: wstr->str, .from_bytes: str->wstr)
		return converter.to_bytes(wstr);
	}

	inline wstring to_wstring(const string& str)
	{
		wstring wstr;
		wstr.assign(str.begin(), str.end());
		return wstr;
	}

	inline string to_string(const std::byte& num)
	{
		return to_string(gsl::narrow_cast<uint8_t>(num));
	}

	inline wstring to_wstring(const std::byte& num)
	{
		return to_wstring(gsl::narrow_cast<uint8_t>(num));
	}
}

struct ci_char_traits
	: public std::char_traits<char>
{
	static char to_upper(char ch) noexcept
	{
		if (ch >= 'a' && ch <= 'z') return _toupper(ch);
		return ch;
	}
	static bool eq(char c1, char c2) noexcept
	{
		return to_upper(c1) == to_upper(c2);
	}
	static bool lt(char c1, char c2) noexcept
	{
		return to_upper(c1) < to_upper(c2);
	}
	static int compare(const char* s1, const char* s2, size_t n) noexcept
	{
		while (n-- != 0)
		{
			if (to_upper(*s1) < to_upper(*s2)) return -1;
			if (to_upper(*s1) > to_upper(*s2)) return 1;
			++s1; ++s2;
		}
		return 0;
	}
	static const char* find(const char* s, int n, char a) noexcept
	{
		if (s)
			for (auto const ua(to_upper(a)); (n != 0); ++s, --n)
			{
				if (to_upper(*s) == ua)
					return s;
			}
		return nullptr;
	}
};
struct ci_wchar_traits
	: public std::char_traits<wchar_t>
{
	static wchar_t to_upper(wchar_t ch) noexcept
	{
		if (ch >= L'a' && ch <= L'z') return _toupper(ch);
		return ch;
	}
	static bool eq(wchar_t c1, wchar_t c2) noexcept
	{
		return to_upper(c1) == to_upper(c2);
	}
	static bool lt(wchar_t c1, wchar_t c2) noexcept
	{
		return to_upper(c1) < to_upper(c2);
	}
	static int compare(const wchar_t* s1, const wchar_t* s2, size_t n) noexcept
	{
		while (n-- != 0)
		{
			if (to_upper(*s1) < to_upper(*s2)) return -1;
			if (to_upper(*s1) > to_upper(*s2)) return 1;
			++s1; ++s2;
		}
		return 0;
	}
	static const wchar_t* find(const wchar_t* s, int n, wchar_t a) noexcept
	{
		if (s)
			for (auto const ua(to_upper(a)); (n-- != 0); ++s)
			{
				if (to_upper(*s) == ua)
					return s;
			}
		return nullptr;
	}
};
using ci_stringview = std::basic_string_view<char, ci_char_traits>;
using ci_wstringview = std::basic_string_view<wchar_t, ci_wchar_traits>;

namespace details {
	template<class _Ty>
	struct is_pod
		: std::integral_constant<bool, std::is_standard_layout_v<_Ty>&& std::is_trivial_v<_Ty> >
	{
	};

	template <typename T>
	constexpr bool is_pod_v = is_pod<T>::value;

	template<typename T>
	concept IsPODText = std::is_same_v<std::remove_all_extents_t<std::remove_cv_t<std::remove_pointer_t<T>>>, char> || std::is_same_v<std::remove_all_extents_t<std::remove_cv_t<std::remove_pointer_t<T>>>, wchar_t>;

	template <class T>
	concept IsNumeric = is_Numeric_v<std::remove_cvref_t<T>>;

	template <class T>
	concept HasDataFunction = requires(T t)
	{
		t.data();
	};

	template <class T>
	concept HasChrFunction = requires(T t)
	{
		t.to_chr();
	};

	template <class T>
	concept HasSizeFunction = requires(T t)
	{
		static_cast<std::size_t>(t.size());
	};

	template <class T>
	concept HasDataSizeNoChr = HasDataFunction<T> && HasSizeFunction<T> && !HasChrFunction<T>;

	template <class T>
	concept HasDataSizeChr = HasDataFunction<T> && HasSizeFunction<T> && HasChrFunction<T>;

	constexpr WCHAR make_upper(const WCHAR c) noexcept
	{
		if (c >= L'a' && c <= L'z') return _toupper(c);
		return c;
	}
	constexpr char make_upper(const char c) noexcept
	{
		if (c >= 'a' && c <= 'z') return _toupper(c);
		return c;
	}
	constexpr bool CompareChar(const WCHAR c, const WCHAR other, const bool bCase) noexcept
	{
		return (bCase) ? c == other : make_upper(c) == make_upper(other);
	}
	constexpr bool CompareChar(const char c, const char other, const bool bCase) noexcept
	{
		return (bCase) ? c == other : make_upper(c) == make_upper(other);
	}

	template <typename Result, typename Format>
	Result& _ts_printf_do(Result& res, const Format& fmt)
	{
		res += fmt;
		return res;
	}

	template <typename Result, typename Format, typename Value, typename... Arguments>
	Result& _ts_printf_do(Result& res, const Format& fmt, const Value& val, Arguments&&... args)
	{
		auto i = 0U;
		auto bSkip = false;

		for (auto c = fmt[0]; c != decltype(c){'\0'}; c = fmt[++i])
		{
			if (!bSkip)
			{
				if (c == decltype(c){'\\'})
				{
					bSkip = true;
					continue;
				}
				else if (c == decltype(c){'%'})
				{
					if constexpr (is_Numeric_v<Value>)
					{
						if constexpr (std::is_same_v<std::string, std::remove_cv_t<Result>>)
							res += std::to_string(val);
						else if constexpr (std::is_same_v<std::wstring, std::remove_cv_t<Result>>)
							res += std::to_wstring(val);
						else
							res += val;	// assumes this type can handle adding numbers.
					}
					else
						res += val;

					if constexpr (std::is_array_v<Format> && details::is_pod_v<Format>)
						return _ts_printf_do(res, &fmt[0] + i + 1, args...);
					else
						return _ts_printf_do(res, fmt + i + 1, args...);
				}
			}
			else
				bSkip = false;
			res += c;
		}

		//// Ook: needs checked may need work
		//for (const auto &c: fmt)
		//{
		//	if (!bSkip)
		//	{
		//		if (c == decltype(c){'\\'})
		//		{
		//			bSkip = true;
		//			continue;
		//		}
		//		else if (c == decltype(c){'%'})
		//		{
		//			if constexpr (is_Numeric_v<Value>)
		//			{
		//				if constexpr (std::is_same_v<std::string, std::remove_cv_t<Result>>)
		//					res += std::to_string(val);
		//				else if constexpr (std::is_same_v<std::wstring, std::remove_cv_t<Result>>)
		//					res += std::to_wstring(val);
		//				else
		//					res += val;	// assumes this type can handle adding numbers.
		//			}
		//			else
		//				res += val;
		//			if constexpr (std::is_array_v<Format> && std::is_pod_v<Format>)
		//				return _ts_printf_do(res, &fmt[0] + i + 1, args...);
		//			else
		//				return _ts_printf_do(res, fmt + i + 1, args...);
		//		}
		//	}
		//	else
		//		bSkip = false;
		//	res += c;
		//}
		return res;
	}

	template<typename T, class TR = std::char_traits<T> >
	struct impl_strstr {
		using ptype = typename TR::char_type*;
		using cptype = typename const ptype;

		ptype operator()(ptype input, cptype find)
		{
			do {
				ptype p{}, q{};
				for (p = input, q = find; !TR::eq(*q, 0) && TR::eq(*p, *q); p++, q++) {}

				if (TR::eq(*q, 0))
					return input;

			} while (!TR::eq(*(input++), 0));
			return nullptr;
		}
	};

	//// Test if a string is empty, works for std::basic_string & TString objects
	//template <typename T>
	//std::enable_if_t<!std::is_pointer_v<T> && !std::is_pod_v<T> && std::is_member_function_pointer_v<decltype(&T::empty)>, bool> _ts_isEmpty(const T &str) noexcept
	//{
	//	return str.empty();
	//}
	//
	//// Test if a string is empty, works for C String char * or wchar_t *
	//template <typename T>
	//std::enable_if_t<std::is_pointer_v<T>, bool> _ts_isEmpty(const T &str) noexcept
	//{
	//	using value_type = std::remove_cv_t<std::remove_pointer_t<T> >;
	//
	//	static_assert(std::is_same_v<value_type, char> || std::is_same_v<value_type, wchar_t>, "Invalid Type used");
	//	return ((str == nullptr) || (str[0] == value_type()));
	//}
	//
	//// Test if a string is empty, works for C char or wchar_t
	//template <typename T>
	//std::enable_if_t<!std::is_pointer_v<T> && std::is_pod_v<T>, bool> _ts_isEmpty(const T &str) noexcept
	//{
	//	using value_type = std::remove_cv_t<T>;
	//
	//	static_assert(std::is_same_v<value_type, char> || std::is_same_v<value_type, wchar_t>, "Invalid Type used");
	//	return (str == value_type());
	//}

	template <typename T>
	bool _ts_isEmpty(const T& str) noexcept
	{
		if constexpr (std::is_pointer_v<T>)
		{
			// T is a pointer
			// Test if a string is empty, works for C String char * or wchar_t *
			using value_type = std::remove_cv_t<std::remove_pointer_t<T> >;

			static_assert(IsPODText<value_type>, "Invalid Type used");
			return ((str == nullptr) || (str[0] == value_type()));
		}
		else if constexpr (std::is_standard_layout_v<T> && std::is_trivial_v<T>) // same as old std::is_pod_v<T>
		{
			if constexpr (std::is_array_v<T>)
			{
				// T is NOT a pointer but IS POD and IS an array (char[3] ...)
				// Test if a string is empty, works for C char or wchar_t
				using value_type = std::remove_all_extents_t<std::remove_cv_t<T>>;

				static_assert(IsPODText<value_type>, "Invalid Type used");
				return (str[0] == value_type());
			}
			else {
				// T is NOT a pointer but IS POD and is NOT an array (single char ...)
				// Test if a string is empty, works for C char or wchar_t
				using value_type = std::remove_cv_t<T>;

				static_assert(IsPODText<value_type>, "Invalid Type used");
				return (str == value_type());
			}
		}
		else if constexpr (std::is_member_function_pointer_v<decltype(&T::empty)>)
		{
			// T is NOT a pointer and is NOT POD
			// Test if a container is empty, works for std::basic_string & TString objects or any container with an empty() member function.
			return str.empty();
		}
	}

	//// Get String length
	//template <typename T, typename size_type = std::size_t>
	//std::enable_if_t<std::is_pointer_v<T>, size_type> _ts_strlen(const T &str) noexcept
	//{
	//	using value_type = std::remove_cv_t<std::remove_pointer_t<T> >;
	//
	//	static_assert(std::is_same_v<value_type, char> || std::is_same_v<value_type, wchar_t>, "Invalid Type used");
	//	auto iLen = size_type();
	//	for (auto p = str; p && *p; ++p)
	//		++iLen;
	//	return iLen;
	//}
	//
	//template <typename T, typename size_type = std::size_t>
	//constexpr inline std::enable_if_t<!std::is_pointer_v<T> && std::is_same_v<std::remove_cv_t<T>, wchar_t>, size_type> _ts_strlen(const T &str) noexcept
	//{
	//	return (str == T() ? 0U : 1U);
	//}
	//
	//template <typename T, typename size_type = std::size_t>
	//constexpr inline std::enable_if_t<!std::is_pointer_v<T> && std::is_same_v<std::remove_cv_t<T>, char>, size_type> _ts_strlen(const T &str) noexcept
	//{
	//	return (str == T() ? 0U : 1U);
	//}
	//
	//template <typename T, typename size_type = std::size_t, std::size_t N>
	//constexpr inline size_type _ts_strlen(T const (&)[N]) noexcept
	//{
	//	return (N == 0U ? 0U : N - 1);
	//}
	//
	//template <typename T, typename size_type = T::size_type>
	//inline std::enable_if_t<!std::is_pointer_v<T> && std::is_member_function_pointer_v<decltype(&T::length)>, size_type> _ts_strlen(const T &str)
	//{
	//	return str.length();
	//}

	// Get String length
	template <typename T, IsNumeric size_type = std::size_t>
	constexpr size_type _ts_strlen(const T& str) noexcept
	{
		if constexpr (std::is_pointer_v<T>)
		{
			// T is a pointer
			//  return length of string...

			static_assert(IsPODText<T>, "Invalid Type used");
			auto iLen = size_type();
			for (auto p = str; p && *p; ++p)
				++iLen;
			return iLen;
		}
		else if constexpr (IsPODText<T>)
		{
			// T is POD, char or wchar_t
			// checks if char is zero or not
			return (str == T() ? 0U : 1U);
		}
		else if constexpr (std::is_member_function_pointer_v<decltype(&T::length)>)
		{
			// T has a member function length()
			return gsl::narrow_cast<size_type>(str.length());
		}
	}

	//template <typename T, typename size_type = std::size_t, std::size_t N>
	//constexpr inline size_type _ts_strlen(T const (&)[N]) noexcept
	//{
	//	// T is a fixed array
	//	return (N == 0U ? 0U : N - 1);
	//}

	template <IsPODText T, IsNumeric size_type = std::size_t, std::size_t N>
	constexpr inline size_type _ts_strlen(T const (&)[N]) noexcept
	{
		// T is a fixed array
		return (N == 0U ? 0U : N - 1);
	}

	template <typename T>
	struct _impl_strnlen {
	};
	template <>
	struct _impl_strnlen<char*> {
		size_t operator()(const char* const ptr, size_t length) noexcept
		{
			return strnlen(ptr, length);
		}
	};
	template <>
	struct _impl_strnlen<wchar_t*> {
		size_t operator()(const wchar_t* const ptr, size_t length) noexcept
		{
			return wcsnlen(ptr, length);
		}
	};
	template <>
	struct _impl_strnlen<char> {
		size_t operator()(const char& ptr, size_t length) noexcept
		{
			return (ptr == 0 || length == 0 ? 0U : 1U);
		}
	};
	template <>
	struct _impl_strnlen<wchar_t> {
		size_t operator()(const wchar_t& ptr, size_t length) noexcept
		{
			return (ptr == 0 || length == 0 ? 0U : 1U);
		}
	};

	template <typename T>
	struct _impl_strcpyn {
	};
	template <>
	struct _impl_strcpyn<char> {
		char* operator()(char* const pDest, const char* const pSrc, const size_t length) noexcept
		{
			//auto t = strncpy(pDest, pSrc, length);	// doesn't guarantee NULL termination!
			//if (t)
			//	t[length - 1] = 0;	// make sure it ends in NULL
			//return t;

			return lstrcpynA(pDest, pSrc, gsl::narrow_cast<int>(length));
		}
	};
	template <>
	struct _impl_strcpyn<wchar_t> {
		wchar_t* operator()(wchar_t* const pDest, const wchar_t* const pSrc, const size_t length) noexcept
		{
			//auto t = wcsncpy(pDest, pSrc, length); // doesn't guarantee NULL termination!
			//if (t)
			//	t[length - 1] = 0;	// make sure it ends in NULL
			//return t;

			return lstrcpynW(pDest, pSrc, gsl::narrow_cast<int>(length));
		}
	};

	template <typename T>
	struct _impl_strcpy {
	};
	template <>
	struct _impl_strcpy<char> {
		char* operator()(char* const pDest, const char* const pSrc) noexcept
		{
			return strcpy(pDest, pSrc);
		}
	};
	template <>
	struct _impl_strcpy<wchar_t> {
		wchar_t* operator()(wchar_t* const pDest, const wchar_t* const pSrc) noexcept
		{
			return wcscpy(pDest, pSrc);
		}
	};

	template <typename T>
	struct _impl_strncat {
	};
	template <>
	struct _impl_strncat<char> {
		char* operator()(char* const pDest, const char* const pSrc, const size_t length) noexcept
		{
			return strncat(pDest, pSrc, length);
		}
	};
	template <>
	struct _impl_strncat<wchar_t> {
		wchar_t* operator()(wchar_t* const pDest, const wchar_t* const pSrc, const size_t length) noexcept
		{
			return wcsncat(pDest, pSrc, length);
		}
	};

	template <typename T>
	struct _impl_strcat {
	};
	template <>
	struct _impl_strcat<char> {
		char* operator()(char* const pDest, const char* const pSrc) noexcept
		{
			return strcat(pDest, pSrc);
		}
	};
	template <>
	struct _impl_strcat<wchar_t> {
		wchar_t* operator()(wchar_t* const pDest, const wchar_t* const pSrc) noexcept
		{
			return wcscat(pDest, pSrc);
		}
	};

	template <typename T>
	struct _impl_strchr {
	};
	template <>
	struct _impl_strchr<char> {
		char* operator()(char* const pString, const char ch)
		{
			return strchr(pString, ch);
		}
	};
	template <>
	struct _impl_strchr<wchar_t> {
		wchar_t* operator()(wchar_t* const pString, const wchar_t ch)
		{
			return wcschr(pString, ch);
		}
	};

	template <typename T>
	struct _impl_strncmp {
	};
	template <>
	struct _impl_strncmp<char> {
		int operator()(const char* const pDest, const char* const pSrc, const size_t length) noexcept
		{
			return strncmp(pDest, pSrc, length);
		}
	};
	template <>
	struct _impl_strncmp<wchar_t> {
		int operator()(const wchar_t* const pDest, const wchar_t* const pSrc, const size_t length) noexcept
		{
			return wcsncmp(pDest, pSrc, length);
		}
	};

	template <typename T>
	struct _impl_strnicmp {
	};
	template <>
	struct _impl_strnicmp<char> {
		int operator()(const char* const pDest, const char* const pSrc, const size_t length) noexcept
		{
			return _strnicmp(pDest, pSrc, length);
		}
	};
	template <>
	struct _impl_strnicmp<wchar_t> {
		int operator()(const wchar_t* const pDest, const wchar_t* const pSrc, const size_t length) noexcept
		{
			return _wcsnicmp(pDest, pSrc, length);
		}
	};

	template <typename T>
	struct _impl_strcmp {
	};
	template <>
	struct _impl_strcmp<char> {
		int operator()(const char* const pDest, const char* const pSrc) noexcept
		{
			return strcmp(pDest, pSrc);
		}
	};
	template <>
	struct _impl_strcmp<wchar_t> {
		int operator()(const wchar_t* const pDest, const wchar_t* const pSrc) noexcept
		{
			return wcscmp(pDest, pSrc);
		}
	};

	template <typename T>
	struct _impl_stricmp {
	};
	template <>
	struct _impl_stricmp<char> {
		int operator()(const char* const pDest, const char* const pSrc) noexcept
		{
			return _stricmp(pDest, pSrc);
		}
	};
	template <>
	struct _impl_stricmp<wchar_t> {
		int operator()(const wchar_t* const pDest, const wchar_t* const pSrc) noexcept
		{
			return _wcsicmp(pDest, pSrc);
		}
	};

	template <typename T>
	struct _impl_ts_find {
	};
	template <>
	struct _impl_ts_find<char> {
		const char* operator()(const char* const str, const char& srch) noexcept
		{
			return strchr(str, srch);
		}
	};
	template <>
	struct _impl_ts_find<const char> {
		const char* operator()(const char* const str, const char& srch) noexcept
		{
			return strchr(str, srch);
		}
	};
	template <>
	struct _impl_ts_find<char*> {
		const char* operator()(const char* const str, const char* srch) noexcept
		{
			return strstr(str, srch);
		}
	};
	template <>
	struct _impl_ts_find<const char*> {
		const char* operator()(const char* const str, const char* srch) noexcept
		{
			return strstr(str, srch);
		}
	};
	template <>
	struct _impl_ts_find<wchar_t> {
		const wchar_t* operator()(const wchar_t* const str, const wchar_t& srch) noexcept
		{
			return wcschr(str, srch);
		}
	};
	template <>
	struct _impl_ts_find<const wchar_t> {
		const wchar_t* operator()(const wchar_t* const str, const wchar_t& srch) noexcept
		{
			return wcschr(str, srch);
		}
	};
	template <>
	struct _impl_ts_find<wchar_t*> {
		const wchar_t* operator()(const wchar_t* const str, const wchar_t* srch) noexcept
		{
			return wcsstr(str, srch);
		}
	};
	template <>
	struct _impl_ts_find<const wchar_t*> {
		const wchar_t* operator()(const wchar_t* const str, const wchar_t* srch) noexcept
		{
			return wcsstr(str, srch);
		}
	};

	template <typename T>
	struct _impl_vscprintf {
	};
	template <>
	struct _impl_vscprintf<char> {
		const int operator()(const char* const fmt, const va_list args) noexcept
		{
			return _vscprintf(fmt, args);
		}
	};
	template <>
	struct _impl_vscprintf<wchar_t> {
		const int operator()(const wchar_t* const fmt, const va_list args) noexcept
		{
			return _vscwprintf(fmt, args);
		}
	};

	template <typename T>
	struct _impl_vsprintf {
	};
	template <>
	struct _impl_vsprintf<char> {
		const int operator()(char* const buf, size_t nCount, const char* const fmt, const va_list args) noexcept
		{
			return vsnprintf(buf, nCount, fmt, args);
		}
	};
	template <>
	struct _impl_vsprintf<wchar_t> {
		const int operator()(wchar_t* const buf, size_t nCount, const wchar_t* const fmt, const va_list args) noexcept
		{
			return vswprintf(buf, nCount, fmt, args);
		}
	};

	template <typename T, typename Format, typename... Arguments>
	struct _impl_snprintf {
	};
	template <typename... Arguments>
	struct _impl_snprintf<char, char, Arguments...> {
		const int operator()(char* const buf, const size_t nCount, const char* const fmt, const Arguments&&... args) noexcept
		{
			return snprintf(buf, nCount, fmt, args...);
		}
	};
	template <typename... Arguments>
	struct _impl_snprintf<wchar_t, wchar_t, Arguments...> {
		const int operator()(wchar_t* const buf, const size_t nCount, const wchar_t* const fmt, const Arguments&&... args) noexcept
		{
			return _snwprintf(buf, nCount, fmt, args...);
		}
	};

	//template <typename T, typename... Arguments>
	//struct _impl_snprintf<T, typename T::value_type, Arguments...> {
	//	const std::enable_if_t<std::is_member_function_pointer_v<decltype(&T::data)> && std::is_member_function_pointer_v<decltype(&T::size)>, int> operator()(T& buf, const typename T::value_type* const fmt, const Arguments&&... args) noexcept
	//	{
	//		if constexpr (std::is_same_v<char, T::value_type>)
	//			return snprintf(buf.data(), buf.size(), fmt, args...);
	//		else
	//			return _snwprintf(buf.data(), buf.size(), fmt, args...);
	//	}
	//};

	template <HasDataSizeNoChr T, typename... Arguments>
	struct _impl_snprintf<T, typename T::value_type, Arguments...> {
		const int operator()(T& buf, const typename T::value_type* const fmt, const Arguments&&... args) noexcept
		{
			if constexpr (std::is_same_v<char, T::value_type>)
				return snprintf(buf.data(), buf.size(), fmt, args...);
			else
				return _snwprintf(buf.data(), buf.size(), fmt, args...);
		}
	};
	template <HasDataSizeChr T, typename... Arguments>
	struct _impl_snprintf<T, typename T::value_type, Arguments...> {
		const int operator()(T& buf, const typename T::value_type* const fmt, const Arguments&&... args) noexcept
		{
			if constexpr (std::is_same_v<char, T::value_type>)
				return snprintf(buf.to_chr(), buf.size(), fmt, args...);
			else
				return _snwprintf(buf.to_chr(), buf.size(), fmt, args...);
		}
	};

	template <typename T>
	struct _impl_atoi {
	};
	template <>
	struct _impl_atoi<char> {
		auto operator()(const char* const buf) noexcept
		{
			return atoi(buf);
		}
	};
	template <>
	struct _impl_atoi<wchar_t> {
		auto operator()(const wchar_t* const buf) noexcept
		{
			return _wtoi(buf);
		}
	};

	template <typename T>
	struct _impl_atoi64 {
	};
	template <>
	struct _impl_atoi64<char> {
		auto operator()(const char* const buf) noexcept
		{
			return _atoi64(buf);
		}
	};
	template <>
	struct _impl_atoi64<wchar_t> {
		auto operator()(const wchar_t* const buf) noexcept
		{
			return _wtoi64(buf);
		}
	};

	template <typename T>
	struct _impl_atof {
	};
	template <>
	struct _impl_atof<char> {
		auto operator()(const char* const buf) noexcept
		{
			return atof(buf);
		}
	};
	template <>
	struct _impl_atof<wchar_t> {
		auto operator()(const wchar_t* const buf) noexcept
		{
			return _wtof(buf);
		}
	};

	template <typename T>
	struct _impl_itoa {
	};
	template <>
	struct _impl_itoa<char> {
		auto operator()(const int val, char* const buf, const int radix) noexcept
		{
			return _itoa(val, buf, radix);
		}
	};
	template <>
	struct _impl_itoa<wchar_t> {
		auto operator()(const int val, wchar_t* const buf, const int radix) noexcept
		{
			return _itow(val, buf, radix);
		}
	};

	template <typename T>
	struct _impl_strtoul {
	};
	template <>
	struct _impl_strtoul<char> {
		auto operator()(const char* const buf, char** endptr, int radx) noexcept
		{
			return strtoul(buf, endptr, radx);
		}
	};
	template <>
	struct _impl_strtoul<wchar_t> {
		auto operator()(const wchar_t* const buf, wchar_t** endptr, int radx) noexcept
		{
			return wcstoul(buf, endptr, radx);
		}
	};

	/// <summary>
	/// Convert a string representation of a binary number to an unsigned long
	/// </summary>
	/// <typeparam name="T">- char or wchar_t</typeparam>
	template <typename T>
	struct _impl_bstrtoul {
	};
	template <>
	struct _impl_bstrtoul<char> {
		auto operator()(const char* const buf) noexcept
		{
			return strtoul(buf, nullptr, 2);
		}
	};
	template <>
	struct _impl_bstrtoul<wchar_t> {
		auto operator()(const wchar_t* const buf) noexcept
		{
			return wcstoul(buf, nullptr, 2);
		}
	};
	template <typename T>
	struct _impl_strtok {
	};
	template <>
	struct _impl_strtok<char> {
		auto operator()(char* const buf, const char* delim, char** contex) noexcept
		{
			return strtok_s(buf, delim, contex);
		}
	};

	template <>
	struct _impl_strtok<wchar_t> {
		auto operator()(wchar_t* const buf, const wchar_t* delim, wchar_t** contex) noexcept
		{
			return wcstok_s(buf, delim, contex);
		}
	};
}

// Check string bounds, make sure dest is not within the source string & vice versa (this could be a possible reason for some strcpyn() fails we see)
template <details::IsPODText T>
constexpr bool isInBounds(const T* const sDest, const T* const sSrc, const std::size_t iLen) noexcept
{
	return (sSrc >= sDest && sSrc <= (sDest + iLen)) || (sDest >= sSrc && sDest <= (sSrc + iLen));
}

template <typename Result, typename Format, typename Value, typename... Arguments>
Result& _ts_sprintf(Result& res, const Format& fmt, const Value& val, Arguments&&... args)
{
	static_assert(details::IsPODText<Format>, "Format string must be char or wchar_t");
	res.clear();
	return details::_ts_printf_do(res, fmt, val, args...);
}

template <details::IsPODText T>
T* _ts_strstr(T* input, const std::remove_const_t<T>* find)
{
	return details::impl_strstr<T>()(input, find);
}

// Get String length
template <typename T>
inline auto _ts_strlen(const T& str) noexcept
{
	return details::_ts_strlen(str);
}

// Get String length (with buffer size limit)
template <details::IsPODText T>
inline size_t _ts_strnlen(const T& str, const size_t& nBufSize) noexcept
{
	return details::_impl_strnlen<T>()(str, nBufSize);
}

// Test if a string is empty, works for any object that has an empty() member function as well as C strings.
template <typename T>
inline bool _ts_isEmpty(const T& str) noexcept
{
	return details::_ts_isEmpty(str);
}

// Finds a string or character within a string & returns a pointer to it.
template <details::IsPODText HayStack, details::IsPODText Needle>
inline HayStack* _ts_find(HayStack* const str, Needle srch) noexcept
{
	return const_cast<HayStack*>(details::_impl_ts_find<Needle>()(str, srch));
}
template <details::IsPODText HayStack, details::IsPODText Needle>
inline const HayStack* _ts_find(const HayStack* const str, Needle srch) noexcept
{
	return details::_impl_ts_find<Needle>()(str, srch);
}

// Finds a string literal within a string & returns a pointer to it.
template <typename T, size_t N>
inline T* _ts_find(T* const str, const T(&srch)[N]) noexcept
{
	return const_cast<T*>(details::_impl_ts_find<std::add_pointer_t<T>>()(str, &srch[0]));
}

//// Finds a string or character within a string & returns a pointer to it.
//template <typename T, typename TStr>
//inline TStr *_ts_find(TStr *const str, T &srch)
//{
//	return const_cast<TStr *>(details::_impl_ts_find<std::remove_cv_t<T>>()(str, srch));
//}
//
//// Finds a string literal within a string & returns a pointer to it.
//template <typename T, typename TStr, size_t N>
//inline TStr *_ts_find(TStr *const str, const T (&srch)[N])
//{
//	return const_cast<TStr *>(details::_impl_ts_find<std::add_pointer_t<T>>()(str, &srch[0]));
//}

//template <typename T, typename TStr>
//inline const TStr *_ts_find(const TStr *const str, const T &srch)
//{
//	return details::_impl_ts_find<std::remove_cv_t<T>>()(str, srch);
//}
//
//template <typename T, typename TStr>
//inline TStr *_ts_find(TStr *const str, const T &srch)
//{
//	return const_cast<TStr *>(details::_impl_ts_find<std::remove_cv_t<T>>()(str, srch));
//}

template <details::IsPODText T>
T* _ts_strcpyn(T* const sDest, const T* const sSrc, const size_t iChars) noexcept
{
	static_assert(details::IsPODText<T>, "Only char & wchar_t supported...");

	//#if DCX_DEBUG_OUTPUT
	//	if ((sDest == nullptr) || (sSrc == nullptr) || isInBounds<std::remove_cv_t<T> >(sDest, sSrc, iChars))
	//		return nullptr;
	//#else
	if ((!sDest) || (!sSrc))
		return nullptr;
	//#endif

	return details::_impl_strcpyn<T>()(sDest, sSrc, iChars);
}

template <details::IsPODText T>
T* _ts_strcpy(T* const sDest, const T* const sSrc) noexcept
{
	static_assert(details::IsPODText<T>, "Only char & wchar_t supported...");

	if ((!sDest) || (!sSrc))
		return nullptr;

	return details::_impl_strcpy<T>()(sDest, sSrc);
}

template <details::IsPODText T>
T* _ts_strncat(T* const sDest, const T* const sSrc, const size_t iChars) noexcept
{
	static_assert(details::IsPODText<T>, "Only char & wchar_t supported...");

	return details::_impl_strncat<T>()(sDest, sSrc, iChars);
}

template <details::IsPODText T>
T* _ts_strcat(T* const sDest, const T* const sSrc) noexcept
{
	static_assert(details::IsPODText<T>, "Only char & wchar_t supported...");

	return details::_impl_strcat<T>()(sDest, sSrc);
}

template <details::IsPODText T>
T* _ts_strchr(T* const sDest, const T ch)
{
	static_assert(details::IsPODText<T>, "Only char & wchar_t supported...");

	return details::_impl_strchr<T>()(sDest, ch);
}

template <details::IsPODText T>
int _ts_strncmp(const T* const sDest, const T* const sSrc, const size_t iChars) noexcept
{
	static_assert(details::IsPODText<T>, "Only char & wchar_t supported...");

	return details::_impl_strncmp<T>()(sDest, sSrc, iChars);
}

template <details::IsPODText T>
int _ts_strnicmp(const T* const sDest, const T* const sSrc, const size_t iChars) noexcept
{
	static_assert(details::IsPODText<T>, "Only char & wchar_t supported...");

	return details::_impl_strnicmp<T>()(sDest, sSrc, iChars);
}

template <details::IsPODText T>
int _ts_strcmp(const T* const sDest, const T* const sSrc) noexcept
{
	static_assert(details::IsPODText<T>, "Only char & wchar_t supported...");

	return details::_impl_strcmp<T>()(sDest, sSrc);
}

template <details::IsPODText T>
int _ts_stricmp(const T* const sDest, const T* const sSrc) noexcept
{
	static_assert(details::IsPODText<T>, "Only char & wchar_t supported...");

	return details::_impl_stricmp<T>()(sDest, sSrc);
}

template <details::IsPODText T>
int _ts_vscprintf(_Printf_format_string_ const T* const _Format, va_list _ArgList) noexcept
{
	static_assert(details::IsPODText<T>, "Only char & wchar_t supported...");

	return details::_impl_vscprintf<T>()(_Format, _ArgList);
}

template <details::IsPODText T>
int _ts_vsprintf(T* const buf, size_t nCount, _Printf_format_string_ const T* const fmt, const va_list args) noexcept
{
	static_assert(details::IsPODText<T>, "Only char & wchar_t supported...");

	return details::_impl_vsprintf<T>()(buf, nCount, fmt, args);
}

template <details::IsPODText T, typename Format, typename... Arguments>
int _ts_snprintf(T* const buf, const size_t nCount, _Printf_format_string_ const Format* const fmt, Arguments&&... args) noexcept
{
	static_assert(details::IsPODText<T>, "Only char & wchar_t supported...");
	static_assert(std::is_same_v<std::remove_cv_t<T>, std::remove_cv_t<Format>>, "Buffer & format must have same type.");

	return details::_impl_snprintf<T, Format, Arguments...>()(buf, nCount, fmt, std::forward<Arguments>(args)...);
}

template <typename T, details::IsPODText Format, typename... Arguments>
int _ts_snprintf(T& buf, _Printf_format_string_ const Format* const fmt, Arguments&&... args) noexcept
{
	static_assert(details::IsPODText<Format>, "Only char & wchar_t supported...");

	return details::_impl_snprintf<T, Format, Arguments...>()(buf, fmt, std::forward<Arguments>(args)...);
}

template <details::IsPODText T>
auto _ts_atoi(const T* const buf) noexcept
{
	static_assert(details::IsPODText<T>, "Only char & wchar_t supported...");

	return details::_impl_atoi<T>()(buf);
}

template <details::IsPODText T>
auto _ts_atoi64(const T* const buf) noexcept
{
	static_assert(details::IsPODText<T>, "Only char & wchar_t supported...");

	return details::_impl_atoi64<T>()(buf);
}

template <details::IsPODText T>
auto _ts_atof(const T* const buf) noexcept
{
	static_assert(details::IsPODText<T>, "Only char & wchar_t supported...");

	return details::_impl_atof<T>()(buf);
}

template <details::IsPODText T>
auto _ts_itoa(const int val, T* const buf, const int radix) noexcept
{
	static_assert(details::IsPODText<T>, "Only char & wchar_t supported...");

	return details::_impl_itoa<T>()(val, buf, radix);
}

template <details::IsPODText T>
auto _ts_strtoul(const T* const buf, T** endptr, int base) noexcept
{
	static_assert(details::IsPODText<T>, "Only char & wchar_t supported...");

	return details::_impl_strtoul<T>()(buf, endptr, base);
}

/// <summary>
/// Convert a string representation of a binary number to an unsigned long
/// </summary>
/// <param name="buf">- String representing a binary number.</param>
/// <returns>Binary number</returns>
template <details::IsPODText T>
auto _ts_bstrtoul(const T* const buf) noexcept
{
	static_assert(details::IsPODText<T>, "Only char & wchar_t supported...");

	return details::_impl_bstrtoul<T>()(buf);
}

/// <summary>
/// same as strtok_s()
/// </summary>
/// <param name="buf"></param>
/// <param name="delim"></param>
/// <param name="contex"></param>
/// <returns></returns>
template <details::IsPODText T>
auto _ts_strtok(T* const buf, const T* delim, T** contex) noexcept
{
	static_assert(details::IsPODText<T>, "Only char & wchar_t supported...");

	return details::_impl_strtok<T>()(buf, delim, contex);
}

/// <summary>
/// Converts a number into a binary string representing that number (whole integers only)
/// </summary>
/// <typeparam name="Result">A string type object</typeparam>
/// <param name="a">- The number to convert.</param>
/// <returns>The string representation of the number.</returns>
template <details::IsNumeric T, class Result>
Result DecimalToBinaryString(const T& a)
{
	Result binary;
	constexpr auto sz = sizeof(a) * 8;
	std::remove_const_t<T> mask = 1;
	for (std::remove_const_t<decltype(sz)> i = 0; i < sz; ++i)
	{
		if ((mask & a))
			binary = '1' + binary;
		else
			binary = '0' + binary;
		mask <<= 1;
	}
	return binary;
}

/// <summary>
/// Replace all instances of 'rep' in 'str' with 'with'
/// </summary>
/// <typeparam name="T"></typeparam>
/// <typeparam name="RepThis"></typeparam>
/// <typeparam name="WithThis"></typeparam>
/// <param name="str">- string to search</param>
/// <param name="rep">- string to search for</param>
/// <param name="with">- replacement string</param>
/// <returns>The string it was passed with the changes made.</returns>
template <class T, class RepThis, class WithThis>
T& _ts_replace(T& str, RepThis rep, WithThis with)
{
	for (std::size_t wlen = _ts_strlen(with), rlen = _ts_strlen(rep), pos = 0U; ; pos += wlen)
	{
		pos = str.find(rep, pos);
		if (pos == T::npos)
			break;

		if constexpr (std::is_same_v<char, std::remove_cv_t<WithThis>> || std::is_same_v<wchar_t, std::remove_cv_t<WithThis>>)
		{
			str.replace(pos, rlen, 1, with);
		}
		else
		{
			str.replace(pos, rlen, with);
		}
	}
	return str;
}

//void ReplaceStringInPlace(std::string& subject, const std::string& search, const std::string& replace)
//{
//	size_t pos = 0;
//	while ((pos = subject.find(search, pos)) != std::string::npos)
//	{
//		subject.replace(pos, search.length(), replace);
//		pos += replace.length();
//	}
//}

/// <summary>
/// Replace all instances of each character in 'rep' in 'str' with 'with'
/// </summary>
/// <typeparam name="T"></typeparam>
/// <typeparam name="RepThis"></typeparam>
/// <typeparam name="WithThis"></typeparam>
/// <param name="str">- string to search</param>
/// <param name="rep">- string of characters to search for</param>
/// <param name="with">- replacement string</param>
/// <returns>The string it was passed with the changes made.</returns>
template <class T, class RepThis, class WithThis>
T& _ts_mreplace(T& str, RepThis rep, WithThis with)
{
	for (std::ptrdiff_t i = 0; rep[i] != 0; ++i)
		_ts_replace(str, rep[i], with);
	return str;
}

/// <summary>
/// Remove all instances of 'rep' within 'str'
/// </summary>
/// <typeparam name="T"></typeparam>
/// <typeparam name="RemThis"></typeparam>
/// <param name="str">- string to search.</param>
/// <param name="rep">- string to remove.</param>
/// <returns>The string it was passed with the changes made.</returns>
template <class T, class RemThis>
T& _ts_remove(T& str, RemThis rep)
{
	for (auto itEnd = str.end(), itStart = str.begin(); str.erase(std::find(itStart, itEnd, rep)) != itEnd; ) {}

	return str;
}

/// <summary>
/// Remove spaces from the front and back of the string.
/// </summary>
/// <typeparam name="T">A string type object</typeparam>
/// <param name="str">- The string to trim.</param>
/// <returns>A reference to the same string object it was passed.</returns>
template <class T>
T& _ts_trim(T& str)
{
	if (str.empty())
		return str;

	while (str.front() == _T(' '))
		str.erase(0, 1);

	while (str.back() == _T(' '))
		str.pop_back();

	return str;
}

/// <summary>
/// Copies the string then remove spaces from the front and back of the string.
/// </summary>
/// <typeparam name="T">A string type object</typeparam>
/// <param name="str">- The string to trim.</param>
/// <returns>A copy of the string object it was passed.</returns>
template <class T>
T _ts_trim_and_copy(const T& str)
{
	if (str.empty())
		return str;

	T res(str);
	while (res.front() == _T(' '))
		res.erase(0, 1);

	while (res.back() == _T(' '))
		res.pop_back();

	return res;
}

/// <summary>
/// Trim the string and remove double spaces.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="str">- string to modify.</param>
/// <returns>The string it was passed with the changes made.</returns>
template <class T>
T& _ts_strip(T& str)
{
	//_ts_remove(str, _T('\0x02'));	//02
	//_ts_remove(str, _T('\0x0F'));	//15
	//_ts_remove(str, _T('\0x16'));	//22
	//_ts_remove(str, _T('\0x1D'));	//29
	_ts_replace(str, _T("  "), _T(' '));
	// NB: TODO: add ctrl-k removal for colour codes.
	return _ts_trim(str);
}

/// <summary>
/// Change a string to uppercase.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="str">- string to modify.</param>
/// <returns>The string it was passed with the changes made.</returns>
template <class T>
T& _ts_toupper(T& str)
{
	for (auto& a : str)
		a = details::make_upper(a);
	return str;
}

template <details::IsPODText T>
T _ts_toupper_c(const T& c) noexcept
{
	return details::make_upper(c);
}

template <details::IsPODText T>
bool _ts_isupper(const T& c) noexcept
{
	if constexpr (std::is_same_v<wchar_t, T>)
		return (iswupper(c) != 0);
	else
		return (isupper(c) != 0);
}

/// <summary>
/// Convert a string to a number.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <typeparam name="Input"></typeparam>
/// <param name="str">- string to convert.</param>
/// <returns>The number contained in the string.</returns>
template <class T, class Input>
T _ts_to_(const Input& str)
{
	static_assert(is_Numeric_v<T>, "Type T must be (int, long, float, double, ....)");

	std::basic_istringstream<TCHAR> ss(str);	// makes copy of string :(
	T result{};
	return ss >> result ? result : T();
}

#define TSTRING_WILDT 0
#define TSTRING_WILDA 0
#define TSTRING_WILDE 0
#define TSTRING_WILDW 0

//template <class T>
//constexpr auto getWildType(T s) noexcept
//{
//	if constexpr (details::is_pod_v<T>)
//		return typename std::remove_pointer_t<std::remove_cv_t<std::remove_all_extents_t<T>>>;
//	else
//		return typename std::remove_pointer_t<std::remove_cv_t<std::remove_all_extents_t<T::value_type>>>;
//}
//
//template <typename TameString, typename WildString>
//[[gsl::suppress(bounds)]] bool _ts_WildcardMatch(const TameString& pszString, const WildString& pszMatch, const bool bCase = false)
//{
//	//if ((!pszMatch) || (!pszString))
//	//	return false;
//
//	if (_ts_isEmpty(pszMatch) || _ts_isEmpty(pszString))
//		return false;
//
//	ptrdiff_t MatchPlaceholder = 0;
//	ptrdiff_t StringPlaceholder = 0;
//	ptrdiff_t iWildOffset = 0;
//	ptrdiff_t iTameOffset = 0;
//
//	//using _WildString = typename std::remove_pointer_t<std::remove_cv_t<std::remove_all_extents_t<WildString::value_type>>>;
//	using _WildString = typename std::remove_pointer_t<std::remove_cv_t<std::remove_all_extents_t<WildString>>>;
//	//auto a = getWildType(pszMatch);
//
//	constexpr _WildString _zero{};
//	constexpr _WildString _star = static_cast<_WildString>('*');
//	constexpr _WildString _question = static_cast<_WildString>('?');
//	constexpr _WildString _tilda = static_cast<_WildString>('~');
//	constexpr _WildString _space = static_cast<_WildString>(' ');
//	constexpr _WildString _power = static_cast<_WildString>('^');
//	constexpr _WildString _hash = static_cast<_WildString>('#');
//	constexpr _WildString _slash = static_cast<_WildString>('\\');
//	constexpr _WildString _tab = static_cast<_WildString>('\t');
//	constexpr _WildString _n = static_cast<_WildString>('\n');
//	constexpr _WildString _r = static_cast<_WildString>('\r');
//
//	while (pszString[iTameOffset])
//	{
//		if (pszMatch[iWildOffset] == _star)
//		{
//			if (pszMatch[++iWildOffset] == _zero)
//				return true;
//			MatchPlaceholder = iWildOffset;
//			StringPlaceholder = iTameOffset + 1;
//		}
//#if TSTRING_WILDT
//		else if (pszMatch[iWildOffset] == _tilda && pszString[iTameOffset] == _space)
//		{
//			++iWildOffset;
//			while (pszString[iTameOffset] == _space)
//				++iTameOffset;
//		}
//#endif
//#if TSTRING_WILDA
//		else if (pszMatch[iWildOffset] == _power)
//		{
//			++iWildOffset;
//			if (details::CompareChar(pszMatch[iWildOffset], pszString[iTameOffset], bCase))
//				++iTameOffset;
//			++iWildOffset;
//		}
//#endif
//#if TSTRING_WILDE
//		else if (pszMatch[iWildOffset] == _slash)
//		{
//			// any character following a '\' is taken as a literal character.
//			++iWildOffset;
//			if (!details::CompareChar(pszMatch[iWildOffset], pszString[iTameOffset], bCase))
//				return false;
//			++iTameOffset;
//		}
//#endif
//#if TSTRING_WILDW
//		else if (pszMatch[iWildOffset] == _hash)
//		{
//			++iWildOffset;
//			while (pszString[iTameOffset] && (pszString[iTameOffset] != _space || pszString[iTameOffset] != _tab || pszString[iTameOffset] != _n || pszString[iTameOffset] != _r))
//				++iTameOffset;
//		}
//#endif
//		//else if (pszMatch[iWildOffset] == TEXT('?') || _toupper(pszMatch[iWildOffset]) == _toupper(pszString[iTameOffset]))
//		else if (pszMatch[iWildOffset] == _question || details::CompareChar(pszMatch[iWildOffset], pszString[iTameOffset], bCase))
//		{
//			++iWildOffset;
//			++iTameOffset;
//		}
//		else if (StringPlaceholder == 0)
//			return false;
//		else
//		{
//			iWildOffset = MatchPlaceholder;
//			iTameOffset = StringPlaceholder++;
//		}
//	}
//
//	while (pszMatch[iWildOffset] == _star)
//		++iWildOffset;
//
//	return !pszMatch[iWildOffset];
//}

/// <summary>
/// Internal wildcard match function.
/// </summary>
/// <typeparam name="_Wild"></typeparam>
/// <typeparam name="TameString"></typeparam>
/// <typeparam name="WildString"></typeparam>
/// <param name="pszString"></param>
/// <param name="pszMatch"></param>
/// <param name="bCase"></param>
/// <returns></returns>
template <class _Wild, typename TameString, typename WildString>
GSL_SUPPRESS(bounds.4) bool _ts_InnerWildcardMatch(const TameString& pszString, const WildString& pszMatch, const bool bCase) noexcept(std::is_nothrow_move_assignable_v<WildString>)
{
	ptrdiff_t MatchPlaceholder = 0;
	ptrdiff_t StringPlaceholder = 0;
	ptrdiff_t iWildOffset = 0;
	ptrdiff_t iTameOffset = 0;

	constexpr _Wild _zero{};
	constexpr _Wild _star = static_cast<_Wild>('*');
	constexpr _Wild _question = static_cast<_Wild>('?');
	constexpr _Wild _tilda = static_cast<_Wild>('~');
	constexpr _Wild _space = static_cast<_Wild>(' ');
	constexpr _Wild _power = static_cast<_Wild>('^');
	constexpr _Wild _hash = static_cast<_Wild>('#');
	constexpr _Wild _slash = static_cast<_Wild>('\\');
	constexpr _Wild _tab = static_cast<_Wild>('\t');
	constexpr _Wild _n = static_cast<_Wild>('\n');
	constexpr _Wild _r = static_cast<_Wild>('\r');

	while (pszString[iTameOffset])
	{
		if (pszMatch[iWildOffset] == _star)
		{
			if (pszMatch[++iWildOffset] == _zero)
				return true;
			MatchPlaceholder = iWildOffset;
			StringPlaceholder = iTameOffset + 1;
		}
#if TSTRING_WILDT
		else if (pszMatch[iWildOffset] == _tilda && pszString[iTameOffset] == _space)
		{
			++iWildOffset;
			while (pszString[iTameOffset] == _space)
				++iTameOffset;
		}
#endif
#if TSTRING_WILDA
		else if (pszMatch[iWildOffset] == _power)
		{
			++iWildOffset;
			if (details::CompareChar(pszMatch[iWildOffset], pszString[iTameOffset], bCase))
				++iTameOffset;
			++iWildOffset;
		}
#endif
#if TSTRING_WILDE
		else if (pszMatch[iWildOffset] == _slash)
		{
			// any character following a '\' is taken as a literal character.
			++iWildOffset;
			if (!details::CompareChar(pszMatch[iWildOffset], pszString[iTameOffset], bCase))
				return false;
			++iTameOffset;
		}
#endif
#if TSTRING_WILDW
		else if (pszMatch[iWildOffset] == _hash)
		{
			++iWildOffset;
			while (pszString[iTameOffset] && (pszString[iTameOffset] != _space || pszString[iTameOffset] != _tab || pszString[iTameOffset] != _n || pszString[iTameOffset] != _r))
				++iTameOffset;
		}
#endif
		//else if (pszMatch[iWildOffset] == _question || _toupper(pszMatch[iWildOffset]) == _toupper(pszString[iTameOffset]))
		else if (pszMatch[iWildOffset] == _question || details::CompareChar(pszMatch[iWildOffset], pszString[iTameOffset], bCase))
		{
			++iWildOffset;
			++iTameOffset;
		}
		else if (StringPlaceholder == 0)
			return false;
		else
		{
			iWildOffset = MatchPlaceholder;
			iTameOffset = StringPlaceholder++;
		}
	}

	while (pszMatch[iWildOffset] == _star)
		++iWildOffset;

	return !pszMatch[iWildOffset];
}

/// <summary>
/// Wildcard match
/// </summary>
/// <typeparam name="TameString"></typeparam>
/// <typeparam name="WildString"></typeparam>
/// <param name="pszString">- string to search</param>
/// <param name="pszMatch">- the wildcard string to search for.</param>
/// <param name="bCase">- does case matter</param>
/// <returns>did match succeed true/false</returns>
template <typename TameString, typename WildString>
GSL_SUPPRESS(bounds) bool _ts_WildcardMatch(const TameString& pszString, const WildString& pszMatch, const bool bCase = false) noexcept(std::is_nothrow_move_assignable_v<WildString>)
{
	if (_ts_isEmpty(pszMatch) || _ts_isEmpty(pszString))
		return false;

	if constexpr (details::is_pod_v<std::remove_pointer_t<std::remove_cv_t<std::remove_all_extents_t<WildString>>>>)
		return _ts_InnerWildcardMatch<std::remove_pointer_t<std::remove_cv_t<std::remove_all_extents_t<WildString>>>>(pszString, pszMatch, bCase);
	else
		return _ts_InnerWildcardMatch<std::remove_pointer_t<std::remove_cv_t<std::remove_all_extents_t<WildString::value_type>>>>(pszString, pszMatch, bCase);
}

template <typename T> T* _ts_AddMem(std::vector<std::shared_ptr<std::vector<char>>>& mem, std::size_t sz = sizeof(T))
{
	std::shared_ptr<std::vector<char>> x = std::make_shared<std::vector<char>>();
	x->resize(sz);
	mem.push_back(x);
	T* d = (T*)mem[mem.size() - 1].get()->data();
	return d;
}

/// <summary>
/// Sort a vector
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="str">- The vector to sort.</param>
/// <returns>A sorted copy of the input.</returns>
template <class T>
std::vector<T> _ts_SortString(const std::vector<T>& str)
{
	std::vector<T> out(str);

	std::sort(out.begin(), out.end(), std::less<T>);

	return out;
}

max_stars_repo_name: twig/dcxdll

max_issues_repo_name: twig/dcxdll

max_forks_repo_name: twig/dcxdll


text:
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <assert.h>
#include <string.h>
#include <time.h>
#include <sys/time.h>
#include <gsl/gsl_math.h>

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

void test_cosmo(char *path);

int main(int argc, char **argv)
{
  cosmoData.useSmoothTransFunc = 0;
  cosmoData.delta = 200.0;
  char path[4096];

  //init cosmology 2
  cosmoData.cosmoNum = 2;
  cosmoData.OmegaM = 0.28;
  cosmoData.OmegaL = 0.72;
  cosmoData.OmegaB = 0.05;
  cosmoData.OmegaNu = 0.0;
  cosmoData.OmegaK = 0.0;
  cosmoData.h = 0.7;
  cosmoData.w0 = -1.0;
  cosmoData.wa = 0.0;
  cosmoData.SpectralIndex = 0.96;
  cosmoData.Sigma8 = 0.8;

  sprintf(path,"./cosmo2");
  test_cosmo(path);

  //init cosmology 1
  cosmoData.cosmoNum = 1;
  cosmoData.OmegaM = 0.3;
  cosmoData.OmegaL = 0.68;
  cosmoData.OmegaB = 0.05;
  cosmoData.OmegaNu = 0.0;
  cosmoData.OmegaK = 1.0 - cosmoData.OmegaM - cosmoData.OmegaL - cosmoData.OmegaNu;
  cosmoData.h = 0.7;
  cosmoData.w0 = -0.8;
  cosmoData.wa = 0.2;
  cosmoData.SpectralIndex = 0.96;
  cosmoData.Sigma8 = 0.8;

  sprintf(path,"./cosmo1");
  test_cosmo(path);

  return 0;
}

void test_cosmo(char *path)
{
  char fname[4096];
  char fnameo[4096];
  char str[4096];
  FILE *fp;
  FILE *fpout;
  double z;

  sprintf(fname,"%s/codist.dat",path);
  sprintf(fnameo,"%s/codist.dat.matt",path);
  fp = fopen(fname,"r");
  if( fp != NULL)
    {
      fpout = fopen(fnameo,"w");
      while(fgets(str,4096,fp) != NULL)
	{
	  if(str[0] == '#')
	    continue;
	  sscanf(str,"%le %*e\n",&z);

	  fprintf(fpout,"%e %e\n",z,comvdist(1.0/(1.0+z)));
	}
      fclose(fp);
      fclose(fpout);
    }

  sprintf(fname,"%s/Evol_z.dat",path);
  sprintf(fnameo,"%s/Evol_z.dat.matt",path);
  fp = fopen(fname,"r");
  if(fp != NULL)
    {
      fpout = fopen(fnameo,"w");
      while(fgets(str,4096,fp) != NULL)
	{
	  if(str[0] == '#')
	    continue;
	  sscanf(str,"%le %*e\n",&z);

	  //fprintf(stderr,"weff(%f) = %f, h(a) = %f\n",1.0/(1.0+z),weff(1.0/(1.0+z)),hubble_noscale(1.0/(1.0+z)));
	  fprintf(fpout,"%e %e\n",z,hubble_noscale(1.0/(1.0+z)));
	}
      fclose(fp);
      fclose(fpout);
    }
}

max_stars_repo_name: beckermr/cosmocalc

max_issues_repo_name: beckermr/cosmocalc

max_forks_repo_name: beckermr/cosmocalc


text:
#include <assert.h>
#include <math.h>
#include <gsl/gsl_randist.h>
#include "nmcalc.h"

void get_ab(struct variant_table *v, struct variant_counts **a, struct variant_counts **b);

// Convenience function to mimic MATLAB function
static inline double binopdf(unsigned int x, unsigned int n, double p) {
	return gsl_ran_binomial_pdf(x, p, n);
}

#define NONZERO_OR_NAN(X, NAN_CODE) ((X) == (X) ? (X) : nan(#NAN_CODE))

void nmcalc(struct context *context,
            struct variant_table *v,
            double prior_map_error,
            int ploidy,
            struct nm_entry *out)
{
	(void) context;

	double a_read_depth, b_read_depth;
	double a_mean_mq, b_mean_mq;

	double prior_hom, prior_het;
	double p_data_map_error, p_data_hom, p_data_het, p_data;
	double p_map_error;

	double per_read_pass, ab_frac;

	struct variant_counts *a, *b;

	get_ab(v, &a, &b);

	// Initialization of useful variables

	a_read_depth = (a->count_f + a->count_r) / 2.0;
	b_read_depth = (b->count_f + b->count_r) / 2.0;

	a_mean_mq = a->total_mq / NONZERO_OR_NAN(a_read_depth, 200);
	b_mean_mq = b->total_mq / NONZERO_OR_NAN(b_read_depth, 200);

	// Normal metrics calculation starts here

	// priors
	if (ploidy == 2) {
		prior_het = 2 * a->pop_af * b->pop_af;
	} else {
		prior_het = 0;
	}

	prior_hom = a->pop_af * a->pop_af;

	// likelihoods
	p_data_map_error = pow(10, -fmin(a_mean_mq, b_mean_mq)/10);
	p_data_hom = binopdf(b_read_depth, v->read_count_pass, pow(10, (-b_mean_mq / 10)));
	p_data_het = binopdf(b_read_depth, v->read_count_pass,  0.5);

	p_data = prior_map_error * p_data_map_error + prior_het * p_data_het + prior_hom * p_data_hom;

	// posteriors
	if (v->read_count_pass > 0) {
		p_map_error = prior_map_error * p_data_map_error / p_data;
	} else {
		p_map_error = nan("300");
	}

	// other metrics
	per_read_pass = v->read_count_pass / NONZERO_OR_NAN(v->read_count, 200);

	ab_frac = (a_read_depth + b_read_depth) / NONZERO_OR_NAN(v->read_count_pass, 200);

	out->pos = v->offset;

	if (ploidy == 1 || ploidy == 2) {
		out->norm_read_depth = (3-ploidy) * v->read_count_pass; // sneak
		out->prob_map_err = p_map_error;
		out->read_pass = per_read_pass;
		out->a_or_b = ab_frac;
	} else  {
		out->norm_read_depth = nan("101");
		out->prob_map_err = nan("102");
		out->read_pass = nan("103");
		out->a_or_b = nan("104");
	}
}

max_stars_repo_name: tgen/gvm

max_issues_repo_name: tgen/gvm

max_forks_repo_name: tgen/gvm


text:
#include <petsc.h>
#if PETSC_VERSION_LE(3,3,0)

PETSC_EXTERN PetscErrorCode PetscOptionsGetViewer(MPI_Comm,const char[],const char[],PetscViewer*,PetscViewerFormat*,PetscBool*);

#undef __FUNCT__
#define __FUNCT__ "PetscEListFind"
static PetscErrorCode PetscEListFind(PetscInt n,const char *const *list,const char *str,PetscInt *value,PetscBool *found)
{
  PetscInt  i;
  PetscBool matched;
  PetscErrorCode ierr;
  PetscFunctionBegin;
  if (found) *found = PETSC_FALSE;
  for (i=0; i<n; i++) {
    ierr = PetscStrcasecmp(str,list[i],&matched);CHKERRQ(ierr);
    if (matched || !str[0]) {
      if (found) *found = PETSC_TRUE;
      *value = i;
      break;
    }
  }
  PetscFunctionReturn(0);
}

#undef __FUNCT__
#define __FUNCT__ "PetscEnumFind"
static PetscErrorCode PetscEnumFind(const char *const *enumlist,const char *str,PetscEnum *value,PetscBool *found)
{
  PetscInt       n,evalue;
  PetscBool      efound;
  PetscErrorCode ierr;
  PetscFunctionBegin;
  for (n = 0; enumlist[n]; n++) {
    if (n > 50) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONG,"List argument appears to be wrong or have more than 50 entries");
  }
  if (n < 3) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONG,"List argument must have at least two entries: typename and type prefix");
  n -= 3;                       /* drop enum name, prefix, and null termination */
  ierr = PetscEListFind(n,enumlist,str,&evalue,&efound);CHKERRQ(ierr);
  if (efound) *value = (PetscEnum)evalue;
  if (found)  *found = efound;
  PetscFunctionReturn(0);
}

#undef __FUNCT__
#define __FUNCT__ "PetscOptionsGetViewer"
PetscErrorCode PetscOptionsGetViewer(MPI_Comm comm,const char pre[],const char name[],PetscViewer *viewer,PetscViewerFormat *format,PetscBool *set)
{
  char           value[2*PETSC_MAX_PATH_LEN];
  PetscBool      flag;
  PetscErrorCode ierr;
  PetscFunctionBegin;
  PetscValidCharPointer(name,3);
  if (format) *format = PETSC_VIEWER_DEFAULT;
  if (set) *set = PETSC_FALSE;
  ierr = PetscOptionsGetString(pre,name,value,sizeof(value),&flag);CHKERRQ(ierr);
  if (flag) {
    if (set) *set = PETSC_TRUE;
    if (!value[0]) {
      ierr = PetscViewerASCIIGetStdout(comm,viewer);CHKERRQ(ierr);
      ierr = PetscObjectReference((PetscObject)*viewer);CHKERRQ(ierr);
    } else {
      char       *loc0_vtype,*loc1_fname,*loc2_fmt = NULL,*loc3_fmode = NULL;
      PetscInt   cnt;
      const char *const PetscFileModes[] = {"READ","WRITE","APPEND","UPDATE","APPEND_UPDATE","PetscFileMode","PETSC_FILE_",0};
      const char *const viewers[] = {PETSCVIEWERASCII,PETSCVIEWERBINARY,PETSCVIEWERDRAW,PETSCVIEWERSOCKET,PETSCVIEWERMATLAB,PETSCVIEWERAMS,PETSCVIEWERVTK,0};
      ierr = PetscStrallocpy(value,&loc0_vtype);CHKERRQ(ierr);
      ierr = PetscStrchr(loc0_vtype,':',&loc1_fname);CHKERRQ(ierr);
      if (loc1_fname) {
        *loc1_fname++ = 0;
        ierr = PetscStrchr(loc1_fname,':',&loc2_fmt);CHKERRQ(ierr);
      }
      if (loc2_fmt) {
        *loc2_fmt++ = 0;
        ierr = PetscStrchr(loc2_fmt,':',&loc3_fmode);CHKERRQ(ierr);
      }
      if (loc3_fmode) *loc3_fmode++ = 0;
      ierr = PetscStrendswithwhich(*loc0_vtype ? loc0_vtype : "ascii",viewers,&cnt);CHKERRQ(ierr);
      if (cnt > (PetscInt)sizeof(viewers)-1) SETERRQ1(comm,PETSC_ERR_ARG_OUTOFRANGE,"Unknown viewer type: %s",loc0_vtype);
      if (!loc1_fname) {
        switch (cnt) {
        case 0:
          ierr = PetscViewerASCIIGetStdout(comm,viewer);CHKERRQ(ierr);
          break;
        case 1:
          if (!(*viewer = PETSC_VIEWER_BINARY_(comm))) CHKERRQ(PETSC_ERR_PLIB);
          break;
        case 2:
          if (!(*viewer = PETSC_VIEWER_DRAW_(comm))) CHKERRQ(PETSC_ERR_PLIB);
          break;
#if defined(PETSC_USE_SOCKET_VIEWER)
        case 3:
          if (!(*viewer = PETSC_VIEWER_SOCKET_(comm))) CHKERRQ(PETSC_ERR_PLIB);
          break;
#endif
#if defined(PETSC_HAVE_MATLAB_ENGINE)
        case 4:
          if (!(*viewer = PETSC_VIEWER_MATLAB_(comm))) CHKERRQ(PETSC_ERR_PLIB);
          break;
#endif
#if defined(PETSC_HAVE_AMS)
        case 5:
          if (!(*viewer = PETSC_VIEWER_AMS_(comm))) CHKERRQ(PETSC_ERR_PLIB);
          break;
#endif
        default: SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Unsupported viewer %s",loc0_vtype);
        }
        ierr = PetscObjectReference((PetscObject)*viewer);CHKERRQ(ierr);
      } else {
        if (loc2_fmt && !*loc1_fname && (cnt == 0)) { /* ASCII format without file name */
          ierr = PetscViewerASCIIGetStdout(comm,viewer);CHKERRQ(ierr);
          ierr = PetscObjectReference((PetscObject)*viewer);CHKERRQ(ierr);
        } else {
          PetscFileMode fmode;
          ierr = PetscViewerCreate(comm,viewer);CHKERRQ(ierr);
          ierr = PetscViewerSetType(*viewer,*loc0_vtype ? loc0_vtype : "ascii");CHKERRQ(ierr);
#if defined(PETSC_HAVE_AMS)
          ierr = PetscViewerAMSSetCommName(*viewer,loc1_fname);CHKERRQ(ierr);
#endif
          fmode = FILE_MODE_WRITE;
          if (loc3_fmode && *loc3_fmode) { /* Has non-empty file mode ("write" or "append") */
            ierr = PetscEnumFind(PetscFileModes,loc3_fmode,(PetscEnum*)&fmode,&flag);CHKERRQ(ierr);
            if (!flag) SETERRQ1(comm,PETSC_ERR_ARG_UNKNOWN_TYPE,"Unknown file mode: %s",loc3_fmode);
          }
          ierr = PetscViewerFileSetMode(*viewer,flag?fmode:FILE_MODE_WRITE);CHKERRQ(ierr);
          ierr = PetscViewerFileSetName(*viewer,loc1_fname);CHKERRQ(ierr);
        }
      }
      if (loc2_fmt && *loc2_fmt) {
        ierr = PetscEnumFind(PetscViewerFormats,loc2_fmt,(PetscEnum*)format,&flag);CHKERRQ(ierr);
        if (!flag) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Unknown viewer format %s",loc2_fmt);CHKERRQ(ierr);
        if (((int)*format) >= 5) *format = (PetscViewerFormat)(((int)*format)-2); /**/
      }
      ierr = PetscViewerSetUp(*viewer);CHKERRQ(ierr);
      ierr = PetscFree(loc0_vtype);CHKERRQ(ierr);
    }
  }
  PetscFunctionReturn(0);
}

#endif

max_stars_repo_name: otherlab/petiga

max_issues_repo_name: otherlab/petiga

max_forks_repo_name: otherlab/petiga


text:
#ifndef GBNET_GRAPHBASE
#define GBNET_GRAPHBASE

#include <iostream>
#include <string>
#include <vector>
#include <utility>
#include <map>
#include <set>
#include <stdio.h>

#include <gsl/gsl_rng.h>

#include "RVNode.h"
#include "XNode.h"
#include "HNodeORNOR.h"
#include "YDataNode.h"
#include "SNode.h"
#include "NodeDictionary.h"

namespace gbn
{
    // used accross module. might want to find a better place for these typedefs
    typedef std::vector<RVNode *> node_vector_t;
    typedef std::pair<std::string, int> trg_de_pair_t;
    typedef std::map<std::string, int> evidence_dict_t;

    typedef std::set<std::string> prior_active_tf_set_t;

    typedef std::pair<std::string, std::string> src_trg_pair_t;
    typedef std::pair<src_trg_pair_t, int> network_edge_t;
    typedef std::vector<network_edge_t> network_t;

    class GraphBase
    {
        private:
        protected:
            gsl_rng * rng;

        public:
            node_vector_t random_nodes;
            node_vector_t norand_nodes; /* Used to keep track of node pointers for later destruction */

            GraphBase (unsigned int);
            virtual ~GraphBase ();

            void sample (unsigned int);
            void burn_stats();
            void print_stats();
    };
}

#endif

max_stars_repo_name: umbibio/gbnet

max_issues_repo_name: umbibio/gbnet

max_forks_repo_name: umbibio/gbnet


text:
#ifndef EXT_VANILLAGENERATOR_LIB_OBJECTS_BIOMEARRAY_H_
#define EXT_VANILLAGENERATOR_LIB_OBJECTS_BIOMEARRAY_H_

#include <cstddef>
#include <gsl/span>

class BiomeArray {
 public:
  static const size_t DATA_SIZE = 256;

  explicit BiomeArray(const gsl::span<const uint_fast8_t, BiomeArray::DATA_SIZE> &values);

  auto Get(uint8_t x, uint8_t z) const -> uint_fast8_t;
  auto Set(uint8_t x, uint8_t z, uint_fast8_t value) -> void;

  [[nodiscard]] gsl::span<const uint_fast8_t, DATA_SIZE> GetRawData() const;

 private:
  std::array<uint_fast8_t, 256> mValues;

  static inline void Index(uint8_t x, uint8_t z, uint_fast8_t &offset);
};

#endif // EXT_VANILLAGENERATOR_LIB_OBJECTS_BIOMEARRAY_H_

max_stars_repo_name: NetherGamesMC/noiselib

max_issues_repo_name: NetherGamesMC/ext-vanillagenerator

max_forks_repo_name: NetherGamesMC/ext-vanillagenerator


text:
/**
 *
 * @file qwrapper_dlag2s.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 Mathieu Faverge
 * @date 2010-11-15
 * @generated ds Tue Jan  7 11:44:57 2014
 *
 **/
#include <lapacke.h>
#include "common.h"

/***************************************************************************//**
 *
 **/
void QUARK_CORE_dlag2s(Quark *quark, Quark_Task_Flags *task_flags,
                       int m, int n, int nb,
                       const double *A, int lda,
                       float *B, int ldb,
                       PLASMA_sequence *sequence, PLASMA_request *request)
{
    DAG_CORE_LAG2C;
    QUARK_Insert_Task(quark, CORE_dlag2s_quark, task_flags,
        sizeof(int),                        &m,         VALUE,
        sizeof(int),                        &n,         VALUE,
        sizeof(double)*nb*nb,    A,                 INPUT,
        sizeof(int),                        &lda,       VALUE,
        sizeof(float)*nb*nb,    B,                 OUTPUT,
        sizeof(int),                        &ldb,       VALUE,
        sizeof(PLASMA_sequence*),           &sequence,  VALUE,
        sizeof(PLASMA_request*),            &request,   VALUE,
        0);
}

/***************************************************************************//**
 *
 **/
#if defined(PLASMA_HAVE_WEAK)
#pragma weak CORE_dlag2s_quark = PCORE_dlag2s_quark
#define CORE_dlag2s_quark PCORE_dlag2s_quark
#endif
void CORE_dlag2s_quark(Quark *quark)
{
    int m;
    int n;
    double *A;
    int lda;
    float *B;
    int ldb;
    PLASMA_sequence *sequence;
    PLASMA_request *request;
    int info;

    quark_unpack_args_8(quark, m, n, A, lda, B, ldb, sequence, request);
    info = LAPACKE_dlag2s_work(LAPACK_COL_MAJOR, m, n, A, lda, B, ldb);
    if (sequence->status == PLASMA_SUCCESS && info != 0)
        plasma_sequence_flush(quark, sequence, request, info);
}

/***************************************************************************//**
 *
 **/
void QUARK_CORE_slag2d(Quark *quark, Quark_Task_Flags *task_flags,
                       int m, int n, int nb,
                       const float *A, int lda,
                       double *B, int ldb)
{
    QUARK_Insert_Task(quark, CORE_slag2d_quark, task_flags,
        sizeof(int),                        &m,     VALUE,
        sizeof(int),                        &n,     VALUE,
        sizeof(float)*nb*nb,    A,             INPUT,
        sizeof(int),                        &lda,   VALUE,
        sizeof(double)*nb*nb,    B,             INOUT,
        sizeof(int),                        &ldb,   VALUE,
        0);
}

/***************************************************************************//**
 *
 **/
#if defined(PLASMA_HAVE_WEAK)
#pragma weak CORE_slag2d_quark = PCORE_slag2d_quark
#define CORE_slag2d_quark PCORE_slag2d_quark
#endif
void CORE_slag2d_quark(Quark *quark)
{
    int m;
    int n;
    float *A;
    int lda;
    double *B;
    int ldb;

    quark_unpack_args_6(quark, m, n, A, lda, B, ldb);
    LAPACKE_slag2d_work(LAPACK_COL_MAJOR, m, n, A, lda, B, ldb);
}


text:
//
// CI Hello World
//
// Copyright (C) 2017 Assured Information Security, Inc.
// Author: Rian Quinn        <quinnr@ainfosec.com>
//
// 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.

#ifndef CONSUMER_H
#define CONSUMER_H

#include <gsl/gsl>
#include <producer.h>

/// Consumer
///
/// A simple example of a consumer that is capable of accepting the real
/// producer, or a mocked version for unit testing.
///
class consumer
{
public:

    /// Default Constructor
    ///
    /// @param p the producer that this consumer will use.
    ///
    explicit consumer(gsl::not_null<producer *> p)
    { p->print_msg(); }

    /// Default Destructor
    ///
    ~consumer() = default;

public:

    // We define the copy and move constructors / operators because Clang Tidy
    // (legitimately) complains about the definition of a destructor without
    // defining the copy and move semantics for this class. In general a class
    // should always be marked non-copyable unless such functionality is
    // specifically desired.

    consumer(consumer &&) noexcept = default;               ///< Default move construction
    consumer &operator=(consumer &&) noexcept = default;    ///< Default move operator

    consumer(const consumer &) = delete;                    ///< Deleted copy construction
    consumer &operator=(const consumer &) = delete;         ///< Deleted copy operator
};

#endif

max_stars_repo_name: lopezfjose/GPP

max_issues_repo_name: lopezfjose/GPP

max_forks_repo_name: lopezfjose/GPP


text:
/**
 *
 * @file qwrapper_dgemv.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 Mark Gates
 * @author Mathieu Faverge
 * @date 2010-11-15
 * @generated d Tue Jan  7 11:44:59 2014
 *
 **/
#include <cblas.h>
#include "common.h"

/***************************************************************************//**
 *
 **/
void QUARK_CORE_dgemv(Quark *quark, Quark_Task_Flags *task_flags,
                      PLASMA_enum trans, int m, int n,
                      double alpha, const double *A, int lda,
                                                const double *x, int incx,
                      double beta,        double *y, int incy)
{
    DAG_CORE_GEMV;
    QUARK_Insert_Task(quark, CORE_dgemv_quark, task_flags,
        sizeof(PLASMA_enum),             &trans,  VALUE,
        sizeof(int),                     &m,      VALUE,
        sizeof(int),                     &n,      VALUE,
        sizeof(double),      &alpha,  VALUE,
        sizeof(double)*m*n,  A,               INPUT,
        sizeof(int),                     &lda,    VALUE,
        sizeof(double)*n,    x,               INPUT,
        sizeof(int),                     &incx,   VALUE,
        sizeof(double),      &beta,   VALUE,
        sizeof(double)*m,    y,               INOUT,
        sizeof(int),                     &incy,   VALUE,
        0);
}

/***************************************************************************//**
 *
 **/
#if defined(PLASMA_HAVE_WEAK)
#pragma weak CORE_dgemv_quark = PCORE_dgemv_quark
#define CORE_dgemv_quark PCORE_dgemv_quark
#endif
void CORE_dgemv_quark(Quark *quark)
{
    PLASMA_enum trans;
    int m, n, lda, incx, incy;
    double alpha, beta;
    const double *A, *x;
    double *y;

    quark_unpack_args_11( quark, trans, m, n, alpha, A, lda, x, incx, beta, y, incy );
    cblas_dgemv(
        CblasColMajor,
        (CBLAS_TRANSPOSE)trans,
        m, n,
        (alpha), A, lda,
                            x, incx,
        (beta),  y, incy);
}


text:
#include "ccv.h"
#ifdef HAVE_CBLAS
#include <cblas.h>
#endif

double ccv_trace(ccv_matrix_t* mat)
{
	return 0;
}

double ccv_norm(ccv_matrix_t* mat, int type)
{
	return 0;
}

double ccv_normalize(ccv_matrix_t* a, ccv_matrix_t** b, int btype, int l_type)
{
	ccv_dense_matrix_t* da = ccv_get_dense_matrix(a);
	assert(CCV_GET_CHANNEL(da->type) == CCV_C1);
	char identifier[20];
	memset(identifier, 0, 20);
	snprintf(identifier, 20, "ccv_normalize(%d)", l_type);
	uint64_t sig = (da->sig == 0) ? 0 : ccv_matrix_generate_signature(identifier, 20, da->sig, 0);
	btype = (btype == 0) ? CCV_GET_DATA_TYPE(da->type) | CCV_C1 : CCV_GET_DATA_TYPE(btype) | CCV_C1;
	ccv_dense_matrix_t* db = *b = ccv_dense_matrix_renew(*b, da->rows, da->cols, CCV_ALL_DATA_TYPE | CCV_C1, btype, sig);
	ccv_cache_return(db, 0);
	double sum = 0;
	int i, j;
	unsigned char* a_ptr = da->data.ptr;
	unsigned char* b_ptr = db->data.ptr;
	switch (l_type)
	{
		case CCV_L2_NORM:
#define for_block(__for_set, __for_get) \
			for (i = 0; i < da->rows; i++) \
			{ \
				for (j = 0; j < da->cols; j++) \
					sum += __for_get(a_ptr, j, 0) * __for_get(a_ptr, j, 0); \
				a_ptr += da->step; \
			} \
			sum = sqrt(sum); \
			double inv = 1.0 / sqrt(sum); \
			a_ptr = da->data.ptr; \
			for (i = 0; i < da->rows; i++) \
			{ \
				for (j = 0; j < da->cols; j++) \
					__for_set(b_ptr, j, __for_get(a_ptr, j, 0) * inv, 0); \
				a_ptr += da->step; \
				b_ptr += db->step; \
			}
			ccv_matrix_setter(db->type, ccv_matrix_getter, da->type, for_block);
#undef for_block
			break;
	}
	return sum;
}

double ccv_sum(ccv_matrix_t* mat)
{
	ccv_dense_matrix_t* dmt = ccv_get_dense_matrix(mat);
	double sum = 0;
	unsigned char* m_ptr = dmt->data.ptr;
	int i, j;
#define for_block(dummy, __for_get) \
	for (i = 0; i < dmt->rows; i++) \
	{ \
		for (j = 0; j < dmt->cols; j++) \
			sum += __for_get(m_ptr, j, 0); \
		m_ptr += dmt->step; \
	}
	ccv_matrix_getter(dmt->type, for_block);
#undef for_block
	return sum;
}

void ccv_zero(ccv_matrix_t* mat)
{
	ccv_dense_matrix_t* dmt = ccv_get_dense_matrix(mat);
	memset(dmt->data.ptr, 0, dmt->step * dmt->rows);
}

void ccv_substract(ccv_matrix_t* a, ccv_matrix_t* b, ccv_matrix_t** c, int type)
{
	ccv_dense_matrix_t* da = ccv_get_dense_matrix(a);
	ccv_dense_matrix_t* db = ccv_get_dense_matrix(b);
	assert(da->rows == db->rows && da->cols == db->cols && CCV_GET_DATA_TYPE(da->type) == CCV_GET_DATA_TYPE(db->type) && CCV_GET_CHANNEL(da->type) == CCV_GET_CHANNEL(db->type));
	uint64_t sig = ccv_matrix_generate_signature("ccv_substract", 13, da->sig, db->sig, 0);
	int no_8u_type = (da->type & CCV_8U) ? CCV_32S : da->type;
	type = (type == 0) ? CCV_GET_DATA_TYPE(no_8u_type) | CCV_GET_CHANNEL(da->type) : CCV_GET_DATA_TYPE(type) | CCV_GET_CHANNEL(da->type);
	ccv_dense_matrix_t* dc = *c = ccv_dense_matrix_renew(*c, da->rows, da->cols, CCV_ALL_DATA_TYPE | CCV_GET_CHANNEL(da->type), type, sig);
	ccv_cache_return(dc, );
	int i, j;
	unsigned char* aptr = da->data.ptr;
	unsigned char* bptr = db->data.ptr;
	unsigned char* cptr = dc->data.ptr;
#define for_block(__for_get, __for_set) \
	for (i = 0; i < da->rows; i++) \
	{ \
		for (j = 0; j < da->cols; j++) \
		{ \
			__for_set(cptr, j, __for_get(aptr, j, 0) - __for_get(bptr, j, 0), 0); \
		} \
		aptr += da->step; \
		bptr += db->step; \
		cptr += dc->step; \
	}
	ccv_matrix_getter(da->type, ccv_matrix_setter, dc->type, for_block);
#undef for_block
}

void ccv_gemm(ccv_matrix_t* a, ccv_matrix_t* b, double alpha, ccv_matrix_t* c, double beta, int transpose, ccv_matrix_t** d, int type)
{
	ccv_dense_matrix_t* da = ccv_get_dense_matrix(a);
	ccv_dense_matrix_t* db = ccv_get_dense_matrix(b);
	ccv_dense_matrix_t* dc = (c == 0) ? 0 : ccv_get_dense_matrix(c);

	assert(CCV_GET_DATA_TYPE(da->type) == CCV_GET_DATA_TYPE(db->type) && CCV_GET_CHANNEL_NUM(da->type) == 1 && CCV_GET_CHANNEL_NUM(db->type) == 1 && ((transpose & CCV_A_TRANSPOSE) ? da->rows : da->cols) == ((transpose & CCV_B_TRANSPOSE) ? db->cols : db->rows));

	if (dc != 0)
		assert(CCV_GET_DATA_TYPE(dc->type) == CCV_GET_DATA_TYPE(da->type) && CCV_GET_CHANNEL_NUM(dc->type) == 1 && ((transpose & CCV_A_TRANSPOSE) ? da->cols : da->rows) == dc->rows && ((transpose & CCV_B_TRANSPOSE) ? db->rows : db->cols) == dc->cols);

	char identifier[20];
	memset(identifier, 0, 20);
	snprintf(identifier, 20, "ccv_gemm(%d)", transpose);
	uint64_t sig = (dc == 0) ? ((da->sig == 0 || db->sig == 0) ? 0 : ccv_matrix_generate_signature(identifier, 20, da->sig, db->sig, 0)) : ((da->sig == 0 || db->sig == 0 || dc->sig == 0) ? 0 : ccv_matrix_generate_signature(identifier, 20, da->sig, db->sig, dc->sig, 0));
	type = CCV_GET_DATA_TYPE(da->type) | CCV_GET_CHANNEL(da->type);
	ccv_dense_matrix_t* dd = *d = ccv_dense_matrix_renew(*d, (transpose & CCV_A_TRANSPOSE) ? da->cols : da->rows, (transpose & CCV_B_TRANSPOSE) ? db->rows : db->cols, type, type, sig);
	ccv_cache_return(dd, );

	if (dd != dc && dc != 0)
		memcpy(dd->data.ptr, dc->data.ptr, dc->step * dc->rows);

#ifdef HAVE_CBLAS
	switch (CCV_GET_DATA_TYPE(dd->type))
	{
		case CCV_32F:
			cblas_sgemm(CblasRowMajor, (transpose & CCV_A_TRANSPOSE) ? CblasTrans : CblasNoTrans, (transpose & CCV_B_TRANSPOSE) ? CblasTrans : CblasNoTrans, dd->rows, dd->cols, da->cols, alpha, da->data.fl, da->cols, db->data.fl, db->cols, beta, dd->data.fl, dd->cols);
			break;
		case CCV_64F:
			cblas_dgemm(CblasRowMajor, (transpose & CCV_A_TRANSPOSE) ? CblasTrans : CblasNoTrans, (transpose & CCV_B_TRANSPOSE) ? CblasTrans : CblasNoTrans, dd->rows, dd->cols, (transpose & CCV_A_TRANSPOSE) ? da->rows : da->cols, alpha, da->data.db, da->cols, db->data.db, db->cols, beta, dd->data.db, dd->cols);
			break;
	}
#endif
}

max_stars_repo_name: deminew/ccv

max_issues_repo_name: deminew/ccv

max_forks_repo_name: deminew/ccv


text:
/*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*
**                                                                                **
** This file forms part of the Underworld geophysics modelling application.         **
**                                                                                **
** For full license and copyright information, please refer to the LICENSE.md file  **
** located at the project root, or contact the authors.                             **
**                                                                                **
**~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*/
#include <petsc.h>
#include <petscvec.h>
#include <petscmat.h>

#include <StGermain/libStGermain/src/StGermain.h>
#include <StgDomain/libStgDomain/src/StgDomain.h>

#include "common-driver-utils.h"

/*
name[] is operator name
*/
PetscErrorCode BSSCR_MatInfoLog(PetscViewer v,Mat A,const char name[])
{
	MatInfo i;
	PetscReal nrm_1,nrm_f,nrm_inf;
	MatType mtype;
	PetscInt M,N;
	PetscViewerType vtype;
	PetscTruth isascii;

	PetscViewerGetType( v, &vtype );
	Stg_PetscObjectTypeCompare( (PetscObject)v,PETSC_VIEWER_ASCII,&isascii );
	if (!isascii) { PetscFunctionReturn(0); }

	MatGetSize( A, &M,&N );
	MatGetInfo(A,MAT_GLOBAL_SUM,&i);

	MatGetType( A, &mtype );
	MatNorm( A, NORM_1, &nrm_1 );
	MatNorm( A, NORM_FROBENIUS, &nrm_f );
	MatNorm( A, NORM_INFINITY, &nrm_inf );

	PetscViewerASCIIPrintf( v, "MatInfo: %s \n", name );
	PetscViewerASCIIPushTab(v);

	PetscViewerASCIIPrintf( v, "type=%s \n", mtype );
	PetscViewerASCIIPrintf( v, "dimension=%Dx%D \n", M,N );
	PetscViewerASCIIPrintf( v, "nnz=%D (total)\n", (PetscInt)i.nz_used );
	PetscViewerASCIIPrintf( v, "nnz=%D (allocated)\n", (PetscInt)i.nz_allocated );
	PetscViewerASCIIPrintf( v, "|A|_1         = %1.12e\n", nrm_1 );
	PetscViewerASCIIPrintf( v, "|A|_frobenius = %1.12e\n", nrm_f );
	PetscViewerASCIIPrintf( v, "|A|_inf       = %1.12e\n", nrm_inf );

	PetscViewerASCIIPopTab(v);

	PetscFunctionReturn(0);
}

/*
name[] is operator name
*/
PetscErrorCode BSSCR_VecInfoLog(PetscViewer v,Vec x,const char name[])
{
	PetscReal nrm_1,nrm_f,nrm_inf;
	VecType vectype;
	PetscInt M;
	PetscViewerType vtype;
	PetscTruth isascii;

	PetscViewerGetType( v, &vtype );
	Stg_PetscObjectTypeCompare( (PetscObject)v,PETSC_VIEWER_ASCII,&isascii );
	if (!isascii) { PetscFunctionReturn(0); }

	VecGetSize( x, &M);

	VecGetType( x, &vectype );
	VecNorm( x, NORM_1, &nrm_1 );
	VecNorm( x, NORM_2, &nrm_f );
	VecNorm( x, NORM_INFINITY, &nrm_inf );

	PetscViewerASCIIPrintf( v, "VecInfo: %s \n", name );
	PetscViewerASCIIPushTab(v);

	PetscViewerASCIIPrintf( v, "type=%s \n", vectype );
	PetscViewerASCIIPrintf( v, "dimension=%Dx1 \n", M);
	PetscViewerASCIIPrintf( v, "|x|_1   = %1.12e\n", nrm_1 );
	PetscViewerASCIIPrintf( v, "|x|_2   = %1.12e\n", nrm_f );
	PetscViewerASCIIPrintf( v, "|x|_inf = %1.12e\n", nrm_inf );

	PetscViewerASCIIPopTab(v);

	PetscFunctionReturn(0);
}

PetscErrorCode BSSCR_StokesCreateOperatorSummary( Mat K, Mat G, Mat C, Vec f, Vec h, const char filename[] )
{
	MPI_Comm comm;
	PetscViewer v;
	char op_name[PETSC_MAX_PATH_LEN];
	PetscTruth flg;

	PetscObjectGetComm( (PetscObject)K, &comm );
	PetscViewerASCIIOpen( comm, filename, &v );

	BSSCR_GeneratePetscHeader_for_viewer( v );
	PetscViewerASCIIPrintf( v, "\nInput matrices:\n");
	PetscViewerASCIIPushTab(v);

	PetscOptionsGetString( PETSC_NULL,"-stokes_A11",op_name,PETSC_MAX_PATH_LEN-1,&flg );
	if (flg) {	PetscViewerASCIIPrintf( v, "A11: %s\n", op_name );	}

	PetscOptionsGetString( PETSC_NULL,"-stokes_A12",op_name,PETSC_MAX_PATH_LEN-1,&flg );
	if (flg) {	PetscViewerASCIIPrintf( v, "A12: %s\n", op_name );	}

	PetscOptionsGetString( PETSC_NULL,"-stokes_A22",op_name,PETSC_MAX_PATH_LEN-1,&flg );
	if (flg) {	PetscViewerASCIIPrintf( v, "A22: %s\n", op_name );	}

	PetscOptionsGetString( PETSC_NULL,"-stokes_Smat",op_name,PETSC_MAX_PATH_LEN-1,&flg );
	if (flg) {	PetscViewerASCIIPrintf( v, "Smat: %s\n", op_name );	}

	PetscOptionsGetString( PETSC_NULL,"-stokes_b1",op_name,PETSC_MAX_PATH_LEN-1,&flg );
	if (flg) {	PetscViewerASCIIPrintf( v, "b1: %s\n", op_name );	}

	PetscOptionsGetString( PETSC_NULL,"-stokes_b2",op_name,PETSC_MAX_PATH_LEN-1,&flg );
	if (flg) {	PetscViewerASCIIPrintf( v, "b2: %s\n", op_name );	}

	PetscViewerASCIIPopTab(v);
	PetscViewerASCIIPrintf( v, "\n");

	BSSCR_MatInfoLog(v,K,"stokes_A11");			PetscViewerASCIIPrintf( v, "\n");

	BSSCR_MatInfoLog(v,G,"stokes_A12");			PetscViewerASCIIPrintf( v, "\n");
	if (C) { BSSCR_MatInfoLog(v,C,"stokes_A22"); 		PetscViewerASCIIPrintf( v, "\n");	}

	BSSCR_VecInfoLog(v,f,"stokes_b1");			PetscViewerASCIIPrintf( v, "\n");
	BSSCR_VecInfoLog(v,h,"stokes_b2");			PetscViewerASCIIPrintf( v, "\n");

	Stg_PetscViewerDestroy(&v );

	PetscFunctionReturn(0);
}


text:
#pragma once
#include "BufferView.h"
#include "Enum.h"
#include "Error.h"
#include "parsers/Parsing.h"
#include <boost/hana/define_struct.hpp>
#include <gsl/span>

namespace gltfpp {
	inline namespace v1 {
		BETTER_ENUM(AccessorComponentType,
		            int,
		            BYTE = 5120,
		            UNSIGNED_BYTE = 5121,
		            SHORT = 5122,
		            UNSIGNED_SHORT = 5123,
		            UNSIGNED_INT = 5125,
		            FLOAT = 5126)

		BETTER_ENUM(AccessorType, int, SCALAR, VEC2, VEC3, VEC4, MAT2, MAT3, MAT4)

		constexpr auto AccessorTypeComponentCount =
		    boost::hana::make_map(boost::hana::make_pair(boost::hana::int_c<(int)AccessorType::SCALAR>, 1),
		                          boost::hana::make_pair(boost::hana::int_c<(int)AccessorType::VEC2>, 2),
		                          boost::hana::make_pair(boost::hana::int_c<(int)AccessorType::VEC3>, 3),
		                          boost::hana::make_pair(boost::hana::int_c<(int)AccessorType::VEC4>, 4),
		                          boost::hana::make_pair(boost::hana::int_c<(int)AccessorType::MAT2>, 4),
		                          boost::hana::make_pair(boost::hana::int_c<(int)AccessorType::MAT3>, 9),
		                          boost::hana::make_pair(boost::hana::int_c<(int)AccessorType::MAT4>, 16));

		struct Accessor {
			BOOST_HANA_DEFINE_STRUCT(Accessor,
			                         (bool, normalized),
			                         (std::vector<double>, min),
			                         (std::vector<double>, max),
			                         (option<std::string>, name),
			                         (option<nlohmann::json>, sparse),
			                         (option<nlohmann::json>, extensions),
			                         (option<nlohmann::json>, extras),
			                         (ptrdiff_t, byteOffset),
			                         (size_t, count),
			                         (AccessorComponentType, componentType));
			BufferView const *bufferView;
		};

		auto parse(Accessor &) noexcept;
	}    // namespace v1
}    // namespace gltfpp

max_stars_repo_name: mmha/gltfpp

max_issues_repo_name: mmha/gltfpp

max_forks_repo_name: mmha/gltfpp


text:
/* Copyright 2019-2021 Canaan Inc.
 *
 * 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.
 */
#pragma once
#include <gsl/gsl-lite.hpp>
#include <type_traits>

#if defined(_MSC_VER)
#ifdef NNCASE_DLL
#define NNCASE_API __declspec(dllexport)
#elif defined(NNCASE_SHARED_LIBS)
#define NNCASE_API __declspec(dllimport)
#else
#define NNCASE_API
#endif
#else
#define NNCASE_API
#endif

#if defined(_MSC_VER)
#define NNCASE_UNREACHABLE() __assume(0)
#else
#define NNCASE_UNREACHABLE() __builtin_unreachable()
#endif

#if gsl_CPP17_OR_GREATER
#define NNCASE_INLINE_VAR inline
#define NNCASE_UNUSED [[maybe_unused]]
namespace nncase
{
template <class Callable, class... Args>
using invoke_result_t = std::invoke_result_t<Callable, Args...>;
}
#else
#define NNCASE_INLINE_VAR
#if defined(_MSC_VER)
#define NNCASE_UNUSED
#else
#define NNCASE_UNUSED __attribute__((unused))
#endif
namespace nncase
{
template <class Callable, class... Args>
using invoke_result_t = std::result_of_t<Callable(Args...)>;
}
#endif

#define NNCASE_LITTLE_ENDIAN 1

#define NNCASE_HAVE_STD_BYTE gsl_CPP17_OR_GREATER
#define NNCASE_NODISCARD gsl_NODISCARD
#define NNCASE_NORETURN gsl_NORETURN

#define BEGIN_NS_NNCASE_RUNTIME \
    namespace nncase            \
    {                           \
        namespace runtime       \
        {
#define END_NS_NNCASE_RUNTIME \
    }                         \
    }

#define BEGIN_NS_NNCASE_RT_MODULE(MODULE) \
    namespace nncase                      \
    {                                     \
        namespace runtime                 \
        {                                 \
            namespace MODULE              \
            {

#define END_NS_NNCASE_RT_MODULE \
    }                           \
    }                           \
    }

#define BEGIN_NS_NNCASE_KERNELS \
    namespace nncase            \
    {                           \
        namespace kernels       \
        {

#define END_NS_NNCASE_KERNELS \
    }                         \
    }

#ifndef DEFINE_ENUM_BITMASK_OPERATORS
#define DEFINE_ENUM_BITMASK_OPERATORS(ENUMTYPE) gsl_DEFINE_ENUM_BITMASK_OPERATORS(ENUMTYPE)
#endif

namespace nncase
{
struct default_init_t
{
};

NNCASE_INLINE_VAR constexpr default_init_t default_init {};
}

max_stars_repo_name: annosoo/nncase

max_issues_repo_name: annosoo/nncase

max_forks_repo_name: annosoo/nncase