text:
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.

#pragma once

#define NOMINMAX
#define WIN32_LEAN_AND_MEAN

#include <array>
#include <iomanip>
#include <optional>
#include <sstream>
#include <string_view>
#include <thread>
#include <unordered_map>
#include <unordered_set>
#include <vector>

#include <d2d1.h>
#include <d3d11_1.h>
#include <d3dcompiler.h>
#include <dwrite_3.h>
#include <dcomp.h>
#include <dxgi1_3.h>
#include <dxgidebug.h>
#include <VersionHelpers.h>

#include <gsl/gsl_util>
#include <gsl/pointers>
#include <gsl/span>
#include <wil/com.h>
#include <wil/filesystem.h>
#include <wil/result_macros.h>
#include <wil/stl.h>
#include <wil/win32_helpers.h>

// Dynamic Bitset (optional dependency on LibPopCnt for perf at bit counting)
// Variable-size compressed-storage header-only bit flag storage library.
#pragma warning(push)
#pragma warning(disable : 4702) // unreachable code
#include <dynamic_bitset.hpp>
#pragma warning(pop)

// Chromium Numerics (safe math)
#pragma warning(push)
#pragma warning(disable : 4100) // '...': unreferenced formal parameter
#pragma warning(disable : 26812) // The enum type '...' is unscoped. Prefer 'enum class' over 'enum' (Enum.3).
#include <base/numerics/safe_math.h>
#pragma warning(pop)

#include <til.h>
#include <til/bit.h>

max_stars_repo_name: by-memory/terminal

max_issues_repo_name: by-memory/terminal

max_forks_repo_name: by-memory/terminal


text:
#ifndef __KILLDUPTRKS_H__
#define __KILLDUPTRKS_H__

#include <cstddef>
#include <vector>
#include <algorithm>
#include <functional>
#include <utility>
#include <iostream>

#include "L1Trigger/TrackFindingTMTT/interface/Settings.h"
#include "L1Trigger/TrackFindingTMTT/interface/Stub.h"
#include "L1Trigger/TrackFindingTMTT/interface/TP.h"
#include "FWCore/Utilities/interface/Exception.h"
#include <gsl/gsl_fit.h>

using namespace std;

/**
*  Kill duplicate reconstructed tracks.
*  e.g. Those sharing many hits in common.
*
*  Currently this is intended to run only on tracks found within a single (eta,phi) sector.
*  It includes a naive algorithms from Ian (dupTrkAlg = 1) & more sophisticated ones from Ivan (dupTrkAlg > 1).
*  The class is implemented inside L1Trigger/TrackFindingTMTT/interface/KillDupTrks.icc
*
*  The template class "T" can be any class inheriting from L1trackBase.
*
*  -------------------------------------------------------------------------------------------
*   GENERAL INFO ABOUT THE FILTER ALGORITHMS DEFINED IN THE CLASS.
*   Some of these algorithms are designed to work on r-phi L1track2D tracks, and some on r-z
*   L1track2D tracks. Others work on L1tracks3D.
*  -------------------------------------------------------------------------------------------
*/

namespace TMTT {

class L1trackBase;
class L1track2D;
class L1track3D;
class L1fittedTrack;

template <class T> class KillDupTrks {

public:

  KillDupTrks()
	{
    // Check that classed used as template "T" inherits from class L1trackBase.
    static_assert(std::is_base_of<L1trackBase, T>::value, "KillDupTrks ERROR: You instantiated this with a template class not inheriting from L1trackBase!");
  }

  ~KillDupTrks() {}

  /**
  *  Make available cfg parameters & specify which algorithm is to be used for duplicate track removal.
  */
  void init(const Settings* settings, unsigned int dupTrkAlg);

  /**
  *  Eliminate duplicate tracks from the input collection, and so return a reduced list of tracks.
  */
  vector<T> filter(const vector<T>& vecTracks) const;

private:

  /**
  *  Implementing "inverse" OSU algorithm, check for stubs in common,
  *  keep largest candidates if common stubs in N or more layers (default 5 at present), both if equal
  *  Implementing "inverse" OSU algorithm, check for stubs in common,
  *  keep largest candidates if common stubs in N or more layers (default 5 at present), both if equal
  */
  vector<T> filterAlg8(const vector<T>& vecTracks) const;

  /** Implementing "inverse" OSU algorithm, check for layers in common, reverse order as per Luis's suggestion
   * Comparison window of up to 6
   * Modified version of Algo23, looking for layers in common as in Algo8
   * Check if N or more common layers (default 5 at present)
   * Then keep candidate with most stubs, use |q/pT| as tie-break, finally drop "latest" if still equal
   */
vector<T> filterAlg25(const vector<T>& vecTracks) const;

  /**
  *  Prints out a consistently formatted formatted report of killed duplicate track
  */
  void printKill(unsigned alg, unsigned dup, unsigned cand, T dupTrack, T candTrack) const;

  /**
  * Counts candidate layers with stubs in common
  */
  unsigned int layerMatches(std::vector< std::pair<unsigned int, unsigned int> >* iStubs,
			    std::vector< std::pair<unsigned int, unsigned int> >* jStubs) const;
private:

  const Settings *settings_; // Configuration parameters.

  unsigned int dupTrkAlg_; // Specifies choice of algorithm for duplicate track removal.
  unsigned int dupTrkMinCommonHitsLayers_;  // Min no of matched stubs & layers to keep smaller cand
};

}
//=== Include file which implements all the functions in the above class.
#include "L1Trigger/TrackFindingTMTT/interface/KillDupTrks.icc"

#endif

ext: h

max_stars_repo_name: djcranshaw/cmssw

max_issues_repo_name: djcranshaw/cmssw

max_forks_repo_name: djcranshaw/cmssw


text:
/**
 * \file TypedBaseFilter.h
 */

#ifndef ATK_CORE_TYPEDBASEFILTER_H
#define ATK_CORE_TYPEDBASEFILTER_H

#include <ATK/Core/BaseFilter.h>
#include <ATK/Core/TypeTraits.h>

#include <memory>
#include <vector>

#include <boost/align/aligned_allocator.hpp>

#include <gsl/gsl>

namespace ATK
{
  const gsl::index ALIGNMENT = 32;

  /// Interface for output filters
  template<typename DataType>
  class ATK_CORE_EXPORT OutputArrayInterface
  {
  public:
    virtual ~OutputArrayInterface() = default;

    /**
     * @brief Returns an array with the processed output
     * @param port is the port that the next plugin listens to
     */
    virtual DataType* get_output_array(gsl::index port) const = 0;
    /**
     * Returns the size of the output arrays (usually the last size processed)
     */
    virtual gsl::index get_output_array_size() const = 0;
  };

  /// Base class for typed filters, contains arrays
  template<typename DataType_, typename DataType__ = DataType_>
  class ATK_CORE_EXPORT TypedBaseFilter : public BaseFilter, public OutputArrayInterface<DataType__>
  {
  protected:
    /// Simplify parent calls
    using Parent = BaseFilter;
  public:
    /// To be used by inherited APIs
    using DataType = DataType_;
    /// To be used by inherited APIs
    using DataTypeInput = DataType_;
    /// To be used by inherited APIs
    using DataTypeOutput = DataType__;
    /// To be used for filters that require aligned data
    using AlignedVector = std::vector<DataTypeInput, boost::alignment::aligned_allocator<DataTypeInput, ALIGNMENT> >;
    /// To be used for filters that require aligned data for output data
    using AlignedOutVector = std::vector<DataTypeOutput, boost::alignment::aligned_allocator<DataTypeOutput, ALIGNMENT> >;
    /// To be used for filters that required aligned data for parameters (like EQ)
    using AlignedScalarVector = std::vector<typename TypeTraits<DataType>::Scalar, boost::alignment::aligned_allocator<typename TypeTraits<DataType>::Scalar, ALIGNMENT> >;

    /// Base constructor for filters with actual data
    TypedBaseFilter(gsl::index nb_input_ports, gsl::index nb_output_ports);
    /// Move constructor
    TypedBaseFilter(TypedBaseFilter&& other);
    /// Destructor
    ~TypedBaseFilter() override = default;

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

    /**
     * @brief Returns an array with the processed output
     * @param port is the port that the next plugin listens to
     */
    DataType__* get_output_array(gsl::index port) const final;
    gsl::index get_output_array_size() const final;

    void set_nb_input_ports(gsl::index nb_ports) override;
    void set_nb_output_ports(gsl::index nb_ports) override;

    void full_setup() override;

    /// Connects this filter input to another's output
    void set_input_port(gsl::index input_port, gsl::not_null<BaseFilter*> filter, gsl::index output_port) final;
    void set_input_port(gsl::index input_port, BaseFilter& filter, gsl::index output_port) final;

  private:
    int get_type() const override;
  protected:
    /// This implementation does nothing
    void process_impl(gsl::index size) const override;
    /// Prepares the filter by retrieving the inputs arrays
    void prepare_process(gsl::index size) final;
    /// Prepares the filter by resizing the outputs arrays
    void prepare_outputs(gsl::index size) final;

    /// Used to convert other filter outputs to DataType*
    void convert_inputs(gsl::index size);

    /// Input arrays with the input delay, owned here
    std::vector<AlignedVector> converted_inputs_delay;
    /// Input arrays, starting from t=0 (without input delay)
    std::vector<DataTypeInput*> converted_inputs;
    /// Current size of the input arrays, without delay
    std::vector<gsl::index> converted_inputs_size;
    /// Current input delay
    std::vector<gsl::index> converted_in_delays;
    /// Pointer to the output interface of the connected filters
    std::vector<OutputArrayInterface<DataType_>*> direct_filters;

    /// Output arrays with the output delay, owned here
    std::vector<AlignedOutVector> outputs_delay;
    /// Output arrays, starting from t=0 (without output delay)
    std::vector<DataTypeOutput*> outputs;
    /// Current size of the output arrays, without delay
    std::vector<gsl::index> outputs_size;
    /// Current output delay
    std::vector<gsl::index> out_delays;

    /// A vector containing the default values for the input arrays
    AlignedVector default_input;
    /// A vector containing the default values for the output arrays
    AlignedOutVector default_output;
  };
}

#endif

max_stars_repo_name: D-J-Roberts/AudioTK

max_issues_repo_name: D-J-Roberts/AudioTK

max_forks_repo_name: D-J-Roberts/AudioTK


text:
#include <lapacke.h>
int main() { LAPACKE_dlapy2(0, 0); }

ext: c

max_stars_repo_name: t-sakashita/rokko

max_issues_repo_name: t-sakashita/rokko

max_forks_repo_name: t-sakashita/rokko


text:
#include <math.h>
#include <gsl/gsl_errno.h>
#include "advanceCN.h"
#include "advanceBE.h"
#include "checkpoint.h"
#include "driver.h"
#include "setup.h"
#include "userFunc.h"

/**************************************************************************/
/* Driver routine                                                         */
/**************************************************************************/

double
driver(
       /* Time parameters */
       const double tStart,
       const double tEnd,
       /* Equation of state parameters */
       const bool eos_func,
       const double gamma_val,
       const double delta_val,
       /* Dimensionless viscosity parameters */
       const bool alpha_func,
       const double alpha_val,
       /* Inner boundary condition parameters */
       const pres_bc_type ibc_pres,
       const enth_bc_type ibc_enth,
       const bool ibc_func,
       const double ibc_pres_val,
       const double ibc_enth_val,
       /* Outer boundary condition parameters */
       const pres_bc_type obc_pres,
       const enth_bc_type obc_enth,
       const bool obc_func,
       const double obc_pres_val,
       const double obc_enth_val,
       /* Source function parameters */
       const bool massSrc_func,
       const double massSrc_val,
       const bool intEnSrc_func,
       const double intEnSrc_val,
       /* Control and method parameters */
       const double dtStart,
       const double dtMin,
       const double dtTol,
       const double errTol,
       const double maxDtIncrease,
       const unsigned long maxIter,
       const unsigned long interpOrder,
       const unsigned long maxStep,
       const bool useBE,
       const bool preTimestep_func,
       const bool postTimestep_func,
       const unsigned long verbosity,
       /* Output control parameters */
       const unsigned long nSave,
       const double *tSave,
       const unsigned long nUserOut,
       const bool *userOutCum,
       const bool *writeCheckpoint,
       const char *checkname,
       const bool userWriteCheckpoint,
       const bool writeFirstStep,
       const unsigned long checknum,
       /* Computational grid and workspace */
       const grid *grd,
       const wksp *w,
       /* Input data */
       double *col,
       double *pres,
       double *eInt,
       /* User-defined extra parameters */
       void *params,
       /* Diagnostic outputs */
       unsigned long *nStep,
       unsigned long *nIter,
       unsigned long *nFail,
       /* Storage for outputs */
       unsigned long *nOut,
       double *tOut,
       double *colOut,
       double *presOut,
       double *eIntOut,
       double *mBndOut,
       double *eBndOut,
       double *mSrcOut,
       double *eSrcOut,
       double *userOut
#ifdef TESTING_MODE
       /* Parameters used in code tests */
       , double *residSum, unsigned long *iterStep,
       double *driverTime, double *advanceTime,
       double *nextIterTime, double *userTime
#endif
       ) {
;
  status stat = RUNNING;
  double t = tStart;
  double dt = dtStart;
  bool writeOut = writeFirstStep;
  unsigned long savePtr = 0, chkPtr = checknum;
  double dtNew;
  unsigned long i, j;
  unsigned long nIterTmp, nreduce;
#ifdef TESTING_MODE
  unsigned long *residType;
  clock_t start_t, end_t;

  /* Start the clocks */
  start_t = clock();
  *advanceTime = *nextIterTime = *userTime = 0.0;

  /* In testing mode, allocate memory for diagnostic array */
  if (!(residType = calloc(maxIter, sizeof(unsigned long)))) {
    fprintf(stderr, "Error: unable to allocate memory for diagnostic arrays!\n");
    exit(1);
  }

  /* In testing mode, initialize sum of residuals and iteration
     counter arrays */
  for (i=0; i<maxIter; i++) residSum[i] = 0.0;
  for (i=0; i<maxStep; i++) iterStep[i] = 0;
#endif

  /* Begin main loop */
  while (stat == RUNNING) {

    /* Print status */
    if (verbosity > 1) {
      printf("Step %ld, t = %e, dt = %e\n", *nStep, t, dt);
    } else if (verbosity > 0) {
      if (*nStep % 100 == 0) {
	printf("Step %ld, t = %e, dt = %e\n", *nStep, t, dt);
      }
    }

    /* Call user work function */
    if (preTimestep_func) {

      userPreTimestep(t, dt, grd, col, pres, eInt, mBndOut+2*(*nOut),
		      eBndOut+2*(*nOut), mSrcOut+grd->nr*(*nOut),
		      eSrcOut+grd->nr*(*nOut), params, nUserOut,
		      userOut+nUserOut*grd->nr*(*nOut));
    }

    /* Try to advance */
    dtNew = -1.0;
    nreduce = 0;
    while (dtNew < 0) {
      if (useBE == 0) {

	dtNew = advanceCN(t, dt, grd, col, pres, eInt,
			  mBndOut+2*(*nOut),
			  eBndOut+2*(*nOut),
			  mSrcOut+grd->nr*(*nOut),
			  eSrcOut+grd->nr*(*nOut),
			  eos_func, gamma_val, delta_val,
			  alpha_func, alpha_val,
			  ibc_pres, ibc_enth,
			  ibc_func, ibc_pres_val, ibc_enth_val,
			  obc_pres, obc_enth,
			  obc_func, obc_pres_val, obc_enth_val,
			  massSrc_func, massSrc_val,
			  intEnSrc_func, intEnSrc_val,
			  errTol, dtTol, maxIter,
			  interpOrder, false, verbosity > 2, w, params,
			  &nIterTmp
#ifdef TESTING_MODE
			  , residSum, residType,
			  advanceTime, nextIterTime, userTime
#endif
			  );
      } else {
	dtNew = advanceBE(t, dt, grd, col, pres, eInt,
			  mBndOut+2*(*nOut),
			  eBndOut+2*(*nOut),
			  mSrcOut+grd->nr*(*nOut),
			  eSrcOut+grd->nr*(*nOut),
			  eos_func, gamma_val, delta_val,
			  alpha_func, alpha_val,
			  ibc_pres, ibc_enth,
			  ibc_func, ibc_pres_val, ibc_enth_val,
			  obc_pres, obc_enth,
			  obc_func, obc_pres_val, obc_enth_val,
			  massSrc_func, massSrc_val,
			  intEnSrc_func, intEnSrc_val,
			  errTol, dtTol, maxIter,
			  interpOrder, false, verbosity > 2, w, params,
			  &nIterTmp
#ifdef TESTING_MODE
			  , residSum, residType,
			  advanceTime, nextIterTime, userTime
#endif
			  );
      }

      /* Upate iteration count. We do it here to ensure that we count
	 iterations even if they fail to converge. */
      *nIter += nIterTmp;
#ifdef TESTING_MODE
      iterStep[*nStep-1] += nIterTmp;
#endif
      if (dtNew < 0) {
	writeOut = false;
	dt = dt/2.0;
	nreduce++;
	(*nFail)++;
	if (verbosity > 1)
	  printf("   Iterative solver non-convergence! Reducing dt to %e.\n", dt);
	if (dt < dtMin*(tEnd - tStart)) {
	  stat = ZENO_ERROR;
	  dtNew = dt;
	  break;
	}
      }
    }
    for (i=0; i<nreduce; i++) dtNew = dtNew / 2;

    /* Update time and step counter */
    t += dt;
    (*nStep)++;

    /* Call user work function */
    if (postTimestep_func) {
      userPostTimestep(t, dt, grd, col, pres, eInt, mBndOut+2*(*nOut),
		       eBndOut+2*(*nOut), mSrcOut+grd->nr*(*nOut),
		       eSrcOut+grd->nr*(*nOut), params, nUserOut,
		       userOut+nUserOut*grd->nr*(*nOut));
    }

    /* If requested, scale back the next time step */
    if (dtNew/dt > maxDtIncrease) dtNew = maxDtIncrease * dt;

    /* Store state */
    if (writeOut) {
      if (verbosity > 0)
	printf("Storing output %lu at step %lu, time %e\n", (*nOut)+1,
	       (*nStep)-1, t);
      tOut[(*nOut)] = t;
      for (i=0; i<grd->nr; i++) {
	colOut[i + (*nOut)*grd->nr] = col[i];
	presOut[i + (*nOut)*grd->nr] = pres[i];
	if (eos_func) eIntOut[i + (*nOut)*grd->nr] = eInt[i];
      }
      /* Boundary and source values are cumulative, so just copy the
      final value during this output interval into the slot for the
      next interval */
      if (savePtr<nSave-1) {
	mBndOut[2*((*nOut)+1)] = mBndOut[2*(*nOut)];
	mBndOut[2*((*nOut)+1)+1] = mBndOut[2*(*nOut)+1];
	eBndOut[2*((*nOut)+1)] = eBndOut[2*(*nOut)];
	eBndOut[2*((*nOut)+1)+1] = eBndOut[2*(*nOut)+1];
	if (massSrc_func == 1) {
	  for (i=0; i<grd->nr; i++) {
	    mSrcOut[((*nOut)+1)*grd->nr+i] = mSrcOut[(*nOut)*grd->nr+i];
	    eSrcOut[((*nOut)+1)*grd->nr+i] = eSrcOut[(*nOut)*grd->nr+i];
	  }
	} else if (intEnSrc_func == 1) {
	  for (i=0; i<grd->nr; i++) {
	    eSrcOut[((*nOut)+1)*grd->nr+i] = eSrcOut[(*nOut)*grd->nr+i];
	  }
	}
	/* Handle any user-defined cumulative outputs in the same way;
	   note that user outputs are a 3D array, with the dimensions
	   being (output time, output variable number, cell number),
	   where cell number is the fastest varying index and output
	   time is the slowest varying index in memory */
	for (j=0; j<nUserOut; j++) {
	  if (userOutCum) {
	    if (userOutCum[j]) {
	      for (i=0; i<grd->nr; i++)
		userOut[((*nOut)+1)*nUserOut*grd->nr + j*grd->nr + i] =
		  userOut[(*nOut)*nUserOut*grd->nr + j*grd->nr + i];
	    }
	  }
	}
      }

      /* Write checkpoint if requested */
      if (0&&writeCheckpoint) {
	if (writeCheckpoint[savePtr]) {
	  saveCheckpoint(checkname, chkPtr,
			 eos_func, massSrc_func, intEnSrc_func,
			 nUserOut, t, dtNew, *nStep, *nIter, *nFail, grd,
			 *nOut+1, tOut, colOut, presOut, eIntOut,
			 mBndOut, eBndOut, mSrcOut, eSrcOut, userOut,
#if AA_M > 0
			 w->constraint,
#endif
			 params, userWriteCheckpoint, verbosity);
	  /* Update checkpoint counter */
	  chkPtr++;
	}
      }

      /* Update counters and flags */
      (*nOut)++;
      savePtr++;
      writeOut = false;
    }

    /* Check termination conditions */
    if ((*nStep > maxStep) && (maxStep > 0)) stat = TOO_MANY_STEPS;
    if (dtNew < dtMin*(tEnd-tStart)) stat = ZENO_ERROR;
    if (t >= tEnd) stat = NORMAL_EXIT;

    /* If necessary, reduce next time step to hit the next output
       time or the end time */
    if (savePtr < nSave) {
      if (t + dtNew > tSave[savePtr]) {
	dtNew = tSave[savePtr] - t;
	writeOut = true;
      }
    }
    if (t + dtNew >= tEnd) dtNew = (1.0+1.0e-10)*(tEnd - t);
    dt = dtNew;

  } /* Main loop end */

#ifdef TESTING_MODE
  /* In testing mode, free memory for diagnostic array */
  free(residType);
#endif

  /* On early exit, store final state in last output */
  if (stat != NORMAL_EXIT) {
    if (savePtr < nSave) {
      tOut[(*nOut)] = t;
      for (i=0; i<grd->nr; i++) {
	colOut[i + (*nOut)*grd->nr] = col[i];
	presOut[i + (*nOut)*grd->nr] = pres[i];
	if (eos_func) eIntOut[i + (*nOut)*grd->nr] = eInt[i];
      }
      (*nOut)++;
    }
  }

  /* Print final status and return */
  if (verbosity > 0) {
    *nStep = *nStep-1;
    if (stat == NORMAL_EXIT)
      printf("Finished computation in %ld steps, t = %e\n", *nStep, t);
    else if (stat == TOO_MANY_STEPS)
      printf("Reached maximum number of steps = %ld, t = %e\n", *nStep, t);
    else if (stat == ZENO_ERROR)
      printf("Time step too small after %ld steps, t = %e, dt = %e\n",
	     *nStep, t, dt);
  }
#ifdef TESTING_MODE
  end_t = clock();
  *driverTime = (double) (end_t - start_t) / CLOCKS_PER_SEC;
#endif
  return(t);
}

max_stars_repo_name: franciscaconcha/amuse-vader

max_issues_repo_name: franciscaconcha/amuse-vader

max_forks_repo_name: franciscaconcha/amuse-vader


text:
#pragma once

#include <initializer_list>
#include <list>
#include <vector>

#include <gsl/gsl_complex.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_permutation.h>
#include <gsl/gsl_vector.h>

#include "../Utils/Types.h"
#include "Expression.h"

#define UNIQUE_GSL(M)                                           \
    typedef std::unique_ptr<M, decltype(&M##_free)> unique_##M; \
    inline unique_##M make_##M(size_t rows, size_t cols){       \
        return unique_##M(M##_alloc(rows, cols), M##_free);     \
    }                                                           \
    unique_##M to_##M(expression e);

UNIQUE_GSL(gsl_matrix)
UNIQUE_GSL(gsl_matrix_complex)

#undef UNIQUE_GSL

#define UNIQUE_GSL(M)                                           \
    typedef std::unique_ptr<M, decltype(&M##_free)> unique_##M; \
    inline unique_##M make_##M(size_t size){                    \
        return unique_##M(M##_alloc(size), M##_free);           \
    }                                                           \
    unique_##M to_##M(expression e);

UNIQUE_GSL(gsl_permutation)
UNIQUE_GSL(gsl_vector)
UNIQUE_GSL(gsl_vector_complex)

#undef UNIQUE_GSL

class MatrixExpression: public Expression {
    std::vector<expression> mat;
    size_t rows, cols;

    MatrixExpression();
    MatrixExpression(size_t numRows, size_t numCols);
    MatrixExpression(std::vector<expression>&& matrix, size_t numRows, size_t numCols);
    MatrixExpression(std::list<expression>& matrix, size_t numRows, size_t numCols);
    MatrixExpression(std::initializer_list<double> matrix, size_t numRows, size_t numCols);
    MatrixExpression(std::initializer_list<gsl_complex> matrix, size_t numRows, size_t numCols);
    MatrixExpression(unique_gsl_matrix& matrix);
    MatrixExpression(unique_gsl_matrix_complex& matrix);
    MatrixExpression(unique_gsl_permutation& permutation);
    MatrixExpression(unique_gsl_vector& vec);
    MatrixExpression(unique_gsl_vector_complex& vec);

    public:

        static expression construct();
        static expression construct(size_t numRows, size_t numCols);
        static expression construct(std::vector<expression>&& matrix, size_t numRows, size_t numCols);
        static expression construct(std::list<expression>& matrix, size_t numRows, size_t numCols);
        static expression construct(std::initializer_list<double> matrix, size_t numRows, size_t numCols);
        static expression construct(std::initializer_list<gsl_complex> matrix, size_t numRows, size_t numCols);
        static expression construct(unique_gsl_matrix& matrix);
        static expression construct(unique_gsl_matrix_complex& matrix);
        static expression construct(unique_gsl_permutation& matrix);
        static expression construct(unique_gsl_vector& vec);
        static expression construct(unique_gsl_vector_complex& vec);

        expression simplify() override;
        expression derivative(const std::string& var) override;
        expression integrate(const std::string& var) override;

        expression at(const int index) override;
        size_t shape(const int axis) const override;
        size_t size() const override;

        expression apply(TransformerFunction f) override;

        EXPRESSION_OVERRIDES
};

max_stars_repo_name: antoniojkim/CalcPlusPlus

max_issues_repo_name: antoniojkim/CalcPlusPlus

max_forks_repo_name: antoniojkim/CalcPlusPlus


text:
#ifndef QDM_BIAS_H
#define QDM_BIAS_H

#include <gsl/gsl_matrix.h>
#include <gsl/gsl_vector.h>

#include "evaluation.h"

gsl_matrix *
qdm_bias_values(
    qdm_evaluation *h,
    qdm_evaluation *f
);

gsl_matrix *
qdm_bias_correct(
    const gsl_vector *years,
    const double month,
    const gsl_vector *days,

    const gsl_vector *y,

    qdm_evaluation *fp,
    qdm_evaluation *ho,
    qdm_evaluation *hc
);

#endif /* QDM_BIAS_H */

max_stars_repo_name: calebcase/qdm

max_issues_repo_name: calebcase/qdm

max_forks_repo_name: calebcase/qdm


text:
#include <stdio.h>
#include <stdarg.h>
#include <string.h>
#include <math.h>
#include <gbpLib.h>
#include <gbpRNG.h>
#include <gbpMCMC.h>
#include <gsl/gsl_linalg.h>
#include <gsl/gsl_fit.h>
#include <gsl/gsl_interp.h>

void generate_MCMC_parameters(MCMC_info *MCMC) {
    int                i_P;
    int                j_P;
    double             factor_i;
    int                flag_continue;
    static int         reflect_priors;
    static int         n_P;
    static double      factor;
    static double *    P_new;
    static double *    P_chain;
    static double *    P_init;
    static double *    P_limit_min;
    static double *    P_limit_max;
    static gsl_vector *b;
    static gsl_matrix *m;
    static RNG_info *  RNG;

    // Initialize a few things on the first call
    switch(MCMC->first_parameter_call) {
        case GBP_TRUE:
            n_P                        = MCMC->n_P;
            P_new                      = MCMC->P_new;
            P_chain                    = MCMC->P_chain;
            P_init                     = MCMC->P_init;
            P_limit_min                = MCMC->P_limit_min;
            P_limit_max                = MCMC->P_limit_max;
            b                          = MCMC->b;
            m                          = MCMC->m;
            RNG                        = MCMC->RNG;
            factor                     = 2.4 / sqrt((double)MCMC->n_M_total);
            MCMC->first_parameter_call = GBP_FALSE;
            reflect_priors             = SID_CHECK_BITFIELD_SWITCH(MCMC->mode, MCMC_MODE_REFLECT_PRIORS);
            break;
    }

    // Loop until a satisfactory set of parameters has been selected
    flag_continue = GBP_TRUE;
    while(flag_continue) {
        // Generate a random displacement vector
        factor_i = MCMC->temperature * factor;
        for(i_P = 0; i_P < n_P; i_P++)
            gsl_vector_set(b, i_P, factor_i * random_gaussian(RNG));

        // Use the rotated covariance matrix (if available)
        if(m != NULL) {
            memcpy(P_new, P_chain, n_P * sizeof(double));
            for(i_P = 0; i_P < n_P; i_P++) {
                for(j_P = 0; j_P < n_P; j_P++)
                    P_new[i_P] += gsl_matrix_get(m, i_P, j_P) * gsl_vector_get(b, j_P);
            }
        } else {
            for(j_P = 0; j_P < n_P; j_P++)
                P_new[j_P] = P_init[j_P] * (1. + gsl_vector_get(b, j_P));
        }

        // Enforce parameter limits
        if(reflect_priors) {
            for(i_P = 0; i_P < n_P; i_P++) {
                if(P_new[i_P] < P_limit_min[i_P])
                    P_new[i_P] = 2 * (P_limit_min[i_P]) - P_new[i_P];
                if(P_new[i_P] > P_limit_max[i_P])
                    P_new[i_P] = 2 * (P_limit_max[i_P]) - P_new[i_P];
            }
        } else {
            for(i_P = 0, flag_continue = GBP_FALSE; i_P < n_P; i_P++)
                if(P_new[i_P] < P_limit_min[i_P] || P_new[i_P] > P_limit_max[i_P])
                    flag_continue = GBP_TRUE;
        }
    }

    if(!SID_CHECK_BITFIELD_SWITCH(MCMC->mode, MCMC_MODE_PARALLEL))
        SID_Bcast(P_new, n_P, SID_DOUBLE, SID_MASTER_RANK, MCMC->comm);
}

max_stars_repo_name: gbpoole/gbpCode

max_issues_repo_name: gbpoole/gbpCode

max_forks_repo_name: gbpoole/gbpCode


text:
/* This program is free software; you can redistribute it and/or
   modify it under the terms of the GNU General Public License as
   published by the Free Software Foundation; either version 2 of the
   License, or (at your option) any later version.

   This program is distributed in the hope that it will be useful, but
   WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
   General Public License for more details.  You should have received
   a copy of the GNU General Public License along with this program;
   if not, write to the Free Foundation, Inc., 59 Temple Place, Suite
   330, Boston, MA 02111-1307 USA

   Original implementation was copyright (C) 1997 Makoto Matsumoto and
   Takuji Nishimura. Coded by Takuji Nishimura, considering the
   suggestions by Topher Cooper and Marc Rieffel in July-Aug. 1997, "A
   C-program for MT19937: Integer version (1998/4/6)"

   This implementation copyright (C) 1998 Brian Gough. I reorganized
   the code to use the module framework of GSL.  The license on this
   implementation was changed from LGPL to GPL, following paragraph 3
   of the LGPL, version 2.

   The seeding procedure has been updated to match the 10/99 release
   of MT19937.

   The original code included the comment: "When you use this, send an
   email to: matumoto@math.keio.ac.jp with an appropriate reference to
   your work".

   Makoto Matsumoto has a web page with more information about the
   generator, http://www.math.keio.ac.jp/~matumoto/emt.html.

   The paper below has details of the algorithm.

   From: Makoto Matsumoto and Takuji Nishimura, "Mersenne Twister: A
   623-dimensionally equidistributerd uniform pseudorandom number
   generator". ACM Transactions on Modeling and Computer Simulation,
   Vol. 8, No. 1 (Jan. 1998), Pages 3-30

   You can obtain the paper directly from Makoto Matsumoto's web page.

   The period of this generator is 2^{19937} - 1.

*/

#include <config.h>
#include <stdlib.h>
#include <gsl/gsl_rng.h>

static inline unsigned long int mt_get (void *vstate);
static double mt_get_double (void *vstate);
static void mt_set (void *state, unsigned long int s);

#define N 624	/* Period parameters */
#define M 397

/* most significant w-r bits */
static const unsigned long UPPER_MASK = 0x80000000UL;

/* least significant r bits */
static const unsigned long LOWER_MASK = 0x7fffffffUL;

typedef struct
  {
    unsigned long mt[N];
    int mti;
  }
mt_state_t;

static inline unsigned long
mt_get (void *vstate)
{
  mt_state_t *state = (mt_state_t *) vstate;

  unsigned long k ;
  unsigned long int *const mt = state->mt;

#define MAGIC(y) (((y)&0x1) ? 0x9908b0dfUL : 0)

  if (state->mti >= N)
    {	/* generate N words at one time */
      int kk;

      for (kk = 0; kk < N - M; kk++)
	{
	  unsigned long y = (mt[kk] & UPPER_MASK) | (mt[kk + 1] & LOWER_MASK);
	  mt[kk] = mt[kk + M] ^ (y >> 1) ^ MAGIC(y);
	}
      for (; kk < N - 1; kk++)
	{
	  unsigned long y = (mt[kk] & UPPER_MASK) | (mt[kk + 1] & LOWER_MASK);
	  mt[kk] = mt[kk + (M - N)] ^ (y >> 1) ^ MAGIC(y);
	}

      {
	unsigned long y = (mt[N - 1] & UPPER_MASK) | (mt[0] & LOWER_MASK);
	mt[N - 1] = mt[M - 1] ^ (y >> 1) ^ MAGIC(y);
      }

      state->mti = 0;
    }

  /* Tempering */

  k = mt[state->mti];
  k ^= (k >> 11);
  k ^= (k << 7) & 0x9d2c5680UL;
  k ^= (k << 15) & 0xefc60000UL;
  k ^= (k >> 18);

  state->mti++;

  return k;
}

static double
mt_get_double (void * vstate)
{
  return mt_get (vstate) / 4294967296.0 ;
}

static void
mt_set (void *vstate, unsigned long int s)
{
  mt_state_t *state = (mt_state_t *) vstate;
  int i;

  if (s == 0)
    s = 4357;	/* the default seed is 4357 */

  /* This is the October 1999 version of the seeding procedure. It
     was updated by the original developers to avoid the periodicity
     in the simple congruence originally used.

     Note that an ANSI-C unsigned long integer arithmetic is
     automatically modulo 2^32 (or a higher power of two), so we can
     safely ignore overflow. */

#define LCG(x) ((69069 * x) + 1) &0xffffffffUL

  for (i = 0; i < N; i++)
    {
      state->mt[i] = s & 0xffff0000UL;
      s = LCG(s);
      state->mt[i] |= (s &0xffff0000UL) >> 16;
      s = LCG(s);
    }

  state->mti = i;
}

/* This is the original version of the seeding procedure, no longer
   used but available for compatibility with the original MT19937. */

static void
mt_1998_set (void *vstate, unsigned long int s)
{
  mt_state_t *state = (mt_state_t *) vstate;
  int i;

  if (s == 0)
    s = 4357;	/* the default seed is 4357 */

  state->mt[0] = s & 0xffffffffUL;

#define LCG1998(n) ((69069 * n) & 0xffffffffUL)

  for (i = 1; i < N; i++)
    state->mt[i] = LCG1998 (state->mt[i - 1]);

  state->mti = i;
}

static const gsl_rng_type mt_type =
{"mt19937",			/* name */
 0xffffffffUL,			/* RAND_MAX  */
 0,			        /* RAND_MIN  */
 sizeof (mt_state_t),
 &mt_set,
 &mt_get,
 &mt_get_double};

static const gsl_rng_type mt_1998_type =
{"mt19937_1998",		/* name */
 0xffffffffUL,			/* RAND_MAX  */
 0,			        /* RAND_MIN  */
 sizeof (mt_state_t),
 &mt_1998_set,
 &mt_get,
 &mt_get_double};

const gsl_rng_type *gsl_rng_mt19937 = &mt_type;
const gsl_rng_type *gsl_rng_mt19937_1998 = &mt_1998_type;

/* MT19937 is the default generator, so define that here too */

const gsl_rng_type *gsl_rng_default = &mt_type;
unsigned long int gsl_rng_default_seed = 0;


text:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define COMPEARTH_PRIVATE_DET3X3 1
#include "compearth.h"
/*
#ifdef COMPEARTH_USE_MKL
#include <mkl_cblas.h>
#else
#include <cblas.h>
#endif
*/

//static double det3x3ColumnMajor(const double *__restrict__ A);

/*!
 * @brief Ensure that U is a rotation matrix with det(U) = 1.
 *
 * @param[in] n      Number of rotation matrices.
 * @param[in] Uin    Rotation matrices to check.  This is an array of dimension
 *                   [3 x 3 x n] where each [3 x 3] matrix is in column major
 *                   format.
 * @param[in] Uout   Rotation matrices with determinants all positive.  This
 *                   is an array of dimension [3 x 3 x n] where each [3 x 3]
 *                   matrix is in column major format.
 *
 * @result 0 indicates success.
 *
 * @author Carl Tape and translated to C by Ben Baker
 *
 * @copyright MIT
 *
 */
int compearth_Udetcheck(const int n,
                        const double *__restrict__ Uin,
                        double *__restrict__ Uout)
{
    double det;
    int i, imt;
    // Copy Uin to Uout
    memcpy(Uout, Uin, 9*(size_t) n*sizeof(double));
    //cblas_dcopy(9*n, Uin, 1, Uout, 1);
    // Fix
    for (imt=0; imt<n; imt++)
    {
        det = det3x3ColumnMajor(&Uout[9*imt]);
        // Negate the second column
        if (det < 0.0)
        {
            for (i=0; i<3; i++)
            {
                Uout[9*imt+3+i] =-Uout[9*imt+3+i];
            }
        }
    }
    // Verify
    for (imt=0; imt<n; imt++)
    {
        det = det3x3ColumnMajor(&Uout[9*imt]);
        if (det < 0.0)
        {
            fprintf(stderr, "%s: Error det(u) < 0\n", __func__);
            return -1;
        }
    }
    return 0;
}

/*
static double det3x3ColumnMajor(const double *__restrict__ A)
{
    double det;
    det = A[0]*( A[4]*A[8] - A[5]*A[7])
        - A[3]*( A[1]*A[8] - A[2]*A[7])
        + A[6]*( A[1]*A[5] - A[2]*A[4]);
    return det;
}
*/

max_stars_repo_name: OUCyf/mtbeach

max_issues_repo_name: carltape/mtbeach

max_forks_repo_name: carltape/mtbeach


text:
#pragma once

#include <winrt\Windows.Foundation.h>
#include <cstdint>
#include <d3d11.h>
#include <DirectXMath.h>
#include <dxgidebug.h>
#include <gsl\gsl>
#include "GameException.h"

namespace Library
{
	enum class ShaderStages
	{
		IA,
		VS,
		HS,
		DS,
		GS,
		SO,
		RS,
		PS,
		OM,

		CS
	};

	const std::array<ShaderStages, 6> ProgrammableGraphicsShaderStages
	{
		ShaderStages::VS,
		ShaderStages::HS,
		ShaderStages::DS,
		ShaderStages::GS,
		ShaderStages::PS,
		ShaderStages::CS,
	};

	inline bool ShaderStageIsProgrammable(ShaderStages shaderStage)
	{
		static const std::map<ShaderStages, bool> isProgrammableMap
		{
			{ShaderStages::IA, false },
			{ ShaderStages::VS, true },
			{ ShaderStages::HS, true },
			{ ShaderStages::DS, true },
			{ ShaderStages::GS, true },
			{ ShaderStages::SO, false },
			{ ShaderStages::RS, false },
			{ ShaderStages::PS, true },
			{ ShaderStages::OM, false },
			{ ShaderStages::CS, true },
		};

		return isProgrammableMap.at(shaderStage);
	}

	void CreateIndexBuffer(gsl::not_null<ID3D11Device*> device, const gsl::span<const std::uint16_t>& indices, gsl::not_null<ID3D11Buffer**> indexBuffer);
	void CreateIndexBuffer(gsl::not_null<ID3D11Device*> device, const gsl::span<const std::uint32_t>& indices, gsl::not_null<ID3D11Buffer**> indexBuffer);
	void CreateConstantBuffer(gsl::not_null<ID3D11Device*> device, std::size_t byteWidth, gsl::not_null<ID3D11Buffer**> constantBuffer);

	inline float ConvertDipsToPixels(float dips, float dpi)
	{
		static const float dipsPerInch = 96.0f;
		return floorf(dips * dpi / dipsPerInch + 0.5f); // Round to nearest integer.
	}

#if defined(DEBUG) || defined(_DEBUG)
	// Check for SDK Layer support.
	inline bool SdkLayersAvailable()
	{
		HRESULT hr = D3D11CreateDevice(
			nullptr,
			D3D_DRIVER_TYPE_NULL,       // There is no need to create a real hardware device.
			0,
			D3D11_CREATE_DEVICE_DEBUG,  // Check for the SDK layers.
			nullptr,                    // Any feature level will do.
			0,
			D3D11_SDK_VERSION,          // Always set this to D3D11_SDK_VERSION for Windows Store apps.
			nullptr,                    // No need to keep the D3D device reference.
			nullptr,                    // No need to know the feature level.
			nullptr                     // No need to keep the D3D device context reference.
			);

		return SUCCEEDED(hr);
	}
#endif

#if defined(DEBUG) || defined(_DEBUG)
	inline void DumpD3DDebug()
	{
		winrt::com_ptr<IDXGIDebug1> debugInterface = nullptr;
		ThrowIfFailed(DXGIGetDebugInterface1(0, IID_PPV_ARGS(debugInterface.put())));
		ThrowIfFailed(debugInterface->ReportLiveObjects(DXGI_DEBUG_ALL, DXGI_DEBUG_RLO_ALL));
	}
#endif
}


text:
#include <stdio.h>
#include <gsl/gsl_statistics.h>
#include <stdlib.h>
#include <float.h>

#ifndef N
#define N 32
#endif

#define K N/2

#include <klee/klee.h>
int
main(void)
{
  double data[K], w[K];
  float input[K];

  // random inputs
  int i;
  for (i = 0; i < K; i++){
    if (i<2) w[i] = 1; else w[i] = 2*w[i-1];
  }

  // symbolic inputs
  klee_make_symbolic(&input, sizeof(input), "input");

  for (i = 0; i < K; i++){
    data[i] = input[i]  / FLT_MAX * 100;
  }

  double wmean;

  wmean     = gsl_stats_wmean(w, 1, data, 1, K);

  printf ("The sample mean is %g\n", wmean);
  return 0;
}

max_stars_repo_name: snipekill/FPGen

max_issues_repo_name: snipekill/FPGen

max_forks_repo_name: snipekill/FPGen


text:
//
//  Author  : github.com/luncliff (luncliff@gmail.com)
//  License : CC BY 4.0
//
//  Note
//      Async I/O operation support for socket
//
#pragma once
// clang-format off
#if defined(FORCE_STATIC_LINK)
#   define _INTERFACE_
#   define _HIDDEN_
#elif defined(_MSC_VER) // MSVC or clang-cl
#   define _HIDDEN_
#   ifdef _WINDLL
#       define _INTERFACE_ __declspec(dllexport)
#   else
#       define _INTERFACE_ __declspec(dllimport)
#   endif
#elif defined(__GNUC__) || defined(__clang__)
#   define _INTERFACE_ __attribute__((visibility("default")))
#   define _HIDDEN_ __attribute__((visibility("hidden")))
#else
#   error "unexpected linking configuration"
#endif
// clang-format on

#ifndef COROUTINE_NET_IO_H
#define COROUTINE_NET_IO_H

#include <chrono>
#include <gsl/gsl>
#include <coroutine/yield.hpp>

#if __has_include(<WinSock2.h>) // use winsock
#include <WS2tcpip.h>
#include <WinSock2.h>
#include <ws2def.h>

using io_control_block = OVERLAPPED;

static constexpr bool is_winsock = true;
static constexpr bool is_netinet = false;

#elif __has_include(<netinet/in.h>) // use netinet
#include <fcntl.h>
#include <netdb.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <sys/socket.h>
#include <unistd.h>

// Follow the definition of Windows `OVERLAPPED`
struct io_control_block {
    uint64_t internal;      // uint32_t errc, int32_t flag
    uint64_t internal_high; // int64_t len, socklen_t addrlen
    union {
        struct {
            int32_t offset;
            int32_t offset_high;
        };
        void* ptr; // sockaddr* addr;
    };
    int64_t handle; // int64_t sd;
};

static constexpr bool is_winsock = false;
static constexpr bool is_netinet = true;

#endif // winsock || netinet

namespace coro {
using namespace std;
using namespace std::experimental;

//  1 I/O task == 1 coroutine function
using io_task_t = coroutine_handle<void>;

//  This is simply a view to storage. Be aware that it doesn't have ownership
using io_buffer_t = gsl::span<std::byte>;
static_assert(sizeof(io_buffer_t) <= sizeof(void*) * 2);

//  A struct to describe "1 I/O request" to system API
class io_work_t : public io_control_block {
  public:
    io_task_t task{};
    io_buffer_t buffer{};

  protected:
    _INTERFACE_ bool ready() const noexcept;

  public:
    // Multiple retrieving won't be a matter
    _INTERFACE_ uint32_t error() const noexcept;
};
static_assert(sizeof(io_work_t) <= 56);

//  Type to perform `sendto` I/O request
class io_send_to final : public io_work_t {
  private:
    // This function must be used through `co_await`
    _INTERFACE_ void suspend(io_task_t t) noexcept(false);
    // This function must be used through `co_await`
    // Unlike inherited `error` function, multiple invoke of this will
    // lead to malfunction.
    _INTERFACE_ int64_t resume() noexcept;

  public:
    bool await_ready() const noexcept {
        return this->ready();
    }
    void await_suspend(io_task_t t) noexcept(false) {
        return this->suspend(t);
    }
    auto await_resume() noexcept {
        return this->resume();
    }
};
static_assert(sizeof(io_send_to) == sizeof(io_work_t));

//  Type to perform `recvfrom` I/O request
class io_recv_from final : public io_work_t {
  private:
    // This function must be used through `co_await`
    _INTERFACE_ void suspend(io_task_t t) noexcept(false);
    // This function must be used through `co_await`
    // Unlike inherited `error` function, multiple invoke of this will
    // lead to malfunction.
    _INTERFACE_ int64_t resume() noexcept;

  public:
    bool await_ready() const noexcept {
        return this->ready();
    }
    void await_suspend(io_task_t t) noexcept(false) {
        return this->suspend(t);
    }
    auto await_resume() noexcept {
        return this->resume();
    }
};
static_assert(sizeof(io_recv_from) == sizeof(io_work_t));

//  Type to perform `send` I/O request
class io_send final : public io_work_t {
  private:
    // This function must be used through `co_await`
    _INTERFACE_ void suspend(io_task_t t) noexcept(false);
    // This function must be used through `co_await`
    // Unlike inherited `error` function, multiple invoke of this will
    // lead to malfunction.
    _INTERFACE_ int64_t resume() noexcept;

  public:
    bool await_ready() const noexcept {
        return this->ready();
    }
    void await_suspend(io_task_t t) noexcept(false) {
        return this->suspend(t);
    }
    auto await_resume() noexcept {
        return this->resume();
    }
};
static_assert(sizeof(io_send) == sizeof(io_work_t));

//  Type to perform `recv` I/O request
class io_recv final : public io_work_t {
  private:
    // This function must be used through `co_await`
    _INTERFACE_ void suspend(io_task_t t) noexcept(false);
    // This function must be used through `co_await`
    // Unlike inherited `error` function, multiple invoke of this will
    // lead to malfunction.
    _INTERFACE_ int64_t resume() noexcept;

  public:
    bool await_ready() const noexcept {
        return this->ready();
    }
    void await_suspend(io_task_t t) noexcept(false) {
        return this->suspend(t);
    }
    auto await_resume() noexcept {
        return this->resume();
    }
};
static_assert(sizeof(io_recv) == sizeof(io_work_t));

//  Constructs awaitable `io_send_to` object with the given parameters
[[nodiscard]] _INTERFACE_                                     //
    auto                                                      //
    send_to(uint64_t sd, const sockaddr_in& remote,           //
            io_buffer_t buf, io_work_t& work) noexcept(false) //
    -> io_send_to&;

//  Constructs awaitable `io_send_to` object with the given parameters
[[nodiscard]] _INTERFACE_                                             //
    auto                                                              //
    send_to(uint64_t sd, const sockaddr_in6& remote, io_buffer_t buf, //
            io_work_t& work) noexcept(false)                          //
    -> io_send_to&;

//  Constructs awaitable `io_recv_from` object with the given parameters
[[nodiscard]] _INTERFACE_                                        //
    auto                                                         //
    recv_from(uint64_t sd, sockaddr_in& remote, io_buffer_t buf, //
              io_work_t& work) noexcept(false)                   //
    -> io_recv_from&;

//  Constructs awaitable `io_recv_from` object with the given parameters
[[nodiscard]] _INTERFACE_                                         //
    auto                                                          //
    recv_from(uint64_t sd, sockaddr_in6& remote, io_buffer_t buf, //
              io_work_t& work) noexcept(false)                    //
    -> io_recv_from&;

//  Constructs awaitable `io_send` object with the given parameters
[[nodiscard]] _INTERFACE_                                    //
    auto                                                     //
    send_stream(uint64_t sd, io_buffer_t buf, uint32_t flag, //
                io_work_t& work) noexcept(false)             //
    -> io_send&;

//  Constructs awaitable `io_recv` object with the given parameters
[[nodiscard]] _INTERFACE_                                    //
    auto                                                     //
    recv_stream(uint64_t sd, io_buffer_t buf, uint32_t flag, //
                io_work_t& work) noexcept(false)             //
    -> io_recv&;

//  This function is for non-Windows platform.
//  Over Windows api, it always yields **nothing**.
//
//  Its caller must continue the loop without break
//  so there is no leak of the I/O events
//
//  Also, the library doesn't guarantee all coroutines(i/o tasks) will be
//  fetched at once. Therefore it is strongly recommended for user to have
//  another method to detect that watching I/O coroutines are returned.
_INTERFACE_
void wait_net_tasks(enumerable<io_task_t>& tasks,
                    chrono::nanoseconds timeout) noexcept(false);

inline auto wait_net_tasks(chrono::nanoseconds timeout) noexcept(false) {
    enumerable<io_task_t> tasks{};
    wait_net_tasks(tasks, timeout);
    return tasks;
}

//
//  Name resolution utilities
//

using zstring_host = gsl::zstring<NI_MAXHOST>;
using zstring_serv = gsl::zstring<NI_MAXSERV>;
using czstring_host = gsl::czstring<NI_MAXHOST>;
using czstring_serv = gsl::czstring<NI_MAXSERV>;

//  Combination of `getaddrinfo` functions
//  If there is an error, the enumerable is untouched
_INTERFACE_
int32_t resolve(enumerable<sockaddr>& g, const addrinfo& hint, //
                czstring_host name, czstring_serv serv) noexcept;

// construct system_error using `gai_strerror` function
_INTERFACE_
auto resolve_error(int32_t ec) noexcept -> std::system_error;

inline auto resolve(const addrinfo& hint, //
                    czstring_host name, czstring_serv serv) noexcept(false)
    -> enumerable<sockaddr> {
    enumerable<sockaddr> g{};
    if (const auto ec = resolve(g, hint, name, serv)) {
        throw resolve_error(ec);
    }
    return g;
}

//  Thin wrapper of `getnameinfo`. Parameter 'serv' can be nullptr.
_INTERFACE_
int32_t get_name(const sockaddr_in& addr, zstring_host name, zstring_serv serv,
                 int32_t flags = NI_NUMERICHOST | NI_NUMERICSERV) noexcept;
_INTERFACE_
int32_t get_name(const sockaddr_in6& addr, zstring_host name, zstring_serv serv,
                 int32_t flags = NI_NUMERICHOST | NI_NUMERICSERV) noexcept;

} // namespace coro

#endif // COROUTINE_NET_IO_H

max_stars_repo_name: Farwaykorse/coroutine

max_issues_repo_name: Farwaykorse/coroutine

max_forks_repo_name: Farwaykorse/coroutine