text:
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::gray(limit() / 2, limit() / 2, limit() / 2);
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::white(limit(), limit(), limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::red(limit(), 0, 0);
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::green(0, limit(), 0);
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::blue(0, 0, limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::cyan(0, limit(), limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::magenta(limit(), 0, limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::yellow(limit(), limit(), 0);
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::black(0, 0, 0);
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::aliceBlue(0.941176*limit(),0.972549*limit(),1*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::antiqueWhite(0.980392*limit(),0.921569*limit(),0.843137*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::aqua(0*limit(),1*limit(),1*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::aquamarine(0.498039*limit(),1*limit(),0.831373*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::azure(0.941176*limit(),1*limit(),1*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::beige(0.960784*limit(),0.960784*limit(),0.862745*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::bisque(1*limit(),0.894118*limit(),0.768627*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::blanchedAlmond(1*limit(),0.921569*limit(),0.803922*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::blueViolet(0.541176*limit(),0.168627*limit(),0.886275*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::brown(0.647059*limit(),0.164706*limit(),0.164706*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::burlyWood(0.870588*limit(),0.721569*limit(),0.529412*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::cadetBlue(0.372549*limit(),0.619608*limit(),0.627451*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::chartreuse(0.498039*limit(),1*limit(),0*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::chocolate(0.823529*limit(),0.411765*limit(),0.117647*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::coral(1*limit(),0.498039*limit(),0.313726*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::cornflowerBlue(0.392157*limit(),0.584314*limit(),0.929412*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::cornsilk(1*limit(),0.972549*limit(),0.862745*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::crimson(0.862745*limit(),0.0784314*limit(),0.235294*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::darkBlue(0*limit(),0*limit(),0.545098*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::darkCyan(0*limit(),0.545098*limit(),0.545098*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::darkGoldenRod(0.721569*limit(),0.52549*limit(),0.0431373*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::darkGray(0.662745*limit(),0.662745*limit(),0.662745*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::darkGrey(0.662745*limit(),0.662745*limit(),0.662745*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::darkGreen(0*limit(),0.392157*limit(),0*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::darkKhaki(0.741176*limit(),0.717647*limit(),0.419608*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::darkMagenta(0.545098*limit(),0*limit(),0.545098*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::darkOliveGreen(0.333333*limit(),0.419608*limit(),0.184314*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::darkorange(1*limit(),0.54902*limit(),0*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::darkOrchid(0.6*limit(),0.196078*limit(),0.8*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::darkRed(0.545098*limit(),0*limit(),0*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::darkSalmon(0.913725*limit(),0.588235*limit(),0.478431*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::darkSeaGreen(0.560784*limit(),0.737255*limit(),0.560784*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::darkSlateBlue(0.282353*limit(),0.239216*limit(),0.545098*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::darkSlateGray(0.184314*limit(),0.309804*limit(),0.309804*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::darkSlateGrey(0.184314*limit(),0.309804*limit(),0.309804*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::darkTurquoise(0*limit(),0.807843*limit(),0.819608*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::darkViolet(0.580392*limit(),0*limit(),0.827451*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::deepPink(1*limit(),0.0784314*limit(),0.576471*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::deepSkyBlue(0*limit(),0.74902*limit(),1*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::dimGray(0.411765*limit(),0.411765*limit(),0.411765*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::dimGrey(0.411765*limit(),0.411765*limit(),0.411765*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::dodgerBlue(0.117647*limit(),0.564706*limit(),1*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::fireBrick(0.698039*limit(),0.133333*limit(),0.133333*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::floralWhite(1*limit(),0.980392*limit(),0.941176*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::forestGreen(0.133333*limit(),0.545098*limit(),0.133333*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::fuchsia(1*limit(),0*limit(),1*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::gainsboro(0.862745*limit(),0.862745*limit(),0.862745*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::ghostWhite(0.972549*limit(),0.972549*limit(),1*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::gold(1*limit(),0.843137*limit(),0*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::goldenRod(0.854902*limit(),0.647059*limit(),0.12549*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::grey(0.501961*limit(),0.501961*limit(),0.501961*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::greenYellow(0.678431*limit(),1*limit(),0.184314*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::honeyDew(0.941176*limit(),1*limit(),0.941176*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::hotPink(1*limit(),0.411765*limit(),0.705882*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::indianRed (0.803922*limit(),0.360784*limit(),0.360784*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::indigo (0.294118*limit(),0*limit(),0.509804*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::ivory(1*limit(),1*limit(),0.941176*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::khaki(0.941176*limit(),0.901961*limit(),0.54902*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::lavender(0.901961*limit(),0.901961*limit(),0.980392*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::lavenderBlush(1*limit(),0.941176*limit(),0.960784*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::lawnGreen(0.486275*limit(),0.988235*limit(),0*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::lemonChiffon(1*limit(),0.980392*limit(),0.803922*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::lightBlue(0.678431*limit(),0.847059*limit(),0.901961*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::lightCoral(0.941176*limit(),0.501961*limit(),0.501961*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::lightCyan(0.878431*limit(),1*limit(),1*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::lightGoldenRodYellow(0.980392*limit(),0.980392*limit(),0.823529*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::lightGray(0.827451*limit(),0.827451*limit(),0.827451*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::lightGrey(0.827451*limit(),0.827451*limit(),0.827451*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::lightGreen(0.564706*limit(),0.933333*limit(),0.564706*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::lightPink(1*limit(),0.713726*limit(),0.756863*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::lightSalmon(1*limit(),0.627451*limit(),0.478431*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::lightSeaGreen(0.12549*limit(),0.698039*limit(),0.666667*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::lightSkyBlue(0.529412*limit(),0.807843*limit(),0.980392*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::lightSlateGray(0.466667*limit(),0.533333*limit(),0.6*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::lightSlateGrey(0.466667*limit(),0.533333*limit(),0.6*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::lightSteelBlue(0.690196*limit(),0.768627*limit(),0.870588*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::lightYellow(1*limit(),1*limit(),0.878431*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::lime(0*limit(),1*limit(),0*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::limeGreen(0.196078*limit(),0.803922*limit(),0.196078*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::linen(0.980392*limit(),0.941176*limit(),0.901961*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::maroon(0.501961*limit(),0*limit(),0*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::mediumAquaMarine(0.4*limit(),0.803922*limit(),0.666667*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::mediumBlue(0*limit(),0*limit(),0.803922*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::mediumOrchid(0.729412*limit(),0.333333*limit(),0.827451*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::mediumPurple(0.576471*limit(),0.439216*limit(),0.858824*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::mediumSeaGreen(0.235294*limit(),0.701961*limit(),0.443137*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::mediumSlateBlue(0.482353*limit(),0.407843*limit(),0.933333*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::mediumSpringGreen(0*limit(),0.980392*limit(),0.603922*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::mediumTurquoise(0.282353*limit(),0.819608*limit(),0.8*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::mediumVioletRed(0.780392*limit(),0.0823529*limit(),0.521569*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::midnightBlue(0.0980392*limit(),0.0980392*limit(),0.439216*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::mintCream(0.960784*limit(),1*limit(),0.980392*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::mistyRose(1*limit(),0.894118*limit(),0.882353*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::moccasin(1*limit(),0.894118*limit(),0.709804*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::navajoWhite(1*limit(),0.870588*limit(),0.678431*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::navy(0*limit(),0*limit(),0.501961*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::oldLace(0.992157*limit(),0.960784*limit(),0.901961*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::olive(0.501961*limit(),0.501961*limit(),0*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::oliveDrab(0.419608*limit(),0.556863*limit(),0.137255*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::orange(1*limit(),0.647059*limit(),0*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::orangeRed(1*limit(),0.270588*limit(),0*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::orchid(0.854902*limit(),0.439216*limit(),0.839216*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::paleGoldenRod(0.933333*limit(),0.909804*limit(),0.666667*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::paleGreen(0.596078*limit(),0.984314*limit(),0.596078*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::paleTurquoise(0.686275*limit(),0.933333*limit(),0.933333*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::paleVioletRed(0.858824*limit(),0.439216*limit(),0.576471*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::papayaWhip(1*limit(),0.937255*limit(),0.835294*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::peachPuff(1*limit(),0.854902*limit(),0.72549*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::peru(0.803922*limit(),0.521569*limit(),0.247059*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::pink(1*limit(),0.752941*limit(),0.796078*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::plum(0.866667*limit(),0.627451*limit(),0.866667*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::powderBlue(0.690196*limit(),0.878431*limit(),0.901961*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::purple(0.501961*limit(),0*limit(),0.501961*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::rosyBrown(0.737255*limit(),0.560784*limit(),0.560784*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::royalBlue(0.254902*limit(),0.411765*limit(),0.882353*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::saddleBrown(0.545098*limit(),0.270588*limit(),0.0745098*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::salmon(0.980392*limit(),0.501961*limit(),0.447059*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::sandyBrown(0.956863*limit(),0.643137*limit(),0.376471*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::seaGreen(0.180392*limit(),0.545098*limit(),0.341176*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::seaShell(1*limit(),0.960784*limit(),0.933333*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::sienna(0.627451*limit(),0.321569*limit(),0.176471*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::silver(0.752941*limit(),0.752941*limit(),0.752941*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::skyBlue(0.529412*limit(),0.807843*limit(),0.921569*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::slateBlue(0.415686*limit(),0.352941*limit(),0.803922*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::slateGray(0.439216*limit(),0.501961*limit(),0.564706*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::slateGrey(0.439216*limit(),0.501961*limit(),0.564706*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::snow(1*limit(),0.980392*limit(),0.980392*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::springGreen(0*limit(),1*limit(),0.498039*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::steelBlue(0.27451*limit(),0.509804*limit(),0.705882*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::blueSteel(0.27451*limit(),0.509804*limit(),0.705882*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::tan(0.823529*limit(),0.705882*limit(),0.54902*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::teal(0*limit(),0.501961*limit(),0.501961*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::thistle(0.847059*limit(),0.74902*limit(),0.847059*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::tomato(1*limit(),0.388235*limit(),0.278431*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::turquoise(0.25098*limit(),0.878431*limit(),0.815686*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::violet(0.933333*limit(),0.509804*limit(),0.933333*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::wheat(0.960784*limit(),0.870588*limit(),0.701961*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::whiteSmoke(0.960784*limit(),0.960784*limit(),0.960784*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::yellowGreen(0.603922*limit(),0.803922*limit(),0.196078*limit());

template<typename A, typename B>
A clampedSubtract(const A& a, const B& b) {
	return CLAMP((float) a - (float) b, 0, ofColor_<A>::limit());
}
template<typename A, typename B>
A clampedAdd(const A& a, const B& b) {
	return CLAMP((float) a + (float) b, 0, ofColor_<A>::limit());
}
template<typename A, typename B>
A clampedDivide(const A& a, const B& b) {
	return CLAMP((float) a / (float) b, 0, ofColor_<A>::limit());
}
template<typename A, typename B>
A clampedMultiply(const A& a, const B& b) {
	return CLAMP((float) a * (float) b, 0, ofColor_<A>::limit());
}

template<typename PixelType>
float ofColor_<PixelType>::limit() {
	return numeric_limits<PixelType>::max();
}

template<>
float ofColor_<float>::limit() {
	return 1.f;
}

template<typename PixelType>
ofColor_<PixelType>::ofColor_(float _r, float _g, float _b, float _a):
    r(_r),
    g(_g),
    b(_b),
    a(_a){
}

template<typename PixelType>
ofColor_<PixelType>::ofColor_ (const ofColor_<PixelType>& color, float _a):
    r(color.r),
    g(color.g),
    b(color.b),
    a(_a){
}

template<typename PixelType>
ofColor_<PixelType>::ofColor_(float gray, float _a):
    r(gray),
    g(gray),
    b(gray),
    a(_a){
}

template<typename PixelType>
ofColor_<PixelType> ofColor_<PixelType>::fromHsb(float hue,
                                                 float saturation,
                                                 float brightness,
                                                 float alpha){
	ofColor_<PixelType> cur;
	cur.setHsb(hue, saturation, brightness, alpha);
	return cur;
}

template<typename PixelType>
ofColor_<PixelType> ofColor_<PixelType>::fromHex(int hexColor, float alpha){
	ofColor_<PixelType> cur;
	cur.setHex(hexColor, alpha);
	return cur;
}

template<typename PixelType>
void ofColor_<PixelType>::set(float _r, float _g, float _b, float _a){
	r = _r;
	g = _g;
	b = _b;
	a = _a;
}

template<typename PixelType>
void ofColor_<PixelType>::set(float _gray, float _a){
	r = _gray;
    g = _gray;
    b = _gray;
	a = _a;
}

template<typename PixelType>
void ofColor_<PixelType>::set(const ofColor_<PixelType>& color){
	r = color.r;
	g = color.g;
	b = color.b;
	a = color.a;
}

template<>
void ofColor_<unsigned char>::setHex(int hexColor, float alpha){
	r = (hexColor >> 16) & 0xff;
	g = (hexColor >> 8) & 0xff;
	b = (hexColor >> 0) & 0xff;
	a = alpha;
}

template<typename PixelType>
void ofColor_<PixelType>::setHex (int hexColor, float alpha){
	ofColor c = ofColor::fromHex(hexColor);
	*this = c;
	a = alpha;
}

template<typename PixelType>
ofColor_<PixelType>& ofColor_<PixelType>::clamp(){
	r = CLAMP(r, 0.0f, limit());
	g = CLAMP(g, 0.0f, limit());
	b = CLAMP(b, 0.0f, limit());
	a = CLAMP(a, 0.0f, limit());
	return *this;
}

template<typename PixelType>
ofColor_<PixelType>& ofColor_<PixelType>::invert() {
	r = limit() - r;
	g = limit() - g;
	b = limit() - b;
	return *this;
}

template<typename PixelType>
ofColor_<PixelType>& ofColor_<PixelType>::normalize() {
	float scaleFactor = getBrightness() / limit();
	*this /= scaleFactor;
	return *this;
}

template<typename PixelType>
ofColor_<PixelType>& ofColor_<PixelType>::lerp(const ofColor_<PixelType>& target,
                                               float amount) {
	float invAmount = 1.f - amount;
	r = invAmount * r + amount * target.r;
	g = invAmount * g + amount * target.g;
	b = invAmount * b + amount * target.b;
	a = invAmount * a + amount * target.a;
	return *this;
}

template<typename PixelType>
ofColor_<PixelType> ofColor_<PixelType>::getClamped() const {
	ofColor_<PixelType> cur(*this);
	cur.clamp();
	return cur;
}

template<typename PixelType>
ofColor_<PixelType> ofColor_<PixelType>::getInverted() const {
	ofColor_<PixelType> cur(*this);
	cur.invert();
	return cur;
}

template<typename PixelType>
ofColor_<PixelType> ofColor_<PixelType>::getNormalized() const {
	ofColor_<PixelType> cur(*this);
	cur.normalize();
	return cur;
}

template<typename PixelType>
ofColor_<PixelType> ofColor_<PixelType>::getLerped(const ofColor_<PixelType>& target,
                                                   float amount) const
{
	ofColor_<PixelType> cur(*this);
	cur.lerp(target, amount);
	return cur;
}

template<typename PixelType>
float ofColor_<PixelType>::getHue() const {
	float hue = 0;
    float saturation = 0;
    float brightness = 0;
	getHsb(hue, saturation, brightness);
	return hue;
}

template<typename PixelType>
float ofColor_<PixelType>::getHueAngle() const {
	return getHue() * 360. / limit();
}

template<typename PixelType>
float ofColor_<PixelType>::getSaturation() const {
	float hue = 0;
    float saturation = 0;
    float brightness = 0;
	getHsb(hue, saturation, brightness);
	return saturation;
}

template<typename PixelType>
float ofColor_<PixelType>::getBrightness() const {
	float max = r;
	if(g > max) {
		max = g;
	}
	if(b > max) {
		max = b;
	}
	return max;
}

template<typename PixelType>
float ofColor_<PixelType>::getLightness() const {
	return (r + g + b) / 3.f;
}

template<typename PixelType>
void ofColor_<PixelType>::getHsb(float& hue,
                                 float& saturation,
                                 float& brightness) const {
	float max = getBrightness();

	float min = r;
	if(g < min) {
		min = g;
	}
	if(b < min) {
		min = b;
	}

	if(max == min) { // grays
		hue = 0.f;
		saturation = 0.f;
		brightness = max;
		return;
	}

	float hueSixth;
	if(r == max) {
		hueSixth = (g - b) / (max - min);
		if(hueSixth < 0.f)
			hueSixth += 6.f;
	} else if (g == max) {
		hueSixth = 2.f + (b - r) / (max - min);
	} else {
		hueSixth = 4.f + (r - g) / (max - min);
	}
	hue = limit() * hueSixth / 6.f;
	saturation = limit() * (max - min) / max;
	brightness = max;
}

template<typename PixelType>
void ofColor_<PixelType>::setHue(float hue) {
	float oldHue = 0;
    float saturation = 0;
    float brightness = 0;
	getHsb(oldHue, saturation, brightness);
	setHsb(hue, saturation, brightness, a);
}

template<typename PixelType>
void ofColor_<PixelType>::setHueAngle(float angle) {
	setHue(angle / 360. * limit());
}

template<typename PixelType>
void ofColor_<PixelType>::setSaturation(float saturation) {
	float hue, oldSaturation, brightness;
	getHsb(hue, oldSaturation, brightness);
	setHsb(hue, saturation, brightness, a );
}

template<typename PixelType>
void ofColor_<PixelType>::setBrightness(float brightness) {
	float hue, saturation, oldBrightness;
	getHsb(hue, saturation, oldBrightness);
	setHsb(hue, saturation, brightness, a );
}

template<typename PixelType>
void ofColor_<PixelType>::setHsb(float hue, float saturation, float brightness, float alpha) {
	saturation = ofClamp(saturation, 0, limit());
	brightness = ofClamp(brightness, 0, limit());
	if(brightness == 0) { // black
		set(0);
	} else if(saturation == 0) { // grays
		set(brightness);
	} else {
		float hueSix = hue * 6.f / limit();
		float saturationNorm = saturation / limit();
		int hueSixCategory = (int) floorf(hueSix);
		float hueSixRemainder = hueSix - hueSixCategory;
		PixelType pv = (PixelType) ((1.f - saturationNorm) * brightness);
		PixelType qv = (PixelType) ((1.f - saturationNorm * hueSixRemainder) * brightness);
		PixelType tv = (PixelType) ((1.f - saturationNorm * (1.f - hueSixRemainder)) * brightness);
		switch(hueSixCategory) {
			case 0: case 6: // r
				r = brightness;
				g = tv;
				b = pv;
				break;
			case 1: // g
				r = qv;
				g = brightness;
				b = pv;
				break;
			case 2:
				r = pv;
				g = brightness;
				b = tv;
				break;
			case 3: // b
				r = pv;
				g = qv;
				b = brightness;
				break;
			case 4:
				r = tv;
				g = pv;
				b = brightness;
				break;
			case 5: // back to r
				r = brightness;
				g = pv;
				b = qv;
				break;
		}
	}

    // finally assign the alpha
    a = alpha;
}

template<>
int ofColor_<unsigned char>::getHex() const {
	return
		((0xff & (unsigned char) r) << 16) |
		((0xff & (unsigned char) g) << 8) |
		((0xff & (unsigned char) b));
}

template<typename PixelType>
int ofColor_<PixelType>::getHex() const {
	return ((ofColor) *this).getHex();
}

template<typename PixelType>
ofColor_<PixelType> & ofColor_<PixelType>::operator = (const float& val){
	r = val;
	g = val;
	b = val;
	a = limit();
	return *this;
}

template<typename PixelType>
bool ofColor_<PixelType>::operator == (const ofColor_<PixelType>& color) const {
	return (r == color.r) && (g == color.g) && (b == color.b) && (a == color.a);
}

template<typename PixelType>
bool ofColor_<PixelType>::operator != (const ofColor_<PixelType>& color) const {
	return (r != color.r) || (g != color.g) || (b != color.b) || (a != color.a);
}

template<typename PixelType>
ofColor_<PixelType> ofColor_<PixelType>::operator + (const ofColor_<PixelType>& color) const{
	ofColor_<PixelType> result(*this);
	result += color;
	return result;
}

template<typename PixelType>
ofColor_<PixelType> ofColor_<PixelType>::operator + (const float& val) const{
	ofColor_<PixelType> result(*this);
	result += val;
	return result;
}

template<typename PixelType>
ofColor_<PixelType> & ofColor_<PixelType>::operator += (const ofColor_<PixelType>& color){
	r = clampedAdd(r, color.r);
	g = clampedAdd(g, color.g);
	b = clampedAdd(b, color.b);
	return *this;
}

template<typename PixelType>
ofColor_<PixelType> & ofColor_<PixelType>::operator += (const float& val){
	r = clampedAdd(r, val);
	g = clampedAdd(g, val);
	b = clampedAdd(b, val);
	return *this;
}

template<typename PixelType>
ofColor_<PixelType> ofColor_<PixelType>::operator - (const ofColor_<PixelType>& color) const{
	ofColor_<PixelType> result(*this);
	result -= color;
	return result;
}

template<typename PixelType>
ofColor_<PixelType> ofColor_<PixelType>::operator - (const float& val) const{
	ofColor_<PixelType> result(*this);
	result -= val;
	return result;
}

template<typename PixelType>
ofColor_<PixelType> & ofColor_<PixelType>::operator -= (const ofColor_<PixelType>& color){
	r = clampedSubtract(r, color.r);
	g = clampedSubtract(g, color.g);
	b = clampedSubtract(b, color.b);
	return *this;
}

template<typename PixelType>
ofColor_<PixelType> & ofColor_<PixelType>::operator -= (const float& val){
	r = clampedSubtract(r, val);
	g = clampedSubtract(g, val);
	b = clampedSubtract(b, val);
	return *this;
}

template<typename PixelType>
ofColor_<PixelType> ofColor_<PixelType>::operator * (const ofColor_<PixelType>& color) const{
	ofColor_<PixelType> result(*this);
	result *= color;
	return result;
}

template<typename PixelType>
ofColor_<PixelType> ofColor_<PixelType>::operator * (const float& val) const{
	ofColor_<PixelType> result(*this);
	result *= val;
	return result;
}

template<typename PixelType>
ofColor_<PixelType> & ofColor_<PixelType>::operator *= (const ofColor_<PixelType>& color){
	r = clampedMultiply(r, (float) color.r / limit());
	g = clampedMultiply(g, (float) color.g / limit());
	b = clampedMultiply(b, (float) color.b / limit());
	return *this;
}

template<typename PixelType>
ofColor_<PixelType> & ofColor_<PixelType>::operator *= (const float& val){
	r = clampedMultiply(r, val);
	g = clampedMultiply(g, val);
	b = clampedMultiply(b, val);
	return *this;
}

template<typename PixelType>
ofColor_<PixelType> ofColor_<PixelType>::operator / (const ofColor_<PixelType>& color) const{
	ofColor_<PixelType> result(*this);
	result /= color;
	return result;
}

template<typename PixelType>
ofColor_<PixelType> ofColor_<PixelType>::operator / (const float& val) const{
	ofColor_<PixelType> result(*this);
	result /= val;
	return result;
}

template<typename PixelType>
ofColor_<PixelType> & ofColor_<PixelType>::operator /= (const ofColor_<PixelType>& color){
	r = clampedDivide(r, (float) color.r / limit());
	g = clampedDivide(g, (float) color.g / limit());
	b = clampedDivide(b, (float) color.b / limit());
	return *this;
}

template<typename PixelType>
ofColor_<PixelType> & ofColor_<PixelType>::operator /= (const float& val){
	r = clampedDivide(r, val);
	g = clampedDivide(g, val);
	b = clampedDivide(b, val);
	return *this;
}

template<typename PixelType>
const PixelType & ofColor_<PixelType>::operator [] (int n) const{
	switch( n ){
		case 0:
			return r;
		case 1:
			return g;
		case 2:
			return b;
		case 3:
			return a;
		default:
			return r;
			break;
	}
}

template<typename PixelType>
PixelType & ofColor_<PixelType>::operator [] (int n){
	switch( n ){
		case 0:
			return r;
		case 1:
			return g;
		case 2:
			return b;
		case 3:
			return a;
		default:
			return r;
			break;
	}
}

template class ofColor_<char>;
template class ofColor_<unsigned char>;
template class ofColor_<short>;
template class ofColor_<unsigned short>;
template class ofColor_<int>;
template class ofColor_<unsigned int>;
template class ofColor_<long>;
template class ofColor_<unsigned long>;
template class ofColor_<float>;
template class ofColor_<double>;


text:
package com.azure.data.cosmos.rx;

import com.azure.data.cosmos.CosmosClient;
import com.azure.data.cosmos.CosmosClientBuilder;
import com.azure.data.cosmos.CosmosDatabase;
import com.azure.data.cosmos.CosmosDatabaseForTest;
import com.azure.data.cosmos.CosmosUserProperties;
import com.azure.data.cosmos.FeedOptions;
import com.azure.data.cosmos.FeedResponse;
import com.azure.data.cosmos.internal.FeedResponseListValidator;
import com.azure.data.cosmos.internal.FeedResponseValidator;
import com.azure.data.cosmos.internal.TestUtils;
import org.apache.commons.lang3.StringUtils;
import org.testng.annotations.Factory;
import org.testng.annotations.Test;
import org.testng.annotations.Ignore;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import reactor.core.publisher.Flux;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

import static org.assertj.core.api.Assertions.assertThat;

public class UserQueryTest extends TestSuiteBase {

    public final String databaseId = CosmosDatabaseForTest.generateId();

    private List<CosmosUserProperties> createdUsers = new ArrayList<>();

    private CosmosClient client;
    private CosmosDatabase createdDatabase;

    @Factory(dataProvider = "clientBuilders")
    public UserQueryTest(CosmosClientBuilder clientBuilder) {
        super(clientBuilder);
    }

    @Test(groups = { "simple" }, timeOut = TIMEOUT)
    public void queryUsersWithFilter() throws Exception {

        String filterUserId = createdUsers.get(0).id();
        String query = String.format("SELECT * from c where c.id = '%s'", filterUserId);

        FeedOptions options = new FeedOptions();
        options.maxItemCount(5);
        Flux<FeedResponse<CosmosUserProperties>> queryObservable = createdDatabase.queryUsers(query, options);

        List<CosmosUserProperties> expectedUsers = createdUsers.stream()
                                                               .filter(c -> StringUtils.equals(filterUserId, c.id()) ).collect(Collectors.toList());

        assertThat(expectedUsers).isNotEmpty();

        int expectedPageSize = (expectedUsers.size() + options.maxItemCount() - 1) / options.maxItemCount();

        FeedResponseListValidator<CosmosUserProperties> validator = new FeedResponseListValidator.Builder<CosmosUserProperties>()
                .totalSize(expectedUsers.size())
                .exactlyContainsInAnyOrder(expectedUsers.stream().map(d -> d.resourceId()).collect(Collectors.toList()))
                .numberOfPages(expectedPageSize)
                .pageSatisfy(0, new FeedResponseValidator.Builder<CosmosUserProperties>()
                        .requestChargeGreaterThanOrEqualTo(1.0).build())
                .build();

        validateQuerySuccess(queryObservable, validator, 10000);
    }

    @Test(groups = { "simple" }, timeOut = TIMEOUT)
    public void queryAllUsers() throws Exception {

        String query = "SELECT * from c";

        FeedOptions options = new FeedOptions();
        options.maxItemCount(2);
        String databaseLink = TestUtils.getDatabaseNameLink(databaseId);
        Flux<FeedResponse<CosmosUserProperties>> queryObservable = createdDatabase.queryUsers(query, options);

        List<CosmosUserProperties> expectedUsers = createdUsers;

        assertThat(expectedUsers).isNotEmpty();

        int expectedPageSize = (expectedUsers.size() + options.maxItemCount() - 1) / options.maxItemCount();

        FeedResponseListValidator<CosmosUserProperties> validator = new FeedResponseListValidator.Builder<CosmosUserProperties>()
                .totalSize(expectedUsers.size())
                .exactlyContainsInAnyOrder(expectedUsers.stream().map(d -> d.resourceId()).collect(Collectors.toList()))
                .numberOfPages(expectedPageSize)
                .pageSatisfy(0, new FeedResponseValidator.Builder<CosmosUserProperties>()
                        .requestChargeGreaterThanOrEqualTo(1.0).build())
                .build();

        validateQuerySuccess(queryObservable, validator, 10000);
    }

    @Test(groups = { "simple" }, timeOut = TIMEOUT)
    public void queryUsers_NoResults() throws Exception {

        String query = "SELECT * from root r where r.id = '2'";
        FeedOptions options = new FeedOptions();
        Flux<FeedResponse<CosmosUserProperties>> queryObservable = createdDatabase.queryUsers(query, options);

        FeedResponseListValidator<CosmosUserProperties> validator = new FeedResponseListValidator.Builder<CosmosUserProperties>()
                .containsExactly(new ArrayList<>())
                .numberOfPages(1)
                .pageSatisfy(0, new FeedResponseValidator.Builder<CosmosUserProperties>()
                        .requestChargeGreaterThanOrEqualTo(1.0).build())
                .build();
        validateQuerySuccess(queryObservable, validator);
    }

    @BeforeClass(groups = { "simple" }, timeOut = SETUP_TIMEOUT)
    public void beforeClass() throws Exception {
        client = clientBuilder().build();

        createdDatabase = createDatabase(client, databaseId);

        for(int i = 0; i < 5; i++) {
            CosmosUserProperties user = new CosmosUserProperties();
            user.id(UUID.randomUUID().toString());
            createdUsers.add(createUser(client, databaseId, user).read().block().properties());
        }

        waitIfNeededForReplicasToCatchUp(clientBuilder());
    }

    @AfterClass(groups = { "simple" }, timeOut = SHUTDOWN_TIMEOUT, alwaysRun = true)
    public void afterClass() {
        safeDeleteDatabase(createdDatabase);
        safeClose(client);
    }
}

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;

namespace Kaleidoscope
{
    public class RadialKaleidoscope : IKaleidoscope
    {
        private int n;
        private Point center;
        private AngleMode mode;

        private static void RectToPolar(double x, double y, out double r, out double theta)
        {
            theta = Math.Atan2(y, x);
            r = Math.Sqrt(x * x + y * y);
        }

        private static void PolarToRect(double r, double theta, out double x, out double y)
        {
            x = Math.Cos(theta) * r;
            y = Math.Sin(theta) * r;
        }

        /// <summary>
        /// Creates a new RadialKaleidoscope object.
        /// </summary>
        /// <param name="n">The number of rays of symmetry.</param>
        /// <param name="center">The location from where the rays are projected.</param>
        public RadialKaleidoscope(int n, Point center, AngleMode mode = AngleMode.TwoWay)
        {
            this.n = n;
            this.center = center;
            this.mode = mode;
        }

        public Point Center
        {
            get { return center; }
        }

        public Point[] GetReflectedPoints(Point location)
        {
            double x = (double)(location.X - center.X);
            double y = (double)(location.Y - center.Y);
            double r, theta; RectToPolar(x, y, out r, out theta);

            Point[] points;
            if (mode == AngleMode.TwoWay) {
                points = new Point[2 * n];
            } else {
                points = new Point[n];
            }

            double angle = 2.0 * Math.PI / n;

            for (int i = 0; i < n; i++) {
                double x1, y1, x2, y2;
                PolarToRect(r, theta + i * angle, out x1, out y1);
                PolarToRect(r, -theta - i * angle, out x2, out y2);

                switch (mode) {
                    case AngleMode.TwoWay:
                        points[2 * i] = new Point((int)x1 + center.X, (int)y1 + center.Y);
                        points[2 * i + 1] = new Point((int)x2 + center.X, (int)y2 + center.Y);
                        break;
                    case AngleMode.OneWay:
                        points[i] = new Point((int)x1 + center.X, (int)y1 + center.Y);
                        break;
                }
            }

            return points;
        }

        public enum AngleMode
        {
            TwoWay = 0,
            OneWay = 1,
        }
    }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Venturia tremulae var. tremulae Aderh.

### Remarks
null


text:
package com.facebook.buck.d;

import com.facebook.buck.io.ProjectFilesystem;
import com.facebook.buck.model.BuildTargets;
import com.facebook.buck.rules.AbstractBuildRule;
import com.facebook.buck.rules.BuildContext;
import com.facebook.buck.rules.BuildRule;
import com.facebook.buck.rules.BuildRuleParams;
import com.facebook.buck.rules.BuildableContext;
import com.facebook.buck.rules.BuildableProperties;
import com.facebook.buck.rules.ExternalTestRunnerRule;
import com.facebook.buck.rules.ExternalTestRunnerTestSpec;
import com.facebook.buck.rules.HasRuntimeDeps;
import com.facebook.buck.rules.Label;
import com.facebook.buck.rules.SourcePathResolver;
import com.facebook.buck.rules.TestRule;
import com.facebook.buck.step.ExecutionContext;
import com.facebook.buck.step.Step;
import com.facebook.buck.step.fs.MakeCleanDirectoryStep;
import com.facebook.buck.test.TestCaseSummary;
import com.facebook.buck.test.TestResultSummary;
import com.facebook.buck.test.TestResults;
import com.facebook.buck.test.TestRunningOptions;
import com.facebook.buck.test.result.type.ResultType;
import com.facebook.buck.util.MoreCollectors;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.ImmutableSortedSet;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.nio.file.Path;
import java.util.Optional;
import java.util.concurrent.Callable;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@SuppressWarnings("PMD.TestClassWithoutTestCases")
public class DTest extends AbstractBuildRule implements
    ExternalTestRunnerRule,
    HasRuntimeDeps,
    TestRule {
  private ImmutableSortedSet<String> contacts;
  private ImmutableSortedSet<Label> labels;
  private final BuildRule testBinaryBuildRule;
  private final Optional<Long> testRuleTimeoutMs;

  public DTest(
      BuildRuleParams params,
      SourcePathResolver resolver,
      BuildRule testBinaryBuildRule,
      ImmutableSortedSet<String> contacts,
      ImmutableSortedSet<Label> labels,
      Optional<Long> testRuleTimeoutMs) {
    super(params, resolver);
    this.contacts = contacts;
    this.labels = labels;
    this.testRuleTimeoutMs = testRuleTimeoutMs;
    this.testBinaryBuildRule = testBinaryBuildRule;
  }

  @Override
  public ImmutableList<Step> getBuildSteps(
      BuildContext context,
      BuildableContext buildableContext) {
    return ImmutableList.of();
  }

  @Override
  public ImmutableSet<String> getContacts() {
    return contacts;
  }

  public ImmutableList<String> getExecutableCommand(ProjectFilesystem projectFilesystem) {
    return ImmutableList.of(
        projectFilesystem.resolve(getPathToOutput()).toString());
  }

  @Override
  public ImmutableSet<Label> getLabels() {
    return labels;
  }

  /**
   * @return the path to which the test commands output is written.
   */
  protected Path getPathToTestExitCode() {
    return getPathToTestOutputDirectory().resolve("exitCode");
  }

  /**
   * @return the path to which the test commands output is written.
   */
  protected Path getPathToTestOutput() {
    return getPathToTestOutputDirectory().resolve("output");
  }

  @Override
  public Path getPathToTestOutputDirectory() {
    return BuildTargets.getGenPath(
        getProjectFilesystem(),
        getBuildTarget(),
        "__test_%s_output__");
  }

  @Override
  public BuildableProperties getProperties() {
    return new BuildableProperties(BuildableProperties.Kind.TEST);
  }

  private ImmutableList<String> getShellCommand() {
    return getExecutableCommand(getProjectFilesystem());
  }

  @Override
  public boolean hasTestResultFiles() {
    return getProjectFilesystem().isFile(getPathToTestOutput());
  }

  @Override
  public Callable<TestResults> interpretTestResults(
      final ExecutionContext executionContext,
      boolean isUsingTestSelectors,
      final boolean isDryRun) {
    return () -> {
      ResultType resultType = ResultType.FAILURE;

      // Successful exit indicates success.
      try (ObjectInputStream objectIn = new ObjectInputStream(new FileInputStream(
              getProjectFilesystem().resolve(getPathToTestExitCode()).toFile()))) {
        int exitCode = objectIn.readInt();
        if (exitCode == 0) {
          resultType = ResultType.SUCCESS;
        }
      } catch (IOException e) {
        // Any IO error means something went awry, so it's a failure.
        resultType = ResultType.FAILURE;
      }

      String testOutput = getProjectFilesystem().readFileIfItExists(
          getPathToTestOutput()).orElse("");
      String message = "";
      String stackTrace = "";
      String testName = "";
      if (resultType == ResultType.FAILURE && !testOutput.isEmpty()) {
        // We don't get any information on successful runs, but failures usually come with
        // some information. This code parses it.
        int firstNewline = testOutput.indexOf('\n');
        String firstLine = firstNewline == -1
              ? testOutput
              : testOutput.substring(0, firstNewline);
        // First line has format <Exception name>@<location>: <message>
        // Use <location> as test name, and <message> as message.
        Pattern firstLinePattern = Pattern.compile("^[^@]*@([^:]*): (.*)");
        Matcher m = firstLinePattern.matcher(firstLine);
        if (m.matches()) {
          testName = m.group(1);
          message = m.group(2);
        }
        // The whole output is actually a stack trace.
        stackTrace = testOutput;
      }

      TestResultSummary summary = new TestResultSummary(
          getBuildTarget().getShortName(),
          testName,
          resultType,
          /* time */ 0,
          message,
          stackTrace,
          testOutput,
          /* stderr */ "");

      return TestResults.of(
          getBuildTarget(),
          ImmutableList.of(
              new TestCaseSummary(
                  "main",
                  ImmutableList.of(summary))
          ),
          contacts,
          labels.stream()
              .map(Object::toString)
              .collect(MoreCollectors.toImmutableSet()));
    };
  }

  @Override
  public ImmutableList<Step> runTests(
      ExecutionContext executionContext,
      TestRunningOptions options,
      TestReportingCallback testReportingCallback) {
    if (options.isDryRun()) {
      return ImmutableList.of();
    } else {
      return ImmutableList.of(
          new MakeCleanDirectoryStep(getProjectFilesystem(), getPathToTestOutputDirectory()),
          new DTestStep(
              getProjectFilesystem(),
              getShellCommand(),
              getPathToTestExitCode(),
              testRuleTimeoutMs,
              getPathToTestOutput()));
    }
  }

  @Override
  public boolean runTestSeparately() {
    return false;
  }

  @Override
  public boolean supportsStreamingTests() {
    return false;
  }

  @Override
  public ExternalTestRunnerTestSpec getExternalTestRunnerSpec(
      ExecutionContext executionContext,
      TestRunningOptions testRunningOptions) {
    return ExternalTestRunnerTestSpec.builder()
        .setTarget(getBuildTarget())
        .setType("dunit")
        .setCommand(getShellCommand())
        .setLabels(getLabels())
        .setContacts(getContacts())
        .build();
  }

  @Override
  public Path getPathToOutput() {
    return Preconditions.checkNotNull(testBinaryBuildRule.getPathToOutput());
  }

  @Override
  public ImmutableSortedSet<BuildRule> getRuntimeDeps() {
    // Return the actual executable as a runtime dependency.
    // Without this, the file is not written when we get a cache hit.
    return ImmutableSortedSet.of(testBinaryBuildRule);
  }

}


text:
package clustering;

import java.util.Random;

/**
 * Created by evelina on 12/04/2014.
 */
public class RandomLocationsGenerator {

    // UK bounds (REMEMBER: Latitude grows from left, longitude grows from bottom)
    // sw=51.508742,-3.240967
    // ne=54.316523,-0.736084

    private static final Random random = new Random();

    public static LatLng generate(LatLng sw, LatLng ne) {
        double latMin = sw.latitude;
        double latRange = ne.latitude - sw.latitude;
        double lngMin = sw.longitude;
        double lngRange = ne.longitude - sw.longitude;

        return new LatLng(latMin + random.nextDouble() * latRange, lngMin + random.nextDouble() * lngRange);
    }
}


text:
<?xml version="1.0"?>
<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta name="generator" content="eZ Components; http://ezcomponents.org"/>
    <title>Empty document</title>
  </head>
  <body/>
</html>


text:
const u8t NIMBUS_EVENT_TOUCH_BEGAN_ID = 3;
const u8t NIMBUS_EVENT_TOUCH_MOVED_ID = 4;
const u8t NIMBUS_EVENT_TOUCH_ENDED_ID = 5;
const u8t NIMBUS_EVENT_TOUCH_STATIONARY_ID = 6;
const u8t NIMBUS_EVENT_TOUCH_ZOOM_ID = 7;
const u8t NIMBUS_EVENT_TOUCH_HOVER_ID = 8;

void nimbus_touch_changed_send(struct nimbus_event_write_stream* stream, u8t event_type_id, u8t button_id,
							   nimbus_vector2 position)
{
	nimbus_touch_changed changed;
	changed.position.x = position.x;
	changed.position.y = position.y;
	changed.finger_id = button_id;

	nimbus_event_stream_write_event(stream, event_type_id, changed);
}


text:
<?php

class Contact extends CAction
{
    /**
     * Displays the contact page
     */

    public function run()
    {
        $this->controller->layout = '//layouts/main';

        $model=new ContactForm;

        if(isset($_POST['ContactForm']))
        {
            $model->attributes=$_POST['ContactForm'];

            if($model->validate())
            {
                $y = Yii::app();
                $y->mail(
                    $y->params['adminEmail'],
                    $model->subject,
                    'user_message',
                    array(
                        'name' => $model->name,
                        'email'=> $model->email,
                        'body' => $model->body,
                    ),
                    $model->email
                );

                $y->user->setFlash('contact','Thanks! We will respond to you as soon as possible.');
                $this->controller->refresh();
            }
        }

        $this->controller->render('contact',array('model'=>$model));
    }
}


text:
Galcon-like Strategy Game
=========================

Galcon (working title) is a real time strategy game in which players fight over scattered planets and build fleets and stuff. While based off of games like Galcon and Eufloria, this game intends to introduce aspects such as building construction, varying ship types, and ship-to-ship interception.

I am currently working on this project by myself in my spare time, but I'd appreciate any playtesting, debugging, or development assistance. Feel free to write up an issue, make a pull request, or email me at austonst@gmail.com

Installation
------------

Galcon's dependencies should be fairly simple to get through most distribution's package manager. Ensure that you have installed:

* SDL
* SDL_image
* SDL_ttf

Currently, Galcon can be built using the provided makefile. It's designed for Linux systems using g++, though with a few adaptations, it can likely work on other platforms. Building is as simple as running:

    make

This will produce an executable binary in the same directory which can be run with:

    ./galcon


text:
//
//  ZDScaleCollectionHeadView.m
//  scalez
//
//  Created by Jorge Moura on 15/06/14.
//  Copyright (c) 2014 Jorge Moura. All rights reserved.
//

#import "ZDScaleCollectionHeadView.h"

@interface ZDScaleCollectionHeadView ()

@property(weak) IBOutlet UILabel *headerLabel;
@end

@implementation ZDScaleCollectionHeadView

//---------------------------------------------------------------------------------------
//---------------------------------------------------------------------------------------
#pragma mark - Constructor
//---------------------------------------------------------------------------------------
- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
        [[self headerLabel] setText:@" "];
    }
    return self;
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
    // Drawing code
}
*/

//---------------------------------------------------------------------------------------
//---------------------------------------------------------------------------------------
#pragma mark - Public Methods
//---------------------------------------------------------------------------------------
- (void)header:(NSString *)text {

    [[self headerLabel] setText:text];
}

@end


text:
package testonly

import (
	"fmt"
	"reflect"
	"sort"

	"github.com/golang/mock/gomock"
	"github.com/google/trillian/storage"
)

type nodeIDEq struct {
	expectedID storage.NodeID
}

// Matches implements the gomock.Matcher API.
func (m nodeIDEq) Matches(x interface{}) bool {
	n, ok := x.(storage.NodeID)
	if !ok {
		return false
	}
	return n.Equivalent(m.expectedID)
}

func (m nodeIDEq) String() string {
	return fmt.Sprintf("is %s", m.expectedID.String())
}

// NodeIDEq returns a matcher that expects the specified NodeID.
func NodeIDEq(n storage.NodeID) gomock.Matcher {
	return nodeIDEq{n}
}

// We need a stable order to match the mock expectations so we sort them by
// prefix len before passing them to the mock library. Might need extending
// if we have more complex tests.
func prefixLen(n1, n2 *storage.Node) bool {
	return n1.NodeID.PrefixLenBits < n2.NodeID.PrefixLenBits
}

// NodeSet returns a matcher that expects the given set of Nodes.
func NodeSet(nodes []storage.Node) gomock.Matcher {
	by(prefixLen).sort(nodes)
	return nodeSet{nodes}
}

type nodeSet struct {
	other []storage.Node
}

// Matches implements the gomock.Matcher API.
func (n nodeSet) Matches(x interface{}) bool {
	nodes, ok := x.([]storage.Node)
	if !ok {
		return false
	}
	by(prefixLen).sort(nodes)
	return reflect.DeepEqual(nodes, n.other)
}

func (n nodeSet) String() string {
	return fmt.Sprintf("equivalent to %v", n.other)
}

// Node sorting boilerplate below.

type by func(n1, n2 *storage.Node) bool

func (by by) sort(nodes []storage.Node) {
	ns := &nodeSorter{nodes: nodes, by: by}
	sort.Sort(ns)
}

type nodeSorter struct {
	nodes []storage.Node
	by    func(n1, n2 *storage.Node) bool
}

// Len implements the sort.Interface API.
func (n *nodeSorter) Len() int {
	return len(n.nodes)
}

// Swap implements the sort.Interface API.
func (n *nodeSorter) Swap(i, j int) {
	n.nodes[i], n.nodes[j] = n.nodes[j], n.nodes[i]
}

// Less implements the sort.Interface API.
func (n *nodeSorter) Less(i, j int) bool {
	return n.by(&n.nodes[i], &n.nodes[j])
}

// End sorting boilerplate.


text:
from sopel.module import commands, example, NOLIMIT
from requests import get

@commands('carry')
@example('.carry fooobarrr')
def carry(bot, trigger):
    """.carry show what nickname is carrying today."""

    qnick = trigger.group(2)
    target_nick = ""
    if not qnick:
        carry_url = bot.db.get_nick_value(trigger.nick, 'todayscarry')
        if not carry_url:
            return bot.msg(trigger.sender, "I don't know what you're carrying. " +
                    "Tell my what you're carrying like, .setcarry imgur.com")
        target_nick = trigger.nick
    else:
        target_nick = qnick.strip()
        carry_url = bot.db.get_nick_value(target_nick, 'todayscarry')
        if not carry_url:
            return bot.msg(trigger.sender, "I don't know what {nickname} is carrying. ".format(nickname=target_nick) +
                    "{nickname}: tell my what you're carrying like, .setcarry imgur.com".format(nickname=target_nick))

    bot.say("{nick} is currently carrying {url}".format(nick=target_nick, url=carry_url))

@commands('setcarry', 'sc')
@example('.sc http://imgur.com')
def update_carry(bot, trigger):
    """Set the knife you're carrying today."""
    selection = trigger.group(2)
    if not selection:
        bot.reply('Give me a list of imgur urls')
        return NOLIMIT
    body = get(selection)
    if not body:
        return bot.reply("Invalid url {}".format(selection))
    bot.db.set_nick_value(trigger.nick, 'todayscarry', trigger.group(2))
    bot.reply("I have your carry set as {url}".format(url=trigger.group(2)))


text:
<?php

namespace AppBundle\Controller;

use AppBundle\Entity\Task;
use AppBundle\Form\TaskType;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;

class TaskController extends Controller
{
    /**
     * @param Request $request
     * @Route("/", name="index")
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function index(Request $request)
    {
        $taskRepository = $this->getDoctrine()->getRepository(Task::class);

        $tasks = $taskRepository->findAll();

        return $this->render('task/index.html.twig', ['tasks' => $tasks]);
    }

    /**
     * @param Request $request
     * @Route("/create", name="create")
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function create(Request $request)
    {
        $task = new Task();

        $form = $this->createForm(TaskType::class, $task);

        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            if ($task->getTitle()==null || $task->getComments()==null) {
                return $this->redirectToRoute('index');
            }
           //return $this->render('task/create.html.twig', ['task'=>$task, 'form'=>$form->createView()]);

            $em = $this->getDoctrine()->getManager();
            $em->persist($task);
            $em->flush();

            return $this->redirectToRoute('index');
        }

        return $this->render('task/create.html.twig', ['form' => $form->createView()]);
    }

    /**
     * @Route("/delete/{id}", name="delete")
     *
     * @param $id
     * @param Request $request
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function delete($id, Request $request)
    {
        $taskRepository=$this->getDoctrine()->getRepository(Task::class);

        $task = $taskRepository->find($id);

        if ($task == null){
            return $this->redirectToRoute('index');
        }
        $form = $this->createForm(TaskType::class, $task);

        $form -> handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $em=$this->getDoctrine()->getManager();

            $em->remove($task);
            $em->flush();
            return $this->redirectToRoute('index');
        }

        return $this->render('task/delete.html.twig',['task'=>$task, 'form' => $form->createView()]);
    }
}


text:
package com.bytebeats.codelab.jackson;

import com.bytebeats.codelab.model.User;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * ${DESCRIPTION}
 *
 * @author Ricky Fung
 * @date 2017-02-27 15:31
 */
public class JacksonDemo {

    public static void main(String[] args) throws IOException {

        new JacksonDemo().readJson();
    }

    public void writeJson() throws IOException {
        ObjectMapper mapper = new ObjectMapper();

        mapper.configure(SerializationFeature.INDENT_OUTPUT, true);
        mapper.configure(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS, true);
        SimpleDateFormat outputFormat = new SimpleDateFormat("yyyy-MMM-dd HH:mm:ss");
        mapper.setDateFormat(outputFormat);

        User user = new User();
        user.setUsername("ricky");
        user.setBirthday(new Date());

        mapper.writeValue(System.out, user);
    }

    public void readJson() throws IOException {

        ObjectMapper mapper = new ObjectMapper();

        String json =
                "{ \"username\" : \"ricky\", \"password\" : \"1234\" }";

        User user = mapper.readValue(json, User.class);
        System.out.println("user.username = " + user.getUsername());
        System.out.println("user.password = " + user.getPassword());

    }
}


text:
package com.facebook.model;

import android.annotation.SuppressLint;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.json.JSONException;
import org.json.JSONObject;

class JsonUtil
{
  static void jsonObjectClear(JSONObject paramJSONObject)
  {
    Iterator localIterator = paramJSONObject.keys();
    while (localIterator.hasNext())
    {
      localIterator.next();
      localIterator.remove();
    }
  }

  static boolean jsonObjectContainsValue(JSONObject paramJSONObject, Object paramObject)
  {
    Iterator localIterator = paramJSONObject.keys();
    while (localIterator.hasNext())
    {
      Object localObject = paramJSONObject.opt((String)localIterator.next());
      if ((localObject != null) && (localObject.equals(paramObject)))
        return true;
    }
    return false;
  }

  static Set<Map.Entry<String, Object>> jsonObjectEntrySet(JSONObject paramJSONObject)
  {
    HashSet localHashSet = new HashSet();
    Iterator localIterator = paramJSONObject.keys();
    while (localIterator.hasNext())
    {
      String str = (String)localIterator.next();
      localHashSet.add(new JSONObjectEntry(str, paramJSONObject.opt(str)));
    }
    return localHashSet;
  }

  static Set<String> jsonObjectKeySet(JSONObject paramJSONObject)
  {
    HashSet localHashSet = new HashSet();
    Iterator localIterator = paramJSONObject.keys();
    while (localIterator.hasNext())
      localHashSet.add(localIterator.next());
    return localHashSet;
  }

  static void jsonObjectPutAll(JSONObject paramJSONObject, Map<String, Object> paramMap)
  {
    Iterator localIterator = paramMap.entrySet().iterator();
    while (localIterator.hasNext())
    {
      Map.Entry localEntry = (Map.Entry)localIterator.next();
      try
      {
        paramJSONObject.putOpt((String)localEntry.getKey(), localEntry.getValue());
      }
      catch (JSONException localJSONException)
      {
        throw new IllegalArgumentException(localJSONException);
      }
    }
  }

  static Collection<Object> jsonObjectValues(JSONObject paramJSONObject)
  {
    ArrayList localArrayList = new ArrayList();
    Iterator localIterator = paramJSONObject.keys();
    while (localIterator.hasNext())
      localArrayList.add(paramJSONObject.opt((String)localIterator.next()));
    return localArrayList;
  }

  static final class JSONObjectEntry
    implements Map.Entry<String, Object>
  {
    private final String key;
    private final Object value;

    JSONObjectEntry(String paramString, Object paramObject)
    {
      this.key = paramString;
      this.value = paramObject;
    }

    @SuppressLint({"FieldGetter"})
    public final String getKey()
    {
      return this.key;
    }

    public final Object getValue()
    {
      return this.value;
    }

    public final Object setValue(Object paramObject)
    {
      throw new UnsupportedOperationException("JSONObjectEntry is immutable");
    }
  }
}

/* Location:           /Users/vikas/Documents/Mhacks_Real_app/classes-dex2jar.jar
 * Qualified Name:     com.facebook.model.JsonUtil
 * JD-Core Version:    0.6.2
 */


text:
/******************************************************************************
 *  Compilation:  javac StdAudio.java
 *  Execution:    java StdAudio
 *  Dependencies: none
 *
 *  Simple library for reading, writing, and manipulating .wav files.
 *
 *
 *  Limitations
 *  -----------
 *    - Does not seem to work properly when reading .wav files from a .jar file.
 *    - Assumes the audio is monaural, with sampling rate of 44,100.
 *
 ******************************************************************************/

package com.afcrowther.algorithms.library;

import javax.sound.sampled.Clip;

import java.io.File;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.IOException;

import java.net.URL;

import javax.sound.sampled.AudioFileFormat;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.SourceDataLine;
import javax.sound.sampled.UnsupportedAudioFileException;

/**
 *  Standard audio. This class provides a basic capability for
 *  creating, reading, and saving audio.
 *

 *  The audio format uses a sampling rate of 44,100 (CD quality audio), 16-bit, monaural.
 *
 *

 *  For additional documentation, see Section 1.5 of
 *  Introduction to Programming in Java: An Interdisciplinary Approach by Robert Sedgewick and Kevin Wayne.
 *
 *  @author Robert Sedgewick
 *  @author Kevin Wayne
 */
public final class StdAudio {

    /**
     *  The sample rate - 44,100 Hz for CD quality audio.
     */
    public static final int SAMPLE_RATE = 44100;

    private static final int BYTES_PER_SAMPLE = 2;                // 16-bit audio
    private static final int BITS_PER_SAMPLE = 16;                // 16-bit audio
    private static final double MAX_16_BIT = Short.MAX_VALUE;     // 32,767
    private static final int SAMPLE_BUFFER_SIZE = 4096;

    private static SourceDataLine line;   // to play the sound
    private static byte[] buffer;         // our internal buffer
    private static int bufferSize = 0;    // number of samples currently in internal buffer

    private StdAudio() {
        // can not instantiate
    }

    // static initializer
    static {
        init();
    }

    // open up an audio stream
    private static void init() {
        try {
            // 44,100 samples per second, 16-bit audio, mono, signed PCM, little Endian
            AudioFormat format = new AudioFormat((float) SAMPLE_RATE, BITS_PER_SAMPLE, 1, true, false);
            DataLine.Info info = new DataLine.Info(SourceDataLine.class, format);

            line = (SourceDataLine) AudioSystem.getLine(info);
            line.open(format, SAMPLE_BUFFER_SIZE * BYTES_PER_SAMPLE);

            // the internal buffer is a fraction of the actual buffer size, this choice is arbitrary
            // it gets divided because we can't expect the buffered data to line up exactly with when
            // the sound card decides to push out its samples.
            buffer = new byte[SAMPLE_BUFFER_SIZE * BYTES_PER_SAMPLE/3];
        }
        catch (LineUnavailableException e) {
            System.out.println(e.getMessage());
        }

        // no sound gets made before this call
        line.start();
    }

    /**
     * Closes standard audio.
     */
    public static void close() {
        line.drain();
        line.stop();
    }

    /**
     * Writes one sample (between -1.0 and +1.0) to standard audio.
     * If the sample is outside the range, it will be clipped.
     *
     * @param  sample the sample to play
     * @throws IllegalArgumentException if the sample is {@code Double.NaN}
     */
    public static void play(double sample) {

        // clip if outside [-1, +1]
        if (Double.isNaN(sample)) throw new IllegalArgumentException("sample is NaN");
        if (sample < -1.0) sample = -1.0;
        if (sample > +1.0) sample = +1.0;

        // convert to bytes
        short s = (short) (MAX_16_BIT * sample);
        buffer[bufferSize++] = (byte) s;
        buffer[bufferSize++] = (byte) (s >> 8);   // little Endian

        // send to sound card if buffer is full
        if (bufferSize >= buffer.length) {
            line.write(buffer, 0, buffer.length);
            bufferSize = 0;
        }
    }

    /**
     * Writes the array of samples (between -1.0 and +1.0) to standard audio.
     * If a sample is outside the range, it will be clipped.
     *
     * @param  samples the array of samples to play
     * @throws IllegalArgumentException if any sample is {@code Double.NaN}
     */
    public static void play(double[] samples) {
        if (samples == null) throw new NullPointerException("argument to play() is null");
        for (int i = 0; i < samples.length; i++) {
            play(samples[i]);
        }
    }

    /**
     * Reads audio samples from a file (in .wav or .au format) and returns
     * them as a double array with values between -1.0 and +1.0.
     *
     * @param  filename the name of the audio file
     * @return the array of samples
     */
    public static double[] read(String filename) {
        byte[] data = readByte(filename);
        int n = data.length;
        double[] d = new double[n/2];
        for (int i = 0; i < n/2; i++) {
            d[i] = ((short) (((data[2*i+1] & 0xFF) << 8) + (data[2*i] & 0xFF))) / ((double) MAX_16_BIT);
        }
        return d;
    }

    /**
     * Plays an audio file (in .wav, .mid, or .au format) in a background thread.
     *
     * @param filename the name of the audio file
     */
    public static synchronized void play(String filename) {
        if (filename == null) throw new NullPointerException();

        // code adapted from: http://stackoverflow.com/questions/26305/how-can-i-play-sound-in-java
        try {
            Clip clip = AudioSystem.getClip();
            InputStream is = StdAudio.class.getResourceAsStream(filename);
            AudioInputStream ais = AudioSystem.getAudioInputStream(is);
            clip.open(ais);
            clip.start();
        }
        catch (RuntimeException e) {
            System.out.println("could not play '" + filename + "'");
            throw e;
        }
        catch (Exception e) {
            System.out.println("could not play '" + filename + "'");
            e.printStackTrace();
        }
    }

    /**
     * Loops an audio file (in .wav, .mid, or .au format) in a background thread.
     *
     * @param filename the name of the audio file
     */
    public static synchronized void loop(String filename) {
        if (filename == null) throw new NullPointerException();

        // code adapted from: http://stackoverflow.com/questions/26305/how-can-i-play-sound-in-java
        try {
            Clip clip = AudioSystem.getClip();
            InputStream is = StdAudio.class.getResourceAsStream(filename);
            AudioInputStream ais = AudioSystem.getAudioInputStream(is);
            clip.open(ais);
            clip.loop(Clip.LOOP_CONTINUOUSLY);
        }
        catch (RuntimeException e) {
            System.out.println("could not play '" + filename + "'");
            throw e;
        }
        catch (Exception e) {
            System.out.println("could not play '" + filename + "'");
            e.printStackTrace();
        }
    }

    // return data as a byte array
    private static byte[] readByte(String filename) {
        byte[] data = null;
        AudioInputStream ais = null;
        try {

            // try to read from file
            File file = new File(filename);
            if (file.exists()) {
                ais = AudioSystem.getAudioInputStream(file);
                int bytesToRead = ais.available();
                data = new byte[bytesToRead];
                int bytesRead = ais.read(data);
                if (bytesToRead != bytesRead) throw new RuntimeException("read only " + bytesRead + " of " + bytesToRead + " bytes");
            }

            // try to read from URL
            else {
                URL url = StdAudio.class.getResource(filename);
                ais = AudioSystem.getAudioInputStream(url);
                int bytesToRead = ais.available();
                data = new byte[bytesToRead];
                int bytesRead = ais.read(data);
                if (bytesToRead != bytesRead) throw new RuntimeException("read only " + bytesRead + " of " + bytesToRead + " bytes");
            }
        }
        catch (IOException e) {
            System.out.println(e.getMessage());
            throw new RuntimeException("Could not read " + filename);
        }

        catch (UnsupportedAudioFileException e) {
            System.out.println(e.getMessage());
            throw new RuntimeException(filename + " in unsupported audio format");
        }

        return data;
    }

    /**
     * Saves the double array as an audio file (using .wav or .au format).
     *
     * @param  filename the name of the audio file
     * @param  samples the array of samples
     */
    public static void save(String filename, double[] samples) {

        // assumes 44,100 samples per second
        // use 16-bit audio, mono, signed PCM, little Endian
        AudioFormat format = new AudioFormat(SAMPLE_RATE, 16, 1, true, false);
        byte[] data = new byte[2 * samples.length];
        for (int i = 0; i < samples.length; i++) {
            int temp = (short) (samples[i] * MAX_16_BIT);
            data[2*i + 0] = (byte) temp;
            data[2*i + 1] = (byte) (temp >> 8);
        }

        // now save the file
        try {
            ByteArrayInputStream bais = new ByteArrayInputStream(data);
            AudioInputStream ais = new AudioInputStream(bais, format, samples.length);
            if (filename.endsWith(".wav") || filename.endsWith(".WAV")) {
                AudioSystem.write(ais, AudioFileFormat.Type.WAVE, new File(filename));
            }
            else if (filename.endsWith(".au") || filename.endsWith(".AU")) {
                AudioSystem.write(ais, AudioFileFormat.Type.AU, new File(filename));
            }
            else {
                throw new RuntimeException("File format not supported: " + filename);
            }
        }
        catch (IOException e) {
            System.out.println(e);
        }
    }

   /***************************************************************************
    * Unit tests {@code StdAudio}.
    ***************************************************************************/

    // create a note (sine wave) of the given frequency (Hz), for the given
    // duration (seconds) scaled to the given volume (amplitude)
    private static double[] note(double hz, double duration, double amplitude) {
        int n = (int) (StdAudio.SAMPLE_RATE * duration);
        double[] a = new double[n+1];
        for (int i = 0; i <= n; i++)
            a[i] = amplitude * Math.sin(2 * Math.PI * i * hz / StdAudio.SAMPLE_RATE);
        return a;
    }

    /**
     * Test client - play an A major scale to standard audio.
     *
     * @param args the command-line arguments
     */
    public static void main(String[] args) {

        // 440 Hz for 1 sec
        double freq = 440.0;
        for (int i = 0; i <= StdAudio.SAMPLE_RATE; i++) {
            StdAudio.play(0.5 * Math.sin(2*Math.PI * freq * i / StdAudio.SAMPLE_RATE));
        }

        // scale increments
        int[] steps = { 0, 2, 4, 5, 7, 9, 11, 12 };
        for (int i = 0; i < steps.length; i++) {
            double hz = 440.0 * Math.pow(2, steps[i] / 12.0);
            StdAudio.play(note(hz, 1.0, 0.5));
        }

        // need to call this in non-interactive stuff so the program doesn't terminate
        // until all the sound leaves the speaker.
        StdAudio.close();
    }
}

/******************************************************************************
 *  Copyright 2002-2016, Robert Sedgewick and Kevin Wayne.
 *
 *  This file is part of algs4.jar, which accompanies the textbook
 *
 *      Algorithms, 4th edition by Robert Sedgewick and Kevin Wayne,
 *      Addison-Wesley Professional, 2011, ISBN 0-321-57351-X.
 *      http://algs4.cs.princeton.edu
 *
 *
 *  algs4.jar is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  algs4.jar is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with algs4.jar.  If not, see http://www.gnu.org/licenses.
 ******************************************************************************/


text:
package com.bdxh.utils.arith;

import java.math.BigDecimal;

/**
 * Created by hanlijin on 2017/9/28 09:47
 * Mail:hanlijin@xihebeidou.com
 */

public class Arith {
    /**
     * 提供精确加法计算的add方法
     * @param value1 被加数
     * @param value2 加数
     * @return 两个参数的和
     */
    public static double add(double value1,double value2){
        BigDecimal b1 = BigDecimal.valueOf(value1);
        BigDecimal b2 = BigDecimal.valueOf(value2);
        return b1.add(b2).doubleValue();
    }

    /**
     * 提供精确减法运算的sub方法
     * @param value1 被减数
     * @param value2 减数
     * @return 两个参数的差
     */
    public static double sub(double value1,double value2){
        BigDecimal b1 = BigDecimal.valueOf(value1);
        BigDecimal b2 = BigDecimal.valueOf(value2);
        return b1.subtract(b2).doubleValue();
    }

    /**
     * 提供精确乘法运算的mul方法
     * @param value1 被乘数
     * @param value2 乘数
     * @return 两个参数的积
     */
    public static double mul(double value1,double value2){
        BigDecimal b1 = BigDecimal.valueOf(value1);
        BigDecimal b2 = BigDecimal.valueOf(value2);
        return b1.multiply(b2).doubleValue();
    }

    /**
     * 提供精确的除法运算方法div
     * @param value1 被除数
     * @param value2 除数
     * @param scale 精确范围
     * @return 两个参数的商
     * @throws IllegalAccessException
     */
    public static double div(double value1,double value2,int scale) throws IllegalAccessException{
        //如果精确范围小于0,抛出异常信息
        if(scale<0){
            throw new IllegalAccessException("精确度不能小于0");
        }
        BigDecimal b1 = BigDecimal.valueOf(value1);
        BigDecimal b2 = BigDecimal.valueOf(value2);
        return b1.divide(b2, scale).doubleValue();
    }
}


text:
class User < ActiveRecord::Base

  has_many :ratings
  has_many :movies, through: :ratings
  has_secure_password

  validates :email, :username, presence: true
  validates :email, :username, uniqueness: true
  validates :password, length: { in: 6..20 }

end


text:
package Armadillo.Analytics.Optimisation.Base.Operators.Selection;

import Armadillo.Analytics.Optimisation.Base.Operators.IndividualClasses.Individual;
import Armadillo.Analytics.Optimisation.Base.Problem.HeuristicProblem;

public abstract class ASelection implements ISelection
{
     protected HeuristicProblem m_heuristicProblem;

     protected ASelection(
        HeuristicProblem heuristicProblem)
    {
        m_heuristicProblem = heuristicProblem;
    }

     public abstract Individual DoSelection();
}


text:
namespace rw {

//
// AnimInterpolatorInfo
//

#define MAXINTERPINFO 10

static AnimInterpolatorInfo *interpInfoList[MAXINTERPINFO];

void
AnimInterpolatorInfo::registerInterp(AnimInterpolatorInfo *interpInfo)
{
	for(int32 i = 0; i < MAXINTERPINFO; i++)
		if(interpInfoList[i] == nil){
			interpInfoList[i] = interpInfo;
			return;
		}
	assert(0 && "no room for interpolatorInfo");
}

void
AnimInterpolatorInfo::unregisterInterp(AnimInterpolatorInfo *interpInfo)
{
	for(int32 i = 0; i < MAXINTERPINFO; i++)
		if(interpInfoList[i] == interpInfo){
			rwFree(interpInfoList[i]);
			interpInfoList[i] = nil;
			return;
		}
}

AnimInterpolatorInfo*
AnimInterpolatorInfo::find(int32 id)
{
	for(int32 i = 0; i < MAXINTERPINFO; i++){
		if(interpInfoList[i] && interpInfoList[i]->id == id)
			return interpInfoList[i];
	}
	return nil;
}

//
// Animation
//

Animation*
Animation::create(AnimInterpolatorInfo *interpInfo, int32 numFrames,
                  int32 flags, float duration)
{
	int32 sz = sizeof(Animation) +
	           numFrames*interpInfo->animKeyFrameSize +
	           interpInfo->customDataSize;
	uint8 *data = (uint8*)rwMalloc(sz, MEMDUR_EVENT | ID_ANIMANIMATION);
	if(data == nil){
		RWERROR((ERR_ALLOC, sz));
		return nil;
	}
	Animation *anim = (Animation*)data;
	data += sizeof(Animation);
	anim->interpInfo = interpInfo;
	anim->numFrames = numFrames;
	anim->flags = flags;
	anim->duration = duration;
	anim->keyframes = data;
	data += anim->numFrames*interpInfo->animKeyFrameSize;
	anim->customData = data;
	return anim;
}

void
Animation::destroy(void)
{
	rwFree(this);
}

int32
Animation::getNumNodes(void)
{
	int32 sz = this->interpInfo->animKeyFrameSize;
	KeyFrameHeader *first = (KeyFrameHeader*)this->keyframes;
	int32 n = 0;
	for(KeyFrameHeader *f = first; f->prev != first; f = f->next(sz))
		n++;
	return n;
}

Animation*
Animation::streamRead(Stream *stream)
{
	Animation *anim;
	if(stream->readI32() != 0x100)
		return nil;
	int32 typeID = stream->readI32();
	AnimInterpolatorInfo *interpInfo = AnimInterpolatorInfo::find(typeID);
	int32 numFrames = stream->readI32();
	int32 flags = stream->readI32();
	float duration = stream->readF32();
	anim = Animation::create(interpInfo, numFrames, flags, duration);
	interpInfo->streamRead(stream, anim);
	return anim;
}

Animation*
Animation::streamReadLegacy(Stream *stream)
{
	Animation *anim;
	AnimInterpolatorInfo *interpInfo = AnimInterpolatorInfo::find(1);
	int32 numFrames = stream->readI32();
	int32 flags = stream->readI32();
	float duration = stream->readF32();
	anim = Animation::create(interpInfo, numFrames, flags, duration);
	HAnimKeyFrame *frames = (HAnimKeyFrame*)anim->keyframes;
	for(int32 i = 0; i < anim->numFrames; i++){
		stream->read32(&frames[i].q, 4*4);
		frames[i].q = conj(frames[i].q);
		stream->read32(&frames[i].t, 3*4);
		frames[i].time = stream->readF32();
		int32 prev = stream->readI32()/0x24;
		frames[i].prev = &frames[prev];
	}
	return anim;
}

bool
Animation::streamWrite(Stream *stream)
{
	writeChunkHeader(stream, ID_ANIMANIMATION, this->streamGetSize());
	stream->writeI32(0x100);
	stream->writeI32(this->interpInfo->id);
	stream->writeI32(this->numFrames);
	stream->writeI32(this->flags);
	stream->writeF32(this->duration);
	this->interpInfo->streamWrite(stream, this);
	return true;
}

bool
Animation::streamWriteLegacy(Stream *stream)
{
	stream->writeI32(this->numFrames);
	stream->writeI32(this->flags);
	stream->writeF32(this->duration);
	assert(interpInfo->id == 1);
	HAnimKeyFrame *frames = (HAnimKeyFrame*)this->keyframes;
	for(int32 i = 0; i < this->numFrames; i++){
		frames[i].q = conj(frames[i].q);
		stream->write32(&frames[i].q, 4*4);
		frames[i].q = conj(frames[i].q);
		stream->write32(&frames[i].t, 3*4);
		stream->writeF32(frames[i].time);
		stream->writeI32((frames[i].prev - frames)*0x24);
	}
	return true;
}

uint32
Animation::streamGetSize(void)
{
	uint32 size = 4 + 4 + 4 + 4 + 4;
	size += this->interpInfo->streamGetSize(this);
	return size;
}

//
// AnimInterpolator
//

AnimInterpolator*
AnimInterpolator::create(int32 numNodes, int32 maxFrameSize)
{
	AnimInterpolator *interp;
	int32 sz;
	int32 realsz = maxFrameSize;

	// Add some space for pointers and padding, hopefully this will be
	// enough. Don't change maxFrameSize not to mess up streaming.
	if(sizeof(void*) > 4)
		realsz += 16;
	sz = sizeof(AnimInterpolator) + numNodes*realsz;
	interp = (AnimInterpolator*)rwMalloc(sz, MEMDUR_EVENT | ID_ANIMANIMATION);
	if(interp == nil){
		RWERROR((ERR_ALLOC, sz));
		return nil;
	}
	interp->currentAnim = nil;
	interp->currentTime = 0.0f;
	interp->nextFrame = nil;
	interp->maxInterpKeyFrameSize = maxFrameSize;
	interp->currentInterpKeyFrameSize = maxFrameSize;
	interp->currentAnimKeyFrameSize = -1;
	interp->numNodes = numNodes;;

	return interp;
}

void
AnimInterpolator::destroy(void)
{
	rwFree(this);
}

bool32
AnimInterpolator::setCurrentAnim(Animation *anim)
{
	int32 i;
	AnimInterpolatorInfo *interpInfo = anim->interpInfo;
	this->currentAnim = anim;
	this->currentTime = 0.0f;
	int32 maxkf = this->maxInterpKeyFrameSize;
	if(sizeof(void*) > 4)	// see above in create()
		maxkf += 16;
	if(interpInfo->interpKeyFrameSize > maxkf){
		RWERROR((ERR_GENERAL, "interpolation frame too big"));
		return 0;
	}
	this->currentInterpKeyFrameSize = interpInfo->interpKeyFrameSize;
	this->currentAnimKeyFrameSize = interpInfo->animKeyFrameSize;
	this->applyCB = interpInfo->applyCB;
	this->blendCB = interpInfo->blendCB;
	this->interpCB = interpInfo->interpCB;
	this->addCB = interpInfo->addCB;
	for(i = 0; i < numNodes; i++){
		InterpFrameHeader *intf;
		KeyFrameHeader *kf1, *kf2;
		intf = this->getInterpFrame(i);
		kf1 = this->getAnimFrame(i);
		kf2 = this->getAnimFrame(i+numNodes);
		intf->keyFrame1 = kf1;
		intf->keyFrame2 = kf2;
		// TODO: perhaps just implement all interpolator infos?
		if(this->interpCB)
			this->interpCB(intf, kf1, kf2, 0.0f, anim->customData);
	}
	this->nextFrame = this->getAnimFrame(numNodes*2);
	return 1;
}

void
AnimInterpolator::addTime(float32 t)
{
	int32 i;
	if(t <= 0.0f)
		return;
	this->currentTime += t;
	// reset animation
	if(this->currentTime > this->currentAnim->duration){
		this->setCurrentAnim(this->currentAnim);
		return;
	}
	KeyFrameHeader *last = this->getAnimFrame(this->currentAnim->numFrames);
	KeyFrameHeader *next = (KeyFrameHeader*)this->nextFrame;
	InterpFrameHeader *ifrm = nil;
	while(next < last && next->prev->time <= this->currentTime){
		// find next interpolation frame to expire
		for(i = 0; i < this->numNodes; i++){
			ifrm = this->getInterpFrame(i);
			if(ifrm->keyFrame2 == next->prev)
				break;
		}
		// advance interpolation frame
		ifrm->keyFrame1 = ifrm->keyFrame2;
		ifrm->keyFrame2 = next;
		// ... and next frame
		next = (KeyFrameHeader*)((uint8*)this->nextFrame +
		                         currentAnimKeyFrameSize);
		this->nextFrame = next;
	}
	for(i = 0; i < this->numNodes; i++){
		ifrm = this->getInterpFrame(i);
		this->interpCB(ifrm, ifrm->keyFrame1, ifrm->keyFrame2,
		               this->currentTime,
		               this->currentAnim->customData);
	}
}

}