// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2009 Benoit Jacob <jacob.benoit.1@gmail.com>
// Copyright (C) 2009 Gael Guennebaud <gael.guennebaud@inria.fr>
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.

#ifndef EIGEN_JACOBI_H
#define EIGEN_JACOBI_H

namespace Eigen {

/** \ingroup Jacobi_Module
  * \jacobi_module
  * \class JacobiRotation
  * \brief Rotation given by a cosine-sine pair.
  *
  * This class represents a Jacobi or Givens rotation.
  * This is a 2D rotation in the plane \c J of angle \f$ \theta \f$ defined by
  * its cosine \c c and sine \c s as follow:
  * \f$ J = \left ( \begin{array}{cc} c & \overline s \\ -s  & \overline c \end{array} \right ) \f$
  *
  * You can apply the respective counter-clockwise rotation to a column vector \c v by
  * applying its adjoint on the left: \f$ v = J^* v \f$ that translates to the following Eigen code:
  * \code
  * v.applyOnTheLeft(J.adjoint());
  * \endcode
  *
  * \sa MatrixBase::applyOnTheLeft(), MatrixBase::applyOnTheRight()
  */
template<typename Scalar> class JacobiRotation
{
  public:
    typedef typename NumTraits<Scalar>::Real RealScalar;

    /** Default constructor without any initialization. */
    EIGEN_DEVICE_FUNC
    JacobiRotation() {}

    /** Construct a planar rotation from a cosine-sine pair (\a c, \c s). */
    EIGEN_DEVICE_FUNC
    JacobiRotation(const Scalar& c, const Scalar& s) : m_c(c), m_s(s) {}

    EIGEN_DEVICE_FUNC Scalar& c() { return m_c; }
    EIGEN_DEVICE_FUNC Scalar c() const { return m_c; }
    EIGEN_DEVICE_FUNC Scalar& s() { return m_s; }
    EIGEN_DEVICE_FUNC Scalar s() const { return m_s; }

    /** Concatenates two planar rotation */
    EIGEN_DEVICE_FUNC
    JacobiRotation operator*(const JacobiRotation& other)
    {
      using numext::conj;
      return JacobiRotation(m_c * other.m_c - conj(m_s) * other.m_s,
                            conj(m_c * conj(other.m_s) + conj(m_s) * conj(other.m_c)));
    }

    /** Returns the transposed transformation */
    EIGEN_DEVICE_FUNC
    JacobiRotation transpose() const { using numext::conj; return JacobiRotation(m_c, -conj(m_s)); }

    /** Returns the adjoint transformation */
    EIGEN_DEVICE_FUNC
    JacobiRotation adjoint() const { using numext::conj; return JacobiRotation(conj(m_c), -m_s); }

    template<typename Derived>
    EIGEN_DEVICE_FUNC
    bool makeJacobi(const MatrixBase<Derived>&, Index p, Index q);
    EIGEN_DEVICE_FUNC
    bool makeJacobi(const RealScalar& x, const Scalar& y, const RealScalar& z);

    EIGEN_DEVICE_FUNC
    void makeGivens(const Scalar& p, const Scalar& q, Scalar* z=0);

  protected:
    EIGEN_DEVICE_FUNC
    void makeGivens(const Scalar& p, const Scalar& q, Scalar* z, internal::true_type);
    EIGEN_DEVICE_FUNC
    void makeGivens(const Scalar& p, const Scalar& q, Scalar* z, internal::false_type);

    Scalar m_c, m_s;
};

/** Makes \c *this as a Jacobi rotation \a J such that applying \a J on both the right and left sides of the selfadjoint 2x2 matrix
  * \f$ B = \left ( \begin{array}{cc} x & y \\ \overline y & z \end{array} \right )\f$ yields a diagonal matrix \f$ A = J^* B J \f$
  *
  * \sa MatrixBase::makeJacobi(const MatrixBase<Derived>&, Index, Index), MatrixBase::applyOnTheLeft(), MatrixBase::applyOnTheRight()
  */
template<typename Scalar>
bool JacobiRotation<Scalar>::makeJacobi(const RealScalar& x, const Scalar& y, const RealScalar& z)
{
  using std::sqrt;
  using std::abs;
  typedef typename NumTraits<Scalar>::Real RealScalar;
  RealScalar deno = RealScalar(2)*abs(y);
  if(deno < (std::numeric_limits<RealScalar>::min)())
  {
    m_c = Scalar(1);
    m_s = Scalar(0);
    return false;
  }
  else
  {
    RealScalar tau = (x-z)/deno;
    RealScalar w = sqrt(numext::abs2(tau) + RealScalar(1));
    RealScalar t;
    if(tau>RealScalar(0))
    {
      t = RealScalar(1) / (tau + w);
    }
    else
    {
      t = RealScalar(1) / (tau - w);
    }
    RealScalar sign_t = t > RealScalar(0) ? RealScalar(1) : RealScalar(-1);
    RealScalar n = RealScalar(1) / sqrt(numext::abs2(t)+RealScalar(1));
    m_s = - sign_t * (numext::conj(y) / abs(y)) * abs(t) * n;
    m_c = n;
    return true;
  }
}

/** Makes \c *this as a Jacobi rotation \c J such that applying \a J on both the right and left sides of the 2x2 selfadjoint matrix
  * \f$ B = \left ( \begin{array}{cc} \text{this}_{pp} & \text{this}_{pq} \\ (\text{this}_{pq})^* & \text{this}_{qq} \end{array} \right )\f$ yields
  * a diagonal matrix \f$ A = J^* B J \f$
  *
  * Example: \include Jacobi_makeJacobi.cpp
  * Output: \verbinclude Jacobi_makeJacobi.out
  *
  * \sa JacobiRotation::makeJacobi(RealScalar, Scalar, RealScalar), MatrixBase::applyOnTheLeft(), MatrixBase::applyOnTheRight()
  */
template<typename Scalar>
template<typename Derived>
inline bool JacobiRotation<Scalar>::makeJacobi(const MatrixBase<Derived>& m, Index p, Index q)
{
  return makeJacobi(numext::real(m.coeff(p,p)), m.coeff(p,q), numext::real(m.coeff(q,q)));
}

/** Makes \c *this as a Givens rotation \c G such that applying \f$ G^* \f$ to the left of the vector
  * \f$ V = \left ( \begin{array}{c} p \\ q \end{array} \right )\f$ yields:
  * \f$ G^* V = \left ( \begin{array}{c} r \\ 0 \end{array} \right )\f$.
  *
  * The value of \a z is returned if \a z is not null (the default is null).
  * Also note that G is built such that the cosine is always real.
  *
  * Example: \include Jacobi_makeGivens.cpp
  * Output: \verbinclude Jacobi_makeGivens.out
  *
  * This function implements the continuous Givens rotation generation algorithm
  * found in Anderson (2000), Discontinuous Plane Rotations and the Symmetric Eigenvalue Problem.
  * LAPACK Working Note 150, University of Tennessee, UT-CS-00-454, December 4, 2000.
  *
  * \sa MatrixBase::applyOnTheLeft(), MatrixBase::applyOnTheRight()
  */
template<typename Scalar>
void JacobiRotation<Scalar>::makeGivens(const Scalar& p, const Scalar& q, Scalar* z)
{
  makeGivens(p, q, z, typename internal::conditional<NumTraits<Scalar>::IsComplex, internal::true_type, internal::false_type>::type());
}

// specialization for complexes
template<typename Scalar>
void JacobiRotation<Scalar>::makeGivens(const Scalar& p, const Scalar& q, Scalar* r, internal::true_type)
{
  using std::sqrt;
  using std::abs;
  using numext::conj;

  if(q==Scalar(0))
  {
    m_c = numext::real(p)<0 ? Scalar(-1) : Scalar(1);
    m_s = 0;
    if(r) *r = m_c * p;
  }
  else if(p==Scalar(0))
  {
    m_c = 0;
    m_s = -q/abs(q);
    if(r) *r = abs(q);
  }
  else
  {
    RealScalar p1 = numext::norm1(p);
    RealScalar q1 = numext::norm1(q);
    if(p1>=q1)
    {
      Scalar ps = p / p1;
      RealScalar p2 = numext::abs2(ps);
      Scalar qs = q / p1;
      RealScalar q2 = numext::abs2(qs);

      RealScalar u = sqrt(RealScalar(1) + q2/p2);
      if(numext::real(p)<RealScalar(0))
        u = -u;

      m_c = Scalar(1)/u;
      m_s = -qs*conj(ps)*(m_c/p2);
      if(r) *r = p * u;
    }
    else
    {
      Scalar ps = p / q1;
      RealScalar p2 = numext::abs2(ps);
      Scalar qs = q / q1;
      RealScalar q2 = numext::abs2(qs);

      RealScalar u = q1 * sqrt(p2 + q2);
      if(numext::real(p)<RealScalar(0))
        u = -u;

      p1 = abs(p);
      ps = p/p1;
      m_c = p1/u;
      m_s = -conj(ps) * (q/u);
      if(r) *r = ps * u;
    }
  }
}

// specialization for reals
template<typename Scalar>
void JacobiRotation<Scalar>::makeGivens(const Scalar& p, const Scalar& q, Scalar* r, internal::false_type)
{
  using std::sqrt;
  using std::abs;
  if(q==Scalar(0))
  {
    m_c = p<Scalar(0) ? Scalar(-1) : Scalar(1);
    m_s = Scalar(0);
    if(r) *r = abs(p);
  }
  else if(p==Scalar(0))
  {
    m_c = Scalar(0);
    m_s = q<Scalar(0) ? Scalar(1) : Scalar(-1);
    if(r) *r = abs(q);
  }
  else if(abs(p) > abs(q))
  {
    Scalar t = q/p;
    Scalar u = sqrt(Scalar(1) + numext::abs2(t));
    if(p<Scalar(0))
      u = -u;
    m_c = Scalar(1)/u;
    m_s = -t * m_c;
    if(r) *r = p * u;
  }
  else
  {
    Scalar t = p/q;
    Scalar u = sqrt(Scalar(1) + numext::abs2(t));
    if(q<Scalar(0))
      u = -u;
    m_s = -Scalar(1)/u;
    m_c = -t * m_s;
    if(r) *r = q * u;
  }

}

/****************************************************************************************
*   Implementation of MatrixBase methods
****************************************************************************************/

namespace internal {
/** \jacobi_module
  * Applies the clock wise 2D rotation \a j to the set of 2D vectors of cordinates \a x and \a y:
  * \f$ \left ( \begin{array}{cc} x \\ y \end{array} \right )  =  J \left ( \begin{array}{cc} x \\ y \end{array} \right ) \f$
  *
  * \sa MatrixBase::applyOnTheLeft(), MatrixBase::applyOnTheRight()
  */
template<typename VectorX, typename VectorY, typename OtherScalar>
EIGEN_DEVICE_FUNC
void apply_rotation_in_the_plane(DenseBase<VectorX>& xpr_x, DenseBase<VectorY>& xpr_y, const JacobiRotation<OtherScalar>& j);
}

/** \jacobi_module
  * Applies the rotation in the plane \a j to the rows \a p and \a q of \c *this, i.e., it computes B = J * B,
  * with \f$ B = \left ( \begin{array}{cc} \text{*this.row}(p) \\ \text{*this.row}(q) \end{array} \right ) \f$.
  *
  * \sa class JacobiRotation, MatrixBase::applyOnTheRight(), internal::apply_rotation_in_the_plane()
  */
template<typename Derived>
template<typename OtherScalar>
inline void MatrixBase<Derived>::applyOnTheLeft(Index p, Index q, const JacobiRotation<OtherScalar>& j)
{
  RowXpr x(this->row(p));
  RowXpr y(this->row(q));
  internal::apply_rotation_in_the_plane(x, y, j);
}

/** \ingroup Jacobi_Module
  * Applies the rotation in the plane \a j to the columns \a p and \a q of \c *this, i.e., it computes B = B * J
  * with \f$ B = \left ( \begin{array}{cc} \text{*this.col}(p) & \text{*this.col}(q) \end{array} \right ) \f$.
  *
  * \sa class JacobiRotation, MatrixBase::applyOnTheLeft(), internal::apply_rotation_in_the_plane()
  */
template<typename Derived>
template<typename OtherScalar>
inline void MatrixBase<Derived>::applyOnTheRight(Index p, Index q, const JacobiRotation<OtherScalar>& j)
{
  ColXpr x(this->col(p));
  ColXpr y(this->col(q));
  internal::apply_rotation_in_the_plane(x, y, j.transpose());
}

namespace internal {

template<typename Scalar, typename OtherScalar,
         int SizeAtCompileTime, int MinAlignment, bool Vectorizable>
struct apply_rotation_in_the_plane_selector
{
  static inline void run(Scalar *x, Index incrx, Scalar *y, Index incry, Index size, OtherScalar c, OtherScalar s)
  {
    for(Index i=0; i<size; ++i)
    {
      Scalar xi = *x;
      Scalar yi = *y;
      *x =  c * xi + numext::conj(s) * yi;
      *y = -s * xi + numext::conj(c) * yi;
      x += incrx;
      y += incry;
    }
  }
};

template<typename Scalar, typename OtherScalar,
         int SizeAtCompileTime, int MinAlignment>
struct apply_rotation_in_the_plane_selector<Scalar,OtherScalar,SizeAtCompileTime,MinAlignment,true /* vectorizable */>
{
  static inline void run(Scalar *x, Index incrx, Scalar *y, Index incry, Index size, OtherScalar c, OtherScalar s)
  {
    enum {
      PacketSize = packet_traits<Scalar>::size,
      OtherPacketSize = packet_traits<OtherScalar>::size
    };
    typedef typename packet_traits<Scalar>::type Packet;
    typedef typename packet_traits<OtherScalar>::type OtherPacket;

    /*** dynamic-size vectorized paths ***/
    if(SizeAtCompileTime == Dynamic && ((incrx==1 && incry==1) || PacketSize == 1))
    {
      // both vectors are sequentially stored in memory => vectorization
      enum { Peeling = 2 };

      Index alignedStart = internal::first_default_aligned(y, size);
      Index alignedEnd = alignedStart + ((size-alignedStart)/PacketSize)*PacketSize;

      const OtherPacket pc = pset1<OtherPacket>(c);
      const OtherPacket ps = pset1<OtherPacket>(s);
      conj_helper<OtherPacket,Packet,NumTraits<OtherScalar>::IsComplex,false> pcj;
      conj_helper<OtherPacket,Packet,false,false> pm;

      for(Index i=0; i<alignedStart; ++i)
      {
        Scalar xi = x[i];
        Scalar yi = y[i];
        x[i] =  c * xi + numext::conj(s) * yi;
        y[i] = -s * xi + numext::conj(c) * yi;
      }

      Scalar* EIGEN_RESTRICT px = x + alignedStart;
      Scalar* EIGEN_RESTRICT py = y + alignedStart;

      if(internal::first_default_aligned(x, size)==alignedStart)
      {
        for(Index i=alignedStart; i<alignedEnd; i+=PacketSize)
        {
          Packet xi = pload<Packet>(px);
          Packet yi = pload<Packet>(py);
          pstore(px, padd(pm.pmul(pc,xi),pcj.pmul(ps,yi)));
          pstore(py, psub(pcj.pmul(pc,yi),pm.pmul(ps,xi)));
          px += PacketSize;
          py += PacketSize;
        }
      }
      else
      {
        Index peelingEnd = alignedStart + ((size-alignedStart)/(Peeling*PacketSize))*(Peeling*PacketSize);
        for(Index i=alignedStart; i<peelingEnd; i+=Peeling*PacketSize)
        {
          Packet xi   = ploadu<Packet>(px);
          Packet xi1  = ploadu<Packet>(px+PacketSize);
          Packet yi   = pload <Packet>(py);
          Packet yi1  = pload <Packet>(py+PacketSize);
          pstoreu(px, padd(pm.pmul(pc,xi),pcj.pmul(ps,yi)));
          pstoreu(px+PacketSize, padd(pm.pmul(pc,xi1),pcj.pmul(ps,yi1)));
          pstore (py, psub(pcj.pmul(pc,yi),pm.pmul(ps,xi)));
          pstore (py+PacketSize, psub(pcj.pmul(pc,yi1),pm.pmul(ps,xi1)));
          px += Peeling*PacketSize;
          py += Peeling*PacketSize;
        }
        if(alignedEnd!=peelingEnd)
        {
          Packet xi = ploadu<Packet>(x+peelingEnd);
          Packet yi = pload <Packet>(y+peelingEnd);
          pstoreu(x+peelingEnd, padd(pm.pmul(pc,xi),pcj.pmul(ps,yi)));
          pstore (y+peelingEnd, psub(pcj.pmul(pc,yi),pm.pmul(ps,xi)));
        }
      }

      for(Index i=alignedEnd; i<size; ++i)
      {
        Scalar xi = x[i];
        Scalar yi = y[i];
        x[i] =  c * xi + numext::conj(s) * yi;
        y[i] = -s * xi + numext::conj(c) * yi;
      }
    }

    /*** fixed-size vectorized path ***/
    else if(SizeAtCompileTime != Dynamic && MinAlignment>0) // FIXME should be compared to the required alignment
    {
      const OtherPacket pc = pset1<OtherPacket>(c);
      const OtherPacket ps = pset1<OtherPacket>(s);
      conj_helper<OtherPacket,Packet,NumTraits<OtherPacket>::IsComplex,false> pcj;
      conj_helper<OtherPacket,Packet,false,false> pm;
      Scalar* EIGEN_RESTRICT px = x;
      Scalar* EIGEN_RESTRICT py = y;
      for(Index i=0; i<size; i+=PacketSize)
      {
        Packet xi = pload<Packet>(px);
        Packet yi = pload<Packet>(py);
        pstore(px, padd(pm.pmul(pc,xi),pcj.pmul(ps,yi)));
        pstore(py, psub(pcj.pmul(pc,yi),pm.pmul(ps,xi)));
        px += PacketSize;
        py += PacketSize;
      }
    }

    /*** non-vectorized path ***/
    else
    {
      apply_rotation_in_the_plane_selector<Scalar,OtherScalar,SizeAtCompileTime,MinAlignment,false>::run(x,incrx,y,incry,size,c,s);
    }
  }
};

template<typename VectorX, typename VectorY, typename OtherScalar>
void /*EIGEN_DONT_INLINE*/ apply_rotation_in_the_plane(DenseBase<VectorX>& xpr_x, DenseBase<VectorY>& xpr_y, const JacobiRotation<OtherScalar>& j)
{
  typedef typename VectorX::Scalar Scalar;
  const bool Vectorizable =    (VectorX::Flags & VectorY::Flags & PacketAccessBit)
                            && (int(packet_traits<Scalar>::size) == int(packet_traits<OtherScalar>::size));

  eigen_assert(xpr_x.size() == xpr_y.size());
  Index size = xpr_x.size();
  Index incrx = xpr_x.derived().innerStride();
  Index incry = xpr_y.derived().innerStride();

  Scalar* EIGEN_RESTRICT x = &xpr_x.derived().coeffRef(0);
  Scalar* EIGEN_RESTRICT y = &xpr_y.derived().coeffRef(0);

  OtherScalar c = j.c();
  OtherScalar s = j.s();
  if (c==OtherScalar(1) && s==OtherScalar(0))
    return;

  apply_rotation_in_the_plane_selector<
    Scalar,OtherScalar,
    VectorX::SizeAtCompileTime,
    EIGEN_PLAIN_ENUM_MIN(evaluator<VectorX>::Alignment, evaluator<VectorY>::Alignment),
    Vectorizable>::run(x,incrx,y,incry,size,c,s);
}

} // end namespace internal

} // end namespace Eigen

#endif // EIGEN_JACOBI_H

{'repo_name': 'bulletphysics/bullet3', 'stars': '6642', 'repo_language': 'C++', 'file_name': 'license.txt', 'mime_type': 'text/plain', 'hash': 7251707891919836764, 'source_dataset': 'data'}


(define (iterative-improve enough? improve)
	(lambda (guess)
		(let ((next (improve guess)))
			(if (enough? guess next)
				next
				((iterative-improve enough? improve) next)
			)
		)
	)
)

; implement iterative-improve

(define (repeated f n)
	(if (= n 1)
		(lambda (x) (f x))
		(lambda (x) (f ((repeated f (- n 1)) x)))
	)
)
(define tolerance 0.00001)
(define (fixed-point f first-guess)
	(define (close-enough? v1 v2) (< (abs (- v1 v2))
		tolerance))
	(define (try guess)
		(let ((next (f guess)))
		(if (close-enough? guess next)
					next
          (try next))))
  ((iterative-improve close-enough? try) first-guess)
)
(define (average a b)
	(/ (+ a b) 2)
)
(define (average-damp f)
	(lambda (x) (average x (f x))))
(define (n-root x n)
	(define (check x)
		(if (< x 2) 1 x)
	)
	(fixed-point ((repeated average-damp (check (- n 2))) (lambda (y) (/ x ((repeated (lambda (x) (* x y)) (check (- n 2))) y) )))
		1.0)
)
(n-root 256 8)

{'repo_name': 'numbbbbb/sicp', 'stars': '587', 'repo_language': 'None', 'file_name': 'e5-12', 'mime_type': 'text/plain', 'hash': -3684531776250282258, 'source_dataset': 'data'}


using System.Collections.Generic;
using System.Web;
using Glimpse.Core.Extensions;

namespace Glimpse.AspNet.Model
{
    public class ServerModel
    {
        public ServerModel(HttpContextBase httpContext)
        {
            HttpVariables = new Dictionary<string, string>();
            GeneralVariables = new Dictionary<string, string>();
            SecurityRelatedVariables = new Dictionary<string, string>();

            foreach (var serverVariable in httpContext.Request.ServerVariables.ToDictionary())
            {
                string lowerCasedKey = serverVariable.Key.ToLower();

                if (lowerCasedKey.StartsWith("http_"))
                {
                    HttpVariables.Add(serverVariable.Key, serverVariable.Value);
                }
                else if (lowerCasedKey.StartsWith("cert_") || lowerCasedKey.StartsWith("https_"))
                {
                    SecurityRelatedVariables.Add(serverVariable.Key, serverVariable.Value);
                }
                else
                {
                    GeneralVariables.Add(serverVariable.Key, serverVariable.Value);
                }
            }
        }

        public IDictionary<string, string> HttpVariables { get; private set; }
        public IDictionary<string, string> GeneralVariables { get; private set; }
        public IDictionary<string, string> SecurityRelatedVariables { get; private set; }
    }
}

{'repo_name': 'Glimpse/Glimpse', 'stars': '2284', 'repo_language': 'C#', 'file_name': 'IEnumerableValueProvider.cs', 'mime_type': 'text/plain', 'hash': -7867921071657608890, 'source_dataset': 'data'}


import _ from 'lodash';
import bluebird from 'bluebird';
import {local} from './store';
import validation from './validation';

const validationTimeout = 60000;

/**
 * @param {object} item
 * @param {Array} item.valid  List of validators by key
 * @param {string} value
 * @returns {Promise<[Error]>}
 */
function validate(item, value) {
  if (!item.valid) {
    return bluebird.resolve([]);
  }
  const promises = _.map(item.valid, key => bluebird.try(function () {
    let validator = validation[key];

    if (!validator) {
      throw new Error('Validator' + key + 'does not exist');
    }

    return validator(value);
  }).reflect());

  return bluebird.all(promises)
    .timeout(validationTimeout)
    // only return list of errors
    .then(function (inspections) {
      const list = _.map(inspections, inspection => inspection.isFulfilled() ? inspection.value() : inspection.reason());

      return _.filter(_.flattenDeep(list), _.isError);
    });
}

/**
 * Convert the preferences definition (from the yaml file) into something that has all the information needed to render.
 * @param {Array} definition
 * @returns {Array}
 */
function define(definition) {
  return _.map(definition, function (preferenceGroup) {
    preferenceGroup = _.clone(preferenceGroup);
    preferenceGroup.items = _.reduce(preferenceGroup.items, function (list, preference) {
      const item = _.clone(preference),
        // remember: false is a valid value here
        storeValue = preference.key ? local.get(preference.key) : null;

      // filter item by platform
      if (_.isArray(item.platform) && !_.includes(item.platform, process.platform)) {
        return list;
      }

      // key from localStorage
      if (storeValue === null) {
        if (preference.value !== undefined) {
          item.value = preference.value;
        } else {
          // not allowed to be undefined, too confusing
          delete item.value;
        }
      } else {
        item.value = storeValue;
      }

      list.push(item);

      return list;
    }, []);

    return preferenceGroup;
  });
}

export default {
  validate,
  define
};

{'repo_name': 'yhat/rodeo', 'stars': '3922', 'repo_language': 'JavaScript', 'file_name': 'index.js', 'mime_type': 'text/plain', 'hash': 509451307332927755, 'source_dataset': 'data'}


from sage.rings.finite_rings.stdint cimport *

cdef struct c_vector_modint:
    int_fast64_t *entries
    int p
    Py_ssize_t *positions
    Py_ssize_t degree
    Py_ssize_t num_nonzero

cdef int allocate_c_vector_modint(c_vector_modint* v, Py_ssize_t num_nonzero) except -1
cdef int init_c_vector_modint(c_vector_modint* v, int p, Py_ssize_t degree, Py_ssize_t num_nonzero) except -1
cdef void clear_c_vector_modint(c_vector_modint* v)
cdef Py_ssize_t binary_search0_modn(Py_ssize_t* v, Py_ssize_t n, int_fast64_t x)
cdef Py_ssize_t binary_search_modn(Py_ssize_t* v, Py_ssize_t n, int_fast64_t x, Py_ssize_t* ins)
cdef int_fast64_t get_entry(c_vector_modint* v, Py_ssize_t n) except -1
cdef bint is_entry_zero_unsafe(c_vector_modint* v, Py_ssize_t n)
cdef object to_list(c_vector_modint* v)
cdef int set_entry(c_vector_modint* v, Py_ssize_t n, int_fast64_t x) except -1
cdef int add_c_vector_modint_init(c_vector_modint* sum, c_vector_modint* v, c_vector_modint* w, int multiple) except -1
cdef int scale_c_vector_modint(c_vector_modint* v, int_fast64_t scalar) except -1

{'repo_name': 'sagemath/sage', 'stars': '1249', 'repo_language': 'Python', 'file_name': 'config.yml', 'mime_type': 'text/plain', 'hash': -9135682102517892514, 'source_dataset': 'data'}


within Buildings.Controls.OBC.ASHRAE.G36_PR1.AHUs.MultiZone.VAV.SetPoints.OutdoorAirFlow;
block AHU "Output outdoor airflow related calculations at the AHU level"

  parameter Real VPriSysMax_flow(unit="m3/s")
    "Maximum expected system primary airflow at design stage"
    annotation(Dialog(group="Nominal condition"));

  parameter Real peaSysPop(final unit="1")
    "Peak system population"
    annotation(Dialog(group="Nominal condition"));

  Buildings.Controls.OBC.CDL.Interfaces.RealInput sumDesZonPop(
    final min=0,
    final unit="1")
    "Sum of the design population of the zones in the group"
    annotation (Placement(transformation(extent={{-260,180},{-220,220}}),
        iconTransformation(extent={{-140,70},{-100,110}})));

  Buildings.Controls.OBC.CDL.Interfaces.RealInput VSumDesPopBreZon_flow(
    final min=0,
    final unit="m3/s",
    final quantity="VolumeFlowRate")
    "Sum of the population component design breathing zone flow rate"
    annotation (Placement(transformation(extent={{-260,140},{-220,180}}),
        iconTransformation(extent={{-140,50},{-100,90}})));

  Buildings.Controls.OBC.CDL.Interfaces.RealInput VSumDesAreBreZon_flow(
    final min=0,
    final unit="m3/s",
    final quantity="VolumeFlowRate")
    "Sum of the area component design breathing zone flow rate"
    annotation (Placement(transformation(extent={{-260,100},{-220,140}}),
        iconTransformation(extent={{-140,30},{-100,70}})));

  Buildings.Controls.OBC.CDL.Interfaces.RealInput uDesSysVenEff(
    final min=0,
    final unit="1")
    "Design system ventilation efficiency, equals to the minimum of all zones ventilation efficiency"
    annotation (Placement(transformation(extent={{-260,60},{-220,100}}),
        iconTransformation(extent={{-140,10},{-100,50}})));

  Buildings.Controls.OBC.CDL.Interfaces.RealInput VSumUncOutAir_flow(
    final min=0,
    final unit="m3/s",
    final quantity="VolumeFlowRate")
    "Sum of all zones required uncorrected outdoor airflow rate"
    annotation (Placement(transformation(extent={{-260,-44},{-220,-4}}),
        iconTransformation(extent={{-140,-10},{-100,30}})));

  Buildings.Controls.OBC.CDL.Interfaces.RealInput VSumSysPriAir_flow(
    final unit="m3/s",
    final quantity="VolumeFlowRate")
    "System primary airflow rate, equals to the sum of the measured discharged flow rate of all terminal units"
    annotation (Placement(transformation(extent={{-260,-80},{-220,-40}}),
        iconTransformation(extent={{-140,-30},{-100,10}})));

  Buildings.Controls.OBC.CDL.Interfaces.RealInput uOutAirFra_max(
    final min=0,
    final unit="1")
    "Maximum zone outdoor air fraction, equals to the maximum of primary outdoor air fraction of all zones"
    annotation (Placement(transformation(extent={{-260,-120},{-220,-80}}),
        iconTransformation(extent={{-140,-50},{-100,-10}})));

  Buildings.Controls.OBC.CDL.Interfaces.BooleanInput uSupFan
    "Supply fan status, true if on, false if off"
    annotation (Placement(transformation(extent={{-260,-160},{-220,-120}}),
      iconTransformation(extent={{-140,-90},{-100,-50}})));

  Buildings.Controls.OBC.CDL.Interfaces.IntegerInput uOpeMod
    "AHU operation mode status signal"
    annotation (Placement(transformation(extent={{-260,-200},{-220,-160}}),
      iconTransformation(extent={{-140,-110},{-100,-70}})));

  Buildings.Controls.OBC.CDL.Interfaces.RealOutput VDesUncOutAir_flow(
    final min=0,
    final unit="m3/s",
    final quantity="VolumeFlowRate")
    "Design uncorrected minimum outdoor airflow rate"
    annotation (Placement(transformation(extent={{240,160},{280,200}}),
        iconTransformation(extent={{100,60},{140,100}})));

  Buildings.Controls.OBC.CDL.Interfaces.RealOutput yAveOutAirFraPlu(
    final min=0,
    final unit="1")
    "Average outdoor air flow fraction plus 1"
    annotation (Placement(transformation(extent={{240,110},{280,150}}),
        iconTransformation(extent={{100,30},{140,70}})));

  Buildings.Controls.OBC.CDL.Interfaces.RealOutput VDesOutAir_flow(
    final min=0,
    final unit="m3/s",
    final quantity="VolumeFlowRate") "Design minimum outdoor airflow rate"
    annotation (Placement(transformation(extent={{240,60},{280,100}}),
        iconTransformation(extent={{100,0},{140,40}})));

  Buildings.Controls.OBC.CDL.Interfaces.RealOutput VEffOutAir_flow(
    final min=0,
    final unit="m3/s",
    final quantity="VolumeFlowRate") "Effective minimum outdoor airflow setpoint"
    annotation (Placement(transformation(extent={{240,10},{280,50}}),
        iconTransformation(extent={{100,-40},{140,0}})));

  Buildings.Controls.OBC.CDL.Interfaces.RealOutput effOutAir_normalized(
    final unit="1")
    "Effective minimum outdoor airflow setpoint, normalized by VDesOutMin_flow_nominal"
    annotation (Placement(transformation(extent={{240,-70},{280,-30}}),
        iconTransformation(extent={{100,-70},{140,-30}})));

  Buildings.Controls.OBC.CDL.Interfaces.BooleanOutput yReqOutAir
    "True if the AHU supply fan is on and the zone is in occupied mode"
    annotation (Placement(transformation(extent={{240,-160},{280,-120}}),
        iconTransformation(extent={{100,-100},{140,-60}})));

protected
  Buildings.Controls.OBC.CDL.Continuous.Division outAirFra
    "System outdoor air fraction"
    annotation (Placement(transformation(extent={{-120,-20},{-100,0}})));

  Buildings.Controls.OBC.CDL.Continuous.AddParameter addPar(
    final p=1,
    final k=1)
    "System outdoor air flow fraction plus 1"
    annotation (Placement(transformation(extent={{-80,-20},{-60,0}})));

  Buildings.Controls.OBC.CDL.Continuous.Add sysVenEff(
    final k2=-1)
    "Current system ventilation efficiency"
    annotation (Placement(transformation(extent={{-40,-40},{-20,-20}})));

  Buildings.Controls.OBC.CDL.Continuous.Division effMinOutAirInt
    "Effective minimum outdoor air setpoint"
    annotation (Placement(transformation(extent={{100,10},{120,30}})));

  Buildings.Controls.OBC.CDL.Continuous.Division occDivFra
    "Occupant diversity fraction"
    annotation (Placement(transformation(extent={{-120,180},{-100,200}})));

  Buildings.Controls.OBC.CDL.Continuous.Add unCorOutAirInk
    "Uncorrected outdoor air intake"
    annotation (Placement(transformation(extent={{0,140},{20,160}})));

  Buildings.Controls.OBC.CDL.Continuous.Product pro
    "Product of inputs"
    annotation (Placement(transformation(extent={{-60,160},{-40,180}})));

  Buildings.Controls.OBC.CDL.Continuous.Gain aveOutAirFra(
    final k=1/VPriSysMax_flow)
    "Average outdoor air fraction"
    annotation (Placement(transformation(extent={{60,120},{80,140}})));

  Buildings.Controls.OBC.CDL.Continuous.AddParameter addPar1(
    final p=1,
    final k=1)
    "Average outdoor air flow fraction plus 1"
    annotation (Placement(transformation(extent={{120,120},{140,140}})));

  Buildings.Controls.OBC.CDL.Continuous.Division desOutAirInt
    "Design system outdoor air intake"
    annotation (Placement(transformation(extent={{60,70},{80,90}})));

  Buildings.Controls.OBC.CDL.Continuous.Min min
    "Minimum outdoor airflow rate should not be more than designed outdoor airflow rate"
    annotation (Placement(transformation(extent={{180,20},{200,40}})));

  Buildings.Controls.OBC.CDL.Continuous.Min sysUncOutAir
    "Uncorrected outdoor air rate should not be higher than its design value"
    annotation (Placement(transformation(extent={{-180,0},{-160,20}})));

  Buildings.Controls.OBC.CDL.Integers.Sources.Constant occMod(
    final k=Buildings.Controls.OBC.ASHRAE.G36_PR1.Types.OperationModes.occupied)
    "Occupied mode index"
    annotation (Placement(transformation(extent={{-180,-230},{-160,-210}})));

  Buildings.Controls.OBC.CDL.Continuous.Sources.Constant peaSysPopulation(
    final k=peaSysPop)
    "Peak system population"
    annotation (Placement(transformation(extent={{-180,210},{-160,230}})));

  Buildings.Controls.OBC.CDL.Integers.Equal intEqu1
    "Check if operation mode is occupied"
    annotation (Placement(transformation(extent={{-100,-190},{-80,-170}})));

  Buildings.Controls.OBC.CDL.Logical.And and1 "Logical and"
    annotation (Placement(transformation(extent={{120,-150},{140,-130}})));

  Buildings.Controls.OBC.CDL.Logical.Switch swi4
    "Ensuring the system efficiency will not be negative"
    annotation (Placement(transformation(extent={{60,-70},{80,-50}})));

  Buildings.Controls.OBC.CDL.Continuous.Sources.Constant conOne(
    final k=1)
    "Set system ventilation efficiency to 1"
    annotation (Placement(transformation(extent={{20,-80},{40,-60}})));

  Buildings.Controls.OBC.CDL.Continuous.Division norVOutMin
    "Normalization for minimum outdoor air flow rate"
    annotation (Placement(transformation(extent={{180,-60},{200,-40}})));

  Buildings.Controls.OBC.CDL.Continuous.Hysteresis hys1(
    final uLow=1E-4,
    final uHigh=1E-3)
    "Check if system ventilation efficiency is greater than 0 (using 1E-4 tolerance)"
    annotation (Placement(transformation(extent={{22,-40},{42,-20}})));

equation
  connect(peaSysPopulation.y, occDivFra.u1)
    annotation (Line(points={{-158,220},{-140,220},{-140,196},{-122,196}},
      color={0,0,127}));
  connect(pro.y, unCorOutAirInk.u1)
    annotation (Line(points={{-38,170},{-20,170},{-20,156},{-2,156}},
      color={0,0,127}));
  connect(aveOutAirFra.y, addPar1.u)
    annotation (Line(points={{82,130},{118,130}},color={0,0,127}));
  connect(unCorOutAirInk.y, desOutAirInt.u1)
    annotation (Line(points={{22,150},{40,150},{40,86},{58,86}},    color={0,0,127}));
  connect(sysUncOutAir.y, effMinOutAirInt.u1) annotation (Line(points={{-158,10},
          {-140,10},{-140,26},{98,26}}, color={0,0,127}));
  connect(sysUncOutAir.y, outAirFra.u1) annotation (Line(points={{-158,10},{-140,
          10},{-140,-4},{-122,-4}}, color={0,0,127}));
  connect(unCorOutAirInk.y, sysUncOutAir.u1) annotation (Line(points={{22,150},{
          40,150},{40,50},{-200,50},{-200,16},{-182,16}}, color={0,0,127}));
  connect(desOutAirInt.y, min.u1)
    annotation (Line(points={{82,80},{140,80},{140,36},{178,36}},
      color={0,0,127}));
  connect(unCorOutAirInk.y, VDesUncOutAir_flow)
    annotation (Line(points={{22,150},{40,150},{40,180},{260,180}},
      color={0,0,127}));
  connect(desOutAirInt.y, VDesOutAir_flow)
    annotation (Line(points={{82,80},{260,80}}, color={0,0,127}));
  connect(occDivFra.y, pro.u1)
    annotation (Line(points={{-98,190},{-80,190},{-80,176},{-62,176}},
      color={0,0,127}));
  connect(uOpeMod, intEqu1.u1)
    annotation (Line(points={{-240,-180},{-102,-180}},color={255,127,0}));
  connect(occMod.y, intEqu1.u2)
    annotation (Line(points={{-158,-220},{-140,-220},{-140,-188},{-102,-188}},
      color={255,127,0}));
  connect(intEqu1.y, and1.u2)
    annotation (Line(points={{-78,-180},{20,-180},{20,-148},{118,-148}},
      color={255,0,255}));
  connect(sysVenEff.y, swi4.u1)
    annotation (Line(points={{-18,-30},{0,-30},{0,-52},{58,-52}},
      color={0,0,127}));
  connect(swi4.y, effMinOutAirInt.u2)
    annotation (Line(points={{82,-60},{90,-60},{90,14},{98,14}},
      color={0,0,127}));
  connect(outAirFra.y, addPar.u)
    annotation (Line(points={{-98,-10},{-82,-10}}, color={0,0,127}));
  connect(addPar.y, sysVenEff.u1)
    annotation (Line(points={{-58,-10},{-50,-10},{-50,-24},{-42,-24}},
      color={0,0,127}));
  connect(conOne.y, swi4.u3)
    annotation (Line(points={{42,-70},{50,-70},{50,-68},{58,-68}},
      color={0,0,127}));
  connect(VEffOutAir_flow, min.y)
    annotation (Line(points={{260,30},{202,30}}, color={0,0,127}));
  connect(effMinOutAirInt.y, min.u2)
    annotation (Line(points={{122,20},{160,20},{160,24},{178,24}},
      color={0,0,127}));
  connect(norVOutMin.u1, min.y)
    annotation (Line(points={{178,-44},{160,-44},{160,-10},{220,-10},
      {220,30},{202,30}}, color={0,0,127}));
  connect(desOutAirInt.y, norVOutMin.u2)
    annotation (Line(points={{82,80},{140,80},{140,-56},{178,-56}},
      color={0,0,127}));
  connect(norVOutMin.y, effOutAir_normalized)
    annotation (Line(points={{202,-50},{260,-50}}, color={0,0,127}));
  connect(uSupFan, and1.u1)
    annotation (Line(points={{-240,-140},{118,-140}},
      color={255,0,255}));
  connect(sysVenEff.y, hys1.u)
    annotation (Line(points={{-18,-30},{20,-30}}, color={0,0,127}));
  connect(hys1.y, swi4.u2)
    annotation (Line(points={{44,-30},{50,-30},{50,-60},{58,-60}},
      color={255,0,255}));
  connect(addPar1.y, yAveOutAirFraPlu)
    annotation (Line(points={{142,130},{260,130}},color={0,0,127}));
  connect(occDivFra.u2, sumDesZonPop)
    annotation (Line(points={{-122,184},{-200,184},{-200,200},{-240,200}},
      color={0,0,127}));
  connect(pro.u2, VSumDesPopBreZon_flow) annotation (Line(points={{-62,164},{-200,
          164},{-200,160},{-240,160}}, color={0,0,127}));
  connect(unCorOutAirInk.u2, VSumDesAreBreZon_flow) annotation (Line(points={{-2,144},
          {-200,144},{-200,120},{-240,120}},      color={0,0,127}));
  connect(desOutAirInt.u2, uDesSysVenEff) annotation (Line(points={{58,74},{-80,
          74},{-80,80},{-240,80}}, color={0,0,127}));
  connect(sysUncOutAir.u2, VSumUncOutAir_flow) annotation (Line(points={{-182,4},
          {-200,4},{-200,-24},{-240,-24}}, color={0,0,127}));
  connect(outAirFra.u2, VSumSysPriAir_flow) annotation (Line(points={{-122,-16},
          {-140,-16},{-140,-60},{-240,-60}}, color={0,0,127}));
  connect(sysVenEff.u2, uOutAirFra_max)
    annotation (Line(points={{-42,-36},{-60,-36},{-60,-100},{-240,-100}},
      color={0,0,127}));

  connect(and1.y, yReqOutAir)
    annotation (Line(points={{142,-140},{260,-140}}, color={255,0,255}));
  connect(aveOutAirFra.u, unCorOutAirInk.y) annotation (Line(points={{58,130},{40,
          130},{40,150},{22,150}}, color={0,0,127}));
annotation (
  defaultComponentName="ahuOutAirSet",
  Icon(coordinateSystem(extent={{-100,-100},{100,100}}),
       graphics={Rectangle(
          extent={{-100,100},{100,-100}},
          lineColor={0,0,0},
          fillColor={255,255,255},
          fillPattern=FillPattern.Solid),
        Text(
          extent={{-100,158},{100,118}},
          lineColor={0,0,255},
          textString="%name"),
        Text(
          extent={{-98,98},{-34,86}},
          lineColor={0,0,0},
          textString="sumDesZonPop"),
        Text(
          extent={{-96,-62},{-52,-76}},
          lineColor={255,0,255},
          textString="uSupFan"),
        Text(
          extent={{-96,-82},{-50,-96}},
          lineColor={255,127,0},
          textString="uOpeMod"),
        Text(
          extent={{-98,78},{-12,62}},
          lineColor={0,0,0},
          textString="VDesPopBreZon_flow"),
        Text(
          extent={{-98,58},{-12,42}},
          lineColor={0,0,0},
          textString="VDesAreBreZon_flow"),
        Text(
          extent={{-98,38},{-34,26}},
          lineColor={0,0,0},
          textString="desSysVenEff"),
        Text(
          extent={{-98,18},{-30,4}},
          lineColor={0,0,0},
          textString="VUncOutAir_flow"),
        Text(
          extent={{-98,-2},{-34,-18}},
          lineColor={0,0,0},
          textString="VSysPriAir_flow"),
        Text(
          extent={{-98,-22},{-28,-38}},
          lineColor={0,0,0},
          textString="uOutAirFra_max"),
        Text(
          extent={{42,-74},{102,-86}},
          lineColor={255,0,255},
          textString="yReqOutAir"),
        Text(
          extent={{20,88},{96,72}},
          lineColor={0,0,0},
          textString="VDesUncOutAir_flow"),
        Text(
          extent={{30,60},{98,44}},
          lineColor={0,0,0},
          textString="yAveOutAirFraPlu"),
        Text(
          extent={{34,30},{98,12}},
          lineColor={0,0,0},
          textString="VDesOutAir_flow"),
        Text(
          extent={{38,-10},{98,-26}},
          lineColor={0,0,0},
          textString="VEffOutAir_flow"),
        Text(
          extent={{18,-40},{98,-56}},
          lineColor={0,0,0},
          textString="effOutAir_normalized")}),
Diagram(coordinateSystem(preserveAspectRatio=false, extent={{-220,-240},{240,240}})),
Documentation(info="

This sequence outputs AHU level design minimum outdoor airflow rate
VDesOutAir_flow and effective minimum outdoor airflow rate
VEffOutAir_flow.

It requires following inputs which are sum, maximum or minimum of the outputs from
the zone level calculation:

Sum of the design population of the zones in the group, sumDesZonPop.

Sum of the population component design breathing zone flow rate,
VSumDesPopBreZon_flow.

Sum of the area component design breathing zone flow rate,
VSumDesAreBreZon_flow.

Minimum of all zones ventilation efficiency, uDesSysVenEff.

Sum of all zones required uncorrected outdoor airflow rate, VSumUncOutAir_flow.

Sum of the measured discharged flow rate of all terminal units,
VSumSysPriAir_flow.

Maximum of primary outdoor air fraction of all zones, uOutAirFra_max.

The calculation is done using the steps below.

Compute the occupancy diversity fraction occDivFra.
During system operation, the system population equals the sum of the zone population,
so occDivFra=1. It has no impact on the calculation of the uncorrected
outdoor airflow sysUncOutAir.
For design purpose, compute for all zones

    occDivFra = peaSysPop/sumDesZonPop

where peaSysPop is the peak system population and
sumDesZonPop is the sum of the design population.

Compute the design uncorrected outdoor airflow rate VDesUncOutAir_flow as

    VDesUncOutAir_flow = occDivFra*VSumDesPopBreZon_flow+VSumDesAreBreZon_flow.

Compute the uncorrected outdoor airflow rate sysUncOutAir as

    sysUncOutAir = min(VDesUncOutAir_flow, VSumUncOutAir_flow)

where VSumUncOutAir_flow is sum of all zones required uncorrected
outdoor airflow rate

Compute the outdoor air fraction as

    outAirFra = sysUncOutAir/VSumSysPriAir_flow.

For design purpose, use

    aveOutAirFra = sysUncOutAir/VPriSysMax_flow.

where VPriSysMax_flow is the maximum expected system primary airflow
at design stage.

Compute the system ventilation efficiency sysVenEff. During system
operation, the efficiency is

    sysVenEff = 1 + outAirFra - uOutAirFra_max

Compute the minimum required AHU outdoor air intake flow rate.
The minimum required system outdoor air intake flow should be the uncorrected
outdoor air intake sysUncOutAir divided by the system ventilation
efficiency sysVenEff, but it should not be larger than the design
outdoor air rate desOutAirInt. Hence,

    effMinOutAirInt = min(sysUncOutAir/sysVenEff, desOutAirInt),

where the design outdoor air rate desOutAirInt is

    desOutAirInt = VDesUncOutAir_flow/uDesSysVenEff.

", revisions="

March 13, 2020, by Jianjun Hu:

Separated from original sequence of finding the system minimum outdoor air setpoint.

This is for
#1829.

February 27, 2020, by Jianjun Hu:

Applied hysteresis for checking ventilation efficiency.

This is for
#1787.

January 30, 2020, by Michael Wetter:

Removed the use of fill when assigning the unit attribute.

This is for
#1728.

January 12, 2019, by Michael Wetter:

Added missing each.

July 5, 2017, by Michael Wetter:

Revised implementation.

May 12, 2017, by Jianjun Hu:

First implementation.

"));
end AHU;

{'repo_name': 'lbl-srg/modelica-buildings', 'stars': '110', 'repo_language': 'Modelica', 'file_name': 'package.order', 'mime_type': 'text/plain', 'hash': 2355238500806129774, 'source_dataset': 'data'}


/*
 * Copyright (C) 2017 Wouter Dullaert
 *
 * 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.
 */

package com.wdullaer.materialdatetimepicker.date;

import android.os.Parcelable;
import androidx.annotation.NonNull;

import java.util.Calendar;

@SuppressWarnings("WeakerAccess")
public interface DateRangeLimiter extends Parcelable {
    /**
     * getMinYear returns the minimum selectable year of the picker.
     * This method should match getStartDate()
     * It is recommended to keep the default implementation
     * This method will be removed from this interface at the next semver major
     * @return the minimum selectable year of the picker
     */
    default int getMinYear() {
        return getStartDate().get(Calendar.YEAR);
    }

    /**
     * getMaxYear returns the maximum selectable year of the picker
     * This method should semantically match getEndDate()
     * It is recommended to keep the default implementation.
     * This method will be removed from this interface at the next semver major
     * @return the maximum selectable year of the picker
     */
    default int getMaxYear() {
        return getEndDate().get(Calendar.YEAR);
    }

    /**
     * getStartDate returns the minimum selectable date of the picker
     * It is called in various places, including the hot loop when rendering.
     * It is highly recommended to keep this method as simple as possible
     * @return the minimum selectable date of the picker
     */
    @NonNull Calendar getStartDate();

    /**
     * getEndDate returns the maximum selectable date of the picker
     * It is called in various places, including the hot loop when rendering.
     * It is highly recommended to keep this method as simple as possible
     * @return the maximum selectable date of the picker
     */
    @NonNull Calendar getEndDate();

    /**
     * isOutOfRange is called for each date when it is about to be rendered
     * Returning true from this function will cause that particular day to be non selectable
     * Since this code is called in the inner loop when rendering, it is highly recommended to
     * keep the logic as simple as possible
     * @param year the year of the date
     * @param month the month of the date
     * @param day the day of the month of the date
     * @return true if the date should be disabled, false otherwise
     */
    boolean isOutOfRange(int year, int month, int day);

    /**
     * setToNearestDate rounds a Date to the nearest selectable value.
     * It is called each time the user makes a year selection: the newly resulting date might not be
     * valid according to the constraints set by the limiter.
     * This method is not called when the user selects a day, since the picker prevents the
     * selection of values which satisfy `isOutOfRange`
     * @param day a date with the current user selection
     * @return the date after rounding to a selectable value
     */
    @NonNull Calendar setToNearestDate(@NonNull Calendar day);
}

{'repo_name': 'wdullaer/MaterialDateTimePicker', 'stars': '4430', 'repo_language': 'Java', 'file_name': 'android-sdk-preview-license', 'mime_type': 'text/plain', 'hash': -244917576118378935, 'source_dataset': 'data'}


######################## BEGIN LICENSE BLOCK ########################
# The Original Code is Mozilla Communicator client code.
#
# The Initial Developer of the Original Code is
# Netscape Communications Corporation.
# Portions created by the Initial Developer are Copyright (C) 1998
# the Initial Developer. All Rights Reserved.
#
# Contributor(s):
#   Mark Pilgrim - port to Python
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library 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
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
# 02110-1301  USA
######################### END LICENSE BLOCK #########################

# 255: Control characters that usually does not exist in any text
# 254: Carriage/Return
# 253: symbol (punctuation) that does not belong to word
# 252: 0 - 9

# Character Mapping Table:
# this table is modified base on win1251BulgarianCharToOrderMap, so
# only number <64 is sure valid

Latin5_BulgarianCharToOrderMap = (
255,255,255,255,255,255,255,255,255,255,254,255,255,254,255,255,  # 00
255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,  # 10
253,253,253,253,253,253,253,253,253,253,253,253,253,253,253,253,  # 20
252,252,252,252,252,252,252,252,252,252,253,253,253,253,253,253,  # 30
253, 77, 90, 99,100, 72,109,107,101, 79,185, 81,102, 76, 94, 82,  # 40
110,186,108, 91, 74,119, 84, 96,111,187,115,253,253,253,253,253,  # 50
253, 65, 69, 70, 66, 63, 68,112,103, 92,194,104, 95, 86, 87, 71,  # 60
116,195, 85, 93, 97,113,196,197,198,199,200,253,253,253,253,253,  # 70
194,195,196,197,198,199,200,201,202,203,204,205,206,207,208,209,  # 80
210,211,212,213,214,215,216,217,218,219,220,221,222,223,224,225,  # 90
 81,226,227,228,229,230,105,231,232,233,234,235,236, 45,237,238,  # a0
 31, 32, 35, 43, 37, 44, 55, 47, 40, 59, 33, 46, 38, 36, 41, 30,  # b0
 39, 28, 34, 51, 48, 49, 53, 50, 54, 57, 61,239, 67,240, 60, 56,  # c0
  1, 18,  9, 20, 11,  3, 23, 15,  2, 26, 12, 10, 14,  6,  4, 13,  # d0
  7,  8,  5, 19, 29, 25, 22, 21, 27, 24, 17, 75, 52,241, 42, 16,  # e0
 62,242,243,244, 58,245, 98,246,247,248,249,250,251, 91,252,253,  # f0
)

win1251BulgarianCharToOrderMap = (
255,255,255,255,255,255,255,255,255,255,254,255,255,254,255,255,  # 00
255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,  # 10
253,253,253,253,253,253,253,253,253,253,253,253,253,253,253,253,  # 20
252,252,252,252,252,252,252,252,252,252,253,253,253,253,253,253,  # 30
253, 77, 90, 99,100, 72,109,107,101, 79,185, 81,102, 76, 94, 82,  # 40
110,186,108, 91, 74,119, 84, 96,111,187,115,253,253,253,253,253,  # 50
253, 65, 69, 70, 66, 63, 68,112,103, 92,194,104, 95, 86, 87, 71,  # 60
116,195, 85, 93, 97,113,196,197,198,199,200,253,253,253,253,253,  # 70
206,207,208,209,210,211,212,213,120,214,215,216,217,218,219,220,  # 80
221, 78, 64, 83,121, 98,117,105,222,223,224,225,226,227,228,229,  # 90
 88,230,231,232,233,122, 89,106,234,235,236,237,238, 45,239,240,  # a0
 73, 80,118,114,241,242,243,244,245, 62, 58,246,247,248,249,250,  # b0
 31, 32, 35, 43, 37, 44, 55, 47, 40, 59, 33, 46, 38, 36, 41, 30,  # c0
 39, 28, 34, 51, 48, 49, 53, 50, 54, 57, 61,251, 67,252, 60, 56,  # d0
  1, 18,  9, 20, 11,  3, 23, 15,  2, 26, 12, 10, 14,  6,  4, 13,  # e0
  7,  8,  5, 19, 29, 25, 22, 21, 27, 24, 17, 75, 52,253, 42, 16,  # f0
)

# Model Table:
# total sequences: 100%
# first 512 sequences: 96.9392%
# first 1024 sequences:3.0618%
# rest  sequences:     0.2992%
# negative sequences:  0.0020%
BulgarianLangModel = (
0,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,2,3,3,3,3,3,3,3,3,2,3,3,3,3,3,
3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,0,3,3,3,2,2,3,2,2,1,2,2,
3,1,3,3,2,3,3,3,3,3,3,3,3,3,3,3,3,0,3,3,3,3,3,3,3,3,3,3,0,3,0,1,
0,0,0,0,0,0,0,0,0,0,1,0,1,1,0,0,0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'charset_name': "ISO-8859-5",
  'language': 'Bulgairan',
}

Win1251BulgarianModel = {
  'char_to_order_map': win1251BulgarianCharToOrderMap,
  'precedence_matrix': BulgarianLangModel,
  'typical_positive_ratio': 0.969392,
  'keep_english_letter': False,
  'charset_name': "windows-1251",
  'language': 'Bulgarian',
}

{'repo_name': 'ehsahil/recon-my-way', 'stars': '245', 'repo_language': 'C', 'file_name': 'csp_parser.py', 'mime_type': 'text/x-python', 'hash': -6883904613951299301, 'source_dataset': 'data'}


"""Classes and functions related to the PSLab's oscilloscope instrument.

Example
-------
>>> from PSL.oscilloscope import Oscilloscope
>>> scope = Oscilloscope()
>>> x, y1, y2, y3, y4 = scope.capture(channels=4, samples=1600, timegap=2)
"""

import time
from typing import Tuple, Union

import numpy as np

import PSL.commands_proto as CP
from PSL import achan, packet_handler

class Oscilloscope:
    """Capture varying voltage signals on up to four channels simultaneously.

    Parameters
    ----------
    device : :class:`Handler`, optional
        Serial interface for communicating with the PSLab device. If not provided, a
        new one will be created.

    Attributes
    ----------
    channel_one_map : str
        Remap the first sampled channel. The default value is "CH1".
    trigger_enabled
    """

    MAX_SAMPLES = 10000
    CH234 = ["CH2", "CH3", "MIC"]

    def __init__(self, device: packet_handler.Handler = None):
        self._device = packet_handler.Handler() if device is None else device
        self._channels = {
            a: achan.AnalogInput(a, self._device) for a in achan.ANALOG_CHANNELS
        }
        self.channel_one_map = "CH1"
        self._trigger_voltage = 0
        self._trigger_enabled = False
        self._trigger_channel = "CH1"

    def capture(self, channels: int, samples: int, timegap: float,) -> np.ndarray:
        """Capture an oscilloscope trace from the specified input channels.

        This is a blocking call.

        Parameters
        ----------
        channels : {1, 2, 4}
            Number of channels to sample from simultaneously. By default, samples are
            captured from CH1, CH2, CH3 and MIC. CH1 can be remapped to any other
            channel (CH2, CH3, MIC, CAP, SEN, AN8) by setting the channel_one_map
            attribute of the Oscilloscope instance to the desired channel.
        samples : int
            Number of samples to fetch. Maximum 10000 divided by number of channels.
        timegap : float
            Time gap between samples in microseconds. Will be rounded to the closest
            1 / 8 µs. The minimum time gap depends on the type of measurement:
                +--------------+------------+----------+------------+
                | Simultaneous | No trigger | Trigger  | No trigger |
                | channels     | (10-bit)   | (10-bit) | (12-bit)   |
                +==============+============+==========+============+
                | 1            | 0.5 µs     | 0.75 µs  | 1 µs       |
                +--------------+------------+----------+------------+
                | 2            | 0.875 µs   | 0.875 µs | N/A        |
                +--------------+------------+----------+------------+
                | 4            | 1.75 µs    | 1.75 µs  | N/A        |
                +--------------+------------+----------+------------+
            Sample resolution is set automatically based on the above limitations; i.e.
            to get 12-bit samples only one channel may be sampled, there must be no
            active trigger, and the time gap must be 1 µs or greater.

        Example
        -------
        >>> from PSL.oscilloscope import Oscilloscope
        >>> scope = Oscilloscope()
        >>> x, y = scope.capture(1, 3200, 1)

        Returns
        -------
        numpy.ndarray
            (:channels:+1)-dimensional array with timestamps in the first dimension
            and corresponding voltages in the following dimensions.

        Raises
        ------
        ValueError
            If :channels: is not 1, 2 or 4, or
            :samples: > 10000 / :channels:, or
            :channel_one_map: is not one of CH1, CH2, CH3, MIC, CAP, SEN, AN8, or
            :timegap: is too low.
        """
        xy = np.zeros([channels + 1, samples])
        xy[0] = self.capture_nonblocking(channels, samples, timegap)
        time.sleep(1e-6 * samples * timegap + 0.01)

        while not self.progress()[0]:
            pass

        active_channels = ([self.channel_one_map] + self.CH234)[:channels]
        for e, c in enumerate(active_channels):
            xy[e + 1] = self.fetch_data(c)

        return xy

    def capture_nonblocking(
        self, channels: int, samples: int, timegap: float
    ) -> np.ndarray:
        """Tell the pslab to start sampling the specified input channels.

        This method is identical to
        :meth:`capture <PSL.oscilloscope.Oscilloscope.capture>`,
        except it does not block while the samples are being captured. Collected
        samples must be manually fetched by calling
        :meth:`fetch_data<PSL.oscilloscope.Oscilloscope.fetch_data>`.

        Parameters
        ----------
        See :meth:`capture <PSL.oscilloscope.Oscilloscope.capture>`.

        Example
        -------
        >>> import time
        >>> from PSL.oscilloscope import Oscilloscope
        >>> scope = Oscilloscope()
        >>> x = scope.capture_nonblocking(1, 3200, 1)
        >>> time.sleep(3200 * 1e-6)
        >>> y = scope.fetch_data("CH1")

        Returns
        -------
        numpy.ndarray
            One-dimensional array of timestamps.

        Raises
        ------
        See :meth:`capture <PSL.oscilloscope.Oscilloscope.capture>`.
        """
        self._check_args(channels, samples, timegap)
        timegap = int(timegap * 8) / 8
        self._capture(channels, samples, timegap)
        return timegap * np.arange(samples)

    def _check_args(self, channels: int, samples: int, timegap: float):
        if channels not in (1, 2, 4):
            raise ValueError("Number of channels to sample must be 1, 2, or 4.")

        max_samples = self.MAX_SAMPLES // channels
        if not 0 < samples <= max_samples:
            e1 = f"Cannot collect more than {max_samples} when sampling from "
            e2 = f"{channels} channels."
            raise ValueError(e1 + e2)

        min_timegap = self._lookup_mininum_timegap(channels)
        if timegap < min_timegap:
            raise ValueError(f"timegap must be at least {min_timegap}.")

        if self.channel_one_map not in self._channels:
            e1 = f"{self.channel_one_map} is not a valid channel. "
            e2 = f"Valid channels are {list(self._channels.keys())}."
            raise ValueError(e1 + e2)

    def _lookup_mininum_timegap(self, channels: int) -> float:
        channels_idx = {
            1: 0,
            2: 1,
            4: 2,
        }
        min_timegaps = [[0.5, 0.75], [0.875, 0.875], [1.75, 1.75]]

        return min_timegaps[channels_idx[channels]][self.trigger_enabled]

    def _capture(self, channels: int, samples: int, timegap: float):
        self._invalidate_buffer()
        chosa = self._channels[self.channel_one_map].chosa
        self._channels[self.channel_one_map].resolution = 10
        self._device.send_byte(CP.ADC)

        CH123SA = 0  # TODO what is this?
        chosa = self._channels[self.channel_one_map].chosa
        self._channels[self.channel_one_map].samples_in_buffer = samples
        self._channels[self.channel_one_map].buffer_idx = 0
        if channels == 1:
            if self.trigger_enabled:
                self._device.send_byte(CP.CAPTURE_ONE)
                self._device.send_byte(chosa | 0x80)  # Trigger
            elif timegap >= 1:
                self._channels[self.channel_one_map].resolution = 12
                self._device.send_byte(CP.CAPTURE_DMASPEED)
                self._device.send_byte(chosa | 0x80)  # 12-bit mode
            else:
                self._device.send_byte(CP.CAPTURE_DMASPEED)
                self._device.send_byte(chosa)  # 10-bit mode
        elif channels == 2:
            self._channels["CH2"].resolution = 10
            self._channels["CH2"].samples_in_buffer = samples
            self._channels["CH2"].buffer_idx = 1 * samples
            self._device.send_byte(CP.CAPTURE_TWO)
            self._device.send_byte(chosa | (0x80 * self.trigger_enabled))
        else:
            for e, c in enumerate(self.CH234):
                self._channels[c].resolution = 10
                self._channels[c].samples_in_buffer = samples
                self._channels[c].buffer_idx = (e + 1) * samples
            self._device.send_byte(CP.CAPTURE_FOUR)
            self._device.send_byte(
                chosa | (CH123SA << 4) | (0x80 * self.trigger_enabled)
            )

        self._device.send_int(samples)
        self._device.send_int(int(timegap * 8))  # 8 MHz clock
        self._device.get_ack()

    def _invalidate_buffer(self):
        for c in self._channels.values():
            c.samples_in_buffer = 0
            c.buffer_idx = None

    def fetch_data(self, channel: str) -> np.ndarray:
        """Fetch samples captured from specified channel.

        Parameters
        ----------
        channel : {'CH1', 'CH2', 'CH3', 'MIC', 'CAP', 'SEN', 'AN8'}
            Name of the channel from which to fetch captured data.

        Example
        -------
        >>> from PSL.oscilloscope import Oscilloscope
        >>> scope = Oscilloscope()
        >>> scope.capture_nonblocking(channels=2, samples=1600, timegap=1)
        >>> y1 = scope.fetch_data("CH1")
        >>> y2 = scope.fetch_data("CH2")

        Returns
        -------
        numpy.ndarray
            One-dimensional array holding the requested voltages.
        """
        data = bytearray()
        channel = self._channels[channel]
        samples = channel.samples_in_buffer

        for i in range(int(np.ceil(samples / CP.DATA_SPLITTING))):
            self._device.send_byte(CP.COMMON)
            self._device.send_byte(CP.RETRIEVE_BUFFER)
            offset = channel.buffer_idx + i * CP.DATA_SPLITTING
            self._device.send_int(offset)
            self._device.send_int(CP.DATA_SPLITTING)  # Ints to read
            # Reading int by int sometimes causes a communication error.
            data += self._device.interface.read(CP.DATA_SPLITTING * 2)
            self._device.get_ack()

        data = [CP.ShortInt.unpack(data[s * 2 : s * 2 + 2])[0] for s in range(samples)]

        return channel.scale(np.array(data))

    def progress(self) -> Tuple[bool, int]:
        """Return the status of a capture call.

        Returns
        -------
        bool, int
            A boolean indicating whether the capture is complete, followed by the
            number of samples currently held in the buffer.
        """
        self._device.send_byte(CP.ADC)
        self._device.send_byte(CP.GET_CAPTURE_STATUS)
        conversion_done = self._device.get_byte()
        samples = self._device.get_int()
        self._device.get_ack()

        return bool(conversion_done), samples

    def configure_trigger(self, channel: str, voltage: float, prescaler: int = 0):
        """Configure trigger parameters for 10-bit capture routines.

        The capture routines will wait until a rising edge of the input signal crosses
        the specified level. The trigger will timeout within 8 ms, and capture will
        start regardless.

        To disable the trigger after configuration, set the trigger_enabled attribute
        of the Oscilloscope instance to False.

        Parameters
        ----------
        channel : {'CH1', 'CH2', 'CH3', 'MIC', 'CAP', 'SEN', 'AN8'}
            The name of the trigger channel.
        voltage : float
            The trigger voltage in volts.
        prescaler : int, optional
            The default value is 0.

        Examples
        --------
        >>> from PSL.oscilloscope import Oscilloscope
        >>> scope = Oscilloscope()
        >>> scope.configure_trigger(channel='CH1', voltage=1.1)
        >>> xy = scope.capture(channels=1, samples=800, timegap=2)
        >>> diff = abs(xy[1, 0] - 1.1)  # Should be small unless a timeout occurred.

        Raises
        ------
        TypeError
            If the trigger channel is set to a channel which cannot be sampled.
        """
        self._trigger_channel = channel

        if channel == self.channel_one_map:
            channel = 0
        elif channel in self.CH234:
            channel = self.CH234.index(channel) + 1
        elif self.channel_one_map == "CH1":
            e = f"Cannot trigger on {channel} unless it is remapped to CH1."
            raise TypeError(e)
        else:
            e = f"Cannot trigger on CH1 when {self.channel_one_map} is mapped to CH1."
            raise TypeError(e)

        self._device.send_byte(CP.ADC)
        self._device.send_byte(CP.CONFIGURE_TRIGGER)
        # Trigger channel (4lsb) , trigger timeout prescaler (4msb)
        self._device.send_byte((prescaler << 4) | (1 << channel))  # TODO prescaler?
        level = self._channels[self._trigger_channel].unscale(voltage)
        self._device.send_int(level)
        self._device.get_ack()
        self._trigger_enabled = True

    @property
    def trigger_enabled(self) -> bool:
        """Activate or deactivate a trigger set by :meth:`configure_trigger`.

        Becomes True automatically when calling :meth:`configure_trigger`.

        If trigger_enabled is set to True without first calling
        :meth:`configure_trigger`, the trigger will be configured with a trigger
        voltage of 0 V on CH1.
        """
        return self._trigger_enabled

    @trigger_enabled.setter
    def trigger_enabled(self, value: bool):
        self._trigger_enabled = value
        if self._trigger_enabled:
            self.configure_trigger(self._trigger_channel, self._trigger_voltage)

    def select_range(self, channel: str, voltage_range: Union[int, float]):
        """Set appropriate gain automatically.

        Setting the right voltage range will result in better resolution.

        Parameters
        ----------
        channel : {'CH1', 'CH2'}
            Channel on which to apply gain.
        voltage_range : {16,8,4,3,2,1.5,1,.5}

        Examples
        --------
        >>> from PSL.oscilloscope import Oscilloscope
        >>> scope = Oscilloscope()
        >>> scope.select_range('CH1', 8)
        # Gain set to 2x on CH1. Voltage range ±8 V.
        """
        ranges = [16, 8, 4, 3, 2, 1.5, 1, 0.5]
        if voltage_range in ranges:
            idx = ranges.index(voltage_range)
            gain = achan.GAIN_VALUES[idx]
            self._channels[channel].gain = gain
        else:
            e = f"Invalid range: {voltage_range}. Valid ranges are {ranges}."
            raise ValueError(e)

{'repo_name': 'fossasia/pslab-python', 'stars': '1178', 'repo_language': 'Python', 'file_name': 'TSL2561.py', 'mime_type': 'text/x-python', 'hash': 2021291888852601922, 'source_dataset': 'data'}


//
// URI.cpp
//
// Library: Foundation
// Package: URI
// Module:  URI
//
// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier:	BSL-1.0
//

#include "Poco/URI.h"
#include "Poco/NumberFormatter.h"
#include "Poco/Exception.h"
#include "Poco/String.h"
#include "Poco/NumberParser.h"
#include "Poco/Path.h"

namespace Poco {

const std::string URI::RESERVED_PATH        = "?#";
const std::string URI::RESERVED_QUERY       = "?#/:;+@";
const std::string URI::RESERVED_QUERY_PARAM = "?#/:;+@&=";
const std::string URI::RESERVED_FRAGMENT    = "";
const std::string URI::ILLEGAL              = "%<>{}|\\\"^`!*'()$,[]";

URI::URI():
	_port(0)
{
}

URI::URI(const std::string& uri):
	_port(0)
{
	parse(uri);
}

URI::URI(const char* uri):
	_port(0)
{
	parse(std::string(uri));
}

URI::URI(const std::string& scheme, const std::string& pathEtc):
	_scheme(scheme),
	_port(0)
{
	toLowerInPlace(_scheme);
	std::string::const_iterator beg = pathEtc.begin();
	std::string::const_iterator end = pathEtc.end();
	parsePathEtc(beg, end);
}

URI::URI(const std::string& scheme, const std::string& authority, const std::string& pathEtc):
	_scheme(scheme)
{
	toLowerInPlace(_scheme);
	std::string::const_iterator beg = authority.begin();
	std::string::const_iterator end = authority.end();
	parseAuthority(beg, end);
	beg = pathEtc.begin();
	end = pathEtc.end();
	parsePathEtc(beg, end);
}

URI::URI(const std::string& scheme, const std::string& authority, const std::string& path, const std::string& query):
	_scheme(scheme),
	_path(path),
	_query(query)
{
	toLowerInPlace(_scheme);
	std::string::const_iterator beg = authority.begin();
	std::string::const_iterator end = authority.end();
	parseAuthority(beg, end);
}

URI::URI(const std::string& scheme, const std::string& authority, const std::string& path, const std::string& query, const std::string& fragment):
	_scheme(scheme),
	_path(path),
	_query(query),
	_fragment(fragment)
{
	toLowerInPlace(_scheme);
	std::string::const_iterator beg = authority.begin();
	std::string::const_iterator end = authority.end();
	parseAuthority(beg, end);
}

URI::URI(const URI& uri):
	_scheme(uri._scheme),
	_userInfo(uri._userInfo),
	_host(uri._host),
	_port(uri._port),
	_path(uri._path),
	_query(uri._query),
	_fragment(uri._fragment)
{
}

URI::URI(URI&& uri) noexcept:
	_scheme(std::move(uri._scheme)),
	_userInfo(std::move(uri._userInfo)),
	_host(std::move(uri._host)),
	_port(std::move(uri._port)),
	_path(std::move(uri._path)),
	_query(std::move(uri._query)),
	_fragment(std::move(uri._fragment))
{
}

URI::URI(const URI& baseURI, const std::string& relativeURI):
	_scheme(baseURI._scheme),
	_userInfo(baseURI._userInfo),
	_host(baseURI._host),
	_port(baseURI._port),
	_path(baseURI._path),
	_query(baseURI._query),
	_fragment(baseURI._fragment)
{
	resolve(relativeURI);
}

URI::URI(const Path& path):
	_scheme("file"),
	_port(0)
{
	Path absolutePath(path);
	absolutePath.makeAbsolute();
	_path = absolutePath.toString(Path::PATH_UNIX);
}

URI::~URI()
{
}

URI& URI::operator = (const URI& uri)
{
	if (&uri != this)
	{
		_scheme   = uri._scheme;
		_userInfo = uri._userInfo;
		_host     = uri._host;
		_port     = uri._port;
		_path     = uri._path;
		_query    = uri._query;
		_fragment = uri._fragment;
	}
	return *this;
}

URI& URI::operator = (URI&& uri) noexcept
{
	_scheme   = std::move(uri._scheme);
	_userInfo = std::move(uri._userInfo);
	_host     = std::move(uri._host);
	_port     = std::move(uri._port);
	_path     = std::move(uri._path);
	_query    = std::move(uri._query);
	_fragment = std::move(uri._fragment);

	return *this;
}

URI& URI::operator = (const std::string& uri)
{
	clear();
	parse(uri);
	return *this;
}

URI& URI::operator = (const char* uri)
{
	clear();
	parse(std::string(uri));
	return *this;
}

void URI::swap(URI& uri)
{
	std::swap(_scheme, uri._scheme);
	std::swap(_userInfo, uri._userInfo);
	std::swap(_host, uri._host);
	std::swap(_port, uri._port);
	std::swap(_path, uri._path);
	std::swap(_query, uri._query);
	std::swap(_fragment, uri._fragment);
}

void URI::clear()
{
	_scheme.clear();
	_userInfo.clear();
	_host.clear();
	_port = 0;
	_path.clear();
	_query.clear();
	_fragment.clear();
}

std::string URI::toString() const
{
	std::string uri;
	if (isRelative())
	{
		encode(_path, RESERVED_PATH, uri);
	}
	else
	{
		uri = _scheme;
		uri += ':';
		std::string auth = getAuthority();
		if (!auth.empty() || _scheme == "file")
		{
			uri.append("//");
			uri.append(auth);
		}
		if (!_path.empty())
		{
			if (!auth.empty() && _path[0] != '/')
				uri += '/';
			encode(_path, RESERVED_PATH, uri);
		}
		else if (!_query.empty() || !_fragment.empty())
		{
			uri += '/';
		}
	}
	if (!_query.empty())
	{
		uri += '?';
		uri.append(_query);
	}
	if (!_fragment.empty())
	{
		uri += '#';
		encode(_fragment, RESERVED_FRAGMENT, uri);
	}
	return uri;
}

void URI::setScheme(const std::string& scheme)
{
	_scheme = scheme;
	toLowerInPlace(_scheme);
}

void URI::setUserInfo(const std::string& userInfo)
{
	_userInfo.clear();
	decode(userInfo, _userInfo);
}

void URI::setHost(const std::string& host)
{
	_host = host;
}

unsigned short URI::getPort() const
{
	if (_port == 0)
		return getWellKnownPort();
	else
		return _port;
}

void URI::setPort(unsigned short port)
{
	_port = port;
}

std::string URI::getAuthority() const
{
	std::string auth;
	if (!_userInfo.empty())
	{
		auth.append(_userInfo);
		auth += '@';
	}
	if (_host.find(':') != std::string::npos)
	{
		auth += '[';
		auth += _host;
		auth += ']';
	}
	else auth.append(_host);
	if (_port && !isWellKnownPort())
	{
		auth += ':';
		NumberFormatter::append(auth, _port);
	}
	return auth;
}

void URI::setAuthority(const std::string& authority)
{
	_userInfo.clear();
	_host.clear();
	_port = 0;
	std::string::const_iterator beg = authority.begin();
	std::string::const_iterator end = authority.end();
	parseAuthority(beg, end);
}

void URI::setPath(const std::string& path)
{
	_path.clear();
	decode(path, _path);
}

void URI::setRawQuery(const std::string& query)
{
	_query = query;
}

void URI::setQuery(const std::string& query)
{
	_query.clear();
	encode(query, RESERVED_QUERY, _query);
}

void URI::addQueryParameter(const std::string& param, const std::string& val)
{
	if (!_query.empty()) _query += '&';
	encode(param, RESERVED_QUERY_PARAM, _query);
	_query += '=';
	encode(val, RESERVED_QUERY_PARAM, _query);
}

std::string URI::getQuery() const
{
	std::string query;
	decode(_query, query);
	return query;
}

URI::QueryParameters URI::getQueryParameters() const
{
	QueryParameters result;
	std::string::const_iterator it(_query.begin());
	std::string::const_iterator end(_query.end());
	while (it != end)
	{
		std::string name;
		std::string value;
		while (it != end && *it != '=' && *it != '&')
		{
			if (*it == '+')
				name += ' ';
			else
				name += *it;
			++it;
		}
		if (it != end && *it == '=')
		{
			++it;
			while (it != end && *it != '&')
			{
				if (*it == '+')
					value += ' ';
				else
					value += *it;
				++it;
			}
		}
		std::string decodedName;
		std::string decodedValue;
		URI::decode(name, decodedName);
		URI::decode(value, decodedValue);
		result.push_back(std::make_pair(decodedName, decodedValue));
		if (it != end && *it == '&') ++it;
	}
	return result;
}

void URI::setQueryParameters(const QueryParameters& params)
{
	_query.clear();
	for (const auto& p: params)
	{
		addQueryParameter(p.first, p.second);
	}
}

void URI::setFragment(const std::string& fragment)
{
	_fragment.clear();
	decode(fragment, _fragment);
}

void URI::setPathEtc(const std::string& pathEtc)
{
	_path.clear();
	_query.clear();
	_fragment.clear();
	std::string::const_iterator beg = pathEtc.begin();
	std::string::const_iterator end = pathEtc.end();
	parsePathEtc(beg, end);
}

std::string URI::getPathEtc() const
{
	std::string pathEtc;
	encode(_path, RESERVED_PATH, pathEtc);
	if (!_query.empty())
	{
		pathEtc += '?';
		pathEtc += _query;
	}
	if (!_fragment.empty())
	{
		pathEtc += '#';
		encode(_fragment, RESERVED_FRAGMENT, pathEtc);
	}
	return pathEtc;
}

std::string URI::getPathAndQuery() const
{
	std::string pathAndQuery;
	encode(_path, RESERVED_PATH, pathAndQuery);
	if (!_query.empty())
	{
		pathAndQuery += '?';
		pathAndQuery += _query;
	}
	return pathAndQuery;
}

void URI::resolve(const std::string& relativeURI)
{
	URI parsedURI(relativeURI);
	resolve(parsedURI);
}

void URI::resolve(const URI& relativeURI)
{
	if (!relativeURI._scheme.empty())
	{
		_scheme   = relativeURI._scheme;
		_userInfo = relativeURI._userInfo;
		_host     = relativeURI._host;
		_port     = relativeURI._port;
		_path     = relativeURI._path;
		_query    = relativeURI._query;
		removeDotSegments();
	}
	else
	{
		if (!relativeURI._host.empty())
		{
			_userInfo = relativeURI._userInfo;
			_host     = relativeURI._host;
			_port     = relativeURI._port;
			_path     = relativeURI._path;
			_query    = relativeURI._query;
			removeDotSegments();
		}
		else
		{
			if (relativeURI._path.empty())
			{
				if (!relativeURI._query.empty())
					_query = relativeURI._query;
			}
			else
			{
				if (relativeURI._path[0] == '/')
				{
					_path = relativeURI._path;
					removeDotSegments();
				}
				else
				{
					mergePath(relativeURI._path);
				}
				_query = relativeURI._query;
			}
		}
	}
	_fragment = relativeURI._fragment;
}

bool URI::isRelative() const
{
	return _scheme.empty();
}

bool URI::empty() const
{
	return _scheme.empty() && _host.empty() && _path.empty() && _query.empty() && _fragment.empty();
}

bool URI::operator == (const URI& uri) const
{
	return equals(uri);
}

bool URI::operator == (const std::string& uri) const
{
	URI parsedURI(uri);
	return equals(parsedURI);
}

bool URI::operator != (const URI& uri) const
{
	return !equals(uri);
}

bool URI::operator != (const std::string& uri) const
{
	URI parsedURI(uri);
	return !equals(parsedURI);
}

bool URI::equals(const URI& uri) const
{
	return _scheme   == uri._scheme
	    && _userInfo == uri._userInfo
	    && _host     == uri._host
	    && getPort() == uri.getPort()
	    && _path     == uri._path
	    && _query    == uri._query
	    && _fragment == uri._fragment;
}

void URI::normalize()
{
	removeDotSegments(!isRelative());
}

void URI::removeDotSegments(bool removeLeading)
{
	if (_path.empty()) return;

	bool leadingSlash  = *(_path.begin()) == '/';
	bool trailingSlash = *(_path.rbegin()) == '/';
	std::vector<std::string> segments;
	std::vector<std::string> normalizedSegments;
	getPathSegments(segments);
	for (const auto& s: segments)
	{
		if (s == "..")
		{
			if (!normalizedSegments.empty())
			{
				if (normalizedSegments.back() == "..")
					normalizedSegments.push_back(s);
				else
					normalizedSegments.pop_back();
			}
			else if (!removeLeading)
			{
				normalizedSegments.push_back(s);
			}
		}
		else if (s != ".")
		{
			normalizedSegments.push_back(s);
		}
	}
	buildPath(normalizedSegments, leadingSlash, trailingSlash);
}

void URI::getPathSegments(std::vector<std::string>& segments)
{
	getPathSegments(_path, segments);
}

void URI::getPathSegments(const std::string& path, std::vector<std::string>& segments)
{
	std::string::const_iterator it  = path.begin();
	std::string::const_iterator end = path.end();
	std::string seg;
	while (it != end)
	{
		if (*it == '/')
		{
			if (!seg.empty())
			{
				segments.push_back(seg);
				seg.clear();
			}
		}
		else seg += *it;
		++it;
	}
	if (!seg.empty())
		segments.push_back(seg);
}

void URI::encode(const std::string& str, const std::string& reserved, std::string& encodedStr)
{
	for (auto c: str)
	{
		if ((c >= 'a' && c <= 'z') ||
		    (c >= 'A' && c <= 'Z') ||
		    (c >= '0' && c <= '9') ||
		    c == '-' || c == '_' ||
		    c == '.' || c == '~')
		{
			encodedStr += c;
		}
		else if (c <= 0x20 || c >= 0x7F || ILLEGAL.find(c) != std::string::npos || reserved.find(c) != std::string::npos)
		{
			encodedStr += '%';
			encodedStr += NumberFormatter::formatHex((unsigned) (unsigned char) c, 2);
		}
		else encodedStr += c;
	}
}

void URI::decode(const std::string& str, std::string& decodedStr, bool plusAsSpace)
{
	bool inQuery = false;
	std::string::const_iterator it  = str.begin();
	std::string::const_iterator end = str.end();
	while (it != end)
	{
		char c = *it++;
		if (c == '?') inQuery = true;
		// spaces may be encoded as plus signs in the query
		if (inQuery && plusAsSpace && c == '+') c = ' ';
		else if (c == '%')
		{
			if (it == end) throw URISyntaxException("URI encoding: no hex digit following percent sign", str);
			char hi = *it++;
			if (it == end) throw URISyntaxException("URI encoding: two hex digits must follow percent sign", str);
			char lo = *it++;
			if (hi >= '0' && hi <= '9')
				c = hi - '0';
			else if (hi >= 'A' && hi <= 'F')
				c = hi - 'A' + 10;
			else if (hi >= 'a' && hi <= 'f')
				c = hi - 'a' + 10;
			else throw URISyntaxException("URI encoding: not a hex digit");
			c *= 16;
			if (lo >= '0' && lo <= '9')
				c += lo - '0';
			else if (lo >= 'A' && lo <= 'F')
				c += lo - 'A' + 10;
			else if (lo >= 'a' && lo <= 'f')
				c += lo - 'a' + 10;
			else throw URISyntaxException("URI encoding: not a hex digit");
		}
		decodedStr += c;
	}
}

bool URI::isWellKnownPort() const
{
	return _port == getWellKnownPort();
}

unsigned short URI::getWellKnownPort() const
{
	if (_scheme == "ftp")
		return 21;
	else if (_scheme == "ssh")
		return 22;
	else if (_scheme == "telnet")
		return 23;
	else if (_scheme == "smtp")
		return 25;
	else if (_scheme == "dns")
		return 53;
	else if (_scheme == "http" || _scheme == "ws")
		return 80;
	else if (_scheme == "nntp")
		return 119;
	else if (_scheme == "imap")
		return 143;
	else if (_scheme == "ldap")
		return 389;
	else if (_scheme == "https" || _scheme == "wss")
		return 443;
	else if (_scheme == "smtps")
		return 465;
	else if (_scheme == "rtsp")
		return 554;
	else if (_scheme == "ldaps")
		return 636;
	else if (_scheme == "dnss")
		return 853;
	else if (_scheme == "imaps")
		return 993;
	else if (_scheme == "sip")
		return 5060;
	else if (_scheme == "sips")
		return 5061;
	else if (_scheme == "xmpp")
		return 5222;
	else
		return 0;
}

void URI::parse(const std::string& uri)
{
	std::string::const_iterator it  = uri.begin();
	std::string::const_iterator end = uri.end();
	if (it == end) return;
	if (*it != '/' && *it != '.' && *it != '?' && *it != '#')
	{
		std::string scheme;
		while (it != end && *it != ':' && *it != '?' && *it != '#' && *it != '/') scheme += *it++;
		if (it != end && *it == ':')
		{
			++it;
			if (it == end) throw URISyntaxException("URI scheme must be followed by authority or path", uri);
			setScheme(scheme);
			if (*it == '/')
			{
				++it;
				if (it != end && *it == '/')
				{
					++it;
					parseAuthority(it, end);
				}
				else --it;
			}
			parsePathEtc(it, end);
		}
		else
		{
			it = uri.begin();
			parsePathEtc(it, end);
		}
	}
	else parsePathEtc(it, end);
}

void URI::parseAuthority(std::string::const_iterator& it, const std::string::const_iterator& end)
{
	std::string userInfo;
	std::string part;
	while (it != end && *it != '/' && *it != '?' && *it != '#')
	{
		if (*it == '@')
		{
			userInfo = part;
			part.clear();
		}
		else part += *it;
		++it;
	}
	std::string::const_iterator pbeg = part.begin();
	std::string::const_iterator pend = part.end();
	parseHostAndPort(pbeg, pend);
	_userInfo = userInfo;
}

void URI::parseHostAndPort(std::string::const_iterator& it, const std::string::const_iterator& end)
{
	if (it == end) return;
	std::string host;
	if (*it == '[')
	{
		// IPv6 address
		++it;
		while (it != end && *it != ']') host += *it++;
		if (it == end) throw URISyntaxException("unterminated IPv6 address");
		++it;
	}
	else
	{
		while (it != end && *it != ':') host += *it++;
	}
	if (it != end && *it == ':')
	{
		++it;
		std::string port;
		while (it != end) port += *it++;
		if (!port.empty())
		{
			int nport = 0;
			if (NumberParser::tryParse(port, nport) && nport > 0 && nport < 65536)
				_port = (unsigned short) nport;
			else
				throw URISyntaxException("bad or invalid port number", port);
		}
		else _port = 0;
	}
	else _port = 0;
	_host = host;
	toLowerInPlace(_host);
}

void URI::parsePath(std::string::const_iterator& it, const std::string::const_iterator& end)
{
	std::string path;
	while (it != end && *it != '?' && *it != '#') path += *it++;
	decode(path, _path);
}

void URI::parsePathEtc(std::string::const_iterator& it, const std::string::const_iterator& end)
{
	if (it == end) return;
	if (*it != '?' && *it != '#')
		parsePath(it, end);
	if (it != end && *it == '?')
	{
		++it;
		parseQuery(it, end);
	}
	if (it != end && *it == '#')
	{
		++it;
		parseFragment(it, end);
	}
}

void URI::parseQuery(std::string::const_iterator& it, const std::string::const_iterator& end)
{
	_query.clear();
	while (it != end && *it != '#') _query += *it++;
}

void URI::parseFragment(std::string::const_iterator& it, const std::string::const_iterator& end)
{
	std::string fragment;
	while (it != end) fragment += *it++;
	decode(fragment, _fragment);
}

void URI::mergePath(const std::string& path)
{
	std::vector<std::string> segments;
	std::vector<std::string> normalizedSegments;
	bool addLeadingSlash = false;
	if (!_path.empty())
	{
		getPathSegments(segments);
		bool endsWithSlash = *(_path.rbegin()) == '/';
		if (!endsWithSlash && !segments.empty())
			segments.pop_back();
		addLeadingSlash = _path[0] == '/';
	}
	getPathSegments(path, segments);
	addLeadingSlash = addLeadingSlash || (!path.empty() && path[0] == '/');
	bool hasTrailingSlash = (!path.empty() && *(path.rbegin()) == '/');
	bool addTrailingSlash = false;
	for (const auto& s: segments)
	{
		if (s == "..")
		{
			addTrailingSlash = true;
			if (!normalizedSegments.empty())
				normalizedSegments.pop_back();
		}
		else if (s != ".")
		{
			addTrailingSlash = false;
			normalizedSegments.push_back(s);
		}
		else addTrailingSlash = true;
	}
	buildPath(normalizedSegments, addLeadingSlash, hasTrailingSlash || addTrailingSlash);
}

void URI::buildPath(const std::vector<std::string>& segments, bool leadingSlash, bool trailingSlash)
{
	_path.clear();
	bool first = true;
	for (const auto& s: segments)
	{
		if (first)
		{
			first = false;
			if (leadingSlash)
				_path += '/';
			else if (_scheme.empty() && s.find(':') != std::string::npos)
				_path.append("./");
		}
		else _path += '/';
		_path.append(s);
	}
	if (trailingSlash)
		_path += '/';
}

} // namespace Poco

{'repo_name': 'pocoproject/poco', 'stars': '4553', 'repo_language': 'C', 'file_name': 'PocoEncodingsConfig.cmake', 'mime_type': 'text/plain', 'hash': 8577045891776160370, 'source_dataset': 'data'}


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

#ifndef lint
static char sccsid[] = "@(#)getcom.c	8.1 (Berkeley) 5/31/93";
#endif /* not lint */

#include <stdio.h>
#include <ctype.h>

char *
getcom(buf, size, prompt, error)
	char *buf;
	int size;
	char *prompt, *error;
{
	for (;;) {
		fputs(prompt, stdout);
		if (fgets(buf, size, stdin) == 0) {
			clearerr(stdin);
			continue;
		}
		while (isspace(*buf))
			buf++;
		if (*buf)
			break;
		if (error)
			puts(error);
	}
	return (buf);
}

/*
 * shifts to UPPERCASE if flag > 0, lowercase if flag < 0,
 * and leaves it unchanged if flag = 0
 */
char *
getword(buf1, buf2, flag)
	register char *buf1, *buf2;
	register flag;
{
	while (isspace(*buf1))
		buf1++;
	if (*buf1 != ',') {
		if (!*buf1) {
			*buf2 = 0;
			return (0);
		}
		while (*buf1 && !isspace(*buf1) && *buf1 != ',')
			if (flag < 0)
				if (isupper(*buf1))
					*buf2++ = tolower(*buf1++);
				else
					*buf2++ = *buf1++;
			else if (flag > 0)
				if (islower(*buf1))
					*buf2++ = toupper(*buf1++);
				else
					*buf2++ = *buf1++;
			else
				*buf2++ = *buf1++;
	} else
		*buf2++ = *buf1++;
	*buf2 = 0;
	while (isspace(*buf1))
		buf1++;
	return (*buf1 ? buf1 : 0);
}

{'repo_name': 'sergev/LiteBSD', 'stars': '236', 'repo_language': 'C', 'file_name': 'README.txt', 'mime_type': 'text/plain', 'hash': -3576979796014017638, 'source_dataset': 'data'}