text:
/**
 * Functions for dealing with window borders.
 */

#include "jwm.h"
#include "border.h"
#include "client.h"
#include "clientlist.h"
#include "color.h"
#include "icon.h"
#include "font.h"
#include "misc.h"
#include "settings.h"
#include "grab.h"
#include "button.h"

static char *buttonNames[BI_COUNT];
static IconNode *buttonIcons[BI_COUNT];

static void DrawBorderHelper(const ClientNode *np);
static void DrawBorderHandles(const ClientNode *np,
                              Pixmap canvas, GC gc);
static void DrawBorderButtons(const ClientNode *np,
                              Pixmap canvas, GC gc);
static char DrawBorderIcon(BorderIconType t,
                           unsigned xoffset, unsigned yoffset,
                           Pixmap canvas);
static void DrawCloseButton(unsigned xoffset, unsigned yoffset,
                            Pixmap canvas, GC gc);
static void DrawMaxIButton(unsigned xoffset, unsigned yoffset,
                           Pixmap canvas, GC gc);
static void DrawMaxAButton(unsigned xoffset, unsigned yoffset,
                           Pixmap canvas, GC gc);
static void DrawLayerNormalButton(unsigned xoffset, unsigned yoffset,
                           Pixmap canvas, GC gc);
static void DrawLayerAboveButton(unsigned xoffset, unsigned yoffset,
                           Pixmap canvas, GC gc);
static void DrawMinButton(unsigned xoffset, unsigned yoffset,
                          Pixmap canvas, GC gc);
static unsigned GetButtonCount(const ClientNode *np);

#ifdef USE_SHAPE
static void FillRoundedRectangle(Drawable d, GC gc, int x, int y,
                                 int width, int height, int radius);
#endif

/** Initialize structures. */
void InitializeBorders(void)
{
   memset(buttonNames, 0, sizeof(buttonNames));
}

/** Initialize server resources. */
void StartupBorders(void)
{
   unsigned int i;

   for(i = 0; i < BI_COUNT; i++) {
      if(buttonNames[i]) {
         buttonIcons[i] = LoadNamedIcon(buttonNames[i], 1, 1);
         Release(buttonNames[i]);
         buttonNames[i] = NULL;
      } else {
         buttonIcons[i] = NULL;
      }
   }

}

/** Destroy structures. */
void DestroyBorders(void)
{
   unsigned i;
   for(i = 0; i < BI_COUNT; i++)
   {
      if(buttonNames[i]) {
         Release(buttonNames[i]);
         buttonNames[i] = NULL;
      }
   }
}

/** Get the size of the icon to display on a window. */
int GetBorderIconSize(void)
{
  return settings.titleHeight/2;
}

/** Determine the border action to take given coordinates. */
BorderActionType GetBorderActionType(const ClientNode *np, int x, int y)
{

   int north, south, east, west;
   unsigned int resizeMask;
   const unsigned int titleHeight = settings.titleHeight;

   GetBorderSize(&np->state, &north, &south, &east, &west);

   /* Check title bar actions. */
   if((np->state.border & BORDER_TITLE) &&
      titleHeight > settings.borderWidth) {

      if(y >= south && y <= titleHeight + south) {

 	 /* Offset for the right x coordinate of the most right title bar buttons */
	 int offset = np->width + west;

         /* Close button. */
         if((np->state.border & BORDER_CLOSE) && offset > titleHeight*2) {
	   if(x > offset - titleHeight*(1+1/4) && x < offset - titleHeight/4) {
               return BA_CLOSE;
	   }
	   offset -= titleHeight*(1+1/4);
	 }

         /* Maximize button. */
         if((np->state.border & BORDER_MAX) && offset > titleHeight*2) {
	   if(x > offset - titleHeight*(1+1/4) && x < offset - titleHeight/4) {
               return BA_MAXIMIZE;
	   }
	   offset -= titleHeight*(1+1/4);
         }

	 /* Above all button toggle. */
         if(offset > titleHeight*2) {
	   if(x > offset - titleHeight*(1+1/4) && x < offset - titleHeight/4) {
               return BA_LAYER;
	   }
	   offset -= titleHeight*(1+1/4);
         }

         /* Minimize button. */
         if((np->state.border & BORDER_MIN) && offset > titleHeight*2) {
	   if(x > offset - titleHeight*(1+1/4) && x < offset - titleHeight/4) {
               return BA_MINIMIZE;
	   }
	   offset -= titleHeight*(1+1/4);
         }

	 /* Check for move. */
         if(x > west && x < offset) {
	   if(np->state.border & BORDER_MOVE) {
	     return BA_MOVE;
	   } else {
	     return BA_NONE;
	   }
         }
      }

   }

   /* Now we check resize actions.
    * There is no need to go further if resizing isn't allowed. */
   if(!(np->state.border & BORDER_RESIZE)) {
      return BA_NONE;
   }

   /* We don't allow resizing maximized windows. */
   resizeMask = BA_RESIZE_S | BA_RESIZE_N
              | BA_RESIZE_E | BA_RESIZE_W
              | BA_RESIZE;
   if(np->state.maxFlags & MAX_HORIZ) {
      resizeMask &= ~(BA_RESIZE_E | BA_RESIZE_W);
   }
   if(np->state.maxFlags & MAX_VERT) {
      resizeMask &= ~(BA_RESIZE_N | BA_RESIZE_S);
   }
   if(np->state.status & STAT_SHADED) {
      resizeMask &= ~(BA_RESIZE_N | BA_RESIZE_S);
   }

   /* Check south east/west and north east/west resizing. */
   if(   np->width >= settings.titleHeight * 2
      && np->height >= settings.titleHeight * 2) {
      if(y > np->height + north - settings.titleHeight) {
         if(x < settings.titleHeight) {
            return (BA_RESIZE_S | BA_RESIZE_W | BA_RESIZE) & resizeMask;
         } else if(x > np->width + west - settings.titleHeight) {
            return (BA_RESIZE_S | BA_RESIZE_E | BA_RESIZE) & resizeMask;
         }
      } else if(y < settings.titleHeight) {
         if(x < settings.titleHeight) {
            return (BA_RESIZE_N | BA_RESIZE_W | BA_RESIZE) & resizeMask;
         } else if(x > np->width + west - settings.titleHeight) {
            return (BA_RESIZE_N | BA_RESIZE_E | BA_RESIZE) & resizeMask;
         }
      }
   }

   /* Check east, west, north, and south resizing. */
   if(x <= west) {
      return (BA_RESIZE_W | BA_RESIZE) & resizeMask;
   } else if(x >= np->width + west) {
      return (BA_RESIZE_E | BA_RESIZE) & resizeMask;
   } else if(y >= np->height + north) {
      return (BA_RESIZE_S | BA_RESIZE) & resizeMask;
   } else if(y <= south) {
      return (BA_RESIZE_N | BA_RESIZE) & resizeMask;
   } else {
      return BA_NONE;
   }

}

/** Reset the shape of a window border. */
void ResetBorder(const ClientNode *np)
{
#ifdef USE_SHAPE
   Pixmap shapePixmap;
   GC shapeGC;
#endif

   int north, south, east, west;
   int width, height;

   if(np->parent == None) {
      JXMoveResizeWindow(display, np->window, np->x, np->y,
                         np->width, np->height);
      return;
   }

   GrabServer();

   /* Determine the size of the window. */
   GetBorderSize(&np->state, &north, &south, &east, &west);
   width = np->width + east + west;
   if(np->state.status & STAT_SHADED) {
      height = north + south;
   } else {
      height = np->height + north + south;
   }

   /** Set the window size. */
   if(!(np->state.status & STAT_SHADED)) {
      JXMoveResizeWindow(display, np->window, west, north,
                         np->width, np->height);
   }
   JXMoveResizeWindow(display, np->parent, np->x - west, np->y - north,
                      width, height);

#ifdef USE_SHAPE
   if(settings.cornerRadius > 0 || (np->state.status & STAT_SHAPED)) {

      /* First set the shape to the window border. */
      shapePixmap = JXCreatePixmap(display, np->parent, width, height, 1);
      shapeGC = JXCreateGC(display, shapePixmap, 0, NULL);

      /* Make the whole area transparent. */
      JXSetForeground(display, shapeGC, 0);
      JXFillRectangle(display, shapePixmap, shapeGC, 0, 0, width, height);

      /* Draw the window area without the corners. */
      /* Corner bound radius -1 to allow slightly better outline drawing */
      JXSetForeground(display, shapeGC, 1);
      if(((np->state.status & STAT_FULLSCREEN) || np->state.maxFlags) &&
         !(np->state.status & (STAT_SHADED))) {
         JXFillRectangle(display, shapePixmap, shapeGC, 0, 0, width, height);
      } else {
         FillRoundedRectangle(shapePixmap, shapeGC, 0, 0, width, height,
                              settings.cornerRadius - 1);
      }

      /* Apply the client window. */
      if(!(np->state.status & STAT_SHADED) &&
          (np->state.status & STAT_SHAPED)) {

         XRectangle *rects;
         int count;
         int ordering;

         /* Cut out an area for the client window. */
         JXSetForeground(display, shapeGC, 0);
         JXFillRectangle(display, shapePixmap, shapeGC, west, north,
                         np->width, np->height);

         /* Fill in the visible area. */
         rects = JXShapeGetRectangles(display, np->window, ShapeBounding,
                                      &count, &ordering);
         if(JLIKELY(rects)) {
            int i;
            for(i = 0; i < count; i++) {
               rects[i].x += east;
               rects[i].y += north;
            }
            JXSetForeground(display, shapeGC, 1);
            JXFillRectangles(display, shapePixmap, shapeGC, rects, count);
            JXFree(rects);
         }

      }

      /* Set the shape. */
      JXShapeCombineMask(display, np->parent, ShapeBounding, 0, 0,
                         shapePixmap, ShapeSet);

      JXFreeGC(display, shapeGC);
      JXFreePixmap(display, shapePixmap);
   }
#endif

   UngrabServer();

}

/** Draw a client border. */
void DrawBorder(ClientNode *np)
{

   Assert(np);

   /* Don't draw any more if we are shutting down. */
   if(JUNLIKELY(shouldExit)) {
      return;
   }

   /* Must be either mapped or shaded to have a border. */
   if(!(np->state.status & (STAT_MAPPED | STAT_SHADED))) {
      return;
   }

   /* Hidden and fullscreen windows don't get borders. */
   if(np->state.status & (STAT_HIDDEN | STAT_FULLSCREEN)) {
      return;
   }

   /* Create the frame if needed. */
   ReparentClient(np);

   /* Return if there is no border. */
   if(np->parent == None) {
      return;
   }

   /* Do the actual drawing. */
   DrawBorderHelper(np);

}

/** Helper method for drawing borders. */
void DrawBorderHelper(const ClientNode *np)
{

   ColorType borderTextColor;

   long titleColor;

   int north, south, east, west;
   unsigned int width, height;
   int iconSize, titlexShift;

   unsigned int buttonCount;
   int titleWidth;
   Pixmap canvas;
   GC gc;

   Assert(np);

   iconSize = GetBorderIconSize();
   GetBorderSize(&np->state, &north, &south, &east, &west);
   width = np->width + east + west;
   height = np->height + north + south;

   /* Determine the colors to use. */
   if(np->state.status & (STAT_ACTIVE | STAT_FLASH)) {

      borderTextColor = COLOR_TITLE_ACTIVE_FG;
      if(np->state.layer == LAYER_ABOVE) {
	titleColor = colors[COLOR_TITLE_ACTIVE_BG2];
      } else {
	titleColor = colors[COLOR_TITLE_ACTIVE_BG1];
      }

   } else {

      borderTextColor = COLOR_TITLE_FG;
      if(np->state.layer == LAYER_ABOVE) {
	titleColor = colors[COLOR_TITLE_BG2];
      } else {
	titleColor = colors[COLOR_TITLE_BG1];
      }

   }

   /* Set parent background to reduce flicker. */
   JXSetWindowBackground(display, np->parent, titleColor);

   canvas = JXCreatePixmap(display, np->parent, width, north, rootDepth);
   gc = JXCreateGC(display, canvas, 0, NULL);

   /* Clear the window with the right color. */
   JXSetForeground(display, gc, titleColor);
   JXFillRectangle(display, canvas, gc, 0, 0, width, north);

   /* Determine how many pixels may be used for the title. */
   buttonCount = GetButtonCount(np);
   titleWidth = width - east - west - 5;
   titleWidth -= settings.titleHeight * (buttonCount + 1);

   /* Draw the top part (either a title or north border). */
   if((np->state.border & BORDER_TITLE) &&
      settings.titleHeight > settings.borderWidth) {

      const unsigned startx = west;
      const unsigned starty = 0;

      /* Draw a title bar. */
      JXSetForeground(display, gc, titleColor);
      JXFillRectangle(display, canvas, gc, 0, 1, width, settings.titleHeight - 2);

      /* Draw the icon. */
      if(np->icon && np->width >= settings.titleHeight) {
         PutIcon(np->icon, canvas, colors[borderTextColor],
                 startx + settings.titleHeight/4, starty + (settings.titleHeight - iconSize) / 2,
                 iconSize, iconSize);
	 titlexShift = iconSize + settings.titleHeight/2;
      } else {
	titlexShift = settings.titleHeight/4;
      }

      if(np->name && np->name[0] && titleWidth > 0) {
         const int sheight = GetStringHeight(FONT_BORDER);
         const unsigned titlex = startx + titlexShift;
         const unsigned titley = starty + (settings.titleHeight - sheight) / 2;
	 char *printableName = np->name;

	 /* Check for E2 80 AA (LEFT-TO-RIGHT-EMBEDDING) character
	    in the beginning and trim it (for Midori) */
	 if(strncmp(printableName, "\xe2\x80\xaa", 3) == 0) {
	   printableName += 3;
	 }

         RenderString(canvas, FONT_BORDER, borderTextColor,
                      titlex, titley, titleWidth, printableName);
      }

      DrawBorderButtons(np, canvas, gc);

   }

   /* Copy the pixmap (for the title bar) to the window. */

   /* Copy the pixmap for the title bar and clear the part of
    * the window to be drawn directly. */
   JXCopyArea(display, canvas, np->parent, gc, 1, 1,
	      width - 2, north - 1, 1, 1);
   JXClearArea(display, np->parent,
	       1, north, width - 2, height - north - 1, False);

   /* Window outline. */
   JXSetForeground(display, gc, titleColor);
   if(np->state.status & STAT_SHADED) {
     DrawRoundedRectangle(np->parent, gc, 0, 0, width - 1, north - 1,
			  settings.cornerRadius);
   } else if(np->state.maxFlags & MAX_HORIZ) {
     if(!(np->state.maxFlags & (MAX_TOP | MAX_VERT))) {
       /* Top */
       JXDrawLine(display, np->parent, gc, 0, 0, width, 0);
     }
     if(!(np->state.maxFlags & (MAX_BOTTOM | MAX_VERT))) {
       /* Bottom */
       JXDrawLine(display, np->parent, gc,
		  0, height - 1, width, height - 1);
     }
   } else if(np->state.maxFlags & MAX_VERT) {
     if(!(np->state.maxFlags & (MAX_LEFT | MAX_HORIZ))) {
       /* Left */
       JXDrawLine(display, np->parent, gc, 0, 0, 0, height);
     }
     if(!(np->state.maxFlags & (MAX_RIGHT | MAX_HORIZ))) {
       /* Right */
       JXDrawLine(display, np->parent, gc, width - 1, 0,
		  width - 1, height);
     }
   } else {
     DrawRoundedRectangle(np->parent, gc, 0, 0, width - 1, height - 1,
			  settings.cornerRadius);
   }

   JXFreePixmap(display, canvas);
   JXFreeGC(display, gc);

}

/** Determine the number of buttons to be displayed for a client. */
unsigned GetButtonCount(const ClientNode *np)
{

   int north, south, east, west;
   unsigned count;
   unsigned buttonWidth;
   int available;

   if(!(np->state.border & BORDER_TITLE)) {
      return 0;
   }
   if(settings.titleHeight <= settings.borderWidth) {
      return 0;
   }

   buttonWidth = settings.titleHeight*1.25;

   GetBorderSize(&np->state, &north, &south, &east, &west);

   count = 0;
   available = np->width - buttonWidth;
   if(available < buttonWidth) {
      return count;
   }

   if(np->state.border & BORDER_CLOSE) {
      count += 1;
      available -= buttonWidth;
      if(available < buttonWidth) {
         return count;
      }
   }

   if(np->state.border & BORDER_MAX) {
      count += 1;
      available -= buttonWidth;
      if(available < buttonWidth) {
         return count;
      }
   }

   /* Above all button. */
   count += 1;
   available -= buttonWidth;
   if(available < buttonWidth) {
     return count;
   }

   if(np->state.border & BORDER_MIN) {
      count += 1;
   }

   return count;
}

/** Draw the buttons on a client frame. */
void DrawBorderButtons(const ClientNode *np, Pixmap canvas, GC gc)
{
   long color;
   int xoffset, yoffset;
   int north, south, east, west;
   int minx;

   GetBorderSize(&np->state, &north, &south, &east, &west);
   minx = settings.titleHeight + east;

   /* Determine the colors to use. */
   if(np->state.status & (STAT_ACTIVE | STAT_FLASH)) {
      color = colors[COLOR_TITLE_ACTIVE_FG];
   } else {
      color = colors[COLOR_TITLE_FG];
   }

   /* Close button. */
   xoffset = np->width + west - settings.titleHeight*(1+1/4);
   yoffset = 0;
   if(xoffset <= minx) {
      return;
   }
   if(np->state.border & BORDER_CLOSE) {

      JXSetForeground(display, gc, color);
      DrawCloseButton(xoffset, yoffset, canvas, gc);

      xoffset -= settings.titleHeight*(1+1/4);
   }

   /* Maximize button. */
   if(xoffset <= minx) {
     return;
   }
   if(np->state.border & BORDER_MAX) {

      JXSetForeground(display, gc, color);
      if(np->state.maxFlags) {
         DrawMaxAButton(xoffset, yoffset, canvas, gc);
      } else {
         DrawMaxIButton(xoffset, yoffset, canvas, gc);
      }

      xoffset -= settings.titleHeight*(1+1/4);
   }

   /* Above all button. */
   if(xoffset <= minx) {
     return;
   }
   JXSetForeground(display, gc, color);
   if(np->state.layer == LAYER_ABOVE) {
     DrawLayerNormalButton(xoffset, yoffset, canvas, gc);
   } else {
     DrawLayerAboveButton(xoffset, yoffset, canvas, gc);
   }

   xoffset -= settings.titleHeight*(1+1/4);

   /* Minimize button. */
   if(xoffset <= minx) {
     return;
   }
   if(np->state.border & BORDER_MIN) {

      JXSetForeground(display, gc, color);
      DrawMinButton(xoffset, yoffset, canvas, gc);

   }
}

/** Attempt to draw a border icon. */
char DrawBorderIcon(BorderIconType t,
                    unsigned xoffset, unsigned yoffset,
                    Pixmap canvas)
{
   if(buttonIcons[t]) {
      ButtonNode button;
      ResetButton(&button, canvas);
      button.x       = xoffset;
      button.y       = yoffset;
      button.width   = settings.titleHeight;
      button.height  = settings.titleHeight;
      button.icon    = buttonIcons[t];
      button.fill    = 0;
      DrawButton(&button);
      return 1;
   } else {
      return 0;
   }
}

/** Draw a close button. */
void DrawCloseButton(unsigned xoffset, unsigned yoffset,
                     Pixmap canvas, GC gc)
{
   XSegment segments[2];
   unsigned size, linewidth;
   unsigned x1, y1;
   unsigned x2, y2;

   size = (settings.titleHeight + 2) / 3;
   linewidth = size / 16 + 1;
   x1 = xoffset + settings.titleHeight / 2 - size / 2;
   y1 = yoffset + settings.titleHeight / 2 - size / 2;
   x2 = x1 + size;
   y2 = y1 + size;

   segments[0].x1 = x1;
   segments[0].y1 = y1;
   segments[0].x2 = x2;
   segments[0].y2 = y2;

   segments[1].x1 = x2;
   segments[1].y1 = y1;
   segments[1].x2 = x1;
   segments[1].y2 = y2;

   JXSetLineAttributes(display, gc, linewidth, LineSolid,
                       CapProjecting, JoinBevel);
   JXDrawSegments(display, canvas, gc, segments, 2);
   JXSetLineAttributes(display, gc, 1, LineSolid,
                       CapNotLast, JoinMiter);

}

/** Draw an inactive maximize button. */
void DrawMaxIButton(unsigned xoffset, unsigned yoffset,
                    Pixmap canvas, GC gc)
{

   XSegment segments[5];
   unsigned int size, linewidth;
   unsigned int x1, y1;
   unsigned int x2, y2;

   size = 2 + (settings.titleHeight + 2) / 3;
   linewidth = size / 16 + 1;
   x1 = xoffset + settings.titleHeight / 2 - size / 2;
   y1 = yoffset + settings.titleHeight / 2 - size / 2;
   x2 = x1 + size;
   y2 = y1 + size;

   segments[0].x1 = x1;
   segments[0].y1 = y1;
   segments[0].x2 = x1 + size;
   segments[0].y2 = y1;

   segments[1].x1 = x1;
   segments[1].y1 = y1 + 1;
   segments[1].x2 = x1 + size;
   segments[1].y2 = y1 + 1;

   segments[2].x1 = x1;
   segments[2].y1 = y1;
   segments[2].x2 = x1;
   segments[2].y2 = y2;

   segments[3].x1 = x2;
   segments[3].y1 = y1;
   segments[3].x2 = x2;
   segments[3].y2 = y2;

   segments[4].x1 = x1;
   segments[4].y1 = y2;
   segments[4].x2 = x2;
   segments[4].y2 = y2;

   JXSetLineAttributes(display, gc, linewidth, LineSolid,
                       CapProjecting, JoinMiter);
   JXDrawSegments(display, canvas, gc, segments, 5);
   JXSetLineAttributes(display, gc, 1, LineSolid,
                       CapButt, JoinMiter);

}

/** Draw an active maximize button. */
void DrawMaxAButton(unsigned xoffset, unsigned yoffset,
                    Pixmap canvas, GC gc)
{
   XSegment segments[8];
   unsigned size, linewidth;
   unsigned x1, y1;
   unsigned x2, y2;
   unsigned x3, y3;

   size = 2 + (settings.titleHeight + 2) / 3;
   linewidth = size / 16 + 1;
   x1 = xoffset + settings.titleHeight / 2 - size / 2;
   y1 = yoffset + settings.titleHeight / 2 - size / 2;
   x2 = x1 + size;
   y2 = y1 + size;
   x3 = x1 + size / 2;
   y3 = y1 + size / 2;

   segments[0].x1 = x1;
   segments[0].y1 = y1;
   segments[0].x2 = x2;
   segments[0].y2 = y1;

   segments[1].x1 = x1;
   segments[1].y1 = y1 + 1;
   segments[1].x2 = x2;
   segments[1].y2 = y1 + 1;

   segments[2].x1 = x1;
   segments[2].y1 = y1;
   segments[2].x2 = x1;
   segments[2].y2 = y2;

   segments[3].x1 = x2;
   segments[3].y1 = y1;
   segments[3].x2 = x2;
   segments[3].y2 = y2;

   segments[4].x1 = x1;
   segments[4].y1 = y2;
   segments[4].x2 = x2;
   segments[4].y2 = y2;

   segments[5].x1 = x1;
   segments[5].y1 = y3;
   segments[5].x2 = x3;
   segments[5].y2 = y3;

   segments[6].x1 = x1;
   segments[6].y1 = y3 + 1;
   segments[6].x2 = x3;
   segments[6].y2 = y3 + 1;

   segments[7].x1 = x3;
   segments[7].y1 = y3;
   segments[7].x2 = x3;
   segments[7].y2 = y2;

   JXSetLineAttributes(display, gc, linewidth, LineSolid,
                       CapProjecting, JoinMiter);
   JXDrawSegments(display, canvas, gc, segments, 8);
   JXSetLineAttributes(display, gc, 1, LineSolid,
                       CapButt, JoinMiter);
}

/** Draw Above all button (switch to above layer). */
void DrawLayerAboveButton(unsigned xoffset, unsigned yoffset,
                    Pixmap canvas, GC gc)
{
   XSegment segments[4];
   unsigned size, linewidth;
   unsigned x1, y1;
   unsigned x2, y2;
   unsigned x3, y3;

   size = 2 + (settings.titleHeight + 2) / 3;
   linewidth = size / 16 + 1;
   x1 = xoffset + settings.titleHeight / 2 - size / 2;
   y1 = yoffset + settings.titleHeight / 2 - size / 2;
   x2 = x1 + size;
   y2 = y1 + size;
   x3 = x1 + size / 2;
   y3 = y1 + size / 2;

   segments[0].x1 = x1;
   segments[0].y1 = y3;
   segments[0].x2 = x3;
   segments[0].y2 = y1;

   segments[1].x1 = x3;
   segments[1].y1 = y1;
   segments[1].x2 = x2;
   segments[1].y2 = y3;

   segments[2].x1 = x2;
   segments[2].y1 = y3;
   segments[2].x2 = x3;
   segments[2].y2 = y2;

   segments[3].x1 = x3;
   segments[3].y1 = y2;
   segments[3].x2 = x1;
   segments[3].y2 = y3;

   JXSetLineAttributes(display, gc, linewidth, LineSolid,
                       CapProjecting, JoinMiter);
   JXDrawSegments(display, canvas, gc, segments, 4);
   JXSetLineAttributes(display, gc, 1, LineSolid,
                       CapButt, JoinMiter);
}

/** Draw Above all button (switch to normal layer). */
void DrawLayerNormalButton(unsigned xoffset, unsigned yoffset,
                    Pixmap canvas, GC gc)
{
   XSegment segments[3];
   unsigned size, linewidth;
   unsigned x1, y1;
   unsigned x2, y2;
   unsigned x3, y3;

   size = 2 + (settings.titleHeight + 2) / 3;
   linewidth = size / 16 + 1;
   x1 = xoffset + settings.titleHeight / 2 - size / 2;
   y1 = yoffset + settings.titleHeight / 2 - size / 2;
   x2 = x1 + size;
   y2 = y1 + size;
   x3 = x1 + size / 2;
   y3 = y1 + size / 2;

   segments[0].x1 = x1;
   segments[0].y1 = y1;
   segments[0].x2 = x2;
   segments[0].y2 = y1;

   segments[1].x1 = x2;
   segments[1].y1 = y1;
   segments[1].x2 = x3;
   segments[1].y2 = y2;

   segments[2].x1 = x3;
   segments[2].y1 = y2;
   segments[2].x2 = x1;
   segments[2].y2 = y1;

   JXSetLineAttributes(display, gc, linewidth, LineSolid,
                       CapProjecting, JoinMiter);
   JXDrawSegments(display, canvas, gc, segments, 3);
   JXSetLineAttributes(display, gc, 1, LineSolid,
                       CapButt, JoinMiter);
}

/** Draw a minimize button. */
void DrawMinButton(unsigned xoffset, unsigned yoffset,
                   Pixmap canvas, GC gc)
{

   unsigned int size, linewidth;
   unsigned int x1, y1;
   unsigned int x2, y2;

   size = (settings.titleHeight + 2) / 3;
   linewidth = size / 16 + 1;
   x1 = xoffset + settings.titleHeight / 2 - size / 2;
   y1 = yoffset + settings.titleHeight / 2 - size / 2;
   x2 = x1 + size;
   y2 = y1 + size;
   JXSetLineAttributes(display, gc, linewidth, LineSolid,
                       CapProjecting, JoinMiter);
   JXDrawLine(display, canvas, gc, x1, y2, x2, y2);
   JXSetLineAttributes(display, gc, 1, LineSolid, CapButt, JoinMiter);

}

/** Redraw the borders on the current desktop.
 * This should be done after loading clients since the stacking order
 * may cause borders on the current desktop to become visible after moving
 * clients to their assigned desktops.
 */
void ExposeCurrentDesktop(void)
{

   ClientNode *np;
   int layer;

   for(layer = 0; layer < LAYER_COUNT; layer++) {
      for(np = nodes[layer]; np; np = np->next) {
         if(!(np->state.status & (STAT_HIDDEN | STAT_MINIMIZED))) {
            DrawBorder(np);
         }
      }
   }

}

/** Get the size of the borders for a client. */
void GetBorderSize(const ClientState *state,
                   int *north, int *south, int *east, int *west)
{

   Assert(state);
   Assert(north);
   Assert(south);
   Assert(east);
   Assert(west);

   /* Full screen is a special case. */
   if(state->status & STAT_FULLSCREEN) {
      *north = 0;
      *south = 0;
      *east = 0;
      *west = 0;
      return;
   }

   if(state->border & BORDER_OUTLINE) {

      if(state->border & BORDER_TITLE) {
         *north = settings.titleHeight;
      } else {
         *north = 0;
      }
      if(state->maxFlags & MAX_VERT) {
         *south = 0;
      } else {
	if(state->status & STAT_SHADED) {
	  *south = 0;
	} else {
	  *south = settings.borderWidth;
	}
      }

      if(state->maxFlags & MAX_HORIZ) {
         *east = 0;
         *west = 0;
      } else {
         *east = settings.borderWidth;
         *west = settings.borderWidth;
      }

   } else {

      *north = 0;
      *south = 0;
      *east = 0;
      *west = 0;

   }
}

/** Draw a rounded rectangle. */
void DrawRoundedRectangle(Drawable d, GC gc, int x, int y,
                          int width, int height, int radius)
{
#ifdef USE_SHAPE
#ifdef USE_XMU

   if(radius > 0) {
      XmuDrawRoundedRectangle(display, d, gc, x, y, width, height,
                              radius, radius);
   } else {
      JXDrawRectangle(display, d, gc, x, y, width, height);
   }

#else

   if(radius > 0) {
      XSegment segments[4];
      XArc     arcs[4];

      segments[0].x1 = x + radius;         segments[0].y1 = y;
      segments[0].x2 = x + width - radius; segments[0].y2 = y;
      segments[1].x1 = x + radius;         segments[1].y1 = y + height;
      segments[1].x2 = x + width - radius; segments[1].y2 = y + height;
      segments[2].x1 = x;                  segments[2].y1 = y + radius;
      segments[2].x2 = x;                  segments[2].y2 = y + height - radius;
      segments[3].x1 = x + width;          segments[3].y1 = y + radius;
      segments[3].x2 = x + width;          segments[3].y2 = y + height - radius;
      JXDrawSegments(display, d, gc, segments, 4);

      arcs[0].x = x;
      arcs[0].y = y;
      arcs[0].width = radius * 2;
      arcs[0].height = radius * 2;
      arcs[0].angle1 = 90 * 64;
      arcs[0].angle2 = 90 * 64;
      arcs[1].x = x + width - radius * 2;
      arcs[1].y = y;
      arcs[1].width  = radius * 2;
      arcs[1].height = radius * 2;
      arcs[1].angle1 = 0 * 64;
      arcs[1].angle2 = 90 * 64;
      arcs[2].x = x;
      arcs[2].y = y + height - radius * 2;
      arcs[2].width  = radius * 2;
      arcs[2].height = radius * 2;
      arcs[2].angle1 = 180 * 64;
      arcs[2].angle2 = 90 * 64;
      arcs[3].x = x + width - radius * 2;
      arcs[3].y = y + height - radius * 2;
      arcs[3].width  = radius * 2;
      arcs[3].height = radius * 2;
      arcs[3].angle1 = 270 * 64;
      arcs[3].angle2 = 90 * 64;
      JXDrawArcs(display, d, gc, arcs, 4);
   } else {
      JXDrawRectangle(display, d, gc, x, y, width, height);
   }

#endif
#else

   JXDrawRectangle(display, d, gc, x, y, width, height);

#endif
}

/** Fill a rounded rectangle. */
#ifdef USE_SHAPE
void FillRoundedRectangle(Drawable d, GC gc, int x, int y,
                          int width, int height, int radius)
{

#ifdef USE_XMU

   XmuFillRoundedRectangle(display, d, gc, x, y, width, height,
                           radius, radius);

#else

   XRectangle  rects[3];
   XArc        arcs[4];

   rects[0].x = x + radius;
   rects[0].y = y;
   rects[0].width = width - radius * 2;
   rects[0].height = radius;
   rects[1].x = x;
   rects[1].y = radius;
   rects[1].width = width;
   rects[1].height = height - radius * 2;
   rects[2].x = x + radius;
   rects[2].y = y + height - radius;
   rects[2].width = width - radius * 2;
   rects[2].height = radius;
   JXFillRectangles(display, d, gc, rects, 3);

   arcs[0].x = x;
   arcs[0].y = y;
   arcs[0].width = radius * 2;
   arcs[0].height = radius * 2;
   arcs[0].angle1 = 90 * 64;
   arcs[0].angle2 = 90 * 64;
   arcs[1].x = x + width - radius * 2 - 1;
   arcs[1].y = y;
   arcs[1].width  = radius * 2;
   arcs[1].height = radius * 2;
   arcs[1].angle1 = 0 * 64;
   arcs[1].angle2 = 90 * 64;
   arcs[2].x = x;
   arcs[2].y = y + height - radius * 2 - 1;
   arcs[2].width  = radius * 2;
   arcs[2].height = radius * 2;
   arcs[2].angle1 = 180 * 64;
   arcs[2].angle2 = 90 * 64;
   arcs[3].x = x + width - radius * 2 - 1;
   arcs[3].y = y + height - radius * 2 -1;
   arcs[3].width  = radius * 2;
   arcs[3].height = radius * 2;
   arcs[3].angle1 = 270 * 64;
   arcs[3].angle2 = 90 * 64;
   JXFillArcs(display, d, gc, arcs, 4);

#endif

}
#endif

/** Set the icon to use for a button. */
void SetBorderIcon(BorderIconType t, const char *name)
{
   if(buttonNames[t]) {
      Release(buttonNames[t]);
   }
   buttonNames[t] = CopyString(name);
}


text:
<?php

namespace Craft;

/**
 * Class MigrationManagerHelper
 */
class MigrationManagerHelper
{
    /**
     * @param $id
     *
     * @return bool|AssetTransformModel
     */
    public static function getTransformById($id)
    {
        $transforms = craft()->assetTransforms->getAllTransforms();
        foreach ($transforms as $key => $transform) {
            if ($transform->id == $id) {
                return $transform;
            }
        }

        return false;
    }

    /**
     * @param int $id
     *
     * @return bool|AssetSourceModel
     */
    public static function getAssetSourceByFolderId($id)
    {
        $folder = craft()->assets->getFolderById($id);
        if ($folder) {
            $source = craft()->assetSources->getSourceById($folder->sourceId);
            if ($source) {
                return $source;
            }
        }

        return false;
    }

    /**
     * @param string $handle
     *
     * @return bool|AssetTransformModel
     */
    public static function getAssetSourceByHandle($handle)
    {
        $sources = craft()->assetSources->getAllSources();
        foreach ($sources as $source) {
            if ($source->handle == $handle) {
                return $source;
            }
        }

        return false;
    }

    /**
     * @param string            $handle
     * @param string|array|null $context
     *
     * @return bool|FieldModel
     */
    public static function getFieldByHandleContext($handle, $context)
    {
        $fields = craft()->fields->getAllFields(null, $context);
        foreach ($fields as $field) {
            if ($field->handle == $handle) {
                return $field;
            }
        }

        return false;
    }

    /**
     * @param $handle
     * @param $fieldId
     *
     * @return bool|MatrixBlockTypeModel
     */
    public static function getMatrixBlockType($handle, $fieldId)
    {
        $blockTypes = craft()->matrix->getBlockTypesByFieldId($fieldId);
        foreach ($blockTypes as $block) {
            if ($block->handle == $handle) {
                return $block;
            }
        }

        return false;
    }

    /**
     * @param $handle
     * @param $fieldId
     *
     * @return bool|NeoBlockTypeModel
     */
    public static function getNeoBlockType($handle, $fieldId)
    {
        $blockTypes = craft()->neo->getBlockTypesByFieldId($fieldId);
        foreach ($blockTypes as $block) {
            if ($block->handle == $handle) {
                return $block;
            }
        }

        return false;
    }

    /**
     * @param array $element
     *
     * @return bool|BaseElementModel|null
     * @throws Exception
     */
    public static function getAssetByHandle($element)
    {
        $source = MigrationManagerHelper::getAssetSourceByHandle($element['source']);
        if ($source) {

            $folderCriteria = new FolderCriteriaModel();
            $folderCriteria->name = $element['folder'];
            $folderCriteria->sourceId = $source->id;

            $folder = craft()->assets->findFolder($folderCriteria);
            if ($folder) {

                $criteria = craft()->elements->getCriteria(ElementType::Asset);
                $criteria->sourceId = $source->id;
                $criteria->folderId = $folder->id;
                $criteria->filename = $element['filename'];

                $asset = $criteria->first();
                if ($asset) {
                    return $asset;
                }
            }
        }

        return false;
    }

    /**
     * @param array $element
     *
     * @return bool|BaseElementModel|null
     * @throws Exception
     */
    public static function getCategoryByHandle($element)
    {
        $categoryGroup = craft()->categories->getGroupByHandle($element['category']);
        if ($categoryGroup) {

            $criteria = craft()->elements->getCriteria(ElementType::Category);
            $criteria->groupId = $categoryGroup->id;
            $criteria->slug = $element['slug'];

            $category = $criteria->first();
            if ($category) {
                return $category;
            }
        }

        return false;
    }

    /**
     * @param array $element
     *
     * @return bool|BaseElementModel|null
     * @throws Exception
     */
    public static function getEntryByHandle($element)
    {
        $section = craft()->sections->getSectionByHandle($element['section']);
        if ($section) {

            $criteria = craft()->elements->getCriteria(ElementType::Entry);
            $criteria->slug = $element['slug'];
            $criteria->sectionId = $section->id;

            $entry = $criteria->first();
            if ($entry) {
                return $entry;
            }
        }

        return false;
    }

    /**
     * @param array $element
     *
     * @return bool|UserModel|null
     */
    public static function getUserByHandle($element)
    {
        $user = craft()->users->getUserByUsernameOrEmail($element['username']);
        if ($user) {
            return $user;
        }

        return false;
    }

    /**
     * @param array $element
     *
     * @return BaseElementModel|null
     * @throws Exception
     */
    public static function getTagByHandle($element)
    {
        $group = craft()->tags->getTagGroupByHandle($element['group']);
        if ($group) {

            $criteria = craft()->elements->getCriteria(ElementType::Tag);
            $criteria->groupId = $group->id;
            $criteria->slug = 'tag1';

            $tag = $criteria->first();
            if ($tag) {
                return $tag;
            }
        }
    }

    /**
     * @param array $permissions
     *
     * @return array
     */
    public static function getPermissionIds($permissions)
    {
        foreach ($permissions as &$permission) {
            //determine if permission references element, get id if it does
            if (preg_match('/(:)/', $permission)) {
                $permissionParts = explode(":", $permission);
                $element = null;

                if (preg_match('/entries|entrydrafts/', $permissionParts[0])) {
                    $element = craft()->sections->getSectionByHandle($permissionParts[1]);
                } elseif (preg_match('/assetsource/', $permissionParts[0])) {
                    $element = MigrationManagerHelper::getAssetSourceByHandle($permissionParts[1]);
                } elseif (preg_match('/categories/', $permissionParts[0])) {
                    $element = craft()->categories->getGroupByHandle($permissionParts[1]);
                }

                if ($element != null) {
                    $permission = $permissionParts[0].':'.$element->id;
                }
            }
        }

        return $permissions;
    }

    /**
     * @param array $permissions
     *
     * @return array
     */
    public static function getPermissionHandles($permissions)
    {
        foreach ($permissions as &$permission) {
            //determine if permission references element, get handle if it does
            if (preg_match('/(:\d)/', $permission)) {
                $permissionParts = explode(":", $permission);
                $element = null;

                if (preg_match('/entries|entrydrafts/', $permissionParts[0])) {
                    $element = craft()->sections->getSectionById($permissionParts[1]);
                } elseif (preg_match('/assetsource/', $permissionParts[0])) {
                    $element = craft()->assetSources->getSourceById($permissionParts[1]);
                } elseif (preg_match('/categories/', $permissionParts[0])) {
                    $element = craft()->categories->getGroupById($permissionParts[1]);
                }

                if ($element != null) {
                    $permission = $permissionParts[0].':'.$element->handle;
                }
            }
        }

        return $permissions;
    }
}

redpajama_set_name: RedPajamaGithub


text:
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';

import { AppComponent } from './app.component';
import { BigHeroDetailComponent, HeroDetailComponent } from './hero-detail.component';
import { ClickDirective, ClickDirective2 } from './click.directive';
import { HeroFormComponent } from './hero-form.component';
import { heroSwitchComponents } from './hero-switch.components';
import { SizerComponent } from './sizer.component';
import { SvgComponent } from './svg.component';

@NgModule({
  imports: [
    BrowserModule,
    FormsModule
  ],
  declarations: [
    AppComponent,
    BigHeroDetailComponent,
    HeroDetailComponent,
    HeroFormComponent,
    heroSwitchComponents,
    ClickDirective,
    ClickDirective2,
    SizerComponent,
    SvgComponent
  ],
  bootstrap: [ AppComponent ]
})
export class AppModule { }


text:
'use strict';

// Load modules
const Glue = require('glue');

// Declare internals
const internals = {};

exports.init = function (manifest, composeOptions, next) {

    Glue.compose(manifest, composeOptions, (err, server) => {

        // If there is error in composing
        if (err) {
            return next(err);
        }

        // Adding resource routes to the server
        server.route(require('./resources').routes);

        server.start((err) => {

            return next(err, server);
        });
    });
};


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>cn.ms</groupId>
		<artifactId>mconf-parent</artifactId>
		<version>1.0.0-SNAPSHOT</version>
	</parent>
	<artifactId>mconf</artifactId>

	<name>The Micro Service Conf Center</name>
	<description>The Micro Service Conf Center</description>

	<properties>
		<micro.version>1.0.0-SNAPSHOT</micro.version>

		<commons-beanutils.version>1.9.3</commons-beanutils.version>
		<commons-configuration2.version>2.1.1</commons-configuration2.version>
		<log4j2.version>2.7</log4j2.version>

		<curator.version>2.8.0</curator.version>
		<jedis.version>2.9.0</jedis.version>

		<junit.version>4.12</junit.version>
	</properties>

	<dependencies>
		<!-- The Micro Core -->
		<dependency>
			<groupId>cn.ms</groupId>
			<artifactId>micro</artifactId>
			<version>${micro.version}</version>
		</dependency>

		<!-- Third Party Dependence -->
		<dependency>
			<groupId>commons-beanutils</groupId>
			<artifactId>commons-beanutils</artifactId>
			<version>${commons-beanutils.version}</version>
		</dependency>
		<dependency>
			<groupId>org.apache.commons</groupId>
			<artifactId>commons-configuration2</artifactId>
			<version>${commons-configuration2.version}</version>
		</dependency>
		<dependency>
			<groupId>org.yaml</groupId>
			<artifactId>snakeyaml</artifactId>
			<version>1.18</version>
		</dependency>

		<!-- Log4J2 -->
		<dependency>
			<groupId>org.apache.logging.log4j</groupId>
			<artifactId>log4j-core</artifactId>
			<version>${log4j2.version}</version>
		</dependency>
		<dependency>
			<groupId>org.apache.logging.log4j</groupId>
			<artifactId>log4j-slf4j-impl</artifactId>
			<version>${log4j2.version}</version>
		</dependency>

		<!-- Redis -->
		<dependency>
			<groupId>redis.clients</groupId>
			<artifactId>jedis</artifactId>
			<version>${jedis.version}</version>
		</dependency>
		<!-- Curator -->
		<dependency>
			<groupId>org.apache.curator</groupId>
			<artifactId>curator-recipes</artifactId>
			<version>${curator.version}</version>
			<exclusions>
				<exclusion>
					<artifactId>log4j</artifactId>
					<groupId>log4j</groupId>
				</exclusion>
			</exclusions>
		</dependency>

		<!-- Test -->
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>${junit.version}</version>
			<scope>test</scope>
		</dependency>
	</dependencies>

</project>


text:
<?php

namespace Ivory\Tests\HttpAdapter\Event\Subscriber;

use Ivory\HttpAdapter\Event\Subscriber\AbstractTimerSubscriber;
use Ivory\HttpAdapter\Event\Timer\TimerInterface;

/**
 * @author GeLo <geloen.eric@gmail.com>
 */
class TimerSubscriberTest extends AbstractSubscriberTest
{
    /**
     * @var AbstractTimerSubscriber|\PHPUnit_Framework_MockObject_MockObject
     */
    private $timerSubscriber;

    /**
     * @var TimerInterface|\PHPUnit_Framework_MockObject_MockObject
     */
    private $timer;

    /**
     * {@inheritdoc}
     */
    protected function setUp()
    {
        $this->timerSubscriber = $this->createTimerSubscriberMockBuilder()
            ->setConstructorArgs([$this->timer = $this->createTimerMock()])
            ->getMockForAbstractClass();
    }

    public function testDefaultState()
    {
        $this->timerSubscriber = $this->createTimerSubscriberMockBuilder()->getMockForAbstractClass();

        $this->assertInstanceOf('Ivory\HttpAdapter\Event\Timer\Timer', $this->timerSubscriber->getTimer());
    }

    public function testInitialState()
    {
        $this->assertSame($this->timer, $this->timerSubscriber->getTimer());
    }

    /**
     * @return AbstractTimerSubscriber|\PHPUnit_Framework_MockObject_MockObject
     */
    private function createTimerSubscriberMockBuilder()
    {
        return $this->getMockBuilder('Ivory\HttpAdapter\Event\Subscriber\AbstractTimerSubscriber');
    }

    /**
     * @return TimerInterface|\PHPUnit_Framework_MockObject_MockObject
     */
    private function createTimerMock()
    {
        return $this->createMock('Ivory\HttpAdapter\Event\Timer\TimerInterface');
    }
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
    <title>Statistics of Animacy in UD_Armenian-BSUT</title>
    <link rel="root" href=""/>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css">
    <link rel="stylesheet" type="text/css" href="../../css/jquery-ui-redmond.css"/>
    <link rel="stylesheet" type="text/css" href="../../css/style.css"/>
    <link rel="stylesheet" type="text/css" href="../../css/style-vis.css"/>
    <link rel="stylesheet" type="text/css" href="../../css/hint.css"/>

          home

          edit page
          issue tracker

          <gcse:search></gcse:search>

        This page pertains to UD version 2.

            It appears that you have Javascript disabled.
            Please consider enabling Javascript for this page to see the visualizations.

Treebank Statistics: UD_Armenian-BSUT: Features: Animacy

This feature is universal but the values Hum are language-specific.
It occurs with 2 different values: Hum, Nhum.

12787 tokens (31%) have a non-empty value of Animacy.
6677 types (60%) occur at least once with a non-empty value of Animacy.
3371 lemmas (54%) occur at least once with a non-empty value of Animacy.
The feature is used with 2 part-of-speech tags: <tt>NOUN</tt> (10980; 26% instances), <tt>PROPN</tt> (1807; 4% instances).

NOUN

10980 <tt>NOUN</tt> tokens (100% of all NOUN tokens) have a non-empty value of Animacy.

The most frequent other feature values with which NOUN and Animacy co-occurred: <tt>Definite</tt><tt>=Ind</tt> (7740; 70%), <tt>Number</tt><tt>=Sing</tt> (7257; 66%).

NOUN tokens may have the following values of Animacy:

Hum (1612; 15% of non-empty Animacy): ժողովրդի, վարչապետի, տեր, հայ, Սարյանը, մարդկանց, Վարպետը, վարպետի, մարդիկ, անձանց

Nhum (9368; 85% of non-empty Animacy): հանրապետության, ի, թվականի, կառավարության, ին, բան, անգամ, ը, տարի, ընկերության

Paradigm ը	<tt>Nhum</tt>	<tt>Hum</tt>

<tt><tt>Case</tt><tt>=Abl</tt>|<tt>Definite</tt><tt>=Ind</tt>|<tt>Number</tt><tt>=Sing</tt></tt>	ից

<tt><tt>Case</tt><tt>=Dat</tt>|<tt>Definite</tt><tt>=Def</tt>|<tt>Number</tt><tt>=Sing</tt></tt>	ին

<tt><tt>Case</tt><tt>=Dat</tt>|<tt>Definite</tt><tt>=Ind</tt>|<tt>Number</tt><tt>=Sing</tt></tt>	ի

<tt><tt>Case</tt><tt>=Dat</tt>|<tt>Definite</tt><tt>=Ind</tt>|<tt>Number</tt><tt>=Plur</tt></tt>	ների

<tt><tt>Case</tt><tt>=Ins</tt>|<tt>Definite</tt><tt>=Ind</tt>|<tt>Number</tt><tt>=Sing</tt></tt>	ով

<tt><tt>Case</tt><tt>=Loc</tt>|<tt>Definite</tt><tt>=Ind</tt>|<tt>Number</tt><tt>=Sing</tt></tt>	ում

<tt><tt>Case</tt><tt>=Nom</tt>|<tt>Definite</tt><tt>=Def</tt>|<tt>Number</tt><tt>=Sing</tt></tt>	ը, ն	ը, ն

<tt><tt>Case</tt><tt>=Nom</tt>|<tt>Definite</tt><tt>=Ind</tt>|<tt>Number</tt><tt>=Plur</tt></tt>	ներ

Animacy seems to be lexical feature of NOUN. 99% lemmas (2750) occur only with one value of Animacy.

PROPN

1807 <tt>PROPN</tt> tokens (100% of all PROPN tokens) have a non-empty value of Animacy.

The most frequent other feature values with which PROPN and Animacy co-occurred: <tt>Number</tt><tt>=Sing</tt> (1792; 99%), <tt>Definite</tt><tt>=Ind</tt> (1364; 75%), <tt>Case</tt><tt>=Nom</tt> (953; 53%).

PROPN tokens may have the following values of Animacy:

Hum (958; 53% of non-empty Animacy): Ջիվանին, Կարինե, Փաշինյանը, Նիկոլ, Նվարդին, Սարյանի, Փաշինյանի, Լևոն, Արտակը, Ղազարոս

Nhum (849; 47% of non-empty Animacy): Հայաստանի, ՀՀ, Հայաստանում, Արցախի, Խոսրովի, Ռուսաստանի, Ադրբեջանի, Իրանի, Հայաստան, Թուրքիայի

Paradigm Սարյան	<tt>Nhum</tt>	<tt>Hum</tt>

<tt><tt>Case</tt><tt>=Dat</tt>|<tt>Definite</tt><tt>=Def</tt>|<tt>NameType</tt><tt>=Sur</tt>|<tt>Number</tt><tt>=Sing</tt></tt>		Սարյանին

<tt><tt>Case</tt><tt>=Dat</tt>|<tt>Definite</tt><tt>=Def</tt>|<tt>NameType</tt><tt>=Sur</tt>|<tt>Number</tt><tt>=Plur</tt></tt>		Սարյաններին

<tt><tt>Case</tt><tt>=Dat</tt>|<tt>Definite</tt><tt>=Ind</tt>|<tt>NameType</tt><tt>=Sur</tt>|<tt>Number</tt><tt>=Sing</tt></tt>		Սարյանի

<tt><tt>Case</tt><tt>=Dat</tt>|<tt>Definite</tt><tt>=Ind</tt>|<tt>NameType</tt><tt>=Sur</tt>|<tt>Number</tt><tt>=Plur</tt></tt>		Սարյանների

<tt><tt>Case</tt><tt>=Ins</tt>|<tt>Definite</tt><tt>=Ind</tt>|<tt>NameType</tt><tt>=Geo</tt>|<tt>Number</tt><tt>=Sing</tt></tt>	Սարյանով

<tt><tt>Case</tt><tt>=Nom</tt>|<tt>Definite</tt><tt>=Def</tt>|<tt>NameType</tt><tt>=Sur</tt>|<tt>Number</tt><tt>=Sing</tt></tt>		Սարյանն

<tt><tt>Case</tt><tt>=Nom</tt>|<tt>Definite</tt><tt>=Ind</tt>|<tt>NameType</tt><tt>=Sur</tt>|<tt>Number</tt><tt>=Sing</tt></tt>		Սարյան

Animacy seems to be lexical feature of PROPN. 99% lemmas (592) occur only with one value of Animacy.

Relations with Agreement in Animacy

The 10 most frequent relations where parent and child node agree in Animacy:
<tt>NOUN –[<tt>nmod:poss</tt>]–> NOUN</tt> (1712; 79%),
<tt>NOUN –[<tt>conj</tt>]–> NOUN</tt> (846; 95%),
<tt>NOUN –[<tt>nmod</tt>]–> NOUN</tt> (319; 90%),
<tt>NOUN –[<tt>nmod:poss</tt>]–> PROPN</tt> (304; 64%),
<tt>PROPN –[<tt>flat:name</tt>]–> PROPN</tt> (250; 100%),
<tt>NOUN –[<tt>nmod:npmod</tt>]–> NOUN</tt> (191; 80%),
<tt>NOUN –[<tt>nmod</tt>]–> PROPN</tt> (120; 80%),
<tt>PROPN –[<tt>nmod</tt>]–> NOUN</tt> (118; 100%),
<tt>PROPN –[<tt>conj</tt>]–> PROPN</tt> (109; 95%),
<tt>NOUN –[<tt>appos</tt>]–> NOUN</tt> (107; 96%).

© 2014–2021
            Universal Dependencies contributors.
            Site powered by Annodoc and brat
.


text:
"""Test win32 shortcut script
"""

from twisted.trial import unittest

import os
if os.name == 'nt':

    from twisted.python import shortcut
    import os.path
    import sys

    class ShortcutTest(unittest.TestCase):
        def testCreate(self):
            s1=shortcut.Shortcut("test_shortcut.py")
            tempname=self.mktemp() + '.lnk'
            s1.save(tempname)
            self.assert_(os.path.exists(tempname))
            sc=shortcut.open(tempname)
            self.assert_(sc.GetPath(0)[0].endswith('test_shortcut.py'))


text:
/**
 * @author mrdoob / http://mrdoob.com/
 */

THREE.VTKLoader = function () {};

THREE.VTKLoader.prototype = {

    constructor: THREE.VTKLoader,

    addEventListener: THREE.EventDispatcher.prototype.addEventListener,
    hasEventListener: THREE.EventDispatcher.prototype.hasEventListener,
    removeEventListener: THREE.EventDispatcher.prototype.removeEventListener,
    dispatchEvent: THREE.EventDispatcher.prototype.dispatchEvent,

    load: function ( url, callback ) {

        var scope = this;
        var request = new XMLHttpRequest();

        request.addEventListener( 'load', function ( event ) {

            var geometry = scope.parse( event.target.responseText );

            scope.dispatchEvent( { type: 'load', content: geometry } );

            if ( callback ) callback( geometry );

        }, false );

        request.addEventListener( 'progress', function ( event ) {

            scope.dispatchEvent( { type: 'progress', loaded: event.loaded, total: event.total } );

        }, false );

        request.addEventListener( 'error', function () {

            scope.dispatchEvent( { type: 'error', message: 'Couldn\'t load URL [' + url + ']' } );

        }, false );

        request.open( 'GET', url, true );
        request.send( null );

    },

    parse: function ( data ) {

        var geometry = new THREE.Geometry();

        function vertex( x, y, z ) {

            geometry.vertices.push( new THREE.Vector3( x, y, z ) );

        }

        function face3( a, b, c ) {

            geometry.faces.push( new THREE.Face3( a, b, c ) );

        }

        function face4( a, b, c, d ) {

            geometry.faces.push( new THREE.Face4( a, b, c, d ) );

        }

        var pattern, result;

        // float float float

        pattern = /([\+|\-]?[\d]+[\.][\d|\-|e]+)[ ]+([\+|\-]?[\d]+[\.][\d|\-|e]+)[ ]+([\+|\-]?[\d]+[\.][\d|\-|e]+)/g;

        while ( ( result = pattern.exec( data ) ) != null ) {

            // ["1.0 2.0 3.0", "1.0", "2.0", "3.0"]

            vertex( parseFloat( result[ 1 ] ), parseFloat( result[ 2 ] ), parseFloat( result[ 3 ] ) );

        }

        // 3 int int int

        pattern = /3[ ]+([\d]+)[ ]+([\d]+)[ ]+([\d]+)/g;

        while ( ( result = pattern.exec( data ) ) != null ) {

            // ["3 1 2 3", "1", "2", "3"]

            face3( parseInt( result[ 1 ] ), parseInt( result[ 2 ] ), parseInt( result[ 3 ] ) );

        }

        // 4 int int int int

        pattern = /4[ ]+([\d]+)[ ]+([\d]+)[ ]+([\d]+)[ ]+([\d]+)/g;

        while ( ( result = pattern.exec( data ) ) != null ) {

            // ["4 1 2 3 4", "1", "2", "3", "4"]

            face4( parseInt( result[ 1 ] ), parseInt( result[ 2 ] ), parseInt( result[ 3 ] ), parseInt( result[ 4 ] ) );

        }

        geometry.computeCentroids();
        geometry.computeFaceNormals();
        geometry.computeVertexNormals();
        geometry.computeBoundingSphere();

        return geometry;

    }

};


text:
project = Project.create name: 'Libro Aprendiendo Ruby on Rails 4', active: true

project.tasks.create name: 'Escribir capítulo', billeable: false
project.tasks.create name: 'Escribir ejemplo', billeable: false
project.tasks.create name: 'Liberar versión', billeable: false


text:
/// Copyright (c) 2012 Ecma International.  All rights reserved.
/**
 * @path ch15/15.2/15.2.3/15.2.3.3/15.2.3.3-4-46.js
 * @description Object.getOwnPropertyDescriptor returns data desc for functions on built-ins (Array.prototype.push)
 */

function testcase() {
  var desc = Object.getOwnPropertyDescriptor(Array.prototype, "push");
  if (desc.value === Array.prototype.push &&
      desc.writable === true &&
      desc.enumerable === false &&
      desc.configurable === true) {
    return true;
  }
 }
runTestCase(testcase);


text:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cz.ascaria.network.central.messages;

import com.jme3.network.AbstractMessage;
import com.jme3.network.serializing.Serializable;
import cz.ascaria.network.central.profiles.EntityItem;
import java.util.ArrayList;

/**
 *
 * @author Ascaria Quynn
 */
@Serializable
public class EntityItemsByTypeMessage extends AbstractMessage {

    public EntityItem.Type type;

    public ArrayList<EntityItem> items;
    public String error = "[unknown]";

    public EntityItemsByTypeMessage() {
        super(true);
    }

    /**
     * User Fleet.
     * @param userProfile
     */
    public EntityItemsByTypeMessage(EntityItem.Type type) {
        super(true);
        this.type = type;
    }
}


text:
/*
 * Generated by asn1c-0.9.29 (http://lionet.info/asn1c)
 * From ASN.1 module "PKIX1Explicit88"
 * 	found in "asn1/rfc3280-PKIX1Explicit88.asn1"
 * 	`asn1c -S asn1c/skeletons -pdu=all -pdu=Certificate -fwide-types`
 */

#ifndef	_ExtensionAttribute_H_
#define	_ExtensionAttribute_H_

#include <asn_application.h>

/* Including external dependencies */
#include <NativeInteger.h>
#include <ANY.h>
#include <constr_SEQUENCE.h>

#ifdef __cplusplus
extern "C" {
#endif

/* ExtensionAttribute */
typedef struct ExtensionAttribute {
	long	 extension_attribute_type;
	ANY_t	 extension_attribute_value;

	/* Context for parsing across buffer boundaries */
	asn_struct_ctx_t _asn_ctx;
} ExtensionAttribute_t;

/* Implementation */
extern asn_TYPE_descriptor_t asn_DEF_ExtensionAttribute;
extern asn_SEQUENCE_specifics_t asn_SPC_ExtensionAttribute_specs_1;
extern asn_TYPE_member_t asn_MBR_ExtensionAttribute_1[2];

#ifdef __cplusplus
}
#endif

#endif	/* _ExtensionAttribute_H_ */
#include <asn_internal.h>


text:
package jobmanager.test;

import jobmanager.Application;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.util.ReflectionTestUtils;
import util.PiazzaLogger;

import java.lang.reflect.Method;
import java.util.concurrent.Executor;

public class ApplicationTests {

    //@Mock
    private Application application = new Application();

    /**
     * Initialize Mock objects.
     */
    @Before
    public void setup() {
        MockitoAnnotations.initMocks(this);

        ReflectionTestUtils.setField(application, "threadCountSize", 100);
        ReflectionTestUtils.setField(application, "threadCountLimit", 500);
    }

    @Test
    public void testGetAsyncExecutor() {
        Executor executor = this.application.getAsyncExecutor();

        Assert.assertNotNull(executor);
    }

    @Test
    public void testUncaughtExceptionHandler()
        throws NoSuchMethodException
    {
        AsyncUncaughtExceptionHandler handler = this.application.getAsyncUncaughtExceptionHandler();

        handler.handleUncaughtException(new Exception("test exception"), this.getClass().getMethod("testUncaughtExceptionHandler"), "Exception Param 1", "Exception Param 2");

        Assert.assertNotNull(handler);
    }
}


text:
package org.alljoyn.ioe.controlpanelservice.communication;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

import org.alljoyn.ioe.controlpanelservice.ControlPanelException;
import org.alljoyn.ioe.controlpanelservice.ui.UIElement;

import android.util.Log;

/**
 * The class includes all the required data to register/unregister signals <br>
 * Additionally the class has a logic to dispatch the received signals to be handled on the separate thread from AllJoyn
 */
public class UIWidgetSignalHandler implements InvocationHandler {
	private static final String TAG = "cpan" + UIWidgetSignalHandler.class.getSimpleName();

	/**
	  * MetadataChanged signal refreshes the {@link UIElement} object properties which it was sent for.
	  * This is done by executing {@link org.alljoyn.bus.ifaces.Properties#GetAll(String)} method.
	  * To avoid load on the AJ daemon when it receives multiple METADATA_CHANGED signals, we handle them
	  * sequentially on a separate thread by invoking {@link TaskManager#enqueue(Runnable)}.
	  * All the other signals that are just delegated to an appropriate listener will be simultaneously
	  * handled by a separate thread from the {@link TaskManager} thread pool by invoking {@link TaskManager#execute(Runnable)}
	  */
	private static final String METADATA_CHANGED = "MetadataChanged";

	/**
	 * The object path that is used as a signal source.
	 */
	 private String objPath;

	 /**
	  * The real signal handler object
	  */
	 private Object signalReceiver;

	 /**
	  * The proxy object signal handler is created based on the {@link Proxy}
	  * This is the object that actually receives signals from the daemon and its {@link InvocationHandler} dispatches
	  * the signal to be handled on the separate thread from AllJoyn.
	  * Signal handling logic is executed in the signalReceiver object
	  */
	 private Object proxySignalReceiver;

	 /**
	  * The reflection of the signal method
	  */
	 private Method method;

	 /**
	  * The interface of the signal
	  */
	 private String ifName;

	/**
	 * Constructor
	 * @param objPath The object path that is used as a signal source.
	 * @param signalReceiver The signal receiver object
	 * @param method The reflection of the signal method
	 * @param ifName The interface of the signal
	 */
	public UIWidgetSignalHandler(String objPath, Object signalReceiver, Method method, String ifName) {
		this.objPath        = objPath;
		this.signalReceiver = signalReceiver;
		this.method         = method;
		this.ifName         = ifName;
	}

	/**
	 * Registers signal handler
	 * @throws ControlPanelException
	 */
	public void register() throws ControlPanelException {

		Class<?>[] ifaceList = signalReceiver.getClass().getInterfaces();
		if ( ifaceList.length == 0 ) {
		    String msg = "Received signalReceiver object doesn't implement any interface";
            Log.e(TAG, msg);
            throw new ControlPanelException(msg);
		}

		proxySignalReceiver = createProxySignalReceiver(ifaceList);

        ConnectionManager.getInstance().registerObjectAndSetSignalHandler(
                ifName,
                method.getName(),
                method,
                proxySignalReceiver,
                objPath,
                objPath
       );
	}//register

	/**
	 * Unregisters signal handler
	 * @throws ControlPanelException
	 */
	public void unregister() throws ControlPanelException {

		Log.v(TAG, "Unregistering signal handler: '" + method.getName() + "', objPath: '" + objPath + "'");
		ConnectionManager.getInstance().unregisterSignalHandler(proxySignalReceiver, method);
		signalReceiver      = null;
		proxySignalReceiver = null;
	}//unregister

	/**
	 * Create {@link Proxy} object based on the given array of interface classes
	 * @return Created object
	 */
	private Object createProxySignalReceiver(Class<?>[] ifaceClassList) {
		return Proxy.newProxyInstance(ifaceClassList[0].getClassLoader(), ifaceClassList, this);
	}

	/**
	 * @see java.lang.reflect.InvocationHandler#invoke(java.lang.Object, java.lang.reflect.Method, java.lang.Object[])
	 */
	@Override
	public Object invoke(Object proxy, final Method method, final Object[] args) throws Throwable {

		Runnable task = new Runnable() {
			@Override
			public void run() {
				try {
					method.invoke(signalReceiver, args);
				} catch (Exception e) {
					Log.d(TAG, "Failed to invoke the method: '" + method.getName() + "', Error: '" + e.getMessage() + "'", e);
				}
			}
		};

		//Received METADATA_CHANGED signal enqueue it to be executed
		if ( METADATA_CHANGED.equals(method.getName()) ) {

			Log.d(TAG, "Received '" + METADATA_CHANGED + "' signal storing it in the queue for later execution");
			TaskManager.getInstance().enqueue(task) ;
		}
		else {

			Log.d(TAG, "Received '" + method.getName() + "' signal passing it for execution");
			TaskManager.getInstance().execute(task);
		}

		return null;
	}//invoke

}


text:
"use strict";

let _ = require("lodash");

const MAPPING_BEFORE = "^|\\s|<\\/?[\\w-]+>";
const MAPPING_AFTER = "<\\/?[\\w-]+>|\\s|$";

/*===================================================== Exports  =====================================================*/

exports.generate = generate;

/*==================================================== Functions  ====================================================*/

function RegexObject(regex) {
  this.source = regex.source;
  this.options = (regex.global ? "g" : "") + (regex.ignoreCase ? "i" : "") + (regex.multiline ? "m" : "");
}

function generate(mapping, excludes) {
  if (mapping == null) { return null; }
  let leadingRE = "";
  let leading = [], wrapped = [];
  // normalize mappings RegExp objects
  _.each(mapping.separationLeading, function (entry, key) {
    if (!_.includes(excludes, key)) { leadingRE = addLeading(leading, key, entry, leadingRE); }
  });
  _.each(mapping.separationWrapped, function (entry, key) {
    if (!_.includes(excludes, key)) { addWrapped(wrapped, key, entry); }
  });
  // generate function with maximum performance
  if (leading.length) {
    let regex = new RegExp("(?:" + MAPPING_BEFORE + ")(" + leadingRE + ")", "ig");
    let handler = genLeadingHandler(leading);
    return wrapped.length ? genLeadingAndWrapped(regex, handler, wrapped) : genLeading(regex, handler);
  } else {
    return wrapped.length ? genWrapped(wrapped) : null;
  }
}

function genLeadingHandler(leading) {
  let _len = leading.length;
  return function (text) {
    for (let i = 0; i < _len; i++) {
      let current = leading[i];
      let result = text.replace(current.regex, current.key);
      if (result !== text) { return result; }
    }
    return text;
  };
}

function genLeading(regExp, handler) { return function (text) { return text.replace(regExp, handler); }; }

function genWrapped(wrapped) {
  let _len = wrapped.length;
  return function (text) {
    for (let i = 0; i < _len; i++) {
      let current = wrapped[i];
      text = text.replace(current.regex, current.key);
    }
    return text;
  };
}

function genLeadingAndWrapped(leadingRegExp, leadingHandler, wrapped) {
  return function (text) {
    text = text.replace(leadingRegExp, leadingHandler);
    for (let i = 0; i < wrapped.length; i++) {
      let entry = wrapped[i];
      text = text.replace(entry.regex, entry.key);
    }
    return text;
  };
}

function addLeading(target, key, regexObject, leadingFullRegex) {
  if (regexObject instanceof Array) {
    _.each(regexObject, function (obj) { leadingFullRegex = addLeading(target, key, obj, leadingFullRegex); });
    return leadingFullRegex;
  }
  regexObject = new RegexObject(regexObject);

  let regexSource = "(" + regexObject.source + ")";
  let regexOptions = regexObject.options;
  if (!~regexOptions.indexOf("g")) { regexOptions += "g"; }

  target.push({regex: new RegExp(regexSource, regexOptions), key: ":" + key + "[$1]:"});

  return leadingFullRegex + (leadingFullRegex ? "|" : "") + regexObject.source;
}

function addWrapped(target, key, regexObject) {
  if (regexObject instanceof Array) {
    _.each(regexObject, function (obj) { addWrapped(target, key, obj); });
    return;
  }
  regexObject = new RegexObject(regexObject);

  let regexSource = "(" + MAPPING_BEFORE + ")(" + regexObject.source + ")(" + MAPPING_AFTER + ")";
  let regexOptions = regexObject.options;
  if (!~regexOptions.indexOf("g")) { regexOptions += "g"; }

  target.push({regex: new RegExp(regexSource, regexOptions), key: "$1:" + key + "[$2]:$3"});
}


text:
package org.apache.commons.compress.compressors.lz4;

import java.io.IOException;
import java.io.OutputStream;
import java.util.Arrays;
import java.util.Deque;
import java.util.Iterator;
import java.util.LinkedList;

import org.apache.commons.compress.compressors.CompressorOutputStream;
import org.apache.commons.compress.compressors.lz77support.LZ77Compressor;
import org.apache.commons.compress.compressors.lz77support.Parameters;
import org.apache.commons.compress.utils.ByteUtils;

/**
 * CompressorOutputStream for the LZ4 block format.
 *
 * @see LZ4 Block Format Description
 * @since 1.14
 * @NotThreadSafe
 */
public class BlockLZ4CompressorOutputStream extends CompressorOutputStream {

    private static final int MIN_BACK_REFERENCE_LENGTH = 4;
    private static final int MIN_OFFSET_OF_LAST_BACK_REFERENCE = 12;

    /*

      The LZ4 block format has a few properties that make it less
      straight-forward than one would hope:

      * literal blocks and back-references must come in pairs (except
        for the very last literal block), so consecutive literal
        blocks created by the compressor must be merged into a single
        block.

      * the start of a literal/back-reference pair contains the length
        of the back-reference (at least some part of it) so we can't
        start writing the literal before we know how long the next
        back-reference is going to be.

      * there are special rules for the final blocks

        > There are specific parsing rules to respect in order to remain
        > compatible with assumptions made by the decoder :
        >
        >     1. The last 5 bytes are always literals
        >
        >     2. The last match must start at least 12 bytes before end of
        >        block. Consequently, a block with less than 13 bytes cannot be
        >        compressed.

        which means any back-reference may need to get rewritten as a
        literal block unless we know the next block is at least of
        length 5 and the sum of this block's length and offset and the
        next block's length is at least twelve.

    */

    private final LZ77Compressor compressor;
    private final OutputStream os;

    // used in one-arg write method
    private final byte[] oneByte = new byte[1];

    private boolean finished;

    private final Deque<Pair> pairs = new LinkedList<>();
    // keeps track of the last window-size bytes (64k) in order to be
    // able to expand back-references when needed
    private final Deque<byte[]> expandedBlocks = new LinkedList<>();

    /**
     * Creates a new LZ4 output stream.
     *
     * @param os
     *            An OutputStream to read compressed data from
     */
    public BlockLZ4CompressorOutputStream(final OutputStream os) {
        this(os, createParameterBuilder().build());
    }

    /**
     * Creates a new LZ4 output stream.
     *
     * @param os
     *            An OutputStream to read compressed data from
     * @param params
     *            The parameters to use for LZ77 compression.
     */
    public BlockLZ4CompressorOutputStream(final OutputStream os, final Parameters params) {
        this.os = os;
        compressor = new LZ77Compressor(params,
            block -> {
                switch (block.getType()) {
                case LITERAL:
                    addLiteralBlock((LZ77Compressor.LiteralBlock) block);
                    break;
                case BACK_REFERENCE:
                    addBackReference((LZ77Compressor.BackReference) block);
                    break;
                case EOD:
                    writeFinalLiteralBlock();
                    break;
                }
            });
    }

    @Override
    public void write(final int b) throws IOException {
        oneByte[0] = (byte) (b & 0xff);
        write(oneByte);
    }

    @Override
    public void write(final byte[] data, final int off, final int len) throws IOException {
        compressor.compress(data, off, len);
    }

    @Override
    public void close() throws IOException {
        try {
            finish();
        } finally {
            os.close();
        }
    }

    /**
     * Compresses all remaining data and writes it to the stream,
     * doesn't close the underlying stream.
     * @throws IOException if an error occurs
     */
    public void finish() throws IOException {
        if (!finished) {
            compressor.finish();
            finished = true;
        }
    }

    /**
     * Adds some initial data to fill the window with.
     *
     * @param data the data to fill the window with.
     * @param off offset of real data into the array
     * @param len amount of data
     * @throws IllegalStateException if the stream has already started to write data
     * @see LZ77Compressor#prefill
     */
    public void prefill(final byte[] data, final int off, final int len) {
        if (len > 0) {
            final byte[] b = Arrays.copyOfRange(data, off, off + len);
            compressor.prefill(b);
            recordLiteral(b);
        }
    }

    private void addLiteralBlock(final LZ77Compressor.LiteralBlock block) throws IOException {
        final Pair last = writeBlocksAndReturnUnfinishedPair(block.getLength());
        recordLiteral(last.addLiteral(block));
        clearUnusedBlocksAndPairs();
    }

    private void addBackReference(final LZ77Compressor.BackReference block) throws IOException {
        final Pair last = writeBlocksAndReturnUnfinishedPair(block.getLength());
        last.setBackReference(block);
        recordBackReference(block);
        clearUnusedBlocksAndPairs();
    }

    private Pair writeBlocksAndReturnUnfinishedPair(final int length) throws IOException {
        writeWritablePairs(length);
        Pair last = pairs.peekLast();
        if (last == null || last.hasBackReference()) {
            last = new Pair();
            pairs.addLast(last);
        }
        return last;
    }

    private void recordLiteral(final byte[] b) {
        expandedBlocks.addFirst(b);
    }

    private void clearUnusedBlocksAndPairs() {
        clearUnusedBlocks();
        clearUnusedPairs();
    }

    private void clearUnusedBlocks() {
        int blockLengths = 0;
        int blocksToKeep = 0;
        for (final byte[] b : expandedBlocks) {
            blocksToKeep++;
            blockLengths += b.length;
            if (blockLengths >= BlockLZ4CompressorInputStream.WINDOW_SIZE) {
                break;
            }
        }
        final int size = expandedBlocks.size();
        for (int i = blocksToKeep; i < size; i++) {
            expandedBlocks.removeLast();
        }
    }

    private void recordBackReference(final LZ77Compressor.BackReference block) {
        expandedBlocks.addFirst(expand(block.getOffset(), block.getLength()));
    }

    private byte[] expand(final int offset, final int length) {
        final byte[] expanded = new byte[length];
        if (offset == 1) { // surprisingly common special case
            final byte[] block = expandedBlocks.peekFirst();
            final byte b = block[block.length - 1];
            if (b != 0) { // the fresh array contains 0s anyway
                Arrays.fill(expanded, b);
            }
        } else {
            expandFromList(expanded, offset, length);
        }
        return expanded;
    }

    private void expandFromList(final byte[] expanded, final int offset, final int length) {
        int offsetRemaining = offset;
        int lengthRemaining = length;
        int writeOffset = 0;
        while (lengthRemaining > 0) {
            // find block that contains offsetRemaining
            byte[] block = null;
            final int copyLen;
            final int copyOffset;
            if (offsetRemaining > 0) {
                int blockOffset = 0;
                for (final byte[] b : expandedBlocks) {
                    if (b.length + blockOffset >= offsetRemaining) {
                        block = b;
                        break;
                    }
                    blockOffset += b.length;
                }
                if (block == null) {
                    // should not be possible
                    throw new IllegalStateException("Failed to find a block containing offset " + offset);
                }
                copyOffset = blockOffset + block.length - offsetRemaining;
                copyLen = Math.min(lengthRemaining, block.length - copyOffset);
            } else {
                // offsetRemaining is negative or 0 and points into the expanded bytes
                block = expanded;
                copyOffset = -offsetRemaining;
                copyLen = Math.min(lengthRemaining, writeOffset + offsetRemaining);
            }
            System.arraycopy(block, copyOffset, expanded, writeOffset, copyLen);
            offsetRemaining -= copyLen;
            lengthRemaining -= copyLen;
            writeOffset += copyLen;
        }
    }

    private void clearUnusedPairs() {
        int pairLengths = 0;
        int pairsToKeep = 0;
        for (final Iterator<Pair> it = pairs.descendingIterator(); it.hasNext(); ) {
            final Pair p = it.next();
            pairsToKeep++;
            pairLengths += p.length();
            if (pairLengths >= BlockLZ4CompressorInputStream.WINDOW_SIZE) {
                break;
            }
        }
        final int size = pairs.size();
        for (int i = pairsToKeep; i < size; i++) {
            final Pair p = pairs.peekFirst();
            if (!p.hasBeenWritten()) {
                break;
            }
            pairs.removeFirst();
        }
    }

    private void writeFinalLiteralBlock() throws IOException {
        rewriteLastPairs();
        for (final Pair p : pairs) {
            if (!p.hasBeenWritten()) {
                p.writeTo(os);
            }
        }
        pairs.clear();
    }

    private void writeWritablePairs(final int lengthOfBlocksAfterLastPair) throws IOException {
        int unwrittenLength = lengthOfBlocksAfterLastPair;
        for (final Iterator<Pair> it = pairs.descendingIterator(); it.hasNext(); ) {
            final Pair p = it.next();
            if (p.hasBeenWritten()) {
                break;
            }
            unwrittenLength += p.length();
        }
        for (final Pair p : pairs) {
            if (p.hasBeenWritten()) {
                continue;
            }
            unwrittenLength -= p.length();
            if (!p.canBeWritten(unwrittenLength)) {
                break;
            }
            p.writeTo(os);
        }
    }

    private void rewriteLastPairs() {
        final LinkedList<Pair> lastPairs = new LinkedList<>();
        final LinkedList<Integer> pairLength = new LinkedList<>();
        int offset = 0;
        for (final Iterator<Pair> it = pairs.descendingIterator(); it.hasNext(); ) {
            final Pair p = it.next();
            if (p.hasBeenWritten()) {
                break;
            }
            final int len = p.length();
            pairLength.addFirst(len);
            lastPairs.addFirst(p);
            offset += len;
            if (offset >= MIN_OFFSET_OF_LAST_BACK_REFERENCE) {
                break;
            }
        }
        lastPairs.forEach(pairs::remove);
        // lastPairs may contain between one and four Pairs:
        // * the last pair may be a one byte literal
        // * all other Pairs contain a back-reference which must be four bytes long at minimum
        // we could merge them all into a single literal block but
        // this may harm compression. For example compressing
        // "bla.tar" from our tests yields a last block containing a
        // back-reference of length > 2k and we'd end up with a last
        // literal of that size rather than a 2k back-reference and a
        // 12 byte literal at the end.

        // Instead we merge all but the first of lastPairs into a new
        // literal-only Pair "replacement" and look at the
        // back-reference in the first of lastPairs and see if we can
        // split it. We can split it if it is longer than 16 -
        // replacement.length (i.e. the minimal length of four is kept
        // while making sure the last literal is at least twelve bytes
        // long). If we can't split it, we expand the first of the pairs
        // as well.

        // this is not optimal, we could get better compression
        // results with more complex approaches as the last literal
        // only needs to be five bytes long if the previous
        // back-reference has an offset big enough

        final int lastPairsSize = lastPairs.size();
        int toExpand = 0;
        for (int i = 1; i < lastPairsSize; i++) {
            toExpand += pairLength.get(i);
        }
        final Pair replacement = new Pair();
        if (toExpand > 0) {
            replacement.prependLiteral(expand(toExpand, toExpand));
        }
        final Pair splitCandidate = lastPairs.get(0);
        final int stillNeeded = MIN_OFFSET_OF_LAST_BACK_REFERENCE - toExpand;
        final int brLen = splitCandidate.hasBackReference() ? splitCandidate.backReferenceLength() : 0;
        if (splitCandidate.hasBackReference() && brLen >= MIN_BACK_REFERENCE_LENGTH + stillNeeded) {
            replacement.prependLiteral(expand(toExpand + stillNeeded, stillNeeded));
            pairs.add(splitCandidate.splitWithNewBackReferenceLengthOf(brLen - stillNeeded));
        } else {
            if (splitCandidate.hasBackReference()) {
                replacement.prependLiteral(expand(toExpand + brLen, brLen));
            }
            splitCandidate.prependTo(replacement);
        }
        pairs.add(replacement);
    }

    /**
     * Returns a builder correctly configured for the LZ4 algorithm.
     * @return a builder correctly configured for the LZ4 algorithm
     */
    public static Parameters.Builder createParameterBuilder() {
        final int maxLen = BlockLZ4CompressorInputStream.WINDOW_SIZE - 1;
        return Parameters.builder(BlockLZ4CompressorInputStream.WINDOW_SIZE)
            .withMinBackReferenceLength(MIN_BACK_REFERENCE_LENGTH)
            .withMaxBackReferenceLength(maxLen)
            .withMaxOffset(maxLen)
            .withMaxLiteralLength(maxLen);
    }

    final static class Pair {
        private final Deque<byte[]> literals = new LinkedList<>();
        private int brOffset, brLength;
        private boolean written;

        private void prependLiteral(final byte[] data) {
            literals.addFirst(data);
        }

        byte[] addLiteral(final LZ77Compressor.LiteralBlock block) {
            final byte[] copy = Arrays.copyOfRange(block.getData(), block.getOffset(),
                block.getOffset() + block.getLength());
            literals.add(copy);
            return copy;
        }

        void setBackReference(final LZ77Compressor.BackReference block) {
            if (hasBackReference()) {
                throw new IllegalStateException();
            }
            brOffset = block.getOffset();
            brLength = block.getLength();
        }

        boolean hasBackReference() {
            return brOffset > 0;
        }

        boolean canBeWritten(final int lengthOfBlocksAfterThisPair) {
            return hasBackReference()
                && lengthOfBlocksAfterThisPair >= MIN_OFFSET_OF_LAST_BACK_REFERENCE + MIN_BACK_REFERENCE_LENGTH;
        }

        int length() {
            return literalLength() + brLength;
        }

        private boolean hasBeenWritten() {
            return written;
        }

        void writeTo(final OutputStream out) throws IOException {
            final int litLength = literalLength();
            out.write(lengths(litLength, brLength));
            if (litLength >= BlockLZ4CompressorInputStream.BACK_REFERENCE_SIZE_MASK) {
                writeLength(litLength - BlockLZ4CompressorInputStream.BACK_REFERENCE_SIZE_MASK, out);
            }
            for (final byte[] b : literals) {
                out.write(b);
            }
            if (hasBackReference()) {
                ByteUtils.toLittleEndian(out, brOffset, 2);
                if (brLength - MIN_BACK_REFERENCE_LENGTH >= BlockLZ4CompressorInputStream.BACK_REFERENCE_SIZE_MASK) {
                    writeLength(brLength - MIN_BACK_REFERENCE_LENGTH
                        - BlockLZ4CompressorInputStream.BACK_REFERENCE_SIZE_MASK, out);
                }
            }
            written = true;
        }

        private int literalLength() {
            return literals.stream().mapToInt(b -> b.length).sum();
        }

        private static int lengths(final int litLength, final int brLength) {
            final int l = Math.min(litLength, 15);
            final int br = brLength < 4 ? 0 : (brLength < 19 ? brLength - 4 : 15);
            return (l << BlockLZ4CompressorInputStream.SIZE_BITS) | br;
        }

        private static void writeLength(int length, final OutputStream out) throws IOException {
            while (length >= 255) {
                out.write(255);
                length -= 255;
            }
            out.write(length);
        }

        private int backReferenceLength() {
            return brLength;
        }

        private void prependTo(final Pair other) {
            final Iterator<byte[]> listBackwards = literals.descendingIterator();
            while (listBackwards.hasNext()) {
                other.prependLiteral(listBackwards.next());
            }
        }

        private Pair splitWithNewBackReferenceLengthOf(final int newBackReferenceLength) {
            final Pair p = new Pair();
            p.literals.addAll(literals);
            p.brOffset = brOffset;
            p.brLength = newBackReferenceLength;
            return p;
        }
    }
}


text:
package org.sfs.nodes;

import com.google.common.base.Optional;
import com.google.common.net.HostAndPort;
import io.vertx.core.Context;
import io.vertx.core.Handler;
import io.vertx.core.logging.Logger;
import org.sfs.Server;
import org.sfs.SfsVertx;
import org.sfs.VertxContext;
import org.sfs.elasticsearch.nodes.GetDocumentsCountForNode;
import org.sfs.filesystem.volume.VolumeManager;
import org.sfs.rx.RxHelper;
import org.sfs.rx.ToVoid;
import org.sfs.vo.TransientServiceDef;
import org.sfs.vo.TransientXFileSystem;
import rx.Observable;
import rx.Subscriber;

import java.io.IOException;
import java.nio.file.FileStore;
import java.nio.file.Path;
import java.util.List;

import static com.google.common.base.Optional.fromNullable;
import static com.google.common.base.Preconditions.checkState;
import static io.vertx.core.logging.LoggerFactory.getLogger;
import static java.lang.Runtime.getRuntime;
import static java.nio.file.Files.getFileStore;
import static org.sfs.rx.Defer.aVoid;
import static org.sfs.rx.Defer.just;
import static rx.Observable.from;

public class NodeStats {

    private static Logger LOGGER = getLogger(NodeStats.class);
    private VertxContext<Server> vertxContext;
    private boolean started = false;
    private TransientServiceDef transientServiceDef;
    private Long timerId;

    public NodeStats() {
    }

    public Observable<Void> open(VertxContext<Server> vertxContext) {
        this.vertxContext = vertxContext;
        return aVoid()
                .flatMap(aVoid -> generate(vertxContext))
                .doOnNext(aVoid -> startTimer())
                .doOnNext(aVoid -> started = true);
    }

    public Observable<Void> close(VertxContext<Server> vertxContext) {
        return aVoid()
                .doOnNext(aVoid -> started = false)
                .doOnNext(aVoid -> stopTimer())
                .onErrorResumeNext(throwable -> {
                    LOGGER.warn("Handling Exception", throwable);
                    return aVoid();
                })
                .onErrorResumeNext(throwable -> {
                    LOGGER.warn("Handling Exception", throwable);
                    return aVoid();
                })
                .doOnNext(aVoid -> {
                    transientServiceDef = null;
                });
    }

    public Observable<Void> forceUpdate(VertxContext<Server> vertxContext) {
        return generate(vertxContext);
    }

    public Optional<TransientServiceDef> getStats() {
        checkStarted();
        return fromNullable(transientServiceDef);
    }

    protected void startTimer() {
        Handler<Long> handler = new Handler<Long>() {

            Handler<Long> _this = this;

            @Override
            public void handle(Long event) {
                generate(vertxContext)
                        .subscribe(new Subscriber<Void>() {
                            @Override
                            public void onCompleted() {
                                long refreshInterval = vertxContext.verticle().nodes().getNodeStatsRefreshInterval();
                                timerId = vertxContext.vertx().setTimer(refreshInterval, _this);
                            }

                            @Override
                            public void onError(Throwable e) {
                                LOGGER.debug("Handling Exception", e);
                                long refreshInterval = vertxContext.verticle().nodes().getNodeStatsRefreshInterval();
                                timerId = vertxContext.vertx().setTimer(refreshInterval, _this);
                            }

                            @Override
                            public void onNext(Void aVoid1) {

                            }
                        });
            }
        };
        long refreshInterval = vertxContext.verticle().nodes().getNodeStatsRefreshInterval();
        timerId = vertxContext.vertx().setTimer(refreshInterval, handler);
    }

    protected void stopTimer() {
        if (timerId != null) {
            vertxContext.vertx().cancelTimer(timerId);
        }
    }

    protected void checkStarted() {
        checkState(started, "Not started");
    }

    protected Observable<Void> generate(VertxContext<Server> vertxContext) {
        NodeStats _this = this;
        SfsVertx sfsVertx = vertxContext.vertx();
        return aVoid()
                .flatMap(aVoid -> {
                    Context context = sfsVertx.getOrCreateContext();
                    return RxHelper.executeBlocking(context, sfsVertx.getBackgroundPool(), () -> {
                        try {
                            Nodes nodes = vertxContext.verticle().nodes();
                            List<HostAndPort> publishAddresses = nodes.getPublishAddresses();

                            Path workingDirectory = vertxContext.verticle().sfsFileSystem().workingDirectory();
                            FileStore fileStore = getFileStore(workingDirectory);

                            TransientXFileSystem fileSystemInfo = new TransientXFileSystem()
                                    .setDevice(fileStore.name())
                                    .setPath(workingDirectory.toString())
                                    .setTotalSpace(fileStore.getTotalSpace())
                                    .setUnallocatedSpace(fileStore.getUnallocatedSpace())
                                    .setUsableSpace(fileStore.getUsableSpace())
                                    .setType(fileStore.type())
                                    .setPartition(workingDirectory.getRoot().toString());

                            Runtime runtime = getRuntime();

                            return new TransientServiceDef(nodes.getNodeId())
                                    .setAvailableProcessors(runtime.availableProcessors())
                                    .setFreeMemory(runtime.freeMemory())
                                    .setMaxMemory(runtime.maxMemory())
                                    .setTotalMemory(runtime.totalMemory())
                                    .setDataNode(nodes.isDataNode())
                                    .setMaster(nodes.isMaster())
                                    .setFileSystem(fileSystemInfo)
                                    .setPublishAddresses(publishAddresses);

                        } catch (IOException e) {
                            throw new RuntimeException(e);
                        }
                    });
                }).flatMap(transientServiceDef -> {
                    VolumeManager volumeManager = vertxContext.verticle().nodes().volumeManager();
                    if (volumeManager != null) {
                        return from(volumeManager.volumes())
                                .map(volumeManager::get)
                                .filter(Optional::isPresent)
                                .map(Optional::get)
                                .flatMap(volume -> volume.volumeInfo(vertxContext.vertx()))
                                .toList()
                                .map(transientServiceDef::setVolumes);
                    } else {
                        return Observable.just(transientServiceDef);
                    }
                })
                .flatMap(transientServiceDef -> getDocumentCount()
                        .doOnNext(transientServiceDef::setDocumentCount)
                        .map(documentCount -> transientServiceDef))
                .doOnNext(transientServiceDef1 -> _this.transientServiceDef = transientServiceDef1)
                .map(new ToVoid<>());

    }

    protected Observable<Long> getDocumentCount() {
        boolean dataNode = vertxContext.verticle().nodes().isDataNode();
        String nodeId = vertxContext.verticle().nodes().getNodeId();
        return
                dataNode ?
                        aVoid()
                                .flatMap(new GetDocumentsCountForNode(vertxContext, nodeId))
                        : just(0L);
    }
}


text:
package dragonflylabs.gobmx;

import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;

/**
 * Created by caprinet on 10/6/14.
 */
public class BaseActivity extends FragmentActivity{

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getActionBar().setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.general_red)));
        getActionBar().setIcon(new ColorDrawable(getResources().getColor(android.R.color.transparent)));
    }

    protected void setSubtitle(int resource_string){
        getActionBar().setSubtitle(getResources().getString(resource_string));
    }

    protected void setSubtitle(String subtitle){
        getActionBar().setSubtitle(subtitle);
    }
}


text:
Nucleator Apache
==================

Nucleator Apache is a Nucleator stackset that provisions and configures a new singleton Apache instance in the specified Nucleator Cage.

The apache instance is not autoscaling.  The stackset is intended as a template for development and deployment of ad-hoc instances within Nucleator Cages that you would like to mantain using infrastructure-as-code.

To see the full list of supported options, use the command:

> nucleator apache --help


text:
package io.katharsis.resource.information;

/**
 * A builder which creates ResourceInformation instances of a specific class.
 */
public interface ResourceInformationBuilder {

	/**
	 * @param resourceClass
	 *            resource class
	 * @return true if this builder can process the provided resource class
	 */
	boolean accept(Class<?> resourceClass);

	/**
	 * @param resourceClass
	 *            resource class
	 * @return ResourceInformation for the provided resource class.
	 */
	ResourceInformation build(Class<?> resourceClass);

	public void init(ResourceInformationBuilderContext context);

	public String getResourceType(Class<?> clazz);

}


text:
package client

import (
	"net/url"

	"golang.org/x/net/context"

	"github.com/docker/docker/api/types"
)

// ContainerStart sends a request to the docker daemon to start a container.
func (cli *Client) ContainerStart(ctx context.Context, containerID string, options types.ContainerStartOptions) error {
	query := url.Values{}
	if len(options.CheckpointID) != 0 {
		query.Set("checkpoint", options.CheckpointID)
	}
	if len(options.CheckpointDir) != 0 {
		query.Set("checkpoint-dir", options.CheckpointDir)
	}

	resp, err := cli.post(ctx, "/containers/"+containerID+"/start", query, nil, nil)
	ensureReaderClosed(resp)
	return err
}


text:
@implementation OCSpecBeAKindOfMatcher

- (id)matches:(id)actual
{
	return @([[super matches:actual] isKindOfClass:NSClassFromString(self.expected)]);
}

@end


text:
package org.apache.commons.collections.iterators;

import java.util.ListIterator;
import java.util.NoSuchElementException;

import org.apache.commons.collections.ResettableListIterator;

/**
 * SingletonIterator is an {@link ListIterator} over a single
 * object instance.
 *
 * @since Commons Collections 2.1
 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $
 *
 * @author Stephen Colebourne
 * @author Rodney Waldhoff
 */
public class SingletonListIterator implements ListIterator, ResettableListIterator {

    private boolean beforeFirst = true;
    private boolean nextCalled = false;
    private boolean removed = false;
    private Object object;

    /**
     * Constructs a new SingletonListIterator.
     *
     * @param object  the single object to return from the iterator
     */
    public SingletonListIterator(Object object) {
        super();
        this.object = object;
    }

    /**
     * Is another object available from the iterator?
     *

     * This returns true if the single object hasn't been returned yet.
     *
     * @return true if the single object hasn't been returned yet
     */
    public boolean hasNext() {
        return beforeFirst && !removed;
    }

    /**
     * Is a previous object available from the iterator?
     *

     * This returns true if the single object has been returned.
     *
     * @return true if the single object has been returned
     */
    public boolean hasPrevious() {
        return !beforeFirst && !removed;
    }

    /**
     * Returns the index of the element that would be returned by a subsequent
     * call to <tt>next</tt>.
     *
     * @return 0 or 1 depending on current state.
     */
    public int nextIndex() {
        return (beforeFirst ? 0 : 1);
    }

    /**
     * Returns the index of the element that would be returned by a subsequent
     * call to <tt>previous</tt>. A return value of -1 indicates that the iterator is currently at
     * the start.
     *
     * @return 0 or -1 depending on current state.
     */
    public int previousIndex() {
        return (beforeFirst ? -1 : 0);
    }

    /**
     * Get the next object from the iterator.
     *

     * This returns the single object if it hasn't been returned yet.
     *
     * @return the single object
     * @throws NoSuchElementException if the single object has already
     *    been returned
     */
    public Object next() {
        if (!beforeFirst || removed) {
            throw new NoSuchElementException();
        }
        beforeFirst = false;
        nextCalled = true;
        return object;
    }

    /**
     * Get the previous object from the iterator.
     *

     * This returns the single object if it has been returned.
     *
     * @return the single object
     * @throws NoSuchElementException if the single object has not already
     *    been returned
     */
    public Object previous() {
        if (beforeFirst || removed) {
            throw new NoSuchElementException();
        }
        beforeFirst = true;
        return object;
    }

    /**
     * Remove the object from this iterator.
     * @throws IllegalStateException if the <tt>next</tt> or <tt>previous</tt>
     *        method has not yet been called, or the <tt>remove</tt> method
     *        has already been called after the last call to <tt>next</tt>
     *        or <tt>previous</tt>.
     */
    public void remove() {
        if(!nextCalled || removed) {
            throw new IllegalStateException();
        } else {
            object = null;
            removed = true;
        }
    }

    /**
     * Add always throws {@link UnsupportedOperationException}.
     *
     * @throws UnsupportedOperationException always
     */
    public void add(Object obj) {
        throw new UnsupportedOperationException("add() is not supported by this iterator");
    }

    /**
     * Set sets the value of the singleton.
     *
     * @param obj  the object to set
     * @throws IllegalStateException if <tt>next</tt> has not been called
     *          or the object has been removed
     */
    public void set(Object obj) {
        if (!nextCalled || removed) {
            throw new IllegalStateException();
        }
        this.object = obj;
    }

    /**
     * Reset the iterator back to the start.
     */
    public void reset() {
        beforeFirst = true;
        nextCalled = false;
    }

}