text:
/* New getargs implementation */

#include "Python.h"

#include <ctype.h>

#ifdef __cplusplus
extern "C" {
#endif
int PyArg_Parse(PyObject *, const char *, ...);
int PyArg_ParseTuple(PyObject *, const char *, ...);
int PyArg_VaParse(PyObject *, const char *, va_list);

int PyArg_ParseTupleAndKeywords(PyObject *, PyObject *,
				const char *, char **, ...);
int PyArg_VaParseTupleAndKeywords(PyObject *, PyObject *,
				const char *, char **, va_list);

#ifdef HAVE_DECLSPEC_DLL
/* Export functions */
PyAPI_FUNC(int) _PyArg_Parse_SizeT(PyObject *, char *, ...);
PyAPI_FUNC(int) _PyArg_ParseTuple_SizeT(PyObject *, char *, ...);
PyAPI_FUNC(int) _PyArg_ParseTupleAndKeywords_SizeT(PyObject *, PyObject *,
                                                  const char *, char **, ...);
PyAPI_FUNC(PyObject *) _Py_BuildValue_SizeT(const char *, ...);
PyAPI_FUNC(int) _PyArg_VaParse_SizeT(PyObject *, char *, va_list);
PyAPI_FUNC(int) _PyArg_VaParseTupleAndKeywords_SizeT(PyObject *, PyObject *,
                                              const char *, char **, va_list);
#endif

#define FLAG_COMPAT 1
#define FLAG_SIZE_T 2

/* Forward */
static int vgetargs1(PyObject *, const char *, va_list *, int);
static void seterror(int, const char *, int *, const char *, const char *);
static char *convertitem(PyObject *, const char **, va_list *, int, int *,
                         char *, size_t, PyObject **);
static char *converttuple(PyObject *, const char **, va_list *, int,
			  int *, char *, size_t, int, PyObject **);
static char *convertsimple(PyObject *, const char **, va_list *, int, char *,
			   size_t, PyObject **);
static Py_ssize_t convertbuffer(PyObject *, void **p, char **);
static int getbuffer(PyObject *, Py_buffer *, char**);

static int vgetargskeywords(PyObject *, PyObject *,
			    const char *, char **, va_list *, int);
static char *skipitem(const char **, va_list *, int);

int
PyArg_Parse(PyObject *args, const char *format, ...)
{
	int retval;
	va_list va;

	va_start(va, format);
	retval = vgetargs1(args, format, &va, FLAG_COMPAT);
	va_end(va);
	return retval;
}

int
_PyArg_Parse_SizeT(PyObject *args, char *format, ...)
{
	int retval;
	va_list va;

	va_start(va, format);
	retval = vgetargs1(args, format, &va, FLAG_COMPAT|FLAG_SIZE_T);
	va_end(va);
	return retval;
}

int
PyArg_ParseTuple(PyObject *args, const char *format, ...)
{
	int retval;
	va_list va;

	va_start(va, format);
	retval = vgetargs1(args, format, &va, 0);
	va_end(va);
	return retval;
}

int
_PyArg_ParseTuple_SizeT(PyObject *args, char *format, ...)
{
	int retval;
	va_list va;

	va_start(va, format);
	retval = vgetargs1(args, format, &va, FLAG_SIZE_T);
	va_end(va);
	return retval;
}

int
PyArg_VaParse(PyObject *args, const char *format, va_list va)
{
	va_list lva;

#ifdef VA_LIST_IS_ARRAY
	memcpy(lva, va, sizeof(va_list));
#else
#ifdef __va_copy
	__va_copy(lva, va);
#else
	lva = va;
#endif
#endif

	return vgetargs1(args, format, &lva, 0);
}

int
_PyArg_VaParse_SizeT(PyObject *args, char *format, va_list va)
{
	va_list lva;

#ifdef VA_LIST_IS_ARRAY
	memcpy(lva, va, sizeof(va_list));
#else
#ifdef __va_copy
	__va_copy(lva, va);
#else
	lva = va;
#endif
#endif

	return vgetargs1(args, format, &lva, FLAG_SIZE_T);
}

/* Handle cleanup of allocated memory in case of exception */

static void
cleanup_ptr(void *ptr)
{
	PyMem_FREE(ptr);
}

static void
cleanup_buffer(void *ptr)
{
	PyBuffer_Release((Py_buffer *) ptr);
}

static int
addcleanup(void *ptr, PyObject **freelist, void (*destr)(void *))
{
	PyObject *cobj;
	if (!*freelist) {
		*freelist = PyList_New(0);
		if (!*freelist) {
			destr(ptr);
			return -1;
		}
	}
	cobj = PyCObject_FromVoidPtr(ptr, destr);
	if (!cobj) {
		destr(ptr);
		return -1;
	}
	if (PyList_Append(*freelist, cobj)) {
		Py_DECREF(cobj);
		return -1;
	}
        Py_DECREF(cobj);
	return 0;
}

static int
cleanreturn(int retval, PyObject *freelist)
{
	if (freelist && retval != 0) {
		/* We were successful, reset the destructors so that they
		   don't get called. */
		Py_ssize_t len = PyList_GET_SIZE(freelist), i;
		for (i = 0; i < len; i++)
			((PyCObject *) PyList_GET_ITEM(freelist, i))
				->destructor = NULL;
	}
	Py_XDECREF(freelist);
	return retval;
}

static int
vgetargs1(PyObject *args, const char *format, va_list *p_va, int flags)
{
	char msgbuf[256];
	int levels[32];
	const char *fname = NULL;
	const char *message = NULL;
	int min = -1;
	int max = 0;
	int level = 0;
	int endfmt = 0;
	const char *formatsave = format;
	Py_ssize_t i, len;
	char *msg;
	PyObject *freelist = NULL;
	int compat = flags & FLAG_COMPAT;

	assert(compat || (args != (PyObject*)NULL));
	flags = flags & ~FLAG_COMPAT;

	while (endfmt == 0) {
		int c = *format++;
		switch (c) {
		case '(':
			if (level == 0)
				max++;
			level++;
			if (level >= 30)
				Py_FatalError("too many tuple nesting levels "
					      "in argument format string");
			break;
		case ')':
			if (level == 0)
				Py_FatalError("excess ')' in getargs format");
			else
				level--;
			break;
		case '\0':
			endfmt = 1;
			break;
		case ':':
			fname = format;
			endfmt = 1;
			break;
		case ';':
			message = format;
			endfmt = 1;
			break;
		default:
			if (level == 0) {
				if (c == 'O')
					max++;
				else if (isalpha(Py_CHARMASK(c))) {
					if (c != 'e') /* skip encoded */
						max++;
				} else if (c == '|')
					min = max;
			}
			break;
		}
	}

	if (level != 0)
		Py_FatalError(/* '(' */ "missing ')' in getargs format");

	if (min < 0)
		min = max;

	format = formatsave;

	if (compat) {
		if (max == 0) {
			if (args == NULL)
				return 1;
			PyOS_snprintf(msgbuf, sizeof(msgbuf),
				      "%.200s%s takes no arguments",
				      fname==NULL ? "function" : fname,
				      fname==NULL ? "" : "()");
			PyErr_SetString(PyExc_TypeError, msgbuf);
			return 0;
		}
		else if (min == 1 && max == 1) {
			if (args == NULL) {
				PyOS_snprintf(msgbuf, sizeof(msgbuf),
				      "%.200s%s takes at least one argument",
					      fname==NULL ? "function" : fname,
					      fname==NULL ? "" : "()");
				PyErr_SetString(PyExc_TypeError, msgbuf);
				return 0;
			}
			msg = convertitem(args, &format, p_va, flags, levels,
					  msgbuf, sizeof(msgbuf), &freelist);
			if (msg == NULL)
				return cleanreturn(1, freelist);
			seterror(levels[0], msg, levels+1, fname, message);
			return cleanreturn(0, freelist);
		}
		else {
			PyErr_SetString(PyExc_SystemError,
			    "old style getargs format uses new features");
			return 0;
		}
	}

	if (!PyTuple_Check(args)) {
		PyErr_SetString(PyExc_SystemError,
		    "new style getargs format but argument is not a tuple");
		return 0;
	}

	len = PyTuple_GET_SIZE(args);

	if (len < min || max < len) {
		if (message == NULL) {
			PyOS_snprintf(msgbuf, sizeof(msgbuf),
				      "%.150s%s takes %s %d argument%s "
				      "(%ld given)",
				      fname==NULL ? "function" : fname,
				      fname==NULL ? "" : "()",
				      min==max ? "exactly"
				      : len < min ? "at least" : "at most",
				      len < min ? min : max,
				      (len < min ? min : max) == 1 ? "" : "s",
				      Py_SAFE_DOWNCAST(len, Py_ssize_t, long));
			message = msgbuf;
		}
		PyErr_SetString(PyExc_TypeError, message);
		return 0;
	}

	for (i = 0; i < len; i++) {
		if (*format == '|')
			format++;
		msg = convertitem(PyTuple_GET_ITEM(args, i), &format, p_va,
				  flags, levels, msgbuf,
				  sizeof(msgbuf), &freelist);
		if (msg) {
			seterror(i+1, msg, levels, fname, message);
			return cleanreturn(0, freelist);
		}
	}

	if (*format != '\0' && !isalpha(Py_CHARMASK(*format)) &&
	    *format != '(' &&
	    *format != '|' && *format != ':' && *format != ';') {
		PyErr_Format(PyExc_SystemError,
			     "bad format string: %.200s", formatsave);
		return cleanreturn(0, freelist);
	}

	return cleanreturn(1, freelist);
}

static void
seterror(int iarg, const char *msg, int *levels, const char *fname,
         const char *message)
{
	char buf[512];
	int i;
	char *p = buf;

	if (PyErr_Occurred())
		return;
	else if (message == NULL) {
		if (fname != NULL) {
			PyOS_snprintf(p, sizeof(buf), "%.200s() ", fname);
			p += strlen(p);
		}
		if (iarg != 0) {
			PyOS_snprintf(p, sizeof(buf) - (p - buf),
				      "argument %d", iarg);
			i = 0;
			p += strlen(p);
			while (levels[i] > 0 && i < 32 && (int)(p-buf) < 220) {
				PyOS_snprintf(p, sizeof(buf) - (p - buf),
					      ", item %d", levels[i]-1);
				p += strlen(p);
				i++;
			}
		}
		else {
			PyOS_snprintf(p, sizeof(buf) - (p - buf), "argument");
			p += strlen(p);
		}
		PyOS_snprintf(p, sizeof(buf) - (p - buf), " %.256s", msg);
		message = buf;
	}
	PyErr_SetString(PyExc_TypeError, message);
}

/* Convert a tuple argument.
   On entry, *p_format points to the character _after_ the opening '('.
   On successful exit, *p_format points to the closing ')'.
   If successful:
      *p_format and *p_va are updated,
      *levels and *msgbuf are untouched,
      and NULL is returned.
   If the argument is invalid:
      *p_format is unchanged,
      *p_va is undefined,
      *levels is a 0-terminated list of item numbers,
      *msgbuf contains an error message, whose format is:
         "must be <typename1>, not <typename2>", where:
            <typename1> is the name of the expected type, and
            <typename2> is the name of the actual type,
      and msgbuf is returned.
*/

static char *
converttuple(PyObject *arg, const char **p_format, va_list *p_va, int flags,
             int *levels, char *msgbuf, size_t bufsize, int toplevel,
             PyObject **freelist)
{
	int level = 0;
	int n = 0;
	const char *format = *p_format;
	int i;

	for (;;) {
		int c = *format++;
		if (c == '(') {
			if (level == 0)
				n++;
			level++;
		}
		else if (c == ')') {
			if (level == 0)
				break;
			level--;
		}
		else if (c == ':' || c == ';' || c == '\0')
			break;
		else if (level == 0 && isalpha(Py_CHARMASK(c)))
			n++;
	}

	if (!PySequence_Check(arg) || PyString_Check(arg)) {
		levels[0] = 0;
		PyOS_snprintf(msgbuf, bufsize,
			      toplevel ? "expected %d arguments, not %.50s" :
			              "must be %d-item sequence, not %.50s",
			      n,
			      arg == Py_None ? "None" : arg->ob_type->tp_name);
		return msgbuf;
	}

	if ((i = PySequence_Size(arg)) != n) {
		levels[0] = 0;
		PyOS_snprintf(msgbuf, bufsize,
			      toplevel ? "expected %d arguments, not %d" :
			             "must be sequence of length %d, not %d",
			      n, i);
		return msgbuf;
	}

	format = *p_format;
	for (i = 0; i < n; i++) {
		char *msg;
		PyObject *item;
		item = PySequence_GetItem(arg, i);
		if (item == NULL) {
			PyErr_Clear();
			levels[0] = i+1;
			levels[1] = 0;
			strncpy(msgbuf, "is not retrievable", bufsize);
			return msgbuf;
		}
		msg = convertitem(item, &format, p_va, flags, levels+1,
				  msgbuf, bufsize, freelist);
		/* PySequence_GetItem calls tp->sq_item, which INCREFs */
		Py_XDECREF(item);
		if (msg != NULL) {
			levels[0] = i+1;
			return msg;
		}
	}

	*p_format = format;
	return NULL;
}

/* Convert a single item. */

static char *
convertitem(PyObject *arg, const char **p_format, va_list *p_va, int flags,
            int *levels, char *msgbuf, size_t bufsize, PyObject **freelist)
{
	char *msg;
	const char *format = *p_format;

	if (*format == '(' /* ')' */) {
		format++;
		msg = converttuple(arg, &format, p_va, flags, levels, msgbuf,
				   bufsize, 0, freelist);
		if (msg == NULL)
			format++;
	}
	else {
		msg = convertsimple(arg, &format, p_va, flags,
				    msgbuf, bufsize, freelist);
		if (msg != NULL)
			levels[0] = 0;
	}
	if (msg == NULL)
		*p_format = format;
	return msg;
}

#define UNICODE_DEFAULT_ENCODING(arg) \
        _PyUnicode_AsDefaultEncodedString(arg, NULL)

/* Format an error message generated by convertsimple(). */

static char *
converterr(const char *expected, PyObject *arg, char *msgbuf, size_t bufsize)
{
	assert(expected != NULL);
	assert(arg != NULL);
	PyOS_snprintf(msgbuf, bufsize,
		      "must be %.50s, not %.50s", expected,
		      arg == Py_None ? "None" : arg->ob_type->tp_name);
	return msgbuf;
}

#define CONV_UNICODE "(unicode conversion error)"

/* explicitly check for float arguments when integers are expected.  For now
 * signal a warning.  Returns true if an exception was raised. */
static int
float_argument_error(PyObject *arg)
{
	if (PyFloat_Check(arg) &&
	    PyErr_Warn(PyExc_DeprecationWarning,
		       "integer argument expected, got float" ))
		return 1;
	else
		return 0;
}

/* Convert a non-tuple argument.  Return NULL if conversion went OK,
   or a string with a message describing the failure.  The message is
   formatted as "must be <desired type>, not <actual type>".
   When failing, an exception may or may not have been raised.
   Don't call if a tuple is expected.

   When you add new format codes, please don't forget poor skipitem() below.
*/

static char *
convertsimple(PyObject *arg, const char **p_format, va_list *p_va, int flags,
              char *msgbuf, size_t bufsize, PyObject **freelist)
{
	/* For # codes */
#define FETCH_SIZE	int *q=NULL;Py_ssize_t *q2=NULL;\
	if (flags & FLAG_SIZE_T) q2=va_arg(*p_va, Py_ssize_t*); \
	else q=va_arg(*p_va, int*);
#define STORE_SIZE(s)   if (flags & FLAG_SIZE_T) *q2=s; else *q=s;
#define BUFFER_LEN      ((flags & FLAG_SIZE_T) ? *q2:*q)

	const char *format = *p_format;
	char c = *format++;
#ifdef Py_USING_UNICODE
	PyObject *uarg;
#endif

	switch (c) {

	case 'b': { /* unsigned byte -- very short int */
		char *p = va_arg(*p_va, char *);
		long ival;
		if (float_argument_error(arg))
			return converterr("integer<b>", arg, msgbuf, bufsize);
		ival = PyInt_AsLong(arg);
		if (ival == -1 && PyErr_Occurred())
			return converterr("integer<b>", arg, msgbuf, bufsize);
		else if (ival < 0) {
			PyErr_SetString(PyExc_OverflowError,
			"unsigned byte integer is less than minimum");
			return converterr("integer<b>", arg, msgbuf, bufsize);
		}
		else if (ival > UCHAR_MAX) {
			PyErr_SetString(PyExc_OverflowError,
			"unsigned byte integer is greater than maximum");
			return converterr("integer<b>", arg, msgbuf, bufsize);
		}
		else
			*p = (unsigned char) ival;
		break;
	}

	case 'B': {/* byte sized bitfield - both signed and unsigned
		      values allowed */
		char *p = va_arg(*p_va, char *);
		long ival;
		if (float_argument_error(arg))
			return converterr("integer<B>", arg, msgbuf, bufsize);
		ival = PyInt_AsUnsignedLongMask(arg);
		if (ival == -1 && PyErr_Occurred())
			return converterr("integer<B>", arg, msgbuf, bufsize);
		else
			*p = (unsigned char) ival;
		break;
	}

	case 'h': {/* signed short int */
		short *p = va_arg(*p_va, short *);
		long ival;
		if (float_argument_error(arg))
			return converterr("integer<h>", arg, msgbuf, bufsize);
		ival = PyInt_AsLong(arg);
		if (ival == -1 && PyErr_Occurred())
			return converterr("integer<h>", arg, msgbuf, bufsize);
		else if (ival < SHRT_MIN) {
			PyErr_SetString(PyExc_OverflowError,
			"signed short integer is less than minimum");
			return converterr("integer<h>", arg, msgbuf, bufsize);
		}
		else if (ival > SHRT_MAX) {
			PyErr_SetString(PyExc_OverflowError,
			"signed short integer is greater than maximum");
			return converterr("integer<h>", arg, msgbuf, bufsize);
		}
		else
			*p = (short) ival;
		break;
	}

	case 'H': { /* short int sized bitfield, both signed and
		       unsigned allowed */
		unsigned short *p = va_arg(*p_va, unsigned short *);
		long ival;
		if (float_argument_error(arg))
			return converterr("integer<H>", arg, msgbuf, bufsize);
		ival = PyInt_AsUnsignedLongMask(arg);
		if (ival == -1 && PyErr_Occurred())
			return converterr("integer<H>", arg, msgbuf, bufsize);
		else
			*p = (unsigned short) ival;
		break;
	}

	case 'i': {/* signed int */
		int *p = va_arg(*p_va, int *);
		long ival;
		if (float_argument_error(arg))
			return converterr("integer<i>", arg, msgbuf, bufsize);
		ival = PyInt_AsLong(arg);
		if (ival == -1 && PyErr_Occurred())
			return converterr("integer<i>", arg, msgbuf, bufsize);
		else if (ival > INT_MAX) {
			PyErr_SetString(PyExc_OverflowError,
				"signed integer is greater than maximum");
			return converterr("integer<i>", arg, msgbuf, bufsize);
		}
		else if (ival < INT_MIN) {
			PyErr_SetString(PyExc_OverflowError,
				"signed integer is less than minimum");
			return converterr("integer<i>", arg, msgbuf, bufsize);
		}
		else
			*p = ival;
		break;
	}

	case 'I': { /* int sized bitfield, both signed and
		       unsigned allowed */
		unsigned int *p = va_arg(*p_va, unsigned int *);
		unsigned int ival;
		if (float_argument_error(arg))
			return converterr("integer<I>", arg, msgbuf, bufsize);
		ival = (unsigned int)PyInt_AsUnsignedLongMask(arg);
		if (ival == (unsigned int)-1 && PyErr_Occurred())
			return converterr("integer<I>", arg, msgbuf, bufsize);
		else
			*p = ival;
		break;
	}

	case 'n': /* Py_ssize_t */
#if SIZEOF_SIZE_T != SIZEOF_LONG
	{
		Py_ssize_t *p = va_arg(*p_va, Py_ssize_t *);
		Py_ssize_t ival;
		if (float_argument_error(arg))
			return converterr("integer<n>", arg, msgbuf, bufsize);
		ival = PyInt_AsSsize_t(arg);
		if (ival == -1 && PyErr_Occurred())
			return converterr("integer<n>", arg, msgbuf, bufsize);
		*p = ival;
		break;
	}
#endif
	/* Fall through from 'n' to 'l' if Py_ssize_t is int */
	case 'l': {/* long int */
		long *p = va_arg(*p_va, long *);
		long ival;
		if (float_argument_error(arg))
			return converterr("integer<l>", arg, msgbuf, bufsize);
		ival = PyInt_AsLong(arg);
		if (ival == -1 && PyErr_Occurred())
			return converterr("integer<l>", arg, msgbuf, bufsize);
		else
			*p = ival;
		break;
	}

	case 'k': { /* long sized bitfield */
		unsigned long *p = va_arg(*p_va, unsigned long *);
		unsigned long ival;
		if (PyInt_Check(arg))
			ival = PyInt_AsUnsignedLongMask(arg);
		else if (PyLong_Check(arg))
			ival = PyLong_AsUnsignedLongMask(arg);
		else
			return converterr("integer<k>", arg, msgbuf, bufsize);
		*p = ival;
		break;
	}

#ifdef HAVE_LONG_LONG
	case 'L': {/* PY_LONG_LONG */
		PY_LONG_LONG *p = va_arg( *p_va, PY_LONG_LONG * );
		PY_LONG_LONG ival = PyLong_AsLongLong( arg );
		if (ival == (PY_LONG_LONG)-1 && PyErr_Occurred() ) {
			return converterr("long<L>", arg, msgbuf, bufsize);
		} else {
			*p = ival;
		}
		break;
	}

	case 'K': { /* long long sized bitfield */
		unsigned PY_LONG_LONG *p = va_arg(*p_va, unsigned PY_LONG_LONG *);
		unsigned PY_LONG_LONG ival;
		if (PyInt_Check(arg))
			ival = PyInt_AsUnsignedLongMask(arg);
		else if (PyLong_Check(arg))
			ival = PyLong_AsUnsignedLongLongMask(arg);
		else
			return converterr("integer<K>", arg, msgbuf, bufsize);
		*p = ival;
		break;
	}
#endif

	case 'f': {/* float */
		float *p = va_arg(*p_va, float *);
		double dval = PyFloat_AsDouble(arg);
		if (PyErr_Occurred())
			return converterr("float<f>", arg, msgbuf, bufsize);
		else
			*p = (float) dval;
		break;
	}

	case 'd': {/* double */
		double *p = va_arg(*p_va, double *);
		double dval = PyFloat_AsDouble(arg);
		if (PyErr_Occurred())
			return converterr("float<d>", arg, msgbuf, bufsize);
		else
			*p = dval;
		break;
	}

#ifndef WITHOUT_COMPLEX
	case 'D': {/* complex double */
		Py_complex *p = va_arg(*p_va, Py_complex *);
		Py_complex cval;
		cval = PyComplex_AsCComplex(arg);
		if (PyErr_Occurred())
			return converterr("complex<D>", arg, msgbuf, bufsize);
		else
			*p = cval;
		break;
	}
#endif /* WITHOUT_COMPLEX */

	case 'c': {/* char */
		char *p = va_arg(*p_va, char *);
		if (PyString_Check(arg) && PyString_Size(arg) == 1)
			*p = PyString_AS_STRING(arg)[0];
		else
			return converterr("char", arg, msgbuf, bufsize);
		break;
	}

	case 's': {/* string */
		if (*format == '*') {
			Py_buffer *p = (Py_buffer *)va_arg(*p_va, Py_buffer *);

			if (PyString_Check(arg)) {
				PyBuffer_FillInfo(p, arg,
						  PyString_AS_STRING(arg), PyString_GET_SIZE(arg),
						  1, 0);
			}
#ifdef Py_USING_UNICODE
			else if (PyUnicode_Check(arg)) {
				uarg = UNICODE_DEFAULT_ENCODING(arg);
				if (uarg == NULL)
					return converterr(CONV_UNICODE,
							  arg, msgbuf, bufsize);
				PyBuffer_FillInfo(p, arg,
						  PyString_AS_STRING(uarg), PyString_GET_SIZE(uarg),
						  1, 0);
			}
#endif
			else { /* any buffer-like object */
				char *buf;
				if (getbuffer(arg, p, &buf) < 0)
					return converterr(buf, arg, msgbuf, bufsize);
			}
			if (addcleanup(p, freelist, cleanup_buffer)) {
				return converterr(
					"(cleanup problem)",
					arg, msgbuf, bufsize);
			}
			format++;
		} else if (*format == '#') {
			void **p = (void **)va_arg(*p_va, char **);
			FETCH_SIZE;

			if (PyString_Check(arg)) {
				*p = PyString_AS_STRING(arg);
				STORE_SIZE(PyString_GET_SIZE(arg));
			}
#ifdef Py_USING_UNICODE
			else if (PyUnicode_Check(arg)) {
				uarg = UNICODE_DEFAULT_ENCODING(arg);
				if (uarg == NULL)
					return converterr(CONV_UNICODE,
							  arg, msgbuf, bufsize);
				*p = PyString_AS_STRING(uarg);
				STORE_SIZE(PyString_GET_SIZE(uarg));
			}
#endif
			else { /* any buffer-like object */
				char *buf;
				Py_ssize_t count = convertbuffer(arg, p, &buf);
				if (count < 0)
					return converterr(buf, arg, msgbuf, bufsize);
				STORE_SIZE(count);
			}
			format++;
		} else {
			char **p = va_arg(*p_va, char **);

			if (PyString_Check(arg))
				*p = PyString_AS_STRING(arg);
#ifdef Py_USING_UNICODE
			else if (PyUnicode_Check(arg)) {
				uarg = UNICODE_DEFAULT_ENCODING(arg);
				if (uarg == NULL)
					return converterr(CONV_UNICODE,
							  arg, msgbuf, bufsize);
				*p = PyString_AS_STRING(uarg);
			}
#endif
			else
				return converterr("string", arg, msgbuf, bufsize);
			if ((Py_ssize_t)strlen(*p) != PyString_Size(arg))
				return converterr("string without null bytes",
						  arg, msgbuf, bufsize);
		}
		break;
	}

	case 'z': {/* string, may be NULL (None) */
		if (*format == '*') {
			Py_buffer *p = (Py_buffer *)va_arg(*p_va, Py_buffer *);

			if (arg == Py_None)
				PyBuffer_FillInfo(p, NULL, NULL, 0, 1, 0);
			else if (PyString_Check(arg)) {
				PyBuffer_FillInfo(p, arg,
						  PyString_AS_STRING(arg), PyString_GET_SIZE(arg),
						  1, 0);
			}
#ifdef Py_USING_UNICODE
			else if (PyUnicode_Check(arg)) {
				uarg = UNICODE_DEFAULT_ENCODING(arg);
				if (uarg == NULL)
					return converterr(CONV_UNICODE,
							  arg, msgbuf, bufsize);
				PyBuffer_FillInfo(p, arg,
						  PyString_AS_STRING(uarg), PyString_GET_SIZE(uarg),
						  1, 0);
			}
#endif
			else { /* any buffer-like object */
				char *buf;
				if (getbuffer(arg, p, &buf) < 0)
					return converterr(buf, arg, msgbuf, bufsize);
			}
			if (addcleanup(p, freelist, cleanup_buffer)) {
				return converterr(
					"(cleanup problem)",
					arg, msgbuf, bufsize);
			}
			format++;
		} else if (*format == '#') { /* any buffer-like object */
			void **p = (void **)va_arg(*p_va, char **);
			FETCH_SIZE;

			if (arg == Py_None) {
				*p = 0;
				STORE_SIZE(0);
			}
			else if (PyString_Check(arg)) {
				*p = PyString_AS_STRING(arg);
				STORE_SIZE(PyString_GET_SIZE(arg));
			}
#ifdef Py_USING_UNICODE
			else if (PyUnicode_Check(arg)) {
				uarg = UNICODE_DEFAULT_ENCODING(arg);
				if (uarg == NULL)
					return converterr(CONV_UNICODE,
							  arg, msgbuf, bufsize);
				*p = PyString_AS_STRING(uarg);
				STORE_SIZE(PyString_GET_SIZE(uarg));
			}
#endif
			else { /* any buffer-like object */
				char *buf;
				Py_ssize_t count = convertbuffer(arg, p, &buf);
				if (count < 0)
					return converterr(buf, arg, msgbuf, bufsize);
				STORE_SIZE(count);
			}
			format++;
		} else {
			char **p = va_arg(*p_va, char **);

			if (arg == Py_None)
				*p = 0;
			else if (PyString_Check(arg))
				*p = PyString_AS_STRING(arg);
#ifdef Py_USING_UNICODE
			else if (PyUnicode_Check(arg)) {
				uarg = UNICODE_DEFAULT_ENCODING(arg);
				if (uarg == NULL)
					return converterr(CONV_UNICODE,
							  arg, msgbuf, bufsize);
				*p = PyString_AS_STRING(uarg);
			}
#endif
			else
				return converterr("string or None",
						  arg, msgbuf, bufsize);
			if (*format == '#') {
				FETCH_SIZE;
				assert(0); /* XXX redundant with if-case */
				if (arg == Py_None)
					*q = 0;
				else
					*q = PyString_Size(arg);
				format++;
			}
			else if (*p != NULL &&
				 (Py_ssize_t)strlen(*p) != PyString_Size(arg))
				return converterr(
					"string without null bytes or None",
					arg, msgbuf, bufsize);
		}
		break;
	}

	case 'e': {/* encoded string */
		char **buffer;
		const char *encoding;
		PyObject *s;
		Py_ssize_t size;
		int recode_strings;

		/* Get 'e' parameter: the encoding name */
		encoding = (const char *)va_arg(*p_va, const char *);
#ifdef Py_USING_UNICODE
		if (encoding == NULL)
			encoding = PyUnicode_GetDefaultEncoding();
#endif

		/* Get output buffer parameter:
		   's' (recode all objects via Unicode) or
		   't' (only recode non-string objects)
		*/
		if (*format == 's')
			recode_strings = 1;
		else if (*format == 't')
			recode_strings = 0;
		else
			return converterr(
				"(unknown parser marker combination)",
				arg, msgbuf, bufsize);
		buffer = (char **)va_arg(*p_va, char **);
		format++;
		if (buffer == NULL)
			return converterr("(buffer is NULL)",
					  arg, msgbuf, bufsize);

		/* Encode object */
		if (!recode_strings && PyString_Check(arg)) {
			s = arg;
			Py_INCREF(s);
		}
		else {
#ifdef Py_USING_UNICODE
		    	PyObject *u;

			/* Convert object to Unicode */
			u = PyUnicode_FromObject(arg);
			if (u == NULL)
				return converterr(
					"string or unicode or text buffer",
					arg, msgbuf, bufsize);

			/* Encode object; use default error handling */
			s = PyUnicode_AsEncodedString(u,
						      encoding,
						      NULL);
			Py_DECREF(u);
			if (s == NULL)
				return converterr("(encoding failed)",
						  arg, msgbuf, bufsize);
			if (!PyString_Check(s)) {
				Py_DECREF(s);
				return converterr(
					"(encoder failed to return a string)",
					arg, msgbuf, bufsize);
			}
#else
			return converterr("string<e>", arg, msgbuf, bufsize);
#endif
		}
		size = PyString_GET_SIZE(s);

		/* Write output; output is guaranteed to be 0-terminated */
		if (*format == '#') {
			/* Using buffer length parameter '#':

			   - if *buffer is NULL, a new buffer of the
			   needed size is allocated and the data
			   copied into it; *buffer is updated to point
			   to the new buffer; the caller is
			   responsible for PyMem_Free()ing it after
			   usage

			   - if *buffer is not NULL, the data is
			   copied to *buffer; *buffer_len has to be
			   set to the size of the buffer on input;
			   buffer overflow is signalled with an error;
			   buffer has to provide enough room for the
			   encoded string plus the trailing 0-byte

			   - in both cases, *buffer_len is updated to
			   the size of the buffer /excluding/ the
			   trailing 0-byte

			*/
			FETCH_SIZE;

			format++;
			if (q == NULL && q2 == NULL) {
				Py_DECREF(s);
				return converterr(
					"(buffer_len is NULL)",
					arg, msgbuf, bufsize);
			}
			if (*buffer == NULL) {
				*buffer = PyMem_NEW(char, size + 1);
				if (*buffer == NULL) {
					Py_DECREF(s);
					return converterr(
						"(memory error)",
						arg, msgbuf, bufsize);
				}
				if (addcleanup(*buffer, freelist, cleanup_ptr)) {
					Py_DECREF(s);
					return converterr(
						"(cleanup problem)",
						arg, msgbuf, bufsize);
				}
			} else {
				if (size + 1 > BUFFER_LEN) {
					Py_DECREF(s);
					return converterr(
						"(buffer overflow)",
						arg, msgbuf, bufsize);
				}
			}
			memcpy(*buffer,
			       PyString_AS_STRING(s),
			       size + 1);
			STORE_SIZE(size);
		} else {
			/* Using a 0-terminated buffer:

			   - the encoded string has to be 0-terminated
			   for this variant to work; if it is not, an
			   error raised

			   - a new buffer of the needed size is
			   allocated and the data copied into it;
			   *buffer is updated to point to the new
			   buffer; the caller is responsible for
			   PyMem_Free()ing it after usage

			*/
			if ((Py_ssize_t)strlen(PyString_AS_STRING(s))
								!= size) {
				Py_DECREF(s);
				return converterr(
					"encoded string without NULL bytes",
					arg, msgbuf, bufsize);
			}
			*buffer = PyMem_NEW(char, size + 1);
			if (*buffer == NULL) {
				Py_DECREF(s);
				return converterr("(memory error)",
						  arg, msgbuf, bufsize);
			}
			if (addcleanup(*buffer, freelist, cleanup_ptr)) {
				Py_DECREF(s);
				return converterr("(cleanup problem)",
						arg, msgbuf, bufsize);
			}
			memcpy(*buffer,
			       PyString_AS_STRING(s),
			       size + 1);
		}
		Py_DECREF(s);
		break;
	}

#ifdef Py_USING_UNICODE
	case 'u': {/* raw unicode buffer (Py_UNICODE *) */
		if (*format == '#') { /* any buffer-like object */
			void **p = (void **)va_arg(*p_va, char **);
			FETCH_SIZE;
			if (PyUnicode_Check(arg)) {
			    	*p = PyUnicode_AS_UNICODE(arg);
				STORE_SIZE(PyUnicode_GET_SIZE(arg));
			}
			else {
				return converterr("cannot convert raw buffers",
						  arg, msgbuf, bufsize);
			}
			format++;
		} else {
			Py_UNICODE **p = va_arg(*p_va, Py_UNICODE **);
			if (PyUnicode_Check(arg))
				*p = PyUnicode_AS_UNICODE(arg);
			else
				return converterr("unicode", arg, msgbuf, bufsize);
		}
		break;
	}
#endif

	case 'S': { /* string object */
		PyObject **p = va_arg(*p_va, PyObject **);
		if (PyString_Check(arg))
			*p = arg;
		else
			return converterr("string", arg, msgbuf, bufsize);
		break;
	}

#ifdef Py_USING_UNICODE
	case 'U': { /* Unicode object */
		PyObject **p = va_arg(*p_va, PyObject **);
		if (PyUnicode_Check(arg))
			*p = arg;
		else
			return converterr("unicode", arg, msgbuf, bufsize);
		break;
	}
#endif

	case 'O': { /* object */
		PyTypeObject *type;
		PyObject **p;
		if (*format == '!') {
			type = va_arg(*p_va, PyTypeObject*);
			p = va_arg(*p_va, PyObject **);
			format++;
			if (PyType_IsSubtype(arg->ob_type, type))
				*p = arg;
			else
				return converterr(type->tp_name, arg, msgbuf, bufsize);

		}
		else if (*format == '?') {
			inquiry pred = va_arg(*p_va, inquiry);
			p = va_arg(*p_va, PyObject **);
			format++;
			if ((*pred)(arg))
				*p = arg;
			else
				return converterr("(unspecified)",
						  arg, msgbuf, bufsize);

		}
		else if (*format == '&') {
			typedef int (*converter)(PyObject *, void *);
			converter convert = va_arg(*p_va, converter);
			void *addr = va_arg(*p_va, void *);
			format++;
			if (! (*convert)(arg, addr))
				return converterr("(unspecified)",
						  arg, msgbuf, bufsize);
		}
		else {
			p = va_arg(*p_va, PyObject **);
			*p = arg;
		}
		break;
	}

	case 'w': { /* memory buffer, read-write access */
		void **p = va_arg(*p_va, void **);
		void *res;
		PyBufferProcs *pb = arg->ob_type->tp_as_buffer;
		Py_ssize_t count;

		if (pb && pb->bf_releasebuffer && *format != '*')
			/* Buffer must be released, yet caller does not use
			   the Py_buffer protocol. */
			return converterr("pinned buffer", arg, msgbuf, bufsize);

		if (pb && pb->bf_getbuffer && *format == '*') {
			/* Caller is interested in Py_buffer, and the object
			   supports it directly. */
			format++;
			if (pb->bf_getbuffer(arg, (Py_buffer*)p, PyBUF_WRITABLE) < 0) {
				PyErr_Clear();
				return converterr("read-write buffer", arg, msgbuf, bufsize);
			}
			if (addcleanup(p, freelist, cleanup_buffer)) {
				return converterr(
					"(cleanup problem)",
					arg, msgbuf, bufsize);
			}
			if (!PyBuffer_IsContiguous((Py_buffer*)p, 'C'))
				return converterr("contiguous buffer", arg, msgbuf, bufsize);
			break;
		}

		if (pb == NULL ||
		    pb->bf_getwritebuffer == NULL ||
		    pb->bf_getsegcount == NULL)
			return converterr("read-write buffer", arg, msgbuf, bufsize);
		if ((*pb->bf_getsegcount)(arg, NULL) != 1)
			return converterr("single-segment read-write buffer",
					  arg, msgbuf, bufsize);
		if ((count = pb->bf_getwritebuffer(arg, 0, &res)) < 0)
			return converterr("(unspecified)", arg, msgbuf, bufsize);
		if (*format == '*') {
			PyBuffer_FillInfo((Py_buffer*)p, arg, res, count, 1, 0);
			format++;
		}
		else {
			*p = res;
			if (*format == '#') {
				FETCH_SIZE;
				STORE_SIZE(count);
				format++;
			}
		}
		break;
	}

	case 't': { /* 8-bit character buffer, read-only access */
		char **p = va_arg(*p_va, char **);
		PyBufferProcs *pb = arg->ob_type->tp_as_buffer;
		Py_ssize_t count;

		if (*format++ != '#')
			return converterr(
				"invalid use of 't' format character",
				arg, msgbuf, bufsize);
		if (!PyType_HasFeature(arg->ob_type,
				       Py_TPFLAGS_HAVE_GETCHARBUFFER) ||
		    pb == NULL || pb->bf_getcharbuffer == NULL ||
		    pb->bf_getsegcount == NULL)
			return converterr(
				"string or read-only character buffer",
				arg, msgbuf, bufsize);

		if (pb->bf_getsegcount(arg, NULL) != 1)
			return converterr(
				"string or single-segment read-only buffer",
				arg, msgbuf, bufsize);

		if (pb->bf_releasebuffer)
			return converterr(
				"string or pinned buffer",
				arg, msgbuf, bufsize);

		count = pb->bf_getcharbuffer(arg, 0, p);
		if (count < 0)
			return converterr("(unspecified)", arg, msgbuf, bufsize);
		{
			FETCH_SIZE;
			STORE_SIZE(count);
		}
		break;
	}

	default:
		return converterr("impossible<bad format char>", arg, msgbuf, bufsize);

	}

	*p_format = format;
	return NULL;
}

static Py_ssize_t
convertbuffer(PyObject *arg, void **p, char **errmsg)
{
	PyBufferProcs *pb = arg->ob_type->tp_as_buffer;
	Py_ssize_t count;
	if (pb == NULL ||
	    pb->bf_getreadbuffer == NULL ||
	    pb->bf_getsegcount == NULL ||
	    pb->bf_releasebuffer != NULL) {
		*errmsg = "string or read-only buffer";
		return -1;
	}
	if ((*pb->bf_getsegcount)(arg, NULL) != 1) {
		*errmsg = "string or single-segment read-only buffer";
		return -1;
	}
	if ((count = (*pb->bf_getreadbuffer)(arg, 0, p)) < 0) {
		*errmsg = "(unspecified)";
	}
	return count;
}

static int
getbuffer(PyObject *arg, Py_buffer *view, char **errmsg)
{
	void *buf;
	Py_ssize_t count;
	PyBufferProcs *pb = arg->ob_type->tp_as_buffer;
	if (pb == NULL) {
		*errmsg = "string or buffer";
		return -1;
	}
	if (pb->bf_getbuffer) {
		if (pb->bf_getbuffer(arg, view, 0) < 0) {
			*errmsg = "convertible to a buffer";
			return -1;
		}
		if (!PyBuffer_IsContiguous(view, 'C')) {
			*errmsg = "contiguous buffer";
			return -1;
		}
		return 0;
	}

	count = convertbuffer(arg, &buf, errmsg);
	if (count < 0) {
		*errmsg = "convertible to a buffer";
		return count;
	}
	PyBuffer_FillInfo(view, NULL, buf, count, 1, 0);
	return 0;
}

/* Support for keyword arguments donated by
   Geoff Philbrick <philbric@delphi.hks.com> */

/* Return false (0) for error, else true. */
int
PyArg_ParseTupleAndKeywords(PyObject *args,
			    PyObject *keywords,
			    const char *format,
			    char **kwlist, ...)
{
	int retval;
	va_list va;

	if ((args == NULL || !PyTuple_Check(args)) ||
	    (keywords != NULL && !PyDict_Check(keywords)) ||
	    format == NULL ||
	    kwlist == NULL)
	{
		PyErr_BadInternalCall();
		return 0;
	}

	va_start(va, kwlist);
	retval = vgetargskeywords(args, keywords, format, kwlist, &va, 0);
	va_end(va);
	return retval;
}

int
_PyArg_ParseTupleAndKeywords_SizeT(PyObject *args,
				  PyObject *keywords,
				  const char *format,
				  char **kwlist, ...)
{
	int retval;
	va_list va;

	if ((args == NULL || !PyTuple_Check(args)) ||
	    (keywords != NULL && !PyDict_Check(keywords)) ||
	    format == NULL ||
	    kwlist == NULL)
	{
		PyErr_BadInternalCall();
		return 0;
	}

	va_start(va, kwlist);
	retval = vgetargskeywords(args, keywords, format,
				  kwlist, &va, FLAG_SIZE_T);
	va_end(va);
	return retval;
}

int
PyArg_VaParseTupleAndKeywords(PyObject *args,
                              PyObject *keywords,
                              const char *format,
                              char **kwlist, va_list va)
{
	int retval;
	va_list lva;

	if ((args == NULL || !PyTuple_Check(args)) ||
	    (keywords != NULL && !PyDict_Check(keywords)) ||
	    format == NULL ||
	    kwlist == NULL)
	{
		PyErr_BadInternalCall();
		return 0;
	}

#ifdef VA_LIST_IS_ARRAY
	memcpy(lva, va, sizeof(va_list));
#else
#ifdef __va_copy
	__va_copy(lva, va);
#else
	lva = va;
#endif
#endif

	retval = vgetargskeywords(args, keywords, format, kwlist, &lva, 0);
	return retval;
}

int
_PyArg_VaParseTupleAndKeywords_SizeT(PyObject *args,
				    PyObject *keywords,
				    const char *format,
				    char **kwlist, va_list va)
{
	int retval;
	va_list lva;

	if ((args == NULL || !PyTuple_Check(args)) ||
	    (keywords != NULL && !PyDict_Check(keywords)) ||
	    format == NULL ||
	    kwlist == NULL)
	{
		PyErr_BadInternalCall();
		return 0;
	}

#ifdef VA_LIST_IS_ARRAY
	memcpy(lva, va, sizeof(va_list));
#else
#ifdef __va_copy
	__va_copy(lva, va);
#else
	lva = va;
#endif
#endif

	retval = vgetargskeywords(args, keywords, format,
				  kwlist, &lva, FLAG_SIZE_T);
	return retval;
}

#define IS_END_OF_FORMAT(c) (c == '\0' || c == ';' || c == ':')

static int
vgetargskeywords(PyObject *args, PyObject *keywords, const char *format,
	         char **kwlist, va_list *p_va, int flags)
{
	char msgbuf[512];
	int levels[32];
	const char *fname, *msg, *custom_msg, *keyword;
	int min = INT_MAX;
	int i, len, nargs, nkeywords;
	PyObject *freelist = NULL, *current_arg;

	assert(args != NULL && PyTuple_Check(args));
	assert(keywords == NULL || PyDict_Check(keywords));
	assert(format != NULL);
	assert(kwlist != NULL);
	assert(p_va != NULL);

	/* grab the function name or custom error msg first (mutually exclusive) */
	fname = strchr(format, ':');
	if (fname) {
		fname++;
		custom_msg = NULL;
	}
	else {
		custom_msg = strchr(format,';');
		if (custom_msg)
			custom_msg++;
	}

	/* scan kwlist and get greatest possible nbr of args */
	for (len=0; kwlist[len]; len++)
		continue;

	nargs = PyTuple_GET_SIZE(args);
	nkeywords = (keywords == NULL) ? 0 : PyDict_Size(keywords);
	if (nargs + nkeywords > len) {
		PyErr_Format(PyExc_TypeError, "%s%s takes at most %d "
			     "argument%s (%d given)",
			     (fname == NULL) ? "function" : fname,
			     (fname == NULL) ? "" : "()",
			     len,
			     (len == 1) ? "" : "s",
			     nargs + nkeywords);
		return 0;
	}

	/* convert tuple args and keyword args in same loop, using kwlist to drive process */
	for (i = 0; i < len; i++) {
		keyword = kwlist[i];
		if (*format == '|') {
			min = i;
			format++;
		}
		if (IS_END_OF_FORMAT(*format)) {
			PyErr_Format(PyExc_RuntimeError,
				     "More keyword list entries (%d) than "
				     "format specifiers (%d)", len, i);
			return cleanreturn(0, freelist);
		}
		current_arg = NULL;
		if (nkeywords) {
			current_arg = PyDict_GetItemString(keywords, keyword);
		}
		if (current_arg) {
			--nkeywords;
			if (i < nargs) {
				/* arg present in tuple and in dict */
				PyErr_Format(PyExc_TypeError,
					     "Argument given by name ('%s') "
					     "and position (%d)",
					     keyword, i+1);
				return cleanreturn(0, freelist);
			}
		}
		else if (nkeywords && PyErr_Occurred())
			return cleanreturn(0, freelist);
		else if (i < nargs)
			current_arg = PyTuple_GET_ITEM(args, i);

		if (current_arg) {
			msg = convertitem(current_arg, &format, p_va, flags,
				levels, msgbuf, sizeof(msgbuf), &freelist);
			if (msg) {
				seterror(i+1, msg, levels, fname, custom_msg);
				return cleanreturn(0, freelist);
			}
			continue;
		}

		if (i < min) {
			PyErr_Format(PyExc_TypeError, "Required argument "
				     "'%s' (pos %d) not found",
				     keyword, i+1);
			return cleanreturn(0, freelist);
		}
		/* current code reports success when all required args
		 * fulfilled and no keyword args left, with no further
		 * validation. XXX Maybe skip this in debug build ?
		 */
		if (!nkeywords)
			return cleanreturn(1, freelist);

		/* We are into optional args, skip thru to any remaining
		 * keyword args */
		msg = skipitem(&format, p_va, flags);
		if (msg) {
			PyErr_Format(PyExc_RuntimeError, "%s: '%s'", msg,
				     format);
			return cleanreturn(0, freelist);
		}
	}

	if (!IS_END_OF_FORMAT(*format) && *format != '|') {
		PyErr_Format(PyExc_RuntimeError,
			"more argument specifiers than keyword list entries "
			"(remaining format:'%s')", format);
		return cleanreturn(0, freelist);
	}

	/* make sure there are no extraneous keyword arguments */
	if (nkeywords > 0) {
		PyObject *key, *value;
		Py_ssize_t pos = 0;
		while (PyDict_Next(keywords, &pos, &key, &value)) {
			int match = 0;
			char *ks;
			if (!PyString_Check(key)) {
				PyErr_SetString(PyExc_TypeError,
					        "keywords must be strings");
				return cleanreturn(0, freelist);
			}
			ks = PyString_AsString(key);
			for (i = 0; i < len; i++) {
				if (!strcmp(ks, kwlist[i])) {
					match = 1;
					break;
				}
			}
			if (!match) {
				PyErr_Format(PyExc_TypeError,
					     "'%s' is an invalid keyword "
					     "argument for this function",
					     ks);
				return cleanreturn(0, freelist);
			}
		}
	}

	return cleanreturn(1, freelist);
}

static char *
skipitem(const char **p_format, va_list *p_va, int flags)
{
	const char *format = *p_format;
	char c = *format++;

	switch (c) {

	/* simple codes
	 * The individual types (second arg of va_arg) are irrelevant */

	case 'b': /* byte -- very short int */
	case 'B': /* byte as bitfield */
	case 'h': /* short int */
	case 'H': /* short int as bitfield */
	case 'i': /* int */
	case 'I': /* int sized bitfield */
	case 'l': /* long int */
	case 'k': /* long int sized bitfield */
#ifdef HAVE_LONG_LONG
	case 'L': /* PY_LONG_LONG */
	case 'K': /* PY_LONG_LONG sized bitfield */
#endif
	case 'f': /* float */
	case 'd': /* double */
#ifndef WITHOUT_COMPLEX
	case 'D': /* complex double */
#endif
	case 'c': /* char */
		{
			(void) va_arg(*p_va, void *);
			break;
		}

	case 'n': /* Py_ssize_t */
		{
			(void) va_arg(*p_va, Py_ssize_t *);
			break;
		}

	/* string codes */

	case 'e': /* string with encoding */
		{
			(void) va_arg(*p_va, const char *);
			if (!(*format == 's' || *format == 't'))
				/* after 'e', only 's' and 't' is allowed */
				goto err;
			format++;
			/* explicit fallthrough to string cases */
		}

	case 's': /* string */
	case 'z': /* string or None */
#ifdef Py_USING_UNICODE
	case 'u': /* unicode string */
#endif
	case 't': /* buffer, read-only */
	case 'w': /* buffer, read-write */
		{
			(void) va_arg(*p_va, char **);
			if (*format == '#') {
				if (flags & FLAG_SIZE_T)
					(void) va_arg(*p_va, Py_ssize_t *);
				else
					(void) va_arg(*p_va, int *);
				format++;
			} else if ((c == 's' || c == 'z') && *format == '*') {
				format++;
			}
			break;
		}

	/* object codes */

	case 'S': /* string object */
#ifdef Py_USING_UNICODE
	case 'U': /* unicode string object */
#endif
		{
			(void) va_arg(*p_va, PyObject **);
			break;
		}

	case 'O': /* object */
		{
			if (*format == '!') {
				format++;
				(void) va_arg(*p_va, PyTypeObject*);
				(void) va_arg(*p_va, PyObject **);
			}
#if 0
/* I don't know what this is for */
			else if (*format == '?') {
				inquiry pred = va_arg(*p_va, inquiry);
				format++;
				if ((*pred)(arg)) {
					(void) va_arg(*p_va, PyObject **);
				}
			}
#endif
			else if (*format == '&') {
				typedef int (*converter)(PyObject *, void *);
				(void) va_arg(*p_va, converter);
				(void) va_arg(*p_va, void *);
				format++;
			}
			else {
				(void) va_arg(*p_va, PyObject **);
			}
			break;
		}

	case '(':	/* bypass tuple, not handled at all previously */
		{
			char *msg;
			for (;;) {
				if (*format==')')
					break;
				if (IS_END_OF_FORMAT(*format))
					return "Unmatched left paren in format "
					       "string";
				msg = skipitem(&format, p_va, flags);
				if (msg)
					return msg;
			}
			format++;
			break;
		}

	case ')':
		return "Unmatched right paren in format string";

	default:
err:
		return "impossible<bad format char>";

	}

	*p_format = format;
	return NULL;
}

int
PyArg_UnpackTuple(PyObject *args, const char *name, Py_ssize_t min, Py_ssize_t max, ...)
{
	Py_ssize_t i, l;
	PyObject **o;
	va_list vargs;

#ifdef HAVE_STDARG_PROTOTYPES
	va_start(vargs, max);
#else
	va_start(vargs);
#endif

	assert(min >= 0);
	assert(min <= max);
	if (!PyTuple_Check(args)) {
		PyErr_SetString(PyExc_SystemError,
		    "PyArg_UnpackTuple() argument list is not a tuple");
		return 0;
	}
	l = PyTuple_GET_SIZE(args);
	if (l < min) {
		if (name != NULL)
			PyErr_Format(
			    PyExc_TypeError,
			    "%s expected %s%zd arguments, got %zd",
			    name, (min == max ? "" : "at least "), min, l);
		else
			PyErr_Format(
			    PyExc_TypeError,
			    "unpacked tuple should have %s%zd elements,"
			    " but has %zd",
			    (min == max ? "" : "at least "), min, l);
		va_end(vargs);
		return 0;
	}
	if (l > max) {
		if (name != NULL)
			PyErr_Format(
			    PyExc_TypeError,
			    "%s expected %s%zd arguments, got %zd",
			    name, (min == max ? "" : "at most "), max, l);
		else
			PyErr_Format(
			    PyExc_TypeError,
			    "unpacked tuple should have %s%zd elements,"
			    " but has %zd",
			    (min == max ? "" : "at most "), max, l);
		va_end(vargs);
		return 0;
	}
	for (i = 0; i < l; i++) {
		o = va_arg(vargs, PyObject **);
		*o = PyTuple_GET_ITEM(args, i);
	}
	va_end(vargs);
	return 1;
}

/* For type constructors that don't take keyword args
 *
 * Sets a TypeError and returns 0 if the kwds dict is
 * not empty, returns 1 otherwise
 */
int
_PyArg_NoKeywords(const char *funcname, PyObject *kw)
{
	if (kw == NULL)
		return 1;
	if (!PyDict_CheckExact(kw)) {
		PyErr_BadInternalCall();
		return 0;
	}
	if (PyDict_Size(kw) == 0)
		return 1;

	PyErr_Format(PyExc_TypeError, "%s does not take keyword arguments",
			funcname);
	return 0;
}
#ifdef __cplusplus
};
#endif


text:
#ifndef __FORK_D3D11_RENDER_SYSTEM_H__
#define __FORK_D3D11_RENDER_SYSTEM_H__

#include "Video/RenderSystem/RenderSystem.h"

#include <d3d11.h>
#include <vector>

namespace Fork
{

namespace Video
{

class D3D11Texture1D;
class D3D11Texture2D;
class D3D11Texture3D;
class D3D11TextureCube;
class D3D11RenderTarget;
class D3D11RenderContext;

//! Direct3D 11 render system implementation.
class D3D11RenderSystem : public RenderSystem
{

    public:

        D3D11RenderSystem();
        virtual ~D3D11RenderSystem();

        /* === Interface implementation === */

        RenderContextPtr CreateRenderContext(
            const VideoMode& videoMode, const ContextDescription& contextDesc,
            const std::wstring& frameTitle, void* parentFrame = nullptr
        );

        /* --- Render states --- */

        RasterizerStatePtr      CreateRasterizerState   (const RasterizerState  ::Description& desc);
        DepthStencilStatePtr    CreateDepthStencilState (const DepthStencilState::Description& desc);
        BlendStatePtr           CreateBlendState        (const BlendState       ::Description& desc);
        SamplerStatePtr         CreateSamplerState      (const SamplerState     ::Description& desc);

        void ChangeStateDesc(RasterizerState*   state, const RasterizerState::Description&      desc);
        void ChangeStateDesc(DepthStencilState* state, const DepthStencilState::Description&    desc);
        void ChangeStateDesc(BlendState*        state, const BlendState::Description&           desc);
        void ChangeStateDesc(SamplerState*      state, const SamplerState::Description&         desc);

        /* --- Hardware buffers --- */

        VertexBufferPtr CreateVertexBuffer();
        IndexBufferPtr CreateIndexBuffer();
        ConstantBufferPtr CreateConstantBuffer(const ConstantBuffer::Description& desc);
        StorageBufferPtr CreateStorageBuffer(const StorageBuffer::Description& desc);

        void WriteBuffer(
            VertexBuffer* vertexBuffer, const VertexFormat& format, const void* data,
            size_t dataSize, const HardwareBufferUsage usage = HardwareBufferUsage::Static
        );
        void WriteBuffer(
            IndexBuffer* indexBuffer, const IndexFormat& format, const void* data,
            size_t dataSize, const HardwareBufferUsage usage = HardwareBufferUsage::Static
        );
        void WriteBuffer(
            ConstantBuffer* constantBuffer, const void* data,
            size_t dataSize, const HardwareBufferUsage usage = HardwareBufferUsage::Static
        );
        //! \todo Not yet implemented
        void WriteBuffer(
            StorageBuffer* storageBuffer, const void* data,
            size_t dataSize, const HardwareBufferUsage usage = HardwareBufferUsage::Static
        );

        void WriteSubBuffer(VertexBuffer* vertexBuffer, const void* data, size_t dataSize, size_t offset = 0);
        void WriteSubBuffer(IndexBuffer* indexBuffer, const void* data, size_t dataSize, size_t offset = 0);
        void WriteSubBuffer(ConstantBuffer* constantBuffer, const void* data, size_t dataSize, size_t offset = 0);

        //! \todo Not yet implemented
        void* MapBuffer(StorageBuffer* storageBuffer, const HardwareBufferCPUAccess cpuAccess = HardwareBufferCPUAccess::ReadWrite);
        //! \todo Not yet implemented
        void UnmapBuffer(StorageBuffer* storageBuffer);

        /* --- Textures --- */

        Texture1DPtr CreateTexture1D();
        Texture2DPtr CreateTexture2D();
        Texture3DPtr CreateTexture3D();
        TextureCubePtr CreateTextureCube();

        void WriteTexture(
            Texture1D* texture,
            const TextureFormats textureFormat, const Texture1D::SizeType& textureSize, unsigned int arraySize,
            const ImageColorFormats imageFormat, const RendererDataTypes imageDataType, const void* imageData
        );
        void WriteSubTexture(
            Texture1D* texture,
            const Texture1D::PositionType& position, const Texture1D::SizeType& size, unsigned int arrayIndex,
            const ImageColorFormats imageFormat, const RendererDataTypes imageDataType, const void* imageData,
            unsigned int mipLevel = 0
        );

        void WriteTexture(
            Texture2D* texture,
            const TextureFormats textureFormat, const Texture2D::SizeType& textureSize, unsigned int arraySize,
            const ImageColorFormats imageFormat, const RendererDataTypes imageDataType, const void* imageData
        );
        void WriteSubTexture(
            Texture2D* texture,
            const Texture2D::PositionType& position, const Texture2D::SizeType& size, unsigned int arrayIndex,
            const ImageColorFormats imageFormat, const RendererDataTypes imageDataType, const void* imageData,
            unsigned int mipLevel = 0
        );

        void WriteTexture(
            Texture3D* texture,
            const TextureFormats textureFormat, const Texture3D::SizeType& textureSize,
            const ImageColorFormats imageFormat, const RendererDataTypes imageDataType, const void* imageData
        );
        void WriteSubTexture(
            Texture3D* texture,
            const Texture3D::PositionType& position, const Texture3D::SizeType& size,
            const ImageColorFormats imageFormat, const RendererDataTypes imageDataType, const void* imageData,
            unsigned int mipLevel = 0
        );

        void WriteTexture(
            TextureCube* texture,
            const TextureFormats textureFormat, const TextureCube::SizeType& textureSize, unsigned int arraySize,
            const ImageColorFormats imageFormat, const RendererDataTypes imageDataType, const void* imageData
        );
        void WriteSubTexture(
            TextureCube* texture,
            const TextureCube::PositionType& position, const TextureCube::SizeType& size,
            const TextureCube::Faces faceDirection, unsigned int arrayIndex,
            const ImageColorFormats imageFormat, const RendererDataTypes imageDataType, const void* imageData,
            unsigned int mipLevel = 0
        );

        //! \todo Not yet implemented!
        bool ReadTexture(const Texture* texture, ImageUByte& image, unsigned int mipLevel = 0);
        //! \todo Not yet implemented!
        bool ReadTexture(const Texture* texture, ImageFloat& image, unsigned int mipLevel = 0);

        /* --- Render targets --- */

        RenderTargetPtr CreateRenderTarget();

        /* --- Shaders --- */

        VertexShaderPtr         CreateVertexShader          ();
        PixelShaderPtr          CreatePixelShader           ();
        GeometryShaderPtr       CreateGeometryShader        ();
        TessControlShaderPtr    CreateTessControlShader     ();
        TessEvaluationShaderPtr CreateTessEvaluationShader  ();
        ComputeShaderPtr        CreateComputeShader         ();
        ShaderCompositionPtr    CreateShaderComposition     ();

        /* --- Misc --- */

        QueryPtr CreateQuery(const Query::Types type);

    protected:

        friend class D3D11RenderContext;
        friend class D3D11RenderTarget;

        std::shared_ptr<D3D11RenderContext> InitRenderContext(
            const std::shared_ptr<D3D11RenderContext>& renderContext,
            const VideoMode& videoMode, const ContextDescription& contextDesc
        );

        //! Creates a new swap chain with the specified configuration.
        IDXGISwapChain* CreateSwapChain(
            const VideoMode& videoMode, const ContextDescription& contextDesc, HWND windowHandle
        );

        //! Queries the back buffer from the specified swap chain.
        ID3D11Texture2D* QueryBackBuffer(IDXGISwapChain* swapChain);

        //! Creates a new render target view for the specified resource.
        ID3D11RenderTargetView* CreateRenderTargetView(ID3D11Resource* resource, const D3D11_RENDER_TARGET_VIEW_DESC* desc = nullptr);

        //! Creates a new depth stencil with the specified configuration.
        ID3D11Texture2D* CreateDepthStencil(const Math::Size2ui& resolution, unsigned int numSamples = 1);

        //! Creates a new depth stencil view for the specified depth stencil.
        ID3D11DepthStencilView* CreateDepthStencilView(ID3D11Texture2D* depthStencil, bool hasAntiAliasing);

    private:

        friend class D3D11ProfilerRenderSystem;

        /* === Structures === */

        struct VideoAdapter
        {
            IDXGIAdapter*   adapter = nullptr;
            Adapter         info;
        };

        /* === Functions === */

        std::unique_ptr<ShaderProvider> CreateShaderProvider();

        //! \throws std::runtime_error On errors.
        static ID3D11Device* CreateDevice(
            const D3D_FEATURE_LEVEL* featureLevel, D3D_FEATURE_LEVEL* featureLevelOut,
            IDXGIAdapter* adapter, ID3D11DeviceContext*& context
        );
        //! \throws std::runtime_error On errors.
        static IDXGIFactory* QueryFactory(ID3D11Device* device);

        static std::vector<VideoAdapter> QueryVideoAdapters(IDXGIFactory* factory, D3D_FEATURE_LEVEL featureLevel);

        /* === Members === */

        ID3D11Device*               device_         = nullptr;
        ID3D11DeviceContext*        context_        = nullptr;

        IDXGIFactory*               factory_        = nullptr;

        D3D_FEATURE_LEVEL           featureLevel_   = D3D_FEATURE_LEVEL_11_0;
        std::vector<VideoAdapter>   videoAdapters_;

};

} // /namespace Video

} // /namespace Fork

#endif

// ========================

redpajama_set_name: RedPajamaGithub


text:
using UnityEngine;
using System.Collections;

public class Rocket : Weapon
{

    public float explosionRadius = 50.0f;

    // Use this for initialization
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {

    }

    public override void FireWeapon(Vector3 rotation, Vector2 position, Vector2 velocity)
    {
        base.FireWeapon(rotation, position, velocity);
    }

    public override void FireWeapon(Vector2 position, Vector2 velocity)
    {
        base.FireWeapon(position, velocity);
    }

    protected override void OnTriggerEnter2D(Collider2D collision)
    {

        GameObject go = collision.gameObject;

        if (go.tag == "Enemy")
        {
            Enemy enemy = go.GetComponent<Enemy>();
            enemy.playDamageEffect();
            ExplosionDamage(enemy.gameObject.transform.position, explosionRadius);
        }

        if (go.tag == "OutOfBounds")
        {
            Destroy(this.gameObject);
        }
    }

    private void ExplosionDamage(Vector3 center, float radius)
    {
        Collider2D[] hitColliders = Physics2D.OverlapCircleAll(center, radius);
        int i = 0;
        int enemyCount = 0;
        Debug.Log(hitColliders.Length);
        while (i < hitColliders.Length)
        {
            GameObject go = hitColliders[i].gameObject;

            if(go.tag == "Enemy")
            {
                enemyCount++;
                Enemy enemy = go.GetComponent<Enemy>();
                enemy.applyDamage(getDamage());
            }

            i++;
        }

        Destroy(this.gameObject);
        Debug.Log("Enemies in Radius: " + enemyCount);
    }
}


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

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

Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied.  See the License for the
specific language governing permissions and limitations
under the License.
--><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

  <modelVersion>4.0.0</modelVersion>

  <parent>
    <groupId>org.codehaus.mojo</groupId>
    <artifactId>mojo-parent</artifactId>
    <version>33</version>
  </parent>
  <artifactId>flatten-maven-plugin</artifactId>
  <packaging>maven-plugin</packaging>
  <name>Maven Flatten Plugin</name>
  <version>1.0.0-beta-6-SNAPSHOT</version>
  <description>Plugin to generate flattened POM (reduced and resolved information required for consumers of maven repositories) and to use (install, sign, deploy) it instead of original pom.xml.</description>
  <inceptionYear>2014</inceptionYear>
  <prerequisites>
    <maven>${mavenVersion}</maven>
  </prerequisites>
  <properties>
    <mavenVersion>3.0</mavenVersion>
  </properties>
  <developers>
    <developer>
      <id>hohwille</id>
      <name>Jörg Hohwiller</name>
      <email>hohwille@users.sourceforge.net</email>
    </developer>
    <developer>
      <id>rfscholte</id>
      <name>Robert Scholte</name>
      <email>rfscholte@codehaus.org</email>
      <timezone>Europe/Amsterdam</timezone>
    </developer>
  </developers>
  <dependencies>
    <dependency>
      <groupId>org.apache.maven</groupId>
      <artifactId>maven-model</artifactId>
      <version>${mavenVersion}</version>
    </dependency>
    <dependency>
      <groupId>org.apache.maven</groupId>
      <artifactId>maven-model-builder</artifactId>
      <version>${mavenVersion}</version>
    </dependency>
    <dependency>
      <groupId>org.apache.maven</groupId>
      <artifactId>maven-artifact</artifactId>
      <version>${mavenVersion}</version>
    </dependency>
    <dependency>
      <groupId>org.apache.maven</groupId>
      <artifactId>maven-core</artifactId>
      <version>${mavenVersion}</version>
    </dependency>
    <dependency>
      <groupId>org.apache.maven</groupId>
      <artifactId>maven-plugin-api</artifactId>
      <version>${mavenVersion}</version>
    </dependency>
    <dependency>
      <groupId>org.codehaus.plexus</groupId>
      <artifactId>plexus-utils</artifactId>
      <version>3.0.17</version>
    </dependency>

    <dependency>
      <groupId>org.apache.maven.plugin-tools</groupId>
      <artifactId>maven-plugin-annotations</artifactId>
      <version>3.2</version>
      <scope>provided</scope>
    </dependency>
  </dependencies>
  <build>
    <pluginManagement>
      <plugins>
        <plugin>
          <groupId>org.apache.maven.plugins</groupId>
          <artifactId>maven-plugin-plugin</artifactId>
          <version>3.2</version>
          <configuration>
            <skipErrorNoDescriptorsFound>true</skipErrorNoDescriptorsFound>
          </configuration>
          <executions>
            <execution>
              <id>mojo-descriptor</id>
              <phase>process-classes</phase>
              <goals>
                <goal>descriptor</goal>
              </goals>
            </execution>
            <execution>
              <id>help-goal</id>
              <goals>
                <goal>helpmojo</goal>
              </goals>
            </execution>
          </executions>
        </plugin>
      </plugins>
    </pluginManagement>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-plugin-plugin</artifactId>
        <configuration>
          <goalPrefix>flatten</goalPrefix>
        </configuration>
      </plugin>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>2.5.1</version>
        <configuration>
          <source>1.5</source>
          <target>1.5</target>
        </configuration>
      </plugin>
    </plugins>
  </build>

  <profiles>
    <profile>
      <id>run-its</id>
      <activation>
        <property>
          <name>skipTests</name>
          <value>!true</value>
        </property>
      </activation>
      <build>
        <plugins>
          <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-invoker-plugin</artifactId>
            <executions>
              <execution>
                <goals>
                  <goal>install</goal>
                  <goal>integration-test</goal>
                  <goal>verify</goal>
                </goals>
              </execution>
            </executions>
            <configuration>
              <debug>true</debug>
              <cloneProjectsTo>${project.build.directory}/it</cloneProjectsTo>
              <localRepositoryPath>${project.build.directory}/local-repo</localRepositoryPath>
              <settingsFile>src/it/mrm/settings.xml</settingsFile>
              <filterProperties>
                <repository.proxy.url>${repository.proxy.url}</repository.proxy.url>
              </filterProperties>
              <properties>
                <settingsFile>${project.build.directory}/it/interpolated-settings.xml</settingsFile>
              </properties>
              <goals>
                <goal>clean</goal>
                <goal>${project.groupId}:${project.artifactId}:${project.version}:flatten</goal>
              </goals>
              <projectsDirectory>src/it/projects</projectsDirectory>
              <postBuildHookScript>verify</postBuildHookScript>
            </configuration>
          </plugin>
          <plugin>
            <groupId>org.codehaus.mojo</groupId>
            <artifactId>mrm-maven-plugin</artifactId>
            <version>1.0-beta-1</version>
            <executions>
              <execution>
                <goals>
                  <goal>start</goal>
                  <goal>stop</goal>
                </goals>
              </execution>
            </executions>
            <configuration>
              <propertyName>repository.proxy.url</propertyName>
              <repositories>
                <mockRepo>
                  <source>src/it/mrm/repository</source>
                </mockRepo>
                <proxyRepo />
              </repositories>
            </configuration>
          </plugin>
        </plugins>
      </build>
    </profile>
  </profiles>
  <licenses>
    <license>
      <name>Apache Software Licenese</name>
      <url>http://www.apache.org/licenses/LICENSE-2.0.txt</url>
      <comments />
    </license>
  </licenses>
  <scm>
    <connection>scm:svn:http://svn.codehaus.org/mojo/trunk/mojo/flatten-maven-plugin</connection>
    <developerConnection>scm:svn:https://svn.codehaus.org/mojo/trunk/mojo/flatten-maven-plugin</developerConnection>
    <url>http://fisheye.codehaus.org/browse/mojo/trunk/mojo/flatten-maven-plugin</url>
  </scm>
</project>


text:
<!DOCTYPE html>

    <title>Protocols  Reference</title>
    <link rel="stylesheet" type="text/css" href="css/jazzy.css" />
    <link rel="stylesheet" type="text/css" href="css/highlight.css" />
    <meta charset='utf-8'>

 Docs (74% documented)

         Reference

        Protocols  Reference

            Classes

                ColResult

                ColResultIterator

                EntityBuilder

                InProgress

                InProgressBuilder

                Mentat

                OptionalRustObject

                Query

                RelResult

                RelResultIterator

                RustObject

                TupleResult

                TxReport

                TypedValue

            Enumerations

                CacheDirection

                PointerError

                QueryError

                ResultError

            Extensions

                Date

                Result

            Protocols

                Observable

                Observing

            Structures

                MentatError

            Type Aliases

                Entid

Protocols

The following protocols are available globally.

                    Observing

Protocol to be implemented by any object that wishes to register for transaction observation

                        See more

Declaration

Swift

public protocol Observing

                    Observable

Protocol to be implemented by any object that provides an interface to Mentat’s transaction observers.

                        See more

Declaration

Swift

public protocol Observable

© 2018 . All rights reserved. (Last updated: 2018-06-21)

Generated by jazzy ♪♫ v0.9.2, a Realm project.


text:
package mock_authentication

import (
	session "github.com/dnp1/conversa/server/data/session"
	errors "github.com/dnp1/conversa/server/errors"
	gomock "github.com/golang/mock/gomock"
)

// Mock of Model interface
type MockModel struct {
	ctrl     *gomock.Controller
	recorder *_MockModelRecorder
}

// Recorder for MockModel (not exported)
type _MockModelRecorder struct {
	mock *MockModel
}

func NewMockModel(ctrl *gomock.Controller) *MockModel {
	mock := &MockModel{ctrl: ctrl}
	mock.recorder = &_MockModelRecorder{mock}
	return mock
}

func (_m *MockModel) EXPECT() *_MockModelRecorder {
	return _m.recorder
}

func (_m *MockModel) Retrieve(_param0 string) (*session.Data, errors.Error) {
	ret := _m.ctrl.Call(_m, "Retrieve", _param0)
	ret0, _ := ret[0].(*session.Data)
	ret1, _ := ret[1].(errors.Error)
	return ret0, ret1
}

func (_mr *_MockModelRecorder) Retrieve(arg0 interface{}) *gomock.Call {
	return _mr.mock.ctrl.RecordCall(_mr.mock, "Retrieve", arg0)
}


text:
using samplog::LogLevel;

class Logger : public samplog::ILogger
{
public:
	using Clock = std::chrono::system_clock;

	struct Config
	{
		LogLevel Level = LogLevel::ERROR | LogLevel::WARNING | LogLevel::FATAL;
		bool PrintToConsole = false;
		bool Append = true;
		LogRotationConfig Rotation;
	};

public:
	Logger(std::string modulename);
	~Logger();

public: // interface implementation
	bool IsLogLevel(LogLevel log_level) const override
	{
		return (_config.Level & log_level) == log_level;
	}

	bool Log(LogLevel level, std::string msg,
		std::vector<samplog::AmxFuncCallInfo> const &call_info) override;
	bool Log(LogLevel level, std::string msg) override;
	bool LogNativeCall(AMX * const amx, cell * const params,
		std::string name, std::string params_format) override;

	void Destroy() override
	{
		delete this;
	}

public:
	inline std::string const &GetModuleName() const
	{
		return _moduleName;
	}

private:
	void OnConfigUpdate(Logger::Config const &config);

	std::string FormatTimestamp(Clock::time_point time);
	std::string FormatLogMessage(std::string message,
		std::vector<samplog::AmxFuncCallInfo> call_info);

	void WriteLogString(std::string const &time, LogLevel level,
		std::string const &message);
	void PrintLogString(std::string const &time, LogLevel level,
		std::string const &message);

private:
	std::string const _moduleName;
	std::string const _logFilePath;
	std::atomic<unsigned int> _logCounter;

	Config _config;
};


text:
from .board import Board

class MemoryBoard(Board):

    def __init__(self):
        Board.__init__(self)
        self._board = []

    def post_message(self, message):
        self._board.append(message)

        self._board = sorted(self._board,
                             key=lambda a: a.timestamp, reverse=True)

    def get_message(self):
        if(len(self._board) > 0):
            return self._board.pop()
        else:
            return None


text:
package taiga.parser;

import taiga.interfaces.TaigaException;
import taiga.parser.node.AInitialization;
import taiga.parser.node.Node;

public class InitializationParserContext extends TypeScopeParserContext {

	private final AInitialization init;
	private final BlocksParserContext blocks;

	protected InitializationParserContext(ParserContext parent, AInitialization init) throws TaigaException {
		super(parent);
		this.init = init;
		blocks = new BlocksParserContext(this, init.getBlocks(), getTypeScope());
	}

	@Override
	public void initialize(InstanceContext ic) throws TaigaException {
		blocks.initialize(ic);
	}

	@Override
	protected Node getASTNode() {
		return init;
	}

	@Override
	public void init() throws TaigaException {
		super.init();
		blocks.init();
	}
}


text:
<?php

namespace Laravelit\Roles\Models;

use Laravelit\Roles\Traits\Slugable;
use Illuminate\Database\Eloquent\Model;
use Laravelit\Roles\Traits\RoleHasRelations;
use Laravelit\Roles\Contracts\RoleHasRelations as RoleHasRelationsContract;

class Role extends Model implements RoleHasRelationsContract
{
    use Slugable, RoleHasRelations;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = ['name', 'slug', 'description', 'level'];

    /**
     * Create a new model instance.
     *
     * @param array $attributes
     * @return void
     */
    public function __construct(array $attributes = [])
    {
        parent::__construct($attributes);

        if ($connection = config('roles.connection')) {
            $this->connection = $connection;
        }
    }
}


text:
package com.mongodb.connection;

import com.mongodb.MongoException;
import com.mongodb.MongoNodeIsRecoveringException;
import com.mongodb.MongoNotPrimaryException;
import com.mongodb.MongoSecurityException;
import com.mongodb.MongoSocketException;
import com.mongodb.MongoSocketReadTimeoutException;
import com.mongodb.ServerAddress;
import com.mongodb.async.SingleResultCallback;

import java.util.Collections;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

import static com.mongodb.assertions.Assertions.isTrue;
import static com.mongodb.assertions.Assertions.notNull;
import static com.mongodb.connection.ServerConnectionState.CONNECTING;
import static com.mongodb.internal.async.ErrorHandlingResultCallback.errorHandlingCallback;

class DefaultServer implements ClusterableServer {
    private final ServerAddress serverAddress;
    private final ConnectionPool connectionPool;
    private final ClusterConnectionMode clusterConnectionMode;
    private final ConnectionFactory connectionFactory;
    private final ServerMonitor serverMonitor;
    private final Set<ChangeListener<ServerDescription>> changeListeners =
    Collections.newSetFromMap(new ConcurrentHashMap<ChangeListener<ServerDescription>, Boolean>());
    private final ChangeListener<ServerDescription> serverStateListener;
    private volatile ServerDescription description;
    private volatile boolean isClosed;

    public DefaultServer(final ServerAddress serverAddress,
                         final ClusterConnectionMode clusterConnectionMode,
                         final ConnectionPool connectionPool,
                         final ConnectionFactory connectionFactory,
                         final ServerMonitorFactory serverMonitorFactory) {
        notNull("serverMonitorFactory", serverMonitorFactory);
        this.clusterConnectionMode = notNull("clusterConnectionMode", clusterConnectionMode);
        this.connectionFactory = notNull("connectionFactory", connectionFactory);
        this.serverAddress = notNull("serverAddress", serverAddress);
        this.connectionPool = notNull("connectionPool", connectionPool);
        this.serverStateListener = new DefaultServerStateListener();
        description = ServerDescription.builder().state(CONNECTING).address(serverAddress).build();
        serverMonitor = serverMonitorFactory.create(serverStateListener);
        serverMonitor.start();
    }

    @Override
    public Connection getConnection() {
        isTrue("open", !isClosed());
        try {
            return connectionFactory.create(connectionPool.get(), new DefaultServerProtocolExecutor(), clusterConnectionMode);
        } catch (MongoSecurityException e) {
            invalidate();
            throw e;
        }
    }

    @Override
    public void getConnectionAsync(final SingleResultCallback<AsyncConnection> callback) {
        isTrue("open", !isClosed());
        connectionPool.getAsync(new SingleResultCallback<InternalConnection>() {
            @Override
            public void onResult(final InternalConnection result, final Throwable t) {
                if (t instanceof MongoSecurityException) {
                    invalidate();
                }
                if (t != null) {
                    callback.onResult(null, t);
                } else {
                    callback.onResult(connectionFactory.createAsync(result, new DefaultServerProtocolExecutor(), clusterConnectionMode),
                                      null);
                }
            }
        });
    }

    @Override
    public ServerDescription getDescription() {
        isTrue("open", !isClosed());

        return description;
    }

    @Override
    public void addChangeListener(final ChangeListener<ServerDescription> changeListener) {
        isTrue("open", !isClosed());

        changeListeners.add(changeListener);
    }

    @Override
    public void invalidate() {
        isTrue("open", !isClosed());

        serverStateListener.stateChanged(new ChangeEvent<ServerDescription>(description, ServerDescription.builder()
                                                                                .state(CONNECTING)
                                                                                .address(serverAddress).build()));
        connectionPool.invalidate();
        serverMonitor.invalidate();
    }

    @Override
    public void close() {
        if (!isClosed()) {
            connectionPool.close();
            serverMonitor.close();
            isClosed = true;
        }
    }

    @Override
    public boolean isClosed() {
        return isClosed;
    }

    @Override
    public void connect() {
        serverMonitor.connect();
    }

    ConnectionPool getConnectionPool() {
        return connectionPool;
    }

    private void handleThrowable(final Throwable t) {
        if ((t instanceof MongoSocketException && !(t instanceof MongoSocketReadTimeoutException))
            || t instanceof MongoNotPrimaryException
            || t instanceof MongoNodeIsRecoveringException) {
            invalidate();
        }
    }

    private class DefaultServerProtocolExecutor implements ProtocolExecutor {
        @Override
        public <T> T execute(final Protocol<T> protocol, final InternalConnection connection) {
            try {
                return protocol.execute(connection);
            } catch (MongoException e) {
                handleThrowable(e);
                throw e;
            }
        }

        @Override
        public <T> void executeAsync(final Protocol<T> protocol, final InternalConnection connection,
                                     final SingleResultCallback<T> callback) {
            protocol.executeAsync(connection, errorHandlingCallback(new SingleResultCallback<T>() {
                @Override
                public void onResult(final T result, final Throwable t) {
                    if (t != null) {
                        handleThrowable(t);
                    }
                    callback.onResult(result, t);
                }
            }));
        }
    }

    private final class DefaultServerStateListener implements ChangeListener<ServerDescription> {
        @Override
        public void stateChanged(final ChangeEvent<ServerDescription> event) {
            description = event.getNewValue();
            for (ChangeListener<ServerDescription> listener : changeListeners) {
                listener.stateChanged(event);
            }
        }
    }
}


text:
<?php

use Drupal\Core\DrupalKernel;
use Symfony\Component\HttpFoundation\Request;

$autoloader = require_once 'autoload.php';

$kernel = new DrupalKernel('prod', $autoloader);
$request = Request::createFromGlobals();

$response = $kernel->handle($request);
$response->send();

$kernel->terminate($request, $response);


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using RedArrow.Argo.TestUtils;
using WovenByFody;
using Xunit;
using Xunit.Abstractions;

namespace RedArrow.Argo.Client.Integration.Session
{
    public class EagerCollectionTests : IntegrationTest
    {
        public EagerCollectionTests(IntegrationTestFixture fixture, ITestOutputHelper outputHelper) :
            base(fixture, outputHelper)
        {
        }

        [Fact, Trait("Category", "Integration")]
        public async Task AddIncluded()
        {
            Guid providerId;
            Guid patientId;
            Guid companyId;

            var stubInsuranceCompany = new Company
            {
                Name = "Primo Insurance Brah!",
                Address = "123 Main St",
                PhoneNumber = "800-555-1234",
            };

            var stubPatient1 = new Patient
            {
                FirstName = "Deltron",
                LastName = "3030",
                Age = 45,
                AccountBalance = (decimal) 15.99,
                Insurance = stubInsuranceCompany
            };

            var stubPatient2 = new Patient
            {
                FirstName = "Del",
                LastName = "The Funky Homosapien",
                Age = 35,
                AccountBalance = (decimal) 125.99,
                Insurance = stubInsuranceCompany
            };

            var stubProvider = new Provider
            {
                FirstName = "Bob",
                LastName = "Dobblena",
                Patients = new List<Patient> {stubPatient1, stubPatient2}
            };

            using (var session = SessionFactory.CreateSession())
            {
                var provider = await session.Create(stubProvider);
                providerId = provider.Id;
                patientId = provider.Patients.First().Id;
            }

            using (var session = SessionFactory.CreateSession())
            {
                var provider = await session.Get<Provider>(providerId);

                Assert.NotNull(provider);
                Assert.NotNull(provider.Patients);

                var patient = provider.Patients.First();
                companyId = patient.Insurance.Id;

                Assert.NotNull(patient);
                Assert.Equal(patientId, patient.Id);
            }

            using (var session = SessionFactory.CreateSession())
            {
                await session.Delete<Provider>(providerId);
                await session.Delete<Patient>(patientId);
                await session.Delete<Company>(companyId);
            }
        }

        [Fact, Trait("Category", "Integration")]
        public async Task GetModelWithEagerLoadedCollection()
        {
            Guid id;
            using (var session = SessionFactory.CreateSession())
            {
                var provider = new Provider
                {
                    FirstName = "Bill",
                    LastName = "Nye",
                    Patients = new List<Patient>
                    {
                        new Patient(),
                        new Patient(),
                        new Patient()
                    }
                };

                provider = await session.Create(provider);
                id = provider.Id;
            }

            using (var session = SessionFactory.CreateSession())
            {
                var provider = await session.Get<Provider>(id);

                Assert.Equal(3, provider.Patients.Count);

                foreach (var patient in provider.Patients)
                {
                    await session.Delete(patient);
                }
                await session.Delete(provider);
            }
        }
    }
}


text:
go-web-proxy
============

A simple web based proxy written in Go. Can be easily hosted on [OpenShift](https://openshift.redhat.com/app/login)

currently provides two options,

1] this is useful for a single file. It only pipes the response.

    ` <hostname>/p/?target=http://foo.com/bar.png`

2] this is useful to view a web page that contains other static images, css, js files

    `<hostname>/t/?target=http://foo.com/bar/`

how to host on OpenShift
------------------------

- fork this repo
- register an account on openshift.redhat.com, follow standard account activation procedure
- go to **Settings** tab and add public key for ssh to work
- go back to **Applications** tab, click **Add Application**
- scroll down and select Go language under Other types
- fill in the form, enter name/domain pair
- enter git repo address for forked repo. enter **master** as branch name
- keep default for rest but know that if you select **No scaling** then you won't be able to scale later
- Click **Create Application**
- Done

Add a bookmarklet to quickly use this proxy
-------------------------------------------

- Add a new bookmark in your browser
- name it anything, say **proxy**
- use this as its URL

    `javascript:location.href='http://<your-hostname-here>/t/?target='+location.href`

- now when you need to use this proxy, simply click the bookmark and it should work

License
-------

MIT license


text:
import has from 'lodash/has';
import logger from 'kolibri.lib.logging';
import { masteryModelValidator } from '../../utils/contentNodeUtils';

export const logging = logger.getLogger(__filename);

export function tryValidator(currentTry) {
  const requiredFields = [
    'id',
    'mastery_criterion',
    'start_timestamp',
    'end_timestamp',
    'correct',
    'time_spent',
    'completion_timestamp',
    'complete',
  ];
  if (
    !requiredFields.every(key => {
      if (!has(currentTry, key)) {
        logging.error(`Missing required field ${key} in try ${JSON.stringify(currentTry)}`);
        return false;
      }
      return true;
    })
  ) {
    return false;
  }
  if (!masteryModelValidator(currentTry.mastery_criterion)) {
    return false;
  }
  if (!currentTry.diff || Object.keys(currentTry.diff).length === 0) {
    return true;
  }
  return has(currentTry.diff, 'correct') && has(currentTry.diff, 'time_spent');
}


text:
"""
a collection of small, general purpose objects and methods
"""

### import ####################################################################

import numpy as np

### math ######################################################################

def grating_linear_dispersion(
    spec_inclusion_angle,
    spec_focal_length,
    spec_focal_length_tilt,
    spec_grooves_per_mm,
    spec_central_wavelength,
    spec_order,
    number_of_pixels,
    pixel_width,
    calibration_pixel,
):
    """
    Parameters
    ----------
    spec_inclusion_angle : float
        Spectrometer inclusion angle (degrees).
    spec_focal_length : float
        Spectrometer focal length (mm).
    spec_focal_length_tilt : float
        Spectrometer focal length tilt (degrees).
    spec_grooves_per_mm : float
        Spectrometer grating grooves per mm.
    spec_central_wavelength : float
        Spectrometer set wavelength (nm).
    spec_order : int
        Spectrometer order of diffraction.
    number_of_pixels : int
        Number of pixels on array detector.
    pixel_width : float
        Pixel width (um)
    calibration_pixel : int
        Pixel on which the spec_central_wavelength falls.

    Returns
    -------
    np.ndarray
        Color found on each pixel (nm)
    """
    # translate inputs into appropriate internal units
    spec_inclusion_angle_rad = np.radians(spec_inclusion_angle)
    spec_focal_length_tilt_rad = np.radians(spec_focal_length_tilt)
    pixel_width_mm = pixel_width / 1e3
    # create array
    i_pixel = np.arange(number_of_pixels)
    # calculate terms
    x = np.arcsin(
        (1e-6 * spec_order * spec_grooves_per_mm * spec_central_wavelength)
        / (2 * np.cos(spec_inclusion_angle_rad / 2.0))
    )
    A = np.sin(x - spec_inclusion_angle_rad / 2)
    B = np.sin(
        (spec_inclusion_angle_rad)
        + x
        - (spec_inclusion_angle_rad / 2)
        - np.arctan(
            (
                pixel_width_mm * (i_pixel - calibration_pixel)
                + spec_focal_length * spec_focal_length_tilt_rad
            )
            / (spec_focal_length * np.cos(spec_focal_length_tilt_rad))
        )
    )
    out = ((A + B) * 1e6) / (spec_order * spec_grooves_per_mm)
    return out

### testing ###################################################################

if __name__ == "__main__":
    arr = grating_linear_dispersion(
        spec_inclusion_angle=24.0,
        spec_focal_length=140.0,
        spec_focal_length_tilt=0.0,
        spec_grooves_per_mm=300.0,
        spec_central_wavelength=1300.0,
        spec_order=1,
        number_of_pixels=256,
        pixel_width=50.0,
        calibration_pixel=100,
    )
    print(arr[100])


text:
using NUnit.Framework;
using Orchard.Core.Common.Services;

namespace Orchard.Core.Tests.Common {
    [TestFixture]
    public class BbcodeFilterTests {

        private readonly BbcodeFilter _filter = new BbcodeFilter();

        [Test]
        public void ShouldIgnoreText() {
            const string text = "foo bar baz";
            var processed = _filter.ProcessContent(text, null);
            Assert.That(processed, Is.EqualTo(text));
        }

        [Test]
        public void ShouldReplaceUrl() {
            const string text = "foo [url]bar[/url] baz";
            var processed = _filter.ProcessContent(text, null);
            Assert.That(processed, Is.EqualTo("foo bar baz"));
        }

        [Test]
        public void ShouldReplaceImg() {
            const string text = "foo [img]bar[/img] baz";
            var processed = _filter.ProcessContent(text, null);
            Assert.That(processed, Is.EqualTo("foo  baz"));
        }

        [Test]
        public void ShouldReplaceUrlWithTitle() {
            const string text = "foo [url=alink]bar[/url] baz";
            var processed = _filter.ProcessContent(text, null);
            Assert.That(processed, Is.EqualTo("foo bar baz"));
        }
    }
}


text:
#region License

#endregion
using System;
using System.Collections.Generic;
using Marius.Html.Css.Values;

namespace Marius.Html.Css.Properties
{
    public partial class VoiceFamily: CssSimplePropertyHandler
    {
        public override bool IsInherited
        {
            get { return true; }
        }

        public override CssValue Initial
        {
            get { return CssKeywords.Male; }
        }

        public VoiceFamily(CssContext context)
            : base(context)
        {
        }

        public override CssValue Parse(CssExpression expression)
        {
            CssValue result = null;
            if (MatchFamily(_context, expression, ref result))
            {
                List<CssValue> values = new List<CssValue>();
                values.Add(result);

                while (expression.Current.ValueType == CssValueType.Comma)
                {
                    if (!MatchFamily(_context, expression, ref result))
                        return null;
                    values.Add(result);
                }

                return new CssValueList(values.ToArray());
            }

            return MatchInherit(expression);
        }

        protected virtual bool MatchFamily(CssContext context, CssExpression expression, ref CssValue result)
        {
            if (MatchAny(expression, new[] { CssKeywords.Male, CssKeywords.Female, CssKeywords.Child }, ref result))
                return true;

            if (MatchString(expression, ref result))
                return true;

            List<CssValue> names = new List<CssValue>();
            CssValue value = null;

            while (MatchIdentifier(expression, ref value))
                names.Add(value);

            if (names.Count == 0)
                return false;

            result = new CssValueList(names.ToArray());
            return true;
        }
    }
}


text:
title: "composer/ERR/2022_001"
linkTitle: "ERR/2022_001"
weight: 1
type: docs
description: >
  Composer Service Agent permissions
---

**Product**: [Cloud Composer](https://cloud.google.com/composer)\
**Rule class**: ERR - Something that is very likely to be wrong

### Description

Cloud Composer uses a Google-managed service account, which is called Cloud
Composer Service Agent, to provision resources in the project.

`composer.serviceAgent` role is automatically assigned to this account during
Composer API activation and shouldn't be revoked.

### Remediation

Ensure that you've the following binding in the IAM policy for the project:

- Principal: `service-PROJECT_NUMBER@cloudcomposer-accounts.iam.gserviceaccount.com`
- Role: `roles/composer.serviceAgent`

### Further information

- [About Cloud Composer Service Agent account](https://cloud.google.com/composer/docs/how-to/access-control#about-composer-sa)


text:
<?php

use yii\helpers\Html;
use yii\widgets\ActiveForm;

/* @var $this yii\web\View */
/* @var $model app\modules\controlcenter\models\DsListSearch */
/* @var $form yii\widgets\ActiveForm */
?>

    <?php $form = ActiveForm::begin([
        'action' => ['index'],
        'method' => 'get',
    ]); ?>

    <?= $form->field($model, 'id') ?>

    <?= $form->field($model, 'name') ?>

    <?= $form->field($model, 'owner') ?>

        <?= Html::submitButton(Yii::t('controlcenter/ds', 'Search'), ['class' => 'btn btn-primary']) ?>
        <?= Html::resetButton(Yii::t('controlcenter/ds', 'Reset'), ['class' => 'btn btn-default']) ?>

    <?php ActiveForm::end(); ?>


text:
// Generated by CoffeeScript 1.6.3
(function() {
  var Access, Base, Block, Call, Class, Code, ES5For, For, LEVEL_TOP, Literal, Param, Return, Transformer, UseES5MethodsInsteadOfForLoops, Value, any, apply, toSAST, underscore, _ref, _ref1,
    __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
    __hasProp = {}.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

  underscore = require('underscore');

  _ref = require('./nodes'), Base = _ref.Base, Return = _ref.Return, Call = _ref.Call, Code = _ref.Code, Param = _ref.Param, Class = _ref.Class, Block = _ref.Block, For = _ref.For, Value = _ref.Value, Access = _ref.Access, Literal = _ref.Literal, any = _ref.any, LEVEL_TOP = _ref.LEVEL_TOP;

  Transformer = (function() {
    function Transformer() {
      this.runOn = __bind(this.runOn, this);
    }

    Transformer.prototype.on = function(node) {
      return true;
    };

    Transformer.prototype.stopOn = function(node) {
      return false;
    };

    Transformer.prototype.map = function(node) {};

    Transformer.prototype.transform = function(node) {
      this.map(node);
      return node;
    };

    Transformer.prototype.runOn = function(node) {
      var attr, _i, _len, _ref1,
        _this = this;
      if (node instanceof Base) {
        if (this.stopOn && this.stopOn(node)) {
          return node;
        }
        _ref1 = node.children;
        for (_i = 0, _len = _ref1.length; _i < _len; _i++) {
          attr = _ref1[_i];
          if (node[attr]) {
            node[attr] = this.runOn(node[attr]);
          }
        }
        if (!this.on || this.on(node)) {
          return this.transform(node);
        }
        return node;
      } else if (node instanceof Array) {
        return node.map(function(e) {
          return _this.runOn(e);
        });
      } else {
        throw "internal compiler error";
      }
    };

    return Transformer;

  })();

  apply = function(transformers) {
    return function(node) {
      var transformer, _i, _len;
      for (_i = 0, _len = transformers.length; _i < _len; _i++) {
        transformer = transformers[_i];
        node = new transformer().runOn(node);
      }
      return node;
    };
  };

  UseES5MethodsInsteadOfForLoops = (function(_super) {
    __extends(UseES5MethodsInsteadOfForLoops, _super);

    function UseES5MethodsInsteadOfForLoops() {
      this.transform = __bind(this.transform, this);
      this.on = __bind(this.on, this);
      _ref1 = UseES5MethodsInsteadOfForLoops.__super__.constructor.apply(this, arguments);
      return _ref1;
    }

    UseES5MethodsInsteadOfForLoops.prototype.on = function(f) {
      return f instanceof For && !(f.index || f.object || f.step || f.pattern || f.jumps() || f.contains(function(n) {
        return n.match([
          new Literal("continue"), new Literal("break"), function() {
            return true;
          }, any, function() {
            return false;
          }
        ]);
      }));
    };

    UseES5MethodsInsteadOfForLoops.prototype.transform = function(f) {
      var comprehension, mkLam, mkMCall;
      mkMCall = function(obj, meth, args) {
        return new Call(new Value(obj, [new Access(new Literal(meth))]), args);
      };
      mkLam = function(exprs) {
        var lam;
        lam = new Code([new Param(f.name)], Block.wrap([exprs]), 'boundfunc');
        lam.undeclaredScope = lam.sharedScope = true;
        return lam;
      };
      if (!f.guard) {
        comprehension = f.source;
      } else {
        comprehension = mkMCall(f.source, "filter", [mkLam(Block.wrap([new Return(f.guard)]))]);
      }
      return new ES5For(comprehension, f.name, f.body);
    };

    return UseES5MethodsInsteadOfForLoops;

  })(Transformer);

  ES5For = (function(_super) {
    __extends(ES5For, _super);

    function ES5For(loopSource, name, body) {
      this.loopSource = loopSource;
      this.forBody = new Code([new Param(name)], Block.wrap([body]), 'boundfunc');
      this.forBody.undeclaredScope = this.forBody.sharedScope = true;
      ES5For.__super__.constructor.call(this, new Value(loopSource, [new Access(new Literal("map"))]), [this.forBody]);
    }

    ES5For.prototype.compileNode = function(o) {
      if (o.level !== LEVEL_TOP) {
        return ES5For.__super__.compileNode.apply(this, arguments);
      }
      return new Call(new Value(this.loopSource, [new Access(new Literal("forEach"))]), [this.forBody]).compileNode(o);
    };

    return ES5For;

  })(Call);

  exports.toSAST = toSAST = apply([UseES5MethodsInsteadOfForLoops]);

}).call(this);

/*
//@ sourceMappingURL=transformer.map
*/


text:
<?xml version="1.0"?>
<OWASPZAPReport version="Dev Build" generated="Tue, 22 Jun 2021 15:11:26">

		<site name="http://example.com" host="example.com" port="80" ssl="false">
			<alerts>

					<alertitem>
						<pluginid>1</pluginid>
						<alertRef>1</alertRef>
						<alert>XSS</alert>
						<name>XSS</name>
						<riskcode>3</riskcode>
						<confidence>2</confidence>
						<riskdesc>!reports.report.risk.3! (!reports.report.confidence.2!)</riskdesc>
						<confidencedesc>!reports.report.confidence.2!</confidencedesc>
						<desc>
XSS Description
</desc>
						<instances>

								<instance>
									<uri>http://example.com/example_3</uri>
									<method>GET</method>
									<param>Test Param</param>
									<attack>Test "Attack\"</attack>
									<evidence>Test
Evidence</evidence>
								</instance>

						</instances>
						<count>1</count>
						<solution>
Test Solution
</solution>
						<otherinfo>
Test 'Other\
</otherinfo>
						<reference>
Test Reference
</reference>
						<cweid>123</cweid>
						<wascid>456</wascid>
						<sourceid>0</sourceid>
					</alertitem>

			</alerts>
		</site>

</OWASPZAPReport>


text:
package goapp

import (
	"bytes"
	"io/ioutil"
	"os"
	"text/template"
)

// helper function to load a configuration file as template,
// and replace {{ env 'ENV_VARIABLE' }} with the variable from
// the environnement
func LoadConfigurationFromFile(path string) (string, error) {
	data, err := ioutil.ReadFile(path)

	PanicOnError(err)

	return LoadConfigurationFromString(string(data[:]))
}

// helper function to load a configuration string as template,
// and replace {{ env 'ENV_VARIABLE' }} with the variable from
// the environnement
func LoadConfigurationFromString(data string) (string, error) {
	var err error

	t := template.New("config")
	t.Funcs(map[string]interface{}{
		"env": os.Getenv,
	})
	_, err = t.Parse(data)

	PanicOnError(err)

	b := bytes.NewBuffer([]byte{})

	err = t.Execute(b, nil)

	PanicOnError(err)

	return b.String(), nil
}