当前位置: 首页>>代码示例>>C++>>正文


C++ PyFloat_AsDouble函数代码示例

本文整理汇总了C++中PyFloat_AsDouble函数的典型用法代码示例。如果您正苦于以下问题:C++ PyFloat_AsDouble函数的具体用法?C++ PyFloat_AsDouble怎么用?C++ PyFloat_AsDouble使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了PyFloat_AsDouble函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。

示例1: select_select

static PyObject *
select_select(PyObject *self, PyObject *args)
{
#ifdef SELECT_USES_HEAP
	pylist *rfd2obj, *wfd2obj, *efd2obj;
#else  /* !SELECT_USES_HEAP */
	/* XXX: All this should probably be implemented as follows:
	 * - find the highest descriptor we're interested in
	 * - add one
	 * - that's the size
	 * See: Stevens, APitUE, $12.5.1
	 */
	pylist rfd2obj[FD_SETSIZE + 1];
	pylist wfd2obj[FD_SETSIZE + 1];
	pylist efd2obj[FD_SETSIZE + 1];
#endif /* SELECT_USES_HEAP */
	PyObject *ifdlist, *ofdlist, *efdlist;
	PyObject *ret = NULL;
	PyObject *tout = Py_None;
	fd_set ifdset, ofdset, efdset;
	double timeout;
	struct timeval tv, *tvp;
	long seconds;
	int imax, omax, emax, max;
	int n;

	/* convert arguments */
	if (!PyArg_ParseTuple(args, "OOO|O:select",
			      &ifdlist, &ofdlist, &efdlist, &tout))
		return NULL;

	if (tout == Py_None)
		tvp = (struct timeval *)0;
	else if (!PyNumber_Check(tout)) {
		PyErr_SetString(PyExc_TypeError,
				"timeout must be a float or None");
		return NULL;
	}
	else {
		timeout = PyFloat_AsDouble(tout);
		if (timeout == -1 && PyErr_Occurred())
			return NULL;
		if (timeout > (double)LONG_MAX) {
			PyErr_SetString(PyExc_OverflowError,
					"timeout period too long");
			return NULL;
		}
		seconds = (long)timeout;
		timeout = timeout - (double)seconds;
		tv.tv_sec = seconds;
		tv.tv_usec = (long)(timeout*1000000.0);
		tvp = &tv;
	}


#ifdef SELECT_USES_HEAP
	/* Allocate memory for the lists */
	rfd2obj = PyMem_NEW(pylist, FD_SETSIZE + 1);
	wfd2obj = PyMem_NEW(pylist, FD_SETSIZE + 1);
	efd2obj = PyMem_NEW(pylist, FD_SETSIZE + 1);
	if (rfd2obj == NULL || wfd2obj == NULL || efd2obj == NULL) {
		if (rfd2obj) PyMem_DEL(rfd2obj);
		if (wfd2obj) PyMem_DEL(wfd2obj);
		if (efd2obj) PyMem_DEL(efd2obj);
		return PyErr_NoMemory();
	}
#endif /* SELECT_USES_HEAP */
	/* Convert sequences to fd_sets, and get maximum fd number
	 * propagates the Python exception set in seq2set()
	 */
	rfd2obj[0].sentinel = -1;
	wfd2obj[0].sentinel = -1;
	efd2obj[0].sentinel = -1;
	if ((imax=seq2set(ifdlist, &ifdset, rfd2obj)) < 0) 
		goto finally;
	if ((omax=seq2set(ofdlist, &ofdset, wfd2obj)) < 0) 
		goto finally;
	if ((emax=seq2set(efdlist, &efdset, efd2obj)) < 0) 
		goto finally;
	max = imax;
	if (omax > max) max = omax;
	if (emax > max) max = emax;

	Py_BEGIN_ALLOW_THREADS
	n = select(max, &ifdset, &ofdset, &efdset, tvp);
	Py_END_ALLOW_THREADS

#ifdef MS_WINDOWS
	if (n == SOCKET_ERROR) {
		PyErr_SetExcFromWindowsErr(SelectError, WSAGetLastError());
	}
#else
	if (n < 0) {
		PyErr_SetFromErrno(SelectError);
	}
#endif
	else if (n == 0) {
                /* optimization */
		ifdlist = PyList_New(0);
		if (ifdlist) {
//.........这里部分代码省略.........
开发者ID:Oize,项目名称:pspstacklesspython,代码行数:101,代码来源:selectmodule.c

示例2: complex_new


//.........这里部分代码省略.........
    }
    else if (PyErr_Occurred()) {
        return NULL;
    }

    nbr = r->ob_type->tp_as_number;
    if (nbr == NULL || nbr->nb_float == NULL) {
        PyErr_Format(PyExc_TypeError,
                     "complex() first argument must be a string or a number, "
                     "not '%.200s'",
                     Py_TYPE(r)->tp_name);
        if (own_r) {
            Py_DECREF(r);
        }
        return NULL;
    }
    if (i != NULL) {
        nbi = i->ob_type->tp_as_number;
        if (nbi == NULL || nbi->nb_float == NULL) {
            PyErr_Format(PyExc_TypeError,
                         "complex() second argument must be a number, "
                         "not '%.200s'",
                         Py_TYPE(i)->tp_name);
            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;
        Py_DECREF(tmp);
    }
    if (i == NULL) {
        // BUG: ci.real = cr.imag;
        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;
    }
    // BUG:
    // if (cr_is_complex && i != NULL) {
    if (cr_is_complex) {
        ci.real += cr.imag;
    }
    return complex_subtype_from_doubles(type, cr.real, ci.real);
}
开发者ID:JamMarHer,项目名称:RepairBox,代码行数:101,代码来源:complexobject.c

示例3: output_val

static int
output_val(PyObject* output, PyObject* value, TType type, PyObject* typeargs) {
  /*
   * Refcounting Strategy:
   *
   * We assume that elements of the thrift_spec tuple are not going to be
   * mutated, so we don't ref count those at all. Other than that, we try to
   * keep a reference to all the user-created objects while we work with them.
   * output_val assumes that a reference is already held. The *caller* is
   * responsible for handling references
   */

  switch (type) {

  case T_BOOL: {
    int v = PyObject_IsTrue(value);
    if (v == -1) {
      return false;
    }

    writeByte(output, (int8_t) v);
    break;
  }
  case T_I08: {
    int32_t val;

    if (!parse_pyint(value, &val, INT8_MIN, INT8_MAX)) {
      return false;
    }

    writeByte(output, (int8_t) val);
    break;
  }
  case T_I16: {
    int32_t val;

    if (!parse_pyint(value, &val, INT16_MIN, INT16_MAX)) {
      return false;
    }

    writeI16(output, (int16_t) val);
    break;
  }
  case T_I32: {
    int32_t val;

    if (!parse_pyint(value, &val, INT32_MIN, INT32_MAX)) {
      return false;
    }

    writeI32(output, val);
    break;
  }
  case T_I64: {
    int64_t nval = PyLong_AsLongLong(value);

    if (INT_CONV_ERROR_OCCURRED(nval)) {
      return false;
    }

    if (!CHECK_RANGE(nval, INT64_MIN, INT64_MAX)) {
      PyErr_SetString(PyExc_OverflowError, "int out of range");
      return false;
    }

    writeI64(output, nval);
    break;
  }

  case T_DOUBLE: {
    double nval = PyFloat_AsDouble(value);
    if (nval == -1.0 && PyErr_Occurred()) {
      return false;
    }

    writeDouble(output, nval);
    break;
  }

  case T_STRING: {
    Py_ssize_t len = PyString_Size(value);

    if (!check_ssize_t_32(len)) {
      return false;
    }

    writeI32(output, (int32_t) len);
    PycStringIO->cwrite(output, PyString_AsString(value), (int32_t) len);
    break;
  }

  case T_LIST:
  case T_SET: {
    Py_ssize_t len;
    SetListTypeArgs parsedargs;
    PyObject *item;
    PyObject *iterator;

    if (!parse_set_list_args(&parsedargs, typeargs)) {
      return false;
//.........这里部分代码省略.........
开发者ID:ahfeel,项目名称:thrift,代码行数:101,代码来源:fastbinary.c

示例4: run

/**
 * Function to call to evaluate model
 * @param args: input q or [q,phi]
 * @return: function value
 */
static PyObject * run(CFlexCylEllipXModel *self, PyObject *args) {
	double q_value, phi_value;
	PyObject* pars;
	int npars;
	
	// Get parameters
	
	    // Reader parameter dictionary
    self->model->scale = PyFloat_AsDouble( PyDict_GetItemString(self->params, "scale") );
    self->model->sldCyl = PyFloat_AsDouble( PyDict_GetItemString(self->params, "sldCyl") );
    self->model->axis_ratio = PyFloat_AsDouble( PyDict_GetItemString(self->params, "axis_ratio") );
    self->model->length = PyFloat_AsDouble( PyDict_GetItemString(self->params, "length") );
    self->model->radius = PyFloat_AsDouble( PyDict_GetItemString(self->params, "radius") );
    self->model->background = PyFloat_AsDouble( PyDict_GetItemString(self->params, "background") );
    self->model->sldSolv = PyFloat_AsDouble( PyDict_GetItemString(self->params, "sldSolv") );
    self->model->kuhn_length = PyFloat_AsDouble( PyDict_GetItemString(self->params, "kuhn_length") );
    // Read in dispersion parameters
    PyObject* disp_dict;
    DispersionVisitor* visitor = new DispersionVisitor();
    disp_dict = PyDict_GetItemString(self->dispersion, "length");
    self->model->length.dispersion->accept_as_destination(visitor, self->model->length.dispersion, disp_dict);
    disp_dict = PyDict_GetItemString(self->dispersion, "kuhn_length");
    self->model->kuhn_length.dispersion->accept_as_destination(visitor, self->model->kuhn_length.dispersion, disp_dict);
    disp_dict = PyDict_GetItemString(self->dispersion, "radius");
    self->model->radius.dispersion->accept_as_destination(visitor, self->model->radius.dispersion, disp_dict);
    disp_dict = PyDict_GetItemString(self->dispersion, "axis_ratio");
    self->model->axis_ratio.dispersion->accept_as_destination(visitor, self->model->axis_ratio.dispersion, disp_dict);

	
	// Get input and determine whether we have to supply a 1D or 2D return value.
	if ( !PyArg_ParseTuple(args,"O",&pars) ) {
	    PyErr_SetString(CFlexCylEllipXModelError, 
	    	"CFlexCylEllipXModel.run expects a q value.");
		return NULL;
	}
	  
	// Check params
	if( PyList_Check(pars)==1) {
		
		// Length of list should be 2 for I(q,phi)
	    npars = PyList_GET_SIZE(pars); 
	    if(npars!=2) {
	    	PyErr_SetString(CFlexCylEllipXModelError, 
	    		"CFlexCylEllipXModel.run expects a double or a list of dimension 2.");
	    	return NULL;
	    }
	    // We have a vector q, get the q and phi values at which
	    // to evaluate I(q,phi)
	    q_value = CFlexCylEllipXModel_readDouble(PyList_GET_ITEM(pars,0));
	    phi_value = CFlexCylEllipXModel_readDouble(PyList_GET_ITEM(pars,1));
	    // Skip zero
	    if (q_value==0) {
	    	return Py_BuildValue("d",0.0);
	    }
		return Py_BuildValue("d",(*(self->model)).evaluate_rphi(q_value,phi_value));

	} else {

		// We have a scalar q, we will evaluate I(q)
		q_value = CFlexCylEllipXModel_readDouble(pars);		
		
		return Py_BuildValue("d",(*(self->model))(q_value));
	}	
}
开发者ID:ricleal,项目名称:SasModeling,代码行数:69,代码来源:CFlexCylEllipXModel.cpp

示例5: get

 const double get(unsigned i) { return PyFloat_AsDouble(PyTuple_GetItem(obj.get(), (Py_ssize_t)i)); }
开发者ID:AlexanderFabisch,项目名称:numpy-c-api,代码行数:1,代码来源:python_interpreter.cpp

示例6: real_from_python

void real_from_python(char* function, int* function_len,
                        double* t,  
                        double* result, int* stat)
{
#ifndef HAVE_PYTHON
  int i;
  strncpy(function, "No Python support!\n", (size_t) *function_len);
  for (i=0; i < *function_len; i++)
  {
    if (function[i] == '\0')
      function[i] = ' ';
  }
  *stat=1;
  return;
#else
  PyObject *pMain, *pGlobals, *pLocals, *pFunc, *pCode, *pResult, 
    *pArgs, *pT;
  
  char *function_c;
  
  // the function string passed down from Fortran needs terminating,
  // so make a copy and fiddle with it (remember to free it)
  function_c = (char *)malloc(*function_len+3);
  memcpy( function_c, function, *function_len );
  function_c[*function_len] = 0;

  // Get a reference to the main module and global dictionary
  pMain = PyImport_AddModule("__main__");

  pGlobals = PyModule_GetDict(pMain);
  // Global and local namespace dictionaries for our code.
  pLocals=PyDict_New();
  
  // Execute the user's code.
  pCode=PyRun_String(function_c, Py_file_input, pGlobals, pLocals);

  // Extract the function from the code.
  pFunc=PyDict_GetItemString(pLocals, "val");

  // Clean up memory from null termination.
  free(function_c);
  
  // Check for errors in executing user code.
  if (PyErr_Occurred()){
    PyErr_Print();
    *stat=1;
    return;
  }

  // Python form of time variable.
  pT=PyFloat_FromDouble(*t);

  // Tuple of arguments to function;
  pArgs=PyTuple_New(1);
  PyTuple_SetItem(pArgs, 0, pT);

  // Check for a Python error in the function call
  if (PyErr_Occurred()){
    PyErr_Print();
    *stat=1;
    return;
  }

  pResult=PyObject_CallObject(pFunc, pArgs); 
  
  // Check for a Python error in the function call
  if (PyErr_Occurred()){
    PyErr_Print();
    *stat=1;
    return;
  }

  *result = PyFloat_AsDouble(pResult);

  // Check for a Python error in result.
  if (PyErr_Occurred()){
    PyErr_Print();
    *stat=1;
    return;
  }

  Py_DECREF(pResult);  
  
  // Clean up
  Py_DECREF(pArgs);  
  Py_DECREF(pLocals);  
  Py_DECREF(pCode);  

  // Force a garbage collection
  PyGC_Collect();


  *stat=0;
  return;
#endif
}
开发者ID:Nasrollah,项目名称:fluidity,代码行数:96,代码来源:embed_python.c

示例7: pyrna_array_contains_py

/* TODO, multi-dimensional arrays */
int pyrna_array_contains_py(PointerRNA *ptr, PropertyRNA *prop, PyObject *value)
{
	int len = RNA_property_array_length(ptr, prop);
	int type;
	int i;

	if (len == 0) /* possible with dynamic arrays */
		return 0;

	if (RNA_property_array_dimension(ptr, prop, NULL) > 1) {
		PyErr_SetString(PyExc_TypeError, "PropertyRNA - multi dimensional arrays not supported yet");
		return -1;
	}

	type = RNA_property_type(prop);

	switch (type) {
		case PROP_FLOAT:
		{
			float value_f = PyFloat_AsDouble(value);
			if (value_f == -1 && PyErr_Occurred()) {
				PyErr_Clear();
				return 0;
			}
			else {
				float tmp[32];
				float *tmp_arr;

				if (len * sizeof(float) > sizeof(tmp)) {
					tmp_arr = PyMem_MALLOC(len * sizeof(float));
				}
				else {
					tmp_arr = tmp;
				}

				RNA_property_float_get_array(ptr, prop, tmp_arr);

				for (i = 0; i < len; i++) {
					if (tmp_arr[i] == value_f) {
						break;
					}
				}

				if (tmp_arr != tmp)
					PyMem_FREE(tmp_arr);

				return i < len ? 1 : 0;
			}
			break;
		}
		case PROP_BOOLEAN:
		case PROP_INT:
		{
			int value_i = PyLong_AsSsize_t(value);
			if (value_i == -1 && PyErr_Occurred()) {
				PyErr_Clear();
				return 0;
			}
			else {
				int tmp[32];
				int *tmp_arr;

				if (len * sizeof(int) > sizeof(tmp)) {
					tmp_arr = PyMem_MALLOC(len * sizeof(int));
				}
				else {
					tmp_arr = tmp;
				}

				if (type == PROP_BOOLEAN)
					RNA_property_boolean_get_array(ptr, prop, tmp_arr);
				else
					RNA_property_int_get_array(ptr, prop, tmp_arr);

				for (i = 0; i < len; i++) {
					if (tmp_arr[i] == value_i) {
						break;
					}
				}

				if (tmp_arr != tmp)
					PyMem_FREE(tmp_arr);

				return i < len ? 1 : 0;
			}
			break;
		}
	}

	/* should never reach this */
	PyErr_SetString(PyExc_TypeError, "PropertyRNA - type not in float/bool/int");
	return -1;
}
开发者ID:vanangamudi,项目名称:blender-main,代码行数:94,代码来源:bpy_rna_array.c

示例8: GETFUNC

int MarcPostDB::element_tensor(int indexE,int indexT,PyTensor **ppTensor)
{
	GETFUNC(m_pFile,"element_tensor",Func_ElementTensor,"**ERROR** Function element_tensor() not found");
	PyObject *pParam = Py_BuildValue("(i,i)",indexE,indexT);
	PyObject * ret = PyEval_CallObject((PyObject *)m_pFunc[Func_ElementTensor],pParam);
	CHECKERR();

	int len = 0;
	if (PyList_Check(ret))
	{
		len = PyList_Size(ret);
		PyObject *item = 0;
		for (int i = 0; i < len; i++)
		{
			item = PyList_GetItem(ret,i);

			PyObject *val = PyObject_GetAttrString(item,"id");
			m_oTensor[i].nodeId = PyInt_AsLong(val);
			Py_DECREF(val);

			val = PyObject_GetAttrString(item,"intensity");
			m_oTensor[i].intensity = PyFloat_AsDouble(val);
			Py_DECREF(val);

			val = PyObject_GetAttrString(item,"t11");
			m_oTensor[i].val[0] = PyFloat_AsDouble(val);
			Py_DECREF(val);

			val = PyObject_GetAttrString(item,"t12");
			m_oTensor[i].val[1] = PyFloat_AsDouble(val);
			Py_DECREF(val);

			val = PyObject_GetAttrString(item,"t13");
			m_oTensor[i].val[2] = PyFloat_AsDouble(val);
			Py_DECREF(val);

			val = PyObject_GetAttrString(item,"t22");
			m_oTensor[i].val[3] = PyFloat_AsDouble(val);
			Py_DECREF(val);

			val = PyObject_GetAttrString(item,"t23");
			m_oTensor[i].val[4] = PyFloat_AsDouble(val);
			Py_DECREF(val);

			val = PyObject_GetAttrString(item,"t33");
			m_oTensor[i].val[5] = PyFloat_AsDouble(val);
			Py_DECREF(val);

			//Py_DECREF(item);
		}
	}
	Py_DECREF(ret);
	Py_DECREF(pParam);
	*ppTensor = m_oTensor;
	return len;
	//printf("%s\n",PyString_AsString(PyObject_Str(ret)));
	//if (PyTuple_Check(ret))
	//{
	//	printf("%s\n","Type of tuple");
	//}
	//else if (PyList_Check(ret))
	//{
	//	printf("%s\n","Type of list");
	//}
	//else if (PyDict_Check(ret))
	//{
	//	printf("%s\n","Type of dict");
	//}
	//else if (PyString_Check(ret))
	//{
	//	printf("%s\n","Type of string");
	//}
	//else if (PySet_Check(ret))
	//{
	//	printf("%s\n","Type of set");
	//}
	//else if (PySequence_Check(ret))
	//{
	//	printf("%s\n","Type of sequence");
	//}
	//else if (PyMapping_Check(ret))
	//{
	//	printf("%s\n","Type of map");
	//}
}
开发者ID:pkhope,项目名称:Marc-result-reader,代码行数:85,代码来源:MarcPostDB.cpp

示例9: convertTo_QVector_0600QPair_2400_0100QVariant

static int convertTo_QVector_0600QPair_2400_0100QVariant(PyObject *sipPy,void **sipCppPtrV,int *sipIsErr,PyObject *sipTransferObj)
{
    QVector<QPair<qreal,QVariant> > **sipCppPtr = reinterpret_cast<QVector<QPair<qreal,QVariant> > **>(sipCppPtrV);

#line 167 "C:\\Users\\marcus\\Downloads\\PyQt-gpl-5.4\\PyQt-gpl-5.4\\sip/QtCore/qpycore_qvector.sip"
    PyObject *iter = PyObject_GetIter(sipPy);

    if (!sipIsErr)
    {
        Py_XDECREF(iter);

        return (iter
#if PY_MAJOR_VERSION < 3
                && !PyString_Check(sipPy)
#endif
                && !PyUnicode_Check(sipPy));
    }

    if (!iter)
    {
        *sipIsErr = 1;

        return 0;
    }

    QVector<QPair<qreal, QVariant> > *qv = new QVector<QPair<qreal, QVariant> >;

    for (SIP_SSIZE_T i = 0; ; ++i)
    {
        PyErr_Clear();
        PyObject *seq = PyIter_Next(iter);

        if (!seq)
        {
            if (PyErr_Occurred())
            {
                delete qv;
                Py_DECREF(iter);
                *sipIsErr = 1;

                return 0;
            }

            break;
        }

        SIP_SSIZE_T sub_len;

        if (PySequence_Check(seq)
#if PY_MAJOR_VERSION < 3
                && !PyString_Check(seq)
#endif
                && !PyUnicode_Check(seq))
            sub_len = PySequence_Size(seq);
        else
            sub_len = -1;

        if (sub_len != 2)
        {
            if (sub_len < 0)
                PyErr_Format(PyExc_TypeError,
                             "index " SIP_SSIZE_T_FORMAT " has type '%s' but a 2 element non-string sequence is expected",
                             i, Py_TYPE(seq)->tp_name);
            else
                PyErr_Format(PyExc_TypeError,
                             "index " SIP_SSIZE_T_FORMAT " is a sequence of " SIP_SSIZE_T_FORMAT " sub-elements but 2 sub-elements are expected",
                             i, sub_len);

            Py_DECREF(seq);
            delete qv;
            Py_DECREF(iter);
            *sipIsErr = 1;

            return 0;
        }

        PyObject *itm1 = PySequence_ITEM(seq, 0);

        if (!itm1)
        {
            Py_DECREF(seq);
            delete qv;
            Py_DECREF(iter);
            *sipIsErr = 1;

            return 0;
        }

        PyErr_Clear();
        qreal s1 = PyFloat_AsDouble(itm1);

        if (PyErr_Occurred())
        {
            PyErr_Format(PyExc_TypeError,
                         "the first sub-element of index " SIP_SSIZE_T_FORMAT " has type '%s' but 'float' is expected",
                         i, Py_TYPE(itm1)->tp_name);

            Py_DECREF(itm1);
            Py_DECREF(seq);
            delete qv;
//.........这里部分代码省略.........
开发者ID:rff255,项目名称:python-qt5,代码行数:101,代码来源:sipQtCoreQVector0600QPair24000100QVariant.cpp

示例10: is_scalar_with_conversion

/* Determine if object is a scalar and if so, convert the object
 *   to a double and place it in the out_exponent argument
 *   and return the "scalar kind" as a result.   If the object is
 *   not a scalar (or if there are other error conditions)
 *   return NPY_NOSCALAR, and out_exponent is undefined.
 */
static NPY_SCALARKIND
is_scalar_with_conversion(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_Check(o2)) {
        if ((PyArray_NDIM(o2) == 0) &&
                ((PyArray_ISINTEGER((PyArrayObject *)o2) ||
                 (optimize_fpexps && PyArray_ISFLOAT((PyArrayObject *)o2))))) {
            temp = Py_TYPE(o2)->tp_as_number->nb_float(o2);
            if (temp == NULL) {
                return NPY_NOSCALAR;
            }
            *out_exponent = PyFloat_AsDouble(o2);
            Py_DECREF(temp);
            if (PyArray_ISINTEGER((PyArrayObject *)o2)) {
                return NPY_INTPOS_SCALAR;
            }
            else { /* ISFLOAT */
                return NPY_FLOAT_SCALAR;
            }
        }
    }
    else if (PyArray_IsScalar(o2, Integer) ||
                (optimize_fpexps && PyArray_IsScalar(o2, Floating))) {
        temp = Py_TYPE(o2)->tp_as_number->nb_float(o2);
        if (temp == NULL) {
            return NPY_NOSCALAR;
        }
        *out_exponent = PyFloat_AsDouble(o2);
        Py_DECREF(temp);

        if (PyArray_IsScalar(o2, Integer)) {
                return NPY_INTPOS_SCALAR;
        }
        else { /* IsScalar(o2, Floating) */
            return NPY_FLOAT_SCALAR;
        }
    }
    else if (PyIndex_Check(o2)) {
        PyObject* value = PyNumber_Index(o2);
        Py_ssize_t val;
        if (value==NULL) {
            if (PyErr_Occurred()) {
                PyErr_Clear();
            }
            return NPY_NOSCALAR;
        }
        val = PyInt_AsSsize_t(value);
        if (val == -1 && PyErr_Occurred()) {
            PyErr_Clear();
            return NPY_NOSCALAR;
        }
        *out_exponent = (double) val;
        return NPY_INTPOS_SCALAR;
    }
    return NPY_NOSCALAR;
}
开发者ID:BenoitDherin,项目名称:numpy,代码行数:73,代码来源:number.c

示例11: PyErr_SetString

PyObject* DetailView::loadDetail(PyObject *dict)
{
    static QString nameFmt = "<span style=\" font-size:16pt; font-weight:600;\">%1</span> (rating: %2)";
    if (!PyDict_Check(dict))
    {
        PyErr_SetString(PyExc_TypeError, "The argument is not a dict.");
        return NULL;
    }

    PyObject *item;
    QString name;
    //name
    if (NULL != (item = PyDict_GetItemString(dict, "name")))
    {
        name = PyString_AsQString(item);
        setWindowTitle(name + tr(" - Detail page"));
    }

    //rating
    if (NULL != (item = PyDict_GetItemString(dict, "rating")))
        ui->nameLabel->setText(nameFmt.arg(name, QString::number(PyFloat_AsDouble(item))));
    else
        ui->nameLabel->setText(nameFmt.arg(name, tr("Unknown")));

    //length
    if (NULL != (item = PyDict_GetItemString(dict, "length")))
        ui->lengthLabel->setText(PyString_AsQString(item));
    else
        ui->lengthLabel->setText(tr("Unknown"));

    //summary
    if (NULL != (item = PyDict_GetItemString(dict, "summary")))
        ui->summaryLabel->setText(PyString_AsQString(item));
    else
        ui->summaryLabel->setText(tr("Unknown"));

    //others
    struct Item {const char *item_name; QLabel *label;};
    struct Item items[] = {
        {"directors", ui->directorLabel},
        {"script_writers", ui->scriptwriterLabel},
        {"players", ui->playerLabel},
        {"types", ui->typeLabel},
        {"nations", ui->nationLabel},
        {"languages", ui->langLabel},
        {"dates", ui->dateLabel},
        {"alt_names", ui->alternameLabel},
        {NULL, NULL}
    };
    for (struct Item *i = items; i->item_name; i++) {
        item = PyDict_GetItemString(dict, i->item_name);
        if (item) {
            QStringList list = PyList_AsQStringList(item);
            i->label->setText(list.join(" / ").simplified());
        }
        else
            i->label->setText(tr("Unknown"));
    }


    // Source
    ui->sourceListWidget->clear();
    urls.clear();
    item = PyDict_GetItemString(dict, "source");
    if (item)
    {
        int n = PyList_Size(item);
        for (int i = 0; i < n; i += 2)
        {
            QString name = PyString_AsQString(PyList_GetItem(item, i));
            const char *url = PyString_AsString(PyList_GetItem(item, i+1));
            ui->sourceListWidget->addItem(name);
            urls.append(url);
        }
    }

    // Image
    item = PyDict_GetItemString(dict, "image");
    if (item)
    {
        QNetworkRequest request(QUrl(PyString_AsQString(item)));
        request.setRawHeader("User-Agent", "moonplayer");
        reply = access_manager->get(request);
        connect(reply, SIGNAL(finished()), this, SLOT(onImageLoaded()));
    }
    Py_IncRef(Py_None);
    return Py_None;
}
开发者ID:jinagko,项目名称:moonplayer,代码行数:88,代码来源:detailview.cpp

示例12: convert_double

// Convert a Python object to a GLdouble.
static void convert_double(PyObject *itm, void *array, SIP_SSIZE_T i)
{
    reinterpret_cast<GLdouble *>(array)[i] = PyFloat_AsDouble(itm);
}
开发者ID:hbyw618,项目名称:pyqt5,代码行数:5,代码来源:qpyopengl_value_array.cpp

示例13: _braid_data_c

PyObject* _braid_data_c(PyObject* data1, PyObject* data2)
{

    int line = 0;           //Current position in the resulting arrays
    int idx1 = 0;           //Current position in data1
    int idx2 = 0;           //Current position in data2

    //Variables for extracting tuple-values
    PyObject* tmp_tuple1;
    PyObject* tmp_tuple2;
    int pin1, pin2;
    int dir1, dir2;
    int o1, o2;
    float dly1, dly2;

    //Calculate max size (Is this correct?)
    int max_size = PyList_Size(data1) + PyList_Size(data2);
    
    // Allocate memory for two arrays of maximum possible size to contain result
    int * pins = (int*) malloc(sizeof(int) * max_size);
    int * dirs = (int*) malloc(sizeof(int) * max_size);
    int * options = (int*) malloc(sizeof(int) * max_size);
    float * delay = (float*) malloc(sizeof(float) * max_size);
        
    //Get first tuples from data1 and data2    
    tmp_tuple1 = PyList_GetItem(data1,idx1);
    pin1 = (int)PyInt_AsLong(PyTuple_GetItem(tmp_tuple1,0));
    dir1 = (int)PyInt_AsLong(PyTuple_GetItem(tmp_tuple1,1));
    o1 = (int)PyInt_AsLong(PyTuple_GetItem(tmp_tuple1,2));
    dly1 = (float)PyFloat_AsDouble(PyTuple_GetItem(tmp_tuple1,3));

    tmp_tuple2 = PyList_GetItem(data2,idx2);
    pin2 = (int)PyInt_AsLong(PyTuple_GetItem(tmp_tuple2,0));
    dir2 = (int)PyInt_AsLong(PyTuple_GetItem(tmp_tuple2,1));
    o2 = (int)PyInt_AsLong(PyTuple_GetItem(tmp_tuple2,2));
    dly2 = (float)PyFloat_AsDouble(PyTuple_GetItem(tmp_tuple2,3));
        
    while (1) {
        if (dly1 == dly2) {
            //Create resulting pin number
            pins[line] = pin1 | pin2;
            dirs[line] = dir1 | dir2;
            options[line] = o1 | o2;
            //Create resulting delay
            delay[line] = dly1;
            
            //Update line
            line++; 
            
            //Update indexes
            idx1++;
            idx2++;
            
            dly2 = dly1 = 0;

            //Check that there are still items left in both arrays
            if (idx1 >= PyList_Size(data1) || idx2 >= PyList_Size(data2))
                break;
            
            //Get next tuples from data1 and data2
            tmp_tuple1 = PyList_GetItem(data1,idx1);
            pin1 = (int)PyInt_AsLong(PyTuple_GetItem(tmp_tuple1,0));
            dir1 = (int)PyInt_AsLong(PyTuple_GetItem(tmp_tuple1,1));
            o1 = (int)PyInt_AsLong(PyTuple_GetItem(tmp_tuple1,2));
            dly1 = (float)PyFloat_AsDouble(PyTuple_GetItem(tmp_tuple1,3));

            tmp_tuple2 = PyList_GetItem(data2,idx2);
            pin2 = (int)PyInt_AsLong(PyTuple_GetItem(tmp_tuple2,0));
            dir2 = (int)PyInt_AsLong(PyTuple_GetItem(tmp_tuple2,1));
            o2 = (int)PyInt_AsLong(PyTuple_GetItem(tmp_tuple2,2));
            dly2 = (float)PyFloat_AsDouble(PyTuple_GetItem(tmp_tuple2,3));
        }
        
        else if (dly1 > dly2) {
            //Create resulting pin number
            pins[line] =  pin2;
            dirs[line] =  dir2;
            options[line] =  o2;
            //Create resulting delay
            delay[line] = dly2;
            
            //DEBUG:
            //printf("Added (%d, %.1f) - dly1>dly2\n", pins[line], delay[line]);
            //printf("dly1=%.1f\n",dly1);
            //printf("dly2=%.1f\n",dly2);
            //printf("idx1=%d\n",idx1);
            //printf("idx2=%d\n",idx2);
            
            //Update line
            line++; 
            
            //Subtract dly2 from dly1 to get the delay from the last tuple we added
            dly1 -= dly2;
            dly2 = 0;
            //Increase idx2
            idx2++;
            
            //Check that there are still items left in data2 array
            if (idx2 >= PyList_Size(data2))
                break;
//.........这里部分代码省略.........
开发者ID:zittix,项目名称:redeem,代码行数:101,代码来源:braidmodule.c

示例14: complex_richcompare

static PyObject *
complex_richcompare(PyObject *v, PyObject *w, int op)
{
    PyObject *res;
    Py_complex i;
    int equal;

    if (op != Py_EQ && op != Py_NE) {
        /* for backwards compatibility, comparisons with non-numbers return
         * NotImplemented.  Only comparisons with core numeric types raise
         * TypeError.
         */
        if (PyInt_Check(w) || PyLong_Check(w) ||
                PyFloat_Check(w) || PyComplex_Check(w)) {
            PyErr_SetString(PyExc_TypeError,
                            "no ordering relation is defined "
                            "for complex numbers");
            return NULL;
        }
        goto Unimplemented;
    }

    assert(PyComplex_Check(v));
    TO_COMPLEX(v, i);

    if (PyInt_Check(w) || PyLong_Check(w)) {
        /* Check for 0.0 imaginary part first to avoid the rich
         * comparison when possible.
         */
        if (i.imag == 0.0) {
            PyObject *j, *sub_res;
            j = PyFloat_FromDouble(i.real);
            if (j == NULL)
                return NULL;

            sub_res = PyObject_RichCompare(j, w, op);
            Py_DECREF(j);
            return sub_res;
        }
        else {
            equal = 0;
        }
    }
    else if (PyFloat_Check(w)) {
        equal = (i.real == PyFloat_AsDouble(w) && i.imag == 0.0);
    }
    else if (PyComplex_Check(w)) {
        Py_complex j;

        TO_COMPLEX(w, j);
        equal = (i.real == j.real && i.imag == j.imag);
    }
    else {
        goto Unimplemented;
    }

    if (equal == (op == Py_EQ))
        res = Py_True;
    else
        res = Py_False;

    Py_INCREF(res);
    return res;

Unimplemented:
    Py_INCREF(Py_NotImplemented);
    return Py_NotImplemented;
}
开发者ID:youseatao,项目名称:Python-2.7.8,代码行数:68,代码来源:complexobject.c

示例15: set_vector_field_from_python


//.........这里部分代码省略.........
    return;
  }
  
  // Python form of time variable.
  pT=PyFloat_FromDouble(*t);
  
  // Tuple containing the current position vector.
  pPos=PyTuple_New(*dim);
  
  // Tuple of arguments to function;
  pArgs=PyTuple_New(2);
  PyTuple_SetItem(pArgs, 1, pT);
  PyTuple_SetItem(pArgs, 0, pPos);
  
  // Check for a Python error in the function call
  if (PyErr_Occurred()){
    PyErr_Print();
    *stat=1;
    return;
  }
  
  for (i = 0; i < *nodes; i++){
    px=PyFloat_FromDouble(x[i]);
    PyTuple_SetItem(pPos, 0, px);    
    
    if (*dim>1) {
      px=PyFloat_FromDouble(y[i]);
      PyTuple_SetItem(pPos, 1, px);
      
      if (*dim>2) {
        px=PyFloat_FromDouble(z[i]);
        PyTuple_SetItem(pPos, 2, px);
      }
    }
    
    pResult=PyObject_CallObject(pFunc, pArgs);
    // Check for a Python error in the function call
    if (PyErr_Occurred()){
      PyErr_Print();
      *stat=1;
      return;
    }

    if (PyObject_Length(pResult) != *result_dim)
    {
      fprintf(stderr, "Error: length of object returned from python (%d) does not match the allocated dimension of the vector field (%d).\n",
              (int) PyObject_Length(pResult), *result_dim);
      *stat = 1;
      return;
    }
    
    
    px=PySequence_GetItem(pResult, 0);
    
    result_x[i]=PyFloat_AsDouble(px);
    // Check for a Python error in unpacking tuple.
    if (PyErr_Occurred()){
      PyErr_Print();
      *stat=1;
      return;
    }
    Py_DECREF(px);
    
    if (*result_dim>1) { 
      px=PySequence_GetItem(pResult, 1);  
      result_y[i]=PyFloat_AsDouble(px);  
      // Check for a Python error in unpacking tuple.  
      if (PyErr_Occurred()){  
         PyErr_Print();  
         return;  
      }  
      
      Py_DECREF(px);  
      if (*result_dim>2) {  
        px=PySequence_GetItem(pResult, 2);  
        result_z[i]=PyFloat_AsDouble(px);  
      // Check for a Python error in unpacking tuple.  
       if (PyErr_Occurred()){  
          PyErr_Print();  
          return;  
       }  
        Py_DECREF(px);  
      } 
    }  
    
    Py_DECREF(pResult);  
  }
  
  // Clean up
  Py_DECREF(pArgs);  
  Py_DECREF(pLocals);  
  Py_DECREF(pCode);  
  
  // Force a garbage collection
  PyGC_Collect();
  
  *stat=0;
  return;
#endif
}
开发者ID:Nasrollah,项目名称:fluidity,代码行数:101,代码来源:embed_python.c


注:本文中的PyFloat_AsDouble函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。