Example #1
0
static PyObject*
test_neighborhood_iterator(PyObject* NPY_UNUSED(self), PyObject* args)
{
    PyObject *x, *fill, *out, *b;
    PyArrayObject *ax, *afill;
    PyArrayIterObject *itx;
    int i, typenum, mode, st;
    npy_intp bounds[NPY_MAXDIMS*2];
    PyArrayNeighborhoodIterObject *niterx;

    if (!PyArg_ParseTuple(args, "OOOi", &x, &b, &fill, &mode)) {
        return NULL;
    }

    if (!PySequence_Check(b)) {
        return NULL;
    }

    typenum = PyArray_ObjectType(x, 0);
    typenum = PyArray_ObjectType(fill, typenum);

    ax = (PyArrayObject*)PyArray_FromObject(x, typenum, 1, 10);
    if (ax == NULL) {
        return NULL;
    }
    if (PySequence_Size(b) != 2 * PyArray_NDIM(ax)) {
        PyErr_SetString(PyExc_ValueError,
                "bounds sequence 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(b, 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 */
    afill = NULL;
    if (mode == NPY_NEIGHBORHOOD_ITER_CONSTANT_PADDING) {
            afill = (PyArrayObject *)PyArray_FromObject(fill, typenum, 0, 0);
            if (afill == NULL) {
            goto clean_itx;
        }
    }

    niterx = (PyArrayNeighborhoodIterObject*)PyArray_NeighborhoodIterNew(
                    (PyArrayIterObject*)itx, bounds, mode, afill);
    if (niterx == NULL) {
        goto clean_afill;
    }

    switch (typenum) {
        case NPY_OBJECT:
            st = copy_object(itx, niterx, bounds, &out);
            break;
        case NPY_INT:
            st = copy_int(itx, niterx, bounds, &out);
            break;
        case NPY_DOUBLE:
            st = copy_double(itx, niterx, bounds, &out);
            break;
        default:
            PyErr_SetString(PyExc_ValueError,
                    "Type not supported");
            goto clean_niterx;
    }

    if (st) {
        goto clean_niterx;
    }

    Py_DECREF(niterx);
    Py_XDECREF(afill);
    Py_DECREF(itx);

    Py_DECREF(ax);

    return out;

clean_niterx:
    Py_DECREF(niterx);
clean_afill:
    Py_XDECREF(afill);
clean_itx:
    Py_DECREF(itx);
clean_out:
    Py_DECREF(out);
clean_ax:
    Py_DECREF(ax);
    return NULL;
}
Example #2
0
/* MGLContext.framebuffer(...)
 */
PyObject * MGLContext_meth_framebuffer(MGLContext * self, PyObject * const * args, Py_ssize_t nargs) {
    if (nargs != 2) {
        PyErr_Format(moderngl_error, "num args");
        return 0;
    }

    PyObject * color_attachments = args[0];
    PyObject * depth_attachment = args[1];

    if (!PySequence_Check(color_attachments)) {
        PyObject * tuple = PyTuple_New(1);
        PyTuple_SET_ITEM(tuple, 0, color_attachments);
        color_attachments = tuple;
    } else {
        color_attachments = PySequence_Fast(color_attachments, "not iterable");
    }

    MGLFramebuffer * framebuffer = MGLContext_new_object(self, Framebuffer);

    const GLMethods & gl = self->gl;
    gl.GenFramebuffers(1, (GLuint *)&framebuffer->framebuffer_obj);

    if (!framebuffer->framebuffer_obj) {
        return 0;
    }

    self->bind_framebuffer(framebuffer->framebuffer_obj);

    int color_attachments_len = (int)PySequence_Fast_GET_SIZE(color_attachments);

    int width, height, samples;

    for (int i = 0; i < color_attachments_len; ++i) {
        PyObject * attachment = PySequence_Fast_GET_ITEM(color_attachments, i);
        if (attachment->ob_type == Renderbuffer_class) {
            MGLRenderbuffer * renderbuffer = SLOT(attachment, MGLRenderbuffer, Renderbuffer_class_mglo);
            framebuffer->attachment_type[i] = renderbuffer->data_type->shape;
            width = renderbuffer->width;
            height = renderbuffer->height;
            samples = renderbuffer->samples;
            gl.FramebufferRenderbuffer(
                GL_FRAMEBUFFER,
                GL_COLOR_ATTACHMENT0 + i,
                GL_RENDERBUFFER,
                renderbuffer->renderbuffer_obj
            );
        } else if (attachment->ob_type == Texture_class) {
            int level = PyLong_AsLong(SLOT(attachment, PyObject, Texture_class_level));
            MGLTexture * texture = SLOT(attachment, MGLTexture, Texture_class_mglo);
            framebuffer->attachment_type[i] = texture->data_type->shape;
            width = texture->width;
            height = texture->height;
            samples = texture->samples;
            if (texture->texture_target == GL_TEXTURE_CUBE_MAP) {
                gl.FramebufferTexture(
                    GL_FRAMEBUFFER,
                    GL_COLOR_ATTACHMENT0 + i,
                    texture->texture_obj,
                    level
                );
            } else {
                gl.FramebufferTexture2D(
                    GL_FRAMEBUFFER,
                    GL_COLOR_ATTACHMENT0 + i,
                    texture->texture_target,
                    texture->texture_obj,
                    level
                );
            }
        } else {
            return 0;
        }
    }

    // TODO:
    framebuffer->width = width;
    framebuffer->height = height;
    framebuffer->samples = samples;

    Py_DECREF(color_attachments);

    if (depth_attachment != Py_None) {
        if (depth_attachment->ob_type == Renderbuffer_class) {
            MGLRenderbuffer * renderbuffer = SLOT(depth_attachment, MGLRenderbuffer, Renderbuffer_class_mglo);
            gl.FramebufferRenderbuffer(
                GL_FRAMEBUFFER,
                GL_DEPTH_ATTACHMENT,
                GL_RENDERBUFFER,
                renderbuffer->renderbuffer_obj
            );
        } else if (depth_attachment->ob_type == Texture_class) {
            int level = PyLong_AsLong(SLOT(depth_attachment, PyObject, Texture_class_level));
            MGLTexture * texture = SLOT(depth_attachment, MGLTexture, Texture_class_mglo);
            if (texture->texture_target == GL_TEXTURE_CUBE_MAP) {
                gl.FramebufferTexture(
                    GL_FRAMEBUFFER,
                    GL_DEPTH_ATTACHMENT,
                    texture->texture_obj,
                    level
                );
            } else {
                gl.FramebufferTexture2D(
                    GL_FRAMEBUFFER,
                    GL_DEPTH_ATTACHMENT,
                    texture->texture_target,
                    texture->texture_obj,
                    level
                );
            }
        } else {
            return 0;
        }
    }

    int status = gl.CheckFramebufferStatus(GL_FRAMEBUFFER);
    self->bind_framebuffer(self->bound_framebuffer->framebuffer_obj);

    if (status != GL_FRAMEBUFFER_COMPLETE) {
        const char * message = "the framebuffer is not complete";

        // switch (status) {
        // 	case GL_FRAMEBUFFER_UNDEFINED:
        // 		message = "the framebuffer is not complete (UNDEFINED)";
        // 		break;

        // 	case GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT:
        // 		message = "the framebuffer is not complete (INCOMPLETE_ATTACHMENT)";
        // 		break;

        // 	case GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:
        // 		message = "the framebuffer is not complete (INCOMPLETE_MISSING_ATTACHMENT)";
        // 		break;

        // 	case GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER:
        // 		message = "the framebuffer is not complete (INCOMPLETE_DRAW_BUFFER)";
        // 		break;

        // 	case GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER:
        // 		message = "the framebuffer is not complete (INCOMPLETE_READ_BUFFER)";
        // 		break;

        // 	case GL_FRAMEBUFFER_UNSUPPORTED:
        // 		message = "the framebuffer is not complete (UNSUPPORTED)";
        // 		break;

        // 	case GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE:
        // 		message = "the framebuffer is not complete (INCOMPLETE_MULTISAMPLE)";
        // 		break;

        // 	case GL_FRAMEBUFFER_INCOMPLETE_LAYER_TARGETS:
        // 		message = "the framebuffer is not complete (INCOMPLETE_LAYER_TARGETS)";
        // 		break;
        // }

        return 0;
    }

    framebuffer->viewport[0] = 0;
    framebuffer->viewport[1] = 0;
    framebuffer->viewport[2] = framebuffer->width;
    framebuffer->viewport[3] = framebuffer->height;
    framebuffer->attachments = color_attachments_len;
    SLOT(framebuffer->wrapper, PyObject, Framebuffer_class_viewport) = int_tuple(0, 0, framebuffer->width, framebuffer->height);
    return NEW_REF(framebuffer->wrapper);
}
Example #3
0
/* note, this is called as a python getset */
int PyObjectPlus::py_set_attrdef(PyObject *self_py, PyObject *value, const PyAttributeDef *attrdef)
{
	PyObjectPlus *ref= (BGE_PROXY_REF(self_py));
	char* ptr = (attrdef->m_usePtr) ? (char*)BGE_PROXY_PTR(self_py) : (char*)ref;
	if (ref==NULL || !ref->py_is_valid() || ptr==NULL) {
		PyErr_SetString(PyExc_SystemError, BGE_PROXY_ERROR_MSG);
		return PY_SET_ATTR_FAIL;
	}

	void *undoBuffer = NULL;
	void *sourceBuffer = NULL;
	size_t bufferSize = 0;
	PyObject *item = NULL;	// to store object that must be dereferenced in case of error
	PyObject *list = NULL;	// to store object that must be dereferenced in case of error
	
	ptr += attrdef->m_offset;
	if (attrdef->m_length > 1)
	{
		if (!PySequence_Check(value)) 
		{
			PyErr_Format(PyExc_TypeError, "expected a sequence for attribute \"%s\"", attrdef->m_name);
			return PY_SET_ATTR_FAIL;
		}
		if (PySequence_Size(value) != attrdef->m_length)
		{
			PyErr_Format(PyExc_TypeError, "incorrect number of elements in sequence for attribute \"%s\"", attrdef->m_name);
			return PY_SET_ATTR_FAIL;
		}
		switch (attrdef->m_type) 
		{
		case KX_PYATTRIBUTE_TYPE_FUNCTION:
			if (attrdef->m_setFunction == NULL) 
			{
				PyErr_Format(PyExc_AttributeError, "function attribute without function for attribute \"%s\", report to blender.org", attrdef->m_name);
				return PY_SET_ATTR_FAIL;
			}
			return (*attrdef->m_setFunction)(ref, attrdef, value);
		case KX_PYATTRIBUTE_TYPE_BOOL:
			bufferSize = sizeof(bool);
			break;
		case KX_PYATTRIBUTE_TYPE_SHORT:
			bufferSize = sizeof(short int);
			break;
		case KX_PYATTRIBUTE_TYPE_ENUM:
		case KX_PYATTRIBUTE_TYPE_INT:
			bufferSize = sizeof(int);
			break;
		case KX_PYATTRIBUTE_TYPE_FLOAT:
			bufferSize = sizeof(float);
			break;
		default:
			// should not happen
			PyErr_Format(PyExc_AttributeError, "Unsupported attribute type for attribute \"%s\", report to blender.org", attrdef->m_name);
			return PY_SET_ATTR_FAIL;
		}
		// let's implement a smart undo method
		bufferSize *= attrdef->m_length;
		undoBuffer = malloc(bufferSize);
		sourceBuffer = ptr;
		if (undoBuffer)
		{
			memcpy(undoBuffer, sourceBuffer, bufferSize);
		}
		for (int i=0; i<attrdef->m_length; i++)
		{
			item = PySequence_GetItem(value, i); /* new ref */
			switch (attrdef->m_type) 
			{
			case KX_PYATTRIBUTE_TYPE_BOOL:
				{
					bool *var = reinterpret_cast<bool*>(ptr);
					ptr += sizeof(bool);
					if (PyLong_Check(item)) 
					{
						*var = (PyLong_AsLong(item) != 0);
					} 
					else if (PyBool_Check(item))
					{
						*var = (item == Py_True);
					}
					else
					{
						PyErr_Format(PyExc_TypeError, "expected an integer or a bool for attribute \"%s\"", attrdef->m_name);
						goto UNDO_AND_ERROR;
					}
					break;
				}
			case KX_PYATTRIBUTE_TYPE_SHORT:
				{
					short int *var = reinterpret_cast<short int*>(ptr);
					ptr += sizeof(short int);
					if (PyLong_Check(item)) 
					{
						int val = PyLong_AsLong(item);
						if (attrdef->m_clamp)
						{
							if (val < attrdef->m_imin)
								val = attrdef->m_imin;
							else if (val > attrdef->m_imax)
								val = attrdef->m_imax;
						}
						else if (val < attrdef->m_imin || val > attrdef->m_imax)
						{
							PyErr_Format(PyExc_ValueError, "item value out of range for attribute \"%s\"", attrdef->m_name);
							goto UNDO_AND_ERROR;
						}
						*var = (short int)val;
					}
					else
					{
						PyErr_Format(PyExc_TypeError, "expected an integer for attribute \"%s\"", attrdef->m_name);
						goto UNDO_AND_ERROR;
					}
					break;
				}
			case KX_PYATTRIBUTE_TYPE_ENUM:
				// enum are equivalent to int, just make sure that the field size matches:
				if (sizeof(int) != attrdef->m_size)
				{
					PyErr_Format(PyExc_AttributeError, "Size check error for attribute, \"%s\", report to blender.org", attrdef->m_name);
					goto UNDO_AND_ERROR;
				}
				// walkthrough
			case KX_PYATTRIBUTE_TYPE_INT:
				{
					int *var = reinterpret_cast<int*>(ptr);
					ptr += sizeof(int);
					if (PyLong_Check(item)) 
					{
						int val = PyLong_AsLong(item);
						if (attrdef->m_clamp)
						{
							if (val < attrdef->m_imin)
								val = attrdef->m_imin;
							else if (val > attrdef->m_imax)
								val = attrdef->m_imax;
						}
						else if (val < attrdef->m_imin || val > attrdef->m_imax)
						{
							PyErr_Format(PyExc_ValueError, "item value out of range for attribute \"%s\"", attrdef->m_name);
							goto UNDO_AND_ERROR;
						}
						*var = (int)val;
					}
					else
					{
						PyErr_Format(PyExc_TypeError, "expected an integer for attribute \"%s\"", attrdef->m_name);
						goto UNDO_AND_ERROR;
					}
					break;
				}
			case KX_PYATTRIBUTE_TYPE_FLOAT:
				{
					float *var = reinterpret_cast<float*>(ptr);
					ptr += sizeof(float);
					float val = PyFloat_AsDouble(item);
					if (val == -1.0f && PyErr_Occurred())
					{
						PyErr_Format(PyExc_TypeError, "expected a float for attribute \"%s\"", attrdef->m_name);
						goto UNDO_AND_ERROR;
					}
					else if (attrdef->m_clamp)
					{
						if (val < attrdef->m_fmin)
							val = attrdef->m_fmin;
						else if (val > attrdef->m_fmax)
							val = attrdef->m_fmax;
					}
					else if (val < attrdef->m_fmin || val > attrdef->m_fmax)
					{
						PyErr_Format(PyExc_ValueError, "item value out of range for attribute \"%s\"", attrdef->m_name);
						goto UNDO_AND_ERROR;
					}
					*var = (float)val;
					break;
				}
			default:
				// should not happen
				PyErr_Format(PyExc_AttributeError, "type check error for attribute \"%s\", report to blender.org", attrdef->m_name);
				goto UNDO_AND_ERROR;
			}
			// finished using item, release
			Py_DECREF(item);
			item = NULL;
		}
		// no error, call check function if any
		if (attrdef->m_checkFunction != NULL)
		{
			if ((*attrdef->m_checkFunction)(ref, attrdef) != 0)
			{
				// if the checing function didnt set an error then set a generic one here so we don't set an error with no exception
				if (PyErr_Occurred()==0)
					PyErr_Format(PyExc_AttributeError, "type check error for attribute \"%s\", reasion unknown", attrdef->m_name);
				
				// post check returned an error, restore values
			UNDO_AND_ERROR:
				if (undoBuffer)
				{
					memcpy(sourceBuffer, undoBuffer, bufferSize);
					free(undoBuffer);
				}
				if (item)
					Py_DECREF(item);
				return PY_SET_ATTR_FAIL;
			}
		}
		if (undoBuffer)
			free(undoBuffer);
		return PY_SET_ATTR_SUCCESS;
	}
	else	// simple attribute value
	{
		if (attrdef->m_type == KX_PYATTRIBUTE_TYPE_FUNCTION)
		{
			if (attrdef->m_setFunction == NULL)
			{
				PyErr_Format(PyExc_AttributeError, "function attribute without function \"%s\", report to blender.org", attrdef->m_name);
				return PY_SET_ATTR_FAIL;
			}
			return (*attrdef->m_setFunction)(ref, attrdef, value);
		}
		if (attrdef->m_checkFunction != NULL || attrdef->m_type == KX_PYATTRIBUTE_TYPE_VECTOR)
		{
			// post check function is provided, prepare undo buffer
			sourceBuffer = ptr;
			switch (attrdef->m_type) 
			{
			case KX_PYATTRIBUTE_TYPE_BOOL:
				bufferSize = sizeof(bool);
				break;
			case KX_PYATTRIBUTE_TYPE_SHORT:
				bufferSize = sizeof(short);
				break;
			case KX_PYATTRIBUTE_TYPE_ENUM:
			case KX_PYATTRIBUTE_TYPE_FLAG:
			case KX_PYATTRIBUTE_TYPE_CHAR:
				bufferSize = attrdef->m_size;
				break;
			case KX_PYATTRIBUTE_TYPE_INT:
				bufferSize = sizeof(int);
				break;
			case KX_PYATTRIBUTE_TYPE_FLOAT:
				bufferSize = sizeof(float);
				if (attrdef->m_imax)
					bufferSize *= attrdef->m_imax;
				if (attrdef->m_imin)
					bufferSize *= attrdef->m_imin;
				break;
			case KX_PYATTRIBUTE_TYPE_STRING:
				sourceBuffer = reinterpret_cast<STR_String*>(ptr)->Ptr();
				if (sourceBuffer)
					bufferSize = strlen(reinterpret_cast<char*>(sourceBuffer))+1;
				break;
			case KX_PYATTRIBUTE_TYPE_VECTOR:
				bufferSize = sizeof(MT_Vector3);
				break;
			default:
				PyErr_Format(PyExc_AttributeError, "unknown type for attribute \"%s\", report to blender.org", attrdef->m_name);
				return PY_SET_ATTR_FAIL;
			}
			if (bufferSize)
			{
				undoBuffer = malloc(bufferSize);
				if (undoBuffer)
				{
					memcpy(undoBuffer, sourceBuffer, bufferSize);
				}
			}
		}
			
		switch (attrdef->m_type) 
		{
		case KX_PYATTRIBUTE_TYPE_BOOL:
			{
				bool *var = reinterpret_cast<bool*>(ptr);
				if (PyLong_Check(value)) 
				{
					*var = (PyLong_AsLong(value) != 0);
				} 
				else if (PyBool_Check(value))
				{
					*var = (value == Py_True);
				}
				else
				{
					PyErr_Format(PyExc_TypeError, "expected an integer or a bool for attribute \"%s\"", attrdef->m_name);
					goto FREE_AND_ERROR;
				}
				break;
			}
		case KX_PYATTRIBUTE_TYPE_FLAG:
			{
				bool bval;
				if (PyLong_Check(value)) 
				{
					bval = (PyLong_AsLong(value) != 0);
				} 
				else if (PyBool_Check(value))
				{
					bval = (value == Py_True);
				}
				else
				{
					PyErr_Format(PyExc_TypeError, "expected an integer or a bool for attribute \"%s\"", attrdef->m_name);
					goto FREE_AND_ERROR;
				}
				if (attrdef->m_imax)
					bval = !bval;
				switch (attrdef->m_size) {
				case 1:
					{
						unsigned char *val = reinterpret_cast<unsigned char*>(ptr);
						*val = (*val & ~attrdef->m_imin) | ((bval)?attrdef->m_imin:0);
						break;
					}
				case 2:
					{
						unsigned short *val = reinterpret_cast<unsigned short*>(ptr);
						*val = (*val & ~attrdef->m_imin) | ((bval)?attrdef->m_imin:0);
						break;
					}
				case 4:
					{
						unsigned int *val = reinterpret_cast<unsigned int*>(ptr);
						*val = (*val & ~attrdef->m_imin) | ((bval)?attrdef->m_imin:0);
						break;
					}
				default:
					PyErr_Format(PyExc_TypeError, "internal error: unsupported flag field \"%s\"", attrdef->m_name);
					goto FREE_AND_ERROR;
				}
				break;
			}
		case KX_PYATTRIBUTE_TYPE_SHORT:
			{
				short int *var = reinterpret_cast<short int*>(ptr);
				if (PyLong_Check(value)) 
				{
					int val = PyLong_AsLong(value);
					if (attrdef->m_clamp)
					{
						if (val < attrdef->m_imin)
							val = attrdef->m_imin;
						else if (val > attrdef->m_imax)
							val = attrdef->m_imax;
					}
					else if (val < attrdef->m_imin || val > attrdef->m_imax)
					{
						PyErr_Format(PyExc_ValueError, "value out of range for attribute \"%s\"", attrdef->m_name);
						goto FREE_AND_ERROR;
					}
					*var = (short int)val;
				}
				else
				{
					PyErr_Format(PyExc_TypeError, "expected an integer for attribute \"%s\"", attrdef->m_name);
					goto FREE_AND_ERROR;
				}
				break;
			}
		case KX_PYATTRIBUTE_TYPE_ENUM:
			// enum are equivalent to int, just make sure that the field size matches:
			if (sizeof(int) != attrdef->m_size)
			{
				PyErr_Format(PyExc_AttributeError, "attribute size check error for attribute \"%s\", report to blender.org", attrdef->m_name);
				goto FREE_AND_ERROR;
			}
			// walkthrough
		case KX_PYATTRIBUTE_TYPE_INT:
			{
				int *var = reinterpret_cast<int*>(ptr);
				if (PyLong_Check(value)) 
				{
					int val = PyLong_AsLong(value);
					if (attrdef->m_clamp)
					{
						if (val < attrdef->m_imin)
							val = attrdef->m_imin;
						else if (val > attrdef->m_imax)
							val = attrdef->m_imax;
					}
					else if (val < attrdef->m_imin || val > attrdef->m_imax)
					{
						PyErr_Format(PyExc_ValueError, "value out of range for attribute \"%s\"", attrdef->m_name);
						goto FREE_AND_ERROR;
					}
					*var = (int)val;
				}
				else
				{
					PyErr_Format(PyExc_TypeError, "expected an integer for attribute \"%s\"", attrdef->m_name);
					goto FREE_AND_ERROR;
				}
				break;
			}
		case KX_PYATTRIBUTE_TYPE_FLOAT:
			{
				float *var = reinterpret_cast<float*>(ptr);
				if (attrdef->m_imin != 0) 
				{
					if (attrdef->m_size != attrdef->m_imin*attrdef->m_imax*sizeof(float)) 
					{
						PyErr_Format(PyExc_TypeError, "internal error: incorrect field size for attribute \"%s\"", attrdef->m_name);
						goto FREE_AND_ERROR;
					}
					if (!PySequence_Check(value) || PySequence_Size(value) != attrdef->m_imin) 
					{
						PyErr_Format(PyExc_TypeError, "expected a sequence of [%d][%d] floats for attribute \"%s\"", attrdef->m_imin, attrdef->m_imax, attrdef->m_name);
						goto FREE_AND_ERROR;
					}
					for (int i=0; i<attrdef->m_imin; i++)
					{
						PyObject *list = PySequence_GetItem(value, i); /* new ref */
						if (!PySequence_Check(list) || PySequence_Size(list) != attrdef->m_imax) 
						{
							PyErr_Format(PyExc_TypeError, "expected a sequence of [%d][%d] floats for attribute \"%s\"", attrdef->m_imin, attrdef->m_imax, attrdef->m_name);
							goto RESTORE_AND_ERROR;
						}
						for (int j=0; j<attrdef->m_imax; j++)
						{
							item = PySequence_GetItem(list, j); /* new ref */
							if (!py_check_attr_float(var, item, attrdef))
							{
								PyErr_Format(PyExc_TypeError, "expected a sequence of [%d][%d] floats for attribute \"%s\"", attrdef->m_imin, attrdef->m_imax, attrdef->m_name);
								goto RESTORE_AND_ERROR;
							}
							Py_DECREF(item);
							item = NULL;
							++var;
						}
						Py_DECREF(list);
						list = NULL;
					}
				} 
				else if (attrdef->m_imax != 0) 
				{
					if (attrdef->m_size != attrdef->m_imax*sizeof(float)) 
					{
						PyErr_Format(PyExc_TypeError, "internal error: incorrect field size for attribute \"%s\"", attrdef->m_name);
						goto FREE_AND_ERROR;
					}
					if (!PySequence_Check(value) || PySequence_Size(value) != attrdef->m_imax) 
					{
						PyErr_Format(PyExc_TypeError, "expected a sequence of [%d] floats for attribute \"%s\"", attrdef->m_imax, attrdef->m_name);
						goto FREE_AND_ERROR;
					}
					for (int i=0; i<attrdef->m_imax; i++)
					{
						item = PySequence_GetItem(value, i); /* new ref */
						if (!py_check_attr_float(var, item, attrdef))
						{
							goto RESTORE_AND_ERROR;
						}
						Py_DECREF(item);
						item = NULL;
						++var;
					}
				} 
				else
				{
					if (!py_check_attr_float(var, value, attrdef))
						goto FREE_AND_ERROR;
				}
				break;
			}
		case KX_PYATTRIBUTE_TYPE_VECTOR:
			{
				if (!PySequence_Check(value) || PySequence_Size(value) != 3) 
				{
					PyErr_Format(PyExc_TypeError, "expected a sequence of 3 floats for attribute \"%s\"", attrdef->m_name);
					goto FREE_AND_ERROR;
				}
				MT_Vector3 *var = reinterpret_cast<MT_Vector3*>(ptr);
				for (int i=0; i<3; i++)
				{
					item = PySequence_GetItem(value, i); /* new ref */
					float val = PyFloat_AsDouble(item);
					Py_DECREF(item);
					item = NULL;
					if (val == -1.0f && PyErr_Occurred())
					{
						PyErr_Format(PyExc_TypeError, "expected a sequence of 3 floats for attribute \"%s\"", attrdef->m_name);
						goto RESTORE_AND_ERROR;
					}
					else if (attrdef->m_clamp)
					{
						if (val < attrdef->m_fmin)
							val = attrdef->m_fmin;
						else if (val > attrdef->m_fmax)
							val = attrdef->m_fmax;
					}
					else if (val < attrdef->m_fmin || val > attrdef->m_fmax)
					{
						PyErr_Format(PyExc_ValueError, "value out of range for attribute \"%s\"", attrdef->m_name);
						goto RESTORE_AND_ERROR;
					}
					(*var)[i] = (MT_Scalar)val;
				}
				break;
			}
		case KX_PYATTRIBUTE_TYPE_CHAR:
			{
				if (PyUnicode_Check(value)) 
				{
					Py_ssize_t val_size;
					const char *val = _PyUnicode_AsStringAndSize(value, &val_size);
					strncpy(ptr, val, attrdef->m_size);
					ptr[attrdef->m_size-1] = 0;
				}
				else
				{
					PyErr_Format(PyExc_TypeError, "expected a string for attribute \"%s\"", attrdef->m_name);
					goto FREE_AND_ERROR;
				}
				break;
			}
		case KX_PYATTRIBUTE_TYPE_STRING:
			{
				STR_String *var = reinterpret_cast<STR_String*>(ptr);
				if (PyUnicode_Check(value)) 
				{
					Py_ssize_t val_len;
					const char *val = _PyUnicode_AsStringAndSize(value, &val_len); /* XXX, should be 'const' but we do a silly trick to have a shorter string */
					if (attrdef->m_clamp)
					{
						if (val_len < attrdef->m_imin)
						{
							// can't increase the length of the string
							PyErr_Format(PyExc_ValueError, "string length too short for attribute \"%s\"", attrdef->m_name);
							goto FREE_AND_ERROR;
						}
						else if (val_len > attrdef->m_imax)
						{
							// trim the string
							var->SetLength(attrdef->m_imax);
							memcpy(var->Ptr(), val, attrdef->m_imax - 1);
							break;
						}
					} else if (val_len < attrdef->m_imin || val_len > attrdef->m_imax)
					{
						PyErr_Format(PyExc_ValueError, "string length out of range for attribute \"%s\"", attrdef->m_name);
						goto FREE_AND_ERROR;
					}
					*var = val;
				}
				else
				{
					PyErr_Format(PyExc_TypeError, "expected a string for attribute \"%s\"", attrdef->m_name);
					goto FREE_AND_ERROR;
				}
				break;
			}
		default:
			// should not happen
			PyErr_Format(PyExc_AttributeError, "unknown type for attribute \"%s\", report to blender.org", attrdef->m_name);
			goto FREE_AND_ERROR;
		}
	}
	// check if post processing is needed
	if (attrdef->m_checkFunction != NULL)
	{
		if ((*attrdef->m_checkFunction)(ref, attrdef) != 0)
		{
			// restore value
		RESTORE_AND_ERROR:
			if (undoBuffer)
			{
				if (attrdef->m_type == KX_PYATTRIBUTE_TYPE_STRING)
				{
					// special case for STR_String: restore the string
					STR_String *var = reinterpret_cast<STR_String*>(ptr);
					*var = reinterpret_cast<char*>(undoBuffer);
				}
				else
				{
					// other field type have direct values
					memcpy(ptr, undoBuffer, bufferSize);
				}
			}
		FREE_AND_ERROR:
			if (undoBuffer)
				free(undoBuffer);
			if (list)
				Py_DECREF(list);
			if (item)
				Py_DECREF(item);
			return 1;
		}
	}
	if (undoBuffer)
		free(undoBuffer);
	return 0;
}
Example #4
0
/** \ingroup python_interface_edgeseq
 * \brief Sets the list of values for a given attribute
 */
int igraphmodule_EdgeSeq_set_attribute_values_mapping(igraphmodule_EdgeSeqObject* self, PyObject* attrname, PyObject* values) {
  PyObject *dict, *list, *item;
  igraphmodule_GraphObject *gr;
  igraph_vector_t es;
  long i, j, n, no_of_edges;
  
  gr = self->gref;
  dict = ATTR_STRUCT_DICT(&gr->g)[ATTRHASH_IDX_EDGE];

  if (!igraphmodule_attribute_name_check(attrname))
    return -1;

  if (values == 0) {
    if (igraph_es_type(&self->es) == IGRAPH_ES_ALL)
      return PyDict_DelItem(dict, attrname);
    PyErr_SetString(PyExc_TypeError, "can't delete attribute from an edge sequence not representing the whole graph");
    return -1;
  }

 if (PyString_Check(values) || !PySequence_Check(values)) {
    /* If values is a string or not a sequence, we construct a list with a
     * single element (the value itself) and then call ourselves again */
    int result;
    PyObject *newList = PyList_New(1);
    if (newList == 0) return -1;
    Py_INCREF(values);
    PyList_SET_ITEM(newList, 0, values);    /* reference stolen here */
    result = igraphmodule_EdgeSeq_set_attribute_values_mapping(self, attrname, newList);
    Py_DECREF(newList);
    return result;
  }

  n=PySequence_Size(values);
  if (n<0) return -1;

  if (igraph_es_type(&self->es) == IGRAPH_ES_ALL) {
    no_of_edges = (long)igraph_ecount(&gr->g);
    if (n == 0 && no_of_edges > 0) {
      PyErr_SetString(PyExc_ValueError, "sequence must not be empty");
      return -1;
    }

    /* Check if we already have attributes with the given name */
    list = PyDict_GetItem(dict, attrname);
    if (list != 0) {
      /* Yes, we have. Modify its items to the items found in values */
      for (i=0, j=0; i<no_of_edges; i++, j++) {
        if (j == n) j = 0;
        item = PySequence_GetItem(values, j);
        if (item == 0) return -1;
        /* No need to Py_INCREF(item), PySequence_GetItem returns a new reference */
        if (PyList_SetItem(list, i, item)) {
          Py_DECREF(item);
          return -1;
        } /* PyList_SetItem stole a reference to the item automatically */ 
      }
    } else if (values != 0) {
      /* We don't have attributes with the given name yet. Create an entry
       * in the dict, create a new list and copy everything */
      list = PyList_New(no_of_edges);
      if (list == 0) return -1;
      for (i=0, j=0; i<no_of_edges; i++, j++) {
        if (j == n) j = 0;
        item = PySequence_GetItem(values, j);
        if (item == 0) { Py_DECREF(list); return -1; }
        /* No need to Py_INCREF(item), PySequence_GetItem returns a new reference */
        PyList_SET_ITEM(list, i, item);
        /* PyList_SET_ITEM stole a reference to the item automatically */
      }
      if (PyDict_SetItem(dict, attrname, list)) {
        Py_DECREF(list);
        return -1;
      }
      Py_DECREF(list);   /* compensating for PyDict_SetItem */
    }
  } else {
    /* We are working with a subset of the graph. Convert the sequence to a
     * vector and loop through it */
    if (igraph_vector_init(&es, 0)) {
      igraphmodule_handle_igraph_error();
      return -1;
    } 
    if (igraph_es_as_vector(&gr->g, self->es, &es)) {
      igraphmodule_handle_igraph_error();
      igraph_vector_destroy(&es);
      return -1;
    }
    no_of_edges = (long)igraph_vector_size(&es);
    if (n == 0 && no_of_edges > 0) {
      PyErr_SetString(PyExc_ValueError, "sequence must not be empty");
      igraph_vector_destroy(&es);
      return -1;
    }
    /* Check if we already have attributes with the given name */
    list = PyDict_GetItem(dict, attrname);
    if (list != 0) {
      /* Yes, we have. Modify its items to the items found in values */
      for (i=0, j=0; i<no_of_edges; i++, j++) {
        if (j == n) j = 0;
        item = PySequence_GetItem(values, j);
        if (item == 0) { igraph_vector_destroy(&es); return -1; }
        /* No need to Py_INCREF(item), PySequence_GetItem returns a new reference */
        if (PyList_SetItem(list, (long)VECTOR(es)[i], item)) {
          Py_DECREF(item);
          igraph_vector_destroy(&es);
          return -1;
        } /* PyList_SetItem stole a reference to the item automatically */ 
      }
      igraph_vector_destroy(&es);
    } else if (values != 0) {
      /* We don't have attributes with the given name yet. Create an entry
       * in the dict, create a new list, fill with None for vertices not in the
       * sequence and copy the rest */
      long n2 = igraph_ecount(&gr->g);
      list = PyList_New(n2);
      if (list == 0) { igraph_vector_destroy(&es); return -1; }
      for (i=0; i<n2; i++) {
        Py_INCREF(Py_None);
        PyList_SET_ITEM(list, i, Py_None);
      }
      for (i=0, j=0; i<no_of_edges; i++, j++) {
        if (j == n) j = 0;
        item = PySequence_GetItem(values, j);
        if (item == 0) {
          igraph_vector_destroy(&es);
          Py_DECREF(list); return -1;
        }
        /* No need to Py_INCREF(item), PySequence_GetItem returns a new reference */
        PyList_SET_ITEM(list, (long)VECTOR(es)[i], item);
        /* PyList_SET_ITEM stole a reference to the item automatically */
      }
      igraph_vector_destroy(&es);
      if (PyDict_SetItem(dict, attrname, list)) {
        Py_DECREF(list);
        return -1;
      }
      Py_DECREF(list);   /* compensating for PyDict_SetItem */
    }
  }
  return 0;
}
Example #5
0
int BL_ArmatureChannel::py_attr_set_joint_rotation(void *self_v, const struct KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
{
	BL_ArmatureChannel* self= static_cast<BL_ArmatureChannel*>(self_v);
	bPoseChannel* pchan = self->m_posechannel;
	PyObject *item;
	float joints[3];
	float quat[4];

	if (!PySequence_Check(value) || PySequence_Size(value) != 3) {
		PyErr_SetString(PyExc_AttributeError, "expected a sequence of [3] floats");
		return PY_SET_ATTR_FAIL;
	}
	for (int i=0; i<3; i++) {
		item = PySequence_GetItem(value, i); /* new ref */
		joints[i] = PyFloat_AsDouble(item);
		Py_DECREF(item);
		if (joints[i] == -1.0f && PyErr_Occurred()) {
			PyErr_SetString(PyExc_AttributeError, "expected a sequence of [3] floats");
			return PY_SET_ATTR_FAIL;
		}
	}

	int flag = 0;
	if (!(pchan->ikflag & BONE_IK_NO_XDOF))
		flag |= 1;
	if (!(pchan->ikflag & BONE_IK_NO_YDOF))
		flag |= 2;
	if (!(pchan->ikflag & BONE_IK_NO_ZDOF))
		flag |= 4;
	unit_qt(quat);
	switch (flag) {
	case 0:	// fixed joint
		break;
	case 1:	// X only
		joints[1] = joints[2] = 0.f;
		eulO_to_quat( quat,joints, EULER_ORDER_XYZ);
		break;
	case 2:	// Y only
		joints[0] = joints[2] = 0.f;
		eulO_to_quat( quat,joints, EULER_ORDER_XYZ);
		break;
	case 3:	// X+Y
		joints[2] = 0.f;
		eulO_to_quat( quat,joints, EULER_ORDER_ZYX);
		break;
	case 4:	// Z only
		joints[0] = joints[1] = 0.f;
		eulO_to_quat( quat,joints, EULER_ORDER_XYZ);
		break;
	case 5:	// X+Z
		// X and Z are components of an equivalent rotation axis
		joints[1] = 0;
		axis_angle_to_quat( quat,joints, len_v3(joints));
		break;
	case 6:	// Y+Z
		joints[0] = 0.f;
		eulO_to_quat( quat,joints, EULER_ORDER_XYZ);
		break;
	case 7: // X+Y+Z
		// equivalent axis
		axis_angle_to_quat( quat,joints, len_v3(joints));
		break;
	}
	if (pchan->rotmode > 0) {
		quat_to_eulO( joints, pchan->rotmode,quat);
		copy_v3_v3(pchan->eul, joints);
	} else
		copy_qt_qt(pchan->quat, quat);
	return PY_SET_ATTR_SUCCESS;
}
Example #6
0
PyObject* JPy_array(PyObject* self, PyObject* args)
{
    JNIEnv* jenv;
    JPy_JType* componentType;
    jarray arrayRef;
    PyObject* objType;
    PyObject* objInit;

    JPy_GET_JNI_ENV_OR_RETURN(jenv, NULL)

    if (!PyArg_ParseTuple(args, "OO:array", &objType, &objInit)) {
        return NULL;
    }

    if (JPy_IS_STR(objType)) {
        const char* typeName;
        typeName = JPy_AS_UTF8(objType);
        componentType = JType_GetTypeForName(jenv, typeName, JNI_FALSE);
        if (componentType == NULL) {
            return NULL;
        }
    } else if (JType_Check(objType)) {
        componentType = (JPy_JType*) objType;
    } else {
        PyErr_SetString(PyExc_ValueError, "array: argument 1 (type) must be a type name or Java type object");
        return NULL;
    }

    if (componentType == JPy_JVoid) {
        PyErr_SetString(PyExc_ValueError, "array: argument 1 (type) must not be 'void'");
        return NULL;
    }

    if (JPy_IS_CLONG(objInit)) {
        jint length = JPy_AS_CLONG(objInit);
        if (length < 0) {
            PyErr_SetString(PyExc_ValueError, "array: argument 2 (init) must be either an integer array length or any sequence");
            return NULL;
        }
        if (componentType == JPy_JBoolean) {
            arrayRef = (*jenv)->NewBooleanArray(jenv, length);
        } else if (componentType == JPy_JChar) {
            arrayRef = (*jenv)->NewCharArray(jenv, length);
        } else if (componentType == JPy_JByte) {
            arrayRef = (*jenv)->NewByteArray(jenv, length);
        } else if (componentType == JPy_JShort) {
            arrayRef = (*jenv)->NewShortArray(jenv, length);
        } else if (componentType == JPy_JInt) {
            arrayRef = (*jenv)->NewIntArray(jenv, length);
        } else if (componentType == JPy_JLong) {
            arrayRef = (*jenv)->NewLongArray(jenv, length);
        } else if (componentType == JPy_JFloat) {
            arrayRef = (*jenv)->NewFloatArray(jenv, length);
        } else if (componentType == JPy_JDouble) {
            arrayRef = (*jenv)->NewDoubleArray(jenv, length);
        } else {
            arrayRef = (*jenv)->NewObjectArray(jenv, length, componentType->classRef, NULL);
        }
        if (arrayRef == NULL) {
            return PyErr_NoMemory();
        }
        return (PyObject*) JObj_New(jenv, arrayRef);
    } else if (PySequence_Check(objInit)) {
        if (JType_CreateJavaArray(jenv, componentType, objInit, &arrayRef) < 0) {
            return NULL;
        }
        return (PyObject*) JObj_New(jenv, arrayRef);
    } else {
        PyErr_SetString(PyExc_ValueError, "array: argument 2 (init) must be either an integer array length or any sequence");
        return NULL;
    }
}
// Parse a Python object as a sequence of either QVector[234]D instances or a
// sequence of sequence of floats and return an array that can be passed to
// QGLShaderProgram::setAttributeArray().  The array is destroyed only when the
// shader is garbage collected or when replaced by another array.
const GLfloat *qpyopengl_attribute_array(PyObject *values, PyObject *shader,
        PyObject *key, int *tsize, sipErrorState *estate)
{
    // Check the key was created correctly.
    if (!key)
    {
        *estate = sipErrorFail;
        return 0;
    }

    // Get the dict that holds the converted arrays.
    PyObject *dict = ((sipSimpleWrapper *)shader)->user;

    if (!dict)
    {
        dict = PyDict_New();

        if (!dict)
        {
            Py_DECREF(key);

            *estate = sipErrorFail;
            return 0;
        }

        ((sipSimpleWrapper *)shader)->user = dict;
    }

    // Check that values is a non-empty sequence.
    values = PySequence_Fast(values, "an attribute array must be a sequence");

    if (!values)
    {
        Py_DECREF(key);

        *estate = sipErrorContinue;
        return 0;
    }

    SIP_SSIZE_T nr_items = PySequence_Fast_GET_SIZE(values);

    if (nr_items < 1)
    {
        PyErr_SetString(PyExc_TypeError,
                "an attribute array must have at least one element");

        Py_DECREF(key);
        Py_DECREF(values);

        *estate = sipErrorFail;
        return 0;
    }

    // The first element determines the type expected.
    PyObject *itm = PySequence_Fast_GET_ITEM(values, 0);

    const sipTypeDef *td;
    SIP_SSIZE_T nr_dim;

    if (sipCanConvertToType(itm, sipType_QVector2D, SIP_NOT_NONE))
    {
        td = sipType_QVector2D;
        nr_dim = 2;
    }
    else if (sipCanConvertToType(itm, sipType_QVector3D, SIP_NOT_NONE))
    {
        td = sipType_QVector3D;
        nr_dim = 3;
    }
    else if (sipCanConvertToType(itm, sipType_QVector4D, SIP_NOT_NONE))
    {
        td = sipType_QVector4D;
        nr_dim = 4;
    }
    else if (PySequence_Check(itm) && (nr_dim = PySequence_Size(itm)) >= 1)
    {
        td = 0;
    }
    else
    {
        PyErr_SetString(PyExc_TypeError,
                "an attribute array must be a sequence of QVector2D, "
                "QVector3D, QVector4D, or a sequence of sequences of floats");

        Py_DECREF(key);
        Py_DECREF(values);

        *estate = sipErrorFail;
        return 0;
    }

    // Create the array that will be returned.
    GLfloat *array = new GLfloat[nr_items * nr_dim];

    // Convert the values.
    GLfloat *ap = array;

    for (SIP_SSIZE_T i = 0; i < nr_items; ++i)
    {
        int iserr = 0;

        itm = PySequence_Fast_GET_ITEM(values, i);

        if (td)
        {
            void *cpp;

            cpp = sipForceConvertToType(itm, td, 0,
                    SIP_NOT_NONE | SIP_NO_CONVERTORS, 0, &iserr);

            if (iserr)
            {
                PyErr_Format(PyExc_TypeError,
                        "attribute array elements should all be '%s', not '%s'",
                        sipTypeAsPyTypeObject(td)->tp_name,
                        Py_TYPE(itm)->tp_name);
            }
            else if (td == sipType_QVector2D)
            {
                QVector2D *v = reinterpret_cast<QVector2D *>(cpp);

                *ap++ = v->x();
                *ap++ = v->y();
            }
            else if (td == sipType_QVector3D)
            {
                QVector3D *v = reinterpret_cast<QVector3D *>(cpp);

                *ap++ = v->x();
                *ap++ = v->y();
                *ap++ = v->z();
            }
            else if (td == sipType_QVector4D)
            {
                QVector4D *v = reinterpret_cast<QVector4D *>(cpp);

                *ap++ = v->x();
                *ap++ = v->y();
                *ap++ = v->z();
                *ap++ = v->w();
            }
        }
        else
        {
            itm = PySequence_Fast(itm,
                    "attribute array elements should all be sequences");

            if (itm)
            {
                if (PySequence_Fast_GET_SIZE(itm) != nr_dim)
                {
                    PyErr_Format(PyExc_TypeError,
                            "attribute array elements should all be sequences "
#if PY_VERSION_HEX >= 0x02050000
                            "of length %zd",
#else
                            "of length %d",
#endif
                            nr_dim);

                    Py_DECREF(itm);
                    iserr = 1;
                }
                else
                {
                    PyErr_Clear();

                    for (SIP_SSIZE_T j = 0; j < nr_dim; ++j)
                        *ap++ = PyFloat_AsDouble(
                                PySequence_Fast_GET_ITEM(itm, j));

                    if (PyErr_Occurred())
                    {
                        PyErr_SetString(PyExc_TypeError,
                                "attribute array elements should all be "
                                "sequences of floats");

                        Py_DECREF(itm);
                        iserr = 1;
                    }
                }
            }
            else
            {
                iserr = 1;
            }
        }

        if (iserr)
        {
            Py_DECREF(key);
            Py_DECREF(values);
            delete[] array;

            *estate = sipErrorFail;
            return 0;
        }
    }

    Py_DECREF(values);

    *tsize = nr_dim;

    // Wrap the array in a Python object so that it won't leak.
#if defined(SIP_USE_PYCAPSULE)
    PyObject *array_obj = PyCapsule_New(array, 0, array_dtor);
#else
    PyObject *array_obj = PyCObject_FromVoidPtr(array, array_dtor);
#endif

    if (!array_obj)
    {
        Py_DECREF(key);
        delete[] array;

        *estate = sipErrorFail;
        return 0;
    }

    int rc = PyDict_SetItem(dict, key, array_obj);

    Py_DECREF(key);
    Py_DECREF(array_obj);

    if (rc < 0)
    {
        *estate = sipErrorFail;
        return 0;
    }

    return array;
}
static s_param *
parse_params(PyObject *pyarray, int *plen)
{
    struct s_param *params;

    // check and parse fractal params
    if(!PySequence_Check(pyarray))
    {
	PyErr_SetString(PyExc_TypeError,
			"parameters argument should be an array");
	return NULL;
    }


    int len = PySequence_Size(pyarray);
    if(len == 0)
    {
	params = (struct s_param *)malloc(sizeof(struct s_param));
	params[0].t = FLOAT;
	params[0].doubleval = 0.0;
    }
    else if(len > PF_MAXPARAMS)
    {
	PyErr_SetString(PyExc_ValueError,"Too many parameters");
	return NULL;
    }
    else
    {
	int i = 0;
	params = (struct s_param *)malloc(len * sizeof(struct s_param));
	if(!params) return NULL;
	for(i = 0; i < len; ++i)
	{
	    PyObject *pyitem = PySequence_GetItem(pyarray,i);
	    if(NULL == pyitem)
	    {
		return NULL;
	    }
	    if(PyFloat_Check(pyitem))
	    {
		params[i].t = FLOAT;
		params[i].doubleval = PyFloat_AsDouble(pyitem);
		//printf("%d = float(%g)\n",i,params[i].doubleval);
	    }
	    else if(PyInt_Check(pyitem))
	    {
		params[i].t = INT;
		params[i].intval = PyInt_AS_LONG(pyitem);
		//printf("%d = int(%d)\n",i,params[i].intval);
	    }
	    else if(
		PyObject_HasAttrString(pyitem,"cobject") &&
		PyObject_HasAttrString(pyitem,"segments"))
	    {
		PyObject *pycob = PyObject_GetAttrString(pyitem,"cobject");
		if(pycob == Py_None)
		{
		    Py_DECREF(pycob);
		    PyObject *pysegs = PyObject_GetAttrString(
			pyitem,"segments");

		    ColorMap *cmap = cmap_from_pyobject(pysegs);
		    Py_DECREF(pysegs);

		    if(NULL == cmap)
		    {
			return NULL;
		    }

		    pycob = PyCObject_FromVoidPtr(
			cmap, (void (*)(void *))cmap_delete);

		    if(NULL != pycob)
		    {
			PyObject_SetAttrString(pyitem,"cobject",pycob);
			// not quite correct, we are leaking some
			// cmap objects 
			Py_XINCREF(pycob);
		    }
		}
		params[i].t = GRADIENT;
		params[i].gradient = PyCObject_AsVoidPtr(pycob);
		//printf("%d = gradient(%p)\n",i,params[i].gradient);
		Py_DECREF(pycob);
	    }
	    else if(
		PyObject_HasAttrString(pyitem,"_img"))
	    {
		PyObject *pycob = PyObject_GetAttrString(pyitem,"_img");
		params[i].t = PARAM_IMAGE;
		params[i].image = PyCObject_AsVoidPtr(pycob);
		Py_DECREF(pycob);
	    }
	    else
	    {
		Py_XDECREF(pyitem);
		PyErr_SetString(
		    PyExc_ValueError,
		    "All params must be floats, ints, or gradients");
		free(params);
		return NULL;
	    }
	    Py_XDECREF(pyitem);
	} 
    }
    *plen = len;
    return params;
}
Example #9
0
/* Open EWF file(s)
 * Returns a Python object if successful or NULL on error
 */
PyObject *pyewf_handle_open(
           pyewf_handle_t *pyewf_handle,
           PyObject *arguments,
           PyObject *keywords )
{
	char error_string[ PYEWF_ERROR_STRING_SIZE ];

	liberror_error_t *error     = NULL;
	char **filenames            = NULL;
	static char *keyword_list[] = { "filenames", "access_flags", NULL };
	PyObject *sequence_object   = NULL;
	PyObject *string_object     = NULL;
	static char *function       = "pyewf_handle_open";
	size_t filename_length      = 0;
	int access_flags            = 0;
	int filename_index          = 0;
	int number_of_filenames     = 0;

	if( pyewf_handle == NULL )
	{
		PyErr_Format(
		 PyExc_TypeError,
		 "%s: invalid pyewf handle.",
		 function );

		return( NULL );
	}
	if( PyArg_ParseTupleAndKeywords(
	     arguments,
	      keywords,
	      "O|i",
	      keyword_list,
	      &sequence_object,
	      &access_flags ) == 0 )
	{
		return( NULL );
	}
	if( PySequence_Check(
	     sequence_object ) == 0 )
	{
		PyErr_Format(
		 PyExc_TypeError,
		 "%s: argument: files must be a list or tuple.",
		 function );

		return( NULL );
	}
	number_of_filenames = PySequence_Size(
	                       sequence_object );

	if( ( number_of_filenames <= 0 )
	 || ( number_of_filenames > (int) UINT16_MAX ) )
	{
		PyErr_Format(
		 PyExc_ValueError,
		 "%s: invalid number of files.",
		 function );

		return( NULL );
	}
	filenames = (char **) memory_allocate(
	                       sizeof( char * ) * number_of_filenames );

	if( filenames == NULL )
	{
		PyErr_Format(
		 PyExc_MemoryError,
		 "%s: unable to create filenames.",
		 function );

		return( NULL );
	}
	if( memory_set(
	     filenames,
	     0,
	     sizeof( char * ) * number_of_filenames ) == NULL )
	{
		PyErr_Format(
		 PyExc_MemoryError,
		 "%s: unable to clear filenames.",
		 function );

		memory_free(
		 filenames );

		return( NULL );
	}
	for( filename_index = 0;
	     filename_index < number_of_filenames;
	     filename_index++ )
	{
		string_object = PySequence_GetItem(
		                 sequence_object,
		                 filename_index );

		filename_length = PyString_Size(
		                   string_object );

		filenames[ filename_index ] = (char *) memory_allocate(
		                                        sizeof( char ) * ( filename_length + 1 ) );

		if( filenames[ filename_index ] == NULL )
		{
			PyErr_Format(
			 PyExc_MemoryError,
			 "%s: unable to create filename: %d.",
			 function,
			 filename_index );

			for( ; filename_index > 0; filename_index-- )
			{
				memory_free(
				 filenames[ filename_index - 1 ] );
			}
			memory_free(
			 filenames );

			return( NULL );
		}
		if( libcstring_narrow_string_copy(
		     filenames[ filename_index ],
		     PyString_AsString(
		      string_object ),
		     filename_length ) == NULL )
		{
			PyErr_Format(
			 PyExc_MemoryError,
			 "%s: unable to set filename: %d.",
			 function,
			 filename_index );

			for( ; filename_index > 0; filename_index-- )
			{
				memory_free(
				 filenames[ filename_index - 1 ] );
			}
			memory_free(
			 filenames );

			return( NULL );
		}
		( filenames[ filename_index ] )[ filename_length ] = 0;

		Py_DecRef(
		 string_object );
	}
	if( libewf_handle_open(
	     pyewf_handle->handle,
             filenames,
             number_of_filenames,
             access_flags,
	     &error ) != 1 )
	{
		if( liberror_error_backtrace_sprint(
		     error,
		     error_string,
		     PYEWF_ERROR_STRING_SIZE ) == -1 )
		{
			PyErr_Format(
			 PyExc_IOError,
			 "%s: unable to open handle.",
			 function );
		}
		else
		{
			PyErr_Format(
			 PyExc_IOError,
			 "%s: unable to open handle.\n%s",
			 function,
			 error_string );
		}
		liberror_error_free(
		 &error );

		for( filename_index = 0;
		     filename_index < number_of_filenames;
		     filename_index++ )
		{
			memory_free(
			 filenames[ filename_index ] );
		}
		memory_free(
		 filenames );

		return( NULL );
	}
	for( filename_index = 0;
	     filename_index < number_of_filenames;
	     filename_index++ )
	{
		memory_free(
		 filenames[ filename_index ] );
	}
	memory_free(
	 filenames );

	return( Py_None );
}
Example #10
0
//-------------------------------------------------------------------------------------
bool Loginapp::_createAccount(Network::Channel* pChannel, std::string& accountName, 
								 std::string& password, std::string& datas, ACCOUNT_TYPE type)
{
	AUTO_SCOPED_PROFILE("createAccount");

	ACCOUNT_TYPE oldType = type;

	if(!g_kbeSrvConfig.getDBMgr().account_registration_enable)
	{
		WARNING_MSG(fmt::format("Loginapp::_createAccount({}): not available!\n", accountName));

		std::string retdatas = "";
		Network::Bundle* pBundle = Network::Bundle::createPoolObject();
		(*pBundle).newMessage(ClientInterface::onCreateAccountResult);
		SERVER_ERROR_CODE retcode = SERVER_ERR_ACCOUNT_REGISTER_NOT_AVAILABLE;
		(*pBundle) << retcode;
		(*pBundle).appendBlob(retdatas);
		pChannel->send(pBundle);
		return false;
	}

	accountName = KBEngine::strutil::kbe_trim(accountName);
	password = KBEngine::strutil::kbe_trim(password);

	if(accountName.size() > ACCOUNT_NAME_MAX_LENGTH)
	{
		ERROR_MSG(fmt::format("Loginapp::_createAccount: accountName too big, size={}, limit={}.\n",
			accountName.size(), ACCOUNT_NAME_MAX_LENGTH));

		return false;
	}

	if(password.size() > ACCOUNT_PASSWD_MAX_LENGTH)
	{
		ERROR_MSG(fmt::format("Loginapp::_createAccount: password too big, size={}, limit={}.\n",
			password.size(), ACCOUNT_PASSWD_MAX_LENGTH));

		return false;
	}

	if(datas.size() > ACCOUNT_DATA_MAX_LENGTH)
	{
		ERROR_MSG(fmt::format("Loginapp::_createAccount: bindatas too big, size={}, limit={}.\n",
			datas.size(), ACCOUNT_DATA_MAX_LENGTH));

		return false;
	}
	
	std::string retdatas = "";
	if(shuttingdown_ != SHUTDOWN_STATE_STOP)
	{
		WARNING_MSG(fmt::format("Loginapp::_createAccount: shutting down, create {} failed!\n", accountName));

		Network::Bundle* pBundle = Network::Bundle::createPoolObject();
		(*pBundle).newMessage(ClientInterface::onCreateAccountResult);
		SERVER_ERROR_CODE retcode = SERVER_ERR_IN_SHUTTINGDOWN;
		(*pBundle) << retcode;
		(*pBundle).appendBlob(retdatas);
		pChannel->send(pBundle);
		return false;
	}

	PendingLoginMgr::PLInfos* ptinfos = pendingCreateMgr_.find(const_cast<std::string&>(accountName));
	if(ptinfos != NULL)
	{
		WARNING_MSG(fmt::format("Loginapp::_createAccount: pendingCreateMgr has {}, request create failed!\n", 
			accountName));

		Network::Bundle* pBundle = Network::Bundle::createPoolObject();
		(*pBundle).newMessage(ClientInterface::onCreateAccountResult);
		SERVER_ERROR_CODE retcode = SERVER_ERR_BUSY;
		(*pBundle) << retcode;
		(*pBundle).appendBlob(retdatas);
		pChannel->send(pBundle);
		return false;
	}
	
	{
		// 把请求交由脚本处理
		SERVER_ERROR_CODE retcode = SERVER_SUCCESS;
		SCOPED_PROFILE(SCRIPTCALL_PROFILE);

		PyObject* pyResult = PyObject_CallMethod(getEntryScript().get(), 
											const_cast<char*>("onRequestCreateAccount"), 
											const_cast<char*>("ssy#"), 
											accountName.c_str(),
											password.c_str(),
											datas.c_str(), datas.length());

		if(pyResult != NULL)
		{
			if(PySequence_Check(pyResult) && PySequence_Size(pyResult) == 4)
			{
				char* sname;
				char* spassword;
			    char *extraDatas;
			    Py_ssize_t extraDatas_size = 0;
				
				if(PyArg_ParseTuple(pyResult, "H|s|s|y#",  &retcode, &sname, &spassword, &extraDatas, &extraDatas_size) == -1)
				{
					ERROR_MSG(fmt::format("Loginapp::_createAccount: {}.onReuqestLogin, Return value error! accountName={}\n", 
						g_kbeSrvConfig.getLoginApp().entryScriptFile, accountName));

					retcode = SERVER_ERR_OP_FAILED;
				}
				else
				{
					accountName = sname;
					password = spassword;

					if (extraDatas && extraDatas_size > 0)
						datas.assign(extraDatas, extraDatas_size);
					else
						SCRIPT_ERROR_CHECK();
				}
			}
			else
			{
				ERROR_MSG(fmt::format("Loginapp::_createAccount: {}.onReuqestLogin, Return value error, must be errorcode or tuple! accountName={}\n", 
					g_kbeSrvConfig.getLoginApp().entryScriptFile, accountName));

				retcode = SERVER_ERR_OP_FAILED;
			}
			
			Py_DECREF(pyResult);
		}
		else
		{
			SCRIPT_ERROR_CHECK();
			retcode = SERVER_ERR_OP_FAILED;
		}
			
		if(retcode != SERVER_SUCCESS)
		{
			Network::Bundle* pBundle = Network::Bundle::createPoolObject();
			(*pBundle).newMessage(ClientInterface::onCreateAccountResult);
			(*pBundle) << retcode;
			(*pBundle).appendBlob(retdatas);
			pChannel->send(pBundle);
			return false;
		}
		else
		{
			if(accountName.size() == 0)
			{
				ERROR_MSG(fmt::format("Loginapp::_createAccount: accountName is empty!\n"));

				retcode = SERVER_ERR_NAME;
				Network::Bundle* pBundle = Network::Bundle::createPoolObject();
				(*pBundle).newMessage(ClientInterface::onCreateAccountResult);
				(*pBundle) << retcode;
				(*pBundle).appendBlob(retdatas);
				pChannel->send(pBundle);
				return false;
			}
		}
	}

	if(type == ACCOUNT_TYPE_SMART)
	{
		if (email_isvalid(accountName.c_str()))
		{
			type = ACCOUNT_TYPE_MAIL;
		}
		else
		{
			if(!validName(accountName))
			{
				ERROR_MSG(fmt::format("Loginapp::_createAccount: invalid accountName({})\n",
					accountName));

				Network::Bundle* pBundle = Network::Bundle::createPoolObject();
				(*pBundle).newMessage(ClientInterface::onCreateAccountResult);
				SERVER_ERROR_CODE retcode = SERVER_ERR_NAME;
				(*pBundle) << retcode;
				(*pBundle).appendBlob(retdatas);
				pChannel->send(pBundle);
				return false;
			}

			type = ACCOUNT_TYPE_NORMAL;
		}
	}
	else if(type == ACCOUNT_TYPE_NORMAL)
	{
		if(!validName(accountName))
		{
			ERROR_MSG(fmt::format("Loginapp::_createAccount: invalid accountName({})\n",
				accountName));

			Network::Bundle* pBundle = Network::Bundle::createPoolObject();
			(*pBundle).newMessage(ClientInterface::onCreateAccountResult);
			SERVER_ERROR_CODE retcode = SERVER_ERR_NAME;
			(*pBundle) << retcode;
			(*pBundle).appendBlob(retdatas);
			pChannel->send(pBundle);
			return false;
		}
	}
	else if (!email_isvalid(accountName.c_str()))
    {
		/*
		std::string user_name, domain_name;
        user_name = regex_replace(accountName, _g_mail_pattern, std::string("$1") );
        domain_name = regex_replace(accountName, _g_mail_pattern, std::string("$2") );
		*/
		WARNING_MSG(fmt::format("Loginapp::_createAccount: invalid mail={}\n", 
			accountName));

		Network::Bundle* pBundle = Network::Bundle::createPoolObject();
		(*pBundle).newMessage(ClientInterface::onCreateAccountResult);
		SERVER_ERROR_CODE retcode = SERVER_ERR_NAME_MAIL;
		(*pBundle) << retcode;
		(*pBundle).appendBlob(retdatas);
		pChannel->send(pBundle);
		return false;
    }

	DEBUG_MSG(fmt::format("Loginapp::_createAccount: accountName={}, passwordsize={}, type={}, oldType={}.\n",
		accountName.c_str(), password.size(), type, oldType));

	ptinfos = new PendingLoginMgr::PLInfos;
	ptinfos->accountName = accountName;
	ptinfos->password = password;
	ptinfos->datas = datas;
	ptinfos->addr = pChannel->addr();
	pendingCreateMgr_.add(ptinfos);

	Components::COMPONENTS& cts = Components::getSingleton().getComponents(DBMGR_TYPE);
	Components::ComponentInfos* dbmgrinfos = NULL;

	if(cts.size() > 0)
		dbmgrinfos = &(*cts.begin());

	if(dbmgrinfos == NULL || dbmgrinfos->pChannel == NULL || dbmgrinfos->cid == 0)
	{
		ERROR_MSG(fmt::format("Loginapp::_createAccount: create({}), not found dbmgr!\n", 
			accountName));

		Network::Bundle* pBundle = Network::Bundle::createPoolObject();
		(*pBundle).newMessage(ClientInterface::onCreateAccountResult);
		SERVER_ERROR_CODE retcode = SERVER_ERR_SRV_NO_READY;
		(*pBundle) << retcode;
		(*pBundle).appendBlob(retdatas);
		pChannel->send(pBundle);
		return false;
	}

	pChannel->extra(accountName);

	Network::Bundle* pBundle = Network::Bundle::createPoolObject();
	(*pBundle).newMessage(DbmgrInterface::reqCreateAccount);
	uint8 uatype = uint8(type);
	(*pBundle) << accountName << password << uatype;
	(*pBundle).appendBlob(datas);
	dbmgrinfos->pChannel->send(pBundle);
	return true;
}
Example #11
0
File: module.c Project: WebSQL/wsql
static PyObject* wsql_server_init(PyObject *self, PyObject *args, PyObject *kwargs)
{
    static char *kwlist[] = {"args", "groups", NULL};
    char **cmd_args_c=NULL, **groups_c=NULL, *s;
    Py_ssize_t cmd_argc=0, i, groupc;
    PyObject *cmd_args=NULL, *groups=NULL, *item;

    if (wsql_server_init_done)
    {
        PyErr_SetString(wsql_programming_error, "already initialized");
        return NULL;
    }

    if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|OO", kwlist, &cmd_args, &groups))
        return NULL;

#if MYSQL_VERSION_ID >= 40000
    if (cmd_args)
    {
        if (!PySequence_Check(cmd_args))
        {
            PyErr_SetString(PyExc_TypeError, "args must be a sequence");
            goto finish;
        }
        cmd_argc = PySequence_Size(cmd_args);
        if (cmd_argc == -1)
        {
            PyErr_SetString(PyExc_TypeError, "args could not be sized");
            goto finish;
        }
        cmd_args_c = (char **) PyMem_Malloc(cmd_argc * sizeof(char *));
        for (i=0; i< cmd_argc; ++i)
        {
            item = PySequence_GetItem(cmd_args, i);
            s = PyString_AsString(item);
            Py_DECREF(item);
            if (!s)
            {
                PyErr_SetString(PyExc_TypeError, "args must contain strings");
                goto finish;
            }
            cmd_args_c[i] = s;
        }
    }
    if (groups)
    {
        if (!PySequence_Check(groups))
        {
            PyErr_SetString(PyExc_TypeError, "groups must be a sequence");
            goto finish;
        }
        groupc = PySequence_Size(groups);
        if (groupc == -1)
        {
            PyErr_SetString(PyExc_TypeError, "groups could not be sized");
            goto finish;
        }
        groups_c = (char **) PyMem_Malloc((1+groupc)*sizeof(char *));
        for (i = 0; i < groupc; ++i)
        {
            item = PySequence_GetItem(groups, i);
            s = PyString_AsString(item);
            Py_DECREF(item);
            if (!s)
            {
                PyErr_SetString(PyExc_TypeError, "groups must contain strings");
                goto finish;
            }
            groups_c[i] = s;
        }
        groups_c[groupc] = (char *)NULL;
    }
    /* even though this may block, don't give up the interpreter lock
       so that the server can't be initialized multiple times. */
    if (mysql_server_init(cmd_argc, cmd_args_c, groups_c))
    {
        wsql_raise_error(NULL);
        goto finish;
    }
#endif
    wsql_server_init_done = 1;
    Py_RETURN_NONE;
  finish:
    PyMem_Free(groups_c);
    PyMem_Free(cmd_args_c);
    return NULL;
}
Example #12
0
//----------------------------------------------------------------------------------------
//
static int
do_set_servers(CmemcacheObject* self, PyObject* servers)
{
    debug(("do_set_servers\n"));
    
    if (!PySequence_Check(servers))
    {
        PyErr_BadArgument();
        return -1;
    }

    int error = 0;
    
    /* there seems to be no way to remove servers, so get rid of memcache all together */
    if (self->mc)
    {
        mcm_free(self->mc_ctxt, self->mc);
        self->mc = NULL;
    }
    assert(self->mc == NULL);

    /* create new instance */
    self->mc = mcm_new(self->mc_ctxt);
    debug(("new mc %p\n", self->mc));
    if (self->mc == NULL)
    {
        PyErr_NoMemory();
        return -1;
    }

    /* add servers, allow any sequence of strings */
    const int size = PySequence_Size(servers);
    int i;
    for (i = 0; i < size && error == 0; ++i)
    {
        PyObject* item = PySequence_GetItem(servers, i);
        if (item)
        {
            PyObject* name = NULL;
            int weight = 1;
            
            if (PyString_Check(item))
            {
                name = item;
            }
            else if (PyTuple_Check(item))
            {
                error = ! PyArg_ParseTuple(item, "Oi", &name, &weight);
            }
            if (name)    
            {
                const char* cserver = PyString_AsString(name);
                assert(cserver);
                debug(("cserver %s weight %d\n", cserver, weight));
            
                /* mc_server_add4 is not happy without ':' (it segfaults!) so check */
                if (strstr(cserver, ":") == NULL)
                {
                    PyErr_Format(PyExc_TypeError,
                                 "expected \"server:port\" but \"%s\" found", cserver);
                    error = 1;
                }
                else
                {
                    int i;
                    if (weight>15)
                    {
                        weight = 15;
                    }
                    Py_BEGIN_ALLOW_THREADS;
                    for (i = 0; i < weight; ++i)
                    {
                        debug_def(int retval =)
                            mcm_server_add4(self->mc_ctxt, self->mc, cserver);
                        debug(("retval %d\n", retval));
                    }
                    Py_END_ALLOW_THREADS;
                }
            }
            else
            {
                PyErr_BadArgument();
                error = 1;
            }
            Py_DECREF(item);
        }
    }
Example #13
0
/* The MediaControl constructor takes either an existing vlc.Instance or a
   list of strings */
static PyObject *
MediaControl_new( PyTypeObject *type, PyObject *args, PyObject *kwds )
{
    MediaControl *self;
    mediacontrol_Exception *exception = NULL;
    PyObject* py_param = NULL;
    char** ppsz_args = NULL;
    libvlc_instance_t* p_instance = NULL;
    Py_ssize_t i_size = 0;

    self = PyObject_New( MediaControl, &MediaControl_Type );

    fprintf (stderr, "Instantiating mediacontrol\n");
    if( PyArg_ParseTuple( args, "O", &py_param ) )
    {
        if( PyObject_TypeCheck( py_param, &vlcInstance_Type ) == 1 )
        {
            p_instance = ((vlcInstance*)py_param)->p_instance;
        }
        else
        {
            Py_ssize_t i_index;

            Py_INCREF( py_param );
            if( ! PySequence_Check( py_param ) )
            {
                PyErr_SetString( PyExc_TypeError, "Parameter must be a vlc.Instance or a sequence of strings." );
                Py_DECREF( py_param );
                return NULL;
            }
            i_size = PySequence_Size( py_param );
            ppsz_args = malloc( ( i_size + 1 ) * sizeof( char * ) );
            if( ! ppsz_args )
            {
                PyErr_SetString( PyExc_MemoryError, "Out of memory" );
                Py_DECREF( py_param );
                return NULL;
            }

            for ( i_index = 0; i_index < i_size; i_index++ )
            {
                ppsz_args[i_index] =
                    strdup( PyString_AsString( PyObject_Str(
                                                   PySequence_GetItem( py_param,
                                                                       i_index ) ) ) );
            }
            ppsz_args[i_size] = NULL;
            Py_DECREF( py_param );
        }
    }
    else
    {
        /* No arguments were given. Clear the exception raised
           by PyArg_ParseTuple. */
        PyErr_Clear( );
    }

    Py_BEGIN_ALLOW_THREADS
    MC_TRY;
    if( p_instance )
    {
        self->mc = mediacontrol_new_from_instance( p_instance, exception );
        Py_INCREF( py_param );
        self->vlc_instance = ( vlcInstance* ) py_param;
    }
    else
    {
        self->mc = mediacontrol_new( i_size, ppsz_args, exception );
        self->vlc_instance = PyObject_New( vlcInstance, &vlcInstance_Type );
        self->vlc_instance->p_instance = mediacontrol_get_libvlc_instance( LIBVLC_MC(self) );
    }
    MC_EXCEPT;
    Py_END_ALLOW_THREADS

    Py_INCREF( self );
    return ( PyObject * )self;
}
Example #14
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;
}
 PythonSequenceIterator(PyObject* sequence, Py_ssize_t position):
   m_sequence(sequence), m_position(position) {
   assert(PySequence_Check(m_sequence));
   assert(m_position >= 0);
   assert(m_position <= PySequence_Size(m_sequence));
 }
Example #16
0
 bool IsSequence (void) const
 {
     return PySequence_Check (Get()) != 0;
 }
Example #17
0
PyObject* JPy_create_jvm(PyObject* self, PyObject* args, PyObject* kwds)
{
    static char* keywords[] = {"options", NULL};
    PyObject*   options;
    Py_ssize_t  optionCount;
    PyObject*   option;
    JavaVMOption* jvmOptions;
    JavaVMInitArgs jvmInitArgs;
    jint        jvmErrorCode;
    JNIEnv*     jenv;
    Py_ssize_t  i;

    //printf("JPy_create_jvm: JPy_JVM=%p\n", JPy_JVM);

    options = NULL;
    if (!PyArg_ParseTupleAndKeywords(args, kwds, "O:create_jvm", keywords, &options)) {
        return NULL;
    }

    if (JPy_JVM != NULL) {
        JPy_DIAG_PRINT(JPy_DIAG_F_JVM + JPy_DIAG_F_ERR, "JPy_create_jvm: WARNING: Java VM is already running.\n");
        Py_DECREF(options);
        return Py_BuildValue("");
    }

    if (!PySequence_Check(options)) {
        PyErr_SetString(PyExc_ValueError, "create_jvm: argument 1 (options) must be a sequence of Java VM option strings");
        return NULL;
    }

    optionCount = PySequence_Length(options);
    if (optionCount == -1) {
        PyErr_SetString(PyExc_ValueError, "create_jvm: failed to determine sequence length of argument 1 (options)");
        return NULL;
    }

    jvmOptions = PyMem_New(JavaVMOption, optionCount);
    if (jvmOptions == NULL) {
        return PyErr_NoMemory();
    }

    for (i = 0; i < optionCount; i++) {
        option = PySequence_GetItem(options, i);
        if (option == NULL) {
            PyMem_Del(jvmOptions);
            return NULL;
        }
        jvmOptions[i].optionString = (char*) JPy_AS_UTF8(option);
        jvmOptions[i].extraInfo = NULL;
        JPy_DIAG_PRINT(JPy_DIAG_F_JVM, "JPy_create_jvm: jvmOptions[%d].optionString = '%s'\n", i, jvmOptions[i].optionString);
        if (jvmOptions[i].optionString == NULL) {
            PyMem_Del(jvmOptions);
            return NULL;
        }
        Py_DECREF(option);
    }

    jvmInitArgs.version = JPY_JNI_VERSION;
    jvmInitArgs.options = jvmOptions;
    jvmInitArgs.nOptions = (size_t) optionCount;
    jvmInitArgs.ignoreUnrecognized = 0;
    jvmErrorCode = JNI_CreateJavaVM(&JPy_JVM, (void**) &jenv, &jvmInitArgs);
    JPy_MustDestroyJVM = JNI_TRUE;

    JPy_DIAG_PRINT(JPy_DIAG_F_JVM, "JPy_create_jvm: res=%d, JPy_JVM=%p, jenv=%p, JPy_MustDestroyJVM=%d\n", jvmErrorCode, JPy_JVM, jenv, JPy_MustDestroyJVM);

    PyMem_Del(jvmOptions);

    if (jvmErrorCode != JNI_OK) {
        JPy_DIAG_PRINT(JPy_DIAG_F_JVM + JPy_DIAG_F_ERR,
                       "JPy_create_jvm: INTERNAL ERROR: Failed to create Java VM (JNI error code %d). Possible reasons are:\n"
                       "* The Java heap space setting is too high (option -Xmx). Try '256M' first, then increment.\n"
                       "* The JVM shared library (Unix: libjvm.so, Windows: jvm.dll) cannot be found or cannot be loaded.\n"
                       "  Make sure the shared library can be found via the 'PATH' environment variable.\n"
                       "  Also make sure that the JVM is compiled for the same architecture as Python.\n",
                       jvmErrorCode);
        PyErr_SetString(PyExc_RuntimeError, "jpy: failed to create Java VM");
        return NULL;
    }

    if (JPy_InitGlobalVars(jenv) < 0) {
        return NULL;
    }

    return Py_BuildValue("");
}
Example #18
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;
}
Example #19
0
NPY_NO_EXPORT int
PyArray_DTypeFromObjectHelper(PyObject *obj, int maxdims,
                              PyArray_Descr **out_dtype, int string_type)
{
    int i, size;
    PyArray_Descr *dtype = NULL;
    PyObject *ip;
    Py_buffer buffer_view;
    /* types for sequence handling */
    PyObject ** objects;
    PyObject * seq;
    PyTypeObject * common_type;

    /* Check if it's an ndarray */
    if (PyArray_Check(obj)) {
        dtype = PyArray_DESCR((PyArrayObject *)obj);
        Py_INCREF(dtype);
        goto promote_types;
    }

    /* See if it's a python None */
    if (obj == Py_None) {
        dtype = PyArray_DescrFromType(NPY_OBJECT);
        if (dtype == NULL) {
            goto fail;
        }
        Py_INCREF(dtype);
        goto promote_types;
    }
    /* Check if it's a NumPy scalar */
    else if (PyArray_IsScalar(obj, Generic)) {
        if (!string_type) {
            dtype = PyArray_DescrFromScalar(obj);
            if (dtype == NULL) {
                goto fail;
            }
        }
        else {
            int itemsize;
            PyObject *temp;

            if (string_type == NPY_STRING) {
                if ((temp = PyObject_Str(obj)) == NULL) {
                    return -1;
                }
#if defined(NPY_PY3K)
    #if PY_VERSION_HEX >= 0x03030000
                itemsize = PyUnicode_GetLength(temp);
    #else
                itemsize = PyUnicode_GET_SIZE(temp);
    #endif
#else
                itemsize = PyString_GET_SIZE(temp);
#endif
            }
            else if (string_type == NPY_UNICODE) {
#if defined(NPY_PY3K)
                if ((temp = PyObject_Str(obj)) == NULL) {
#else
                if ((temp = PyObject_Unicode(obj)) == NULL) {
#endif
                    return -1;
                }
                itemsize = PyUnicode_GET_DATA_SIZE(temp);
#ifndef Py_UNICODE_WIDE
                itemsize <<= 1;
#endif
            }
            else {
                goto fail;
            }
            Py_DECREF(temp);
            if (*out_dtype != NULL &&
                    (*out_dtype)->type_num == string_type &&
                    (*out_dtype)->elsize >= itemsize) {
                return 0;
            }
            dtype = PyArray_DescrNewFromType(string_type);
            if (dtype == NULL) {
                goto fail;
            }
            dtype->elsize = itemsize;
        }
        goto promote_types;
    }

    /* Check if it's a Python scalar */
    dtype = _array_find_python_scalar_type(obj);
    if (dtype != NULL) {
        if (string_type) {
            int itemsize;
            PyObject *temp;

            if (string_type == NPY_STRING) {
                if ((temp = PyObject_Str(obj)) == NULL) {
                    return -1;
                }
#if defined(NPY_PY3K)
    #if PY_VERSION_HEX >= 0x03030000
                itemsize = PyUnicode_GetLength(temp);
    #else
                itemsize = PyUnicode_GET_SIZE(temp);
    #endif
#else
                itemsize = PyString_GET_SIZE(temp);
#endif
            }
            else if (string_type == NPY_UNICODE) {
#if defined(NPY_PY3K)
                if ((temp = PyObject_Str(obj)) == NULL) {
#else
                if ((temp = PyObject_Unicode(obj)) == NULL) {
#endif
                    return -1;
                }
                itemsize = PyUnicode_GET_DATA_SIZE(temp);
#ifndef Py_UNICODE_WIDE
                itemsize <<= 1;
#endif
            }
            else {
                goto fail;
            }
            Py_DECREF(temp);
            if (*out_dtype != NULL &&
                    (*out_dtype)->type_num == string_type &&
                    (*out_dtype)->elsize >= itemsize) {
                return 0;
            }
            dtype = PyArray_DescrNewFromType(string_type);
            if (dtype == NULL) {
                goto fail;
            }
            dtype->elsize = itemsize;
        }
        goto promote_types;
    }

    /* Check if it's an ASCII string */
    if (PyBytes_Check(obj)) {
        int itemsize = PyString_GET_SIZE(obj);

        /* If it's already a big enough string, don't bother type promoting */
        if (*out_dtype != NULL &&
                        (*out_dtype)->type_num == NPY_STRING &&
                        (*out_dtype)->elsize >= itemsize) {
            return 0;
        }
        dtype = PyArray_DescrNewFromType(NPY_STRING);
        if (dtype == NULL) {
            goto fail;
        }
        dtype->elsize = itemsize;
        goto promote_types;
    }

    /* Check if it's a Unicode string */
    if (PyUnicode_Check(obj)) {
        int itemsize = PyUnicode_GET_DATA_SIZE(obj);
#ifndef Py_UNICODE_WIDE
        itemsize <<= 1;
#endif

        /*
         * If it's already a big enough unicode object,
         * don't bother type promoting
         */
        if (*out_dtype != NULL &&
                        (*out_dtype)->type_num == NPY_UNICODE &&
                        (*out_dtype)->elsize >= itemsize) {
            return 0;
        }
        dtype = PyArray_DescrNewFromType(NPY_UNICODE);
        if (dtype == NULL) {
            goto fail;
        }
        dtype->elsize = itemsize;
        goto promote_types;
    }

    /* PEP 3118 buffer interface */
    if (PyObject_CheckBuffer(obj) == 1) {
        memset(&buffer_view, 0, sizeof(Py_buffer));
        if (PyObject_GetBuffer(obj, &buffer_view,
                               PyBUF_FORMAT|PyBUF_STRIDES) == 0 ||
            PyObject_GetBuffer(obj, &buffer_view, PyBUF_FORMAT) == 0) {

            PyErr_Clear();
            dtype = _descriptor_from_pep3118_format(buffer_view.format);
            PyBuffer_Release(&buffer_view);
            if (dtype) {
                goto promote_types;
            }
        }
        else if (PyObject_GetBuffer(obj, &buffer_view, PyBUF_STRIDES) == 0 ||
                 PyObject_GetBuffer(obj, &buffer_view, PyBUF_SIMPLE) == 0) {

            PyErr_Clear();
            dtype = PyArray_DescrNewFromType(NPY_VOID);
            dtype->elsize = buffer_view.itemsize;
            PyBuffer_Release(&buffer_view);
            goto promote_types;
        }
        else {
            PyErr_Clear();
        }
    }

    /* The array interface */
    ip = PyArray_GetAttrString_SuppressException(obj, "__array_interface__");
    if (ip != NULL) {
        if (PyDict_Check(ip)) {
            PyObject *typestr;
#if defined(NPY_PY3K)
            PyObject *tmp = NULL;
#endif
            typestr = PyDict_GetItemString(ip, "typestr");
#if defined(NPY_PY3K)
            /* Allow unicode type strings */
            if (PyUnicode_Check(typestr)) {
                tmp = PyUnicode_AsASCIIString(typestr);
                typestr = tmp;
            }
#endif
            if (typestr && PyBytes_Check(typestr)) {
                dtype =_array_typedescr_fromstr(PyBytes_AS_STRING(typestr));
#if defined(NPY_PY3K)
                if (tmp == typestr) {
                    Py_DECREF(tmp);
                }
#endif
                Py_DECREF(ip);
                if (dtype == NULL) {
                    goto fail;
                }
                goto promote_types;
            }
        }
        Py_DECREF(ip);
    }

    /* The array struct interface */
    ip = PyArray_GetAttrString_SuppressException(obj, "__array_struct__");
    if (ip != NULL) {
        PyArrayInterface *inter;
        char buf[40];

        if (NpyCapsule_Check(ip)) {
            inter = (PyArrayInterface *)NpyCapsule_AsVoidPtr(ip);
            if (inter->two == 2) {
                PyOS_snprintf(buf, sizeof(buf),
                        "|%c%d", inter->typekind, inter->itemsize);
                dtype = _array_typedescr_fromstr(buf);
                Py_DECREF(ip);
                if (dtype == NULL) {
                    goto fail;
                }
                goto promote_types;
            }
        }
        Py_DECREF(ip);
    }

    /* The old buffer interface */
#if !defined(NPY_PY3K)
    if (PyBuffer_Check(obj)) {
        dtype = PyArray_DescrNewFromType(NPY_VOID);
        if (dtype == NULL) {
            goto fail;
        }
        dtype->elsize = Py_TYPE(obj)->tp_as_sequence->sq_length(obj);
        PyErr_Clear();
        goto promote_types;
    }
#endif

    /* The __array__ attribute */
    ip = PyArray_GetAttrString_SuppressException(obj, "__array__");
    if (ip != NULL) {
        Py_DECREF(ip);
        ip = PyObject_CallMethod(obj, "__array__", NULL);
        if(ip && PyArray_Check(ip)) {
            dtype = PyArray_DESCR((PyArrayObject *)ip);
            Py_INCREF(dtype);
            Py_DECREF(ip);
            goto promote_types;
        }
        Py_XDECREF(ip);
        if (PyErr_Occurred()) {
            goto fail;
        }
    }

    /* Not exactly sure what this is about... */
#if !defined(NPY_PY3K)
    if (PyInstance_Check(obj)) {
        dtype = _use_default_type(obj);
        if (dtype == NULL) {
            goto fail;
        }
        else {
            goto promote_types;
        }
    }
#endif

    /*
     * If we reached the maximum recursion depth without hitting one
     * of the above cases, the output dtype should be OBJECT
     */
    if (maxdims == 0 || !PySequence_Check(obj)) {
        if (*out_dtype == NULL || (*out_dtype)->type_num != NPY_OBJECT) {
            Py_XDECREF(*out_dtype);
            *out_dtype = PyArray_DescrFromType(NPY_OBJECT);
            if (*out_dtype == NULL) {
                return -1;
            }
        }
        return 0;
    }

    /*
     * fails if convertable to list but no len is defined which some libraries
     * require to get object arrays
     */
    size = PySequence_Size(obj);
    if (size < 0) {
        goto fail;
    }

    /* Recursive case, first check the sequence contains only one type */
    seq = PySequence_Fast(obj, "Could not convert object to sequence");
    if (seq == NULL) {
        goto fail;
    }
    objects = PySequence_Fast_ITEMS(seq);
    common_type = size > 0 ? Py_TYPE(objects[0]) : NULL;
    for (i = 1; i < size; ++i) {
        if (Py_TYPE(objects[i]) != common_type) {
            common_type = NULL;
            break;
        }
    }

    /* all types are the same and scalar, one recursive call is enough */
    if (common_type != NULL && !string_type &&
            (common_type == &PyFloat_Type ||
/* TODO: we could add longs if we add a range check */
#if !defined(NPY_PY3K)
             common_type == &PyInt_Type ||
#endif
             common_type == &PyBool_Type ||
             common_type == &PyComplex_Type)) {
        size = 1;
    }

    /* Recursive call for each sequence item */
    for (i = 0; i < size; ++i) {
        int res = PyArray_DTypeFromObjectHelper(objects[i], maxdims - 1,
                                                out_dtype, string_type);
        if (res < 0) {
            Py_DECREF(seq);
            goto fail;
        }
        else if (res > 0) {
            Py_DECREF(seq);
            return res;
        }
    }

    Py_DECREF(seq);

    return 0;


promote_types:
    /* Set 'out_dtype' if it's NULL */
    if (*out_dtype == NULL) {
        if (!string_type && dtype->type_num == NPY_STRING) {
            Py_DECREF(dtype);
            return RETRY_WITH_STRING;
        }
        if (!string_type && dtype->type_num == NPY_UNICODE) {
            Py_DECREF(dtype);
            return RETRY_WITH_UNICODE;
        }
        *out_dtype = dtype;
        return 0;
    }
    /* Do type promotion with 'out_dtype' */
    else {
        PyArray_Descr *res_dtype = PyArray_PromoteTypes(dtype, *out_dtype);
        Py_DECREF(dtype);
        if (res_dtype == NULL) {
            return -1;
        }
        if (!string_type &&
                res_dtype->type_num == NPY_UNICODE &&
                (*out_dtype)->type_num != NPY_UNICODE) {
            Py_DECREF(res_dtype);
            return RETRY_WITH_UNICODE;
        }
        if (!string_type &&
                res_dtype->type_num == NPY_STRING &&
                (*out_dtype)->type_num != NPY_STRING) {
            Py_DECREF(res_dtype);
            return RETRY_WITH_STRING;
        }
        Py_DECREF(*out_dtype);
        *out_dtype = res_dtype;
        return 0;
    }

fail:
    Py_XDECREF(*out_dtype);
    *out_dtype = NULL;
    return -1;
}

#undef RETRY_WITH_STRING
#undef RETRY_WITH_UNICODE

/* new reference */
NPY_NO_EXPORT PyArray_Descr *
_array_typedescr_fromstr(char *c_str)
{
    PyArray_Descr *descr = NULL;
    PyObject *stringobj = PyString_FromString(c_str);

    if (stringobj == NULL) {
        return NULL;
    }
    if (PyArray_DescrConverter(stringobj, &descr) != NPY_SUCCEED) {
        Py_DECREF(stringobj);
        return NULL;
    }
    Py_DECREF(stringobj);
    return descr;
}


NPY_NO_EXPORT char *
index2ptr(PyArrayObject *mp, npy_intp i)
{
    npy_intp dim0;

    if (PyArray_NDIM(mp) == 0) {
        PyErr_SetString(PyExc_IndexError, "0-d arrays can't be indexed");
        return NULL;
    }
    dim0 = PyArray_DIMS(mp)[0];
    if (check_and_adjust_index(&i, dim0, 0, NULL) < 0)
        return NULL;
    if (i == 0) {
        return PyArray_DATA(mp);
    }
    return PyArray_BYTES(mp)+i*PyArray_STRIDES(mp)[0];
}
Example #20
0
static PyObject*
mseed_store_traces (PyObject *dummy, PyObject *args)
{
    char          *filename;
    MSTrace       *mst = NULL;
    PyObject      *array = NULL;
    PyObject      *in_traces = NULL;
    PyObject      *in_trace = NULL;
    PyArrayObject *contiguous_array = NULL;
    int           i;
    char          *network, *station, *location, *channel;
    char          mstype;
    int           msdetype;
    int           psamples, precords;
    int           numpytype;
    int           length;
    FILE          *outfile;

    if (!PyArg_ParseTuple(args, "Os", &in_traces, &filename)) {
        PyErr_SetString(MSeedError, "usage store_traces(traces, filename)" );
        return NULL;
    }
    if (!PySequence_Check( in_traces )) {
        PyErr_SetString(MSeedError, "Traces is not of sequence type." );
        return NULL;
    }

    outfile = fopen(filename, "w" );
    if (outfile == NULL) {
        PyErr_SetString(MSeedError, "Error opening file.");
        return NULL;
    }

    for (i=0; i<PySequence_Length(in_traces); i++) {
        
        in_trace = PySequence_GetItem(in_traces, i);
        if (!PyTuple_Check(in_trace)) {
            PyErr_SetString(MSeedError, "Trace record must be a tuple of (network, station, location, channel, starttime, endtime, samprate, data)." );
            Py_DECREF(in_trace);
            return NULL;
        }
        mst = mst_init (NULL);
        
        if (!PyArg_ParseTuple(in_trace, "ssssLLdO",
                                    &network,
                                    &station,
                                    &location,
                                    &channel,
                                    &(mst->starttime),
                                    &(mst->endtime),
                                    &(mst->samprate),
                                    &array )) {
            PyErr_SetString(MSeedError, "Trace record must be a tuple of (network, station, location, channel, starttime, endtime, samprate, data)." );
            mst_free( &mst );  
            Py_DECREF(in_trace);
            return NULL;
        }

        strncpy( mst->network, network, 10);
        strncpy( mst->station, station, 10);
        strncpy( mst->location, location, 10);
        strncpy( mst->channel, channel, 10);
        mst->network[10] = '\0';
        mst->station[10] = '\0';
        mst->location[10] ='\0';
        mst->channel[10] = '\0';
        
        if (!PyArray_Check(array)) {
            PyErr_SetString(MSeedError, "Data must be given as NumPy array." );
            mst_free( &mst );  
            Py_DECREF(in_trace);
            return NULL;
        }
        numpytype = PyArray_TYPE(array);
        switch (numpytype) {
                case NPY_INT32:
                    assert( ms_samplesize('i') == 4 );
                    mstype = 'i';
                    msdetype = DE_STEIM1;
                    break;
                case NPY_INT8:
                    assert( ms_samplesize('a') == 1 );
                    mstype = 'a';
                    msdetype = DE_ASCII;
                    break;
                case NPY_FLOAT32:
                    assert( ms_samplesize('f') == 4 );
                    mstype = 'f';
                    msdetype = DE_FLOAT32;
                    break;
                case NPY_FLOAT64:
                    assert( ms_samplesize('d') == 8 );
                    mstype = 'd';
                    msdetype = DE_FLOAT64;
                    break;
                default:
                    PyErr_SetString(MSeedError, "Data must be of type float64, float32, int32 or int8.");
                    mst_free( &mst );  
                    Py_DECREF(in_trace);
                    return NULL;
            }
        mst->sampletype = mstype;

        contiguous_array = PyArray_GETCONTIGUOUS((PyArrayObject*)array);

        length = PyArray_SIZE(contiguous_array);
        mst->numsamples = length;
        mst->samplecnt = length;

        mst->datasamples = calloc(length,ms_samplesize(mstype));
        memcpy(mst->datasamples, PyArray_DATA(contiguous_array), length*ms_samplesize(mstype));
        Py_DECREF(contiguous_array);

        precords = mst_pack (mst, &record_handler, outfile, 4096, msdetype,
                                     1, &psamples, 1, 0, NULL);
        mst_free( &mst );
        Py_DECREF(in_trace);
    }
    fclose( outfile );

    Py_INCREF(Py_None);
    return Py_None;
}
static int convertTo_QList_0600QPair_2400_2400(PyObject *sipPy,void **sipCppPtrV,int *sipIsErr,PyObject *sipTransferObj)
{
    QList<QPair<qreal,qreal> > **sipCppPtr = reinterpret_cast<QList<QPair<qreal,qreal> > **>(sipCppPtrV);

#line 441 "/home/vikky/Desktop/DVCS/stuff/scrapy/soft/PyQt-x11-gpl-4.11.4/sip/QtCore/qlist.sip"
    SIP_SSIZE_T len;

    // Check the type if that is all that is required.
    if (sipIsErr == NULL)
    {
        if (!PySequence_Check(sipPy) || (len = PySequence_Size(sipPy)) < 0)
            return 0;

        for (SIP_SSIZE_T i = 0; i < len; ++i)
        {
            PyObject *seq = PySequence_ITEM(sipPy, i);

            if (!seq || !PySequence_Check(seq) || PySequence_Size(seq) != 2)
            {
                Py_XDECREF(seq);
                return 0;
            }
        }

        return 1;
    }

    QList<QPair<qreal, qreal> > *ql = new QList<QPair<qreal, qreal> >;
    len = PySequence_Size(sipPy);
 
    for (SIP_SSIZE_T i = 0; i < len; ++i)
    {
        PyObject *seq = PySequence_ITEM(sipPy, i);
        PyObject *itm0 = PySequence_ITEM(seq, 0);
        PyObject *itm1 = PySequence_ITEM(seq, 1);

        Py_DECREF(seq);

        if (!itm0 || !itm1)
        {
            Py_XDECREF(itm0);
            Py_XDECREF(itm1);

            delete ql;
            *sipIsErr = 1;

            return 0;
        }

        qreal first = PyFloat_AsDouble(itm0);
        qreal second = PyFloat_AsDouble(itm1);
 
        Py_DECREF(itm0);
        Py_DECREF(itm1);

        ql->append(QPair<qreal, qreal>(first, second));
    }
 
    *sipCppPtr = ql;
 
    return sipGetState(sipTransferObj);
#line 128 "/home/vikky/Desktop/DVCS/stuff/scrapy/soft/PyQt-x11-gpl-4.11.4/QtCore/sipQtCoreQList0600QPair24002400.cpp"
}
Example #22
0
NPY_NO_EXPORT int
PyArray_DTypeFromObjectHelper(PyObject *obj, int maxdims,
                              PyArray_Descr **out_dtype, int string_type)
{
    int i, size;
    PyArray_Descr *dtype = NULL;
    PyObject *ip;
#if PY_VERSION_HEX >= 0x02060000
    Py_buffer buffer_view;
#endif

    /* Check if it's an ndarray */
    if (PyArray_Check(obj)) {
        dtype = PyArray_DESCR((PyArrayObject *)obj);
        Py_INCREF(dtype);
        goto promote_types;
    }

    /* Check if it's a NumPy scalar */
    if (PyArray_IsScalar(obj, Generic)) {
        if (!string_type) {
            dtype = PyArray_DescrFromScalar(obj);
            if (dtype == NULL) {
                goto fail;
            }
        }
        else {
            int itemsize;
            PyObject *temp;

            if (string_type == NPY_STRING) {
                if ((temp = PyObject_Str(obj)) == NULL) {
                    return -1;
                }
#if defined(NPY_PY3K)
    #if PY_VERSION_HEX >= 0x03030000
                itemsize = PyUnicode_GetLength(temp);
    #else
                itemsize = PyUnicode_GET_SIZE(temp);
    #endif
#else
                itemsize = PyString_GET_SIZE(temp);
#endif
            }
            else if (string_type == NPY_UNICODE) {
#if defined(NPY_PY3K)
                if ((temp = PyObject_Str(obj)) == NULL) {
#else
                if ((temp = PyObject_Unicode(obj)) == NULL) {
#endif
                    return -1;
                }
                itemsize = PyUnicode_GET_DATA_SIZE(temp);
#ifndef Py_UNICODE_WIDE
                itemsize <<= 1;
#endif
            }
            else {
                goto fail;
            }
            Py_DECREF(temp);
            if (*out_dtype != NULL &&
                    (*out_dtype)->type_num == string_type &&
                    (*out_dtype)->elsize >= itemsize) {
                return 0;
            }
            dtype = PyArray_DescrNewFromType(string_type);
            if (dtype == NULL) {
                goto fail;
            }
            dtype->elsize = itemsize;
        }
        goto promote_types;
    }

    /* Check if it's a Python scalar */
    dtype = _array_find_python_scalar_type(obj);
    if (dtype != NULL) {
        if (string_type) {
            int itemsize;
            PyObject *temp;

            if (string_type == NPY_STRING) {
                if ((temp = PyObject_Str(obj)) == NULL) {
                    return -1;
                }
#if defined(NPY_PY3K)
    #if PY_VERSION_HEX >= 0x03030000
                itemsize = PyUnicode_GetLength(temp);
    #else
                itemsize = PyUnicode_GET_SIZE(temp);
    #endif
#else
                itemsize = PyString_GET_SIZE(temp);
#endif
            }
            else if (string_type == NPY_UNICODE) {
#if defined(NPY_PY3K)
                if ((temp = PyObject_Str(obj)) == NULL) {
#else
                if ((temp = PyObject_Unicode(obj)) == NULL) {
#endif
                    return -1;
                }
                itemsize = PyUnicode_GET_DATA_SIZE(temp);
#ifndef Py_UNICODE_WIDE
                itemsize <<= 1;
#endif
            }
            else {
                goto fail;
            }
            Py_DECREF(temp);
            if (*out_dtype != NULL &&
                    (*out_dtype)->type_num == string_type &&
                    (*out_dtype)->elsize >= itemsize) {
                return 0;
            }
            dtype = PyArray_DescrNewFromType(string_type);
            if (dtype == NULL) {
                goto fail;
            }
            dtype->elsize = itemsize;
        }
        goto promote_types;
    }

    /* Check if it's an ASCII string */
    if (PyBytes_Check(obj)) {
        int itemsize = PyString_GET_SIZE(obj);

        /* If it's already a big enough string, don't bother type promoting */
        if (*out_dtype != NULL &&
                        (*out_dtype)->type_num == NPY_STRING &&
                        (*out_dtype)->elsize >= itemsize) {
            return 0;
        }
        dtype = PyArray_DescrNewFromType(NPY_STRING);
        if (dtype == NULL) {
            goto fail;
        }
        dtype->elsize = itemsize;
        goto promote_types;
    }

    /* Check if it's a Unicode string */
    if (PyUnicode_Check(obj)) {
        int itemsize = PyUnicode_GET_DATA_SIZE(obj);
#ifndef Py_UNICODE_WIDE
        itemsize <<= 1;
#endif

        /*
         * If it's already a big enough unicode object,
         * don't bother type promoting
         */
        if (*out_dtype != NULL &&
                        (*out_dtype)->type_num == NPY_UNICODE &&
                        (*out_dtype)->elsize >= itemsize) {
            return 0;
        }
        dtype = PyArray_DescrNewFromType(NPY_UNICODE);
        if (dtype == NULL) {
            goto fail;
        }
        dtype->elsize = itemsize;
        goto promote_types;
    }

#if PY_VERSION_HEX >= 0x02060000
    /* PEP 3118 buffer interface */
    memset(&buffer_view, 0, sizeof(Py_buffer));
    if (PyObject_GetBuffer(obj, &buffer_view, PyBUF_FORMAT|PyBUF_STRIDES) == 0 ||
        PyObject_GetBuffer(obj, &buffer_view, PyBUF_FORMAT) == 0) {

        PyErr_Clear();
        dtype = _descriptor_from_pep3118_format(buffer_view.format);
        PyBuffer_Release(&buffer_view);
        if (dtype) {
            goto promote_types;
        }
    }
    else if (PyObject_GetBuffer(obj, &buffer_view, PyBUF_STRIDES) == 0 ||
             PyObject_GetBuffer(obj, &buffer_view, PyBUF_SIMPLE) == 0) {

        PyErr_Clear();
        dtype = PyArray_DescrNewFromType(NPY_VOID);
        dtype->elsize = buffer_view.itemsize;
        PyBuffer_Release(&buffer_view);
        goto promote_types;
    }
    else {
        PyErr_Clear();
    }
#endif

    /* The array interface */
    ip = PyObject_GetAttrString(obj, "__array_interface__");
    if (ip != NULL) {
        if (PyDict_Check(ip)) {
            PyObject *typestr;
#if defined(NPY_PY3K)
            PyObject *tmp = NULL;
#endif
            typestr = PyDict_GetItemString(ip, "typestr");
#if defined(NPY_PY3K)
            /* Allow unicode type strings */
            if (PyUnicode_Check(typestr)) {
                tmp = PyUnicode_AsASCIIString(typestr);
                typestr = tmp;
            }
#endif
            if (typestr && PyBytes_Check(typestr)) {
                dtype =_array_typedescr_fromstr(PyBytes_AS_STRING(typestr));
#if defined(NPY_PY3K)
                if (tmp == typestr) {
                    Py_DECREF(tmp);
                }
#endif
                Py_DECREF(ip);
                if (dtype == NULL) {
                    goto fail;
                }
                goto promote_types;
            }
        }
        Py_DECREF(ip);
    }
    else {
        PyErr_Clear();
    }

    /* The array struct interface */
    ip = PyObject_GetAttrString(obj, "__array_struct__");
    if (ip != NULL) {
        PyArrayInterface *inter;
        char buf[40];

        if (NpyCapsule_Check(ip)) {
            inter = (PyArrayInterface *)NpyCapsule_AsVoidPtr(ip);
            if (inter->two == 2) {
                PyOS_snprintf(buf, sizeof(buf),
                        "|%c%d", inter->typekind, inter->itemsize);
                dtype = _array_typedescr_fromstr(buf);
                Py_DECREF(ip);
                if (dtype == NULL) {
                    goto fail;
                }
                goto promote_types;
            }
        }
        Py_DECREF(ip);
    }
    else {
        PyErr_Clear();
    }

    /* The old buffer interface */
#if !defined(NPY_PY3K)
    if (PyBuffer_Check(obj)) {
        dtype = PyArray_DescrNewFromType(NPY_VOID);
        if (dtype == NULL) {
            goto fail;
        }
        dtype->elsize = Py_TYPE(obj)->tp_as_sequence->sq_length(obj);
        PyErr_Clear();
        goto promote_types;
    }
#endif

    /* The __array__ attribute */
    if (PyObject_HasAttrString(obj, "__array__")) {
        ip = PyObject_CallMethod(obj, "__array__", NULL);
        if(ip && PyArray_Check(ip)) {
            dtype = PyArray_DESCR((PyArrayObject *)ip);
            Py_INCREF(dtype);
            Py_DECREF(ip);
            goto promote_types;
        }
        Py_XDECREF(ip);
        if (PyErr_Occurred()) {
            goto fail;
        }
    }

    /* Not exactly sure what this is about... */
#if !defined(NPY_PY3K)
    if (PyInstance_Check(obj)) {
        dtype = _use_default_type(obj);
        if (dtype == NULL) {
            goto fail;
        }
        else {
            goto promote_types;
        }
    }
#endif

    /*
     * If we reached the maximum recursion depth without hitting one
     * of the above cases, the output dtype should be OBJECT
     */
    if (maxdims == 0 || !PySequence_Check(obj)) {
        if (*out_dtype == NULL || (*out_dtype)->type_num != NPY_OBJECT) {
            Py_XDECREF(*out_dtype);
            *out_dtype = PyArray_DescrFromType(NPY_OBJECT);
            if (*out_dtype == NULL) {
                return -1;
            }
        }
        return 0;
    }

    /* Recursive case */
    size = PySequence_Size(obj);
    if (size < 0) {
        goto fail;
    }
    /* Recursive call for each sequence item */
    for (i = 0; i < size; ++i) {
        int res;
        ip = PySequence_GetItem(obj, i);
        if (ip == NULL) {
            goto fail;
        }
        res = PyArray_DTypeFromObjectHelper(ip, maxdims - 1,
                                            out_dtype, string_type);
        if (res < 0) {
            Py_DECREF(ip);
            goto fail;
        }
        else if (res > 0) {
            Py_DECREF(ip);
            return res;
        }
        Py_DECREF(ip);
    }

    return 0;


promote_types:
    /* Set 'out_dtype' if it's NULL */
    if (*out_dtype == NULL) {
        if (!string_type && dtype->type_num == NPY_STRING) {
            Py_DECREF(dtype);
            return RETRY_WITH_STRING;
        }
        if (!string_type && dtype->type_num == NPY_UNICODE) {
            Py_DECREF(dtype);
            return RETRY_WITH_UNICODE;
        }
        *out_dtype = dtype;
        return 0;
    }
    /* Do type promotion with 'out_dtype' */
    else {
        PyArray_Descr *res_dtype = PyArray_PromoteTypes(dtype, *out_dtype);
        Py_DECREF(dtype);
        if (res_dtype == NULL) {
            return -1;
        }
        if (!string_type &&
                res_dtype->type_num == NPY_UNICODE &&
                (*out_dtype)->type_num != NPY_UNICODE) {
            Py_DECREF(res_dtype);
            return RETRY_WITH_UNICODE;
        }
        if (!string_type &&
                res_dtype->type_num == NPY_STRING &&
                (*out_dtype)->type_num != NPY_STRING) {
            Py_DECREF(res_dtype);
            return RETRY_WITH_STRING;
        }
        Py_DECREF(*out_dtype);
        *out_dtype = res_dtype;
        return 0;
    }

fail:
    Py_XDECREF(*out_dtype);
    *out_dtype = NULL;
    return -1;
}

#undef RETRY_WITH_STRING
#undef RETRY_WITH_UNICODE

/* new reference */
NPY_NO_EXPORT PyArray_Descr *
_array_typedescr_fromstr(char *c_str)
{
    PyArray_Descr *descr = NULL;
    PyObject *stringobj = PyString_FromString(c_str);

    if (stringobj == NULL) {
        return NULL;
    }
    if (PyArray_DescrConverter(stringobj, &descr) != NPY_SUCCEED) {
        Py_DECREF(stringobj);
        return NULL;
    }
    Py_DECREF(stringobj);
    return descr;
}

NPY_NO_EXPORT int
check_and_adjust_index(npy_intp *index, npy_intp max_item, int axis)
{
    /* Check that index is valid, taking into account negative indices */
    if ((*index < -max_item) || (*index >= max_item)) {
        /* Try to be as clear as possible about what went wrong. */
        if (axis >= 0) {
            PyErr_Format(PyExc_IndexError,
                         "index %"NPY_INTP_FMT" is out of bounds "
                         "for axis %d with size %"NPY_INTP_FMT,
                         *index, axis, max_item);
        } else {
            PyErr_Format(PyExc_IndexError,
                         "index %"NPY_INTP_FMT" is out of bounds "
                         "for size %"NPY_INTP_FMT,
                         *index, max_item);
        }
        return -1;
    }
    /* adjust negative indices */
    if (*index < 0) {
        *index += max_item;
    }
    return 0;
}

NPY_NO_EXPORT char *
index2ptr(PyArrayObject *mp, npy_intp i)
{
    npy_intp dim0;

    if (PyArray_NDIM(mp) == 0) {
        PyErr_SetString(PyExc_IndexError, "0-d arrays can't be indexed");
        return NULL;
    }
    dim0 = PyArray_DIMS(mp)[0];
    if (check_and_adjust_index(&i, dim0, 0) < 0)
        return NULL;
    if (i == 0) {
        return PyArray_DATA(mp);
    }
    return PyArray_BYTES(mp)+i*PyArray_STRIDES(mp)[0];
}
Example #23
0
static PyObject *
csv_writerow(WriterObj *self, PyObject *seq)
{
        DialectObj *dialect = self->dialect;
	int len, i;

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

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

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

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

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

		if (PyUnicode_Check(field)) {
			append_ok = join_append(self,
						PyUnicode_AS_UNICODE(field),
						&quoted, len == 1);
			Py_DECREF(field);
		}
		else if (field == Py_None) {
			append_ok = join_append(self, NULL,
                                    &quoted, len == 1);
			Py_DECREF(field);
		}
		else {
			PyObject *str;

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

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

	return PyObject_CallFunction(self->writeline,
				     "(u#)", self->rec,
				     self->rec_len);
}
Example #24
0
it is in 0.3 of the list\n\
\n\
";

static PyObject *clistfns_contents(PyObject *self, PyObject *args)
{
    int i;
    PyObject *items, *counts, *percentages;
    PyObject *countitems, *countitem;
    PyObject *key, *count, *perc;
    long c;
    double total;

    if(!PyArg_ParseTuple(args, "O", &items))
	return NULL;
    if(!PySequence_Check(items)) {
	PyErr_SetString(PyExc_TypeError, "expected mapping type");
	return NULL;
    }
    if((total = PySequence_Length(items)) == -1) {
	PyErr_SetString(PyExc_ValueError, "I couldn't get length of item.");
	return NULL;
    }
    
    counts = clistfns_count(self, args);
    if(!counts || PyErr_Occurred())
	return NULL;

    if(!(percentages = PyDict_New())) {
	Py_DECREF(counts);
	return NULL;
    }

    /* Loop through every element in counts, calculating the probabilities. */
    if(!(countitems = PyMapping_Items(counts))) {
	Py_DECREF(counts);
        Py_DECREF(percentages);
	return NULL;
    }

    /* Go through the loop, counting how often each item appears. */
    i = 0;
    while(1) {
	if(!(countitem = PyList_GetItem(countitems, i))) {
	    PyErr_Clear(); /* clear the exception set by PyList_GetItem */
	    break;         /* no more numbers */
        }
	key = PyTuple_GetItem(countitem, 0);
	count = PyTuple_GetItem(countitem, 1);
	c = PyInt_AsLong(count);
	perc = PyFloat_FromDouble((double)c / total);
	PyDict_SetItem(percentages, key, perc);
	Py_DECREF(perc);
	if(PyErr_Occurred())   /* PyDict_SetItem failed */
	    break;
	i++;
    }
    if(PyErr_Occurred()) {
	Py_DECREF(percentages);
	percentages = NULL;
    }
    Py_DECREF(countitems);
    Py_DECREF(counts);
    
    return percentages;
}
Example #25
0
static gboolean
marshal_value(CORBA_TypeCode tc, gconstpointer *val, PyObject *value)
{
    gboolean ret = FALSE;
    gint i;

    while (tc->kind == CORBA_tk_alias)
	tc = tc->subtypes[0];

    switch (tc->kind) {
    case CORBA_tk_null:
    case CORBA_tk_void:
	ret = (value == Py_None);
	break;
    case CORBA_tk_short:
	alignval(val, ORBIT_ALIGNOF_CORBA_SHORT);
	getval(val, CORBA_short) = PyInt_AsLong(value);
	advanceptr(val, sizeof(CORBA_short));
	if (!PyErr_Occurred()) ret = TRUE;
	break;
    case CORBA_tk_long:
	alignval(val, ORBIT_ALIGNOF_CORBA_LONG);
	getval(val, CORBA_long) = PyInt_AsLong(value);
	advanceptr(val, sizeof(CORBA_long));
	if (!PyErr_Occurred()) ret = TRUE;
	break;
    case CORBA_tk_ushort:
	alignval(val, ORBIT_ALIGNOF_CORBA_SHORT);
	getval(val, CORBA_unsigned_short) = PyInt_AsLong(value);
	advanceptr(val, sizeof(CORBA_unsigned_short));
	if (!PyErr_Occurred()) ret = TRUE;
	break;
    case CORBA_tk_ulong:
    case CORBA_tk_enum:
	alignval(val, ORBIT_ALIGNOF_CORBA_LONG);
	if (PyLong_Check(value))
	    getval(val, CORBA_unsigned_long) = PyLong_AsUnsignedLong(value);
	else
	    getval(val, CORBA_unsigned_long) = PyInt_AsLong(value);
	advanceptr(val, sizeof(CORBA_unsigned_long));
	if (!PyErr_Occurred()) ret = TRUE;
	break;
    case CORBA_tk_float:
	alignval(val, ORBIT_ALIGNOF_CORBA_FLOAT);
	getval(val, CORBA_float) = PyFloat_AsDouble(value);
	advanceptr(val, sizeof(CORBA_float));
	if (!PyErr_Occurred()) ret = TRUE;
	break;
    case CORBA_tk_double:
	alignval(val, ORBIT_ALIGNOF_CORBA_DOUBLE);
	getval(val, CORBA_double) = PyFloat_AsDouble(value);
	advanceptr(val, sizeof(CORBA_double));
	if (!PyErr_Occurred()) ret = TRUE;
	break;
    case CORBA_tk_boolean:
	getval(val, CORBA_boolean) = PyObject_IsTrue(value);
	advanceptr(val, sizeof(CORBA_boolean));
	if (!PyErr_Occurred()) ret = TRUE;
	break;
    case CORBA_tk_char:
	if (PyString_Check(value) && PyString_Size(value) == 1) {
	    getval(val, CORBA_char) = PyString_AsString(value)[0];
	    advanceptr(val, sizeof(CORBA_char));
	    ret = TRUE;
	}
	break;
    case CORBA_tk_octet:
	getval(val, CORBA_long) = PyInt_AsLong(value);
	advanceptr(val, sizeof(CORBA_octet));
	if (!PyErr_Occurred()) ret = TRUE;
	break;
    case CORBA_tk_any:
	if (PyObject_TypeCheck(value, &PyCORBA_Any_Type)) {
	    alignval(val, ORBIT_ALIGNOF_CORBA_ANY);
	    CORBA_any__copy(&getval(val, CORBA_any),
			    &((PyCORBA_Any *)value)->any);
	    advanceptr(val, sizeof(CORBA_any));
	    ret = TRUE;
	}
	break;
    case CORBA_tk_TypeCode:
	alignval(val, ORBIT_ALIGNOF_CORBA_POINTER);
	if (PyObject_TypeCheck(value, &PyCORBA_TypeCode_Type)) {
	    getval(val, CORBA_TypeCode) =
		(CORBA_TypeCode)CORBA_Object_duplicate(
			(CORBA_Object)((PyCORBA_TypeCode *)value)->tc, NULL);
	    ret = TRUE;
	}
	advanceptr(val, sizeof(CORBA_TypeCode));
	break;
    case CORBA_tk_Principal:
	g_warning("can't marshal Principal");
	break;
    case CORBA_tk_objref:
	alignval(val, ORBIT_ALIGNOF_CORBA_POINTER);
	if (value == Py_None) {
	    getval(val, CORBA_Object) = CORBA_OBJECT_NIL;
	    ret = TRUE;
	} else if (PyObject_TypeCheck(value, &PyCORBA_Object_Type)) {
	    CORBA_Object objref = ((PyCORBA_Object *)value)->objref;
	    getval(val, CORBA_Object) = CORBA_Object_duplicate(objref, NULL);
	    advanceptr(val, sizeof(CORBA_Object));
	    ret = TRUE;
	}
	break;
    case CORBA_tk_except:
    case CORBA_tk_struct:
	alignval(val, tc->c_align);
	for (i = 0; i < tc->sub_parts; i++) {
	    gchar *pyname;
	    PyObject *item;
	    gboolean itemret;

	    pyname = _pyorbit_escape_name(tc->subnames[i]);
	    item = PyObject_GetAttrString(value, pyname);
	    g_free(pyname);
	    if (!item) break;
	    itemret = marshal_value(tc->subtypes[i], val, item);
	    Py_DECREF(item);
	    if (!itemret) break;
	}
	if (i == tc->sub_parts) ret = TRUE; /* no error */
	break;
    case CORBA_tk_union: {
	PyObject *discrim, *subval;
	CORBA_TypeCode subtc;
	gconstpointer body;
	int sz = 0;

	discrim = PyObject_GetAttrString(value, "_d");
	if (!discrim) break;
	subval = PyObject_GetAttrString(value, "_v");
	if (!subval) break;

	alignval(val, MAX(tc->c_align, tc->discriminator->c_align));
	ret = marshal_value(tc->discriminator, val, discrim);
	if (!ret) {
	    Py_DECREF(discrim);
	    Py_DECREF(subval);
	    break;
	}

	/* calculate allocation info */
	for (i = 0; i < tc->sub_parts; i++) {
	    sz = MAX(sz, ORBit_gather_alloc_info(tc->subtypes[i]));
	}
	subtc = get_union_tc(tc, discrim);
	Py_DECREF(discrim);
	if (!subtc) {
	    Py_DECREF(subval);
	    break;
	}

	alignval(val, tc->c_align);
	body = *val;

	ret = marshal_value(subtc, &body, subval);
	Py_DECREF(subval);
	advanceptr(val, sz);
	break;
    }
    case CORBA_tk_string:
	if (PyString_Check(value)) {
	    /* error out if python string is longer than the bound
	     * specified in the string typecode. */
	    if (tc->length > 0 && PyString_Size(value) > tc->length)
		break;

	    alignval(val, ORBIT_ALIGNOF_CORBA_POINTER);
	    getval(val, CORBA_string) = CORBA_string_dup(PyString_AsString(value));
	    advanceptr(val, sizeof(CORBA_char *));
	    ret = TRUE;
	}
	break;
    case CORBA_tk_sequence: 
	if (PySequence_Check(value)) {
	    CORBA_sequence_CORBA_octet *sval;
	    gconstpointer seqval;
	    gint i;

	    /* error out if python sequence is longer than the bound
	     * specified in the sequence typecode. */
	    if (tc->length > 0 && PySequence_Length(value) > tc->length)
		break;

	    alignval(val, ORBIT_ALIGNOF_CORBA_SEQ);
	    sval = (CORBA_sequence_CORBA_octet *)*val;
	    if (CORBA_TypeCode_equal(tc->subtypes[0], TC_CORBA_octet, NULL)
		&& PyString_Check(value))
	    {
		Py_ssize_t length;
		char *buffer;
		if (PyString_AsStringAndSize(value, &buffer, &length) == -1)
		    ret = FALSE;
		else {
		    sval->_release = CORBA_TRUE;
		    sval->_buffer  = ORBit_alloc_tcval(TC_CORBA_octet, length);
		    memcpy(sval->_buffer, buffer, length);
		    sval->_length  = length;
		    ret = TRUE;
		}
	    } else {
		sval->_release = TRUE;
		sval->_length = PySequence_Length(value);
		sval->_buffer = ORBit_alloc_tcval(tc->subtypes[0], sval->_length);
		seqval = sval->_buffer;
		for (i = 0; i < sval->_length; i++) {
		    PyObject *item = PySequence_GetItem(value, i);
		    gboolean itemret;
		    
		    if (!item) break;
		    itemret = marshal_value(tc->subtypes[0], &seqval, item);
		    Py_DECREF(item);
		    if (!itemret) break;
		}
		if (i == sval->_length) ret = TRUE; /* no error */
	    }
	    advanceptr(val, sizeof(CORBA_sequence_CORBA_octet));
	}
	break;
    case CORBA_tk_array:
	if (PySequence_Check(value) &&
	    PySequence_Length(value) == tc->length) {
	    gint i;

	    for (i = 0; i < tc->length; i++) {
		PyObject *item = PySequence_GetItem(value, i);
		gboolean itemret;

		if (!item) break;
		itemret = marshal_value(tc->subtypes[0], val, item);
		Py_DECREF(item);
		if (!itemret) break;
	    }
	    if (i == tc->length) ret = TRUE; /* no error */
	}
	break;
    case CORBA_tk_longlong:
	alignval(val, ORBIT_ALIGNOF_CORBA_LONG_LONG);
	if (PyLong_Check(value))
	    getval(val, CORBA_long_long) = PyLong_AsLongLong(value);
	else
	    getval(val, CORBA_long_long) = PyInt_AsLong(value);
	advanceptr(val, sizeof(CORBA_long_long));
	if (!PyErr_Occurred()) ret = TRUE;
	break;
    case CORBA_tk_ulonglong:
	alignval(val, ORBIT_ALIGNOF_CORBA_LONG_LONG);
	if (PyLong_Check(value))
	    getval(val, CORBA_unsigned_long_long) =PyLong_AsUnsignedLongLong(value);
	else
	    getval(val, CORBA_unsigned_long_long) = PyInt_AsLong(value);
	advanceptr(val, sizeof(CORBA_unsigned_long_long));
	if (!PyErr_Occurred()) ret = TRUE;
	break;
    case CORBA_tk_longdouble:
	g_warning("can't marshal long double");
	break;
    case CORBA_tk_wchar:
	if (PyUnicode_Check(value) && PyUnicode_GetSize(value) == 1) {
	    alignval(val, ORBIT_ALIGNOF_CORBA_SHORT);
	    getval(val, CORBA_wchar) = PyUnicode_AsUnicode(value)[0];
	    advanceptr(val, sizeof(CORBA_wchar));
	    ret = TRUE;
	}
	break;
    case CORBA_tk_wstring:
	if (PyUnicode_Check(value)) {
	    int length = PyUnicode_GetSize(value);
	    Py_UNICODE *unicode = PyUnicode_AsUnicode(value);
	    CORBA_wchar *wstr;

	    /* error out if python unicode string is longer than the
	     * bound specified in the wstring typecode. */
	    if (tc->length > 0 && length > tc->length)
		break;

	    alignval(val, ORBIT_ALIGNOF_CORBA_POINTER);
	    wstr = CORBA_wstring_alloc(length);
	    getval(val, CORBA_wstring) = wstr;
	    for (i = 0; i < length; i++) {
		wstr[i] = unicode[i];
	    }
	    advanceptr(val, sizeof(CORBA_wchar *));
	    ret = TRUE;
	}
	break;
    default:
	g_warning("unhandled typecode: %s (kind=%d)", tc->repo_id, tc->kind);
	break;
    }
    if (!ret)
	PyErr_Clear();
    return ret;
}
Example #26
0
//-------------------------------------------------------------------------------------
int Sequence::seq_ass_slice(PyObject* self, Py_ssize_t index1, Py_ssize_t index2, PyObject* oterSeq)
{
	Sequence* seq = static_cast<Sequence*>(self);
	std::vector<PyObject*>& values = seq->getValues();
		
	// 是否是删除元素
	if (!oterSeq)
	{
		if (index1 < index2)
			values.erase(values.begin() + index1, values.begin() + index2);

		return 0;
	}

	// oterSeq必须是一个 sequence
	if (!PySequence_Check(oterSeq))
	{
		PyErr_Format(PyExc_TypeError, "Sequence slices can only be assigned to a sequence");
		PyErr_PrintEx(0);
		return -1;
	}

	if (oterSeq == seq)
	{
		PyErr_Format(PyExc_TypeError, "Sequence does not support assignment of itself to a slice of itself");
		PyErr_PrintEx(0);
		return -1;
	}

	int sz = values.size();
	int osz = PySequence_Size(oterSeq);

	// 保证index不会越界
	if (index1 > sz) index1 = sz;
	if (index1 < 0) index1 = 0;
	if (index2 > sz) index2 = sz;
	if (index2 < 0) index2 = 0;

	// 检查一下 看看有无错误类别
	for (int i = 0; i < osz; ++i)
	{
		PyObject* pyVal = PySequence_GetItem(oterSeq, i);
		bool ok = seq->isSameItemType(pyVal);
		Py_DECREF(pyVal);

		if (!ok)
		{
			PyErr_Format(PyExc_TypeError, "Array elements must be set to type %s (setting slice %d-%d)", "ss", index1, index2);
			PyErr_PrintEx(0);
			return -1;
		}
	}

	
	if (index1 < index2)
		values.erase(values.begin() + index1, values.begin() + index2);

	// 先让vector分配好内存
	values.insert(values.begin() + index1, osz, (PyObject*)NULL);
	for(int i = 0; i < osz; ++i)
	{
		PyObject* pyTemp = PySequence_GetItem(oterSeq, i);
		if(pyTemp == NULL)
		{
			PyErr_Format(PyExc_TypeError, "Sequence::seq_ass_slice::PySequence_GetItem %d is NULL.", i);
			PyErr_PrintEx(0);
		}
		
		values[index1 + i] = seq->createNewItemFromObj(pyTemp);
		Py_DECREF(pyTemp);
	}

	return 0;
}
Example #27
0
PyObject* EntityApp<E>::__py_listPathRes(PyObject* self, PyObject* args)
{
	int argCount = PyTuple_Size(args);
	if(argCount < 1 || argCount > 2)
	{
		PyErr_Format(PyExc_TypeError, "KBEngine::listPathRes(): args[path, pathargs=\'*.*\'] is error!");
		PyErr_PrintEx(0);
		return 0;
	}

	std::wstring wExtendName = L"*";
	PyObject* pathobj = NULL;
	PyObject* path_argsobj = NULL;

	if(argCount == 1)
	{
		if(PyArg_ParseTuple(args, "O", &pathobj) == -1)
		{
			PyErr_Format(PyExc_TypeError, "KBEngine::listPathRes(): args[path] is error!");
			PyErr_PrintEx(0);
			return 0;
		}
	}
	else
	{
		if(PyArg_ParseTuple(args, "O|O", &pathobj, &path_argsobj) == -1)
		{
			PyErr_Format(PyExc_TypeError, "KBEngine::listPathRes(): args[path, pathargs=\'*.*\'] is error!");
			PyErr_PrintEx(0);
			return 0;
		}
		
		if(PyUnicode_Check(path_argsobj))
		{
			wchar_t* fargs = NULL;
			fargs = PyUnicode_AsWideCharString(path_argsobj, NULL);
			wExtendName = fargs;
			PyMem_Free(fargs);
		}
		else
		{
			if(PySequence_Check(path_argsobj))
			{
				wExtendName = L"";
				Py_ssize_t size = PySequence_Size(path_argsobj);
				for(int i=0; i<size; i++)
				{
					PyObject* pyobj = PySequence_GetItem(path_argsobj, i);
					if(!PyUnicode_Check(pyobj))
					{
						PyErr_Format(PyExc_TypeError, "KBEngine::listPathRes(): args[path, pathargs=\'*.*\'] is error!");
						PyErr_PrintEx(0);
						return 0;
					}
					
					wchar_t* wtemp = NULL;
					wtemp = PyUnicode_AsWideCharString(pyobj, NULL);
					wExtendName += wtemp;
					wExtendName += L"|";
					PyMem_Free(wtemp);
				}
			}
			else
			{
				PyErr_Format(PyExc_TypeError, "KBEngine::listPathRes(): args[pathargs] is error!");
				PyErr_PrintEx(0);
				return 0;
			}
		}
	}

	if(!PyUnicode_Check(pathobj))
	{
		PyErr_Format(PyExc_TypeError, "KBEngine::listPathRes(): args[path] is error!");
		PyErr_PrintEx(0);
		return 0;
	}

	if(wExtendName.size() == 0)
	{
		PyErr_Format(PyExc_TypeError, "KBEngine::listPathRes(): args[pathargs] is NULL!");
		PyErr_PrintEx(0);
		return 0;
	}

	if(wExtendName[0] == '.')
		wExtendName.erase(wExtendName.begin());

	if(wExtendName.size() == 0)
		wExtendName = L"*";

	wchar_t* respath = PyUnicode_AsWideCharString(pathobj, NULL);
	if(respath == NULL)
	{
		PyErr_Format(PyExc_TypeError, "KBEngine::listPathRes(): args[path] is NULL!");
		PyErr_PrintEx(0);
		return 0;
	}

	char* cpath = strutil::wchar2char(respath);
	std::string foundPath = Resmgr::getSingleton().matchPath(cpath);
	free(cpath);
	PyMem_Free(respath);

	respath = strutil::char2wchar(foundPath.c_str());

	std::vector<std::wstring> results;
	Resmgr::getSingleton().listPathRes(respath, wExtendName, results);
	PyObject* pyresults = PyTuple_New(results.size());

	std::vector<std::wstring>::iterator iter = results.begin();
	int i = 0;

	for(; iter != results.end(); iter++)
	{
		PyTuple_SET_ITEM(pyresults, i++, PyUnicode_FromWideChar((*iter).c_str(), (*iter).size()));
	}

	free(respath);
	return pyresults;
}
Example #28
0
// Create a dynamic meta-object for a Python type by introspecting its
// attributes.  Note that it leaks if the type is deleted.
static int create_dynamic_metaobject(pyqtWrapperType *pyqt_wt)
{
    PyTypeObject *pytype = (PyTypeObject *)pyqt_wt;
    qpycore_metaobject *qo = new qpycore_metaobject;
#if QT_VERSION >= 0x050000
    QMetaObjectBuilder builder;
#endif

    // Get any class info.
    QList<ClassInfo> class_info_list = qpycore_get_class_info_list();

    // Get the super-type's meta-object.
#if QT_VERSION >= 0x050000
    builder.setSuperClass(get_qmetaobject((pyqtWrapperType *)pytype->tp_base));
#else
    qo->mo.d.superdata = get_qmetaobject((pyqtWrapperType *)pytype->tp_base);
#endif

    // Get the name of the type.  Dynamic types have simple names.
#if QT_VERSION >= 0x050000
    builder.setClassName(pytype->tp_name);
#else
    qo->str_data = pytype->tp_name;
    qo->str_data.append('\0');
#endif

    // Go through the class dictionary getting all PyQt properties, slots,
    // signals or a (deprecated) sequence of signals.

    typedef QPair<PyObject *, PyObject *> prop_data;
    QMap<uint, prop_data> pprops;
    QList<QByteArray> psigs;
    SIP_SSIZE_T pos = 0;
    PyObject *key, *value;
#if QT_VERSION < 0x050000
    bool has_notify_signal = false;
    QList<const QMetaObject *> enum_scopes;
#endif

    while (PyDict_Next(pytype->tp_dict, &pos, &key, &value))
    {
        // See if it is a slot, ie. it has been decorated with pyqtSlot().
        PyObject *sig_obj = PyObject_GetAttr(value,
                qpycore_signature_attr_name);

        if (sig_obj)
        {
            // Make sure it is a list and not some legitimate attribute that
            // happens to use our special name.
            if (PyList_Check(sig_obj))
            {
                for (SIP_SSIZE_T i = 0; i < PyList_GET_SIZE(sig_obj); ++i)
                {
                    qpycore_slot slot;

                    // Set up the skeleton slot.
                    PyObject *decoration = PyList_GET_ITEM(sig_obj, i);
                    slot.signature = Chimera::Signature::fromPyObject(decoration);

                    slot.sip_slot.pyobj = 0;
                    slot.sip_slot.name = 0;
                    slot.sip_slot.meth.mfunc = value;
                    slot.sip_slot.meth.mself = 0;
#if PY_MAJOR_VERSION < 3
                    slot.sip_slot.meth.mclass = (PyObject *)pyqt_wt;
#endif
                    slot.sip_slot.weakSlot = 0;

                    qo->pslots.append(slot);
                }
            }

            Py_DECREF(sig_obj);
        }
        else
        {
            PyErr_Clear();

            // Make sure the key is an ASCII string.  Delay the error checking
            // until we know we actually need it.
            const char *ascii_key = sipString_AsASCIIString(&key);

            // See if the value is of interest.
            if (PyType_IsSubtype(Py_TYPE(value), &qpycore_pyqtProperty_Type))
            {
                // It is a property.

                if (!ascii_key)
                    return -1;

                Py_INCREF(value);

                qpycore_pyqtProperty *pp = (qpycore_pyqtProperty *)value;

                pprops.insert(pp->pyqtprop_sequence, prop_data(key, value));

                // See if the property has a scope.  If so, collect all
                // QMetaObject pointers that are not in the super-class
                // hierarchy.
                const QMetaObject *mo = get_scope_qmetaobject(pp->pyqtprop_parsed_type);

#if QT_VERSION >= 0x050000
                if (mo)
                    builder.addRelatedMetaObject(mo);
#else
                if (mo && !enum_scopes.contains(mo))
                    enum_scopes.append(mo);
#endif

#if QT_VERSION < 0x050000
                // See if the property has a notify signal so that we can
                // allocate space for it in the meta-object.  We will check if
                // it is valid later on.  If there is one property with a
                // notify signal then a signal index is stored for all
                // properties.
                if (pp->pyqtprop_notify)
                    has_notify_signal = true;
#endif
            }
            else if (PyType_IsSubtype(Py_TYPE(value), &qpycore_pyqtSignal_Type))
            {
                // It is a signal.

                if (!ascii_key)
                    return -1;

                qpycore_pyqtSignal *ps = (qpycore_pyqtSignal *)value;

                // Make sure the signal has a name.
                qpycore_set_signal_name(ps, pytype->tp_name, ascii_key);

                // Add all the overloads.
                do
                {
                    psigs.append(ps->signature->signature);

                    ps = ps->next;
                }
                while (ps);

                Py_DECREF(key);
            }
            else if (ascii_key && qstrcmp(ascii_key, "__pyqtSignals__") == 0)
            {
                // It is a sequence of signal signatures.  This is deprecated
                // in favour of pyqtSignal().

                if (PySequence_Check(value))
                {
                    SIP_SSIZE_T seq_sz = PySequence_Size(value);

                    for (SIP_SSIZE_T i = 0; i < seq_sz; ++i)
                    {
                        PyObject *itm = PySequence_ITEM(value, i);

                        if (!itm)
                        {
                            Py_DECREF(key);
                            return -1;
                        }

                        PyObject *ascii_itm = itm;
                        const char *ascii = sipString_AsASCIIString(&ascii_itm);
                        Py_DECREF(itm);

                        if (!ascii)
                        {
                            Py_DECREF(key);
                            return -1;
                        }

                        QByteArray old_sig = QMetaObject::normalizedSignature(ascii);
                        old_sig.prepend('2');
                        psigs.append(old_sig);

                        Py_DECREF(ascii_itm);
                    }
                }

                Py_DECREF(key);
            }
            else
            {
                PyErr_Clear();
            }
        }
    }

    qo->nr_signals = psigs.count();

#if QT_VERSION < 0x050000
    // Create and fill the extradata array.
    if (enum_scopes.isEmpty())
    {
        qo->mo.d.extradata = 0;
    }
    else
    {
        const QMetaObject **objects = new const QMetaObject *[enum_scopes.size() + 1];

        for (int i = 0; i < enum_scopes.size(); ++i)
            objects[i] = enum_scopes.at(i);

        objects[enum_scopes.size()] = 0;

#if QT_VERSION >= 0x040600
        qo->ed.objects = objects;
        qo->ed.static_metacall = 0;

        qo->mo.d.extradata = &qo->ed;
#else
        qo->mo.d.extradata = objects;
#endif
    }
#endif

    // Initialise the header section of the data table.  Note that Qt v4.5
    // introduced revision 2 which added constructors.  However the design is
    // broken in that the static meta-call function doesn't provide enough
    // information to determine which Python sub-class of a Qt class is to be
    // created.  So we stick with revision 1 (and don't allow pyqtSlot() to
    // decorate __init__).

#if QT_VERSION < 0x050000
#if QT_VERSION >= 0x040600
    const int revision = 4;
    const int header_size = 14;
#else
    const int revision = 1;
    const int header_size = 10;
#endif

    int data_len = header_size + class_info_list.count() * 2 +
            qo->nr_signals * 5 + qo->pslots.count() * 5 + 
            pprops.count() * (has_notify_signal ? 4 : 3) + 1;
    uint *data = new uint[data_len];
    int i_offset = header_size;
    int g_offset = i_offset + class_info_list.count() * 2;
    int s_offset = g_offset + qo->nr_signals * 5;
    int p_offset = s_offset + qo->pslots.count() * 5;
    int n_offset = p_offset + pprops.count() * 3;
    int empty = 0;

    for (int i = 0; i < data_len; ++i)
        data[i] = 0;

    // The revision number.
    data[0] = revision;
#endif

    // Set up any class information.
    if (class_info_list.count() > 0)
    {
#if QT_VERSION < 0x050000
        data[2] = class_info_list.count();
        data[3] = i_offset;
#endif

        for (int i = 0; i < class_info_list.count(); ++i)
        {
            const ClassInfo &ci = class_info_list.at(i);

#if QT_VERSION >= 0x050000
            builder.addClassInfo(ci.first, ci.second);
#else
            data[i_offset + (i * 2) + 0] = qo->str_data.size();
            qo->str_data.append(ci.first.constData());
            qo->str_data.append('\0');

            data[i_offset + (i * 2) + 1] = qo->str_data.size();
            qo->str_data.append(ci.second.constData());
            qo->str_data.append('\0');
#endif
        }
    }

#if QT_VERSION < 0x050000
    // Set up the methods count and offset.
    if (qo->nr_signals || qo->pslots.count())
    {
        data[4] = qo->nr_signals + qo->pslots.count();
        data[5] = g_offset;

        // We might need an empty string.
        empty = qo->str_data.size();
        qo->str_data.append('\0');
    }

    // Set up the properties count and offset.
    if (pprops.count())
    {
        data[6] = pprops.count();
        data[7] = p_offset;
    }

#if QT_VERSION >= 0x040600
    data[13] = qo->nr_signals;
#endif
#endif

    // Add the signals to the meta-object.
    for (int g = 0; g < qo->nr_signals; ++g)
    {
        const QByteArray &norm = psigs.at(g);

#if QT_VERSION >= 0x050000
        builder.addSignal(norm.mid(1));
#else
        // Add the (non-existent) argument names.
        data[g_offset + (g * 5) + 1] = add_arg_names(qo, norm, empty);

        // Add the full signature.
        data[g_offset + (g * 5) + 0] = qo->str_data.size();
        qo->str_data.append(norm.constData() + 1);
        qo->str_data.append('\0');

        // Add the type, tag and flags.
        data[g_offset + (g * 5) + 2] = empty;
        data[g_offset + (g * 5) + 3] = empty;
        data[g_offset + (g * 5) + 4] = 0x05;
#endif
    }

    // Add the slots to the meta-object.
    for (int s = 0; s < qo->pslots.count(); ++s)
    {
        const qpycore_slot &slot = qo->pslots.at(s);
        const QByteArray &sig = slot.signature->signature;

#if QT_VERSION >= 0x050000
        QMetaMethodBuilder slot_builder = builder.addSlot(sig);
#else
        // Add the (non-existent) argument names.
        data[s_offset + (s * 5) + 1] = add_arg_names(qo, sig, empty);

        // Add the full signature.
        data[s_offset + (s * 5) + 0] = qo->str_data.size();
        qo->str_data.append(sig);
        qo->str_data.append('\0');
#endif

        // Add any type.
        if (slot.signature->result)
        {
#if QT_VERSION >= 0x050000
            slot_builder.setReturnType(slot.signature->result->name());
#else
            data[s_offset + (s * 5) + 2] = qo->str_data.size();
            qo->str_data.append(slot.signature->result->name());
            qo->str_data.append('\0');
#endif
        }
#if QT_VERSION < 0x050000
        else
        {
            data[s_offset + (s * 5) + 2] = empty;
        }

        // Add the tag and flags.
        data[s_offset + (s * 5) + 3] = empty;
        data[s_offset + (s * 5) + 4] = 0x0a;
#endif
    }

    // Add the properties to the meta-object.
#if QT_VERSION < 0x050000
    QList<uint> notify_signals;
#endif
    QMapIterator<uint, prop_data> it(pprops);

    for (int p = 0; it.hasNext(); ++p)
    {
        it.next();

        const prop_data &pprop = it.value();
        const char *prop_name = SIPBytes_AS_STRING(pprop.first);
        qpycore_pyqtProperty *pp = (qpycore_pyqtProperty *)pprop.second;
        int notifier_id;
#if QT_VERSION < 0x050000
        uint flags = 0;
#endif

        if (pp->pyqtprop_notify)
        {
            qpycore_pyqtSignal *ps = (qpycore_pyqtSignal *)pp->pyqtprop_notify;
            const QByteArray &sig = ps->signature->signature;

#if QT_VERSION >= 0x050000
            notifier_id = builder.indexOfSignal(sig.mid(1));
#else
            notifier_id = psigs.indexOf(sig);
#endif

            if (notifier_id < 0)
            {
                PyErr_Format(PyExc_TypeError,
                        "the notify signal '%s' was not defined in this class",
                        sig.constData() + 1);

                // Note that we leak the property name.
                return -1;
            }

#if QT_VERSION < 0x050000
            notify_signals.append(notifier_id);
            flags |= 0x00400000;
#endif
        }
        else
        {
#if QT_VERSION >= 0x050000
            notifier_id = -1;
#else
            notify_signals.append(0);
#endif
        }

#if QT_VERSION >= 0x050000
        // A Qt v5 revision 7 meta-object holds the QMetaType::Type of the type
        // or its name if it is unresolved (ie. not known to the type system).
        // In Qt v4 both are held.  For QObject sub-classes Chimera will fall
        // back to the QMetaType::QObjectStar if there is no specific meta-type
        // for the sub-class.  This means that, for Qt v4,
        // QMetaProperty::read() can handle the type.  However, Qt v5 doesn't
        // know that the unresolved type is a QObject sub-class.  Therefore we
        // have to tell it that the property is a QObject, rather than the
        // sub-class.  This means that QMetaProperty.typeName() will always
        // return "QObject*".
        QByteArray prop_type;

        if (pp->pyqtprop_parsed_type->metatype() == QMetaType::QObjectStar)
            prop_type = "QObject*";
        else
            prop_type = pp->pyqtprop_parsed_type->name();

        QMetaPropertyBuilder prop_builder = builder.addProperty(prop_name,
                prop_type, notifier_id);

        // Reset the defaults.
        prop_builder.setReadable(false);
        prop_builder.setWritable(false);
#else
        // Add the property name.
        data[p_offset + (p * 3) + 0] = qo->str_data.size();
        qo->str_data.append(prop_name);
        qo->str_data.append('\0');

        // Add the name of the property type.
        data[p_offset + (p * 3) + 1] = qo->str_data.size();
        qo->str_data.append(pp->pyqtprop_parsed_type->name());
        qo->str_data.append('\0');

        // There are only 8 bits available for the type so use the special
        // value if more are required.
        uint metatype = pp->pyqtprop_parsed_type->metatype();

        if (metatype > 0xff)
        {
#if QT_VERSION >= 0x040600
            // Qt assumes it is an enum.
            metatype = 0;
            flags |= 0x00000008;
#else
            // This is the old PyQt behaviour.  It may not be correct, but
            // nobody has complained, and if it ain't broke...
            metatype = 0xff;
#endif
        }
#endif

        // Enum or flag.
        if (pp->pyqtprop_parsed_type->isEnum() || pp->pyqtprop_parsed_type->isFlag())
        {
#if QT_VERSION >= 0x050000
            prop_builder.setEnumOrFlag(true);
#else
#if QT_VERSION >= 0x040600
            metatype = 0;
#endif
            flags |= 0x00000008;
#endif
        }

#if QT_VERSION < 0x050000
        flags |= metatype << 24;
#endif

        if (pp->pyqtprop_get && PyCallable_Check(pp->pyqtprop_get))
            // Readable.
#if QT_VERSION >= 0x050000
            prop_builder.setReadable(true);
#else
            flags |= 0x00000001;
#endif

        if (pp->pyqtprop_set && PyCallable_Check(pp->pyqtprop_set))
        {
            // Writable.
#if QT_VERSION >= 0x050000
            prop_builder.setWritable(true);
#else
            flags |= 0x00000002;
#endif

            // See if the name of the setter follows the Designer convention.
            // If so tell the UI compilers not to use setProperty().
            PyObject *setter_name_obj = PyObject_GetAttr(pp->pyqtprop_set,
                    qpycore_name_attr_name);

            if (setter_name_obj)
            {
                PyObject *ascii_obj = setter_name_obj;
                const char *ascii = sipString_AsASCIIString(&ascii_obj);
                Py_DECREF(setter_name_obj);

                if (ascii)
                {
                    if (qstrlen(ascii) > 3 && ascii[0] == 's' &&
                            ascii[1] == 'e' && ascii[2] == 't' &&
                            ascii[3] == toupper(prop_name[0]) &&
                            qstrcmp(&ascii[4], &prop_name[1]) == 0)
#if QT_VERSION >= 0x050000
                        prop_builder.setStdCppSet(true);
#else
                        flags |= 0x00000100;
#endif
                }

                Py_DECREF(ascii_obj);
            }

            PyErr_Clear();
        }

        if (pp->pyqtprop_reset && PyCallable_Check(pp->pyqtprop_reset))
            // Resetable.
#if QT_VERSION >= 0x050000
            prop_builder.setResettable(true);
#else
            flags |= 0x00000004;
#endif

        // Add the property flags.
#if QT_VERSION >= 0x050000
        // Note that Qt4 always seems to have ResolveEditable set but
        // QMetaObjectBuilder doesn't provide an API call to do it.
        prop_builder.setDesignable(pp->pyqtprop_flags & 0x00001000);
        prop_builder.setScriptable(pp->pyqtprop_flags & 0x00004000);
        prop_builder.setStored(pp->pyqtprop_flags & 0x00010000);
        prop_builder.setUser(pp->pyqtprop_flags & 0x00100000);
        prop_builder.setConstant(pp->pyqtprop_flags & 0x00000400);
        prop_builder.setFinal(pp->pyqtprop_flags & 0x00000800);
#else
        flags |= pp->pyqtprop_flags;

        data[p_offset + (p * 3) + 2] = flags;
#endif

        // Save the property data for qt_metacall().  (We already have a
        // reference.)
        qo->pprops.append(pp);

        // We've finished with the property name.
        Py_DECREF(pprop.first);
    }

#if QT_VERSION < 0x050000
    // Add the indices of the notify signals.
    if (has_notify_signal)
    {
        QListIterator<uint> notify_it(notify_signals);

        while (notify_it.hasNext())
            data[n_offset++] = notify_it.next();
    }
#endif

    // Initialise the rest of the meta-object.
#if QT_VERSION >= 0x050000
    qo->mo = builder.toMetaObject();
#else
    qo->mo.d.stringdata = qo->str_data.constData();
    qo->mo.d.data = data;
#endif

    // Save the meta-object.
    pyqt_wt->metaobject = qo;

    return 0;
}
Example #29
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);
}
Example #30
0
static int
_context_init (PyObject *self, PyObject *args, PyObject *kwds)
{
    PyObject *device;
    PyObject *attrlist = NULL;
    ALCint *attrs = NULL;
    
    if (!PyArg_ParseTuple (args, "O|O", &device, &attrlist))
        return -1;

    if (!PyDevice_Check (device))
    {
        PyErr_SetString (PyExc_TypeError, "device must be a Device");
        return -1;
    }
    
    if (attrlist)
    {
        ALCint attr;
        if (PySequence_Check (attrlist))
        {
            PyObject *item;
            Py_ssize_t i;
            Py_ssize_t count = PySequence_Size (attrlist);
            if (count == -1)
                return -1;
            if (count > 0)
                attrs = PyMem_New (ALCint, (count * 2) + 1);
            else
                attrs = NULL;
            for (i = 0; i < (count * 2); i += 2)
            {
                item = PySequence_ITEM (attrlist, i);
                if (!item)
                {
                    PyMem_Free (attrs);
                    return -1;
                }

                if (!IntFromSeqIndex (item, (Py_ssize_t)0, (int*)&attr))
                {
                    PyMem_Free (attrs);
                    return -1;
                }
                attrs[i] = attr;
                if (!IntFromSeqIndex (item, (Py_ssize_t)1, (int*)&attr))
                {
                    PyMem_Free (attrs);
                    return -1;
                }
                attrs[i+1] = attr;
            }
            attrs[(count*2)] = 0;
        }
        else
        {
            PyErr_Clear ();
            PyErr_SetString (PyExc_TypeError,
                "attrs must be a sequence of attibute/value pairs");
            return -1;
        }
    }

    CLEAR_ALCERROR_STATE ();
    ((PyContext*)self)->context = alcCreateContext (PyDevice_AsDevice (device),
        attrs);
    if (attrs)
        PyMem_Free (attrs);
    if (((PyContext*)self)->context == NULL)
    {
        SetALCErrorException (alcGetError (PyDevice_AsDevice (device)), 1);
        return -1;
    }
    Py_INCREF (device);
    ((PyContext*)self)->device = device;
    return 0;
}