text:
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

/* For (get|set)rlimit() ... */
#include <sys/time.h>
#include <sys/resource.h>
/* ... end */
/* For (get|set)rlimit(), sleep(), and getpid() ... */
#include <unistd.h>
/* ... end */

/* For errno ... */
#include <errno.h>
/* ... end */

#include <X11/Xlib.h>
#include <X11/Intrinsic.h>
#include <X11/Shell.h>
#include <X11/Xos.h>
#include <X11/extensions/Xinerama.h>
#include "dynlist.h"
#include "drawing.h"
#include "resources.h"
#include "x11-ssh-askpass.h"

#undef MAX
#define MAX(a,b) (((a) > (b)) ? (a) : (b))

char *progname = NULL;
char *progclass = NULL;
XrmDatabase db = 0;

static char *defaults[] = {
#include "SshAskpass_ad.h"
   0
};

void outOfMemory(AppInfo *app, int line)
{
   fprintf(stderr, "%s[%ld]: Aaahhh! I ran out of memory at line %d.\n",
	   app->appName, (long) app->pid, line);
   exit(EXIT_STATUS_NO_MEMORY);
}

void freeIf(void *p)
{
   if (p) {
      free(p);
   }
}

void freeFontIf(AppInfo *app, XFontStruct *f)
{
   if (f) {
      XFreeFont(app->dpy, f);
   }
}

XFontStruct *getFontResource(AppInfo *app, char *instanceName, char *className)
{
   char *fallbackFont = "fixed";

   XFontStruct *f = NULL;
   char *s = get_string_resource(instanceName, className);
   f = XLoadQueryFont(app->dpy, (s ? s : fallbackFont));
   if (!f) {
      f = XLoadQueryFont(app->dpy, fallbackFont);
   }
   if (s) {
      free(s);
   }
   return(f);
}

char *getStringResourceWithDefault(char *instanceName, char *className,
				   char *defaultText)
{
   char *s = get_string_resource(instanceName, className);
   if (!s) {
      if (!defaultText) {
	 s = strdup("");
      } else {
	 s = strdup(defaultText);
      }
   }
   return(s);
}

unsigned int getUnsignedIntegerResource(AppInfo *app, char *instanceName,
					char *className,
					unsigned int defaultValue)
{
   int n;
   unsigned int value;
   char c;
   char *s = get_string_resource(instanceName, className);
   char *cp = s;

   if (NULL == s) {
      return(defaultValue);
   }
   while ((*cp) && isspace(*cp)) {
      /* Skip whitespace. */
      cp++;
   }
   if (*cp) {
      if (('0' == cp[0]) && cp[1]) {
	 if (('x' == cp[1]) || ('X' == cp[1])) {
	    /* Hex */
	    n = sscanf(cp + 2, "%x %c", &value, &c);
	 } else {
	    /* Octal */
	    n = sscanf(cp + 1, "%o %c", &value, &c);
	 }
	 if (1 == n) {
	    free(s);
	    return(value);
	 }
      } else {
	 /* Unsigned Decimal */
	 n = sscanf(cp, "%u %c", &value, &c);
	 if (1 == n) {
	    free(s);
	    return(value);
	 }
      }
   }
   /* If we get here, no conversion succeeded. */
   fprintf(stderr, "%s[%ld]: invalid value '%s' for %s.\n",
	   app->appName, (long) app->pid, s, instanceName);
   free(s);
   return(defaultValue);
}

/* Default resolution is 75 dots/inch.  1 in = 2.54 cm. */
#define DefaultResolution ((75 * 10000) / 254)
long getResolutionResource(AppInfo *app, char *instanceName, char *className,
			   char *defaultResolutionSpec)
{
   char units[3];
   char *s;
   int n;
   long resolution;
   unsigned int i;

   memset(units, 0, sizeof(units));
   s = getStringResourceWithDefault(instanceName, className,
				    defaultResolutionSpec);
   /* NOTE: The width of the %s format must be one less than
    * the length of the units[] array above!
    */
   n = sscanf(s, "%ld / %2s", &resolution, units);
   if (n != 2) {
      fprintf(stderr, "%s[%ld]: invalid value '%s' for %s.\n",
	      app->appName, (long) app->pid, s, instanceName);
      resolution = DefaultResolution;
   } else {
      if (resolution < 0) {
	 /* Resolution specifications should not be negative. */
	 resolution = -(resolution);
      }
      for (i = 0; i < (sizeof(units) - 1); i++) {
	 units[i] = tolower(units[i]);
      }
      if ((0 == strcmp(units, "in")) ||
	  (0 == strcmp(units, "i")) ||
	  (0 == strcmp(units, "\""))) {
	 /* dots/inch */
	 resolution = resolution * 10000 / 254;
      } else if ((0 == strcmp(units, "m")) ||
		 (0 == strcmp(units, "me"))) {
	 /* dots/meter; no conversion necessary */
	 ;
      } else {
	 /* some unit we don't recognize; cringe and stare at the floor */
	 resolution = DefaultResolution;
      }
   }
   return(resolution);
}
#undef DefaultResolution

void calcTextObjectExtents(TextObject *t, XFontStruct *font) {
   if ((!t) || (!(t->text))) {
      return;
   }
   t->textLength = strlen(t->text);
   XTextExtents(font, t->text, t->textLength, &(t->direction),
		&(t->ascent), &(t->descent), &(t->overall));
}

void calcLabelTextExtents(LabelInfo *label)
{
   TextObject *t;
   int first = 1;

   if ((!label) || (!(label->fullText)) || (!(label->font))) {
      return;
   }
   t = label->multiText;
   while (NULL != t) {
      if (first) {
         calcTextObjectExtents(t, label->font);
	 first = 0;
      } else
         calcTextObjectExtents(t, label->fixedFont);
      label->w.height += (t->ascent + t->descent);
      if (label->w.width < t->overall.width) {
	 label->w.width = t->overall.width;
      }
      t = t->next;
   }
}

void calcTotalButtonExtents(ButtonInfo *button)
{
   if (!button) {
      return;
   }
   button->w3.w.width = (button->w3.interiorWidth +
			 (2 * button->w3.shadowThickness));
   button->w3.w.width += (2 * button->w3.borderWidth);
   button->w3.w.height = (button->w3.interiorHeight +
			  (2 * button->w3.shadowThickness));
   button->w3.w.height += (2 * button->w3.borderWidth);
}

void calcButtonExtents(ButtonInfo *button)
{
   if (!button) {
      return;
   }
   calcLabelTextExtents(&(button->label));
   button->w3.interiorWidth = (button->label.w.width +
			       (2 * button->w3.horizontalSpacing));
   button->w3.interiorHeight = (button->label.w.height +
				(2 * button->w3.verticalSpacing));
   calcTotalButtonExtents(button);
}

void balanceButtonExtents(ButtonInfo *button1, ButtonInfo *button2)
{
   if ((!button1) || (!button2)) {
      return;
   }
   button1->w3.interiorWidth = button2->w3.interiorWidth =
      MAX(button1->w3.interiorWidth, button2->w3.interiorWidth);
   button1->w3.interiorHeight = button2->w3.interiorHeight =
      MAX(button1->w3.interiorHeight, button2->w3.interiorHeight);
   calcTotalButtonExtents(button1);
   calcTotalButtonExtents(button2);
}

void calcButtonLabelPosition(ButtonInfo *button)
{
   if (!button) {
      return;
   }
   button->label.w.x = button->w3.w.x +
      ((button->w3.w.width - button->label.w.width) / 2);
   button->label.w.y = button->w3.w.y +
      ((button->w3.w.height - button->label.w.height) / 2);
}

Dimension scaleXDimension(AppInfo *app, Dimension unscaled)
{
   Dimension scaled;

   if (((app->defaultXResolution < app->xResolution) &&
	((app->defaultXResolution + app->xFuzz) < app->xResolution)) ||
       ((app->xResolution < app->defaultXResolution) &&
	((app->xResolution + app->xFuzz) < app->defaultXResolution))) {
      scaled = (unscaled * app->xResolution) / app->defaultXResolution;
   } else {
      scaled = unscaled;
   }
   return(scaled);
}

Dimension scaleYDimension(AppInfo *app, Dimension unscaled)
{
   Dimension scaled;

   if (((app->defaultYResolution < app->yResolution) &&
	((app->defaultYResolution + app->yFuzz) < app->yResolution)) ||
       ((app->yResolution < app->defaultYResolution) &&
	((app->yResolution + app->yFuzz) < app->defaultYResolution))) {
      scaled = (unscaled * app->yResolution) / app->defaultYResolution;
   } else {
      scaled = unscaled;
   }
   return(scaled);
}

/* Assumes 's' is non-NULL. */
TextObject *createTextObject(AppInfo *app, char *s)
{
   TextObject *t = malloc(sizeof(*t));
   if (NULL == t) {
      outOfMemory(app, __LINE__);
   }
   memset(t, 0, sizeof(*t));
   if (('\n' == *s) || ('\0' == *s)) {
      t->text = " ";
   } else {
      t->text = s;
   }
   return(t);
}

/* Assumes 'label' object exists and is zeroed. */
void createLabel(AppInfo *app, char *text, LabelInfo *label)
{
   char *substring;
   TextObject *t;

   if ((!app) || (!text)) {
      return;
   }
   label->fullText = strdup(text);
   label->multiText = createTextObject(app, label->fullText);
   t = label->multiText;
   substring = strchr(label->fullText, '\n');
   while (NULL != substring) {
      *(substring++) = '\0';
      t->next = createTextObject(app, substring);
      if (t->next) {
	 t = t->next;
      }
      substring = strchr(substring, '\n');
   }
}

void createDialog(AppInfo *app)
{
   DialogInfo *d;
   char *labelText;

   if (app->dialog) {
      return;
   }
   d = malloc(sizeof(*d));
   if (NULL == d) {
      outOfMemory(app, __LINE__);
   }
   memset(d, 0, sizeof(*d));

   app->grabKeyboard =
      get_boolean_resource("grabKeyboard", "GrabKeyboard", True);
   app->grabPointer =
      get_boolean_resource("grabPointer", "GrabPointer", False);
   app->grabServer =
      get_boolean_resource("grabServer", "GrabServer", False);

   /* inputTimeout resource specified in seconds for easy human interface.
    * Convert to milliseconds here.
    */
   app->inputTimeout = (unsigned long) 1000 *
      getUnsignedIntegerResource(app, "inputTimeout", "InputTimeout", 0);

   app->defaultXResolution =
      getResolutionResource(app, "defaultXResolution", "DefaultXResolution",
			    "75/in");
   app->defaultYResolution =
      getResolutionResource(app, "defaultYResolution", "DefaultYResolution",
			    "75/in");
   app->xFuzz =
      getResolutionResource(app, "xResolutionFuzz", "XResolutionFuzz", "20/in");
   app->yFuzz =
      getResolutionResource(app, "yResolutionFuzz", "YResolutionFuzz", "20/in");

   d->title =
      getStringResourceWithDefault("dialog.title", "Dialog.Title",
				   "OpenSSH Authentication Passphrase Request");
   d->w3.w.foreground =
      get_pixel_resource("foreground", "Foreground",
			 app->dpy, app->colormap, app->black);
   d->w3.w.background =
      get_pixel_resource("background", "Background",
			 app->dpy, app->colormap, app->white);
   d->w3.topShadowColor =
      get_pixel_resource("topShadowColor", "TopShadowColor",
			 app->dpy, app->colormap, app->white);
   d->w3.bottomShadowColor =
      get_pixel_resource("bottomShadowColor", "BottomShadowColor",
			 app->dpy, app->colormap, app->black);
   d->w3.shadowThickness =
      get_integer_resource("shadowThickness", "ShadowThickness", 3);
   d->w3.borderColor =
      get_pixel_resource("borderColor", "BorderColor",
			 app->dpy, app->colormap, app->black);
   d->w3.borderWidth =
      get_integer_resource("borderWidth", "BorderWidth", 1);

   d->w3.horizontalSpacing = scaleXDimension(app,
      get_integer_resource("horizontalSpacing", "Spacing", 5));
   d->w3.verticalSpacing = scaleYDimension(app,
      get_integer_resource("verticalSpacing", "Spacing", 6));

   if (2 == app->argc) {
      labelText = strdup(app->argv[1]);
   } else {
      labelText =
	 getStringResourceWithDefault("dialog.label", "Dialog.Label",
				      "Please enter your authentication passphrase:");
   }
   createLabel(app, labelText, &(d->label));
   freeIf(labelText);
   d->label.font = getFontResource(app, "dialog.font", "Dialog.Font");
   d->label.fixedFont = getFontResource(app, "dialog.fixedFont",
       "Dialog.FixedFont");
   calcLabelTextExtents(&(d->label));
   d->label.w.foreground = d->w3.w.foreground;
   d->label.w.background = d->w3.w.background;

   d->okButton.w3.w.foreground =
      get_pixel_resource("okButton.foreground", "Button.Foreground",
			 app->dpy, app->colormap, app->black);
   d->okButton.w3.w.background =
      get_pixel_resource("okButton.background", "Button.Background",
			 app->dpy, app->colormap, app->white);
   d->okButton.w3.topShadowColor =
      get_pixel_resource("okButton.topShadowColor", "Button.TopShadowColor",
			 app->dpy, app->colormap, app->white);
   d->okButton.w3.bottomShadowColor =
      get_pixel_resource("okButton.bottomShadowColor",
			 "Button.BottomShadowColor",
			 app->dpy, app->colormap, app->black);
   d->okButton.w3.shadowThickness =
      get_integer_resource("okButton.shadowThickness",
			   "Button.ShadowThickness", 2);
   d->okButton.w3.borderColor =
      get_pixel_resource("okButton.borderColor", "Button.BorderColor",
			 app->dpy, app->colormap, app->black);
   d->okButton.w3.borderWidth =
      get_integer_resource("okButton.borderWidth", "Button.BorderWidth", 1);
   d->okButton.w3.horizontalSpacing = scaleXDimension(app,
      get_integer_resource("okButton.horizontalSpacing", "Button.Spacing", 4));
   d->okButton.w3.verticalSpacing = scaleYDimension(app,
      get_integer_resource("okButton.verticalSpacing", "Button.Spacing", 2));
   labelText =
      getStringResourceWithDefault("okButton.label", "Button.Label", "OK");
   createLabel(app, labelText, &(d->okButton.label));
   freeIf(labelText);
   d->okButton.label.font =
      getFontResource(app, "okButton.font", "Button.Font");
   calcButtonExtents(&(d->okButton));
   d->okButton.label.w.foreground = d->okButton.w3.w.foreground;
   d->okButton.label.w.background = d->okButton.w3.w.background;

   d->cancelButton.w3.w.foreground =
      get_pixel_resource("cancelButton.foreground", "Button.Foreground",
			 app->dpy, app->colormap, app->black);
   d->cancelButton.w3.w.background =
      get_pixel_resource("cancelButton.background", "Button.Background",
			 app->dpy, app->colormap, app->white);
   d->cancelButton.w3.topShadowColor =
      get_pixel_resource("cancelButton.topShadowColor",
			 "Button.TopShadowColor",
			 app->dpy, app->colormap, app->white);
   d->cancelButton.w3.bottomShadowColor =
      get_pixel_resource("cancelButton.bottomShadowColor",
			 "Button.BottomShadowColor",
			 app->dpy, app->colormap, app->black);
   d->cancelButton.w3.shadowThickness =
      get_integer_resource("cancelButton.shadowThickness",
			   "Button.ShadowThickness", 2);
   d->cancelButton.w3.borderColor =
      get_pixel_resource("cancelButton.borderColor", "Button.BorderColor",
			 app->dpy, app->colormap, app->black);
   d->cancelButton.w3.borderWidth =
      get_integer_resource("cancelButton.borderWidth", "Button.BorderWidth",
			   1);
   d->cancelButton.w3.horizontalSpacing = scaleXDimension(app,
      get_integer_resource("cancelButton.horizontalSpacing", "Button.Spacing",
			   4));
   d->cancelButton.w3.verticalSpacing = scaleYDimension(app,
      get_integer_resource("cancelButton.verticalSpacing", "Button.Spacing",
			   2));
   labelText =
      getStringResourceWithDefault("cancelButton.label", "Button.Label",
				   "Cancel");
   createLabel(app, labelText, &(d->cancelButton.label));
   freeIf(labelText);
   d->cancelButton.label.font =
      getFontResource(app, "cancelButton.font", "Button.Font");
   calcButtonExtents(&(d->cancelButton));
   d->cancelButton.label.w.foreground = d->cancelButton.w3.w.foreground;
   d->cancelButton.label.w.background = d->cancelButton.w3.w.background;

   balanceButtonExtents(&(d->okButton), &(d->cancelButton));

   d->indicator.w3.w.foreground =
      get_pixel_resource("indicator.foreground", "Indicator.Foreground",
			 app->dpy, app->colormap, app->black);
   d->indicator.w3.w.background =
      get_pixel_resource("indicator.background", "Indicator.Background",
			 app->dpy, app->colormap, app->white);
   d->indicator.w3.w.width = scaleXDimension(app,
      get_integer_resource("indicator.width", "Indicator.Width", 15));
   d->indicator.w3.w.height = scaleYDimension(app,
      get_integer_resource("indicator.height", "Indicator.Height", 7));
   d->indicator.w3.topShadowColor =
      get_pixel_resource("indicator.topShadowColor",
			 "Indicator.TopShadowColor",
			 app->dpy, app->colormap, app->white);
   d->indicator.w3.bottomShadowColor =
      get_pixel_resource("indicator.bottomShadowColor",
			 "Indicator.BottomShadowColor",
			 app->dpy, app->colormap, app->black);
   d->indicator.w3.shadowThickness =
      get_integer_resource("indicator.shadowThickness",
			   "Indicator.ShadowThickness", 2);
   d->indicator.w3.borderColor =
      get_pixel_resource("indicator.borderColor", "Indicator.BorderColor",
			 app->dpy, app->colormap, app->black);
   d->indicator.w3.borderWidth =
      get_integer_resource("indicator.borderWidth", "Indicator.BorderWidth",
			   0);
   d->indicator.w3.horizontalSpacing = scaleXDimension(app,
      get_integer_resource("indicator.horizontalSpacing", "Indicator.Spacing",
			   2));
   d->indicator.w3.verticalSpacing =scaleYDimension(app,
      get_integer_resource("indicator.verticalSpacing", "Indicator.Spacing",
			   4));
   d->indicator.minimumCount =
      get_integer_resource("indicator.minimumCount", "Indicator.MinimumCount",
			   8);
   d->indicator.maximumCount =
      get_integer_resource("indicator.maximumCount", "Indicator.MaximumCount",
			   24);
   d->indicator.w3.interiorWidth = d->indicator.w3.w.width;
   d->indicator.w3.interiorHeight = d->indicator.w3.w.height;
   d->indicator.w3.w.width += (2 * d->indicator.w3.shadowThickness);
   d->indicator.w3.w.width += (2 * d->indicator.w3.borderWidth);
   d->indicator.w3.w.height += (2 * d->indicator.w3.shadowThickness);
   d->indicator.w3.w.height += (2 * d->indicator.w3.borderWidth);
   {
      /* Make sure the indicators can all fit on the screen.
       * 80% of the screen width seems fine.
       */
      Dimension maxWidth = (app->screen_width * 8 / 10);
      Dimension extraSpace = ((2 * d->w3.horizontalSpacing) +
			      (2 * d->w3.shadowThickness));

      if (d->indicator.maximumCount < 8) {
	 d->indicator.maximumCount = 8;
      }
      if (((d->indicator.maximumCount * d->indicator.w3.w.width) +
	   ((d->indicator.maximumCount - 1) *
	    d->indicator.w3.horizontalSpacing) + extraSpace) > maxWidth) {
	 d->indicator.maximumCount =
	    ((maxWidth - extraSpace - d->indicator.w3.w.width) /
	     (d->indicator.w3.w.width + d->indicator.w3.horizontalSpacing))
	    + 1;
      }
      if (d->indicator.minimumCount <= 6) {
	 d->indicator.minimumCount = 6;
      }
      if (d->indicator.minimumCount > d->indicator.maximumCount) {
	 d->indicator.minimumCount = d->indicator.maximumCount;
      }
   }

   {
      /* Calculate the width and horizontal position of things. */
      Dimension labelAreaWidth;
      Dimension buttonAreaWidth;
      Dimension indicatorAreaWidth;
      Dimension extraIndicatorSpace;
      Dimension singleIndicatorSpace;
      Dimension interButtonSpace;
      Dimension w;
      Position leftX;
      int i;

      labelAreaWidth = d->label.w.width + (2 * d->w3.horizontalSpacing);
      buttonAreaWidth = ((3 * d->w3.horizontalSpacing) +
			 d->okButton.w3.w.width +
			 d->cancelButton.w3.w.width);
      w = MAX(labelAreaWidth, buttonAreaWidth);
      extraIndicatorSpace = ((2 * d->w3.horizontalSpacing) +
			     d->indicator.w3.w.width);
      singleIndicatorSpace = (d->indicator.w3.w.width +
			      d->indicator.w3.horizontalSpacing);
      d->indicator.count = ((w - extraIndicatorSpace) / singleIndicatorSpace);
      d->indicator.current = 0;
      d->indicator.count++; /* For gatepost indicator in extra space. */
      if (((w - extraIndicatorSpace) % singleIndicatorSpace) >
	  (singleIndicatorSpace / 2)) {
	 d->indicator.count++;
      }
      if (d->indicator.count < d->indicator.minimumCount) {
	 d->indicator.count = d->indicator.minimumCount;
      }
      if (d->indicator.count > d->indicator.maximumCount) {
	 d->indicator.count = d->indicator.maximumCount;
      }
      indicatorAreaWidth = ((singleIndicatorSpace * (d->indicator.count - 1)) +
			    extraIndicatorSpace);
      d->w3.interiorWidth = MAX(w, indicatorAreaWidth);
      d->w3.w.width = d->w3.interiorWidth + (2 * d->w3.shadowThickness);

      leftX = (d->w3.w.width - d->label.w.width) / 2;
      d->label.w.x = leftX;

      leftX = ((d->w3.w.width -
	       (d->indicator.count * d->indicator.w3.w.width) -
	       ((d->indicator.count - 1) * d->indicator.w3.horizontalSpacing))
	       / 2);
      {
	 int n = d->indicator.count * sizeof(IndicatorElement);
	 d->indicators = malloc(n);
	 if (NULL == d->indicators) {
	    destroyDialog(app);
	    outOfMemory(app, __LINE__);
	 }
	 memset(d->indicators, 0, n);
      }
      d->indicators[0].parent = &(d->indicator);
      d->indicators[0].w.x = d->indicator.w3.w.x = leftX;
      d->indicators[0].w.width = d->indicator.w3.w.width;
      d->indicators[0].isLit = False;
      for (i = 1; i < d->indicator.count; i++) {
	 d->indicators[i].parent = &(d->indicator);
	 d->indicators[i].w.x = (d->indicators[i - 1].w.x +
				 d->indicator.w3.w.width +
				 d->indicator.w3.horizontalSpacing);
	 d->indicators[i].w.width = d->indicator.w3.w.width;
	 d->indicators[i].isLit = False;
      }
      interButtonSpace = ((d->w3.interiorWidth - d->okButton.w3.w.width -
			   d->cancelButton.w3.w.width) / 3);
      d->okButton.w3.w.x = interButtonSpace + d->w3.shadowThickness;
      d->cancelButton.w3.w.x = (d->okButton.w3.w.x + d->okButton.w3.w.width +
				interButtonSpace);
   }
   {
      /* Calculate the height and vertical position of things. */
      int i;

      d->w3.interiorHeight = ((4 * d->w3.verticalSpacing) +
			      (2 * d->indicator.w3.verticalSpacing) +
			      d->label.w.height +
			      d->indicator.w3.w.height +
			      d->okButton.w3.w.height);
      d->w3.w.height = d->w3.interiorHeight + (2 * d->w3.shadowThickness);
      d->label.w.y = d->w3.shadowThickness + d->w3.verticalSpacing;
      d->indicator.w3.w.y = (d->label.w.y + d->label.w.height +
			     d->w3.verticalSpacing +
			     d->indicator.w3.verticalSpacing);
      for (i = 0; i < d->indicator.count; i++) {
	 d->indicators[i].w.y = d->indicator.w3.w.y;
	 d->indicators[i].w.height = d->indicator.w3.w.height;
      }
      d->okButton.w3.w.y = d->cancelButton.w3.w.y =
	 (d->indicator.w3.w.y + d->indicator.w3.w.height +
	  d->w3.verticalSpacing + d->indicator.w3.verticalSpacing);
   }
   calcButtonLabelPosition(&(d->okButton));
   calcButtonLabelPosition(&(d->cancelButton));

   d->w3.w.x = (app->screen_width - d->w3.w.width) / 2;
   d->w3.w.y = (app->screen_height - d->w3.w.height) / 3;

   app->dialog = d;
}

void destroyLabel(AppInfo *app, LabelInfo *label)
{
   TextObject *thisTextObject;
   TextObject *nextTextObject;

   thisTextObject = label->multiText;
   nextTextObject = thisTextObject->next;
   freeIf(thisTextObject);
   while (NULL != nextTextObject) {
      thisTextObject = nextTextObject;
      nextTextObject = thisTextObject->next;
      freeIf(thisTextObject);
   }
   freeIf(label->fullText);
   freeFontIf(app, label->font);
   freeFontIf(app, label->fixedFont);
}

void destroyDialog(AppInfo *app)
{
   DialogInfo *d = app->dialog;

   freeIf(d->title);
   freeIf(d->indicators);

   destroyLabel(app, &(d->label));
   destroyLabel(app, &(d->okButton.label));
   destroyLabel(app, &(d->cancelButton.label));

   XFree(d->sizeHints);
   XFree(d->wmHints);
   XFree(d->classHints);
   XFree(d->windowName.value);

   freeIf(d);
}

void createDialogWindow(AppInfo *app)
{
   XSetWindowAttributes attr;
   unsigned long attrMask = 0;
   DialogInfo *d = app->dialog;

   attr.background_pixel = d->w3.w.background;
   attrMask |= CWBackPixel;
   attr.border_pixel = d->w3.borderColor;
   attrMask |= CWBorderPixel;
   attr.cursor = None;
   attrMask |= CWCursor;
   attr.event_mask = app->eventMask;
   attrMask |= CWEventMask;

   d->dialogWindow = XCreateWindow(app->dpy, app->rootWindow,
				   d->w3.w.x, d->w3.w.y,
				   d->w3.w.width, d->w3.w.height,
				   d->w3.borderWidth,
				   DefaultDepthOfScreen(app->screen),
				   InputOutput,
				   DefaultVisualOfScreen(app->screen),
				   attrMask, &attr);

   d->sizeHints = XAllocSizeHints();
   if (!(d->sizeHints)) {
      destroyDialog(app);
      outOfMemory(app, __LINE__);
   }
   d->sizeHints->flags = 0;
   d->sizeHints->flags |= PPosition;
   d->sizeHints->flags |= PSize;
   d->sizeHints->min_width = d->w3.w.width;
   d->sizeHints->min_height = d->w3.w.height;
   d->sizeHints->flags |= PMinSize;
   d->sizeHints->max_width = d->w3.w.width;
   d->sizeHints->max_height = d->w3.w.height;
   d->sizeHints->flags |= PMaxSize;
   d->sizeHints->base_width = d->w3.w.width;
   d->sizeHints->base_height = d->w3.w.height;
   d->sizeHints->flags |= PBaseSize;

   d->wmHints = XAllocWMHints();
   if (!(d->wmHints)) {
      destroyDialog(app);
      outOfMemory(app, __LINE__);
   }
   d->wmHints->flags = 0;
   d->wmHints->input = True;
   d->wmHints->flags |= InputHint;
   d->wmHints->initial_state = NormalState;
   d->wmHints->flags |= StateHint;

   d->classHints = XAllocClassHint();
   if (!(d->classHints)) {
      destroyDialog(app);
      outOfMemory(app, __LINE__);
   }
   d->classHints->res_name = app->appName;
   d->classHints->res_class = app->appClass;

   if (!XStringListToTextProperty(&(d->title), 1, &(d->windowName))) {
      destroyDialog(app);
      outOfMemory(app, __LINE__);
   }
   XSetWMProperties(app->dpy, d->dialogWindow, &(d->windowName), NULL,
		    app->argv, app->argc, d->sizeHints,
		    d->wmHints, d->classHints);
   XSetTransientForHint(app->dpy, d->dialogWindow, d->dialogWindow);

   app->wmDeleteWindowAtom = XInternAtom(app->dpy, "WM_DELETE_WINDOW", False);
   XSetWMProtocols(app->dpy, d->dialogWindow, &(app->wmDeleteWindowAtom), 1);
}

void createGCs(AppInfo *app)
{
   DialogInfo *d = app->dialog;

   XGCValues gcv;
   unsigned long gcvMask;

   gcvMask = 0;
   gcv.foreground = d->w3.w.background;
   gcvMask |= GCForeground;
   gcv.fill_style = FillSolid;
   gcvMask |= GCFillStyle;
   app->fillGC = XCreateGC(app->dpy, app->rootWindow, gcvMask, &gcv);

   gcvMask = 0;
   gcv.foreground = d->w3.borderColor;
   gcvMask |= GCForeground;
   gcv.line_width = d->w3.borderWidth;
   gcvMask |= GCLineWidth;
   gcv.line_style = LineSolid;
   gcvMask |= GCLineStyle;
   gcv.cap_style = CapButt;
   gcvMask |= GCCapStyle;
   gcv.join_style = JoinMiter;
   gcvMask |= GCJoinStyle;
   app->borderGC = XCreateGC(app->dpy, app->rootWindow, gcvMask, &gcv);

   gcvMask = 0;
   gcv.foreground = d->label.w.foreground;
   gcvMask |= GCForeground;
   gcv.background = d->label.w.background;
   gcvMask |= GCBackground;
   gcv.font = d->label.font->fid;
   gcvMask |= GCFont;
   app->textGC = XCreateGC(app->dpy, app->rootWindow, gcvMask, &gcv);

   gcvMask = 0;
   gcv.foreground = d->indicator.w3.w.foreground;
   gcvMask |= GCForeground;
   gcv.fill_style = FillSolid;
   gcvMask |= GCFillStyle;
   app->brightGC = XCreateGC(app->dpy, app->rootWindow, gcvMask, &gcv);

   gcvMask = 0;
   gcv.foreground = d->indicator.w3.w.background;
   gcvMask |= GCForeground;
   gcv.fill_style = FillSolid;
   gcvMask |= GCFillStyle;
   app->dimGC = XCreateGC(app->dpy, app->rootWindow, gcvMask, &gcv);
}

void destroyGCs(AppInfo *app)
{
   XFreeGC(app->dpy, app->fillGC);
   XFreeGC(app->dpy, app->borderGC);
   XFreeGC(app->dpy, app->textGC);
   XFreeGC(app->dpy, app->brightGC);
   XFreeGC(app->dpy, app->dimGC);
}

void paintLabel(AppInfo *app, Drawable draw, LabelInfo label)
{
   TextObject *t;
   Position x;
   Position y;
   int first = 1;

   if (!(label.fullText)) {
      return;
   }
   XSetForeground(app->dpy, app->textGC, label.w.foreground);
   XSetBackground(app->dpy, app->textGC, label.w.background);
   XSetFont(app->dpy, app->textGC, label.font->fid);

   t = label.multiText;
   x = label.w.x;
   y = label.w.y + t->ascent;
   while (NULL != t) {
      if (!first)
	 XSetFont(app->dpy, app->textGC, label.fixedFont->fid);
      else
	 first = 0;

      if (t->text) {
	 XDrawString(app->dpy, draw, app->textGC, x, y, t->text,
		     t->textLength);
      }
      y += t->descent;
      t = t->next;
      if (t) {
	 y += t->ascent;
      }
   }
}

void paintButton(AppInfo *app, Drawable draw, ButtonInfo button)
{
   Position x;
   Position y;
   Dimension width;
   Dimension height;

   if (button.w3.borderWidth > 0) {
      XSetForeground(app->dpy, app->borderGC, button.w3.borderColor);
      XFillRectangle(app->dpy, draw, app->borderGC, button.w3.w.x,
		     button.w3.w.y, button.w3.w.width, button.w3.w.height);
   }
   if ((button.w3.shadowThickness <= 0) && (button.pressed)) {
      Pixel tmp = button.w3.w.background;
      button.w3.w.background = button.w3.w.foreground;
      button.w3.w.foreground = tmp;
      tmp = button.label.w.background;
      button.label.w.background = button.label.w.foreground;
      button.label.w.foreground = tmp;
   }
   x = (button.w3.w.x + button.w3.borderWidth);
   y = (button.w3.w.y + button.w3.borderWidth);
   width = (button.w3.w.width - (2 * button.w3.borderWidth));
   height = (button.w3.w.height - (2 * button.w3.borderWidth));
   if ((button.w3.shadowThickness > 0) && (button.pressed)) {
      XSetForeground(app->dpy, app->fillGC, button.w3.topShadowColor);
   } else {
      XSetForeground(app->dpy, app->fillGC, button.w3.w.background);
   }
   XFillRectangle(app->dpy, draw, app->fillGC, x, y, width, height);
   if (button.w3.shadowThickness > 0) {
      if (button.pressed) {
	 draw_shaded_rectangle(app->dpy, draw, x, y, width, height,
			       button.w3.shadowThickness,
			       button.w3.bottomShadowColor,
			       button.w3.topShadowColor);
      } else {
	 draw_shaded_rectangle(app->dpy, draw, x, y, width, height,
			       button.w3.shadowThickness,
			       button.w3.topShadowColor,
			       button.w3.bottomShadowColor);
      }
   }
   if ((button.w3.shadowThickness > 0) && (button.pressed)) {
      Dimension pressedAdjustment;

      pressedAdjustment = button.w3.shadowThickness / 2;
      if (pressedAdjustment < 1) {
	 pressedAdjustment = 1;
      }
      x = button.label.w.x;
      y = button.label.w.y;
      button.label.w.x += pressedAdjustment;
      button.label.w.y += pressedAdjustment;
      paintLabel(app, draw, button.label);
      button.label.w.x = x;
      button.label.w.y = y;
   } else {
      paintLabel(app, draw, button.label);
   }
   if ((button.w3.shadowThickness <= 0) && (button.pressed)) {
      Pixel tmp = button.w3.w.background;
      button.w3.w.background = button.w3.w.foreground;
      button.w3.w.foreground = tmp;
      tmp = button.label.w.background;
      button.label.w.background = button.label.w.foreground;
      button.label.w.foreground = tmp;
   }
}

void paintIndicator(AppInfo *app, Drawable draw, IndicatorElement indicator)
{
   Position x;
   Position y;
   Dimension width;
   Dimension height;
   GC gc = app->dimGC;

   if (indicator.parent->w3.borderWidth > 0) {
      XSetForeground(app->dpy, app->borderGC,
		     indicator.parent->w3.borderColor);
      XFillRectangle(app->dpy, draw, app->borderGC, indicator.w.x,
		     indicator.w.y, indicator.w.width, indicator.w.height);
   }
   if (indicator.isLit) {
      gc = app->brightGC;
   }
   x = (indicator.w.x + indicator.parent->w3.borderWidth);
   y = (indicator.w.y + indicator.parent->w3.borderWidth);
   width = (indicator.w.width - (2 * indicator.parent->w3.borderWidth));
   height = (indicator.w.height - (2 * indicator.parent->w3.borderWidth));
   XFillRectangle(app->dpy, draw, gc, x, y, width, height);
   if (indicator.parent->w3.shadowThickness > 0) {
      draw_shaded_rectangle(app->dpy, draw, x, y, width, height,
			    indicator.parent->w3.shadowThickness,
			    indicator.parent->w3.bottomShadowColor,
			    indicator.parent->w3.topShadowColor);
   }
}

void updateIndicatorElement(AppInfo *app, int i)
{
   DialogInfo *d = app->dialog;

   d->indicators[i].isLit = !(d->indicators[i].isLit);
   paintIndicator(app, d->dialogWindow, d->indicators[i]);
}

void updateIndicators(AppInfo *app, int condition)
{
   DialogInfo *d = app->dialog;

   if (condition > 0) {
      /* Move forward one. */
      updateIndicatorElement(app, d->indicator.current);
      if (d->indicator.current < (d->indicator.count - 1)) {
	 (d->indicator.current)++;
      } else {
	 d->indicator.current = 0;
      }
   } else if (condition < 0) {
      /* Move backward one. */
      if (d->indicator.current > 0) {
	 (d->indicator.current)--;
      } else {
	 d->indicator.current = d->indicator.count - 1;
      }
      updateIndicatorElement(app, d->indicator.current);
   } else {
      /* Erase them all. */
      int i;

      for (i = 0; i < d->indicator.count; i++) {
	 d->indicators[i].isLit = False;
	 paintIndicator(app, d->dialogWindow, d->indicators[i]);
      }
      d->indicator.current = 0;
   }
   XSync(app->dpy, False);
}

void paintDialog(AppInfo *app)
{
   DialogInfo *d = app->dialog;
   Drawable draw = d->dialogWindow;
   int i;

   XSetForeground(app->dpy, app->fillGC, d->w3.w.background);
   XFillRectangle(app->dpy, draw, app->fillGC, 0, 0,
		  d->w3.w.width, d->w3.w.height);
   if (d->w3.shadowThickness > 0) {
      draw_shaded_rectangle(app->dpy, draw, 0, 0,
			    d->w3.w.width, d->w3.w.height,
			    d->w3.shadowThickness,
			    d->w3.topShadowColor,
			    d->w3.bottomShadowColor);
   }
   paintLabel(app, draw, d->label);
   for (i = 0; i < d->indicator.count; i++) {
      paintIndicator(app, draw, d->indicators[i]);
   }
   paintButton(app, draw, d->okButton);
   paintButton(app, draw, d->cancelButton);
   XSync(app->dpy, False);
}

void performGrab(AppInfo *app, int grabType, char *grabTypeName,
		 Bool shouldGrab, Bool *isGrabbed) {
   if ((!(shouldGrab)) || (*isGrabbed)) {
      return;
   } else if ((GRAB_KEYBOARD != grabType) && (GRAB_POINTER != grabType)) {
      fprintf(stderr, "%s[%ld]: performGrab: invalid grab type (%d).\n",
	      app->appName, (long) app->pid, grabType);
      return;
   } else {
      int status = GrabInvalidTime;	/* keep gcc -Wall from complaining */
      unsigned int seconds = 0;
      int helpful_message = 0;
      /* keyboard and pointer */
      Window grabWindow = app->dialog->dialogWindow;
      Bool ownerEvents = False;
      Bool pointerMode = GrabModeAsync;
      Bool keyboardMode = GrabModeAsync;
      /* pointer only */
      unsigned int eventMask = ButtonPressMask | ButtonReleaseMask;
      Window confineTo = None;
      Cursor cursor = None;

      *isGrabbed = True;

      if (NULL == grabTypeName) {
	 fprintf(stderr, "%s[%ld]: performGrab: null grab type name.\n",
		 app->appName, (long) app->pid);
      }

      if (0 == app->grabFailTimeout) {
	 /* Ensure we try to perform the grab at least once. */
	 app->grabFailTimeout = 1;
      }
      while (seconds < app->grabFailTimeout) {
	 XSync(app->dpy, False);
	 switch (grabType) {
	  case GRAB_KEYBOARD:
	    status = XGrabKeyboard(app->dpy, grabWindow, ownerEvents,
				   pointerMode, keyboardMode, CurrentTime);
	    break;
	  case GRAB_POINTER:
	    status = XGrabPointer(app->dpy, grabWindow, ownerEvents,
				  eventMask, pointerMode, keyboardMode,
				  confineTo, cursor, CurrentTime);
	    break;
	 }
	 XSync(app->dpy, False);
	 if (GrabSuccess == status) {
	    if (helpful_message) {
	       fprintf(stderr, "%s[%ld]: Got %s.\n",
		       app->appName, (long) app->pid, grabTypeName);
	    }
	    break;
	 }
	 if (!helpful_message) {
	    fprintf(stderr, "%s[%ld]: Trying to grab %s ...\n",
		    app->appName, (long) app->pid, grabTypeName);
	    helpful_message = 1;
	 }
	 seconds += app->grabRetryInterval;
	 sleep(app->grabRetryInterval);
      }
      if (GrabSuccess != status) {
	 char *reason = "reason unknown";

	 switch (status) {
	  case AlreadyGrabbed:
	    reason = "someone else already has it";
	    break;
	  case GrabFrozen:
	    reason = "someone else has frozen it";
	    break;
	  case GrabInvalidTime:
	    reason = "bad grab time [this shouldn't happen]";
	    break;
	  case GrabNotViewable:
	    reason = "grab not viewable [this shouldn't happen]";
	    break;
	 }
	 fprintf(stderr, "%s[%ld]: Could not grab %s (%s)\n",
		 app->appName, (long) app->pid, grabTypeName, reason);
	 exitApp(app, EXIT_STATUS_ERROR);
      }
   }
}

void grabKeyboard(AppInfo *app)
{
   performGrab(app, GRAB_KEYBOARD, "keyboard", app->grabKeyboard,
	       &(app->isKeyboardGrabbed));
}

void ungrabKeyboard(AppInfo *app)
{
   if (app->grabKeyboard) {
      XUngrabKeyboard(app->dpy, CurrentTime);
   }
}

void grabPointer(AppInfo *app)
{
   performGrab(app, GRAB_POINTER, "pointer", app->grabPointer,
	       &(app->isPointerGrabbed));
}

void ungrabPointer(AppInfo *app)
{
   if (app->grabPointer) {
      XUngrabPointer(app->dpy, CurrentTime);
   }
}

void grabServer(AppInfo *app)
{
   if ((!(app->grabServer)) || (app->isServerGrabbed)) {
      return;
   } else {
      app->isServerGrabbed = True;
      XSync(app->dpy, False);
      XGrabServer(app->dpy);
      XSync(app->dpy, False);
   }
}

void ungrabServer(AppInfo *app)
{
   if (app->grabServer) {
      XUngrabServer(app->dpy);
   }
}

void cleanUp(AppInfo *app)
{
   cancelInputTimeout(app);
   XDestroyWindow(app->dpy, app->dialog->dialogWindow);
   destroyGCs(app);
   destroyDialog(app);
   if (app->buf) {
      memset(app->buf, 0, app->bufSize);
   }
   freeIf(app->buf);
   ungrabPointer(app);
   ungrabKeyboard(app);
   ungrabServer(app);
}

void exitApp(AppInfo *app, int exitCode)
{
   cleanUp(app);
   exit(exitCode);
}

void acceptAction(AppInfo *app)
{
   int status = append_to_buf(&(app->buf), &(app->bufSize),
			      &(app->bufIndex), '\0');
   if (APPEND_FAILURE == status) {
      cleanUp(app);
      outOfMemory(app, __LINE__);
   }
   fputs(app->buf, stdout);
   fputc('\n', stdout);
   exitApp(app, EXIT_STATUS_ACCEPT);
}

void cancelAction(AppInfo *app)
{
   exitApp(app, EXIT_STATUS_CANCEL);
}

void backspacePassphrase(AppInfo *app)
{
   if (0 >= app->bufIndex) {
      XBell(app->dpy, 0);
      return;
   }
   (app->bufIndex)--;
   updateIndicators(app, -1);
}

void erasePassphrase(AppInfo *app)
{
   if (0 >= app->bufIndex) {
      XBell(app->dpy, 0);
      return;
   }
   updateIndicators(app, 0);
   app->bufIndex = 0;
}

void addToPassphrase(AppInfo *app, char c)
{
   int status = append_to_buf(&(app->buf), &(app->bufSize),
			      &(app->bufIndex), c);
   if (APPEND_FAILURE == status) {
      cleanUp(app);
      outOfMemory(app, __LINE__);
   }
   updateIndicators(app, 1);
}

void handleKeyPress(AppInfo *app, XEvent *event)
{
   char s[2];
   int n;

   if (event->xkey.send_event) {
      /* Pay no attention to synthetic key events. */
      return;
   }
   cancelInputTimeout(app);
   n = XLookupString(&(event->xkey), s, 1, NULL, NULL);

   if (1 != n) {
      return;
   }
   s[1] = '\0';
   switch (s[0]) {
    case '\010':
    case '\177':
      backspacePassphrase(app);
      break;
    case '\025':
    case '\030':
      erasePassphrase(app);
      break;
    case '\012':
    case '\015':
      acceptAction(app);
      break;
    case '\033':
      cancelAction(app);
      break;
    default:
      addToPassphrase(app, s[0]);
      break;
   }
}

Bool eventIsInsideButton(AppInfo *app, XEvent *event, ButtonInfo button)
{
   /* 'gcc -Wall' complains about 'app' being an unused parameter.
    * Tough.  We might want to use it later, and then we don't have
    * to change it in each place it's called.  Performance won't suffer.
    */
   int status = False;
   int x, y;

   switch(event->type) {
    case ButtonPress:
    case ButtonRelease:
      x = event->xbutton.x;
      y = event->xbutton.y;
      break;
    case MotionNotify:
      x = event->xmotion.x;
      y = event->xmotion.y;
      break;
    default:
      return(False);
   }
   if ((x >= (button.w3.w.x + button.w3.borderWidth)) &&
       (x < (button.w3.w.x + button.w3.w.width -
	     (2 * button.w3.borderWidth))) &&
       (y >= (button.w3.w.y + button.w3.borderWidth)) &&
       (y < (button.w3.w.y + button.w3.w.height -
	     (2 * button.w3.borderWidth)))) {
      status = True;
   }
   return(status);
}

void handleButtonPress(AppInfo *app, XEvent *event)
{
   DialogInfo *d = app->dialog;

   cancelInputTimeout(app);
   if (event->xbutton.button != Button1) {
      return;
   }
   if (ButtonPress == event->type) {
      if (eventIsInsideButton(app, event, d->okButton)) {
	 d->pressedButton = OK_BUTTON;
	 d->okButton.pressed = True;
	 paintButton(app, d->dialogWindow, d->okButton);
      } else if (eventIsInsideButton(app, event, d->cancelButton)) {
	 d->pressedButton = CANCEL_BUTTON;
	 d->cancelButton.pressed = True;
	 paintButton(app, d->dialogWindow, d->cancelButton);
      } else {
	 d->pressedButton = NO_BUTTON;
      }
   } else if (ButtonRelease == event->type) {
      if (OK_BUTTON == d->pressedButton) {
	 if (eventIsInsideButton(app, event, d->okButton)) {
	    acceptAction(app);
	 } else {
	    if (d->okButton.pressed) {
	       d->okButton.pressed = False;
	       paintButton(app, d->dialogWindow, d->okButton);
	    }
	 }
      } else if (CANCEL_BUTTON == d->pressedButton) {
	 if (eventIsInsideButton(app, event, d->cancelButton)) {
	    cancelAction(app);
	 } else {
	    if (d->cancelButton.pressed) {
	       d->cancelButton.pressed = False;
	       paintButton(app, d->dialogWindow, d->cancelButton);
	    }
	 }
      }
      d->pressedButton = NO_BUTTON;
   }
}

void handlePointerMotion(AppInfo *app, XEvent *event)
{
   DialogInfo *d = app->dialog;

   if (NO_BUTTON == d->pressedButton) {
      return;
   } else if (OK_BUTTON == d->pressedButton) {
      if (eventIsInsideButton(app, event, d->okButton)) {
	 if (!(d->okButton.pressed)) {
	    d->okButton.pressed = True;
	    paintButton(app, d->dialogWindow, d->okButton);
	 }
      } else {
	 if (d->okButton.pressed) {
	    d->okButton.pressed = False;
	    paintButton(app, d->dialogWindow, d->okButton);
	 }
      }
   } else if (CANCEL_BUTTON == d->pressedButton) {
      if (eventIsInsideButton(app, event, d->cancelButton)) {
	 if (!(d->cancelButton.pressed)) {
	    d->cancelButton.pressed = True;
	    paintButton(app, d->dialogWindow, d->cancelButton);
	 }
      } else {
	 if (d->cancelButton.pressed) {
	    d->cancelButton.pressed = False;
	    paintButton(app, d->dialogWindow, d->cancelButton);
	 }
      }
   }
}

void handleInputTimeout(XtPointer data, XtIntervalId *timerId)
{
   /* 'gcc -Wall' complains about 'timerId' being an unused parameter.
    * Tough.  Xt forces us to have it here.  Like it.
    */
   AppInfo *app = (AppInfo *) data;
   if (app->inputTimeoutActive) {
      app->inputTimeoutActive = False;
      fprintf(stderr, "%s[%ld]: *Yawn*...timed out after %lu seconds.\n",
	      app->appName, (long) app->pid, (app->inputTimeout / 1000));
      exitApp(app, EXIT_STATUS_TIMEOUT);
   }
}

void cancelInputTimeout(AppInfo *app)
{
   if (app->inputTimeoutActive) {
      app->inputTimeoutActive = False;
      XtRemoveTimeOut(app->inputTimeoutTimerId);
   }
}

int main(int argc, char **argv)
{
   AppInfo app;
   XEvent event;
   XineramaScreenInfo *screens;
   int nscreens;

   memset(&app, 0, sizeof(app));

   progclass = "SshAskpass";
   app.toplevelShell = XtAppInitialize(&(app.appContext), progclass,
					NULL, 0, &argc, argv,
					defaults, NULL, 0);
   app.argc = argc;
   app.argv = argv;
   app.dpy = XtDisplay(app.toplevelShell);
   app.screen = DefaultScreenOfDisplay(app.dpy);
   app.rootWindow = RootWindowOfScreen(app.screen);
   app.black = BlackPixel(app.dpy, DefaultScreen(app.dpy));
   app.white = WhitePixel(app.dpy, DefaultScreen(app.dpy));
   app.colormap = DefaultColormapOfScreen(app.screen);
   app.resourceDb = XtDatabase(app.dpy);
   XtGetApplicationNameAndClass(app.dpy, &progname, &progclass);
   app.appName = progname;
   app.appClass = progclass;
   /* For resources.c. */
   db = app.resourceDb;

   /* Seconds after which keyboard/pointer grab fail. */
   app.grabFailTimeout = 5;
   /* Number of seconds to wait between grab attempts. */
   app.grabRetryInterval = 1;

   app.pid = getpid();

   {
      struct rlimit resourceLimit;
      int status;

      status = getrlimit(RLIMIT_CORE, &resourceLimit);
      if (-1 == status) {
	 fprintf(stderr, "%s[%ld]: getrlimit failed (%s)\n", app.appName,
		 (long) app.pid, strerror(errno));
	 exit(EXIT_STATUS_ERROR);
      }
      resourceLimit.rlim_cur = 0;
      status = setrlimit(RLIMIT_CORE, &resourceLimit);
      if (-1 == status) {
	 fprintf(stderr, "%s[%ld]: setrlimit failed (%s)\n", app.appName,
		 (long) app.pid, strerror(errno));
	 exit(EXIT_STATUS_ERROR);
      }
   }

   app.screen_width = WidthOfScreen(app.screen);
   app.screen_height = HeightOfScreen(app.screen);
   if (XineramaIsActive(app.dpy) &&
      (screens = XineramaQueryScreens(app.dpy, &nscreens)) != NULL &&
      nscreens) {
      app.screen_width = screens[0].width;
      app.screen_height = screens[0].height;
      XFree(screens);
   }

   app.xResolution =
      app.screen_width * 1000 / WidthMMOfScreen(app.screen);
   app.yResolution =
      app.screen_height * 1000 / HeightMMOfScreen(app.screen);

   createDialog(&app);
   createGCs(&app);

   app.eventMask = 0;
   app.eventMask |= ExposureMask;
   app.eventMask |= ButtonPressMask;
   app.eventMask |= ButtonReleaseMask;
   app.eventMask |= Button1MotionMask;
   app.eventMask |= KeyPressMask;

   createDialogWindow(&app);

   XMapWindow(app.dpy, app.dialog->dialogWindow);
   if (app.inputTimeout > 0) {
      app.inputTimeoutActive = True;
      app.inputTimeoutTimerId =
	 XtAppAddTimeOut(app.appContext, app.inputTimeout,
			 handleInputTimeout, (XtPointer) &app);
   }

   while(True) {
      XtAppNextEvent(app.appContext, &event);
      switch (event.type) {
       case Expose:
	 grabServer(&app);
	 grabKeyboard(&app);
	 grabPointer(&app);
	 if (event.xexpose.count) {
	    break;
	 }
	 paintDialog(&app);
	 break;
       case ButtonPress:
       case ButtonRelease:
	 handleButtonPress(&app, &event);
	 break;
       case MotionNotify:
	 handlePointerMotion(&app, &event);
       case KeyPress:
	 handleKeyPress(&app, &event);
	 break;
       case ClientMessage:
	 if ((32 == event.xclient.format) &&
	     ((unsigned long) event.xclient.data.l[0] ==
	      app.wmDeleteWindowAtom)) {
	    cancelAction(&app);
	 }
	 break;
       default:
	 break;
      }
   }

   fprintf(stderr, "%s[%ld]: This should not happen.\n", app.appName,
	   (long) app.pid);
   return(EXIT_STATUS_ANOMALY);
}


text:
include $(GOROOT)/src/Make.inc

TARG=ab
GOFILES=ab.go

include $(GOROOT)/src/Make.cmd

redpajama_set_name: RedPajamaGithub


text:
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=8 sts=2 et sw=2 tw=80: */
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

#ifndef _nsLocalFileWIN_H_
#define _nsLocalFileWIN_H_

#include "nscore.h"
#include "nsError.h"
#include "nsString.h"
#include "nsCRT.h"
#include "nsIFile.h"
#include "nsIFactory.h"
#include "nsILocalFileWin.h"
#include "nsIHashable.h"
#include "nsIClassInfoImpl.h"
#include "prio.h"

#include "mozilla/Attributes.h"

#include "windows.h"
#include "shlobj.h"

#include <sys/stat.h>

class nsLocalFile final
  : public nsILocalFileWin
  , public nsIHashable
{
public:
  NS_DEFINE_STATIC_CID_ACCESSOR(NS_LOCAL_FILE_CID)

  nsLocalFile();

  static nsresult nsLocalFileConstructor(nsISupports* aOuter,
                                         const nsIID& aIID,
                                         void** aInstancePtr);

  // nsISupports interface
  NS_DECL_THREADSAFE_ISUPPORTS

  // nsIFile interface
  NS_DECL_NSIFILE

  // nsILocalFile interface
  NS_DECL_NSILOCALFILE

  // nsILocalFileWin interface
  NS_DECL_NSILOCALFILEWIN

  // nsIHashable interface
  NS_DECL_NSIHASHABLE

public:
  static void GlobalInit();
  static void GlobalShutdown();

private:
  // CopyMove and CopySingleFile constants for |options| parameter:
  enum CopyFileOption {
    FollowSymlinks          = 1u << 0,
    Move                    = 1u << 1,
    SkipNtfsAclReset        = 1u << 2,
    Rename                  = 1u << 3
  };

  nsLocalFile(const nsLocalFile& aOther);
  ~nsLocalFile()
  {
  }

  bool mDirty;            // cached information can only be used when this is false
  bool mResolveDirty;
  bool mFollowSymlinks;   // should we follow symlinks when working on this file

  // this string will always be in native format!
  nsString mWorkingPath;

  // this will be the resolved path of shortcuts, it will *NEVER*
  // be returned to the user
  nsString mResolvedPath;

  // this string, if not empty, is the *short* pathname that represents
  // mWorkingPath
  nsString mShortWorkingPath;

  PRFileInfo64 mFileInfo64;

  void MakeDirty()
  {
    mDirty = true;
    mResolveDirty = true;
    mShortWorkingPath.Truncate();
  }

  nsresult ResolveAndStat();
  nsresult Resolve();
  nsresult ResolveShortcut();

  void EnsureShortPath();

  nsresult CopyMove(nsIFile* aNewParentDir, const nsAString& aNewName,
                    uint32_t aOptions);
  nsresult CopySingleFile(nsIFile* aSource, nsIFile* aDest,
                          const nsAString& aNewName, uint32_t aOptions);

  nsresult SetModDate(int64_t aLastModifiedTime, const wchar_t* aFilePath);
  nsresult HasFileAttribute(DWORD aFileAttrib, bool* aResult);
  nsresult AppendInternal(const nsAFlatString& aNode,
                          bool aMultipleComponents);

  nsresult OpenNSPRFileDescMaybeShareDelete(int32_t aFlags,
                                            int32_t aMode,
                                            bool aShareDelete,
                                            PRFileDesc** aResult);
};

#endif


text:
You might have noticed, that the above code will results in "Not found" page in case `Db.validateUser` returns None.
That's because we temporarily assigned `never` to the latter match.
Ideally, we'd like to see some kind of a validation message next to the form.
To achieve that, let's add `msg` parameter to `View.logon`:

==> View.fs:`let logon`

Now we can invoke it in two ways:

==> App.fs:`let logon`

The first one being GET `logon` handler, and the other one being returned if provided credentials are incorrect.


text:
import { Clipboard, Waiter } from '@ephox/agar';
import { context, describe, it } from '@ephox/bedrock-client';
import { TinyAssertions, TinyDom, TinyHooks, TinySelections } from '@ephox/wrap-mcagar';
import { assert } from 'chai';

import Editor from 'tinymce/core/api/Editor';
import { PastePostProcessEvent, PastePreProcessEvent } from 'tinymce/core/api/EventTypes';
import { EditorEvent } from 'tinymce/core/api/util/EventDispatcher';
import * as InternalHtml from 'tinymce/core/paste/InternalHtml';
import TablePlugin from 'tinymce/plugins/table/Plugin';

describe('browser.tinymce.core.paste.InternalClipboardTest', () => {
  let dataTransfer: DataTransfer | undefined;
  let lastPreProcessEvent: EditorEvent<PastePreProcessEvent> | undefined;
  let lastPostProcessEvent: EditorEvent<PastePostProcessEvent> | undefined;

  const hook = TinyHooks.bddSetupLight<Editor>({
    plugins: 'table',
    init_instance_callback: (editor: Editor) => {
      editor.on('PastePreProcess', (evt) => {
        lastPreProcessEvent = evt;
      });

      editor.on('PastePostProcess', (evt) => {
        lastPostProcessEvent = evt;
      });

      editor.on('copy cut paste', (e) => {
        dataTransfer = e.clipboardData;
      });
    },
    base_url: '/project/tinymce/js/tinymce'
  }, [ TablePlugin ]);

  const resetProcessEvents = () => {
    lastPreProcessEvent = undefined;
    lastPostProcessEvent = undefined;
  };

  const cutCopyDataTransferEvent = (editor: Editor, type: 'cut' | 'copy') => {
    const action = type === 'cut' ? Clipboard.cut : Clipboard.copy;
    action(TinyDom.body(editor));
  };

  const pasteDataTransferEvent = (editor: Editor, data: Record<string, string>) =>
    Clipboard.pasteItems(TinyDom.body(editor), data);

  const assertClipboardData = (expectedHtml: string, expectedText: string) => {
    assert.equal(dataTransfer?.getData('text/html'), expectedHtml, 'text/html data should match');
    assert.equal(dataTransfer?.getData('text/plain'), expectedText, 'text/plain data should match');
  };

  const copy = (editor: Editor, html: string, spath: number[], soffset: number, fpath: number[], foffset: number) => {
    editor.setContent(html);
    TinySelections.setSelection(editor, spath, soffset, fpath, foffset);
    cutCopyDataTransferEvent(editor, 'copy');
  };

  const cut = (editor: Editor, html: string, spath: number[], soffset: number, fpath: number[], foffset: number) => {
    editor.setContent(html);
    TinySelections.setSelection(editor, spath, soffset, fpath, foffset);
    cutCopyDataTransferEvent(editor, 'cut');
  };

  const paste = (editor: Editor, startHtml: string, pasteData: Record<string, string>, spath: number[], soffset: number, fpath: number[], foffset: number) => {
    editor.setContent(startHtml);
    TinySelections.setSelection(editor, spath, soffset, fpath, foffset);
    resetProcessEvents();
    pasteDataTransferEvent(editor, pasteData);
  };

  context('copy', () => {
    it('TBA: Copy simple text', () => {
      const editor = hook.editor();
      copy(editor, '
text
', [ 0, 0 ], 0, [ 0, 0 ], 4);
      assertClipboardData('text', 'text');
      TinyAssertions.assertContent(editor, '
text
');
      TinyAssertions.assertSelection(editor, [ 0, 0 ], 0, [ 0, 0 ], 4);
    });

    it('TBA: Copy inline elements', () => {
      const editor = hook.editor();
      copy(editor, '
text
', [ 0, 0 ], 0, [ 0, 2 ], 1);
      assertClipboardData('text', 'text');
      TinyAssertions.assertContent(editor, '
text
');
      TinyAssertions.assertSelection(editor, [ 0, 0 ], 0, [ 0, 2 ], 1);
    });

    it('TBA: Copy partially selected inline elements', () => {
      const editor = hook.editor();
      copy(editor, '
acde
', [ 0, 0 ], 0, [ 0, 1, 0 ], 1);
      assertClipboardData('ac', 'ac');
      TinyAssertions.assertContent(editor, '
acde
');
      TinyAssertions.assertSelection(editor, [ 0, 0 ], 0, [ 0, 1, 0 ], 1);
    });

    it('TBA: Copy collapsed selection', () => {
      const editor = hook.editor();
      copy(editor, '
abc
', [ 0, 0 ], 1, [ 0, 0 ], 1);
      assertClipboardData('', '');
      TinyAssertions.assertContent(editor, '
abc
');
      TinyAssertions.assertSelection(editor, [ 0, 0 ], 1, [ 0, 0 ], 1);
    });

    it('TBA: Copy collapsed selection with table selection', () => {
      const editor = hook.editor();
      copy(editor,
        '
' +
            '
' +
              '
' +
                'a	' +
                'b	' +
              '
' +
            '
' +
          '
',
        [ 0, 0, 0, 1, 0 ], 0, [ 0, 0, 0, 1, 0 ], 0);
      assertClipboardData(
        '
\n' +
            '
\n' +
              '
\n' +
                'a	\n' +
                'b	\n' +
              '
\n' +
            '
\n' +
          '
', 'ab');
      TinyAssertions.assertSelection(editor, [ 0, 0, 0, 1, 0 ], 0, [ 0, 0, 0, 1, 0 ], 0);
    });

    it('TINY-8563: Copy cef element', () => {
      const editor = hook.editor();
      copy(editor, '
abc
', [ 0 ], 1, [ 0 ], 2);
      assertClipboardData('bc', 'bc');
      TinyAssertions.assertContent(editor, '
abc
');
      TinyAssertions.assertSelection(editor, [ 0 ], 1, [ 0 ], 2);
    });
  });

  context('cut', () => {
    const pWaitUntilAssertContent = (editor: Editor, expected: string) =>
      Waiter.pTryUntil('Cut is async now, so need to wait for content', () => TinyAssertions.assertContent(editor, expected));

    it('TBA: Cut simple text', async () => {
      const editor = hook.editor();
      cut(editor, '
text
', [ 0, 0 ], 0, [ 0, 0 ], 4);
      assertClipboardData('text', 'text');
      await pWaitUntilAssertContent(editor, '');
      TinyAssertions.assertSelection(editor, [ 0 ], 0, [ 0 ], 0);
    });

    it('TBA: Cut inline elements', async () => {
      const editor = hook.editor();
      cut(editor, '
text
', [ 0, 0 ], 0, [ 0, 2 ], 1);
      assertClipboardData('text', 'text');
      await pWaitUntilAssertContent(editor, '');
      TinyAssertions.assertSelection(editor, [ 0 ], 0, [ 0 ], 0);
    });

    it('TBA: Cut partially selected inline elements', async () => {
      const editor = hook.editor();
      cut(editor, '
acde
', [ 0, 0 ], 0, [ 0, 1, 0 ], 1);
      assertClipboardData('ac', 'ac');
      await pWaitUntilAssertContent(editor, '
de
');
      TinyAssertions.assertSelection(editor, [ 0, 0, 0 ], 0, [ 0, 0, 0 ], 0);
    });

    it('TBA: Cut collapsed selection', async () => {
      const editor = hook.editor();
      cut(editor, '
abc
', [ 0, 0 ], 1, [ 0, 0 ], 1);
      assertClipboardData('', '');
      await pWaitUntilAssertContent(editor, '
abc
');
      TinyAssertions.assertSelection(editor, [ 0, 0 ], 1, [ 0, 0 ], 1);
    });

    it('TINY-8563: Cut cef element', async () => {
      const editor = hook.editor();
      cut(editor, '
abc
', [ 0 ], 1, [ 0 ], 2);
      assertClipboardData('bc', 'bc');
      await pWaitUntilAssertContent(editor, '
a
');
      TinyAssertions.assertSelection(editor, [ 0, 0 ], 1, [ 0, 0 ], 1);
    });
  });

  context('paste', () => {
    const assertLastPreProcessEvent = (expectedData: { internal: boolean; content: string }) => {
      assert.equal(lastPreProcessEvent?.internal, expectedData.internal, 'Internal property should be equal');
      assert.equal(lastPreProcessEvent?.content, expectedData.content, 'Content property should be equal');
    };

    const assertLastPostProcessEvent = (expectedData: { internal: boolean; content: string }) => {
      assert.equal(lastPostProcessEvent?.internal, expectedData.internal, 'Internal property should be equal');
      assert.equal(lastPostProcessEvent?.node.innerHTML, expectedData.content, 'Content property should be equal');
    };

    const pWaitForProcessEvents = () => Waiter.pTryUntil('Did not get any events fired', () => {
      assert.isDefined(lastPreProcessEvent, 'PastePreProcess event object');
      assert.isDefined(lastPostProcessEvent, 'PastePostProcess event object');
    });

    it('TBA: Paste external content', async () => {
      const editor = hook.editor();
      paste(editor, '
abc
', { 'text/plain': 'X', 'text/html': '
X
' }, [ 0, 0 ], 0, [ 0, 0 ], 3);
      await pWaitForProcessEvents();
      assertLastPreProcessEvent({ internal: false, content: 'X' });
      assertLastPostProcessEvent({ internal: false, content: 'X' });
    });

    it('TBA: Paste external content treated as plain text', async () => {
      const editor = hook.editor();
      paste(editor, '
abc
', { 'text/html': '
X
' }, [ 0, 0 ], 0, [ 0, 0 ], 3);
      await pWaitForProcessEvents();
      assertLastPreProcessEvent({ internal: false, content: 'X' });
      assertLastPostProcessEvent({ internal: false, content: 'X' });
    });

    it('TBA: Paste internal content with mark', async () => {
      const editor = hook.editor();
      paste(editor, '
abc
', { 'text/plain': 'X', 'text/html': InternalHtml.mark('
X
') }, [ 0, 0 ], 0, [ 0, 0 ], 3);
      await pWaitForProcessEvents();
      assertLastPreProcessEvent({ internal: true, content: '
X
' });
      assertLastPostProcessEvent({ internal: true, content: '
X
' });
    });

    it('TBA: Paste internal content with mime', async () => {
      const editor = hook.editor();
      paste(editor, '
abc
', { 'text/plain': 'X', 'text/html': '
X
', 'x-tinymce/html': '
X
' }, [ 0, 0 ], 0, [ 0, 0 ], 3);
      await pWaitForProcessEvents();
      assertLastPreProcessEvent({ internal: true, content: '
X
' });
      assertLastPostProcessEvent({ internal: true, content: '
X
' });
    });
  });
});


text:
package pl.touk.nussknacker.engine.testing

import pl.touk.nussknacker.engine.api.SpelExpressionExcludeList
import pl.touk.nussknacker.engine.api.component.SingleComponentConfig
import pl.touk.nussknacker.engine.api.definition.Parameter
import pl.touk.nussknacker.engine.api.process.{ClassExtractionSettings, LanguageConfiguration}
import pl.touk.nussknacker.engine.api.typed.typing.{Typed, Unknown}
import pl.touk.nussknacker.engine.definition.DefinitionExtractor.{ObjectDefinition, ObjectWithMethodDef, StandardObjectWithMethodDef}
import pl.touk.nussknacker.engine.definition.MethodDefinitionExtractor.{MethodDefinition, OrderedDependencies}
import pl.touk.nussknacker.engine.definition.ProcessDefinitionExtractor.{CustomTransformerAdditionalData, ExpressionDefinition, ProcessDefinition}
import pl.touk.nussknacker.engine.util.Implicits._

import scala.concurrent.Future

object ProcessDefinitionBuilder {

  def empty: ProcessDefinition[ObjectDefinition] =
    ProcessDefinition(Map.empty, Map.empty, Map.empty, Map.empty, Map.empty,
      ExpressionDefinition(Map.empty, List.empty, List.empty, languages = LanguageConfiguration(List.empty),
        optimizeCompilation = true, strictTypeChecking = true, dictionaries = Map.empty, hideMetaVariable = false,
        strictMethodsChecking = true, staticMethodInvocationsChecking = false, methodExecutionForUnknownAllowed = false,
        dynamicPropertyAccessAllowed = false, spelExpressionExcludeList = SpelExpressionExcludeList.default,
        customConversionsProviders = List.empty), ClassExtractionSettings.Default)

  def withEmptyObjects(definition: ProcessDefinition[ObjectDefinition]): ProcessDefinition[ObjectWithMethodDef] = {
    val expressionConfig = definition.expressionConfig
    val expressionDefinition = toExpressionDefinition(expressionConfig)
    ProcessDefinition(
      definition.services.mapValuesNow(makeDummyDefinition(_, classOf[Future[_]])),
      definition.sourceFactories.mapValuesNow(makeDummyDefinition(_)),
      definition.sinkFactories.mapValuesNow(makeDummyDefinition(_)),
      definition.customStreamTransformers.mapValuesNow { case (transformer, queryNames) => (makeDummyDefinition(transformer), queryNames) },
      definition.signalsWithTransformers.mapValuesNow(sign => (makeDummyDefinition(sign._1), sign._2)),
      expressionDefinition,
      definition.settings
    )
  }

  private def toExpressionDefinition(expressionConfig: ExpressionDefinition[ObjectDefinition]) =
    ExpressionDefinition(
      expressionConfig.globalVariables.mapValuesNow(makeDummyDefinition(_)),
      expressionConfig.globalImports,
      expressionConfig.additionalClasses,
      expressionConfig.languages,
      expressionConfig.optimizeCompilation,
      expressionConfig.strictTypeChecking,
      expressionConfig.dictionaries,
      expressionConfig.hideMetaVariable,
      expressionConfig.strictMethodsChecking,
      expressionConfig.staticMethodInvocationsChecking,
      expressionConfig.methodExecutionForUnknownAllowed,
      expressionConfig.dynamicPropertyAccessAllowed,
      expressionConfig.spelExpressionExcludeList,
      expressionConfig.customConversionsProviders)

  private def makeDummyDefinition(objectDefinition: ObjectDefinition, realType: Class[_] = classOf[Any]): ObjectWithMethodDef =
    StandardObjectWithMethodDef(null, MethodDefinition("", (_, _) => null, new OrderedDependencies(objectDefinition.parameters),
      Unknown, realType, List()), objectDefinition)

  implicit class ObjectProcessDefinition(definition: ProcessDefinition[ObjectDefinition]) {
    def withService(id: String, returnType: Class[_], params: Parameter*): ProcessDefinition[ObjectDefinition] =
      definition.copy(services = definition.services + (id -> ObjectDefinition(params.toList, Typed(returnType))))

    def withService(id: String, params: Parameter*): ProcessDefinition[ObjectDefinition] =
      definition.copy(services = definition.services + (id -> ObjectDefinition.withParams(params.toList)))

    def withSourceFactory(typ: String, params: Parameter*): ProcessDefinition[ObjectDefinition] =
      definition.copy(sourceFactories = definition.sourceFactories + (typ -> ObjectDefinition.withParams(params.toList)))

    def withSourceFactory(typ: String, category: String, params: Parameter*): ProcessDefinition[ObjectDefinition] =
      definition.copy(sourceFactories = definition.sourceFactories + (typ -> new ObjectDefinition(params.toList, Unknown, Some(List(category)), SingleComponentConfig.zero)))

    def withSinkFactory(typ: String, params: Parameter*): ProcessDefinition[ObjectDefinition] =
      definition.copy(sinkFactories = definition.sinkFactories + (typ -> ObjectDefinition.withParams(params.toList)))

    def withCustomStreamTransformer(id: String, returnType: Class[_], additionalData: CustomTransformerAdditionalData, params: Parameter*): ProcessDefinition[ObjectDefinition] =
      definition.copy(customStreamTransformers =
        definition.customStreamTransformers + (id -> (ObjectDefinition(params.toList, Typed(returnType)), additionalData)))

    def withSignalsWithTransformers(id: String, returnType: Class[_], transformers: Set[String], params: Parameter*): ProcessDefinition[ObjectDefinition] =
      definition.copy(signalsWithTransformers = definition.signalsWithTransformers + (id -> (ObjectDefinition(params.toList, Typed(returnType)), transformers)))

  }

}


text:
<?php  namespace Jai\Authentication\Tests\Unit\Stubs;

use Jai\Library\Repository\EloquentBaseRepository;

class VoidRepository extends EloquentBaseRepository{
    public function __construct(){}
    public function create(array $data){}
    public function update($id, array $data){}
    public function delete($id){}
    public function find($id){}
    public function all(){}
}


text:
package org.gobiiproject.gobiidtomapping;

import org.gobiiproject.gobiimodel.config.GobiiException;
import org.gobiiproject.gobiimodel.headerlesscontainer.ExtractorInstructionFilesDTO;
import org.gobiiproject.gobiimodel.headerlesscontainer.QCInstructionsDTO;

public interface DtoMapQCInstructions {

    QCInstructionsDTO createInstructions(String cropType, QCInstructionsDTO qcInstructionsDTO)  throws GobiiException;

    QCInstructionsDTO getInstruction(String cropType, String instructionFileName);
}


text:
set -e

# utilities
source "${DATA_DIR}/utils.sh"

# script variables
LOG_TITLE="deps"

log "nothing to install" 0


text:
/*
 * Created on May 30, 2004
 */
package net.charabia.jsmoothgen.application.swtgui;

import net.charabia.jsmoothgen.application.swtgui.resources.JSmoothResources;

import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.ui.forms.HyperlinkGroup;
import org.eclipse.ui.forms.widgets.Form;
import org.eclipse.ui.forms.widgets.FormText;
import org.eclipse.ui.forms.widgets.FormToolkit;
import org.eclipse.ui.forms.widgets.TableWrapData;
import org.eclipse.ui.forms.widgets.TableWrapLayout;

/**
 * @author Dumon
 */
public class WelcomePage extends JSmoothPage {

    public WelcomePage(JSmoothApplication js) {
        super(js);
    }

    public Control createPageArea(Composite parent) {
        Display display = parent.getDisplay();

        Composite top = new Composite(parent, SWT.NONE);
        GridLayout layout = new GridLayout();
        layout.marginHeight = 0;
        layout.marginWidth = 0;
        top.setLayout(layout);

        FormToolkit kit = new FormToolkit(parent.getDisplay());
        Form form = kit.createForm(top);
        GridData grid = new GridData(GridData.FILL_BOTH);
        grid.widthHint = 400;
        form.setLayoutData(grid);
        form.setText("Welcome to JSmooth !");
        TableWrapLayout wraplayout = new TableWrapLayout();
        form.getBody().setLayout(wraplayout);
        HyperlinkGroup hypergroup = kit.getHyperlinkGroup();
        hypergroup.setActiveForeground(display.getSystemColor(SWT.COLOR_BLUE));
        hypergroup.setForeground(display.getSystemColor(SWT.COLOR_BLUE));
        hypergroup.setHyperlinkUnderlineMode(HyperlinkGroup.UNDERLINE_HOVER);

        Label label = kit.createSeparator(form.getBody(), SWT.HORIZONTAL);
        TableWrapData wrapgrid = new TableWrapData(TableWrapData.FILL_GRAB);
        label.setLayoutData(wrapgrid);

        FormText text = kit.createFormText(form.getBody(), true);
        wrapgrid = new TableWrapData(TableWrapData.FILL);
        text.setLayoutData(wrapgrid);
        text.setText(JSmoothResources.TEXT_HELP_WELCOME, true, false);

        return top;
    }

    public boolean apply() {
        return false;
    }

    protected void configureResources() {
        setImage(JSmoothResources.IMG_SWITCHER_WELCOME);
        setToolTip("Welcome");
    }

    public void load() {
        // Do nothing.
    }

}


text:
package week.of.awesome;

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

import com.badlogic.gdx.math.Vector2;

public class Level {
	private List<Tile> tiles;
	private List<Spawner> spawners = new ArrayList<Spawner>();
	private Collection<Tile> goalTiles = new ArrayList<Tile>();
	private Collection<Tile> lockTiles = new ArrayList<Tile>();
	private Inventory inventory = new Inventory();
	private String name;
	private int number;
	private int numRescuedNeeded = 5;
	private int width;
	private int height;

	public Level(int number, String name, List<List<Tile>> tileGrid, int numRescuedNeeded) {
		this.number = number;
		this.name = name;
		this.numRescuedNeeded = numRescuedNeeded;

		width = tileGrid.get(0).size();
		height = tileGrid.size();
		tiles = new ArrayList<Tile>(width*height);

		// need to init up to full size
		for (int i = 0; i < width * height; ++i) {
			tiles.add(null);
		}

		// add tiles to the level
		int y = height-1;
		for (List<Tile> row : tileGrid) {
			int x = 0;
			for (Tile tile : row) {
				setTile(tile, x, y);
				++x;
			}
			--y;
		}
	}

	public String getName() { return name; }
	public int getNumber() { return number; }
	public int getNumRescuedNeeded() { return numRescuedNeeded; }
	public Inventory getInventory() { return inventory; }
	public int getWidth() { return width; }
	public int getHeight() { return height; }

	public void setTile(Tile tile, int x, int y) {
		tiles.set(index(x, y), tile);

		if (tile == null) { return; }

		tile.setPosition(new Vector2(x, y));

		if (tile.getType() == Tile.Type.START) {
			spawners.add(new Spawner(tile));
		}
		else if (tile.getType() == Tile.Type.GOAL) {
			goalTiles.add(tile);
		}
		else if (tile.getType() == Tile.Type.LOCK) {
			lockTiles.add(tile);
		}
	}

	public Tile getTile(int x, int y) {
		if (x < 0 || y < 0 || x >= width || y >= height) { return null; }
		return tiles.get(index(x, y));
	}

	public List<Spawner> getSpawners() {
		return spawners;
	}

	public Collection<Tile> getGoalTiles() {
		return goalTiles;
	}

	public Collection<Tile> getLockTiles() {
		return lockTiles;
	}

	public void removeLockTiles() {
		for (Tile lock : lockTiles) {
			setTile(null, (int)lock.getPosition().x, (int)lock.getPosition().y);
		}
		lockTiles.clear();
	}

	public boolean hasSpawnRemaining() {
		for (Spawner spawner : spawners) {
			if (spawner.getSpawnRemaining() > 0) { return true; }
		}
		return false;
	}

	public int getSpawnRemaining() {
		int remaining = 0;
		for (Spawner spawner : spawners) {
			remaining += spawner.getSpawnRemaining();
		}
		return remaining;
	}

	private int index(int x, int y) {
		return y * width + x;
	}
}


text:
import moment from 'moment'
import firstDayOfEachWeek from './firstDayOfEachWeek'

describe('First day of each week finder', () => {
  it('Handles a month where the first day falls on a Sunday', () => {
    const firstDayOfCalendar = moment('2016-05-01')
    const mayIndex = 4
    const sundays = firstDayOfEachWeek(firstDayOfCalendar, mayIndex)

    expect((sundays[0].format('YYYY-MM-DD'))).toEqual('2016-05-01')
    expect((sundays[1].format('YYYY-MM-DD'))).toEqual('2016-05-08')
    expect((sundays[2].format('YYYY-MM-DD'))).toEqual('2016-05-15')
    expect((sundays[3].format('YYYY-MM-DD'))).toEqual('2016-05-22')
    expect((sundays[4].format('YYYY-MM-DD'))).toEqual('2016-05-29')
  })

  it('Handles a month where the first day does not fall on a Sunday', () => {
    const firstDayOfCalendar = moment('2016-05-29')
    const juneIndex = 5
    const sundays = firstDayOfEachWeek(firstDayOfCalendar, juneIndex)

    expect((sundays[0].format('YYYY-MM-DD'))).toEqual('2016-05-29')
    expect((sundays[1].format('YYYY-MM-DD'))).toEqual('2016-06-05')
    expect((sundays[2].format('YYYY-MM-DD'))).toEqual('2016-06-12')
    expect((sundays[3].format('YYYY-MM-DD'))).toEqual('2016-06-19')
    expect((sundays[4].format('YYYY-MM-DD'))).toEqual('2016-06-26')
  })
})


text:
BEGIN;
UPDATE portal_location
  SET q_stmt = REPLACE(q_stmt, 'please visit cps.edu/readytolearn', 'please visit cps.edu/readytolearn.');
COMMIT;


text:
public class assign5
{
 public static void main(String[] args)
 {
  System.out.println("___Area and Perimeter of Circle___");
  int x=Integer.parseInt(args[0]);
  System.out.println("You entered radius of circle_" +args[0] );
  System.out.println("Perimeter : "+ 2 * 3.14* x);
  System.out.println("Area :   "   + 3.14* x * x);
 }

}


text:
using System;

class Elevator
{
    static void Main()
    {
        int peopleN = int.Parse(Console.ReadLine());
        int capacityP = int.Parse(Console.ReadLine());

        int courses = (int)Math.Ceiling((double)peopleN / capacityP);
        Console.WriteLine(courses);
    }
}


text:
package net.opengis.gml.impl;
/**
 * A document containing one dictionaryEntry(@http://www.opengis.net/gml) element.
 *
 * This is a complex type.
 */
public class DictionaryEntryDocumentImpl extends org.apache.xmlbeans.impl.values.XmlComplexContentImpl implements net.opengis.gml.DictionaryEntryDocument
{
    private static final long serialVersionUID = 1L;

    public DictionaryEntryDocumentImpl(org.apache.xmlbeans.SchemaType sType)
    {
        super(sType);
    }

    private static final javax.xml.namespace.QName DICTIONARYENTRY$0 =
        new javax.xml.namespace.QName("http://www.opengis.net/gml", "dictionaryEntry");
    private static final org.apache.xmlbeans.QNameSet DICTIONARYENTRY$1 = org.apache.xmlbeans.QNameSet.forArray( new javax.xml.namespace.QName[] {
        new javax.xml.namespace.QName("http://www.opengis.net/gml", "definitionMember"),
        new javax.xml.namespace.QName("http://www.opengis.net/gml", "dictionaryEntry"),
    });

    /**
     * Gets the "dictionaryEntry" element
     */
    public net.opengis.gml.DictionaryEntryType getDictionaryEntry()
    {
        synchronized (monitor())
        {
            check_orphaned();
            net.opengis.gml.DictionaryEntryType target = null;
            target = (net.opengis.gml.DictionaryEntryType)get_store().find_element_user(DICTIONARYENTRY$1, 0);
            if (target == null)
            {
                return null;
            }
            return target;
        }
    }

    /**
     * Sets the "dictionaryEntry" element
     */
     public void setDictionaryEntry(net.opengis.gml.DictionaryEntryType dictionaryEntry)
    {
        synchronized (monitor())
        {
            check_orphaned();
            net.opengis.gml.DictionaryEntryType target = null;
            target = (net.opengis.gml.DictionaryEntryType)get_store().find_element_user(DICTIONARYENTRY$1, 0);
            if (target == null)
            {
                target = (net.opengis.gml.DictionaryEntryType)get_store().add_element_user(DICTIONARYENTRY$0);
            }
            target.set(dictionaryEntry);
        }
    }

    /**
     * Appends and returns a new empty "dictionaryEntry" element
     */
    public net.opengis.gml.DictionaryEntryType addNewDictionaryEntry()
    {
        synchronized (monitor())
        {
            check_orphaned();
            net.opengis.gml.DictionaryEntryType target = null;
            target = (net.opengis.gml.DictionaryEntryType)get_store().add_element_user(DICTIONARYENTRY$0);
            return target;
        }
    }
}


text:
using System;
using System.Collections.Generic;
using System.Text;
using Alachisoft.NCache.Common;
using Alachisoft.NCache.Runtime.Exceptions;
using System.IO;
using Alachisoft.NCache.Common.Configuration;
using Alachisoft.NCache.Config;

namespace Alachisoft.NCache.Management.MappingConfiguration
{
    public class MappingConfigurationManager
    {
        static string m_configDir = DIRNAME;
        static string m_configFileName = FILENAME;
        static string DIRNAME = "Config";
        static string FILENAME = "server-end-point.ncconf";
        private static object _syncRoot = new object();

        private static void CombinePath()
        {
            m_configDir = AppUtil.InstallDir;

            if (m_configDir == null || m_configDir.Length == 0)
            {
                throw new ManagementException("Missing installation folder information");
            }

            m_configDir = Path.Combine(m_configDir, DIRNAME);
            if (!Directory.Exists(m_configDir))
                Directory.CreateDirectory(m_configDir);

            m_configFileName = Path.Combine(m_configDir, FILENAME);
        }

        private static MappingConfiguration.Dom.MappingConfiguration LoadXml()
        {
            MappingConfiguration.Dom.MappingConfiguration config= null;
            lock (_syncRoot)
            {
                if (String.IsNullOrEmpty(m_configFileName))
                    CombinePath();
                try
                {
                    ConfigurationBuilder configBuilder = new ConfigurationBuilder(m_configFileName);
                    configBuilder.RegisterRootConfigurationObject(typeof(Alachisoft.NCache.Management.MappingConfiguration.Dom.MappingConfiguration));
                    configBuilder.ReadConfiguration();

                    MappingConfiguration.Dom.MappingConfiguration mappingConfiguration = null;
                    Object[] configuration = configBuilder.Configuration;

                    if (configuration != null && configuration.Length > 0)
                    {
                        for (int i = 0; i < configuration.Length; i++)
                        {
                            mappingConfiguration = configuration[i] as MappingConfiguration.Dom.MappingConfiguration;
                            break;
                        }
                    }

                    config = mappingConfiguration;
                }
                catch (Exception)
                { }

                if (config == null)
                    config = new Alachisoft.NCache.Management.MappingConfiguration.Dom.MappingConfiguration();

                if (config.ManagementIPMapping == null)
                    config.ManagementIPMapping = new ServerMapping();

                if (config.ClientIPMapping == null)
                    config.ClientIPMapping = new ServerMapping();
            }
            return config;
        }

        private static string ToXml(MappingConfiguration.Dom.MappingConfiguration config)
        {
            StringBuilder sb = new StringBuilder();
            object[] configuration = new object[1];
            configuration[0] = config;
            ConfigurationBuilder cfgBuilder = new ConfigurationBuilder(configuration);
            cfgBuilder.RegisterRootConfigurationObject(typeof(ClientConfiguration.Dom.ClientConfiguration));
            sb.Append(cfgBuilder.GetXmlString());
            return sb.ToString();
        }

        private static void SaveConfiguration(MappingConfiguration.Dom.MappingConfiguration config)
        {
            lock (_syncRoot)
            {
                if (m_configFileName == null || m_configFileName == "")
                    CombinePath();

                FileStream fs = null;
                StreamWriter sw = null;

                try
                {
                    fs = new FileStream(m_configFileName, FileMode.Create);
                    sw = new StreamWriter(fs);
                    sw.Write(ToXml(config));
                    sw.Flush();
                }
                catch (Exception e)
                {
                    throw new ManagementException(e.Message, e);
                }
                finally
                {
                    if (sw != null) sw.Close();
                    if (fs != null) fs.Close();
                }
            }
        }

        public static void UpdateMappingConfiguration(MappingConfiguration.Dom.MappingConfiguration configuration)
        {
            MappingConfiguration.Dom.MappingConfiguration config = LoadXml();
            if(configuration.ManagementIPMapping != null)
            {
                config.ManagementIPMapping = new ServerMapping(Management.Util.ManagementWorkFlow.GetUpdatedMappingList(config.ManagementIPMapping.MappingServers, configuration.ManagementIPMapping.MappingServers));
            }
            if (configuration.ClientIPMapping != null)
            {
                config.ClientIPMapping = new ServerMapping(Management.Util.ManagementWorkFlow.GetUpdatedMappingList(config.ClientIPMapping.MappingServers, configuration.ClientIPMapping.MappingServers));
            }
            SaveConfiguration(config);
        }

        public static MappingConfiguration.Dom.MappingConfiguration GetMappingConfiguration()
        {
            MappingConfiguration.Dom.MappingConfiguration config = LoadXml();
            return config;
        }
    }
}


text:
\hypertarget{unionun__rtcc0}{\section{un\-\_\-rtcc0 Union Reference}
\label{unionun__rtcc0}\index{un\-\_\-rtcc0@{un\-\_\-rtcc0}}
}
\subsection*{Data Fields}
\begin{DoxyCompactItemize}
\item
\hypertarget{unionun__rtcc0_aa4b449cf68d6ec72a8eb169e1d70a082}{unsigned char {\bfseries rtcc0}}\label{unionun__rtcc0_aa4b449cf68d6ec72a8eb169e1d70a082}

\item
\hypertarget{unionun__rtcc0_a662fda767bb130c24c84919d3eae1990}{\hyperlink{struct_____b_i_t_s8}{\-\_\-\-\_\-\-B\-I\-T\-S8} {\bfseries B\-I\-T}}\label{unionun__rtcc0_a662fda767bb130c24c84919d3eae1990}

\end{DoxyCompactItemize}

\subsection{Detailed Description}

Definition at line 198 of file iodefine.\-h.

The documentation for this union was generated from the following file\-:\begin{DoxyCompactItemize}
\item
C\-:/\-Users/\-Omega\-Dog/\-Dropbox/\-Kiln/\-Open\-R\-F/\-Protocol\-\_\-\-Platform/\-Source\-Code/\-Application/\-S\-X1231 Simple Test Application/iodefine.\-h\end{DoxyCompactItemize}


text:
'use strict';

const sinon = require('sinon');
const BaseStep = require('../../lib/install/base-step');

module.exports = class DummyStep extends BaseStep {
  constructor(action, options) {
    if (typeof action == 'object') {
      ([action, options] = [options, action]);
    }
    super(options);
    this.action = action;
    sinon.spy(this, 'start');
  }

  start(state, install) {
    return new Promise((resolve, reject) => {
      this.resolve = resolve;
      this.reject = reject;
      this.action && this.action(this, state, install);
    });
  }
};


text:
<?php

declare(strict_types=1);

namespace Centreon\Domain\Option;

class OptionException extends \Exception
{
}


text:
package ch15;

public class RunThreads implements Runnable {

	public static void main(String[] args) {
		// Make one Runnable instance
		RunThreads runner = new RunThreads();

		// Make the threads
		Thread alpha = new Thread(runner);
		Thread beta = new Thread(runner);

		// Name the threads
		alpha.setName("Alpha thread");
		beta.setName("Beta thread");

		// Start the threads
		alpha.start();
		beta.start();
	}

	public void run() {
		for (int i = 0; i < 25; i++) {
			String threadName = Thread.currentThread().getName();
			System.out.println(threadName + " is running");
		}
	}
}


text:
<?xml version='1.0' encoding='utf-8' ?>
<!DOCTYPE section PUBLIC "-//OASIS//DTD DocBook XML V4.5//EN" "http://www.oasis-open.org/docbook/xml/4.5/docbookx.dtd" [
<!ENTITY % BOOK_ENTITIES SYSTEM "cloudstack.ent">
%BOOK_ENTITIES;
]>

<!-- Licensed to the Apache Software Foundation (ASF) under one
    or more contributor license agreements.  See the NOTICE file
    distributed with this work for additional information
    regarding copyright ownership.  The ASF licenses this file
    to you under the Apache License, Version 2.0 (the
    "License"); you may not use this file except in compliance
    with the License.  You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing,
    software distributed under the License is distributed on an
    "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
    KIND, either express or implied.  See the License for the
    specific language governing permissions and limitations
    under the License.
-->
<section id="events-log">
    <title>Event Logs</title>
    <para>There are two types of events logged in the &PRODUCT; Event Log. Standard events log
        the success or failure of an event and can be used to identify jobs or processes that have
        failed. There are also long running job events. Events for asynchronous jobs log when a job
        is scheduled, when it starts, and when it completes. Other long running synchronous jobs log
        when a job starts, and when it completes. Long running synchronous and asynchronous event
        logs can be used to gain more information on the status of a pending job or can be used to
        identify a job that is hanging or has not started. The following sections provide more
        information on these events..</para>
</section>


text:
<?php

namespace Rhapsody\ForumBundle\Form\Type;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;

/**
 *
 * @author    Sean W. Quinn
 * @category  Rhapsody ForumBundle
 * @package   Rhapsody\ForumBundle\Form\Type
 * @copyright Copyright (c) 2013 Rhapsody Project
 * @license   http://opensource.org/licenses/MIT
 * @version   $Id$
 * @since     1.0
 */
class ForumType extends AbstractType
{
	private $class;

	/**
	* @param string $class The Forum class name
	*/
	public function __construct($class)
	{
		$this->class = $class;
	}

	/**
	 * (non-PHPdoc)
	 * @see \Symfony\Component\Form\AbstractType::buildForm()
	 */
	public function buildForm(FormBuilderInterface $builder, array $options)
	{
		parent::buildForm($builder, $options);
		$builder->add('name', 'text');
		$builder->add('description', 'textarea');
		$builder->add('enabled', 'checkbox');
		$builder->add('order', 'number');
	}

	public function getName()
	{
		return 'rhapsody_forum_form_type_forum';
	}

	public function setDefaultOptions(OptionsResolverInterface $resolver)
	{
		$resolver->setDefaults(array(
				'csrf_protection'   => true,
				'data_class'        => $this->class,
				'intention'         => 'forum'
		));
	}
}


text:
Posts = new Mongo.Collection('posts');

Posts.allow({
    update: function (userId, post) { return ownsDocument(userId, post); },
    remove: function (userId, post) { return ownsDocument(userId, post); }
});

/**
 * This deny update callback, verifies only url or title are being modified,
 * else prevents the update action from occurring.
 *
 *  (using underscore, without returns the difference of fieldNames and the
 *  listed fields, in an array. If there are fields remaining (length > 0),
 *  the deny returns true, meaning to deny the operation request.
 */
Posts.deny({
    update: function (userId, post, fieldNames) {
        return (_.without(fieldNames, 'url', 'title').length > 0);
    }
});

/**
 * This deny update callback, verifies the submitted post contains valid data
 * (a title and url).
 */
Posts.deny({
    update: function (userId, post, fieldNames, modifier) {
        var errors = validatePost(modifier.$set);
        return errors.title || errors.url;
    }
});

Meteor.methods({
    postInsert: function (postAttributes) {
        check(Meteor.userId(), String);
        check(postAttributes, {
            title: String,
            url: String
        });

        var errors = validatePost(postAttributes);
        if (errors.title || errors.url) {
            throw new Meteor.Error('invalid-post', "You must set a title and URL for your post");
        }

        var postWithSameLink = Posts.findOne({ url: postAttributes.url });
        if (postWithSameLink) {
            return {
                postExists: true,
                _id: postWithSameLink._id
            }
        }

        var user = Meteor.user();
        var post = _.extend(postAttributes, {
            userId: user._id,
            author: user.username,
            submitted: new Date(),
            upVoters: [],
            votes: 0,
            commentsCount: 0
        });

        // Due to latency compensation, calling this method in both environments
        // (client & server), make sure this if statement is ony executed on the
        // server side call
        if (Meteor.isServer) {
            var shortUrl = Bitly.shortenURL(post.url);
            if (post.url && shortUrl) {
                post.shortUrl = shortUrl;
            }
        }

        var postId = Posts.insert(post);

        return { _id: postId };
    },
    upvote: function (postId) {
        check(this.userId, String);
        check(postId, String);

        var affected = Posts.update({
            _id: postId,
            upVoters: {$ne: this.userId}
        }, {
            $addToSet: {upVoters: this.userId},
            $inc: {votes: 1}
        });
        if (!affected) {
            throw new Meteor.Error('invalid', "You weren't able to update that post");
        }
    }
});

validatePost = function (post) {
    var errors = {};

    if (!post.title) {
        errors.title = 'Please fill in a headline'
    }

    if (!post.url) {
        errors.url = 'Please fill in a URL'
    }

    return errors;
};


text:
module SilverSpoon
  VERSION = "0.0.2"
end


text:
Wed Nov 14 08:01:03 EST 2012
# Plant / Garden DB
Rails application to store plants in our garden. Include pictures with clickable
areas that link to the plant in the picture. Similar to how flickr picture can
be tagged.

Plant information with accurate pictures. Allow ppl to upload their own photos
and tag them.

Finding accurate plant information is difficult and it's scattered across
various sites and/or books. Provide community edited plant database that is
searchable. Allow people to modify details like growing information, flowering
etc.

The plant DB is the MVP. Allow CRUD plus powerful searching.

[Herbage] (http://herbage.herokuapp.com/)

Features:

 * Searchable catalogue of plants
 * Pictures of garden tagged with plant information
 * Individual Plant pages.
 * Map of areas with plantings.
 * Customised dashboard with recommendations, upcoming things to do, news feed?
 * scrap book page with plants, maybe collect plants / pictures u like.
 * Recommendations on plants or feedback on how they are going.
 * Map with flowering slider, showing what will be flowering at particular times so you can plan a garden around it.
 * Intelligent agent to recommend fixes/solutions to common plant issues. ie describe leaf colour, soil condition, etc and come up with some solutions to try.
 * Link to sellers of plants, seeds and related equipment.
 * Social by having notifications, follow other people and forum/comments on
   peoples work
 * Landscape designers and other professionals could have personalised space to
   showcase their work with pictures and explaination. As an alternative to
   having their own site?
 * Concept of tools for planning gardens and choosing plants.
   * Flowering chooser
   * Fruit / Vegie Chooser
 * Companion plant recommendations with user feedback

## Location

https://bitbucket.org/lambda_foo/herbage

## Technologies

* Rails 3.2 or higher
* Postgres 9
* Heroku hosting

## Data Model

 * Map -> basic dimensions, geolocation, plan/schematic?
 * Plant -> individual species

 * Garden -> a garden for specific site, which can be broken up into a number of
   'Sites'

Store data as markdown within the application and render it on demand?

Provide github like markdown editing page with preview button that works via
AJAX.

Provide rails controller that takes markdown request and returns html.

## Links and Inspiration

  * [http://www.frecklegirl.com/blog/2005/04/12/knitters-help/](http://www.frecklegirl.com/blog/2005/04/12/knitters-help/)
  * [http://codemonkey.ravelry.com/2010/03/24/ravelry-runs-on-2010/](http://codemonkey.ravelry.com/2010/03/24/ravelry-runs-on-2010/)

 Plant: Describes a species of plant.
 Plant Location: Physical location for a plant

 Gardener: person who owns or manages a garden(s)

 Garden: bounded physical location, associated with a Gardener containing many
 plants

### Deploying to Heroku

Commit changes and `git push heroku`

Run rake commands on heroku

  heroku run ...
  eg
  heroku run rake db:seed

See
[https://devcenter.heroku.com/articles/rails3](https://devcenter.heroku.com/articles/rails3)
for more details.

[Herbage] (http://herbage.herokuapp.com/)


text:
#include <stdio.h>
#include <stdlib.h>
#include <sys/resource.h>
#include <assert.h>
#include "liquid.h"

// Helper function to keep code base small
void benchmark_flexframesync(
    struct rusage *_start,
    struct rusage *_finish,
    unsigned long int *_num_iterations)
{
    *_num_iterations /= 128;
    unsigned long int i;

    // create flexframegen object
    flexframegenprops_s fgprops;
    flexframegenprops_init_default(&fgprops);
    fgprops.check      = LIQUID_CRC_32;
    fgprops.fec0       = LIQUID_FEC_NONE;
    fgprops.fec1       = LIQUID_FEC_NONE;
    fgprops.mod_scheme = LIQUID_MODEM_QPSK;
    flexframegen fg = flexframegen_create(&fgprops);

    // generate the frame
    unsigned int payload_len = 8;
    unsigned char header[14];
    unsigned char payload[payload_len];
    flexframegen_assemble(fg, header, payload, payload_len);
    unsigned int frame_len = flexframegen_getframelen(fg);
    float complex frame[frame_len];
    flexframegen_write_samples(fg, frame, frame_len);

    // add some noise
    for (i=0; i<frame_len; i++)
        frame[i] += 0.02f*(randnf() + _Complex_I*randnf());

    // create flexframesync object
    flexframesync fs = flexframesync_create(NULL, NULL);

    // start trials
    getrusage(RUSAGE_SELF, _start);
    for (i=0; i<(*_num_iterations); i++) {
        flexframesync_execute(fs, frame, frame_len);
    }
    getrusage(RUSAGE_SELF, _finish);

    // print frame data statistics
    //flexframesync_print(fs);

    // destroy objects
    flexframegen_destroy(fg);
    flexframesync_destroy(fs);
}


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="bambi.andrapix"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="23"
        android:targetSdkVersion="25" />

    <meta-data
        android:name="android.support.VERSION"
        android:value="26.0.0-alpha1" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme" >
        <activity android:name="bambi.andrapix.MainActivity" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <provider
            android:name="com.android.tools.fd.runtime.InstantRunContentProvider"
            android:authorities="bambi.andrapix.com.android.tools.fd.runtime.InstantRunContentProvider"
            android:multiprocess="true" />
    </application>

</manifest>


text:
Given the runner interface, implement func race, which takes a distance and
multiple runners, and calculates the winner based on the shortest time. Then,
implement several runners.

```go
type runner interface {
	name() string
	run(distance int) (seconds int)
}

func race( ??? ) (winner string) {
	// ???
}
```

Be creative. Some runners might run at a fixed speed; some might slow down with
the distance; some might cheat and teleport?


text:
#pragma once

#ifndef MECHLABSCREEN_H
#define MECHLABSCREEN_H

#ifndef LOGISTICSSCREEN_H
#include "mechgui/logisticsscreen.h"
#endif

#ifndef ATTRIBUTEMETER_H
#include "attributemeter.h"
#endif

#ifndef COMPONENTLISTBOX_H
#include "componentlistbox.h"
#endif

#ifndef SIMPLECAMERA_H
#include "simplecamera.h"
#endif

#define MECH_LAB_ATTRIBUTE_METER_COUNT 9
class FitIniFile;
class LogisticsVariant;
class LogisticsComponent;
class LogisticsVariantDialog;
class LogisticsAcceptVariantDialog;

/**************************************************************************************************
CLASS DESCRIPTION
MechLabScreen:
**************************************************************************************************/
class MechLabScreen : public LogisticsScreen
{
public:
	MechLabScreen(void);
	virtual ~MechLabScreen(void);

	int32_t init(FitIniFile&);

	virtual void begin(void);
	virtual void end(void);
	virtual void update(void);
	virtual void render(int32_t xOffset, int32_t yOffset);

	virtual int32_t handleMessage(uint32_t, uint32_t);

	void setComponent(LogisticsComponent* pComponent, bool bMessageFromLB = 0);
	int32_t addComponent(LogisticsComponent* pComponent, int32_t& x, int32_t& y);
	void beginDrag(LogisticsComponent* pComponent);
	void endDrag();

	int32_t canAddComponent(LogisticsComponent* pComponent);

	static MechLabScreen* instance() { return s_instance; }

	bool canRemoveComponent(LogisticsComponent* pComp);

private:
	MechLabScreen(const MechLabScreen& src);
	MechLabScreen& operator=(const MechLabScreen& echLabScreen);
	static MechLabScreen* s_instance;

	static LogisticsVariantDialog* saveDlg;
	static LogisticsAcceptVariantDialog* acceptDlg;

	LogisticsVariantDialog* pCurDialog;

	LogisticsVariant* pVariant;
	LogisticsComponent* pSelectedComponent;
	int32_t selI;
	int32_t selJ;

	ComponentIconListBox componentListBox;
	aComboBox variantList;

	AttributeMeter attributeMeters[MECH_LAB_ATTRIBUTE_METER_COUNT];

	aObject componentIcons[128];
	int32_t componentCount;

	aObject payloadIcon;

	aObject dragIcon;

	LogisticsComponent* pDragComponent;
	LogisticsComponent* pCurComponent;

	void showJumpJetItems(bool doshow);

	void updateDiagram(void);

	float originalCost;

	aObject selRects[2][5];
	aObject selJumpJetRect;
	aObject* selRect;

	bool bSaveDlg;
	bool bDragLeft;

	SimpleCamera camera;

	const std::wstring_view& varName;

	static RECT sensorRects[4];
	static int32_t sensorHelpIDs[4];

	float countDownTime;
	float curCount;
	float previousAmount;
	float oldCBillsAmount;

	float oldHeat;
	float heatTime;
	bool flashHeatRange;

	float oldArmor;
	float newArmor;
	float armorTime;

	bool bErrorDlg;

	// HELPER FUNCTIONS
	void getMouseDiagramCoords(int32_t& x, int32_t& y);
	void getMouseDiagramCoords(int32_t screenX, int32_t screenY, int32_t& x, int32_t& y);

	void diagramToScreen(int32_t i, int32_t j, int32_t& x, int32_t& y);
	int32_t selectFirstDiagramComponent(void);
	int32_t selectFirstLBComponent(void);
	void updateDiagramInput(void);
	void swapVariant(void);
	void updateHeatMeter(void);
	void updateArmorMeter(void);
	void removeComponent(int32_t i, int32_t j);
};

#endif // end of file ( MechLabScreen.h )