text:
half _cl_hypot(half x0, half x1)
{
  vecmathlib::realvec<half,1> y0 = bitcast<half,vecmathlib::realvec<half,1> >(x0);
  vecmathlib::realvec<half,1> y1 = bitcast<half,vecmathlib::realvec<half,1> >(x1);
  vecmathlib::realvec<half,1> r = vecmathlib::hypot(y0, y1);
  return bitcast<vecmathlib::realvec<half,1>,half>((r));
}
#elif ! defined POCL_VECMATHLIB_BUILTIN
// Implement hypot by calling libm
half _cl_hypot(half x0, half x1)
{
  vecmathlib::realpseudovec<half,1> y0 = x0;
  vecmathlib::realpseudovec<half,1> y1 = x1;
  vecmathlib::realpseudovec<half,1> r = hypot(y0, y1);
  return (r)[0];
}
#else
// Implement hypot by calling builtin
half _cl_hypot(half x0, half x1)
{
  vecmathlib::realbuiltinvec<half,1> y0 = x0;
  vecmathlib::realbuiltinvec<half,1> y1 = x1;
  vecmathlib::realbuiltinvec<half,1> r = hypot(y0, y1);
  return (r)[0];
}
#endif

// hypot: VF=half2
#if defined VECMATHLIB_HAVE_VEC_HALF_2 && ! defined POCL_VECMATHLIB_BUILTIN
// Implement hypot by calling vecmathlib
half2 _cl_hypot(half2 x0, half2 x1)
{
  vecmathlib::realvec<half,2> y0 = bitcast<half2,vecmathlib::realvec<half,2> >(x0);
  vecmathlib::realvec<half,2> y1 = bitcast<half2,vecmathlib::realvec<half,2> >(x1);
  vecmathlib::realvec<half,2> r = vecmathlib::hypot(y0, y1);
  return bitcast<vecmathlib::realvec<half,2>,half2>((r));
}
#elif (defined VECMATHLIB_HAVE_VEC_HALF_4 || defined VECMATHLIB_HAVE_VEC_HALF_8 || defined VECMATHLIB_HAVE_VEC_HALF_16) && ! defined POCL_VECMATHLIB_BUILTIN
// Implement hypot by using a larger vector size
half4 _cl_hypot(half4, half4);
half2 _cl_hypot(half2 x0, half2 x1)
{
  half4 y0 = bitcast<half2,half4>(x0);
  half4 y1 = bitcast<half2,half4>(x1);
  half4 r = _cl_hypot(y0, y1);
  return bitcast<half4,half2>(r);
}
#else
// Implement hypot by splitting into a smaller vector size
half _cl_hypot(half, half);
half2 _cl_hypot(half2 x0, half2 x1)
{
  pair_half y0 = bitcast<half2,pair_half>(x0);
  pair_half y1 = bitcast<half2,pair_half>(x1);
  pair_half r;
  r.lo = _cl_hypot(y0.lo, y1.lo);
  r.hi = _cl_hypot(y0.hi, y1.hi);
  pocl_static_assert(sizeof(pair_half) == sizeof(half2));
  return bitcast<pair_half,half2>(r);
}
#endif

// hypot: VF=half3
#if defined VECMATHLIB_HAVE_VEC_HALF_3 && ! defined POCL_VECMATHLIB_BUILTIN
// Implement hypot by calling vecmathlib
half3 _cl_hypot(half3 x0, half3 x1)
{
  vecmathlib::realvec<half,3> y0 = bitcast<half3,vecmathlib::realvec<half,3> >(x0);
  vecmathlib::realvec<half,3> y1 = bitcast<half3,vecmathlib::realvec<half,3> >(x1);
  vecmathlib::realvec<half,3> r = vecmathlib::hypot(y0, y1);
  return bitcast<vecmathlib::realvec<half,3>,half3>((r));
}
#elif (defined VECMATHLIB_HAVE_VEC_HALF_4 || defined VECMATHLIB_HAVE_VEC_HALF_8 || defined VECMATHLIB_HAVE_VEC_HALF_16) && ! defined POCL_VECMATHLIB_BUILTIN
// Implement hypot by using a larger vector size
half4 _cl_hypot(half4, half4);
half3 _cl_hypot(half3 x0, half3 x1)
{
  half4 y0 = bitcast<half3,half4>(x0);
  half4 y1 = bitcast<half3,half4>(x1);
  half4 r = _cl_hypot(y0, y1);
  return bitcast<half4,half3>(r);
}
#else
// Implement hypot by splitting into a smaller vector size
half2 _cl_hypot(half2, half2);
half3 _cl_hypot(half3 x0, half3 x1)
{
  pair_half2 y0 = bitcast<half3,pair_half2>(x0);
  pair_half2 y1 = bitcast<half3,pair_half2>(x1);
  pair_half2 r;
  r.lo = _cl_hypot(y0.lo, y1.lo);
  r.hi = _cl_hypot(y0.hi, y1.hi);
  pocl_static_assert(sizeof(pair_half2) == sizeof(half3));
  return bitcast<pair_half2,half3>(r);
}
#endif

// hypot: VF=half4
#if defined VECMATHLIB_HAVE_VEC_HALF_4 && ! defined POCL_VECMATHLIB_BUILTIN
// Implement hypot by calling vecmathlib
half4 _cl_hypot(half4 x0, half4 x1)
{
  vecmathlib::realvec<half,4> y0 = bitcast<half4,vecmathlib::realvec<half,4> >(x0);
  vecmathlib::realvec<half,4> y1 = bitcast<half4,vecmathlib::realvec<half,4> >(x1);
  vecmathlib::realvec<half,4> r = vecmathlib::hypot(y0, y1);
  return bitcast<vecmathlib::realvec<half,4>,half4>((r));
}
#elif (defined VECMATHLIB_HAVE_VEC_HALF_8 || defined VECMATHLIB_HAVE_VEC_HALF_16) && ! defined POCL_VECMATHLIB_BUILTIN
// Implement hypot by using a larger vector size
half8 _cl_hypot(half8, half8);
half4 _cl_hypot(half4 x0, half4 x1)
{
  half8 y0 = bitcast<half4,half8>(x0);
  half8 y1 = bitcast<half4,half8>(x1);
  half8 r = _cl_hypot(y0, y1);
  return bitcast<half8,half4>(r);
}
#else
// Implement hypot by splitting into a smaller vector size
half2 _cl_hypot(half2, half2);
half4 _cl_hypot(half4 x0, half4 x1)
{
  pair_half2 y0 = bitcast<half4,pair_half2>(x0);
  pair_half2 y1 = bitcast<half4,pair_half2>(x1);
  pair_half2 r;
  r.lo = _cl_hypot(y0.lo, y1.lo);
  r.hi = _cl_hypot(y0.hi, y1.hi);
  pocl_static_assert(sizeof(pair_half2) == sizeof(half4));
  return bitcast<pair_half2,half4>(r);
}
#endif

// hypot: VF=half8
#if defined VECMATHLIB_HAVE_VEC_HALF_8 && ! defined POCL_VECMATHLIB_BUILTIN
// Implement hypot by calling vecmathlib
half8 _cl_hypot(half8 x0, half8 x1)
{
  vecmathlib::realvec<half,8> y0 = bitcast<half8,vecmathlib::realvec<half,8> >(x0);
  vecmathlib::realvec<half,8> y1 = bitcast<half8,vecmathlib::realvec<half,8> >(x1);
  vecmathlib::realvec<half,8> r = vecmathlib::hypot(y0, y1);
  return bitcast<vecmathlib::realvec<half,8>,half8>((r));
}
#elif (defined VECMATHLIB_HAVE_VEC_HALF_16) && ! defined POCL_VECMATHLIB_BUILTIN
// Implement hypot by using a larger vector size
half16 _cl_hypot(half16, half16);
half8 _cl_hypot(half8 x0, half8 x1)
{
  half16 y0 = bitcast<half8,half16>(x0);
  half16 y1 = bitcast<half8,half16>(x1);
  half16 r = _cl_hypot(y0, y1);
  return bitcast<half16,half8>(r);
}
#else
// Implement hypot by splitting into a smaller vector size
half4 _cl_hypot(half4, half4);
half8 _cl_hypot(half8 x0, half8 x1)
{
  pair_half4 y0 = bitcast<half8,pair_half4>(x0);
  pair_half4 y1 = bitcast<half8,pair_half4>(x1);
  pair_half4 r;
  r.lo = _cl_hypot(y0.lo, y1.lo);
  r.hi = _cl_hypot(y0.hi, y1.hi);
  pocl_static_assert(sizeof(pair_half4) == sizeof(half8));
  return bitcast<pair_half4,half8>(r);
}
#endif

// hypot: VF=half16
#if defined VECMATHLIB_HAVE_VEC_HALF_16 && ! defined POCL_VECMATHLIB_BUILTIN
// Implement hypot by calling vecmathlib
half16 _cl_hypot(half16 x0, half16 x1)
{
  vecmathlib::realvec<half,16> y0 = bitcast<half16,vecmathlib::realvec<half,16> >(x0);
  vecmathlib::realvec<half,16> y1 = bitcast<half16,vecmathlib::realvec<half,16> >(x1);
  vecmathlib::realvec<half,16> r = vecmathlib::hypot(y0, y1);
  return bitcast<vecmathlib::realvec<half,16>,half16>((r));
}
#else
// Implement hypot by splitting into a smaller vector size
half8 _cl_hypot(half8, half8);
half16 _cl_hypot(half16 x0, half16 x1)
{
  pair_half8 y0 = bitcast<half16,pair_half8>(x0);
  pair_half8 y1 = bitcast<half16,pair_half8>(x1);
  pair_half8 r;
  r.lo = _cl_hypot(y0.lo, y1.lo);
  r.hi = _cl_hypot(y0.hi, y1.hi);
  pocl_static_assert(sizeof(pair_half8) == sizeof(half16));
  return bitcast<pair_half8,half16>(r);
}
#endif

#endif // #ifdef cl_khr_fp16

// hypot: VF=float
#if defined VECMATHLIB_HAVE_VEC_FLOAT_1 && ! defined POCL_VECMATHLIB_BUILTIN
// Implement hypot by calling vecmathlib
float _cl_hypot(float x0, float x1)
{
  vecmathlib::realvec<float,1> y0 = bitcast<float,vecmathlib::realvec<float,1> >(x0);
  vecmathlib::realvec<float,1> y1 = bitcast<float,vecmathlib::realvec<float,1> >(x1);
  vecmathlib::realvec<float,1> r = vecmathlib::hypot(y0, y1);
  return bitcast<vecmathlib::realvec<float,1>,float>((r));
}
#elif ! defined POCL_VECMATHLIB_BUILTIN
// Implement hypot by calling libm
float _cl_hypot(float x0, float x1)
{
  vecmathlib::realpseudovec<float,1> y0 = x0;
  vecmathlib::realpseudovec<float,1> y1 = x1;
  vecmathlib::realpseudovec<float,1> r = hypot(y0, y1);
  return (r)[0];
}
#else
// Implement hypot by calling builtin
float _cl_hypot(float x0, float x1)
{
  vecmathlib::realbuiltinvec<float,1> y0 = x0;
  vecmathlib::realbuiltinvec<float,1> y1 = x1;
  vecmathlib::realbuiltinvec<float,1> r = hypot(y0, y1);
  return (r)[0];
}
#endif

// hypot: VF=float2
#if defined VECMATHLIB_HAVE_VEC_FLOAT_2 && ! defined POCL_VECMATHLIB_BUILTIN
// Implement hypot by calling vecmathlib
float2 _cl_hypot(float2 x0, float2 x1)
{
  vecmathlib::realvec<float,2> y0 = bitcast<float2,vecmathlib::realvec<float,2> >(x0);
  vecmathlib::realvec<float,2> y1 = bitcast<float2,vecmathlib::realvec<float,2> >(x1);
  vecmathlib::realvec<float,2> r = vecmathlib::hypot(y0, y1);
  return bitcast<vecmathlib::realvec<float,2>,float2>((r));
}
#elif (defined VECMATHLIB_HAVE_VEC_FLOAT_4 || defined VECMATHLIB_HAVE_VEC_FLOAT_8 || defined VECMATHLIB_HAVE_VEC_FLOAT_16) && ! defined POCL_VECMATHLIB_BUILTIN
// Implement hypot by using a larger vector size
float4 _cl_hypot(float4, float4);
float2 _cl_hypot(float2 x0, float2 x1)
{
  float4 y0 = bitcast<float2,float4>(x0);
  float4 y1 = bitcast<float2,float4>(x1);
  float4 r = _cl_hypot(y0, y1);
  return bitcast<float4,float2>(r);
}
#else
// Implement hypot by splitting into a smaller vector size
float _cl_hypot(float, float);
float2 _cl_hypot(float2 x0, float2 x1)
{
  pair_float y0 = bitcast<float2,pair_float>(x0);
  pair_float y1 = bitcast<float2,pair_float>(x1);
  pair_float r;
  r.lo = _cl_hypot(y0.lo, y1.lo);
  r.hi = _cl_hypot(y0.hi, y1.hi);
  pocl_static_assert(sizeof(pair_float) == sizeof(float2));
  return bitcast<pair_float,float2>(r);
}
#endif

// hypot: VF=float3
#if defined VECMATHLIB_HAVE_VEC_FLOAT_3 && ! defined POCL_VECMATHLIB_BUILTIN
// Implement hypot by calling vecmathlib
float3 _cl_hypot(float3 x0, float3 x1)
{
  vecmathlib::realvec<float,3> y0 = bitcast<float3,vecmathlib::realvec<float,3> >(x0);
  vecmathlib::realvec<float,3> y1 = bitcast<float3,vecmathlib::realvec<float,3> >(x1);
  vecmathlib::realvec<float,3> r = vecmathlib::hypot(y0, y1);
  return bitcast<vecmathlib::realvec<float,3>,float3>((r));
}
#elif (defined VECMATHLIB_HAVE_VEC_FLOAT_4 || defined VECMATHLIB_HAVE_VEC_FLOAT_8 || defined VECMATHLIB_HAVE_VEC_FLOAT_16) && ! defined POCL_VECMATHLIB_BUILTIN
// Implement hypot by using a larger vector size
float4 _cl_hypot(float4, float4);
float3 _cl_hypot(float3 x0, float3 x1)
{
  float4 y0 = bitcast<float3,float4>(x0);
  float4 y1 = bitcast<float3,float4>(x1);
  float4 r = _cl_hypot(y0, y1);
  return bitcast<float4,float3>(r);
}
#else
// Implement hypot by splitting into a smaller vector size
float2 _cl_hypot(float2, float2);
float3 _cl_hypot(float3 x0, float3 x1)
{
  pair_float2 y0 = bitcast<float3,pair_float2>(x0);
  pair_float2 y1 = bitcast<float3,pair_float2>(x1);
  pair_float2 r;
  r.lo = _cl_hypot(y0.lo, y1.lo);
  r.hi = _cl_hypot(y0.hi, y1.hi);
  pocl_static_assert(sizeof(pair_float2) == sizeof(float3));
  return bitcast<pair_float2,float3>(r);
}
#endif

// hypot: VF=float4
#if defined VECMATHLIB_HAVE_VEC_FLOAT_4 && ! defined POCL_VECMATHLIB_BUILTIN
// Implement hypot by calling vecmathlib
float4 _cl_hypot(float4 x0, float4 x1)
{
  vecmathlib::realvec<float,4> y0 = bitcast<float4,vecmathlib::realvec<float,4> >(x0);
  vecmathlib::realvec<float,4> y1 = bitcast<float4,vecmathlib::realvec<float,4> >(x1);
  vecmathlib::realvec<float,4> r = vecmathlib::hypot(y0, y1);
  return bitcast<vecmathlib::realvec<float,4>,float4>((r));
}
#elif (defined VECMATHLIB_HAVE_VEC_FLOAT_8 || defined VECMATHLIB_HAVE_VEC_FLOAT_16) && ! defined POCL_VECMATHLIB_BUILTIN
// Implement hypot by using a larger vector size
float8 _cl_hypot(float8, float8);
float4 _cl_hypot(float4 x0, float4 x1)
{
  float8 y0 = bitcast<float4,float8>(x0);
  float8 y1 = bitcast<float4,float8>(x1);
  float8 r = _cl_hypot(y0, y1);
  return bitcast<float8,float4>(r);
}
#else
// Implement hypot by splitting into a smaller vector size
float2 _cl_hypot(float2, float2);
float4 _cl_hypot(float4 x0, float4 x1)
{
  pair_float2 y0 = bitcast<float4,pair_float2>(x0);
  pair_float2 y1 = bitcast<float4,pair_float2>(x1);
  pair_float2 r;
  r.lo = _cl_hypot(y0.lo, y1.lo);
  r.hi = _cl_hypot(y0.hi, y1.hi);
  pocl_static_assert(sizeof(pair_float2) == sizeof(float4));
  return bitcast<pair_float2,float4>(r);
}
#endif

// hypot: VF=float8
#if defined VECMATHLIB_HAVE_VEC_FLOAT_8 && ! defined POCL_VECMATHLIB_BUILTIN
// Implement hypot by calling vecmathlib
float8 _cl_hypot(float8 x0, float8 x1)
{
  vecmathlib::realvec<float,8> y0 = bitcast<float8,vecmathlib::realvec<float,8> >(x0);
  vecmathlib::realvec<float,8> y1 = bitcast<float8,vecmathlib::realvec<float,8> >(x1);
  vecmathlib::realvec<float,8> r = vecmathlib::hypot(y0, y1);
  return bitcast<vecmathlib::realvec<float,8>,float8>((r));
}
#elif (defined VECMATHLIB_HAVE_VEC_FLOAT_16) && ! defined POCL_VECMATHLIB_BUILTIN
// Implement hypot by using a larger vector size
float16 _cl_hypot(float16, float16);
float8 _cl_hypot(float8 x0, float8 x1)
{
  float16 y0 = bitcast<float8,float16>(x0);
  float16 y1 = bitcast<float8,float16>(x1);
  float16 r = _cl_hypot(y0, y1);
  return bitcast<float16,float8>(r);
}
#else
// Implement hypot by splitting into a smaller vector size
float4 _cl_hypot(float4, float4);
float8 _cl_hypot(float8 x0, float8 x1)
{
  pair_float4 y0 = bitcast<float8,pair_float4>(x0);
  pair_float4 y1 = bitcast<float8,pair_float4>(x1);
  pair_float4 r;
  r.lo = _cl_hypot(y0.lo, y1.lo);
  r.hi = _cl_hypot(y0.hi, y1.hi);
  pocl_static_assert(sizeof(pair_float4) == sizeof(float8));
  return bitcast<pair_float4,float8>(r);
}
#endif

// hypot: VF=float16
#if defined VECMATHLIB_HAVE_VEC_FLOAT_16 && ! defined POCL_VECMATHLIB_BUILTIN
// Implement hypot by calling vecmathlib
float16 _cl_hypot(float16 x0, float16 x1)
{
  vecmathlib::realvec<float,16> y0 = bitcast<float16,vecmathlib::realvec<float,16> >(x0);
  vecmathlib::realvec<float,16> y1 = bitcast<float16,vecmathlib::realvec<float,16> >(x1);
  vecmathlib::realvec<float,16> r = vecmathlib::hypot(y0, y1);
  return bitcast<vecmathlib::realvec<float,16>,float16>((r));
}
#else
// Implement hypot by splitting into a smaller vector size
float8 _cl_hypot(float8, float8);
float16 _cl_hypot(float16 x0, float16 x1)
{
  pair_float8 y0 = bitcast<float16,pair_float8>(x0);
  pair_float8 y1 = bitcast<float16,pair_float8>(x1);
  pair_float8 r;
  r.lo = _cl_hypot(y0.lo, y1.lo);
  r.hi = _cl_hypot(y0.hi, y1.hi);
  pocl_static_assert(sizeof(pair_float8) == sizeof(float16));
  return bitcast<pair_float8,float16>(r);
}
#endif

#ifdef cl_khr_fp64

// hypot: VF=double
#if defined VECMATHLIB_HAVE_VEC_DOUBLE_1 && ! defined POCL_VECMATHLIB_BUILTIN
// Implement hypot by calling vecmathlib
double _cl_hypot(double x0, double x1)
{
  vecmathlib::realvec<double,1> y0 = bitcast<double,vecmathlib::realvec<double,1> >(x0);
  vecmathlib::realvec<double,1> y1 = bitcast<double,vecmathlib::realvec<double,1> >(x1);
  vecmathlib::realvec<double,1> r = vecmathlib::hypot(y0, y1);
  return bitcast<vecmathlib::realvec<double,1>,double>((r));
}
#elif ! defined POCL_VECMATHLIB_BUILTIN
// Implement hypot by calling libm
double _cl_hypot(double x0, double x1)
{
  vecmathlib::realpseudovec<double,1> y0 = x0;
  vecmathlib::realpseudovec<double,1> y1 = x1;
  vecmathlib::realpseudovec<double,1> r = hypot(y0, y1);
  return (r)[0];
}
#else
// Implement hypot by calling builtin
double _cl_hypot(double x0, double x1)
{
  vecmathlib::realbuiltinvec<double,1> y0 = x0;
  vecmathlib::realbuiltinvec<double,1> y1 = x1;
  vecmathlib::realbuiltinvec<double,1> r = hypot(y0, y1);
  return (r)[0];
}
#endif

// hypot: VF=double2
#if defined VECMATHLIB_HAVE_VEC_DOUBLE_2 && ! defined POCL_VECMATHLIB_BUILTIN
// Implement hypot by calling vecmathlib
double2 _cl_hypot(double2 x0, double2 x1)
{
  vecmathlib::realvec<double,2> y0 = bitcast<double2,vecmathlib::realvec<double,2> >(x0);
  vecmathlib::realvec<double,2> y1 = bitcast<double2,vecmathlib::realvec<double,2> >(x1);
  vecmathlib::realvec<double,2> r = vecmathlib::hypot(y0, y1);
  return bitcast<vecmathlib::realvec<double,2>,double2>((r));
}
#elif (defined VECMATHLIB_HAVE_VEC_DOUBLE_4 || defined VECMATHLIB_HAVE_VEC_DOUBLE_8 || defined VECMATHLIB_HAVE_VEC_DOUBLE_16) && ! defined POCL_VECMATHLIB_BUILTIN
// Implement hypot by using a larger vector size
double4 _cl_hypot(double4, double4);
double2 _cl_hypot(double2 x0, double2 x1)
{
  double4 y0 = bitcast<double2,double4>(x0);
  double4 y1 = bitcast<double2,double4>(x1);
  double4 r = _cl_hypot(y0, y1);
  return bitcast<double4,double2>(r);
}
#else
// Implement hypot by splitting into a smaller vector size
double _cl_hypot(double, double);
double2 _cl_hypot(double2 x0, double2 x1)
{
  pair_double y0 = bitcast<double2,pair_double>(x0);
  pair_double y1 = bitcast<double2,pair_double>(x1);
  pair_double r;
  r.lo = _cl_hypot(y0.lo, y1.lo);
  r.hi = _cl_hypot(y0.hi, y1.hi);
  pocl_static_assert(sizeof(pair_double) == sizeof(double2));
  return bitcast<pair_double,double2>(r);
}
#endif

// hypot: VF=double3
#if defined VECMATHLIB_HAVE_VEC_DOUBLE_3 && ! defined POCL_VECMATHLIB_BUILTIN
// Implement hypot by calling vecmathlib
double3 _cl_hypot(double3 x0, double3 x1)
{
  vecmathlib::realvec<double,3> y0 = bitcast<double3,vecmathlib::realvec<double,3> >(x0);
  vecmathlib::realvec<double,3> y1 = bitcast<double3,vecmathlib::realvec<double,3> >(x1);
  vecmathlib::realvec<double,3> r = vecmathlib::hypot(y0, y1);
  return bitcast<vecmathlib::realvec<double,3>,double3>((r));
}
#elif (defined VECMATHLIB_HAVE_VEC_DOUBLE_4 || defined VECMATHLIB_HAVE_VEC_DOUBLE_8 || defined VECMATHLIB_HAVE_VEC_DOUBLE_16) && ! defined POCL_VECMATHLIB_BUILTIN
// Implement hypot by using a larger vector size
double4 _cl_hypot(double4, double4);
double3 _cl_hypot(double3 x0, double3 x1)
{
  double4 y0 = bitcast<double3,double4>(x0);
  double4 y1 = bitcast<double3,double4>(x1);
  double4 r = _cl_hypot(y0, y1);
  return bitcast<double4,double3>(r);
}
#else
// Implement hypot by splitting into a smaller vector size
double2 _cl_hypot(double2, double2);
double3 _cl_hypot(double3 x0, double3 x1)
{
  pair_double2 y0 = bitcast<double3,pair_double2>(x0);
  pair_double2 y1 = bitcast<double3,pair_double2>(x1);
  pair_double2 r;
  r.lo = _cl_hypot(y0.lo, y1.lo);
  r.hi = _cl_hypot(y0.hi, y1.hi);
  pocl_static_assert(sizeof(pair_double2) == sizeof(double3));
  return bitcast<pair_double2,double3>(r);
}
#endif

// hypot: VF=double4
#if defined VECMATHLIB_HAVE_VEC_DOUBLE_4 && ! defined POCL_VECMATHLIB_BUILTIN
// Implement hypot by calling vecmathlib
double4 _cl_hypot(double4 x0, double4 x1)
{
  vecmathlib::realvec<double,4> y0 = bitcast<double4,vecmathlib::realvec<double,4> >(x0);
  vecmathlib::realvec<double,4> y1 = bitcast<double4,vecmathlib::realvec<double,4> >(x1);
  vecmathlib::realvec<double,4> r = vecmathlib::hypot(y0, y1);
  return bitcast<vecmathlib::realvec<double,4>,double4>((r));
}
#elif (defined VECMATHLIB_HAVE_VEC_DOUBLE_8 || defined VECMATHLIB_HAVE_VEC_DOUBLE_16) && ! defined POCL_VECMATHLIB_BUILTIN
// Implement hypot by using a larger vector size
double8 _cl_hypot(double8, double8);
double4 _cl_hypot(double4 x0, double4 x1)
{
  double8 y0 = bitcast<double4,double8>(x0);
  double8 y1 = bitcast<double4,double8>(x1);
  double8 r = _cl_hypot(y0, y1);
  return bitcast<double8,double4>(r);
}
#else
// Implement hypot by splitting into a smaller vector size
double2 _cl_hypot(double2, double2);
double4 _cl_hypot(double4 x0, double4 x1)
{
  pair_double2 y0 = bitcast<double4,pair_double2>(x0);
  pair_double2 y1 = bitcast<double4,pair_double2>(x1);
  pair_double2 r;
  r.lo = _cl_hypot(y0.lo, y1.lo);
  r.hi = _cl_hypot(y0.hi, y1.hi);
  pocl_static_assert(sizeof(pair_double2) == sizeof(double4));
  return bitcast<pair_double2,double4>(r);
}
#endif

// hypot: VF=double8
#if defined VECMATHLIB_HAVE_VEC_DOUBLE_8 && ! defined POCL_VECMATHLIB_BUILTIN
// Implement hypot by calling vecmathlib
double8 _cl_hypot(double8 x0, double8 x1)
{
  vecmathlib::realvec<double,8> y0 = bitcast<double8,vecmathlib::realvec<double,8> >(x0);
  vecmathlib::realvec<double,8> y1 = bitcast<double8,vecmathlib::realvec<double,8> >(x1);
  vecmathlib::realvec<double,8> r = vecmathlib::hypot(y0, y1);
  return bitcast<vecmathlib::realvec<double,8>,double8>((r));
}
#elif (defined VECMATHLIB_HAVE_VEC_DOUBLE_16) && ! defined POCL_VECMATHLIB_BUILTIN
// Implement hypot by using a larger vector size
double16 _cl_hypot(double16, double16);
double8 _cl_hypot(double8 x0, double8 x1)
{
  double16 y0 = bitcast<double8,double16>(x0);
  double16 y1 = bitcast<double8,double16>(x1);
  double16 r = _cl_hypot(y0, y1);
  return bitcast<double16,double8>(r);
}
#else
// Implement hypot by splitting into a smaller vector size
double4 _cl_hypot(double4, double4);
double8 _cl_hypot(double8 x0, double8 x1)
{
  pair_double4 y0 = bitcast<double8,pair_double4>(x0);
  pair_double4 y1 = bitcast<double8,pair_double4>(x1);
  pair_double4 r;
  r.lo = _cl_hypot(y0.lo, y1.lo);
  r.hi = _cl_hypot(y0.hi, y1.hi);
  pocl_static_assert(sizeof(pair_double4) == sizeof(double8));
  return bitcast<pair_double4,double8>(r);
}
#endif

// hypot: VF=double16
#if defined VECMATHLIB_HAVE_VEC_DOUBLE_16 && ! defined POCL_VECMATHLIB_BUILTIN
// Implement hypot by calling vecmathlib
double16 _cl_hypot(double16 x0, double16 x1)
{
  vecmathlib::realvec<double,16> y0 = bitcast<double16,vecmathlib::realvec<double,16> >(x0);
  vecmathlib::realvec<double,16> y1 = bitcast<double16,vecmathlib::realvec<double,16> >(x1);
  vecmathlib::realvec<double,16> r = vecmathlib::hypot(y0, y1);
  return bitcast<vecmathlib::realvec<double,16>,double16>((r));
}
#else
// Implement hypot by splitting into a smaller vector size
double8 _cl_hypot(double8, double8);
double16 _cl_hypot(double16 x0, double16 x1)
{
  pair_double8 y0 = bitcast<double16,pair_double8>(x0);
  pair_double8 y1 = bitcast<double16,pair_double8>(x1);
  pair_double8 r;
  r.lo = _cl_hypot(y0.lo, y1.lo);
  r.hi = _cl_hypot(y0.hi, y1.hi);
  pocl_static_assert(sizeof(pair_double8) == sizeof(double16));
  return bitcast<pair_double8,double16>(r);
}
#endif

#endif // #ifdef cl_khr_fp64


text:
package org.apache.camel.reifier;

import java.nio.charset.Charset;
import java.nio.charset.UnsupportedCharsetException;

import org.apache.camel.Processor;
import org.apache.camel.Route;
import org.apache.camel.model.ConvertBodyDefinition;
import org.apache.camel.model.ProcessorDefinition;
import org.apache.camel.processor.ConvertBodyProcessor;

public class ConvertBodyReifier extends ProcessorReifier<ConvertBodyDefinition> {

    public ConvertBodyReifier(Route route, ProcessorDefinition<?> definition) {
        super(route, ConvertBodyDefinition.class.cast(definition));
    }

    @Override
    public Processor createProcessor() throws Exception {
        Class<?> typeClass = parse(Class.class, or(definition.getTypeClass(), parseString(definition.getType())));
        String charset = validateCharset(parseString(definition.getCharset()));
        return new ConvertBodyProcessor(typeClass, charset);
    }

    public static String validateCharset(String charset) throws UnsupportedCharsetException {
        if (charset != null) {
            if (Charset.isSupported(charset)) {
                return Charset.forName(charset).name();
            }
            throw new UnsupportedCharsetException(charset);
        }
        return null;
    }

}

redpajama_set_name: RedPajamaGithub


text:
import os

from watcher import conf

CONF = conf.CONF

def basedir_rel(*args):
    """Return a path relative to $pybasedir."""
    return os.path.join(CONF.pybasedir, *args)

def bindir_rel(*args):
    """Return a path relative to $bindir."""
    return os.path.join(CONF.bindir, *args)

def state_path_rel(*args):
    """Return a path relative to $state_path."""
    return os.path.join(CONF.state_path, *args)


text:
from baremetal_network_provisioning.bnpclient.bnp_client_ext.bnpswitch import (
    _bnp_credential as bnp_credential)
from baremetal_network_provisioning.bnpclient.bnp_client_ext import shell
from baremetal_network_provisioning.tests.unit.bnpclient import test_cli20

import mock
from neutronclient.common import exceptions

import sys

class CLITestV20ExtensionBNPCredentialJSON(test_cli20.CLITestV20Base):

    def setUp(self):
        self._mock_extension_loading()
        super(CLITestV20ExtensionBNPCredentialJSON,
              self).setUp(plurals={'tags': 'tag'})

    def _create_patch(self, name, func=None):
        patcher = mock.patch(name)
        thing = patcher.start()
        self.addCleanup(patcher.stop)
        return thing

    def _mock_extension_loading(self):
        ext_pkg = ('baremetal_network_provisioning.bnpclient.bnp_client_ext'
                   '.shell')
        contrib = self._create_patch(ext_pkg + '.discover_via_entry_points')
        contrib.return_value = [("_bnp_credential",
                                 bnp_credential)]
        return contrib

    def test_ext_cmd_loaded(self):
        """Tests bnpcredential commands loaded."""
        shell.BnpShell('2.0')
        ext_cmd = {
            'credential-list':
            bnp_credential.BnpCredentialList,
            'credential-create':
            bnp_credential.BnpCredentialCreate,
            'credential-delete':
            bnp_credential.BnpCredentialDelete,
            'credential-show':
            bnp_credential.BnpCredentialShow,
            'credential-update':
            bnp_credential.BnpCredentialUpdate}
        self.assertDictContainsSubset(ext_cmd, shell.COMMANDS['2.0'])

    def test_create_bnp_credential_snmpv1(self):
        resource = 'bnp_credential'
        cmd = bnp_credential.BnpCredentialCreate(
            test_cli20.MyApp(sys.stdout), None)
        name = 'bnpCredName'
        myid = 'myid'
        snmpv1 = {'write_community': 'public'}
        position_names = ['name', 'snmpv1']
        position_values = [name, snmpv1]
        args = [name, '--snmpv1', 'write_community=public']
        self._test_create_resource(
            resource, cmd, None, myid, args, position_names, position_values)

    def test_create_bnp_credential_with_mulitple_snmpv1(self):
        resource = 'bnp_credential'
        cmd = bnp_credential.BnpCredentialCreate(
            test_cli20.MyApp(sys.stdout), None)
        name = 'bnpCredName'
        myid = 'myid'
        snmpv1 = {'write_community': 'public'}
        position_names = ['name', 'snmpv1']
        position_values = [name, snmpv1]
        args = [name, '--snmpv1', 'write_community=public',
                '--snmpv1', 'write_community=public']
        self.assertRaises(exceptions.CommandError, self._test_create_resource,
                          resource, cmd, None, myid, args, position_names,
                          position_values)

    def test_create_bnp_credential_snmpv2c(self):
        resource = 'bnp_credential'
        cmd = bnp_credential.BnpCredentialCreate(
            test_cli20.MyApp(sys.stdout), None)
        name = 'bnpCredName'
        myid = 'myid'
        snmpv2c = {'write_community': 'public'}
        position_names = ['name', 'snmpv2c']
        position_values = [name, snmpv2c]
        args = [name, '--snmpv2c', 'write_community=public']
        self._test_create_resource(
            resource, cmd, None, myid, args, position_names, position_values)

    def test_create_bnp_credential_with_multiple_snmpv2c(self):
        resource = 'bnp_credential'
        cmd = bnp_credential.BnpCredentialCreate(
            test_cli20.MyApp(sys.stdout), None)
        name = 'bnpCredName'
        myid = 'myid'
        snmpv2c = {'write_community': 'public'}
        position_names = ['name', 'snmpv2c']
        position_values = [name, snmpv2c]
        args = [name, '--snmpv2c', 'write_community=public',
                '--snmpv2', 'write_community=public']
        self.assertRaises(exceptions.CommandError, self._test_create_resource,
                          resource, cmd, None, myid, args, position_names,
                          position_values)

    def test_create_credential_snmpv3_with_auth_protocol_key(self):
        resource = 'bnp_credential'
        cmd = bnp_credential.BnpCredentialCreate(
            test_cli20.MyApp(sys.stdout), None)
        name = 'bnpCredName'
        myid = 'myid'
        snmpv3 = {'security_name': 'secName',
                  'auth_protocol': 'authProtocol', 'auth_key': 'authKey'}
        position_names = ['name', 'snmpv3']
        position_values = [name, snmpv3]
        args = [name, '--snmpv3',
                'security_name=secName,auth_protocol=authProtocol,'
                'auth_key=authKey']
        self._test_create_resource(
            resource, cmd, None, myid, args, position_names, position_values)

    def test_create_credential_snmpv3_with_priv_protocol_key(self):
        resource = 'bnp_credential'
        cmd = bnp_credential.BnpCredentialCreate(
            test_cli20.MyApp(sys.stdout), None)
        name = 'bnpCredName'
        myid = 'myid'
        snmpv3 = {'security_name': 'secName',
                  'priv_protocol': 'privProtocol', 'priv_key': 'privKey'}
        position_names = ['name', 'snmpv3']
        position_values = [name, snmpv3]
        args = [name, '--snmpv3', 'security_name=secName,'
                'priv_protocol=privProtocol,priv_key=privKey']
        self._test_create_resource(
            resource, cmd, None, myid, args, position_names, position_values)

    def test_create_credential_snmpv3_full(self):
        resource = 'bnp_credential'
        cmd = bnp_credential.BnpCredentialCreate(
            test_cli20.MyApp(sys.stdout), None)
        name = 'bnpCredName'
        myid = 'myid'
        snmpv3 = {'security_name': 'secName', 'auth_protocol': 'authProtocol',
                  'priv_protocol': 'privProtocol', 'priv_key': 'privKey',
                  'auth_key': 'authKey'}
        position_names = ['name', 'snmpv3']
        position_values = [name, snmpv3]
        args = [name, '--snmpv3', 'security_name=secName,'
                'auth_protocol=authProtocol,priv_protocol=privProtocol,'
                'priv_key=privKey,auth_key=authKey']
        self._test_create_resource(
            resource, cmd, None, myid, args, position_names, position_values)

    def test_create_credential_with_multiple_snmpv3(self):
        resource = 'bnp_credential'
        cmd = bnp_credential.BnpCredentialCreate(
            test_cli20.MyApp(sys.stdout), None)
        name = 'bnpCredName'
        myid = 'myid'
        snmpv3 = {'security_name': 'secName',
                  'auth_protocol': 'authProtocol', 'auth_key': 'authKey'}
        position_names = ['name', 'snmpv3']
        position_values = [name, snmpv3]
        args = [name, '--snmpv3',
                'security_name=secName,auth_protocol=authProtocol,'
                'auth_key=authKey', '--snmpv3',
                'security_name=secName,auth_protocol=authProtocol,'
                'auth_key=authKey']
        self.assertRaises(exceptions.CommandError, self._test_create_resource,
                          resource, cmd, None, myid, args, position_names,
                          position_values)

    def test_create_credential_netconf_ssh_with_user_name_password(self):
        resource = 'bnp_credential'
        cmd = bnp_credential.BnpCredentialCreate(
            test_cli20.MyApp(sys.stdout), None)
        name = 'bnpCredName'
        myid = 'myid'
        netconf_ssh = {'user_name': 'userName', 'password': 'Password'}
        position_names = ['name', 'netconf_ssh']
        position_values = [name, netconf_ssh]
        args = [name, '--netconf-ssh', 'user_name=userName,password=Password']
        self._test_create_resource(
            resource, cmd, None, myid, args, position_names, position_values)

    def test_create_credential_netconf_ssh_with_key_path(self):
        resource = 'bnp_credential'
        cmd = bnp_credential.BnpCredentialCreate(
            test_cli20.MyApp(sys.stdout), None)
        name = 'bnpCredName'
        myid = 'myid'
        netconf_ssh = {'key_path': 'KeyPath'}
        position_names = ['name', 'netconf_ssh']
        position_values = [name, netconf_ssh]
        args = [name, '--netconf-ssh', 'key_path=KeyPath']
        self._test_create_resource(
            resource, cmd, None, myid, args, position_names, position_values)

    def test_create_credential_netconf_ssh_full(self):
        resource = 'bnp_credential'
        cmd = bnp_credential.BnpCredentialCreate(
            test_cli20.MyApp(sys.stdout), None)
        name = 'bnpCredName'
        myid = 'myid'
        netconf_ssh = {'user_name': 'userName',
                       'password': 'Password', 'key_path': 'KeyPath'}
        position_names = ['name', 'netconf_ssh']
        position_values = [name, netconf_ssh]
        args = [name, '--netconf-ssh',
                'user_name=userName,password=Password,key_path=KeyPath']
        self._test_create_resource(
            resource, cmd, None, myid, args, position_names, position_values)

    def test_create_credential_with_multiple_netconf_ssh(self):
        resource = 'bnp_credential'
        cmd = bnp_credential.BnpCredentialCreate(
            test_cli20.MyApp(sys.stdout), None)
        name = 'bnpCredName'
        myid = 'myid'
        netconf_ssh = {'user_name': 'userName', 'password': 'Password'}
        position_names = ['name', 'netconf_ssh']
        position_values = [name, netconf_ssh]
        args = [name, '--netconf-ssh', 'user_name=userName,password=Password',
                '--netconf-ssh', 'user_name=userName,password=Password']
        self.assertRaises(exceptions.CommandError, self._test_create_resource,
                          resource, cmd, None, myid, args, position_names,
                          position_values)

    def test_create_credential_netconf_soap_full(self):
        resource = 'bnp_credential'
        cmd = bnp_credential.BnpCredentialCreate(
            test_cli20.MyApp(sys.stdout), None)
        name = 'bnpCredName'
        myid = 'myid'
        netconf_soap = {'user_name': 'userName', 'password': 'Password'}
        position_names = ['name', 'netconf_soap']
        position_values = [name, netconf_soap]
        args = [name, '--netconf-soap', 'user_name=userName,password=Password']
        self._test_create_resource(
            resource, cmd, None, myid, args, position_names, position_values)

    def test_create_credential_with_multiple_netconf_soap(self):
        resource = 'bnp_credential'
        cmd = bnp_credential.BnpCredentialCreate(
            test_cli20.MyApp(sys.stdout), None)
        name = 'bnpCredName'
        myid = 'myid'
        netconf_soap = {'user_name': 'userName', 'password': 'Password'}
        position_names = ['name', 'netconf_soap']
        position_values = [name, netconf_soap]
        args = [name, '--netconf-soap', 'user_name=userName,password=Password',
                '--netconf-soap', 'user_name=userName,password=Password']
        self.assertRaises(exceptions.CommandError, self._test_create_resource,
                          resource, cmd, None, myid, args, position_names,
                          position_values)

    def test_update_credential_snmpv1(self):
        resource = 'bnp_credential'
        cmd = bnp_credential.BnpCredentialUpdate(
            test_cli20.MyApp(sys.stdout), None)
        myid = 'myid'
        args = ['--snmpv1', 'write_community=public',
                '--name', 'bnpCredName', myid]
        updatefields = {'snmpv1': {
            'write_community': 'public'}, 'name': 'bnpCredName'}
        self._test_update_resource(resource, cmd, myid, args, updatefields)

    def test_update_credential_snmpv2c(self):
        resource = 'bnp_credential'
        cmd = bnp_credential.BnpCredentialUpdate(
            test_cli20.MyApp(sys.stdout), None)
        myid = 'myid'
        name = 'bnpCredName'
        args = ['--snmpv2c', 'write_community=public', '--name', name, myid]
        updatefields = {'snmpv2c': {'write_community': 'public'}, 'name': name}
        self._test_update_resource(resource, cmd, myid, args, updatefields)

    def test_update_credential_snmpv3(self):
        resource = 'bnp_credential'
        cmd = bnp_credential.BnpCredentialUpdate(
            test_cli20.MyApp(sys.stdout), None)
        myid = 'myid'
        name = 'bnpCredName'
        args = ['--snmpv3', 'security_name=secName,auth_protocol=authProtocol,'
                'priv_protocol=privProtocol,priv_key=privKey,auth_key=authKey',
                '--name', name, myid]
        snmpv3 = {'security_name': 'secName', 'auth_protocol': 'authProtocol',
                  'priv_protocol': 'privProtocol', 'priv_key': 'privKey',
                  'auth_key': 'authKey'}
        updatefields = {'snmpv3': snmpv3, 'name': name}
        self._test_update_resource(resource, cmd, myid, args, updatefields)

    def test_update_credential_netconf_ssh(self):
        resource = 'bnp_credential'
        cmd = bnp_credential.BnpCredentialUpdate(
            test_cli20.MyApp(sys.stdout), None)
        myid = 'myid'
        name = 'bnpCredName'
        args = ['--netconf-ssh', 'user_name=userName,password=Password,'
                'key_path=KeyPath', '--name', name, myid]
        netconf_ssh = {'user_name': 'userName',
                       'password': 'Password', 'key_path': 'KeyPath'}
        updatefields = {'netconf_ssh': netconf_ssh, 'name': name}
        self._test_update_resource(resource, cmd, myid, args, updatefields)

    def test_update_credential_netconf_soap(self):
        resource = 'bnp_credential'
        cmd = bnp_credential.BnpCredentialUpdate(
            test_cli20.MyApp(sys.stdout), None)
        myid = 'myid'
        name = 'bnpCredName'
        args = ['--netconf-soap', 'user_name=userName,password=Password',
                '--name', name, myid]
        netconf_soap = {'user_name': 'userName', 'password': 'Password'}
        updatefields = {'netconf_soap': netconf_soap, 'name': name}
        self._test_update_resource(resource, cmd, myid, args, updatefields)

    def test_list_credentials(self):
        resources = 'bnp_credentials'
        cmd = bnp_credential.BnpCredentialList(
            test_cli20.MyApp(sys.stdout), None)
        self._test_list_resources(resources, cmd, True)

    def test_list_credentials_pagination(self):
        resources = 'bnp_credentials'
        cmd = bnp_credential.BnpCredentialList(
            test_cli20.MyApp(sys.stdout), None)
        self._test_list_resources_with_pagination(resources, cmd)

    def test_list_credentials_sort(self):
        resources = 'bnp_credentials'
        cmd = bnp_credential.BnpCredentialList(
            test_cli20.MyApp(sys.stdout), None)
        self._test_list_resources(resources, cmd,
                                  sort_key=["name", "id"],
                                  sort_dir=["asc", "desc"])

    def test_list_credentials_limit(self):
        resources = 'bnp_credentials'
        cmd = bnp_credential.BnpCredentialList(
            test_cli20.MyApp(sys.stdout), None)
        self._test_list_resources(resources, cmd, page_size=1000)

    def test_list_credentials_tags(self):
        resources = 'bnp_credentials'
        cmd = bnp_credential.BnpCredentialList(
            test_cli20.MyApp(sys.stdout), None)
        self._test_list_resources(resources, cmd, tags=['a', 'b'])

    def test_list_credentials_detail_tags(self):
        resources = 'bnp_credentials'
        cmd = bnp_credential.BnpCredentialList(
            test_cli20.MyApp(sys.stdout), None)
        self._test_list_resources(resources, cmd, detail=True, tags=['a', 'b'])

    def test_show_credential(self):
        resource = 'bnp_credential'
        cmd = bnp_credential.BnpCredentialShow(
            test_cli20.MyApp(sys.stdout), None)
        args = ['--fields', 'id', '--fields', 'name', self.test_id]
        self._test_show_resource(resource, cmd, self.test_id,
                                 args, ['id', 'name'])

    def test_delete_credential(self):
        resource = 'bnp_credential'
        cmd = bnp_credential.BnpCredentialDelete(
            test_cli20.MyApp(sys.stdout), None)
        myid = 'myid'
        args = [myid]
        self._test_delete_resource(resource, cmd, myid, args)


text:
/// <binding Clean='clean' />

var gulp = require("gulp"),
    rimraf = require("rimraf"),
    fs = require("fs"),
    sourcemaps = require('gulp-sourcemaps'),
    sass = require('gulp-sass');

eval("var project = " + fs.readFileSync("./project.json"));

var paths = {
    bower: "./bower_components/",
    lib: "./" + project.webroot + "/lib/",
    cssFolder: './' + project.webroot + '/css',
    sassFiles: './Assets/Styles/**/*.scss'
};

gulp.task("clean", function (cb) {
  rimraf(paths.lib, cb);
});

gulp.task("copy", ["clean"], function () {
  var bower = {
    "bootstrap": "bootstrap/dist/**/*.{js,map,css,ttf,svg,woff,eot}",
    "bootstrap-touch-carousel": "bootstrap-touch-carousel/dist/**/*.{js,css}",
    "hammer.js": "hammer.js/hammer*.{js,map}",
    "jquery": "jquery/jquery*.{js,map}",
    "jquery-validation": "jquery-validation/jquery.validate.js",
    "jquery-validation-unobtrusive": "jquery-validation-unobtrusive/jquery.validate.unobtrusive.js"
  }

  for (var destinationDir in bower) {
    gulp.src(paths.bower + bower[destinationDir])
      .pipe(gulp.dest(paths.lib + destinationDir));
  }
});

gulp.task('sass', function () {
    gulp.src(paths.sassFiles)
        .pipe(sourcemaps.init())
            .pipe(sass().on('errer', sass.logError))
        .pipe(sourcemaps.write('/maps'))
        .pipe(gulp.dest(paths.cssFolder));
});

gulp.task('watch', ['sass'], function () {
    gulp.watch(paths.sassFiles, ['sass']);
});

gulp.task('default', ['watch']);


text:
namespace SQLLite
{
    using System;
    using System.Data.SQLite;

    /// <summary>
    /// Download and install MySQL database, MySQL Connector/Net (.NET Data Provider for MySQL)
    /// + MySQL Workbench GUI administration tool.
    /// Create a MySQL database to store Books (title, author, publish date and ISBN).
    /// Write methods for listing all books, finding a book by name and adding a book.
    /// </summary>
    public class EntryPoint
    {
        private static SQLiteConnection sqLiteConnection;

        public static void Main()
        {
            var connectionString = "Data Source=C:\\SQLite\\bookstore.sqlite;Version=3;";
            sqLiteConnection = new SQLiteConnection(connectionString);

            sqLiteConnection.Open();
            using (sqLiteConnection)
            {
                // Add books
                AddBook("Pesho", "Gosho", DateTime.Now, 12345679);
                AddBook("Stamat", "Kencho", DateTime.Now, 45645757);
                AddBook("Super Kencho", "I.K.", DateTime.Now, 78978977);
                AddBook("Zadushaam Sa", "Bat Joro", DateTime.Now, 45123423);

                // List all books
                ListAllBooks();

                // Find book by name
                ShowBookByTitle("Zadushaam Sa");

                // Clears the table so i don't have 1231231 "Pesho" titles! :)
                DeleteAllBooks();
            }
        }

        private static void ListAllBooks()
        {
            string sqlCommand = "SELECT * FROM books";
            var commandToExecute = new SQLiteCommand(sqlCommand, sqLiteConnection);
            var reader = commandToExecute.ExecuteReader();

            UseGivenReader(reader);
        }

        private static void ShowBookByTitle(string bookTitle)
        {
            string sqlCommand = "SELECT * FROM books WHERE title LIKE '%" + bookTitle + "%'";
            var commandToExecute = new SQLiteCommand(sqlCommand, sqLiteConnection);
            var reader = commandToExecute.ExecuteReader();

            UseGivenReader(reader);
        }

        private static void AddBook(string title, string author, DateTime publishDate, int isbn)
        {
            string sqlCommand =
                "INSERT INTO books (title, author, publish_date, isbn) " +
                "VALUES (@title, @author, @publishDate, @isbn)";

            var commandToExecute = new SQLiteCommand(sqlCommand, sqLiteConnection);

            commandToExecute.Parameters.AddWithValue("@title", title);
            commandToExecute.Parameters.AddWithValue("@author", author);
            commandToExecute.Parameters.AddWithValue("@publishDate", publishDate);
            commandToExecute.Parameters.AddWithValue("@isbn", isbn);

            commandToExecute.ExecuteNonQuery();
        }

        private static void UseGivenReader(SQLiteDataReader reader)
        {
            using (reader)
            {
                while (reader.Read())
                {
                    string title = (string)reader["title"];
                    string author = (string)reader["author"];

                    Console.WriteLine("Title: {0}\nAuthor:{1}\n", title, author);
                }
            }
        }

        private static void DeleteAllBooks()
        {
            string sqlCommand = "DELETE FROM books";
            var commandToExecute = new SQLiteCommand(sqlCommand, sqLiteConnection);
            commandToExecute.ExecuteNonQuery();
        }
    }
}


text:
local common = require('test_scripts/WebEngine/commonWebEngine')

--[[ Local Variables ]]
local createWindowParams = {
  windowID = 1,
  windowName = "Name",
  type = "WIDGET"
}

local showParams = {
  mainField1 = "MainField1",
  windowID = createWindowParams.windowID,
  templateConfiguration = {
    template = "Template1"
  }
}

local appSessionId = 1
local appHMIType = { "WEB_VIEW" }

--[[ General configuration parameters ]]
config.application1.registerAppInterfaceParams.appHMIType = appHMIType

--[[ Local Functions ]]
local function sendShow()
  local cid = common.getMobileSession():SendRPC("Show", showParams)
  common.getHMIConnection():ExpectRequest("UI.Show")
  :Do(function(_, data)
      common.getHMIConnection():SendResponse(data.id, data.method, "SUCCESS", {})
    end)
  common.getMobileSession():ExpectResponse(cid, { success = true, resultCode = "SUCCESS" })
  common.getMobileSession():ExpectNotification("OnSystemCapabilityUpdated")
  :Times(0)
end

local function sendOnSCU()
  local paramsToSDL = common.getOnSystemCapabilityParams()
  paramsToSDL.appID = common.getHMIAppId()
  common.getHMIConnection():SendNotification("BasicCommunication.OnSystemCapabilityUpdated", paramsToSDL)
  common.getMobileSession():ExpectNotification("OnSystemCapabilityUpdated", common.getOnSystemCapabilityParams())
end

--[[ Scenario ]]
common.Title("Preconditions")
common.Step("Clean environment", common.preconditions)
common.Step("Update WS Server Certificate parameters in smartDeviceLink.ini file", common.commentAllCertInIniFile)
common.Step("Add AppHMIType to preloaded policy table", common.updatePreloadedPT, { appSessionId, appHMIType })
common.Step("Start SDL, HMI", common.startWOdeviceConnect)
common.Step("Connect WebEngine device", common.connectWebEngine, { appSessionId, "WS" })
common.Step("Register App without PTU", common.registerAppWOPTU, { appSessionId })
common.Step("Activate web app", common.activateApp, { appSessionId })
common.Step("Create widget", common.createWindow, { createWindowParams })
common.Step("Activate widget", common.activateWidgetFromNoneToFULL, { createWindowParams.windowID })

common.Title("Test")
common.Step("App sends Show RPC no OnSystemCapabilitiesUpdated notification", sendShow)
common.Step("HMI sends OnSystemCapabilitiesUpdated notification", sendOnSCU)

common.Title("Postconditions")
common.Step("Stop SDL", common.postconditions)


text:
The [Configuration Admin](http://wiki.osgi.org/wiki/Configuration_Admin) helps to manage services' configuration and makes it possible to provide those two separately.
A `ManagedServiceFactory` implementation is provided by this module, so that you can use the Configuration Admin to create process engines.
The factory is registered with the PID `org.camunda.bpm.extension.osgi.configadmin.ManagedProcessEngineFactory`.
You only have to find a way to provide your configuration to the admin. Most OSGi runtimes provide a way to directly add a configuration file. An alternative approach would be to create a configuration bundle which contains the configuration.
The `BundleActivator`could look like this:
```java
public class Activator implements BundleActivator {

    public void start(BundleContext context) throws Exception {
        ServiceReference ref = context.getServiceReference(ConfigurationAdmin.class.getName());
        ConfigurationAdmin admin = (ConfigurationAdmin) context.getService(ref);
        String pid = "org.camunda.bpm.extension.osgi.configadmin.ManagedProcessEngineFactory";
        Configuration configuration = admin.createFactoryConfiguration(pid, null);
        Hashtable properties = new Hashtable();
        properties.put("databaseSchemaUpdate","false");
        properties.put("jobExecutorActivate","true");
        properties.put("processEngineName","TestEngine");
        properties.put("databaseType","mysql");
        properties.put("dataSourceJndiName", "osgi:service/jdbc/test");
        configuration.update(properties);
    }
```
Currently, the factory supports all primitive values that you can set on the `ProcessEngineConfiguration`.
The key is the name of the according set method with the "set" and starting with a lowercase letter.

A good starting point is the example from the Apache Felix project. See [here](http://felix.apache.org/documentation/subprojects/apache-felix-config-admin.html).


text:
import { reduce } from './reduce';
import { MonoTypeOperatorFunction } from '../types';
import { isFunction } from '../util/isFunction';

/**
 * The Max operator operates on an Observable that emits numbers (or items that can be compared with a provided function),
 * and when source Observable completes it emits a single item: the item with the largest value.
 *
 * ![](max.png)
 *
 * ## Examples
 *
 * Get the maximal value of a series of numbers
 *
 * ```ts
 * import { of, max } from 'rxjs';
 *
 * of(5, 4, 7, 2, 8)
 *   .pipe(max())
 *   .subscribe(x => console.log(x));
 *
 * // Outputs
 * // 8
 * ```
 *
 * Use a comparer function to get the maximal item
 *
 * ```ts
 * import { of, max } from 'rxjs';
 *
 * of(
 *   { age: 7, name: 'Foo' },
 *   { age: 5, name: 'Bar' },
 *   { age: 9, name: 'Beer' }
 * ).pipe(
 *   max((a, b) => a.age < b.age ? -1 : 1)
 * )
 * .subscribe(x => console.log(x.name));
 *
 * // Outputs
 * // 'Beer'
 * ```
 *
 * @see {@link min}
 *
 * @param {Function} [comparer] - Optional comparer function that it will use instead of its default to compare the
 * value of two items.
 * @return A function that returns an Observable that emits item with the
 * largest value.
 */
export function max<T>(comparer?: (x: T, y: T) => number): MonoTypeOperatorFunction<T> {
  return reduce(isFunction(comparer) ? (x, y) => (comparer(x, y) > 0 ? x : y) : (x, y) => (x > y ? x : y));
}


text:
<?php

use yii\helpers\Html;
use yii\helpers\Url;

use app\models\general\GeneralLabel;

/* @var $this yii\web\View */
/* @var $model app\models\AdminEBiasiswa */

$this->title = GeneralLabel::admin_audit_log;
$this->params['breadcrumbs'][] = $this->title;
?>

<?= Html::encode($this->title) ?>

    <iframe src="<?php echo Url::to(['/audit/trail']);?>" width="1500px" height="1570px" frameBorder="0">


text:
package pl.touk.hades.sql.timemonitoring;

import org.junit.Test;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import pl.touk.hades.Hades;
import pl.touk.hades.sql.exception.ConnException;

import javax.sql.DataSource;
import java.net.UnknownHostException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Timer;
import java.util.concurrent.Executors;

import static org.junit.Assert.assertEquals;
import static org.mockito.Matchers.*;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

/**
 * @author Michal Sokolowski
 */
public class SqlTimeBasedTimerTaskMonitorTest {

    @Test
    public void shouldCancelExecutionScheduledAtFixedRateIfLastExecutionDelayedTheCurrentOne()
            throws InterruptedException, SQLException, ConnException, Hades.NoMonitorException, UnknownHostException {
        shouldCancelExecutionIfLastExecutionDelayedTheCurrentOne(true);
    }

    @Test
    public void shouldCancelExecutionIfLastExecutionDelayedTheCurrentOne()
            throws InterruptedException, SQLException, ConnException, Hades.NoMonitorException, UnknownHostException {
        shouldCancelExecutionIfLastExecutionDelayedTheCurrentOne(false);
    }

    private void shouldCancelExecutionIfLastExecutionDelayedTheCurrentOne(boolean scheduleAtFixedRate)
            throws InterruptedException, SQLException, ConnException, Hades.NoMonitorException, UnknownHostException {
        // given:
        final float[] runMethodExecutionCount = new float[]{0};
        int periodMillis = 200;
        int sleepTimeEqualsToThreeAndAHalfPeriodsMillis = (int) (3.5 * periodMillis);
        int runMethodExecTimeEqualsToOneAndAHalfPeriodsMillis = (int) (1.5 * periodMillis);
        SqlTimeBasedTimerTaskMonitor monitor = createSqlTimeBasedTimerTaskMonitorExecutingRunMethodForGivenTimeMillis(
                runMethodExecTimeEqualsToOneAndAHalfPeriodsMillis,
                runMethodExecutionCount);

        // when:
        Timer timer = new Timer();
        if (scheduleAtFixedRate) {
            timer.scheduleAtFixedRate(monitor, 0, periodMillis);
        } else {
            timer.schedule(monitor, 0, periodMillis);
        }
        Thread.sleep(sleepTimeEqualsToThreeAndAHalfPeriodsMillis);
        timer.cancel();

        // then:
        assertEquals(2, (int) runMethodExecutionCount[0]);
    }

    @Test
    public void shouldFailover() throws SQLException, InterruptedException, UnknownHostException {
        // given:
        SqlTimeBasedTimerTaskMonitor activator = createSqlTimeBasedTimerTaskMonitor(200, 100,
                new int[]{
                        33, 66, 50, 50, 50, 150, 133, 166, 150, 250, 250, 250, 250, 300,
                        150, 166, 133, 150, 50, 250, 50, 300, 50, 250, 150, 250, 250},
                new int[]{
                        66, 33, 50, 150, 250, 50, 166, 133, 250, 300, 50, 50, 150, 250,
                        50, 133, 166, 150, 50, 150, 150, 250, 250, 50, 250, 150, 350});
        boolean[] expectedFailoverActive = new boolean[]{
                false, false, false, false, false, false, false, false, false, false, true, true, true,
                true, true, true, true, true, false, true, false, true, false, true, false, true, false};
        boolean[] actualFailoverActive = new boolean[expectedFailoverActive.length];

        // when:
        for (int i = 0; i < expectedFailoverActive.length; i++) {
            activator.run();
            actualFailoverActive[i] = activator.isFailoverActive();
        }

        // then:
        for (int i = 0; i < expectedFailoverActive.length; i++) {
            assertEquals("i: " + i, expectedFailoverActive[i], actualFailoverActive[i]);
        }
    }

    @Test
    public void shouldFailoverForEqualLimits() throws SQLException, InterruptedException, UnknownHostException {
        // given:
        SqlTimeBasedTimerTaskMonitor activator = createSqlTimeBasedTimerTaskMonitor(200, 200,
                new int[]{
                        33, 66, 50, 50, 50, 150, 133, 166, 150, 250, 250, 250,
                        250, 300, 50, 250, 50, 300, 50, 250, 150, 250, 250},
                new int[]{
                        66, 33, 50, 150, 250, 50, 166, 133, 250, 300, 50, 50,
                        150, 250, 50, 150, 150, 250, 250, 50, 250, 150, 350});
        boolean[] expectedFailoverActive = new boolean[]{
                false, false, false, false, false, false, false, false, false, false, true,
                true, true, true, false, true, false, true, false, true, false, true, false};
        boolean[] actualFailoverActive = new boolean[expectedFailoverActive.length];

        // when:
        for (int i = 0; i < expectedFailoverActive.length; i++) {
            activator.run();
            actualFailoverActive[i] = activator.isFailoverActive();
        }

        // then:
        for (int i = 0; i < expectedFailoverActive.length; i++) {
            assertEquals("i: " + i, expectedFailoverActive[i], actualFailoverActive[i]);
        }
    }

    private SqlTimeBasedTimerTaskMonitor createSqlTimeBasedTimerTaskMonitorExecutingRunMethodForGivenTimeMillis(
            final int runMethodExecutionTimeMillis,
            final float[] runMethodExecutionCount)
            throws SQLException, ConnException, InterruptedException, Hades.NoMonitorException, UnknownHostException {
        Hades<SqlTimeBasedMonitorImpl> hades = mock(Hades.class);
        when(hades.getDsName(eq(true), anyBoolean())).thenReturn("FAILOVER_DB");
        when(hades.getDsName(eq(false), anyBoolean())).thenReturn("MAIN_DB    ");

        RepoJdbcImpl sqlTimeRepoMock = mock(RepoJdbcImpl.class);
        when(sqlTimeRepoMock.findSqlTimeYoungerThan(
                any(MonitorRunLogPrefix.class),
                anyString(),
                anyString())).thenReturn(null);
        SqlTimeCalculatorImpl calc = new SqlTimeCalculatorImpl(
                hades,
                sqlTimeRepoMock,
                // one thread to be sure that main and failover sql times are measured sequentially:
                Executors.newFixedThreadPool(1)
        );

        Repo repo = createSqlTimeRepoMock();
        SqlTimeBasedTimerTaskMonitor monitor =
                new SqlTimeBasedTimerTaskMonitor(hades, 100, 50, 1, true, true, calc, 1, 1, 1, repo);

        Connection connectionMock = mock(Connection.class);
        PreparedStatement statementMock = mock(PreparedStatement.class);
        when(hades.getConnection(any(MonitorRunLogPrefix.class), anyBoolean())).thenReturn(connectionMock);
        when(hades.getFailoverDsName()).thenReturn("FAILOVER_DS");
        when(hades.getMainDsName()).thenReturn("MAIN_DS");
        when(hades.getFailoverDataSourcePinned()).thenReturn(null);
//        when(hades.getMonitor()).thenReturn(monitor);
        when(connectionMock.prepareStatement(anyString())).thenReturn(statementMock);
        when(statementMock.execute()).thenAnswer(new Answer() {
            public Object answer(InvocationOnMock invocationOnMock) throws Throwable {
                runMethodExecutionCount[0] += 0.5;
                Thread.sleep(runMethodExecutionTimeMillis / 2);
                return null;
            }
        });

        monitor.init();

        return monitor;
    }

    private SqlTimeBasedTimerTaskMonitor createSqlTimeBasedTimerTaskMonitor(int sqlExecTimeTriggeringFailoverMillis,
                                                                            int sqlExecTimeTriggeringFailbackMillis,
                                                                            final int[] mainDbExecutionTimesMillis,
                                                                            final int[] failoverDbExecutionTimesMillis)
            throws SQLException, InterruptedException, UnknownHostException {
        Hades<SqlTimeBasedMonitorImpl> hades = new Hades<SqlTimeBasedMonitorImpl>(
                createDsMock(mainDbExecutionTimesMillis),
                createDsMock(failoverDbExecutionTimesMillis),
                "MAIN_DS",
                "FAILOVER_DS");

        Repo repo = createSqlTimeRepoMock();
        SqlTimeCalculatorImpl sqlTimeCalculator = new SqlTimeCalculatorImpl(hades, repo, null);

        SqlTimeBasedTimerTaskMonitor monitor = new SqlTimeBasedTimerTaskMonitor(
                hades,
                sqlExecTimeTriggeringFailoverMillis,
                sqlExecTimeTriggeringFailbackMillis,
                1,
                true,
                true,
                sqlTimeCalculator,
                1,
                1,
                1,
                repo);

        monitor.init();

        return monitor;
    }

    public static Repo createSqlTimeRepoMock() throws InterruptedException {
        Repo repo = mock(RepoJdbcImpl.class);
        when(repo.findSqlTimeYoungerThan(any(MonitorRunLogPrefix.class), anyString(), anyString())).thenReturn(null);
        when(repo.getHost()).thenReturn("localhost");
        when(repo.getRepoId()).thenReturn("repo1");
        final int indexOfSqlTimeToStoreParameter = 3;
        when(repo.storeSqlTime(
                any(MonitorRunLogPrefix.class),
                any(Hades.class),
                anyString(),
                anyLong(),
                anyString())).thenAnswer(new Answer<Long>() {
            public Long answer(InvocationOnMock invocationOnMock) throws Throwable {
                return (Long) invocationOnMock.getArguments()[indexOfSqlTimeToStoreParameter];
            }
        });
        when(repo.storeException(
                any(MonitorRunLogPrefix.class),
                any(Hades.class),
                anyString(),
                any(Exception.class),
                anyString())).thenCallRealMethod();
        return repo;
    }

    private DataSource createDsMock(final int[] executionTimesMillis) throws SQLException {
        DataSource dsMock = mock(DataSource.class);
        Connection connectionMock = mock(Connection.class);
        PreparedStatement statementMock = mock(PreparedStatement.class);

        when(dsMock.getConnection()).thenReturn(connectionMock);
        when(connectionMock.prepareStatement(anyString())).thenReturn(statementMock);
        when(statementMock.execute()).thenAnswer(new Answer() {
            private int i = 0;
            public Object answer(InvocationOnMock invocationOnMock) throws Throwable {
                Thread.sleep(executionTimesMillis[i]);
                i++;
                return null;
            }
        });

        return dsMock;
    }
}


text:
#include "loadsofa.h"

#include <algorithm>
#include <atomic>
#include <chrono>
#include <cmath>
#include <cstdio>
#include <functional>
#include <future>
#include <iterator>
#include <memory>
#include <numeric>
#include <string>
#include <vector>

#include "makemhr.h"
#include "polyphase_resampler.h"
#include "sofa-support.h"

#include "mysofa.h"

using uint = unsigned int;

/* Attempts to produce a compatible layout.  Most data sets tend to be
 * uniform and have the same major axis as used by OpenAL Soft's HRTF model.
 * This will remove outliers and produce a maximally dense layout when
 * possible.  Those sets that contain purely random measurements or use
 * different major axes will fail.
 */
static bool PrepareLayout(const uint m, const float *xyzs, HrirDataT *hData)
{
    fprintf(stdout, "Detecting compatible layout...\n");

    auto fds = GetCompatibleLayout(m, xyzs);
    if(fds.size() > MAX_FD_COUNT)
    {
        fprintf(stdout, "Incompatible layout (inumerable radii).\n");
        return false;
    }

    double distances[MAX_FD_COUNT]{};
    uint evCounts[MAX_FD_COUNT]{};
    auto azCounts = std::vector<uint>(MAX_FD_COUNT*MAX_EV_COUNT, 0u);

    uint fi{0u}, ir_total{0u};
    for(const auto &field : fds)
    {
        distances[fi] = field.mDistance;
        evCounts[fi] = field.mEvCount;

        for(uint ei{0u};ei < field.mEvStart;ei++)
            azCounts[fi*MAX_EV_COUNT + ei] = field.mAzCounts[field.mEvCount-ei-1];
        for(uint ei{field.mEvStart};ei < field.mEvCount;ei++)
        {
            azCounts[fi*MAX_EV_COUNT + ei] = field.mAzCounts[ei];
            ir_total += field.mAzCounts[ei];
        }

        ++fi;
    }
    fprintf(stdout, "Using %u of %u IRs.\n", ir_total, m);
    return PrepareHrirData(fi, distances, evCounts, azCounts.data(), hData) != 0;
}

bool PrepareSampleRate(MYSOFA_HRTF *sofaHrtf, HrirDataT *hData)
{
    const char *srate_dim{nullptr};
    const char *srate_units{nullptr};
    MYSOFA_ARRAY *srate_array{&sofaHrtf->DataSamplingRate};
    MYSOFA_ATTRIBUTE *srate_attrs{srate_array->attributes};
    while(srate_attrs)
    {
        if(std::string{"DIMENSION_LIST"} == srate_attrs->name)
        {
            if(srate_dim)
            {
                fprintf(stderr, "Duplicate SampleRate.DIMENSION_LIST\n");
                return false;
            }
            srate_dim = srate_attrs->value;
        }
        else if(std::string{"Units"} == srate_attrs->name)
        {
            if(srate_units)
            {
                fprintf(stderr, "Duplicate SampleRate.Units\n");
                return false;
            }
            srate_units = srate_attrs->value;
        }
        else
            fprintf(stderr, "Unexpected sample rate attribute: %s = %s\n", srate_attrs->name,
                srate_attrs->value);
        srate_attrs = srate_attrs->next;
    }
    if(!srate_dim)
    {
        fprintf(stderr, "Missing sample rate dimensions\n");
        return false;
    }
    if(srate_dim != std::string{"I"})
    {
        fprintf(stderr, "Unsupported sample rate dimensions: %s\n", srate_dim);
        return false;
    }
    if(!srate_units)
    {
        fprintf(stderr, "Missing sample rate unit type\n");
        return false;
    }
    if(srate_units != std::string{"hertz"})
    {
        fprintf(stderr, "Unsupported sample rate unit type: %s\n", srate_units);
        return false;
    }
    /* I dimensions guarantees 1 element, so just extract it. */
    hData->mIrRate = static_cast<uint>(srate_array->values[0] + 0.5f);
    if(hData->mIrRate < MIN_RATE || hData->mIrRate > MAX_RATE)
    {
        fprintf(stderr, "Sample rate out of range: %u (expected %u to %u)", hData->mIrRate,
            MIN_RATE, MAX_RATE);
        return false;
    }
    return true;
}

bool PrepareDelay(MYSOFA_HRTF *sofaHrtf, HrirDataT *hData)
{
    const char *delay_dim{nullptr};
    MYSOFA_ARRAY *delay_array{&sofaHrtf->DataDelay};
    MYSOFA_ATTRIBUTE *delay_attrs{delay_array->attributes};
    while(delay_attrs)
    {
        if(std::string{"DIMENSION_LIST"} == delay_attrs->name)
        {
            if(delay_dim)
            {
                fprintf(stderr, "Duplicate Delay.DIMENSION_LIST\n");
                return false;
            }
            delay_dim = delay_attrs->value;
        }
        else
            fprintf(stderr, "Unexpected delay attribute: %s = %s\n", delay_attrs->name,
                delay_attrs->value);
        delay_attrs = delay_attrs->next;
    }
    if(!delay_dim)
    {
        fprintf(stderr, "Missing delay dimensions\n");
        /*return false;*/
    }
    else if(delay_dim != std::string{"I,R"})
    {
        fprintf(stderr, "Unsupported delay dimensions: %s\n", delay_dim);
        return false;
    }
    else if(hData->mChannelType == CT_STEREO)
    {
        /* I,R is 1xChannelCount. Makemhr currently removes any delay constant,
         * so we can ignore this as long as it's equal.
         */
        if(delay_array->values[0] != delay_array->values[1])
        {
            fprintf(stderr, "Mismatched delays not supported: %f, %f\n", delay_array->values[0],
                delay_array->values[1]);
            return false;
        }
    }
    return true;
}

bool CheckIrData(MYSOFA_HRTF *sofaHrtf)
{
    const char *ir_dim{nullptr};
    MYSOFA_ARRAY *ir_array{&sofaHrtf->DataIR};
    MYSOFA_ATTRIBUTE *ir_attrs{ir_array->attributes};
    while(ir_attrs)
    {
        if(std::string{"DIMENSION_LIST"} == ir_attrs->name)
        {
            if(ir_dim)
            {
                fprintf(stderr, "Duplicate IR.DIMENSION_LIST\n");
                return false;
            }
            ir_dim = ir_attrs->value;
        }
        else
            fprintf(stderr, "Unexpected IR attribute: %s = %s\n", ir_attrs->name,
                ir_attrs->value);
        ir_attrs = ir_attrs->next;
    }
    if(!ir_dim)
    {
        fprintf(stderr, "Missing IR dimensions\n");
        return false;
    }
    if(ir_dim != std::string{"M,R,N"})
    {
        fprintf(stderr, "Unsupported IR dimensions: %s\n", ir_dim);
        return false;
    }
    return true;
}

/* Calculate the onset time of a HRIR. */
static constexpr int OnsetRateMultiple{10};
static double CalcHrirOnset(PPhaseResampler &rs, const uint rate, const uint n,
    std::vector<double> &upsampled, const double *hrir)
{
    rs.process(n, hrir, static_cast<uint>(upsampled.size()), upsampled.data());

    auto abs_lt = [](const double &lhs, const double &rhs) -> bool
    { return std::abs(lhs) < std::abs(rhs); };
    auto iter = std::max_element(upsampled.cbegin(), upsampled.cend(), abs_lt);
    return static_cast<double>(std::distance(upsampled.cbegin(), iter)) /
        (double{OnsetRateMultiple}*rate);
}

/* Calculate the magnitude response of a HRIR. */
static void CalcHrirMagnitude(const uint points, const uint n, std::vector<complex_d> &h,
    double *hrir)
{
    auto iter = std::copy_n(hrir, points, h.begin());
    std::fill(iter, h.end(), complex_d{0.0, 0.0});

    FftForward(n, h.data());
    MagnitudeResponse(n, h.data(), hrir);
}

static bool LoadResponses(MYSOFA_HRTF *sofaHrtf, HrirDataT *hData)
{
    std::atomic<uint> loaded_count{0u};

    auto load_proc = [sofaHrtf,hData,&loaded_count]() -> bool
    {
        const uint channels{(hData->mChannelType == CT_STEREO) ? 2u : 1u};
        hData->mHrirsBase.resize(channels * hData->mIrCount * hData->mIrSize, 0.0);
        double *hrirs = hData->mHrirsBase.data();

        for(uint si{0u};si < sofaHrtf->M;++si)
        {
            loaded_count.fetch_add(1u);

            float aer[3]{
                sofaHrtf->SourcePosition.values[3*si],
                sofaHrtf->SourcePosition.values[3*si + 1],
                sofaHrtf->SourcePosition.values[3*si + 2]
            };
            mysofa_c2s(aer);

            if(std::abs(aer[1]) >= 89.999f)
                aer[0] = 0.0f;
            else
                aer[0] = std::fmod(360.0f - aer[0], 360.0f);

            auto field = std::find_if(hData->mFds.cbegin(), hData->mFds.cend(),
                [&aer](const HrirFdT &fld) -> bool
                {
                    double delta = aer[2] - fld.mDistance;
                    return (std::abs(delta) < 0.001);
                });
            if(field == hData->mFds.cend())
                continue;

            double ef{(90.0+aer[1]) / 180.0 * (field->mEvCount-1)};
            auto ei = static_cast<int>(std::round(ef));
            ef = (ef-ei) * 180.0 / (field->mEvCount-1);
            if(std::abs(ef) >= 0.1) continue;

            double af{aer[0] / 360.0 * field->mEvs[ei].mAzCount};
            auto ai = static_cast<int>(std::round(af));
            af = (af-ai) * 360.0 / field->mEvs[ei].mAzCount;
            ai %= field->mEvs[ei].mAzCount;
            if(std::abs(af) >= 0.1) continue;

            HrirAzT *azd = &field->mEvs[ei].mAzs[ai];
            if(azd->mIrs[0] != nullptr)
            {
                fprintf(stderr, "\nMultiple measurements near [ a=%f, e=%f, r=%f ].\n",
                    aer[0], aer[1], aer[2]);
                return false;
            }

            for(uint ti{0u};ti < channels;++ti)
            {
                azd->mIrs[ti] = &hrirs[hData->mIrSize * (hData->mIrCount*ti + azd->mIndex)];
                std::copy_n(&sofaHrtf->DataIR.values[(si*sofaHrtf->R + ti)*sofaHrtf->N],
                    hData->mIrPoints, azd->mIrs[ti]);
            }

            /* TODO: Since some SOFA files contain minimum phase HRIRs,
             * it would be beneficial to check for per-measurement delays
             * (when available) to reconstruct the HRTDs.
             */
        }
        return true;
    };

    std::future_status load_status{};
    auto load_future = std::async(std::launch::async, load_proc);
    do {
        load_status = load_future.wait_for(std::chrono::milliseconds{50});
        printf("\rLoading HRIRs... %u of %u", loaded_count.load(), sofaHrtf->M);
        fflush(stdout);
    } while(load_status != std::future_status::ready);
    fputc('\n', stdout);
    return load_future.get();
}

/* Calculates the frequency magnitudes of the HRIR set. Work is delegated to
 * this struct, which runs asynchronously on one or more threads (sharing the
 * same calculator object).
 */
struct MagCalculator {
    const uint mFftSize{};
    const uint mIrPoints{};
    std::vector<double*> mIrs{};
    std::atomic<size_t> mCurrent{};
    std::atomic<size_t> mDone{};

    void Worker()
    {
        auto htemp = std::vector<complex_d>(mFftSize);

        while(1)
        {
            /* Load the current index to process. */
            size_t idx{mCurrent.load()};
            do {
                /* If the index is at the end, we're done. */
                if(idx >= mIrs.size())
                    return;
                /* Otherwise, increment the current index atomically so other
                 * threads know to go to the next one. If this call fails, the
                 * current index was just changed by another thread and the new
                 * value is loaded into idx, which we'll recheck.
                 */
            } while(!mCurrent.compare_exchange_weak(idx, idx+1, std::memory_order_relaxed));

            CalcHrirMagnitude(mIrPoints, mFftSize, htemp, mIrs[idx]);

            /* Increment the number of IRs done. */
            mDone.fetch_add(1);
        }
    }
};

bool LoadSofaFile(const char *filename, const uint numThreads, const uint fftSize,
    const uint truncSize, const ChannelModeT chanMode, HrirDataT *hData)
{
    int err;
    MySofaHrtfPtr sofaHrtf{mysofa_load(filename, &err)};
    if(!sofaHrtf)
    {
        fprintf(stdout, "Error: Could not load %s: %s\n", filename, SofaErrorStr(err));
        return false;
    }

    /* NOTE: Some valid SOFA files are failing this check. */
    err = mysofa_check(sofaHrtf.get());
    if(err != MYSOFA_OK)
        fprintf(stderr, "Warning: Supposedly malformed source file '%s' (%s).\n", filename,
            SofaErrorStr(err));

    mysofa_tocartesian(sofaHrtf.get());

    /* Make sure emitter and receiver counts are sane. */
    if(sofaHrtf->E != 1)
    {
        fprintf(stderr, "%u emitters not supported\n", sofaHrtf->E);
        return false;
    }
    if(sofaHrtf->R > 2 || sofaHrtf->R < 1)
    {
        fprintf(stderr, "%u receivers not supported\n", sofaHrtf->R);
        return false;
    }
    /* Assume R=2 is a stereo measurement, and R=1 is mono left-ear-only. */
    if(sofaHrtf->R == 2 && chanMode == CM_AllowStereo)
        hData->mChannelType = CT_STEREO;
    else
        hData->mChannelType = CT_MONO;

    /* Check and set the FFT and IR size. */
    if(sofaHrtf->N > fftSize)
    {
        fprintf(stderr, "Sample points exceeds the FFT size.\n");
        return false;
    }
    if(sofaHrtf->N < truncSize)
    {
        fprintf(stderr, "Sample points is below the truncation size.\n");
        return false;
    }
    hData->mIrPoints = sofaHrtf->N;
    hData->mFftSize = fftSize;
    hData->mIrSize = std::max(1u + (fftSize/2u), sofaHrtf->N);

    /* Assume a default head radius of 9cm. */
    hData->mRadius = 0.09;

    if(!PrepareSampleRate(sofaHrtf.get(), hData) || !PrepareDelay(sofaHrtf.get(), hData)
        || !CheckIrData(sofaHrtf.get()))
        return false;
    if(!PrepareLayout(sofaHrtf->M, sofaHrtf->SourcePosition.values, hData))
        return false;

    if(!LoadResponses(sofaHrtf.get(), hData))
        return false;
    sofaHrtf = nullptr;

    for(uint fi{0u};fi < hData->mFdCount;fi++)
    {
        uint ei{0u};
        for(;ei < hData->mFds[fi].mEvCount;ei++)
        {
            uint ai{0u};
            for(;ai < hData->mFds[fi].mEvs[ei].mAzCount;ai++)
            {
                HrirAzT &azd = hData->mFds[fi].mEvs[ei].mAzs[ai];
                if(azd.mIrs[0] != nullptr) break;
            }
            if(ai < hData->mFds[fi].mEvs[ei].mAzCount)
                break;
        }
        if(ei >= hData->mFds[fi].mEvCount)
        {
            fprintf(stderr, "Missing source references [ %d, *, * ].\n", fi);
            return false;
        }
        hData->mFds[fi].mEvStart = ei;
        for(;ei < hData->mFds[fi].mEvCount;ei++)
        {
            for(uint ai{0u};ai < hData->mFds[fi].mEvs[ei].mAzCount;ai++)
            {
                HrirAzT &azd = hData->mFds[fi].mEvs[ei].mAzs[ai];
                if(azd.mIrs[0] == nullptr)
                {
                    fprintf(stderr, "Missing source reference [ %d, %d, %d ].\n", fi, ei, ai);
                    return false;
                }
            }
        }
    }

    size_t hrir_total{0};
    const uint channels{(hData->mChannelType == CT_STEREO) ? 2u : 1u};
    double *hrirs = hData->mHrirsBase.data();
    for(uint fi{0u};fi < hData->mFdCount;fi++)
    {
        for(uint ei{0u};ei < hData->mFds[fi].mEvStart;ei++)
        {
            for(uint ai{0u};ai < hData->mFds[fi].mEvs[ei].mAzCount;ai++)
            {
                HrirAzT &azd = hData->mFds[fi].mEvs[ei].mAzs[ai];
                for(uint ti{0u};ti < channels;ti++)
                    azd.mIrs[ti] = &hrirs[hData->mIrSize * (hData->mIrCount*ti + azd.mIndex)];
            }
        }

        for(uint ei{hData->mFds[fi].mEvStart};ei < hData->mFds[fi].mEvCount;ei++)
            hrir_total += hData->mFds[fi].mEvs[ei].mAzCount * channels;
    }

    std::atomic<size_t> hrir_done{0};
    auto onset_proc = [hData,channels,&hrir_done]() -> bool
    {
        /* Temporary buffer used to calculate the IR's onset. */
        auto upsampled = std::vector<double>(OnsetRateMultiple * hData->mIrPoints);
        /* This resampler is used to help detect the response onset. */
        PPhaseResampler rs;
        rs.init(hData->mIrRate, OnsetRateMultiple*hData->mIrRate);

        for(uint fi{0u};fi < hData->mFdCount;fi++)
        {
            for(uint ei{hData->mFds[fi].mEvStart};ei < hData->mFds[fi].mEvCount;ei++)
            {
                for(uint ai{0};ai < hData->mFds[fi].mEvs[ei].mAzCount;ai++)
                {
                    HrirAzT &azd = hData->mFds[fi].mEvs[ei].mAzs[ai];
                    for(uint ti{0};ti < channels;ti++)
                    {
                        hrir_done.fetch_add(1u, std::memory_order_acq_rel);
                        azd.mDelays[ti] = CalcHrirOnset(rs, hData->mIrRate, hData->mIrPoints,
                            upsampled, azd.mIrs[ti]);
                    }
                }
            }
        }
        return true;
    };

    std::future_status load_status{};
    auto load_future = std::async(std::launch::async, onset_proc);
    do {
        load_status = load_future.wait_for(std::chrono::milliseconds{50});
        printf("\rCalculating HRIR onsets... %zu of %zu", hrir_done.load(), hrir_total);
        fflush(stdout);
    } while(load_status != std::future_status::ready);
    fputc('\n', stdout);
    if(!load_future.get())
        return false;

    MagCalculator calculator{hData->mFftSize, hData->mIrPoints};
    for(uint fi{0u};fi < hData->mFdCount;fi++)
    {
        for(uint ei{hData->mFds[fi].mEvStart};ei < hData->mFds[fi].mEvCount;ei++)
        {
            for(uint ai{0};ai < hData->mFds[fi].mEvs[ei].mAzCount;ai++)
            {
                HrirAzT &azd = hData->mFds[fi].mEvs[ei].mAzs[ai];
                for(uint ti{0};ti < channels;ti++)
                    calculator.mIrs.push_back(azd.mIrs[ti]);
            }
        }
    }

    std::vector<std::thread> thrds;
    thrds.reserve(numThreads);
    for(size_t i{0};i < numThreads;++i)
        thrds.emplace_back(std::mem_fn(&MagCalculator::Worker), &calculator);
    size_t count;
    do {
        std::this_thread::sleep_for(std::chrono::milliseconds{50});
        count = calculator.mDone.load();

        printf("\rCalculating HRIR magnitudes... %zu of %zu", count, calculator.mIrs.size());
        fflush(stdout);
    } while(count != calculator.mIrs.size());
    fputc('\n', stdout);

    for(auto &thrd : thrds)
    {
        if(thrd.joinable())
            thrd.join();
    }
    return true;
}


text:
/*
 * LIRC base driver
 *
 * by Artur Lipowski <alipowski@interia.pl>
 *        This code is licensed under GNU GPL
 *
 */

#ifndef _LINUX_LIRC_DEV_H
#define _LINUX_LIRC_DEV_H

#define MAX_IRCTL_DEVICES 8
#define BUFLEN            16

#define mod(n, div) ((n) % (div))

#include <linux/slab.h>
#include <linux/fs.h>
#include <linux/ioctl.h>
#include <linux/poll.h>
#include <linux/kfifo.h>
#include <media/lirc.h>

struct lirc_buffer {
	wait_queue_head_t wait_poll;
	spinlock_t fifo_lock;
	unsigned int chunk_size;
	unsigned int size; /* in chunks */
	/* Using chunks instead of bytes pretends to simplify boundary checking
	 * And should allow for some performance fine tunning later */
	struct kfifo fifo;
	u8 fifo_initialized;
};

static inline void lirc_buffer_clear(struct lirc_buffer *buf)
{
	unsigned long flags;

	if (buf->fifo_initialized) {
		spin_lock_irqsave(&buf->fifo_lock, flags);
		kfifo_reset(&buf->fifo);
		spin_unlock_irqrestore(&buf->fifo_lock, flags);
	} else
		WARN(1, "calling %s on an uninitialized lirc_buffer\n",
		     __func__);
}

static inline int lirc_buffer_init(struct lirc_buffer *buf,
				    unsigned int chunk_size,
				    unsigned int size)
{
	int ret;

	init_waitqueue_head(&buf->wait_poll);
	spin_lock_init(&buf->fifo_lock);
	buf->chunk_size = chunk_size;
	buf->size = size;
	ret = kfifo_alloc(&buf->fifo, size * chunk_size, GFP_KERNEL);
	if (ret == 0)
		buf->fifo_initialized = 1;

	return ret;
}

static inline void lirc_buffer_free(struct lirc_buffer *buf)
{
	if (buf->fifo_initialized) {
		kfifo_free(&buf->fifo);
		buf->fifo_initialized = 0;
	} else
		WARN(1, "calling %s on an uninitialized lirc_buffer\n",
		     __func__);
}

static inline int lirc_buffer_len(struct lirc_buffer *buf)
{
	int len;
	unsigned long flags;

	spin_lock_irqsave(&buf->fifo_lock, flags);
	len = kfifo_len(&buf->fifo);
	spin_unlock_irqrestore(&buf->fifo_lock, flags);

	return len;
}

static inline int lirc_buffer_full(struct lirc_buffer *buf)
{
	return lirc_buffer_len(buf) == buf->size * buf->chunk_size;
}

static inline int lirc_buffer_empty(struct lirc_buffer *buf)
{
	return !lirc_buffer_len(buf);
}

static inline int lirc_buffer_available(struct lirc_buffer *buf)
{
	return buf->size - (lirc_buffer_len(buf) / buf->chunk_size);
}

static inline unsigned int lirc_buffer_read(struct lirc_buffer *buf,
					    unsigned char *dest)
{
	unsigned int ret = 0;

	if (lirc_buffer_len(buf) >= buf->chunk_size)
		ret = kfifo_out_locked(&buf->fifo, dest, buf->chunk_size,
				       &buf->fifo_lock);
	return ret;

}

static inline unsigned int lirc_buffer_write(struct lirc_buffer *buf,
					     unsigned char *orig)
{
	unsigned int ret;

	ret = kfifo_in_locked(&buf->fifo, orig, buf->chunk_size,
			      &buf->fifo_lock);

	return ret;
}

struct lirc_driver {
	char name[40];
	int minor;
	__u32 code_length;
	unsigned int buffer_size; /* in chunks holding one code each */
	int sample_rate;
	__u32 features;

	unsigned int chunk_size;

	void *data;
	int min_timeout;
	int max_timeout;
	int (*add_to_buf) (void *data, struct lirc_buffer *buf);
	struct lirc_buffer *rbuf;
	int (*set_use_inc) (void *data);
	void (*set_use_dec) (void *data);
	const struct file_operations *fops;
	struct device *dev;
	struct module *owner;
};

/* name:
 * this string will be used for logs
 *
 * minor:
 * indicates minor device (/dev/lirc) number for registered driver
 * if caller fills it with negative value, then the first free minor
 * number will be used (if available)
 *
 * code_length:
 * length of the remote control key code expressed in bits
 *
 * sample_rate:
 *
 * data:
 * it may point to any driver data and this pointer will be passed to
 * all callback functions
 *
 * add_to_buf:
 * add_to_buf will be called after specified period of the time or
 * triggered by the external event, this behavior depends on value of
 * the sample_rate this function will be called in user context. This
 * routine should return 0 if data was added to the buffer and
 * -ENODATA if none was available. This should add some number of bits
 * evenly divisible by code_length to the buffer
 *
 * rbuf:
 * if not NULL, it will be used as a read buffer, you will have to
 * write to the buffer by other means, like irq's (see also
 * lirc_serial.c).
 *
 * set_use_inc:
 * set_use_inc will be called after device is opened
 *
 * set_use_dec:
 * set_use_dec will be called after device is closed
 *
 * fops:
 * file_operations for drivers which don't fit the current driver model.
 *
 * Some ioctl's can be directly handled by lirc_dev if the driver's
 * ioctl function is NULL or if it returns -ENOIOCTLCMD (see also
 * lirc_serial.c).
 *
 * owner:
 * the module owning this struct
 *
 */

/* following functions can be called ONLY from user context
 *
 * returns negative value on error or minor number
 * of the registered device if success
 * contents of the structure pointed by p is copied
 */
extern int lirc_register_driver(struct lirc_driver *d);

/* returns negative value on error or 0 if success
*/
extern int lirc_unregister_driver(int minor);

/* Returns the private data stored in the lirc_driver
 * associated with the given device file pointer.
 */
void *lirc_get_pdata(struct file *file);

/* default file operations
 * used by drivers if they override only some operations
 */
int lirc_dev_fop_open(struct inode *inode, struct file *file);
int lirc_dev_fop_close(struct inode *inode, struct file *file);
unsigned int lirc_dev_fop_poll(struct file *file, poll_table *wait);
long lirc_dev_fop_ioctl(struct file *file, unsigned int cmd, unsigned long arg);
ssize_t lirc_dev_fop_read(struct file *file, char __user *buffer, size_t length,
			  loff_t *ppos);
ssize_t lirc_dev_fop_write(struct file *file, const char __user *buffer,
			   size_t length, loff_t *ppos);

#endif


text:
package manifest1

import (
	"bufio"
	"bytes"
	"encoding/json"
	"fmt"
	"html/template"
	"io/ioutil"
	"math/rand"
	"net/url"
	"os"
	"path/filepath"
	"sort"
	"strconv"
	"strings"
)

var ManifestRandomPorts = true

type Service struct {
	Name string `yaml:"-"`

	Build       Build       `yaml:"build,omitempty"`
	Command     Command     `yaml:"command,omitempty"`
	Dockerfile  string      `yaml:"dockerfile,omitempty"`
	Entrypoint  string      `yaml:"entrypoint,omitempty"`
	Environment Environment `yaml:"environment,omitempty"`
	ExtraHosts  []string    `yaml:"extra_hosts,omitempty"`
	Image       string      `yaml:"image,omitempty"`
	Labels      Labels      `yaml:"labels,omitempty"`
	Links       []string    `yaml:"links,omitempty"`
	Networks    Networks    `yaml:"-"`
	Ports       Ports       `yaml:"ports,omitempty"`
	Privileged  bool        `yaml:"privileged,omitempty"`
	Volumes     []string    `yaml:"volumes,omitempty"`

	Cpu    int64  `yaml:"cpu_shares,omitempty"`
	Memory Memory `yaml:"mem_limit,omitempty"`

	//TODO from models manifest, not passive and used at runtime
	Exports  map[string]string        `yaml:"-"`
	LinkVars map[string]template.HTML `yaml:"-"`

	Primary bool `yaml:"-"`

	randoms map[string]int
}

// Services are a list of Services
type Services []Service

// see yaml.go for unmarshallers
type Build struct {
	Context    string            `yaml:"context,omitempty"`
	Dockerfile string            `yaml:"dockerfile,omitempty"`
	Args       map[string]string `yaml:"args,omitempty"`
}

// Command represents the command docker will run either in string or array of strings
type Command struct {
	String string   `yaml:"-"`
	Array  []string `yaml:"-"`
}

// EnvironmentItem is a single item in an environment
type EnvironmentItem struct {
	Name   string
	Value  string
	Needed bool // if true this value should be provided by the user in .env or convox env
}

// Environment is a service's default environment
type Environment []EnvironmentItem

type Labels map[string]string
type Memory int64
type Networks map[string]InternalNetwork

type InternalNetwork map[string]ExternalNetwork
type ExternalNetwork Network

type Network struct {
	Name string
}

// Hash returns a string suitable for using as a map key
func (b *Build) Hash() string {
	argKeys := []string{}
	for k := range b.Args {
		argKeys = append(argKeys, k)
	}
	sort.Strings(argKeys)

	hashParts := make([]string, len(argKeys))
	for i, key := range argKeys {
		hashParts[i] = fmt.Sprintf("%s=%s", key, b.Args[key])
	}
	argsHash := strings.Join(hashParts, "@@@@@")

	return fmt.Sprintf("%+v|||||%+v|||||%+v", b.Context, b.Dockerfile, argsHash)
}

func (s *Service) Process(app string, m Manifest) Process {
	return NewProcess(app, *s, m)
}

// UseSecureEnvironment - Determines if the service intends to use a secure environment
func (s Service) UseSecureEnvironment() bool {
	return s.Labels["convox.environment.secure"] == "true"
}

// HasBalancer returns false if the Service contains no public ports,
// or if the `convox.balancer` label is set to false
func (s Service) HasBalancer() bool {
	if s.Labels["convox.balancer"] == "false" {
		return false
	}

	for _, p := range s.Ports {
		if p.Protocol == TCP {
			return true
		}
	}

	return false
}

// IsAgent returns true if Service is a per-host agent, otherwise it returns false
func (s Service) IsAgent() bool {
	// BackCompat: Some people might already be trying to use `convox.daemon` based on
	// https://github.com/convox-examples/dd-agent/blob/master/docker-compose.yml#L13
	_, okAgent := s.Labels["convox.agent"]
	_, okDaemon := s.Labels["convox.daemon"]
	return okAgent || okDaemon
}

// DefaultParams returns a string of comma-delimited Count, CPU, and Memory params
func (s Service) DefaultParams() string {
	count := 1
	cpu := 128
	memory := 256

	if s.IsAgent() {
		count = 0
	}

	return fmt.Sprintf("%d,%d,%d", count, cpu, memory)
}

func (s *Service) Proxies(app string) []Proxy {
	proxies := []Proxy{}

	for i, p := range s.Ports {
		if p.Public {
			name := fmt.Sprintf("%s-%s-proxy-%d", app, s.Name, p.Balancer)

			proxy := Proxy{
				Name:      name,
				Balancer:  p.Balancer,
				Container: p.Container,
				Host:      fmt.Sprintf("%s-%s", app, s.Name),
				Network:   s.NetworkName(),
			}

			s.Ports[i].Balancer = 0

			proxy.Protocol = coalesce(s.Labels[fmt.Sprintf("convox.port.%d.protocol", p.Balancer)], "tcp")
			proxy.Proxy = s.Labels[fmt.Sprintf("convox.port.%d.proxy", p.Balancer)] == "true"
			proxy.Secure = s.Labels[fmt.Sprintf("convox.port.%d.secure", p.Balancer)] == "true"

			proxies = append(proxies, proxy)
		}
	}

	return proxies
}

func (s *Service) SyncPaths() (map[string]string, error) {
	sp := map[string]string{}
	ev := map[string]string{}

	if s.Build.Context == "" {
		return sp, nil
	}

	dockerFile := s.Build.Dockerfile
	if dockerFile == "" {
		dockerFile = s.Dockerfile
	}

	data, err := ioutil.ReadFile(filepath.Join(s.Build.Context, coalesce(dockerFile, "Dockerfile")))
	if err != nil {
		return nil, err
	}

	scanner := bufio.NewScanner(bytes.NewReader(data))

	for scanner.Scan() {
		rparts := strings.Fields(scanner.Text())

		if len(rparts) < 1 {
			continue
		}

		parts := []string{}

		// skip the --options to ADD/COPY
		for _, p := range rparts {
			if !strings.HasPrefix(p, "--") {
				parts = append(parts, p)
			}
		}

		if len(parts) < 1 {
			continue
		}

		switch parts[0] {
		case "ENV":
			if len(parts) >= 3 {
				ev[parts[1]] = parts[2]
			}
		case "ADD", "COPY":
			if len(parts) >= 3 {
				u, err := url.Parse(parts[1])
				if err != nil {
					return nil, err
				}

				switch u.Scheme {
				case "http", "https":
					// do nothing
				default:
					path := parts[2]
					for k, v := range ev {
						if strings.Contains(path, fmt.Sprintf("$%s", k)) {
							path = strings.Replace(path, fmt.Sprintf("$%s", k), v, -1)
						}
					}
					sp[filepath.Join(s.Build.Context, parts[1])] = path
				}
			}
		}
	}

	return sp, nil
}

// Tag generates a string used to tag an image.
func (s *Service) Tag(appName string) string {
	return (fmt.Sprintf("%s/%s", appName, strings.Replace(s.Name, "_", "-", -1)))
}

// MountableVolume describes a mountable volume
type MountableVolume struct {
	Host      string
	Container string
}

// MountableVolumes return the mountable volumes for a service
func (s Service) MountableVolumes() []MountableVolume {
	volumes := []MountableVolume{}

	for _, volume := range s.Volumes {
		parts := strings.Split(volume, ":")

		// if only one volume part use it for both sides
		if len(parts) == 1 {
			parts = append(parts, parts[0])
		}

		// if we dont have two volume parts bail
		if len(parts) != 2 {
			continue
		}

		// only support absolute paths for volume source
		if !filepath.IsAbs(parts[0]) {
			continue
		}

		volumes = append(volumes, MountableVolume{
			Host:      parts[0],
			Container: parts[1],
		})
	}

	return volumes
}

// IsSystem white lists special host volumes to pass through to the container
// instead of turning them into an application EFS mount
func (v MountableVolume) IsSystem() bool {
	switch v.Host {
	case "/var/run/docker.sock":
		return true
	case "/proc/":
		return true
	case "/cgroup/":
		return true
	default:
		return false
	}
}

// DeploymentMinimum returns the min percent of containers that are allowed during deployment
func (s Service) DeploymentMinimum() string {
	return s.LabelDefault("convox.deployment.minimum", "50")
}

// DeploymentMaximum returns the max percent of containers that are allowed during deployment
// This will be most likely be overridden and set to 100 for singleton processes like schedulers that cannot have 2 running at once
func (s Service) DeploymentMaximum() string {
	return s.LabelDefault("convox.deployment.maximum", "200")
}

// NetworkName returns custom network name from the networks, defined in compose file.
// REturns empty string, if no custom network is defined.
// We pick the last one, as we currently support only single one.
func (s *Service) NetworkName() string {
	// No custom docker network by default
	networkName := ""

	for _, n := range s.Networks {
		for _, in := range n {
			networkName = in.Name
		}
	}
	return networkName
}

func containerEnv(container string) map[string]string {
	es := []string{}

	data, _ := Docker("inspect", "-f", "{{json .Config.Env}}", container).Output()

	json.Unmarshal(data, &es)

	env := map[string]string{}

	for _, e := range es {
		parts := strings.SplitN(e, "=", 2)
		if len(parts) > 1 {
			env[parts[0]] = parts[1]
		} else {
			env[parts[0]] = ""
		}
	}

	return env
}

func containerHost(container string, networks Networks) string {
	ipFilterString := "{{ .NetworkSettings.IPAddress }}"

	// TODO container is part of network, look up IP there
	if len(networks) > 0 {
		for _, n := range networks {
			for _, in := range n {
				ipFilterString = "{{ .NetworkSettings.Networks." + in.Name + ".IPAddress }}"
				break
			}
			break
		}
	}

	data, _ := Docker("inspect", "-f", ipFilterString, container).Output()

	if s := strings.TrimSpace(string(data)); s != "" {
		return s
	}

	return ""
}

func containerPort(container string) string {
	data, _ := Docker("inspect", "-f", "{{range $k,$v := .Config.ExposedPorts}}{{$k}}|{{end}}", container).Output()

	return strings.Split(string(data), "/")[0]
}

func linkArgs(s Service, container string) []string {
	args := []string{}

	prefix := strings.Replace(strings.ToUpper(s.Name), "-", "_", -1)
	env := containerEnv(container)

	scheme := coalesce(env["LINK_SCHEME"], "tcp")
	host := containerHost(container, s.Networks)
	port := coalesce(env["LINK_PORT"], containerPort(container))
	path := env["LINK_PATH"]
	username := env["LINK_USERNAME"]
	password := env["LINK_PASSWORD"]

	args = append(args, "--add-host", fmt.Sprintf("%s:%s", s.Name, host))
	args = append(args, "-e", fmt.Sprintf("%s_SCHEME=%s", prefix, scheme))
	args = append(args, "-e", fmt.Sprintf("%s_HOST=%s", prefix, host))
	args = append(args, "-e", fmt.Sprintf("%s_PORT=%s", prefix, port))
	args = append(args, "-e", fmt.Sprintf("%s_PATH=%s", prefix, path))
	args = append(args, "-e", fmt.Sprintf("%s_USERNAME=%s", prefix, username))
	args = append(args, "-e", fmt.Sprintf("%s_PASSWORD=%s", prefix, password))

	u := url.URL{
		Scheme: scheme,
		Host:   fmt.Sprintf("%s:%s", host, port),
		Path:   path,
	}

	if username != "" || password != "" {
		u.User = url.UserPassword(username, password)
	}

	args = append(args, "-e", fmt.Sprintf("%s_URL=%s", prefix, u.String()))

	return args
}

func (ee Environment) Len() int           { return len(ee) }
func (ee Environment) Less(i, j int) bool { return ee[i].Name < ee[j].Name }
func (ee Environment) Swap(i, j int)      { ee[i], ee[j] = ee[j], ee[i] }

// LabelsByPrefix retuns a map of string values with the labels filtered by prefix
func (s Service) LabelsByPrefix(prefix string) map[string]string {
	returnLabels := make(map[string]string)
	for k, v := range s.Labels {
		if strings.HasPrefix(k, prefix) {
			returnLabels[k] = v
		}
	}
	return returnLabels
}

// LabelDefault returns the value of a given label if it exists, otherwise the specified default
func (s Service) LabelDefault(label, def string) string {
	if val, ok := s.Labels[label]; ok {
		return val
	}

	return def
}

// ExternalPorts returns a collection of Port structs from the Service which are TCP and Public
func (s Service) ExternalPorts() []Port {
	ports := []Port{}

	for _, port := range s.Ports {
		if port.Public && port.Protocol == TCP {
			ports = append(ports, port)
		}
	}

	return ports
}

// InternalPorts returns a collection of Port structs from the Service which are TCP and not Public
func (s Service) InternalPorts() []Port {
	ports := []Port{}

	for _, port := range s.Ports {
		if !port.Public && port.Protocol == TCP {
			ports = append(ports, port)
		}
	}

	return ports
}

// TCPPorts returns a collection of Port structs from the Service which are TCP
func (s Service) TCPPorts() []Port {
	ports := []Port{}

	for _, port := range s.Ports {
		if port.Protocol == TCP {
			ports = append(ports, port)
		}
	}

	return ports
}

// UDPPorts returns a collection of Port structs from the Service which are UDP
func (s Service) UDPPorts() []Port {
	ports := []Port{}

	for _, port := range s.Ports {
		if port.Protocol == UDP {
			ports = append(ports, port)
		}
	}

	return ports
}

func (s Service) ContainerPorts() []string {
	ext := []string{}

	for _, port := range s.Ports {
		if port.Container != 0 {
			ext = append(ext, strconv.Itoa(port.Container))
		}
	}

	sort.Strings(ext)

	return ext
}

func (s Service) ParamName(name string) string {
	return fmt.Sprintf("%s%s", UpperName(s.Name), name)
}

func (s Service) RegistryImage(appName, buildId string, outputs map[string]string) string {
	if registryId := outputs["RegistryId"]; registryId != "" {
		return fmt.Sprintf("%s.dkr.ecr.%s.amazonaws.com/%s:%s.%s", registryId, os.Getenv("AWS_REGION"), outputs["RegistryRepository"], s.Name, buildId)
	}

	return fmt.Sprintf("%s/%s-%s:%s", os.Getenv("REGISTRY_HOST"), appName, s.Name, buildId)
}

//ExtraHostsMap is a convenience method to allow for easier use of the hosts in
//AWS templates
func (s Service) ExtraHostsMap() map[string]string {
	res := map[string]string{}
	for _, str := range s.ExtraHosts {
		parts := strings.Split(str, ":")
		res[parts[0]] = parts[1]
	}
	return res
}

func (s *Service) Randoms() map[string]int {
	if s.randoms != nil {
		return s.randoms
	}

	currentPort := 5000
	s.randoms = make(map[string]int)
	for _, port := range s.Ports {
		if ManifestRandomPorts {
			s.randoms[strconv.Itoa(port.Balancer)] = rand.Intn(62000) + 3000
		} else {
			s.randoms[strconv.Itoa(port.Balancer)] = currentPort
			currentPort += 1
		}
	}
	return s.randoms
}

func (ss Services) Len() int {
	return len(ss)
}

func (ss Services) Less(i, j int) bool {
	return ss[i].Name < ss[j].Name
}

func (ss Services) Swap(i, j int) {
	ss[i], ss[j] = ss[j], ss[i]
}