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) {
			ret = PyTuple_Pack(3, ifdlist, ifdlist, ifdlist);
			Py_DECREF(ifdlist);
		}
	}
	else {
		/* any of these three calls can raise an exception.  it's more
		   convenient to test for this after all three calls... but
		   is that acceptable?
		*/
		ifdlist = set2list(&ifdset, rfd2obj);
		ofdlist = set2list(&ofdset, wfd2obj);
		efdlist = set2list(&efdset, efd2obj);
		if (PyErr_Occurred())
			ret = NULL;
		else
			ret = PyTuple_Pack(3, ifdlist, ofdlist, efdlist);

		Py_DECREF(ifdlist);
		Py_DECREF(ofdlist);
		Py_DECREF(efdlist);
	}
	
  finally:
	reap_obj(rfd2obj);
	reap_obj(wfd2obj);
	reap_obj(efd2obj);
#ifdef SELECT_USES_HEAP
	PyMem_DEL(rfd2obj);
	PyMem_DEL(wfd2obj);
	PyMem_DEL(efd2obj);
#endif /* SELECT_USES_HEAP */
	return ret;
}
Exemple #2
0
static PyObject *
complex_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
    PyObject *r, *i, *tmp;
    PyNumberMethods *nbr, *nbi = NULL;
    Py_complex cr, ci;
    int own_r = 0;
    int cr_is_complex = 0;
    int ci_is_complex = 0;
    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 (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 && PyUnicode_Check(i)) {
        PyErr_SetString(PyExc_TypeError,
                        "complex() second arg can't be a string");
        return NULL;
    }

    tmp = try_complex_special_method(r);
    if (tmp) {
        r = tmp;
        own_r = 1;
    }
    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);
}
Exemple #3
0
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;
    }

    len = PyObject_Length(value);

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

    writeByte(output, parsedargs.element_type);
    writeI32(output, (int32_t) len);

    iterator =  PyObject_GetIter(value);
    if (iterator == NULL) {
      return false;
    }

    while ((item = PyIter_Next(iterator))) {
      if (!output_val(output, item, parsedargs.element_type, parsedargs.typeargs)) {
        Py_DECREF(item);
        Py_DECREF(iterator);
        return false;
      }
      Py_DECREF(item);
    }

    Py_DECREF(iterator);

    if (PyErr_Occurred()) {
      return false;
    }

    break;
  }

  case T_MAP: {
    PyObject *k, *v;
    Py_ssize_t pos = 0;
    Py_ssize_t len;

    MapTypeArgs parsedargs;

    len = PyDict_Size(value);
    if (!check_ssize_t_32(len)) {
      return false;
    }

    if (!parse_map_args(&parsedargs, typeargs)) {
      return false;
    }

    writeByte(output, parsedargs.ktag);
    writeByte(output, parsedargs.vtag);
    writeI32(output, len);

    // TODO(bmaurer): should support any mapping, not just dicts
    while (PyDict_Next(value, &pos, &k, &v)) {
      // TODO(dreiss): Think hard about whether these INCREFs actually
      //               turn any unsafe scenarios into safe scenarios.
      Py_INCREF(k);
      Py_INCREF(v);

      if (!output_val(output, k, parsedargs.ktag, parsedargs.ktypeargs)
          || !output_val(output, v, parsedargs.vtag, parsedargs.vtypeargs)) {
        Py_DECREF(k);
        Py_DECREF(v);
        return false;
      }
    }
    break;
  }

  // TODO(dreiss): Consider breaking this out as a function
  //               the way we did for decode_struct.
  case T_STRUCT: {
    StructTypeArgs parsedargs;
    Py_ssize_t nspec;
    Py_ssize_t i;

    if (!parse_struct_args(&parsedargs, typeargs)) {
      return false;
    }

    nspec = PyTuple_Size(parsedargs.spec);

    if (nspec == -1) {
      return false;
    }

    for (i = 0; i < nspec; i++) {
      StructItemSpec parsedspec;
      PyObject* spec_tuple;
      PyObject* instval = NULL;

      spec_tuple = PyTuple_GET_ITEM(parsedargs.spec, i);
      if (spec_tuple == Py_None) {
        continue;
      }

      if (!parse_struct_item_spec (&parsedspec, spec_tuple)) {
        return false;
      }

      instval = PyObject_GetAttr(value, parsedspec.attrname);

      if (!instval) {
        return false;
      }

      if (instval == Py_None) {
        Py_DECREF(instval);
        continue;
      }

      writeByte(output, (int8_t) parsedspec.type);
      writeI16(output, parsedspec.tag);

      if (!output_val(output, instval, parsedspec.type, parsedspec.typeargs)) {
        Py_DECREF(instval);
        return false;
      }

      Py_DECREF(instval);
    }

    writeByte(output, (int8_t)T_STOP);
    break;
  }

  case T_STOP:
  case T_VOID:
  case T_UTF16:
  case T_UTF8:
  case T_U64:
  default:
    PyErr_SetString(PyExc_TypeError, "Unexpected TType");
    return false;

  }

  return true;
}
/**
 * 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));
	}	
}
 const double get(unsigned i) { return PyFloat_AsDouble(PyTuple_GetItem(obj.get(), (Py_ssize_t)i)); }
Exemple #6
0
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
}
/* 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;
}
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");
	//}
}
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;
            Py_DECREF(iter);
            *sipIsErr = 1;

            return 0;
        }

        PyObject *itm2 = PySequence_ITEM(seq, 1);

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

            return 0;
        }

        int state2;
        QVariant *s2 = reinterpret_cast<QVariant *>(
                           sipForceConvertToType(itm2, sipType_QVariant, sipTransferObj,
                                   SIP_NOT_NONE, &state2, sipIsErr));

        if (*sipIsErr)
        {
            PyErr_Format(PyExc_TypeError,
                         "the second sub-element of index " SIP_SSIZE_T_FORMAT " has type '%s' but 'QVariant' is expected",
                         i, Py_TYPE(itm2)->tp_name);

            Py_DECREF(itm2);
            Py_DECREF(itm1);
            Py_DECREF(seq);
            delete qv;
            Py_DECREF(iter);

            return 0;
        }

        qv->append(QPair<qreal, QVariant>(s1, *s2));

        sipReleaseType(s2, sipType_QVariant, state2);
        Py_DECREF(itm2);
        Py_DECREF(itm1);
        Py_DECREF(seq);
    }

    Py_DECREF(iter);

    *sipCppPtr = qv;

    return sipGetState(sipTransferObj);
#line 220 "C:\\Users\\marcus\\Downloads\\PyQt-gpl-5.4\\PyQt-gpl-5.4\\QtCore/sipQtCoreQVector0600QPair24000100QVariant.cpp"
}
Exemple #10
0
/* 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;
}
Exemple #11
0
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;
}
Exemple #12
0
/* This evals py driver expressions, 'expr' is a Python expression that
 * should evaluate to a float number, which is returned.
 *
 * note: PyGILState_Ensure() isnt always called because python can call the
 * bake operator which intern starts a thread which calls scene update which
 * does a driver update. to avoid a deadlock check PyThreadState_Get() if PyGILState_Ensure() is needed.
 */
float BPY_driver_exec(ChannelDriver *driver)
{
	PyObject *driver_vars=NULL;
	PyObject *retval= NULL;
	PyObject *expr_vars; /* speed up by pre-hashing string & avoids re-converting unicode strings for every execution */
	PyObject *expr_code;
	PyGILState_STATE gilstate;
	int use_gil;

	DriverVar *dvar;
	double result = 0.0; /* default return */
	char *expr = NULL;
	short targets_ok= 1;
	int i;

	/* get the py expression to be evaluated */
	expr = driver->expression;
	if ((expr == NULL) || (expr[0]=='\0'))
		return 0.0f;

	if(!(G.f & G_SCRIPT_AUTOEXEC)) {
		printf("skipping driver '%s', automatic scripts are disabled\n", driver->expression);
		return 0.0f;
	}

	use_gil= 1; //(PyThreadState_Get()==NULL);

	if(use_gil)
		gilstate = PyGILState_Ensure();

	/* init global dictionary for py-driver evaluation settings */
	if (!bpy_pydriver_Dict) {
		if (bpy_pydriver_create_dict() != 0) {
			fprintf(stderr, "Pydriver error: couldn't create Python dictionary");
			if(use_gil)
				PyGILState_Release(gilstate);
			return 0.0f;
		}
	}

	if(driver->expr_comp==NULL)
		driver->flag |= DRIVER_FLAG_RECOMPILE;

	/* compile the expression first if it hasn't been compiled or needs to be rebuilt */
	if(driver->flag & DRIVER_FLAG_RECOMPILE) {
		Py_XDECREF(driver->expr_comp);
		driver->expr_comp= PyTuple_New(2);

		expr_code= Py_CompileString(expr, "<bpy driver>", Py_eval_input);
		PyTuple_SET_ITEM(((PyObject *)driver->expr_comp), 0, expr_code);

		driver->flag &= ~DRIVER_FLAG_RECOMPILE;
		driver->flag |= DRIVER_FLAG_RENAMEVAR; /* maybe this can be removed but for now best keep until were sure */
	}
	else {
		expr_code= PyTuple_GET_ITEM(((PyObject *)driver->expr_comp), 0);
	}

	if(driver->flag & DRIVER_FLAG_RENAMEVAR) {
		/* may not be set */
		expr_vars= PyTuple_GET_ITEM(((PyObject *)driver->expr_comp), 1);
		Py_XDECREF(expr_vars);

		/* intern the arg names so creating the namespace for every run is faster */
		expr_vars= PyTuple_New(BLI_countlist(&driver->variables));
		PyTuple_SET_ITEM(((PyObject *)driver->expr_comp), 1, expr_vars);

		for (dvar= driver->variables.first, i=0; dvar; dvar= dvar->next) {
			PyTuple_SET_ITEM(expr_vars, i++, PyUnicode_InternFromString(dvar->name));
		}
		
		driver->flag &= ~DRIVER_FLAG_RENAMEVAR;
	}
	else {
		expr_vars= PyTuple_GET_ITEM(((PyObject *)driver->expr_comp), 1);
	}

	/* add target values to a dict that will be used as '__locals__' dict */
	driver_vars = PyDict_New(); // XXX do we need to decref this?
	for (dvar= driver->variables.first, i=0; dvar; dvar= dvar->next) {
		PyObject *driver_arg = NULL;
		float tval = 0.0f;
		
		/* try to get variable value */
		tval= driver_get_variable_value(driver, dvar);
		driver_arg= PyFloat_FromDouble((double)tval);
		
		/* try to add to dictionary */
		/* if (PyDict_SetItemString(driver_vars, dvar->name, driver_arg)) { */
		if (PyDict_SetItem(driver_vars, PyTuple_GET_ITEM(expr_vars, i++), driver_arg) < 0) { /* use string interning for faster namespace creation */
			/* this target failed - bad name */
			if (targets_ok) {
				/* first one - print some extra info for easier identification */
				fprintf(stderr, "\nBPY_driver_eval() - Error while evaluating PyDriver:\n");
				targets_ok= 0;
			}
			
			fprintf(stderr, "\tBPY_driver_eval() - couldn't add variable '%s' to namespace\n", dvar->name);
			// BPy_errors_to_report(NULL); // TODO - reports
			PyErr_Print();
			PyErr_Clear();
		}
	}

#if 0 // slow, with this can avoid all Py_CompileString above.
	/* execute expression to get a value */
	retval = PyRun_String(expr, Py_eval_input, bpy_pydriver_Dict, driver_vars);
#else
	/* evaluate the compiled expression */
	if (expr_code)
		retval= PyEval_EvalCode((void *)expr_code, bpy_pydriver_Dict, driver_vars);
#endif

	/* decref the driver vars first...  */
	Py_DECREF(driver_vars);

	/* process the result */
	if (retval == NULL) {
		pydriver_error(driver);
	} else if((result= PyFloat_AsDouble(retval)) == -1.0 && PyErr_Occurred()) {
		pydriver_error(driver);
		Py_DECREF(retval);
		result = 0.0;
	}
	else {
		/* all fine, make sure the "invalid expression" flag is cleared */
		driver->flag &= ~DRIVER_FLAG_INVALID;
		Py_DECREF(retval);
	}

	if(use_gil)
		PyGILState_Release(gilstate);
    
	if(finite(result)) {
		return (float)result;
	}
	else {
		fprintf(stderr, "\tBPY_driver_eval() - driver '%s' evaluates to '%f'\n", dvar->name, result);
		return 0.0f;
	}
}
// 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);
}
Exemple #14
0
/* return -1 on error, else 0 */
int BPY_button_exec(bContext *C, const char *expr, double *value, const short verbose)
{
	PyGILState_STATE gilstate;
	PyObject *py_dict, *mod, *retval;
	int error_ret = 0;
	PyObject *main_mod = NULL;
	
	if (!value || !expr) return -1;

	if (expr[0] == '\0') {
		*value = 0.0;
		return error_ret;
	}

	bpy_context_set(C, &gilstate);

	PyC_MainModule_Backup(&main_mod);

	py_dict = PyC_DefaultNameSpace("<blender button>");

	mod = PyImport_ImportModule("math");
	if (mod) {
		PyDict_Merge(py_dict, PyModule_GetDict(mod), 0); /* 0 - dont overwrite existing values */
		Py_DECREF(mod);
	}
	else { /* highly unlikely but possibly */
		PyErr_Print();
		PyErr_Clear();
	}
	
	retval = PyRun_String(expr, Py_eval_input, py_dict, py_dict);
	
	if (retval == NULL) {
		error_ret = -1;
	}
	else {
		double val;

		if (PyTuple_Check(retval)) {
			/* Users my have typed in 10km, 2m
			 * add up all values */
			int i;
			val = 0.0;

			for (i = 0; i < PyTuple_GET_SIZE(retval); i++) {
				val += PyFloat_AsDouble(PyTuple_GET_ITEM(retval, i));
			}
		}
		else {
			val = PyFloat_AsDouble(retval);
		}
		Py_DECREF(retval);
		
		if (val == -1 && PyErr_Occurred()) {
			error_ret = -1;
		}
		else if (!finite(val)) {
			*value = 0.0;
		}
		else {
			*value = val;
		}
	}
	
	if (error_ret) {
		if (verbose) {
			BPy_errors_to_report(CTX_wm_reports(C));
		}
		else {
			PyErr_Clear();
		}
	}

	PyC_MainModule_Backup(&main_mod);
	
	bpy_context_clear(C, &gilstate);
	
	return error_ret;
}
Exemple #15
0
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;
            
            //Get next tuple from data2
            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] = pin1;
            dirs[line] = dir1;
            options[line] = o1;
            //Create resulting delay
            delay[line] = dly1;
            
            //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 dly1 from dly2 to get the delay from the last tuple we added
            dly2 -= dly1;
            dly1 = 0;

            //Increase idx1
            idx1++;
            
            //Check that there are still items left in data1 array
            if (idx1 >= PyList_Size(data1))
                break;
                
            //Get next tuple from data1
            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));
        }
    }    

    /*if(dly2>0) {
        pins[line] = pin2;
        dirs[line] = dir2;
        options[line] = o2;
        delay[line] = dly2;
        line++;
    } else if (dly1>0) {
        pins[line] = pin1;
        dirs[line] = dir1;
        options[line] = o1;
        delay[line] = dly1;
        line++;
    }

    dly2 = dly1 = 0;*/

    //If we are here, then we have gone through at least one of the arrays.
    //Need to check if there are items left in the other array

    if (idx1 < PyList_Size(data1)) 
    {
        pins[line] = pin1;
        dirs[line] = dir1;
        options[line] = o1;
        delay[line] = dly1;
        line++;
        idx1++;

        //Iterate through any items left in data1
        for (; idx1 < PyList_Size(data1); idx1++) 
        {
            //Get tuple from data1
            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));

            //Add new tuple to result
            pins[line] = pin1;
            dirs[line] = dir1;
            options[line] = o1;
            delay[line] = dly1;
            
            //Increase indexes
            line++;
        }
    }

    if (idx2 < PyList_Size(data2)) 
    {
        pins[line] = pin2;
        dirs[line] =   dir2;
        options[line] =  o2;
        delay[line] = dly2;
        line++;
        idx2++;     
            
            
        //Iterate through any items left in data2
        for (; idx2 < PyList_Size(data2); idx2++) 
        {
            //Get tuple from data2
            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));

            //Add new tuple to result
            pins[line] = pin2;
            dirs[line] =   dir2;
            options[line] =  o2;
            delay[line] = dly2;
            
            //Increase indexes
            line++;
        }
    }


    //Print result for debugging:
    //printf("\nResulting array:\n");
    //for (int i=0; i<line; i++)
    //    printf("(%d, %.1f), ", pins[i], delay[i]);

    //printf("\n\n");    


    //Create a returnable object from the two arrays "pins" and "delay"
    PyObject *pylist = PyList_New(line);
    int i;
    for (i=0; i<line; i++){
		PyList_SetItem(pylist, i, Py_BuildValue("(iiif)", pins[i],dirs[i],options[i], delay[i]));
    }

    //Free allocated memory
    free(pins);
    free(dirs);
    free(options);
    free(delay);
	
    //Return array
    return pylist;
}
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;
}
Exemple #17
0
void set_vector_field_from_python(char *function, int *function_len, int *dim, 
                                  int *nodes, 
                                  double x[], double y[], double z[], double *t, 
                                  int *result_dim, 
                                  double result_x[], double result_y[], 
                                  double result_z[], 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, *pPos, *px, *pT;
  char *function_c;
  int i;
  
  // 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 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
}
Exemple #18
0
dbtype_t
from_python(pgctx_t *ctx, PyObject *ob)
{
    dbtype_t db;
    char *buf;
    Py_ssize_t length;
    PyObject *items;
    struct tm tm;
    long usec;
    //int i;
    
    if (PyObject_HasAttrString(ob, "__topongo__")) {
        ob = PyObject_CallMethod(ob, "__topongo__", NULL);
        if (PyErr_Occurred())
            return DBNULL;
    }
    if (ob == Py_None) {
        db = DBNULL;
    } else if (ob == pongo_id) {
        db = dbuuid_new(ctx, NULL);
    } else if (ob == pongo_utcnow) {
        db = dbtime_now(ctx);
    } else if (PyBool_Check(ob)) {
        db = dbboolean_new(ctx, ob == Py_True);
    } else if (PyInt_Check(ob)) {
        db = dbint_new(ctx, PyInt_AsLong(ob));
    } else if (PyLong_Check(ob)) {
        db = dbint_new(ctx, PyLong_AsLongLong(ob));
    } else if (PyFloat_Check(ob)) {
        db = dbfloat_new(ctx, PyFloat_AsDouble(ob));
    } else if (PyString_Check(ob)) {
        PyString_AsStringAndSize(ob, &buf, &length);
        // FIXME:
        //db = dbbuffer_new(ctx, buf, length);
        db = dbstring_new(ctx, buf, length);
    } else if (PyUnicode_Check(ob)) {
        ob = PyUnicode_AsUTF8String(ob);
        if (ob) {
            PyString_AsStringAndSize(ob, &buf, &length);
            db = dbstring_new(ctx, buf, length);
            Py_DECREF(ob);
        }
    } else if (PyDateTime_Check(ob)) {
        memset(&tm, 0, sizeof(tm));
        tm.tm_year = PyDateTime_GET_YEAR(ob);
        tm.tm_mon = PyDateTime_GET_MONTH(ob);
        tm.tm_mday = PyDateTime_GET_DAY(ob);
        tm.tm_hour = PyDateTime_DATE_GET_HOUR(ob);
        tm.tm_min = PyDateTime_DATE_GET_MINUTE(ob);
        tm.tm_sec = PyDateTime_DATE_GET_SECOND(ob);
        usec = PyDateTime_DATE_GET_MICROSECOND(ob);
        tm.tm_year -= 1900;
        db = dbtime_newtm(ctx, &tm, usec);
#ifdef WANT_UUID_TYPE
    } else if (PyObject_TypeCheck(ob, uuid_class)) {
        ob = PyObject_CallMethod(ob, "get_bytes", NULL);
        PyString_AsStringAndSize(ob, &buf, &length);
        db = dbuuid_new(ctx, (uint8_t*)buf);
#endif
    } else if (Py_TYPE(ob) == &PongoList_Type) {
        // Resolve proxy types back to their original dbtype
        PongoList *p = (PongoList*)ob;
        db = p->dbptr;
    } else if (Py_TYPE(ob) == &PongoDict_Type) {
        // Resolve proxy types back to their original dbtype
        PongoDict *p = (PongoDict*)ob;
        db = p->dbptr;
    } else if (Py_TYPE(ob) == &PongoCollection_Type) {
        // Resolve proxy types back to their original dbtype
        PongoCollection *p = (PongoCollection*)ob;
        db = p->dbptr;
    } else if (PyMapping_Check(ob)) {
        length = PyMapping_Length(ob);
        items = PyMapping_Items(ob);
        if (items) {
            // mapping object implements "items"
            db = dbobject_new(ctx);
            dbobject_update(ctx, db, length, _py_mapping_cb, items, NOSYNC);
            Py_XDECREF(items);
        } else {
            // mapping object implements iterator protocol
            // don't have to decref the iterator object cuz it self-decrefs
            // upon StopIteration
            PyErr_Clear();
            items = PyObject_GetIter(ob);
            db = dbobject_new(ctx);
            dbobject_update(ctx, db, length, _py_itermapping_cb, items, NOSYNC);
        }
    } else if (PySequence_Check(ob)) {
        length = PySequence_Length(ob);
        db = dblist_new(ctx);
        dblist_extend(ctx, db, length, _py_sequence_cb, ob, NOSYNC);
    } else {
        // FIXME: Unknown object type
        PyErr_SetObject(PyExc_TypeError, (PyObject*)Py_TYPE(ob));
        db = DBNULL;
    }
    return db;
}
static void py_to_float(PyObject *py, char *data)
{
	*(float *)data = (float)PyFloat_AsDouble(py);
}
Exemple #20
0
// takes one arg: Params
int smds_core_init(PyObject *self, PyObject *args, PyObject *kwds)
{
  static  char *kwlist[] = { "p", NULL };
  smds_core *c = (smds_core*)self;
  PyObject *p = NULL, *o = NULL, *oo = NULL, *s = NULL, *ss = NULL;
  double dX, dT, size, concentration;
  double preSize, postSize;
  int i;
#ifdef CORE_INTENS
  int binWidth_x;
#ifdef CORE_3D
  int binWidth_z;
#endif
#else
  int radius;
  int threshold;
#ifdef CORE_3D
  int Z;
  int threshold_Z;
#endif
#endif
  double flow_x;		// m/s

  if (!ParamsType)
  {
    PyErr_SetString(PyExc_SystemError, "Unable to find Params type.");
    return -1;
  }

#ifdef CORE_INTENS
  if (!IntensType)
  {
    PyErr_SetString(PyExc_SystemError, "Unable to find Intens type.");
    return -1;
  }
#endif

  seedRnd(Random(NULL), &c->rs);

  // p is borrowed
  if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!", kwlist, 
  					&PyInstance_Type, &p))
    return -1;
  {
    PyObject *cls = PyObject_GetAttrString(p, "__class__");
    if (!cls) return -1;
    i = PyObject_Compare(cls, ParamsType);
    Py_DECREF(cls);
    if (PyErr_Occurred()) return -1;
    if (i != 0)
    {
      PyErr_SetString(PyExc_TypeError,
           "Argument must be an instance of the correct smds.Params type.");
      return -1;
    }
  }

  c->ready = 0;
  c->dur = 0;
  c->I = 0.0;

  o = PyObject_GetAttrString(p, "dT");
  if (!o) return -1;
  dT = PyFloat_AsDouble(o)*1e-9;		// s
  Py_DECREF(o);
  if (PyErr_Occurred()) return -1;

  o = PyObject_GetAttrString(p, "binWidth");
  if (!o) return -1;
  c->bw = PyFloat_AsDouble(o);			// ms
  c->steps = (int)(c->bw * 1.0e-3 / dT + 0.5);
  Py_DECREF(o);
  if (PyErr_Occurred()) return -1;

  o = PyObject_GetAttrString(p, "bkg");
  if (!o) return -1;
  c->bkg = c->bw * PyFloat_AsDouble(o);
  Py_DECREF(o);
  if (PyErr_Occurred()) return -1;
  
  o = PyObject_GetAttrString(p, "numMolecs");
  if (!o) return -1;
  c->numMolecs = PyInt_AsLong(o);
  Py_DECREF(o);
  if (PyErr_Occurred()) return -1;
  
  o = PyObject_GetAttrString(p, "flowLength");
  if (!o) return -1;
  preSize = PyFloat_AsDouble(o);		// um
  Py_DECREF(o);
  if (PyErr_Occurred()) return -1;
  
  o = PyObject_GetAttrString(p, "drainLength");
  if (!o) return -1;
  postSize = PyFloat_AsDouble(o);		// um
  Py_DECREF(o);
  if (PyErr_Occurred()) return -1;
  
  o = PyObject_GetAttrString(p, "concentration");
  if (!o) return -1;
  concentration = PyFloat_AsDouble(o);
#ifdef CORE_3D
  size = sqrt((double)(c->numMolecs)/concentration/(preSize+postSize));
#else
  size = (double)(c->numMolecs)/concentration/(preSize+postSize);
#endif
  Py_DECREF(o);
  if (PyErr_Occurred()) return -1;
  
#ifdef CORE_INTENS
  s = PyObject_GetAttrString(p, "intens");
  if (!s || !PyInstance_Check(s) ||
      !(o = PyObject_GetAttrString(s, "__class__")) ||
      PyObject_Compare(IntensType, o) != 0 || (i = (int)PyErr_Occurred()))
  {
    if (!i)  PyErr_SetString(PyExc_TypeError,
                      "Expected an instance of type smds.Task.Intens.");
    goto bail;
  }
  Py_DECREF(o);

  o = PyObject_GetAttrString(s, "data");
  if (!o)
  {
    PyErr_SetString(PyExc_ValueError, "Intensity Profile lacks data!");
    goto bail;
  }
  c->intens = (PyArrayObject*)PyArray_ContiguousFromObject(o, 
  				PyArray_DOUBLE, 1, 1);
			  	// c->intens is a new ref
  if (PyErr_Occurred())
  {
    PyErr_SetString(PyExc_ValueError, "Unintelligible Intensity profile.");
    goto bail;
  }
  Py_DECREF(o);

  o = PyObject_GetAttrString(s, "binWidth_x");
  if (!o) goto bail;
  binWidth_x = PyInt_AsLong(o);
  if (PyErr_Occurred()) goto bail;
  Py_DECREF(o);

  o = PyObject_GetAttrString(s, "numBins_x");
  if (!o) goto bail;
  c->numBins_x = PyInt_AsLong(o);
  if (PyErr_Occurred()) goto bail;
  Py_DECREF(o);
#ifdef CORE_3D
  o = PyObject_GetAttrString(s, "binWidth_z");
  if (!o) goto bail;
  binWidth_z = PyInt_AsLong(o);
  if (PyErr_Occurred()) goto bail;
  Py_DECREF(o);

  o = PyObject_GetAttrString(s, "numBins_z");
  if (!o) goto bail;
  c->numBins_z = PyInt_AsLong(o);
  if (PyErr_Occurred()) goto bail;
  Py_DECREF(o);
#endif
  Py_DECREF(s);  s = NULL;
#else
  o = PyObject_GetAttrString(p, "radius");
  if (!o) return -1;
  radius = PyInt_AsLong(o);
  Py_DECREF(o);
  if (PyErr_Occurred()) return -1;

  o = PyObject_GetAttrString(p, "threshold");
  if (!o) return -1;
  threshold = PyInt_AsLong(o);
  Py_DECREF(o);
  if (PyErr_Occurred()) return -1;
#ifdef CORE_3D
  o = PyObject_GetAttrString(p, "Z");
  if (!o) return -1;
  Z = PyInt_AsLong(o);
  Py_DECREF(o);
  if (PyErr_Occurred()) return -1;

  o = PyObject_GetAttrString(p, "threshold_Z");
  if (!o) return -1;
  threshold_Z = PyInt_AsLong(o);
  Py_DECREF(o);
  if (PyErr_Occurred()) return -1;
#endif
#endif

  o = PyObject_GetAttrString(p, "flow");		// m/s
  if (!o) return -1;
  flow_x = PyFloat_AsDouble(o) * 1e6;			// um/s
  if (flow_x == 0.0) c->dir_flow_x = 0;
  else c->dir_flow_x = (flow_x > 0.0 ? 1 : -1);
  flow_x = fabs(flow_x);
  Py_DECREF(o);
  if (PyErr_Occurred()) return -1;

#ifdef CORE_3D
  c->t_insert_avg = -1./(concentration*size*size*flow_x*dT);
#else
  c->t_insert_avg = -1./(concentration*size*flow_x*dT);
#endif
  do
  {
    c->t_insert = (int)(log(DRandom(&c->rs))*c->t_insert_avg);
  }
  while (!c->t_insert);

  ss = PyObject_GetAttrString(p, "SpeciesType");
  if (!ss) return -1;

  o = PyObject_GetAttrString(p, "sample");
  if (!o) return -1;
  if (PyList_Check(o))
  {
    PyObject *oo = PyList_AsTuple(o);
    Py_DECREF(o);
    o = oo;
  }
  if (!PyTuple_Check(o)) goto bail;
  c->numSpecies = PyTuple_Size(o);
  if (c->numSpecies <= 0)
  {
    PyErr_SetString(PyExc_ValueError, "You must have at least one species.");
    goto bail;
  }
  free(c->size); c->size = (Int32*)malloc(sizeof(Int32)*c->numSpecies);
  free(c->minX); c->minX = (Int32*)malloc(sizeof(Int32)*c->numSpecies);
  free(c->maxX); c->maxX = (Int32*)malloc(sizeof(Int32)*c->numSpecies);
  free(c->X);  c->X = (double*)malloc(sizeof(double)*c->numSpecies);
  free(c->a);  c->a = (double*)malloc(sizeof(double)*c->numSpecies);
  free(c->counts);  c->counts = (int*)malloc(sizeof(int)*c->numSpecies);
#ifdef CORE_INTENS
  free(c->sc_x);  c->sc_x = (double*)malloc(sizeof(double)*c->numSpecies);
#ifdef CORE_3D
  free(c->sc_z);  c->sc_z = (double*)malloc(sizeof(double)*c->numSpecies);
#endif
#else
  free(c->threshold);  
    c->threshold = (Int32*)malloc(sizeof(Int32)*c->numSpecies);
  free(c->b);  c->b = (double*)malloc(sizeof(double)*c->numSpecies);
#ifdef CORE_3D
  free(c->threshold_z);  
    c->threshold_z = (Int32*)malloc(sizeof(Int32)*c->numSpecies);
  free(c->c);  c->c = (double*)malloc(sizeof(double)*c->numSpecies);
#endif
#endif
#ifdef CORE_BLEACH
  free(c->tol);  c->tol = (int*)malloc(sizeof(int)*c->numSpecies);
  free(c->numBleached);
    c->numBleached = (int*)malloc(sizeof(int)*c->numSpecies);
#endif
  free(c->flow_x);
  c->flow_x = (double*)malloc(sizeof(double)*c->numSpecies);
  if (!(c->size && c->minX && c->maxX && c->X && c->a && c->counts
#ifdef CORE_INTENS
        && c->sc_x
#ifdef CORE_3D
        && c->sc_z
#endif
#else
        && c->threshold && c->b
#ifdef CORE_3D
        && c->threshold_z && c->c
#endif
#endif
#ifdef CORE_BLEACH
        && c->tol && c->numBleached
#endif
        && c->flow_x
     ))
  {
    PyErr_SetString(PyExc_MemoryError, "Memory allocation error.");
    goto bail;
  }
  for(i=0; i < c->numSpecies; i++)
  {
    int I = 0;
    s = PyTuple_GetItem(o, i);		// s is borrowed
    if (!s || !PyInstance_Check(s) || 
        !(oo = PyObject_GetAttrString(s, "__class__")) ||
        PyObject_Compare(ss, oo) != 0 || (I = (int)PyErr_Occurred()) )
    {
      if (!I)  PyErr_SetString(PyExc_TypeError,
      			"Wrong species type for this core.");
      goto bail;
    }
    Py_DECREF(oo);
    
    oo = PyObject_GetAttrString(s, "Fraction");
    if (!oo) goto bail;
    c->X[i] = PyFloat_AsDouble(oo);
    if (PyErr_Occurred()) goto bail;
    Py_DECREF(oo);
    
#ifdef CORE_BLEACH
    c->numBleached[i] = 0;
    oo = PyObject_GetAttrString(s, "tolerance");
    if (!oo) goto bail;
    c->tol[i] = -PyFloat_AsDouble(oo);
    if (PyErr_Occurred()) goto bail;
    Py_DECREF(oo);
#endif

                /* diffCoeff is in cm^2/s, 1.0e-4 converts to um^-1
                        multiply dX by a um distance to get 'dX'es  */
    oo = PyObject_GetAttrString(s, "D");
    if (!oo) goto bail;
#ifdef CORE_3D
    dX = 1.0 / sqrt(6.0 * PyFloat_AsDouble(oo) * dT) * 1e-4;
#else
    dX = 1.0 / sqrt(4.0 * PyFloat_AsDouble(oo) * dT) * 1e-4;
#endif
    if (PyErr_Occurred()) goto bail;
    Py_DECREF(oo);
    
    oo = PyObject_GetAttrString(s, "Imax");
    if (!oo) goto bail;
    c->a[i] = PyFloat_AsDouble(oo) * dT * 1.0e3;
    if (PyErr_Occurred()) goto bail;
    Py_DECREF(oo);  oo = NULL;

    c->size[i] = (int)((double)(size) * dX / 2.0);
    if (c->dir_flow_x < 0)
    {
      c->minX[i] = -(int)(postSize * dX);
      c->maxX[i] = (int)(preSize * dX);
    } else {
      c->minX[i] = -(int)(preSize * dX);
      c->maxX[i] = (int)(postSize * dX);
    }
    if (!( c->size[i] < sqrt((unsigned)(1 << 31)) &&
           c->maxX[i]-c->minX[i] < sqrt((unsigned)(1 << 31)) ))
    {
      PyErr_SetString(PyExc_ValueError, "Simulation space is too large.");
      goto bail;
    }

#ifdef CORE_INTENS
    c->sc_x[i] = 1.0 / binWidth_x / dX * 1.0e3;
#ifdef CORE_3D
    c->sc_z[i] = 1.0 / binWidth_z / dX * 1.0e3;
#endif
#else
    c->threshold[i] = (int)((double)(threshold * threshold) *
                    (dX * dX) * 1.0e-6);
    c->b[i] = -2.0 / (double)(radius * radius) / (dX * dX) * 1.0e6;
#ifdef CORE_3D
    c->threshold_z[i] = (int)( (double)(threshold_Z) * dX * 1.0e-3);
    c->c[i] = -2.0 / (double)(Z * Z) / (dX * dX) * 1.0e6;
#endif
#endif

    c->flow_x[i] = flow_x*dT*dX;

    c->counts[i] = 0;
    Py_DECREF(s);  s = NULL;
  }
  Py_DECREF(ss);  ss = NULL;

  if (c->molecs)
  {
    smds_molec *m = c->avail;
    if (!c->avail) c->avail = c->molecs;
    else 
    {
      while (m->next) m = m->next;
      m->next = c->molecs;
      c->molecs = NULL;
    }
  }
  for (i=0; i < c->numMolecs; i++)
  {
    smds_molec *m;
    if (c->avail)
    {
      m = c->avail;
      c->avail = c->avail->next;
    } else {
      m = (smds_molec*)malloc(sizeof(smds_molec));
    }
    m->prev = NULL;
    smds_core_create_molec(m, c, 0);
    if (c->molecs) c->molecs->prev = m;
    m->next = c->molecs;
    c->molecs = m;
  }

  c->ready = 1;
  return 0;
bail:
  if (o)  { Py_DECREF(o);  }
  if (oo) { Py_DECREF(oo); }
  if (s)  { Py_DECREF(s);  }
  if (ss) { Py_DECREF(ss); }
  return -1;
}
/**
 *  evalDistribution function evaluate a model function with input vector
 *  @param args: input q as vector or [qx, qy] where qx, qy are vectors
 *
 */ 
static PyObject * evalDistribution(CFlexCylEllipXModel *self, PyObject *args){
	PyObject *qx, *qy;
	PyArrayObject * pars;
	int npars ,mpars;
	
	// 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.evalDistribution expects a q value.");
		return NULL;
	}
    // Check params
	
    if(PyArray_Check(pars)==1) {
		
	    // Length of list should 1 or 2
	    npars = pars->nd; 
	    if(npars==1) {
	        // input is a numpy array
	        if (PyArray_Check(pars)) {
		        return evaluateOneDim(self->model, (PyArrayObject*)pars); 
		    }
		}else{
		    PyErr_SetString(CFlexCylEllipXModelError, 
                   "CFlexCylEllipXModel.evalDistribution expect numpy array of one dimension.");
	        return NULL;
		}
    }else if( PyList_Check(pars)==1) {
    	// Length of list should be 2 for I(qx,qy)
	    mpars = PyList_GET_SIZE(pars); 
	    if(mpars!=2) {
	    	PyErr_SetString(CFlexCylEllipXModelError, 
	    		"CFlexCylEllipXModel.evalDistribution expects a list of dimension 2.");
	    	return NULL;
	    }
	     qx = PyList_GET_ITEM(pars,0);
	     qy = PyList_GET_ITEM(pars,1);
	     if (PyArray_Check(qx) && PyArray_Check(qy)) {
	         return evaluateTwoDimXY(self->model, (PyArrayObject*)qx,
		           (PyArrayObject*)qy);
		 }else{
		    PyErr_SetString(CFlexCylEllipXModelError, 
                   "CFlexCylEllipXModel.evalDistribution expect 2 numpy arrays in list.");
	        return NULL;
	     }
	}
	PyErr_SetString(CFlexCylEllipXModelError, 
                   "CFlexCylEllipXModel.evalDistribution couln't be run.");
	return NULL;
	
}
//-------------------------------------------------------------------------------------
bool InitProgressHandler::process()
{
	Components::COMPONENTS& cts = Components::getSingleton().getComponents(BASEAPPMGR_TYPE);
	Mercury::Channel* pChannel = NULL;

	if(cts.size() > 0)
	{
		Components::COMPONENTS::iterator ctiter = cts.begin();
		if((*ctiter).pChannel == NULL)
			return true;

		pChannel = (*ctiter).pChannel;
	}

	if(pChannel == NULL)
		return true;

	float v = 0.0f;
	bool completed = false;

	if(PyObject_HasAttrString(Baseapp::getSingleton().getEntryScript().get(), "readlyForLogin") > 0)
	{
		// 所有脚本都加载完毕
		PyObject* pyResult = PyObject_CallMethod(Baseapp::getSingleton().getEntryScript().get(), 
											const_cast<char*>("readlyForLogin"), 
											const_cast<char*>("i"), 
											g_componentGroupOrder);

		if(pyResult != NULL)
		{
			completed = (pyResult == Py_True);
			
			if(!completed)
			{
				v = (float)PyFloat_AsDouble(pyResult);
				if (PyErr_Occurred())
				{
					SCRIPT_ERROR_CHECK();
					Py_DECREF(pyResult);
					return true;
				}
			}
			else
			{
				v = 100.f;
			}

			Py_DECREF(pyResult);
		}
		else
		{
			SCRIPT_ERROR_CHECK();
			return true;
		}
	}
	else
	{
		v = 100.f;
		completed = true;
	}
	
	if(v >= 0.9999f)
	{
		v = 100.f;
		completed = true;
	}

	Mercury::Bundle::SmartPoolObjectPtr bundleptr = Mercury::Bundle::createSmartPoolObj();

	(*bundleptr)->newMessage(BaseappmgrInterface::onBaseappInitProgress);
	(*(*bundleptr)) << g_componentID << v;
	(*bundleptr)->send(networkInterface_, pChannel);

	if(completed)
	{
		delete this;
		return false;
	}

	return true;
}
static PyObject*
cdr_count(PyObject* self, PyObject* args)
{
    /* Arguments. */
    char format;
    PyObject* octet_string;
    unsigned long offset;
    PyObject* value;
    CORBA_boolean byte_order;

    /* The return value is the new offset after 'marshalling' the data. */
    PyObject* result;

    /* Stuff to get the job done! */
    CORBA_octet* os;
    CORBA_octet* p;

    CORBA_boolean boolean_val;
    CORBA_octet octet_val;
    CORBA_unsigned_short ushort_val;
    CORBA_short short_val;
    CORBA_unsigned_long ulong_val;
    CORBA_long long_val;
    CORBA_unsigned_longlong ulonglong_val;
    CORBA_longlong longlong_val;
    CORBA_float float_val;
    CORBA_double double_val;
    CORBA_char* string_val;
    CORBA_octet* octets_val;
    CORBA_unsigned_long len;
    
    /* Parse the arguments. */
    if (!PyArg_ParseTuple(args, "cO!lbO", &format, &PyString_Type,
			  &octet_string, (long*) &offset, &byte_order, &value))
    {
	return NULL;
    }

    /* Get a pointer to the data of the Python string. */
    os = (CORBA_octet*) PyString_AsString(octet_string);
    p = &os[offset];

    switch(format) {

    case 'b':
	/* boolean */
	boolean_val = (CORBA_boolean) PyInt_AsLong(value);
	(void) cdr_count_boolean(os, &p, byte_order, boolean_val);
	result = Py_BuildValue ("l", p - os);
 	break;

    case 'c':
	/* char */
	string_val = (CORBA_char*) PyString_AsString(value);
	(void) cdr_count_char(os, &p, byte_order, (CORBA_char) string_val[0]);
	result = Py_BuildValue ("l", p - os);
	break;

    case 'o':
	/* octet */
	octet_val = (CORBA_octet) PyInt_AsLong(value);
	(void) cdr_count_octet(os, &p, byte_order, octet_val);
	result = Py_BuildValue ("l", p - os);
	break;

    case 'h':
	/* short */
	short_val = (CORBA_short) PyInt_AsLong(value);
	(void) cdr_count_short(os, &p, byte_order, short_val);
	result = Py_BuildValue ("l", p - os);
	break;

    case 'H':
	/* unsigned short */
	ushort_val = (CORBA_unsigned_short) PyInt_AsLong(value);
	(void) cdr_count_unsigned_short(os,&p, byte_order, ushort_val);
	result = Py_BuildValue ("l", p - os);
	break;

    case 'l':
	/* long */
	long_val = (CORBA_long) PyInt_AsLong(value);
	(void) cdr_count_long(os, &p, byte_order, long_val);
	result = Py_BuildValue ("l", p - os);
	break;

    case 'L':
	/* unsigned long */
	if PyInt_Check(value) {
	  ulong_val = (CORBA_unsigned_long) PyInt_AsLong(value);
	}
	else {
	  ulong_val = (CORBA_unsigned_long) PyLong_AsUnsignedLong(value);
        }
	(void) cdr_count_unsigned_long(os, &p, byte_order, ulong_val);
	result = Py_BuildValue ("l", p - os);
	break;

    case 'n':
	/* long long */
	(void) cdr_count_longlong(os, &p, byte_order, longlong_val);
	result = Py_BuildValue ("l", p - os);
	break;

    case 'N':
	/* unsigned long long */
	(void) cdr_count_unsigned_longlong(os, &p, byte_order, ulonglong_val);
	result = Py_BuildValue ("l", p - os);
	break;

    case 'f':
	/* float */
	float_val = (CORBA_float) PyFloat_AsDouble(value);
	(void) cdr_count_float(os, &p, byte_order, float_val);
	result = Py_BuildValue ("l", p - os);
	break;

    case 'd':
	/* double */
	double_val = (CORBA_double) PyFloat_AsDouble(value);
	(void) cdr_count_double(os, &p, byte_order, double_val);
	result = Py_BuildValue ("l", p - os);
	break;

    case 's':
	/* string */
	string_val = (CORBA_char*) PyString_AsString(value);
	(void) cdr_count_string(os, &p, byte_order, string_val);
	result = Py_BuildValue ("l", p - os);
	break;

    case 'O':
	/* sequence of octets */
	len = PyString_Size(value);
	octets_val = (CORBA_octet*) PyString_AsString(value);
	(void) cdr_count_octets(os, &p, byte_order, octets_val, len);
	result = Py_BuildValue ("l", p - os);
	break;

    default:
	return cdr_error("Invalid format character", 0);
    };
Exemple #24
0
static PyObject* pysplicing_to_gff(PyObject *self, PyObject *args) {
  
  PyObject *pygff, *entries;
  size_t i, noRec;
  splicing_gff_t *cgff;
  PyObject *IDkey, *Parentkey;
  
  if (!PyArg_ParseTuple(args, "O", &pygff)) { return NULL; }

  if (!PyObject_HasAttrString(pygff, "_GFFDatabase__entries")) {
    splicingmodule_handle_splicing_error();
    return NULL;
  }
  entries=PyObject_GetAttrString(pygff, "_GFFDatabase__entries");
  noRec=PySequence_Size(entries);

  IDkey=PyString_FromString("ID");
  Parentkey=PyString_FromString("Parent");

  cgff=malloc(sizeof(splicing_gff_t));
  if (!cgff) { splicingmodule_handle_splicing_error(); return NULL; }
  splicing_gff_init(cgff, noRec);
  
  for (i=0; i<noRec; i++) {
    PyObject *rec=0, *seqid=0, *source=0, *type=0, *start=0, *end=0,
      *score=0, *strand=0, *phase=0, *attributes=0, *ID=0, *Parent=0;
    char *Cseqid, *Csource, *CID, *Cparent=0, *Ctype;
    splicing_type_t Ctype2;
    int Cstart, Cend, Cphase;
    double Cscore;
    splicing_strand_t Cstrand;
    
    rec=PySequence_GetItem(entries, i);
    seqid=PyObject_GetAttrString(rec, "seqid");
    source=PyObject_GetAttrString(rec, "source");
    type=PyObject_GetAttrString(rec, "type");
    start=PyObject_GetAttrString(rec, "start");
    end=PyObject_GetAttrString(rec, "end");
    score=PyObject_GetAttrString(rec, "score");
    strand=PyObject_GetAttrString(rec, "strand");
    phase=PyObject_GetAttrString(rec, "phase");
    attributes=PyObject_GetAttrString(rec, "attributes");
    ID=PyDict_GetItem(attributes, IDkey);
    Parent=PyDict_GetItem(attributes, Parentkey);

    Cseqid=PyString_AsString(seqid);
    Csource=PyString_AsString(source);

    Ctype=PyString_AsString(type);
    if (!strcmp(Ctype, "gene")) { 
      Ctype2=SPLICING_TYPE_GENE;
    } else if (!strcmp(Ctype, "mRNA")) {
      Ctype2=SPLICING_TYPE_MRNA;
    } else if (!strcmp(Ctype, "exon")) {
      Ctype2=SPLICING_TYPE_EXON;
    } else if (!strcmp(Ctype, "CDS")) {
      Ctype2=SPLICING_TYPE_CDS;
    } else if (!strcmp(Ctype, "start_codon")) {
      Ctype2=SPLICING_TYPE_START_CODON;
    } else if (!strcmp(Ctype, "stop_codon")) {
      Ctype2=SPLICING_TYPE_STOP_CODON;
    } /* TODO: else error? */

    Cstart=PyInt_AsLong(start);
    Cend=PyInt_AsLong(end);
    Cscore=PyFloat_AsDouble(score);
    Cstrand=PyInt_AsLong(strand);
    Cphase=PyInt_AsLong(phase);
    CID=PyString_AsString(ID);
    if (Parent) { Cparent=PyString_AsString(Parent); }

    SPLICING_PYCHECK(splicing_gff_append(cgff, Cseqid, Csource, Ctype2, 
					 Cstart, Cend, Cscore, Cstrand,
					 Cphase, CID, Cparent));

    Py_DECREF(rec); Py_DECREF(seqid); Py_DECREF(source); Py_DECREF(type);
    Py_DECREF(start); Py_DECREF(end); Py_DECREF(score); Py_DECREF(strand);
    Py_DECREF(phase); Py_DECREF(attributes);
  }

  Py_DECREF(entries);
  Py_DECREF(IDkey);
  Py_DECREF(Parentkey);
  
  return PyCObject_FromVoidPtr(cgff, splicing_gff_destroy2);
}
 const double get() { return PyFloat_AsDouble(obj.get()); }
Exemple #26
0
//-------------------------------------------------------------------------------------
int ScriptVector4::pySetW(PyObject *value)
{ 
	getVector().w = float(PyFloat_AsDouble(value)); 
	return 0; 
}
Exemple #27
0
/**
 * Constructor
 */
dtnode :: dtnode(PyArrayObject* arg_edges, PyObject* arg_children,
                 PyObject* arg_maxind, int arg_leafstart)
{       
  // Do some argument checking
  if(!PyList_Check(arg_children) || !PyList_Check(arg_maxind))
    {    
      // ERROR
      PyErr_SetString(PyExc_RuntimeError,
                      "Non-List children/maxind element in dirtree node");
      throw 1;
    }
  if(arg_leafstart < 0) 
    {
      // ERROR
      PyErr_SetString(PyExc_RuntimeError,
                      "Negative leafstart value in dirtree node");
      throw 1;
    }
  if(PyList_Size(arg_children) != PyList_Size(arg_maxind))
    {
      // ERROR
      PyErr_SetString(PyExc_RuntimeError,
                      "Different sizes for children/maxind in dirtree node");
      throw 1;
    }    
  double edgemin = PyFloat_AsDouble(PyArray_Min(arg_edges,NPY_MAXDIMS,NULL));    
  if(edgemin <= 0) 
    {
      // ERROR
      PyErr_SetString(PyExc_RuntimeError,
                      "Negative/zero edge value in dirtree node");
      throw 1;
    }

  // Populate data members
  int nci = PyList_Size(arg_children);
  this->leafstart = arg_leafstart;
  
  // Get edge values and sum
  // (note that this *must* be a copy!)
  npy_intp* edims = new npy_intp[1];
  edims[0] = PyArray_DIM(arg_edges,0);
  this->edges = (PyArrayObject*) PyArray_ZEROS(1,edims,PyArray_DOUBLE,0);
  PyArray_CopyInto(this->edges,arg_edges);
  this->edgesum = PyFloat_AsDouble(PyArray_Sum(this->edges,NPY_MAXDIMS,
                                               PyArray_DOUBLE,NULL));   
  // Also make a copy of *original* edge values 
  // (not augmented by counts)
  this->orig_edges = (PyArrayObject*) PyArray_ZEROS(1,edims,PyArray_DOUBLE,0);
  PyArray_CopyInto(this->orig_edges,arg_edges);
  this->orig_edgesum = PyFloat_AsDouble(PyArray_Sum(this->orig_edges,NPY_MAXDIMS,
                                                    PyArray_DOUBLE,NULL));   
  delete[] edims;

  // Recursively build children
  // 
  int c;
  for(c = 0; c < nci; c++)
    {    
      // Get max leaf index under this child, check it
      maxind.push_back(PyInt_AsLong(PyList_GetItem(arg_maxind,c)));
      if(maxind[c] < 0)
        {
          // ERROR
          PyErr_SetString(PyExc_RuntimeError,
                          "Negative maxind value in dirtree node");
          throw 1;
        }
      // exploiting boolean short-circuit here...
      if(c > 0 && maxind[c] <= maxind[c-1])
        {
          // ERROR
          PyErr_SetString(PyExc_RuntimeError,
                          "Non-increasing maxind value in dirtree node");
          throw 1;
        }
     
      // Recursively build child
      //
      try{
        // Check that node tuple size is correct
        PyObject* pynode = PyList_GetItem(arg_children,c);
        // Is child a dtnode, or a multinode?
        //
        if(4 == PyTuple_Size(pynode))
          {
            // dtnode

            // Unpack tuple contents
            PyArrayObject* cedges = (PyArrayObject*) PyTuple_GetItem(pynode,0);
            PyObject* cchildren = PyTuple_GetItem(pynode,1);
            PyObject* cmaxind = PyTuple_GetItem(pynode,2);
            int cleafstart = PyInt_AsLong(PyTuple_GetItem(pynode,3));
        
            // Build child dtnode
            node* newchild = new dtnode(cedges,cchildren,
                                        cmaxind,cleafstart);
            ichildren.push_back(newchild);
          }
        else if(5 == PyTuple_Size(pynode))
          {
            // multinode

            // Unpack tuple contents        
            PyObject* cchildren = PyTuple_GetItem(pynode,1);
            PyObject* cmaxind = PyTuple_GetItem(pynode,2);
            int cleafstart = PyInt_AsLong(PyTuple_GetItem(pynode,3));
            PyObject* variants = PyTuple_GetItem(pynode,4);

            // Build child multinode
            node* newchild = new multinode(cchildren,cmaxind,
                                           cleafstart,variants);
            ichildren.push_back(newchild);
          }
        else{
          // ERROR
          PyErr_SetString(PyExc_RuntimeError,
                          "Node has wrong number of elements");
          throw 1;
        }
      }
      catch (int err)
        {
          throw 1;
        }
    }
}
Exemple #28
0
static PyObject *compute_emd(PyObject *self, PyObject *args, PyObject *keywds)
{
  static char *kwlist[] = {"feature1", "feature2", "weight1", "weight2",
                           NULL};

  PyObject *feature1, *feature2, *weight1, *weight2;
  double *f1, *f2;
  float *w1, *w2;
  int length1, length2;
  signature_t signature1, signature2;
  float distance;
  PyObject *item;
  int i;

  if(!PyArg_ParseTupleAndKeywords(args, keywds, "OOOO", kwlist,
                                  &feature1, &feature2, &weight1, &weight2))
     return NULL;

  if(!PySequence_Check(feature1)) {
    PyErr_SetString(PyExc_TypeError, "feature1 must be a sequence");
    return NULL;
  }

  if(!PySequence_Check(feature2)) {
    PyErr_SetString(PyExc_TypeError, "feature2 must be a sequence");
    return NULL;
  }

  if(!PySequence_Check(weight1)) {
    PyErr_SetString(PyExc_TypeError, "weight1 must be a sequence");
    return NULL;
  }

  if(!PySequence_Check(weight2)) {
    PyErr_SetString(PyExc_TypeError, "weight2 must be a sequence");
    return NULL;
  }

  length1 = PySequence_Size(feature1);
  length2 = PySequence_Size(feature2);

  if(PySequence_Size(weight1) != length1) {
    PyErr_SetString(PyExc_TypeError, "feature1 and weight1 must be the same");
    return NULL;
  }

  if(PySequence_Size(weight2) != length2) {
    PyErr_SetString(PyExc_TypeError, "feature2 and weight2 must be the same");
    return NULL;
  }

  f1 = alloca(length1 * sizeof(double));
  f2 = alloca(length2 * sizeof(double));
  w1 = alloca(length1 * sizeof(double));
  w2 = alloca(length2 * sizeof(double));

  for(i = 0; i < length1; i ++) {
    item = PySequence_GetItem(feature1, i);
    if(!PyFloat_Check(item) && !PyInt_Check(item)) {
      Py_DECREF(item);
      PyErr_SetString(PyExc_TypeError, "f1 should be a sequence of numbers");
      return NULL;
    }
    f1[i] = PyFloat_AsDouble(item);
    Py_DECREF(item);

    item = PySequence_GetItem(weight1, i);
    if(!PyFloat_Check(item) && !PyInt_Check(item)) {
      Py_DECREF(item);
      PyErr_SetString(PyExc_TypeError, "w1 should be a sequence of numbers");
      return NULL;
    }
    w1[i] = PyFloat_AsDouble(item);
    Py_DECREF(item);
  }

  for(i = 0; i < length2; i ++) {
    item = PySequence_GetItem(feature2, i);
    if(!PyFloat_Check(item) && !PyInt_Check(item)) {
      Py_DECREF(item);
      PyErr_SetString(PyExc_TypeError, "f2 should be a sequence of numbers");
      return NULL;
    }
    f2[i] = PyFloat_AsDouble(item);
    Py_DECREF(item);

    item = PySequence_GetItem(weight2, i);
    if(!PyFloat_Check(item) && !PyInt_Check(item)) {
      Py_DECREF(item);
      PyErr_SetString(PyExc_TypeError, "w2 should be a sequence of numbers");
      return NULL;
    }
    w2[i] = PyFloat_AsDouble(item);
    Py_DECREF(item);
  }

  signature1.n = length1;
  signature1.Features = f1;
  signature1.Weights = w1;

  signature2.n = length2;
  signature2.Features = f2;
  signature2.Weights = w2;

  distance = emd(&signature1, &signature2, double_dist, 0, 0);

  return Py_BuildValue("d", distance);
}
int convert_dashes(PyObject *dashobj, void *dashesp)
{
    Dashes *dashes = (Dashes *)dashesp;

    if (dashobj == NULL && dashobj == Py_None) {
        return 1;
    }

    PyObject *dash_offset_obj = NULL;
    double dash_offset = 0.0;
    PyObject *dashes_seq = NULL;
    Py_ssize_t nentries;

    if (!PyArg_ParseTuple(dashobj, "OO:dashes", &dash_offset_obj, &dashes_seq)) {
        return 0;
    }

    if (dash_offset_obj != Py_None) {
        dash_offset = PyFloat_AsDouble(dash_offset_obj);
        if (PyErr_Occurred()) {
            return 0;
        }
    }

    if (dashes_seq == Py_None) {
        return 1;
    }

    if (!PySequence_Check(dashes_seq)) {
        PyErr_SetString(PyExc_TypeError, "Invalid dashes sequence");
        return 0;
    }

    nentries = PySequence_Size(dashes_seq);
    if (nentries % 2 != 0) {
        PyErr_Format(PyExc_ValueError, "dashes sequence must have an even number of elements");
        return 0;
    }

    for (Py_ssize_t i = 0; i < nentries; ++i) {
        PyObject *item;
        double length;
        double skip;

        item = PySequence_GetItem(dashes_seq, i);
        if (item == NULL) {
            return 0;
        }
        length = PyFloat_AsDouble(item);
        if (PyErr_Occurred()) {
            Py_DECREF(item);
            return 0;
        }
        Py_DECREF(item);

        ++i;

        item = PySequence_GetItem(dashes_seq, i);
        if (item == NULL) {
            return 0;
        }
        skip = PyFloat_AsDouble(item);
        if (PyErr_Occurred()) {
            Py_DECREF(item);
            return 0;
        }
        Py_DECREF(item);

        dashes->add_dash_pair(length, skip);
    }

    dashes->set_dash_offset(dash_offset);

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

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

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

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

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


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

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

		PyObject *obUse = NULL;

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

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

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

	Py_INCREF(Py_None);
	return Py_None;
Error:
	return NULL;
}