/**
 *******************************************************************************************************
 * This function will get a batch of records from the Aeropike DB.
 *
 * @param err                   as_error object
 * @param self                  AerospikeClient object
 * @param py_keys               The list of keys
 * @param batch_policy_p        as_policy_batch object
 *
 * Returns the record if key exists otherwise NULL.
 *******************************************************************************************************
 */
static PyObject * batch_select_aerospike_batch_get(as_error *err, AerospikeClient * self, PyObject *py_keys, as_policy_batch * batch_policy_p, char **filter_bins, Py_ssize_t bins_size)
{
    PyObject * py_recs = NULL;

    as_batch batch;
    bool batch_initialised = false;

    // Convert python keys list to as_key ** and add it to as_batch.keys
    // keys can be specified in PyList or PyTuple
    if ( py_keys != NULL && PyList_Check(py_keys) ) {
        Py_ssize_t size = PyList_Size(py_keys);

        py_recs = PyList_New(size);
        as_batch_init(&batch, size);

        // Batch object initialised
        batch_initialised = true;

        for ( int i = 0; i < size; i++ ) {

            PyObject * py_key = PyList_GetItem(py_keys, i);

            if ( !PyTuple_Check(py_key) ) {
                as_error_update(err, AEROSPIKE_ERR_PARAM, "Key should be a tuple.");
                goto CLEANUP;
            }

            pyobject_to_key(err, py_key, as_batch_keyat(&batch, i));

            if ( err->code != AEROSPIKE_OK ) {
                goto CLEANUP;
            }
        }
    }
    else if ( py_keys != NULL && PyTuple_Check(py_keys) ) {
        Py_ssize_t size = PyTuple_Size(py_keys);

        py_recs = PyList_New(size);
        as_batch_init(&batch, size);
        // Batch object initialised
        batch_initialised = true;

        for ( int i = 0; i < size; i++ ) {
            PyObject * py_key = PyTuple_GetItem(py_keys, i);

            if ( !PyTuple_Check(py_key) ) {
                as_error_update(err, AEROSPIKE_ERR_PARAM, "Key should be a tuple.");
                goto CLEANUP;
            }

            pyobject_to_key(err, py_key, as_batch_keyat(&batch, i));

            if ( err->code != AEROSPIKE_OK ) {
                goto CLEANUP;
            }
        }
    }
    else {
        as_error_update(err, AEROSPIKE_ERR_PARAM, "Keys should be specified as a list or tuple.");
        goto CLEANUP;
    }

    // Invoke C-client API
    aerospike_batch_get_bins(self->as, err, batch_policy_p,
                             &batch, (const char **) filter_bins, bins_size,
                             (aerospike_batch_read_callback) batch_select_cb,
                             py_recs);

CLEANUP:
    if (batch_initialised == true) {
        // We should destroy batch object as we are using 'as_batch_init' for initialisation
        // Also, pyobject_to_key is soing strdup() in case of Unicode. So, object destruction
        // is necessary.
        as_batch_destroy(&batch);
    }

    return py_recs;
}
示例#2
0
static PyObject *
partial_new(PyTypeObject *type, PyObject *args, PyObject *kw)
{
    PyObject *func, *pargs, *nargs, *pkw;
    partialobject *pto;

    if (PyTuple_GET_SIZE(args) < 1) {
        PyErr_SetString(PyExc_TypeError,
                        "type 'partial' takes at least one argument");
        return NULL;
    }

    pargs = pkw = NULL;
    func = PyTuple_GET_ITEM(args, 0);
    if (Py_TYPE(func) == &partial_type && type == &partial_type) {
        partialobject *part = (partialobject *)func;
        if (part->dict == NULL) {
            pargs = part->args;
            pkw = part->kw;
            func = part->fn;
            assert(PyTuple_Check(pargs));
            assert(PyDict_Check(pkw));
        }
    }
    if (!PyCallable_Check(func)) {
        PyErr_SetString(PyExc_TypeError,
                        "the first argument must be callable");
        return NULL;
    }

    /* create partialobject structure */
    pto = (partialobject *)type->tp_alloc(type, 0);
    if (pto == NULL)
        return NULL;

    pto->fn = func;
    Py_INCREF(func);

    nargs = PyTuple_GetSlice(args, 1, PY_SSIZE_T_MAX);
    if (nargs == NULL) {
        Py_DECREF(pto);
        return NULL;
    }
    if (pargs == NULL) {
        pto->args = nargs;
    }
    else {
        pto->args = PySequence_Concat(pargs, nargs);
        Py_DECREF(nargs);
        if (pto->args == NULL) {
            Py_DECREF(pto);
            return NULL;
        }
        assert(PyTuple_Check(pto->args));
    }

    if (pkw == NULL || PyDict_GET_SIZE(pkw) == 0) {
        if (kw == NULL) {
            pto->kw = PyDict_New();
        }
        else if (Py_REFCNT(kw) == 1) {
            Py_INCREF(kw);
            pto->kw = kw;
        }
        else {
            pto->kw = PyDict_Copy(kw);
        }
    }
    else {
        pto->kw = PyDict_Copy(pkw);
        if (kw != NULL && pto->kw != NULL) {
            if (PyDict_Merge(pto->kw, kw, 1) != 0) {
                Py_DECREF(pto);
                return NULL;
            }
        }
    }
    if (pto->kw == NULL) {
        Py_DECREF(pto);
        return NULL;
    }

    pto->use_fastcall = _PyObject_HasFastCall(func);

    return (PyObject *)pto;
}
PyObject * dataconv_WriteFromOutTuple(PyObject *self, PyObject *args)
{
	PyObject *obArgTypes;
	PyObject *obArgType;
	PyObject *obRetValues;
	PyObject *obPtr;
	PyObject *obOutValue;
	VARTYPE vtArgType;
	BYTE *pbArgs;
	BYTE *pbArg;
	Py_ssize_t cArgs;
	UINT uiIndirectionLevel = 0;
	Py_ssize_t i;
	
	if (!PyArg_ParseTuple(args, "OOO:WriteFromOutTuple", &obRetValues, &obArgTypes, &obPtr))
		return NULL;

	pbArgs = (BYTE *)PyLong_AsVoidPtr(obPtr);
	assert(pbArgs);
	if (!pbArgs)
		return NULL;

	// Nothing to do, oh darn.
	if (obRetValues == Py_None || obArgTypes == Py_None)
	{
		Py_INCREF(Py_None);
		return Py_None;
	}

	if (!PyTuple_Check(obArgTypes))
	{
		PyErr_SetString(PyExc_TypeError, "OLE type description - expecting a tuple");
		return NULL;
	}

	cArgs = PyTuple_Size(obArgTypes);
	if (!PyTuple_Check(obRetValues) && (UINT)PyTuple_Size(obRetValues) != cArgs)
	{
		PyErr_Format(PyExc_TypeError, "Expecting a tuple of length %d or None.", cArgs);
		return NULL;
	}
	
	for(i = 0 ; i < cArgs; i++)
	{
		obArgType = PyTuple_GET_ITEM(PyTuple_GET_ITEM(obArgTypes, i), 0);
		vtArgType = (VARTYPE)PyInt_AS_LONG(obArgType);


		// The following types aren't supported:
		// SAFEARRAY *: This requires support for SAFEARRAYs as a
		//              Python extensions type so we can update the SAFEARRAY
		//              in place.
		// VT_LPWSTR:   This just hasn't been written yet.
		// VT_LPSTR:    This just hasn't been written yet.
		// VT_LPWSTR | VT_BYREF:
		// VT_LPSTR  | VT_BYREF:
		//              These can't be supported since we don't know the correct
		//              memory allocation policy.

		// Find the start of the argument.
		pbArg = pbArgs + PyInt_AS_LONG(PyTuple_GET_ITEM(PyTuple_GET_ITEM(obArgTypes, i), 1));
		obOutValue = PyTuple_GET_ITEM(obRetValues, i);
	
		if (vtArgType & VT_ARRAY)
		{
			VARENUM rawVT = (VARENUM)(vtArgType & VT_TYPEMASK);
			if (vtArgType & VT_BYREF)
			{
				SAFEARRAY **ppsa = *(SAFEARRAY ***)pbArg;
				SAFEARRAY *psa;
				if (!VALID_BYREF_MISSING(obOutValue))
				{
					if (!PyCom_SAFEARRAYFromPyObject(obOutValue, ppsa, rawVT))
					{
						goto Error;
					}
				}
				else
				{
					SAFEARRAYBOUND rgsabound[1];
					rgsabound[0].lLbound = 0;
					rgsabound[0].cElements = 1;
					psa = SafeArrayCreate(rawVT, 1, rgsabound);
					*ppsa = psa;
				}
			}
			else
			{
				// We can't convert this in place... Ack...
				PyErr_SetString(
					PyExc_TypeError,
					"Inplace SAFEARRAY mucking isn't allowed, doh!");
				goto Error;
				
				SAFEARRAY *psa = *(SAFEARRAY **)pbArg;
				// Here we're updating an existing SafeArray.
				// so we need to handle it very carefully....
				SafeArrayDestroy(psa);
				if (!PyCom_SAFEARRAYFromPyObject(obOutValue, &psa, rawVT))
					return NULL;
			}
		}
			
		// All done with safe array handling.

		PyObject *obUse = NULL;

		switch (vtArgType) {
		case VT_VARIANT | VT_BYREF:
		{
			VARIANT *pvar = *(VARIANT **)pbArg;
			VariantClear(pvar);
			if (!VALID_BYREF_MISSING(obOutValue)) {
				PyCom_VariantFromPyObject(obOutValue, pvar);
			}
			else
			{
				V_VT(pvar) = VT_NULL;
			}
			break;
		}
		case VT_BSTR:
		{
			// This is the normal "BSTR" case, we can't
			// allocate a new BSTR we have to back patch the one
			// thats already there...
			BSTR bstr = *(BSTR *)pbArg;
			BSTR bstrT;
			UINT cch = SysStringLen(bstr);
			if ( PyString_Check(obOutValue) || PyUnicode_Check(obOutValue) )
			{
				if ( !PyWinObject_AsBstr(obOutValue, &bstrT) )
				{
					goto Error;
				}
			}
			else
			{
				// Use str(object) instead!
				obUse = PyObject_Str(obOutValue);
				if (obUse == NULL)
				{
					goto Error;
				}
				if ( !PyWinObject_AsBstr(obUse, &bstrT) )
				{
					goto Error;
				}
			}
			
			if (SysStringLen(bstrT) > cch)
			{
				PyErr_Format(
					PyExc_ValueError,
					"Return value[%d] with type BSTR was "
					"longer than the input value: %d",
					i,
					cch);
				goto Error;
			}
				
			// Ok, now we know theres enough room in the source BSTR to
			// modify the sucker in place.
			wcscpy(bstr, bstrT);

			// Free the temp BSTR.
			SysFreeString(bstrT);
			break;
		}
		case VT_BSTR | VT_BYREF:
		{
			BSTR *pbstr = *(BSTR **)pbArg;
			BSTR bstrT = NULL;
			SysFreeString(*pbstr);

			*pbstr = NULL;
			
			if ( PyString_Check(obOutValue) || PyUnicode_Check(obOutValue) )
			{
				if ( !PyWinObject_AsBstr(obOutValue, &bstrT) )
				{
					goto Error;
				}
			}
			else
			{
				// Use str(object) instead!
				obUse = PyObject_Str(obOutValue);
				if (obUse == NULL)
				{
					goto Error;
				}
				if (!PyWinObject_AsBstr(obUse, &bstrT) )
				{
					goto Error;
				}
			}
			*pbstr = bstrT;
			break;
		}
		case VT_ERROR | VT_BYREF:
		case VT_HRESULT | VT_BYREF:
		case VT_I4 | VT_BYREF:
		{
			INT *pi = *(INT **)pbArg;
			obUse = PyNumber_Int(obOutValue);
			if (obUse == NULL)
			{
				goto Error;
			}
			*pi = PyInt_AsLong(obUse);
			if (*pi == (UINT)-1 && PyErr_Occurred())
				goto Error;
			break;
		}
		case VT_UI4 | VT_BYREF:
		{
			UINT *pui = *(UINT **)pbArg;
			// special care here as we could be > sys.maxint,
			// in which case we must work with longs.
			// Avoiding PyInt_AsUnsignedLongMask as it doesn't
			// exist in 2.2.
			if (PyLong_Check(obOutValue)) {
				*pui = PyLong_AsUnsignedLong(obOutValue);
			} else {
				// just do the generic "number" thing.
				obUse = PyNumber_Int(obOutValue);
				if (obUse == NULL)
				{
					goto Error;
				}
				*pui = (UINT)PyInt_AsLong(obUse);
			}
			if (*pui == (UINT)-1 && PyErr_Occurred())
				goto Error;
			break;
		}
		case VT_I2 | VT_BYREF:
		{
			short *ps = *(short **)pbArg;
			obUse = PyNumber_Int(obOutValue);
			if (obUse == NULL)
			{
				goto Error;
			}
			*ps = (short)PyInt_AsLong(obUse);
			if (*ps == (UINT)-1 && PyErr_Occurred())
				goto Error;
			break;
		}
		case VT_UI2 | VT_BYREF:
		{
			unsigned short *pus = *(unsigned short **)pbArg;
			obUse = PyNumber_Int(obOutValue);
			if (obUse == NULL)
			{
				goto Error;
			}
			*pus = (unsigned short)PyInt_AsLong(obUse);
			if (*pus == (UINT)-1 && PyErr_Occurred())
				goto Error;
			break;
		}
		case VT_I1 | VT_BYREF:
		{
			signed char *pb = *(signed char **)pbArg;
			obUse = PyNumber_Int(obOutValue);
			if (obUse == NULL)
			{
				goto Error;
			}
			*pb = (signed char)PyInt_AsLong(obUse);
			if (*pb == (UINT)-1 && PyErr_Occurred())
				goto Error;
			break;
		}
		case VT_UI1 | VT_BYREF:
		{
			BYTE *pb = *(BYTE **)pbArg;
			BYTE *pbOutBuffer = NULL;
			if (PyString_Check(obOutValue))
			{
				pbOutBuffer = (BYTE *)PyString_AS_STRING(obOutValue);
				Py_ssize_t cb = PyString_GET_SIZE(obOutValue);
				memcpy(pb, pbOutBuffer, cb);
			}
			// keep this after string check since string can act as buffers
			else if (obOutValue->ob_type->tp_as_buffer)
			{
				DWORD cb;
				if (!PyWinObject_AsReadBuffer(obOutValue, (void **)&pbOutBuffer, &cb))
					goto Error;
				memcpy(pb, pbOutBuffer, cb);
			}
			else
			{
				obUse = PyNumber_Int(obOutValue);
				if (obUse == NULL)
				{
					goto Error;
				}
				*pb = (BYTE)PyInt_AsLong(obUse);
				if (*pb == (UINT)-1 && PyErr_Occurred())
					goto Error;
			}
			break;
		}
		case VT_BOOL | VT_BYREF:
		{
			VARIANT_BOOL *pbool = *(VARIANT_BOOL **)pbArg;
			obUse = PyNumber_Int(obOutValue);
			if (obUse == NULL)
			{
				goto Error;
			}
			*pbool = PyInt_AsLong(obUse) ? VARIANT_TRUE : VARIANT_FALSE;
			if (*pbool == (UINT)-1 && PyErr_Occurred())
				goto Error;
			break;
		}
		case VT_R8 | VT_BYREF:
		{
			double *pdbl = *(double **)pbArg;
			obUse = PyNumber_Float(obOutValue);
			if (obUse == NULL)
			{
				goto Error;
			}
			*pdbl = PyFloat_AsDouble(obUse);
			break;
		}
		case VT_R4 | VT_BYREF:
		{
			float *pfloat = *(float **)pbArg;
			obUse = PyNumber_Float(obOutValue);
			if (obUse == NULL)
			{
				goto Error;
			}
			*pfloat = (float)PyFloat_AsDouble(obUse);
			break;
		}
		case VT_DISPATCH | VT_BYREF:
		{
			PyObject *obIID = PyTuple_GET_ITEM(PyTuple_GET_ITEM(obArgTypes, i), 3);
			IID iid = IID_IDispatch;
			if (obIID != NULL && obIID!=Py_None)
				PyWinObject_AsIID(obIID, &iid);
			IDispatch **pdisp = *(IDispatch ***)pbArg;
			if (!PyCom_InterfaceFromPyInstanceOrObject(
				obOutValue,
				iid,
				(void **)pdisp,
				TRUE))
			{
				goto Error;
			}
			// COM Reference added by InterfaceFrom...
			break;
		}
		case VT_UNKNOWN | VT_BYREF:
		{
			PyObject *obIID = PyTuple_GET_ITEM(PyTuple_GET_ITEM(obArgTypes, i), 3);
			IID iid = IID_IUnknown;
			if (obIID != NULL && obIID!=Py_None)
				PyWinObject_AsIID(obIID, &iid);
			IUnknown **punk = *(IUnknown ***)pbArg;
			if (!PyCom_InterfaceFromPyInstanceOrObject(
				obOutValue,
				iid,
				(void **)punk, TRUE))
			{
				goto Error;
			}
			// COM Reference added by InterfaceFrom...
			break;
		}
		case VT_DATE | VT_BYREF:
		{
			DATE *pdbl = *(DATE **)pbArg;
			if ( !PyWinObject_AsDATE(obOutValue, pdbl) )
			{
				goto Error;
			}
			break;
		}
		case VT_CY | VT_BYREF:
		{
			CY *pcy = *(CY **)pbArg;
			if (!PyObject_AsCurrency(obOutValue, pcy))
				goto Error;
			break;
		}
		case VT_I8 | VT_BYREF:
		{
			LARGE_INTEGER *pi64 = *(LARGE_INTEGER **)pbArg;
			if (!PyWinObject_AsLARGE_INTEGER(obOutValue, pi64))
			{
				goto Error;
			}
			break;
		}
		case VT_UI8 | VT_BYREF:
		{
			ULARGE_INTEGER *pui64 = *(ULARGE_INTEGER **)pbArg;
			if (!PyWinObject_AsULARGE_INTEGER(obOutValue, pui64))
			{
				goto Error;
			}
			break;
		}
		default:
			// could try default, but this error indicates we need to
			// beef up the VARIANT support, rather than default.
			PyErr_Format(PyExc_TypeError, "The VARIANT type is unknown (0x%x).",
			             vtArgType);
			goto Error;
		}
		
		Py_XDECREF(obUse);
	}

	Py_INCREF(Py_None);
	return Py_None;
Error:
	return NULL;
}
示例#4
0
文件: pygtype.c 项目: nzjrs/pygobject
/**
 * pyg_flags_get_value:
 * @flag_type: the GType of the flag.
 * @obj: a Python object representing the flag value
 * @val: a pointer to the location to store the integer representation of the flag.
 *
 * Converts a Python object to the integer equivalent.  The conversion
 * will depend on the type of the Python object.  If the object is an
 * integer, it is passed through directly.  If it is a string, it will
 * be treated as a full or short flag name as defined in the GType.
 * If it is a tuple, then the items are treated as strings and ORed
 * together.
 *
 * Returns: 0 on success or -1 on failure
 */
gint
pyg_flags_get_value(GType flag_type, PyObject *obj, gint *val)
{
    GFlagsClass *fclass = NULL;
    gint res = -1;

    g_return_val_if_fail(val != NULL, -1);
    if (!obj) {
	*val = 0;
	res = 0;
    } else if (PYGLIB_PyLong_Check(obj)) {
	*val = PYGLIB_PyLong_AsLong(obj);
	res = 0;
    } else if (PyLong_Check(obj)) {
        *val = PyLong_AsLongLong(obj);
        res = 0;
    } else if (PYGLIB_PyUnicode_Check(obj)) {
	GFlagsValue *info;
	char *str = PYGLIB_PyUnicode_AsString(obj);

	if (flag_type != G_TYPE_NONE)
	    fclass = G_FLAGS_CLASS(g_type_class_ref(flag_type));
	else {
	    PyErr_SetString(PyExc_TypeError, "could not convert string to flag because there is no GType associated to look up the value");
	    res = -1;
	}
	info = g_flags_get_value_by_name(fclass, str);
	g_type_class_unref(fclass);

	if (!info)
	    info = g_flags_get_value_by_nick(fclass, str);
	if (info) {
	    *val = info->value;
	    res = 0;
	} else {
	    PyErr_SetString(PyExc_TypeError, "could not convert string");
	    res = -1;
	}
    } else if (PyTuple_Check(obj)) {
	int i, len;

	len = PyTuple_Size(obj);
	*val = 0;
	res = 0;

	if (flag_type != G_TYPE_NONE)
	    fclass = G_FLAGS_CLASS(g_type_class_ref(flag_type));
	else {
	    PyErr_SetString(PyExc_TypeError, "could not convert string to flag because there is no GType associated to look up the value");
	    res = -1;
	}

	for (i = 0; i < len; i++) {
	    PyObject *item = PyTuple_GetItem(obj, i);
	    char *str = PYGLIB_PyUnicode_AsString(item);
	    GFlagsValue *info = g_flags_get_value_by_name(fclass, str);

	    if (!info)
		info = g_flags_get_value_by_nick(fclass, str);
	    if (info) {
		*val |= info->value;
	    } else {
		PyErr_SetString(PyExc_TypeError, "could not convert string");
		res = -1;
		break;
	    }
	}
	g_type_class_unref(fclass);
    } else {
	PyErr_SetString(PyExc_TypeError,
			"flag values must be strings, ints, longs, or tuples");
	res = -1;
    }
    return res;
}
示例#5
0
static PyObject *swi_swi(PyObject *self,PyObject *args)
{ PyObject *name,*format,*result,*v;
  int swino,carry,rno=0,j,n;
  char *swiname,*fmt,*outfmt;
  _kernel_swi_regs r;
  PyBlockObject *ao;
  if(args==NULL||!PyTuple_Check(args)||(n=PyTuple_Size(args))<2)
  { PyErr_BadArgument(); return NULL;}
  name=PyTuple_GetItem(args,0);
  if(!PyArg_Parse(name,"i",&swino))
  { PyErr_Clear();
    if(!PyArg_Parse(name,"s",&swiname)) return NULL;
    e=xos_swi_number_from_string(swiname,&swino);
    if(e) return swi_oserror();
  }
  format=PyTuple_GetItem(args,1);
  if(!PyArg_Parse(format,"s",&fmt)) return NULL;
  j=2;
  for(;;fmt++)
  { switch(*fmt)
    { case '.': rno++;continue;
      case ';':case 0: goto swicall;
      case '0':case '1':case '2':case '3':case '4':
      case '5':case '6':case '7':case '8':case '9':
        r.r[rno++]=*fmt-'0';continue;
      case '-':r.r[rno++]=-1;continue;
    }
    if(j>=n) return swi_error("Too few arguments");
    v=PyTuple_GetItem(args,j++);
    switch(*fmt)
    { case 'i':if(!PyArg_Parse(v,"i",&r.r[rno])) return NULL;
               break;
      case 's':if(!PyArg_Parse(v,"s",(char**)(&r.r[rno]))) return NULL;
               break;
      case 'b':if(!PyArg_Parse(v,"O",(PyObject**)&ao)) return NULL;
               if(!PyBlock_Check(v)) return swi_error("Not a block");
               r.r[rno]=(int)(ao->block);
               break;
      case 'e':if(!PyArg_Parse(v,"O",(PyObject**)&ao)) return NULL;
               if(!PyBlock_Check(v)) return swi_error("Not a block");
               r.r[rno]=(int)(ao->block)+ao->length;
               break;
      default:return swi_error("Odd format character");
    }
    rno++;
  }
  swicall:e=(os_error*)_kernel_swi_c(swino,&r,&r,&carry);
  if(e) return swi_oserror();
  if(*fmt==0) { Py_INCREF(Py_None);return Py_None;}
  n=0;
  for(outfmt=++fmt;*outfmt;outfmt++)  switch(*outfmt)
  { case 'i':case 's':case '*':n++;break;
    case '.':break;
    default:return swi_error("Odd format character");
  }
  if(n==0) { Py_INCREF(Py_None);return Py_None;}
  if(n!=1)
  { result=PyTuple_New(n);
    if(!result) return NULL;
  }
  rno=0;j=0;
  for(;*fmt;fmt++)
  {  switch(*fmt)
    { case 'i':v=PyInt_FromLong((long)r.r[rno++]); break;
      case 's':v=PyString_FromString((char*)(r.r[rno++])); break;
      case '.':rno++; continue;
      case '*':v=PyInt_FromLong((long)carry); break;
    }
    if(!v) goto fail;
    if(n==1) return v;
    PyTuple_SetItem(result,j,v);
    j++;
  }
  return result;
  fail:Py_DECREF(result);return 0;
}
示例#6
0
NUITKA_MAY_BE_UNUSED static void RAISE_EXCEPTION_WITH_TYPE( PyObject **exception_type, PyObject **exception_value, PyTracebackObject **exception_tb )
{
    *exception_value = NULL;
    *exception_tb = NULL;

#if PYTHON_VERSION < 300
    // Next, repeatedly, replace a tuple exception with its first item
    while( PyTuple_Check( *exception_type ) && PyTuple_Size( *exception_type ) > 0 )
    {
         PyObject *tmp = *exception_type;
         *exception_type = PyTuple_GET_ITEM( *exception_type, 0 );
         Py_INCREF( *exception_type );
         Py_DECREF( tmp );
    }
#endif

    if ( PyExceptionClass_Check( *exception_type ) )
    {
        NORMALIZE_EXCEPTION( exception_type, exception_value, exception_tb );
#if PYTHON_VERSION >= 270
        if (unlikely( !PyExceptionInstance_Check( *exception_value ) ))
        {
            PyErr_Format(
                PyExc_TypeError,
                "calling %s() should have returned an instance of BaseException, not '%s'",
                ((PyTypeObject *)*exception_type)->tp_name,
                Py_TYPE( *exception_value )->tp_name
            );

            Py_DECREF( *exception_type );
            Py_DECREF( *exception_value );

            FETCH_ERROR_OCCURRED( exception_type, exception_value, exception_tb );
            return;
        }
#endif

#if PYTHON_VERSION >= 300
        CHAIN_EXCEPTION( *exception_value );
#endif
        return;
    }
    else if ( PyExceptionInstance_Check( *exception_type ) )
    {
        *exception_value = *exception_type;
        *exception_type = PyExceptionInstance_Class( *exception_type );
        Py_INCREF( *exception_type );

#if PYTHON_VERSION >= 300
        CHAIN_EXCEPTION( *exception_value );

        // TODO: Ever true?
        if ( *exception_tb )
        {
            PyTracebackObject *prev = (PyTracebackObject *)PyException_GetTraceback( *exception_value );

            if ( prev != NULL )
            {
                assert( (*exception_tb)->tb_next == NULL );
                (*exception_tb)->tb_next = prev;
            }

            PyException_SetTraceback( *exception_value, (PyObject *)(*exception_tb ? *exception_tb : (PyTracebackObject *)Py_None ) );
        }

        *exception_tb = (PyTracebackObject *)PyException_GetTraceback( *exception_value );
#endif

        return;
    }
    else
    {
        Py_DECREF( *exception_type );

        PyErr_Format( PyExc_TypeError, WRONG_EXCEPTION_TYPE_ERROR_MESSAGE, Py_TYPE( *exception_type )->tp_name );
        FETCH_ERROR_OCCURRED( exception_type, exception_value, exception_tb );
        return;
    }
}
示例#7
0
static PyObject *Py_GenericFilter(PyObject *obj, PyObject *args)
{
    PyArrayObject *input = NULL, *output = NULL, *footprint = NULL;
    PyObject *fnc = NULL, *extra_arguments = NULL, *extra_keywords = NULL;
    void *func = NULL, *data = NULL;
    NI_PythonCallbackData cbdata;
    int mode;
    PyArray_Dims origin;
    double cval;
    ccallback_t callback;
    static ccallback_signature_t callback_signatures[] = {
        {"int (double *, intptr_t, double *, void *)"},
        {"int (double *, npy_intp, double *, void *)"},
#if NPY_SIZEOF_INTP == NPY_SIZEOF_SHORT
        {"int (double *, short, double *, void *)"},
#endif
#if NPY_SIZEOF_INTP == NPY_SIZEOF_INT
        {"int (double *, int, double *, void *)"},
#endif
#if NPY_SIZEOF_INTP == NPY_SIZEOF_LONG
        {"int (double *, long, double *, void *)"},
#endif
#if NPY_SIZEOF_INTP == NPY_SIZEOF_LONGLONG
        {"int (double *, long long, double *, void *)"},
#endif
        {NULL}
    };

    callback.py_function = NULL;
    callback.c_function = NULL;

    if (!PyArg_ParseTuple(args, "O&OO&O&idO&OO",
                          NI_ObjectToInputArray, &input,
                          &fnc,
                          NI_ObjectToInputArray, &footprint,
                          NI_ObjectToOutputArray, &output,
                          &mode, &cval,
                          PyArray_IntpConverter, &origin,
                          &extra_arguments, &extra_keywords)) {
        goto exit;
    }
    if (!_validate_origin(input, origin)) {
        goto exit;
    }
    if (!PyTuple_Check(extra_arguments)) {
        PyErr_SetString(PyExc_RuntimeError, "extra_arguments must be a tuple");
        goto exit;
    }
    if (!PyDict_Check(extra_keywords)) {
        PyErr_SetString(PyExc_RuntimeError,
                                        "extra_keywords must be a dictionary");
        goto exit;
    }
    if (PyCapsule_CheckExact(fnc) && PyCapsule_GetName(fnc) == NULL) {
        func = PyCapsule_GetPointer(fnc, NULL);
        data = PyCapsule_GetContext(fnc);
#if PY_VERSION_HEX < 0x03000000
    } else if (PyCObject_Check(fnc)) {
        /* 'Legacy' low-level callable on Py2 */
        func = PyCObject_AsVoidPtr(fnc);
        data = PyCObject_GetDesc(fnc);
#endif
    } else {
        int ret;

        ret = ccallback_prepare(&callback, callback_signatures, fnc, CCALLBACK_DEFAULTS);
        if (ret == -1) {
            goto exit;
        }

        if (callback.py_function != NULL) {
            cbdata.extra_arguments = extra_arguments;
            cbdata.extra_keywords = extra_keywords;
            callback.info_p = (void*)&cbdata;
            func = Py_FilterFunc;
            data = (void*)&callback;
        }
        else {
            func = callback.c_function;
            data = callback.user_data;
        }
    }

    NI_GenericFilter(input, func, data, footprint, output, (NI_ExtendMode)mode,
                     cval, origin.ptr);
    #ifdef HAVE_WRITEBACKIFCOPY
        PyArray_ResolveWritebackIfCopy(output);
    #endif

exit:
    if (callback.py_function != NULL || callback.c_function != NULL) {
        ccallback_release(&callback);
    }
    Py_XDECREF(input);
    Py_XDECREF(output);
    Py_XDECREF(footprint);
    PyDimMem_FREE(origin.ptr);
    return PyErr_Occurred() ? NULL : Py_BuildValue("");
}
示例#8
0
/* Return:
   NULL for exception;
   some object not equal to NotImplemented if it is implemented
     (this latter object may not be a Boolean).
*/
PyObject *
PyObject_RichCompare(PyObject *v, PyObject *w, int op)
{
	PyObject *res;

	assert(Py_LT <= op && op <= Py_GE);

	compare_nesting++;
	if (compare_nesting > NESTING_LIMIT &&
		(v->ob_type->tp_as_mapping
		 || (v->ob_type->tp_as_sequence
		     && !PyString_Check(v)
		     && !PyTuple_Check(v)))) {

		/* try to detect circular data structures */
		PyObject *token = check_recursion(v, w, op);
		if (token == NULL) {
			res = NULL;
			goto Done;
		}
		else if (token == Py_None) {
			/* already comparing these objects with this operator.
			   assume they're equal until shown otherwise */
			if (op == Py_EQ)
				res = Py_True;
			else if (op == Py_NE)
				res = Py_False;
			else {
				PyErr_SetString(PyExc_ValueError,
					"can't order recursive values");
				res = NULL;
			}
			Py_XINCREF(res);
		}
		else {
			res = do_richcmp(v, w, op);
			delete_token(token);
		}
		goto Done;
	}

	/* No nesting extremism.
	   If the types are equal, and not old-style instances, try to
	   get out cheap (don't bother with coercions etc.). */
	if (v->ob_type == w->ob_type && !PyInstance_Check(v)) {
		cmpfunc fcmp;
		richcmpfunc frich = RICHCOMPARE(v->ob_type);
		/* If the type has richcmp, try it first.  try_rich_compare
		   tries it two-sided, which is not needed since we've a
		   single type only. */
		if (frich != NULL) {
			res = (*frich)(v, w, op);
			if (res != Py_NotImplemented)
				goto Done;
			Py_DECREF(res);
		}
		/* No richcmp, or this particular richmp not implemented.
		   Try 3-way cmp. */
		fcmp = v->ob_type->tp_compare;
		if (fcmp != NULL) {
			int c = (*fcmp)(v, w);
			if (c < 0 && PyErr_Occurred()) {
				res = NULL;
				goto Done;
			}
			res = convert_3way_to_object(op, c);
			goto Done;
		}
	}

	/* Fast path not taken, or couldn't deliver a useful result. */
	res = do_richcmp(v, w, op);
Done:
	compare_nesting--;
	return res;
}
示例#9
0
PyObject *_PyCodec_Lookup(const char *encoding)
{
    PyInterpreterState *interp;
    PyObject *result, *args = NULL, *v;
    Py_ssize_t i, len;

    if (encoding == NULL) {
        PyErr_BadArgument();
        goto onError;
    }

    interp = PyThreadState_GET()->interp;
    if (interp->codec_search_path == NULL && _PyCodecRegistry_Init())
        goto onError;

    /* Convert the encoding to a normalized Python string: all
       characters are converted to lower case, spaces and hyphens are
       replaced with underscores. */
    v = normalizestring(encoding);
    if (v == NULL)
        goto onError;
    PyUnicode_InternInPlace(&v);

    /* First, try to lookup the name in the registry dictionary */
    result = PyDict_GetItem(interp->codec_search_cache, v);
    if (result != NULL) {
        Py_INCREF(result);
        Py_DECREF(v);
        return result;
    }

    /* Next, scan the search functions in order of registration */
    args = PyTuple_New(1);
    if (args == NULL)
        goto onError;
    PyTuple_SET_ITEM(args,0,v);

    len = PyList_Size(interp->codec_search_path);
    if (len < 0)
        goto onError;
    if (len == 0) {
        PyErr_SetString(PyExc_LookupError,
                        "no codec search functions registered: "
                        "can't find encoding");
        goto onError;
    }

    for (i = 0; i < len; i++) {
        PyObject *func;

        func = PyList_GetItem(interp->codec_search_path, i);
        if (func == NULL)
            goto onError;
        result = PyEval_CallObject(func, args);
        if (result == NULL)
            goto onError;
        if (result == Py_None) {
            Py_DECREF(result);
            continue;
        }
        if (!PyTuple_Check(result) || PyTuple_GET_SIZE(result) != 4) {
            PyErr_SetString(PyExc_TypeError,
                            "codec search functions must return 4-tuples");
            Py_DECREF(result);
            goto onError;
        }
        break;
    }
    if (i == len) {
        /* XXX Perhaps we should cache misses too ? */
        PyErr_Format(PyExc_LookupError,
                     "unknown encoding: %s", encoding);
        goto onError;
    }

    /* Cache and return the result */
    if (PyDict_SetItem(interp->codec_search_cache, v, result) < 0) {
        Py_DECREF(result);
        goto onError;
    }
    Py_DECREF(args);
    return result;

 onError:
    Py_XDECREF(args);
    return NULL;
}
示例#10
0
static PyObject *
tuplerichcompare(PyObject *v, PyObject *w, int op)
{
    PyTupleObject *vt, *wt;
    Py_ssize_t i;
    Py_ssize_t vlen, wlen;

    if (!PyTuple_Check(v) || !PyTuple_Check(w))
        Py_RETURN_NOTIMPLEMENTED;

    vt = (PyTupleObject *)v;
    wt = (PyTupleObject *)w;

    vlen = Py_SIZE(vt);
    wlen = Py_SIZE(wt);

    /* Note:  the corresponding code for lists has an "early out" test
     * here when op is EQ or NE and the lengths differ.  That pays there,
     * but Tim was unable to find any real code where EQ/NE tuple
     * compares don't have the same length, so testing for it here would
     * have cost without benefit.
     */

    /* Search for the first index where items are different.
     * Note that because tuples are immutable, it's safe to reuse
     * vlen and wlen across the comparison calls.
     */
    for (i = 0; i < vlen && i < wlen; i++) {
        int k = PyObject_RichCompareBool(vt->ob_item[i],
                                         wt->ob_item[i], Py_EQ);
        if (k < 0)
            return NULL;
        if (!k)
            break;
    }

    if (i >= vlen || i >= wlen) {
        /* No more items to compare -- compare sizes */
        int cmp;
        PyObject *res;
        switch (op) {
        case Py_LT: cmp = vlen <  wlen; break;
        case Py_LE: cmp = vlen <= wlen; break;
        case Py_EQ: cmp = vlen == wlen; break;
        case Py_NE: cmp = vlen != wlen; break;
        case Py_GT: cmp = vlen >  wlen; break;
        case Py_GE: cmp = vlen >= wlen; break;
        default: return NULL; /* cannot happen */
        }
        if (cmp)
            res = Py_True;
        else
            res = Py_False;
        Py_INCREF(res);
        return res;
    }

    /* We have an item that differs -- shortcuts for EQ/NE */
    if (op == Py_EQ) {
        Py_INCREF(Py_False);
        return Py_False;
    }
    if (op == Py_NE) {
        Py_INCREF(Py_True);
        return Py_True;
    }

    /* Compare the final item again using the proper operator */
    return PyObject_RichCompare(vt->ob_item[i], wt->ob_item[i], op);
}
示例#11
0
// The type init slot.
static int pyqtSignal_init(PyObject *self, PyObject *args, PyObject *kwd_args)
{
    qpycore_pyqtSignal *ps = (qpycore_pyqtSignal *)self;

    // Get the keyword arguments.
    PyObject *name_obj = 0;
    const char *name = 0;

    if (kwd_args)
    {
        SIP_SSIZE_T pos = 0;
        PyObject *key, *value;

        while (PyDict_Next(kwd_args, &pos, &key, &value))
        {
#if PY_MAJOR_VERSION >= 3
            if (PyUnicode_CompareWithASCIIString(key, "name") != 0)
            {
                PyErr_Format(PyExc_TypeError,
                        "pyqtSignal() got an unexpected keyword argument '%U'",
                        key);

                Py_XDECREF(name_obj);
                return -1;
            }
#else
            Q_ASSERT(PyString_Check(key));

            if (qstrcmp(PyString_AS_STRING(key), "name") != 0)
            {
                PyErr_Format(PyExc_TypeError,
                        "pyqtSignal() got an unexpected keyword argument '%s'",
                        PyString_AS_STRING(key));

                Py_XDECREF(name_obj);
                return -1;
            }
#endif

            name_obj = value;
            name = sipString_AsASCIIString(&name_obj);

            if (!name)
                return -1;
        }
    }

    // If there is at least one argument and it is a sequence then assume all
    // arguments are sequences.  Unfortunately a string is also a sequence so
    // check for tuples and lists explicitly.
    if (PyTuple_GET_SIZE(args) > 0 && (PyTuple_Check(PyTuple_GET_ITEM(args, 0)) || PyList_Check(PyTuple_GET_ITEM(args, 0))))
    {
        for (SIP_SSIZE_T i = 0; i < PyTuple_GET_SIZE(args); ++i)
        {
            PyObject *types = PySequence_Tuple(PyTuple_GET_ITEM(args, i));

            if (!types)
            {
                PyErr_SetString(PyExc_TypeError,
                        "pyqtSignal() argument expected to be sequence of types");

                if (name)
                {
                    Py_DECREF(name_obj);
                }

                return -1;
            }

            int rc;

            if (i == 0)
            {
                // The first is the default.
                rc = init_signal_from_types(ps, name, types);
            }
            else
            {
                qpycore_pyqtSignal *overload = (qpycore_pyqtSignal *)PyType_GenericNew(&qpycore_pyqtSignal_Type, 0, 0);

                if (!overload)
                {
                    rc = -1;
                }
                else if ((rc = init_signal_from_types(overload, name, types)) < 0)
                {
                    Py_DECREF((PyObject *)overload);
                }
                else
                {
                    overload->default_signal = ps;
                    append_overload(overload);
                }
            }

            Py_DECREF(types);

            if (rc < 0)
            {
                if (name)
                {
                    Py_DECREF(name_obj);
                }

                return -1;
            }
        }
    }
    else if (init_signal_from_types(ps, name, args) < 0)
    {
        if (name)
        {
            Py_DECREF(name_obj);
        }

        return -1;
    }

    if (name)
    {
        Py_DECREF(name_obj);
    }

    return 0;
}
示例#12
0
/*
    Returns new reference that must be decref'd.
*/
static PyObject*
obexserver_notifynewrequest(OBEXServer *self, obex_object_t *obj, int obex_cmd, int *respcode)
{
    PyObject *resp;
    PyObject *respheaders;
    PyObject *tmpfileobj;

    PyObject *reqheaders;
    int nonhdrdata_len;
    PyObject *nonhdrdata_obj;
    uint8_t *nonhdrdata;

    DEBUG("%s() cmd=%d\n", __func__, obex_cmd);

    if (self->notifiednewrequest) {
        DEBUG("\tAlready called cb_newrequest");
        return NULL;
    }

    if (self->cb_newrequest == NULL) {  /* shouldn't happen */
        obexserver_errorstr(self, PyExc_IOError, "cb_newrequest is NULL");
        return NULL;
    }

    reqheaders = lightblueobex_readheaders(self->obex, obj);
    if (reqheaders == NULL) {
        obexserver_errorstr(self, PyExc_IOError,
                            "error reading request headers");
        return NULL;
    }

    nonhdrdata_len = OBEX_ObjectGetNonHdrData(obj, &nonhdrdata);
    if (nonhdrdata_len < 0) {
        obexserver_errorstr(self, PyExc_IOError,
                            "error reading non-header data");
        return NULL;
    }

    nonhdrdata_obj = PyBuffer_FromMemory(nonhdrdata,
                                         (Py_ssize_t)nonhdrdata_len);
    if (nonhdrdata_obj == NULL) {
        obexserver_errorstr(self, PyExc_IOError,
                            "error reading non-header buffer");
        return NULL;
    }

    resp = PyObject_CallFunction(self->cb_newrequest, "iOOO",
                                 obex_cmd, reqheaders, nonhdrdata_obj,
                                 (self->hasbodydata ? Py_True : Py_False));
    Py_DECREF(nonhdrdata_obj);
    self->notifiednewrequest = 1;

    if (resp == NULL) {
        DEBUG("\terror calling cb_newrequest\n");
        obexserver_errorfetch(self);
        return NULL;
    }

    if ( !PyTuple_Check(resp) || PyTuple_Size(resp) < 3 ||
            !PyInt_Check(PyTuple_GetItem(resp, 0)) ||
            !PyDict_Check(PyTuple_GetItem(resp, 1)) ) {
        obexserver_errorstr(self, PyExc_TypeError,
                            "callback must return (int, dict, fileobj | None) tuple");
        return NULL;
    }

    tmpfileobj = PyTuple_GetItem(resp, 2);

    if (obex_cmd == OBEX_CMD_PUT && self->hasbodydata &&
            !PyObject_HasAttrString(tmpfileobj, "write")) {
        obexserver_errorstr(self, PyExc_ValueError,
                            "specified file object does not have 'write' method for Put request");
        return NULL;
    }

    if (obex_cmd == OBEX_CMD_GET &&
            !PyObject_HasAttrString(tmpfileobj, "read")) {
        obexserver_errorstr(self, PyExc_ValueError,
                            "specified file object does not have 'read' method for Get request");
        return NULL;
    }

    *respcode = PyInt_AsLong(PyTuple_GetItem(resp, 0));
    if (PyErr_Occurred()) {
        PyErr_Clear();
        obexserver_errorstr(self, PyExc_IOError,
                            "error reading returned response code");
        return NULL;
    }

    Py_XDECREF(self->fileobj);
    Py_INCREF(tmpfileobj);
    self->fileobj = tmpfileobj;

    respheaders = PyTuple_GetItem(resp, 1);
    Py_INCREF(respheaders);
    return respheaders;
}
示例#13
0
int pygrpc_produce_op(PyObject *op, grpc_op *result) {
  static const int OP_TUPLE_SIZE = 6;
  static const int STATUS_TUPLE_SIZE = 2;
  static const int TYPE_INDEX = 0;
  static const int INITIAL_METADATA_INDEX = 1;
  static const int TRAILING_METADATA_INDEX = 2;
  static const int MESSAGE_INDEX = 3;
  static const int STATUS_INDEX = 4;
  static const int STATUS_CODE_INDEX = 0;
  static const int STATUS_DETAILS_INDEX = 1;
  static const int WRITE_FLAGS_INDEX = 5;
  int type;
  Py_ssize_t message_size;
  char *message;
  char *status_details;
  gpr_slice message_slice;
  grpc_op c_op;
  if (!PyTuple_Check(op)) {
    PyErr_SetString(PyExc_TypeError, "expected tuple op");
    return 0;
  }
  if (PyTuple_Size(op) != OP_TUPLE_SIZE) {
    char *buf;
    gpr_asprintf(&buf, "expected tuple op of length %d", OP_TUPLE_SIZE);
    PyErr_SetString(PyExc_ValueError, buf);
    gpr_free(buf);
    return 0;
  }
  type = PyInt_AsLong(PyTuple_GET_ITEM(op, TYPE_INDEX));
  if (PyErr_Occurred()) {
    return 0;
  }
  c_op.op = type;
  c_op.flags = PyInt_AsLong(PyTuple_GET_ITEM(op, WRITE_FLAGS_INDEX));
  if (PyErr_Occurred()) {
    return 0;
  }
  switch (type) {
  case GRPC_OP_SEND_INITIAL_METADATA:
    if (!pygrpc_cast_pyseq_to_send_metadata(
            PyTuple_GetItem(op, INITIAL_METADATA_INDEX),
            &c_op.data.send_initial_metadata.metadata,
            &c_op.data.send_initial_metadata.count)) {
      return 0;
    }
    break;
  case GRPC_OP_SEND_MESSAGE:
    PyString_AsStringAndSize(
        PyTuple_GET_ITEM(op, MESSAGE_INDEX), &message, &message_size);
    message_slice = gpr_slice_from_copied_buffer(message, message_size);
    c_op.data.send_message = grpc_raw_byte_buffer_create(&message_slice, 1);
    gpr_slice_unref(message_slice);
    break;
  case GRPC_OP_SEND_CLOSE_FROM_CLIENT:
    /* Don't need to fill in any other fields. */
    break;
  case GRPC_OP_SEND_STATUS_FROM_SERVER:
    if (!pygrpc_cast_pyseq_to_send_metadata(
            PyTuple_GetItem(op, TRAILING_METADATA_INDEX),
            &c_op.data.send_status_from_server.trailing_metadata,
            &c_op.data.send_status_from_server.trailing_metadata_count)) {
      return 0;
    }
    if (!PyTuple_Check(PyTuple_GET_ITEM(op, STATUS_INDEX))) {
      char *buf;
      gpr_asprintf(&buf, "expected tuple status in op of length %d",
                   STATUS_TUPLE_SIZE);
      PyErr_SetString(PyExc_ValueError, buf);
      gpr_free(buf);
      return 0;
    }
    c_op.data.send_status_from_server.status = PyInt_AsLong(
        PyTuple_GET_ITEM(PyTuple_GET_ITEM(op, STATUS_INDEX), STATUS_CODE_INDEX));
    status_details = PyString_AsString(
        PyTuple_GET_ITEM(PyTuple_GET_ITEM(op, STATUS_INDEX), STATUS_DETAILS_INDEX));
    if (PyErr_Occurred()) {
      return 0;
    }
    c_op.data.send_status_from_server.status_details =
        gpr_malloc(strlen(status_details) + 1);
    strcpy((char *)c_op.data.send_status_from_server.status_details,
           status_details);
    break;
  case GRPC_OP_RECV_INITIAL_METADATA:
    c_op.data.recv_initial_metadata = gpr_malloc(sizeof(grpc_metadata_array));
    grpc_metadata_array_init(c_op.data.recv_initial_metadata);
    break;
  case GRPC_OP_RECV_MESSAGE:
    c_op.data.recv_message = gpr_malloc(sizeof(grpc_byte_buffer *));
    break;
  case GRPC_OP_RECV_STATUS_ON_CLIENT:
    c_op.data.recv_status_on_client.trailing_metadata =
        gpr_malloc(sizeof(grpc_metadata_array));
    grpc_metadata_array_init(c_op.data.recv_status_on_client.trailing_metadata);
    c_op.data.recv_status_on_client.status =
        gpr_malloc(sizeof(grpc_status_code *));
    c_op.data.recv_status_on_client.status_details =
        gpr_malloc(sizeof(char *));
    *c_op.data.recv_status_on_client.status_details = NULL;
    c_op.data.recv_status_on_client.status_details_capacity =
        gpr_malloc(sizeof(size_t));
    *c_op.data.recv_status_on_client.status_details_capacity = 0;
    break;
  case GRPC_OP_RECV_CLOSE_ON_SERVER:
    c_op.data.recv_close_on_server.cancelled = gpr_malloc(sizeof(int));
    break;
  default:
    return 0;
  }
  *result = c_op;
  return 1;
}
/**
 *********************************************************************
 * This function will invoke aerospike_batch_get_bins to get filtered
 * bins from all the records in a batches.
 *
 * @param self                    AerospikeClient object
 * @param py_keys                 List of keys passed on by user
 * @param py_bins                 List of filter bins passed on by user
 * @param py_policy               User specified Policy dictionary
 *
 *********************************************************************
 **/
static
PyObject * AerospikeClient_Select_Many_Invoke(
    AerospikeClient * self,
    PyObject * py_keys, PyObject * py_bins, PyObject * py_policy)
{
    // Python Return Value
    PyObject * py_recs = NULL;

    // Aerospike Client Arguments
    as_error err;
    as_policy_batch policy;
    as_policy_batch * batch_policy_p = NULL;
    Py_ssize_t bins_size = 0;
    char **filter_bins = NULL;
    bool has_batch_index = false;

    // Unicode object's pool
    UnicodePyObjects u_objs;
    u_objs.size = 0;
    int i = 0;

    // Initialize error
    as_error_init(&err);

    if (!self || !self->as) {
        as_error_update(&err, AEROSPIKE_ERR_PARAM, "Invalid aerospike object");
        goto CLEANUP;
    }

    if (!self->is_conn_16) {
        as_error_update(&err, AEROSPIKE_ERR_CLUSTER, "No connection to aerospike cluster");
        goto CLEANUP;
    }

    // Check the type of bins and get it's size
    // i.e. number of bins provided
    if (py_bins != NULL && PyList_Check(py_bins)) {
        bins_size    = PyList_Size(py_bins);
    }
    else if (py_bins != NULL && PyTuple_Check(py_bins)) {
        bins_size    = PyTuple_Size(py_bins);
    }
    else {
        as_error_update(&err, AEROSPIKE_ERR_PARAM, "Filter bins should be specified as a list or tuple.");
        goto CLEANUP;
    }

    filter_bins = (char **)malloc(sizeof(long int) * bins_size);

    for (i = 0; i < bins_size; i++) {
        PyObject *py_bin = NULL;
        if(PyList_Check(py_bins)) {
            py_bin = PyList_GetItem(py_bins, i);
        }
        if(PyTuple_Check(py_bins)) {
            py_bin = PyTuple_GetItem(py_bins, i);
        }
        if (PyUnicode_Check(py_bin)) {
            // Store the unicode object into a pool
            // It is DECREFed at later stages
            // So, no need of DECREF here.
            filter_bins[i] = PyStr_AsString(
                                 store_unicode_bins(&u_objs, PyUnicode_AsUTF8String(py_bin)));
        }
        else if (PyStr_Check(py_bin)) {
            filter_bins[i]    = PyStr_AsString(py_bin);
        }
        else {
            as_error_update(&err, AEROSPIKE_ERR_PARAM, "Bin name should be a string or unicode string.");
            goto CLEANUP;
        }
    }

    // Convert python policy object to as_policy_batch
    pyobject_to_policy_batch(&err, py_policy, &policy, &batch_policy_p,
                             &self->as->config.policies.batch);
    if ( err.code != AEROSPIKE_OK ) {
        goto CLEANUP;
    }

    has_batch_index = aerospike_has_batch_index(self->as);
    if (has_batch_index) {
        py_recs = batch_select_aerospike_batch_read(&err, self, py_keys, batch_policy_p, filter_bins, bins_size);
    } else {
        py_recs = batch_select_aerospike_batch_get(&err, self, py_keys, batch_policy_p, filter_bins, bins_size);
    }

CLEANUP:

    if (filter_bins != NULL) {
        free(filter_bins);
    }

    // DECREFed all the unicode objects stored in Pool
    for ( i = 0; i< u_objs.size; i++) {
        Py_DECREF(u_objs.ob[i]);
    }

    if ( err.code != AEROSPIKE_OK ) {
        PyObject * py_err = NULL;
        error_to_pyobject(&err, &py_err);
        PyObject *exception_type = raise_exception(&err);
        if(PyObject_HasAttrString(exception_type, "key")) {
            PyObject_SetAttrString(exception_type, "key", py_keys);
        }
        if(PyObject_HasAttrString(exception_type, "bin")) {
            PyObject_SetAttrString(exception_type, "bin", Py_None);
        }
        PyErr_SetObject(exception_type, py_err);
        Py_DECREF(py_err);
        return NULL;
    }
    return py_recs;
}
示例#15
0
void Object_beginTypeContext (JSOBJ _obj, JSONTypeContext *tc)
{
  PyObject *obj, *exc, *toFunc;
  TypeContext *pc;
  PRINTMARK();
  if (!_obj) {
    tc->type = JT_INVALID;
    return;
  }

  obj = (PyObject*) _obj;

  tc->prv = PyObject_Malloc(sizeof(TypeContext));
  pc = (TypeContext *) tc->prv;
  if (!pc)
  {
    tc->type = JT_INVALID;
    PyErr_NoMemory();
    return;
  }
  pc->newObj = NULL;
  pc->dictObj = NULL;
  pc->itemValue = NULL;
  pc->itemName = NULL;
  pc->attrList = NULL;
  pc->index = 0;
  pc->size = 0;
  pc->longValue = 0;

  if (PyIter_Check(obj))
  {
    PRINTMARK();
    goto ISITERABLE;
  }

  if (PyBool_Check(obj))
  {
    PRINTMARK();
    tc->type = (obj == Py_True) ? JT_TRUE : JT_FALSE;
    return;
  }
  else
  if (PyLong_Check(obj))
  {
    PRINTMARK();
    pc->PyTypeToJSON = PyLongToINT64;
    tc->type = JT_LONG;
    GET_TC(tc)->longValue = PyLong_AsLongLong(obj);

    exc = PyErr_Occurred();

    if (exc && PyErr_ExceptionMatches(PyExc_OverflowError))
    {
      PRINTMARK();
      goto INVALID;
    }

    return;
  }
  else
  if (PyInt_Check(obj))
  {
    PRINTMARK();
#ifdef _LP64
    pc->PyTypeToJSON = PyIntToINT64; tc->type = JT_LONG;
#else
    pc->PyTypeToJSON = PyIntToINT32; tc->type = JT_INT;
#endif
    return;
  }
  else
  if (PyString_Check(obj))
  {
    PRINTMARK();
    pc->PyTypeToJSON = PyStringToUTF8; tc->type = JT_UTF8;
    return;
  }
  else
  if (PyUnicode_Check(obj))
  {
    PRINTMARK();
    pc->PyTypeToJSON = PyUnicodeToUTF8; tc->type = JT_UTF8;
    return;
  }
  else
  if (PyFloat_Check(obj) || (type_decimal && PyObject_IsInstance(obj, type_decimal)))
  {
    PRINTMARK();
    pc->PyTypeToJSON = PyFloatToDOUBLE; tc->type = JT_DOUBLE;
    return;
  }
  else
  if (PyDateTime_Check(obj))
  {
    PRINTMARK();
    pc->PyTypeToJSON = PyDateTimeToINT64; tc->type = JT_LONG;
    return;
  }
  else
  if (PyDate_Check(obj))
  {
    PRINTMARK();
    pc->PyTypeToJSON = PyDateToINT64; tc->type = JT_LONG;
    return;
  }
  else
  if (obj == Py_None)
  {
    PRINTMARK();
    tc->type = JT_NULL;
    return;
  }

ISITERABLE:
  if (PyDict_Check(obj))
  {
    PRINTMARK();
    tc->type = JT_OBJECT;
    pc->iterBegin = Dict_iterBegin;
    pc->iterEnd = Dict_iterEnd;
    pc->iterNext = Dict_iterNext;
    pc->iterGetValue = Dict_iterGetValue;
    pc->iterGetName = Dict_iterGetName;
    pc->dictObj = obj;
    Py_INCREF(obj);
    return;
  }
  else
  if (PyList_Check(obj))
  {
    PRINTMARK();
    tc->type = JT_ARRAY;
    pc->iterBegin = List_iterBegin;
    pc->iterEnd = List_iterEnd;
    pc->iterNext = List_iterNext;
    pc->iterGetValue = List_iterGetValue;
    pc->iterGetName = List_iterGetName;
    return;
  }
  else
  if (PyTuple_Check(obj))
  {
    PRINTMARK();
    tc->type = JT_ARRAY;
    pc->iterBegin = Tuple_iterBegin;
    pc->iterEnd = Tuple_iterEnd;
    pc->iterNext = Tuple_iterNext;
    pc->iterGetValue = Tuple_iterGetValue;
    pc->iterGetName = Tuple_iterGetName;
    return;
  }
  else
  if (PyAnySet_Check(obj))
  {
    PRINTMARK();
    tc->type = JT_ARRAY;
    pc->iterBegin = Iter_iterBegin;
    pc->iterEnd = Iter_iterEnd;
    pc->iterNext = Iter_iterNext;
    pc->iterGetValue = Iter_iterGetValue;
    pc->iterGetName = Iter_iterGetName;
    return;
  }

  toFunc = PyObject_GetAttrString(obj, "toDict");

  if (toFunc)
  {
    PyObject* tuple = PyTuple_New(0);
    PyObject* toDictResult = PyObject_Call(toFunc, tuple, NULL);
    Py_DECREF(tuple);
    Py_DECREF(toFunc);

    if (toDictResult == NULL)
    {
      PyErr_Clear();
      tc->type = JT_NULL;
      return;
    }

    if (!PyDict_Check(toDictResult))
    {
      Py_DECREF(toDictResult);
      tc->type = JT_NULL;
      return;
    }

    PRINTMARK();
    tc->type = JT_OBJECT;
    pc->iterBegin = Dict_iterBegin;
    pc->iterEnd = Dict_iterEnd;
    pc->iterNext = Dict_iterNext;
    pc->iterGetValue = Dict_iterGetValue;
    pc->iterGetName = Dict_iterGetName;
    pc->dictObj = toDictResult;
    return;
  }

  PyErr_Clear();

  toFunc = PyObject_GetAttrString(obj, "toJson");

  if (toFunc)
  {
    PyObject* tuple = PyTuple_New(0);
    PyObject* toJsonResult = PyObject_Call(toFunc, tuple, NULL);
    Py_DECREF(tuple);
    Py_DECREF(toFunc);

    if (toJsonResult == NULL)
    {
      PyErr_Clear();
      tc->type = JT_NULL;
      return;
    }

    if (PyString_Check(toJsonResult))
    {
      PRINTMARK();
      pc->PyTypeToJSON = NewObjPyStringToUTF8;
      pc->newObj = toJsonResult;
      tc->type = JT_JSON;
      return;
    }
    else
    if (PyUnicode_Check(toJsonResult))
    {
      PRINTMARK();
      pc->PyTypeToJSON = NewObjPyUnicodeToUTF8;
      pc->newObj = toJsonResult;
      tc->type = JT_JSON;
      return;
    }
    else
    {
      Py_DECREF(toJsonResult);
      tc->type = JT_NULL;
      return;
    }
  }

  PyErr_Clear();

  PRINTMARK();
  tc->type = JT_OBJECT;
  pc->iterBegin = Dir_iterBegin;
  pc->iterEnd = Dir_iterEnd;
  pc->iterNext = Dir_iterNext;
  pc->iterGetValue = Dir_iterGetValue;
  pc->iterGetName = Dir_iterGetName;
  return;

INVALID:
  tc->type = JT_INVALID;
  PyObject_Free(tc->prv);
  tc->prv = NULL;
  return;
}
示例#16
0
文件: errors.c 项目: ARK4579/cpython
/* Used in many places to normalize a raised exception, including in
   eval_code2(), do_raise(), and PyErr_Print()

   XXX: should PyErr_NormalizeException() also call
            PyException_SetTraceback() with the resulting value and tb?
*/
void
PyErr_NormalizeException(PyObject **exc, PyObject **val, PyObject **tb)
{
    PyObject *type = *exc;
    PyObject *value = *val;
    PyObject *inclass = NULL;
    PyObject *initial_tb = NULL;
    PyThreadState *tstate = NULL;

    if (type == NULL) {
        /* There was no exception, so nothing to do. */
        return;
    }

    /* If PyErr_SetNone() was used, the value will have been actually
       set to NULL.
    */
    if (!value) {
        value = Py_None;
        Py_INCREF(value);
    }

    if (PyExceptionInstance_Check(value))
        inclass = PyExceptionInstance_Class(value);

    /* Normalize the exception so that if the type is a class, the
       value will be an instance.
    */
    if (PyExceptionClass_Check(type)) {
        int is_subclass;
        if (inclass) {
            is_subclass = PyObject_IsSubclass(inclass, type);
            if (is_subclass < 0)
                goto finally;
        }
        else
            is_subclass = 0;

        /* if the value was not an instance, or is not an instance
           whose class is (or is derived from) type, then use the
           value as an argument to instantiation of the type
           class.
        */
        if (!inclass || !is_subclass) {
            PyObject *args, *res;

            if (value == Py_None)
                args = PyTuple_New(0);
            else if (PyTuple_Check(value)) {
                Py_INCREF(value);
                args = value;
            }
            else
                args = PyTuple_Pack(1, value);

            if (args == NULL)
                goto finally;
            res = PyEval_CallObject(type, args);
            Py_DECREF(args);
            if (res == NULL)
                goto finally;
            Py_DECREF(value);
            value = res;
        }
        /* if the class of the instance doesn't exactly match the
           class of the type, believe the instance
        */
        else if (inclass != type) {
            Py_DECREF(type);
            type = inclass;
            Py_INCREF(type);
        }
    }
    *exc = type;
    *val = value;
    return;
finally:
    Py_DECREF(type);
    Py_DECREF(value);
    /* If the new exception doesn't set a traceback and the old
       exception had a traceback, use the old traceback for the
       new exception.  It's better than nothing.
    */
    initial_tb = *tb;
    PyErr_Fetch(exc, val, tb);
    if (initial_tb != NULL) {
        if (*tb == NULL)
            *tb = initial_tb;
        else
            Py_DECREF(initial_tb);
    }
    /* normalize recursively */
    tstate = PyThreadState_GET();
    if (++tstate->recursion_depth > Py_GetRecursionLimit()) {
        --tstate->recursion_depth;
        /* throw away the old exception and use the recursion error instead */
        Py_INCREF(PyExc_RecursionError);
        Py_SETREF(*exc, PyExc_RecursionError);
        Py_INCREF(PyExc_RecursionErrorInst);
        Py_SETREF(*val, PyExc_RecursionErrorInst);
        /* just keeping the old traceback */
        return;
    }
    PyErr_NormalizeException(exc, val, tb);
    --tstate->recursion_depth;
}
示例#17
0
NUITKA_MAY_BE_UNUSED static inline void RAISE_EXCEPTION_WITH_TRACEBACK( PyObject **exception_type, PyObject **exception_value, PyTracebackObject **exception_tb )
{
    CHECK_OBJECT( *exception_type );
    CHECK_OBJECT( *exception_value );

    if ( *exception_tb == (PyTracebackObject *)Py_None )
    {
        Py_DECREF( *exception_tb );
        *exception_tb = NULL;
    }

    // Non-empty tuple exceptions are the first element.
    while (unlikely( PyTuple_Check( *exception_type ) && PyTuple_Size( *exception_type ) > 0 ))
    {
        *exception_type = PyTuple_GET_ITEM( *exception_type, 0 );
    }

    if ( PyExceptionClass_Check( *exception_type ) )
    {
        NORMALIZE_EXCEPTION( exception_type, exception_value, exception_tb );
#if PYTHON_VERSION >= 270
        if (unlikely( !PyExceptionInstance_Check( *exception_value ) ))
        {
            PyErr_Format(
                PyExc_TypeError,
                "calling %s() should have returned an instance of BaseException, not '%s'",
                ((PyTypeObject *)*exception_type)->tp_name,
                Py_TYPE( *exception_value )->tp_name
            );

            Py_DECREF( *exception_type );
            Py_XDECREF( *exception_value );
            Py_XDECREF( *exception_tb );

            FETCH_ERROR_OCCURRED( exception_type, exception_value, exception_tb );
        }
#endif

        return;
    }
    else if ( PyExceptionInstance_Check( *exception_type ) )
    {
        if (unlikely( *exception_value != NULL && *exception_value != Py_None ))
        {
            PyErr_Format(
                PyExc_TypeError,
                "instance exception may not have a separate value"
            );

            Py_DECREF( *exception_type );
            Py_XDECREF( *exception_value );
            Py_XDECREF( *exception_tb );

            FETCH_ERROR_OCCURRED( exception_type, exception_value, exception_tb );

            return;
        }

        // The type is rather a value, so we are overriding it here.
        *exception_value = *exception_type;
        *exception_type = PyExceptionInstance_Class( *exception_type );
        Py_INCREF( *exception_type );

        return;
    }
    else
    {
        PyErr_Format( PyExc_TypeError, WRONG_EXCEPTION_TYPE_ERROR_MESSAGE, Py_TYPE( exception_type )->tp_name );
        FETCH_ERROR_OCCURRED( exception_type, exception_value, exception_tb );
        return;
    }
}
示例#18
0
文件: errors.c 项目: ARK4579/cpython
void
PyErr_SetObject(PyObject *exception, PyObject *value)
{
    PyThreadState *tstate = PyThreadState_GET();
    PyObject *exc_value;
    PyObject *tb = NULL;

    if (exception != NULL &&
        !PyExceptionClass_Check(exception)) {
        PyErr_Format(PyExc_SystemError,
                     "exception %R not a BaseException subclass",
                     exception);
        return;
    }
    Py_XINCREF(value);
    exc_value = tstate->exc_value;
    if (exc_value != NULL && exc_value != Py_None) {
        /* Implicit exception chaining */
        Py_INCREF(exc_value);
        if (value == NULL || !PyExceptionInstance_Check(value)) {
            /* We must normalize the value right now */
            PyObject *args, *fixed_value;

            /* Issue #23571: PyEval_CallObject() must not be called with an
               exception set */
            PyErr_Clear();

            if (value == NULL || value == Py_None)
                args = PyTuple_New(0);
            else if (PyTuple_Check(value)) {
                Py_INCREF(value);
                args = value;
            }
            else
                args = PyTuple_Pack(1, value);
            fixed_value = args ?
                PyEval_CallObject(exception, args) : NULL;
            Py_XDECREF(args);
            Py_XDECREF(value);
            if (fixed_value == NULL)
                return;
            value = fixed_value;
        }
        /* Avoid reference cycles through the context chain.
           This is O(chain length) but context chains are
           usually very short. Sensitive readers may try
           to inline the call to PyException_GetContext. */
        if (exc_value != value) {
            PyObject *o = exc_value, *context;
            while ((context = PyException_GetContext(o))) {
                Py_DECREF(context);
                if (context == value) {
                    PyException_SetContext(o, NULL);
                    break;
                }
                o = context;
            }
            PyException_SetContext(value, exc_value);
        } else {
            Py_DECREF(exc_value);
        }
    }
    if (value != NULL && PyExceptionInstance_Check(value))
        tb = PyException_GetTraceback(value);
    Py_XINCREF(exception);
    PyErr_Restore(exception, value, tb);
}
示例#19
0
/**
 *******************************************************************************************************
 * Callback for as_info_foreach().
 *
 * @param err                   The as_error to be populated by the function
 *                              with the encountered error if any.
 * @param node                  The current as_node object for which the
 *                              callback is fired by c client.
 * @param req                   The info request string.
 * @param res                   The info response string for current node.
 * @pram udata                  The callback udata containing the host_lookup
 *                              array and the return zval to be populated with
 *                              an entry for current node's info response with
 *                              the node's ID as the key.
 *
 * Returns true if callback is successful, Otherwise false.
 *******************************************************************************************************
 */
static bool AerospikeClient_Info_each(as_error * err, const as_node * node, const char * req, char * res, void * udata)
{
	PyObject * py_err = NULL;
	PyObject * py_ustr = NULL;
	PyObject * py_out = NULL;
	foreach_callback_info_udata* udata_ptr = (foreach_callback_info_udata *) udata;
	struct sockaddr_in* addr = NULL;


	if ( err && err->code != AEROSPIKE_OK ) {
		as_error_update(err, err->code, NULL);
        goto CLEANUP;
	}
	else if ( res != NULL ) {
		char * out = strchr(res,'\t');
		if ( out != NULL ) {
			out++;
			py_out = PyString_FromString(out);
		}
		else {
			py_out = PyString_FromString(res);
		}
	}

	if ( py_err == NULL ) {
		Py_INCREF(Py_None);
		py_err = Py_None;
	}

	if ( py_out == NULL ) {
		Py_INCREF(Py_None);
		py_out = Py_None;
	}

	PyObject * py_res = PyTuple_New(2);
	PyTuple_SetItem(py_res, 0, py_err);
	PyTuple_SetItem(py_res, 1, py_out);

	if(udata_ptr->host_lookup_p) {
		PyObject * py_hosts = (PyObject *)udata_ptr->host_lookup_p;
			if ( py_hosts && PyList_Check(py_hosts) ) {
				addr = as_node_get_address((as_node *)node);
				int size = (int) PyList_Size(py_hosts);
				for ( int i = 0; i < size && i < AS_CONFIG_HOSTS_SIZE; i++ ) {
					char * host_addr = NULL;
					int port = -1;
					PyObject * py_host = PyList_GetItem(py_hosts, i);
					if ( PyTuple_Check(py_host) && PyTuple_Size(py_host) == 2 ) {
						PyObject * py_addr = PyTuple_GetItem(py_host,0);
						PyObject * py_port = PyTuple_GetItem(py_host,1);
						if (PyUnicode_Check(py_addr)) {
							py_ustr = PyUnicode_AsUTF8String(py_addr);
							host_addr = PyString_AsString(py_ustr);
						} else if ( PyString_Check(py_addr) ) {
							host_addr = PyString_AsString(py_addr);
						} else {
							as_error_update(&udata_ptr->error, AEROSPIKE_ERR_PARAM, "Host address is of type incorrect");
							if (py_res) {
								Py_DECREF(py_res);
							}
							return false;
						}
						if ( PyInt_Check(py_port) ) {
							port = (uint16_t) PyInt_AsLong(py_port);
						}
						else if ( PyLong_Check(py_port) ) {
							port = (uint16_t) PyLong_AsLong(py_port);
						} else {
							break;
						}
						char ip_port[IP_PORT_MAX_LEN];
						inet_ntop(addr->sin_family, &(addr->sin_addr), ip_port, INET_ADDRSTRLEN);
						if( (!strcmp(host_addr,ip_port)) && (port
												== ntohs(addr->sin_port))) {
							PyObject * py_nodes = (PyObject *) udata_ptr->udata_p;
							PyDict_SetItemString(py_nodes, node->name, py_res);
						}	
					}
				}
			} else if ( !PyList_Check( py_hosts )){
				as_error_update(&udata_ptr->error, AEROSPIKE_ERR_PARAM, "Hosts should be specified in a list.");
				goto CLEANUP;
			}
	} else {
		PyObject * py_nodes = (PyObject *) udata_ptr->udata_p;
		PyDict_SetItemString(py_nodes, node->name, py_res);
	}
	Py_DECREF(py_res);
CLEANUP:
	if ( udata_ptr->error.code != AEROSPIKE_OK ) {
		PyObject * py_err = NULL;
		error_to_pyobject( &udata_ptr->error, &py_err);
		PyObject *exception_type = raise_exception(&udata_ptr->error);
		PyErr_SetObject(exception_type, py_err);
		Py_DECREF(py_err);
		return NULL;
	}
	if ( err->code != AEROSPIKE_OK ) {
		PyObject * py_err = NULL;
		error_to_pyobject(err, &py_err);
		PyObject *exception_type = raise_exception(err);
		PyErr_SetObject(exception_type, py_err);
		Py_DECREF(py_err);
		return NULL;
	}
	return true;
}
示例#20
0
static PyObject *
Text2DObject_SetTextColor(PyObject *self, PyObject *args)
{
    Text2DObjectObject *obj = (Text2DObjectObject *)self;

    int c[4];
    if(!PyArg_ParseTuple(args, "iiii", &c[0], &c[1], &c[2], &c[3]))
    {
        c[3] = 255;
        if(!PyArg_ParseTuple(args, "iii", &c[0], &c[1], &c[2]))
        {
            double dr, dg, db, da;
            if(PyArg_ParseTuple(args, "dddd", &dr, &dg, &db, &da))
            {
                c[0] = int(dr);
                c[1] = int(dg);
                c[2] = int(db);
                c[3] = int(da);
            }
            else if(PyArg_ParseTuple(args, "ddd", &dr, &dg, &db))
            {
                c[0] = int(dr);
                c[1] = int(dg);
                c[2] = int(db);
                c[3] = 255;
            }
            else
            {
                PyObject *tuple = NULL;
                if(!PyArg_ParseTuple(args, "O", &tuple))
                    return NULL;

                if(!PyTuple_Check(tuple))
                    return NULL;

                // Make sure that the tuple is the right size.
                if(PyTuple_Size(tuple) < 3 || PyTuple_Size(tuple) > 4)
                    return NULL;

                // Make sure that all elements in the tuple are ints.
                for(int i = 0; i < PyTuple_Size(tuple); ++i)
                {
                    PyObject *item = PyTuple_GET_ITEM(tuple, i);
                    if(PyInt_Check(item))
                        c[i] = int(PyInt_AS_LONG(PyTuple_GET_ITEM(tuple, i)));
                    else if(PyFloat_Check(item))
                        c[i] = int(PyFloat_AS_DOUBLE(PyTuple_GET_ITEM(tuple, i)));
                    else
                        return NULL;
                }
            }
        }
        PyErr_Clear();
    }

    // Set the textColor in the object.
    ColorAttribute ca(c[0], c[1], c[2], c[3]);
    obj->data->SetTextColor(ca);
/*CUSTOM*/
    UpdateAnnotationHelper(obj->data);

    Py_INCREF(Py_None);
    return Py_None;
}
示例#21
0
static PyObject *Py_GeometricTransform(PyObject *obj, PyObject *args)
{
    PyArrayObject *input = NULL, *output = NULL;
    PyArrayObject *coordinates = NULL, *matrix = NULL, *shift = NULL;
    PyObject *fnc = NULL, *extra_arguments = NULL, *extra_keywords = NULL;
    int mode, order;
    double cval;
    void *func = NULL, *data = NULL;
    NI_PythonCallbackData cbdata;
    ccallback_t callback;
    static ccallback_signature_t callback_signatures[] = {
        {"int (intptr_t *, double *, int, int, void *)"},
        {"int (npy_intp *, double *, int, int, void *)"},
#if NPY_SIZEOF_INTP == NPY_SIZEOF_SHORT
        {"int (short *, double *, int, int, void *)"},
#endif
#if NPY_SIZEOF_INTP == NPY_SIZEOF_INT
        {"int (int *, double *, int, int, void *)"},
#endif
#if NPY_SIZEOF_INTP == NPY_SIZEOF_LONG
        {"int (long *, double *, int, int, void *)"},
#endif
#if NPY_SIZEOF_INTP == NPY_SIZEOF_LONGLONG
        {"int (long long *, double *, int, int, void *)"},
#endif
        {NULL}
    };

    callback.py_function = NULL;
    callback.c_function = NULL;

    if (!PyArg_ParseTuple(args, "O&OO&O&O&O&iidOO",
                          NI_ObjectToInputArray, &input,
                          &fnc,
                          NI_ObjectToOptionalInputArray, &coordinates,
                          NI_ObjectToOptionalInputArray, &matrix,
                          NI_ObjectToOptionalInputArray, &shift,
                          NI_ObjectToOutputArray, &output,
                          &order, &mode, &cval,
                          &extra_arguments, &extra_keywords))
        goto exit;

    if (fnc != Py_None) {
        if (!PyTuple_Check(extra_arguments)) {
            PyErr_SetString(PyExc_RuntimeError,
                                            "extra_arguments must be a tuple");
            goto exit;
        }
        if (!PyDict_Check(extra_keywords)) {
            PyErr_SetString(PyExc_RuntimeError,
                                            "extra_keywords must be a dictionary");
            goto exit;
        }
        if (PyCapsule_CheckExact(fnc) && PyCapsule_GetName(fnc) == NULL) {
            func = PyCapsule_GetPointer(fnc, NULL);
            data = PyCapsule_GetContext(fnc);
#if PY_VERSION_HEX < 0x03000000
        } else if (PyCObject_Check(fnc)) {
            /* 'Legacy' low-level callable on Py2 */
            func = PyCObject_AsVoidPtr(fnc);
            data = PyCObject_GetDesc(fnc);
#endif
        } else {
            int ret;

            ret = ccallback_prepare(&callback, callback_signatures, fnc, CCALLBACK_DEFAULTS);
            if (ret == -1) {
                goto exit;
            }

            if (callback.py_function != NULL) {
                cbdata.extra_arguments = extra_arguments;
                cbdata.extra_keywords = extra_keywords;
                callback.info_p = (void*)&cbdata;
                func = Py_Map;
                data = (void*)&callback;
            }
            else {
                func = callback.c_function;
                data = callback.user_data;
            }
        }
    }

    NI_GeometricTransform(input, func, data, matrix, shift, coordinates,
                          output, order, (NI_ExtendMode)mode, cval);
    #ifdef HAVE_WRITEBACKIFCOPY
        PyArray_ResolveWritebackIfCopy(output);
    #endif

exit:
    if (callback.py_function != NULL || callback.c_function != NULL) {
        ccallback_release(&callback);
    }
    Py_XDECREF(input);
    Py_XDECREF(output);
    Py_XDECREF(coordinates);
    Py_XDECREF(matrix);
    Py_XDECREF(shift);
    return PyErr_Occurred() ? NULL : Py_BuildValue("");
}
示例#22
0
static PyObject *cboodle_init(PyObject *self, PyObject *args)
{
  char *devname = NULL;
  int ratewanted = 0;
  int verbose = 0;
  int ix, res;
  PyObject *extras = NULL;
  extraopt_t *opts = NULL;
  extraopt_t dummyopt = {NULL, NULL};

  if (!PyArg_ParseTuple(args, "|ziiO:init", &devname, &ratewanted, &verbose, &extras))
    return NULL;

  res = noteq_init();
  if (!res) {
    PyErr_SetString(PyExc_IOError, "unable to initialize note queue");
    return NULL;
  }

  if (extras && PyList_Check(extras)) {
    int count = PyList_Size(extras);

    opts = (extraopt_t *)malloc(sizeof(extraopt_t) * (count+1));
    if (!opts) {
      PyErr_SetString(PyExc_IOError, "unable to initialize extra options");
      return NULL;
    }

    for (ix=0; ix<count; ix++) {
      PyObject *tup = PyList_GetItem(extras, ix);
      PyObject *tkey, *tval;
      if (!tup)
	return NULL;
      if (!PyTuple_Check(tup) || PyTuple_Size(tup) != 2) {
	PyErr_SetString(PyExc_TypeError, "extraopts must be a list of 2-tuples");
	return NULL;
      }

      tkey = PyTuple_GetItem(tup, 0);
      if (!tkey)
	return NULL;
      tval = PyTuple_GetItem(tup, 1);
      if (!tval)
	return NULL;
      if (!PyString_Check(tkey) 
	|| !(tval == Py_None || PyString_Check(tval))) {
	PyErr_SetString(PyExc_TypeError, "extraopts must be (string, string) or (string, None)");
	return NULL;
      }

      opts[ix].key = PyString_AsString(tkey);
      if (tval == Py_None)
	opts[ix].val = NULL;
      else
	opts[ix].val = PyString_AsString(tval);
    }

    opts[count].key = NULL;
    opts[count].val = NULL;
  }

  res = audev_init_device(devname, ratewanted, (verbose!=0),
    (opts?opts:(&dummyopt)));
  if (!res) {
    PyErr_SetString(PyExc_IOError, "unable to initialize audio device");
    if (opts) {
      free(opts);
    }
    return NULL;
  }

  if (opts) {
    free(opts);
  }

  Py_INCREF(Py_None);
  return Py_None;
}
示例#23
0
/* The item is a new reference. */
static PyObject*
get_filter(PyObject *category, PyObject *text, Py_ssize_t lineno,
           PyObject *module, PyObject **item)
{
    PyObject *action;
    Py_ssize_t i;
    PyObject *warnings_filters;

    warnings_filters = get_warnings_attr("filters", 0);
    if (warnings_filters == NULL) {
        if (PyErr_Occurred())
            return NULL;
    }
    else {
        Py_DECREF(_filters);
        _filters = warnings_filters;
    }

    if (_filters == NULL || !PyList_Check(_filters)) {
        PyErr_SetString(PyExc_ValueError,
                        MODULE_NAME ".filters must be a list");
        return NULL;
    }

    /* _filters could change while we are iterating over it. */
    for (i = 0; i < PyList_GET_SIZE(_filters); i++) {
        PyObject *tmp_item, *action, *msg, *cat, *mod, *ln_obj;
        Py_ssize_t ln;
        int is_subclass, good_msg, good_mod;

        tmp_item = PyList_GET_ITEM(_filters, i);
        if (!PyTuple_Check(tmp_item) || PyTuple_GET_SIZE(tmp_item) != 5) {
            PyErr_Format(PyExc_ValueError,
                         MODULE_NAME ".filters item %zd isn't a 5-tuple", i);
            return NULL;
        }

        /* Python code: action, msg, cat, mod, ln = item */
        Py_INCREF(tmp_item);
        action = PyTuple_GET_ITEM(tmp_item, 0);
        msg = PyTuple_GET_ITEM(tmp_item, 1);
        cat = PyTuple_GET_ITEM(tmp_item, 2);
        mod = PyTuple_GET_ITEM(tmp_item, 3);
        ln_obj = PyTuple_GET_ITEM(tmp_item, 4);

        good_msg = check_matched(msg, text);
        if (good_msg == -1) {
            Py_DECREF(tmp_item);
            return NULL;
        }

        good_mod = check_matched(mod, module);
        if (good_mod == -1) {
            Py_DECREF(tmp_item);
            return NULL;
        }

        is_subclass = PyObject_IsSubclass(category, cat);
        if (is_subclass == -1) {
            Py_DECREF(tmp_item);
            return NULL;
        }

        ln = PyLong_AsSsize_t(ln_obj);
        if (ln == -1 && PyErr_Occurred()) {
            Py_DECREF(tmp_item);
            return NULL;
        }

        if (good_msg && is_subclass && good_mod && (ln == 0 || lineno == ln)) {
            *item = tmp_item;
            return action;
        }

        Py_DECREF(tmp_item);
    }

    action = get_default_action();
    if (action != NULL) {
        Py_INCREF(Py_None);
        *item = Py_None;
        return action;
    }

    PyErr_SetString(PyExc_ValueError,
                    MODULE_NAME ".defaultaction not found");
    return NULL;
}
示例#24
0
文件: lxc.c 项目: SethRobertson/lxc
static PyObject *
Container_start(Container *self, PyObject *args, PyObject *kwds)
{
    PyObject *useinit = NULL;
    PyObject *daemonize = NULL;
    PyObject *close_fds = NULL;

    PyObject *vargs = NULL;
    char** init_args = {NULL};

    PyObject *retval = NULL;
    int init_useinit = 0, i = 0;
    static char *kwlist[] = {"useinit", "daemonize", "close_fds",
                             "cmd", NULL};

    if (! PyArg_ParseTupleAndKeywords(args, kwds, "|OOOO", kwlist,
                                      &useinit, &daemonize, &close_fds,
                                      &vargs))
        return NULL;

    if (useinit && useinit == Py_True) {
        init_useinit = 1;
    }

    if (vargs && PyTuple_Check(vargs)) {
        init_args = convert_tuple_to_char_pointer_array(vargs);
        if (!init_args) {
            return NULL;
        }
    }

    if (close_fds && close_fds == Py_True) {
        self->container->want_close_all_fds(self->container, true);
    }
    else {
        self->container->want_close_all_fds(self->container, false);
    }

    if (!daemonize || daemonize == Py_True) {
        self->container->want_daemonize(self->container, true);
    }
    else {
        self->container->want_daemonize(self->container, false);
    }

    if (self->container->start(self->container, init_useinit, init_args))
        retval = Py_True;
    else
        retval = Py_False;

    if (vargs) {
        /* We cannot have gotten here unless vargs was given and create_args
         * was successfully allocated.
         */
        for (i = 0; i < PyTuple_GET_SIZE(vargs); i++)
            free(init_args[i]);
        free(init_args);
    }

    Py_INCREF(retval);
    return retval;
}
示例#25
0
void Object_beginTypeContext (PyObject *obj, JSONTypeContext *tc)
{
	TypeContext *pc = (TypeContext *) tc->prv;
	PyObject *toDictFunc;

	tc->prv[0] = 0;
	tc->prv[1] = 0;
	tc->prv[2] = 0;
	tc->prv[3] = 0;
	tc->prv[4] = 0;
	tc->prv[5] = 0;
	tc->prv[6] = 0;
	tc->prv[7] = 0;
	tc->prv[8] = 0;
	tc->prv[9] = 0;
	tc->prv[10] = 0;
	tc->prv[11] = 0;
	tc->prv[12] = 0;
	tc->prv[13] = 0;
	tc->prv[14] = 0;
	
	if (PyIter_Check(obj))
	{
		goto ISITERABLE;
	}

	if (PyBool_Check(obj))
	{
		PRINTMARK();
		tc->type = (obj == Py_True) ? JT_TRUE : JT_FALSE;
		return;
	}
	else
	if (PyInt_Check(obj))
	{
		PRINTMARK();
		pc->PyTypeToJSON = PyIntToINT32; tc->type = JT_INT;
		return;
	}
	else 
	if (PyLong_Check(obj))
	{
		PRINTMARK();
		pc->PyTypeToJSON = PyLongToINT64; tc->type = JT_LONG;
		return;
	}
	else
	if (PyString_Check(obj))
	{
		PRINTMARK();
		pc->PyTypeToJSON = PyStringToUTF8; tc->type = JT_UTF8;
		return;
	}
	else
	if (PyUnicode_Check(obj))
	{
		PRINTMARK();
		pc->PyTypeToJSON = PyUnicodeToUTF8; tc->type = JT_UTF8;
		return;
	}
	else
	if (PyFloat_Check(obj))
	{
		PRINTMARK();
		pc->PyTypeToJSON = PyFloatToDOUBLE; tc->type = JT_DOUBLE;
		return;
	}
	else 
	if (PyDateTime_Check(obj))
	{
		PRINTMARK();
		pc->PyTypeToJSON = PyDateTimeToINT64; tc->type = JT_LONG;
		return;
	}
	else 
	if (PyDate_Check(obj))
	{
		PRINTMARK();
		pc->PyTypeToJSON = PyDateToINT64; tc->type = JT_LONG;
		return;
	}
	else
	if (obj == Py_None)
	{
		PRINTMARK();
		tc->type = JT_NULL;
		return;
	}


ISITERABLE:

	if (PyDict_Check(obj))
	{
		PRINTMARK();
		tc->type = JT_OBJECT;
		pc->iterBegin = Dict_iterBegin;
		pc->iterEnd = Dict_iterEnd;
		pc->iterNext = Dict_iterNext;
		pc->iterGetValue = Dict_iterGetValue;
		pc->iterGetName = Dict_iterGetName;
		pc->dictObj = obj;
		Py_INCREF(obj);

		return;
	}
	else
	if (PyList_Check(obj))
	{
		PRINTMARK();
		tc->type = JT_ARRAY;
		pc->iterBegin = List_iterBegin;
		pc->iterEnd = List_iterEnd;
		pc->iterNext = List_iterNext;
		pc->iterGetValue = List_iterGetValue;
		pc->iterGetName = List_iterGetName;
		return;
	}
	else
	if (PyTuple_Check(obj))
	{
		PRINTMARK();
		tc->type = JT_ARRAY;
		pc->iterBegin = Tuple_iterBegin;
		pc->iterEnd = Tuple_iterEnd;
		pc->iterNext = Tuple_iterNext;
		pc->iterGetValue = Tuple_iterGetValue;
		pc->iterGetName = Tuple_iterGetName;
		return;
	}


	toDictFunc = PyObject_GetAttrString(obj, "toDict");

	if (toDictFunc)
	{
		PyObject* tuple = PyTuple_New(0);
		PyObject* toDictResult = PyObject_Call(toDictFunc, tuple, NULL);
		Py_DECREF(tuple);
		Py_DECREF(toDictFunc);

		if (toDictResult == NULL)
		{
			PyErr_Clear();
			tc->type = JT_NULL;
			return;
		}

		if (!PyDict_Check(toDictResult))
		{
			Py_DECREF(toDictResult);
			tc->type = JT_NULL;
			return;
		}

		PRINTMARK();
		tc->type = JT_OBJECT;
		pc->iterBegin = Dict_iterBegin;
		pc->iterEnd = Dict_iterEnd;
		pc->iterNext = Dict_iterNext;
		pc->iterGetValue = Dict_iterGetValue;
		pc->iterGetName = Dict_iterGetName;
		pc->dictObj = toDictResult;
		return;
	}

	PyErr_Clear();

	tc->type = JT_OBJECT;
	pc->iterBegin = Dir_iterBegin;
	pc->iterEnd = Dir_iterEnd;
	pc->iterNext = Dir_iterNext;
	pc->iterGetValue = Dir_iterGetValue;
	pc->iterGetName = Dir_iterGetName;

	return;
}
示例#26
0
文件: lxc.c 项目: SethRobertson/lxc
static PyObject *
Container_clone(Container *self, PyObject *args, PyObject *kwds)
{
    char *newname = NULL;
    char *config_path = NULL;
    int flags = 0;
    char *bdevtype = NULL;
    char *bdevdata = NULL;
    unsigned long newsize = 0;
    char **hookargs = NULL;

    PyObject *py_hookargs = NULL;
    PyObject *py_config_path = NULL;
    struct lxc_container *new_container = NULL;
    int i = 0;

    static char *kwlist[] = {"newname", "config_path", "flags", "bdevtype",
                             "bdevdata", "newsize", "hookargs", NULL};
    if (! PyArg_ParseTupleAndKeywords(args, kwds, "s|O&isskO", kwlist,
                                      &newname,
                                      PyUnicode_FSConverter, &py_config_path,
                                      &flags, &bdevtype, &bdevdata, &newsize,
                                      &py_hookargs))
        return NULL;

    if (py_hookargs) {
        if (PyTuple_Check(py_hookargs)) {
            hookargs = convert_tuple_to_char_pointer_array(py_hookargs);
            if (!hookargs) {
                return NULL;
            }
        }
        else {
            PyErr_SetString(PyExc_ValueError, "hookargs needs to be a tuple");
            return NULL;
        }
    }

    if (py_config_path != NULL) {
        config_path = PyBytes_AS_STRING(py_config_path);
        assert(config_path != NULL);
    }

    new_container = self->container->clone(self->container, newname,
                                           config_path, flags, bdevtype,
                                           bdevdata, newsize, hookargs);

    Py_XDECREF(py_config_path);

    if (hookargs) {
        for (i = 0; i < PyTuple_GET_SIZE(py_hookargs); i++)
            free(hookargs[i]);
        free(hookargs);
    }

    if (new_container == NULL) {
        Py_RETURN_FALSE;
    }

    lxc_container_put(new_container);

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

    assert(compat || (args != (PyObject*)NULL));

    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(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, 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 "
                          "(%d 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",
                          len);
            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,
                          levels, msgbuf, sizeof(msgbuf), &freelist);
        if (msg) {
            seterror(i+1, msg, levels, fname, message);
            return cleanreturn(0, freelist);
        }
    }

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

    return cleanreturn(1, freelist);
}
示例#28
0
static gboolean
gplp_func_desc_load (GOPluginService *service,
		     char const *name,
		     GnmFuncDescriptor *res)
{
	ServiceLoaderDataFunctionGroup *loader_data;
	PyObject *fn_info_obj;

	g_return_val_if_fail (IS_GNM_PLUGIN_SERVICE_FUNCTION_GROUP (service), FALSE);
	g_return_val_if_fail (name != NULL, FALSE);

	loader_data = g_object_get_data (G_OBJECT (service), "loader_data");
	SWITCH_TO_PLUGIN (go_plugin_service_get_plugin (service));
	fn_info_obj = PyDict_GetItemString (loader_data->python_fn_info_dict,
					    (gchar *) name);
	if (fn_info_obj == NULL) {
		gnm_python_clear_error_if_needed (SERVICE_GET_LOADER (service)->py_object);
		return FALSE;
	}

	if (PyTuple_Check (fn_info_obj)) {
		PyObject *python_args, *python_arg_names;
		PyObject *python_fn;

		if (PyTuple_Size (fn_info_obj) == 3 &&
		    (python_args = PyTuple_GetItem (fn_info_obj, 0)) != NULL &&
			PyString_Check (python_args) &&
		    (python_arg_names = PyTuple_GetItem (fn_info_obj, 1)) != NULL &&
		    PyString_Check (python_arg_names) &&
		    (python_fn = PyTuple_GetItem (fn_info_obj, 2)) != NULL &&
		    PyFunction_Check (python_fn)) {
			res->arg_spec	= PyString_AsString (python_args);
#if 0
			res->arg_names  = PyString_AsString (python_arg_names);
#endif
			res->help	= python_function_get_gnumeric_help (
				loader_data->python_fn_info_dict, python_fn, name);
			res->fn_args	= &call_python_function_args;
			res->fn_nodes	= NULL;
			res->linker	= NULL;
			res->unlinker	= NULL;
			res->impl_status = GNM_FUNC_IMPL_STATUS_UNIQUE_TO_GNUMERIC;
			res->test_status = GNM_FUNC_TEST_STATUS_UNKNOWN;
			return TRUE;
		}

		gnm_python_clear_error_if_needed (SERVICE_GET_LOADER (service)->py_object);
		return FALSE;
	}

	if (PyFunction_Check (fn_info_obj)) {
		res->arg_spec	= "";
		res->help	= python_function_get_gnumeric_help (
			loader_data->python_fn_info_dict, fn_info_obj, name);
		res->fn_args	= NULL;
		res->fn_nodes	= &call_python_function_nodes;
		res->linker	= NULL;
		res->unlinker	= NULL;
		res->impl_status = GNM_FUNC_IMPL_STATUS_UNIQUE_TO_GNUMERIC;
		res->test_status = GNM_FUNC_TEST_STATUS_UNKNOWN;
		return TRUE;
	}

	gnm_python_clear_error_if_needed (SERVICE_GET_LOADER (service)->py_object);
	return FALSE;
}
PyObject * dataconv_ReadFromInTuple(PyObject *self, PyObject *args)
{
	PyObject *obArgTypes;
	PyObject *obArgType;
	PyObject *obPtr;
	BYTE *pb;
	BYTE *pbArg;
	Py_ssize_t cArgs, i;
	PyObject *obArgs = NULL;
	PyObject *obArg;
	VARTYPE vtArgType;
	UINT cb;
	VARIANT var;
	BOOL bIsByRef;
	

	if (!PyArg_ParseTuple(args, "OO:ReadFromInTuple", &obArgTypes, &obPtr))
		return NULL;
	
	pbArg = (BYTE *)PyLong_AsVoidPtr(obPtr);
	assert(pbArg);
	if (!pbArg)
		return NULL;

	pb = pbArg;

	if (!PyTuple_Check(obArgTypes))
	{
		PyErr_SetString(PyExc_TypeError, "OLE type description - expecting a tuple");
		return NULL;
	}
	
	cArgs = PyTuple_Size(obArgTypes);
	obArgs = PyTuple_New(cArgs);
	if (!obArgs)
		return NULL;

	for(i = 0 ; i < cArgs; i++)
	{
		// (<type tuple>, argPtr offset, arg size)
		if (PyTuple_Size(PyTuple_GET_ITEM(obArgTypes, i)) != 3)
		{
			PyErr_SetString(PyExc_TypeError, "OLE type description - expecting an arg desc tuple of size 3");
			goto Error;
		}
		
		obArgType = PyTuple_GET_ITEM(PyTuple_GET_ITEM(obArgTypes, i), 0);

		// Position pb to point to the current argument.
		pb = pbArg + PyInt_AS_LONG(PyTuple_GET_ITEM(PyTuple_GET_ITEM(obArgTypes, i), 1));
		vtArgType = (VARTYPE)PyInt_AS_LONG(obArgType);
#ifdef _M_IX86
		bIsByRef = vtArgType & VT_BYREF;
#elif _M_X64
		// params > 64bits always passed by address - and the only
		// arg we support > 64 bits is a VARIANT structure.
		bIsByRef = (vtArgType==VT_VARIANT) || (vtArgType & VT_BYREF);
#else
#error Unknown platform
#endif
		VARTYPE vtConversionType = vtArgType & VT_TYPEMASK;
		if (vtArgType & VT_ARRAY) {
			SAFEARRAY FAR *psa = *((SAFEARRAY **)pb);
			if (psa==NULL) { // A NULL array
				Py_INCREF(Py_None);
				obArg = Py_None;
			} else {
				if (vtArgType & VT_BYREF) // one more level of indirection
					psa = *((SAFEARRAY FAR **)psa);
				if (psa==NULL) { // A NULL array
					Py_INCREF(Py_None);
					obArg = Py_None;
				} else 
					obArg = PyCom_PyObjectFromSAFEARRAY(psa, (VARENUM)vtConversionType);
			}
		} else {
			switch (vtConversionType)
			{
			// If they can fit in a VARIANT, cheat and make that code do all of the work...
			case VT_I2:
			case VT_I4:
			case VT_R4:
			case VT_R8:
			case VT_CY:
			case VT_DATE:
			case VT_BSTR:
			case VT_ERROR:
			case VT_BOOL:
			case VT_I1:
			case VT_UI1:
			case VT_UI2:
			case VT_UI4:
			case VT_INT:
			case VT_UINT:
			case VT_UNKNOWN:
			case VT_DISPATCH:
			case VT_HRESULT:
				VariantInit(&var);
				if (vtConversionType == VT_HRESULT ||
					vtConversionType == VT_INT)
				{
					// Preserve VT_BYREF or VT_ARRAY
					vtArgType = VT_I4 | (vtArgType & VT_TYPEMASK);
				}
				if (vtArgType == VT_UINT) 
				{
					// Preserve VT_BYREF or VT_ARRAY
					vtArgType = VT_UI4 | (vtArgType & VT_TYPEMASK);
				}
				V_VT(&var) = vtArgType;
				// Copy the data into the variant...
				if (!SizeOfVT(V_VT(&var), (int *)&cb, NULL))
					goto Error;
				memcpy(&V_I4(&var), pb, cb);
				// Convert it into a PyObject:
				obArg = PyCom_PyObjectFromVariant(&var);
				break;
			case VT_VARIANT:
				// A _real_ variant.
				if (bIsByRef)
					obArg = PyCom_PyObjectFromVariant(*(VARIANT**)pb);
				else
					obArg = PyCom_PyObjectFromVariant((VARIANT*)pb);
				break;
			case VT_LPSTR:
				obArg = PyString_FromString(*(CHAR **)pb);
				break;
			case VT_LPWSTR:
				obArg = PyWinObject_FromOLECHAR(*(OLECHAR **)pb);
				break;
			// Special cases:
			case VT_UI8:
				if (bIsByRef)
				{
					obArg = PyWinObject_FromULARGE_INTEGER(*(ULARGE_INTEGER *)pb);
				}
				else
				{
					obArg = PyWinObject_FromULARGE_INTEGER(**(ULARGE_INTEGER **)pb);
				}
				break;
			case VT_I8:
				if (bIsByRef)
				{
					obArg = PyWinObject_FromLARGE_INTEGER(*(LARGE_INTEGER *)pb);
				}
				else
				{
					obArg = PyWinObject_FromLARGE_INTEGER(**(LARGE_INTEGER **)pb);
				}
				break;
			// Pointers to unhandled arguments:
			// neither of these will be VT_BYREF'd.
			case VT_RECORD:
			case VT_PTR:
				obArg = PyLong_FromVoidPtr((void *)pb);
				break;
			// None of these should ever happen:
			case VT_USERDEFINED:
			// Should have been coerced into VT_PTR.
			case VT_CARRAY:
			default:
				obArg = NULL;
				PyErr_SetString(PyExc_TypeError, "Unknown/bad type description type!");
				// barf here, we don't wtf they were thinking...
				break;
			} // switch
		} // if ARRAY

		if (obArg == NULL)
		{
			goto Error;
		}
		PyTuple_SET_ITEM(obArgs, i, obArg);
	}

	return obArgs;
	
Error:
	Py_XDECREF(obArgs);
	return NULL;
}
/**
 *******************************************************************************************************
 * This function will get a batch of records from the Aeropike DB.
 *
 * @param err                   as_error object
 * @param self                  AerospikeClient object
 * @param py_keys               The list of keys
 * @param batch_policy_p        as_policy_batch object
 *
 * Returns the record if key exists otherwise NULL.
 *******************************************************************************************************
 */
static PyObject * batch_select_aerospike_batch_read(as_error *err, AerospikeClient * self, PyObject *py_keys, as_policy_batch * batch_policy_p, char** filter_bins, Py_ssize_t bins_size)
{
    PyObject * py_recs = NULL;

    as_batch_read_records records;

    as_batch_read_record* record = NULL;
    bool batch_initialised = false;

    // Convert python keys list to as_key ** and add it to as_batch.keys
    // keys can be specified in PyList or PyTuple
    if ( py_keys != NULL && PyList_Check(py_keys) ) {
        Py_ssize_t size = PyList_Size(py_keys);

        py_recs = PyList_New(size);
        as_batch_read_inita(&records, size);

        // Batch object initialised
        batch_initialised = true;

        for ( int i = 0; i < size; i++ ) {

            PyObject * py_key = PyList_GetItem(py_keys, i);

            if ( !PyTuple_Check(py_key) ) {
                as_error_update(err, AEROSPIKE_ERR_PARAM, "Key should be a tuple.");
                goto CLEANUP;
            }

            record = as_batch_read_reserve(&records);

            pyobject_to_key(err, py_key, &record->key);
            if (bins_size) {
                record->bin_names = filter_bins;
                record->n_bin_names = bins_size;
            } else {
                record->read_all_bins = true;
            }

            if ( err->code != AEROSPIKE_OK ) {
                goto CLEANUP;
            }
        }
    }
    else if ( py_keys != NULL && PyTuple_Check(py_keys) ) {
        Py_ssize_t size = PyTuple_Size(py_keys);

        py_recs = PyList_New(size);
        as_batch_read_inita(&records, size);
        // Batch object initialised
        batch_initialised = true;

        for ( int i = 0; i < size; i++ ) {
            PyObject * py_key = PyTuple_GetItem(py_keys, i);

            if ( !PyTuple_Check(py_key) ) {
                as_error_update(err, AEROSPIKE_ERR_PARAM, "Key should be a tuple.");
                goto CLEANUP;
            }

            record = as_batch_read_reserve(&records);

            pyobject_to_key(err, py_key, &record->key);
            if (bins_size) {
                record->bin_names = filter_bins;
                record->n_bin_names = bins_size;
            } else {
                record->read_all_bins = true;
            }

            if ( err->code != AEROSPIKE_OK ) {
                goto CLEANUP;
            }
        }
    }
    else {
        as_error_update(err, AEROSPIKE_ERR_PARAM, "Keys should be specified as a list or tuple.");
        goto CLEANUP;
    }

    // Invoke C-client API
    if (aerospike_batch_read(self->as, err, batch_policy_p, &records) != AEROSPIKE_OK)
    {
        goto CLEANUP;
    }
    batch_select_recs(err, &records, &py_recs);

CLEANUP:
    if (batch_initialised == true) {
        // We should destroy batch object as we are using 'as_batch_init' for initialisation
        // Also, pyobject_to_key is soing strdup() in case of Unicode. So, object destruction
        // is necessary.
        as_batch_read_destroy(&records);
    }

    return py_recs;
}