text:
/* Entry points used

    cairo_arc
    cairo_clip
    cairo_close_path
    cairo_create
    cairo_destroy
    cairo_fill_preserve
    cairo_get_source
    cairo_get_target
    cairo_image_surface_create
    cairo_image_surface_create_for_data
    cairo_image_surface_get_data (1.2)
    cairo_image_surface_get_stride
    cairo_line_to
    cairo_move_to
    cairo_new_path
    cairo_paint
    cairo_pattern_set_extend
    cairo_pattern_set_filter
    cairo_rectangle
    cairo_rel_move_to
    cairo_reset_clip
    cairo_restore
    cairo_rotate
    cairo_save
    cairo_scale
    cairo_set_antialias
    cairo_set_dash
    cairo_set_fill_rule
    cairo_set_line_cap
    cairo_set_line_join
    cairo_set_line_width
    cairo_set_miter_limit
    cairo_set_operator
    cairo_set_source_rgb
    cairo_set_source_rgba
    cairo_set_source_surface
    cairo_status
    cairo_status_to_string
    cairo_stroke
    cairo_surface_destroy
    cairo_surface_status

    cairo_xlib_surface_create
    cairo_xlib_surface_set_size

    cairo_show_text
    cairo_text_extents

    cairo_ft_font_face_create_for_ft_face [OS X]

    g_object_unref  (glib)

    pango_cairo_create_layout (1.10)
    pango_cairo_show_layout (1.10)
    pango_font_description_free
    pango_font_description_new
    pango_font_description_set_family
    pango_font_description_set_size
    pango_font_description_set_style
    pango_font_description_set_weight
    pango_layout_get_line
    pango_layout_line_get_pixel_extents
    pango_layout_set_font_description
    pango_layout_set_text

*/

static void CairoColor(unsigned int col, pX11Desc xd)
{
    unsigned int alpha = R_ALPHA(col);
    double red, blue, green;

    red = R_RED(col)/255.0;
    green = R_GREEN(col)/255.0;
    blue = R_BLUE(col)/255.0;
    red = pow(red, RedGamma);
    green = pow(green, GreenGamma);
    blue = pow(blue, BlueGamma);

    /* This optimization should not be necessary, but alpha = 1 seems
       to cause image fallback in some backends */
    if (alpha == 255)
	cairo_set_source_rgb(xd->cc, red, green, blue);
    else
	cairo_set_source_rgba(xd->cc, red, green, blue, alpha/255.0);
}

static void CairoLineType(const pGEcontext gc, pX11Desc xd)
{
    cairo_t *cc = xd->cc;
    double lwd = gc->lwd;
    cairo_line_cap_t lcap = CAIRO_LINE_CAP_SQUARE;
    cairo_line_join_t ljoin = CAIRO_LINE_JOIN_ROUND;
    switch(gc->lend){
    case GE_ROUND_CAP: lcap = CAIRO_LINE_CAP_ROUND; break;
    case GE_BUTT_CAP: lcap = CAIRO_LINE_CAP_BUTT; break;
    case GE_SQUARE_CAP: lcap = CAIRO_LINE_CAP_SQUARE; break;
    }
    switch(gc->ljoin){
    case GE_ROUND_JOIN: ljoin = CAIRO_LINE_JOIN_ROUND; break;
    case GE_MITRE_JOIN: ljoin = CAIRO_LINE_JOIN_MITER; break;
    case GE_BEVEL_JOIN: ljoin = CAIRO_LINE_JOIN_BEVEL; break;
    }
    cairo_set_line_width(cc, (lwd > 0.01 ? lwd : 0.01) * xd->lwdscale);
    cairo_set_line_cap(cc, lcap);
    cairo_set_line_join(cc, ljoin);
    cairo_set_miter_limit(cc, gc->lmitre);

    if (gc->lty == 0 || gc->lty == -1 || gc->lty == NA_INTEGER)
	cairo_set_dash(cc, 0, 0, 0);
    else {
	double ls[16], lwd = (gc->lwd > 1) ? gc->lwd : 1;
	int l;
        /* Use unsigned int otherwise right shift of 'dt'
           may not terminate for loop */
        unsigned int dt = gc->lty;
	for (l = 0; dt != 0; dt >>= 4, l++)
	    ls[l] = (dt & 0xF) * lwd * xd->lwdscale;
	cairo_set_dash(cc, ls, l, 0);
    }
}

static void Cairo_Clip(double x0, double x1, double y0, double y1,
		       pDevDesc dd)
{
    pX11Desc xd = (pX11Desc) dd->deviceSpecific;

    if (x1 < x0) { double h = x1; x1 = x0; x0 = h; };
    if (y1 < y0) { double h = y1; y1 = y0; y0 = h; };

    cairo_reset_clip(xd->cc);
    cairo_new_path(xd->cc);
    /* Add 1 per X11_Clip */
    cairo_rectangle(xd->cc, x0, y0, x1 - x0 + 1, y1 - y0 + 1);
    cairo_clip(xd->cc);
}

static void Cairo_Rect(double x0, double y0, double x1, double y1,
		       const pGEcontext gc, pDevDesc dd)
{
    pX11Desc xd = (pX11Desc) dd->deviceSpecific;

    cairo_new_path(xd->cc);
    cairo_rectangle(xd->cc, x0, y0, x1 - x0, y1 - y0);

    if (R_ALPHA(gc->fill) > 0) {
	cairo_set_antialias(xd->cc, CAIRO_ANTIALIAS_NONE);
	CairoColor(gc->fill, xd);
	cairo_fill_preserve(xd->cc);
	cairo_set_antialias(xd->cc, xd->antialias);
    }

    if (R_ALPHA(gc->col) > 0 && gc->lty != -1) {
	CairoColor(gc->col, xd);
	CairoLineType(gc, xd);
	cairo_stroke(xd->cc);
    }
}

static void Cairo_Circle(double x, double y, double r,
			 const pGEcontext gc, pDevDesc dd)
{
    pX11Desc xd = (pX11Desc) dd->deviceSpecific;

    cairo_new_path(xd->cc);
    /* radius 0.5 seems to be visible */
    cairo_arc(xd->cc, x, y, (r > 0.5 ? r : 0.5), 0.0, 2 * M_PI);

    if (R_ALPHA(gc->fill) > 0) {
	cairo_set_antialias(xd->cc, CAIRO_ANTIALIAS_NONE);
	CairoColor(gc->fill, xd);
	cairo_fill_preserve(xd->cc);
	cairo_set_antialias(xd->cc, xd->antialias);
   }
    if (R_ALPHA(gc->col) > 0 && gc->lty != -1) {
	CairoColor(gc->col, xd);
	CairoLineType(gc, xd);
	cairo_stroke(xd->cc);
    }
}

static void Cairo_Line(double x1, double y1, double x2, double y2,
		       const pGEcontext gc, pDevDesc dd)
{
    pX11Desc xd = (pX11Desc) dd->deviceSpecific;

    if (R_ALPHA(gc->col) > 0) {
	CairoColor(gc->col, xd);
	CairoLineType(gc, xd);
	cairo_new_path(xd->cc);
	cairo_move_to(xd->cc, x1, y1);
	cairo_line_to(xd->cc, x2, y2);
	cairo_stroke(xd->cc);
    }
}

static void Cairo_Polyline(int n, double *x, double *y,
			   const pGEcontext gc, pDevDesc dd)
{
    int i;
    pX11Desc xd = (pX11Desc) dd->deviceSpecific;

    if (R_ALPHA(gc->col) > 0) {
	CairoColor(gc->col, xd);
	CairoLineType(gc, xd);
	cairo_new_path(xd->cc);
	cairo_move_to(xd->cc, x[0], y[0]);
	for(i = 0; i < n; i++) cairo_line_to(xd->cc, x[i], y[i]);
	cairo_stroke(xd->cc);
    }
}

static void Cairo_Polygon(int n, double *x, double *y,
			  const pGEcontext gc, pDevDesc dd)
{
    int i;
    pX11Desc xd = (pX11Desc) dd->deviceSpecific;

    cairo_new_path(xd->cc);
    cairo_move_to(xd->cc, x[0], y[0]);
    for(i = 0; i < n; i++) cairo_line_to(xd->cc, x[i], y[i]);
    cairo_close_path(xd->cc);

    if (R_ALPHA(gc->fill) > 0) {
	cairo_set_antialias(xd->cc, CAIRO_ANTIALIAS_NONE);
	CairoColor(gc->fill, xd);
	cairo_fill_preserve(xd->cc);
	cairo_set_antialias(xd->cc, xd->antialias);
    }
    if (R_ALPHA(gc->col) > 0 && gc->lty != -1) {
	CairoColor(gc->col, xd);
	CairoLineType(gc, xd);
	cairo_stroke(xd->cc);
    }
}

static void Cairo_Path(double *x, double *y,
                       int npoly, int *nper,
                       Rboolean winding,
                       const pGEcontext gc, pDevDesc dd)
{
    int i, j, n;
    pX11Desc xd = (pX11Desc) dd->deviceSpecific;

    cairo_new_path(xd->cc);
    n = 0;
    for (i=0; i < npoly; i++) {
        cairo_move_to(xd->cc, x[n], y[n]);
        n++;
        for(j=1; j < nper[i]; j++) {
            cairo_line_to(xd->cc, x[n], y[n]);
            n++;
        }
        cairo_close_path(xd->cc);
    }

    if (R_ALPHA(gc->fill) > 0) {
	cairo_set_antialias(xd->cc, CAIRO_ANTIALIAS_NONE);
        if (winding)
            cairo_set_fill_rule(xd->cc, CAIRO_FILL_RULE_WINDING);
        else
            cairo_set_fill_rule(xd->cc, CAIRO_FILL_RULE_EVEN_ODD);
	CairoColor(gc->fill, xd);
	cairo_fill_preserve(xd->cc);
	cairo_set_antialias(xd->cc, xd->antialias);
    }
    if (R_ALPHA(gc->col) > 0 && gc->lty != -1) {
	CairoColor(gc->col, xd);
	CairoLineType(gc, xd);
	cairo_stroke(xd->cc);
    }
}

static cairo_surface_t* createImageSurface(unsigned int *raster, int w, int h)
{
    int i;
    cairo_surface_t *image;
    unsigned char *imageData;

    imageData = (unsigned char *) R_alloc(4*w*h, sizeof(unsigned char));
    /* The R ABGR needs to be converted to a Cairo ARGB
     * AND values need to by premultiplied by alpha
     */
    for (i=0; i<w*h; i++) {
        int alpha = R_ALPHA(raster[i]);
        imageData[i*4 + 3] = (unsigned char) alpha;
        if (alpha < 255) {
            imageData[i*4 + 2] = (unsigned char)(R_RED(raster[i]) * alpha / 255);
	    imageData[i*4 + 1] = (unsigned char)(R_GREEN(raster[i]) * alpha / 255);
	    imageData[i*4 + 0] = (unsigned char)(R_BLUE(raster[i]) * alpha / 255);
        } else {
            imageData[i*4 + 2] = R_RED(raster[i]);
            imageData[i*4 + 1] = R_GREEN(raster[i]);
            imageData[i*4 + 0] = R_BLUE(raster[i]);
        }
    }
    image = cairo_image_surface_create_for_data(imageData,
                                                CAIRO_FORMAT_ARGB32,
                                                w, h,
                                                4*w);
    return(image);
}

static void Cairo_Raster(unsigned int *raster, int w, int h,
                         double x, double y,
                         double width, double height,
                         double rot,
                         Rboolean interpolate,
                         const pGEcontext gc, pDevDesc dd)
{
    int imageWidth, imageHeight;
    const void *vmax = vmaxget();
    cairo_surface_t *image;
    pX11Desc xd = (pX11Desc) dd->deviceSpecific;

    cairo_save(xd->cc);

    /* If we are going to use the graphics engine for interpolation
     * the image used for the Cairo surface is going to be a
     * different size
     */
    if (interpolate && CAIRO_VERSION_MAJOR < 2 && CAIRO_VERSION_MINOR < 6) {
        imageWidth = (int) (width + .5);
        imageHeight = abs((int) (height + .5));
    } else {
        imageWidth = w;
        imageHeight = h;
    }

    cairo_translate(xd->cc, x, y);
    cairo_rotate(xd->cc, -rot*M_PI/180);
    cairo_scale(xd->cc, width/imageWidth, height/imageHeight);
    /* Flip vertical first */
    cairo_translate(xd->cc, 0, imageHeight/2.0);
    cairo_scale(xd->cc, 1, -1);
    cairo_translate(xd->cc, 0, -imageHeight/2.0);

    if (interpolate) {
        if (CAIRO_VERSION_MAJOR < 2 && CAIRO_VERSION_MINOR < 6) {
            /* CAIRO_EXTEND_PAD not supported for image sources
             * so use graphics engine for interpolation
             */
            unsigned int *rasterImage;
            rasterImage = (unsigned int *) R_alloc(imageWidth * imageHeight,
                                                   sizeof(unsigned int));
            R_GE_rasterInterpolate(raster, w, h,
                                   rasterImage, imageWidth, imageHeight);
            image = createImageSurface(rasterImage, imageWidth, imageHeight);
            cairo_set_source_surface(xd->cc, image, 0, 0);
        } else {
            image = createImageSurface(raster, w, h);
            cairo_set_source_surface(xd->cc, image, 0, 0);
            cairo_pattern_set_filter(cairo_get_source(xd->cc),
                                     CAIRO_FILTER_BILINEAR);
            cairo_pattern_set_extend(cairo_get_source(xd->cc),
                                     CAIRO_EXTEND_PAD);
        }
    } else {
        image = createImageSurface(raster, w, h);
        cairo_set_source_surface(xd->cc, image, 0, 0);
        cairo_pattern_set_filter(cairo_get_source(xd->cc),
                                 CAIRO_FILTER_NEAREST);
    }

    cairo_new_path(xd->cc);
    cairo_rectangle(xd->cc, 0, 0, imageWidth, imageHeight);
    cairo_clip(xd->cc);
    cairo_paint(xd->cc);

    cairo_restore(xd->cc);
    cairo_surface_destroy(image);

    vmaxset(vmax);
}

#ifndef NO_X11
static SEXP Cairo_Cap(pDevDesc dd)
{
    int i, width, height, size;
    pX11Desc xd = (pX11Desc) dd->deviceSpecific;
    cairo_surface_t* screen;
    cairo_format_t format;
    unsigned int *screenData;
    SEXP dim, raster = R_NilValue;
    unsigned int *rint;

    screen = cairo_surface_reference(cairo_get_target(xd->cc));
    width = cairo_image_surface_get_width(screen);
    height = cairo_image_surface_get_height(screen);
    screenData = (unsigned int*) cairo_image_surface_get_data(screen);

    /* The type of image surface will depend on what sort
     * of X11 color model has been used */
    format = cairo_image_surface_get_format(screen);
    /* For now, if format is not RGB24 just bail out */
    if (format != CAIRO_FORMAT_RGB24) {
	cairo_surface_destroy(screen);
        return raster;
    }

    size = width*height;

    /* FIXME: the screen surface reference will leak if allocVector() fails */
    PROTECT(raster = allocVector(INTSXP, size));

    /* Copy each byte of screen to an R matrix.
     * The Cairo RGB24 needs to be converted to an R ABGR32.
     * Cairo uses native endiannes (A=msb,R,G,B=lsb) so use int* instead of char* */
    rint = (unsigned int *) INTEGER(raster);
    for (i = 0; i < size; i++)
        rint[i] = R_RGB((screenData[i] >> 16) & 255, (screenData[i] >> 8) & 255, screenData[i] & 255);

    /* Release MY reference to the screen surface (do it here in case anything fails below) */
    cairo_surface_destroy(screen);

    PROTECT(dim = allocVector(INTSXP, 2));
    INTEGER(dim)[0] = height;
    INTEGER(dim)[1] = width;
    setAttrib(raster, R_DimSymbol, dim);

    UNPROTECT(2);
    return raster;
}
#endif

#ifdef HAVE_PANGOCAIRO
/* ------------- pangocairo section --------------- */

static PangoFontDescription
*PG_getFont(const pGEcontext gc, double fs, const char *family)
{
    PangoFontDescription *fontdesc;
    gint face = gc->fontface;
    double size = gc->cex * gc->ps * fs, ssize = PANGO_SCALE * size;
#ifdef Win32
    const char *times = "Times New Roman", *hv = "Arial";
#else
    const char *times = "times", *hv = "Helvetica";
#endif
    if (face < 1 || face > 5) face = 1;

    fontdesc = pango_font_description_new();
    if (face == 5)
	pango_font_description_set_family(fontdesc, "symbol");
    else {
	const char *fm = gc->fontfamily;
	if (!fm[0]) fm = family;
	if (streql(fm, "mono")) fm = "courier";
	else if (streql(fm, "serif")) fm = times;
	else if (streql(fm, "sans")) fm = hv;
	pango_font_description_set_family(fontdesc, fm);
	if (face == 2 || face == 4)
	    pango_font_description_set_weight(fontdesc, PANGO_WEIGHT_BOLD);
	if (face == 3 || face == 4)
	    pango_font_description_set_style(fontdesc, PANGO_STYLE_OBLIQUE);
    }
    /* seems a ssize < 1 gums up pango, PR#14369 */
    if (ssize < 1) ssize = 1.0;
    pango_font_description_set_size(fontdesc, (gint) ssize);

    return fontdesc;
}

static PangoLayout
*PG_layout(PangoFontDescription *desc, cairo_t *cc, const char *str)
{
    PangoLayout *layout;

    layout = pango_cairo_create_layout(cc);
    pango_layout_set_font_description(layout, desc);
    pango_layout_set_text(layout, str, -1);
    return layout;
}

static void
PG_text_extents(cairo_t *cc, PangoLayout *layout,
		gint *lbearing, gint *rbearing,
		gint *width, gint *ascent, gint *descent, int ink)
{
    PangoRectangle rect, lrect;

    pango_layout_line_get_pixel_extents(pango_layout_get_line(layout, 0),
					&rect, &lrect);

    if (width) *width = lrect.width;
    if (ink) {
	if (ascent) *ascent = PANGO_ASCENT(rect);
	if (descent) *descent = PANGO_DESCENT(rect);
	if (lbearing) *lbearing = PANGO_LBEARING(rect);
	if (rbearing) *rbearing = PANGO_RBEARING(rect);
    } else {
	if (ascent) *ascent = PANGO_ASCENT(lrect);
	if (descent) *descent = PANGO_DESCENT(lrect);
	if (lbearing) *lbearing = PANGO_LBEARING(lrect);
	if (rbearing) *rbearing = PANGO_RBEARING(lrect);
    }
}

static void
PangoCairo_MetricInfo(int c, const pGEcontext gc,
		      double* ascent, double* descent,
		      double* width, pDevDesc dd)
{
    pX11Desc xd = (pX11Desc) dd->deviceSpecific;
    char str[16];
    int Unicode = mbcslocale;
    PangoFontDescription *desc =
	PG_getFont(gc, xd->fontscale, xd->basefontfamily);
    PangoLayout *layout;
    gint iascent, idescent, iwidth;

    if (c == 0) c = 77;
    if (c < 0) {c = -c; Unicode = 1;}

    if (Unicode) {
	Rf_ucstoutf8(str, (unsigned int) c);
    } else {
	/* Here we assume that c < 256 */
	str[0] = (char) c; str[1] = (char) 0;
    }
    layout = PG_layout(desc, xd->cc, str);
    PG_text_extents(xd->cc, layout, NULL, NULL, &iwidth,
		    &iascent, &idescent, 1);
    g_object_unref(layout);
    pango_font_description_free(desc);
    *ascent = iascent;
    *descent = idescent;
    *width = iwidth;
#if 0
    printf("c = %d, '%s', face %d %f %f %f\n",
	   c, str, gc->fontface, *width, *ascent, *descent);
#endif
}

static double
PangoCairo_StrWidth(const char *str, const pGEcontext gc, pDevDesc dd)
{
    pX11Desc xd = (pX11Desc) dd->deviceSpecific;
    gint width;
    PangoFontDescription *desc =
	PG_getFont(gc, xd->fontscale, xd->basefontfamily);
    PangoLayout *layout = PG_layout(desc, xd->cc, str);

    PG_text_extents(xd->cc, layout, NULL, NULL, &width, NULL, NULL, 0);
    g_object_unref(layout);
    pango_font_description_free(desc);
    return (double) width;
}

static void
PangoCairo_Text(double x, double y,
		const char *str, double rot, double hadj,
		const pGEcontext gc, pDevDesc dd)
{
    if (R_ALPHA(gc->col) > 0) {
	pX11Desc xd = (pX11Desc) dd->deviceSpecific;
	gint ascent, lbearing, width;
	PangoLayout *layout;
	PangoFontDescription *desc =
	    PG_getFont(gc, xd->fontscale, xd->basefontfamily);
	cairo_save(xd->cc);
	layout = PG_layout(desc, xd->cc, str);
	PG_text_extents(xd->cc, layout, &lbearing, NULL, &width,
			&ascent, NULL, 0);
	cairo_move_to(xd->cc, x, y);
	if (rot != 0.0) cairo_rotate(xd->cc, -rot/180.*M_PI);
	/* pango has a coord system at top left */
	cairo_rel_move_to(xd->cc, -lbearing - width*hadj, -ascent);
	CairoColor(gc->col, xd);
	pango_cairo_show_layout(xd->cc, layout);
	cairo_restore(xd->cc);
	g_object_unref(layout);
	pango_font_description_free(desc);
    }
}

#else
/* ------------- cairo-ft section --------------- */

/* This uses what cairo refers to as its 'toy' interface:
   http://cairographics.org/manual/cairo-text.html

   No diagnostics that glyphs are present, no kerning.
 */

#ifdef __APPLE__
# define USE_FC 1
#endif

#if CAIRO_HAS_FT_FONT && USE_FC

/* FT implies FC in Cairo */
#include <cairo-ft.h>

/* cairo font cache - to prevent unnecessary font look ups */
typedef struct Rc_font_cache_s {
    const char *family;
    int face;
    cairo_font_face_t *font;
    struct Rc_font_cache_s *next;
} Rc_font_cache_t;

static Rc_font_cache_t *cache, *cache_tail;

static cairo_font_face_t *Rc_findFont(const char *family, int face)
{
    Rc_font_cache_t *here = cache;
    while (here) {
	if (here->face == face && streql(here->family, family))
	    return here->font;
	here = here->next;
    }
    return NULL;
}

static void Rc_addFont(const char *family, int face, cairo_font_face_t* font)
{
    Rc_font_cache_t *fc = (Rc_font_cache_t*) malloc(sizeof(Rc_font_cache_t));
    if (!fc) return;
    fc->family = strdup(family);
    fc->face = face;
    fc->font = font;
    fc->next = NULL;
    if (cache)
	cache_tail = cache_tail->next = fc;
    else
	cache = cache_tail = fc;
}

/* FC patterns to append to font family names */
static const char *face_styles[4] = {
    ":style=Regular",
    ":style=Bold",
    ":style=Italic",
    ":style=Bold Italic,BoldItalic"
};

static int fc_loaded;
static FT_Library ft_library;

/* use FC to find a font, load it in FT and return the Cairo FT font face */
static cairo_font_face_t *FC_getFont(const char *family, int style)
{
    FcFontSet *fs;
    FcPattern *pat, *match;
    FcResult  result;
    FcChar8   *file;
    char      fcname[250]; /* 200 for family + 50 for style */

    /* find candidate fonts via FontConfig */
    if (!fc_loaded) {
	if (!FcInit()) return NULL;
	fc_loaded = 1;
    }
    style &= 3;
    strcpy(fcname, family);
    strcat(fcname, face_styles[style]);
    pat = FcNameParse((FcChar8 *)fcname);
    if (!pat) return NULL;
    FcConfigSubstitute (0, pat, FcMatchPattern);
    FcDefaultSubstitute (pat);
    fs = FcFontSetCreate ();
    match = FcFontMatch (0, pat, &result);
    FcPatternDestroy (pat);
    if (!match) {
	FcFontSetDestroy (fs);
	return NULL;
    }
    FcFontSetAdd (fs, match);

    /* then try to load the font into FT */
    if (fs) {
	int j = 0, index = 0;
	while (j < fs->nfont) {
	    /* find the font file + face index and use it with FreeType */
	    if (FcPatternGetString (fs->fonts[j], FC_FILE, 0, &file)
		== FcResultMatch &&
		FcPatternGetInteger(fs->fonts[j], FC_INDEX, 0, &index)
		== FcResultMatch) {
		FT_Face face;
		if (!ft_library && FT_Init_FreeType(&ft_library)) {
		    FcFontSetDestroy (fs);
		    return NULL;
		}
		/* some FreeType versions have broken index support,
		   fall back to index 0 */
		if (!FT_New_Face(ft_library,
				 (const char *) file, index, &face) ||
		    (index && !FT_New_Face(ft_library,
					   (const char *) file, 0, &face))) {
		    FcFontSetDestroy (fs);

#ifdef __APPLE__
		    /* FreeType is broken on OS X in that face index
		       is often wrong (unfortunately even for Helvetica!)
		       - we try to find the best match through enumeration.
		       And italic and bold are swapped */
		    if (style == 2) style = 1; else if (style == 1) style = 2;
		    if (face->num_faces > 1 &&
			(face->style_flags & 3) != style) {
			FT_Face alt_face;
			int i = 0;
			while (i < face->num_faces)
			    if (!FT_New_Face(ft_library,
					     (const char *) file,
					     i++, &alt_face)) {
				if ((alt_face->style_flags & 3) == style) {
				    FT_Done_Face(face);
				    face = alt_face;
				    break;
				} else FT_Done_Face(alt_face);
			    }
		    }
#endif

		    return cairo_ft_font_face_create_for_ft_face(face, FT_LOAD_DEFAULT);
		}
	    }
	    j++;
	}
	FcFontSetDestroy (fs);
    }
    return NULL;
}

static void FT_getFont(pGEcontext gc, pDevDesc dd, double fs)
{
    pX11Desc xd = (pX11Desc) dd->deviceSpecific;
    int face = gc->fontface;
    double size = gc->cex * gc->ps *fs;
    cairo_font_face_t *cairo_face = NULL;
    const char *family;
#ifdef Win32
    char *times = "Times New Roman", *hv = "Arial";
#else
    char *times = "times", *hv = "Helvetica";
#endif

    if (face < 1 || face > 5) face = 1;
    family = gc->fontfamily;
    if (face == 5) {
#ifdef Win32
	if (!*family) family = "Standard Symbols L";
#else
	if (!*family) family = "Symbol";
#endif
    } else {
	if (!*family) family = xd->basefontfamily;
	if (streql(family, "sans")) family = hv;
	else if (streql(family, "serif")) family = times;
	else if (streql(family, "mono")) family = "Courier";
    }
    /* check the cache first */
    cairo_face = Rc_findFont(family, face);
    if (!cairo_face) {
	cairo_face = FC_getFont(family, face - 1);
	if (!cairo_face) return; /* No message? */
	Rc_addFont(family, face, cairo_face);
    }
    cairo_set_font_face (xd->cc, cairo_face);
    /* FIXME: this should really use cairo_set_font_matrix
       if pixels are non-square on a screen device. */
    cairo_set_font_size (xd->cc, size);
}

#else

static void FT_getFont(pGEcontext gc, pDevDesc dd, double fs)
{
    pX11Desc xd = (pX11Desc) dd->deviceSpecific;
    int face = gc->fontface;
    double size = gc->cex * gc->ps *fs;
    char *family;
    int slant = CAIRO_FONT_SLANT_NORMAL, wt = CAIRO_FONT_WEIGHT_NORMAL;
#ifdef Win32
    char *times = "Times New Roman", *hv = "Arial";
#else
    char *times = "times", *hv = "Helvetica";
#endif

    if (face < 1 || face > 5) face = 1;
    if (face == 5) family = "Symbol";
    if (face == 2 || face == 4) wt = CAIRO_FONT_WEIGHT_BOLD;
    if (face == 3 || face == 4) slant = CAIRO_FONT_SLANT_ITALIC;
    if (face != 5) {
	/* This is a 'toy', remember?
	   The manual recommnends the CSS2 names "serif", "sans-serif",
	   "monospace" */
	char *fm = gc->fontfamily;
	if (!fm[0]) fm = xd->basefontfamily;
	if (streql(fm, "mono")) family = "courier";
	else if (streql(fm, "serif")) family = times;
	else if (streql(fm, "sans")) family = hv;
	else if (fm[0]) family = fm;
    }

    cairo_select_font_face (xd->cc, family, slant, wt);
    /* FIXME: this should really use cairo_set_font_matrix
       if pixels are non-square on a screen device. */
    cairo_set_font_size (xd->cc, size);
}
#endif

static void Cairo_MetricInfo(int c, pGEcontext gc,
			     double* ascent, double* descent,
			     double* width, pDevDesc dd)
{
    pX11Desc xd = (pX11Desc) dd->deviceSpecific;
    cairo_text_extents_t exts;
    char str[16];
    int Unicode = mbcslocale;

    if (c == 0) c = 77;
    if (c < 0) {c = -c; Unicode = 1;}

    if (Unicode) {
	Rf_ucstoutf8(str, (unsigned int) c);
    } else {
	/* Here, we assume that c < 256 */
	str[0] = (char)c; str[1] = 0;
    }

    FT_getFont(gc, dd, xd->fontscale);
    cairo_text_extents(xd->cc, str, &exts);
    *ascent  = -exts.y_bearing;
    *descent = exts.height + exts.y_bearing;
    *width = exts.x_advance;
}

static double Cairo_StrWidth(const char *str, pGEcontext gc, pDevDesc dd)
{
    pX11Desc xd = (pX11Desc) dd->deviceSpecific;
    cairo_text_extents_t exts;

    if (!utf8Valid(str)) error("invalid string in Cairo_StrWidth");
    FT_getFont(gc, dd, xd->fontscale);
    cairo_text_extents(xd->cc, str, &exts);
    return exts.x_advance;
}

static void Cairo_Text(double x, double y,
		       const char *str, double rot, double hadj,
		       pGEcontext gc, pDevDesc dd)
{
    if (!utf8Valid(str)) error("invalid string in Cairo_Text");
    if (R_ALPHA(gc->col) > 0) {
	pX11Desc xd = (pX11Desc) dd->deviceSpecific;
	cairo_save(xd->cc);
	FT_getFont(gc, dd, xd->fontscale);
	cairo_move_to(xd->cc, x, y);
	if (hadj != 0.0 || rot != 0.0) {
	    cairo_text_extents_t te;
	    cairo_text_extents(xd->cc, str, &te);
	    if (rot != 0.0) cairo_rotate(xd->cc, -rot/180.*M_PI);
	    if (hadj != 0.0)
		cairo_rel_move_to(xd->cc, -te.x_advance * hadj, 0);
	}
	CairoColor(gc->col, xd);
	cairo_show_text(xd->cc, str);
	cairo_restore(xd->cc);
    }
}
#endif


text:
package config

import (
	"reflect"
	"testing"

	"github.com/phil-mansfield/rogue/error"
)

func TestParseLine(t *testing.T) {
	tests := []struct {
		in           string
		field, value string
		isValid      bool
	}{
		{"A=B", "A", "B", true},
		{" A = B ", "A", "B", true},
		{"A =	B = C", "A", "B = C", true},
		{"", "", "", true},
		{" 		 ", "", "", true},
		{"What I cannot create, I do not understand.", "", "", false},
	}

	for i, test := range tests {
		field, value, desc := parseLine(test.in)
		if desc != "" && test.isValid {
			t.Errorf("Test %d: Expected valid output for parseLine('%s'), "+
				"but got desc = '%s'", i, test.in, desc)
		} else if desc == "" && !test.isValid {
			t.Errorf("Test %d: Expected invalid output for parseLine('%s'), "+
				"but got field = '%s' and value = '%s'.",
				i, test.in, field, value)
		} else if field != test.field || value != test.value {
			t.Errorf("Test %d: Expected field = '%s' and value = '%s' for "+
				"parseLine('%s'), but got field = '%s' and value = '%s'.",
				i, test.field, test.value, test.in, field, value)
		}
	}
}

// This is not really the best, since it relies on the test being run in the
// directory where it's source code is.

func TestReadFile(t *testing.T) {
	tests := []struct {
		in      string
		lines   []string
		isValid bool
		code    error.ErrorCode
	}{
		{"test_config_files/no_assignment.txt",
			[]string{"What I cannot create, I do not understand.", ""}, true,0},
		{"test_config_files/does_not_exist.txt",
			[]string{}, false, error.MissingFile},
		{"test_config_files/double_assignment.txt",
			[]string{"A = B", "", "C = D", ""}, true, 0},

	}

	for i, test := range tests {
		lines, err := readFile(test.in)

		if !test.isValid && err == nil {
			t.Errorf("Test %d: Expected %s for config file '%s', but got " +
				"lines %v.", i, test.code.String(), test.in, lines)
		} else if !test.isValid && (test.code != err.Code) {
			t.Errorf("Test %d: Expected %s for config file '%s', but got " +
				"%s. Verbose error is:\n%s", i, test.code.String(),
				test.in, err.Code, err.VerboseError())
		} else if test.isValid && err != nil {
			t.Errorf("Test %d: Expected lines %v for config file '%s', but " +
				"got %s. Verbose error is:\n%s",
				i, test.lines, test.in, err.Code.String(), err.VerboseError())
		} else if test.isValid && !stringSliceEqual(test.lines, lines) {
			t.Errorf("Test %d: Expected lines to be %v for config file " +
				"'%s', but got %v.", i, test.lines, test.in, lines)
		}
	}
}

type setFieldTestStruct struct {
	Ned, Ed string
}

func TestSetField(t *testing.T) {
	tests := [] struct {
		inField, inValue string
		isValid bool
	} {
		{"Ned", "Meow", true},
		{"Rabina", "Meow", false},
	}

	testStruct :=  &setFieldTestStruct{"meow", "meow"}
	val := reflect.Indirect(reflect.ValueOf(testStruct))

	for i, test := range tests {
		if test.isValid != setField(val, test.inField, test.inValue) {
			t.Errorf("Test %d: Expected testStruct.%s = '%s' to be a %s " +
				" operation.", i, test.inField, test.inValue,
				boolToValid(test.isValid))
		} else if test.isValid {
			fieldStr := val.FieldByName(test.inField).String()
			if fieldStr != test.inValue {
				t.Errorf("Test %d: Expected struct.%s to be set to '%s', " +
					"but found '%s'", i , test.inField, test.inValue, fieldStr)
			}
		}
	}
}

func TestParse(t *testing.T) {
	var parseTests = [] struct {
		filePath string
		favoriteQuote string
		favoriteNumber int
		isValid bool
		code error.ErrorCode
	} {
		{"test_config_files/valid_config.txt",
		"Do not destroy what you cannot create.", 3, true, 0},
		{"test_config_files/invalid_var_config.txt",
		"What I cannot create, I do not understand.", 1729,
		false, error.Configuration},
		{"test_config_files/does_not_exist.txt",
		"What I cannot create, I do not understand.", 1729,
		false, error.MissingFile},
		{"test_config_files/partial_config.txt",
		"Do not destroy what you cannot create.", 1729, true, 0},
	}

	for i, test := range parseTests {
		info, err := Parse(test.filePath)

		if test.isValid && err != nil {
			t.Errorf("Test %d: Expected '%s' to be valid, but gave %s. " +
				"Verbose error:\n%s", i, test.filePath, err.Code.String(),
				err.VerboseError())
		} else if !test.isValid && err == nil {
			t.Errorf("Test %d: Expected '%s' to give %s, but gave the struct" +
				"%v instead.", i, test.filePath, test.code.String(), info)
		} else if info.FavoriteQuote != test.favoriteQuote {
			t.Errorf("Test %d: Expected '%s' to give FavoriteQuote = '%s'," +
				"but got '%s' instead.", i, test.filePath, test.favoriteQuote,
				info.FavoriteQuote)
		} else if info.FavoriteNumber != test.favoriteNumber {
			t.Errorf("Test %d: Expected '%s' to give FavoriteNumber = '%s'," +
				"but got '%s' instead.", i, test.filePath, test.favoriteNumber,
				info.FavoriteNumber)
		}
	}
}

func boolToValid(b bool) string {
	if b {
		return "valid"
	}
	return "invalid"
}

func stringSliceEqual(s1, s2 []string) bool {
	if len(s1) != len(s2) {
		return false
	}

	for i := range s1 {
		if s1[i] != s2[i] {
			return false
		}
	}

	return true
}

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE HTML>
<html>
    <head>
        <meta charset="UTF-8">
        <title>Tezos Explorer</title>
        <link rel="stylesheet" href="https://yui-s.yahooapis.com/pure/0.6.0/pure-min.css">
        <link rel="stylesheet" href="tezos.css">
    </head>
    <body>
        <script src="elm.js"></script>
        <script src="tezos.js"></script>
    </body>
</html>


text:
// Licensed to the .NET Foundation under one or more agreements.
// See the LICENSE file in the project root for more information.

//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

using Xunit;
using System.IO;
using System.Xml;
using System.Data.SqlTypes;
using System.Globalization;

namespace System.Data.Tests.SqlTypes
{
    public class SqlBytesTest
    {
        // Test constructor
        [Fact]
        public void SqlBytesItem()
        {
            SqlBytes bytes = new SqlBytes();
            try
            {
                Assert.Equal(bytes[0], 0);
                Assert.False(true);
            }
            catch (Exception ex)
            {
                Assert.Equal(typeof(SqlNullValueException), ex.GetType());
            }
            byte[] b = null;
            bytes = new SqlBytes(b);
            try
            {
                Assert.Equal(bytes[0], 0);
                Assert.False(true);
            }
            catch (Exception ex)
            {
                Assert.Equal(typeof(SqlNullValueException), ex.GetType());
            }
            b = new byte[10];
            bytes = new SqlBytes(b);
            Assert.Equal(bytes[0], 0);
            try
            {
                Assert.Equal(bytes[-1], 0);
                Assert.False(true);
            }
            catch (Exception ex)
            {
                Assert.Equal(typeof(ArgumentOutOfRangeException), ex.GetType());
            }
            try
            {
                Assert.Equal(bytes[10], 0);
                Assert.False(true);
            }
            catch (Exception ex)
            {
                Assert.Equal(typeof(ArgumentOutOfRangeException), ex.GetType());
            }
        }
        [Fact]
        public void SqlBytesLength()
        {
            byte[] b = null;
            SqlBytes bytes = new SqlBytes();
            try
            {
                Assert.Equal(bytes.Length, 0);
                Assert.False(true);
            }
            catch (Exception ex)
            {
                Assert.Equal(typeof(SqlNullValueException), ex.GetType());
            }
            bytes = new SqlBytes(b);
            try
            {
                Assert.Equal(bytes.Length, 0);
                Assert.False(true);
            }
            catch (Exception ex)
            {
                Assert.Equal(typeof(SqlNullValueException), ex.GetType());
            }
            b = new byte[10];
            bytes = new SqlBytes(b);
            Assert.Equal(bytes.Length, 10);
        }
        [Fact]
        public void SqlBytesMaxLength()
        {
            byte[] b = null;
            SqlBytes bytes = new SqlBytes();
            Assert.Equal(bytes.MaxLength, -1);
            bytes = new SqlBytes(b);
            Assert.Equal(bytes.MaxLength, -1);
            b = new byte[10];
            bytes = new SqlBytes(b);
            Assert.Equal(bytes.MaxLength, 10);
        }
        [Fact]
        public void SqlBytesNull()
        {
            byte[] b = null;
            SqlBytes bytes = SqlBytes.Null;
            Assert.Equal(bytes.IsNull, true);
        }
        [Fact]
        public void SqlBytesStorage()
        {
            byte[] b = null;
            SqlBytes bytes = new SqlBytes();
            try
            {
                Assert.Equal(bytes.Storage, StorageState.Buffer);
                Assert.False(true);
            }
            catch (Exception ex)
            {
                Assert.Equal(typeof(SqlNullValueException), ex.GetType());
            }
            bytes = new SqlBytes(b);
            try
            {
                Assert.Equal(bytes.Storage, StorageState.Buffer);
                Assert.False(true);
            }
            catch (Exception ex)
            {
                Assert.Equal(typeof(SqlNullValueException), ex.GetType());
            }
            b = new byte[10];
            bytes = new SqlBytes(b);
            Assert.Equal(bytes.Storage, StorageState.Buffer);
            FileStream fs = null;
            bytes = new SqlBytes(fs);
            try
            {
                Assert.Equal(bytes.Storage, StorageState.Buffer);
                Assert.False(true);
            }
            catch (Exception ex)
            {
                Assert.Equal(typeof(SqlNullValueException), ex.GetType());
            }
        }
        [Fact]
        public void SqlBytesValue()
        {
            byte[] b1 = new byte[10];
            SqlBytes bytes = new SqlBytes(b1);
            byte[] b2 = bytes.Value;
            Assert.Equal(b1[0], b2[0]);
            b2[0] = 10;
            Assert.Equal(b1[0], 0);
            Assert.Equal(b2[0], 10);
        }
        [Fact]
        public void SqlBytesSetLength()
        {
            byte[] b1 = new byte[10];
            SqlBytes bytes = new SqlBytes();
            try
            {
                bytes.SetLength(20);
                Assert.False(true);
            }
            catch (Exception ex)
            {
                Assert.Equal(typeof(SqlTypeException), ex.GetType());
            }
            bytes = new SqlBytes(b1);
            Assert.Equal(bytes.Length, 10);
            try
            {
                bytes.SetLength(-1);
                Assert.False(true);
            }
            catch (Exception ex)
            {
                Assert.Equal(typeof(ArgumentOutOfRangeException), ex.GetType());
            }
            try
            {
                bytes.SetLength(11);
                Assert.False(true);
            }
            catch (Exception ex)
            {
                Assert.Equal(typeof(ArgumentOutOfRangeException), ex.GetType());
            }
            bytes.SetLength(2);
            Assert.Equal(bytes.Length, 2);
        }
        [Fact]
        public void SqlBytesSetNull()
        {
            byte[] b1 = new byte[10];
            SqlBytes bytes = new SqlBytes(b1);
            Assert.Equal(bytes.Length, 10);
            bytes.SetNull();
            try
            {
                Assert.Equal(bytes.Length, 10);
                Assert.False(true);
            }
            catch (Exception ex)
            {
                Assert.Equal(typeof(SqlNullValueException), ex.GetType());
            }
            Assert.Equal(true, bytes.IsNull);
        }
        [Fact]
        public void GetXsdTypeTest()
        {
            XmlQualifiedName qualifiedName = SqlBytes.GetXsdType(null);
            Assert.Equal("base64Binary", qualifiedName.Name);
        }

        /* Read tests */
        [Fact]
        public void Read_SuccessTest1()
        {
            byte[] b1 = { 33, 34, 35, 36, 37, 38, 39, 40, 41, 42 };
            SqlBytes bytes = new SqlBytes(b1);
            byte[] b2 = new byte[10];

            bytes.Read(0, b2, 0, (int)bytes.Length);
            Assert.Equal(bytes.Value[5], b2[5]);
        }

        [Fact]
        public void Read_NullBufferTest()
        {
            byte[] b1 = { 33, 34, 35, 36, 37, 38, 39, 40, 41, 42 };
            SqlBytes bytes = new SqlBytes(b1);
            byte[] b2 = null;

            Assert.Throws<ArgumentNullException>(() => bytes.Read(0, b2, 0, 10));
        }

        [Fact]
        public void Read_InvalidCountTest1()
        {
            byte[] b1 = { 33, 34, 35, 36, 37, 38, 39, 40, 41, 42 };
            SqlBytes bytes = new SqlBytes(b1);
            byte[] b2 = new byte[5];

            Assert.Throws<ArgumentOutOfRangeException>(() => bytes.Read(0, b2, 0, 10));
        }

        [Fact]
        public void Read_NegativeOffsetTest()
        {
            byte[] b1 = { 33, 34, 35, 36, 37, 38, 39, 40, 41, 42 };
            SqlBytes bytes = new SqlBytes(b1);
            byte[] b2 = new byte[5];

            Assert.Throws<ArgumentOutOfRangeException>(() => bytes.Read(-1, b2, 0, 4));
        }

        [Fact]
        public void Read_NegativeOffsetInBufferTest()
        {
            byte[] b1 = { 33, 34, 35, 36, 37, 38, 39, 40, 41, 42 };
            SqlBytes bytes = new SqlBytes(b1);
            byte[] b2 = new byte[5];

            Assert.Throws<ArgumentOutOfRangeException>(() => bytes.Read(0, b2, -1, 4));
        }

        [Fact]
        public void Read_InvalidOffsetInBufferTest()
        {
            byte[] b1 = { 33, 34, 35, 36, 37, 38, 39, 40, 41, 42 };
            SqlBytes bytes = new SqlBytes(b1);
            byte[] b2 = new byte[5];

            Assert.Throws<ArgumentOutOfRangeException>(() => bytes.Read(0, b2, 8, 4));
        }

        [Fact]
        public void Read_NullInstanceValueTest()
        {
            byte[] b2 = new byte[5];
            SqlBytes bytes = new SqlBytes();

            Assert.Throws<SqlNullValueException>(() => bytes.Read(0, b2, 8, 4));
        }

        [Fact]
        public void Read_SuccessTest2()
        {
            byte[] b1 = { 33, 34, 35, 36, 37, 38, 39, 40, 41, 42 };
            SqlBytes bytes = new SqlBytes(b1);
            byte[] b2 = new byte[10];

            bytes.Read(5, b2, 0, 10);
            Assert.Equal(bytes.Value[5], b2[0]);
            Assert.Equal(bytes.Value[9], b2[4]);
        }

        [Fact]
        public void Read_NullBufferAndInstanceValueTest()
        {
            byte[] b2 = null;
            SqlBytes bytes = new SqlBytes();

            Assert.Throws<SqlNullValueException>(() => bytes.Read(0, b2, 8, 4));
        }

        [Fact]
        public void Read_NegativeCountTest()
        {
            byte[] b1 = { 33, 34, 35, 36, 37, 38, 39, 40, 41, 42 };
            SqlBytes bytes = new SqlBytes(b1);
            byte[] b2 = new byte[5];

            Assert.Throws<ArgumentOutOfRangeException>(() => bytes.Read(0, b2, 0, -1));
        }

        [Fact]
        public void Read_InvalidCountTest2()
        {
            byte[] b1 = { 33, 34, 35, 36, 37, 38, 39, 40, 41, 42 };
            SqlBytes bytes = new SqlBytes(b1);
            byte[] b2 = new byte[5];

            Assert.Throws<ArgumentOutOfRangeException>(() => bytes.Read(0, b2, 3, 4));
        }

        /* Write Tests */
        [Fact]
        public void Write_SuccessTest1()
        {
            byte[] b1 = { 33, 34, 35, 36, 37, 38, 39, 40, 41, 42 };
            byte[] b2 = new byte[10];
            SqlBytes bytes = new SqlBytes(b2);

            bytes.Write(0, b1, 0, b1.Length);
            Assert.Equal(bytes.Value[0], b1[0]);
        }

        [Fact]
        public void Write_NegativeOffsetTest()
        {
            byte[] b1 = { 33, 34, 35, 36, 37, 38, 39, 40, 41, 42 };
            byte[] b2 = new byte[10];
            SqlBytes bytes = new SqlBytes(b2);

            Assert.Throws<ArgumentOutOfRangeException>(() => bytes.Write(-1, b1, 0, b1.Length));
        }

        [Fact]
        public void Write_InvalidOffsetTest()
        {
            byte[] b1 = { 33, 34, 35, 36, 37, 38, 39, 40, 41, 42 };
            byte[] b2 = new byte[10];
            SqlBytes bytes = new SqlBytes(b2);

            Assert.Throws<SqlTypeException>(() => bytes.Write(bytes.Length + 5, b1, 0, b1.Length));
        }

        [Fact]
        public void Write_NegativeOffsetInBufferTest()
        {
            byte[] b1 = { 33, 34, 35, 36, 37, 38, 39, 40, 41, 42 };
            byte[] b2 = new byte[10];
            SqlBytes bytes = new SqlBytes(b2);

            Assert.Throws<ArgumentOutOfRangeException>(() => bytes.Write(0, b1, -1, b1.Length));
        }

        [Fact]
        public void Write_InvalidOffsetInBufferTest()
        {
            byte[] b1 = { 33, 34, 35, 36, 37, 38, 39, 40, 41, 42 };
            byte[] b2 = new byte[10];
            SqlBytes bytes = new SqlBytes(b2);

            Assert.Throws<ArgumentOutOfRangeException>(() => bytes.Write(0, b1, b1.Length + 5, b1.Length));
        }

        [Fact]
        public void Write_InvalidCountTest1()
        {
            byte[] b1 = { 33, 34, 35, 36, 37, 38, 39, 40, 41, 42 };
            byte[] b2 = new byte[10];
            SqlBytes bytes = new SqlBytes(b2);

            Assert.Throws<ArgumentOutOfRangeException>(() => bytes.Write(0, b1, 0, b1.Length + 5));
        }

        [Fact]
        public void Write_InvalidCountTest2()
        {
            byte[] b1 = { 33, 34, 35, 36, 37, 38, 39, 40, 41, 42 };
            byte[] b2 = new byte[10];
            SqlBytes bytes = new SqlBytes(b2);

            Assert.Throws<SqlTypeException>(() => bytes.Write(8, b1, 0, b1.Length));
        }

        [Fact]
        public void Write_NullBufferTest()
        {
            byte[] b1 = { 33, 34, 35, 36, 37, 38, 39, 40, 41, 42 };
            byte[] b2 = null;
            SqlBytes bytes = new SqlBytes(b1);

            Assert.Throws<ArgumentNullException>(() => bytes.Write(0, b2, 0, 10));
        }

        [Fact]
        public void Write_NullInstanceValueTest()
        {
            byte[] b1 = { 33, 34, 35, 36, 37, 38, 39, 40, 41, 42 };
            SqlBytes bytes = new SqlBytes();

            Assert.Throws<SqlTypeException>(() => bytes.Write(0, b1, 0, 10));
        }

        [Fact]
        public void Write_NullBufferAndInstanceValueTest()
        {
            byte[] b1 = null;
            SqlBytes bytes = new SqlBytes();

            Assert.Throws<ArgumentNullException>(() => bytes.Write(0, b1, 0, 10));
        }

        [Fact]
        public void Write_SuccessTest2()
        {
            byte[] b1 = { 33, 34, 35, 36, 37, 38, 39, 40, 41, 42 };
            byte[] b2 = new byte[20];
            SqlBytes bytes = new SqlBytes(b2);

            bytes.Write(8, b1, 0, 10);
            Assert.Equal(bytes.Value[8], b1[0]);
            Assert.Equal(bytes.Value[17], b1[9]);
        }

        [Fact]
        public void Write_NegativeCountTest()
        {
            byte[] b1 = { 33, 34, 35, 36, 37, 38, 39, 40, 41, 42 };
            byte[] b2 = new byte[10];
            SqlBytes bytes = new SqlBytes(b2);

            Assert.Throws<ArgumentOutOfRangeException>(() => bytes.Write(0, b1, 0, -1));
        }
    }
}


text:
import json
import os
import sys
import select
import time
import io
import threading
import sh as real_sh
from contextlib import contextmanager

plugin_id = os.environ.get("PLUGIN_ID")
# May be overwritten by user program to fore all error to log
stderr = sys.stderr

def ellipsis_str(str, maxs=50):
    if len(str) < maxs:
        return str
    else:
        firsth = int(maxs * 3 / 4)
        lasth = maxs - firsth
        return "%s...%s" % (str[:firsth], str[-lasth:])

class RPC:
    """
    Manages all the RPC status and calls.
    """
    def __init__(self, stdin, stdout):
        """
        Initilize the JSON-RPC communication object

        This class allows to register methods, event handlers, timers and file
        descriptor handlers to ease the communication using JSON-RPC.

        # Parameters

        param  | type     | description
        -------|----------|------------
        stdin  | file     | Which input file to use to read JSON-RPC calls.
        stdout | file     | File to write JSON-RPC calls. The remote endpoint.
        """
        self.__rpc_registry = {}
        # ensure input is utf8,
        # https://stackoverflow.com/questions/16549332/python-3-how-to-specify-stdin-encoding
        self.__stdin = None
        self.stdout = stdout
        self.__loop_status = 'OUT'  # IN | OUT | EXIT
        self.__requestq = []  # requests that are pending to do
        self.__replyq = {}  # replies got out of order: id to msg
        self.__send_id = 1  # current id to send
        self.__manual_replies = set()  # this has been replied with `reply`
        self.__fdevents = {}
        # timer_id -> (next_stop, id, seconds, continuation)
        self.__timers = {}
        self.__timer_id = 1
        self.__subscriptions = {}
        self.__subscriptions_ids = {}
        self.__subscription_id = 1
        self.__pending_events_queue = []
        # This is the last id received from the other side
        self.__last_rpc_id = 0
        # id to callback when receiving asynchornous responses
        self.__async_cb = {}
        self.__debug = False
        # functions to be called ASAP at the main loops
        self.__call_soon = []

        # Async events, managed at the __event_signal_r/w fds
        # If a 4 byte int is written to event_signal_w, that event is
        # trigered to be returned by loop_until(event=id)
        self.__event_id = 1
        self.__event_results = {}
        self.__events = {}
        r, w = os.pipe()
        r, w = os.fdopen(r, "rb"), os.fdopen(w, "wb")
        self.__event_signal_r = r
        self.__event_signal_w = w
        self.add_event(self.__event_signal_r, self.__received_event)

        self.set_stdin(stdin)

    def __received_event(self):
        """
        Read an event at __event_signal_r, and mark it as received.
        """
        event_idb = self.__event_signal_r.read(4)
        event_id = int.from_bytes(event_idb, "big")
        del self.__events[event_id]

    def __call_local(self, rpc):
        """
        Performs a local call into a registered method.

        This is use internally for all incomming rpc calls.
        """
        method = rpc['method']
        params = rpc['params'] or []
        call_id = rpc.get('id')
        (args, kwargs) = ([], params) if type(params) == dict else (params, {})

        if method in self.__rpc_registry:
            f = self.__rpc_registry[method]
            try:
                # print(method, params, args, kwargs)
                res = f(*args, **kwargs)
                return {
                    'result': res,
                    'id': call_id
                }
            except Exception as e:
                log_traceback()
                return {
                    'error': str(e),
                    'id': call_id
                }
        if not call_id:
            self.__emit_event(method, *args, **kwargs)
        else:
            return {'error': 'unknown_method %s' % method, 'id': call_id}

    def __emit_event(self, method, *args, **kwargs):
        """
        Emits the event to the subscription watchers.

        It takes care of not doing reentries, at it leads to bugs, as
        for example processing data from one event, do some remote call,
        another event arrives, and finished before the first.

        This is a real case of race condition writing to a file.

        The code here avoids the situation making events not reentrable; if
        processing an event, it queues newer to be delivered later.
        """
        do_later = len(self.__pending_events_queue) > 0
        self.__pending_events_queue.append((method, args, kwargs))
        if do_later:
            debug("No emit %s yet, as processing something else" % method)
            return
        # debug("Check subscriptions %s in %s"%(method,
        #        repr(self.__subscriptions.keys())))
        # do all the items on the queue
        while len(self.__pending_events_queue) > 0:
            (method, args, kwargs) = self.__pending_events_queue[0]
            if method in self.__subscriptions:
                for f in self.__subscriptions[method]:
                    if f:
                        try:
                            # debug("Calling %s b/o event %s(%s)" %
                            #       (f, method, args or kwargs))
                            f(*args, **kwargs)
                        except Exception:
                            log_traceback()
            # pop from top
            self.__pending_events_queue = self.__pending_events_queue[1:]

    def __loop(self):
        """
        Ener into the read remote loop.

        This loop also perform the timers watch and extra fds select.
        """
        prev_status = self.__loop_status
        self.__loop_status = 'IN'

        # pending requests
        while self.__requestq:
            rpc = self.__requestq[0]
            self.__requestq = self.__requestq[1:]
            self.__process_line(rpc)

        # incoming
        while self.__loop_status == 'IN':
            # debug("Wait fds: %s" %
            #       ([x.fileno() for x in self.__fdevents.keys()]))
            self.__loop_one()
        self.__loop_status = prev_status

    def __loop_one(self):
        # Call pending call_soon, in FIFO mode. New may appear while
        # processing this, and its ok
        while self.__call_soon:
            cb = self.__call_soon[0]
            try:
                cb()
            except Exception:
                log_traceback()
            self.__call_soon = self.__call_soon[1:]

        if self.__timers:
            timer = min(self.__timers.values(), key=lambda x: x.next)
            next_timeout = timer.next - time.time()
        else:
            timer = None
            next_timeout = None

        # debug("Next timeout", next_timeout, timeout_id)
        # print("Wait for ", self.__fdevents.keys(),
        #                    next_timeout, file=stderr)
        if not next_timeout or next_timeout >= 0:
            res = select.select(self.__fdevents.keys(), [], [], next_timeout)
            read_ready = res[0]
        else:  # maybe timeout already expired
            read_ready = []

        # print("Select finished: ", res, next_timeout, file=stderr)

        if read_ready:
            for ready in read_ready:
                try:
                    self.__fdevents[ready]()
                except Exception:
                    log_traceback()
        elif timer:  # timeout
            if timer.rearm:
                timer.arm()
            else:
                del self.__timers[timer.id]
            # rearm ?? Docs says no rearming
            try:
                timer.cont()
            except Exception:
                log_traceback()

    def __loop_until(self, id=None, event=None, method=None):
        """
        Performs an inner loop to be done while calling into the server.
        It is as the other loop, but until it get the proper reply.

        Requires the id of the reply to wait for, and the name of the method
        for error reporting.
        """
        # mini loop, may request calls while here
        while self.__loop_status != "EXIT":
            # if waiting for event, and event is no more, return
            # print("Wait for events ", self.__events, file=stderr)
            # I wait for an event, and its not there, then it has happened
            if event and not self.__events.get(event):
                # print("Return from event ", event, file=stderr)
                return

            rpc = self.__replyq.get(id)
            if rpc:
                del self.__replyq[id]
                if 'result' in rpc:
                    return rpc['result']
                else:
                    if rpc["error"] == "unknown_method":
                        raise Exception("unknown_method %s" % method)
                    raise Exception(rpc["error"])
            # this is last, so that if conditions are fulfilled at start, just
            # return
            self.__loop_one()

    def __read_parse_line(self):
        """
        Reads a line from the rpc input line, and parses it.
        """
        line = self.__stdin.readline()
        if self.__debug:
            print("%s<< %s" % (plugin_id, line), file=stderr, end='\r\n')
        if not line:
            self.stop()
            return
        rpc = json.loads(line)
        self.__process_line(rpc)

    def __process_line(self, rpc):
        """
        Performs the request processing to the external RPC endpoint.

        This internal function is used to do the real writing to the
        other end, as in some conditions it may be delayed.
        """
        if "result" in rpc or "error" in rpc:
            return self.__process_result(rpc)
        if "method" in rpc:
            return self.__process_call(rpc)
        raise Exception("unknown line type: %s" % (rpc.keys(),))

    def __process_result(self, rpc):
        id = rpc.get("id")
        # Might be an asynchronous result or error
        async_cb = self.__async_cb.get(id)
        if async_cb:
            # User can set only success condition, or a tuple with both
            error_cb = None
            if type(async_cb) == tuple:
                async_cb, error_cb = async_cb

            try:  # try to call the error or result handlers
                if async_cb and 'result' in rpc:
                    async_cb(rpc.get("result"))
                elif error_cb and 'error' in rpc:
                    error_cb(rpc.get("error"))
            except Exception:
                log_traceback()
            del self.__async_cb[id]
        # Or just an answer
        else:
            # keep it in the response store, later will check if ready
            self.__replyq[id] = rpc

    def __process_call(self, rpc):
        # If not ready yet to process requests, queue it for later.
        if self.__loop_status != 'IN':
            self.__requestq.append(rpc)
            return

        self.__last_rpc_id = rpc.get("id")
        res = self.__call_local(rpc)
        # subscription do not give back response
        if not res:
            return
        # might be already answered via `reply`
        if res.get("id") in self.__manual_replies:
            self.__manual_replies.discard(res.get("id"))
            return

        # normal case
        try:
            self.__println(json.dumps(res))
        except Exception:
            log_traceback()
            self.__println(json.dumps({
                "error": "serializing json response",
                "id": res["id"]
            }))

    def __println(self, line):
        """
        Prints a line onto the external endpoint.

        This function allows for easy debugging and some error conditions.
        """
        try:
            if self.__debug:
                print("%s>> %s" % (plugin_id, line), file=stderr, end='\r\n')
            self.stdout.write(line + '\n')
            self.stdout.flush()
        except IOError:
            if self.__loop_status == 'EXIT':
                sys.exit(1)
            self.stop()

    def add_method(self, name, f):
        """
        Adds a method to the local method registry.

        All local methods that can be caled b the remote endpoint have to be
        registered here.

        Normally the `@rpc_method` decorator is used for ease of use.
        """
        self.__rpc_registry[name] = f

    def loop(self):
        """
        Starts the remote reading mode.

        This loops indefinetely until stop_loop is called.
        """
        self.__loop()

    def loop_until(self, id=None, event=None):
        return self.__loop_until(id, event)

    def stop(self):
        """
        Forces loop stop on next iteration.

        This can be used to force program stop, although normally
        serverboards will emit a SIGSTOP signal to stop processes when
        required.
        """
        self.__loop_status = 'EXIT'
        debug("--- EOF ---")

    def set_debug(self, debug=True):
        """
        Enabled debug mode, shows all communications
        """
        self.__debug = debug
        print("DEBUG MODE ON", file=stderr, end='\r\n')

    def set_stdin(self, stdin):
        """
        Replaces current stdin for RPC

        Can be used for testing.
        """
        if stdin == sys.stdin:
            stdin = io.TextIOWrapper(sys.stdin.buffer, encoding='utf-8')

        if self.__stdin:
            self.remove_event(self.__stdin)

        # Can not set a stdin, in which case, the loop becomes infinite until
        # stop
        if stdin is not None:
            self.add_event(stdin, self.__read_parse_line)

        self.__stdin = stdin

    def add_event(self, fd, cont):
        """
        Watches for changes in a external file descriptor and calls the
        continuation function.

        This allows this class to also listen for external processes and file
        description changes.

        # Parameters

        param | type       | description
        ------|------------|------------
        fd    | int        | File descriptor
        cont  | function() | Continuation function to call when new data ready
        """
        if fd not in self.__fdevents:
            self.__fdevents[fd] = cont

    def remove_event(self, fd):
        """
        Removes an event from the event watching list
        """
        if fd in self.__fdevents:
            del self.__fdevents[fd]
            return True
        return False

    class Timer:
        """
        Data about timers
        """
        def __init__(self, id, interval, cont, rearm):
            self.next = None
            self.id = id
            self.interval = interval
            self.cont = cont
            self.rearm = rearm

            self.arm()

        def arm(self):
            self.next = time.time() + self.interval
            return self

    def add_timer(self, interval, cont, rearm=False):
        """
        Adds a timer to the rpc object

        After the given interval the continuation object will be called.
        The timer is not rearmed; it must be added again by the caller if
        desired.

        This timers are not in realtime, and may be called well after the
        timer expires, if the process is performing other actions, but will be
        called as soon as possible.

        # Parameters

        param | type       | description
        ------|------------|------------
        interval | float   | Time in seconds to wait until calling this timer
        cont  | function() | Function to call when the timer expires.
        rearm | bool       | Whether this timer automatically rearms. [false]

        # Returns
        timer_id : int
          Timer id to be used for later removal of timer
        """
        assert interval and cont, "Required interval and continuation"

        tid = self.__timer_id
        self.__timers[tid] = RPC.Timer(tid, interval, cont, rearm)

        self.__timer_id += 1
        return tid

    def remove_timer(self, tid):
        """
        Removes a timer.
        """
        if tid in self.__timers:
            del self.__timers[tid]

    def event(self, method, *params, **kparams):
        """
        Sends an event to the other side
        """
        rpcd = dict(method=method, params=params or kparams)
        try:
            rpc = json.dumps(rpcd)
            self.__println(rpc)
        except TypeError:
            error("Invalid JSON data: ", repr(rpcd))

    def reply(self, result):
        """
        Shortcuts request processing returning an inmediate answer. The final
        answer will be ignored.

        This allows to start long running processes that may send events in a
        loop.

        If more calls are expected, it is recomended to spawn new threads.
        """
        self.__manual_replies.add(self.__last_rpc_id)
        self.__println(json.dumps({
            "id": self.__last_rpc_id,
            "result": result
        }))

    def call(self, method, *params, _async=False, **kwparams):
        """
        Calls a method on the other side and waits until answer.

        If receives a call while waiting for answer there are two behaviours:

        1. If at self.loop, processes the request inmediatly
        2. If not, queues it to be processed wehn loop is called

        This allows to setup the environment.

        Optional arguments:
         * _async -- Set to a callback to be called when the answer is
                     received. Makes the call asynchronous. callback receives
                     the answer. It is called with response None in case of
                     error.
        """
        id = self.__send_id
        self.__send_id += 1
        # if both, pass kwparams as last argument. This sensible default works
        # with for example action calling and passing more calls to plugins
        if params and kwparams:
            params = [*params, kwparams]
        rpc = json.dumps(dict(method=method, params=params or kwparams, id=id))
        self.__println(rpc)
        if _async:  # Will get answer later calling the _async callback
            self.__async_cb[id] = _async
            return
        return self.__loop_until(id, method=method)

    def subscribe(self, event, callback):
        """
        Subscribes for a serverevent, calling the callback(eventdata) when it
        happens.

        Returns a subscription id, tahta can be used to unsubscribe.
        """
        # maybe event[context], we keep only event as only events are sent.
        eventname = event.split('[', 1)[0]
        sid = self.__subscription_id

        events = self.__subscriptions.get(eventname, []) + [callback]
        self.__subscriptions[eventname] = events
        self.__subscriptions_ids[sid] = (eventname, callback)

        self.call("event.subscribe", event)
        self.__subscription_id += 1

        # debug("Subscribed to %s" % event)
        # debug("Added subscription %s id %s: %s"%(eventname, sid,
        #                     repr(self.__subscriptions[eventname])))
        return sid

    def unsubscribe(self, subscription_id):
        """
        Unsubscribes from an event.
        """
        if subscription_id in self.__subscriptions:
            debug("%s in %s" %
                  (subscription_id, repr(self.__subscriptions_ids))
                  )
            (event, callback) = self.__subscriptions_ids[subscription_id]
            self.__subscriptions[event] = [
                x for x in self.__subscriptions[event] if x != callback
            ]
            # debug("Removed subscription %s id %s" % (event, subscription_id))
            self.call("event.unsubscribe", event)
            del self.__subscriptions_ids[subscription_id]

    def thread_run(self, cmd, *args, **kwargs):
        """
        Runs a function in another thread, and on completion returns, but
        keeping the loop running.

        This efectively means that the other function is not blocking the
        event loop.
        """
        id = self.__event_id
        self.__event_id += 1

        def run():
            result = cmd(*args, **kwargs)
            self.__event_results[id] = result
            self.__event_signal_w.write(id.to_bytes(4, "big"))
            self.__event_signal_w.flush()
        thread = threading.Thread(target=run)
        thread.start()
        self.__events[id] = thread.join

        # "context" switch
        rpc.loop_until(event=id)

        res = self.__event_results[id]
        del self.__event_results[id]
        return res

    def call_soon(self, callback):
        """
        Call ASAP the given callback, inside the loop
        """
        self.__call_soon.append(callback)

    def status(self):
        """
        Returns current loop status
        """
        return self.__loop_status

    def method_list(self):
        """
        Returns the list of known methods, for `dir` pourposes
        """
        return self.__rpc_registry.keys()

# RPC singleton
rpc = RPC(sys.stdin, sys.stdout)
sys.stdout = stderr  # allow debugging by print

def rpc_method(f):
    """
    Decorator to add this method to the known RPC methods.

    Use as simple decorator:

    ```python
    @decorator
    def func(param1, param2):
        ....
    ```

    or with a specific name

    ```python
    @decorator("rpc-name")
    def func(param1=None):
        ...
    ```
    """
    if type(f) == str:
        method_name = f

        def regf(f):
            # print("Registry %s: %s"%(method_name, repr(f)))
            rpc.add_method(method_name, f)
            return f
        return regf
    else:
        # print("Registry %s"%(f.__name__))
        rpc.add_method(f.__name__, f)
    return f

@rpc_method("dir")
def __dir():
    """
    Returns the list of all registered methods.

    Normally used by the other endpoint.
    """
    return list(rpc.method_list())

def loop():
    """
    Wrapper to easily start rpc loop

    Can replace the stdin and stdout here. Use only for debug. This change is
    permanent.

    Normal stdin may not be UTF8. To force do:

    ```
    stdin = io.TextIOWrapper(sys.stdin.buffer, encoding='utf-8')
    ```
    """
    rpc.loop()

class WriteTo:
    def __init__(self, fn, **extra):
        self.fn = fn
        self.extra = extra

    def __call__(self, *args, **extra):
        nextra = {**{"level": 1}, **self.extra, **extra}
        if not args:  # if no data, add extras for contexts.
            return WriteTo(self.fn, **nextra)
        self.fn(*args, **nextra)

    def write(self, data, *args, **extra):
        if data.endswith('\n'):
            data = data[:-1]
        self.fn(data, *args, **{**{"level": 1}, **self.extra, **extra})

    def flush(*args, **kwargs):
        pass

    @contextmanager
    def context(self, level=2, **extra):
        value = io.StringIO()
        yield value
        value.seek(0)
        self.fn(value.read(), **{**{"level": level}, **self.extra, **extra})

def log_(rpc, type):
    def decorate_log(extra, level=2):
        """
        Helper that decorates the given log messages with data of which
        function, line and file calls the log.
        """
        import inspect
        callerf = inspect.stack()[level]

        caller = {
            "plugin_id": plugin_id,
            "function": callerf[3],
            "file": callerf[1],
            "line": callerf[2],
            "pid": os.getpid(),
        }
        caller.update(extra)
        return caller

    log_method = "log.%s" % type

    def log_inner(*msg, level=0, file=None, **extra):
        msg = ' '.join(str(x) for x in msg)
        if file is not None:
            file.write(msg + "\n")
        if not msg:
            return
        return rpc.event(
            log_method,
            str(msg),
            decorate_log(extra, level=level + 2)
        )

    return log_inner

error = WriteTo(log_(rpc, "error"))
debug = WriteTo(log_(rpc, "debug"))
info = WriteTo(log_(rpc, "info"))
warning = WriteTo(log_(rpc, "warning"))
real_print = print

def print(*args, file=None, **kwargs):
    """
    Wraps around real print to allow to just print to the
    log.

    If has the file= kwarg, uses the normal print.
    """
    if file is None:
        debug(*args, **kwargs)
    else:
        real_print(*args, file=file, **kwargs)

def log_traceback(e=None):
    """
    Logs the given traceback to the error log.
    """
    if e:
        error(str(e))
    import traceback, io
    ss = io.StringIO()
    traceback.print_exc(file=ss)
    ss.seek(0)
    error(ss.read(), level=2)

def __simple_hash__(*args, **kwargs):
    hs = ";".join(str(x) for x in args)
    hs += ";"
    hs += ";".join(
        "%s=%s" % (
            __simple_hash__(k),
            __simple_hash__(kwargs[k])
        ) for k in sorted(kwargs.keys()))
    return hash(hs)

def cache_ttl(ttl=10, maxsize=50, hashf=__simple_hash__):
    """
    Simple decorator, not very efficient, for a time based cache.

    Params:
        ttl -- seconds this entry may live. After this time, next use is
               evicted.
        maxsize -- If trying to add more than maxsize elements, older will be
                   evicted.
        hashf -- Hash function for the arguments. Defaults to same data as
                 keys, but may require customization.
    """
    def wrapper(f):
        data = {}

        def wrapped(*args, **kwargs):
            nonlocal data
            currentt = time.time()
            if len(data) >= maxsize:
                # first take out all expired
                data = {
                    k: (timeout, v)
                    for k, (timeout, v) in data.items()
                    if timeout > currentt
                }
                if len(data) >= maxsize:
                    # not enough, expire oldest
                    oldest_k = None
                    oldest_t = currentt + ttl
                    for k, (timeout, v) in data.items():
                        if timeout < oldest_t:
                            oldest_k = k
                            oldest_t = timeout

                    del data[oldest_k]
            assert len(data) < maxsize

            if not args and not kwargs:
                hs = None
            else:
                hs = hashf(*args, **kwargs)
            timeout, value = data.get(hs, (currentt, None))
            if timeout <= currentt or not value:
                # recalculate
                value = f(*args, **kwargs)
                # store
                data[hs] = (currentt + ttl, value)
            return value

        def invalidate_cache():
            nonlocal data
            data = {}

        wrapped.invalidate_cache = invalidate_cache
        return wrapped
    return wrapper

class Config:
    """
    Easy access some configuration data for this plugin
    """
    def __init__(self):
        self.path = os.path.expanduser(
            os.environ.get('SERVERBOARDS_PATH', '~/.local/serverboards/')
        )
        Config.__ensure_path_exists(self.path)

    def file(self, filename):
        """
        Gets the absolute path of a local file for this plugin.

        This uses the serverboards configured local storage for the current
        plugin
        """
        p = os.path.join(self.path, filename)
        if not p.startswith(self.path):
            raise Exception("Trying to escape from config directory.")
        Config.__ensure_path_exists(os.path.dirname(p))
        return p

    @staticmethod
    def __ensure_path_exists(path):
        try:
            os.makedirs(path, 0o0700)
        except OSError as e:
            if 'File exists' not in str(e):
                raise

# config singleton
config = Config()

class Plugin:
    """
    Wraps a plugin to easily call the methods in it.

    It has no recovery in it.

    Can specify to ensure it is dead (kill_and_restart=True) before use. This
    is only useful at tests.
    """
    class Method:
        def __init__(self, plugin, method):
            self.plugin = plugin
            self.method = method

        def __call__(self, *args, **kwargs):
            return self.plugin.call(self.method, *args, **kwargs)

    def __init__(self, plugin_id, kill_and_restart=False, restart=True):
        self.plugin_id = plugin_id
        if kill_and_restart:
            try:
                rpc.call("plugin.kill", plugin_id)
                time.sleep(1)
            except Exception:
                pass
        self.restart = restart
        self.start()

    def __getattr__(self, method):
        if not self.uuid:
            self.uuid = rpc.call("plugin.start", self.plugin_id)
        return Plugin.Method(self, method)

    def start(self):
        self.uuid = rpc.call("plugin.start", self.plugin_id)
        return self

    def stop(self):
        """
        Stops the plugin.
        """
        if not self.uuid:  # not running
            return self
        rpc.call("plugin.stop", self.uuid)
        self.uuid = None
        return self

    RETRY_EVENTS = ["exit", "unknown_plugin at plugin.call", "unknown_plugin"]

    def call(self, method, *args, _async=False, **kwargs):
        """
        Call a method by name.

        This is also a workaround calling methods called `call` and `stop`.
        """
        try:
            return rpc.call(
                "plugin.call",
                self.uuid,
                method,
                args or kwargs,
                _async=_async
            )
        except Exception as e:
            # if exited or plugin call returns unknown method (refered to the
            # method to call at the plugin), restart and try again.
            if (str(e) in Plugin.RETRY_EVENTS) and self.restart:
                # if error because exitted, and may restart,
                # restart and try again (no loop)
                debug("Restarting plugin", self.plugin_id)
                self.start()
                return rpc.call(
                    "plugin.call",
                    self.uuid,
                    method,
                    args or kwargs
                )
            else:
                raise

    def __enter__(self):
        return self

    def __exit__(self, _type, _value, _traceback):
        try:
            self.stop()
        except Exception as ex:
            if str(ex) != "cant_stop at plugin.stop":
                raise

class SH:
    """
    Wrapper around `sh` that integrates into the serverboards loop.

    This allows to call external long running or even blocking programs
    and keep receiving requests.

    Special care must be taken as it may introduce subtle bugs when using
    global state, as this has no synchronization mechanisms and the same
    function may be called twice (by remote end).

    Not all functionalities of `sh` are included, only most common ones.
    """
    def __init__(self):
        pass

    def __getattr__(self, cmd):
        return self.Command(cmd)

    def Command(self, cmd):
        def caller(*args, **kwargs):
            # print("Call %s(%s,%s)" % (cmd, args, kwargs), file=stderr)

            def run():
                return real_sh.Command(cmd)(*args, **kwargs)
            response = rpc.thread_run(run)
            # print("SH / %s: %s" % (cmd, repr(response)), file=stderr)
            return response
        return caller

# An sh-like wrapper to have it integrated into serverboards.
sh = SH()

class RPCWrapper:
    """
    Wraps any module or function to be able to be called.

    This allows to do a simple `service.get(uuid)`, given that before you did a
    `service = RPCWrapper("service")`.

    There are already some instances ready for importing as:
    `from serverboards import service, issues, rules, action`
    """
    def __init__(self, module):
        self.module = module

    def __getattr__(self, sub):
        return RPCWrapper(self.module + '.' + sub)

    def __call__(self, *args, **kwargs):
        if args and kwargs:
            return rpc.call(self.module, *args, kwargs)
        return rpc.call(self.module, *args, **kwargs)

action = RPCWrapper("action")
auth = RPCWrapper("auth")
group = RPCWrapper("group")
perm = RPCWrapper("perm")
user = RPCWrapper("user")
dashboard = RPCWrapper("dashboard")
event = RPCWrapper("event")
issues = RPCWrapper("issues")
logs = RPCWrapper("logs")
notifications = RPCWrapper("notifications")
plugin = RPCWrapper("plugin")
plugin.component = RPCWrapper("plugin.component")
project = RPCWrapper("project")
rules = RPCWrapper("rules")
rules_v2 = RPCWrapper("rules_v2")
service = RPCWrapper("service")
settings = RPCWrapper("settings")
file = RPCWrapper("file")


text:
<form act='<?php echo $site_dir; ?>' method='post'>
  <input type='hidden' name='act' value='newtopic'>

      Posting new topic

        Category:
        <select class='form-control' id='inputCategory' name='inputCategory'>
<?php
 foreach($categories as $cat) {
   if($user->permissions->post_category($cat->id) == "true") {
?>
          <option value='<?php echo $cat->id; ?>'><?php echo $cat->name; ?></option>
<?php
   }
 }
?>
        </select>

        Topic Title:
        <input type='text' class='form-control' id='inputTitle' name='inputTitle'>

        Post Content:
        <textarea class='form-control' id='inputContent' name='inputContent'></textarea>

      <button type='submit' class='btn btn-primary'>Submit</button>

</form>


text:
#pragma once
#include <aws/shield/Shield_EXPORTS.h>
#include <aws/core/utils/DateTime.h>
#include <utility>

namespace Aws
{
namespace Utils
{
namespace Json
{
  class JsonValue;
  class JsonView;
} // namespace Json
} // namespace Utils
namespace Shield
{
namespace Model
{

  /**
   *
The time range.

See Also:
   AWS
   * API Reference

   */
  class AWS_SHIELD_API TimeRange
  {
  public:
    TimeRange();
    TimeRange(Aws::Utils::Json::JsonView jsonValue);
    TimeRange& operator=(Aws::Utils::Json::JsonView jsonValue);
    Aws::Utils::Json::JsonValue Jsonize() const;

    /**
     *
The start time, in Unix time in seconds. For more information see timestamp.

     */
    inline const Aws::Utils::DateTime& GetFromInclusive() const{ return m_fromInclusive; }

    /**
     *
The start time, in Unix time in seconds. For more information see timestamp.

     */
    inline bool FromInclusiveHasBeenSet() const { return m_fromInclusiveHasBeenSet; }

    /**
     *
The start time, in Unix time in seconds. For more information see timestamp.

     */
    inline void SetFromInclusive(const Aws::Utils::DateTime& value) { m_fromInclusiveHasBeenSet = true; m_fromInclusive = value; }

    /**
     *
The start time, in Unix time in seconds. For more information see timestamp.

     */
    inline void SetFromInclusive(Aws::Utils::DateTime&& value) { m_fromInclusiveHasBeenSet = true; m_fromInclusive = std::move(value); }

    /**
     *
The start time, in Unix time in seconds. For more information see timestamp.

     */
    inline TimeRange& WithFromInclusive(const Aws::Utils::DateTime& value) { SetFromInclusive(value); return *this;}

    /**
     *
The start time, in Unix time in seconds. For more information see timestamp.

     */
    inline TimeRange& WithFromInclusive(Aws::Utils::DateTime&& value) { SetFromInclusive(std::move(value)); return *this;}

    /**
     *
The end time, in Unix time in seconds. For more information see timestamp.

     */
    inline const Aws::Utils::DateTime& GetToExclusive() const{ return m_toExclusive; }

    /**
     *
The end time, in Unix time in seconds. For more information see timestamp.

     */
    inline bool ToExclusiveHasBeenSet() const { return m_toExclusiveHasBeenSet; }

    /**
     *
The end time, in Unix time in seconds. For more information see timestamp.

     */
    inline void SetToExclusive(const Aws::Utils::DateTime& value) { m_toExclusiveHasBeenSet = true; m_toExclusive = value; }

    /**
     *
The end time, in Unix time in seconds. For more information see timestamp.

     */
    inline void SetToExclusive(Aws::Utils::DateTime&& value) { m_toExclusiveHasBeenSet = true; m_toExclusive = std::move(value); }

    /**
     *
The end time, in Unix time in seconds. For more information see timestamp.

     */
    inline TimeRange& WithToExclusive(const Aws::Utils::DateTime& value) { SetToExclusive(value); return *this;}

    /**
     *
The end time, in Unix time in seconds. For more information see timestamp.

     */
    inline TimeRange& WithToExclusive(Aws::Utils::DateTime&& value) { SetToExclusive(std::move(value)); return *this;}

  private:

    Aws::Utils::DateTime m_fromInclusive;
    bool m_fromInclusiveHasBeenSet;

    Aws::Utils::DateTime m_toExclusive;
    bool m_toExclusiveHasBeenSet;
  };

} // namespace Model
} // namespace Shield
} // namespace Aws


text:
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="CheckStyle-IDEA">
    <option name="configuration">
      <map>
        <entry key="active-configuration" value="LOCAL_FILE:$PRJ_DIR$/checkstyle.xml:Buck Checkstyle" />
        <entry key="check-nonjava-files" value="false" />
        <entry key="check-test-classes" value="false" />
        <entry key="location-0" value="CLASSPATH:/sun_checks.xml:The default CheckStyle rules" />
        <entry key="location-1" value="LOCAL_FILE:$PRJ_DIR$/checkstyle.xml:Buck Checkstyle" />
        <entry key="property-1.com.puppycrawl.tools.checkstyle.checks.sizes.LineLength.ignorePattern" value="^(package .*;\s*)|(import .*;\s*)|( *[\*\/]* *https?://.*)$" />
        <entry key="property-1.com.puppycrawl.tools.checkstyle.checks.sizes.LineLength.max" value="100" />
        <entry key="suppress-errors" value="true" />
        <entry key="thirdparty-classpath" value="" />
      </map>
    </option>
  </component>
</project>


text:
package upside_down

import (
	"bytes"

	"github.com/blevesearch/bleve/index"
	"github.com/blevesearch/bleve/index/store"
)

type UpsideDownCouchTermFieldReader struct {
	indexReader  *IndexReader
	iterator     store.KVIterator
	count        uint64
	term         []byte
	field        uint16
	readerPrefix []byte
}

func newUpsideDownCouchTermFieldReader(indexReader *IndexReader, term []byte, field uint16) (*UpsideDownCouchTermFieldReader, error) {
	dictionaryRow := NewDictionaryRow(term, field, 0)
	val, err := indexReader.kvreader.Get(dictionaryRow.Key())
	if err != nil {
		return nil, err
	}
	if val == nil {
		return &UpsideDownCouchTermFieldReader{
			count: 0,
			term:  term,
			field: field,
		}, nil
	}

	err = dictionaryRow.parseDictionaryV(val)
	if err != nil {
		return nil, err
	}

	tfr := NewTermFrequencyRow(term, field, "", 0, 0)
	readerPrefix := tfr.Key()
	it := indexReader.kvreader.Iterator(readerPrefix)

	return &UpsideDownCouchTermFieldReader{
		indexReader:  indexReader,
		iterator:     it,
		count:        dictionaryRow.count,
		term:         term,
		field:        field,
		readerPrefix: readerPrefix,
	}, nil
}

func (r *UpsideDownCouchTermFieldReader) Count() uint64 {
	return r.count
}

func (r *UpsideDownCouchTermFieldReader) Next() (*index.TermFieldDoc, error) {
	if r.iterator != nil {
		key, val, valid := r.iterator.Current()
		if valid {
			if !bytes.HasPrefix(key, r.readerPrefix) {
				// end of the line
				return nil, nil
			}
			tfr, err := NewTermFrequencyRowKV(key, val)
			if err != nil {
				return nil, err
			}
			r.iterator.Next()
			return &index.TermFieldDoc{
				ID:      string(tfr.doc),
				Freq:    tfr.freq,
				Norm:    float64(tfr.norm),
				Vectors: r.indexReader.index.termFieldVectorsFromTermVectors(tfr.vectors),
			}, nil
		}
	}
	return nil, nil
}

func (r *UpsideDownCouchTermFieldReader) Advance(docID string) (*index.TermFieldDoc, error) {
	if r.iterator != nil {
		tfr := NewTermFrequencyRow(r.term, r.field, docID, 0, 0)
		r.iterator.Seek(tfr.Key())
		key, val, valid := r.iterator.Current()
		if valid {
			if !bytes.HasPrefix(key, r.readerPrefix) {
				// end of the line
				return nil, nil
			}
			tfr, err := NewTermFrequencyRowKV(key, val)
			if err != nil {
				return nil, err
			}
			r.iterator.Next()
			return &index.TermFieldDoc{
				ID:      string(tfr.doc),
				Freq:    tfr.freq,
				Norm:    float64(tfr.norm),
				Vectors: r.indexReader.index.termFieldVectorsFromTermVectors(tfr.vectors),
			}, nil
		}
	}
	return nil, nil
}

func (r *UpsideDownCouchTermFieldReader) Close() error {
	if r.iterator != nil {
		return r.iterator.Close()
	}
	return nil
}

type UpsideDownCouchDocIDReader struct {
	indexReader *IndexReader
	iterator    store.KVIterator
	start       string
	end         string
}

func newUpsideDownCouchDocIDReader(indexReader *IndexReader, start, end string) (*UpsideDownCouchDocIDReader, error) {
	if start == "" {
		start = string([]byte{0x0})
	}
	if end == "" {
		end = string([]byte{0xff})
	}
	bisr := NewBackIndexRow(start, nil, nil)
	it := indexReader.kvreader.Iterator(bisr.Key())

	return &UpsideDownCouchDocIDReader{
		indexReader: indexReader,
		iterator:    it,
		start:       start,
		end:         end,
	}, nil
}

func (r *UpsideDownCouchDocIDReader) Next() (string, error) {
	key, val, valid := r.iterator.Current()
	if valid {
		bier := NewBackIndexRow(r.end, nil, nil)
		if bytes.Compare(key, bier.Key()) > 0 {
			// end of the line
			return "", nil
		}
		br, err := NewBackIndexRowKV(key, val)
		if err != nil {
			return "", err
		}
		r.iterator.Next()
		return string(br.doc), nil
	}
	return "", nil
}

func (r *UpsideDownCouchDocIDReader) Advance(docID string) (string, error) {
	bir := NewBackIndexRow(docID, nil, nil)
	r.iterator.Seek(bir.Key())
	key, val, valid := r.iterator.Current()
	if valid {
		bier := NewBackIndexRow(r.end, nil, nil)
		if bytes.Compare(key, bier.Key()) > 0 {
			// end of the line
			return "", nil
		}
		br, err := NewBackIndexRowKV(key, val)
		if err != nil {
			return "", err
		}
		r.iterator.Next()
		return string(br.doc), nil
	}
	return "", nil
}

func (r *UpsideDownCouchDocIDReader) Close() error {
	return r.iterator.Close()
}


text:
class Repository
  include Gitlab::ShellAdapter

  attr_accessor :raw_repository, :path_with_namespace, :project

  def initialize(path_with_namespace, default_branch = nil, project = nil)
    @path_with_namespace = path_with_namespace
    @raw_repository = Gitlab::Git::Repository.new(path_to_repo) if path_with_namespace
    @project = project
  rescue Gitlab::Git::Repository::NoRepository
    nil
  end

  # Return absolute path to repository
  def path_to_repo
    @path_to_repo ||= File.expand_path(
      File.join(Gitlab.config.gitlab_shell.repos_path, path_with_namespace + ".git")
    )
  end

  def exists?
    raw_repository
  end

  def empty?
    raw_repository.empty?
  end

  def commit(id = 'HEAD')
    return nil unless raw_repository
    commit = Gitlab::Git::Commit.find(raw_repository, id)
    commit = Commit.new(commit, @project) if commit
    commit
  rescue Rugged::OdbError
    nil
  end

  def commits(ref, path = nil, limit = nil, offset = nil, skip_merges = false)
    commits = Gitlab::Git::Commit.where(
      repo: raw_repository,
      ref: ref,
      path: path,
      limit: limit,
      offset: offset,
    )
    commits = Commit.decorate(commits, @project) if commits.present?
    commits
  end

  def commits_between(from, to)
    commits = Gitlab::Git::Commit.between(raw_repository, from, to)
    commits = Commit.decorate(commits, @project) if commits.present?
    commits
  end

  def find_branch(name)
    branches.find { |branch| branch.name == name }
  end

  def find_tag(name)
    tags.find { |tag| tag.name == name }
  end

  def add_branch(branch_name, ref)
    cache.expire(:branch_names)
    @branches = nil

    gitlab_shell.add_branch(path_with_namespace, branch_name, ref)
  end

  def add_tag(tag_name, ref, message = nil)
    cache.expire(:tag_names)
    @tags = nil

    gitlab_shell.add_tag(path_with_namespace, tag_name, ref, message)
  end

  def rm_branch(branch_name)
    cache.expire(:branch_names)
    @branches = nil

    gitlab_shell.rm_branch(path_with_namespace, branch_name)
  end

  def rm_tag(tag_name)
    cache.expire(:tag_names)
    @tags = nil

    gitlab_shell.rm_tag(path_with_namespace, tag_name)
  end

  def round_commit_count
    if commit_count > 10000
      '10000+'
    elsif commit_count > 5000
      '5000+'
    elsif commit_count > 1000
      '1000+'
    else
      commit_count
    end
  end

  def branch_names
    cache.fetch(:branch_names) { raw_repository.branch_names }
  end

  def tag_names
    cache.fetch(:tag_names) { raw_repository.tag_names }
  end

  def commit_count
    cache.fetch(:commit_count) do
      begin
        raw_repository.commit_count(self.root_ref)
      rescue
        0
      end
    end
  end

  # Return repo size in megabytes
  # Cached in redis
  def size
    cache.fetch(:size) { raw_repository.size }
  end

  def expire_cache
    %i(size branch_names tag_names commit_count graph_log
       readme version contribution_guide changelog license).each do |key|
      cache.expire(key)
    end
  end

  def graph_log
    cache.fetch(:graph_log) do
      commits = raw_repository.log(limit: 6000, skip_merges: true,
                                   ref: root_ref)

      commits.map do |rugged_commit|
        commit = Gitlab::Git::Commit.new(rugged_commit)

        {
          author_name: commit.author_name,
          author_email: commit.author_email,
          additions: commit.stats.additions,
          deletions: commit.stats.deletions,
        }
      end
    end
  end

  def lookup_cache
    @lookup_cache ||= {}
  end

  def method_missing(m, *args, &block)
    if m == :lookup && !block_given?
      lookup_cache[m] ||= {}
      lookup_cache[m][args.join(":")] ||= raw_repository.send(m, *args, &block)
    else
      raw_repository.send(m, *args, &block)
    end
  end

  def respond_to_missing?(method, include_private = false)
    raw_repository.respond_to?(method, include_private) || super
  end

  def blob_at(sha, path)
    Gitlab::Git::Blob.find(self, sha, path)
  end

  def blob_by_oid(oid)
    Gitlab::Git::Blob.raw(self, oid)
  end

  def readme
    cache.fetch(:readme) { tree(:head).readme }
  end

  def version
    cache.fetch(:version) do
      tree(:head).blobs.find do |file|
        file.name.downcase == 'version'
      end
    end
  end

  def contribution_guide
    cache.fetch(:contribution_guide) do
      tree(:head).blobs.find do |file|
        file.contributing?
      end
    end
  end

  def changelog
    cache.fetch(:changelog) do
      tree(:head).blobs.find do |file|
        file.name =~ /\A(changelog|history)/i
      end
    end
  end

  def license
    cache.fetch(:license) do
      tree(:head).blobs.find do |file|
        file.name =~ /\Alicense/i
      end
    end
  end

  def head_commit
    @head_commit ||= commit(self.root_ref)
  end

  def head_tree
    @head_tree ||= Tree.new(self, head_commit.sha, nil)
  end

  def tree(sha = :head, path = nil)
    if sha == :head
      if path.nil?
        return head_tree
      else
        sha = head_commit.sha
      end
    end

    Tree.new(self, sha, path)
  end

  def blob_at_branch(branch_name, path)
    last_commit = commit(branch_name)

    if last_commit
      blob_at(last_commit.sha, path)
    else
      nil
    end
  end

  # Returns url for submodule
  #
  # Ex.
  #   @repository.submodule_url_for('master', 'rack')
  #   # => git@localhost:rack.git
  #
  def submodule_url_for(ref, path)
    if submodules(ref).any?
      submodule = submodules(ref)[path]

      if submodule
        submodule['url']
      end
    end
  end

  def last_commit_for_path(sha, path)
    args = %W(git rev-list --max-count=1 #{sha} -- #{path})
    sha = Gitlab::Popen.popen(args, path_to_repo).first.strip
    commit(sha)
  end

  # Remove archives older than 2 hours
  def clean_old_archives
    repository_downloads_path = Gitlab.config.gitlab.repository_downloads_path

    return unless File.directory?(repository_downloads_path)

    Gitlab::Popen.popen(%W(find #{repository_downloads_path} -not -path #{repository_downloads_path} -mmin +120 -delete))
  end

  def branches_sorted_by(value)
    case value
    when 'recently_updated'
      branches.sort do |a, b|
        commit(b.target).committed_date <=> commit(a.target).committed_date
      end
    when 'last_updated'
      branches.sort do |a, b|
        commit(a.target).committed_date <=> commit(b.target).committed_date
      end
    else
      branches
    end
  end

  def contributors
    commits = self.commits(nil, nil, 2000, 0, true)

    commits.group_by(&:author_email).map do |email, commits|
      contributor = Gitlab::Contributor.new
      contributor.email = email

      commits.each do |commit|
        if contributor.name.blank?
          contributor.name = commit.author_name
        end

        contributor.commits += 1
      end

      contributor
    end
  end

  def blob_for_diff(commit, diff)
    file = blob_at(commit.id, diff.new_path)

    unless file
      file = prev_blob_for_diff(commit, diff)
    end

    file
  end

  def prev_blob_for_diff(commit, diff)
    if commit.parent_id
      blob_at(commit.parent_id, diff.old_path)
    end
  end

  def branch_names_contains(sha)
    args = %W(git branch --contains #{sha})
    names = Gitlab::Popen.popen(args, path_to_repo).first

    if names.respond_to?(:split)
      names = names.split("\n").map(&:strip)

      names.each do |name|
        name.slice! '* '
      end

      names
    else
      []
    end
  end

  def tag_names_contains(sha)
    args = %W(git tag --contains #{sha})
    names = Gitlab::Popen.popen(args, path_to_repo).first

    if names.respond_to?(:split)
      names = names.split("\n").map(&:strip)

      names.each do |name|
        name.slice! '* '
      end

      names
    else
      []
    end
  end

  def branches
    @branches ||= raw_repository.branches
  end

  def tags
    @tags ||= raw_repository.tags
  end

  def root_ref
    @root_ref ||= raw_repository.root_ref
  end

  def commit_file(user, path, content, message, ref)
    path[0] = '' if path[0] == '/'

    committer = user_to_comitter(user)
    options = {}
    options[:committer] = committer
    options[:author] = committer
    options[:commit] = {
      message: message,
      branch: ref
    }

    options[:file] = {
      content: content,
      path: path
    }

    Gitlab::Git::Blob.commit(raw_repository, options)
  end

  def remove_file(user, path, message, ref)
    path[0] = '' if path[0] == '/'

    committer = user_to_comitter(user)
    options = {}
    options[:committer] = committer
    options[:author] = committer
    options[:commit] = {
      message: message,
      branch: ref
    }

    options[:file] = {
      path: path
    }

    Gitlab::Git::Blob.remove(raw_repository, options)
  end

  private

  def user_to_comitter(user)
    {
      email: user.email,
      name: user.name,
      time: Time.now
    }
  end

  def cache
    @cache ||= RepositoryCache.new(path_with_namespace)
  end
end


text:
package sim.workload.routing;

public abstract class Default extends sim.workload.stealth.Default {
	public Default(String[] arglist) throws Exception {
		super(arglist);
	}
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Bull. Torrey bot. Club 32(7): 370 (1905)

#### Original name
Daedalea pallidofulva Berk.

### Remarks
null