Ejemplo n.º 1
0
/* Retrieve item from external memory list.
 *
 * XXX: Support slice objects and negative indices?
 */
static PyObject *em_list_getitem(em_list_t *self, PyObject *key)
{
    Py_ssize_t index;

    PyObject *r = NULL;

    /* Python 3 supports only long integers. */
#if PY_MAJOR_VERSION < 3
    if(PyInt_CheckExact(key))
    {
        index = PyInt_AsSsize_t(key);
        r = em_list_getitem_internal(self, index);
    }
    else if(PyLong_CheckExact(key))
#else
    if(PyLong_CheckExact(key))
#endif
    {
        index = PyLong_AsSsize_t(key);
        r = em_list_getitem_internal(self, index);
    }
    else
        PyErr_SetString(PyExc_TypeError, "Invalid key object type");

    return r;
}
Ejemplo n.º 2
0
SobolSampler* SobolSampler_New(size_t dims, PyObject* size)
{
    size_t _size   = 0;
    size_t _is_inf = 0;

    if (size == Py_None)
    {
        _size   = 1;
        _is_inf = 1;
    }
    else if (PyInt_Check(size) || PyLong_Check(size))
    {
        _size   = PyInt_AsSsize_t(size);
        _is_inf = 0;
    }
    else
    {
        PyErr_SetString(PyExc_TypeError, "size must be an integer, or None");
        return NULL;
    }
    
    SobolSampler* s = PyObject_New(SobolSampler, &SobolSamplerType);
    if (!s) return NULL;

    s->_size   = _size;
    s->_is_inf = _is_inf;
    s->_dims   = dims;
    s->_rng    = gsl_qrng_alloc(gsl_qrng_sobol, dims);

    return s;
}
Ejemplo n.º 3
0
static ssize_t python_write(vfs_handle_struct *handle, files_struct *fsp, const void *data, size_t n)
{
	struct pyfuncs *pf = handle->data;
	PyObject *pArgs, *pRet, *pValue;
	char *pydata;
	ssize_t s;

	if (!pf->pFuncWrite) {
		errno = ENOSYS;
		return -1;
	}

	PY_TUPLE_NEW(2);
	PY_ADD_TO_TUPLE(fsp->fh->fd, PyInt_FromSsize_t, 0);
	if (!(pValue = PyString_FromStringAndSize(data, n))) {
		Py_DECREF(pArgs);
		errno = E_INTERNAL;
		return -1;
	}
	PyTuple_SetItem(pArgs, 1, pValue);
	PY_CALL_WITH_ARGS(Write);

	s = PyInt_AsSsize_t(pRet);

	Py_DECREF(pRet);
	return s;
}
Ejemplo n.º 4
0
static PyObject* transfer(PyObject* self, PyObject* arg)
{
	PyObject* transferTuple;

	if(!PyArg_ParseTuple(arg, "O", &transferTuple))		// "O" - Gets non-NULL borrowed reference to Python argument.
		return NULL;					// As far as I can tell, it's mostly just copying arg[0] into transferTuple
								// and making sure at least one arg has been passed (I think)

	if(!PyTuple_Check(transferTuple))			// The only argument we support is a single tuple.
		pabort("Only accepts a single tuple as an argument\n");


	uint32_t tupleSize = PyTuple_Size(transferTuple);

	uint8_t tx[tupleSize];
	uint8_t rx[tupleSize];
	PyObject* tempItem;

	uint16_t i=0;

	while(i < tupleSize)
	{
		tempItem = PyTuple_GetItem(transferTuple, i);		//
		if(!PyInt_Check(tempItem))
		{
			pabort("non-integer contained in tuple\n");
		}
		tx[i] = (uint8_t)PyInt_AsSsize_t(tempItem);

		i++;

	}

	struct spi_ioc_transfer tr = {
		.tx_buf = (unsigned long)tx,
		.rx_buf = (unsigned long)rx,
		.len = tupleSize,
		.delay_usecs = delay,
		.speed_hz = speed,
		.bits_per_word = bits,
                .cs_change = 1,
	};

	ret = ioctl(fd, SPI_IOC_MESSAGE(1), &tr);
	if (ret < 1)
		pabort("can't send spi message");

	transferTuple = PyTuple_New(tupleSize);
	for(i=0;i<tupleSize;i++)
		PyTuple_SetItem(transferTuple, i, Py_BuildValue("i",rx[i]));

	return transferTuple;
}


static PyObject* closeSPI(PyObject* self,PyObject* args)
{
	close(fd);
	Py_RETURN_NONE;
}
Ejemplo n.º 5
0
static PyObject* directWrite(PyObject* self, PyObject* arg)
{
	PyObject* transferTuple;
	unsigned int offset, returnVal ;

	if(!PyArg_ParseTuple(arg, "lO", &offset, &transferTuple))		
		return NULL;					

	if(!PyTuple_Check(transferTuple))			
		pabort("Only accepts a single tuple as an argument\n");


	uint32_t tupleSize = PyTuple_Size(transferTuple);
	uint8_t tx[tupleSize];
	PyObject* tempItem;
	uint32_t i=0;
	while(i < tupleSize)
	{
		tempItem = PyTuple_GetItem(transferTuple, i);		//
		if(!PyInt_Check(tempItem))
		{
			pabort("non-integer contained in tuple\n");
		}
		tx[i] = (uint8_t)PyInt_AsSsize_t(tempItem);
		i++;

	}
	returnVal = direct_write(offset, tx, tupleSize);
	return Py_BuildValue("l", returnVal) ;
}
Ejemplo n.º 6
0
static int
image_set_int (zbarImage *self,
               PyObject *value,
               void *closure)
{
    unsigned int tmp, val = PyInt_AsSsize_t(value);
    if(val == -1 && PyErr_Occurred()) {
        PyErr_SetString(PyExc_TypeError, "expecting an integer");
        return(-1);
    }
    switch((int)closure) {
    case 0:
        tmp = zbar_image_get_height(self->zimg);
        zbar_image_set_size(self->zimg, val, tmp);
        break;
    case 1:
        tmp = zbar_image_get_width(self->zimg);
        zbar_image_set_size(self->zimg, tmp, val);
        break;
    case 2:
        zbar_image_set_sequence(self->zimg, val);
    default:
        assert(0);
    }
    return(0);
}
Ejemplo n.º 7
0
grub_err_t do_pyfs_open(const char *name, grub_off_t *size)
{
    PyObject *pyret;
    Py_ssize_t pysize;

    if (!pyfs_open_callable)
        return GRUB_ERR_FILE_NOT_FOUND;

    pyret = PyObject_CallFunction(pyfs_open_callable, "s", name);

    if (pyret == NULL) {
        PyErr_Print();
        return grub_error(GRUB_ERR_IO, "Internal error: Failed to call Python open callback, or it threw an exception");
    }

    if (pyret == Py_None) {
        Py_DECREF(pyret);
        return GRUB_ERR_BAD_FILE_TYPE;
    }

    pysize = PyInt_AsSsize_t(pyret);
    Py_DECREF(pyret);
    if (pysize < 0) {
        if (PyErr_Occurred())
            PyErr_Print();
        return grub_error(GRUB_ERR_IO, "Internal error: Python open callback returned a bad or negative size");
    }

    *size = (grub_off_t)pysize;
    return GRUB_ERR_NONE;
}
Ejemplo n.º 8
0
/* Insert item in external memory list.
 *
 * XXX: Support slice objects and negative indices?
 */
static int em_list_setitem(em_list_t *self, PyObject *key, PyObject *value)
{
    Py_ssize_t index;

    int ret = -1;

    /* Python 3 supports only long integers. */
#if PY_MAJOR_VERSION < 3
    if(PyInt_CheckExact(key))
    {
        index = PyInt_AsSsize_t(key);
        ret = em_list_setitem_safe(self, index, value);
    }
    else if(PyLong_CheckExact(key))
#else
    if(PyLong_CheckExact(key))
#endif
    {
        index = PyLong_AsSsize_t(key);
        ret = em_list_setitem_safe(self, index, value);
    }
    else
        PyErr_SetString(PyExc_TypeError, "Invalid index type");

    return ret;
}
Ejemplo n.º 9
0
static PyObject *SEQUENCE_REPEAT( ssizeargfunc repeatfunc, PyObject *seq, PyObject *n )
{
    if (unlikely( !PyIndex_Check( n ) ))
    {
        PyErr_Format(
            PyExc_TypeError,
            "can't multiply sequence by non-int of type '%s'",
            Py_TYPE( n )->tp_name
        );

        return NULL;
    }

    PyObject *index_value = PyNumber_Index( n );

    if (unlikely( index_value == NULL ))
    {
        return NULL;
    }

    /* We're done if PyInt_AsSsize_t() returns without error. */
#if PYTHON_VERSION < 300
    Py_ssize_t count = PyInt_AsSsize_t( index_value );
#else
    Py_ssize_t count = PyLong_AsSsize_t( index_value );
#endif

    Py_DECREF( index_value );

    if (unlikely( count == -1 )) // Note: -1 is an unlikely repetition count
    {
        PyObject *exception = GET_ERROR_OCCURRED();

        if (unlikely(  exception ))
        {
            if ( !EXCEPTION_MATCH_BOOL_SINGLE( exception, PyExc_OverflowError ) )
            {
                return NULL;
            }

            PyErr_Format(
                PyExc_OverflowError,
                "cannot fit '%s' into an index-sized integer",
                Py_TYPE( n )->tp_name
            );

            return NULL;
        }
    }

    PyObject *result = (*repeatfunc)( seq, count );

    if (unlikely( result == NULL ))
    {
        return NULL;
    }

    return result;
}
Ejemplo n.º 10
0
static INLINE Py_ssize_t __pyx_PyIndex_AsSsize_t(PyObject* b) {
  Py_ssize_t ival;
  PyObject* x = PyNumber_Index(b);
  if (!x) return -1;
  ival = PyInt_AsSsize_t(x);
  Py_DECREF(x);
  return ival;
}
Ejemplo n.º 11
0
Archivo: rowe_1.c Proyecto: jwilk/Pyrex
/* Implementation of rowe_1 */

static PyObject *__pyx_f_6rowe_1_function(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/
static PyObject *__pyx_f_6rowe_1_function(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) {
  PyObject *__pyx_v_data = 0;
  PyObject *__pyx_v_a;
  PyObject *__pyx_r;
  PyObject *__pyx_1 = 0;
  PyObject *__pyx_2 = 0;
  int __pyx_3;
  Py_ssize_t __pyx_4;
  Py_ssize_t __pyx_5;
  static char *__pyx_argnames[] = {"data",0};
  if (!PyArg_ParseTupleAndKeywords(__pyx_args, __pyx_kwds, "O", __pyx_argnames, &__pyx_v_data)) return 0;
  Py_INCREF(__pyx_v_data);
  __pyx_v_a = Py_None; Py_INCREF(Py_None);

  /* "/Local/Projects/D/Pyrex/Source/Tests/Bugs/other/rowe_1.pyx":7 */
  __pyx_1 = PyInt_FromLong(4); if (!__pyx_1) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 7; goto __pyx_L1;}
  __pyx_2 = PyNumber_Multiply(__pyx_1, __pyx_v_a); if (!__pyx_2) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 7; goto __pyx_L1;}
  Py_DECREF(__pyx_1); __pyx_1 = 0;
  __pyx_3 = PyInt_AsLong(__pyx_2); if (PyErr_Occurred()) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 7; goto __pyx_L1;}
  Py_DECREF(__pyx_2); __pyx_2 = 0;
  blarg(__pyx_3);

  /* "/Local/Projects/D/Pyrex/Source/Tests/Bugs/other/rowe_1.pyx":8 */
  __pyx_4 = PyInt_AsSsize_t(__pyx_v_a); if (PyErr_Occurred()) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 8; goto __pyx_L1;}
  __pyx_1 = __Pyx_GetName(__pyx_b, __pyx_n_b); if (!__pyx_1) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 8; goto __pyx_L1;}
  __pyx_2 = PyNumber_Add(__pyx_v_a, __pyx_1); if (!__pyx_2) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 8; goto __pyx_L1;}
  Py_DECREF(__pyx_1); __pyx_1 = 0;
  __pyx_5 = PyInt_AsSsize_t(__pyx_2); if (PyErr_Occurred()) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 8; goto __pyx_L1;}
  Py_DECREF(__pyx_2); __pyx_2 = 0;
  __pyx_1 = PySequence_GetSlice(__pyx_v_data, __pyx_4, __pyx_5); if (!__pyx_1) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 8; goto __pyx_L1;}
  __pyx_r = __pyx_1;
  __pyx_1 = 0;
  goto __pyx_L0;

  __pyx_r = Py_None; Py_INCREF(Py_None);
  goto __pyx_L0;
  __pyx_L1:;
  Py_XDECREF(__pyx_1);
  Py_XDECREF(__pyx_2);
  __Pyx_AddTraceback("rowe_1.function");
  __pyx_r = 0;
  __pyx_L0:;
  Py_DECREF(__pyx_v_a);
  Py_DECREF(__pyx_v_data);
  return __pyx_r;
}
Ejemplo n.º 12
0
static PyObject* logiWrite(PyObject* self, PyObject* arg)
{
	PyObject* transferTuple;
	unsigned int offset, returnVal ;
	unsigned char type_size = 1 ;

	if(!PyArg_ParseTuple(arg, "lO|b", &offset, &transferTuple, &type_size))
		return NULL;

	if(!PyTuple_Check(transferTuple))
		pabort("Only accepts a single tuple as an argument\n");

	if(type_size != 1 && type_size != 2 && type_size != 4)
		pabort("type_size argument can only be 1, 2, 4\n");
	uint32_t tupleSize = PyTuple_Size(transferTuple);
	uint8_t tx[tupleSize*type_size];
	PyObject* tempItem;
	uint32_t i=0;
	while(i < tupleSize)
	{
		tempItem = PyTuple_GetItem(transferTuple, i);		//
		if(!PyInt_Check(tempItem))
		{
			pabort("non-integer contained in tuple\n");
		}
		switch(type_size){
			case 1:
				tx[i] = (uint8_t)PyInt_AsSsize_t(tempItem);
				break ;
			case 2:
				((uint16_t*)tx)[i] = (uint16_t)PyInt_AsSsize_t(tempItem);
				break ;
			case 4:
				((uint32_t*)tx)[i] = (uint32_t)PyInt_AsSsize_t(tempItem);
				break ;
			default:
				break ;

			
		}
		i++;

	}
	returnVal = logi_write(tx, tupleSize*type_size, offset);
	return Py_BuildValue("l", returnVal) ;
}
Ejemplo n.º 13
0
Archivo: split.c Proyecto: S-YOU/split
static PyObject*
_split_u_list(PyObject* self, PyObject* arg) {
	size_t sLen = 0, splitterLen = 1, maxsplit = 1, index = 0;
	Py_UNICODE *src = NULL, *s, *ss, *sEnd = NULL, *sPrev = NULL;
	Py_UNICODE defaultSplitter = ',', *splitter = &defaultSplitter, *sp, *spEnd = splitter + splitterLen;
	PyObject *list;
	PyTupleObject* argTuple = (PyTupleObject*) arg;

	if (PyUnicode_CheckExact(argTuple->ob_item[0])) {
		src = PyUnicode_AS_UNICODE(argTuple->ob_item[0]);
		sLen = PyUnicode_GET_SIZE(argTuple->ob_item[0]);
	} else {
		return NULL;
	}

	maxsplit = PyInt_AsSsize_t(argTuple->ob_item[1]);
	if (!maxsplit || maxsplit > 100) {
		return NULL;
	}

	if (argTuple->ob_size > 2) {
		if (PyUnicode_CheckExact(argTuple->ob_item[2])) {
			splitter = PyUnicode_AS_UNICODE(argTuple->ob_item[2]);
			splitterLen = PyUnicode_GET_SIZE(argTuple->ob_item[2]);
			spEnd = splitter + splitterLen;
		} else {
			return NULL;
		}
	}

	sPrev = s = src, sEnd = src + sLen;
	list = TYPE_NEW(maxsplit);
	while (s < sEnd) {
		if (*s == *splitter) {
			if (splitterLen > 1) {
				sp = splitter, ss = s;
				while (*++sp == *++ss);
				if (sp >= spEnd) {
					ADD_U;
					if (index >= maxsplit) return list;
					sPrev = s + splitterLen;
					s += splitterLen;
					continue;
				}
			} else {
				ADD_U;
				if (index >= maxsplit) return list;
				sPrev = s + 1;
			}
		}
		s++;
	}
	if (index < maxsplit) {
		ADD_U;
	}
	Py_SIZE(list) = index;
	return list;
}
Ejemplo n.º 14
0
size_t modena_model_outputs_argPos(const modena_model_t *m, const char *name)
{
    PyObject *pRet = PyObject_CallMethod(m->pModel, "outputs_argPos", NULL);
    if(!pRet){ Modena_PyErr_Print(); }
    size_t ret = PyInt_AsSsize_t(pRet);
    Py_DECREF(pRet);

    return ret;
}
Ejemplo n.º 15
0
void modena_substitute_model_calculate_maps
(
    modena_substitute_model_t *sm,
    modena_model_t *parent
)
{
    PyObject *pMaps = PyObject_CallMethod
    (
        parent->pModel, "calculate_maps", "(O)", sm->model->pModel
    );
    if(!pMaps){ Modena_PyErr_Print(); }

    PyObject *pMapOutputs = PyTuple_GET_ITEM(pMaps, 0); // Borrowed ref
    if(!pMapOutputs){ Modena_PyErr_Print(); }
    PyObject *pSeq = PySequence_Fast(pMapOutputs, "expected a sequence");
    sm->map_outputs_size = PySequence_Size(pMapOutputs);
    sm->map_outputs = malloc(sm->map_outputs_size*sizeof(double));
    size_t i;
    for(i = 0; i < sm->map_outputs_size; i++)
    {
        sm->map_outputs[i] = PyInt_AsSsize_t(PyList_GET_ITEM(pSeq, i));
        parent->argPos_used[sm->map_outputs[i]] = true;
    }
    sm->map_outputs_size /= 2;
    Py_DECREF(pSeq);
    Py_DECREF(pMapOutputs);
    if(PyErr_Occurred()){ Modena_PyErr_Print(); }

    PyObject *pMapInputs = PyTuple_GET_ITEM(pMaps, 1); // Borrowed ref
    if(!pMapInputs){ Modena_PyErr_Print(); }
    pSeq = PySequence_Fast(pMapInputs, "expected a sequence");
    sm->map_inputs_size = PySequence_Size(pMapInputs);
    sm->map_inputs = malloc(sm->map_inputs_size*sizeof(double));
    for(i = 0; i < sm->map_inputs_size; i++)
    {
        sm->map_inputs[i] = PyInt_AsSsize_t(PyList_GET_ITEM(pSeq, i));
    }
    sm->map_inputs_size /= 2;
    Py_DECREF(pSeq);
    Py_DECREF(pMapInputs);
    if(PyErr_Occurred()){ Modena_PyErr_Print(); }

    Py_DECREF(pMaps);
}
Ejemplo n.º 16
0
//Py Conversion Functions with overloads
int Pywrap::py_extractInt(PyObject *results) const
{
    if(PyInt_Check(results))
    {
        return PyInt_AsSsize_t(results);
    }
    std::cout << "Warning: PyObject is not Integer. Undefined behavior may occur! Warning in script: " << path
            << std::endl;
    return 0;
}
Ejemplo n.º 17
0
static CYTHON_INLINE PyObject* __Pyx_PyNumber_Int(PyObject* x) {
  PyNumberMethods *m;
  const char *name = NULL;
  PyObject *res = NULL;
#if PY_VERSION_HEX < 0x03000000
  if (PyInt_Check(x) || PyLong_Check(x))
#else
  if (PyLong_Check(x))
#endif
    return Py_INCREF(x), x;
  m = Py_TYPE(x)->tp_as_number;
#if PY_VERSION_HEX < 0x03000000
  if (m && m->nb_int) {
    name = "int";
    res = PyNumber_Int(x);
  }
  else if (m && m->nb_long) {
    name = "long";
    res = PyNumber_Long(x);
  }
#else
  if (m && m->nb_int) {
    name = "int";
    res = PyNumber_Long(x);
  }
#endif
  if (res) {
#if PY_VERSION_HEX < 0x03000000
    if (!PyInt_Check(res) && !PyLong_Check(res)) {
#else
    if (!PyLong_Check(res)) {
#endif
      PyErr_Format(PyExc_TypeError,
                   "__%s__ returned non-%s (type %.200s)",
                   name, name, Py_TYPE(res)->tp_name);
      Py_DECREF(res);
      return NULL;
    }
  }
  else if (!PyErr_Occurred()) {
    PyErr_SetString(PyExc_TypeError,
                    "an integer is required");
  }
  return res;
}

static CYTHON_INLINE Py_ssize_t __Pyx_PyIndex_AsSsize_t(PyObject* b) {
  Py_ssize_t ival;
  PyObject* x = PyNumber_Index(b);
  if (!x) return -1;
  ival = PyInt_AsSsize_t(x);
  Py_DECREF(x);
  return ival;
}
Ejemplo n.º 18
0
static int
Row_setattro(PyObject* o, PyObject *name, PyObject* v)
{
    Row* self = (Row*)o;

    PyObject* index = PyDict_GetItem(self->map_name_to_index, name);

    if (index)
        return Row_ass_item(self, PyInt_AsSsize_t(index), v);

    return PyObject_GenericSetAttr(o, name, v);
}
Ejemplo n.º 19
0
/* Constructor */
PyObject *
Image_new(PyTypeObject *type, PyObject *args, PyObject *kwargs)
{
    ImageObject *self = (ImageObject*) type->tp_alloc(type, 0);
    if (self != NULL)
    {
        PyObject *input = NULL;

        if (PyArg_ParseTuple(args, "|O", &input))
        {
            if (input != NULL)
            {
                try
                {
                    PyObject *pyStr;
                    // If the input object is a tuple, consider it (index, filename)
                    if (PyTuple_Check(input))
                    {
                      // Get the index and filename from the Python tuple object
                      size_t index = PyInt_AsSsize_t(PyTuple_GetItem(input, 0));
                      const char * filename = PyString_AsString(PyTuple_GetItem(input, 1));
                      // Now read using both of index and filename
                      self->image = new ImageGeneric();
                      self->image->read(filename, DATA, index);

                    }
                    else if ((pyStr = PyObject_Str(input)) != NULL)
                    {
                        self->image = new ImageGeneric(PyString_AsString(pyStr));
                        //todo: add copy constructor
                    }
                    else
                    {
                        PyErr_SetString(PyExc_TypeError,
                                        "Image_new: Expected string, FileName or tuple as first argument");
                        return NULL;
                    }
                }
                catch (XmippError &xe)
                {
                    PyErr_SetString(PyXmippError, xe.msg.c_str());
                    return NULL;
                }
            }
            else
                self->image = new ImageGeneric();
        }
        else
            return NULL;
    }
    return (PyObject *) self;
}//function Image_new
Ejemplo n.º 20
0
PyObject *
dealloc_cpt(PyObject *self, PyObject *args) {
    PyObject *pycpt; // addr of cpt as a python int

    if (!PyArg_ParseTuple(args, "O", &pycpt)) {
        return NULL;
    }

    CPT *cpt = (CPT*) PyInt_AsSsize_t(pycpt);
    _dealloc_cpt(cpt);

    Py_RETURN_NONE;
}
Ejemplo n.º 21
0
/** Helper to verify current reference count and avoid memory leaks */
size_t PythonTotalRefCount()
{
#ifdef Py_DEBUG
	#pragma message("Open3DMotion MESSAGE: Debug build selected. Ensure that a custom build of python shared library is used (one built with Py_DEBUG defined).")
	PyObject* borrowed_count_function = PySys_GetObject("gettotalrefcount");
	PyObject* py_count = PyObject_CallObject(borrowed_count_function, NULL);
  size_t count = PyInt_AsSsize_t(py_count);
  Py_DECREF(py_count);
	return count;
#else
	return 0;
#endif
}
Ejemplo n.º 22
0
static int
image_set_size (zbarImage *self,
                PyObject *value,
                void *closure)
{
    if(!value) {
        PyErr_SetString(PyExc_TypeError, "cannot delete size attribute");
        return(-1);
    }
    int rc = -1;
    PyObject *wobj = NULL, *hobj = NULL;
    if(!PySequence_Check(value) ||
       PySequence_Size(value) != 2)
        goto error;
    wobj = PySequence_GetItem(value, 0);
    hobj = PySequence_GetItem(value, 1);
    if(!wobj || !hobj)
        goto error;

    int width = PyInt_AsSsize_t(wobj);
    if(width == -1 && PyErr_Occurred())
        goto error;

    int height = PyInt_AsSsize_t(hobj);
    if(height == -1 && PyErr_Occurred())
        goto error;

    zbar_image_set_size(self->zimg, width, height);
    rc = 0;

error:
    Py_XDECREF(wobj);
    Py_XDECREF(hobj);
    if(rc)
        PyErr_SetString(PyExc_ValueError,
                        "size must be a sequence of two ints");
    return(rc);
}
Ejemplo n.º 23
0
static int
array_power_is_scalar(PyObject *o2, double* exp)
{
    PyObject *temp;
    const int optimize_fpexps = 1;

    if (PyInt_Check(o2)) {
        *exp = (double)PyInt_AsLong(o2);
        return 1;
    }
    if (optimize_fpexps && PyFloat_Check(o2)) {
        *exp = PyFloat_AsDouble(o2);
        return 1;
    }
    if ((PyArray_IsZeroDim(o2) &&
         ((PyArray_ISINTEGER(o2) ||
           (optimize_fpexps && PyArray_ISFLOAT(o2))))) ||
        PyArray_IsScalar(o2, Integer) ||
        (optimize_fpexps && PyArray_IsScalar(o2, Floating))) {
        temp = o2->ob_type->tp_as_number->nb_float(o2);
        if (temp != NULL) {
            *exp = PyFloat_AsDouble(o2);
            Py_DECREF(temp);
            return 1;
        }
    }
#if (PY_VERSION_HEX >= 0x02050000)
    if (PyIndex_Check(o2)) {
        PyObject* value = PyNumber_Index(o2);
        Py_ssize_t val;
        if (value==NULL) {
            if (PyErr_Occurred()) {
                PyErr_Clear();
            }
            return 0;
        }
        val = PyInt_AsSsize_t(value);
        if (val == -1 && PyErr_Occurred()) {
            PyErr_Clear();
            return 0;
        }
        *exp = (double) val;
        return 1;
    }
#endif
    return 0;
}
Ejemplo n.º 24
0
static PyObject *
enum_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
	enumobject *en;
	PyObject *seq = NULL;
	PyObject *start = NULL;
	static char *kwlist[] = {"sequence", "start", 0};

	if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O:enumerate", kwlist,
					 &seq, &start))
		return NULL;

	en = (enumobject *)type->tp_alloc(type, 0);
	if (en == NULL)
		return NULL;
	if (start != NULL) {
		start = PyNumber_Index(start);
		if (start == NULL) {
			Py_DECREF(en);
			return NULL;
		}
		assert(PyInt_Check(start) || PyLong_Check(start));
		en->en_index = PyInt_AsSsize_t(start);
		if (en->en_index == -1 && PyErr_Occurred()) {
			PyErr_Clear();
			en->en_index = PY_SSIZE_T_MAX;
			en->en_longindex = start;
		} else {
			en->en_longindex = NULL;
			Py_DECREF(start);
		}
	} else {
		en->en_index = 0;
		en->en_longindex = NULL;
	}
	en->en_sit = PyObject_GetIter(seq);
	if (en->en_sit == NULL) {
		Py_DECREF(en);
		return NULL;
	}
	en->en_result = PyTuple_Pack(2, Py_None, Py_None);
	if (en->en_result == NULL) {
		Py_DECREF(en);
		return NULL;
	}
	return (PyObject *)en;
}
Ejemplo n.º 25
0
static off_t python_lseek(vfs_handle_struct *handle, files_struct *fsp, off_t offset, int whence)
{
	struct pyfuncs *pf = handle->data;
	PyObject *pArgs, *pRet, *pValue;
	off_t o;

	PY_TUPLE_NEW(3);
	PY_ADD_TO_TUPLE(fsp->fh->fd, PyInt_FromSsize_t, 0);
	PY_ADD_TO_TUPLE(offset, PyInt_FromSize_t, 1);
	PY_ADD_TO_TUPLE(whence, PyInt_FromSize_t, 2);
	PY_CALL_WITH_ARGS(LSeek);

	o = PyInt_AsSsize_t(pRet);

	Py_DECREF(pRet);
	return o;
}
Ejemplo n.º 26
0
/* write */
PyObject *
Image_write(PyObject *obj, PyObject *args, PyObject *kwargs)
{
    ImageObject *self = (ImageObject*) obj;
    if (self != NULL)
    {
        PyObject *input = NULL;
        if (PyArg_ParseTuple(args, "O", &input))
        {
            try
            {
              PyObject *pyStr;
              // If the input object is a tuple, consider it (index, filename)
              if (PyTuple_Check(input))
              {
                // Get the index and filename from the Python tuple object
                size_t index = PyInt_AsSsize_t(PyTuple_GetItem(input, 0));
                const char * filename = PyString_AsString(PyTuple_GetItem(input, 1));
                // Now read using both of index and filename
                bool isStack = (index > 0);
                WriteMode writeMode = isStack ? WRITE_REPLACE : WRITE_OVERWRITE;
                self->image->write(filename, index, isStack, writeMode);

                Py_RETURN_NONE;
              }
              if ((pyStr = PyObject_Str(input)) != NULL)
              {
                  self->image->write(PyString_AsString(input));
                  Py_RETURN_NONE;
              }
              else
              {
                  PyErr_SetString(PyExc_TypeError,
                                  "Image_write: Expected an string or FileName as first argument");
              }
            }
            catch (XmippError &xe)
            {
                PyErr_SetString(PyXmippError, xe.msg.c_str());
            }
        }
    }
    return NULL;
}//function Image_write
Ejemplo n.º 27
0
/* read */
PyObject *
Image_read(PyObject *obj, PyObject *args, PyObject *kwargs)
{
    ImageObject *self = (ImageObject*) obj;

    if (self != NULL)
    {
        int datamode = DATA;
        PyObject *input = NULL;
        if (PyArg_ParseTuple(args, "O|i", &input, &datamode))
        {

            try
            {
              PyObject *pyStr;
              // If the input object is a tuple, consider it (index, filename)
              if (PyTuple_Check(input))
              {
                // Get the index and filename from the Python tuple object
                size_t index = PyInt_AsSsize_t(PyTuple_GetItem(input, 0));
                const char * filename = PyString_AsString(PyTuple_GetItem(input, 1));
                // Now read using both of index and filename
                self->image->read(filename,(DataMode)datamode, index);
                Py_RETURN_NONE;
              }
              else if ((pyStr = PyObject_Str(input)) != NULL)
              {
                  self->image->read(PyString_AsString(pyStr),(DataMode)datamode);
                  Py_RETURN_NONE;
              }
              else
              {
                  PyErr_SetString(PyExc_TypeError,
                                  "Image_write: Expected an string or FileName as first argument");
              }
            }
            catch (XmippError &xe)
            {
                PyErr_SetString(PyXmippError, xe.msg.c_str());
            }
        }
    }
    return NULL;
}//function Image_read
Ejemplo n.º 28
0
ssize_t skull_module_unpack (void* md, skull_txn_t* txn,
                         const void* data, size_t data_len)
{
    PyGILState_STATE state = PyGILState_Ensure();
    module_data_t* mdata = (module_data_t*)md;

    // Prepare args
    PyObject* pyArgs = PyTuple_New(4);
    PyObject* pyModuleName = PyString_FromString(mdata->name);
    PyObject* pyEntryName  = PyString_FromString(MODULE_UNPACK_FUNCNAME);
    PyObject* pyTxn        = PyCapsule_New(txn, "skull_txn", NULL);
    PyObject* pyData       = PyString_FromStringAndSize((const char*)data,
                                                        (Py_ssize_t)data_len);

    PyTuple_SetItem(pyArgs, 0, pyModuleName);
    PyTuple_SetItem(pyArgs, 1, pyEntryName);
    PyTuple_SetItem(pyArgs, 2, pyTxn);
    PyTuple_SetItem(pyArgs, 3, pyData);

    // Call user module_unpack
    PyObject* pyConsumed = PyObject_CallObject(mdata->pyExecutorFunc, pyArgs);

    // Set to -1 by default, so if error occurred, like un-handled excpetions,
    //  then the entity will be destroyed soon
    ssize_t consumed = -1;

    if (!pyConsumed) {
        if (PyErr_Occurred()) PyErr_Print();
    } else {
        if (PyInt_Check(pyConsumed)) {
            consumed = PyInt_AsSsize_t(pyConsumed);
        } else if (PyLong_Check(pyConsumed)) {
            consumed = PyLong_AsSsize_t(pyConsumed);
        } else {
            fprintf(stderr, "Error: Cannot parse the pyConsumed object");
            _PyObject_Dump(pyConsumed);
        }
    }

    Py_XDECREF(pyConsumed);
    Py_DECREF(pyArgs);
    PyGILState_Release(state);
    return consumed;
}
Ejemplo n.º 29
0
Archivo: myson.c Proyecto: S-YOU/myson
void encode_object(PyObject *arg) {
	Py_ssize_t size, i;
	char *p;

	if (PyString_CheckExact(arg)) {
		uint8_t *s, *sEnd;
		*d++ = '"';
		ENCODE_STR(arg, s, sEnd)
		*d++ = '"';
	} else if (PyUnicode_CheckExact(arg)) {
		*d++ = '"';
		Py_UNICODE *u, *uEnd;
		ENCODE_UNICODE(arg, u, uEnd)
		*d++ = '"';
	} else if (PyInt_CheckExact(arg) || PyLong_CheckExact(arg)) {
		i = PyInt_AsSsize_t(arg);
		uint64_t val = i < 0 ? *d++ = '-', (uint64_t)(~i + 1) : i;
		ITOA(val)
	} else if (PyList_CheckExact(arg)) {
Ejemplo n.º 30
0
 // [ changed, idx ]
 static cbret_t py_as_cbret(PyObject *py_ret)
 {
   cbret_t ret;
   if ( PySequence_Check(py_ret) )
   {
     {
       newref_t item(PySequence_GetItem(py_ret, 0));
       if ( item.o != NULL && PyInt_Check(item.o) )
         ret.changed = cbres_t(PyInt_AsLong(item.o));
     }
     if ( ret.changed != NOTHING_CHANGED )
     {
       newref_t item(PySequence_GetItem(py_ret, 1));
       if ( item.o != NULL && PyInt_Check(item.o) )
         ret.idx = ssize_t(PyInt_AsSsize_t(item.o));
     }
   }
   return ret;
 }