Beispiel #1
0
//-------------------------------------------------------------------------------------
PyObject* Entity::pyTeleport(PyObject* nearbyMBRef, PyObject* pyposition, PyObject* pydirection)
{
	if(!PySequence_Check(pyposition) || PySequence_Size(pyposition) != 3)
	{
		PyErr_Format(PyExc_Exception, "%s::teleport: %d position not is Sequence!\n", getScriptName(), getID());
		PyErr_PrintEx(0);
		S_Return;
	}

	if(!PySequence_Check(pydirection) || PySequence_Size(pydirection) != 3)
	{
		PyErr_Format(PyExc_Exception, "%s::teleport: %d direction not is Sequence!\n", getScriptName(), getID());
		PyErr_PrintEx(0);
		S_Return;
	}

	Position3D pos;
	Direction3D dir;

	PyObject* pyitem = PySequence_GetItem(pyposition, 0);
	pos.x = (float)PyFloat_AsDouble(pyitem);
	Py_DECREF(pyitem);

	pyitem = PySequence_GetItem(pyposition, 1);
	pos.y = (float)PyFloat_AsDouble(pyitem);
	Py_DECREF(pyitem);

	pyitem = PySequence_GetItem(pyposition, 2);
	pos.z = (float)PyFloat_AsDouble(pyitem);
	Py_DECREF(pyitem);

	pyitem = PySequence_GetItem(pydirection, 0);
	dir.roll = (float)PyFloat_AsDouble(pyitem);
	Py_DECREF(pyitem);

	pyitem = PySequence_GetItem(pydirection, 1);
	dir.pitch = (float)PyFloat_AsDouble(pyitem);
	Py_DECREF(pyitem);

	pyitem = PySequence_GetItem(pydirection, 2);
	dir.yaw = (float)PyFloat_AsDouble(pyitem);
	Py_DECREF(pyitem);
	
	teleport(nearbyMBRef, pos, dir);
	S_Return;
}
static int double_from_pyobj(double* v,PyObject *obj,const char *errmess) {
  PyObject* tmp = NULL;
  if (PyFloat_Check(obj)) {
#ifdef __sgi
    *v = PyFloat_AsDouble(obj);
#else
    *v = PyFloat_AS_DOUBLE(obj);
#endif
    return 1;
  }
  tmp = PyNumber_Float(obj);
  if (tmp) {
#ifdef __sgi
    *v = PyFloat_AsDouble(tmp);
#else
    *v = PyFloat_AS_DOUBLE(tmp);
#endif
    Py_DECREF(tmp);
    return 1;
  }
  if (PyComplex_Check(obj))
    tmp = PyObject_GetAttrString(obj,"real");
  else if (PyString_Check(obj) || PyUnicode_Check(obj))
    /*pass*/;
  else if (PySequence_Check(obj))
    tmp = PySequence_GetItem(obj,0);
  if (tmp) {
    PyErr_Clear();
    if (double_from_pyobj(v,tmp,errmess)) {Py_DECREF(tmp); return 1;}
    Py_DECREF(tmp);
  }
  {
    PyObject* err = PyErr_Occurred();
    if (err==NULL) err = uts_scsmfo_error;
    PyErr_SetString(err,errmess);
  }
  return 0;
}
Beispiel #3
0
/*returns NULL on success, error string on failure*/
static int idp_sequence_type(PyObject *seq)
{
    PyObject *item;
    int type= IDP_INT;

    int i, len = PySequence_Size(seq);
    for (i=0; i < len; i++) {
        item = PySequence_GetItem(seq, i);
        if (PyFloat_Check(item)) {
            if(type == IDP_IDPARRAY) { /* mixed dict/int */
                Py_DECREF(item);
                return -1;
            }
            type= IDP_DOUBLE;
        }
        else if (PyLong_Check(item)) {
            if(type == IDP_IDPARRAY) { /* mixed dict/int */
                Py_DECREF(item);
                return -1;
            }
        }
        else if (PyMapping_Check(item)) {
            if(i != 0 && (type != IDP_IDPARRAY)) { /* mixed dict/int */
                Py_DECREF(item);
                return -1;
            }
            type= IDP_IDPARRAY;
        }
        else {
            Py_XDECREF(item);
            return -1;
        }

        Py_DECREF(item);
    }

    return type;
}
Beispiel #4
0
/*
 * Converts a Python sequence into 'count' PyArrayObjects
 *
 * seq       - Input Python object, usually a tuple but any sequence works.
 * op        - Where the arrays are placed.
 * count     - How many arrays there should be (errors if it doesn't match).
 * paramname - The name of the parameter that produced 'seq'.
 */
static int sequence_to_arrays(PyObject *seq,
                                PyArrayObject **op, int count,
                                char *paramname)
{
    int i;

    if (!PySequence_Check(seq) || PySequence_Size(seq) != count) {
        PyErr_Format(PyExc_ValueError,
                "parameter %s must be a sequence of length %d",
                paramname, count);
        return -1;
    }

    for (i = 0; i < count; ++i) {
        PyObject *item = PySequence_GetItem(seq, i);
        if (item == NULL) {
            while (--i >= 0) {
                Py_DECREF(op[i]);
                op[i] = NULL;
            }
            return -1;
        }

        op[i] = (PyArrayObject *)PyArray_FromAny(item, NULL, 0, 0, 0, NULL);
        if (op[i] == NULL) {
            while (--i >= 0) {
                Py_DECREF(op[i]);
                op[i] = NULL;
            }
            Py_DECREF(item);
            return -1;
        }

        Py_DECREF(item);
    }

    return 0;
}
Beispiel #5
0
BOOL PyADSIObject_AsADS_SEARCHPREF_INFOs(PyObject *ob, ADS_SEARCHPREF_INFO **ppret, DWORD *pcinfos)
{
	BOOL ret = FALSE;
	if (!PySequence_Check(ob)) {
		PyErr_SetString(PyExc_TypeError, "ADS_SEARCHPREF_INFOs must be a sequence");
		return FALSE;
	}
	// Use C++ reference to make working with ppret more convenient.
	ADS_SEARCHPREF_INFO *&pret = *ppret;
	DWORD &nitems = *pcinfos;
	nitems = PySequence_Length(ob);

	pret = (ADS_SEARCHPREF_INFO *)malloc(sizeof(ADS_SEARCHPREF_INFO) * nitems);
	if (!pret) {
		PyErr_NoMemory();
		return NULL;
	}
	memset(pret, 0, sizeof(ADS_SEARCHPREF_INFO) * nitems);
	PyObject *sub = NULL;
	PyObject *obValue; // no reference
	DWORD i;
	for (i=0;i<nitems;i++) {
		PyObject *sub = PySequence_GetItem(ob, i);
		if (!sub) goto done;
		if (!PyArg_ParseTuple(sub, "iO:ADS_SEARCHPREF_INFO tuple", &pret[i].dwSearchPref, &obValue))
			goto done;
		if (!PyADSIObject_AsADSVALUE(obValue, pret[i].vValue))
			goto done;
		Py_DECREF(sub);
		sub = NULL;
	}
	ret = TRUE;
done:
	Py_XDECREF(sub);
	if (!ret && pret)
		PyADSIObject_FreeADS_SEARCHPREF_INFOs(pret, nitems);
	return ret;
}
static GPtrArray *create_row(PyObject *item){
	assert(item);
	GPtrArray *row = g_ptr_array_new();
	if(!row)
		return NULL;
	int i;
	for(i = 0; i < PySequence_Size(item); i++){
		PyObject *elem = PySequence_GetItem(item, i);
		if(!elem)
			goto failed;
		PyObject *elem_str = PyObject_Str(elem);
		Py_DECREF(elem);
		if(!elem_str)
			goto failed;
		g_ptr_array_add(row, g_strdup(PyString_AsString(elem_str)));
		Py_DECREF(elem_str);
	}
	return row;

failed:
	g_ptr_array_clear(row);
	return NULL;
}
double* listtoarray(PyObject* o,int *size)
{
    int length;
    double* result;
    double tempval;
    PyObject* tempObject;
    int i;
    //printf("Started List to Array\n");
    length = PySequence_Size(o);
    //printf("%d\n",length);
    result=malloc(length*sizeof(double));
    for(i=0;i<length;i++)
    {
      //printf("%d\n",i);
	tempObject=PySequence_GetItem(o,i);
	tempval=PyFloat_AsDouble(tempObject);
	//printf("%g\n",tempval);
	result[i]=tempval;
    }
    //printf("The length is: %d\n",length);
    *size=length;
    return result;
}
Beispiel #8
0
static PyObject*
save_mask(PyObject *self, PyObject *arg)
{
    int idx, size;
    PyObject *list, *item;

    if (!PyArg_ParseTuple(arg, "O", &list)) {
        return NULL;
    }

    sigemptyset(&newmask);
    size = PySequence_Length(list);
    for (idx = 0; idx < size; ++idx) {
        item = PySequence_GetItem(list, idx);
        sigaddset(&newmask, PyInt_AsLong(item));
    }

    if (sigprocmask(SIG_BLOCK, &newmask, &oldmask) != 0) {
        Py_Exit(1);
    }

    Py_RETURN_NONE;
}
void convert2_float_array(float *result, PyObject *input, int size) {
  int i;
  if (!PySequence_Check(input)) {
    printf("Expected a sequence\n");
    exit(EXIT_FAILURE);
  }
  int length=PySequence_Length(input);
  if (length > size) {
    printf("Size mismatch.\n");
    exit(EXIT_FAILURE);
  }
  for (i = 0; i < length; i++) {
    PyObject *o = PySequence_GetItem(input,i);
    if (PyNumber_Check(o)) {
      result[i] = (float) PyFloat_AsDouble(o);
    } else {
      printf("Sequence elements must be numbers\n");
      free(result);       
      exit(EXIT_FAILURE);
    }
    free(o);
  }
}
Beispiel #10
0
static Box* seqiterHasnext_capi(Box* s) noexcept {
    RELEASE_ASSERT(s->cls == seqiter_cls || s->cls == seqreviter_cls, "");
    BoxedSeqIter* self = static_cast<BoxedSeqIter*>(s);

    if (!self->b) {
        Py_RETURN_FALSE;
    }

    Box* next = PySequence_GetItem(self->b, self->idx);
    if (!next) {
        if (PyErr_ExceptionMatches(IndexError) || PyErr_ExceptionMatches(StopIteration)) {
            PyErr_Clear();
            Py_CLEAR(self->b);
            Py_RETURN_FALSE;
        }
        return NULL;
    }

    self->idx++;
    RELEASE_ASSERT(!self->next, "");
    self->next = next;
    Py_RETURN_TRUE;
}
Beispiel #11
0
static PyObject *Playlist_remove_tracks(Playlist *self, PyObject *args) {
    PyObject *py_tracks;
    PyObject *item;
    sp_error err;
    int *tracks;
    int num_tracks;
    int playlist_length;
    int i;

    if(!PyArg_ParseTuple(args, "O", &py_tracks))
        return NULL;
    if (!PySequence_Check(py_tracks)) {
        PyErr_SetString(PyExc_TypeError, "expected sequence");
        return NULL;
    }
    num_tracks = PySequence_Size(py_tracks);
    tracks = (int *) malloc(sizeof(tracks)*num_tracks);
    playlist_length = sp_playlist_num_tracks(self->_playlist);
    for (i = 0; i < num_tracks; i++) {
        item = PySequence_GetItem(py_tracks, i);
        if (!PyInt_Check(item)) {
            free(tracks);
            PyErr_SetString(PyExc_TypeError, "expected sequence of integers");
            return NULL;
        }
        tracks[i] = (int)PyInt_AsLong(item);
        if (tracks[i] > playlist_length) {
            PyErr_SetString(PyExc_IndexError, "specified track does not exist");
            return NULL;
        }
        Py_DECREF(item);
    }
    Py_BEGIN_ALLOW_THREADS
    err = sp_playlist_remove_tracks(self->_playlist, tracks, num_tracks);
    Py_END_ALLOW_THREADS
    return handle_error(err);
}
static GPtrArray *create_fields(PyObject *resultset){
	assert(resultset);
	if(!PyDict_Check(resultset)){
		PyErr_SetString(PyExc_ValueError, "response.resultset must be a dict");
		return NULL;
	}
	PyObject *res_fields = PyDict_GetItemString(resultset, "fields");
	if(!res_fields){
		PyErr_SetString(PyExc_KeyError, "resultset has no key named 'fields'!");
		return NULL;
	}
	if(!PySequence_Check(res_fields)){
		PyErr_SetString(PyExc_ValueError, "proxy.response.resultset.fields "
					"should be eigher a list or a tuple");
		return NULL;
	}
	GPtrArray *fields = network_mysqld_proto_fielddefs_new();
	int i;
	for(i = 0; i < PySequence_Size(res_fields); i++){
		PyObject *item = PySequence_GetItem(res_fields, i);
		if(!item){
			network_mysqld_proto_fielddefs_free(fields);
			g_critical("Create item failed");
			return NULL;
		}
		MYSQL_FIELD *field = create_field(item);
		Py_DECREF(item);

		if(!field){
			network_mysqld_proto_fielddefs_free(fields);
			g_critical("Create fields failed");
			return NULL;
		}
		g_ptr_array_add(fields, field);
	}
	return fields;
}
// ---------------------------------------------------
//
// Gateway Implementation
STDMETHODIMP PyGSpecifyPropertyPages::GetPages(
		/* [out] */ CAUUID __RPC_FAR * pPages)
{
	PY_GATEWAY_METHOD;
	PyObject *result;
	HRESULT hr=InvokeViaPolicy("GetPages", &result);
	if (FAILED(hr)) return hr;

    int length=PyObject_Length(result);

    if(length<1 || !PySequence_Check(result) )
    {
        // Python implementation did not return a sequence
        PyErr_Clear();
        return E_NOTIMPL;
    }

    pPages->cElems=0;
    pPages->pElems=(GUID *)CoTaskMemAlloc(length*sizeof(GUID)); // Not all may be used

    for(int i=0;i<length;++i)
    {
        if(PyWinObject_AsIID(PySequence_GetItem(result,i),pPages->pElems+pPages->cElems))
        {
            // Sucessfully converted, so put the next GUID in the next slot
            pPages->cElems++;
        }
        else
        {
            // Could not convert this GUID; ignore it and continue.
            PyErr_Clear();
        }
    }

	Py_DECREF(result);
	return hr;
}
Beispiel #14
0
/*NUMPY_API
 * Convert an object to an array of n NPY_CLIPMODE values.
 * This is intended to be used in functions where a different mode
 * could be applied to each axis, like in ravel_multi_index.
 */
NPY_NO_EXPORT int
PyArray_ConvertClipmodeSequence(PyObject *object, NPY_CLIPMODE *modes, int n)
{
    int i;
    /* Get the clip mode(s) */
    if (object && (PyTuple_Check(object) || PyList_Check(object))) {
        if (PySequence_Size(object) != n) {
            PyErr_Format(PyExc_ValueError,
                    "list of clipmodes has wrong length (%d instead of %d)",
                    (int)PySequence_Size(object), n);
            return NPY_FAIL;
        }

        for (i = 0; i < n; ++i) {
            PyObject *item = PySequence_GetItem(object, i);
            if(item == NULL) {
                return NPY_FAIL;
            }

            if(PyArray_ClipmodeConverter(item, &modes[i]) != NPY_SUCCEED) {
                Py_DECREF(item);
                return NPY_FAIL;
            }

            Py_DECREF(item);
        }
    }
    else if (PyArray_ClipmodeConverter(object, &modes[0]) == NPY_SUCCEED) {
        for (i = 1; i < n; ++i) {
            modes[i] = modes[0];
        }
    }
    else {
        return NPY_FAIL;
    }
    return NPY_SUCCEED;
}
Beispiel #15
0
static double * read_list_float_attr(PyObject * record_obj, char * attr_name)
/* Read a list of floating point values from a Python record given the
 * attribute name and return a C list of doubles. The C list has to be
 * deallocated with free.
 */
{
  /* new reference */
  PyObject * item_list_obj = PyObject_GetAttrString(record_obj, attr_name);
  
  int num_item = (int) PySequence_Length(item_list_obj);
  
  double * retval = (double *) malloc(num_item * sizeof(double));

  int idx;
  
  for (idx = 0; idx < num_item; idx++)
  {
    /* new reference */
    PyObject * item_obj = PySequence_GetItem(item_list_obj, (Py_ssize_t) idx);

    retval[idx] = PyFloat_AsDouble(item_obj);

    Py_DECREF(item_obj);
  }
  
  Py_DECREF(item_list_obj);

#ifdef VERYVERBOSE
  printf(" %s = [", attr_name);
  for (idx = 0; idx < num_item; idx++)
    printf("%lf, ", retval[idx]);
  printf("]\n");
#endif

  return retval;
}
Beispiel #16
0
	static void* convertible(PyObject* obj_ptr){
		if(!PySequence_Check(obj_ptr)) return 0;
		bool isFlat=!PySequence_Check(py::handle<>(PySequence_GetItem(obj_ptr,0)).get());
		// mixed static/dynamic not handled (also not needed)
		BOOST_STATIC_ASSERT(
			(MT::RowsAtCompileTime!=Eigen::Dynamic && MT::ColsAtCompileTime!=Eigen::Dynamic)
			||
			(MT::RowsAtCompileTime==Eigen::Dynamic && MT::ColsAtCompileTime==Eigen::Dynamic)
		);
		int sz=PySequence_Size(obj_ptr);
		if(MT::RowsAtCompileTime!=Eigen::Dynamic){
			if(isFlat){
				// flat sequence (first item not sub-sequence), must contain exactly all items
				if(sz!=MT::RowsAtCompileTime*MT::ColsAtCompileTime) return 0;
			} else {
				// contains nested sequences, one per row
				if(sz!=MT::RowsAtCompileTime) return 0;
			}
		};
		return obj_ptr;
		// other checks done in the construct function
		// FIXME: it may be too late to do it there, as overloads are chosen based on *convertible*
		// (at least a clear message should be given when py::extract fails there)
	}
Beispiel #17
0
static PyObject *t_sequence_pop(t_sequence *self, PyObject *args)
{
    int index = -1, setDirty = 1;
    PyObject *value;

    if (!PyArg_ParseTuple(args, "|ii", &index, &setDirty))
        return NULL;

    value = PySequence_GetItem(self->sequence, index);
    if (!value)
        return NULL;

    if (!(self->itemvalue.flags & V_PURE))
    {
        PyObject *v = _restoreValue(self, value);
        Py_DECREF(value);
        
        if (!v)
            return NULL;
        value = v;
    }

    if (PySequence_DelItem(self->sequence, index) < 0)
    {
        Py_DECREF(value);
        return NULL;
    }

    if (setDirty && _t_itemvalue__setDirty((t_itemvalue *) self, 0) < 0)
    {
        Py_DECREF(value);
        return NULL;
    }

    return value;
}
Beispiel #18
0
//-------------------------------------------------------------------------
Py_ssize_t pyvar_walk_list(
        const ref_t &py_list,
        int (idaapi *cb)(const ref_t &py_item, Py_ssize_t index, void *ud),
        void *ud)
{
  PYW_GIL_CHECK_LOCKED_SCOPE();

  Py_ssize_t size = CIP_FAILED;
  do
  {
    PyObject *o = py_list.o;
    if ( !PyList_CheckExact(o) && !PyW_IsSequenceType(o) )
      break;

    bool is_seq = !PyList_CheckExact(o);
    size = is_seq ? PySequence_Size(o) : PyList_Size(o);
    if ( cb == NULL )
      break;

    Py_ssize_t i;
    for ( i=0; i<size; i++ )
    {
      // Get the item
      ref_t py_item;
      if ( is_seq )
        py_item = newref_t(PySequence_GetItem(o, i));
      else
        py_item = borref_t(PyList_GetItem(o, i));

      if ( py_item == NULL || cb(py_item, i, ud) < CIP_OK )
        break;
    }
    size = i;
  } while ( false );
  return size;
}
Beispiel #19
0
Robot::Location Robot::getLocation() {

	Robot::Location l;
	PyObject *pValue = callMethod("getLocation");
	/** pValue = ('locName', (x, y, orientation)) **/

	if (pValue != NULL) {
		PythonLock lock = PythonLock();

		if (!PySequence_Check(pValue)) {
			//problem!
		} else {
			l.name = std::string(PyString_AsString(PySequence_GetItem(pValue, 0)));
			l.x = PyFloat_AsDouble(PySequence_GetItem(PySequence_GetItem(pValue, 1), 0));
			l.y = PyFloat_AsDouble(PySequence_GetItem(PySequence_GetItem(pValue, 1), 1));
			l.orientation = PyFloat_AsDouble(PySequence_GetItem(PySequence_GetItem(pValue, 1), 2));
		}

		Py_DECREF(pValue);
	}

	return l;
}
Beispiel #20
0
static char *
converttuple(PyObject *arg, char **p_format, va_list *p_va, int *levels,
	     char *msgbuf, size_t bufsize, int toplevel, PyObject **freelist)
{
	int level = 0;
	int n = 0;
	char *format = *p_format;
	int i;
	
	for (;;) {
		int c = *format++;
		if (c == '(') {
			if (level == 0)
				n++;
			level++;
		}
		else if (c == ')') {
			if (level == 0)
				break;
			level--;
		}
		else if (c == ':' || c == ';' || c == '\0')
			break;
		else if (level == 0 && isalpha(c))
			n++;
	}
	
	if (!PySequence_Check(arg) || PyString_Check(arg)) {
		levels[0] = 0;
		PyOS_snprintf(msgbuf, bufsize,
			      toplevel ? "expected %d arguments, not %.50s" :
			              "must be %d-item sequence, not %.50s",
			      n, 
			      arg == Py_None ? "None" : arg->ob_type->tp_name);
		return msgbuf;
	}
	
	if ((i = PySequence_Size(arg)) != n) {
		levels[0] = 0;
		PyOS_snprintf(msgbuf, bufsize,
			      toplevel ? "expected %d arguments, not %d" :
			             "must be sequence of length %d, not %d",
			      n, i);
		return msgbuf;
	}

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

	*p_format = format;
	return NULL;
}
Beispiel #21
0
/*
  Retrive the (optional) _pack_ attribute from a type, the _fields_ attribute,
  and create an StgDictObject.  Used for Structure and Union subclasses.
*/
int
StructUnionType_update_stgdict(PyObject *type, PyObject *fields, int isStruct)
{
	StgDictObject *stgdict, *basedict;
	Py_ssize_t len, offset, size, align, i;
	Py_ssize_t union_size, total_align;
	Py_ssize_t field_size = 0;
	int bitofs;
	PyObject *isPacked;
	int pack = 0;
	Py_ssize_t ffi_ofs;
	int big_endian;

	/* HACK Alert: I cannot be bothered to fix ctypes.com, so there has to
	   be a way to use the old, broken sematics: _fields_ are not extended
	   but replaced in subclasses.
	   
	   XXX Remove this in ctypes 1.0!
	*/
	int use_broken_old_ctypes_semantics;

	if (fields == NULL)
		return 0;

#ifdef WORDS_BIGENDIAN
	big_endian = PyObject_HasAttrString(type, "_swappedbytes_") ? 0 : 1;
#else
	big_endian = PyObject_HasAttrString(type, "_swappedbytes_") ? 1 : 0;
#endif

	use_broken_old_ctypes_semantics = \
		PyObject_HasAttrString(type, "_use_broken_old_ctypes_structure_semantics_");

	isPacked = PyObject_GetAttrString(type, "_pack_");
	if (isPacked) {
		pack = PyInt_AsLong(isPacked);
		if (pack < 0 || PyErr_Occurred()) {
			Py_XDECREF(isPacked);
			PyErr_SetString(PyExc_ValueError,
					"_pack_ must be a non-negative integer");
			return -1;
		}
		Py_DECREF(isPacked);
	} else
		PyErr_Clear();

	len = PySequence_Length(fields);
	if (len == -1) {
		PyErr_SetString(PyExc_TypeError,
				"'_fields_' must be a sequence of pairs");
		return -1;
	}

	stgdict = PyType_stgdict(type);
	if (!stgdict)
		return -1;
	/* If this structure/union is already marked final we cannot assign
	   _fields_ anymore. */

	if (stgdict->flags & DICTFLAG_FINAL) {/* is final ? */
		PyErr_SetString(PyExc_AttributeError,
				"_fields_ is final");
		return -1;
	}

	if (stgdict->format) {
		PyMem_Free(stgdict->format);
		stgdict->format = NULL;
	}

	if (stgdict->ffi_type_pointer.elements)
		PyMem_Free(stgdict->ffi_type_pointer.elements);

	basedict = PyType_stgdict((PyObject *)((PyTypeObject *)type)->tp_base);
	if (basedict && !use_broken_old_ctypes_semantics) {
		size = offset = basedict->size;
		align = basedict->align;
		union_size = 0;
		total_align = align ? align : 1;
		stgdict->ffi_type_pointer.type = FFI_TYPE_STRUCT;
		stgdict->ffi_type_pointer.elements = PyMem_Malloc(sizeof(ffi_type *) * (basedict->length + len + 1));
		if (stgdict->ffi_type_pointer.elements == NULL) {
			PyErr_NoMemory();
			return -1;
		}
		memset(stgdict->ffi_type_pointer.elements, 0,
		       sizeof(ffi_type *) * (basedict->length + len + 1));
		memcpy(stgdict->ffi_type_pointer.elements,
		       basedict->ffi_type_pointer.elements,
		       sizeof(ffi_type *) * (basedict->length));
		ffi_ofs = basedict->length;
	} else {
		offset = 0;
		size = 0;
		align = 0;
		union_size = 0;
		total_align = 1;
		stgdict->ffi_type_pointer.type = FFI_TYPE_STRUCT;
		stgdict->ffi_type_pointer.elements = PyMem_Malloc(sizeof(ffi_type *) * (len + 1));
		if (stgdict->ffi_type_pointer.elements == NULL) {
			PyErr_NoMemory();
			return -1;
		}
		memset(stgdict->ffi_type_pointer.elements, 0,
		       sizeof(ffi_type *) * (len + 1));
		ffi_ofs = 0;
	}

	assert(stgdict->format == NULL);
	if (isStruct && !isPacked) {
		stgdict->format = alloc_format_string(NULL, "T{");
	} else {
		/* PEP3118 doesn't support union, or packed structures (well,
		   only standard packing, but we dont support the pep for
		   that). Use 'B' for bytes. */
		stgdict->format = alloc_format_string(NULL, "B");
	}

#define realdict ((PyObject *)&stgdict->dict)
	for (i = 0; i < len; ++i) {
		PyObject *name = NULL, *desc = NULL;
		PyObject *pair = PySequence_GetItem(fields, i);
		PyObject *prop;
		StgDictObject *dict;
		int bitsize = 0;

		if (!pair || !PyArg_ParseTuple(pair, "OO|i", &name, &desc, &bitsize)) {
			PyErr_SetString(PyExc_AttributeError,
					"'_fields_' must be a sequence of pairs");
			Py_XDECREF(pair);
			return -1;
		}
		dict = PyType_stgdict(desc);
		if (dict == NULL) {
			Py_DECREF(pair);
			PyErr_Format(PyExc_TypeError,
#if (PY_VERSION_HEX < 0x02050000)
				     "second item in _fields_ tuple (index %d) must be a C type",
#else
				     "second item in _fields_ tuple (index %zd) must be a C type",
#endif
				     i);
			return -1;
		}
		stgdict->ffi_type_pointer.elements[ffi_ofs + i] = &dict->ffi_type_pointer;
		if (dict->flags & (TYPEFLAG_ISPOINTER | TYPEFLAG_HASPOINTER))
			stgdict->flags |= TYPEFLAG_HASPOINTER;
		dict->flags |= DICTFLAG_FINAL; /* mark field type final */
		if (PyTuple_Size(pair) == 3) { /* bits specified */
			switch(dict->ffi_type_pointer.type) {
			case FFI_TYPE_UINT8:
			case FFI_TYPE_UINT16:
			case FFI_TYPE_UINT32:
			case FFI_TYPE_SINT64:
			case FFI_TYPE_UINT64:
				break;

			case FFI_TYPE_SINT8:
			case FFI_TYPE_SINT16:
			case FFI_TYPE_SINT32:
				if (dict->getfunc != getentry("c")->getfunc
#ifdef CTYPES_UNICODE
				    && dict->getfunc != getentry("u")->getfunc
#endif
					)
					break;
				/* else fall through */
			default:
				PyErr_Format(PyExc_TypeError,
					     "bit fields not allowed for type %s",
					     ((PyTypeObject *)desc)->tp_name);
				Py_DECREF(pair);
				return -1;
			}
			if (bitsize <= 0 || bitsize > dict->size * 8) {
				PyErr_SetString(PyExc_ValueError,
						"number of bits invalid for bit field");
				Py_DECREF(pair);
				return -1;
			}
		} else
			bitsize = 0;
		if (isStruct && !isPacked) {
			char *fieldfmt = dict->format ? dict->format : "B";
			char *fieldname = PyString_AsString(name);
			char *ptr;
			Py_ssize_t len = strlen(fieldname) + strlen(fieldfmt);
			char *buf = alloca(len + 2 + 1);

			sprintf(buf, "%s:%s:", fieldfmt, fieldname);

			ptr = stgdict->format;
			stgdict->format = alloc_format_string(stgdict->format, buf);
			PyMem_Free(ptr);

			if (stgdict->format == NULL) {
				Py_DECREF(pair);
				return -1;
			}
		}
		if (isStruct) {
			prop = CField_FromDesc(desc, i,
					       &field_size, bitsize, &bitofs,
					       &size, &offset, &align,
					       pack, big_endian);
		} else /* union */ {
			size = 0;
			offset = 0;
			align = 0;
			prop = CField_FromDesc(desc, i,
					       &field_size, bitsize, &bitofs,
					       &size, &offset, &align,
					       pack, big_endian);
			union_size = max(size, union_size);
		}
		total_align = max(align, total_align);

		if (!prop) {
			Py_DECREF(pair);
			return -1;
		}
		if (-1 == PyObject_SetAttr(type, name, prop)) {
			Py_DECREF(prop);
			Py_DECREF(pair);
			return -1;
		}
		Py_DECREF(pair);
		Py_DECREF(prop);
	}
#undef realdict

	if (isStruct && !isPacked) {
		char *ptr = stgdict->format;
		stgdict->format = alloc_format_string(stgdict->format, "}");
		PyMem_Free(ptr);
		if (stgdict->format == NULL)
			return -1;
	}

	if (!isStruct)
		size = union_size;

	/* Adjust the size according to the alignment requirements */
	size = ((size + total_align - 1) / total_align) * total_align;

	stgdict->ffi_type_pointer.alignment = Py_SAFE_DOWNCAST(total_align,
							       Py_ssize_t,
							       unsigned short);
	stgdict->ffi_type_pointer.size = size;

	stgdict->size = size;
	stgdict->align = total_align;
	stgdict->length = len;	/* ADD ffi_ofs? */

	/* We did check that this flag was NOT set above, it must not
	   have been set until now. */
	if (stgdict->flags & DICTFLAG_FINAL) {
		PyErr_SetString(PyExc_AttributeError,
				"Structure or union cannot contain itself");
		return -1;
	}
	stgdict->flags |= DICTFLAG_FINAL;

	return MakeAnonFields(type);
}
Beispiel #22
0
static PyObject *
Process_func_spawn(Process *self, PyObject *args, PyObject *kwargs)
{
    int err, flags, len, stdio_count;
    unsigned int uid, gid;
    char *cwd, *cwd2, *file, *file2, *arg_str, *tmp_str, *key_str, *value_str;
    char **ptr, **process_args, **process_env;
    Py_ssize_t i, n, pos;
    PyObject *key, *value, *item, *tmp, *callback, *arguments, *env, *stdio, *ret;
    uv_process_options_t options;
    uv_stdio_container_t *stdio_container;

    static char *kwlist[] = {"file", "exit_callback", "args", "env", "cwd", "uid", "gid", "flags", "stdio", NULL};

    cwd = NULL;
    ptr = process_args = process_env = NULL;
    tmp = arguments = env = stdio = NULL;
    stdio_container = NULL;
    flags = uid = gid = stdio_count = 0;

    RAISE_IF_SPAWNED(self, NULL);

    if (!PyArg_ParseTupleAndKeywords(args, kwargs, "s|OOO!sIIiO:__init__", kwlist, &file, &callback, &arguments, &PyDict_Type, &env, &cwd, &uid, &gid, &flags, &stdio)) {
        return NULL;
    }

    if (callback != Py_None && !PyCallable_Check(callback)) {
        PyErr_SetString(PyExc_TypeError, "a callable is required");
        return NULL;
    }

    if (arguments && !PySequence_Check(arguments)) {
        PyErr_SetString(PyExc_TypeError, "only iterable objects are supported for 'args'");
        return NULL;
    }

    if (stdio && !PySequence_Check(stdio)) {
        PyErr_SetString(PyExc_TypeError, "only iterable objects are supported for 'stdio'");
        return NULL;
    }

    memset(&options, 0, sizeof(uv_process_options_t));

    options.uid = uid;
    options.gid = gid;
    options.flags = flags;
    options.exit_cb = on_process_exit;

    file2 = PyMem_Malloc(strlen(file) + 1);
    if (!file2) {
        PyErr_NoMemory();
        ret = NULL;
        goto cleanup;
    }
    strcpy(file2, file);
    options.file = file2;

    if (arguments) {
        n = PySequence_Length(arguments);
        process_args = PyMem_Malloc(sizeof *process_args * (n + 2));
        if (!process_args) {
            PyErr_NoMemory();
            PyMem_Free(file2);
            ret = NULL;
            goto cleanup;
        }
        process_args[0] = file2;
        i = 0;
        while (i < n) {
            item = PySequence_GetItem(arguments, i);
            if (!item || !PyArg_Parse(item, "s;args contains a non-string value", &arg_str)) {
                Py_XDECREF(item);
                ret = NULL;
                goto cleanup;
            }
            tmp_str = PyMem_Malloc(strlen(arg_str) + 1);
            if (!tmp_str) {
                Py_DECREF(item);
                ret = NULL;
                goto cleanup;
            }
            strcpy(tmp_str, arg_str);
            process_args[i+1] = tmp_str;
            Py_DECREF(item);
            i++;
        }
        process_args[i+1] = NULL;
    } else {
        process_args = PyMem_Malloc(sizeof *process_args * 2);
        if (!process_args) {
            PyErr_NoMemory();
            PyMem_Free(file2);
            ret = NULL;
            goto cleanup;
        }
        process_args[0] = file2;
        process_args[1] = NULL;
    }
    options.args = process_args;

    if (cwd) {
        cwd2 = PyMem_Malloc(strlen(cwd) + 1);
        if (!cwd2) {
            PyErr_NoMemory();
            ret = NULL;
            goto cleanup;
        }
        strcpy(cwd2, cwd);
        options.cwd = cwd2;
    }

    if (env) {
        n = PyDict_Size(env);
        if (n > 0) {
            process_env = PyMem_Malloc(sizeof *process_env * (n + 1));
            if (!process_env) {
                PyErr_NoMemory();
                ret = NULL;
                goto cleanup;
            }
            i = 0;
            pos = 0;
            while (PyDict_Next(env, &pos, &key, &value)) {
                if (!PyArg_Parse(key, "s;env contains a non-string key", &key_str) || !PyArg_Parse(value, "s;env contains a non-string value", &value_str)) {
                    ret = NULL;
                    goto cleanup;
                }
                len = strlen(key_str) + strlen(value_str) + 2;
                tmp_str = PyMem_Malloc(len);
                if (!tmp_str) {
                    PyErr_NoMemory();
                    ret = NULL;
                    goto cleanup;
                }
                PyOS_snprintf(tmp_str, len, "%s=%s", key_str, value_str);
                process_env[i] = tmp_str;
                i++;
            }
            process_env[i] = NULL;
        }
    }
    options.env = process_env;

    if (stdio) {
        n = PySequence_Length(stdio);
        stdio_container = PyMem_Malloc(sizeof *stdio_container * n);
        if (!stdio_container) {
            PyErr_NoMemory();
            ret = NULL;
            goto cleanup;
        }
        item = NULL;
        for (i = 0;i < n; i++) {
            item = PySequence_GetItem(stdio, i);
            if (!item || !PyObject_TypeCheck(item, &StdIOType)) {
                Py_XDECREF(item);
                PyErr_SetString(PyExc_TypeError, "a StdIO instance is required");
                ret = NULL;
                goto cleanup;
            }
            stdio_count++;
            stdio_container[i].flags = ((StdIO *)item)->flags;
            if (((StdIO *)item)->flags & (UV_CREATE_PIPE | UV_INHERIT_STREAM)) {
                stdio_container[i].data.stream = (uv_stream_t *)(UV_HANDLE(((StdIO *)item)->stream));
            } else if (((StdIO *)item)->flags & UV_INHERIT_FD) {
                stdio_container[i].data.fd = ((StdIO *)item)->fd;
            }
            Py_DECREF(item);
        }
    }
    options.stdio = stdio_container;
    options.stdio_count = stdio_count;

    err = uv_spawn(UV_HANDLE_LOOP(self), &self->process_h, &options);
    if (err < 0) {
        RAISE_UV_EXCEPTION(err, PyExc_ProcessError);
        ret = NULL;
        goto cleanup;
    }

    tmp = (PyObject *)self->on_exit_cb;
    Py_INCREF(callback);
    self->on_exit_cb = callback;
    Py_XDECREF(tmp);

    tmp = self->stdio;
    Py_XINCREF(stdio);
    self->stdio = stdio;
    Py_XDECREF(tmp);

    HANDLE(self)->initialized = True;
    self->spawned = True;

    ret = Py_None;

    /* Increase refcount so that object is not removed before the exit callback is called */
    Py_INCREF(self);

cleanup:
    if (options.args) {
        for (ptr = options.args; *ptr != NULL; ptr++) {
            PyMem_Free(*ptr);
        }
    }

    if (options.env) {
        for (ptr = options.env; *ptr != NULL; ptr++) {
            PyMem_Free(*ptr);
        }
    }

    PyMem_Free(options.args);
    PyMem_Free(options.cwd);
    PyMem_Free(options.env);
    PyMem_Free(options.stdio);

    Py_XINCREF(ret);
    return ret;
}
Beispiel #23
0
int
set_pscards(
    /*@unused@*/ const char* propname,
    PyObject* value,
    struct pscard** ps,
    int *nps,
    int *npsmax) {

  PyObject*   subvalue  = NULL;
  Py_ssize_t  i         = 0;
  Py_ssize_t  size      = 0;
  int         ival      = 0;
  int         mval      = 0;
  const char* strvalue  = 0;
  void*       newmem    = NULL;

  if (!PySequence_Check(value))
    return -1;
  size = PySequence_Size(value);
  if (size > 0x7fffffff) {
    /* Must be a 32-bit size */
    return -1;
  }

  if (size > (Py_ssize_t)*npsmax) {
    newmem = malloc(sizeof(struct pscard) * size);
    if (newmem == NULL) {
      PyErr_SetString(PyExc_MemoryError, "Could not allocate memory.");
      return -1;
    }
    free(*ps);
    *ps = newmem;
    *npsmax = (int)size;
  }

  /* Verify the entire list for correct types first, so we don't have
     to undo anything copied into the canonical array. */
  for (i = 0; i < size; ++i) {
    subvalue = PySequence_GetItem(value, i);
    if (subvalue == NULL) {
      return -1;
    }
    if (!PyArg_ParseTuple(subvalue, "iis", &ival, &mval, &strvalue)) {
      Py_DECREF(subvalue);
      return -1;
    }
    Py_DECREF(subvalue);
  }

  for (i = 0; i < size; ++i) {
    subvalue = PySequence_GetItem(value, i);
    if (subvalue == NULL) {
      return -1;
    }
    if (!PyArg_ParseTuple(subvalue, "iis", &ival, &mval, &strvalue)) {
      Py_DECREF(subvalue);
      return -1;
    }
    Py_DECREF(subvalue);

    (*ps)[i].i = ival;
    (*ps)[i].m = mval;
    strncpy((*ps)[i].value, strvalue, 72);
    (*ps)[i].value[71] = '\0';
    (*nps) = (int)(i + 1);
  }

  return 0;
}
Beispiel #24
0
int
set_str_list(
    const char* propname,
    PyObject* value,
    Py_ssize_t len,
    Py_ssize_t maxlen,
    char (*dest)[72]) {

  PyObject*  str      = NULL;
  Py_ssize_t input_len;
  Py_ssize_t i        = 0;

  if (check_delete(propname, value)) {
    return -1;
  }

  if (maxlen == 0) {
    maxlen = 68;
  }

  if (!PySequence_Check(value)) {
    PyErr_Format(
        PyExc_TypeError,
        "'%s' must be a sequence of strings",
        propname);
    return -1;
  }

  if (PySequence_Size(value) != len) {
    PyErr_Format(
        PyExc_ValueError,
        "len(%s) must be %u",
        propname,
        (unsigned int)len);
    return -1;
  }

  /* We go through the list twice, once to verify that the list is
     in the correct format, and then again to do the data copy.  This
     way, we won't partially copy the contents and then throw an
     exception. */
  for (i = 0; i < len; ++i) {
    str = PySequence_GetItem(value, i);
    if (str == NULL) {
      return -1;
    }

    if (!(PyBytes_CheckExact(str) || PyUnicode_CheckExact(str))) {
      PyErr_Format(
          PyExc_TypeError,
          "'%s' must be a sequence of bytes or strings",
          propname);
      Py_DECREF(str);
      return -1;
    }

    input_len = PySequence_Size(str);
    if (input_len > maxlen) {
      PyErr_Format(
          PyExc_ValueError,
          "Each entry in '%s' must be less than %u characters",
          propname, (unsigned int)maxlen);
      Py_DECREF(str);
      return -1;
    } else if (input_len == -1) {
      Py_DECREF(str);
      return -1;
    }

    Py_DECREF(str);
  }

  for (i = 0; i < len; ++i) {
    str = PySequence_GetItem(value, i);
    if (str == NULL) {
      /* Theoretically, something has gone really wrong here, since
         we've already verified the list. */
      PyErr_Clear();
      PyErr_Format(
          PyExc_RuntimeError,
          "Input values have changed underneath us.  Something is seriously wrong.");
      return -1;
    }

    if (set_string(propname, str, dest[i], maxlen)) {
      PyErr_Clear();
      PyErr_Format(
          PyExc_RuntimeError,
          "Input values have changed underneath us.  Something is seriously wrong.");
      Py_DECREF(str);
      return -1;
    }

    Py_DECREF(str);
  }

  return 0;
}
Beispiel #25
0
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;
}
Beispiel #26
0
static int DCVertexBufferInit(DCVertexBuffer *self, PyObject *args, PyObject *kwds)
{
	DKObject<DKVertexBuffer> vb = NULL;
	if (self->buffer == NULL)
	{
		PyObject* decls;
		Py_ssize_t size;
		int location;
		int usage;

		char* kwlist[] = { "decls", "size", "location", "usage", NULL };
		if (!PyArg_ParseTupleAndKeywords(args, kwds, "Onii", kwlist,
			&decls, &size, &location, &usage))
			return -1;

		if (!PySequence_Check(decls))
		{
			PyErr_SetString(PyExc_TypeError, "first argument must be sequence object.");
			return -1;
		}
		if (size <= 0)
		{
			PyErr_SetString(PyExc_ValueError, "second argument must be greater than zero.");
			return -1;
		}
		// DKGeometryBuffer::MemoryLocation
		if (location < DKGeometryBuffer::MemoryLocationStatic ||
			location > DKGeometryBuffer::MemoryLocationStream)
		{
			PyErr_SetString(PyExc_ValueError, "thrid argument is invalid. (wrong location)");
			return -1;
		}
		// DKGeometryBuffer::BufferUsage
		if (usage < DKGeometryBuffer::BufferUsageDraw ||
			usage > DKGeometryBuffer::BufferUsageCopy)
		{
			PyErr_SetString(PyExc_ValueError, "fourth argument is invalid. (wrong usage)");
			return -1;
		}
		DKArray<DKVertexBuffer::Decl> declArray;

		PyObject* decl_args = PyTuple_New(0);
		DCObjectRelease decl_args_(decl_args);
		char* decl_kwlist[] = { "id", "name", "type", "normalize", "offset", NULL };

		Py_ssize_t len = PySequence_Size(decls);
		for (int i = 0; i < len; ++i)
		{
			PyObject* dict = PySequence_GetItem(decls, i);
			if (dict == NULL)
			{
				PyErr_SetString(PyExc_TypeError, "first argument must be sequence object.");
				return -1;
			}
			DCObjectRelease dict_(dict);

			if (!PyDict_Check(dict))
			{
				PyErr_SetString(PyExc_TypeError, "decl element must be dictionary object.");
				return -1;
			}

			int stream;
			const char* name;
			int type;
			int normalize;
			Py_ssize_t offset;

			if (!PyArg_ParseTupleAndKeywords(decl_args, dict, "isipn", decl_kwlist,
				&stream, &name, &type, &normalize, &offset))
			{
				PyErr_Clear();
				PyErr_SetString(PyExc_TypeError, "invalid decl data.");
				return -1;
			}

			if (stream <= DKVertexStream::StreamUnknown || stream >= DKVertexStream::StreamMax)
			{
				PyErr_SetString(PyExc_ValueError, "decl['id'] is out of range");
				return -1;
			}
			if (type <= DKVertexStream::TypeUnknown || type >= DKVertexStream::TypeMax)
			{
				PyErr_SetString(PyExc_ValueError, "decl['type'] is out of range");
				return -1;
			}
			if (offset < 0)
			{
				PyErr_SetString(PyExc_ValueError, "decl['offset'] must be greater than zero.");
				return -1;
			}

			DKVertexBuffer::Decl decl;
			decl.id = (DKVertexStream::Stream)stream;
			decl.name = name;
			decl.type = (DKVertexStream::Type)type;
			decl.normalize = normalize != 0;
			decl.offset = offset;

			declArray.Add(decl);
		}

		if (declArray.Count() == 0)
		{
			PyErr_SetString(PyExc_ValueError, "invalid vertex declarations");
			return -1;
		}

		Py_BEGIN_ALLOW_THREADS
		vb = DKVertexBuffer::Create(declArray, declArray.Count(), NULL, size, 0,
			(DKGeometryBuffer::MemoryLocation)location,
			(DKGeometryBuffer::BufferUsage)usage);
		Py_END_ALLOW_THREADS

		if (vb == NULL)
		{
			PyErr_SetString(PyExc_RuntimeError, "failed to create vertex-buffer");
			return -1;
		}
		self->buffer = vb;
		DCObjectSetAddress(self->buffer, (PyObject*)self);
	}
Beispiel #27
0
/**
 * \note group can be a pointer array or a group.
 * assume we already checked key is a string.
 *
 * \return success.
 */
bool BPy_IDProperty_Map_ValidateAndCreate(PyObject *name_obj, IDProperty *group, PyObject *ob)
{
    IDProperty *prop = NULL;
    IDPropertyTemplate val = {0};

    const char *name;

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

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

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

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

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

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

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

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

        val.array.len = PySequence_Fast_GET_SIZE(ob_seq_fast);

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

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

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

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

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

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

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

            Py_DECREF (tuple);
          }
          else
          {
            PyErr_SetString (PyExc_TypeError, "All sub-sequences must have the same number of entries");
            cvReleaseMat (& matrix);
            Py_DECREF (colobj);
            Py_DECREF (rowobj);
            return NULL;
          }
        }
        else
        {
          if (PyFloat_Check (colobj) || PyInt_Check (colobj))
          {
            cvmSet (matrix, y, x, PyFloat_AsDouble (colobj));
          }
          else
          {
            PyErr_SetString (PyExc_TypeError, "OpenCV only accepts numbers that can be converted to float");
            cvReleaseMat (& matrix);
            Py_DECREF (colobj);
            Py_DECREF (rowobj);
            return NULL;
          }
        }
        
        Py_DECREF (colobj);
      }
    }
    else
    {
      PyErr_SetString (PyExc_TypeError, "All sub-sequences must have the same number of entries");
      cvReleaseMat (& matrix);
      Py_DECREF (rowobj);
      return NULL;
    }
    
    Py_DECREF (rowobj);
  }
  
  return matrix;
}
/* inspect a message, update the seen set
 * return 1 if we should pass this message on to the caller
 * return 0 if we should drop it
 * return -1 on internal error (exception has been raised)
 */
static int filter_message(modesreader *self, PyObject *o)
{
    modesmessage *message = (modesmessage *)o;

    if (message->df == DF_MODEAC) {
        return self->want_modeac_messages;  /* no address in mode a/c, no further filtering possible */
    }

    if (!message->valid) {
        return self->want_invalid_messages; /* don't process further, contents are dubious */
    }

    if (self->seen != NULL && self->seen != Py_None) {
        if (message->df == 11 || message->df == 17 || message->df == 18) {
            /* note that we saw this aircraft, even if the message is filtered.
             * only do this for CRC-checked messages as we get a lot of noise
             * otherwise.
             */
            if (PySet_Add(self->seen, message->address) < 0) {
                return -1;
            }
        }
    }

    if (message->timestamp == 0 && !self->want_zero_timestamps) {
        return 0;
    }

    if (message->timestamp == MAGIC_MLAT_TIMESTAMP && !self->want_mlat_messages) {
        return 0;
    }

    if ((self->default_filter == NULL || self->default_filter == Py_None) &&
        (self->specific_filter == NULL || self->specific_filter == Py_None)) {
        /* no filters installed, match everything */
        return 1;
    }

    /* check per-type filters */
    if (self->default_filter != NULL && self->default_filter != Py_None) {
        int rv;
        PyObject *entry = PySequence_GetItem(self->default_filter, message->df);
        if (entry == NULL)
            return -1;

        rv = PyObject_IsTrue(entry);
        Py_DECREF(entry);
        if (rv != 0)
            return rv;
    }

    if (self->specific_filter != NULL && self->specific_filter != Py_None) {
        int rv;
        PyObject *entry = PySequence_GetItem(self->specific_filter, message->df);
        if (entry == NULL)
            return -1;

        if (entry == Py_None) {
            rv = 0;
        } else {
            rv = PySequence_Contains(entry, message->address);
        }

        Py_DECREF(entry);
        if (rv != 0)
            return rv;
    }

    return 0;
}
static PyObject*
test_neighborhood_iterator_oob(PyObject* NPY_UNUSED(self), PyObject* args)
{
    PyObject *x, *out, *b1, *b2;
    PyArrayObject *ax;
    PyArrayIterObject *itx;
    int i, typenum, mode1, mode2, st;
    npy_intp bounds[NPY_MAXDIMS*2];
    PyArrayNeighborhoodIterObject *niterx1, *niterx2;

    if (!PyArg_ParseTuple(args, "OOiOi", &x, &b1, &mode1, &b2, &mode2)) {
        return NULL;
    }

    if (!PySequence_Check(b1) || !PySequence_Check(b2)) {
        return NULL;
    }

    typenum = PyArray_ObjectType(x, 0);

    ax = (PyArrayObject*)PyArray_FromObject(x, typenum, 1, 10);
    if (ax == NULL) {
        return NULL;
    }
    if (PySequence_Size(b1) != 2 * PyArray_NDIM(ax)) {
        PyErr_SetString(PyExc_ValueError,
                "bounds sequence 1 size not compatible with x input");
        goto clean_ax;
    }
    if (PySequence_Size(b2) != 2 * PyArray_NDIM(ax)) {
        PyErr_SetString(PyExc_ValueError,
                "bounds sequence 2 size not compatible with x input");
        goto clean_ax;
    }

    out = PyList_New(0);
    if (out == NULL) {
        goto clean_ax;
    }

    itx = (PyArrayIterObject*)PyArray_IterNew(x);
    if (itx == NULL) {
        goto clean_out;
    }

    /* Compute boundaries for the neighborhood iterator */
    for (i = 0; i < 2 * PyArray_NDIM(ax); ++i) {
        PyObject* bound;
        bound = PySequence_GetItem(b1, i);
        if (bounds == NULL) {
            goto clean_itx;
        }
        if (!PyInt_Check(bound)) {
            PyErr_SetString(PyExc_ValueError,
                    "bound not long");
            Py_DECREF(bound);
            goto clean_itx;
        }
        bounds[i] = PyInt_AsLong(bound);
        Py_DECREF(bound);
    }

    /* Create the neighborhood iterator */
    niterx1 = (PyArrayNeighborhoodIterObject*)PyArray_NeighborhoodIterNew(
                    (PyArrayIterObject*)itx, bounds,
                    mode1, NULL);
    if (niterx1 == NULL) {
        goto clean_out;
    }

    for (i = 0; i < 2 * PyArray_NDIM(ax); ++i) {
        PyObject* bound;
        bound = PySequence_GetItem(b2, i);
        if (bounds == NULL) {
            goto clean_itx;
        }
        if (!PyInt_Check(bound)) {
            PyErr_SetString(PyExc_ValueError,
                    "bound not long");
            Py_DECREF(bound);
            goto clean_itx;
        }
        bounds[i] = PyInt_AsLong(bound);
        Py_DECREF(bound);
    }

    niterx2 = (PyArrayNeighborhoodIterObject*)PyArray_NeighborhoodIterNew(
                    (PyArrayIterObject*)niterx1, bounds,
                    mode2, NULL);
    if (niterx1 == NULL) {
        goto clean_niterx1;
    }

    switch (typenum) {
        case NPY_DOUBLE:
            st = copy_double_double(niterx1, niterx2, bounds, &out);
            break;
        default:
            PyErr_SetString(PyExc_ValueError,
                    "Type not supported");
            goto clean_niterx2;
    }

    if (st) {
        goto clean_niterx2;
    }

    Py_DECREF(niterx2);
    Py_DECREF(niterx1);
    Py_DECREF(itx);
    Py_DECREF(ax);
    return out;

clean_niterx2:
    Py_DECREF(niterx2);
clean_niterx1:
    Py_DECREF(niterx1);
clean_itx:
    Py_DECREF(itx);
clean_out:
    Py_DECREF(out);
clean_ax:
    Py_DECREF(ax);
    return NULL;
}