text:
// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2008-2016 Konstantinos Margaritis <markos@freevec.org>
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.

#ifndef EIGEN_PACKET_MATH_ALTIVEC_H
#define EIGEN_PACKET_MATH_ALTIVEC_H

namespace Eigen {

namespace internal {

#ifndef EIGEN_CACHEFRIENDLY_PRODUCT_THRESHOLD
#define EIGEN_CACHEFRIENDLY_PRODUCT_THRESHOLD 4
#endif

#ifndef EIGEN_HAS_SINGLE_INSTRUCTION_MADD
#define EIGEN_HAS_SINGLE_INSTRUCTION_MADD
#endif

#ifndef EIGEN_HAS_SINGLE_INSTRUCTION_CJMADD
#define EIGEN_HAS_SINGLE_INSTRUCTION_CJMADD
#endif

// NOTE Altivec has 32 registers, but Eigen only accepts a value of 8 or 16
#ifndef EIGEN_ARCH_DEFAULT_NUMBER_OF_REGISTERS
#define EIGEN_ARCH_DEFAULT_NUMBER_OF_REGISTERS  32
#endif

typedef __vector float          Packet4f;
typedef __vector int            Packet4i;
typedef __vector unsigned int   Packet4ui;
typedef __vector __bool int     Packet4bi;
typedef __vector short int      Packet8i;
typedef __vector unsigned char  Packet16uc;

// We don't want to write the same code all the time, but we need to reuse the constants
// and it doesn't really work to declare them global, so we define macros instead

#define _EIGEN_DECLARE_CONST_FAST_Packet4f(NAME,X) \
  Packet4f p4f_##NAME = reinterpret_cast<Packet4f>(vec_splat_s32(X))

#define _EIGEN_DECLARE_CONST_FAST_Packet4i(NAME,X) \
  Packet4i p4i_##NAME = vec_splat_s32(X)

#define _EIGEN_DECLARE_CONST_Packet4f(NAME,X) \
  Packet4f p4f_##NAME = pset1<Packet4f>(X)

#define _EIGEN_DECLARE_CONST_Packet4i(NAME,X) \
  Packet4i p4i_##NAME = pset1<Packet4i>(X)

#define _EIGEN_DECLARE_CONST_Packet2d(NAME,X) \
  Packet2d p2d_##NAME = pset1<Packet2d>(X)

#define _EIGEN_DECLARE_CONST_Packet2l(NAME,X) \
  Packet2l p2l_##NAME = pset1<Packet2l>(X)

#define _EIGEN_DECLARE_CONST_Packet4f_FROM_INT(NAME,X) \
  const Packet4f p4f_##NAME = reinterpret_cast<Packet4f>(pset1<Packet4i>(X))

#define DST_CHAN 1
#define DST_CTRL(size, count, stride) (((size) << 24) | ((count) << 16) | (stride))

// These constants are endian-agnostic
static _EIGEN_DECLARE_CONST_FAST_Packet4f(ZERO, 0); //{ 0.0, 0.0, 0.0, 0.0}
static _EIGEN_DECLARE_CONST_FAST_Packet4i(ZERO, 0); //{ 0, 0, 0, 0,}
static _EIGEN_DECLARE_CONST_FAST_Packet4i(ONE,1); //{ 1, 1, 1, 1}
static _EIGEN_DECLARE_CONST_FAST_Packet4i(MINUS16,-16); //{ -16, -16, -16, -16}
static _EIGEN_DECLARE_CONST_FAST_Packet4i(MINUS1,-1); //{ -1, -1, -1, -1}
static Packet4f p4f_MZERO = (Packet4f) vec_sl((Packet4ui)p4i_MINUS1, (Packet4ui)p4i_MINUS1); //{ 0x80000000, 0x80000000, 0x80000000, 0x80000000}
#ifndef __VSX__
static Packet4f p4f_ONE = vec_ctf(p4i_ONE, 0); //{ 1.0, 1.0, 1.0, 1.0}
#endif

static Packet4f p4f_COUNTDOWN = { 0.0, 1.0, 2.0, 3.0 };
static Packet4i p4i_COUNTDOWN = { 0, 1, 2, 3 };

static Packet16uc p16uc_REVERSE32 = { 12,13,14,15, 8,9,10,11, 4,5,6,7, 0,1,2,3 };
static Packet16uc p16uc_DUPLICATE32_HI = { 0,1,2,3, 0,1,2,3, 4,5,6,7, 4,5,6,7 };

// Mask alignment
#ifdef __PPC64__
#define _EIGEN_MASK_ALIGNMENT	0xfffffffffffffff0
#else
#define _EIGEN_MASK_ALIGNMENT	0xfffffff0
#endif

#define _EIGEN_ALIGNED_PTR(x)	((std::ptrdiff_t)(x) & _EIGEN_MASK_ALIGNMENT)

// Handle endianness properly while loading constants
// Define global static constants:
#ifdef _BIG_ENDIAN
static Packet16uc p16uc_FORWARD = vec_lvsl(0, (float*)0);
#ifdef __VSX__
static Packet16uc p16uc_REVERSE64 = { 8,9,10,11, 12,13,14,15, 0,1,2,3, 4,5,6,7 };
#endif
static Packet16uc p16uc_PSET32_WODD   = vec_sld((Packet16uc) vec_splat((Packet4ui)p16uc_FORWARD, 0), (Packet16uc) vec_splat((Packet4ui)p16uc_FORWARD, 2), 8);//{ 0,1,2,3, 0,1,2,3, 8,9,10,11, 8,9,10,11 };
static Packet16uc p16uc_PSET32_WEVEN  = vec_sld(p16uc_DUPLICATE32_HI, (Packet16uc) vec_splat((Packet4ui)p16uc_FORWARD, 3), 8);//{ 4,5,6,7, 4,5,6,7, 12,13,14,15, 12,13,14,15 };
static Packet16uc p16uc_HALF64_0_16 = vec_sld((Packet16uc)p4i_ZERO, vec_splat((Packet16uc) vec_abs(p4i_MINUS16), 3), 8);      //{ 0,0,0,0, 0,0,0,0, 16,16,16,16, 16,16,16,16};
#else
static Packet16uc p16uc_FORWARD = p16uc_REVERSE32;
static Packet16uc p16uc_REVERSE64 = { 8,9,10,11, 12,13,14,15, 0,1,2,3, 4,5,6,7 };
static Packet16uc p16uc_PSET32_WODD = vec_sld((Packet16uc) vec_splat((Packet4ui)p16uc_FORWARD, 1), (Packet16uc) vec_splat((Packet4ui)p16uc_FORWARD, 3), 8);//{ 0,1,2,3, 0,1,2,3, 8,9,10,11, 8,9,10,11 };
static Packet16uc p16uc_PSET32_WEVEN = vec_sld((Packet16uc) vec_splat((Packet4ui)p16uc_FORWARD, 0), (Packet16uc) vec_splat((Packet4ui)p16uc_FORWARD, 2), 8);//{ 4,5,6,7, 4,5,6,7, 12,13,14,15, 12,13,14,15 };
static Packet16uc p16uc_HALF64_0_16 = vec_sld(vec_splat((Packet16uc) vec_abs(p4i_MINUS16), 0), (Packet16uc)p4i_ZERO, 8);      //{ 0,0,0,0, 0,0,0,0, 16,16,16,16, 16,16,16,16};
#endif // _BIG_ENDIAN

static Packet16uc p16uc_PSET64_HI = (Packet16uc) vec_mergeh((Packet4ui)p16uc_PSET32_WODD, (Packet4ui)p16uc_PSET32_WEVEN);     //{ 0,1,2,3, 4,5,6,7, 0,1,2,3, 4,5,6,7 };
static Packet16uc p16uc_PSET64_LO = (Packet16uc) vec_mergel((Packet4ui)p16uc_PSET32_WODD, (Packet4ui)p16uc_PSET32_WEVEN);     //{ 8,9,10,11, 12,13,14,15, 8,9,10,11, 12,13,14,15 };
static Packet16uc p16uc_TRANSPOSE64_HI = p16uc_PSET64_HI + p16uc_HALF64_0_16;                                         //{ 0,1,2,3, 4,5,6,7, 16,17,18,19, 20,21,22,23};
static Packet16uc p16uc_TRANSPOSE64_LO = p16uc_PSET64_LO + p16uc_HALF64_0_16;                                         //{ 8,9,10,11, 12,13,14,15, 24,25,26,27, 28,29,30,31};

static Packet16uc p16uc_COMPLEX32_REV = vec_sld(p16uc_REVERSE32, p16uc_REVERSE32, 8);                                         //{ 4,5,6,7, 0,1,2,3, 12,13,14,15, 8,9,10,11 };

#ifdef _BIG_ENDIAN
static Packet16uc p16uc_COMPLEX32_REV2 = vec_sld(p16uc_FORWARD, p16uc_FORWARD, 8);                                            //{ 8,9,10,11, 12,13,14,15, 0,1,2,3, 4,5,6,7 };
#else
static Packet16uc p16uc_COMPLEX32_REV2 = vec_sld(p16uc_PSET64_HI, p16uc_PSET64_LO, 8);                                            //{ 8,9,10,11, 12,13,14,15, 0,1,2,3, 4,5,6,7 };
#endif // _BIG_ENDIAN

#if EIGEN_HAS_BUILTIN(__builtin_prefetch) || EIGEN_COMP_GNUC
  #define EIGEN_PPC_PREFETCH(ADDR) __builtin_prefetch(ADDR);
#else
  #define EIGEN_PPC_PREFETCH(ADDR) asm( "   dcbt [%[addr]]\n" :: [addr] "r" (ADDR) : "cc" );
#endif

template<> struct packet_traits<float>  : default_packet_traits
{
  typedef Packet4f type;
  typedef Packet4f half;
  enum {
    Vectorizable = 1,
    AlignedOnScalar = 1,
    size=4,
    HasHalfPacket = 1,

    HasAdd  = 1,
    HasSub  = 1,
    HasMul  = 1,
    HasDiv  = 1,
    HasMin  = 1,
    HasMax  = 1,
    HasAbs  = 1,
    HasSin  = 0,
    HasCos  = 0,
    HasLog  = 0,
    HasExp  = 1,
#ifdef __VSX__
    HasSqrt = 1,
#if !EIGEN_COMP_CLANG
    HasRsqrt = 1,
#else
    HasRsqrt = 0,
#endif
#else
    HasSqrt = 0,
    HasRsqrt = 0,
#endif
    HasRound = 1,
    HasFloor = 1,
    HasCeil = 1,
    HasNegate = 1,
    HasBlend = 1
  };
};
template<> struct packet_traits<int>    : default_packet_traits
{
  typedef Packet4i type;
  typedef Packet4i half;
  enum {
    Vectorizable = 1,
    AlignedOnScalar = 1,
    size = 4,
    HasHalfPacket = 0,

    HasAdd  = 1,
    HasSub  = 1,
    HasMul  = 1,
    HasDiv  = 0,
    HasBlend = 1
  };
};

template<> struct unpacket_traits<Packet4f> { typedef float  type; enum {size=4, alignment=Aligned16}; typedef Packet4f half; };
template<> struct unpacket_traits<Packet4i> { typedef int    type; enum {size=4, alignment=Aligned16}; typedef Packet4i half; };

inline std::ostream & operator <<(std::ostream & s, const Packet16uc & v)
{
  union {
    Packet16uc   v;
    unsigned char n[16];
  } vt;
  vt.v = v;
  for (int i=0; i< 16; i++)
    s << (int)vt.n[i] << ", ";
  return s;
}

inline std::ostream & operator <<(std::ostream & s, const Packet4f & v)
{
  union {
    Packet4f   v;
    float n[4];
  } vt;
  vt.v = v;
  s << vt.n[0] << ", " << vt.n[1] << ", " << vt.n[2] << ", " << vt.n[3];
  return s;
}

inline std::ostream & operator <<(std::ostream & s, const Packet4i & v)
{
  union {
    Packet4i   v;
    int n[4];
  } vt;
  vt.v = v;
  s << vt.n[0] << ", " << vt.n[1] << ", " << vt.n[2] << ", " << vt.n[3];
  return s;
}

inline std::ostream & operator <<(std::ostream & s, const Packet4ui & v)
{
  union {
    Packet4ui   v;
    unsigned int n[4];
  } vt;
  vt.v = v;
  s << vt.n[0] << ", " << vt.n[1] << ", " << vt.n[2] << ", " << vt.n[3];
  return s;
}

// Need to define them first or we get specialization after instantiation errors
template<> EIGEN_STRONG_INLINE Packet4f pload<Packet4f>(const float* from)
{
  EIGEN_DEBUG_ALIGNED_LOAD
#ifdef __VSX__
  return vec_vsx_ld(0, from);
#else
  return vec_ld(0, from);
#endif
}

template<> EIGEN_STRONG_INLINE Packet4i pload<Packet4i>(const int*     from)
{
  EIGEN_DEBUG_ALIGNED_LOAD
#ifdef __VSX__
  return vec_vsx_ld(0, from);
#else
  return vec_ld(0, from);
#endif
}

template<> EIGEN_STRONG_INLINE void pstore<float>(float*   to, const Packet4f& from)
{
  EIGEN_DEBUG_ALIGNED_STORE
#ifdef __VSX__
  vec_vsx_st(from, 0, to);
#else
  vec_st(from, 0, to);
#endif
}

template<> EIGEN_STRONG_INLINE void pstore<int>(int*       to, const Packet4i& from)
{
  EIGEN_DEBUG_ALIGNED_STORE
#ifdef __VSX__
  vec_vsx_st(from, 0, to);
#else
  vec_st(from, 0, to);
#endif
}

template<> EIGEN_STRONG_INLINE Packet4f pset1<Packet4f>(const float&  from) {
  Packet4f v = {from, from, from, from};
  return v;
}

template<> EIGEN_STRONG_INLINE Packet4i pset1<Packet4i>(const int&    from)   {
  Packet4i v = {from, from, from, from};
  return v;
}
template<> EIGEN_STRONG_INLINE void
pbroadcast4<Packet4f>(const float *a,
                      Packet4f& a0, Packet4f& a1, Packet4f& a2, Packet4f& a3)
{
  a3 = pload<Packet4f>(a);
  a0 = vec_splat(a3, 0);
  a1 = vec_splat(a3, 1);
  a2 = vec_splat(a3, 2);
  a3 = vec_splat(a3, 3);
}
template<> EIGEN_STRONG_INLINE void
pbroadcast4<Packet4i>(const int *a,
                      Packet4i& a0, Packet4i& a1, Packet4i& a2, Packet4i& a3)
{
  a3 = pload<Packet4i>(a);
  a0 = vec_splat(a3, 0);
  a1 = vec_splat(a3, 1);
  a2 = vec_splat(a3, 2);
  a3 = vec_splat(a3, 3);
}

template<> EIGEN_DEVICE_FUNC inline Packet4f pgather<float, Packet4f>(const float* from, Index stride)
{
  float EIGEN_ALIGN16 af[4];
  af[0] = from[0*stride];
  af[1] = from[1*stride];
  af[2] = from[2*stride];
  af[3] = from[3*stride];
 return pload<Packet4f>(af);
}
template<> EIGEN_DEVICE_FUNC inline Packet4i pgather<int, Packet4i>(const int* from, Index stride)
{
  int EIGEN_ALIGN16 ai[4];
  ai[0] = from[0*stride];
  ai[1] = from[1*stride];
  ai[2] = from[2*stride];
  ai[3] = from[3*stride];
 return pload<Packet4i>(ai);
}
template<> EIGEN_DEVICE_FUNC inline void pscatter<float, Packet4f>(float* to, const Packet4f& from, Index stride)
{
  float EIGEN_ALIGN16 af[4];
  pstore<float>(af, from);
  to[0*stride] = af[0];
  to[1*stride] = af[1];
  to[2*stride] = af[2];
  to[3*stride] = af[3];
}
template<> EIGEN_DEVICE_FUNC inline void pscatter<int, Packet4i>(int* to, const Packet4i& from, Index stride)
{
  int EIGEN_ALIGN16 ai[4];
  pstore<int>((int *)ai, from);
  to[0*stride] = ai[0];
  to[1*stride] = ai[1];
  to[2*stride] = ai[2];
  to[3*stride] = ai[3];
}

template<> EIGEN_STRONG_INLINE Packet4f plset<Packet4f>(const float& a) { return pset1<Packet4f>(a) + p4f_COUNTDOWN; }
template<> EIGEN_STRONG_INLINE Packet4i plset<Packet4i>(const int& a)   { return pset1<Packet4i>(a) + p4i_COUNTDOWN; }

template<> EIGEN_STRONG_INLINE Packet4f padd<Packet4f>(const Packet4f& a, const Packet4f& b) { return a + b; }
template<> EIGEN_STRONG_INLINE Packet4i padd<Packet4i>(const Packet4i& a, const Packet4i& b) { return a + b; }

template<> EIGEN_STRONG_INLINE Packet4f psub<Packet4f>(const Packet4f& a, const Packet4f& b) { return a - b; }
template<> EIGEN_STRONG_INLINE Packet4i psub<Packet4i>(const Packet4i& a, const Packet4i& b) { return a - b; }

template<> EIGEN_STRONG_INLINE Packet4f pnegate(const Packet4f& a) { return p4f_ZERO - a; }
template<> EIGEN_STRONG_INLINE Packet4i pnegate(const Packet4i& a) { return p4i_ZERO - a; }

template<> EIGEN_STRONG_INLINE Packet4f pconj(const Packet4f& a) { return a; }
template<> EIGEN_STRONG_INLINE Packet4i pconj(const Packet4i& a) { return a; }

template<> EIGEN_STRONG_INLINE Packet4f pmul<Packet4f>(const Packet4f& a, const Packet4f& b) { return vec_madd(a,b, p4f_MZERO); }
template<> EIGEN_STRONG_INLINE Packet4i pmul<Packet4i>(const Packet4i& a, const Packet4i& b) { return a * b; }

template<> EIGEN_STRONG_INLINE Packet4f pdiv<Packet4f>(const Packet4f& a, const Packet4f& b)
{
#ifndef __VSX__  // VSX actually provides a div instruction
  Packet4f t, y_0, y_1;

  // Altivec does not offer a divide instruction, we have to do a reciprocal approximation
  y_0 = vec_re(b);

  // Do one Newton-Raphson iteration to get the needed accuracy
  t   = vec_nmsub(y_0, b, p4f_ONE);
  y_1 = vec_madd(y_0, t, y_0);

  return vec_madd(a, y_1, p4f_MZERO);
#else
  return vec_div(a, b);
#endif
}

template<> EIGEN_STRONG_INLINE Packet4i pdiv<Packet4i>(const Packet4i& /*a*/, const Packet4i& /*b*/)
{ eigen_assert(false && "packet integer division are not supported by AltiVec");
  return pset1<Packet4i>(0);
}

// for some weird raisons, it has to be overloaded for packet of integers
template<> EIGEN_STRONG_INLINE Packet4f pmadd(const Packet4f& a, const Packet4f& b, const Packet4f& c) { return vec_madd(a,b,c); }
template<> EIGEN_STRONG_INLINE Packet4i pmadd(const Packet4i& a, const Packet4i& b, const Packet4i& c) { return a*b + c; }

template<> EIGEN_STRONG_INLINE Packet4f pmin<Packet4f>(const Packet4f& a, const Packet4f& b) { return vec_min(a, b); }
template<> EIGEN_STRONG_INLINE Packet4i pmin<Packet4i>(const Packet4i& a, const Packet4i& b) { return vec_min(a, b); }

template<> EIGEN_STRONG_INLINE Packet4f pmax<Packet4f>(const Packet4f& a, const Packet4f& b) { return vec_max(a, b); }
template<> EIGEN_STRONG_INLINE Packet4i pmax<Packet4i>(const Packet4i& a, const Packet4i& b) { return vec_max(a, b); }

template<> EIGEN_STRONG_INLINE Packet4f pand<Packet4f>(const Packet4f& a, const Packet4f& b) { return vec_and(a, b); }
template<> EIGEN_STRONG_INLINE Packet4i pand<Packet4i>(const Packet4i& a, const Packet4i& b) { return vec_and(a, b); }

template<> EIGEN_STRONG_INLINE Packet4f por<Packet4f>(const Packet4f& a, const Packet4f& b) { return vec_or(a, b); }
template<> EIGEN_STRONG_INLINE Packet4i por<Packet4i>(const Packet4i& a, const Packet4i& b) { return vec_or(a, b); }

template<> EIGEN_STRONG_INLINE Packet4f pxor<Packet4f>(const Packet4f& a, const Packet4f& b) { return vec_xor(a, b); }
template<> EIGEN_STRONG_INLINE Packet4i pxor<Packet4i>(const Packet4i& a, const Packet4i& b) { return vec_xor(a, b); }

template<> EIGEN_STRONG_INLINE Packet4f pandnot<Packet4f>(const Packet4f& a, const Packet4f& b) { return vec_and(a, vec_nor(b, b)); }
template<> EIGEN_STRONG_INLINE Packet4i pandnot<Packet4i>(const Packet4i& a, const Packet4i& b) { return vec_and(a, vec_nor(b, b)); }

template<> EIGEN_STRONG_INLINE Packet4f pround<Packet4f>(const Packet4f& a) { return vec_round(a); }
template<> EIGEN_STRONG_INLINE Packet4f pceil<Packet4f>(const  Packet4f& a) { return vec_ceil(a); }
template<> EIGEN_STRONG_INLINE Packet4f pfloor<Packet4f>(const Packet4f& a) { return vec_floor(a); }

#ifdef _BIG_ENDIAN
template<> EIGEN_STRONG_INLINE Packet4f ploadu<Packet4f>(const float* from)
{
  EIGEN_DEBUG_ALIGNED_LOAD
  Packet16uc MSQ, LSQ;
  Packet16uc mask;
  MSQ = vec_ld(0, (unsigned char *)from);          // most significant quadword
  LSQ = vec_ld(15, (unsigned char *)from);         // least significant quadword
  mask = vec_lvsl(0, from);                        // create the permute mask
  return (Packet4f) vec_perm(MSQ, LSQ, mask);           // align the data

}
template<> EIGEN_STRONG_INLINE Packet4i ploadu<Packet4i>(const int* from)
{
  EIGEN_DEBUG_ALIGNED_LOAD
  // Taken from http://developer.apple.com/hardwaredrivers/ve/alignment.html
  Packet16uc MSQ, LSQ;
  Packet16uc mask;
  MSQ = vec_ld(0, (unsigned char *)from);          // most significant quadword
  LSQ = vec_ld(15, (unsigned char *)from);         // least significant quadword
  mask = vec_lvsl(0, from);                        // create the permute mask
  return (Packet4i) vec_perm(MSQ, LSQ, mask);    // align the data
}
#else
// We also need ot redefine little endian loading of Packet4i/Packet4f using VSX
template<> EIGEN_STRONG_INLINE Packet4i ploadu<Packet4i>(const int* from)
{
  EIGEN_DEBUG_UNALIGNED_LOAD
  return (Packet4i) vec_vsx_ld((long)from & 15, (const int*) _EIGEN_ALIGNED_PTR(from));
}
template<> EIGEN_STRONG_INLINE Packet4f ploadu<Packet4f>(const float* from)
{
  EIGEN_DEBUG_UNALIGNED_LOAD
  return (Packet4f) vec_vsx_ld((long)from & 15, (const float*) _EIGEN_ALIGNED_PTR(from));
}
#endif

template<> EIGEN_STRONG_INLINE Packet4f ploaddup<Packet4f>(const float*   from)
{
  Packet4f p;
  if((std::ptrdiff_t(from) % 16) == 0)  p = pload<Packet4f>(from);
  else                                  p = ploadu<Packet4f>(from);
  return vec_perm(p, p, p16uc_DUPLICATE32_HI);
}
template<> EIGEN_STRONG_INLINE Packet4i ploaddup<Packet4i>(const int*     from)
{
  Packet4i p;
  if((std::ptrdiff_t(from) % 16) == 0)  p = pload<Packet4i>(from);
  else                                  p = ploadu<Packet4i>(from);
  return vec_perm(p, p, p16uc_DUPLICATE32_HI);
}

#ifdef _BIG_ENDIAN
template<> EIGEN_STRONG_INLINE void pstoreu<float>(float*  to, const Packet4f& from)
{
  EIGEN_DEBUG_UNALIGNED_STORE
  // Taken from http://developer.apple.com/hardwaredrivers/ve/alignment.html
  // Warning: not thread safe!
  Packet16uc MSQ, LSQ, edges;
  Packet16uc edgeAlign, align;

  MSQ = vec_ld(0, (unsigned char *)to);                     // most significant quadword
  LSQ = vec_ld(15, (unsigned char *)to);                    // least significant quadword
  edgeAlign = vec_lvsl(0, to);                              // permute map to extract edges
  edges=vec_perm(LSQ,MSQ,edgeAlign);                        // extract the edges
  align = vec_lvsr( 0, to );                                // permute map to misalign data
  MSQ = vec_perm(edges,(Packet16uc)from,align);             // misalign the data (MSQ)
  LSQ = vec_perm((Packet16uc)from,edges,align);             // misalign the data (LSQ)
  vec_st( LSQ, 15, (unsigned char *)to );                   // Store the LSQ part first
  vec_st( MSQ, 0, (unsigned char *)to );                    // Store the MSQ part
}
template<> EIGEN_STRONG_INLINE void pstoreu<int>(int*      to, const Packet4i& from)
{
  EIGEN_DEBUG_UNALIGNED_STORE
  // Taken from http://developer.apple.com/hardwaredrivers/ve/alignment.html
  // Warning: not thread safe!
  Packet16uc MSQ, LSQ, edges;
  Packet16uc edgeAlign, align;

  MSQ = vec_ld(0, (unsigned char *)to);                     // most significant quadword
  LSQ = vec_ld(15, (unsigned char *)to);                    // least significant quadword
  edgeAlign = vec_lvsl(0, to);                              // permute map to extract edges
  edges=vec_perm(LSQ, MSQ, edgeAlign);                      // extract the edges
  align = vec_lvsr( 0, to );                                // permute map to misalign data
  MSQ = vec_perm(edges, (Packet16uc) from, align);          // misalign the data (MSQ)
  LSQ = vec_perm((Packet16uc) from, edges, align);          // misalign the data (LSQ)
  vec_st( LSQ, 15, (unsigned char *)to );                   // Store the LSQ part first
  vec_st( MSQ, 0, (unsigned char *)to );                    // Store the MSQ part
}
#else
// We also need ot redefine little endian loading of Packet4i/Packet4f using VSX
template<> EIGEN_STRONG_INLINE void pstoreu<int>(int*       to, const Packet4i& from)
{
  EIGEN_DEBUG_ALIGNED_STORE
  vec_vsx_st(from, (long)to & 15, (int*) _EIGEN_ALIGNED_PTR(to));
}
template<> EIGEN_STRONG_INLINE void pstoreu<float>(float*   to, const Packet4f& from)
{
  EIGEN_DEBUG_ALIGNED_STORE
  vec_vsx_st(from, (long)to & 15, (float*) _EIGEN_ALIGNED_PTR(to));
}
#endif

template<> EIGEN_STRONG_INLINE void prefetch<float>(const float* addr)    { EIGEN_PPC_PREFETCH(addr); }
template<> EIGEN_STRONG_INLINE void prefetch<int>(const int*     addr)    { EIGEN_PPC_PREFETCH(addr); }

template<> EIGEN_STRONG_INLINE float  pfirst<Packet4f>(const Packet4f& a) { float EIGEN_ALIGN16 x; vec_ste(a, 0, &x); return x; }
template<> EIGEN_STRONG_INLINE int    pfirst<Packet4i>(const Packet4i& a) { int   EIGEN_ALIGN16 x; vec_ste(a, 0, &x); return x; }

template<> EIGEN_STRONG_INLINE Packet4f preverse(const Packet4f& a)
{
  return reinterpret_cast<Packet4f>(vec_perm(reinterpret_cast<Packet16uc>(a), reinterpret_cast<Packet16uc>(a), p16uc_REVERSE32));
}
template<> EIGEN_STRONG_INLINE Packet4i preverse(const Packet4i& a)
{
  return reinterpret_cast<Packet4i>(vec_perm(reinterpret_cast<Packet16uc>(a), reinterpret_cast<Packet16uc>(a), p16uc_REVERSE32)); }

template<> EIGEN_STRONG_INLINE Packet4f pabs(const Packet4f& a) { return vec_abs(a); }
template<> EIGEN_STRONG_INLINE Packet4i pabs(const Packet4i& a) { return vec_abs(a); }

template<> EIGEN_STRONG_INLINE float predux<Packet4f>(const Packet4f& a)
{
  Packet4f b, sum;
  b   = vec_sld(a, a, 8);
  sum = a + b;
  b   = vec_sld(sum, sum, 4);
  sum += b;
  return pfirst(sum);
}

template<> EIGEN_STRONG_INLINE Packet4f preduxp<Packet4f>(const Packet4f* vecs)
{
  Packet4f v[4], sum[4];

  // It's easier and faster to transpose then add as columns
  // Check: http://www.freevec.org/function/matrix_4x4_transpose_floats for explanation
  // Do the transpose, first set of moves
  v[0] = vec_mergeh(vecs[0], vecs[2]);
  v[1] = vec_mergel(vecs[0], vecs[2]);
  v[2] = vec_mergeh(vecs[1], vecs[3]);
  v[3] = vec_mergel(vecs[1], vecs[3]);
  // Get the resulting vectors
  sum[0] = vec_mergeh(v[0], v[2]);
  sum[1] = vec_mergel(v[0], v[2]);
  sum[2] = vec_mergeh(v[1], v[3]);
  sum[3] = vec_mergel(v[1], v[3]);

  // Now do the summation:
  // Lines 0+1
  sum[0] = sum[0] + sum[1];
  // Lines 2+3
  sum[1] = sum[2] + sum[3];
  // Add the results
  sum[0] = sum[0] + sum[1];

  return sum[0];
}

template<> EIGEN_STRONG_INLINE int predux<Packet4i>(const Packet4i& a)
{
  Packet4i sum;
  sum = vec_sums(a, p4i_ZERO);
#ifdef _BIG_ENDIAN
  sum = vec_sld(sum, p4i_ZERO, 12);
#else
  sum = vec_sld(p4i_ZERO, sum, 4);
#endif
  return pfirst(sum);
}

template<> EIGEN_STRONG_INLINE Packet4i preduxp<Packet4i>(const Packet4i* vecs)
{
  Packet4i v[4], sum[4];

  // It's easier and faster to transpose then add as columns
  // Check: http://www.freevec.org/function/matrix_4x4_transpose_floats for explanation
  // Do the transpose, first set of moves
  v[0] = vec_mergeh(vecs[0], vecs[2]);
  v[1] = vec_mergel(vecs[0], vecs[2]);
  v[2] = vec_mergeh(vecs[1], vecs[3]);
  v[3] = vec_mergel(vecs[1], vecs[3]);
  // Get the resulting vectors
  sum[0] = vec_mergeh(v[0], v[2]);
  sum[1] = vec_mergel(v[0], v[2]);
  sum[2] = vec_mergeh(v[1], v[3]);
  sum[3] = vec_mergel(v[1], v[3]);

  // Now do the summation:
  // Lines 0+1
  sum[0] = sum[0] + sum[1];
  // Lines 2+3
  sum[1] = sum[2] + sum[3];
  // Add the results
  sum[0] = sum[0] + sum[1];

  return sum[0];
}

// Other reduction functions:
// mul
template<> EIGEN_STRONG_INLINE float predux_mul<Packet4f>(const Packet4f& a)
{
  Packet4f prod;
  prod = pmul(a, vec_sld(a, a, 8));
  return pfirst(pmul(prod, vec_sld(prod, prod, 4)));
}

template<> EIGEN_STRONG_INLINE int predux_mul<Packet4i>(const Packet4i& a)
{
  EIGEN_ALIGN16 int aux[4];
  pstore(aux, a);
  return aux[0] * aux[1] * aux[2] * aux[3];
}

// min
template<> EIGEN_STRONG_INLINE float predux_min<Packet4f>(const Packet4f& a)
{
  Packet4f b, res;
  b = vec_min(a, vec_sld(a, a, 8));
  res = vec_min(b, vec_sld(b, b, 4));
  return pfirst(res);
}

template<> EIGEN_STRONG_INLINE int predux_min<Packet4i>(const Packet4i& a)
{
  Packet4i b, res;
  b = vec_min(a, vec_sld(a, a, 8));
  res = vec_min(b, vec_sld(b, b, 4));
  return pfirst(res);
}

// max
template<> EIGEN_STRONG_INLINE float predux_max<Packet4f>(const Packet4f& a)
{
  Packet4f b, res;
  b = vec_max(a, vec_sld(a, a, 8));
  res = vec_max(b, vec_sld(b, b, 4));
  return pfirst(res);
}

template<> EIGEN_STRONG_INLINE int predux_max<Packet4i>(const Packet4i& a)
{
  Packet4i b, res;
  b = vec_max(a, vec_sld(a, a, 8));
  res = vec_max(b, vec_sld(b, b, 4));
  return pfirst(res);
}

template<int Offset>
struct palign_impl<Offset,Packet4f>
{
  static EIGEN_STRONG_INLINE void run(Packet4f& first, const Packet4f& second)
  {
#ifdef _BIG_ENDIAN
    switch (Offset % 4) {
    case 1:
      first = vec_sld(first, second, 4); break;
    case 2:
      first = vec_sld(first, second, 8); break;
    case 3:
      first = vec_sld(first, second, 12); break;
    }
#else
    switch (Offset % 4) {
    case 1:
      first = vec_sld(second, first, 12); break;
    case 2:
      first = vec_sld(second, first, 8); break;
    case 3:
      first = vec_sld(second, first, 4); break;
    }
#endif
  }
};

template<int Offset>
struct palign_impl<Offset,Packet4i>
{
  static EIGEN_STRONG_INLINE void run(Packet4i& first, const Packet4i& second)
  {
#ifdef _BIG_ENDIAN
    switch (Offset % 4) {
    case 1:
      first = vec_sld(first, second, 4); break;
    case 2:
      first = vec_sld(first, second, 8); break;
    case 3:
      first = vec_sld(first, second, 12); break;
    }
#else
    switch (Offset % 4) {
    case 1:
      first = vec_sld(second, first, 12); break;
    case 2:
      first = vec_sld(second, first, 8); break;
    case 3:
      first = vec_sld(second, first, 4); break;
    }
#endif
  }
};

EIGEN_DEVICE_FUNC inline void
ptranspose(PacketBlock<Packet4f,4>& kernel) {
  Packet4f t0, t1, t2, t3;
  t0 = vec_mergeh(kernel.packet[0], kernel.packet[2]);
  t1 = vec_mergel(kernel.packet[0], kernel.packet[2]);
  t2 = vec_mergeh(kernel.packet[1], kernel.packet[3]);
  t3 = vec_mergel(kernel.packet[1], kernel.packet[3]);
  kernel.packet[0] = vec_mergeh(t0, t2);
  kernel.packet[1] = vec_mergel(t0, t2);
  kernel.packet[2] = vec_mergeh(t1, t3);
  kernel.packet[3] = vec_mergel(t1, t3);
}

EIGEN_DEVICE_FUNC inline void
ptranspose(PacketBlock<Packet4i,4>& kernel) {
  Packet4i t0, t1, t2, t3;
  t0 = vec_mergeh(kernel.packet[0], kernel.packet[2]);
  t1 = vec_mergel(kernel.packet[0], kernel.packet[2]);
  t2 = vec_mergeh(kernel.packet[1], kernel.packet[3]);
  t3 = vec_mergel(kernel.packet[1], kernel.packet[3]);
  kernel.packet[0] = vec_mergeh(t0, t2);
  kernel.packet[1] = vec_mergel(t0, t2);
  kernel.packet[2] = vec_mergeh(t1, t3);
  kernel.packet[3] = vec_mergel(t1, t3);
}

template<> EIGEN_STRONG_INLINE Packet4i pblend(const Selector<4>& ifPacket, const Packet4i& thenPacket, const Packet4i& elsePacket) {
  Packet4ui select = { ifPacket.select[0], ifPacket.select[1], ifPacket.select[2], ifPacket.select[3] };
  Packet4ui mask = reinterpret_cast<Packet4ui>(vec_cmpeq(reinterpret_cast<Packet4ui>(select), reinterpret_cast<Packet4ui>(p4i_ONE)));
  return vec_sel(elsePacket, thenPacket, mask);
}

template<> EIGEN_STRONG_INLINE Packet4f pblend(const Selector<4>& ifPacket, const Packet4f& thenPacket, const Packet4f& elsePacket) {
  Packet4ui select = { ifPacket.select[0], ifPacket.select[1], ifPacket.select[2], ifPacket.select[3] };
  Packet4ui mask = reinterpret_cast<Packet4ui>(vec_cmpeq(reinterpret_cast<Packet4ui>(select), reinterpret_cast<Packet4ui>(p4i_ONE)));
  return vec_sel(elsePacket, thenPacket, mask);
}

//---------- double ----------
#ifdef __VSX__
typedef __vector double              Packet2d;
typedef __vector unsigned long long  Packet2ul;
typedef __vector long long           Packet2l;
#if EIGEN_COMP_CLANG
typedef Packet2ul                    Packet2bl;
#else
typedef __vector __bool long         Packet2bl;
#endif

static Packet2l  p2l_ONE  = { 1, 1 };
static Packet2l  p2l_ZERO = reinterpret_cast<Packet2l>(p4i_ZERO);
static Packet2d  p2d_ONE  = { 1.0, 1.0 };
static Packet2d  p2d_ZERO = reinterpret_cast<Packet2d>(p4f_ZERO);
static Packet2d  p2d_MZERO = { -0.0, -0.0 };

#ifdef _BIG_ENDIAN
static Packet2d p2d_COUNTDOWN = reinterpret_cast<Packet2d>(vec_sld(reinterpret_cast<Packet4f>(p2d_ZERO), reinterpret_cast<Packet4f>(p2d_ONE), 8));
#else
static Packet2d p2d_COUNTDOWN = reinterpret_cast<Packet2d>(vec_sld(reinterpret_cast<Packet4f>(p2d_ONE), reinterpret_cast<Packet4f>(p2d_ZERO), 8));
#endif

template<int index> Packet2d vec_splat_dbl(Packet2d& a);

template<> EIGEN_STRONG_INLINE Packet2d vec_splat_dbl<0>(Packet2d& a)
{
  return reinterpret_cast<Packet2d>(vec_perm(a, a, p16uc_PSET64_HI));
}

template<> EIGEN_STRONG_INLINE Packet2d vec_splat_dbl<1>(Packet2d& a)
{
  return reinterpret_cast<Packet2d>(vec_perm(a, a, p16uc_PSET64_LO));
}

template<> struct packet_traits<double> : default_packet_traits
{
  typedef Packet2d type;
  typedef Packet2d half;
  enum {
    Vectorizable = 1,
    AlignedOnScalar = 1,
    size=2,
    HasHalfPacket = 1,

    HasAdd  = 1,
    HasSub  = 1,
    HasMul  = 1,
    HasDiv  = 1,
    HasMin  = 1,
    HasMax  = 1,
    HasAbs  = 1,
    HasSin  = 0,
    HasCos  = 0,
    HasLog  = 0,
    HasExp  = 1,
    HasSqrt = 1,
    HasRsqrt = 1,
    HasRound = 1,
    HasFloor = 1,
    HasCeil = 1,
    HasNegate = 1,
    HasBlend = 1
  };
};

template<> struct unpacket_traits<Packet2d> { typedef double type; enum {size=2, alignment=Aligned16}; typedef Packet2d half; };

inline std::ostream & operator <<(std::ostream & s, const Packet2l & v)
{
  union {
    Packet2l   v;
    int64_t n[2];
  } vt;
  vt.v = v;
  s << vt.n[0] << ", " << vt.n[1];
  return s;
}

inline std::ostream & operator <<(std::ostream & s, const Packet2d & v)
{
  union {
    Packet2d   v;
    double n[2];
  } vt;
  vt.v = v;
  s << vt.n[0] << ", " << vt.n[1];
  return s;
}

// Need to define them first or we get specialization after instantiation errors
template<> EIGEN_STRONG_INLINE Packet2d pload<Packet2d>(const double* from)
{
  EIGEN_DEBUG_ALIGNED_LOAD
#ifdef __VSX__
  return vec_vsx_ld(0, from);
#else
  return vec_ld(0, from);
#endif
}

template<> EIGEN_STRONG_INLINE void pstore<double>(double*   to, const Packet2d& from)
{
  EIGEN_DEBUG_ALIGNED_STORE
#ifdef __VSX__
  vec_vsx_st(from, 0, to);
#else
  vec_st(from, 0, to);
#endif
}

template<> EIGEN_STRONG_INLINE Packet2d pset1<Packet2d>(const double&  from) {
  Packet2d v = {from, from};
  return v;
}

template<> EIGEN_STRONG_INLINE void
pbroadcast4<Packet2d>(const double *a,
                      Packet2d& a0, Packet2d& a1, Packet2d& a2, Packet2d& a3)
{
  a1 = pload<Packet2d>(a);
  a0 = vec_splat_dbl<0>(a1);
  a1 = vec_splat_dbl<1>(a1);
  a3 = pload<Packet2d>(a+2);
  a2 = vec_splat_dbl<0>(a3);
  a3 = vec_splat_dbl<1>(a3);
}

template<> EIGEN_DEVICE_FUNC inline Packet2d pgather<double, Packet2d>(const double* from, Index stride)
{
  double EIGEN_ALIGN16 af[2];
  af[0] = from[0*stride];
  af[1] = from[1*stride];
 return pload<Packet2d>(af);
}
template<> EIGEN_DEVICE_FUNC inline void pscatter<double, Packet2d>(double* to, const Packet2d& from, Index stride)
{
  double EIGEN_ALIGN16 af[2];
  pstore<double>(af, from);
  to[0*stride] = af[0];
  to[1*stride] = af[1];
}

template<> EIGEN_STRONG_INLINE Packet2d plset<Packet2d>(const double& a) { return pset1<Packet2d>(a) + p2d_COUNTDOWN; }

template<> EIGEN_STRONG_INLINE Packet2d padd<Packet2d>(const Packet2d& a, const Packet2d& b) { return a + b; }

template<> EIGEN_STRONG_INLINE Packet2d psub<Packet2d>(const Packet2d& a, const Packet2d& b) { return a - b; }

template<> EIGEN_STRONG_INLINE Packet2d pnegate(const Packet2d& a) { return p2d_ZERO - a; }

template<> EIGEN_STRONG_INLINE Packet2d pconj(const Packet2d& a) { return a; }

template<> EIGEN_STRONG_INLINE Packet2d pmul<Packet2d>(const Packet2d& a, const Packet2d& b) { return vec_madd(a,b,p2d_MZERO); }
template<> EIGEN_STRONG_INLINE Packet2d pdiv<Packet2d>(const Packet2d& a, const Packet2d& b) { return vec_div(a,b); }

// for some weird raisons, it has to be overloaded for packet of integers
template<> EIGEN_STRONG_INLINE Packet2d pmadd(const Packet2d& a, const Packet2d& b, const Packet2d& c) { return vec_madd(a, b, c); }

template<> EIGEN_STRONG_INLINE Packet2d pmin<Packet2d>(const Packet2d& a, const Packet2d& b) { return vec_min(a, b); }

template<> EIGEN_STRONG_INLINE Packet2d pmax<Packet2d>(const Packet2d& a, const Packet2d& b) { return vec_max(a, b); }

template<> EIGEN_STRONG_INLINE Packet2d pand<Packet2d>(const Packet2d& a, const Packet2d& b) { return vec_and(a, b); }

template<> EIGEN_STRONG_INLINE Packet2d por<Packet2d>(const Packet2d& a, const Packet2d& b) { return vec_or(a, b); }

template<> EIGEN_STRONG_INLINE Packet2d pxor<Packet2d>(const Packet2d& a, const Packet2d& b) { return vec_xor(a, b); }

template<> EIGEN_STRONG_INLINE Packet2d pandnot<Packet2d>(const Packet2d& a, const Packet2d& b) { return vec_and(a, vec_nor(b, b)); }

template<> EIGEN_STRONG_INLINE Packet2d pround<Packet2d>(const Packet2d& a) { return vec_round(a); }
template<> EIGEN_STRONG_INLINE Packet2d pceil<Packet2d>(const  Packet2d& a) { return vec_ceil(a); }
template<> EIGEN_STRONG_INLINE Packet2d pfloor<Packet2d>(const Packet2d& a) { return vec_floor(a); }

template<> EIGEN_STRONG_INLINE Packet2d ploadu<Packet2d>(const double* from)
{
  EIGEN_DEBUG_ALIGNED_LOAD
  return (Packet2d) vec_vsx_ld((long)from & 15, (const double*) _EIGEN_ALIGNED_PTR(from));
}

template<> EIGEN_STRONG_INLINE Packet2d ploaddup<Packet2d>(const double*   from)
{
  Packet2d p;
  if((std::ptrdiff_t(from) % 16) == 0)  p = pload<Packet2d>(from);
  else                                  p = ploadu<Packet2d>(from);
  return vec_splat_dbl<0>(p);
}

template<> EIGEN_STRONG_INLINE void pstoreu<double>(double*  to, const Packet2d& from)
{
  EIGEN_DEBUG_ALIGNED_STORE
  vec_vsx_st((Packet4f)from, (long)to & 15, (float*) _EIGEN_ALIGNED_PTR(to));
}

template<> EIGEN_STRONG_INLINE void prefetch<double>(const double* addr) { EIGEN_PPC_PREFETCH(addr); }

template<> EIGEN_STRONG_INLINE double  pfirst<Packet2d>(const Packet2d& a) { double EIGEN_ALIGN16 x[2]; pstore<double>(x, a); return x[0]; }

template<> EIGEN_STRONG_INLINE Packet2d preverse(const Packet2d& a)
{
  return reinterpret_cast<Packet2d>(vec_perm(reinterpret_cast<Packet16uc>(a), reinterpret_cast<Packet16uc>(a), p16uc_REVERSE64));
}
template<> EIGEN_STRONG_INLINE Packet2d pabs(const Packet2d& a) { return vec_abs(a); }

template<> EIGEN_STRONG_INLINE double predux<Packet2d>(const Packet2d& a)
{
  Packet2d b, sum;
  b   = reinterpret_cast<Packet2d>(vec_sld(reinterpret_cast<Packet4f>(a), reinterpret_cast<Packet4f>(a), 8));
  sum = a + b;
  return pfirst<Packet2d>(sum);
}

template<> EIGEN_STRONG_INLINE Packet2d preduxp<Packet2d>(const Packet2d* vecs)
{
  Packet2d v[2], sum;
  v[0] = vecs[0] + reinterpret_cast<Packet2d>(vec_sld(reinterpret_cast<Packet4f>(vecs[0]), reinterpret_cast<Packet4f>(vecs[0]), 8));
  v[1] = vecs[1] + reinterpret_cast<Packet2d>(vec_sld(reinterpret_cast<Packet4f>(vecs[1]), reinterpret_cast<Packet4f>(vecs[1]), 8));

#ifdef _BIG_ENDIAN
  sum = reinterpret_cast<Packet2d>(vec_sld(reinterpret_cast<Packet4f>(v[0]), reinterpret_cast<Packet4f>(v[1]), 8));
#else
  sum = reinterpret_cast<Packet2d>(vec_sld(reinterpret_cast<Packet4f>(v[1]), reinterpret_cast<Packet4f>(v[0]), 8));
#endif

  return sum;
}
// Other reduction functions:
// mul
template<> EIGEN_STRONG_INLINE double predux_mul<Packet2d>(const Packet2d& a)
{
  return pfirst(pmul(a, reinterpret_cast<Packet2d>(vec_sld(reinterpret_cast<Packet4ui>(a), reinterpret_cast<Packet4ui>(a), 8))));
}

// min
template<> EIGEN_STRONG_INLINE double predux_min<Packet2d>(const Packet2d& a)
{
  return pfirst(pmin(a, reinterpret_cast<Packet2d>(vec_sld(reinterpret_cast<Packet4ui>(a), reinterpret_cast<Packet4ui>(a), 8))));
}

// max
template<> EIGEN_STRONG_INLINE double predux_max<Packet2d>(const Packet2d& a)
{
  return pfirst(pmax(a, reinterpret_cast<Packet2d>(vec_sld(reinterpret_cast<Packet4ui>(a), reinterpret_cast<Packet4ui>(a), 8))));
}

template<int Offset>
struct palign_impl<Offset,Packet2d>
{
  static EIGEN_STRONG_INLINE void run(Packet2d& first, const Packet2d& second)
  {
    if (Offset == 1)
#ifdef _BIG_ENDIAN
      first = reinterpret_cast<Packet2d>(vec_sld(reinterpret_cast<Packet4ui>(first), reinterpret_cast<Packet4ui>(second), 8));
#else
      first = reinterpret_cast<Packet2d>(vec_sld(reinterpret_cast<Packet4ui>(second), reinterpret_cast<Packet4ui>(first), 8));
#endif
  }
};

EIGEN_DEVICE_FUNC inline void
ptranspose(PacketBlock<Packet2d,2>& kernel) {
  Packet2d t0, t1;
  t0 = vec_perm(kernel.packet[0], kernel.packet[1], p16uc_TRANSPOSE64_HI);
  t1 = vec_perm(kernel.packet[0], kernel.packet[1], p16uc_TRANSPOSE64_LO);
  kernel.packet[0] = t0;
  kernel.packet[1] = t1;
}

template<> EIGEN_STRONG_INLINE Packet2d pblend(const Selector<2>& ifPacket, const Packet2d& thenPacket, const Packet2d& elsePacket) {
  Packet2l select = { ifPacket.select[0], ifPacket.select[1] };
  Packet2bl mask = vec_cmpeq(reinterpret_cast<Packet2d>(select), reinterpret_cast<Packet2d>(p2l_ONE));
  return vec_sel(elsePacket, thenPacket, mask);
}
#endif // __VSX__
} // end namespace internal

} // end namespace Eigen

#endif // EIGEN_PACKET_MATH_ALTIVEC_H


text:
With these two API's you can make Chrome extensions and use the same code and manifest in Safari and Firefox.
If you have more than one '*' in your urls in the manifest Firefox or Safari (I don't remember) fails.

The manifest parser for Firefox is the same as main.js.

Safari:

- Build an extension with the extension builder and set the web_accessible_resources the same as in your manifest.json.
  Maybe the permissions can be parsed from manifest.json, but for now you have to do it manually. You can also edit the           info.plist:
```
<key>Permissions</key>
	<dict>
		<key>Website Access</key>
		<dict>
			<key>Include Secure Pages</key>
			<true/>
			<key>Level</key>
			<string>All</string>
		</dict>
	</dict>
```

- Copy the chromeAPISafari directory, your js directory and the manifest.json to your Safari extension.

- Add the chromeAPISafari to extensionName.html, it should look like this:

```
<!DOCTYPE html>
<html>
<head>
    <title>Hello World</title>
    <script type="text/javascript" src="chromeAPISafari/chromeManifestSimulatorSafari.js"></script>
    <script type="text/javascript" src="chromeAPISafari/chromeAPIForSafari.js"></script>
    <script type="text/javascript" src="js/background.js"></script>
</head>
<body>Hello World!</body>
</html>
```

If you inject css with fonts you need to use .ttf instead of .wof
If you have only used Chrome Api's defined in the ChromeAPIForSafari.js, it should work.

Firefox:

ChromeApiForFirefox have a hack to follow a tab which is moved between windows. I found no better solution, and the solution does not work in FirefoxDeveloperEdition where you eventually lose the tab reference. For some strange reason, tab id change when moving tab to another window.

I used the cfx init, but I see that tool is deprecated. But I think you can do jpm init,
choose the chromeApiForSafari/chromeManifestSimulatorFirefox.js as your entry point.
Make a data directory, then copy all your files (js directory, html, img..) into the data directory.

If you inject css with fonts you need to use dataURL instead.
If you have only used Chrome Api's defined in the ChromeAPIForFirefox.js, it should work.

Things I want to add:

- chrome.browserAction    It should be possible to parse popup information from manifest.json.
  https://developer.mozilla.org/en-US/Add-ons/SDK/High-Level_APIs/panel#Attaching_panels_to_buttons
 https://developer.apple.com/library/safari/documentation/Tools/Conceptual/SafariExtensionGuide/AddingPopovers/AddingPopovers.html

- Grunt/Gulp task for building Safari And Firefox extension and a Yeoman generator :)

I will include a sample later.

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
    metadata-complete="false"
    version="3.0">
    <welcome-file-list>
        <welcome-file>lista.faces</welcome-file>
    </welcome-file-list>
</web-app>


text:
package org.wyttenbach.dale.document.model;

import java.util.Date;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;

/**
 * @author dwyttenbach
 */
@Entity
@Table(name = "DOCUMENT")
public class Document {
	@Id
	@SequenceGenerator(name = "DOCUMENT_SEQ", sequenceName = "DOCUMENT_SEQ",allocationSize=1)
	@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "DOCUMENT_SEQ")
	@Column(name = "DOCUMENT_ID")
	private Long id;

	@Column(name = "BUS_SEG")
	private String busSeg;

	@Column(name = "EXTERNAL_ID")
	private String externalId;

	@Column(name = "NOTE")
	private String note;

	@Column(name = "RCVD_DATE")
	private Date receivedDate;

	@Column(name = "SIZE")
	private Long size;

	public Long getSize() {
		return size;
	}

	public void setSize(Long size) {
		this.size = size;
	}

	public Date getReceivedDate() {
		return receivedDate;
	}

	public void setReceivedDate(Date receivedDate) {
		this.receivedDate = receivedDate;
	}

	public String getNote() {
		return note;
	}

	public void setNote(String note) {
		this.note = note;
	}

	public Long getId() {
		return id;
	}

	public void setId(Long id) {
		this.id = id;
	}

	public String getBusSeg() {
		return busSeg;
	}

	public void setBusSeg(String busSeg) {
		this.busSeg = busSeg;
	}

	public String getExternalId() {
		return externalId;
	}

	public void setExternalId(String externalId) {
		this.externalId = externalId;
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((busSeg == null) ? 0 : busSeg.hashCode());
		result = prime * result
				+ ((externalId == null) ? 0 : externalId.hashCode());
		result = prime * result + ((id == null) ? 0 : id.hashCode());
		result = prime * result + ((note == null) ? 0 : note.hashCode());
		result = prime * result
				+ ((receivedDate == null) ? 0 : receivedDate.hashCode());
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		Document other = (Document) obj;
		if (busSeg == null) {
			if (other.busSeg != null)
				return false;
		} else if (!busSeg.equals(other.busSeg))
			return false;
		if (externalId == null) {
			if (other.externalId != null)
				return false;
		} else if (!externalId.equals(other.externalId))
			return false;
		if (id == null) {
			if (other.id != null)
				return false;
		} else if (!id.equals(other.id))
			return false;
		if (note == null) {
			if (other.note != null)
				return false;
		} else if (!note.equals(other.note))
			return false;
		if (receivedDate == null) {
			if (other.receivedDate != null)
				return false;
		} else if (!receivedDate.equals(other.receivedDate))
			return false;
		return true;
	}

}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;

namespace OmmitedDatabaseModel3WithCollections
{
    public class Entity14 : BaseEntity
    {
        public Entity14()
        {
            this.Entities12 = new List<Entity12>();
            this.Entities1 = new List<Entity1>();
        }

        public ICollection<Entity12> Entities12 { get; set; }
        public ICollection<Entity1> Entities1 { get; set; }
    }
}


text:
import React, { Component, PropTypes } from "react";
import { connect }                     from "react-redux";
import classNames                      from "classnames";
import Home                            from "../../containers/Home/HomeContainer";
import NotificationContainer           from "../../containers/Notification/Notification";
import Loading                         from "../../components/Loading/Loading";
import Header                          from "../../components/Header/Header";
import Footer                          from "../Footer/Footer";
import { loadCalendars}                from "../../actions/calendars"
import { bindActionCreators }          from "redux"

class App extends Component {

  render() {

    const { isLoading } = this.props.ui;

    return (

        <NotificationContainer />
        <Loading isLoading={isLoading} />

            {!this.props.children && <Home />}
            {this.props.children}

    );
  }

  componentDidMount() {

    let { loadCalendars } = this.props;

  }

}

const mapStateToProps = state => ({
  calendars: state.calendars,
  ui: state.ui
})

const mapDispatchToProps = dispatch => bindActionCreators({
    loadCalendars
}, dispatch)

export default connect(mapStateToProps, mapDispatchToProps)(App);


text:
class DummyClient < Struct.new(:consumer_key, :consumer_secret)

  DUMMY_KEY    = 'key'
  DUMMY_SECRET = 'shhhh'

  def self.find_by_consumer_key(key)
    if key == DUMMY_KEY
      new(key, DUMMY_SECRET)
    end
  end

end


text:
package javax.servlet;

import java.util.Set;

/**
 * @since Servlet 3.0
 * $Id: ServletContainerInitializer.java 899493 2010-01-15 00:18:24Z markt $
 * TODO SERVLET3 - Add comments
 */
public interface ServletContainerInitializer {

    /**
     *
     * @param c
     * @param ctx
     * @throws ServletException
     */
    public void onStartup(Set<Class<?>> c, ServletContext ctx)
    throws ServletException;
}


text: <!DOCTYPE html>


text:
function F = real2complex2(Y)
%F = real2complex2(Y)
%
%Returns the complex-valued vector F in the convention of the output of the
%fft, given the real-valued vectors containing phases and amplitudes in the
%structure Y.  This is the inverse function of 'complex2real'
%
%Inputs:    Structure Y with fields:
%   dc       mean value of y
%   amp      vector of amplitudes (length ceil(length(t)/2))
%   ph       vector of phases (in degrees, cosine phase)
%   n       length of t (needed for myifft)

%Outputs:
%   Y        complex-valued vector in the convention of the output of fft
%   t        time vector of size y (default is 1:length(y));
%
%SEE ALSO    complex2real2 fft2 ifft2

%4/15/09     Written by G.M. Boynton at the University of Washington

%'amp' and 'ph' have dc in center
F = zeros(Y.nPix,Y.nPix);

amp = Y.nPix^2*Y.amp/2;
ph = -pi*Y.ph/180;

F = amp.*exp(sqrt(-1)*ph);

F = ifftshift(F);
F(1) = Y.dc*Y.nPix^2;

%F has dc in corner


text:
package org.apache.servicecomb.qps;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.netflix.config.DynamicBooleanProperty;
import com.netflix.config.DynamicPropertyFactory;

public final class Config {
  private static final Logger LOGGER = LoggerFactory.getLogger(Config.class);

  public static final String STRATEGY_KEY = "servicecomb.flowcontrol.strategy";

  public static final String ANY_SERVICE = "ANY";

  public static final String CONSUMER_BUCKET_KEY_PREFIX = "servicecomb.flowcontrol.Consumer.qps.bucket.";

  public static final String PROVIDER_BUCKET_KEY_PREFIX = "servicecomb.flowcontrol.Provider.qps.bucket.";

  public static final String PROVIDER_BUCKET_KEY_GLOBAL =
      "servicecomb.flowcontrol.Provider.qps.global.bucket";

  public static final String CONSUMER_BUCKET_KEY_GLOBAL =
      "servicecomb.flowcontrol.Consumer.qps.global.bucket";

  public static final String CONSUMER_LIMIT_KEY_PREFIX = "servicecomb.flowcontrol.Consumer.qps.limit.";

  public static final String PROVIDER_LIMIT_KEY_PREFIX = "servicecomb.flowcontrol.Provider.qps.limit.";

  public static final String PROVIDER_LIMIT_KEY_GLOBAL =
      "servicecomb.flowcontrol.Provider.qps.global.limit";

  public static final String CONSUMER_LIMIT_KEY_GLOBAL =
      "servicecomb.flowcontrol.Consumer.qps.global.limit";

  public static final String CONSUMER_ENABLED = "servicecomb.flowcontrol.Consumer.qps.enabled";

  public static final String PROVIDER_ENABLED = "servicecomb.flowcontrol.Provider.qps.enabled";

  public static Config INSTANCE = new Config();

  private final DynamicBooleanProperty consumerEnabled =
      DynamicPropertyFactory.getInstance().getBooleanProperty(CONSUMER_ENABLED, true);

  private final DynamicBooleanProperty providerEnabled =
      DynamicPropertyFactory.getInstance().getBooleanProperty(PROVIDER_ENABLED, true);

  public Config() {
    consumerEnabled.addCallback(() -> {
      boolean newValue = consumerEnabled.get();
      LOGGER.info("{} changed from {} to {}", CONSUMER_ENABLED, consumerEnabled, newValue);
    });

    providerEnabled.addCallback(() -> {
      boolean newValue = providerEnabled.get();
      LOGGER.info("{} changed from {} to {}", PROVIDER_ENABLED, providerEnabled, newValue);
    });
  }

  public boolean isConsumerEnabled() {
    return consumerEnabled.get();
  }

  public boolean isProviderEnabled() {
    return providerEnabled.get();
  }
}


text:
package org.gradle.plugins.ide.internal.tooling.model;

import org.gradle.tooling.model.gradle.GradleScript;

import java.io.File;
import java.io.Serializable;

public class DefaultGradleScript implements GradleScript, Serializable {
    private File sourceFile;

    @Override
    public File getSourceFile() {
        return sourceFile;
    }

    public void setSourceFile(File sourceFile) {
        this.sourceFile = sourceFile;
    }
}


text:
package de.rwth.idsg.bikeman.ixsi.processor.query.user;

import com.google.common.base.Optional;
import de.rwth.idsg.bikeman.ixsi.ErrorFactory;
import de.rwth.idsg.bikeman.ixsi.processor.api.UserRequestProcessor;
import org.springframework.stereotype.Component;
import xjc.schema.ixsi.ErrorType;
import xjc.schema.ixsi.Language;
import xjc.schema.ixsi.PriceInformationRequestType;
import xjc.schema.ixsi.PriceInformationResponseType;
import xjc.schema.ixsi.UserInfoType;

/**
 * @author Sevket Goekay <goekay@dbis.rwth-aachen.de>
 * @since 26.09.2014
 */
@Component
public class PriceInformationRequestProcessor implements
        UserRequestProcessor<PriceInformationRequestType, PriceInformationResponseType> {

    @Override
    public Class<PriceInformationRequestType> getProcessingClass() {
        return PriceInformationRequestType.class;
    }

    @Override
    public PriceInformationResponseType processAnonymously(PriceInformationRequestType request, Optional<Language> lan) {
        // TODO FUTURE
        return buildError(ErrorFactory.Sys.notImplemented(null, null));
    }

    @Override
    public PriceInformationResponseType processForUser(PriceInformationRequestType request, Optional<Language> lan,
                                                       UserInfoType userInfo) {
        // TODO FUTURE
        return buildError(ErrorFactory.Sys.notImplemented(null, null));
    }

    // -------------------------------------------------------------------------
    // Error handling
    // -------------------------------------------------------------------------

    @Override
    public PriceInformationResponseType buildError(ErrorType e) {
        return new PriceInformationResponseType().withError(e);
    }
}


text:
weechat.register("RedbrickCmt", "butlerx", "1.0", "GPL3", "Redbrick Committee script", "", "");
weechat.hook_command("cmt", "printcmt", "", "", "", "loadCmt", "");

async function loadCmt () {
  const request = new XMLHttpRequest();
  request.open('GET', 'https://www.redbrick.dcu.ie/api/committee', true );
  request.onreadystatechange = () => {
    if(request.readyState === XMLHttpRequest.DONE && request.status === 200) {
      const cmt = JSON.parse(request.responseText);
      let list = '';
      await cmt.forEach(({nick}) => { list += `${nick}, ` });
      return list
    }
  };
  request.send();
}

function print () {
  weechat.prnt(weechat.current_buffer(), loadCmt);
}


text:
const ClientCommand = require('./_base-command.js');

/**
 * Retrieve all cookies visible to the current page. The cookies are returned as an array of cookie JSON object, as defined [here](https://github.com/SeleniumHQ/selenium/wiki/JsonWireProtocol#cookie-json-object).
 *
 * Uses `cookie` protocol command.
 *
 * @example
 * this.demoTest = function(browser) {
 *   browser.getCookies(function callback(result) {
 *     this.assert.equal(result.value.length, 1);
 *     this.assert.equals(result.value[0].name, 'test_cookie');
 *   });
 * }
 *
 *
 * @method getCookies
 * @param {function} callback The callback function which will receive the response as an argument.
 * @syntax .getCookies(callback)
 * @api protocol.cookies
 * @see cookie
 * @returns {Array.<object>} A list of cookies.
 */

class GetCookies extends ClientCommand {
  performAction(callback) {
    this.api.cookie('GET', callback);
  }
}

module.exports = GetCookies;


text:
/* See license.txt for terms of usage */

require.def("preview/menu", [
    "domplate/domplate",
    "core/lib",
    "domplate/toolbar",
    "core/trace"
],

function(Domplate, Lib, Toolbar, Trace) { with (Domplate) {

// ********************************************************************************************* //
// Credentials for HAR Preview

/**
 * Renders a menu at the top-right corner of the preview.
 */
function Menu() {}
Menu.prototype =
/** @lends Menu */
{
    render: function(parentNode)
    {
        // Render basic layout of the menu.
        this.element = MenuPlate.render(parentNode);

        // Construct toolbar and render it inside the menu.
        this.toolbar = new Toolbar();

        this.toolbar.addButton({
            id: "credentials",
            label: "Powered by Jan Odvarko",
            tooltiptext: "http://www.softwareishard.com/blog/har-viewer/",
            command: Lib.bindFixed(this.onCredentials, this, true)
        });

        /*this.toolbar.addButton({
            id: "fullPreview",
            label: "Open in HAR Viewer",
            tooltiptext: "Open the current HAR file in HAR Viewer",
            command: Lib.bindFixed(this.onFullPreview, this, true)
        });*/

        var menuContent = Lib.getElementByClass(this.element, "menuContent");
        this.toolbar.render(menuContent);

        if (Lib.isWebkit)
            menuContent.style.paddingTop = "1px";
    },

    // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
    // Commands

    onCredentials: function()
    {
        // Do not remove: credentials for HAR Viewer author.
        window.open("http://www.softwareishard.com/blog/har-viewer/");
    },

    onFullPreview: function()
    {
    }
};

// ********************************************************************************************* //

var MenuPlate = domplate(
{
    tag:
        DIV({"class": "menu", _repObject: "$object"},
            DIV({"class": "menuHandle", onmousemove: "$onMouseMove", onclick: "$onMouseClick"}),
            DIV({"class": "menuContent", "style": "display: none"})
        ),

    onMouseMove: function(event)
    {
        var e = Lib.fixEvent(event);
        this.open(e.target);
    },

    onMouseClick: function(event)
    {
        var e = Lib.fixEvent(event);
        this.toggle(e.target);
    },

    open: function(element)
    {
        var menu = Lib.getAncestorByClass(element, "menu");
        var content = Lib.getElementByClass(menu, "menuContent");
        if (content.clientWidth > 0)
            return;

        this.toggle(element);
    },

    toggle: function(element)
    {
        var menu = Lib.getAncestorByClass(element, "menu");
        var content = Lib.getElementByClass(menu, "menuContent");
        $(content).animate({width: "toggle"}, undefined, undefined, function()
        {
            // Update class on the handle element.
            var handle = Lib.getElementByClass(menu, "menuHandle");
            if (content.clientWidth > 0)
                Lib.setClass(handle, "opened");
            else
                Lib.removeClass(handle, "opened");
        });
    },

    // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
    // Public

    render: function(parentNode, scope)
    {
        return this.tag.append({object: scope}, parentNode, this);
    }
});

// ********************************************************************************************* //

return Menu;

// ********************************************************************************************* //
}});


text:
const ds = require( '../services/ds' );

Vue.component( 'file-transfer', {
	template: `

			folder
			face

= 100 ? 'green' : 'blue'">

			folder
			face

	`,
	props: [ 'origin', 'destination', 'uuid' ],
	data: function() {
		return {
			progress: 0
		}
	},
	created() {
		ds.client.on( 'file-progress/_' + this.$props.uuid, this.updateFileProgress.bind( this ) );
	},
	methods: {
		cleanUp() {

			console.log( 'DONE' );
		},
		updateFileProgress( progress ) {
			this.$data.progress = progress * 100;
			if( progress >= 1 ) {
				this.cleanUp();
			}
		}
	}
});


text:
from pornote import manager

if __name__ == "__main__":
    manager.run()


text:
package com.netflix.hystrix.metric;

import com.netflix.hystrix.ExecutionResult;
import com.netflix.hystrix.HystrixCollapserKey;
import com.netflix.hystrix.HystrixCommandKey;
import com.netflix.hystrix.HystrixInvokableInfo;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class HystrixRequestEvents {
    private final Collection<HystrixInvokableInfo<?>> executions;

    public HystrixRequestEvents(Collection<HystrixInvokableInfo<?>> executions) {
        this.executions = executions;
    }

    public Collection<HystrixInvokableInfo<?>> getExecutions() {
        return executions;
    }

    public Map<ExecutionSignature, List<Integer>> getExecutionsMappedToLatencies() {
        Map<CommandAndCacheKey, Integer> cachingDetector = new HashMap<CommandAndCacheKey, Integer>();
        List<HystrixInvokableInfo<?>> nonCachedExecutions = new ArrayList<HystrixInvokableInfo<?>>(executions.size());
        for (HystrixInvokableInfo<?> execution: executions) {
            if (execution.getPublicCacheKey() != null) {
                //eligible for caching - might be the initial, or might be from cache
                CommandAndCacheKey key = new CommandAndCacheKey(execution.getCommandKey().name(), execution.getPublicCacheKey());
                Integer count = cachingDetector.get(key);
                if (count != null) {
                    //key already seen
                    cachingDetector.put(key, count + 1);
                } else {
                    //key not seen yet
                    cachingDetector.put(key, 0);
                }
            }
            if (!execution.isResponseFromCache()) {
                nonCachedExecutions.add(execution);
            }
        }

        Map<ExecutionSignature, List<Integer>> commandDeduper = new HashMap<ExecutionSignature, List<Integer>>();
        for (HystrixInvokableInfo<?> execution: nonCachedExecutions) {
            int cachedCount = 0;
            String cacheKey = execution.getPublicCacheKey();
            if (cacheKey != null) {
                CommandAndCacheKey key = new CommandAndCacheKey(execution.getCommandKey().name(), cacheKey);
                cachedCount = cachingDetector.get(key);
            }
            ExecutionSignature signature;
            if (cachedCount > 0) {
                //this has a RESPONSE_FROM_CACHE and needs to get split off
                signature = ExecutionSignature.from(execution, cacheKey, cachedCount);
            } else {
                //nothing cached from this, can collapse further
                signature = ExecutionSignature.from(execution);
            }
            List<Integer> currentLatencyList = commandDeduper.get(signature);
            if (currentLatencyList != null) {
                currentLatencyList.add(execution.getExecutionTimeInMilliseconds());
            } else {
                List<Integer> newLatencyList = new ArrayList<Integer>();
                newLatencyList.add(execution.getExecutionTimeInMilliseconds());
                commandDeduper.put(signature, newLatencyList);
            }
        }

        return commandDeduper;
    }

    private static class CommandAndCacheKey {
        private final String commandName;
        private final String cacheKey;

        public CommandAndCacheKey(String commandName, String cacheKey) {
            this.commandName = commandName;
            this.cacheKey = cacheKey;
        }

        @Override
        public boolean equals(Object o) {
            if (this == o) return true;
            if (o == null || getClass() != o.getClass()) return false;

            CommandAndCacheKey that = (CommandAndCacheKey) o;

            if (!commandName.equals(that.commandName)) return false;
            return cacheKey.equals(that.cacheKey);

        }

        @Override
        public int hashCode() {
            int result = commandName.hashCode();
            result = 31 * result + cacheKey.hashCode();
            return result;
        }

        @Override
        public String toString() {
            return "CommandAndCacheKey{" +
                    "commandName='" + commandName + '\'' +
                    ", cacheKey='" + cacheKey + '\'' +
                    '}';
        }
    }

    public static class ExecutionSignature {
        private final String commandName;
        private final ExecutionResult.EventCounts eventCounts;
        private final String cacheKey;
        private final int cachedCount;
        private final HystrixCollapserKey collapserKey;
        private final int collapserBatchSize;

        private ExecutionSignature(HystrixCommandKey commandKey, ExecutionResult.EventCounts eventCounts, String cacheKey, int cachedCount, HystrixCollapserKey collapserKey, int collapserBatchSize) {
            this.commandName = commandKey.name();
            this.eventCounts = eventCounts;
            this.cacheKey = cacheKey;
            this.cachedCount = cachedCount;
            this.collapserKey = collapserKey;
            this.collapserBatchSize = collapserBatchSize;
        }

        public static ExecutionSignature from(HystrixInvokableInfo<?> execution) {
            return new ExecutionSignature(execution.getCommandKey(), execution.getEventCounts(), null, 0, execution.getOriginatingCollapserKey(), execution.getNumberCollapsed());
        }

        public static ExecutionSignature from(HystrixInvokableInfo<?> execution, String cacheKey, int cachedCount) {
            return new ExecutionSignature(execution.getCommandKey(), execution.getEventCounts(), cacheKey, cachedCount, execution.getOriginatingCollapserKey(), execution.getNumberCollapsed());
        }

        @Override
        public boolean equals(Object o) {
            if (this == o) return true;
            if (o == null || getClass() != o.getClass()) return false;

            ExecutionSignature that = (ExecutionSignature) o;

            if (!commandName.equals(that.commandName)) return false;
            if (!eventCounts.equals(that.eventCounts)) return false;
            return !(cacheKey != null ? !cacheKey.equals(that.cacheKey) : that.cacheKey != null);

        }

        @Override
        public int hashCode() {
            int result = commandName.hashCode();
            result = 31 * result + eventCounts.hashCode();
            result = 31 * result + (cacheKey != null ? cacheKey.hashCode() : 0);
            return result;
        }

        public String getCommandName() {
            return commandName;
        }

        public ExecutionResult.EventCounts getEventCounts() {
            return eventCounts;
        }

        public int getCachedCount() {
            return cachedCount;
        }

        public HystrixCollapserKey getCollapserKey() {
            return collapserKey;
        }

        public int getCollapserBatchSize() {
            return collapserBatchSize;
        }
    }
}


text:
#include "ssGlobal.h"
#include "ssTsd.h"
#include "TG3_Type.h"
#include <stdio.h>
#include "TCOM.h"
#include "ssAppMgr.h"
#include "TG3AppDllEntry.h"

#ifdef __TCOM_SUPPORT__

#ifdef __cplusplus
extern "C" {
#endif

    //实现TCOM所需要的DLL函数

    //DLL提供的获取指定CLSID的指定接口
    SS_EXPORT HRESULT TDllGetClassObject(TREFCLSID rclsid, TREFIID riid, LPVOID * ppv);

    //DLL提供的查询DLL能否被Unload
    SS_EXPORT HRESULT TDllCanUnloadNow(void);

    //DLL提供的把DLL的TCOM信息加入到注册表
    SS_EXPORT HRESULT TDllRegisterServer(void);

    //DLL提供的把DLL的TCOM信息从注册表中删除
    SS_EXPORT HRESULT TDllUnregisterServer(void);

#ifdef __cplusplus
}
#endif

#ifdef __TCOM_OUTPUT_DEBUG_INFO__
#include <stdio.h>
#endif

//TCOM实现中需要用到的函数和数据

//实例对象被引用的次数
static Int32 __TCOM_ClsidInstanceRefCount;

//ClassFactory被Locked的次数
static Int32 __TCOM_CalssFactoryLockedCount;

//做必要的初始化
static Int32 __TCOM_Init()
{
    __TCOM_ClsidInstanceRefCount = 0;
    __TCOM_CalssFactoryLockedCount = 0;
    return 0;
}

//做必要的清除工作
static Int32 __TCOM_DeInit()
{
    return 0;
}

//DLL全局使用:增加对象实例被引用次数
Int32 TCOM_AddClsidInstanceRefCount()
{
    __TCOM_ClsidInstanceRefCount++;
#ifdef __TCOM_OUTPUT_DEBUG_INFO__
    SS_printf("[TCOM_SYSTEM] TCOM_AddClsidInstanceRefCount: address: %p, value: %d.\n",
		&__TCOM_ClsidInstanceRefCount, __TCOM_ClsidInstanceRefCount);
#endif
    if(__TCOM_ClsidInstanceRefCount <= 0)
	{
        return 0;
	}
    return __TCOM_ClsidInstanceRefCount;
}

//DLL全局使用:减少对象实例被引用次数
Int32 TCOM_DecClsidInstanceRefCount()
{
    __TCOM_ClsidInstanceRefCount--;
#ifdef __TCOM_OUTPUT_DEBUG_INFO__
    SS_printf("[TCOM_SYSTEM] TCOM_DecClsidInstanceRefCount: address: %p, value: %d.\n",
		&__TCOM_ClsidInstanceRefCount, __TCOM_ClsidInstanceRefCount);
#endif
    if(__TCOM_ClsidInstanceRefCount <= 0)
	{
        return 0;
	}
    return __TCOM_ClsidInstanceRefCount;
}

//DLL全局使用:增加ClassFactory被Locked的次数
Int32 TCOM_AddCalssFactoryLockedCount()
{
    __TCOM_CalssFactoryLockedCount++;
#ifdef __TCOM_OUTPUT_DEBUG_INFO__
    SS_printf("[TCOM_SYSTEM] TCOM_AddCalssFactoryLockedCount: address: %p, value: %d.\n",
		&__TCOM_CalssFactoryLockedCount, __TCOM_CalssFactoryLockedCount);
#endif
    if(__TCOM_CalssFactoryLockedCount <= 0)
	{
        return 0;
	}
    return __TCOM_CalssFactoryLockedCount;
}

//DLL全局使用:减少ClassFactory被Locked的次数
Int32 TCOM_DecCalssFactoryLockedCount()
{
    __TCOM_CalssFactoryLockedCount--;
#ifdef __TCOM_OUTPUT_DEBUG_INFO__
    SS_printf("[TCOM_SYSTEM] TCOM_DecCalssFactoryLockedCount: address: %p, value: %d.\n",
		&__TCOM_CalssFactoryLockedCount, __TCOM_CalssFactoryLockedCount);
#endif
    if(__TCOM_CalssFactoryLockedCount <= 0)
	{
        return 0;
	}
    return __TCOM_CalssFactoryLockedCount;
}

//实现TCOM所需要的DLL函数

//DLL提供的获取指定CLSID的指定接口
SS_EXPORT HRESULT TDllGetClassObject(TREFCLSID rclsid, TREFIID riid, LPVOID * ppv)
{
    return TCOM_Srv_GetClassObject(rclsid, riid, ppv);
}

//DLL提供的查询DLL能否被Unload
SS_EXPORT HRESULT TDllCanUnloadNow(void)
{
#ifdef __TCOM_OUTPUT_DEBUG_INFO__
    SS_printf("[TCOM_SYSTEM] TDllCanUnloadNow: address1: %p, address2: %p, value1: %d, value2: %d.\n",
		&__TCOM_ClsidInstanceRefCount, &__TCOM_CalssFactoryLockedCount, __TCOM_ClsidInstanceRefCount,
		__TCOM_CalssFactoryLockedCount);
#endif
    if((__TCOM_ClsidInstanceRefCount <= 0) && (__TCOM_CalssFactoryLockedCount <= 0))
        return TCOM_S_TRUE;
    return TCOM_S_FALSE;
}

//DLL提供的把DLL的TCOM信息加入到注册表
SS_EXPORT HRESULT TDllRegisterServer(void)
{
    return TCOM_Srv_RegisterServer();
}

//DLL提供的把DLL的TCOM信息从注册表中删除
SS_EXPORT HRESULT TDllUnregisterServer(void)
{
    return  TCOM_Srv_UnregisterServer();
}

#endif  //__TCOM_SUPPORT__

#ifdef _WIN32

#ifndef SS_MAKEDLL
    #error Error!!! SS_MAKEDLL Must defined!
#endif

BOOL APIENTRY DllMain(HANDLE hModule, DWORD  ul_reason_for_call, LPVOID lpReserved)
{
	switch (ul_reason_for_call)
	{
	case DLL_PROCESS_ATTACH:
		//进程加载动态库进行的操作
#ifdef __TCOM_SUPPORT__
        __TCOM_Init();
#endif
		break;
	case DLL_THREAD_ATTACH:
		//线程加载动态库进行的操作
		break;
	case DLL_THREAD_DETACH:
		//线程卸载动态库进行的操作
		break;
	case DLL_PROCESS_DETACH:
		//进程卸载动态库进行的操作
#ifdef __TCOM_SUPPORT__
        __TCOM_DeInit();
#endif
		break;
	}
	return TRUE;
}
#else   //linux

#ifndef SS_SHARED
    #error Error!!! SS_SHARED Must defined!
#endif

void __attribute((constructor)) TG3_Dll_Attach()
{
    //进程加载动态库进行的操作
#ifdef __TCOM_SUPPORT__
    __TCOM_Init();
#endif
}

void __attribute((destructor)) TG3_Dll_Detach()
{
    //进程卸载动态库进行的操作
#ifdef __TCOM_SUPPORT__
    __TCOM_DeInit();
#endif
}

#endif

//如果不是作为TG3的动态库应用,请在VC项目中和TMK3文件中定义  __TG3_PURE_DLL__ 宏
#ifndef __TG3_PURE_DLL__

//动态库应用使用的统一导出名字的入口函数
SS_EXPORT Int32 TDllTG3AppMain(const TUChar * pAppID, UInt32 nCmd, void * pCmdParam)
{
	Int32 retValue;

	//初始化TCOM
	TCoInitialize(NULL);

	retValue = TG3AppMain(pAppID, nCmd, pCmdParam);

	//释放TCOM
	TCoUninitialize();

	return retValue;
}

#endif


text:
package org.apache.hyracks.data.std.api;

public interface IMutableValueStorage extends IValueReference, IDataOutputProvider {
    public void reset();
}


text:
#ifndef GHOST_LIB_BPF_SCHEDRUN_SHARED_H_
#define GHOST_LIB_BPF_SCHEDRUN_SHARED_H_

// Keep this file's structs in sync with bpf/schedrun_shared_bpf.h.
// We need different headers for BPF and C programs due to various Google3
// reasons.

#include <stdint.h>

#define MAX_PIDS 102400
#define MAX_NR_HIST_SLOTS 25

/*
 * Power of 2 histogram, <=1 us, 2us, 4us, etc.  This struct must be at least
 * 8-byte aligned, since it is a value for a BPF map.
 */
struct hist {
  uint32_t slots[MAX_NR_HIST_SLOTS];
} __attribute__((aligned(64)));

enum {
  RUNTIMES_PREEMPTED_YIELDED,
  RUNTIMES_BLOCKED,
  RUNTIMES_ALL,
  NR_HISTS,
};

#endif  // GHOST_LIB_BPF_SCHEDRUN_SHARED_H_


text:
"""Loading of attrs classes."""
from ipaddress import IPv4Address, IPv6Address, ip_address
from typing import Union
from unittest.mock import Mock

import pytest
from attr import (
    NOTHING,
    Factory,
    asdict,
    astuple,
    attrib,
    define,
    fields,
    make_class,
)
from hypothesis import assume, given
from hypothesis.strategies import data, lists, sampled_from

from cattr._compat import is_py37
from cattr.converters import Converter, GenConverter

from . import simple_classes

@given(simple_classes())
def test_structure_simple_from_dict(cl_and_vals):
    """Test structuring non-nested attrs classes dumped with asdict."""
    converter = Converter()
    cl, vals = cl_and_vals
    obj = cl(*vals)

    dumped = asdict(obj)
    loaded = converter.structure(dumped, cl)

    assert obj == loaded

@given(simple_classes(defaults=True, min_attrs=1, frozen=False), data())
def test_structure_simple_from_dict_default(cl_and_vals, data):
    """Test structuring non-nested attrs classes with default value."""
    converter = Converter()
    cl, vals = cl_and_vals
    obj = cl(*vals)
    attrs_with_defaults = [a for a in fields(cl) if a.default is not NOTHING]
    to_remove = data.draw(
        lists(elements=sampled_from(attrs_with_defaults), unique=True)
    )

    for a in to_remove:
        if isinstance(a.default, Factory):
            setattr(obj, a.name, a.default.factory())
        else:
            setattr(obj, a.name, a.default)

    dumped = asdict(obj)

    for a in to_remove:
        del dumped[a.name]

    assert obj == converter.structure(dumped, cl)

@given(simple_classes())
def test_roundtrip(cl_and_vals):
    """We dump the class, then we load it."""
    converter = Converter()
    cl, vals = cl_and_vals
    obj = cl(*vals)

    dumped = converter.unstructure(obj)
    loaded = converter.structure(dumped, cl)

    assert obj == loaded

@given(simple_classes())
def test_structure_tuple(cl_and_vals):
    """Test loading from a tuple, by registering the loader."""
    converter = Converter()
    cl, vals = cl_and_vals
    converter.register_structure_hook(cl, converter.structure_attrs_fromtuple)
    obj = cl(*vals)

    dumped = astuple(obj)
    loaded = converter.structure(dumped, cl)

    assert obj == loaded

@given(simple_classes(defaults=False), simple_classes(defaults=False))
def test_structure_union(cl_and_vals_a, cl_and_vals_b):
    """Structuring of automatically-disambiguable unions works."""
    converter = Converter()
    cl_a, vals_a = cl_and_vals_a
    cl_b, vals_b = cl_and_vals_b
    a_field_names = {a.name for a in fields(cl_a)}
    b_field_names = {a.name for a in fields(cl_b)}
    assume(a_field_names)
    assume(b_field_names)

    common_names = a_field_names & b_field_names
    if len(a_field_names) > len(common_names):
        obj = cl_a(*vals_a)
        dumped = asdict(obj)
        res = converter.structure(dumped, Union[cl_a, cl_b])
        assert isinstance(res, cl_a)
        assert obj == res

@given(simple_classes(defaults=False), simple_classes(defaults=False))
def test_structure_union_none(cl_and_vals_a, cl_and_vals_b):
    """Structuring of automatically-disambiguable unions works."""
    converter = Converter()
    cl_a, vals_a = cl_and_vals_a
    cl_b, _ = cl_and_vals_b
    a_field_names = {a.name for a in fields(cl_a)}
    b_field_names = {a.name for a in fields(cl_b)}
    assume(a_field_names)
    assume(b_field_names)

    common_names = a_field_names & b_field_names
    if len(a_field_names) > len(common_names):
        obj = cl_a(*vals_a)
        dumped = asdict(obj)
        res = converter.structure(dumped, Union[cl_a, cl_b, None])
        assert isinstance(res, cl_a)
        assert obj == res

@given(simple_classes(), simple_classes())
def test_structure_union_explicit(cl_and_vals_a, cl_and_vals_b):
    """Structuring of manually-disambiguable unions works."""
    converter = Converter()
    cl_a, vals_a = cl_and_vals_a
    cl_b, vals_b = cl_and_vals_b

    def dis(obj, _):
        return converter.structure(obj, cl_a)

    converter.register_structure_hook(Union[cl_a, cl_b], dis)

    inst = cl_a(*vals_a)

    assert inst == converter.structure(
        converter.unstructure(inst), Union[cl_a, cl_b]
    )

@pytest.mark.skipif(is_py37, reason="Not supported on 3.7")
@pytest.mark.parametrize("converter_cls", [Converter, GenConverter])
def test_structure_literal(converter_cls):
    """Structuring a class with a literal field works."""
    from typing import Literal

    converter = converter_cls()

    @define
    class ClassWithLiteral:
        literal_field: Literal[4] = 4

    assert converter.structure(
        {"literal_field": 4}, ClassWithLiteral
    ) == ClassWithLiteral(4)

@pytest.mark.skipif(is_py37, reason="Not supported on 3.7")
@pytest.mark.parametrize("converter_cls", [Converter, GenConverter])
def test_structure_literal_error(converter_cls):
    """Structuring a class with a literal field can raise an error."""
    from typing import Literal

    converter = converter_cls()

    @define
    class ClassWithLiteral:
        literal_field: Literal[4] = 4

    with pytest.raises(Exception):
        converter.structure({"literal_field": 3}, ClassWithLiteral)

@pytest.mark.parametrize("converter_type", [Converter, GenConverter])
def test_structure_fallback_to_attrib_converters(converter_type):
    attrib_converter = Mock()
    attrib_converter.side_effect = lambda val: str(val)

    def called_after_default_converter(val):
        if not isinstance(val, int):
            raise ValueError(
                "The 'int' conversion should have happened first by the built-in hooks"
            )
        return 42

    converter = converter_type()
    cl = make_class(
        "HasConverter",
        {
            # non-built-in type with custom converter
            "ip": attrib(
                type=Union[IPv4Address, IPv6Address], converter=ip_address
            ),
            # attribute without type
            "x": attrib(converter=attrib_converter),
            # built-in types converters
            "z": attrib(type=int, converter=called_after_default_converter),
        },
    )

    inst = converter.structure(dict(ip="10.0.0.0", x=1, z="3"), cl)

    assert inst.ip == IPv4Address("10.0.0.0")
    assert inst.x == "1"
    attrib_converter.assert_any_call(1)
    assert inst.z == 42

@pytest.mark.parametrize("converter_type", [Converter, GenConverter])
def test_structure_prefers_attrib_converters(converter_type):
    attrib_converter = Mock()
    attrib_converter.side_effect = lambda val: str(val)

    converter = converter_type(prefer_attrib_converters=True)
    cl = make_class(
        "HasConverter",
        {
            # non-built-in type with custom converter
            "ip": attrib(
                type=Union[IPv4Address, IPv6Address], converter=ip_address
            ),
            # attribute without type
            "x": attrib(converter=attrib_converter),
            # built-in types converters
            "y": attrib(type=int, converter=attrib_converter),
            # attribute with type and default value
            "z": attrib(type=int, converter=attrib_converter, default=5),
        },
    )

    inst = converter.structure(dict(ip="10.0.0.0", x=1, y=3), cl)

    assert inst.ip == IPv4Address("10.0.0.0")

    attrib_converter.assert_any_call(1)
    assert inst.x == "1"

    attrib_converter.assert_any_call(3)
    assert inst.y == "3"

    attrib_converter.assert_any_call(5)
    assert inst.z == "5"


text:
' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.

Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Recommendations.OptionStatements
    Public Class OptionNamesRecommenderTests
        <Fact>
        <Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
        Public Sub OptionNamesAfterOptionTest()
            VerifyRecommendationsAreExactly(<File>Option |</File>, "Compare", "Explicit", "Infer", "Strict")
        End Sub
    End Class
End Namespace


text: rm -rf final work plots && build_keys && batch_fvs


text: package triggers


text:
from invoke import task
import pytest, logging.config

import settings as app_settings

@task()
def clean():
    '''Clean build directory.'''
    print 'Cleaning build directory...'

@task(clean, help={'name': "Name of the person to say hi to."})
def hi(name):
    print("Hi %s!" % name)

@task
def all():
    pytest.main()

@task(clean)
def unit():
    # initialize logging config
    logging.config.dictConfig(app_settings.LOGGING)
    # add -x to enable print
    #pytest.main(['-x','tests/unit'])
    pytest.main('tests/unit')


text:
> A postmortem is a written record of an incident, its impact, the actions taken
> to mitigate or resolve it, the root cause(s), and the follow-up actions to
> prevent the incident from recurring.
>
> [Postmortem Culture: Learning from failure](https://landing.google.com/sre/sre-book/chapters/postmortem-culture/),
> _Devin Carraway_

For a full overview, checkout the Software Reliability Engineering book on this
topic [here](https://landing.google.com/sre/sre-book/chapters/postmortem/).

## Process

- Copy the [Postmortem template](./00-template.md) over to a new file
- This file should be named: `YYYY-MM-DD-title.md`
  - For example: `10-11-05-critical-layout-breaking-change.md`
- Fill out the template as best you can, be as detailed as needed
- Submit a Pull Request to the project, make sure to include anyone involved in
  the incident as a reviewer so they can provide additional perspectives if
  needed


text:
Status: Implemented

Resolves the full path for views/partials. Might want to give it a RequestHandler.

## Basic Syntax ##
```ruby
dtp = PathResolver.new(template_context)
dtp.path_for('')
```

## TemplateContext ##
    controller:string
    action:string
    type: :view, :controller

## Examples ##
For the Foo controller inside of the view
```ruby
dtp = PathResolver.new(controller: Foo, action: :index, type: :view)
dtp.path_for('table') == foo/_table
dtp.path_for('shared/dialogs/bar') == shared/dialogs/bar (Or should it also search foo/shared/..?)
dtp.path_for('') == InvalidPath_forException
```

For the Foo controler inside of the controller
```ruby
dtp = PathResolver.new(controller: Foo, action: :index, type: :controller)
dtp.path_for('') == foo/index
dtp.path_for('bar') == foo/bar
```

# ViewRenderer (Rails Specific) #
Status: Implemented

Interfaces between the rails renderer and rest of code.

## Basic Syntax ##
```ruby
vr = ViewRenderer.new
# Render a specific partial (just placeholder likely)
vr.render_partial(full_partial_path)
# Render a full view
vr.render_view(full_view_path)
# Render a full view and extract a single fragment
vr.render_fragment(full_view_path, fragment_name)
```

# RequestHandler (Rack Specific) #
Status: Implemented

Parses the request object to determine if this is the main load of the app and if not, what partial view is being requested

## Basic Syntax ##
```ruby
rh = RequestHandler.new(request)
rh.main_load?
rh.fragment_name
rh.load_path(fragment_name)
rh.should_render_partial?(fragment_name)
```

# Rails Engine #
Status: Implemented

Installs the view/controller renderer into ActionView/ActionController

## Basic Syntax ##
```ruby
class Engine < ::Rails::Engine
  # .. installation code ..
end
```

# Structure #
```
lib/
  progressive_render.rb
  rails/
    rails.rb
    engine.rb
    builder.rb
    view_renderer.rb
    path_resolver.rb
  rack/
    request_handler.rb
```


text:
                        Home

RFQ

<form action="<?php echo site_url('quotes/rfq_action'); ?>" method="post">

Type of Fixture

        <select>
                <option value="volvo">Volvo</option>
                <option value="saab">Saab</option>
                <option value="mercedes">Mercedes</option>
                <option value="audi">Audi</option>
        </select>

Material

            <button class="add_field_button">Add More Fields</button>

Material 1
<input type="text" name="name" id="name1" value="">
            <input type="text" name="xvalue" id="xvalue1" value="">
            <input type="text" name="yvalue" id="yvalue1" value="">
            <input type="text" name="total" id="total1">

        <?php echo "**********************************

" ?>

others

            Item
            Cost/Unit
            Quantity
            Cost

            <input type="text" name="clamb" value="clamb" readonly />
            <input type="text" name="unit-cost" />
            <input type="text" name="quantity" />
            <input type="text" name="total-cost" />

        <input type="button" id="calculate" value="Calculate" />
<input type="submit" value="Submit" />


text:
_shop_complete() {
  COMPREPLY=()
  local word="${COMP_WORDS[COMP_CWORD]}"
  local completions="$(shop cmplt "$word")"
  COMPREPLY=( $(compgen -W "$completions" -- "$word") )
}

complete -F _shop_complete shop


text:
<?php

use League\Fractal\Manager;
use League\Fractal\Resource\Collection;
use League\Fractal\Resource\Item;
use League\Fractal\Scope;
use League\Fractal\Serializer\JsonApiSerializer;
use League\Fractal\Test\Stub\Transformer\GenericBookTransformer;

class JsonApiSerializerTest extends PHPUnit_Framework_TestCase {

    private $manager;

    public function setUp()
    {
        $this->manager = new Manager();
        $this->manager->setSerializer(new JsonApiSerializer());
    }

    public function testSerializingEmptyIncludes()
    {
        $this->manager->parseIncludes('author');

        $bookData = array(
            'title' => 'Foo',
            'year' => '1991',
            '_author' => array(
                'name' => 'Dave',
            ),
        );

        $resource = new Item($bookData, new GenericBookTransformer(), 'book');

        $scope = new Scope($this->manager, $resource);

        $expected = array(
            'book' => array(
                array(
                    'title' => 'Foo',
                    'year' => 1991,
                )
            ),
            'linked' => array(
                'author' => array(
                    array(
                        'name' => 'Dave'
                    )
                )
            ),
        );

        $this->assertEquals($expected, $scope->toArray());

        $expectedJson = '{"book":[{"title":"Foo","year":1991}],"linked":{"author":[{"name":"Dave"}]}}';
        $this->assertEquals($expectedJson, $scope->toJson());
    }

    public function testSerializingItemResource()
    {
        $this->manager->parseIncludes('author');

        $bookData = array(
            'title' => 'Foo',
            'year' => '1991',
            '_author' => array(
                'name' => 'Dave',
            ),
        );

        $resource = new Item($bookData, new GenericBookTransformer(), 'book');

        $scope = new Scope($this->manager, $resource);

        $expected = array(
            'book' => array(
                array(
                    'title' => 'Foo',
                    'year' => 1991,
                )
            ),
            'linked' => array(
                'author' => array(
                    array(
                        'name' => 'Dave'
                    )
                )
            ),
        );

        $this->assertEquals($expected, $scope->toArray());

        $expectedJson = '{"book":[{"title":"Foo","year":1991}],"linked":{"author":[{"name":"Dave"}]}}';
        $this->assertEquals($expectedJson, $scope->toJson());
    }

    public function testSerializingCollectionResource()
    {
        $this->manager->parseIncludes('author');

        $booksData = array(
            array(
                'title' => 'Foo',
                'year' => '1991',
                '_author' => array(
                    'name' => 'Dave',
                ),
            ),
            array(
                'title' => 'Bar',
                'year' => '1997',
                '_author' => array(
                    'name' => 'Bob',
                ),
            ),
        );

        $resource = new Collection($booksData, new GenericBookTransformer(), 'book');
        $scope = new Scope($this->manager, $resource);

        $expected = array(
            'book' => array(
                array(
                    'title' => 'Foo',
                    'year' => 1991,
                ),
                array(
                    'title' => 'Bar',
                    'year' => 1997,
                ),
            ),
            'linked' => array(
                'author' => array(
                    array('name' => 'Dave'),
                    array('name' => 'Bob'),
                ),
            ),
        );

        $this->assertEquals($expected, $scope->toArray());

        $expectedJson = '{"book":[{"title":"Foo","year":1991},{"title":"Bar","year":1997}],"linked":{"author":[{"name":"Dave"},{"name":"Bob"}]}}';
        $this->assertEquals($expectedJson, $scope->toJson());
    }

    public function testSerializingItemResourceWithMeta()
    {
        $this->manager->parseIncludes('author');

        $bookData = array(
            'title' => 'Foo',
            'year' => '1991',
            '_author' => array(
                'name' => 'Dave',
            ),
        );

        $resource = new Item($bookData, new GenericBookTransformer(), 'book');
        $resource->setMetaValue('foo', 'bar');

        $scope = new Scope($this->manager, $resource);

        $expected = array(
            'book' => array(
                array(
                    'title' => 'Foo',
                    'year' => 1991,
                )
            ),
            'linked' => array(
                'author' => array(
                    array(
                        'name' => 'Dave'
                    )
                )
            ),
            'meta' => array(
                'foo' => 'bar',
            ),
        );

        $this->assertEquals($expected, $scope->toArray());

        $expectedJson = '{"book":[{"title":"Foo","year":1991}],"linked":{"author":[{"name":"Dave"}]},"meta":{"foo":"bar"}}';
        $this->assertEquals($expectedJson, $scope->toJson());
    }

    public function testSerializingCollectionResourceWithMeta()
    {
        $this->manager->parseIncludes('author');

        $booksData = array(
            array(
                'title' => 'Foo',
                'year' => '1991',
                '_author' => array(
                    'name' => 'Dave',
                ),
            ),
            array(
                'title' => 'Bar',
                'year' => '1997',
                '_author' => array(
                    'name' => 'Bob',
                ),
            ),
        );

        $resource = new Collection($booksData, new GenericBookTransformer(), 'book');
        $resource->setMetaValue('foo', 'bar');

        $scope = new Scope($this->manager, $resource);

        $expected = array(
            'book' => array(
                array(
                    'title' => 'Foo',
                    'year' => 1991,
                ),
                array(
                    'title' => 'Bar',
                    'year' => 1997,
                ),
            ),
            'linked' => array(
                'author' => array(
                    array('name' => 'Dave'),
                    array('name' => 'Bob'),
                ),
            ),
            'meta' => array(
                'foo' => 'bar',
            ),
        );

        $this->assertEquals($expected, $scope->toArray());

        $expectedJson = '{"book":[{"title":"Foo","year":1991},{"title":"Bar","year":1997}],"linked":{"author":[{"name":"Dave"},{"name":"Bob"}]},"meta":{"foo":"bar"}}';
        $this->assertEquals($expectedJson, $scope->toJson());
    }

    public function testResourceKeyMissing()
    {
        $this->manager->setSerializer(new JsonApiSerializer());

        $bookData = array(
            'title' => 'Foo',
            'year' => '1991',
        );

        $resource = new Item($bookData, new GenericBookTransformer());
        $scope = new Scope($this->manager, $resource);

        $expected = array(
            'data' => array(
                array(
                    'title' => 'Foo',
                    'year' => 1991,
                ),
            ),
        );

        $this->assertEquals($expected, $scope->toArray());
    }

    public function tearDown()
    {
        Mockery::close();
    }

}


text:
package collector

import (
	"regexp"
)

type netDevFilter struct {
	ignorePattern *regexp.Regexp
	acceptPattern *regexp.Regexp
}

func newNetDevFilter(ignoredPattern, acceptPattern string) (f netDevFilter) {
	if ignoredPattern != "" {
		f.ignorePattern = regexp.MustCompile(ignoredPattern)
	}

	if acceptPattern != "" {
		f.acceptPattern = regexp.MustCompile(acceptPattern)
	}

	return
}

// ignores returns whether the device should be ignored
func (f *netDevFilter) ignored(name string) bool {
	return ((f.ignorePattern != nil && f.ignorePattern.MatchString(name)) ||
		(f.acceptPattern != nil && !f.acceptPattern.MatchString(name)))
}


text:
import type { CodeKeywordDefinition, ErrorObject } from "../../types";
export declare type ConstError = ErrorObject<"const", {
    allowedValue: any;
}>;
declare const def: CodeKeywordDefinition;
export default def;


text:
from nose.tools import eq_

from bleach import Bleach

bl = Bleach()

def test_bleach_shortcut():
    eq_('< escaped and '
        'linkified.com', bl.bleach('< escaped and linkified.com'))

def test_bleach_with_href():
    """Make sure an explicit link doesn't get linkified as well."""
    eq_(u'xx '
        u'http://yy.com',
        bl.bleach('xx http://yy.com'))
    eq_('http://xx.com',
        bl.bleach('http://xx.com'))

def test_idempotent():
    """Make sure that applying the filter twice doesn't change anything."""
    dirty = u'invalid &  < extra http://link.com'

    clean = bl.clean(dirty)
    eq_(clean, bl.clean(clean))

    bleached = bl.bleach(dirty)
    eq_(bleached, bl.bleach(bleached))

    linked = bl.linkify(dirty)
    eq_(linked, bl.linkify(linked))

def test_escaped_html():
    s = u'<em>strong</em>'
    eq_(s, bl.bleach(s))

def test_self_closing():
    """Self closing tags are untouched."""
    eq_('', bl.clean('', tags=['img']))


text:
package problems_1_to_25;

import java.util.ArrayList;

public class Problem_23_Sum {
	//	A perfect number is a number for which the sum of its proper divisors is exactly equal to the number. For example, the sum of the proper divisors of 28 would be 1 + 2 + 4 + 7 + 14 = 28, which means that 28 is a perfect number.
	//
	//			A number n is called deficient if the sum of its proper divisors is less than n and it is called abundant if this sum exceeds n.
	//
	//			As 12 is the smallest abundant number, 1 + 2 + 3 + 4 + 6 = 16, the smallest number that can be written as the sum of two abundant numbers is 24. By mathematical analysis, it can be shown that all integers greater than 28123 can be written as the sum of two abundant numbers. However, this upper limit cannot be reduced any further by analysis even though it is known that the greatest number that cannot be expressed as the sum of two abundant numbers is less than this limit.
	//
	//			Find the sum of all the positive integers which cannot be written as the sum of two abundant numbers.

	public static int getSumOfNotNumbers(){
		int sum = 1;
		ArrayList<Integer> abundantNumbers = new ArrayList<Integer>();

		for(int number = 2;  number <= 28123; number++){
			int dividerSum =1;
			for(int divider= 2; divider < number-1; divider++){
				if(number % divider == 0){
					if(number / divider < divider){
						break;
					}else if(number / divider == divider){
						dividerSum+= divider;
					}else{
						int secondDivider = number / divider;
						dividerSum+= divider + secondDivider;
					}
				}

			}
			if(dividerSum > number){
				abundantNumbers.add(number);
			}

			if(abundantNumbers.size() >0){
				for(int index = 0; index < abundantNumbers.size(); index++){
					int abundantNumber = abundantNumbers.get(index);
					int b = number - abundantNumber;
					if(abundantNumbers.contains(b) || abundantNumber >number){
						break;
					}else if(index == abundantNumbers.size()-1){
						sum+= number;
					}
				}
			}else{
				sum+= number;
			}

		}

		return sum;
	}

	public static int getSumOfNotNumbers2(){
		int sum=0;
		ArrayList<Integer> abundantNumbers = new ArrayList<Integer>();

		for(int number = 2;  number <= 28123; number++){
			int dividerSum =1;
			for(int divider= 2; divider < number-1; divider++){
				if(number % divider == 0){
					if(number / divider < divider){
						break;
					}else if(number / divider == divider){
						dividerSum+= divider;
					}else{
						int secondDivider = number / divider;
						dividerSum+= divider + secondDivider;
					}
				}

			}
			if(dividerSum > number){
				abundantNumbers.add(number);
			}
		}

		ArrayList<Integer> sumsOfAbundantNumbers = new ArrayList<Integer>();
		for(int index=0; index < abundantNumbers.size(); index++){
			int number1 = abundantNumbers.get(index);
			for(int indexB= index; indexB < abundantNumbers.size(); indexB++){
				int number2 = abundantNumbers.get(indexB);
				int sumOfTwoAbundants = number2+ number1;
				sumsOfAbundantNumbers.add(sumOfTwoAbundants);
			}
		}

		for(int index = 0; index <= 28123; index++ ){
			if(sumsOfAbundantNumbers.contains(index)== false){
				sum+= index;
			}
		}
			return sum;
		}

	public static void main(String[] args) {

			//4179871
			System.out.println(getSumOfNotNumbers2());

		}

	}