text:
template <class T>
void hyp0F1(T& result, const T& b, const T& x)
{
   typedef typename boost::multiprecision::detail::canonical<boost::int32_t, T>::type si_type;
   typedef typename boost::multiprecision::detail::canonical<boost::uint32_t, T>::type ui_type;

   // Compute the series representation of Hypergeometric0F1 taken from
   // http://functions.wolfram.com/HypergeometricFunctions/Hypergeometric0F1/06/01/01/
   // There are no checks on input range or parameter boundaries.

   T x_pow_n_div_n_fact(x);
   T pochham_b         (b);
   T bp                (b);

   eval_divide(result, x_pow_n_div_n_fact, pochham_b);
   eval_add(result, ui_type(1));

   si_type n;

   T tol;
   tol = ui_type(1);
   eval_ldexp(tol, tol, 1 - boost::multiprecision::detail::digits2<number<T, et_on> >::value());
   eval_multiply(tol, result);
   if(eval_get_sign(tol) < 0)
      tol.negate();
   T term;

   const int series_limit =
      boost::multiprecision::detail::digits2<number<T, et_on> >::value() < 100
      ? 100 : boost::multiprecision::detail::digits2<number<T, et_on> >::value();
   // Series expansion of hyperg_0f1(; b; x).
   for(n = 2; n < series_limit; ++n)
   {
      eval_multiply(x_pow_n_div_n_fact, x);
      eval_divide(x_pow_n_div_n_fact, n);
      eval_increment(bp);
      eval_multiply(pochham_b, bp);

      eval_divide(term, x_pow_n_div_n_fact, pochham_b);
      eval_add(result, term);

      bool neg_term = eval_get_sign(term) < 0;
      if(neg_term)
         term.negate();
      if(term.compare(tol) <= 0)
         break;
   }

   if(n >= series_limit)
      BOOST_THROW_EXCEPTION(std::runtime_error("H0F1 Failed to Converge"));
}

template <class T>
void eval_sin(T& result, const T& x)
{
   BOOST_STATIC_ASSERT_MSG(number_category<T>::value == number_kind_floating_point, "The sin function is only valid for floating point types.");
   if(&result == &x)
   {
      T temp;
      eval_sin(temp, x);
      result = temp;
      return;
   }

   typedef typename boost::multiprecision::detail::canonical<boost::int32_t, T>::type si_type;
   typedef typename boost::multiprecision::detail::canonical<boost::uint32_t, T>::type ui_type;
   typedef typename mpl::front<typename T::float_types>::type fp_type;

   switch(eval_fpclassify(x))
   {
   case FP_INFINITE:
   case FP_NAN:
      if(std::numeric_limits<number<T, et_on> >::has_quiet_NaN)
      {
         result = std::numeric_limits<number<T, et_on> >::quiet_NaN().backend();
         errno = EDOM;
      }
      else
         BOOST_THROW_EXCEPTION(std::domain_error("Result is undefined or complex and there is no NaN for this number type."));
      return;
   case FP_ZERO:
      result = x;
      return;
   default: ;
   }

   // Local copy of the argument
   T xx = x;

   // Analyze and prepare the phase of the argument.
   // Make a local, positive copy of the argument, xx.
   // The argument xx will be reduced to 0 <= xx <= pi/2.
   bool b_negate_sin = false;

   if(eval_get_sign(x) < 0)
   {
      xx.negate();
      b_negate_sin = !b_negate_sin;
   }

   T n_pi, t;
   // Remove even multiples of pi.
   if(xx.compare(get_constant_pi<T>()) > 0)
   {
      eval_divide(n_pi, xx, get_constant_pi<T>());
      eval_trunc(n_pi, n_pi);
      t = ui_type(2);
      eval_fmod(t, n_pi, t);
      const bool b_n_pi_is_even = eval_get_sign(t) == 0;
      eval_multiply(n_pi, get_constant_pi<T>());
      eval_subtract(xx, n_pi);

      BOOST_MATH_INSTRUMENT_CODE(xx.str(0, std::ios_base::scientific));
      BOOST_MATH_INSTRUMENT_CODE(n_pi.str(0, std::ios_base::scientific));

      // Adjust signs if the multiple of pi is not even.
      if(!b_n_pi_is_even)
      {
         b_negate_sin = !b_negate_sin;
      }
   }

   // Reduce the argument to 0 <= xx <= pi/2.
   eval_ldexp(t, get_constant_pi<T>(), -1);
   if(xx.compare(t) > 0)
   {
      eval_subtract(xx, get_constant_pi<T>(), xx);
      BOOST_MATH_INSTRUMENT_CODE(xx.str(0, std::ios_base::scientific));
   }

   eval_subtract(t, xx);
   const bool b_zero    = eval_get_sign(xx) == 0;
   const bool b_pi_half = eval_get_sign(t) == 0;

   // Check if the reduced argument is very close to 0 or pi/2.
   const bool    b_near_zero    = xx.compare(fp_type(1e-1)) < 0;
   const bool    b_near_pi_half = t.compare(fp_type(1e-1)) < 0;;

   if(b_zero)
   {
      result = ui_type(0);
   }
   else if(b_pi_half)
   {
      result = ui_type(1);
   }
   else if(b_near_zero)
   {
      eval_multiply(t, xx, xx);
      eval_divide(t, si_type(-4));
      T t2;
      t2 = fp_type(1.5);
      hyp0F1(result, t2, t);
      BOOST_MATH_INSTRUMENT_CODE(result.str(0, std::ios_base::scientific));
      eval_multiply(result, xx);
   }
   else if(b_near_pi_half)
   {
      eval_multiply(t, t);
      eval_divide(t, si_type(-4));
      T t2;
      t2 = fp_type(0.5);
      hyp0F1(result, t2, t);
      BOOST_MATH_INSTRUMENT_CODE(result.str(0, std::ios_base::scientific));
   }
   else
   {
      // Scale to a small argument for an efficient Taylor series,
      // implemented as a hypergeometric function. Use a standard
      // divide by three identity a certain number of times.
      // Here we use division by 3^9 --> (19683 = 3^9).

      static const si_type n_scale = 9;
      static const si_type n_three_pow_scale = static_cast<si_type>(19683L);

      eval_divide(xx, n_three_pow_scale);

      // Now with small arguments, we are ready for a series expansion.
      eval_multiply(t, xx, xx);
      eval_divide(t, si_type(-4));
      T t2;
      t2 = fp_type(1.5);
      hyp0F1(result, t2, t);
      BOOST_MATH_INSTRUMENT_CODE(result.str(0, std::ios_base::scientific));
      eval_multiply(result, xx);

      // Convert back using multiple angle identity.
      for(boost::int32_t k = static_cast<boost::int32_t>(0); k < n_scale; k++)
      {
         // Rescale the cosine value using the multiple angle identity.
         eval_multiply(t2, result, ui_type(3));
         eval_multiply(t, result, result);
         eval_multiply(t, result);
         eval_multiply(t, ui_type(4));
         eval_subtract(result, t2, t);
      }
   }

   if(b_negate_sin)
      result.negate();
}

template <class T>
void eval_cos(T& result, const T& x)
{
   BOOST_STATIC_ASSERT_MSG(number_category<T>::value == number_kind_floating_point, "The cos function is only valid for floating point types.");
   if(&result == &x)
   {
      T temp;
      eval_cos(temp, x);
      result = temp;
      return;
   }

   typedef typename boost::multiprecision::detail::canonical<boost::int32_t, T>::type si_type;
   typedef typename boost::multiprecision::detail::canonical<boost::uint32_t, T>::type ui_type;
   typedef typename mpl::front<typename T::float_types>::type fp_type;

   switch(eval_fpclassify(x))
   {
   case FP_INFINITE:
   case FP_NAN:
      if(std::numeric_limits<number<T, et_on> >::has_quiet_NaN)
      {
         result = std::numeric_limits<number<T, et_on> >::quiet_NaN().backend();
         errno = EDOM;
      }
      else
         BOOST_THROW_EXCEPTION(std::domain_error("Result is undefined or complex and there is no NaN for this number type."));
      return;
   case FP_ZERO:
      result = ui_type(1);
      return;
   default: ;
   }

   // Local copy of the argument
   T xx = x;

   // Analyze and prepare the phase of the argument.
   // Make a local, positive copy of the argument, xx.
   // The argument xx will be reduced to 0 <= xx <= pi/2.
   bool b_negate_cos = false;

   if(eval_get_sign(x) < 0)
   {
      xx.negate();
   }

   T n_pi, t;
   // Remove even multiples of pi.
   if(xx.compare(get_constant_pi<T>()) > 0)
   {
      eval_divide(t, xx, get_constant_pi<T>());
      eval_trunc(n_pi, t);
      BOOST_MATH_INSTRUMENT_CODE(n_pi.str(0, std::ios_base::scientific));
      eval_multiply(t, n_pi, get_constant_pi<T>());
      BOOST_MATH_INSTRUMENT_CODE(t.str(0, std::ios_base::scientific));
      eval_subtract(xx, t);
      BOOST_MATH_INSTRUMENT_CODE(xx.str(0, std::ios_base::scientific));

      // Adjust signs if the multiple of pi is not even.
      t = ui_type(2);
      eval_fmod(t, n_pi, t);
      const bool b_n_pi_is_even = eval_get_sign(t) == 0;

      if(!b_n_pi_is_even)
      {
         b_negate_cos = !b_negate_cos;
      }
   }

   // Reduce the argument to 0 <= xx <= pi/2.
   eval_ldexp(t, get_constant_pi<T>(), -1);
   int com = xx.compare(t);
   if(com > 0)
   {
      eval_subtract(xx, get_constant_pi<T>(), xx);
      b_negate_cos = !b_negate_cos;
      BOOST_MATH_INSTRUMENT_CODE(xx.str(0, std::ios_base::scientific));
   }

   const bool b_zero    = eval_get_sign(xx) == 0;
   const bool b_pi_half = com == 0;

   // Check if the reduced argument is very close to 0.
   const bool    b_near_zero    = xx.compare(fp_type(1e-1)) < 0;

   if(b_zero)
   {
      result = si_type(1);
   }
   else if(b_pi_half)
   {
      result = si_type(0);
   }
   else if(b_near_zero)
   {
      eval_multiply(t, xx, xx);
      eval_divide(t, si_type(-4));
      n_pi = fp_type(0.5f);
      hyp0F1(result, n_pi, t);
      BOOST_MATH_INSTRUMENT_CODE(result.str(0, std::ios_base::scientific));
   }
   else
   {
      eval_subtract(t, xx);
      eval_sin(result, t);
   }
   if(b_negate_cos)
      result.negate();
}

template <class T>
void eval_tan(T& result, const T& x)
{
   BOOST_STATIC_ASSERT_MSG(number_category<T>::value == number_kind_floating_point, "The tan function is only valid for floating point types.");
   if(&result == &x)
   {
      T temp;
      eval_tan(temp, x);
      result = temp;
      return;
   }
   T t;
   eval_sin(result, x);
   eval_cos(t, x);
   eval_divide(result, t);
}

template <class T>
void hyp2F1(T& result, const T& a, const T& b, const T& c, const T& x)
{
  // Compute the series representation of hyperg_2f1 taken from
  // Abramowitz and Stegun 15.1.1.
  // There are no checks on input range or parameter boundaries.

   typedef typename boost::multiprecision::detail::canonical<boost::uint32_t, T>::type ui_type;

   T x_pow_n_div_n_fact(x);
   T pochham_a         (a);
   T pochham_b         (b);
   T pochham_c         (c);
   T ap                (a);
   T bp                (b);
   T cp                (c);

   eval_multiply(result, pochham_a, pochham_b);
   eval_divide(result, pochham_c);
   eval_multiply(result, x_pow_n_div_n_fact);
   eval_add(result, ui_type(1));

   T lim;
   eval_ldexp(lim, result, 1 - boost::multiprecision::detail::digits2<number<T, et_on> >::value());

   if(eval_get_sign(lim) < 0)
      lim.negate();

   ui_type n;
   T term;

   const unsigned series_limit =
      boost::multiprecision::detail::digits2<number<T, et_on> >::value() < 100
      ? 100 : boost::multiprecision::detail::digits2<number<T, et_on> >::value();
   // Series expansion of hyperg_2f1(a, b; c; x).
   for(n = 2; n < series_limit; ++n)
   {
      eval_multiply(x_pow_n_div_n_fact, x);
      eval_divide(x_pow_n_div_n_fact, n);

      eval_increment(ap);
      eval_multiply(pochham_a, ap);
      eval_increment(bp);
      eval_multiply(pochham_b, bp);
      eval_increment(cp);
      eval_multiply(pochham_c, cp);

      eval_multiply(term, pochham_a, pochham_b);
      eval_divide(term, pochham_c);
      eval_multiply(term, x_pow_n_div_n_fact);
      eval_add(result, term);

      if(eval_get_sign(term) < 0)
         term.negate();
      if(lim.compare(term) >= 0)
         break;
   }
   if(n > series_limit)
      BOOST_THROW_EXCEPTION(std::runtime_error("H2F1 failed to converge."));
}

template <class T>
void eval_asin(T& result, const T& x)
{
   BOOST_STATIC_ASSERT_MSG(number_category<T>::value == number_kind_floating_point, "The asin function is only valid for floating point types.");
   typedef typename boost::multiprecision::detail::canonical<boost::uint32_t, T>::type ui_type;
   typedef typename mpl::front<typename T::float_types>::type fp_type;

   if(&result == &x)
   {
      T t(x);
      eval_asin(result, t);
      return;
   }

   switch(eval_fpclassify(x))
   {
   case FP_NAN:
   case FP_INFINITE:
      if(std::numeric_limits<number<T, et_on> >::has_quiet_NaN)
      {
         result = std::numeric_limits<number<T, et_on> >::quiet_NaN().backend();
         errno = EDOM;
      }
      else
         BOOST_THROW_EXCEPTION(std::domain_error("Result is undefined or complex and there is no NaN for this number type."));
      return;
   case FP_ZERO:
      result = x;
      return;
   default: ;
   }

   const bool b_neg = eval_get_sign(x) < 0;

   T xx(x);
   if(b_neg)
      xx.negate();

   int c = xx.compare(ui_type(1));
   if(c > 0)
   {
      if(std::numeric_limits<number<T, et_on> >::has_quiet_NaN)
      {
         result = std::numeric_limits<number<T, et_on> >::quiet_NaN().backend();
         errno = EDOM;
      }
      else
         BOOST_THROW_EXCEPTION(std::domain_error("Result is undefined or complex and there is no NaN for this number type."));
      return;
   }
   else if(c == 0)
   {
      result = get_constant_pi<T>();
      eval_ldexp(result, result, -1);
      if(b_neg)
         result.negate();
      return;
   }

   if(xx.compare(fp_type(1e-4)) < 0)
   {
      // http://functions.wolfram.com/ElementaryFunctions/ArcSin/26/01/01/
      eval_multiply(xx, xx);
      T t1, t2;
      t1 = fp_type(0.5f);
      t2 = fp_type(1.5f);
      hyp2F1(result, t1, t1, t2, xx);
      eval_multiply(result, x);
      return;
   }
   else if(xx.compare(fp_type(1 - 1e-4f)) > 0)
   {
      T dx1;
      T t1, t2;
      eval_subtract(dx1, ui_type(1), xx);
      t1 = fp_type(0.5f);
      t2 = fp_type(1.5f);
      eval_ldexp(dx1, dx1, -1);
      hyp2F1(result, t1, t1, t2, dx1);
      eval_ldexp(dx1, dx1, 2);
      eval_sqrt(t1, dx1);
      eval_multiply(result, t1);
      eval_ldexp(t1, get_constant_pi<T>(), -1);
      result.negate();
      eval_add(result, t1);
      if(b_neg)
         result.negate();
      return;
   }
#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS
   typedef typename boost::multiprecision::detail::canonical<long double, T>::type guess_type;
#else
   typedef fp_type guess_type;
#endif
   // Get initial estimate using standard math function asin.
   guess_type dd;
   eval_convert_to(&dd, xx);

   result = (guess_type)(std::asin(dd));

   // Newton-Raphson iteration, we should double our precision with each iteration,
   // in practice this seems to not quite work in all cases... so terminate when we
   // have at least 2/3 of the digits correct on the assumption that the correction
   // we've just added will finish the job...

   boost::intmax_t current_precision = eval_ilogb(result);
   boost::intmax_t target_precision = current_precision - 1 - (std::numeric_limits<number<T> >::digits * 2) / 3;

   // Newton-Raphson iteration
   while(current_precision > target_precision)
   {
      T sine, cosine;
      eval_sin(sine, result);
      eval_cos(cosine, result);
      eval_subtract(sine, xx);
      eval_divide(sine, cosine);
      eval_subtract(result, sine);
      current_precision = eval_ilogb(sine);
      if(current_precision <= (std::numeric_limits<typename T::exponent_type>::min)() + 1)
         break;
   }
   if(b_neg)
      result.negate();
}

template <class T>
inline void eval_acos(T& result, const T& x)
{
   BOOST_STATIC_ASSERT_MSG(number_category<T>::value == number_kind_floating_point, "The acos function is only valid for floating point types.");
   typedef typename boost::multiprecision::detail::canonical<boost::uint32_t, T>::type ui_type;

   switch(eval_fpclassify(x))
   {
   case FP_NAN:
   case FP_INFINITE:
      if(std::numeric_limits<number<T, et_on> >::has_quiet_NaN)
      {
         result = std::numeric_limits<number<T, et_on> >::quiet_NaN().backend();
         errno = EDOM;
      }
      else
         BOOST_THROW_EXCEPTION(std::domain_error("Result is undefined or complex and there is no NaN for this number type."));
      return;
   case FP_ZERO:
      result = get_constant_pi<T>();
      eval_ldexp(result, result, -1); // divide by two.
      return;
   }

   eval_abs(result, x);
   int c = result.compare(ui_type(1));

   if(c > 0)
   {
      if(std::numeric_limits<number<T, et_on> >::has_quiet_NaN)
      {
         result = std::numeric_limits<number<T, et_on> >::quiet_NaN().backend();
         errno = EDOM;
      }
      else
         BOOST_THROW_EXCEPTION(std::domain_error("Result is undefined or complex and there is no NaN for this number type."));
      return;
   }
   else if(c == 0)
   {
      if(eval_get_sign(x) < 0)
         result = get_constant_pi<T>();
      else
         result = ui_type(0);
      return;
   }

   eval_asin(result, x);
   T t;
   eval_ldexp(t, get_constant_pi<T>(), -1);
   eval_subtract(result, t);
   result.negate();
}

template <class T>
void eval_atan(T& result, const T& x)
{
   BOOST_STATIC_ASSERT_MSG(number_category<T>::value == number_kind_floating_point, "The atan function is only valid for floating point types.");
   typedef typename boost::multiprecision::detail::canonical<boost::int32_t, T>::type si_type;
   typedef typename boost::multiprecision::detail::canonical<boost::uint32_t, T>::type ui_type;
   typedef typename mpl::front<typename T::float_types>::type fp_type;

   switch(eval_fpclassify(x))
   {
   case FP_NAN:
      result = x;
      errno = EDOM;
      return;
   case FP_ZERO:
      result = x;
      return;
   case FP_INFINITE:
      if(eval_get_sign(x) < 0)
      {
         eval_ldexp(result, get_constant_pi<T>(), -1);
         result.negate();
      }
      else
         eval_ldexp(result, get_constant_pi<T>(), -1);
      return;
   default: ;
   }

   const bool b_neg = eval_get_sign(x) < 0;

   T xx(x);
   if(b_neg)
      xx.negate();

   if(xx.compare(fp_type(0.1)) < 0)
   {
      T t1, t2, t3;
      t1 = ui_type(1);
      t2 = fp_type(0.5f);
      t3 = fp_type(1.5f);
      eval_multiply(xx, xx);
      xx.negate();
      hyp2F1(result, t1, t2, t3, xx);
      eval_multiply(result, x);
      return;
   }

   if(xx.compare(fp_type(10)) > 0)
   {
      T t1, t2, t3;
      t1 = fp_type(0.5f);
      t2 = ui_type(1u);
      t3 = fp_type(1.5f);
      eval_multiply(xx, xx);
      eval_divide(xx, si_type(-1), xx);
      hyp2F1(result, t1, t2, t3, xx);
      eval_divide(result, x);
      if(!b_neg)
         result.negate();
      eval_ldexp(t1, get_constant_pi<T>(), -1);
      eval_add(result, t1);
      if(b_neg)
         result.negate();
      return;
   }

   // Get initial estimate using standard math function atan.
   fp_type d;
   eval_convert_to(&d, xx);
   result = fp_type(std::atan(d));

   // Newton-Raphson iteration, we should double our precision with each iteration,
   // in practice this seems to not quite work in all cases... so terminate when we
   // have at least 2/3 of the digits correct on the assumption that the correction
   // we've just added will finish the job...

   boost::intmax_t current_precision = eval_ilogb(result);
   boost::intmax_t target_precision = current_precision - 1 - (std::numeric_limits<number<T> >::digits * 2) / 3;

   T s, c, t;
   while(current_precision > target_precision)
   {
      eval_sin(s, result);
      eval_cos(c, result);
      eval_multiply(t, xx, c);
      eval_subtract(t, s);
      eval_multiply(s, t, c);
      eval_add(result, s);
      current_precision = eval_ilogb(s);
      if(current_precision <= (std::numeric_limits<typename T::exponent_type>::min)() + 1)
         break;
   }
   if(b_neg)
      result.negate();
}

template <class T>
void eval_atan2(T& result, const T& y, const T& x)
{
   BOOST_STATIC_ASSERT_MSG(number_category<T>::value == number_kind_floating_point, "The atan2 function is only valid for floating point types.");
   if(&result == &y)
   {
      T temp(y);
      eval_atan2(result, temp, x);
      return;
   }
   else if(&result == &x)
   {
      T temp(x);
      eval_atan2(result, y, temp);
      return;
   }

   typedef typename boost::multiprecision::detail::canonical<boost::uint32_t, T>::type ui_type;

   switch(eval_fpclassify(y))
   {
   case FP_NAN:
      result = y;
      errno = EDOM;
      return;
   case FP_ZERO:
      {
         if(eval_signbit(x))
         {
            result = get_constant_pi<T>();
            if(eval_signbit(y))
               result.negate();
         }
         else
         {
            result = y; // Note we allow atan2(0,0) to be +-zero, even though it's mathematically undefined
         }
         return;
      }
   case FP_INFINITE:
      {
         if(eval_fpclassify(x) == FP_INFINITE)
         {
            if(eval_signbit(x))
            {
               // 3Pi/4
               eval_ldexp(result, get_constant_pi<T>(), -2);
               eval_subtract(result, get_constant_pi<T>());
               if(eval_get_sign(y) >= 0)
                  result.negate();
            }
            else
            {
               // Pi/4
               eval_ldexp(result, get_constant_pi<T>(), -2);
               if(eval_get_sign(y) < 0)
                  result.negate();
            }
         }
         else
         {
            eval_ldexp(result, get_constant_pi<T>(), -1);
            if(eval_get_sign(y) < 0)
               result.negate();
         }
         return;
      }
   }

   switch(eval_fpclassify(x))
   {
   case FP_NAN:
      result = x;
      errno = EDOM;
      return;
   case FP_ZERO:
      {
         eval_ldexp(result, get_constant_pi<T>(), -1);
         if(eval_get_sign(y) < 0)
            result.negate();
         return;
      }
   case FP_INFINITE:
      if(eval_get_sign(x) > 0)
         result = ui_type(0);
      else
         result = get_constant_pi<T>();
      if(eval_get_sign(y) < 0)
         result.negate();
      return;
   }

   T xx;
   eval_divide(xx, y, x);
   if(eval_get_sign(xx) < 0)
      xx.negate();

   eval_atan(result, xx);

   // Determine quadrant (sign) based on signs of x, y
   const bool y_neg = eval_get_sign(y) < 0;
   const bool x_neg = eval_get_sign(x) < 0;

   if(y_neg != x_neg)
      result.negate();

   if(x_neg)
   {
      if(y_neg)
         eval_subtract(result, get_constant_pi<T>());
      else
         eval_add(result, get_constant_pi<T>());
   }
}
template<class T, class A>
inline typename enable_if<is_arithmetic<A>, void>::type eval_atan2(T& result, const T& x, const A& a)
{
   typedef typename boost::multiprecision::detail::canonical<A, T>::type canonical_type;
   typedef typename mpl::if_<is_same<A, canonical_type>, T, canonical_type>::type cast_type;
   cast_type c;
   c = a;
   eval_atan2(result, x, c);
}

template<class T, class A>
inline typename enable_if<is_arithmetic<A>, void>::type eval_atan2(T& result, const A& x, const T& a)
{
   typedef typename boost::multiprecision::detail::canonical<A, T>::type canonical_type;
   typedef typename mpl::if_<is_same<A, canonical_type>, T, canonical_type>::type cast_type;
   cast_type c;
   c = x;
   eval_atan2(result, c, a);
}

#ifdef BOOST_MSVC
#pragma warning(pop)
#endif


text:
.class Landroid/support/v4/app/RemoteInput$ImplJellybean;
.super Ljava/lang/Object;
.source "RemoteInput.java"

# interfaces
.implements Landroid/support/v4/app/RemoteInput$Impl;

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Landroid/support/v4/app/RemoteInput;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x8
    name = "ImplJellybean"
.end annotation

# direct methods
.method constructor <init>()V
    .registers 1

    .prologue
    .line 228
    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    return-void
.end method

# virtual methods
.method public addResultsToIntent([Landroid/support/v4/app/RemoteInput;Landroid/content/Intent;Landroid/os/Bundle;)V
    .registers 4
    .param p1, "remoteInputs"    # [Landroid/support/v4/app/RemoteInput;
    .param p2, "intent"    # Landroid/content/Intent;
    .param p3, "results"    # Landroid/os/Bundle;

    .prologue
    .line 236
    invoke-static {p1, p2, p3}, Landroid/support/v4/app/RemoteInputCompatJellybean;->addResultsToIntent([Landroid/support/v4/app/RemoteInputCompatBase$RemoteInput;Landroid/content/Intent;Landroid/os/Bundle;)V

    .line 237
    return-void
.end method

.method public getResultsFromIntent(Landroid/content/Intent;)Landroid/os/Bundle;
    .registers 3
    .param p1, "intent"    # Landroid/content/Intent;

    .prologue
    .line 231
    invoke-static {p1}, Landroid/support/v4/app/RemoteInputCompatJellybean;->getResultsFromIntent(Landroid/content/Intent;)Landroid/os/Bundle;

    move-result-object v0

    return-object v0
.end method

redpajama_set_name: RedPajamaGithub


text:
describe('angular-bootstrap-form-validation', function() {
	beforeEach(module('ui.bootstrap.validation'));

	function setup (html, initialScope) {
		var container;
		inject(function($compile, $rootScope) {
			if (angular.isDefined(initialScope)) {
				angular.extend($rootScope, initialScope);
			}

			container = $compile(html)($rootScope);
			$rootScope.$apply();
		});
		return container;
	}

	describe('uiValidationErrorMessages', function() {
		it('should thrown an error if used outside a form', function() {
			expect(function() {
				setup('');
			}).toThrow();
		});

		it('should thrown an error if an input/select/textarea was not found', function() {
			expect(function() {
				setup('<form></form>');
			}).toThrow();
		});

		it('should not thrown an error if properly configured', function() {
			expect(function() {
				setup('<form><input name="model"></form>');
			}).not.toThrow();
		});

		it('should have an error message container', function() {
			var form = setup('<form><input name="model"></form>');

			var validationsContainer = form.find('div');
			expect(validationsContainer.hasClass('ui-validation')).toBe(true);
			expect(validationsContainer.hasClass('help-block')).toBe(true);
		});

		it('should show validation error for a required input', function() {
			var form = setup('<form><input name="model" ng-model="model" required></form>');

			var validations = form.find('small');
			expect(validations.length).toBe(1);
			expect(validations.text()).toBe('This field cannot be blank ');
		});

		it('should work inside input-group', function() {
			var form = setup('<form>
<input name="model" ng-model="model" required><button type="button" class="btn btn-default">+</button>

</form>');

			var validations = form.find('small');
			expect(validations.length).toBe(1);
			expect(validations.text()).toBe('This field cannot be blank ');
		});

		it('should show validation errors for input fields generated by ng-repeat', function() {
			var form = setup('<form>
<input name="model_{{e}}" ng-model="model" required>
</form>');

			var validations = form.find('small');
			expect(validations.length).toBe(3);
			for (var i = 0; i < 3; i++) {
				expect(angular.element(validations[i]).text()).toBe('This field cannot be blank ');
			}
		});

		it('should expose (in the scope) the values used in the validation (to appear in the validation message', function() {
			var form = setup('<form><input name="model" ng-model="model" ng-minlength="8"></form>');

			var validations = form.find('small');
			expect(validations.length).toBe(1);
			expect(validations.text()).toBe('Minimum length:  8');
		});

		it('should ignore ng-require value ("require" validation covers it)', function() {
			var form = setup('<form><input name="model" ng-model="model" ng-required="true"></form>');

			var validations = form.find('small');
			expect(validations.length).toBe(1);
			expect(validations.text()).toBe('This field cannot be blank ');
		});

		it('should parse validation values if necessary', function() {
			var form = setup('<form><input name="model" ng-model="model" ng-minlength="min"></form>',{
				min: 12
			});

			var validations = form.find('small');
			expect(validations.length).toBe(1);
			expect(validations.text()).toBe('Minimum length:  12');
		});
	});

	describe('uiValidationSubmit', function() {
		it('should prevent form submit in the presence of validation errors', function() {
			var form = setup('<form ui-validation-submit="action()"><input name="model" ng-model="model" ng-minlength="3"><button type="submit">Submit</button></form>', {
				model: 'ab',
				action: function() {
					this.model = 'success';
				}
			});

			var model = form.find('input').controller('ngModel');
			expect(model.$modelValue).toBe('ab');

			var formCtrl = form.controller('uiValidationSubmit');
			expect(formCtrl.attempted).toBe(false);

			form.triggerHandler('submit');
			expect(formCtrl.attempted).toBe(true);
			expect(model.$modelValue).toBe('ab');
		});

		it('should allow form submit when no validation errors have been found', function() {
			var form = setup('<form ui-validation-submit="action()"><input name="model" ng-model="model" ng-minlength="3"><button type="submit">Submit</button></form>', {
				model: 'abc',
				action: function() {
					this.model = 'success';
				}
			});

			var model = form.find('input').controller('ngModel');
			expect(model.$modelValue).toBe('abc');

			var formCtrl = form.controller('uiValidationSubmit');
			expect(formCtrl.attempted).toBe(false);

			form.triggerHandler('submit');
			expect(formCtrl.attempted).toBe(true);
			expect(model.$modelValue).toBe('success');
		});
	});

	describe('uiValidationShowErrors', function() {
		it('should thrown an error if used outside a form', function() {
			expect(function() {
				setup('

');
			}).toThrow();
		});

		it('should throw an error if the element does not have .form-group class', function() {
			expect(function() {
				setup('<form>

</form>');
			}).toThrow();
		});

		it('should throw an error when it does not have an input/selec/textarea child', function() {
			expect(function() {
				setup('<form>

</form>');
			}).toThrow();
		});

		it('should not thrown an error if properly configured', function() {
			expect(function() {
				setup('<form>
<input name="model" ng-model="model" ng-maxlength="4">
</form>');
			}).not.toThrow();
		});

		it('should only have .has-error class after the form has been submitted when using uiValidationSubmit', function() {
			var form = setup('<form ui-validation-submit="action()">
<input name="model" ng-model="model" ng-maxlength="4">
</form>', {
				model: 'abcde',
				action: function() {
					this.model = 'success';
				}
			});

			var formCtrl = form.controller('uiValidationSubmit');
			expect(formCtrl.attempted).toBe(false);

			var formGroup = form.children();
			expect(formGroup.hasClass('form-group')).toBe(true);
			expect(formGroup.hasClass('has-error')).toBe(false);

			var model = form.find('input').controller('ngModel');
			expect(model.$modelValue).toBe('abcde');

			form.triggerHandler('submit');
			expect(formCtrl.attempted).toBe(true);
			expect(formGroup.hasClass('has-error')).toBe(true);
			expect(model.$modelValue).toBe('abcde');

			var validations = form.find('small');
			expect(validations.length).toBe(1);
			expect(validations.text()).toBe('Maximum length:  4');
		});
	});

	describe('uiCustomErrorMessage', function() {
		it('should throw an error if used (not implemented yet', function() {
			expect(function() {
				setup('<ui-custom-error-message></ui-custom-error-message>');
			}).toThrow();
		});
	});
});


text:
"""Pure-Python Jewish calendar implementation.

Copyright 2014, Eitan Mosenkis, all rights reserved.
Released under the MIT license which can be found at
http://opensource.org/licenses/MIT.

Based on jewish.c from the PHP standard library, which includes the following
statement:

Copyright 1993-1995, Scott E. Lee, all rights reserved.
Permission granted to use, copy, modify, distribute and sell so long as
the above copyright and this permission statement are retained in all
copies. THERE IS NO WARRANTY - USE AT YOUR OWN RISK.
"""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals

import datetime

HALAKIM_PER_HOUR = 1080
HALAKIM_PER_DAY = 25920
HALAKIM_PER_LUNAR_CYCLE = 29 * HALAKIM_PER_DAY + 13753
HALAKIM_PER_METONIC_CYCLE = HALAKIM_PER_LUNAR_CYCLE * (12 * 19 + 7)

_GREGORIAN_SDN_OFFSET  = 1721425
_JEWISH_SDN_OFFSET = 347997
_NEW_MOON_OF_CREATION = 31524

_SUNDAY = 0
_MONDAY = 1
_TUESDAY = 2
_WEDNESDAY = 3
_FRIDAY = 5

_NOON = 18 * HALAKIM_PER_HOUR
_AM3_11_20 = 9 * HALAKIM_PER_HOUR + 204
_AM9_32_43 = 15 * HALAKIM_PER_HOUR + 589

LEAP_YEARS = set((2, 5, 7, 10, 13, 16, 18))
_YEAR_OFFSET = (0, 12, 24, 37, 49, 61, 74, 86, 99, 111, 123, 136, 148, 160,
                173, 185, 197, 210, 222)

class JewishDateError(Exception):
    """Parent for all exceptions defined in jewish.date."""

class InvalidDateError(JewishDateError):
    """Error arising from attempting to calculate based on an invalid date."""

def months_in_metonic_year(year):
    return 13 if year in LEAP_YEARS else 12

def metonic_year(year):
    return (year - 1) % 19

def is_leap_year(year):
    return metonic_year(year) in LEAP_YEARS

class _Molad(object):

    def __init__(self, day=0, halakim=0):
        self.day = day
        self.halakim = halakim
        self._fix()

    def _fix(self):
        """Adjusts day and halakim so halakim < HALAKIM_PER_DAY."""
        self.day += self.halakim // HALAKIM_PER_DAY
        self.halakim %= HALAKIM_PER_DAY

    def _add_halakim(self, halakim):
        self.halakim += halakim
        self._fix()
        return self

    def add_lunar_cycles(self, lunarCycles):
        self._add_halakim(HALAKIM_PER_LUNAR_CYCLE * lunarCycles)
        return self

    def add_metonic_cycles(self, metonicCycles):
        self._add_halakim(HALAKIM_PER_METONIC_CYCLE * metonicCycles)
        return self

    def day_of_week(self):
        return self.day % 7

    def __repr__(self):
        return '_Molad(day=%s, halakim=%s)' % (self.day, self.halakim)

class JewishDate(object):
    """A date in the Jewish calendar."""

    TISHREI = 1
    CHESHVAN = 2
    KISLEV = 3
    TEVET = 4
    SHEVAT = 5
    ADAR_I = 6
    ADAR_II = 7
    NISAN = 8
    IYAR = 9
    SIVAN = 10
    TAMUZ = 11
    AV = 12
    ELUL = 13

    def __init__(self, year, month, day):
        """Create a JewishDate.

        Args:
            year: the year (must be >= 1)
            month: the month (must be in the range 1-13 inclusive, with 6
                   always representing Adar I and 7 representing Adar in
                   non-leap years and Adar II in leap years)
            day: the day (must be in the range 1-30 inclusive)

        Raises:
            InvalidDateError if year, month, or day is outside of the bounds
            described above. Note that it is still possible to create
            JewishDate objects that represent invalid dates, such as the 30th
            of a month with 29 days or a leap month in a non-leap year.
        """
        self.year = year
        self.month = month
        self.day = day
        self.isLeapYear = is_leap_year(year)
        if year <= 0 or month < 1 or month > 13 or day < 1 or day > 30:
            raise self._invalid_date_error()

    @classmethod
    def from_sdn(cls, sdn):
        """Create a JewishDate from a serial day number (SDN).

        Args:
            sdn: a serial day number

        Returns:
            A JewishDate

        Raises:
            InvalidDateError: if the input SDN is before the beginning of
                              Jewish year 1
        """
        if sdn <= _JEWISH_SDN_OFFSET:
            raise InvalidDateError(
                'Serial day number %s is before the first Jewish year' % sdn)
        inputDay = sdn - _JEWISH_SDN_OFFSET

        def get_result():
            return cls(year, month, day)

        metonicCycle, metonicYear, molad = _find_nearby_tishrei_molad(inputDay)
        tishrei1 = _get_first_day_of_year(metonicYear, molad)

        if inputDay >= tishrei1:
            # It found Tishrei 1 at the start of the year
            year = metonicCycle * 19 + metonicYear + 1
            if inputDay < tishrei1 + 59:
                if inputDay < tishrei1 + 30:
                    month = cls.TISHREI
                    day = inputDay - tishrei1 + 1
                else:
                    month = cls.CHESHVAN
                    day = inputDay - tishrei1 - 29
                return get_result()
            else:
                # Date is in Kislev
                molad.add_lunar_cycles(months_in_metonic_year(metonicYear))
                nextTishrei1 = _get_first_day_of_year((metonicYear + 1) % 19,
                                                      molad)
        else:
            # It found Tishrei 1 at the end of the year
            nextTishrei1 = tishrei1
            year = metonicCycle * 19 + metonicYear
            if inputDay >= nextTishrei1 - 177:
                # It is one of the last 6 months of the year
                for month, offset in (
                        (cls.ELUL, 30),
                        (cls.AV, 60),
                        (cls.TAMUZ, 89),
                        (cls.SIVAN, 119),
                        (cls.IYAR, 148),
                        (cls.NISAN, 178)):
                    if inputDay > nextTishrei1 - offset:
                        day = inputDay - nextTishrei1 + offset
                        break
                return get_result()
            else:
                day = inputDay - nextTishrei1 + 207
                if day > 0:
                    month = cls.ADAR_II
                    return get_result()
                if is_leap_year(year):
                    day += 30
                    if day > 0:
                        month = cls.ADAR_I
                        return get_result()
                day += 30
                if day > 0:
                    month = cls.SHEVAT
                    return get_result()
                day += 29
                if day > 0:
                    month = cls.TEVET
                    return get_result()

                # We need the length of the year to figure this out, so find
                # Tishrei 1 of this year.
                metonicCycle, metonicYear, molad = _find_nearby_tishrei_molad(
                    molad.day - 365)
                tishrei1 = _get_first_day_of_year(metonicYear, molad)

        yearLength = nextTishrei1 - tishrei1
        day = inputDay - tishrei1 - 29
        cheshvanLength = 30 if yearLength in (355, 385) else 29
        if day <= cheshvanLength:
            month = cls.CHESHVAN
            return get_result()
        else:
            day -= cheshvanLength
        # There's only one option left
        month = cls.KISLEV
        return get_result()

    @classmethod
    def from_date(cls, date):
        return cls.from_sdn(date.toordinal() + _GREGORIAN_SDN_OFFSET)

    def to_sdn(self):
        """Convert a JewishDate to serial day number (SDN).

        The return value will be > 0 for all valid dates, but there are some
        invalid dates that will return a positive value. To verify that a date
        is valid, convert it to SDN and then back and compare with the
        original.

        Returns:
            a serial day number (integer)

        Raises:
            InvalidDateError: if this JewishDate is invalid
        """
        year = self.year
        month = self.month
        day = self.day
        if year <= 0 or day <= 0 or day > 30:
            raise self._invalid_date_error()
        metonicCycle, metonicYear, molad, tishrei1 = _find_start_of_year(year)
        molad.add_lunar_cycles(months_in_metonic_year(metonicYear))
        nextTishrei1= _get_first_day_of_year((metonicYear + 1) % 19, molad)
        yearLength = nextTishrei1 - tishrei1
        adarsLength = 59 if self.isLeapYear else 29
        offset = {
            self.TISHREI: -1,
            self.CHESHVAN: 29,
            # Kislev is variable
            self.TEVET: adarsLength + 237,
            self.SHEVAT: adarsLength + 208,
            self.ADAR_I: adarsLength + 178,
            self.ADAR_II: 207,
            self.NISAN: 178,
            self.IYAR: 148,
            self.SIVAN: 119,
            self.TAMUZ: 89,
            self.AV: 60,
            self.ELUL: 30,
        }

        if month in (self.TISHREI, self.CHESHVAN):
            sdn = tishrei1 + day + offset[month]
        elif month == self.KISLEV:
            if yearLength in (355, 385):
                sdn = tishrei1 + day + 59
            else:
                sdn = tishrei1 + day + 58
        else:
            try:
                sdn = nextTishrei1 + day - offset[month]
            except KeyError:
                raise self._invalid_date_error()
        return sdn + _JEWISH_SDN_OFFSET

    def to_date(self):
        return datetime.date.fromordinal(self.to_sdn() - _GREGORIAN_SDN_OFFSET)

    def english_month_name(self):
        names = ('Tishrei', 'Cheshvan', 'Kislev', 'Tevet', 'Shevat', 'Adar I',
                 'Adar II', 'Nisan', 'Iyar', 'Sivan', 'Tamuz', 'Av', 'Elul')
        if self.month == self.ADAR_II and not self.isLeapYear:
            return 'Adar II'
        else:
            return names[self.month - 1]

    def _invalid_date_error(self):
        return InvalidDateError('%r represents an invalid date' % self)

    def __str__(self):
        return '%s %s %s' % (self.day, self.english_month_name(), self.year)

    def __repr__(self):
        return '%s(%s, %s, %s)' % (type(self).__name__,
                                   self.year, self.month, self.day)

def _get_first_day_of_year(metonicCycleYear, molad):
    """Calculate which day a year starts on.

    Args:
        cycleYear: year of 19-year cycle (0-18)
        molad: a _Molad object

    Returns:
        the serial day number of the first day of the year

    Given the year within the 19 year metonic cycle and the time of a molad
    (new moon) which starts that year, this routine will calculate what day
    will be the actual start of the year (Tishrei 1 or Rosh Ha-Shanah). This
    first day of the year will be the day of the molad unless one of 4 rules
    (called dehiyyot) delays it. These 4 rules can delay the start of the year
    by as much as 2 days.
    """
    tishrei1 = molad.day
    dow = molad.day_of_week()
    lastWasLeapYear = ((metonicCycleYear - 1) % 19) in LEAP_YEARS

    # Apply rules 2, 3, and 4
    if (molad.halakim >= _NOON
            or (metonicCycleYear not in LEAP_YEARS
                    and dow == _TUESDAY
                    and molad.halakim >= _AM3_11_20)
            or (lastWasLeapYear
                    and dow == _MONDAY
                    and molad.halakim >= _AM9_32_43)):
        tishrei1 += 1
        dow = (dow + 1) % 7

    # Apply rule 1 after the others because it can cause an additional delay of
    # one day.
    if dow in (_WEDNESDAY, _FRIDAY, _SUNDAY):
        tishrei1 += 1

    return tishrei1

def _molad_of_metonic_cycle(metonicCycle):
    """Calculate the date and time of the molad that starts a metonic cycle.

    Args:
        metonicCycle: the number of the metonic cycle

    Returns:
        a _Molad object representing the molad

    Since the length of a metonic cycle is a constant, this is a simple
    calculation, except that it requires an intermediate value which is bigger
    than 32 bits. Since Python automatically uses unlimited precision integers
    when necessary, this is does not pose a challenge, unlike in C.
    """
    return _Molad(halakim=_NEW_MOON_OF_CREATION).add_metonic_cycles(
        metonicCycle)

def _find_nearby_tishrei_molad(inputDay):
    """Find the closes molad of Tishrei to a given day number.

    Args:
        inputDay: a serial day number

    Returns:
        a tuple (metonicCycle, metonicYear, molad)

    It's not really the *closest* molad that we want here. If the input day is
    in the first two months, we want the molad at the start of the year. If the
    input day is in the fourth to last months, we want the molad at the end of
    the year. If the input day is in the third month, it doesn't matter which
    molad is returned, because both will be required. This type of "rounding"
    allows us to avoid calculating the length of the year in most cases.
    """
    # Estimate the metonic cycle number. Note that this may be an under
    # estimate because there are 6939.6896 days in a metonic cycle not 6940,
    # but it will never be an over estimate. The loop below will correct for
    # any error in this estimate.
    metonicCycle = (inputDay + 310) // 6940

    # Calculate the time of the starting molad for this metonic cycle.
    molad = _molad_of_metonic_cycle(metonicCycle)

    # If the above was an under estimate, increment the cycle number until the
    # correct one is found. For modern dates this loop is about 98.6% likely to
    # not execute, even once, because the above estimate is really quite close.
    while molad.day < inputDay - 6940 + 310:
        metonicCycle += 1
        molad.add_metonic_cycles(1)

    # Find the molad of Tishrei closest to this date.
    metonicYear = 0
    while metonicYear < 18:  # Not quite the same as a for loop over range(18)
        if molad.day > inputDay - 74:
            break
        molad.add_lunar_cycles(months_in_metonic_year(metonicYear))
        metonicYear += 1

    return metonicCycle, metonicYear, molad

def _find_start_of_year(year):
    """Find the serial day number of the the first day of a Jewish year.

    Args:
        year: the number of a Jewish calendar year

    Returns:
        the tuple (metonicCycle, metonicYear, molad, tishrei1)
    """
    metonicCycle, metonicYear = divmod(year - 1, 19)
    molad = _molad_of_metonic_cycle(metonicCycle)

    molad.add_lunar_cycles(_YEAR_OFFSET[metonicYear])
    tishrei1 = _get_first_day_of_year(metonicYear, molad)
    return (metonicCycle, metonicYear, molad, tishrei1)


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">

    <title>Concept</title>

    <link href="{{site.baseurl}}/vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">

    <link href="vendor/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">
    <link href='https://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800' rel='stylesheet' type='text/css'>
    <link href='https://fonts.googleapis.com/css?family=Merriweather:400,300,300italic,400italic,700,700italic,900,900italic' rel='stylesheet' type='text/css'>

    <link href="vendor/magnific-popup/magnific-popup.css" rel="stylesheet">
    <link rel="stylesheet" type="text/css" href="http://cdn.rawgit.com/Eonasdan/bootstrap-datetimepicker/v4.0.0/build/css/bootstrap-datetimepicker.css">

    <link href="css/creative.css" rel="stylesheet">

                <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
                     Menu
                </button>
                ocnevysetrenie.sk

                        O nás

                        Služby

                        Objednávky

                        Kontakt

Hlavný nadpis

Lorem ipsum dolor sit amet, qui ne fugit labore definitiones.

O nás

Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo.

Služby

Služba1

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum auctor sapien pharetra consequat mattis. Integer nec nisl sed elit sollicitudin.

Služba2

Neque porro quisquam est qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit...

Služba3

Nunc id euismod lorem. Donec eget elit mauris. In et.

Objednávky

Kontaktujte nás!

123-456-6789

 feedback@example.com


text:
#include "ecclesia/lib/redfish/dellicius/engine/internal/query_planner.h"

#include <cstddef>
#include <map>
#include <memory>
#include <optional>
#include <string>
#include <tuple>
#include <utility>
#include <vector>

#include "absl/container/flat_hash_map.h"
#include "absl/log/log.h"
#include "absl/status/status.h"
#include "absl/status/statusor.h"
#include "absl/strings/match.h"
#include "absl/strings/numbers.h"
#include "absl/strings/str_format.h"
#include "absl/strings/str_split.h"
#include "absl/strings/string_view.h"
#include "ecclesia/lib/redfish/dellicius/engine/internal/interface.h"
#include "ecclesia/lib/redfish/dellicius/query/query.pb.h"
#include "ecclesia/lib/redfish/dellicius/query/query_result.pb.h"
#include "ecclesia/lib/redfish/interface.h"
#include "ecclesia/lib/time/proto.h"
#include "single_include/nlohmann/json.hpp"
#include "re2/re2.h"

namespace ecclesia {

namespace {

using SubqueryHandle = QueryPlanner::SubqueryHandle;
using RedPathStep = SubqueryHandle::RedPathStep;
using ContextNodeToSubqueryHandles =
    SubqueryHandle::ContextNodeToSubqueryHandles;
using FilterContext = SubqueryHandle::FilterContext;

// Regex definitions to identify LocationStep expression and extract NodeName,
// Predicate and Filter Expressions.
// Note: Regex patterns here are not meant to detect malformed RedPaths.
//
// Pattern for location step: NodeName[Predicate]
constexpr LazyRE2 kLocationStepRegex = {
    "^([a-zA-Z#@][0-9a-zA-Z.]+)(?:\\[(.*?)\\]|)$"};
// Pattern for predicate formatted with relational operators:
constexpr LazyRE2 kPredicateRegexRelationalOperator = {
    "^([a-zA-Z#@][0-9a-zA-Z.]*)(?:(!=|>|<|=|>=|<=))([a-zA-Z0-9._#]+)$"};

constexpr absl::string_view kPredicateSelectAll = "*";
constexpr absl::string_view kPredicateSelectLastIndex = "last()";
constexpr absl::string_view kBinaryOperandTrue = "true";
constexpr absl::string_view kBinaryOperandFalse = "false";
// Supported relational operators
constexpr std::array<const char *, 6> kRelationsOperators = {
    "<", ">", "!=", ">=", "<=", "="};

// Creates RedPathStep objects from the given RedPath string.
absl::StatusOr<std::vector<RedPathStep>> RedPathToSteps(
    absl::string_view redpath) {
  std::vector<RedPathStep> steps;
  for (absl::string_view step_expression :
       absl::StrSplit(redpath, '/', absl::SkipEmpty())) {
    std::string node_name, predicate;
    if (!RE2::FullMatch(step_expression, *kLocationStepRegex, &node_name,
                        &predicate)) {
      return absl::InvalidArgumentError(
          absl::StrFormat("Cannot parse Step expression %s in RedPath %s",
                          step_expression, redpath));
    }
    steps.push_back({node_name, predicate});
  }
  return steps;
}

template <typename F>
bool ApplyNumberComparisonFilter(const nlohmann::json &obj, F comparator) {
  double number;
  if (obj.is_number()) {
    number = obj.get<double>();
  } else if (!obj.is_string() ||
             !absl::SimpleAtod(obj.get<std::string>(), &number)) {
    return false;
  }
  return comparator(number);
}

// Helper function is used to ensure the obtained value equal or not equal to a
// non-number value.
template <typename F>
bool ApplyStringComparisonFilter(F filter_condition,
                                 absl::string_view inequality_string) {
  if (inequality_string == "!=") {
    return !filter_condition();
  }
  return filter_condition();
}

// Gets all the node names in the given expression.
// parent.child.grandchild -> {parent, child, grandchild}
std::vector<std::string> GetNodeNamesFromChain(absl::string_view node_name) {
  std::vector<std::string> nodes;
  if (auto pos = node_name.find("@odata."); pos != std::string::npos) {
    std::string odata_str = std::string(node_name.substr(pos));
    if (absl::StrContains(odata_str, "@odata.id")) return nodes;
    nodes = absl::StrSplit(node_name.substr(0, pos), '.', absl::SkipEmpty());
    nodes.push_back(std::move(odata_str));
  } else {
    nodes = absl::StrSplit(node_name, '.', absl::SkipEmpty());
  }
  return nodes;
}

// Helper function to resolve node_name for nested nodes if any and return json
// object to be evaluated for required property.
absl::StatusOr<nlohmann::json> GetJsonObjectFromNodeName(
    const RedfishVariant &variant, absl::string_view node_name) {
  std::vector<std::string> node_names = GetNodeNamesFromChain(node_name);
  if (node_names.empty()) {
    return absl::InternalError("Cannot parse any node from given NodeName");
  }
  nlohmann::json json_obj = variant.AsObject()->GetContentAsJson();
  // If given expression has multiple nodes, we need to return the json object
  // associated with the leaf node.
  for (auto const &name : node_names) {
    if (!json_obj.contains(name)) {
      return absl::InternalError(
          absl::StrFormat("Node %s not found in json object", name));
    }
    json_obj = json_obj.at(name);
  }
  return json_obj;
}

// Handler for predicate expressions containing relational operators.
bool PredicateFilterByNodeComparison(const RedfishVariant &variant,
                                     absl::string_view predicate) {
  std::string node_name, op, test_value;
  bool ret = false;
  if (RE2::FullMatch(predicate, *kPredicateRegexRelationalOperator, &node_name,
                     &op, &test_value)) {
    double value;
    auto json_obj = GetJsonObjectFromNodeName(variant, node_name);
    if (!json_obj.ok()) {
      LOG(ERROR) << json_obj.status();
      return false;
    }

    // Number comparison.
    if (absl::SimpleAtod(test_value, &value)) {
      const auto condition = [&op, value](double number) {
        if (op == ">=") return number >= value;
        if (op == ">") return number > value;
        if (op == "<=") return number <= value;
        if (op == "<") return number < value;
        if (op == "!=") return number != value;
        if (op == "=") return number == value;
        return false;
      };
      ret = ApplyNumberComparisonFilter(*json_obj, condition);
    } else if (test_value == kBinaryOperandFalse ||
               test_value == kBinaryOperandTrue) {
      // For the property value's type is boolean.
      bool bool_value = test_value != kBinaryOperandFalse;
      const auto condition = [json_obj, bool_value]() {
        return *json_obj == bool_value;
      };
      ret = ApplyStringComparisonFilter(condition, op);
    } else if (test_value == "null") {
      // For the property value is null.
      const auto condition = [json_obj]() { return json_obj->is_null(); };
      ret = ApplyStringComparisonFilter(condition, op);
    } else {
      // For the property value's type is string.
      const auto condition = [json_obj, test_value]() {
        return *json_obj == test_value;
      };
      ret = ApplyStringComparisonFilter(condition, op);
    }
  }
  return ret;
}

// Handler for '[nodename]'
// Checks if given Redfish Resource encapsulated in the Variant contains
// predicate string.
bool PredicateFilterByNodeName(const RedfishVariant &variant,
                               absl::string_view predicate) {
  std::vector<std::string> node_names = GetNodeNamesFromChain(predicate);
  if (node_names.empty()) {
    return false;
  }
  nlohmann::json leaf = variant.AsObject()->GetContentAsJson();
  for (auto const &name : node_names) {
    if (!leaf.contains(name)) {
      return false;
    }
    leaf = leaf.at(name);
  }
  return true;
}

using NodeNameToSubqueryHandles =
    absl::flat_hash_map<std::string, std::vector<SubqueryHandle>>;

// Deduplicates the next NodeName expression in the RedPath of each subquery
// and returns NodeName to SubqueryHandle map. This is to ensure Redfish Request
// is sent out once but the dataset obtained can be processed per Subquery
// using the mapped SubqueryHandle objects.
NodeNameToSubqueryHandles DeduplicateNodeNamesAcrossSubqueries(
    std::vector<SubqueryHandle> &subquery_handles) {
  NodeNameToSubqueryHandles node_to_subquery;
  for (auto &subquery_handle : subquery_handles) {
    // Pair resource name and those subqueries that have this resource as next
    // element in their respective RedPaths
    auto node_name = subquery_handle.GetNodeNameFromRedPathStep();
    if (node_name != std::nullopt) {
      node_to_subquery[*node_name].push_back(subquery_handle);
    }
  }
  return node_to_subquery;
}

// A helper utility to iterate over a Collection and Singleton Resource.
// The callback apply_predicate_from_each_subquery is responsible for applying
// Predicate Expression rules from each subquery using Redfish Resource
// encapsulated in the variant as the context node. This callback has a
// signature:
//     void f(SubqueryHandle::FilterContext context)
//         args: FilterContext {
//                 RedfishVariant: Redfish Resource used as context node.
//                 node_index: The specific instance of a Resource in Collection
//                             or 0 if the resource is Singleton
//                 node_set_size: Resource Collection size; 1 if Singleton.
//               }
template <typename Callback>
void PredicateRunner(RedfishVariant &&var,
                     Callback &&apply_predicate_from_each_subquery) {
  auto iter = var.AsIterable();
  size_t node_index = 0, node_count = 1;
  if (iter != nullptr) {
    // Iterate over each Resource in Collection and invoke predicate handler
    node_count = iter->Size();
    for (size_t index = 0; index < node_count; ++index) {
      apply_predicate_from_each_subquery(
          {std::move(var[index]), index, node_count});
    }
  } else {
    apply_predicate_from_each_subquery(
        {std::move(var), node_index, node_count});
  }
}

}  // namespace

SubqueryHandle::SubqueryHandle(const DelliciusQuery::Subquery &subquery,
                               Normalizer *normalizer)
    : subquery_(subquery), normalizer_(normalizer) {
  is_redpath_valid_ = false;
  auto steps = RedPathToSteps(subquery.redpath());
  if (!steps.ok()) {
    LOG(ERROR) << steps.status();
    return;
  }
  steps_in_redpath_ = *std::move(steps);
  // An iterator is configured to traverse the Step expressions in subquery's
  // RedPath as redfish requests are dispatched.
  iter_ = steps_in_redpath_.begin();
  is_redpath_valid_ = true;
}

std::optional<std::string> SubqueryHandle::GetNodeNameFromRedPathStep() const {
  if (is_redpath_valid_) return iter_->node_name;
  return std::nullopt;
}

// Normalizes dataset from filtered node if there are no more RedPathSteps left
// else updates URI to Context node mapping with current subquery.
void SubqueryHandle::NormalizeOrContinueQuery(
    const RedfishVariant &node,
    ContextNodeToSubqueryHandles &context_node_to_sq,
    DelliciusQueryResult &result) {
  // If iterator reached end of RedPath
  if (!steps_in_redpath_.empty() &&
      iter_->node_name == steps_in_redpath_.back().node_name) {
    // Normalize redfish response per the property requirements in
    // subquery.
    absl::StatusOr<SubqueryDataSet> normalized_data =
        normalizer_->Normalize(node, subquery_);
    if (normalized_data.ok()) {
      // Populate the response data in subquery output for the given id.
      auto *subquery_output = result.mutable_subquery_output_by_id();
      (*subquery_output)[subquery_.subquery_id()].mutable_data_sets()->Add(
          std::move(normalized_data.value()));
    }
  } else if (std::unique_ptr<RedfishObject> obj = node.AsObject()) {
    // Update Context Node URI to SubqueryHandle map to share context node
    // across subqueries.
    std::optional<std::string> maybe_uri = obj->GetUriString();
    // Objects that don't have a URI cannot serve as context node.
    // To reference into such objects, a Query needs to use property path
    // instead of using RedPath NodeName expressions.
    if (!maybe_uri.has_value()) return;
    auto uri_to_subqueries_pair = context_node_to_sq.find(*maybe_uri);
    // Since iterator has not reached the end of RedPath, increment the iterator
    // to point to next RedPath Step expression.
    ++iter_;
    // If URI exists in the map, add redfish object and subquery handle.
    if (uri_to_subqueries_pair != context_node_to_sq.end()) {
      // Insert the Redfish Object to be used as context node.
      uri_to_subqueries_pair->second.first = std::move(obj);
      // Insert this SubqueryHandle.
      uri_to_subqueries_pair->second.second.push_back(*this);
    } else {
      // If URI of the new context node does not exist, insert a new URI and
      // SubqueryHandle pair.
      std::vector<SubqueryHandle> context_node_sq_handles = {*this};
      context_node_to_sq[*std::move(maybe_uri)] = {std::move(obj),
                                                   context_node_sq_handles};
    }
    // Decrement the iterator to allow the same subquery handle to be tested for
    // next context node in the iterable.
    --iter_;
  }
}

bool SubqueryHandle::ApplyPredicateRule(const FilterContext &filter_context) {
  std::string_view predicate = iter_->predicate;
  size_t num;
  // If '[last()]' predicate expression, check if current node at last index.
  if ((predicate == kPredicateSelectLastIndex &&
       filter_context.node_index == filter_context.node_set_size - 1) ||
      // If '[Index]' predicate expression, check if current node at given index
      (absl::SimpleAtoi(predicate, &num) && num == filter_context.node_index) ||
      // If '[*]' predicate expression or empty predicate, no filter required.
      (predicate.empty() || predicate == kPredicateSelectAll)) {
    return true;
  }

  // Boolean tracking the status of filter operation using predicate expression
  // rule.
  bool is_filter_success = false;
  if (std::any_of(
          kRelationsOperators.begin(), kRelationsOperators.end(),
          [&](const char *op) { return absl::StrContains(predicate, op); })) {
    // Look for predicate expression containing relational operators.
    is_filter_success =
        PredicateFilterByNodeComparison(filter_context.node, predicate);
  } else {
    // Filter node-set by NodeName
    is_filter_success =
        PredicateFilterByNodeName(filter_context.node, predicate);
  }
  return is_filter_success;
}

void QueryPlanner::ExecuteRedPathStepFromEachSubquery(
    const RedfishObject *redfish_object,
    std::vector<SubqueryHandle> &subquery_handles,
    DelliciusQueryResult &result) {
  ContextNodeToSubqueryHandles context_node_to_sq;
  NodeNameToSubqueryHandles node_name_to_subquery =
      DeduplicateNodeNamesAcrossSubqueries(subquery_handles);
  if (node_name_to_subquery.empty()) return;
  for (auto &[node_name, handles] : node_name_to_subquery) {
    // Reference to allow capture in the PredicateRunner.
    std::vector<SubqueryHandle> &subquery_handles_mapped_to_node = handles;
    // Dispatch Redfish Request for the Redfish Resource associated with the
    // NodeName expression.
    auto node_set = redfish_object->Get(node_name);
    // If NodeName does not resolve to a valid Redfish Resource, skip it!
    if (node_set.AsObject() == nullptr && node_set.AsIterable() == nullptr) {
      continue;
    }
    // At this point we have executed redfish request for a NodeName that
    // results in a node-set which can be a singleton Redfish resource or
    // a Collection.
    // As we are batch processing subqueries, it is possible that a node in
    // this node-set can satisfy predicates across subqueries. Example
    // /Chassis[SKU=1234] and /Chassis[Name=Foo] could be the same chassis
    // instance /redfish/v1/Chassis/1U.
    // So instead of applying predicate expression individually on the node-set
    // we can batch process predicate expressions so that we iterate the
    // node-set once.
    //
    // On successful filter, map the subquery with the URI. The mapped
    // subqueries can then use the Resource associated with the URI as context
    // node for executing next NodeName expression.
    // Example: {"/redfish/v1/Chassis/1U" : {SQ1, SQ4, SQ5}},
    //           "/redfish/v1/Chassis/4U" : {SQ1, SQ4, SQ9}}
    PredicateRunner(std::move(node_set), [&](FilterContext filter_context) {
      for (auto &subquery_handle : subquery_handles_mapped_to_node) {
        if (subquery_handle.ApplyPredicateRule(filter_context)) {
          subquery_handle.NormalizeOrContinueQuery(filter_context.node,
                                                   context_node_to_sq, result);
        }
      }
    });
  }
  // Now, for each new context node obtained after applying Predicates, execute
  // next RedPath Step expression from the mapped subqueries.
  for (auto &[uri, redfish_obj_and_sq_handles] : context_node_to_sq) {
    ExecuteRedPathStepFromEachSubquery(redfish_obj_and_sq_handles.first.get(),
                                       redfish_obj_and_sq_handles.second,
                                       result);
  }
}

void QueryPlanner::Run(const RedfishVariant &variant, const Clock &clock,
                       DelliciusQueryResult &result) {
  auto timestamp = AbslTimeToProtoTime(clock.Now());
  if (timestamp.ok()) {
    *result.mutable_start_timestamp() = *std::move(timestamp);
  }
  result.set_query_id(plan_id_);
  if (auto obj = variant.AsObject()) {
    ExecuteRedPathStepFromEachSubquery(obj.get(), subquery_handles_, result);
  }
  timestamp = AbslTimeToProtoTime(clock.Now());
  if (timestamp.ok()) {
    *result.mutable_end_timestamp() = *std::move(timestamp);
  }
}

QueryPlanner::QueryPlanner(const DelliciusQuery &query, Normalizer *normalizer)
    : plan_id_(query.query_id()) {
  // Create SubqueryHandle for each Subquery in a RedPath Query.
  for (const auto &subquery : query.subquery()) {
    auto subquery_handle = SubqueryHandle(subquery, normalizer);
    // If SubqueryHandle instantiation fails for some reason, QueryPlanner will
    // not be able to fetch the first NodeName in Subquery's RedPath.
    // This however is not a fatal error and the QueryPlanner will continue
    // to create SubqueryHandles for remaining Subqueries.
    if (subquery_handle.GetNodeNameFromRedPathStep() == std::nullopt) continue;
    subquery_handles_.push_back(std::move(subquery_handle));
  }
}

}  // namespace ecclesia


text:
"""
    PyValitron
    ~~~~~~
    Python Inputs Validation Library
    :copyright: (c) 2016 by Clivern (hello@clivern.com).
    :license: MIT, see LICENSE for more details.
"""
from .validator import Validator
from .sanitizer import Sanitizer
from .utils import Utils
from .exceptions import PyValitronError

class Form(object):

    _inputs = {}
    _errors = {}
    _sinputs = {}

    _vstatus = False
    _sstatus = False

    _validator = None
    _sanitizer = None
    _sanitizers = []
    _validators = []
    _utils = None

    def __init__(self, inputs={}):
        """Init Form Module"""
        self._inputs = inputs
        self._validator = Validator()
        self._sanitizer = Sanitizer()
        self._utils = Utils()

    def add_inputs(self, inputs={}):
        """Set inputs"""
        self._inputs = inputs

    def get_inputs(self):
        """Get Original Inputs Values"""
        return self._inputs

    def get_errors(self):
        """Get All Errors"""
        return self._errors

    def get_vstatus(self):
        """Get Overall Sanitization Status"""
        return self._vstatus

    def get_sstatus(self):
        """Get Overall Sanitization Status"""
        return self._sstatus

    def process(self, direction=['sanitize', 'validate']):
        """Process both validation and sanitization"""
        if direction[0] == 'sanitize':
            if 'sanitize' in direction:
                self._sanitize()
            if 'validate' in direction:
                self._validate()
        else:
            if 'validate' in direction:
                self._validate()
            if 'sanitize' in direction:
                self._sanitize()

    def add_validator(self, val_instance):
        """Add custom validator"""
        self._validators.append(val_instance)

    def add_sanitizer(self, san_instance):
        """Add custom sanitizer"""
        self._sanitizers.append(san_instance)

    def _validate(self):
        """Validate, Set Errors and Return Overall Status"""

        # Validate current inputs value
        status = True

        for current_input, validation_rule in self._inputs.items():
            # Push input value to validator
            self._validator.set_input(self._inputs[current_input]['value'])
            if 'validate' in validation_rule:
                self._errors[current_input] = []
                for rule_name, rule_args in validation_rule['validate'].items():
                    self._update_validator(rule_name)
                    # Check if param exist and pass them to the method
                    if 'param' in rule_args.keys() and len(rule_args['param']) > 0:
                        current_status = getattr(self._validator, rule_name)(*rule_args['param'])
                    else:
                        current_status = getattr(self._validator, rule_name)()
                    self._inputs[current_input]['status'] = current_status
                    status &= current_status
                    if not current_status and 'error' in rule_args.keys():
                        self._errors[current_input].append(rule_args['error'])

        # Set and return Overall status
        self._vstatus = status
        return status

    def _sanitize(self):
        """Sanitize Inputs and Store Them"""

        # Sanitize current input value
        status = True
        for current_input, sanitization_rule in self._inputs.items():
            # Push input value to sanitizer
            self._sanitizer.set_input(self._inputs[current_input]['value'])
            self._sanitizer.set_sinput(None)
            if 'sanitize' in sanitization_rule:
                for rule_name, rule_args in sanitization_rule['sanitize'].items():
                    self._update_sanitizer(rule_name)
                    # Check if param provided and pass them to the method
                    if 'param' in rule_args.keys() and len(rule_args['param']) > 0:
                        sanitized_value = getattr(self._sanitizer, rule_name)(*rule_args['param'])
                    else:
                        sanitized_value = getattr(self._sanitizer, rule_name)()
                    self._inputs[current_input]['svalue'] = sanitized_value
                    self._inputs[current_input]['is_exact'] = True if self._inputs[current_input]['value'] == self._sanitizer.get_sinput() else False
                    status &= self._inputs[current_input]['is_exact']

        # Set and return Overall status
        self._sstatus = status
        return status

    def _update_validator(self, rule_name):
        """Update current validator"""
        if hasattr(self._validator, rule_name):
            return True
        for validator in self._validators:
            if hasattr(validator, rule_name):
                self._validator = validator
                return True
        raise PyValitronError('Non existent validation rule %s' % rule_name)

    def _update_sanitizer(self, rule_name):
        """Update current sanitizer"""
        if hasattr(self._sanitizer, rule_name):
            if self._sanitizer.get_sinput() is None:
                self._sanitizer.set_input(self._sanitizer.get_input())
                self._sanitizer.set_sinput(None)
            else:
                self._sanitizer.set_input(self._sanitizer.get_sinput())
            return True
        for sanitizer in self._sanitizers:
            if hasattr(sanitizer, rule_name):
                if self._sanitizer.get_sinput() is None:
                    sanitizer.set_input(self._sanitizer.get_input())
                    sanitizer.set_sinput(None)
                else:
                    sanitizer.set_input(self._sanitizer.get_sinput())
                self._sanitizer = sanitizer
                return True
        raise PyValitronError('Non existent sanitization rule %s' % rule_name)


text:
/**
 * This plugin sanitizes input with google caja sanitizer
 *
 * https://code.google.com/p/google-caja/
 */

var caja = require('google-caja');

var plugin = {
  name: 'sanitize'
, parser: function (next, block) {
    var sanitized = caja.sanitize(block);
    return next(sanitized);
  }
};

module.exports = plugin;

if (global.formatter) {
  formatter.addPlugin(plugin);
}


text:
<!DOCTYPE html>

    <link href='http://fonts.googleapis.com/css?family=Poiret+One|Open+Sans+Condensed:300|Amatic+SC|Rock+Salt|Satisfy' rel='stylesheet' type='text/css'>
    <title>Madison [builds] Sites</title>
    <link rel="stylesheet" type="text/css" href="style.css">

Cultural Blog: Week 6

July 26, 2015

Stereotype Threats

      As irony would have it, I was never much of a feminist. As the only girl in a clan of four kids, I always ran with the boys. They comprised a majority of my friends and have been my favorite roommates.

      In my old life, back in Tennessee, I never once felt the need to be a feminist. I felt the work and pay was fair for me and my other co-workers, male and female. The ones who didn't usually didn't seem to be working very hard anyway.

        Everything changed when I moved to Silicon Valley, though, and even though I wasn't working in a full-capacity tech company, I had moved out of a female-ruled hospitality industry into a completely different realm, and it showed.

        I worked several jobs, some even in hospitality, and found that I was working hard than the boys and still getting denied for raises, despite bringing in what I felt like was sufficient data. Had I moved up the ranks enough before leaving Tennessee, I would have likely found the same frustrations, even had I stayed in hospitality. A broad assumption, I know, but I've heard it from friends that stayed behind enough to feel comfortable making it.

        It's a relief to see that we as society, and in particular the culture of Silicon Valley, is recognizing the discrimination. It's the first step in the problem. And while I'm not sure where I stand on the Ellen Pao case, it certainly brought the issue more light. I do fear that this isn't enough.

        I don't want to see us waste this opportunity to make great change by only talking about it. I don't want to continue to see the social excuses of "well, I have a black/female/minority friend". These get us no where. I want action.

        I want to see companies taking small steps to test their effectiveness. Maybe removing names and ages when reviewing resumes - as sadly age is also discriminated against here as well. Studies have shown that simply including "salary negotiable" encourages women to negotiate enough that it closes the pay gap by 45%.

        One of my deepest fears is finishing Dev Bootcamp and having no leads on a job. This is of course only heightened with these discriminations. I know the problem can't possible be solved by the end of October when I graduate, but I hope to see enough progress to feel comfortable around my co-workers in a field I'm quickly falling in love with otherwise.


text:
package org.apache.clerezza.dataset.providers;

import org.apache.clerezza.Graph;
import org.apache.clerezza.IRI;
import org.apache.clerezza.ImmutableGraph;
import org.apache.clerezza.dataset.EntityUndeletableException;
import org.apache.clerezza.dataset.NoSuchEntityException;
import org.apache.clerezza.dataset.TcManagerTest;
import org.apache.clerezza.dataset.WeightedTcProvider;
import org.apache.clerezza.implementation.TripleImpl;
import org.apache.clerezza.implementation.in_memory.SimpleGraph;

import java.util.HashSet;
import java.util.Set;

/**
 *
 * @author reto
 */
public class WeightedBlight implements WeightedTcProvider {

    @Override
    public int getWeight() {
        return 2;
    }

    @Override
    public ImmutableGraph getImmutableGraph(IRI name) throws NoSuchEntityException {
        if (name.equals(TcManagerTest.uriRefB)) {
            Graph mResult = new SimpleGraph();
            mResult.add(new TripleImpl(TcManagerTest.uriRefB, TcManagerTest.uriRefB, TcManagerTest.uriRefB));
            return mResult.getImmutableGraph();
        }
        if (name.equals(TcManagerTest.uriRefA)) {
            Graph mResult = new SimpleGraph();
            //empty ImmutableGraph
            return mResult.getImmutableGraph();
        }
        throw new NoSuchEntityException(name);
    }

    @Override
    public Graph getMGraph(IRI name) throws NoSuchEntityException {
        throw new NoSuchEntityException(name);
    }

    @Override
    public Graph getGraph(IRI name) throws NoSuchEntityException {
        return getImmutableGraph(name);
    }

    @Override
    public Graph createGraph(IRI name) {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public ImmutableGraph createImmutableGraph(IRI name, Graph triples) {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public void deleteGraph(IRI name) throws NoSuchEntityException,
            EntityUndeletableException {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public Set<IRI> getNames(ImmutableGraph ImmutableGraph) {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public Set<IRI> listImmutableGraphs() {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public Set<IRI> listMGraphs() {
        return new HashSet<IRI>();
    }

    @Override
    public Set<IRI> listGraphs() {
        return listMGraphs();
    }

}


text:
package fr.jblezoray.mygeneticalgo.utils;

public class Normalizer {

  /**
   * This method normalizes a float from range [currentMin, currentMax] to
   * range [newMin, newMax].
   *
   * @param valueToNormalize
   * @param currentMin
   * @param currentMax
   * @param newMin
   * @param newMax
   * @return
   */
  public static float normalizeFloat(float valueToNormalize,
      float currentMin, float currentMax, float newMin, float newMax) {
    float scale = (valueToNormalize - currentMin) / currentMax;
    return (scale * (newMax - newMin)) + newMin;
  }

  /**
   * This method normalizes a, integer from range [currentMin, currentMax] to
   * range [newMin, newMax].
   *
   * @param valueToNormalize
   * @param currentMin
   * @param currentMax
   * @param newMin
   * @param newMax
   * @return
   */
  public static int normalizeInteger(int valueToNormalize, int currentMin,
      int currentMax, int newMin, int newMax) {
    float scale = (valueToNormalize - currentMin) / (float) currentMax;
    return (int)((scale * (newMax - newMin)) + newMin);
  }

}


text:
<?php
require_once(__DIR__.'/../../files/Fairy.php');

class ORMTest extends PHPUnit_Framework_TestCase{

	protected $pager;
	protected $db_file;
	protected $conf_file;
	protected $fairies;
	protected $pixie;

	protected function setUp() {
		$this->db_file = tempnam(sys_get_temp_dir(), 'test.sqlite');
		$this->conf_file = tempnam(sys_get_temp_dir(), 'test.conf');
		file_put_contents($this->db_file, '');
		$db = new PDO('sqlite:'.$this->db_file);
		$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
		$db->exec("CREATE TABLE fairies(id INT PRIMARY_KEY)");

		for($i=0;$i<22;$i++)
			$db->exec("INSERT INTO fairies(id) VALUES ($i)");

		$this->pixie = $this->getMock('\PHPixie\Pixie',array('find_file'));
		$this->pixie->expects($this->any())
                 ->method('find_file')
                 ->will($this->returnValue($this->conf_file));

		$this->pixie->router = new \PHPixie\Router($this->pixie);
		$this->pixie->router->add(new \PHPixie\Route('test', '/<category>/page-<page>', array()));
		$this->pixie->db = new \PHPixie\DB($this->pixie);
		$this->pixie->orm = new \PHPixie\ORM($this->pixie);

		$this->pixie->config->set('db.default.connection', 'sqlite:'.$this->db_file);
		$this->pixie->config->set('db.default.driver', 'pdo');

		$this->fairies = new \Model\Fairy($this->pixie);
		$this->fairies->where('id', '>', 2);
		$this->pager = new \PHPixie\Paginate\Pager\ORM($this->pixie, $this->fairies, 2, 5);
	}

	public function testException() {
		$except = false;
		try{
			$this->pager->url(1);
		}catch(\Exception $e){
			$except = true;
		}
		$this->assertEquals(true, $except);
	}

	public function testPageProperties() {
		$this->assertEquals(4, $this->pager->num_pages);
		$this->assertEquals(2, $this->pager->page);
		$this->assertEquals(5, $this->pager->page_size);
	}

	public function testPattern() {
		$this->pager->set_url_pattern('/page-#page#');
		$this->assertEquals('/page-1', $this->pager->url(1));
		$this->assertEquals('/page-2', $this->pager->url(2));
	}

	public function testRoute() {
		$this->pager->set_url_route('test', array('category' => 'fairy'));
		$this->assertEquals('/fairy/page-1', $this->pager->url(1));
		$this->assertEquals('/fairy/page-2', $this->pager->url(2));
	}

	public function testCallback() {
		$this->pager->set_url_callback(function($page) {
			return "/callback/page-$page";
		});
		$this->assertEquals('/callback/page-1', $this->pager->url(1));
		$this->assertEquals('/callback/page-2', $this->pager->url(2));
	}

	public function testFirstPage() {
		$pager = new \PHPixie\Paginate\Pager\ORM($this->pixie, $this->fairies, 2, 5, '/first_page');
		$pager->set_url_pattern('/page-#page#');
		$this->assertEquals('/first_page', $pager->url(1));
		$this->assertEquals('/page-2', $pager->url(2));
	}

	public function testItems() {
		$items = $this->pager->current_items();
		$i = 8;
		foreach($items as $item)
			$this->assertEquals($i++, $item->id);
	}

	protected function tearDown(){
		$db = $this->pixie->db->get();
		$db->conn = null;
		unlink($this->db_file);
		unlink($this->conf_file);
	}
}


text:
import 'jquery';
import config from 'scripts/config.js';
import gameModel from 'scripts/gameModel.js';

var tetris = {

    // Initialize to start the game
    start: function (game) {
        tetris.bound = $.browser == 'msie' ? '#tetris' : window;
        $(tetris.bound).keypress(tetris.key);
        tetris.game = game;
        game.start(tetris.gameOver);
        tetris.duration = 600;
        tetris.timer = window.setInterval(game.moveDown, tetris.duration);
    },

    // Define the action to be fired depending on key entry
    key: function (e) {
        switch (e.charCode || e.keyCode) {
        case 74:
        case 106:
            tetris.game.moveLeft();
            break; // J
        case 76:
        case 108:
            tetris.game.moveRight();
            break; // L
        case 75:
        case 107:
            tetris.game.moveDown();
            break; // K
        case 73:
        case 105:
            tetris.game.rotate();
            break; // I
        }
        return false;
    },

    gameOver: function () {
        if (tetris.timer) {
            window.clearInterval(tetris.timer);
            tetris.timer = null;
        }
    }
};

export function init() {
    $('#grid table, #next table').css('backgroundColor', config.colors[0]);

    $('#start').click(function () {
        $('#start').attr('disabled', 'disabled');
        $('#stop').removeAttr('disabled');
        gameModel.init();
        tetris.start(gameModel);
    });
    $('#stop').click(function () {
        $('#stop').attr('disabled', 'disabled');
        $('#start').removeAttr('disabled');
        tetris.gameOver();
    });
}


text:
package hrv.lib.hrv.calc.manipulator;

import hrv.lib.common.ArrayUtils;
import hrv.lib.hrv.RRData;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class HRVCleanRRDataByLimits implements HRVDataManipulator {

	private static final double LOWER_RR_LIMIT = 0.2; // = 300 beats per minute
	private static final double UPPER_RR_LIMIT = 3.0; // = 20 beats per minute

	@Override
	public RRData manipulate(RRData data) {

		double[] oldRRY = data.getValueAxis();

		Set<Integer> indicesToRemove = getIndicesToRemoveByLimit(oldRRY);

		double[] newRRY = removeIndices(oldRRY, indicesToRemove);

		return RRData.createFromRRInterval(newRRY, data.getValueAxisUnit());
	}

	private Set<Integer> getIndicesToRemoveByLimit(double[] data) {
		Set<Integer> indicesToRemove = new HashSet<>();

		for (var i = 0; i < data.length; i++) {
			if (data[i] < LOWER_RR_LIMIT || data[i] > UPPER_RR_LIMIT) {
				indicesToRemove.add(i);
			}
		}

		return indicesToRemove;
	}

	private double[] removeIndices(double[] data, Set<Integer> indicesToRemove) {
		var newData = new ArrayList<Double>();

		for (var i = 0; i < data.length; i++) {
			if (!indicesToRemove.contains(i)) {
				newData.add(data[i]);
			}
		}
		return ArrayUtils.toPrimitive(newData, 0.0);
	}
}


text:
package cucumber.runtime.jython;

import cucumber.api.Scenario;
import cucumber.runtime.Backend;
import cucumber.runtime.CucumberException;
import cucumber.runtime.Glue;
import cucumber.runtime.UnreportedStepExecutor;
import cucumber.runtime.io.Resource;
import cucumber.runtime.io.ResourceLoader;
import cucumber.runtime.snippets.FunctionNameSanitizer;
import cucumber.runtime.snippets.SnippetGenerator;
import gherkin.formatter.model.Step;
import org.python.core.*;
import org.python.util.PythonInterpreter;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.List;

public class JythonBackend implements Backend {
    private static final String DSL = "/cucumber/runtime/jython/dsl.py";
    private final SnippetGenerator snippetGenerator = new SnippetGenerator(new JythonSnippet());
    private final ResourceLoader resourceLoader;
    private final PythonInterpreter jython;
    private PyObject pyWorld;
    private Glue glue;

    public JythonBackend(ResourceLoader resourceLoader, PythonInterpreter jython) {
        this.resourceLoader = resourceLoader;
        this.jython = jython;
        jython.set("backend", this);
        jython.execfile(getClass().getResourceAsStream(DSL), DSL);
    }

    public JythonBackend(ResourceLoader resourceLoader) {
        this(resourceLoader, new PythonInterpreter());
    }

    @Override
    public void loadGlue(Glue glue, List<String> gluePaths) {
        this.glue = glue;

        for (String gluePath : gluePaths) {
            for (Resource resource : resourceLoader.resources(gluePath, ".py")) {
                execFile(resource);
            }
        }
    }

    @Override
    public void setUnreportedStepExecutor(UnreportedStepExecutor executor) {
        //Not used yet
    }

    @Override
    public void buildWorld() {
        this.pyWorld = jython.eval("World()");
    }

    private void execFile(Resource resource) {
        try {
            jython.execfile(resource.getInputStream(), resource.getPath());
        } catch (IOException e) {
            throw new CucumberException(e);
        }
    }

    @Override
    public void disposeWorld() {
    }

    @Override
    public String getSnippet(Step step, FunctionNameSanitizer functionNameSanitizer) {
        return snippetGenerator.getSnippet(step, functionNameSanitizer);
    }

    public void registerStepdef(PyInstance stepdef, int arity) {
        glue.addStepDefinition(new JythonStepDefinition(this, stepdef, arity));
    }

    public void addBeforeHook(PyInstance hookDefinition) {
        glue.addBeforeHook(new JythonHookDefinition(this, hookDefinition));
    }

    public void addAfterHook(PyInstance hookDefinition) {
        glue.addAfterHook(new JythonHookDefinition(this, hookDefinition));
    }

    public void executeHook(PyInstance hookDefinition, Scenario scenario) {
        try {
            // Try to pass the scenario
            hookDefinition.invoke("execute", pyWorld, Py.java2py(scenario));
        } catch (PyException e) {
            if (getStacktrace(e).contains("takes exactly 1 argument (2 given)")) {
                // The stepdef doesn't want the scenario
                hookDefinition.invoke("execute", pyWorld);
            } else {
                // Some other error. Just rethrow.
                throw e;
            }
        }
    }

    private String getStacktrace(PyException e) {
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        e.printStackTrace(pw);
        return sw.getBuffer().toString();
    }

    public void execute(PyInstance stepdef, Object[] args) throws Throwable {

        PyObject[] pyArgs = new PyObject[args.length + 1];
        pyArgs[0] = pyWorld;
        for (int i = 0; i < args.length; i++) {
            pyArgs[i + 1] = new PyString((String) args[i]);
        }
        try {
            stepdef.invoke("execute", pyArgs);
        } catch (PyException t) {
            Object unwrapped = t.value.__tojava__(Object.class);
            if (unwrapped instanceof Throwable) {
                throw (Throwable) unwrapped;
            } else {
                throw t.getCause() == null ? t : t.getCause();
            }
        }
    }
}


text:
<?php

Yii::import('nfy.NfyModule');

/**
 * The Nfy class acts like the CLogger class. Instead of collecting the messages,
 * it instantly passes them to each channel for processing, similar to CLogRouter
 * calling collectLogs on each route on log flush event.
 */
class Nfy {

	/**
	 * Sends passed message to all enabled channels matching specified level and category.
	 *
	 * @param mixed $msg if string, is treated as message to be logged, if an array, should contain 'old' and 'new' keys with CModel objects as values
	 * @param string $level level of the message (e.g. 'trace', 'warning', 'error'). It is case-insensitive.
	 * @param string $category category of the message (e.g. 'system.web'). It is case-insensitive.
	 */
	public static function log($msg,$level=CLogger::LEVEL_INFO,$category='application') {
		$cacheDuration=3600;
		$channels = NfyChannels::model()->cache($cacheDuration)->findAll('t.enabled=:enabled', array(':enabled'=>true));
		foreach($channels as $key=>$channel) {
			if ($channel->levels !== null) {
				$levels=preg_split('/[\s,]+/',strtolower($channel->levels),-1,PREG_SPLIT_NO_EMPTY);
				if (!in_array($level, $levels)) continue;
			}
			if ($channel->categories !== null) {
				$categories=preg_split('/[\s,]+/',strtolower($channel->categories),-1,PREG_SPLIT_NO_EMPTY);
				if (!in_array($category, $categories)) continue;
			}

			$route = Yii::createComponent(array(
				'class'=>$channel->route_class,
				'message_template'=>$channel->message_template,
			));
			if (!($route instanceof INfyRoute)) {
				$error = Yii::t('NfyModule.app', 'Route class {route} specified for channel {channel_name} must implement the INfyRoute interface.', array(
					'{route}' => $channel->route_class,
					'{channel_name}' => $channel->name,
				));
				// fail silently so the normal app workflow won't be disrupted by invalid notification configuration
				Yii::log($error, 'error', 'nfy');
				continue;
			}
			$route->process($msg, $channel->id, $channel->subscriptions);
		}
	}
}


text:
libdir = File.dirname(__FILE__) + '/../lib/'
$LOAD_PATH.unshift(libdir) unless $LOAD_PATH.include?(libdir)

require 'awesome_print'
require 'yaml'

require 'aws-cache'
require 'redis'

host = 'redis.aws.ecnext.net'
port = 6379

keyspace = ARGV[0] || 'debug'
cache = AwsCache.new({'keyspace' => keyspace, 'host' => host, 'port' => port})

##############################################################
#To get all instances associated with a given auto scaling group
#you can do something like this.
##############################################################
#placeHolder = Array.new()
#cache.get_asg_instances( "manta-site-e2e-smoketest-AdminServiceNestedStack-1LB9D75MS2SUE-AdminServiceAutoScalingGroup-1I2AY0INI3GH").each do |instances|
#  placeHolder.push(instances[:instance_id])
#end
#cache.describe_instances().each do |instance|
#  instance[:instances].each do |stuff|
#    if placeHolder.include?(stuff[:instance_id]) then
#      ap instance
#    end
#  end
#end
##############################################################

##############################################################
#To get all instances in a stack with substacks do this.
##############################################################
#cache.stack_auto_scaling_groups('manta-site--main--production').each do |asg|
#  ap cache.get_asg_instances(asg[:physical_resource_id])
#end
#
#cache.get_sub_stacks('manta-site--main--production').each do |stack|
#  ap stack[:stack_name]
#  cache.stack_auto_scaling_groups(stack[:stack_name]).each do |asg|
#    ap cache.get_asg_instances(asg[:physical_resource_id])
#  end
#end
##############################################################

cache.describe_instance("i-5f1824a0")

puts AwsCache::VERSION

exit


text:
package com.jevetools.unmarshal.python.api.impl.test; //NOPMD

import static com.jevetools.unmarshal.python.api.impl.test.OrderingComparison.comparesEqualTo;
import static com.jevetools.unmarshal.python.api.impl.test.OrderingComparison.greaterThan;
import static com.jevetools.unmarshal.python.api.impl.test.OrderingComparison.lessThan;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.not;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.junit.Assert.assertThat;

import org.junit.Test;

import com.jevetools.unmarshal.python.api.PyBase;
import com.jevetools.unmarshal.python.api.PyShort;
import com.jevetools.unmarshal.python.api.PyFactory;
import com.jevetools.unmarshal.python.api.PyNone;
import com.jevetools.unmarshal.python.api.PyVisitor;

/**
 * Copyright (c) 2013, jEVETools.
 *
 * All rights reserved.
 *
 * @version 0.0.1
 * @since 0.0.1
 */
public final class PyShortTest
    extends AbstractPyBaseTest
{
  /**
   * Test method for {@link PyShort#value()}.
   */
  @Test
  public void testDefault()
  {
    final PyFactory.PyShortBuilder builder = getPyFactory().getPyShortBuilder();

    final PyShort testSubject = builder.build();

    assertThat(testSubject, not(nullValue()));
    assertThat(testSubject.value(), equalTo(((short) 0))); // NOPMD
    assertThat(testSubject.toString(), equalTo(Short.toString((short) 0))); // NOPMD
  }

  /**
   * Test method for {@link PyShort#value()}.
   */
  @Test
  public void testValueOne()
  {
    final PyFactory.PyShortBuilder builder = getPyFactory().getPyShortBuilder();

    builder.value((short) 1); // NOPMD

    final PyShort testSubject = builder.build();

    assertThat(testSubject, not(nullValue()));
    assertThat(testSubject.value(), equalTo(((short) 1))); // NOPMD
    assertThat(testSubject.toString(), equalTo(Short.toString((short) 1))); // NOPMD
  }

  /**
   * Test method for {@link PyShort#value()}.
   */
  @Test
  public void testValueTwo()
  {
    final PyFactory.PyShortBuilder builder = getPyFactory().getPyShortBuilder();

    builder.value((short) 2); // NOPMD

    final PyShort testSubject = builder.build();

    assertThat(testSubject, not(nullValue()));
    assertThat(testSubject.value(), equalTo((short) 2)); // NOPMD
    assertThat(testSubject.toString(), equalTo(Short.toString((short) 2))); // NOPMD
  }

  /**
   * Test method for {@link PyShort#hashCode()}.
   */
  @Test
  public void testHashCode()
  {
    final PyFactory.PyShortBuilder builder = getPyFactory().getPyShortBuilder();

    builder.value((short) 1); //NOPMD

    final PyShort testSubject11 = builder.build();
    final PyShort testSubject12 = builder.build();

    builder.value((short) 2); //NOPMD

    final PyShort testSubject21 = builder.build();
    final PyShort testSubject22 = builder.build();

    assertThat(testSubject11.hashCode(), equalTo(testSubject12.hashCode())); //NOPMD
    assertThat(testSubject21.hashCode(), equalTo(testSubject22.hashCode())); //NOPMD

    assertThat(testSubject11.hashCode(), not(equalTo(testSubject22.hashCode())));
  }

  /**
   * Test method for {@link PyShort#getPyType()}.
   */
  @Test
  public void testGetPyType()
  {
    final PyFactory.PyShortBuilder builder = getPyFactory().getPyShortBuilder();

    final PyShort testSubject = builder.build();

    assertThat(testSubject, not(nullValue()));
    assertThat(testSubject.getPyType(), equalTo(PyBase.PyType.SHORT));
    assertThat(testSubject.isShort(), not(false));
    assertThat(testSubject.asShort(), not(nullValue()));
  }

  /**
   * Test method for {@link PyShort#equals()}.
   */
  @Test
  public void testEquals()
  {
    final PyFactory.PyShortBuilder builder = getPyFactory().getPyShortBuilder();
    final PyFactory.PyNoneBuilder builderNone = getPyFactory()
        .getPyNoneBuilder();

    builder.value((short) 1); //NOPMD

    final PyNone none = builderNone.build();

    final PyShort testSubject11 = builder.build();
    final PyShort testSubject12 = builder.build();

    builder.value((short) 2); //NOPMD

    final PyShort testSubject21 = builder.build();
    final PyShort testSubject22 = builder.build();

    assertThat(testSubject11, equalTo(testSubject12));
    assertThat(testSubject21, equalTo(testSubject22));

    assertThat(testSubject11, not(equalTo(testSubject22)));

    assertThat(((PyBase) testSubject11), not(equalTo(((PyBase) none))));
  }

  /**
   * Test method for {@link PyShort#accept(PyVisitor)}.
   */
  @Test
  public void testAccept()
  {
    final PyFactory.PyShortBuilder builder = getPyFactory().getPyShortBuilder();

    final PyShort testSubject = builder.build();

    assertThat(testSubject, not(nullValue()));

    final PyVisitor visitor = new TestVisitor(testSubject);

    testSubject.accept(visitor);
  }

  /**
   * Test method for {@link PyShort#compareTo(PyBase)}.
   */
  @Test
  public void testCompareTo()
  {
    final PyFactory.PyShortBuilder builder = getPyFactory().getPyShortBuilder();
    final PyFactory.PyNoneBuilder builderNone = getPyFactory()
        .getPyNoneBuilder();

    builder.value((short) 1); //NOPMD

    final PyNone none = builderNone.build();

    final PyShort testSubject11 = builder.build();
    final PyShort testSubject12 = builder.build();

    builder.value((short) 2); //NOPMD

    final PyShort testSubject21 = builder.build();
    final PyShort testSubject22 = builder.build();

    assertThat(((PyBase) testSubject11),
        comparesEqualTo((PyBase) testSubject12));
    assertThat(((PyBase) testSubject21),
        comparesEqualTo((PyBase) testSubject22));

    assertThat(((PyBase) testSubject11), lessThan((PyBase) testSubject21));
    assertThat(((PyBase) testSubject21), greaterThan((PyBase) testSubject11));

    assertThat(((PyBase) testSubject11), not(comparesEqualTo(((PyBase) none))));
  }

}


text:
package com.oukingtim.util;

/**
 * Created by oukingtim
 */
public final class Constants {

    public static final String SPRING_PROFILE_DEVELOPMENT = "dev";

}


text:
package net.happybrackets.device;

import net.happybrackets.device.config.DeviceConfig;
import net.happybrackets.core.config.LoadableConfig;

public class ManagerAgent {

	public static void main(String[] args) {
		DeviceConfig env = new DeviceConfig();
		env = LoadableConfig.load("config/device-config.json", env);
//		System.out.println("Device Manager Agent Started as: " + env.getMyHostName());
		System.out.println("Listening for Controller...");
		System.out.println("Found controller on host: " + env.getControllerHostname());
		System.out.println("Requesting configuration settings from controller...");
		System.out.println("Device Manager Agent Exiting");
	}

}