예제 #1
0
BOOL PyObject_AsPROPVARIANT(PyObject *ob, PROPVARIANT *pVar)
{
	if (ob==Py_True) {
		pVar->boolVal = -1;
		pVar->vt = VT_BOOL;
	} else if (ob==Py_False) {
		pVar->boolVal = 0;
		pVar->vt = VT_BOOL;
	} else if (PyInt_Check(ob)) {
		pVar->lVal = PyInt_AsLong(ob);
		pVar->vt = VT_I4;
	} else if (PyFloat_Check(ob)) {
		pVar->dblVal = PyFloat_AsDouble(ob);
		pVar->vt = VT_R8;
	} else if (PyUnicode_Check(ob) || PyString_Check(ob)) {
		PyWinObject_AsBstr(ob, &pVar->bstrVal);
		pVar->vt = VT_BSTR;
	} else {
		PyErr_SetString(PyExc_TypeError, "Unsupported object for PROPVARIANT");
		return FALSE;
	}
	return TRUE;
}
예제 #2
0
/** \ingroup python_interface_arpack
 * \brief Sets one of the attributes of a given ARPACK parameters object
 */
int igraphmodule_ARPACKOptions_setattr(
  igraphmodule_ARPACKOptionsObject* self, char* attrname,
  PyObject* value) {
  if (value == 0) {
    PyErr_SetString(PyExc_TypeError, "attribute can not be deleted");
    return -1;
  }
  if (strcmp(attrname, "maxiter") == 0 ||
      strcmp(attrname, "mxiter") == 0) {
    if (PyInt_Check(value)) {
      long int n=PyInt_AsLong(value);
      if (n>0)
          self->params.mxiter=(igraph_integer_t)n;
      else {
        PyErr_SetString(PyExc_ValueError, "maxiter must be positive");
        return -1;
      }
    } else {
      PyErr_SetString(PyExc_ValueError, "integer expected");
      return -1;
    }
  } else if (strcmp(attrname, "tol") == 0) {
    if (PyInt_Check(value)) {
      self->params.tol = (igraph_real_t) PyInt_AsLong(value);
    } else if (PyFloat_Check(value)) {
      self->params.tol = (igraph_real_t) PyFloat_AsDouble(value);
    } else {
      PyErr_SetString(PyExc_ValueError, "integer or float expected");
      return -1;
    }
  } else {
    PyErr_SetString(PyExc_AttributeError, attrname);
    return -1;
  }

  return 0;
}
예제 #3
0
Variant Variant_from_py(PyObject* py)
{
    Variant var;

    if (PyString_Check(py))
    {
        var = std::string(PyString_AsString(py));
        return var;
    }

    else if (PyBool_Check(py))
    {
        var = (bool)(py == Py_True);
        return var;
    }

    else if (PyInt_Check(py))
    {
        var = PyInt_AsLong(py);
        return var;
    }

    else if (PyLong_Check(py))
    {
        var = PyLong_AsLong(py);
        return var;
    }

    else if (PyFloat_Check(py))
    {
        var = PyFloat_AsDouble(py);
        return var;
    }

    string msg = "could not convert Python type to built in type";
    throw invalid_argument(msg);
}
예제 #4
0
static int
get_wrapped_ulong(PyObject *v, unsigned long *p)
{
	long x = (long)PyLong_AsUnsignedLong(v);
	if (x == -1 && PyErr_Occurred()) {
		PyObject *wrapped;
		PyErr_Clear();
#ifdef PY_STRUCT_FLOAT_COERCE
		if (PyFloat_Check(v)) {
			PyObject *o;
			int res;
			PyErr_Clear();
			if (PyErr_WarnEx(PyExc_DeprecationWarning, FLOAT_COERCE, 2) < 0)
				return -1;
			o = PyNumber_Int(v);
			if (o == NULL)
				return -1;
			res = get_wrapped_ulong(o, p);
			Py_DECREF(o);
			return res;
		}
#endif
		wrapped = PyNumber_And(v, pylong_ulong_mask);
		if (wrapped == NULL)
			return -1;
		if (PyErr_WarnEx(PyExc_DeprecationWarning, INT_OVERFLOW, 2) < 0) {
			Py_DECREF(wrapped);
			return -1;
		}
		x = (long)PyLong_AsUnsignedLong(wrapped);
		Py_DECREF(wrapped);
		if (x == -1 && PyErr_Occurred())
			return -1;
	}
	*p = (unsigned long)x;
	return 0;
}
예제 #5
0
		DVariant PyObjectToDVariant(PyObject* obj) {
			// Do a conversion from python object to DVariant instance
			// Look for the type of the python object

			if (PyLong_Check(obj))
				return DVariant(static_cast<int>(PyLong_AsLong(obj)));
			else if (PyBool_Check(obj))
			{
				if(obj == Py_True)
					return DVariant((bool)true);
				else
					return DVariant((bool)false);
			}
			else if (PyFloat_Check(obj))
				return DVariant((float)PyFloat_AsDouble(obj));
#ifdef IS_PY3K
			else if (PyBytes_Check(obj))
				return DVariant(PyBytes_AsString(obj));
#else
			else if (PyString_Check(obj))
				return DVariant(PyString_AsString(obj));
#endif
			else if (PyModule_Check(obj))
			{
				float x, y, z, w;

				if (PyArg_Parse(obj, "[ffff]", &x, &y, &z, &w)) {
					return DVariant(x, y, z, w);
				} else if (PyArg_Parse(obj, "[fff]", &x, &y, &z)) {
					return DVariant(x, y, z);
				} else
					return DVariant(DVariant::DV_INVALID);

			}

			return DVariant(DVariant::DV_INVALID); //Py_None, or a non-handled type
		}
예제 #6
0
static int Vector3D_setattro(PyVector3D *self, PyObject *oname, PyObject *v)
{
    char * name = PyString_AsString(oname);
    float val;
    if (PyInt_Check(v)) {
        val = PyInt_AsLong(v);
    } else if (PyFloat_Check(v)) {
        val = PyFloat_AsDouble(v);
    } else {
        PyErr_SetString(PyExc_TypeError, "Vector3D attributes must be numeric");
        return -1;
    }
    if (strcmp(name, "x") == 0) {
        self->coords.x() = val;
    } else if (strcmp(name, "y") == 0) {
        self->coords.y() = val;
    } else if (strcmp(name, "z") == 0) {
        self->coords.z() = val;
    } else {
        PyErr_SetString(PyExc_AttributeError, "Vector3D attribute does not exist");
        return -1;
    }
    return 0;
}
예제 #7
0
static double* GetPyFloatListToArrayOfDoubles(const char*const argName,
					      const int requiredSize,
					      const double minVal,
					      const double maxVal,
					      PyObject* pyList) {
  int i, size;
  double* result;
  PyObject* item;

  assert(PyList_Check(pyList));
  size = PyList_GET_SIZE(pyList);
  if (requiredSize != size) {
    PyErr_Format(PyExc_TypeError,"%s:list size should be %i not %i",
		 argName,requiredSize,size);
    return NULL;
  }
  result = SafeCalloc(requiredSize,sizeof(double));
  for (i=0; i<requiredSize; i++) {
    item = PyList_GET_ITEM(pyList,i);
    if (PyInt_Check(item)) result[i] = PyInt_AsLong(item);
    else if (PyFloat_Check(item)) result[i]=PyFloat_AsDouble(item);
    else {
      PyErr_Format(PyExc_TypeError,"%s:element %i not an int or float",
		   argName,i);
      free(result);
      return NULL;
    }
    if (result[i] > maxVal || result[i] < minVal) {
      PyErr_Format(PyExc_TypeError,"%s:element %i not in required range",
		   argName,i);
      free(result);
      return NULL;
    }
  }
  return result;
}
예제 #8
0
int pysqlite_statement_bind_parameter(pysqlite_Statement* self, int pos, PyObject* parameter)
{
    int rc = SQLITE_OK;
    long longval;
#ifdef HAVE_LONG_LONG
    PY_LONG_LONG longlongval;
#endif
    const char* buffer;
    char* string;
    Py_ssize_t buflen;
    PyObject* stringval;

    if (parameter == Py_None) {
        rc = sqlite3_bind_null(self->st, pos);
    } else if (PyInt_Check(parameter)) {
        longval = PyInt_AsLong(parameter);
        rc = sqlite3_bind_int64(self->st, pos, (sqlite_int64)longval);
#ifdef HAVE_LONG_LONG
    } else if (PyLong_Check(parameter)) {
        longlongval = PyLong_AsLongLong(parameter);
        /* in the overflow error case, longlongval is -1, and an exception is set */
        rc = sqlite3_bind_int64(self->st, pos, (sqlite_int64)longlongval);
#endif
    } else if (PyFloat_Check(parameter)) {
        rc = sqlite3_bind_double(self->st, pos, PyFloat_AsDouble(parameter));
    } else if (PyBuffer_Check(parameter)) {
        if (PyObject_AsCharBuffer(parameter, &buffer, &buflen) == 0) {
            rc = sqlite3_bind_blob(self->st, pos, buffer, buflen, SQLITE_TRANSIENT);
        } else {
            PyErr_SetString(PyExc_ValueError, "could not convert BLOB to buffer");
            rc = -1;
        }
    } else if PyString_Check(parameter) {
        string = PyString_AsString(parameter);
        rc = sqlite3_bind_text(self->st, pos, string, -1, SQLITE_TRANSIENT);
    } else if PyUnicode_Check(parameter) {
예제 #9
0
static int
array_power_is_scalar(PyObject *o2, double* out_exponent)
{
    PyObject *temp;
    const int optimize_fpexps = 1;

    if (PyInt_Check(o2)) {
        *out_exponent = (double)PyInt_AsLong(o2);
        return NPY_INTPOS_SCALAR;
    }
    if (optimize_fpexps && PyFloat_Check(o2)) {
        *out_exponent = PyFloat_AsDouble(o2);
        return NPY_FLOAT_SCALAR;
    }
    if ((PyArray_IsZeroDim(o2) &&
            ((PyArray_ISINTEGER((PyArrayObject *)o2) ||
              (optimize_fpexps && PyArray_ISFLOAT((PyArrayObject *)o2))))) ||
            PyArray_IsScalar(o2, Integer) ||
            (optimize_fpexps && PyArray_IsScalar(o2, Floating))) {
        temp = Py_TYPE(o2)->tp_as_number->nb_float(o2);
        if (temp != NULL) {
            *out_exponent = PyFloat_AsDouble(o2);
            Py_DECREF(temp);
            if (PyArray_IsZeroDim(o2)) {
                if (PyArray_ISINTEGER((PyArrayObject *)o2)) {
                    return NPY_INTPOS_SCALAR;
                }
                else { /* ISFLOAT */
                    return NPY_FLOAT_SCALAR;
                }
            }
            else if PyArray_IsScalar(o2, Integer) {
                return NPY_INTPOS_SCALAR;
            }
            else { /* IsScalar(o2, Floating) */
                return NPY_FLOAT_SCALAR;
예제 #10
0
static MPC_Object *
GMPy_MPC_From_Complex(PyObject* obj, mp_prec_t rprec, mp_prec_t iprec,
                           CTXT_Object *context)
{
    CHECK_CONTEXT(context);

    if (MPC_Check(obj))
        return GMPy_MPC_From_MPC((MPC_Object*)obj, rprec, iprec, context);

    if (MPFR_Check(obj))
        return GMPy_MPC_From_MPFR((MPFR_Object*)obj, rprec, iprec, context);

    if (PyFloat_Check(obj))
        return GMPy_MPC_From_PyFloat(obj, rprec, iprec, context);

    if (PyComplex_Check(obj))
        return GMPy_MPC_From_PyComplex(obj, rprec, iprec, context);

    if (MPQ_Check(obj))
        return GMPy_MPC_From_MPQ((MPQ_Object*)obj, rprec, iprec, context);

    if (MPZ_Check(obj) || XMPZ_Check(obj))
        return GMPy_MPC_From_MPZ((MPZ_Object*)obj, rprec, iprec, context);

    if (PyIntOrLong_Check(obj))
        return GMPy_MPC_From_PyIntOrLong(obj, rprec, iprec, context);

    if (IS_DECIMAL(obj))
        return GMPy_MPC_From_Decimal(obj, rprec, iprec, context);

    if (IS_FRACTION(obj))
        return GMPy_MPC_From_Fraction(obj, rprec, iprec, context);

    TYPE_ERROR("object could not be converted to 'mpc'");
    return NULL;
}
예제 #11
0
static PyObject *
cdistance_distance(PyObject *self, PyObject *args)
{
    PyObject *resulto, *ratioo, *ret;
    PyObject *cutoffo = Py_None;
    const char *a, *b, *t;
    int cutoff = -1;
    int al, bl, tl;
    float ratio;
    if (!PyArg_ParseTuple(args, "s#s#|O", &a, &al, &b, &bl, &cutoffo))
        return NULL;
    if (al > bl) {
        t = a; tl = al;
        a = b; al = bl;
        b = t; bl = tl;
    }
    if (cutoffo != Py_None) {
        if (PyInt_Check(cutoffo)) {
            cutoff = (int)PyInt_AsLong(cutoffo);
        } else if (PyFloat_Check(cutoffo)) {
            cutoff = (int)(float)(bl-PyFloat_AsDouble(cutoffo)*bl);
        } else {
            PyErr_SetString(PyExc_TypeError, "cutoff must be int or float");
            return NULL;
        }
    }
    resulto = PyInt_FromLong(distance(a, al, b, bl, cutoff, &ratio));
    if (!resulto) return NULL;
    ratioo = PyFloat_FromDouble((double)ratio);
    if (!ratioo) return NULL;
    ret = PyTuple_New(2);
    if (!ret) return NULL;
    PyTuple_SET_ITEM(ret, 0, resulto);
    PyTuple_SET_ITEM(ret, 1, ratioo);
    return ret;
}
예제 #12
0
파일: _cmormodule.c 프로젝트: PCMDI/cmor
static PyObject *PyCMOR_set_variable_attribute(PyObject * self, PyObject * args)
{
    signal(signal_to_catch, signal_handler);
    char *name;
    char *value;
    char *type;
    long lValue;
    int nValue;
    float fValue;
    double dValue;
    PyObject *oValue;
    int ierr, var_id;
    value = NULL;
    if (!PyArg_ParseTuple(args, "issO", &var_id, &name, &type, &oValue))
        return NULL;

#if PY_MAJOR_VERSION >= 3
    if(PyBytes_Check(oValue)) {
        value = PyBytes_AsString(oValue);
#else
    if(PyString_Check(oValue)) {
        value = PyString_AsString(oValue);
#endif
    } else if(PyLong_Check(oValue)) {
        lValue = PyLong_AsLong(oValue);
    } else if (PyFloat_Check(oValue)) {
        dValue = PyFloat_AsDouble(oValue);
    }

    if (type[0] == 'f') {
        fValue = (float) dValue;
        value = (char *) &fValue;
    } else if (type[0] == 'd') {
        value = (char *) &dValue;
    } else if (type[0] == 'i') {
        nValue = (int) lValue;
        value = (char *) &nValue;
    } else if (type[0] == 'l') {
        value = (char *) &lValue;
    }

    ierr = cmor_set_variable_attribute(var_id, name, type[0], (void *)value);

    if (ierr != 0 || raise_exception) {
        raise_exception = 0;
        PyErr_Format(CMORError, exception_message, "set_variable_attribute");
        return NULL;
    }

    return (Py_BuildValue("i", ierr));
}

/************************************************************************/
/*                   PyCMOR_get_variable_attribute()                    */
/************************************************************************/
static PyObject *PyCMOR_get_variable_attribute(PyObject * self, PyObject * args)
{
    signal(signal_to_catch, signal_handler);
    char *name;
    char value[CMOR_MAX_STRING];
    int ierr, var_id;

    if (!PyArg_ParseTuple(args, "is", &var_id, &name))
        return NULL;

    ierr = cmor_get_variable_attribute(var_id, name, (void *)value);

    if (ierr != 0 || raise_exception) {
        raise_exception = 0;
        PyErr_Format(CMORError, exception_message, "get_variable_attribute");
        return NULL;
    }

    return (Py_BuildValue("s", value));
}
예제 #13
0
파일: _sane.c 프로젝트: 10printhello/gitpil
static PyObject *
SaneDev_set_option(SaneDevObject *self, PyObject *args)
{
  SANE_Status st;
  const SANE_Option_Descriptor *d;
  SANE_Int i;
  PyObject *value;
  int n;
  void *v;
  
  if (!PyArg_ParseTuple(args, "iO", &n, &value))
    return NULL;
  if (self->h==NULL)
    {
      PyErr_SetString(ErrorObject, "SaneDev object is closed");
      return NULL;
    }
  d=sane_get_option_descriptor(self->h, n);
  v=malloc(d->size+1);

  switch(d->type)
    {
    case(SANE_TYPE_BOOL):
      if (!PyInt_Check(value)) 
	{
	  PyErr_SetString(PyExc_TypeError, "SANE_BOOL requires an integer");
	  free(v);
	  return NULL;
	}
	/* fall through */
    case(SANE_TYPE_INT):
      if (!PyInt_Check(value)) 
	{
	  PyErr_SetString(PyExc_TypeError, "SANE_INT requires an integer");
	  free(v);
	  return NULL;
	}
      *( (SANE_Int*)v) = PyInt_AsLong(value);
      break;
    case(SANE_TYPE_FIXED):
      if (!PyFloat_Check(value)) 
	{
	  PyErr_SetString(PyExc_TypeError, "SANE_FIXED requires a floating point number");
	  free(v);
	  return NULL;
	}
      *( (SANE_Fixed*)v) = SANE_FIX(PyFloat_AsDouble(value));
      break;
    case(SANE_TYPE_STRING):
      if (!PyString_Check(value)) 
	{
	  PyErr_SetString(PyExc_TypeError, "SANE_STRING requires a string");
	  free(v);
	  return NULL;
	}
      strncpy(v, PyString_AsString(value), d->size-1);
      ((char*)v)[d->size-1] = 0;
      break;
    case(SANE_TYPE_BUTTON): 
    case(SANE_TYPE_GROUP):
      break;
    }
  
  st=sane_control_option(self->h, n, SANE_ACTION_SET_VALUE,
			 v, &i);
  if (st) {free(v); return PySane_Error(st);}
  
  free(v);
  return Py_BuildValue("i", i);
}
예제 #14
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();
#ifdef _LP64
		pc->PyTypeToJSON = PyIntToINT64; tc->type = JT_LONG;
#else
		pc->PyTypeToJSON = PyIntToINT32; tc->type = JT_INT;
#endif
		return;
	}
	else 
	if (PyLong_Check(obj))
	{
		PyObject *exc;

		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();
			tc->type = JT_INVALID;
			return;
		}

		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;
}
예제 #15
0
static PyObject *
GMPy_Real_Add(PyObject *x, PyObject *y, CTXT_Object *context)
{
    MPFR_Object *result;

    CHECK_CONTEXT(context);

    if (!(result = GMPy_MPFR_New(0, context)))
        return NULL;

    if (MPFR_Check(x) && MPFR_Check(y)) {
        mpfr_clear_flags();
        result->rc = mpfr_add(result->f, MPFR(x), MPFR(y), GET_MPFR_ROUND(context));
        goto done;
    }

    if (MPFR_Check(x)) {
        if (PyIntOrLong_Check(y)) {
            mpz_t tempz;
            long temp;
            int error;

            temp = GMPy_Integer_AsLongAndError(y, &error);
            
            if (error) {
                mpz_inoc(tempz);
                mpz_set_PyIntOrLong(tempz, y);
                mpfr_clear_flags();
                result->rc = mpfr_add_z(result->f, MPFR(x), tempz, GET_MPFR_ROUND(context));
                mpz_cloc(tempz);
                goto done;
            }
            else {
                mpfr_clear_flags();
                result->rc = mpfr_add_si(result->f, MPFR(x), temp, GET_MPFR_ROUND(context));
                goto done;
            }
        }

        if (CHECK_MPZANY(y)) {
            mpfr_clear_flags();
            result->rc = mpfr_add_z(result->f, MPFR(x), MPZ(y), GET_MPFR_ROUND(context));
            goto done;
        }

        if (IS_RATIONAL(y)) {
            MPQ_Object *tempy;

            if (!(tempy = GMPy_MPQ_From_Number(y, context))) {
                Py_DECREF((PyObject*)result);
                return NULL;
            }
            mpfr_clear_flags();
            result->rc = mpfr_add_q(result->f, MPFR(x), tempy->q, GET_MPFR_ROUND(context));
            Py_DECREF((PyObject*)tempy);
            goto done;
        }

        if (PyFloat_Check(y)) {
            mpfr_clear_flags();
            result->rc = mpfr_add_d(result->f, MPFR(x), PyFloat_AS_DOUBLE(y), GET_MPFR_ROUND(context));
            goto done;
        }
    }

    if (MPFR_Check(y)) {
        if (PyIntOrLong_Check(x)) {
            mpz_t tempz;
            long temp;
            int error;

            temp = GMPy_Integer_AsLongAndError(x, &error);
            if (error) {
                mpz_inoc(tempz);
                mpz_set_PyIntOrLong(tempz, x);
                mpfr_clear_flags();
                result->rc = mpfr_add_z(result->f, MPFR(y), tempz, GET_MPFR_ROUND(context));
                mpz_cloc(tempz);
                goto done;
            }
            else {
                mpfr_clear_flags();
                result->rc = mpfr_add_si(result->f, MPFR(y), temp, GET_MPFR_ROUND(context));
                goto done;
            }
        }

        if (CHECK_MPZANY(x)) {
            mpfr_clear_flags();
            result->rc = mpfr_add_z(result->f, MPFR(y), MPZ(x), GET_MPFR_ROUND(context));
            goto done;
        }

        if (IS_RATIONAL(x)) {
            MPQ_Object *tempx;

            if (!(tempx = GMPy_MPQ_From_Number(x, context))) {
                Py_DECREF((PyObject*)result);
                return NULL;
            }
            mpfr_clear_flags();
            result->rc = mpfr_add_q(result->f, MPFR(y), tempx->q, GET_MPFR_ROUND(context));
            Py_DECREF((PyObject*)tempx);
            goto done;
        }

        if (PyFloat_Check(x)) {
            mpfr_clear_flags();
            result->rc = mpfr_add_d(result->f, MPFR(y), PyFloat_AS_DOUBLE(x), GET_MPFR_ROUND(context));
            goto done;
        }
    }

    if (IS_REAL(x) && IS_REAL(y)) {
        MPFR_Object *tempx, *tempy;

        tempx = GMPy_MPFR_From_Real(x, 1, context);
        tempy = GMPy_MPFR_From_Real(y, 1, context);
        if (!tempx || !tempy) {
            Py_XDECREF((PyObject*)tempx);
            Py_XDECREF((PyObject*)tempy);
            Py_DECREF((PyObject*)result);
            return NULL;
        }
        mpfr_clear_flags();
        result->rc = mpfr_add(result->f, MPFR(tempx), MPFR(tempy), GET_MPFR_ROUND(context));
        Py_DECREF((PyObject*)tempx);
        Py_DECREF((PyObject*)tempy);
        goto done;
    }

    Py_DECREF((PyObject*)result);
    Py_RETURN_NOTIMPLEMENTED;

  done:
    GMPY_MPFR_CLEANUP(result, context, "addition");
    return (PyObject*)result;
}
예제 #16
0
/**
 * \note group can be a pointer array or a group.
 * assume we already checked key is a string.
 *
 * \return success.
 */
bool BPy_IDProperty_Map_ValidateAndCreate(PyObject *name_obj, IDProperty *group, PyObject *ob)
{
    IDProperty *prop = NULL;
    IDPropertyTemplate val = {0};

    const char *name;

    if (name_obj) {
        Py_ssize_t name_size;
        name = _PyUnicode_AsStringAndSize(name_obj, &name_size);

        if (name == NULL) {
            PyErr_Format(PyExc_KeyError,
                         "invalid id-property key, expected a string, not a %.200s",
                         Py_TYPE(name_obj)->tp_name);
            return false;
        }

        if (name_size > MAX_IDPROP_NAME) {
            PyErr_SetString(PyExc_KeyError, "the length of IDProperty names is limited to 63 characters");
            return false;
        }
    }
    else {
        name = "";
    }

    if (PyFloat_Check(ob)) {
        val.d = PyFloat_AsDouble(ob);
        prop = IDP_New(IDP_DOUBLE, &val, name);
    }
    else if (PyLong_Check(ob)) {
        val.i = _PyLong_AsInt(ob);
        if (val.i == -1 && PyErr_Occurred()) {
            return false;
        }
        prop = IDP_New(IDP_INT, &val, name);
    }
    else if (PyUnicode_Check(ob)) {
#ifdef USE_STRING_COERCE
        PyObject *value_coerce = NULL;
        val.string.str = (char *)PyC_UnicodeAsByte(ob, &value_coerce);
        val.string.subtype = IDP_STRING_SUB_UTF8;
        prop = IDP_New(IDP_STRING, &val, name);
        Py_XDECREF(value_coerce);
#else
        val.str = _PyUnicode_AsString(ob);
        prop = IDP_New(IDP_STRING, val, name);
#endif
    }
    else if (PyBytes_Check(ob)) {
        val.string.str = PyBytes_AS_STRING(ob);
        val.string.len = PyBytes_GET_SIZE(ob);
        val.string.subtype = IDP_STRING_SUB_BYTE;

        prop = IDP_New(IDP_STRING, &val, name);
        //prop = IDP_NewString(PyBytes_AS_STRING(ob), name, PyBytes_GET_SIZE(ob));
        //prop->subtype = IDP_STRING_SUB_BYTE;
    }
    else if (PySequence_Check(ob)) {
        PyObject *ob_seq_fast = PySequence_Fast(ob, "py -> idprop");
        PyObject *item;
        int i;

        if (ob_seq_fast == NULL) {
            return false;
        }

        if ((val.array.type = idp_sequence_type(ob_seq_fast)) == -1) {
            Py_DECREF(ob_seq_fast);
            PyErr_SetString(PyExc_TypeError, "only floats, ints and dicts are allowed in ID property arrays");
            return false;
        }

        /* validate sequence and derive type.
         * we assume IDP_INT unless we hit a float
         * number; then we assume it's */

        val.array.len = PySequence_Fast_GET_SIZE(ob_seq_fast);

        switch (val.array.type) {
        case IDP_DOUBLE:
        {
            double *prop_data;

            prop = IDP_New(IDP_ARRAY, &val, name);
            prop_data = IDP_Array(prop);
            for (i = 0; i < val.array.len; i++) {
                item = PySequence_Fast_GET_ITEM(ob_seq_fast, i);
                if (((prop_data[i] = PyFloat_AsDouble(item)) == -1.0) && PyErr_Occurred()) {
                    Py_DECREF(ob_seq_fast);
                    return false;
                }
            }
            break;
        }
        case IDP_INT:
        {
            int *prop_data;
            prop = IDP_New(IDP_ARRAY, &val, name);
            prop_data = IDP_Array(prop);
            for (i = 0; i < val.array.len; i++) {
                item = PySequence_Fast_GET_ITEM(ob_seq_fast, i);
                if (((prop_data[i] = _PyLong_AsInt(item)) == -1) && PyErr_Occurred()) {
                    Py_DECREF(ob_seq_fast);
                    return false;
                }
            }
            break;
        }
        case IDP_IDPARRAY:
        {
            prop = IDP_NewIDPArray(name);
            for (i = 0; i < val.array.len; i++) {
                item = PySequence_Fast_GET_ITEM(ob_seq_fast, i);

                if (BPy_IDProperty_Map_ValidateAndCreate(NULL, prop, item) == false) {
                    Py_DECREF(ob_seq_fast);
                    return false;
                }
            }
            break;
        }
        default:
            /* should never happen */
            Py_DECREF(ob_seq_fast);
            PyErr_SetString(PyExc_RuntimeError, "internal error with idp array.type");
            return false;
        }

        Py_DECREF(ob_seq_fast);
    }
    else if (PyMapping_Check(ob)) {
        PyObject *keys, *vals, *key, *pval;
        int i, len;
        /*yay! we get into recursive stuff now!*/
        keys = PyMapping_Keys(ob);
        vals = PyMapping_Values(ob);

        /* we allocate the group first; if we hit any invalid data,
         * we can delete it easily enough.*/
        prop = IDP_New(IDP_GROUP, &val, name);
        len = PyMapping_Length(ob);
        for (i = 0; i < len; i++) {
            key = PySequence_GetItem(keys, i);
            pval = PySequence_GetItem(vals, i);
            if (BPy_IDProperty_Map_ValidateAndCreate(key, prop, pval) == false) {
                IDP_FreeProperty(prop);
                MEM_freeN(prop);
                Py_XDECREF(keys);
                Py_XDECREF(vals);
                Py_XDECREF(key);
                Py_XDECREF(pval);
                /* error is already set */
                return false;
            }
            Py_XDECREF(key);
            Py_XDECREF(pval);
        }
        Py_XDECREF(keys);
        Py_XDECREF(vals);
    }
    else {
        PyErr_Format(PyExc_TypeError,
                     "invalid id-property type %.200s not supported",
                     Py_TYPE(ob)->tp_name);
        return false;
    }

    if (group->type == IDP_IDPARRAY) {
        IDP_AppendArray(group, prop);
        // IDP_FreeProperty(item);  /* IDP_AppendArray does a shallow copy (memcpy), only free memory */
        MEM_freeN(prop);
    }
    else {
        IDP_ReplaceInGroup(group, prop);
    }

    return true;
}
예제 #17
0
/* note: group can be a pointer array or a group */
const char *BPy_IDProperty_Map_ValidateAndCreate(const char *name, IDProperty *group, PyObject *ob)
{
    IDProperty *prop = NULL;
    IDPropertyTemplate val = {0};

    if(strlen(name) >= sizeof(group->name))
        return "the length of IDProperty names is limited to 31 characters";

    if (PyFloat_Check(ob)) {
        val.d = PyFloat_AsDouble(ob);
        prop = IDP_New(IDP_DOUBLE, val, name);
    } else if (PyLong_Check(ob)) {
        val.i = (int) PyLong_AsSsize_t(ob);
        prop = IDP_New(IDP_INT, val, name);
    } else if (PyUnicode_Check(ob)) {
#ifdef USE_STRING_COERCE
        PyObject *value_coerce= NULL;
        val.str = (char *)PyC_UnicodeAsByte(ob, &value_coerce);
        prop = IDP_New(IDP_STRING, val, name);
        Py_XDECREF(value_coerce);
#else
        val.str = _PyUnicode_AsString(ob);
        prop = IDP_New(IDP_STRING, val, name);
#endif
    } else if (PySequence_Check(ob)) {
        PyObject *item;
        int i;

        if((val.array.type= idp_sequence_type(ob)) == -1)
            return "only floats, ints and dicts are allowed in ID property arrays";

        /*validate sequence and derive type.
        we assume IDP_INT unless we hit a float
        number; then we assume it's */

        val.array.len = PySequence_Size(ob);

        switch(val.array.type) {
        case IDP_DOUBLE:
            prop = IDP_New(IDP_ARRAY, val, name);
            for (i=0; i<val.array.len; i++) {
                item = PySequence_GetItem(ob, i);
                ((double*)prop->data.pointer)[i] = (float)PyFloat_AsDouble(item);
                Py_DECREF(item);
            }
            break;
        case IDP_INT:
            prop = IDP_New(IDP_ARRAY, val, name);
            for (i=0; i<val.array.len; i++) {
                item = PySequence_GetItem(ob, i);
                ((int*)prop->data.pointer)[i] = (int)PyLong_AsSsize_t(item);
                Py_DECREF(item);
            }
            break;
        case IDP_IDPARRAY:
            prop= IDP_NewIDPArray(name);
            for (i=0; i<val.array.len; i++) {
                const char *error;
                item = PySequence_GetItem(ob, i);
                error= BPy_IDProperty_Map_ValidateAndCreate("", prop, item);
                Py_DECREF(item);

                if(error)
                    return error;
            }
            break;
        }
    } else if (PyMapping_Check(ob)) {
        PyObject *keys, *vals, *key, *pval;
        int i, len;
        /*yay! we get into recursive stuff now!*/
        keys = PyMapping_Keys(ob);
        vals = PyMapping_Values(ob);

        /*we allocate the group first; if we hit any invalid data,
          we can delete it easily enough.*/
        prop = IDP_New(IDP_GROUP, val, name);
        len = PyMapping_Length(ob);
        for (i=0; i<len; i++) {
            key = PySequence_GetItem(keys, i);
            pval = PySequence_GetItem(vals, i);
            if (!PyUnicode_Check(key)) {
                IDP_FreeProperty(prop);
                MEM_freeN(prop);
                Py_XDECREF(keys);
                Py_XDECREF(vals);
                Py_XDECREF(key);
                Py_XDECREF(pval);
                return "invalid element in subgroup dict template!";
            }
            if (BPy_IDProperty_Map_ValidateAndCreate(_PyUnicode_AsString(key), prop, pval)) {
                IDP_FreeProperty(prop);
                MEM_freeN(prop);
                Py_XDECREF(keys);
                Py_XDECREF(vals);
                Py_XDECREF(key);
                Py_XDECREF(pval);
                return "invalid element in subgroup dict template!";
            }
            Py_XDECREF(key);
            Py_XDECREF(pval);
        }
        Py_XDECREF(keys);
        Py_XDECREF(vals);
    } else return "invalid property value";

    if(group->type==IDP_IDPARRAY) {
        IDP_AppendArray(group, prop);
        // IDP_FreeProperty(item); // IDP_AppendArray does a shallow copy (memcpy), only free memory
        MEM_freeN(prop);
    } else {
        IDP_ReplaceInGroup(group, prop);
    }

    return NULL;
}
예제 #18
0
void DataSourceWrapper::GetRow(StringList& row, const String& table, int row_index, const StringList& columns)
{
	PyObject* callable = PyObject_GetAttrString(self, "GetRow");
	if (!callable)
	{
		Core::String error_message(128, "Function \"GetRow\" not found on python data source %s.", Utilities::GetPythonClassName(self).CString());
		Log::Message(LC_COREPYTHON, Log::LT_WARNING, "%s", error_message.CString());
		PyErr_SetString(PyExc_RuntimeError, error_message.CString());
		python::throw_error_already_set();
		return;
	}

	python::tuple t = python::make_tuple(table.CString(), row_index, columns);
	PyObject* result = PyObject_CallObject(callable, t.ptr());
	Py_DECREF(callable);	

	// If it's a list, then just get the entries out of it
	if (result && PyList_Check(result))
	{
		int num_entries = PyList_Size(result);
		for (int i = 0; i < num_entries; i++)
		{
			Core::String entry;

			PyObject* entry_object = PyList_GetItem(result, i);
			if (PyString_Check(entry_object))
			{
				entry = PyString_AS_STRING(entry_object);
			}
			else if (PyInt_Check(entry_object))
			{
				int entry_int = (int)PyInt_AS_LONG(entry_object);
				Core::TypeConverter< int, Core::String >::Convert(entry_int, entry);
			}
			else if (PyFloat_Check(entry_object))
			{
				float entry_float = (float)PyFloat_AS_DOUBLE(entry_object);
				Core::TypeConverter< float, Core::String >::Convert(entry_float, entry);
			}
			else
			{
				Core::String error_message(128, "Failed to convert row %d entry %d on data source %s.", row_index, i, Utilities::GetPythonClassName(self).CString());
				Log::Message(LC_COREPYTHON, Log::LT_WARNING, "%s", error_message.CString());
				PyErr_SetString(PyExc_RuntimeError, error_message.CString());
				python::throw_error_already_set();
			}

			row.push_back(entry);
		}
	}
	else
	{
		// Print the error and restore it to the caller
		PyObject *type, *value, *traceback;
		PyErr_Fetch(&type, &value, &traceback);
		Py_XINCREF(type);
		Py_XINCREF(value);
		Py_XINCREF(traceback);

		Core::String error_message(128, "Failed to get entries for table %s row %d from python data source %s.", table.CString(), row_index, Utilities::GetPythonClassName(self).CString());
		Log::Message(LC_COREPYTHON, Log::LT_WARNING, "%s", error_message.CString());
		if (type == NULL)
			PyErr_SetString(PyExc_RuntimeError, error_message.CString());
		else
			PyErr_Restore(type, value, traceback);

		python::throw_error_already_set();
	}

	if (result)
		Py_DECREF(result);
}
bool
GetJSONVectorFromPyObject(PyObject *obj, JSONNode &vec)
{
    bool retval = true;

    if(obj == 0)
    {
        retval = false;
    }
    else if(PyBool_Check(obj))
    {
        vec = obj == Py_True ? true : false;
    }
    else if(PyTuple_Check(obj))
    {
        // Extract arguments from the tuple.
        vec = JSONNode::JSONArray();

        for(int i = 0; i < PyTuple_Size(obj); ++i)
        {
            PyObject *item = PyTuple_GET_ITEM(obj, i);
            JSONNode node;
            if(!GetJSONVectorFromPyObject(item,node))
                return false;
            vec.Append(node);
        }
    }
    else if(PyList_Check(obj))
    {
        vec = JSONNode::JSONArray();

        // Extract arguments from the list.
        for(int i = 0; i < PyList_Size(obj); ++i)
        {
            PyObject *item = PyList_GET_ITEM(obj, i);
            JSONNode node;
            if(!GetJSONVectorFromPyObject(item,node))
                return false;
            vec.Append(node);
        }
    }
    else if(PyString_Check(obj))
    {
        vec = PyString_AS_STRING(obj);
    }
    else if(PyInt_Check(obj))
    {
        vec = PyInt_AsLong(obj);
    }
    else if(PyFloat_Check(obj))
    {
        vec = PyFloat_AsDouble(obj);
    }
    else if(PyDict_Check(obj))
    {
        vec = JSONNode::JSONObject();

        PyObject* keys = PyDict_Keys(obj);
        for(int i = 0; i < PyList_Size(keys); ++i)
        {
            PyObject *item = PyList_GET_ITEM(keys, i);
            if(!PyString_Check(item))
            {
                std::cerr << "unknown element type, skipping " << std::endl;
                continue;
            }

            JSONNode node;

            std::string key = PyString_AsString(item);

            PyObject *value = PyDict_GetItem(obj,item);
            if(!GetJSONVectorFromPyObject(value,node))
                return false;
            vec[key] = node;
        }
    }
    else
    {
        retval = false;
        VisItErrorFunc("The object could not be converted to a "
                       "vector of strings.");
    }

    return retval;
}
예제 #20
0
/* Convert a Python object to a QVariant */
QVariant PyObject_AsQVariant(PyObject *obj)
{
    // Dict -> QVariantHash
    if (PyDict_Check(obj))
    {
        QVariantHash result;
        Py_ssize_t pos = 0;
        PyObject *pykey, *pyval;
        while (PyDict_Next(obj, &pos, &pykey, &pyval))
        {
            QString key = PyString_AsQString(pykey);
            result[key] = PyObject_AsQVariant(pyval);
        }
        return result;
    }
    // List -> QVariantList
    else if (PyList_Check(obj))
    {
        QVariantList result;
        Py_ssize_t len = PyList_Size(obj);
        for (Py_ssize_t i = 0; i < len; i++)
        {
            PyObject *item = PyList_GetItem(obj, i);
            result << PyObject_AsQVariant(item);
        }
        return result;
    }
    // Tuple -> QVariantList
    else if (PyTuple_Check(obj))
    {
        QVariantList result;
        Py_ssize_t len = PyTuple_Size(obj);
        for (Py_ssize_t i = 0; i < len; i++)
        {
            PyObject *item = PyTuple_GetItem(obj, i);
            result << PyObject_AsQVariant(item);
        }
        return result;
    }
    // Long
    else if (PyLong_Check(obj))
        return PyLong_AsLongLong(obj);

    // Int
#if PY_MAJOR_VERSION == 2
    else if (PyInt_Check(obj))
        return (long long) PyInt_AsLong(obj);
#endif

    // Float
    else if (PyFloat_Check(obj))
        return PyFloat_AsDouble(obj);

    // String
#if PY_MAJOR_VERSION >= 3
    else if (PyUnicode_Check(obj) || PyByteArray_Check(obj))
#else
    else if (PyUnicode_Check(obj) || PyString_Check(obj))
#endif
        return PyString_AsQString(obj);

    // Unknown
    else
    {
        qDebug("Error: convert an PyObject of unknown type to QVariant.");
        return QVariant();
    }
}
예제 #21
0
/**
 *******************************************************************************************************
 * This function invokes csdk's API's.
 *
 * @param self                  AerospikeClient object
 * @param err                   The as_error to be populated by the function
 *                              with the encountered error if any.
 * @param key                   The C client's as_key that identifies the record.
 * @param py_list               The list containing op, bin and value.
 * @param py_meta               The metadata for the operation.
 * @param operate_policy_p      The value for operate policy.
 *******************************************************************************************************
 */
static
PyObject *  AerospikeClient_Operate_Invoke(
	AerospikeClient * self, as_error *err,
	as_key * key, PyObject * py_list, PyObject * py_meta,
	as_policy_operate * operate_policy_p)
{
	as_val* put_val = NULL;
	char* bin = NULL;
	char* val = NULL;
	long offset = 0;
    double double_offset = 0.0;
	uint32_t ttl = 0;
	long operation = 0;
	int i = 0;
	PyObject * py_rec = NULL;
	PyObject * py_ustr = NULL;
	PyObject * py_ustr1 = NULL;
	PyObject * py_bin = NULL;
	as_record * rec = NULL;

	as_static_pool static_pool;
	memset(&static_pool, 0, sizeof(static_pool));

	as_operations ops;
	Py_ssize_t size = PyList_Size(py_list);
	as_operations_inita(&ops, size);

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

	if(py_meta) {
		AerospikeClient_CheckForMeta(py_meta, &ops, err);
	}

	if (err->code != AEROSPIKE_OK) {
		goto CLEANUP;
	}

	for ( i = 0; i < size; i++) {
		PyObject * py_val = PyList_GetItem(py_list, i);
		operation = -1;
		offset = 0;
        double_offset = 0.0;
		if ( PyDict_Check(py_val) ) {
			PyObject *key_op = NULL, *value = NULL;
			PyObject * py_value = NULL;
			Py_ssize_t pos = 0;
			while (PyDict_Next(py_val, &pos, &key_op, &value)) {
				if ( ! PyString_Check(key_op) ) {
					as_error_update(err, AEROSPIKE_ERR_CLIENT, "A operation key must be a string.");
					goto CLEANUP;
				} else {
					char * name = PyString_AsString(key_op);
					if(!strcmp(name,"op") && (PyInt_Check(value) || PyLong_Check(value))) {
						operation = PyInt_AsLong(value);
					} else if (!strcmp(name, "bin")) {
						py_bin = value;
					} else if(!strcmp(name, "val")) {
						py_value = value;
					} else {
						as_error_update(err, AEROSPIKE_ERR_PARAM, "operation can contain only op, bin and val keys");
						goto CLEANUP;
					}
				}
			}

			if (py_bin) {
				if (PyUnicode_Check(py_bin)) {
					py_ustr = PyUnicode_AsUTF8String(py_bin);
					bin = PyString_AsString(py_ustr);
				} else if (PyString_Check(py_bin)) {
					bin = PyString_AsString(py_bin);
				} else {
					as_error_update(err, AEROSPIKE_ERR_PARAM, "Bin name should be of type string");
					goto CLEANUP;
				}
			} else if (!py_bin && operation != AS_OPERATOR_TOUCH) {
				as_error_update(err, AEROSPIKE_ERR_PARAM, "Bin is not given");
				goto CLEANUP;
			}
			if (py_value) {
				if (check_type(self, py_value, operation, err)) {
                    goto CLEANUP;
				} else if (PyString_Check(py_value) && (operation == AS_OPERATOR_INCR)) {
                    char * incr_string = PyString_AsString(py_value);
                    int incr_value = 0, sign = 1;

                    if (strlen(incr_string) > 15) {
				        as_error_update(err, AEROSPIKE_ERR_PARAM, "Unsupported string length for increment operation");
                        goto CLEANUP;
                    }
                    if (*incr_string == '-') {
                        incr_string = incr_string + 1;
                        sign = -1;
                    } else if (*incr_string == '+') {
                        incr_string = incr_string + 1;
                        sign = 1;
                    }
                    while (*incr_string != '\0') {
                        if (*incr_string >= 48 && *incr_string <= 57) {
                            incr_value = (incr_value * 10) + (*incr_string ^ 0x30);
                        } else {
				            as_error_update(err, AEROSPIKE_ERR_PARAM, "Unsupported operand type(s) for +: 'int' and 'str'");
                            goto CLEANUP;
                        }
                        incr_string = incr_string + 1;
                    }
                    incr_value = incr_value * sign;
                    py_value = PyInt_FromLong(incr_value);
                }
			} else if ((!py_value) && (operation != AS_OPERATOR_READ)) {
				as_error_update(err, AEROSPIKE_ERR_PARAM, "Value should be given");
				goto CLEANUP;
			}

			switch(operation) {
				case AS_OPERATOR_APPEND:
					if (PyUnicode_Check(py_value)) {
						py_ustr1 = PyUnicode_AsUTF8String(py_value);
						val = PyString_AsString(py_ustr1);
					} else {
						val = PyString_AsString(py_value);
					}
					as_operations_add_append_str(&ops, bin, val);
					break;
				case AS_OPERATOR_PREPEND:
					if (PyUnicode_Check(py_value)) {
						py_ustr1 = PyUnicode_AsUTF8String(py_value);
						val = PyString_AsString(py_ustr1);
					} else {
						val = PyString_AsString(py_value);
					}
					as_operations_add_prepend_str(&ops, bin, val);
					break;
				case AS_OPERATOR_INCR:
					if (PyInt_Check(py_value)) {
                        offset = PyInt_AsLong(py_value);
                        as_operations_add_incr(&ops, bin, offset);
                    } else if ( PyLong_Check(py_value) ) {
                        offset = PyLong_AsLong(py_value);
                        if(-1 == offset) {
                            as_error_update(err, AEROSPIKE_ERR_PARAM, "integer value exceeds sys.maxsize");
                            goto CLEANUP;
                        }
                        as_operations_add_incr(&ops, bin, offset);
                    } else if (PyFloat_Check(py_value)) {
                        double_offset = PyFloat_AsDouble(py_value);
                        as_operations_add_incr_double(&ops, bin, double_offset);
                    }
                    break;
				case AS_OPERATOR_TOUCH:
					if (PyInt_Check(py_value)) {
                        ops.ttl = PyInt_AsLong(py_value);
                    } else if ( PyLong_Check(py_value) ) {
                        ttl = PyLong_AsLong(py_value);
                        if((uint32_t)-1 == ttl) {
                            as_error_update(err, AEROSPIKE_ERR_PARAM, "integer value for ttl exceeds sys.maxsize");
                            goto CLEANUP;
                        }
                        ops.ttl = ttl;
                    }
					as_operations_add_touch(&ops);
					break;
				case AS_OPERATOR_READ:
					as_operations_add_read(&ops, bin);
					break;
				case AS_OPERATOR_WRITE:
					pyobject_to_astype_write(self, err, bin, py_value, &put_val, &ops,
							&static_pool, SERIALIZER_PYTHON);
					if (err->code != AEROSPIKE_OK) {
						goto CLEANUP;
					}
					as_operations_add_write(&ops, bin, (as_bin_value *) put_val);
					break;
				default:
					as_error_update(err, AEROSPIKE_ERR_PARAM, "Invalid operation given");
			}
		}
	}

	// Initialize record
	as_record_init(rec, 0);

	aerospike_key_operate(self->as, err, operate_policy_p, key, &ops, &rec);
	if (err->code != AEROSPIKE_OK) {
		as_error_update(err, err->code, NULL);
		goto CLEANUP;
	}
	if(rec) {
		record_to_pyobject(err, rec, key, &py_rec);
	}

CLEANUP:
	if (py_ustr) {
		Py_DECREF(py_ustr);
	}
	if (py_ustr1) {
		Py_DECREF(py_ustr1);
	}
	if (rec) {
		as_record_destroy(rec);
	}
	if (key->valuep) {
		as_key_destroy(key);
	}
	if (put_val) {
		as_val_destroy(put_val);
	}

	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;
	}

	if (py_rec) {
		return py_rec;
	} else {
		return PyLong_FromLong(0);
	}
}
예제 #22
0
파일: path.c 프로젝트: agross91/pil-py3k
int
PyPath_Flatten(PyObject* data, double **pxy)
{
    int i, j, n;
    double *xy;
    PyBufferProcs *buffer;
	Py_buffer view;

    if (PyPath_Check(data)) {
	/* This was another path object. */
	PyPathObject *path = (PyPathObject*) data;
        xy = alloc_array(path->count);
	if (!xy)
	    return -1;
	memcpy(xy, path->xy, 2 * path->count * sizeof(double));
	*pxy = xy;
	return path->count;
    }
	
    buffer = Py_TYPE(data)->tp_as_buffer;
    if (buffer && buffer->bf_getbuffer &&
			 (*buffer->bf_getbuffer)(data, &view, PyBUF_SIMPLE) == 1) {
        /* Assume the buffer contains floats */
        float* ptr;
        int n = view.len;
	    PyBuffer_Release(&view);
        n /= 2 * sizeof(float);
        xy = alloc_array(n);
        if (!xy)
            return -1;
        for (i = 0; i < n+n; i++)
            xy[i] = ptr[i];
        *pxy = xy;
        return n;
    }

    if (!PySequence_Check(data)) {
	PyErr_SetString(PyExc_TypeError, "argument must be sequence");
	return -1;
    }

    j = 0;
    n = PyObject_Length(data);
    /* Just in case __len__ breaks (or doesn't exist) */
    if (PyErr_Occurred())
        return -1;

    /* Allocate for worst case */
    xy = alloc_array(n);
    if (!xy)
	return -1;

    /* Copy table to path array */
    if (PyList_Check(data)) {
        for (i = 0; i < n; i++) {
            double x, y;
            PyObject *op = PyList_GET_ITEM(data, i);
            if (PyFloat_Check(op))
		xy[j++] = PyFloat_AS_DOUBLE(op);
            else if (PyLong_Check(op))
		xy[j++] = (float) PyLong_AS_LONG(op);
            else if (PyNumber_Check(op))
                xy[j++] = PyFloat_AsDouble(op);
            else if (PyArg_ParseTuple(op, "dd", &x, &y)) {
                xy[j++] = x;
                xy[j++] = y;
            } else {
                free(xy);
                return -1;
            }
        }
    } else if (PyTuple_Check(data)) {
        for (i = 0; i < n; i++) {
            double x, y;
            PyObject *op = PyTuple_GET_ITEM(data, i);
            if (PyFloat_Check(op))
		xy[j++] = PyFloat_AS_DOUBLE(op);
            else if (PyLong_Check(op))
		xy[j++] = (float) PyLong_AS_LONG(op);
            else if (PyNumber_Check(op))
                xy[j++] = PyFloat_AsDouble(op);
            else if (PyArg_ParseTuple(op, "dd", &x, &y)) {
                xy[j++] = x;
                xy[j++] = y;
            } else {
                free(xy);
                return -1;
            }
        }
    } else {
        for (i = 0; i < n; i++) {
            double x, y;
            PyObject *op = PySequence_GetItem(data, i);
            if (!op) {
                /* treat IndexError as end of sequence */
                if (PyErr_Occurred() &&
                    PyErr_ExceptionMatches(PyExc_IndexError)) {
                    PyErr_Clear();
                    break;
                } else {
                    free(xy);
                    return -1;
                }
            }
            if (PyFloat_Check(op))
		xy[j++] = PyFloat_AS_DOUBLE(op);
            else if (PyLong_Check(op))
		xy[j++] = (float) PyLong_AS_LONG(op);
            else if (PyNumber_Check(op))
                xy[j++] = PyFloat_AsDouble(op);
            else if (PyArg_ParseTuple(op, "dd", &x, &y)) {
                xy[j++] = x;
                xy[j++] = y;
            } else {
                Py_DECREF(op);
                free(xy);
                return -1;
            }
            Py_DECREF(op);
        }
    }

    if (j & 1) {
	PyErr_SetString(PyExc_ValueError, "wrong number of coordinates");
	free(xy);
	return -1;
    }

    *pxy = xy;
    return j/2;
}
예제 #23
0
static PyObject *
complex_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
	PyObject *r, *i, *tmp, *f;
	PyNumberMethods *nbr, *nbi = NULL;
	Py_complex cr, ci;
	int own_r = 0;
	int cr_is_complex = 0;
	int ci_is_complex = 0;
	static PyObject *complexstr;
	static char *kwlist[] = {"real", "imag", 0};

	r = Py_False;
	i = NULL;
	if (!PyArg_ParseTupleAndKeywords(args, kwds, "|OO:complex", kwlist,
					 &r, &i))
		return NULL;

	/* Special-case for a single argument when type(arg) is complex. */
	if (PyComplex_CheckExact(r) && i == NULL &&
	    type == &PyComplex_Type) {
		/* Note that we can't know whether it's safe to return
		   a complex *subclass* instance as-is, hence the restriction
		   to exact complexes here.  If either the input or the
		   output is a complex subclass, it will be handled below 
		   as a non-orthogonal vector.  */
		Py_INCREF(r);
		return r;
	}
	if (PyString_Check(r) || PyUnicode_Check(r)) {
		if (i != NULL) {
			PyErr_SetString(PyExc_TypeError,
					"complex() can't take second arg"
					" if first is a string");
			return NULL;
		}
		return complex_subtype_from_string(type, r);
	}
	if (i != NULL && (PyString_Check(i) || PyUnicode_Check(i))) {
		PyErr_SetString(PyExc_TypeError,
				"complex() second arg can't be a string");
		return NULL;
	}

	/* XXX Hack to support classes with __complex__ method */
	if (complexstr == NULL) {
		complexstr = PyString_InternFromString("__complex__");
		if (complexstr == NULL)
			return NULL;
	}
	f = PyObject_GetAttr(r, complexstr);
	if (f == NULL)
		PyErr_Clear();
	else {
		PyObject *args = PyTuple_New(0);
		if (args == NULL)
			return NULL;
		r = PyEval_CallObject(f, args);
		Py_DECREF(args);
		Py_DECREF(f);
		if (r == NULL)
			return NULL;
		own_r = 1;
	}
	nbr = r->ob_type->tp_as_number;
	if (i != NULL)
		nbi = i->ob_type->tp_as_number;
	if (nbr == NULL || nbr->nb_float == NULL ||
	    ((i != NULL) && (nbi == NULL || nbi->nb_float == NULL))) {
		PyErr_SetString(PyExc_TypeError,
			   "complex() argument must be a string or a number");
		if (own_r) {
			Py_DECREF(r);
		}
		return NULL;
	}

	/* If we get this far, then the "real" and "imag" parts should
	   both be treated as numbers, and the constructor should return a
	   complex number equal to (real + imag*1j).

 	   Note that we do NOT assume the input to already be in canonical
	   form; the "real" and "imag" parts might themselves be complex
	   numbers, which slightly complicates the code below. */
	if (PyComplex_Check(r)) {
		/* Note that if r is of a complex subtype, we're only
		   retaining its real & imag parts here, and the return
		   value is (properly) of the builtin complex type. */
		cr = ((PyComplexObject*)r)->cval;
		cr_is_complex = 1;
		if (own_r) {
			Py_DECREF(r);
		}
	}
	else {
		/* The "real" part really is entirely real, and contributes
		   nothing in the imaginary direction.  
		   Just treat it as a double. */
		tmp = PyNumber_Float(r);
		if (own_r) {
			/* r was a newly created complex number, rather
			   than the original "real" argument. */
			Py_DECREF(r);
		}
		if (tmp == NULL)
			return NULL;
		if (!PyFloat_Check(tmp)) {
			PyErr_SetString(PyExc_TypeError,
					"float(r) didn't return a float");
			Py_DECREF(tmp);
			return NULL;
		}
		cr.real = PyFloat_AsDouble(tmp);
		cr.imag = 0.0; /* Shut up compiler warning */
		Py_DECREF(tmp);
	}
	if (i == NULL) {
		ci.real = 0.0;
	}
	else if (PyComplex_Check(i)) {
		ci = ((PyComplexObject*)i)->cval;
		ci_is_complex = 1;
	} else {
		/* The "imag" part really is entirely imaginary, and
		   contributes nothing in the real direction.
		   Just treat it as a double. */
		tmp = (*nbi->nb_float)(i);
		if (tmp == NULL)
			return NULL;
		ci.real = PyFloat_AsDouble(tmp);
		Py_DECREF(tmp);
	}
	/*  If the input was in canonical form, then the "real" and "imag"
	    parts are real numbers, so that ci.imag and cr.imag are zero.
	    We need this correction in case they were not real numbers. */

	if (ci_is_complex) {
		cr.real -= ci.imag;
	}
	if (cr_is_complex) {
		ci.real += cr.imag;
	}
	return complex_subtype_from_doubles(type, cr.real, ci.real);
}
예제 #24
0
// Convert Python lists to CvMat *
CvArr * PySequence_to_CvArr (PyObject * obj)
{
  int        dims     [CV_MAX_DIM]   = {   1,    1,    1};
  PyObject * container[CV_MAX_DIM+1] = {NULL, NULL, NULL, NULL};
  int        ndim                    = 0;
  PyObject * item                    = Py_None;
  
  // TODO: implement type detection - currently we create CV_64F only
  // scan full array to
  // - figure out dimensions
  // - check consistency of dimensions
  // - find appropriate data-type and signedness
  //  enum NEEDED_DATATYPE { NEEDS_CHAR, NEEDS_INTEGER, NEEDS_FLOAT, NEEDS_DOUBLE };
  //  NEEDED_DATATYPE needed_datatype = NEEDS_CHAR;
  //  bool            needs_sign      = false;
  
  // scan first entries to find out dimensions
  for (item = obj, ndim = 0; PySequence_Check (item) && ndim <= CV_MAX_DIM; ndim++)
  {
    dims [ndim]      = PySequence_Size    (item);
    container [ndim] = PySequence_GetItem (item, 0); 
    item             = container[ndim];
  }
  
  // in contrast to PyTuple_GetItem, PySequence_GetItame returns a NEW reference
  if (container[0])
  {
    Py_DECREF (container[0]);
  }
  if (container[1])
  {
    Py_DECREF (container[1]);
  }
  if (container[2])
  {
    Py_DECREF (container[2]);
  }
  if (container[3])
  {
    Py_DECREF (container[3]);
  }
  
  // it only makes sense to support 2 and 3 dimensional data at this time
  if (ndim < 2 || ndim > 3)
  {
    PyErr_SetString (PyExc_TypeError, "Nested sequences should have 2 or 3 dimensions");
    return NULL;
  }
  
  // also, the number of channels should match what's typical for OpenCV
  if (ndim == 3  &&  (dims[2] < 1  ||  dims[2] > 4))
  {
    PyErr_SetString (PyExc_TypeError, "Currently, the third dimension of CvMat only supports 1 to 4 channels");
    return NULL;
  }
  
  // CvMat
  CvMat * matrix = cvCreateMat (dims[0], dims[1], CV_MAKETYPE (CV_64F, dims[2]));
  
  for (int y = 0; y < dims[0]; y++)
  {
    PyObject * rowobj = PySequence_GetItem (obj, y);
    
    // double check size
    if (PySequence_Check (rowobj)  &&  PySequence_Size (rowobj) == dims[1])
    {
      for (int x = 0; x < dims[1]; x++)
      {
        PyObject * colobj = PySequence_GetItem (rowobj, x);
        
        if (dims [2] > 1)
        {
          if (PySequence_Check (colobj)  &&  PySequence_Size (colobj) == dims[2])
          {
            PyObject * tuple = PySequence_Tuple (colobj);
            
            double  a, b, c, d;
            if (PyArg_ParseTuple (colobj, "d|d|d|d", &a, &b, &c, &d))
            {
              cvSet2D (matrix, y, x, cvScalar (a, b, c, d));
            }
            else 
            {
              PyErr_SetString (PyExc_TypeError, "OpenCV only accepts numbers that can be converted to float");
              cvReleaseMat (& matrix);
              Py_DECREF (tuple);
              Py_DECREF (colobj);
              Py_DECREF (rowobj);
              return NULL;
            }

            Py_DECREF (tuple);
          }
          else
          {
            PyErr_SetString (PyExc_TypeError, "All sub-sequences must have the same number of entries");
            cvReleaseMat (& matrix);
            Py_DECREF (colobj);
            Py_DECREF (rowobj);
            return NULL;
          }
        }
        else
        {
          if (PyFloat_Check (colobj) || PyInt_Check (colobj))
          {
            cvmSet (matrix, y, x, PyFloat_AsDouble (colobj));
          }
          else
          {
            PyErr_SetString (PyExc_TypeError, "OpenCV only accepts numbers that can be converted to float");
            cvReleaseMat (& matrix);
            Py_DECREF (colobj);
            Py_DECREF (rowobj);
            return NULL;
          }
        }
        
        Py_DECREF (colobj);
      }
    }
    else
    {
      PyErr_SetString (PyExc_TypeError, "All sub-sequences must have the same number of entries");
      cvReleaseMat (& matrix);
      Py_DECREF (rowobj);
      return NULL;
    }
    
    Py_DECREF (rowobj);
  }
  
  return matrix;
}
예제 #25
0
static PyObject *
csv_writerow(WriterObj *self, PyObject *seq)
{
    DialectObj *dialect = self->dialect;
    int len, i;

    if (!PySequence_Check(seq))
        return PyErr_Format(error_obj, "sequence expected");

    len = PySequence_Length(seq);
    if (len < 0)
        return NULL;

    /* Join all fields in internal buffer.
     */
    join_reset(self);
    for (i = 0; i < len; i++) {
        PyObject *field;
        int append_ok;
        int quoted;

        field = PySequence_GetItem(seq, i);
        if (field == NULL)
            return NULL;

        switch (dialect->quoting) {
        case QUOTE_NONNUMERIC:
            quoted = !PyNumber_Check(field);
            break;
        case QUOTE_ALL:
            quoted = 1;
            break;
        default:
            quoted = 0;
            break;
        }

        if (PyString_Check(field)) {
            append_ok = join_append(self,
                                    PyString_AS_STRING(field),
                                    &quoted, len == 1);
            Py_DECREF(field);
        }
        else if (field == Py_None) {
            append_ok = join_append(self, "", &quoted, len == 1);
            Py_DECREF(field);
        }
        else {
            PyObject *str;

            if (PyFloat_Check(field)) {
                str = PyObject_Repr(field);
            } else {
                str = PyObject_Str(field);
            }
            Py_DECREF(field);
            if (str == NULL)
                return NULL;

            append_ok = join_append(self, PyString_AS_STRING(str),
                                    &quoted, len == 1);
            Py_DECREF(str);
        }
        if (!append_ok)
            return NULL;
    }

    /* Add line terminator.
     */
    if (!join_append_lineterminator(self))
        return 0;

    return PyObject_CallFunction(self->writeline,
                                 "(s#)", self->rec, self->rec_len);
}
예제 #26
0
PyObject* scribus_setproperty(PyObject* /*self*/, PyObject* args, PyObject* kw)
{
	PyObject* objArg = NULL;
	char* propertyName = NULL;
	PyObject* objValue = NULL;
	char* kwargs[] = {const_cast<char*>("object"),
					  const_cast<char*>("property"),
					  const_cast<char*>("value"),
					  NULL};
	if (!PyArg_ParseTupleAndKeywords(args, kw, "OesO", kwargs,
				&objArg, "ascii", &propertyName, &objValue))
		return NULL;

	// We're going to hang on to the value object for a while, so
	// claim a reference to it.
	Py_INCREF(objValue);

	// Get the QObject* the object argument refers to
	QObject* obj = getQObjectFromPyArg(objArg);
	if (!obj)
		return NULL;
	objArg = NULL; // no need to decref, it's borrowed

	const QString propertyType = getpropertytype(obj, propertyName, true);

	// Did we know how to convert the value argument to the right type?
	bool matched = false;
	// Did the set call succceed?
	bool success = false;

	// Check the C++ type of the property, and try to convert the passed
	// PyObject to something sensible looking for it.
	// FIXME: handle enums/sets
	// NUMERIC TYPES
	// These are unfortuately a TOTAL PITA because of the multitude of
	// C and Python numeric types. TODO This needs to be broken out into a subroutine.
	if (propertyType == "bool")
	{
		matched = true;
		if (PyObject_IsTrue(objValue) == 0)
			success = obj->setProperty(propertyName, 0);
		else if (PyObject_IsTrue(objValue) == 1)
			success = obj->setProperty(propertyName, 1);
		else if (PyInt_Check(objValue))
			success = obj->setProperty(propertyName, PyInt_AsLong(objValue) == 0);
		else if (PyLong_Check(objValue))
			success = obj->setProperty(propertyName, PyLong_AsLong(objValue) == 0);
		else
			matched = false;
	}
	else if (propertyType == "int")
	{
		matched = true;
		if (PyObject_IsTrue(objValue) == 0)
			success = obj->setProperty(propertyName, 0);
		else if (PyObject_IsTrue(objValue) == 1)
			success = obj->setProperty(propertyName, 1);
		else if (PyInt_Check(objValue))
			success = obj->setProperty(propertyName, (int)PyInt_AsLong(objValue));
		else if (PyLong_Check(objValue))
			success = obj->setProperty(propertyName, (int)PyLong_AsLong(objValue));
		else
			matched = false;
	}
	else if (propertyType == "double")
	{
		matched = true;
		// FIXME: handle int, long  and bool too
		if (PyFloat_Check(objValue))
			success = obj->setProperty(propertyName, PyFloat_AsDouble(objValue));
		else
			matched = false;
	}
	// STRING TYPES
	else if (propertyType == "QString")
	{
		matched = true;
		if (PyString_Check(objValue))
			success = obj->setProperty(propertyName, QString::fromUtf8(PyString_AsString(objValue)));
		else if (PyUnicode_Check(objValue))
		{
			// Get a pointer to the internal buffer of the Py_Unicode object, which is UCS2 formatted
			const unsigned short * ucs2Data = (const unsigned short *)PyUnicode_AS_UNICODE(objValue);
			// and make a new QString from it (the string is copied)
			success = obj->setProperty(propertyName, QString::fromUtf16(ucs2Data));
		}
		else
			matched = false;
	}
	else if (propertyType == "QCString")
	{
		matched = true;
		if (PyString_Check(objValue))
		{
			// FIXME: should raise an exception instead of mangling the string when
			// out of charset chars present.
			QString utfString = QString::fromUtf8(PyString_AsString(objValue));
			success = obj->setProperty(propertyName, utfString.toAscii());
		}
		else if (PyUnicode_Check(objValue))
		{
			// Get a pointer to the internal buffer of the Py_Unicode object, which is UCS2 formatted
			const unsigned short * utf16Data = (const unsigned short *)PyUnicode_AS_UNICODE(objValue);
			// and make a new QString from it (the string is copied)
			success = obj->setProperty(propertyName, QString::fromUtf16(utf16Data).toAscii());
		}
		else
			matched = false;
	}
	// HIGHER ORDER TYPES
	// ... which I can't be stuffed supporting yet. FIXME.
	else
	{
		Py_DECREF(objValue);
		PyErr_SetString(PyExc_TypeError,
				QObject::tr("Property type '%1' not supported").arg(propertyType).toLocal8Bit().constData());
		return NULL;
	}

	// If `matched' is false, we recognised the C type but weren't able to
	// convert the passed Python value to anything suitable.
	if (!matched)
	{
		// Get a string representation of the object
		PyObject* objRepr = PyObject_Repr(objValue);
		Py_DECREF(objValue); // We're done with it now
		if (!objRepr)
			return NULL;
		// Extract the repr() string
		QString reprString = QString::fromUtf8(PyString_AsString(objRepr));
		Py_DECREF(objRepr);

		// And return an error
		PyErr_SetString(PyExc_TypeError,
				QObject::tr("Couldn't convert '%1' to property type '%2'").arg(reprString).arg(propertyType).toLocal8Bit().constData());
		return NULL;
	}

	// `success' is the return value of the setProperty() call
	if (!success)
	{
		Py_DECREF(objValue);
		PyErr_SetString(PyExc_ValueError, QObject::tr("Types matched, but setting property failed.").toLocal8Bit().constData());
		return NULL;
	}

	Py_DECREF(objValue);
//	Py_INCREF(Py_None);
//	return Py_None;
	Py_RETURN_NONE;
}
예제 #27
0
void Object_beginTypeContext (JSOBJ _obj, JSONTypeContext *tc)
{
  PyObject *obj, *exc, *toDictFunc;
  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))
    {
#if HAS_JSON_HANDLE_BIGINTS
      PyErr_Clear();
      pc->PyTypeToJSON = PyBigIntToSTR;
      tc->type = JT_BIGINT;
      GET_TC(tc)->longValue = 0;
      return;
#endif
      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;
  }

  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();

  PRINTMARK();
  // Falling to INVALID case as this type of object(class instance, module,
  // class, function, etc..) can't be serialized.
  PyErr_Format (PyExc_TypeError, "%s", "Object is not JSON serializable");

INVALID:
  tc->type = JT_INVALID;
  PyObject_Free(tc->prv);
  tc->prv = NULL;
  return;
}
/*static*/ PyObject *
ConstructDataBinningAttributes_SetBinType(PyObject *self, PyObject *args)
{
    ConstructDataBinningAttributesObject *obj = (ConstructDataBinningAttributesObject *)self;

    unsignedCharVector  &vec = obj->data->GetBinType();
    PyObject     *tuple;
    if(!PyArg_ParseTuple(args, "O", &tuple))
        return NULL;

    if(PyTuple_Check(tuple))
    {
        vec.resize(PyTuple_Size(tuple));
        for(int i = 0; i < PyTuple_Size(tuple); ++i)
        {
            int c;
            PyObject *item = PyTuple_GET_ITEM(tuple, i);
            if(PyFloat_Check(item))
                c = int(PyFloat_AS_DOUBLE(item));
            else if(PyInt_Check(item))
                c = int(PyInt_AS_LONG(item));
            else if(PyLong_Check(item))
                c = int(PyLong_AsDouble(item));
            else
                c = 0;

            if(c < 0) c = 0;
            if(c > 255) c = 255;
            vec[i] = (unsigned char)(c);
        }
    }
    else if(PyFloat_Check(tuple))
    {
        vec.resize(1);
        int c = int(PyFloat_AS_DOUBLE(tuple));
        if(c < 0) c = 0;
        if(c > 255) c = 255;
        vec[0] = (unsigned char)(c);
    }
    else if(PyInt_Check(tuple))
    {
        vec.resize(1);
        int c = int(PyInt_AS_LONG(tuple));
        if(c < 0) c = 0;
        if(c > 255) c = 255;
        vec[0] = (unsigned char)(c);
    }
    else if(PyLong_Check(tuple))
    {
        vec.resize(1);
        int c = PyLong_AsLong(tuple);
        if(c < 0) c = 0;
        if(c > 255) c = 255;
        vec[0] = (unsigned char)(c);
    }
    else
        return NULL;

    // Mark the binType in the object as modified.
    obj->data->SelectBinType();

    Py_INCREF(Py_None);
    return Py_None;
}
예제 #29
0
static PyObject *
Text3DObject_SetTextColor(PyObject *self, PyObject *args)
{
    Text3DObjectObject *obj = (Text3DObjectObject *)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;
}
예제 #30
0
static bool GetParameterInfo(Cursor* cur, Py_ssize_t index, PyObject* param, ParamInfo& info)
{
    // Determines the type of SQL parameter that will be used for this parameter based on the Python data type.
    //
    // Populates `info`.

    // TODO: if the param is a SQLParameter object, then bind to the wrapped value and use the input/output type from that

    // Hold a reference to param until info is freed, because info will often be holding data borrowed from param.
    if (PyObject_TypeCheck(param, (PyTypeObject*)SQLParameter_type))
    {
        info.pParam = ((SQLParameter*)param)->value;
        info.InputOutputType = ((SQLParameter*)param)->type;
    }
    else
    {
        info.pParam = param;
        info.InputOutputType = SQL_PARAM_INPUT;
    }

    if (info.pParam == Py_None)
        return GetNullInfo(cur, index, info);

    if (info.pParam == null_binary)
        return GetNullBinaryInfo(cur, index, info);

    if (PyBytes_Check(info.pParam))
        return GetBytesInfo(cur, index, info.pParam, info);

    if (PyUnicode_Check(info.pParam))
        return GetUnicodeInfo(cur, index, info.pParam, info);

    if (PyBool_Check(info.pParam))
        return GetBooleanInfo(cur, index, info.pParam, info);

    if (PyDateTime_Check(info.pParam))
        return GetDateTimeInfo(cur, index, info.pParam, info);

    if (PyDate_Check(info.pParam))
        return GetDateInfo(cur, index, info.pParam, info);

    if (PyTime_Check(info.pParam))
        return GetTimeInfo(cur, index, info.pParam, info);

    if (PyLong_Check(info.pParam))
        return GetLongInfo(cur, index, info.pParam, info);

    if (PyFloat_Check(info.pParam))
        return GetFloatInfo(cur, index, info.pParam, info);

    if (PyDecimal_Check(info.pParam))
        return GetDecimalInfo(cur, index, info.pParam, info);

#if PY_VERSION_HEX >= 0x02060000
    if (PyByteArray_Check(info.pParam))
        return GetByteArrayInfo(cur, index, info.pParam, info);
#endif

#if PY_MAJOR_VERSION < 3
    if (PyInt_Check(info.pParam))
        return GetIntInfo(cur, index, info.pParam, info);

    if (PyBuffer_Check(info.pParam))
        return GetBufferInfo(cur, index, info.pParam, info);
#endif

    RaiseErrorV("HY105", ProgrammingError, "Invalid parameter type.  param-index=%zd param-type=%s", index, Py_TYPE(info.pParam)->tp_name);
    return false;
}