/* pngerror.c - stub functions for i/o and memory allocation
 *
 * Last changed in libpng 1.6.31 [July 27, 2017]
 * Copyright (c) 1998-2002,2004,2006-2017 Glenn Randers-Pehrson
 * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
 * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
 *
 * This code is released under the libpng license.
 * For conditions of distribution and use, see the disclaimer
 * and license in png.h
 *
 * This file provides a location for all error handling.  Users who
 * need special error handling are expected to write replacement functions
 * and use png_set_error_fn() to use those functions.  See the instructions
 * at each function.
 */

#include "pngpriv.h"

#if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)

static PNG_FUNCTION(void, png_default_error,PNGARG((png_const_structrp png_ptr,
    png_const_charp error_message)),PNG_NORETURN);

#ifdef PNG_WARNINGS_SUPPORTED
static void /* PRIVATE */
png_default_warning PNGARG((png_const_structrp png_ptr,
    png_const_charp warning_message));
#endif /* WARNINGS */

/* This function is called whenever there is a fatal error.  This function
 * should not be changed.  If there is a need to handle errors differently,
 * you should supply a replacement error function and use png_set_error_fn()
 * to replace the error function at run-time.
 */
#ifdef PNG_ERROR_TEXT_SUPPORTED
PNG_FUNCTION(void,PNGAPI
png_error,(png_const_structrp png_ptr, png_const_charp error_message),
    PNG_NORETURN)
{
#ifdef PNG_ERROR_NUMBERS_SUPPORTED
   char msg[16];
   if (png_ptr != NULL)
   {
      if ((png_ptr->flags &
         (PNG_FLAG_STRIP_ERROR_NUMBERS|PNG_FLAG_STRIP_ERROR_TEXT)) != 0)
      {
         if (*error_message == PNG_LITERAL_SHARP)
         {
            /* Strip "#nnnn " from beginning of error message. */
            int offset;
            for (offset = 1; offset<15; offset++)
               if (error_message[offset] == ' ')
                  break;

            if ((png_ptr->flags & PNG_FLAG_STRIP_ERROR_TEXT) != 0)
            {
               int i;
               for (i = 0; i < offset - 1; i++)
                  msg[i] = error_message[i + 1];
               msg[i - 1] = '\0';
               error_message = msg;
            }

            else
               error_message += offset;
         }

         else
         {
            if ((png_ptr->flags & PNG_FLAG_STRIP_ERROR_TEXT) != 0)
            {
               msg[0] = '0';
               msg[1] = '\0';
               error_message = msg;
            }
         }
      }
   }
#endif
   if (png_ptr != NULL && png_ptr->error_fn != NULL)
      (*(png_ptr->error_fn))(png_constcast(png_structrp,png_ptr),
          error_message);

   /* If the custom handler doesn't exist, or if it returns,
      use the default handler, which will not return. */
   png_default_error(png_ptr, error_message);
}
#else
PNG_FUNCTION(void,PNGAPI
png_err,(png_const_structrp png_ptr),PNG_NORETURN)
{
   /* Prior to 1.5.2 the error_fn received a NULL pointer, expressed
    * erroneously as '\0', instead of the empty string "".  This was
    * apparently an error, introduced in libpng-1.2.20, and png_default_error
    * will crash in this case.
    */
   if (png_ptr != NULL && png_ptr->error_fn != NULL)
      (*(png_ptr->error_fn))(png_constcast(png_structrp,png_ptr), "");

   /* If the custom handler doesn't exist, or if it returns,
      use the default handler, which will not return. */
   png_default_error(png_ptr, "");
}
#endif /* ERROR_TEXT */

/* Utility to safely appends strings to a buffer.  This never errors out so
 * error checking is not required in the caller.
 */
size_t
png_safecat(png_charp buffer, size_t bufsize, size_t pos,
    png_const_charp string)
{
   if (buffer != NULL && pos < bufsize)
   {
      if (string != NULL)
         while (*string != '\0' && pos < bufsize-1)
           buffer[pos++] = *string++;

      buffer[pos] = '\0';
   }

   return pos;
}

#if defined(PNG_WARNINGS_SUPPORTED) || defined(PNG_TIME_RFC1123_SUPPORTED)
/* Utility to dump an unsigned value into a buffer, given a start pointer and
 * and end pointer (which should point just *beyond* the end of the buffer!)
 * Returns the pointer to the start of the formatted string.
 */
png_charp
png_format_number(png_const_charp start, png_charp end, int format,
    png_alloc_size_t number)
{
   int count = 0;    /* number of digits output */
   int mincount = 1; /* minimum number required */
   int output = 0;   /* digit output (for the fixed point format) */

   *--end = '\0';

   /* This is written so that the loop always runs at least once, even with
    * number zero.
    */
   while (end > start && (number != 0 || count < mincount))
   {

      static const char digits[] = "0123456789ABCDEF";

      switch (format)
      {
         case PNG_NUMBER_FORMAT_fixed:
            /* Needs five digits (the fraction) */
            mincount = 5;
            if (output != 0 || number % 10 != 0)
            {
               *--end = digits[number % 10];
               output = 1;
            }
            number /= 10;
            break;

         case PNG_NUMBER_FORMAT_02u:
            /* Expects at least 2 digits. */
            mincount = 2;
            /* FALLTHROUGH */

         case PNG_NUMBER_FORMAT_u:
            *--end = digits[number % 10];
            number /= 10;
            break;

         case PNG_NUMBER_FORMAT_02x:
            /* This format expects at least two digits */
            mincount = 2;
            /* FALLTHROUGH */

         case PNG_NUMBER_FORMAT_x:
            *--end = digits[number & 0xf];
            number >>= 4;
            break;

         default: /* an error */
            number = 0;
            break;
      }

      /* Keep track of the number of digits added */
      ++count;

      /* Float a fixed number here: */
      if ((format == PNG_NUMBER_FORMAT_fixed) && (count == 5) && (end > start))
      {
         /* End of the fraction, but maybe nothing was output?  In that case
          * drop the decimal point.  If the number is a true zero handle that
          * here.
          */
         if (output != 0)
            *--end = '.';
         else if (number == 0) /* and !output */
            *--end = '0';
      }
   }

   return end;
}
#endif

#ifdef PNG_WARNINGS_SUPPORTED
/* This function is called whenever there is a non-fatal error.  This function
 * should not be changed.  If there is a need to handle warnings differently,
 * you should supply a replacement warning function and use
 * png_set_error_fn() to replace the warning function at run-time.
 */
void PNGAPI
png_warning(png_const_structrp png_ptr, png_const_charp warning_message)
{
   int offset = 0;
   if (png_ptr != NULL)
   {
#ifdef PNG_ERROR_NUMBERS_SUPPORTED
   if ((png_ptr->flags &
       (PNG_FLAG_STRIP_ERROR_NUMBERS|PNG_FLAG_STRIP_ERROR_TEXT)) != 0)
#endif
      {
         if (*warning_message == PNG_LITERAL_SHARP)
         {
            for (offset = 1; offset < 15; offset++)
               if (warning_message[offset] == ' ')
                  break;
         }
      }
   }
   if (png_ptr != NULL && png_ptr->warning_fn != NULL)
      (*(png_ptr->warning_fn))(png_constcast(png_structrp,png_ptr),
          warning_message + offset);
   else
      png_default_warning(png_ptr, warning_message + offset);
}

/* These functions support 'formatted' warning messages with up to
 * PNG_WARNING_PARAMETER_COUNT parameters.  In the format string the parameter
 * is introduced by @<number>, where 'number' starts at 1.  This follows the
 * standard established by X/Open for internationalizable error messages.
 */
void
png_warning_parameter(png_warning_parameters p, int number,
    png_const_charp string)
{
   if (number > 0 && number <= PNG_WARNING_PARAMETER_COUNT)
      (void)png_safecat(p[number-1], (sizeof p[number-1]), 0, string);
}

void
png_warning_parameter_unsigned(png_warning_parameters p, int number, int format,
    png_alloc_size_t value)
{
   char buffer[PNG_NUMBER_BUFFER_SIZE];
   png_warning_parameter(p, number, PNG_FORMAT_NUMBER(buffer, format, value));
}

void
png_warning_parameter_signed(png_warning_parameters p, int number, int format,
    png_int_32 value)
{
   png_alloc_size_t u;
   png_charp str;
   char buffer[PNG_NUMBER_BUFFER_SIZE];

   /* Avoid overflow by doing the negate in a png_alloc_size_t: */
   u = (png_alloc_size_t)value;
   if (value < 0)
      u = ~u + 1;

   str = PNG_FORMAT_NUMBER(buffer, format, u);

   if (value < 0 && str > buffer)
      *--str = '-';

   png_warning_parameter(p, number, str);
}

void
png_formatted_warning(png_const_structrp png_ptr, png_warning_parameters p,
    png_const_charp message)
{
   /* The internal buffer is just 192 bytes - enough for all our messages,
    * overflow doesn't happen because this code checks!  If someone figures
    * out how to send us a message longer than 192 bytes, all that will
    * happen is that the message will be truncated appropriately.
    */
   size_t i = 0; /* Index in the msg[] buffer: */
   char msg[192];

   /* Each iteration through the following loop writes at most one character
    * to msg[i++] then returns here to validate that there is still space for
    * the trailing '\0'.  It may (in the case of a parameter) read more than
    * one character from message[]; it must check for '\0' and continue to the
    * test if it finds the end of string.
    */
   while (i<(sizeof msg)-1 && *message != '\0')
   {
      /* '@' at end of string is now just printed (previously it was skipped);
       * it is an error in the calling code to terminate the string with @.
       */
      if (p != NULL && *message == '@' && message[1] != '\0')
      {
         int parameter_char = *++message; /* Consume the '@' */
         static const char valid_parameters[] = "123456789";
         int parameter = 0;

         /* Search for the parameter digit, the index in the string is the
          * parameter to use.
          */
         while (valid_parameters[parameter] != parameter_char &&
            valid_parameters[parameter] != '\0')
            ++parameter;

         /* If the parameter digit is out of range it will just get printed. */
         if (parameter < PNG_WARNING_PARAMETER_COUNT)
         {
            /* Append this parameter */
            png_const_charp parm = p[parameter];
            png_const_charp pend = p[parameter] + (sizeof p[parameter]);

            /* No need to copy the trailing '\0' here, but there is no guarantee
             * that parm[] has been initialized, so there is no guarantee of a
             * trailing '\0':
             */
            while (i<(sizeof msg)-1 && *parm != '\0' && parm < pend)
               msg[i++] = *parm++;

            /* Consume the parameter digit too: */
            ++message;
            continue;
         }

         /* else not a parameter and there is a character after the @ sign; just
          * copy that.  This is known not to be '\0' because of the test above.
          */
      }

      /* At this point *message can't be '\0', even in the bad parameter case
       * above where there is a lone '@' at the end of the message string.
       */
      msg[i++] = *message++;
   }

   /* i is always less than (sizeof msg), so: */
   msg[i] = '\0';

   /* And this is the formatted message. It may be larger than
    * PNG_MAX_ERROR_TEXT, but that is only used for 'chunk' errors and these
    * are not (currently) formatted.
    */
   png_warning(png_ptr, msg);
}
#endif /* WARNINGS */

#ifdef PNG_BENIGN_ERRORS_SUPPORTED
void PNGAPI
png_benign_error(png_const_structrp png_ptr, png_const_charp error_message)
{
   if ((png_ptr->flags & PNG_FLAG_BENIGN_ERRORS_WARN) != 0)
   {
#     ifdef PNG_READ_SUPPORTED
         if ((png_ptr->mode & PNG_IS_READ_STRUCT) != 0 &&
            png_ptr->chunk_name != 0)
            png_chunk_warning(png_ptr, error_message);
         else
#     endif
      png_warning(png_ptr, error_message);
   }

   else
   {
#     ifdef PNG_READ_SUPPORTED
         if ((png_ptr->mode & PNG_IS_READ_STRUCT) != 0 &&
            png_ptr->chunk_name != 0)
            png_chunk_error(png_ptr, error_message);
         else
#     endif
      png_error(png_ptr, error_message);
   }

#  ifndef PNG_ERROR_TEXT_SUPPORTED
      PNG_UNUSED(error_message)
#  endif
}

void /* PRIVATE */
png_app_warning(png_const_structrp png_ptr, png_const_charp error_message)
{
   if ((png_ptr->flags & PNG_FLAG_APP_WARNINGS_WARN) != 0)
      png_warning(png_ptr, error_message);
   else
      png_error(png_ptr, error_message);

#  ifndef PNG_ERROR_TEXT_SUPPORTED
      PNG_UNUSED(error_message)
#  endif
}

void /* PRIVATE */
png_app_error(png_const_structrp png_ptr, png_const_charp error_message)
{
   if ((png_ptr->flags & PNG_FLAG_APP_ERRORS_WARN) != 0)
      png_warning(png_ptr, error_message);
   else
      png_error(png_ptr, error_message);

#  ifndef PNG_ERROR_TEXT_SUPPORTED
      PNG_UNUSED(error_message)
#  endif
}
#endif /* BENIGN_ERRORS */

#define PNG_MAX_ERROR_TEXT 196 /* Currently limited by profile_error in png.c */
#if defined(PNG_WARNINGS_SUPPORTED) || \
   (defined(PNG_READ_SUPPORTED) && defined(PNG_ERROR_TEXT_SUPPORTED))
/* These utilities are used internally to build an error message that relates
 * to the current chunk.  The chunk name comes from png_ptr->chunk_name,
 * which is used to prefix the message.  The message is limited in length
 * to 63 bytes. The name characters are output as hex digits wrapped in []
 * if the character is invalid.
 */
#define isnonalpha(c) ((c) < 65 || (c) > 122 || ((c) > 90 && (c) < 97))
static PNG_CONST char png_digit[16] = {
   '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
   'A', 'B', 'C', 'D', 'E', 'F'
};

static void /* PRIVATE */
png_format_buffer(png_const_structrp png_ptr, png_charp buffer, png_const_charp
    error_message)
{
   png_uint_32 chunk_name = png_ptr->chunk_name;
   int iout = 0, ishift = 24;

   while (ishift >= 0)
   {
      int c = (int)(chunk_name >> ishift) & 0xff;

      ishift -= 8;
      if (isnonalpha(c) != 0)
      {
         buffer[iout++] = PNG_LITERAL_LEFT_SQUARE_BRACKET;
         buffer[iout++] = png_digit[(c & 0xf0) >> 4];
         buffer[iout++] = png_digit[c & 0x0f];
         buffer[iout++] = PNG_LITERAL_RIGHT_SQUARE_BRACKET;
      }

      else
      {
         buffer[iout++] = (char)c;
      }
   }

   if (error_message == NULL)
      buffer[iout] = '\0';

   else
   {
      int iin = 0;

      buffer[iout++] = ':';
      buffer[iout++] = ' ';

      while (iin < PNG_MAX_ERROR_TEXT-1 && error_message[iin] != '\0')
         buffer[iout++] = error_message[iin++];

      /* iin < PNG_MAX_ERROR_TEXT, so the following is safe: */
      buffer[iout] = '\0';
   }
}
#endif /* WARNINGS || ERROR_TEXT */

#if defined(PNG_READ_SUPPORTED) && defined(PNG_ERROR_TEXT_SUPPORTED)
PNG_FUNCTION(void,PNGAPI
png_chunk_error,(png_const_structrp png_ptr, png_const_charp error_message),
    PNG_NORETURN)
{
   char msg[18+PNG_MAX_ERROR_TEXT];
   if (png_ptr == NULL)
      png_error(png_ptr, error_message);

   else
   {
      png_format_buffer(png_ptr, msg, error_message);
      png_error(png_ptr, msg);
   }
}
#endif /* READ && ERROR_TEXT */

#ifdef PNG_WARNINGS_SUPPORTED
void PNGAPI
png_chunk_warning(png_const_structrp png_ptr, png_const_charp warning_message)
{
   char msg[18+PNG_MAX_ERROR_TEXT];
   if (png_ptr == NULL)
      png_warning(png_ptr, warning_message);

   else
   {
      png_format_buffer(png_ptr, msg, warning_message);
      png_warning(png_ptr, msg);
   }
}
#endif /* WARNINGS */

#ifdef PNG_READ_SUPPORTED
#ifdef PNG_BENIGN_ERRORS_SUPPORTED
void PNGAPI
png_chunk_benign_error(png_const_structrp png_ptr, png_const_charp
    error_message)
{
   if ((png_ptr->flags & PNG_FLAG_BENIGN_ERRORS_WARN) != 0)
      png_chunk_warning(png_ptr, error_message);

   else
      png_chunk_error(png_ptr, error_message);

#  ifndef PNG_ERROR_TEXT_SUPPORTED
      PNG_UNUSED(error_message)
#  endif
}
#endif
#endif /* READ */

void /* PRIVATE */
png_chunk_report(png_const_structrp png_ptr, png_const_charp message, int error)
{
#  ifndef PNG_WARNINGS_SUPPORTED
      PNG_UNUSED(message)
#  endif

   /* This is always supported, but for just read or just write it
    * unconditionally does the right thing.
    */
#  if defined(PNG_READ_SUPPORTED) && defined(PNG_WRITE_SUPPORTED)
      if ((png_ptr->mode & PNG_IS_READ_STRUCT) != 0)
#  endif

#  ifdef PNG_READ_SUPPORTED
      {
         if (error < PNG_CHUNK_ERROR)
            png_chunk_warning(png_ptr, message);

         else
            png_chunk_benign_error(png_ptr, message);
      }
#  endif

#  if defined(PNG_READ_SUPPORTED) && defined(PNG_WRITE_SUPPORTED)
      else if ((png_ptr->mode & PNG_IS_READ_STRUCT) == 0)
#  endif

#  ifdef PNG_WRITE_SUPPORTED
      {
         if (error < PNG_CHUNK_WRITE_ERROR)
            png_app_warning(png_ptr, message);

         else
            png_app_error(png_ptr, message);
      }
#  endif
}

#ifdef PNG_ERROR_TEXT_SUPPORTED
#ifdef PNG_FLOATING_POINT_SUPPORTED
PNG_FUNCTION(void,
png_fixed_error,(png_const_structrp png_ptr, png_const_charp name),PNG_NORETURN)
{
#  define fixed_message "fixed point overflow in "
#  define fixed_message_ln ((sizeof fixed_message)-1)
   unsigned int  iin;
   char msg[fixed_message_ln+PNG_MAX_ERROR_TEXT];
   memcpy(msg, fixed_message, fixed_message_ln);
   iin = 0;
   if (name != NULL)
      while (iin < (PNG_MAX_ERROR_TEXT-1) && name[iin] != 0)
      {
         msg[fixed_message_ln + iin] = name[iin];
         ++iin;
      }
   msg[fixed_message_ln + iin] = 0;
   png_error(png_ptr, msg);
}
#endif
#endif

#ifdef PNG_SETJMP_SUPPORTED
/* This API only exists if ANSI-C style error handling is used,
 * otherwise it is necessary for png_default_error to be overridden.
 */
jmp_buf* PNGAPI
png_set_longjmp_fn(png_structrp png_ptr, png_longjmp_ptr longjmp_fn,
    size_t jmp_buf_size)
{
   /* From libpng 1.6.0 the app gets one chance to set a 'jmpbuf_size' value
    * and it must not change after that.  Libpng doesn't care how big the
    * buffer is, just that it doesn't change.
    *
    * If the buffer size is no *larger* than the size of jmp_buf when libpng is
    * compiled a built in jmp_buf is returned; this preserves the pre-1.6.0
    * semantics that this call will not fail.  If the size is larger, however,
    * the buffer is allocated and this may fail, causing the function to return
    * NULL.
    */
   if (png_ptr == NULL)
      return NULL;

   if (png_ptr->jmp_buf_ptr == NULL)
   {
      png_ptr->jmp_buf_size = 0; /* not allocated */

      if (jmp_buf_size <= (sizeof png_ptr->jmp_buf_local))
         png_ptr->jmp_buf_ptr = &png_ptr->jmp_buf_local;

      else
      {
         png_ptr->jmp_buf_ptr = png_voidcast(jmp_buf *,
             png_malloc_warn(png_ptr, jmp_buf_size));

         if (png_ptr->jmp_buf_ptr == NULL)
            return NULL; /* new NULL return on OOM */

         png_ptr->jmp_buf_size = jmp_buf_size;
      }
   }

   else /* Already allocated: check the size */
   {
      size_t size = png_ptr->jmp_buf_size;

      if (size == 0)
      {
         size = (sizeof png_ptr->jmp_buf_local);
         if (png_ptr->jmp_buf_ptr != &png_ptr->jmp_buf_local)
         {
            /* This is an internal error in libpng: somehow we have been left
             * with a stack allocated jmp_buf when the application regained
             * control.  It's always possible to fix this up, but for the moment
             * this is a png_error because that makes it easy to detect.
             */
            png_error(png_ptr, "Libpng jmp_buf still allocated");
            /* png_ptr->jmp_buf_ptr = &png_ptr->jmp_buf_local; */
         }
      }

      if (size != jmp_buf_size)
      {
         png_warning(png_ptr, "Application jmp_buf size changed");
         return NULL; /* caller will probably crash: no choice here */
      }
   }

   /* Finally fill in the function, now we have a satisfactory buffer. It is
    * valid to change the function on every call.
    */
   png_ptr->longjmp_fn = longjmp_fn;
   return png_ptr->jmp_buf_ptr;
}

void /* PRIVATE */
png_free_jmpbuf(png_structrp png_ptr)
{
   if (png_ptr != NULL)
   {
      jmp_buf *jb = png_ptr->jmp_buf_ptr;

      /* A size of 0 is used to indicate a local, stack, allocation of the
       * pointer; used here and in png.c
       */
      if (jb != NULL && png_ptr->jmp_buf_size > 0)
      {

         /* This stuff is so that a failure to free the error control structure
          * does not leave libpng in a state with no valid error handling: the
          * free always succeeds, if there is an error it gets ignored.
          */
         if (jb != &png_ptr->jmp_buf_local)
         {
            /* Make an internal, libpng, jmp_buf to return here */
            jmp_buf free_jmp_buf;

            if (!setjmp(free_jmp_buf))
            {
               png_ptr->jmp_buf_ptr = &free_jmp_buf; /* come back here */
               png_ptr->jmp_buf_size = 0; /* stack allocation */
               png_ptr->longjmp_fn = longjmp;
               png_free(png_ptr, jb); /* Return to setjmp on error */
            }
         }
      }

      /* *Always* cancel everything out: */
      png_ptr->jmp_buf_size = 0;
      png_ptr->jmp_buf_ptr = NULL;
      png_ptr->longjmp_fn = 0;
   }
}
#endif

/* This is the default error handling function.  Note that replacements for
 * this function MUST NOT RETURN, or the program will likely crash.  This
 * function is used by default, or if the program supplies NULL for the
 * error function pointer in png_set_error_fn().
 */
static PNG_FUNCTION(void /* PRIVATE */,
png_default_error,(png_const_structrp png_ptr, png_const_charp error_message),
    PNG_NORETURN)
{
#ifdef PNG_CONSOLE_IO_SUPPORTED
#ifdef PNG_ERROR_NUMBERS_SUPPORTED
   /* Check on NULL only added in 1.5.4 */
   if (error_message != NULL && *error_message == PNG_LITERAL_SHARP)
   {
      /* Strip "#nnnn " from beginning of error message. */
      int offset;
      char error_number[16];
      for (offset = 0; offset<15; offset++)
      {
         error_number[offset] = error_message[offset + 1];
         if (error_message[offset] == ' ')
            break;
      }

      if ((offset > 1) && (offset < 15))
      {
         error_number[offset - 1] = '\0';
         fprintf(stderr, "libpng error no. %s: %s",
             error_number, error_message + offset + 1);
         fprintf(stderr, PNG_STRING_NEWLINE);
      }

      else
      {
         fprintf(stderr, "libpng error: %s, offset=%d",
             error_message, offset);
         fprintf(stderr, PNG_STRING_NEWLINE);
      }
   }
   else
#endif
   {
      fprintf(stderr, "libpng error: %s", error_message ? error_message :
         "undefined");
      fprintf(stderr, PNG_STRING_NEWLINE);
   }
#else
   PNG_UNUSED(error_message) /* Make compiler happy */
#endif
   png_longjmp(png_ptr, 1);
}

PNG_FUNCTION(void,PNGAPI
png_longjmp,(png_const_structrp png_ptr, int val),PNG_NORETURN)
{
#ifdef PNG_SETJMP_SUPPORTED
   if (png_ptr != NULL && png_ptr->longjmp_fn != NULL &&
       png_ptr->jmp_buf_ptr != NULL)
      png_ptr->longjmp_fn(*png_ptr->jmp_buf_ptr, val);
#else
   PNG_UNUSED(png_ptr)
   PNG_UNUSED(val)
#endif

   /* If control reaches this point, png_longjmp() must not return. The only
    * choice is to terminate the whole process (or maybe the thread); to do
    * this the ANSI-C abort() function is used unless a different method is
    * implemented by overriding the default configuration setting for
    * PNG_ABORT().
    */
   PNG_ABORT();
}

#ifdef PNG_WARNINGS_SUPPORTED
/* This function is called when there is a warning, but the library thinks
 * it can continue anyway.  Replacement functions don't have to do anything
 * here if you don't want them to.  In the default configuration, png_ptr is
 * not used, but it is passed in case it may be useful.
 */
static void /* PRIVATE */
png_default_warning(png_const_structrp png_ptr, png_const_charp warning_message)
{
#ifdef PNG_CONSOLE_IO_SUPPORTED
#  ifdef PNG_ERROR_NUMBERS_SUPPORTED
   if (*warning_message == PNG_LITERAL_SHARP)
   {
      int offset;
      char warning_number[16];
      for (offset = 0; offset < 15; offset++)
      {
         warning_number[offset] = warning_message[offset + 1];
         if (warning_message[offset] == ' ')
            break;
      }

      if ((offset > 1) && (offset < 15))
      {
         warning_number[offset + 1] = '\0';
         fprintf(stderr, "libpng warning no. %s: %s",
             warning_number, warning_message + offset);
         fprintf(stderr, PNG_STRING_NEWLINE);
      }

      else
      {
         fprintf(stderr, "libpng warning: %s",
             warning_message);
         fprintf(stderr, PNG_STRING_NEWLINE);
      }
   }
   else
#  endif

   {
      fprintf(stderr, "libpng warning: %s", warning_message);
      fprintf(stderr, PNG_STRING_NEWLINE);
   }
#else
   PNG_UNUSED(warning_message) /* Make compiler happy */
#endif
   PNG_UNUSED(png_ptr) /* Make compiler happy */
}
#endif /* WARNINGS */

/* This function is called when the application wants to use another method
 * of handling errors and warnings.  Note that the error function MUST NOT
 * return to the calling routine or serious problems will occur.  The return
 * method used in the default routine calls longjmp(png_ptr->jmp_buf_ptr, 1)
 */
void PNGAPI
png_set_error_fn(png_structrp png_ptr, png_voidp error_ptr,
    png_error_ptr error_fn, png_error_ptr warning_fn)
{
   if (png_ptr == NULL)
      return;

   png_ptr->error_ptr = error_ptr;
   png_ptr->error_fn = error_fn;
#ifdef PNG_WARNINGS_SUPPORTED
   png_ptr->warning_fn = warning_fn;
#else
   PNG_UNUSED(warning_fn)
#endif
}

/* This function returns a pointer to the error_ptr associated with the user
 * functions.  The application should free any memory associated with this
 * pointer before png_write_destroy and png_read_destroy are called.
 */
png_voidp PNGAPI
png_get_error_ptr(png_const_structrp png_ptr)
{
   if (png_ptr == NULL)
      return NULL;

   return ((png_voidp)png_ptr->error_ptr);
}

#ifdef PNG_ERROR_NUMBERS_SUPPORTED
void PNGAPI
png_set_strip_error_numbers(png_structrp png_ptr, png_uint_32 strip_mode)
{
   if (png_ptr != NULL)
   {
      png_ptr->flags &=
         ((~(PNG_FLAG_STRIP_ERROR_NUMBERS |
         PNG_FLAG_STRIP_ERROR_TEXT))&strip_mode);
   }
}
#endif

#if defined(PNG_SIMPLIFIED_READ_SUPPORTED) ||\
   defined(PNG_SIMPLIFIED_WRITE_SUPPORTED)
   /* Currently the above both depend on SETJMP_SUPPORTED, however it would be
    * possible to implement without setjmp support just so long as there is some
    * way to handle the error return here:
    */
PNG_FUNCTION(void /* PRIVATE */, (PNGCBAPI
png_safe_error),(png_structp png_nonconst_ptr, png_const_charp error_message),
    PNG_NORETURN)
{
   const png_const_structrp png_ptr = png_nonconst_ptr;
   png_imagep image = png_voidcast(png_imagep, png_ptr->error_ptr);

   /* An error is always logged here, overwriting anything (typically a warning)
    * that is already there:
    */
   if (image != NULL)
   {
      png_safecat(image->message, (sizeof image->message), 0, error_message);
      image->warning_or_error |= PNG_IMAGE_ERROR;

      /* Retrieve the jmp_buf from within the png_control, making this work for
       * C++ compilation too is pretty tricky: C++ wants a pointer to the first
       * element of a jmp_buf, but C doesn't tell us the type of that.
       */
      if (image->opaque != NULL && image->opaque->error_buf != NULL)
         longjmp(png_control_jmp_buf(image->opaque), 1);

      /* Missing longjmp buffer, the following is to help debugging: */
      {
         size_t pos = png_safecat(image->message, (sizeof image->message), 0,
             "bad longjmp: ");
         png_safecat(image->message, (sizeof image->message), pos,
             error_message);
      }
   }

   /* Here on an internal programming error. */
   abort();
}

#ifdef PNG_WARNINGS_SUPPORTED
void /* PRIVATE */ PNGCBAPI
png_safe_warning(png_structp png_nonconst_ptr, png_const_charp warning_message)
{
   const png_const_structrp png_ptr = png_nonconst_ptr;
   png_imagep image = png_voidcast(png_imagep, png_ptr->error_ptr);

   /* A warning is only logged if there is no prior warning or error. */
   if (image->warning_or_error == 0)
   {
      png_safecat(image->message, (sizeof image->message), 0, warning_message);
      image->warning_or_error |= PNG_IMAGE_WARNING;
   }
}
#endif

int /* PRIVATE */
png_safe_execute(png_imagep image_in, int (*function)(png_voidp), png_voidp arg)
{
   volatile png_imagep image = image_in;
   volatile int result;
   volatile png_voidp saved_error_buf;
   jmp_buf safe_jmpbuf;

   /* Safely execute function(arg) with png_error returning to this function. */
   saved_error_buf = image->opaque->error_buf;
   result = setjmp(safe_jmpbuf) == 0;

   if (result != 0)
   {

      image->opaque->error_buf = safe_jmpbuf;
      result = function(arg);
   }

   image->opaque->error_buf = saved_error_buf;

   /* And do the cleanup prior to any failure return. */
   if (result == 0)
      png_image_free(image);

   return result;
}
#endif /* SIMPLIFIED READ || SIMPLIFIED_WRITE */
#endif /* READ || WRITE */


from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import numpy as np
import matplotlib.pyplot as plt
import utils.tfrecord_imagenet_utils as imagenet_utils

os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
os.environ['CUDA_VISIBLE_DEVICES'] = '0'

tfrecord = imagenet_utils.dataset2tfrecord('F:\\test\\',
                                           'F:\\tfrecord\\', 'test', 5)
print(tfrecord)


#include <netdb.h>
#include "locale_impl.h"

static const char msgs[] =
	"Invalid flags\0"
	"Name does not resolve\0"
	"Try again\0"
	"Non-recoverable error\0"
	"Unknown error\0"
	"Unrecognized address family or invalid length\0"
	"Unrecognized socket type\0"
	"Unrecognized service\0"
	"Unknown error\0"
	"Out of memory\0"
	"System error\0"
	"Overflow\0"
	"\0Unknown error";

const char *gai_strerror(int ecode)
{
	const char *s;
	for (s=msgs, ecode++; ecode && *s; ecode++, s++) for (; *s; s++);
	if (!*s) s++;
	return LCTRANS_CUR(s);
}


#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include <string>
#include <iostream>
#include <dirent.h>
#include <cstring>
#include <errno.h>
#include <attr/xattr.h>

#include "../BaseTestCase.h"
#include "../../user_tools/api/workload.h"
#include "../../user_tools/api/actions.h"

using fs_testing::tests::DataTestResult;
using fs_testing::user_tools::api::WriteData;
using fs_testing::user_tools::api::WriteDataMmap;
using fs_testing::user_tools::api::Checkpoint;
using std::string;

#define TEST_FILE_PERMS  ((mode_t) (S_IRWXU | S_IRWXG | S_IRWXO))

namespace fs_testing {
    namespace tests {

        class testName: public BaseTestCase {

            public:

            virtual int setup() override {

				test_path = mnt_dir_ ;
				A_path = mnt_dir_ + "/A";
				AC_path = mnt_dir_ + "/A/C";
				B_path = mnt_dir_ + "/B";
				foo_path = mnt_dir_ + "/foo";
				bar_path = mnt_dir_ + "/bar";
				Afoo_path = mnt_dir_ + "/A/foo";
				Abar_path = mnt_dir_ + "/A/bar";
				Bfoo_path = mnt_dir_ + "/B/foo";
				Bbar_path = mnt_dir_ + "/B/bar";
				ACfoo_path = mnt_dir_ + "/A/C/foo";
				ACbar_path = mnt_dir_ + "/A/C/bar";
                return 0;
            }

            virtual int run( int checkpoint ) override {

				test_path = mnt_dir_ ;
				A_path =  mnt_dir_ + "/A";
				AC_path =  mnt_dir_ + "/A/C";
				B_path =  mnt_dir_ + "/B";
				foo_path =  mnt_dir_ + "/foo";
				bar_path =  mnt_dir_ + "/bar";
				Afoo_path =  mnt_dir_ + "/A/foo";
				Abar_path =  mnt_dir_ + "/A/bar";
				Bfoo_path =  mnt_dir_ + "/B/foo";
				Bbar_path =  mnt_dir_ + "/B/bar";
				ACfoo_path =  mnt_dir_ + "/A/C/foo";
				ACbar_path =  mnt_dir_ + "/A/C/bar";
				int local_checkpoint = 0 ;

				int fd_foo = cm_->CmOpen(foo_path.c_str() , O_RDWR|O_CREAT , 0777);
				if ( fd_foo < 0 ) {
					cm_->CmClose( fd_foo);
					return errno;
				}

				if ( WriteData ( fd_foo, 0, 32768) < 0){
					cm_->CmClose( fd_foo);
					return errno;
				}

				if ( fallocate( fd_foo , 0 , 0 , 8192) < 0){
					cm_->CmClose( fd_foo);
					 return errno;
				}
				char *filep_foo = (char *) cm_->CmMmap(NULL, 8192 + 0, PROT_WRITE|PROT_READ, MAP_SHARED, fd_foo, 0);
				if (filep_foo == MAP_FAILED) {
					 return -1;
				}

				int moffset_foo = 0;
				int to_write_foo = 8192 ;
				const char *mtext_foo  = "mmmmmmmmmmklmnopqrstuvwxyz123456";

				while (moffset_foo < 8192){
					if (to_write_foo < 32){
						memcpy(filep_foo + 0 + moffset_foo, mtext_foo, to_write_foo);
						moffset_foo += to_write_foo;
					}
					else {
						memcpy(filep_foo + 0 + moffset_foo,mtext_foo, 32);
						moffset_foo += 32;
					}
				}

				if ( cm_->CmMsync ( filep_foo + 0, 8192 , MS_SYNC) < 0){
					cm_->CmMunmap( filep_foo,0 + 8192);
					return -1;
				}
				cm_->CmMunmap( filep_foo , 0 + 8192);

				if ( cm_->CmCheckpoint() < 0){
					return -1;
				}
				local_checkpoint += 1;
				if (local_checkpoint == checkpoint) {
					return 1;
				}

				if ( cm_->CmClose ( fd_foo) < 0){
					return errno;
				}

                return 0;
            }

            virtual int check_test( unsigned int last_checkpoint, DataTestResult *test_result) override {

				test_path = mnt_dir_ ;
				A_path =  mnt_dir_ + "/A";
				AC_path =  mnt_dir_ + "/A/C";
				B_path =  mnt_dir_ + "/B";
				foo_path =  mnt_dir_ + "/foo";
				bar_path =  mnt_dir_ + "/bar";
				Afoo_path =  mnt_dir_ + "/A/foo";
				Abar_path =  mnt_dir_ + "/A/bar";
				Bfoo_path =  mnt_dir_ + "/B/foo";
				Bbar_path =  mnt_dir_ + "/B/bar";
				ACfoo_path =  mnt_dir_ + "/A/C/foo";
				ACbar_path =  mnt_dir_ + "/A/C/bar";
                return 0;
            }

            private:

			 string test_path;
			 string A_path;
			 string AC_path;
			 string B_path;
			 string foo_path;
			 string bar_path;
			 string Afoo_path;
			 string Abar_path;
			 string Bfoo_path;
			 string Bbar_path;
			 string ACfoo_path;
			 string ACbar_path;

            };

    }  // namespace tests
    }  // namespace fs_testing

   extern "C" fs_testing::tests::BaseTestCase *test_case_get_instance() {
       return new fs_testing::tests::testName;
   }

   extern "C" void test_case_delete_instance(fs_testing::tests::BaseTestCase *tc) {
       delete tc;
   }


//===------------------------ memory.cpp ----------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//

#include "memory"
#ifndef _LIBCPP_HAS_NO_THREADS
#include "mutex"
#include "thread"
#if defined(__ELF__) && defined(_LIBCPP_LINK_PTHREAD_LIB)
#pragma comment(lib, "pthread")
#endif
#endif
#if !defined(_LIBCPP_HAS_NO_THREADS)
#include <atomic>
#else
#include "include/atomic_support.h"
#endif

_LIBCPP_BEGIN_NAMESPACE_STD

const allocator_arg_t allocator_arg = allocator_arg_t();

bad_weak_ptr::~bad_weak_ptr() _NOEXCEPT {}

const char*
bad_weak_ptr::what() const _NOEXCEPT
{
    return "bad_weak_ptr";
}

__shared_count::~__shared_count()
{
}

__shared_weak_count::~__shared_weak_count()
{
}

#if defined(_LIBCPP_DEPRECATED_ABI_LEGACY_LIBRARY_DEFINITIONS_FOR_INLINE_FUNCTIONS)
void
__shared_count::__add_shared() _NOEXCEPT
{
#ifdef _LIBCPP_HAS_NO_THREADS
    __libcpp_atomic_refcount_increment(__shared_owners_);
#else
    ++__shared_owners_;
#endif
}

bool
__shared_count::__release_shared() _NOEXCEPT
{
#ifdef _LIBCPP_HAS_NO_THREADS
    if (__libcpp_atomic_refcount_decrement(__shared_owners_) == -1)
#else
    if (--__shared_owners_ == -1)
#endif
    {
        __on_zero_shared();
        return true;
    }
    return false;
}

void
__shared_weak_count::__add_shared() _NOEXCEPT
{
    __shared_count::__add_shared();
}

void
__shared_weak_count::__add_weak() _NOEXCEPT
{
#ifdef _LIBCPP_HAS_NO_THREADS
    __libcpp_atomic_refcount_increment(__shared_weak_owners_);
#else
    ++__shared_weak_owners_;
#endif
}

void
__shared_weak_count::__release_shared() _NOEXCEPT
{
    if (__shared_count::__release_shared())
        __release_weak();
}

#endif // _LIBCPP_DEPRECATED_ABI_LEGACY_LIBRARY_DEFINITIONS_FOR_INLINE_FUNCTIONS

void
__shared_weak_count::__release_weak() _NOEXCEPT
{
    // NOTE: The acquire load here is an optimization of the very
    // common case where a shared pointer is being destructed while
    // having no other contended references.
    //
    // BENEFIT: We avoid expensive atomic stores like XADD and STREX
    // in a common case.  Those instructions are slow and do nasty
    // things to caches.
    //
    // IS THIS SAFE?  Yes.  During weak destruction, if we see that we
    // are the last reference, we know that no-one else is accessing
    // us. If someone were accessing us, then they would be doing so
    // while the last shared / weak_ptr was being destructed, and
    // that's undefined anyway.
    //
    // If we see anything other than a 0, then we have possible
    // contention, and need to use an atomicrmw primitive.
    // The same arguments don't apply for increment, where it is legal
    // (though inadvisable) to share shared_ptr references between
    // threads, and have them all get copied at once.  The argument
    // also doesn't apply for __release_shared, because an outstanding
    // weak_ptr::lock() could read / modify the shared count.
#ifdef _LIBCPP_HAS_NO_THREADS
    if (__libcpp_atomic_load(&__shared_weak_owners_, _AO_Acquire) == 0)
#else
    if (__shared_weak_owners_.load(memory_order_acquire) == 0)
#endif
    {
        // no need to do this store, because we are about
        // to destroy everything.
        //__libcpp_atomic_store(&__shared_weak_owners_, -1, _AO_Release);
        __on_zero_shared_weak();
    }
#ifdef _LIBCPP_HAS_NO_THREADS
    else if (__libcpp_atomic_refcount_decrement(__shared_weak_owners_) == -1)
#else
    else if (--__shared_weak_owners_ == -1)
#endif
        __on_zero_shared_weak();
}

__shared_weak_count*
__shared_weak_count::lock() _NOEXCEPT
{
#ifdef _LIBCPP_HAS_NO_THREADS
    long object_owners = __libcpp_atomic_load(&__shared_owners_);
#else
    long object_owners = __shared_owners_.load();
#endif
    while (object_owners != -1)
    {
#ifdef _LIBCPP_HAS_NO_THREADS
        if (__libcpp_atomic_compare_exchange(&__shared_owners_,
                                             &object_owners,
                                             object_owners+1))
#else
        if (__shared_owners_.compare_exchange_weak(object_owners, object_owners+1))
#endif
            return this;
    }
    return nullptr;
}

#if !defined(_LIBCPP_NO_RTTI) || !defined(_LIBCPP_BUILD_STATIC)

const void*
__shared_weak_count::__get_deleter(const type_info&) const _NOEXCEPT
{
    return nullptr;
}

#endif  // _LIBCPP_NO_RTTI

#if !defined(_LIBCPP_HAS_NO_ATOMIC_HEADER)

_LIBCPP_SAFE_STATIC static const std::size_t __sp_mut_count = 16;
_LIBCPP_SAFE_STATIC static __libcpp_mutex_t mut_back[__sp_mut_count] =
{
    _LIBCPP_MUTEX_INITIALIZER, _LIBCPP_MUTEX_INITIALIZER, _LIBCPP_MUTEX_INITIALIZER, _LIBCPP_MUTEX_INITIALIZER,
    _LIBCPP_MUTEX_INITIALIZER, _LIBCPP_MUTEX_INITIALIZER, _LIBCPP_MUTEX_INITIALIZER, _LIBCPP_MUTEX_INITIALIZER,
    _LIBCPP_MUTEX_INITIALIZER, _LIBCPP_MUTEX_INITIALIZER, _LIBCPP_MUTEX_INITIALIZER, _LIBCPP_MUTEX_INITIALIZER,
    _LIBCPP_MUTEX_INITIALIZER, _LIBCPP_MUTEX_INITIALIZER, _LIBCPP_MUTEX_INITIALIZER, _LIBCPP_MUTEX_INITIALIZER
};

_LIBCPP_CONSTEXPR __sp_mut::__sp_mut(void* p) _NOEXCEPT
   : __lx(p)
{
}

void
__sp_mut::lock() _NOEXCEPT
{
    auto m = static_cast<__libcpp_mutex_t*>(__lx);
    unsigned count = 0;
    while (!__libcpp_mutex_trylock(m))
    {
        if (++count > 16)
        {
            __libcpp_mutex_lock(m);
            break;
        }
        this_thread::yield();
    }
}

void
__sp_mut::unlock() _NOEXCEPT
{
    __libcpp_mutex_unlock(static_cast<__libcpp_mutex_t*>(__lx));
}

__sp_mut&
__get_sp_mut(const void* p)
{
    static __sp_mut muts[__sp_mut_count]
    {
        &mut_back[ 0], &mut_back[ 1], &mut_back[ 2], &mut_back[ 3],
        &mut_back[ 4], &mut_back[ 5], &mut_back[ 6], &mut_back[ 7],
        &mut_back[ 8], &mut_back[ 9], &mut_back[10], &mut_back[11],
        &mut_back[12], &mut_back[13], &mut_back[14], &mut_back[15]
    };
    return muts[hash<const void*>()(p) & (__sp_mut_count-1)];
}

#endif // !defined(_LIBCPP_HAS_NO_ATOMIC_HEADER)

void
declare_reachable(void*)
{
}

void
declare_no_pointers(char*, size_t)
{
}

void
undeclare_no_pointers(char*, size_t)
{
}

#if !defined(_LIBCPP_ABI_POINTER_SAFETY_ENUM_TYPE)
pointer_safety get_pointer_safety() _NOEXCEPT
{
    return pointer_safety::relaxed;
}
#endif

void*
__undeclare_reachable(void* p)
{
    return p;
}

void*
align(size_t alignment, size_t size, void*& ptr, size_t& space)
{
    void* r = nullptr;
    if (size <= space)
    {
        char* p1 = static_cast<char*>(ptr);
        char* p2 = reinterpret_cast<char*>(reinterpret_cast<size_t>(p1 + (alignment - 1)) & -alignment);
        size_t d = static_cast<size_t>(p2 - p1);
        if (d <= space - size)
        {
            r = p2;
            ptr = r;
            space -= d;
        }
    }
    return r;
}

_LIBCPP_END_NAMESPACE_STD


// This file declares the IPersistFolder Interface and Gateway for Python.
// Generated by makegw.py
// ---------------------------------------------------
//
// Interface Declaration

// The shlwapi.h included with MSVC6 does not have this interface.
// A default Microsoft SDK does not provide an updated shlwapi.h file
// (even though the SDK on mhammond's machine does!).  Rather than
// try and figure out these header versions, just copy the interface
// definition here.
// #include "shlwapi.h"

// *** - start of shlwapi.h clone
enum {
    ASSOCF_INIT_NOREMAPCLSID = 0x00000001,     //  do not remap clsids to progids
    ASSOCF_INIT_BYEXENAME = 0x00000002,        //  executable is being passed in
    ASSOCF_OPEN_BYEXENAME = 0x00000002,        //  executable is being passed in
    ASSOCF_INIT_DEFAULTTOSTAR = 0x00000004,    //  treat "*" as the BaseClass
    ASSOCF_INIT_DEFAULTTOFOLDER = 0x00000008,  //  treat "Folder" as the BaseClass
    ASSOCF_NOUSERSETTINGS = 0x00000010,        //  dont use HKCU
    ASSOCF_NOTRUNCATE = 0x00000020,            //  dont truncate the return string
    ASSOCF_VERIFY = 0x00000040,                //  verify data is accurate (DISK HITS)
    ASSOCF_REMAPRUNDLL = 0x00000080,           //  actually gets info about rundlls target if applicable
    ASSOCF_NOFIXUPS = 0x00000100,              //  attempt to fix errors if found
    ASSOCF_IGNOREBASECLASS = 0x00000200,       //  dont recurse into the baseclass
};
typedef DWORD ASSOCF;
#define LWSTDAPI STDAPI
typedef enum {} ASSOCSTR;
typedef enum {} ASSOCKEY;
typedef enum {} ASSOCDATA;
typedef enum {} ASSOCENUM;
#undef INTERFACE
#define INTERFACE IQueryAssociations

DECLARE_INTERFACE_(IQueryAssociations, IUnknown)
{
    // IUnknown methods
    STDMETHOD(QueryInterface)(THIS_ REFIID riid, void **ppv) PURE;
    STDMETHOD_(ULONG, AddRef)(THIS) PURE;
    STDMETHOD_(ULONG, Release)(THIS) PURE;

    // IQueryAssociations methods
    STDMETHOD(Init)(THIS_ ASSOCF flags, LPCWSTR pszAssoc, HKEY hkProgid, HWND hwnd) PURE;
    STDMETHOD(GetString)(THIS_ ASSOCF flags, ASSOCSTR str, LPCWSTR pszExtra, LPWSTR pszOut, DWORD * pcchOut) PURE;
    STDMETHOD(GetKey)(THIS_ ASSOCF flags, ASSOCKEY key, LPCWSTR pszExtra, HKEY * phkeyOut) PURE;
    STDMETHOD(GetData)(THIS_ ASSOCF flags, ASSOCDATA data, LPCWSTR pszExtra, LPVOID pvOut, DWORD * pcbOut) PURE;
    STDMETHOD(GetEnum)(THIS_ ASSOCF flags, ASSOCENUM assocenum, LPCWSTR pszExtra, REFIID riid, LPVOID * ppvOut) PURE;
};

LWSTDAPI AssocCreate(CLSID clsid, REFIID riid, LPVOID *ppv);
// *** - end of shlwapi.h clone

class PyIQueryAssociations : public PyIUnknown {
   public:
    MAKE_PYCOM_CTOR(PyIQueryAssociations);
    static IQueryAssociations *GetI(PyObject *self);
    static PyComTypeObject type;

    // The Python methods
    static PyObject *Init(PyObject *self, PyObject *args);
    static PyObject *GetKey(PyObject *self, PyObject *args);
    static PyObject *GetString(PyObject *self, PyObject *args);

   protected:
    PyIQueryAssociations(IUnknown *pdisp);
    ~PyIQueryAssociations();
};


namespace weka.filters.unsupervised.attribute;

class AddCluster
{
  isA UnsupervisedFilter,OptionHandler;
  isA Filter;
 depend java.io.File;
 depend java.io.FileInputStream;
 depend java.io.FileNotFoundException;
 depend java.io.ObjectInputStream;
 depend java.util.ArrayList;
 depend java.util.Enumeration;
 depend java.util.Vector;
 depend weka.clusterers.AbstractClusterer;
 depend weka.clusterers.Clusterer;
 depend weka.core.Attribute;
 depend weka.core.Capabilities;
 depend weka.core.DenseInstance;
 depend weka.core.Instance;
 depend weka.core.Instances;
 depend weka.core.Option;
 depend weka.core.OptionHandler;
 depend weka.core.Range;
 depend weka.core.RevisionUtils;
 depend weka.core.SparseInstance;
 depend weka.core.Utils;
 depend weka.core.WekaException;
 depend weka.filters.Filter;
 depend weka.filters.UnsupervisedFilter;
/**
 * for serialization.
 */
static final long serialVersionUID=7414280611943807337L;

/**
 * The clusterer used to do the cleansing.
 */
protected Clusterer m_Clusterer=new weka.clusterers.SimpleKMeans();

/**
 * The file from which to load a serialized clusterer.
 */
protected File m_SerializedClustererFile=new File(System.getProperty("user.dir"));

/**
 * The actual clusterer used to do the clustering.
 */
protected Clusterer m_ActualClusterer=null;

/**
 * Range of attributes to ignore.
 */
protected Range m_IgnoreAttributesRange=null;

/**
 * Filter for removing attributes.
 */
protected Filter m_removeAttributes=new Remove();

/**
 * Returns the Capabilities of this filter, makes sure that the class is never set (for the clusterer).
 * @param data the data to use for customization
 * @return the capabilities of this object, based on the data
 * @see #getCapabilities()
 */
@Override public Capabilities getCapabilities(Instances data){
  Instances newData;
  newData=new Instances(data,0);
  newData.setClassIndex(-1);
  return super.getCapabilities(newData);
}

/**
 * Returns the Capabilities of this filter.
 * @return the capabilities of this object
 * @see Capabilities
 */
@Override public Capabilities getCapabilities(){
  Capabilities result=m_Clusterer.getCapabilities();
  result.enableAllClasses();
  result.setMinimumNumberInstances(0);
  return result;
}

/**
 * tests the data whether the filter can actually handle it.
 * @param instanceInfo the data to test
 * @throws Exception if the test fails
 */
@Override protected void testInputFormat(Instances instanceInfo) throws Exception {
  getCapabilities(instanceInfo).testWithFail(removeIgnored(instanceInfo));
}

/**
 * Sets the format of the input instances.
 * @param instanceInfo an Instances object containing the input instancestructure (any instances contained in the object are ignored - only the structure is required).
 * @return true if the outputFormat may be collected immediately
 * @throws Exception if the inputFormat can't be set successfully
 */
@Override public boolean setInputFormat(Instances instanceInfo) throws Exception {
  super.setInputFormat(instanceInfo);
  m_removeAttributes=null;
  return false;
}

/**
 * filters all attributes that should be ignored.
 * @param data the data to filter
 * @return the filtered data
 * @throws Exception if filtering fails
 */
protected Instances removeIgnored(Instances data) throws Exception {
  Instances result=data;
  if (m_IgnoreAttributesRange != null || data.classIndex() >= 0) {
    m_removeAttributes=new Remove();
    String rangeString="";
    if (m_IgnoreAttributesRange != null) {
      rangeString+=m_IgnoreAttributesRange.getRanges();
    }
    if (data.classIndex() >= 0) {
      if (rangeString.length() > 0) {
        rangeString+="," + (data.classIndex() + 1);
      }
 else {
        rangeString="" + (data.classIndex() + 1);
      }
    }
    ((Remove)m_removeAttributes).setAttributeIndices(rangeString);
    ((Remove)m_removeAttributes).setInvertSelection(false);
    m_removeAttributes.setInputFormat(data);
    result=Filter.useFilter(data,m_removeAttributes);
  }
  return result;
}

/**
 * Signify that this batch of input to the filter is finished.
 * @return true if there are instances pending output
 * @throws IllegalStateException if no input structure has been defined
 */
@Override public boolean batchFinished() throws Exception {
  if (getInputFormat() == null) {
    throw new IllegalStateException("No input instance format defined");
  }
  Instances toFilter=getInputFormat();
  if (!isFirstBatchDone()) {
    Instances toFilterIgnoringAttributes=removeIgnored(toFilter);
    File file=getSerializedClustererFile();
    if (!file.isDirectory()) {
      ObjectInputStream ois=new ObjectInputStream(new FileInputStream(file));
      m_ActualClusterer=(Clusterer)ois.readObject();
      Instances header=null;
      try {
        header=(Instances)ois.readObject();
      }
 catch (      Exception e) {
      }
      ois.close();
      if ((header != null) && (!header.equalHeaders(toFilterIgnoringAttributes))) {
        throw new WekaException("Training header of clusterer and filter dataset don't match:\n" + header.equalHeadersMsg(toFilterIgnoringAttributes));
      }
    }
 else {
      m_ActualClusterer=AbstractClusterer.makeCopy(m_Clusterer);
      m_ActualClusterer.buildClusterer(toFilterIgnoringAttributes);
    }
    Instances filtered=new Instances(toFilter,0);
    ArrayList<String> nominal_values=new ArrayList<String>(m_ActualClusterer.numberOfClusters());
    for (int i=0; i < m_ActualClusterer.numberOfClusters(); i++) {
      nominal_values.add("cluster" + (i + 1));
    }
    filtered.insertAttributeAt(new Attribute("cluster",nominal_values),filtered.numAttributes());
    setOutputFormat(filtered);
  }
  for (int i=0; i < toFilter.numInstances(); i++) {
    convertInstance(toFilter.instance(i));
  }
  flushInput();
  m_NewBatch=true;
  m_FirstBatchDone=true;
  return (numPendingOutput() != 0);
}

/**
 * Input an instance for filtering. Ordinarily the instance is processed and made available for output immediately. Some filters require all instances be read before producing output.
 * @param instance the input instance
 * @return true if the filtered instance may now be collected with output().
 * @throws IllegalStateException if no input format has been defined.
 */
@Override public boolean input(Instance instance) throws Exception {
  if (getInputFormat() == null) {
    throw new IllegalStateException("No input instance format defined");
  }
  if (m_NewBatch) {
    resetQueue();
    m_NewBatch=false;
  }
  if (outputFormatPeek() != null) {
    convertInstance(instance);
    return true;
  }
  bufferInput(instance);
  return false;
}

/**
 * Convert a single instance over. The converted instance is added to the end of the output queue.
 * @param instance the instance to convert
 * @throws Exception if something goes wrong
 */
protected void convertInstance(Instance instance) throws Exception {
  Instance original, processed;
  original=instance;
  double[] instanceVals=new double[instance.numAttributes() + 1];
  for (int j=0; j < instance.numAttributes(); j++) {
    instanceVals[j]=original.value(j);
  }
  Instance filteredI=null;
  if (m_removeAttributes != null) {
    m_removeAttributes.input(instance);
    filteredI=m_removeAttributes.output();
  }
 else {
    filteredI=instance;
  }
  try {
    instanceVals[instance.numAttributes()]=m_ActualClusterer.clusterInstance(filteredI);
  }
 catch (  Exception e) {
    instanceVals[instance.numAttributes()]=Utils.missingValue();
  }
  if (original instanceof SparseInstance) {
    processed=new SparseInstance(original.weight(),instanceVals);
  }
 else {
    processed=new DenseInstance(original.weight(),instanceVals);
  }
  processed.setDataset(instance.dataset());
  copyValues(processed,false,instance.dataset(),getOutputFormat());
  processed.setDataset(getOutputFormat());
  push(processed);
}

/**
 * Returns an enumeration describing the available options.
 * @return an enumeration of all the available options.
 */
@Override public Enumeration<Option> listOptions(){
  Vector<Option> result=new Vector<Option>(3);
  result.addElement(new Option("\tFull class name of clusterer to use, followed\n" + "\tby scheme options. eg:\n" + "\t\t\"weka.clusterers.SimpleKMeans -N 3\"\n"+ "\t(default: weka.clusterers.SimpleKMeans)","W",1,"-W <clusterer specification>"));
  result.addElement(new Option("\tInstead of building a clusterer on the data, one can also provide\n" + "\ta serialized model and use that for adding the clusters.","serialized",1,"-serialized <file>"));
  result.addElement(new Option("\tThe range of attributes the clusterer should ignore.\n","I",1,"-I <att1,att2-att4,...>"));
  return result.elements();
}

/**
 * Parses a given list of options. <p/> <!-- options-start --> Valid options are: <p/> <pre> -W <clusterer specification> Full class name of clusterer to use, followed by scheme options. eg: "weka.clusterers.SimpleKMeans -N 3" (default: weka.clusterers.SimpleKMeans) </pre> <pre> -serialized <file> Instead of building a clusterer on the data, one can also provide a serialized model and use that for adding the clusters. </pre> <pre> -I <att1,att2-att4,...> The range of attributes the clusterer should ignore. </pre> <!-- options-end -->
 * @param options the list of options as an array of strings
 * @throws Exception if an option is not supported
 */
@Override public void setOptions(String[] options) throws Exception {
  String tmpStr;
  String[] tmpOptions;
  File file;
  boolean serializedModel;
  serializedModel=false;
  tmpStr=Utils.getOption("serialized",options);
  if (tmpStr.length() != 0) {
    file=new File(tmpStr);
    if (!file.exists()) {
      throw new FileNotFoundException("File '" + file.getAbsolutePath() + "' not found!");
    }
    if (file.isDirectory()) {
      throw new FileNotFoundException("'" + file.getAbsolutePath() + "' points to a directory not a file!");
    }
    setSerializedClustererFile(file);
    serializedModel=true;
  }
 else {
    setSerializedClustererFile(null);
  }
  if (!serializedModel) {
    tmpStr=Utils.getOption('W',options);
    if (tmpStr.length() == 0) {
      tmpStr=weka.clusterers.SimpleKMeans.class.getName();
    }
    tmpOptions=Utils.splitOptions(tmpStr);
    if (tmpOptions.length == 0) {
      throw new Exception("Invalid clusterer specification string");
    }
    tmpStr=tmpOptions[0];
    tmpOptions[0]="";
    setClusterer(AbstractClusterer.forName(tmpStr,tmpOptions));
  }
  setIgnoredAttributeIndices(Utils.getOption('I',options));
  Utils.checkForRemainingOptions(options);
}

/**
 * Gets the current settings of the filter.
 * @return an array of strings suitable for passing to setOptions
 */
@Override public String[] getOptions(){
  Vector<String> result;
  File file;
  result=new Vector<String>();
  file=getSerializedClustererFile();
  if ((file != null) && (!file.isDirectory())) {
    result.add("-serialized");
    result.add(file.getAbsolutePath());
  }
 else {
    result.add("-W");
    result.add(getClustererSpec());
  }
  if (!getIgnoredAttributeIndices().equals("")) {
    result.add("-I");
    result.add(getIgnoredAttributeIndices());
  }
  return result.toArray(new String[result.size()]);
}

/**
 * Returns a string describing this filter.
 * @return a description of the filter suitable for displaying in theexplorer/experimenter gui
 */
public String globalInfo(){
  return "A filter that adds a new nominal attribute representing the cluster " + "assigned to each instance by the specified clustering algorithm.\n" + "Either the clustering algorithm gets built with the first batch of "+ "data or one specifies are serialized clusterer model file to use "+ "instead.";
}

/**
 * Returns the tip text for this property.
 * @return tip text for this property suitable for displaying in theexplorer/experimenter gui
 */
public String clustererTipText(){
  return "The clusterer to assign clusters with.";
}

/**
 * Sets the clusterer to assign clusters with.
 * @param clusterer The clusterer to be used (with its options set).
 */
public void setClusterer(Clusterer clusterer){
  m_Clusterer=clusterer;
}

/**
 * Gets the clusterer used by the filter.
 * @return The clusterer being used.
 */
public Clusterer getClusterer(){
  return m_Clusterer;
}

/**
 * Gets the clusterer specification string, which contains the class name of the clusterer and any options to the clusterer.
 * @return the clusterer string.
 */
protected String getClustererSpec(){
  Clusterer c=getClusterer();
  if (c instanceof OptionHandler) {
    return c.getClass().getName() + " " + Utils.joinOptions(((OptionHandler)c).getOptions());
  }
  return c.getClass().getName();
}

/**
 * Returns the tip text for this property.
 * @return tip text for this property suitable for displaying in theexplorer/experimenter gui
 */
public String ignoredAttributeIndicesTipText(){
  return "The range of attributes to be ignored by the clusterer. eg: first-3,5,9-last";
}

/**
 * Gets ranges of attributes to be ignored.
 * @return a string containing a comma-separated list of ranges
 */
public String getIgnoredAttributeIndices(){
  if (m_IgnoreAttributesRange == null) {
    return "";
  }
 else {
    return m_IgnoreAttributesRange.getRanges();
  }
}

/**
 * Sets the ranges of attributes to be ignored. If provided string is null, no attributes will be ignored.
 * @param rangeList a string representing the list of attributes. eg:first-3,5,6-last
 * @throws IllegalArgumentException if an invalid range list is supplied
 */
public void setIgnoredAttributeIndices(String rangeList){
  if ((rangeList == null) || (rangeList.length() == 0)) {
    m_IgnoreAttributesRange=null;
  }
 else {
    m_IgnoreAttributesRange=new Range();
    m_IgnoreAttributesRange.setRanges(rangeList);
  }
}

/**
 * Gets the file pointing to a serialized, built clusterer. If it is null or pointing to a directory it will not be used.
 * @return the file the serialized, built clusterer is located in
 */
public File getSerializedClustererFile(){
  return m_SerializedClustererFile;
}

/**
 * Sets the file pointing to a serialized, built clusterer. If the argument is null, doesn't exist or pointing to a directory, then the value is ignored.
 * @param value the file pointing to the serialized, built clusterer
 */
public void setSerializedClustererFile(File value){
  if ((value == null) || (!value.exists())) {
    value=new File(System.getProperty("user.dir"));
  }
  m_SerializedClustererFile=value;
}

/**
 * Returns the tip text for this property.
 * @return tip text for this property suitable for displaying in theexplorer/experimenter gui
 */
public String serializedClustererFileTipText(){
  return "A file containing the serialized model of a built clusterer.";
}

/**
 * Returns the revision string.
 * @return the revision
 */
@Override public String getRevision(){
  return RevisionUtils.extract("$Revision: 10215 $");
}

/**
 * Main method for testing this class.
 * @param argv should contain arguments to the filter: use -h for help
 */
public static void main(String[] argv){
  runFilter(new AddCluster(),argv);
}
}


GL_SGIS_point_line_texgen
http://www.opengl.org/registry/specs/SGIS/point_line_texgen.txt
GL_SGIS_point_line_texgen
	GL_EYE_DISTANCE_TO_POINT_SGIS 0x81F0
	GL_OBJECT_DISTANCE_TO_POINT_SGIS 0x81F1
	GL_EYE_DISTANCE_TO_LINE_SGIS 0x81F2
	GL_OBJECT_DISTANCE_TO_LINE_SGIS 0x81F3
	GL_EYE_POINT_SGIS 0x81F4
	GL_OBJECT_POINT_SGIS 0x81F5
	GL_EYE_LINE_SGIS 0x81F6
	GL_OBJECT_LINE_SGIS 0x81F7


/* Base16 Atelier Lakeside Dark - Theme */
/* by Bram de Haan (http://atelierbram.github.io/syntax-highlighting/atelier-schemes/lakeside/) */
/* Original Base16 color scheme by Chris Kempson (https://github.com/chriskempson/base16) */
/* https://github.com/jmblog/color-themes-for-highlightjs */

/* Atelier Lakeside Dark Comment */
.hljs-comment,
.hljs-title {
  color: #7195a8;
}

/* Atelier Lakeside Dark Red */
.hljs-variable,
.hljs-attribute,
.hljs-tag,
.hljs-regexp,
.ruby .hljs-constant,
.xml .hljs-tag .hljs-title,
.xml .hljs-pi,
.xml .hljs-doctype,
.html .hljs-doctype,
.css .hljs-id,
.css .hljs-class,
.css .hljs-pseudo {
  color: #d22d72;
}

/* Atelier Lakeside Dark Orange */
.hljs-number,
.hljs-preprocessor,
.hljs-pragma,
.hljs-built_in,
.hljs-literal,
.hljs-params,
.hljs-constant {
  color: #935c25;
}

/* Atelier Lakeside Dark Yellow */
.hljs-ruby .hljs-class .hljs-title,
.css .hljs-rules .hljs-attribute {
  color: #8a8a0f;
}

/* Atelier Lakeside Dark Green */
.hljs-string,
.hljs-value,
.hljs-inheritance,
.hljs-header,
.ruby .hljs-symbol,
.xml .hljs-cdata {
  color: #568c3b;
}

/* Atelier Lakeside Dark Aqua */
.css .hljs-hexcolor {
  color: #2d8f6f;
}

/* Atelier Lakeside Dark Blue */
.hljs-function,
.python .hljs-decorator,
.python .hljs-title,
.ruby .hljs-function .hljs-title,
.ruby .hljs-title .hljs-keyword,
.perl .hljs-sub,
.javascript .hljs-title,
.coffeescript .hljs-title {
  color: #257fad;
}

/* Atelier Lakeside Dark Purple */
.hljs-keyword,
.javascript .hljs-function {
  color: #5d5db1;
}

.hljs {
  display: block;
  background: #1f292e;
  color: #7ea2b4;
  padding: 0.5em;
}

.coffeescript .javascript,
.javascript .xml,
.tex .hljs-formula,
.xml .javascript,
.xml .vbscript,
.xml .css,
.xml .hljs-cdata {
  opacity: 0.5;
}


package protocol

import (
	"strings"

	"github.com/aws/aws-sdk-go/aws/request"
)

// ValidateEndpointHostHandler is a request handler that will validate the
// request endpoint's hosts is a valid RFC 3986 host.
var ValidateEndpointHostHandler = request.NamedHandler{
	Name: "awssdk.protocol.ValidateEndpointHostHandler",
	Fn: func(r *request.Request) {
		err := ValidateEndpointHost(r.Operation.Name, r.HTTPRequest.URL.Host)
		if err != nil {
			r.Error = err
		}
	},
}

// ValidateEndpointHost validates that the host string passed in is a valid RFC
// 3986 host. Returns error if the host is not valid.
func ValidateEndpointHost(opName, host string) error {
	paramErrs := request.ErrInvalidParams{Context: opName}
	labels := strings.Split(host, ".")

	for i, label := range labels {
		if i == len(labels)-1 && len(label) == 0 {
			// Allow trailing dot for FQDN hosts.
			continue
		}

		if !ValidHostLabel(label) {
			paramErrs.Add(request.NewErrParamFormat(
				"endpoint host label", "[a-zA-Z0-9-]{1,63}", label))
		}
	}

	if len(host) > 255 {
		paramErrs.Add(request.NewErrParamMaxLen(
			"endpoint host", 255, host,
		))
	}

	if paramErrs.Len() > 0 {
		return paramErrs
	}
	return nil
}

// ValidHostLabel returns if the label is a valid RFC 3986 host label.
func ValidHostLabel(label string) bool {
	if l := len(label); l == 0 || l > 63 {
		return false
	}
	for _, r := range label {
		switch {
		case r >= '0' && r <= '9':
		case r >= 'A' && r <= 'Z':
		case r >= 'a' && r <= 'z':
		case r == '-':
		default:
			return false
		}
	}

	return true
}


#   Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed 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.

from __future__ import print_function

import unittest
import numpy as np

import paddle.fluid as fluid
from benchmark import BenchmarkSuite
from op_test import OpTest

# This is a demo op test case for operator benchmarking and high resolution number stability alignment.

class TestSumOp(BenchmarkSuite):
    def setUp(self):
        self.op_type = "sum"
        self.customize_testcase()
        self.customize_fetch_list()

    def customize_fetch_list(self):
        """
        customize fetch list, configure the wanted variables.
        >>> self.fetch_list = ["Out"]
        """
        self.fetch_list = ["Out"]
        # pass

    def customize_testcase(self):
        # a test case
        x0 = np.random.random((300, 400)).astype('float32')
        x1 = np.random.random((300, 400)).astype('float32')
        x2 = np.random.random((300, 400)).astype('float32')

        # NOTE: if the output is empty, then it will autofilled by benchmarkSuite.
        # only the output dtype is used, the shape, lod and data is computed from input.
        self.inputs = {"X": [("x0", x0), ("x1", x1), ("x2", x2)]}
        self.outputs = {"Out": x0 + x1 + x2}

    def test_check_output(self):
        """
        compare the output with customized output. In this case,
        you should set the correct output by hands.
        >>> self.outputs = {"Out": x0 + x1 + x2}
        """
        self.check_output(atol=1e-8)

    def test_output_stability(self):
        # compare the cpu gpu output in high resolution.
        self.check_output_stability()

    def test_timeit_output(self):
        """
        perf the op, time cost will be averged in iters.
        output example
        >>> One pass of (sum_op) at CPUPlace cost 0.000461330413818
        >>> One pass of (sum_op) at CUDAPlace(0) cost 0.000556070804596
        """
        self.timeit_output(iters=100)

    def test_timeit_grad(self):
        """
        perf the op gradient, time cost will be averged in iters.
        output example
        >>> One pass of (sum_grad_op) at CPUPlace cost 0.00279935121536
        >>> One pass of (sum_grad_op) at CUDAPlace(0) cost 0.00500632047653
        """
        self.timeit_grad(iters=100)

if __name__ == "__main__":
    unittest.main()


<?php

declare(strict_types=1);

namespace DI\Test\IntegrationTest\Issues;

use DI\ContainerBuilder;
use DI\Test\IntegrationTest\BaseContainerTest;

/**
 * Test that chaining several sources works.
 *
 * @see https://github.com/mnapoli/PHP-DI/issues/141
 */
class Issue141Test extends BaseContainerTest
{
    /**
     * @dataProvider provideContainer
     */
    public function testIssue141(ContainerBuilder $builder)
    {
        $builder->addDefinitions(__DIR__ . '/Issue141/config1.php');
        $builder->addDefinitions(__DIR__ . '/Issue141/config2.php');
        $container = $builder->build();

        $this->assertEquals('bar1', $container->get('foo1'));
        $this->assertEquals('bar2', $container->get('foo2'));
    }
}


=========
Transport
=========

.. currentmodule:: zaqar.transport.base

.. autoclass:: DriverBase
   :noindex:
   :members:


# Copyright 2013 the V8 project authors. All rights reserved.
# Copyright (C) 2005, 2006, 2007, 2008, 2009 Apple Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# 1.  Redistributions of source code must retain the above copyright
#     notice, this list of conditions and the following disclaimer.
# 2.  Redistributions in binary form must reproduce the above copyright
#     notice, this list of conditions and the following disclaimer in the
#     documentation and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' AND ANY
# EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS BE LIABLE FOR ANY
# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
# ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

Test for https://bugs.webkit.org/show_bug.cgi?id=46077

On success, you will see a series of "PASS" messages, followed by "TEST COMPLETE".

PASS re.test(str) is false
PASS successfullyParsed is true

TEST COMPLETE


--! qt:dataset:src
set hive.cbo.enable=false;

-- no agg, corr
explain rewrite
select *
from src b
where exists
  (select a.key
  from src a
  where b.value = a.value  and a.key = b.key and a.value > 'val_9'
  )
;

-- sq in from
explain rewrite
select *
from (select *
      from src b
      where exists
          (select a.key
          from src a
          where b.value = a.value  and a.key = b.key and a.value > 'val_9')
     ) a
;


{
  "docker_version": "__DOCKER_VERSION__",
  "aci_gw_image": "contiv/aci-gw:__ACI_GW_VERSION__",
  "contiv_network_version": "__CONTIV_VERSION__",
  "env": {},
  "etcd_peers_group": "netplugin-master",
  "service_vip": "__NETMASTER_IP__",
  "validate_certs": false,
  "cluster_store_driver": "__CLUSTER_STORE_TYPE__",
  "cluster_store_url": "__CLUSTER_STORE_URLS__",
  "auth_proxy_image": "contiv/auth_proxy:__API_PROXY_VERSION__",
  "docker_reset_container_state": __DOCKER_RESET_CONTAINER_STATE__,
  "docker_reset_image_state": __DOCKER_RESET_IMAGE_STATE__,
  "etcd_cleanup_state": __ETCD_CLEANUP_STATE__,
  "auth_proxy_local_install": __AUTH_PROXY_LOCAL_INSTALL__,
  "contiv_network_local_install": __CONTIV_NETWORK_LOCAL_INSTALL__,
  "vxlan_port": __VXLAN_PORT__,
  "netctl_url": "http://__NETMASTER_IP__:9999",
  "contiv_v2plugin_install": __CONTIV_V2PLUGIN_INSTALL__,
  "contiv_v2plugin_image": "contiv/v2plugin:__CONTIV_V2PLUGIN_VERSION__"
}


package org.basex.core.cmd;

import org.basex.core.*;
import org.basex.core.locks.*;
import org.basex.core.users.*;

/**
 * Abstract class for repository commands.
 *
 * @author BaseX Team 2005-20, BSD License
 * @author Jens Erat
 */
abstract class ARepo extends Command {
  /**
   * Constructor for repository commands.
   * @param perm required permission
   * @param args arguments
   */
  ARepo(final Perm perm, final String... args) {
    super(perm, args);
  }

  @Override
  public void addLocks() {
    jc().locks.writes.add(Locking.REPO); // Repository commands are exclusive
  }
}


.cm-s-the-matrix.CodeMirror { background: #000000; color: #00FF00; }
.cm-s-the-matrix div.CodeMirror-selected { background: #2D2D2D !important; }
.cm-s-the-matrix .CodeMirror-gutters { background: #060; border-right: 2px solid #00FF00; }
.cm-s-the-matrix .CodeMirror-linenumber { color: #FFFFFF; }
.cm-s-the-matrix .CodeMirror-cursor { border-left: 1px solid #00FF00 !important; }

.cm-s-the-matrix span.cm-keyword {color: #008803; font-weight: bold;}
.cm-s-the-matrix span.cm-atom {color: #3FF;}
.cm-s-the-matrix span.cm-number {color: #FFB94F;}
.cm-s-the-matrix span.cm-def {color: #99C;}
.cm-s-the-matrix span.cm-variable {color: #F6C;}
.cm-s-the-matrix span.cm-variable-2 {color: #C6F;}
.cm-s-the-matrix span.cm-variable-3 {color: #96F;}
.cm-s-the-matrix span.cm-property {color: #62FFA0;}
.cm-s-the-matrix span.cm-operator {color: #999}
.cm-s-the-matrix span.cm-comment {color: #CCCCCC;}
.cm-s-the-matrix span.cm-string {color: #39C;}
.cm-s-the-matrix span.cm-meta {color: #C9F;}
.cm-s-the-matrix span.cm-qualifier {color: #FFF700;}
.cm-s-the-matrix span.cm-builtin {color: #30a;}
.cm-s-the-matrix span.cm-bracket {color: #cc7;}
.cm-s-the-matrix span.cm-tag {color: #FFBD40;}
.cm-s-the-matrix span.cm-attribute {color: #FFF700;}
.cm-s-the-matrix span.cm-error {color: #FF0000;}

.cm-s-the-matrix .CodeMirror-activeline-background {background: #040;}


This file describes implementation and API changes; stuff more visible to the
user appears in the "release notes" instead.  See the bottom of this file
for original notes on source style and organization.

0.42.0

changed definition of t_float, t_sample, t_floatarg so that they can be
set via #defines (PD_FLOATTYPE, etc).

0.41.0

add support for callback-based audio I/O
headers & code changed to use t_float or t_sample instead of float (patches
by zmoelnig).

0.40.0

0.39.0

canvas_dspstate and signalinlet_new() exported to m_pd.h

new function verbose() added to m_pd.h

0.38.0

finally figured out how to do "-enable-", etc., flags in the configure
script correctly.

The scheduler now has a hook (set_so you can add polling routines) :
    sys_idlehook().

I'm now uploading directly to CVS repository ("main" and "stable_0_38"
branches.)  There are still problems keeping CVS's and my versions of
portaudio the same (CVS bashes the "ident" lines).

t_int to int in binbuf_addv prototype

64-bit fix to externs makefiles

Pd now uses portaudio out-of-the-box; customized files are moved to
"src" directory.

All "tags" are printf'd as %lx to make 64-bit safe.

GUI queueing mechanism added: sys_queuegui() etc.

massive rewrite of array code to unify arrays and scalars.

fixed empty lists automatically to call "bang" method if one is supplied.

rewrote the "namelist" stuff to facilitate preference saving (s_stuff.h,
s_path.c, s_file.c, s_main.c)

0.37.2

expr() "exp" temporary variables renamed to avoid compilation problems

0.37.1

makefile.in: MANINSTDIR = $(DESTDIR)/$(MANDIR) changed to
    $(DESTDIR)/$(INSTALL_PREFIX)/$(MANDIR) (thx. Mathieu Bouchard)

applied 2 jack patches from Luke Yelavich

add -fno-strict-aliasing to config script (linux&mac) to improve underflow,
etc., protection

add underflow protection to vcf~ object; rewrote underflow protection to be
faster in throw~/catch~ and send~/receive~

fixed bug in -inchannels/-outchannels arg parsing

fixed u_main.tk to make "apple" key work to accelerate menus on MACOS

fooled with MIDI to try to get sysex and other system messages to work.
Needs lots of testing now...

finally fixed OSS to open audio with NODELAY... also cleared dup-on-exec flag.

bug fix in scalar_properties

major editions to the IEM GUIs to fix bugs in how "$" variables are handled.
The code still isn't pretty but hopefully at least works now.

tried to get alsa noninterleaved access to work (needed for RME).  Failed
to get my RME card to load under ALSA and gave up for now.

fixed scalar drawing to fail gracefully when the template canvas disappears

bug fix in vd~ for very small delays (d_delay.c)

set up sys_oldtclversion flag to correct for changed text selection
(u_main.tk, s_main.c, g_rtext.c)

tried again to add "readn" support to s_audio_alsa.c: coded, but failing so far.

fixed broken octave divider example

removed "-Werror" from default makefile; fixed  configure script to respect
"CFLAGS" environment variable instead.  Suggest developers should use
"setenv CFLAGS -Werror".

added "-alsaadd" flag so people can specify alsa devnames to add to list.
fixed some problems with Pd crashing when ALSA failed to open.

took out the 2-pixel padding for MSW in g_canvas.g (HORIZBORDER/VERTBORDER)

went back to s_midi_mmio (portaudio version got assertion errors and anyway
I could never get sysex working in it as I had wanted.)

Took bug fixes from s_midi_pm.c, s_audio_jack.c, s_inter.c from "devel" branch;
also added "static" flag to configure.in (but the devel configure.in as a whole
doesn't seem to work for OSX, for me at least.)

Might have fixed a bug where labels disappear in buttons, etc, when saved
and reloaded.

brought s_audio_alsa.c up to alsa 1.0.0 compatibility

fixed "-alsaadd" (never worked before)

fooled with macintosh audio.  Fixed some (not all) of the audio I/O APIs
to deal with open failures better (reducing sys_{in,out}channels accordingly)

In the Alsa API, the synchronization test was too stringent and was loosened
to 3*DACBLKSIZE/2.

'make install' fixed to deal with 'extra' correctly.

one more improvement in jack support (guenter)

make an "nrt" flag so mac can disable pthread_setschedparam call if yu want.

------------------- original source notes -------------

0.  structure definition roadmap.  First, the containment tree of things
that can be sent messages ("pure data").  (note that t_object and t_text,
and t_graph and t_canvas, should be unified...)

------------ BFFORE 0.35: ---------
m_pd.h	    t_pd    	    	    anything with a class
    	    	t_gobj	    	    "graphic object"
    	    	    t_text  	    text object
g_canvas.h
    	    	    t_glist 	    list of graphic objects
g_canvas.c  	    	t_canvas    Pd "document"

------------ AFTER 0.35: ---------
m_pd.h	    t_pd    	    	    anything with a class
    	    	t_gobj	    	    "graphic object"
    	    	    t_text  	    patchable object, AKA t_object
g_canvas.h     	    	t_glist     list of graphic objects, AKA t_canvas

... and other structures:
g_canvas.h  t_selection -- linked list of gobjs
    	    t_editor -- editor state, allocated for visible glists
m_imp.h     t_methodentry -- method handler
    	    t_widgetbehavior -- class-dependent editing behavior for gobjs
    	    t_parentwidgetbehavior -- objects' behavior on parent window
    	    t_class -- method definitions, instance size, flags, etc.

1.  C coding style.  The source should pass most "warnings" of C compilers
(-Wall on linux, for instance; see the makefile.)  Some informalities
are intentional, for instance the loose use of function prototypes (see
below) and uncast conversions from longer to shorter numerical formats.
The code doesn't respect "const" yet.

1.1.  Prefixes in structure elements.  The names of structure elements always
have a K&R-style prefix, as in ((t_atom)x)->a_type, where the "a_" prefix
indicates "atom."  This is intended to enhance readability (although the
convention arose from a limitation of early C compilers.)  Common prefixes are
"w_" (word), "a_" (atom), "s_" (symbol), "ob_" (object), "te_" (text object),
"g_" (graphical object), and "gl_" (glist, a list of graphical objects).  Also,
global symbols sometimes get prefixes, as in "s_float" (the symbol whose string
is "float).  Typedefs are prefixed by "t_".  Most _private_ structures, i.e.,
structures whose definitions appear in a ".c" file, are prefixed by "x_".

1.2.   Function arguments.  Many functions take as their first
argument a pointer named "x", which is a pointer to a structure suggested
by the function prefix; e.g., canvas_dirty(x, n) where "x" points to a canvas
(t_canvas *x).

1.3.  Function Prototypes.  Functions which are used in at least two different
files (besides where they originate) are prototyped in the appropriate include
file. Functions which are provided in one file and used in one other are
prototyped right where they are used.  This is just to keep the size of the
".h" files down for readability's sake.

1.4.  Whacko private terminology.  Some terms are lifted from other historically
relevant programs, notably "ugen" (which is just a tilde object; see d_ugen.c.)

1.5.  Spacing.  Tabs are 8 spaces; indentation is 4 spaces.  Indenting
curly brackets are by themselves on their own lines, as in:

    if (x)
    {
	x = 0;
    }

Lines should fit within 80 spaces.

2.  Max patch-level compatibility.  "Import" and "Export" functions are
provided which aspire to strict compatibility with 0.26 patches (ISPW version),
but which don't get anywhere close to that yet.  Where possible, features
appearing on the Mac will comeday also be provided; for instance, the connect
message on the Mac offers segmented patch cords; these will devolve into
straight lines in Pd.  Many, many UI objects in Opcode Max will not appear in
Pd, at least at first.

3.  Compatibility with Max 0.26 "externs", i.e., source-level compatibility. Pd
objects follow the style of 0.26 objects as closely as possible, making
exceptions in cases where the 0.26 model is clearly deficient.  These are:

3.1.  Anything involving the MacIntosh "Handle" data type is changed to use
char * or void * instead.

3.2.  Pd passes true single-precision floating-point arguments to methods;
Max uses double.
Typedefs are provided:
    t_floatarg, t_intarg for arguments passed by the message system
    t_float, t_int for the "word" union (in atoms, for example.)

3.3.  Badly-named entities got name changes:

    w_long --> w_int (in the "union word" structure)

3.4.  Many library functions are renamed and have different arguments;
I hope to provide an include file to alias them when compiling Max externs.

4.  Function name prefixes.
Many function names have prefixes which indicate what "package" they belong
to.  The exceptions are:
    typedmess, vmess, getfn, gensym (m_class.c)
    getbytes, freebytes, resizebytes (m_memory.c)
    post, error, bug (s_print.c)
which are all frequently called and which don't fit into simple categories.
Important packages are:
(pd-gui:)   pdgui -- everything
(pd:)	    pd -- functions common to all "pd" objects
    	    obj -- fuctions common to all "patchable" objects ala Max
    	    sys -- "system" level functions
    	    binbuf -- functions manipulating binbufs
    	    class -- functions manipulating classes
    	    (other) -- functions common to the named Pd class

5. Source file prefixes.
PD:
s    system interface
m    message system
g    graphics stuff
d    DSP objects
x    control objects
z    other

PD-GUI:
t    TK front end


import torch
import utils as u
import os

class sbm_dataset():
    def __init__(self,args):
        assert args.task in ['link_pred'], 'sbm only implements link_pred'
        self.ecols = u.Namespace({'FromNodeId': 0,
                                  'ToNodeId': 1,
                                  'Weight': 2,
                                  'TimeStep': 3
                                })
        args.sbm_args = u.Namespace(args.sbm_args)

        #build edge data structure
        edges = self.load_edges(args.sbm_args)
        timesteps = u.aggregate_by_time(edges[:,self.ecols.TimeStep], args.sbm_args.aggr_time)
        self.max_time = timesteps.max()
        self.min_time = timesteps.min()
        print ('TIME', self.max_time, self.min_time )
        edges[:,self.ecols.TimeStep] = timesteps

        edges[:,self.ecols.Weight] = self.cluster_negs_and_positives(edges[:,self.ecols.Weight])
        self.num_classes = edges[:,self.ecols.Weight].unique().size(0)

        self.edges = self.edges_to_sp_dict(edges)

        #random node features
        self.num_nodes = int(self.get_num_nodes(edges))
        self.feats_per_node = args.sbm_args.feats_per_node
        self.nodes_feats = torch.rand((self.num_nodes,self.feats_per_node))

        self.num_non_existing = self.num_nodes ** 2 - edges.size(0)

    def cluster_negs_and_positives(self,ratings):
        pos_indices = ratings >= 0
        neg_indices = ratings < 0
        ratings[pos_indices] = 1
        ratings[neg_indices] = 0
        return ratings

    def prepare_node_feats(self,node_feats):
        node_feats = node_feats[0]
        return node_feats

    def edges_to_sp_dict(self,edges):
        idx = edges[:,[self.ecols.FromNodeId,
                       self.ecols.ToNodeId,
                       self.ecols.TimeStep]]

        vals = edges[:,self.ecols.Weight]
        return {'idx': idx,
                'vals': vals}

    def get_num_nodes(self,edges):
        all_ids = edges[:,[self.ecols.FromNodeId,self.ecols.ToNodeId]]
        num_nodes = all_ids.max() + 1
        return num_nodes

    def load_edges(self,sbm_args, starting_line = 1):
        file = os.path.join(sbm_args.folder,sbm_args.edges_file)
        with open(file) as f:
            lines = f.read().splitlines()
        edges = [[float(r) for r in row.split(',')] for row in lines[starting_line:]]
        edges = torch.tensor(edges,dtype = torch.long)
        return edges

    def make_contigous_node_ids(self,edges):
        new_edges = edges[:,[self.ecols.FromNodeId,self.ecols.ToNodeId]]
        _, new_edges = new_edges.unique(return_inverse=True)
        edges[:,[self.ecols.FromNodeId,self.ecols.ToNodeId]] = new_edges
        return edges


apiVersion: v1
kind: ConfigMap
metadata:
  labels:
    k8s-app: kubernetes-dashboard
    # Allows editing resource and makes sure it is created first.
    addonmanager.kubernetes.io/mode: EnsureExists
  name: kubernetes-dashboard-settings
  namespace: kube-system


// Copyright 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "ui/events/x/x11_event_translation.h"

#include <vector>

#include "base/check.h"
#include "base/notreached.h"
#include "base/time/time.h"
#include "ui/events/devices/x11/touch_factory_x11.h"
#include "ui/events/event.h"
#include "ui/events/event_utils.h"
#include "ui/events/keycodes/keyboard_code_conversion_x.h"
#include "ui/events/pointer_details.h"
#include "ui/events/types/event_type.h"
#include "ui/events/x/events_x_utils.h"
#include "ui/gfx/geometry/point.h"
#include "ui/gfx/x/x11.h"

namespace ui {

namespace {

// In X11 touch events, a new tracking_id/slot mapping is set up for each new
// event (see |ui::GetTouchIdFromXEvent| function), which needs to be cleared
// at destruction time for corresponding release/cancel events. In this
// particular case, ui::TouchEvent class is extended so that dtor can be
// overridden in order to implement this platform-specific behavior.
class TouchEventX11 : public ui::TouchEvent {
 public:
  TouchEventX11(EventType type,
                gfx::Point location,
                base::TimeTicks timestamp,
                const PointerDetails& pointer_details)
      : TouchEvent(type, location, timestamp, pointer_details) {}

  ~TouchEventX11() override {
    if (type() == ET_TOUCH_RELEASED || type() == ET_TOUCH_CANCELLED)
      TouchFactory::GetInstance()->ReleaseSlot(pointer_details().id);
  }
};

Event::Properties GetEventPropertiesFromXEvent(EventType type,
                                               const x11::Event& x11_event) {
  const XEvent& xev = x11_event.xlib_event();
  using Values = std::vector<uint8_t>;
  Event::Properties properties;
  if (type == ET_KEY_PRESSED || type == ET_KEY_RELEASED) {
    // Keyboard group
    uint8_t group = XkbGroupForCoreState(xev.xkey.state);
    properties.emplace(kPropertyKeyboardGroup, Values{group});

    // Hardware keycode
    uint8_t hw_keycode = xev.xkey.keycode;
    properties.emplace(kPropertyKeyboardHwKeyCode, Values{hw_keycode});

    // IBus-gtk specific flags
    uint8_t ibus_flags = (xev.xkey.state >> kPropertyKeyboardIBusFlagOffset) &
                         kPropertyKeyboardIBusFlagMask;
    if (ibus_flags)
      properties.emplace(kPropertyKeyboardIBusFlag, Values{ibus_flags});

  } else if (type == ET_MOUSE_EXITED) {
    // NotifyVirtual events are created for intermediate windows that the
    // pointer crosses through. These occur when middle clicking.
    // Change these into mouse move events.
    bool crossing_intermediate_window = xev.xcrossing.detail == NotifyVirtual;
    if (crossing_intermediate_window) {
      properties.emplace(kPropertyMouseCrossedIntermediateWindow,
                         crossing_intermediate_window);
    }
  }
  return properties;
}

std::unique_ptr<KeyEvent> CreateKeyEvent(EventType event_type,
                                         const x11::Event& x11_event) {
  const XEvent& xev = x11_event.xlib_event();
  KeyboardCode key_code = KeyboardCodeFromXKeyEvent(&xev);
  int event_flags = EventFlagsFromXEvent(x11_event);

  // In Ozone builds, keep DomCode/DomKey unset, so they are extracted lazily
  // in KeyEvent::ApplyLayout() which makes it possible for CrOS/Linux, for
  // example, to support host system keyboard layouts.
#if defined(USE_OZONE)
  auto event = std::make_unique<KeyEvent>(event_type, key_code, event_flags,
                                          EventTimeFromXEvent(x11_event));
#else
  auto event = std::make_unique<KeyEvent>(
      event_type, key_code, CodeFromXEvent(&xev), event_flags,
      GetDomKeyFromXEvent(&xev), EventTimeFromXEvent(x11_event));
#endif

  DCHECK(event);
  event->SetProperties(GetEventPropertiesFromXEvent(event_type, x11_event));
  event->InitializeNative();
  return event;
}

void SetEventSourceDeviceId(MouseEvent* event, const x11::Event& x11_event) {
  const XEvent& xev = x11_event.xlib_event();
  DCHECK(event);
  if (xev.type == x11::GeGenericEvent::opcode) {
    XIDeviceEvent* xiev = static_cast<XIDeviceEvent*>(xev.xcookie.data);
    event->set_source_device_id(xiev->sourceid);
  }
}

std::unique_ptr<MouseEvent> CreateMouseEvent(EventType type,
                                             const x11::Event& x11_event) {
  const XEvent& xev = x11_event.xlib_event();
  // Ignore EventNotify and LeaveNotify events from children of |xwindow_|.
  // NativeViewGLSurfaceGLX adds a child to |xwindow_|.
  // https://crbug.com/792322
  bool enter_or_leave = xev.type == x11::CrossingEvent::EnterNotify ||
                        xev.type == x11::CrossingEvent::LeaveNotify;
  if (enter_or_leave && xev.xcrossing.detail == NotifyInferior)
    return nullptr;

  PointerDetails details{EventPointerType::kMouse};
  auto event = std::make_unique<MouseEvent>(
      type, EventLocationFromXEvent(x11_event),
      EventSystemLocationFromXEvent(x11_event), EventTimeFromXEvent(x11_event),
      EventFlagsFromXEvent(x11_event),
      GetChangedMouseButtonFlagsFromXEvent(x11_event), details);

  DCHECK(event);
  SetEventSourceDeviceId(event.get(), x11_event);
  event->SetProperties(GetEventPropertiesFromXEvent(type, x11_event));
  event->InitializeNative();
  return event;
}

std::unique_ptr<MouseWheelEvent> CreateMouseWheelEvent(
    const x11::Event& x11_event) {
  const XEvent& xev = x11_event.xlib_event();
  int button_flags = (xev.type == x11::GeGenericEvent::opcode)
                         ? GetChangedMouseButtonFlagsFromXEvent(x11_event)
                         : 0;
  auto event = std::make_unique<MouseWheelEvent>(
      GetMouseWheelOffsetFromXEvent(x11_event),
      EventLocationFromXEvent(x11_event),
      EventSystemLocationFromXEvent(x11_event), EventTimeFromXEvent(x11_event),
      EventFlagsFromXEvent(x11_event), button_flags);

  DCHECK(event);
  event->InitializeNative();
  return event;
}

std::unique_ptr<TouchEvent> CreateTouchEvent(EventType type,
                                             const x11::Event& xev) {
  auto event = std::make_unique<TouchEventX11>(
      type, EventLocationFromXEvent(xev), EventTimeFromXEvent(xev),
      GetTouchPointerDetailsFromXEvent(xev));
#if defined(USE_OZONE)
  // Touch events don't usually have |root_location| set differently than
  // |location|, since there is a touch device to display association, but this
  // doesn't happen in Ozone X11.
  event->set_root_location(EventSystemLocationFromXEvent(xev));
#endif
  return event;
}

std::unique_ptr<ScrollEvent> CreateScrollEvent(EventType type,
                                               const x11::Event& xev) {
  float x_offset, y_offset, x_offset_ordinal, y_offset_ordinal;
  int finger_count = 0;

  if (type == ET_SCROLL) {
    GetScrollOffsetsFromXEvent(xev, &x_offset, &y_offset, &x_offset_ordinal,
                               &y_offset_ordinal, &finger_count);
  } else {
    GetFlingDataFromXEvent(xev, &x_offset, &y_offset, &x_offset_ordinal,
                           &y_offset_ordinal, nullptr);
  }
  auto event = std::make_unique<ScrollEvent>(
      type, EventLocationFromXEvent(xev), EventTimeFromXEvent(xev),
      EventFlagsFromXEvent(xev), x_offset, y_offset, x_offset_ordinal,
      y_offset_ordinal, finger_count);

  DCHECK(event);
  // We need to filter zero scroll offset here. Because MouseWheelEventQueue
  // assumes we'll never get a zero scroll offset event and we need delta to
  // determine which element to scroll on phaseBegan.
  return (event->x_offset() != 0.0 || event->y_offset() != 0.0)
             ? std::move(event)
             : nullptr;
}

// Translates XI2 XEvent into a ui::Event.
std::unique_ptr<ui::Event> TranslateFromXI2Event(const x11::Event& xev,
                                                 EventType event_type) {
  switch (event_type) {
    case ET_KEY_PRESSED:
    case ET_KEY_RELEASED:
      return CreateKeyEvent(event_type, xev);
    case ET_MOUSE_PRESSED:
    case ET_MOUSE_RELEASED:
    case ET_MOUSE_MOVED:
    case ET_MOUSE_DRAGGED:
    case ET_MOUSE_ENTERED:
    case ET_MOUSE_EXITED:
      return CreateMouseEvent(event_type, xev);
    case ET_MOUSEWHEEL:
      return CreateMouseWheelEvent(xev);
    case ET_SCROLL_FLING_START:
    case ET_SCROLL_FLING_CANCEL:
    case ET_SCROLL:
      return CreateScrollEvent(event_type, xev);
    case ET_TOUCH_MOVED:
    case ET_TOUCH_PRESSED:
    case ET_TOUCH_CANCELLED:
    case ET_TOUCH_RELEASED:
      return CreateTouchEvent(event_type, xev);
    case ET_UNKNOWN:
      return nullptr;
    default:
      break;
  }
  return nullptr;
}

std::unique_ptr<Event> TranslateFromXEvent(const x11::Event& xev) {
  EventType event_type = EventTypeFromXEvent(xev);
  switch (xev.xlib_event().type) {
    case x11::CrossingEvent::LeaveNotify:
    case x11::CrossingEvent::EnterNotify:
    case x11::MotionNotifyEvent::opcode:
      return CreateMouseEvent(event_type, xev);
    case x11::KeyEvent::Press:
    case x11::KeyEvent::Release:
      return CreateKeyEvent(event_type, xev);
    case x11::ButtonEvent::Press:
    case x11::ButtonEvent::Release: {
      switch (event_type) {
        case ET_MOUSEWHEEL:
          return CreateMouseWheelEvent(xev);
        case ET_MOUSE_PRESSED:
        case ET_MOUSE_RELEASED:
          return CreateMouseEvent(event_type, xev);
        case ET_UNKNOWN:
          // No event is created for X11-release events for mouse-wheel
          // buttons.
          break;
        default:
          NOTREACHED();
      }
      break;
    }
    case x11::GeGenericEvent::opcode:
      return TranslateFromXI2Event(xev, event_type);
  }
  return nullptr;
}

}  // namespace

// Translates a XEvent into a ui::Event.
std::unique_ptr<Event> BuildEventFromXEvent(const x11::Event& xev) {
  auto event = TranslateFromXEvent(xev);
  if (event)
    ui::ComputeEventLatencyOS(event.get());
  return event;
}

// Convenience function that translates XEvent into ui::KeyEvent
std::unique_ptr<KeyEvent> BuildKeyEventFromXEvent(const x11::Event& xev) {
  auto event = BuildEventFromXEvent(xev);
  if (!event || !event->IsKeyEvent())
    return nullptr;
  return std::unique_ptr<KeyEvent>{event.release()->AsKeyEvent()};
}

// Convenience function that translates XEvent into ui::MouseEvent
std::unique_ptr<MouseEvent> BuildMouseEventFromXEvent(const x11::Event& xev) {
  auto event = BuildEventFromXEvent(xev);
  if (!event || !event->IsMouseEvent())
    return nullptr;
  return std::unique_ptr<MouseEvent>{event.release()->AsMouseEvent()};
}

// Convenience function that translates XEvent into ui::TouchEvent
std::unique_ptr<TouchEvent> BuildTouchEventFromXEvent(const x11::Event& xev) {
  auto event = BuildEventFromXEvent(xev);
  if (!event || !event->IsTouchEvent())
    return nullptr;
  return std::unique_ptr<TouchEvent>{event.release()->AsTouchEvent()};
}

// Convenience function that translates XEvent into ui::MouseWheelEvent
std::unique_ptr<MouseWheelEvent> BuildMouseWheelEventFromXEvent(
    const x11::Event& xev) {
  auto event = BuildEventFromXEvent(xev);
  if (!event || !event->IsMouseWheelEvent())
    return nullptr;
  return std::unique_ptr<MouseWheelEvent>{event.release()->AsMouseWheelEvent()};
}

}  // namespace ui


// Copyright 2018 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package lsp

import (
	"context"
	"fmt"
	"strings"

	"golang.org/x/tools/internal/lsp/protocol"
	"golang.org/x/tools/internal/lsp/source"
	"golang.org/x/tools/internal/span"
)

func (s *Server) codeAction(ctx context.Context, params *protocol.CodeActionParams) ([]protocol.CodeAction, error) {
	uri := span.NewURI(params.TextDocument.URI)
	view := s.session.ViewOf(uri)
	_, m, err := getSourceFile(ctx, view, uri)
	if err != nil {
		return nil, err
	}
	spn, err := m.RangeSpan(params.Range)
	if err != nil {
		return nil, err
	}
	var codeActions []protocol.CodeAction
	// TODO(rstambler): Handle params.Context.Only when VSCode-Go uses a
	// version of vscode-languageclient that fixes
	// https://github.com/Microsoft/vscode-languageserver-node/issues/442.
	edits, err := organizeImports(ctx, view, spn)
	if err != nil {
		return nil, err
	}
	if len(edits) > 0 {
		codeActions = append(codeActions, protocol.CodeAction{
			Title: "Organize Imports",
			Kind:  protocol.SourceOrganizeImports,
			Edit: &protocol.WorkspaceEdit{
				Changes: &map[string][]protocol.TextEdit{
					string(spn.URI()): edits,
				},
			},
		})
		// If we also have diagnostics, we can associate them with quick fixes.
		if findImportErrors(params.Context.Diagnostics) {
			// TODO(rstambler): Separate this into a set of codeActions per diagnostic,
			// where each action is the addition or removal of one import.
			// This can only be done when https://golang.org/issue/31493 is resolved.
			codeActions = append(codeActions, protocol.CodeAction{
				Title: "Organize All Imports", // clarify that all imports will change
				Kind:  protocol.QuickFix,
				Edit: &protocol.WorkspaceEdit{
					Changes: &map[string][]protocol.TextEdit{
						string(uri): edits,
					},
				},
			})
		}
	}
	return codeActions, nil
}

func organizeImports(ctx context.Context, v source.View, s span.Span) ([]protocol.TextEdit, error) {
	f, m, err := getGoFile(ctx, v, s.URI())
	if err != nil {
		return nil, err
	}
	rng, err := s.Range(m.Converter)
	if err != nil {
		return nil, err
	}
	if rng.Start == rng.End {
		// If we have a single point, assume we want the whole file.
		tok := f.GetToken(ctx)
		if tok == nil {
			return nil, fmt.Errorf("no file information for %s", f.URI())
		}
		rng.End = tok.Pos(tok.Size())
	}
	edits, err := source.Imports(ctx, f, rng)
	if err != nil {
		return nil, err
	}
	return ToProtocolEdits(m, edits)
}

// findImports determines if a given diagnostic represents an error that could
// be fixed by organizing imports.
// TODO(rstambler): We need a better way to check this than string matching.
func findImportErrors(diagnostics []protocol.Diagnostic) bool {
	for _, diagnostic := range diagnostics {
		// "undeclared name: X" may be an unresolved import.
		if strings.HasPrefix(diagnostic.Message, "undeclared name: ") {
			return true
		}
		// "could not import: X" may be an invalid import.
		if strings.HasPrefix(diagnostic.Message, "could not import: ") {
			return true
		}
		// "X imported but not used" is an unused import.
		if strings.HasSuffix(diagnostic.Message, " imported but not used") {
			return true
		}
	}
	return false
}