Beispiel #1
0
static PyObject*
memoryview_get_extents_info(PyObject *self, PyObject *args)
{
    int i;
    Py_ssize_t *shape_ary = NULL;
    Py_ssize_t *strides_ary = NULL;
    PyObject *shape_tuple = NULL;
    PyObject *strides_tuple = NULL;
    PyObject *shape = NULL, *strides = NULL;
    Py_ssize_t itemsize = 0;
    int ndim = 0;
    PyObject* res = NULL;

    if (!PyArg_ParseTuple(args, "OOin", &shape, &strides, &ndim, &itemsize))
        goto cleanup;

    if (ndim < 0) {
        PyErr_SetString(PyExc_ValueError, "ndim is negative");
        goto cleanup;
    }

    if (itemsize <= 0) {
        PyErr_SetString(PyExc_ValueError, "ndim <= 0");
        goto cleanup;
    }

    shape_ary = malloc(sizeof(Py_ssize_t) * ndim + 1);
    strides_ary = malloc(sizeof(Py_ssize_t) * ndim + 1);

    shape_tuple = PySequence_Fast(shape, "shape is not a sequence");
    if (!shape_tuple) goto cleanup;

    for (i = 0; i < ndim; ++i) {
        shape_ary[i] = PyNumber_AsSsize_t(
                           PySequence_Fast_GET_ITEM(shape_tuple, i),
                           PyExc_OverflowError);
    }

    strides_tuple = PySequence_Fast(strides, "strides is not a sequence");
    if (!strides_tuple) goto cleanup;

    for (i = 0; i < ndim; ++i) {
        strides_ary[i] = PyNumber_AsSsize_t(
                           PySequence_Fast_GET_ITEM(strides_tuple, i),
                           PyExc_OverflowError);
    }

    res = get_extents(shape_ary, strides_ary, ndim, itemsize, 0);
cleanup:
    free(shape_ary);
    free(strides_ary);
    Py_XDECREF(shape_tuple);
    Py_XDECREF(strides_tuple);
    return res;
}
Beispiel #2
0
PyObject*
select_overload(PyObject* self, PyObject* args)
{
    PyObject *tmcap, *sigtup, *ovsigstup;
    int allow_unsafe;

    if (!PyArg_ParseTuple(args, "OOOi", &tmcap, &sigtup, &ovsigstup,
                          &allow_unsafe)) {
        return NULL;
    }

    TypeManager *tm = unwrap_TypeManager(tmcap);
    if (!tm) {
        BAD_TM_ARGUMENT;
    }

    Py_ssize_t sigsz = PySequence_Size(sigtup);
    Py_ssize_t ovsz = PySequence_Size(ovsigstup);

    Type *sig = new Type[sigsz];
    Type *ovsigs = new Type[ovsz * sigsz];

    for (int i = 0; i < sigsz; ++i) {
        sig[i] = Type(PyNumber_AsSsize_t(PySequence_Fast_GET_ITEM(sigtup,
                                                                  i), NULL));
    }

    for (int i = 0; i < ovsz; ++i) {
        PyObject *cursig = PySequence_Fast_GET_ITEM(ovsigstup, i);
        for (int j = 0; j < sigsz; ++j) {
            long tid = PyNumber_AsSsize_t(PySequence_Fast_GET_ITEM(cursig,
                                                                   j), NULL);
            ovsigs[i * sigsz + j] = Type(tid);
        }
    }

    int selected = -42;
    int matches = tm->selectOverload(sig, ovsigs, selected, sigsz, ovsz,
                                     (bool) allow_unsafe);

    delete [] sig;
    delete [] ovsigs;

    if (matches > 1) {
        PyErr_SetString(PyExc_TypeError, "Ambigous overloading");
        return NULL;
    } else if (matches == 0) {
        PyErr_SetString(PyExc_TypeError, "No compatible overload");
        return NULL;
    }

    return PyLong_FromLong(selected);
}
Beispiel #3
0
PYTHON_INIT_DEFINITION(ptPlayer, args, keywords)
{
    // we have two sets of arguments we can use, hence the generic PyObject* pointers
    // argument set 1: pyKey, string, uint32_t, float
    // argument set 2: string, uint32_t
    PyObject* firstObj = NULL; // can be a pyKey or a string
    PyObject* secondObj = NULL; // can be a string or a uint32_t
    PyObject* thirdObj = NULL; // uint32_t
    PyObject* fourthObj = NULL; // float
    if (!PyArg_ParseTuple(args, "OO|OO", &firstObj, &secondObj, &thirdObj, &fourthObj))
    {
        PyErr_SetString(PyExc_TypeError, "__init__ expects one of two argument lists: (ptKey, string, unsigned long, float) or (string, unsigned long)");
        PYTHON_RETURN_INIT_ERROR;
    }

    plKey key;
    plString name;
    uint32_t pid = -1;
    float distSeq = -1;

    if (pyKey::Check(firstObj))
    {
        if (!(PyString_CheckEx(secondObj) && PyNumber_Check(thirdObj) && PyFloat_Check(fourthObj)))
        {
            PyErr_SetString(PyExc_TypeError, "__init__ expects one of two argument lists: (ptKey, string, unsigned long, float) or (string, unsigned long)");
            PYTHON_RETURN_INIT_ERROR;
        }

        key = pyKey::ConvertFrom(firstObj)->getKey();
        name = PyString_AsStringEx(secondObj);
        pid = PyNumber_AsSsize_t(thirdObj, NULL);
        distSeq = (float)PyFloat_AsDouble(fourthObj);
    } else if (PyString_CheckEx(firstObj)) {
        name = PyString_AsStringEx(firstObj);
        if (!PyNumber_Check(secondObj) || thirdObj  || fourthObj)
        {
            PyErr_SetString(PyExc_TypeError, "__init__ expects one of two argument lists: (ptKey, string, unsigned long, float) or (string, unsigned long)");
            PYTHON_RETURN_INIT_ERROR;
        }

        pid = PyNumber_AsSsize_t(secondObj, NULL);
    } else {
        PyErr_SetString(PyExc_TypeError, "__init__ expects one of two argument lists: (ptKey, string, unsigned long, float) or (string, unsigned long)");
        PYTHON_RETURN_INIT_ERROR;
    }

    self->fThis->Init(key, name.c_str(), pid, distSeq);
    PYTHON_RETURN_INIT_OK;
}
Beispiel #4
0
NUITKA_MAY_BE_UNUSED static Py_ssize_t CONVERT_TO_INDEX( PyObject *value )
{
    assertObject( value );

#if PYTHON_VERSION < 300
    if ( PyInt_Check( value ) )
    {
        return PyInt_AS_LONG( value );
    }
    else
#endif
    if ( PyIndex_Check( value ) )
    {
        Py_ssize_t result = PyNumber_AsSsize_t( value, NULL );

        if (unlikely( result == -1 ))
        {
            THROW_IF_ERROR_OCCURED();
        }

        return result;
    }
    else
    {
        PyErr_Format( PyExc_TypeError, "slice indices must be integers or None or have an __index__ method" );
        throw PythonException();
    }
}
Beispiel #5
0
static PyObject *Euler_subscript(EulerObject *self, PyObject *item)
{
	if (PyIndex_Check(item)) {
		Py_ssize_t i;
		i = PyNumber_AsSsize_t(item, PyExc_IndexError);
		if (i == -1 && PyErr_Occurred())
			return NULL;
		if (i < 0)
			i += EULER_SIZE;
		return Euler_item(self, i);
	} else if (PySlice_Check(item)) {
		Py_ssize_t start, stop, step, slicelength;

		if (PySlice_GetIndicesEx((void *)item, EULER_SIZE, &start, &stop, &step, &slicelength) < 0)
			return NULL;

		if (slicelength <= 0) {
			return PyTuple_New(0);
		}
		else if (step == 1) {
			return Euler_slice(self, start, stop);
		}
		else {
			PyErr_SetString(PyExc_TypeError, "slice steps not supported with eulers");
			return NULL;
		}
	}
	else {
		PyErr_Format(PyExc_TypeError, "euler indices must be integers, not %.200s", Py_TYPE(item)->tp_name);
		return NULL;
	}
}
Beispiel #6
0
/* Function to handle the conversion of base to integers.
 * 0 is success, 1 is failure.
 */
int
assess_integer_base_input(PyObject *pybase, int *base)
{
    Py_ssize_t longbase = 0;

    /* Default to INT_MIN.
     */
    if (pybase == NULL) {
        *base = INT_MIN;
        return 0;
    }

    /* Convert to int and check for overflow.
     */
    longbase = PyNumber_AsSsize_t(pybase, NULL);
    if (longbase == -1 && PyErr_Occurred()) {
        return 1;
    }

    /* Ensure valid integer in valid range.
     */
    if ((longbase != 0 && longbase < 2) || longbase > 36) {
        PyErr_SetString(PyExc_ValueError,
                        "int() base must be >= 2 and <= 36");
        return 1;
    }
    *base = (int) longbase;
    return 0;
}
Beispiel #7
0
static PyObject *
_io__RawIOBase_read_impl(PyObject *self, Py_ssize_t n)
/*[clinic end generated code: output=6cdeb731e3c9f13c input=b6d0dcf6417d1374]*/
{
    PyObject *b, *res;

    if (n < 0) {
        _Py_IDENTIFIER(readall);

        return _PyObject_CallMethodId(self, &PyId_readall, NULL);
    }

    /* TODO: allocate a bytes object directly instead and manually construct
       a writable memoryview pointing to it. */
    b = PyByteArray_FromStringAndSize(NULL, n);
    if (b == NULL)
        return NULL;

    res = PyObject_CallMethodObjArgs(self, _PyIO_str_readinto, b, NULL);
    if (res == NULL || res == Py_None) {
        Py_DECREF(b);
        return res;
    }

    n = PyNumber_AsSsize_t(res, PyExc_ValueError);
    Py_DECREF(res);
    if (n == -1 && PyErr_Occurred()) {
        Py_DECREF(b);
        return NULL;
    }

    res = PyBytes_FromStringAndSize(PyByteArray_AsString(b), n);
    Py_DECREF(b);
    return res;
}
Beispiel #8
0
Box* tupleMul(BoxedTuple* self, Box* rhs) {
    Py_ssize_t n;
    if (PyIndex_Check(rhs)) {
        n = PyNumber_AsSsize_t(rhs, PyExc_OverflowError);
        if (n == -1 && PyErr_Occurred())
            throwCAPIException();
    } else {
        raiseExcHelper(TypeError, "can't multiply sequence by non-int of type '%s'", getTypeName(rhs));
    }

    int s = self->size();

    if (n < 0)
        n = 0;

    if ((s == 0 || n == 1) && PyTuple_CheckExact(self)) {
        return self;
    } else {
        BoxedTuple* rtn = BoxedTuple::create(n * s);
        int rtn_i = 0;
        for (int i = 0; i < n; ++i) {
            memmove(&rtn->elts[rtn_i], &self->elts[0], sizeof(Box*) * s);
            rtn_i += s;
        }
        return rtn;
    }
}
Beispiel #9
0
static int PyBobSpIDCT1D_SetShape
(PyBobSpIDCT1DObject* self, PyObject* o, void* /*closure*/) {

  if (!PySequence_Check(o)) {
    PyErr_Format(PyExc_TypeError, "`%s' shape can only be set using tuples (or sequences), not `%s'", Py_TYPE(self)->tp_name, Py_TYPE(o)->tp_name);
    return -1;
  }

  PyObject* shape = PySequence_Tuple(o);
  auto shape_ = make_safe(shape);

  if (PyTuple_GET_SIZE(shape) != 1) {
    PyErr_Format(PyExc_RuntimeError, "`%s' shape can only be set using 1-position tuples (or sequences), not an %" PY_FORMAT_SIZE_T "d-position sequence", Py_TYPE(self)->tp_name, PyTuple_GET_SIZE(shape));
    return -1;
  }

  Py_ssize_t len = PyNumber_AsSsize_t(PyTuple_GET_ITEM(shape, 0), PyExc_OverflowError);
  if (PyErr_Occurred()) return -1;

  try {
    self->cxx->setLength(len);
  }
  catch (std::exception& ex) {
    PyErr_SetString(PyExc_RuntimeError, ex.what());
    return -1;
  }
  catch (...) {
    PyErr_Format(PyExc_RuntimeError, "cannot reset `shape' of %s: unknown exception caught", Py_TYPE(self)->tp_name);
    return -1;
  }

  return 0;

}
Beispiel #10
0
static int PyPointlessVector_check_index(PyPointlessVector* self, PyObject* item, Py_ssize_t* i)
{
	// if this is not an index: throw an exception
	if (!PyIndex_Check(item)) {
		PyErr_Format(PyExc_TypeError, "PointlessVector: integer indexes please, got <%s>\n", item->ob_type->tp_name);
		return 0;
	}

	// if index value is not an integer: throw an exception
	*i = PyNumber_AsSsize_t(item, PyExc_IndexError);

	if (*i == -1 && PyErr_Occurred())
		return 0;

	// if index is negative, it is relative to vector end
	if (*i < 0)
		*i += PyPointlessVector_length(self);

	// if it is out of bounds: throw an exception
	if (!(0 <= *i && *i < PyPointlessVector_length(self))) {
		PyErr_SetString(PyExc_IndexError, "index is out of bounds");
		return 0;
	}

	return 1;
}
Beispiel #11
0
static int BPy_IDArray_ass_subscript(BPy_IDArray *self, PyObject *item, PyObject *value)
{
    if (PyIndex_Check(item)) {
        Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
        if (i == -1 && PyErr_Occurred())
            return -1;
        if (i < 0)
            i += self->prop->len;
        return BPy_IDArray_SetItem(self, i, value);
    }
    else if (PySlice_Check(item)) {
        Py_ssize_t start, stop, step, slicelength;

        if (PySlice_GetIndicesEx(item, self->prop->len, &start, &stop, &step, &slicelength) < 0)
            return -1;

        if (step == 1)
            return BPy_IDArray_ass_slice(self, start, stop, value);
        else {
            PyErr_SetString(PyExc_TypeError, "slice steps not supported with vectors");
            return -1;
        }
    }
    else {
        PyErr_Format(PyExc_TypeError,
                     "vector indices must be integers, not %.200s",
                     Py_TYPE(item)->tp_name);
        return -1;
    }
}
Beispiel #12
0
static PyObject *t_sequence_map_get(t_sequence* self, PyObject *item)
{
    PyObject *value;

    if (PyIndex_Check(item))
    {
        Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);

        if (i == -1 && PyErr_Occurred())
            return NULL;
        value = t_sequence_seq_get(self, i);
    }
    else if ((!(self->itemvalue.flags & V_PURE)) ||
             (!((self->sequence->ob_type->tp_as_mapping &&
                 self->sequence->ob_type->tp_as_mapping->mp_subscript) ||
                (PyObject_HasAttr(self->sequence, __getitem___NAME)))))
    {
        int size = PySequence_Size(self->sequence);
        PyObject *values;

        if (size < 0)
            return NULL;

        values = t_sequence_seq_getslice(self, 0, size);
        if (!values)
            return NULL;

        value = PyObject_GetItem(values, item);
        Py_DECREF(values);
    }
    else
        value = PyObject_GetItem(self->sequence, item);
    
    return value;
}
static PyObject *bpy_bmdeformvert_subscript(BPy_BMDeformVert *self, PyObject *key)
{
	if (PyIndex_Check(key)) {
		int i;
		i = PyNumber_AsSsize_t(key, PyExc_IndexError);
		if (i == -1 && PyErr_Occurred()) {
			return NULL;
		}
		else {
			MDeformWeight *dw = defvert_find_index(self->data, i);

			if (dw == NULL) {
				PyErr_SetString(PyExc_KeyError, "BMDeformVert[key] = x: "
				                "key not found");
				return NULL;
			}
			else {
				return PyFloat_FromDouble(dw->weight);
			}
		}
	}
	else {
		PyErr_Format(PyExc_TypeError,
		             "BMDeformVert keys must be integers, not %.200s",
		             Py_TYPE(key)->tp_name);
		return NULL;
	}
}
static PyObject *
Affine_subscript(polypaths_planar_overrideAffineObject *self, PyObject *item)
{
    Py_ssize_t i;
    PyObject *t, *s;

    assert(polypaths_planar_overrideAffine_Check(self));
    if (PyIndex_Check(item)) {
        i = PyNumber_AsSsize_t(item, PyExc_IndexError);
        if (i == -1 && PyErr_Occurred()) {
            return NULL;
        }
        if (i < 0) {
            i += Affine_len((PyObject *)self);
        }
        return Affine_getitem(self, i);
    } else if (PySlice_Check(item)) {
        /* We cheat a bit here by constructing a tuple from ourself and 
           slicing that, which is convenient since slicing a transform
           results in a tuple. Not the most efficient, but I don't expect
           transform slicing to be a common, performance sensitive operation
         */
        t = PySequence_Tuple((PyObject *)self);
        if (t == NULL) {
            return NULL;
        }
        s = PyObject_GetItem(t, item);
        Py_DECREF(t);
        return s;
    }
	PyErr_Format(PyExc_TypeError,
		 "Affine indices must be integers, not %.200s",
		 Py_TYPE(item)->tp_name);
	return NULL;
}
Beispiel #15
0
/**
  Helper routine to convert a PyList of integers to a c array of integers.
  */
static int unpack_list_of_ssize_t(PyObject * pylist, Py_ssize_t **dst, Py_ssize_t *len,
                                  const char* kwname)
{
  Py_ssize_t buflen, *buf;
  if (!PyList_Check(pylist))
    {
      PyErr_Format(PyExc_TypeError, "%s must be list", kwname);
      return -1;
    }
  assert (NULL == *dst);
  *len = buflen = PyList_Size(pylist);
  *dst = buf = (Py_ssize_t*)calloc(buflen, sizeof(Py_ssize_t));
  assert(buf);
  for (int ii = 0; ii < buflen; ++ii)
    {
      PyObject * el_i = PyList_GetItem(pylist, ii);
      Py_ssize_t n_i = PyNumber_AsSsize_t(el_i, PyExc_IndexError);
      if (PyErr_Occurred())
        {
          free(buf);
          *dst = NULL;
          return -1;
        }
      buf[ii] = n_i;
    }
  return 0;
}
Beispiel #16
0
static PyObject* PyBlitzArray_getitem(PyBlitzArrayObject* self,
    PyObject* item) {

  if (PyBob_NumberCheck(item)) {

    if (self->ndim != 1) {
      PyErr_Format(PyExc_TypeError, "expected tuple for accessing %" PY_FORMAT_SIZE_T "dD array", self->ndim);
      return 0;
    }

    // if you get to this point, the user has passed single number
    Py_ssize_t k = PyNumber_AsSsize_t(item, PyExc_IndexError);
    return PyBlitzArray_GetItem(self, &k);

  }

  if (PySequence_Check(item)) {

    if (self->ndim != PySequence_Fast_GET_SIZE(item)) {
      PyErr_Format(PyExc_TypeError, "expected tuple of size %" PY_FORMAT_SIZE_T "d for accessing %" PY_FORMAT_SIZE_T "dD array", self->ndim, self->ndim);
      return 0;
    }

    // if you get to this point, then the input tuple has the same size
    PyBlitzArrayObject shape;
    PyBlitzArrayObject* shape_p = &shape;
    if (!PyBlitzArray_IndexConverter(item, &shape_p)) return 0;
    return PyBlitzArray_GetItem(self, shape.shape);

  }

  PyErr_Format(PyExc_TypeError, "%s(@%" PY_FORMAT_SIZE_T "d,'%s') indexing requires a single integers (for 1D arrays) or sequences, for any rank size", Py_TYPE(self)->tp_name, self->ndim, PyBlitzArray_TypenumAsString(self->type_num));
  return 0;
}
Beispiel #17
0
PyObject* igraphmodule_EdgeSeq_get_attribute_values_mapping(igraphmodule_EdgeSeqObject *self, PyObject *o) {
  Py_ssize_t index;

  /* Handle integer indices according to the sequence protocol */
  if (PyIndex_Check(o)) {
    index = PyNumber_AsSsize_t(o, 0);
    return igraphmodule_EdgeSeq_sq_item(self, index);
  }

  /* Handle strings according to the mapping protocol */
  if (PyBaseString_Check(o))
    return igraphmodule_EdgeSeq_get_attribute_values(self, o);

  /* Handle iterables and slices by calling the select() method */
  if (PySlice_Check(o) || PyObject_HasAttrString(o, "__iter__")) {
    PyObject *result, *args;
    args = Py_BuildValue("(O)", o);
    if (!args)
      return NULL;
    result = igraphmodule_EdgeSeq_select(self, args);
    Py_DECREF(args);
    return result;
  }

  /* Handle everything else according to the mapping protocol */
  return igraphmodule_EdgeSeq_get_attribute_values(self, o);
}
Beispiel #18
0
static int Color_ass_subscript(ColorObject *self, PyObject *item, PyObject *value)
{
	if (PyIndex_Check(item)) {
		Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
		if (i == -1 && PyErr_Occurred())
			return -1;
		if (i < 0)
			i += COLOR_SIZE;
		return Color_ass_item(self, i, value);
	}
	else if (PySlice_Check(item)) {
		Py_ssize_t start, stop, step, slicelength;

		if (PySlice_GetIndicesEx((void *)item, COLOR_SIZE, &start, &stop, &step, &slicelength) < 0)
			return -1;

		if (step == 1)
			return Color_ass_slice(self, start, stop, value);
		else {
			PyErr_SetString(PyExc_IndexError,
			                "slice steps not supported with color");
			return -1;
		}
	}
	else {
		PyErr_Format(PyExc_TypeError,
		             "color indices must be integers, not %.200s",
		             Py_TYPE(item)->tp_name);
		return -1;
	}
}
Beispiel #19
0
static int PyBobSpIDCT1D_SetLength
(PyBobSpIDCT1DObject* self, PyObject* o, void* /*closure*/) {

  if (!PyBob_NumberCheck(o)) {
    PyErr_Format(PyExc_TypeError, "`%s' length can only be set using a number, not `%s'", Py_TYPE(self)->tp_name, Py_TYPE(o)->tp_name);
    return -1;
  }

  Py_ssize_t len = PyNumber_AsSsize_t(o, PyExc_OverflowError);
  if (PyErr_Occurred()) return -1;

  try {
    self->cxx->setLength(len);
  }
  catch (std::exception& ex) {
    PyErr_SetString(PyExc_RuntimeError, ex.what());
    return -1;
  }
  catch (...) {
    PyErr_Format(PyExc_RuntimeError, "cannot reset `length' of %s: unknown exception caught", Py_TYPE(self)->tp_name);
    return -1;
  }

  return 0;

}
Beispiel #20
0
static int PyBobLearnMLPTrainer_setBatchSize
(PyBobLearnMLPTrainerObject* self, PyObject* o, void* /*closure*/) {

  Py_ssize_t value = PyNumber_AsSsize_t(o, PyExc_OverflowError);
  if (PyErr_Occurred()) return -1;
  self->cxx->setBatchSize(value);
  return 0;

}
static PyObject *bpy_bmlayercollection_subscript(BPy_BMLayerCollection *self, PyObject *key)
{
	/* don't need error check here */
	if (PyUnicode_Check(key)) {
		return bpy_bmlayercollection_subscript_str(self, _PyUnicode_AsString(key));
	}
	else if (PyIndex_Check(key)) {
		Py_ssize_t i = PyNumber_AsSsize_t(key, PyExc_IndexError);
		if (i == -1 && PyErr_Occurred())
			return NULL;
		return bpy_bmlayercollection_subscript_int(self, i);
	}
	else if (PySlice_Check(key)) {
		PySliceObject *key_slice = (PySliceObject *)key;
		Py_ssize_t step = 1;

		if (key_slice->step != Py_None && !_PyEval_SliceIndex(key, &step)) {
			return NULL;
		}
		else if (step != 1) {
			PyErr_SetString(PyExc_TypeError,
			                "BMLayerCollection[slice]: slice steps not supported");
			return NULL;
		}
		else if (key_slice->start == Py_None && key_slice->stop == Py_None) {
			return bpy_bmlayercollection_subscript_slice(self, 0, PY_SSIZE_T_MAX);
		}
		else {
			Py_ssize_t start = 0, stop = PY_SSIZE_T_MAX;

			/* avoid PySlice_GetIndicesEx because it needs to know the length ahead of time. */
			if (key_slice->start != Py_None && !_PyEval_SliceIndex(key_slice->start, &start)) return NULL;
			if (key_slice->stop != Py_None && !_PyEval_SliceIndex(key_slice->stop, &stop))    return NULL;

			if (start < 0 || stop < 0) {
				/* only get the length for negative values */
				Py_ssize_t len = bpy_bmlayercollection_length(self);
				if (start < 0) start += len;
				if (stop  < 0) stop  += len;
			}

			if (stop - start <= 0) {
				return PyTuple_New(0);
			}
			else {
				return bpy_bmlayercollection_subscript_slice(self, start, stop);
			}
		}
	}
	else {
		PyErr_SetString(PyExc_AttributeError,
		                "BMLayerCollection[key]: invalid key, key must be an int");
		return NULL;
	}
}
static PyObject*
tuplesubscript(PyTupleObject* self, PyObject* item)
{
    if (PyIndex_Check(item)) {
        Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
        if (i == -1 && PyErr_Occurred())
            return NULL;
        if (i < 0)
            i += PyTuple_GET_SIZE(self);
        return tupleitem(self, i);
    }
    else if (PySlice_Check(item)) {
        Py_ssize_t start, stop, step, slicelength, cur, i;
        PyObject* result;
        PyObject* it;
        PyObject **src, **dest;

        if (PySlice_GetIndicesEx(item,
                         PyTuple_GET_SIZE(self),
                         &start, &stop, &step, &slicelength) < 0) {
            return NULL;
        }

        if (slicelength <= 0) {
            return PyTuple_New(0);
        }
        else if (start == 0 && step == 1 &&
                 slicelength == PyTuple_GET_SIZE(self) &&
                 PyTuple_CheckExact(self)) {
            Py_INCREF(self);
            return (PyObject *)self;
        }
        else {
            result = PyTuple_New(slicelength);
            if (!result) return NULL;

            src = self->ob_item;
            dest = ((PyTupleObject *)result)->ob_item;
            for (cur = start, i = 0; i < slicelength;
                 cur += step, i++) {
                it = src[cur];
                Py_INCREF(it);
                dest[i] = it;
            }

            return result;
        }
    }
    else {
        PyErr_Format(PyExc_TypeError,
                     "tuple indices must be integers, not %.200s",
                     Py_TYPE(item)->tp_name);
        return NULL;
    }
}
Beispiel #23
0
/*
 * Implement mapping assignment sub-script for the type.
 */
static int sipArray_ass_subscript(PyObject *self, PyObject *key,
        PyObject *value)
{
    sipArrayObject *array = (sipArrayObject *)self;
    SIP_SSIZE_T start, len;
    void *value_data;

    if (check_writable(array) < 0)
        return -1;

    if (PyIndex_Check(key))
    {
        start = PyNumber_AsSsize_t(key, PyExc_IndexError);

        if (start == -1 && PyErr_Occurred())
            return -1;

        if (start < 0)
            start += array->len;

        if (check_index(array, start) < 0)
            return -1;

        if ((value_data = get_value(array, value)) == NULL)
            return -1;

        len = 1;
    }
    else if (PySlice_Check(key))
    {
        Py_ssize_t stop, step;

        if (sipConvertFromSliceObject(key, array->len, &start, &stop, &step, &len) < 0)
            return -1;

        if (step != 1)
        {
            PyErr_SetNone(PyExc_NotImplementedError);
            return -1;
        }

        if ((value_data = get_slice(array, value, len)) == NULL)
            return -1;
    }
    else
    {
        bad_key(key);

        return -1;
    }

    memmove(element(array, start), value_data, len * array->stride);

    return 0;
}
Beispiel #24
0
static PyObject *bserobj_getattrro(PyObject *o, PyObject *name) {
  bserObject *obj = (bserObject*)o;
  Py_ssize_t i, n;
  PyObject *name_bytes = NULL;
  PyObject *ret = NULL;
  const char *namestr;

  if (PyIndex_Check(name)) {
    i = PyNumber_AsSsize_t(name, PyExc_IndexError);
    if (i == -1 && PyErr_Occurred()) {
      goto bail;
    }
    ret = PySequence_GetItem(obj->values, i);
    goto bail;
  }

  // We can be passed in Unicode objects here -- we don't support anything other
  // than UTF-8 for keys.
  if (PyUnicode_Check(name)) {
    name_bytes = PyUnicode_AsUTF8String(name);
    if (name_bytes == NULL) {
      goto bail;
    }
    namestr = PyBytes_AsString(name_bytes);
  } else {
    namestr = PyBytes_AsString(name);
  }

  if (namestr == NULL) {
    goto bail;
  }
  // hack^Wfeature to allow mercurial to use "st_size" to reference "size"
  if (!strncmp(namestr, "st_", 3)) {
    namestr += 3;
  }

  n = PyTuple_GET_SIZE(obj->keys);
  for (i = 0; i < n; i++) {
    const char *item_name = NULL;
    PyObject *key = PyTuple_GET_ITEM(obj->keys, i);

    item_name = PyBytes_AsString(key);
    if (!strcmp(item_name, namestr)) {
      ret = PySequence_GetItem(obj->values, i);
      goto bail;
    }
  }

  PyErr_Format(PyExc_AttributeError,
              "bserobject has no attribute '%.400s'", namestr);
 bail:
  Py_XDECREF(name_bytes);
  return ret;
}
Beispiel #25
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(o, PyNumber_AsSsize_t(index, 0), v);

    return PyObject_GenericSetAttr(o, name, v);
}
Beispiel #26
0
static int py_anal(RAnal *a, RAnalOp *op, ut64 addr, const ut8 *buf, int len, RAnalOpMask mask) {
	PyObject *tmpreg = NULL;
	int size = 0;
	int seize = -1;
	int i = 0;
	if (!op) return -1;
	if (py_anal_cb) {
		memset(op, 0, sizeof (RAnalOp));
		// anal(addr, buf) - returns size + dictionary (structure) for RAnalOp
		Py_buffer pybuf = {
			.buf = (void *) buf, // Warning: const is lost when casting
			.len = len,
			.readonly = 1,
			.ndim = 1,
			.itemsize = 1,
		};
		PyObject *memview = PyMemoryView_FromBuffer (&pybuf);
		PyObject *arglist = Py_BuildValue ("(NK)", memview, addr);
		PyObject *result = PyEval_CallObject (py_anal_cb, arglist);
		if (result && PyList_Check (result)) {
			PyObject *len = PyList_GetItem (result, 0);
			PyObject *dict = PyList_GetItem (result, 1);
			if (dict && PyDict_Check (dict)) {
				seize = PyNumber_AsSsize_t (len, NULL);
				op->type = getI (dict, "type");
				op->cycles = getI (dict, "cycles");
				op->size = seize;
				op->addr = getI (dict, "addr");
				op->jump = getI (dict, "jump");
				op->fail = getI (dict, "fail");
				op->stackop = getI (dict, "stackop");
				op->stackptr = getI (dict, "stackptr");
				op->ptr = getI (dict, "ptr");
				op->eob = getB (dict, "eob");
				// Loading 'src' and 'dst' values
				// SRC is is a list of 3 elements
				PyObject *tmpsrc = getO (dict, "src");
				if (tmpsrc && PyList_Check (tmpsrc)) {
					for (i = 0; i < 3; i++) {
						PyObject *tmplst = PyList_GetItem (tmpsrc, i);
						// Read value and underlying regs
						READ_VAL(tmplst, op->src[i], tmpreg)
					}
				}
				PyObject *tmpdst = getO (dict, "dst");
				// Read value and underlying regs
				READ_VAL(tmpdst, op->dst, tmpreg)
				// Loading 'var' value if presented
				r_strbuf_set (&op->esil, getS (dict, "esil"));
				// TODO: Add opex support here
				Py_DECREF (dict);
			}
			Py_DECREF (result);
		} else {
static PyObject *
buffer_subscript(PyBufferObject *self, PyObject *item)
{
    void *p;
    Py_ssize_t size;

    if (!get_buf(self, &p, &size, ANY_BUFFER))
        return NULL;
    if (PyIndex_Check(item)) {
        Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
        if (i == -1 && PyErr_Occurred())
            return NULL;
        if (i < 0)
            i += size;
        return buffer_item(self, i);
    }
    else if (PySlice_Check(item)) {
        Py_ssize_t start, stop, step, slicelength, cur, i;

        if (PySlice_GetIndicesEx((PySliceObject*)item, size,
                         &start, &stop, &step, &slicelength) < 0) {
            return NULL;
        }

        if (slicelength <= 0)
            return PyString_FromStringAndSize("", 0);
        else if (step == 1)
            return PyString_FromStringAndSize((char *)p + start,
                                              stop - start);
        else {
            PyObject *result;
            char *source_buf = (char *)p;
            char *result_buf = (char *)PyMem_Malloc(slicelength);

            if (result_buf == NULL)
                return PyErr_NoMemory();

            for (cur = start, i = 0; i < slicelength;
                 cur += step, i++) {
                result_buf[i] = source_buf[cur];
            }

            result = PyString_FromStringAndSize(result_buf,
                                                slicelength);
            PyMem_Free(result_buf);
            return result;
        }
    }
    else {
        PyErr_SetString(PyExc_TypeError,
                        "sequence index must be integer");
        return NULL;
    }
}
Beispiel #28
0
static PyObject *
mmap_subscript(mmap_object *self, PyObject *item)
{
    CHECK_VALID(NULL);
    if (PyIndex_Check(item)) {
        Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
        if (i == -1 && PyErr_Occurred())
            return NULL;
        if (i < 0)
            i += self->size;
        if (i < 0 || i >= self->size) {
            PyErr_SetString(PyExc_IndexError,
                "mmap index out of range");
            return NULL;
        }
        return PyLong_FromLong(Py_CHARMASK(self->data[i]));
    }
    else if (PySlice_Check(item)) {
        Py_ssize_t start, stop, step, slicelen;

        if (PySlice_Unpack(item, &start, &stop, &step) < 0) {
            return NULL;
        }
        slicelen = PySlice_AdjustIndices(self->size, &start, &stop, step);

        if (slicelen <= 0)
            return PyBytes_FromStringAndSize("", 0);
        else if (step == 1)
            return PyBytes_FromStringAndSize(self->data + start,
                                              slicelen);
        else {
            char *result_buf = (char *)PyMem_Malloc(slicelen);
            Py_ssize_t cur, i;
            PyObject *result;

            if (result_buf == NULL)
                return PyErr_NoMemory();
            for (cur = start, i = 0; i < slicelen;
                 cur += step, i++) {
                result_buf[i] = self->data[cur];
            }
            result = PyBytes_FromStringAndSize(result_buf,
                                                slicelen);
            PyMem_Free(result_buf);
            return result;
        }
    }
    else {
        PyErr_SetString(PyExc_TypeError,
                        "mmap indices must be integers");
        return NULL;
    }
}
Beispiel #29
0
static inline void checkedImportModule (const char *name, bool decref)
{
  qDebug () << "Attempting import of " << name << "\n";
  PyObject *config_module = PyImport_ImportModule (name);
  PyObject *etype, *evalue, *etraceback;
  etype = NULL;
  evalue = NULL;
  etraceback = NULL;
  PyErr_Fetch (&etype, &evalue, &etraceback);
  if (evalue != NULL)
    { 
      if (checkTypeIsExit (etype))
	{
	  Py_ssize_t the_code = PyNumber_AsSsize_t (evalue, NULL);
	  rfgisExit ((int)the_code);
	}
      else
	{
	  if (etraceback != NULL)
	    {
	      /* If the application ends up here, it means trouble */
	      PyObject *traceback_module = PyImport_ImportModule ("traceback");
	      PyObject *args = PyTuple_New (3);
	      PyObject *traceback_module_dict = PyModule_GetDict (traceback_module);
	      PyTuple_SetItem (args, 0, etype);
	      PyTuple_SetItem (args, 1, evalue);
	      PyTuple_SetItem (args, 2, etraceback);
	      PyObject *func = PyDict_GetItemString (traceback_module_dict, 
						     "format_exception");
	      PyObject *res = PyObject_CallObject (func, args);
	      if (res)
		{
		  for (Py_ssize_t i = 0; i < PyList_GET_SIZE (res); ++i)
		    {
		      PyObject *item = PyList_GET_ITEM (res, i);
		      QString s = PyString_AsString (item);
		      Py_XDECREF (item);
		      qDebug() << s;
		    }
		}
	  
	      Py_XDECREF (args);
	      Py_XDECREF (traceback_module);
	    }
	  rfgisExit (01);
	}
    }
  else if (decref)
    {
      Py_XDECREF (config_module);
    }

}
Beispiel #30
0
static PyObject* Row_subscript(PyObject* o, PyObject* key)
{
    Row* row = (Row*)o;

    if (PyIndex_Check(key))
    {
        Py_ssize_t i = PyNumber_AsSsize_t(key, PyExc_IndexError);
        if (i == -1 && PyErr_Occurred())
            return 0;
        if (i < 0)
            i += row->cValues;

        if (i < 0 || i >= row->cValues)
            return PyErr_Format(PyExc_IndexError, "row index out of range index=%d len=%d", (int)i, (int)row->cValues);

        Py_INCREF(row->apValues[i]);
        return row->apValues[i];
    }

    if (PySlice_Check(key))
    {
        Py_ssize_t start, stop, step, slicelength;
#if PY_VERSION_HEX >= 0x03020000
        if (PySlice_GetIndicesEx(key, row->cValues, &start, &stop, &step, &slicelength) < 0)
            return 0;
#else
        if (PySlice_GetIndicesEx((PySliceObject*)key, row->cValues, &start, &stop, &step, &slicelength) < 0)
            return 0;
#endif

        if (slicelength <= 0)
            return PyTuple_New(0);

        if (start == 0 && step == 1 && slicelength == row->cValues)
        {
            Py_INCREF(o);
            return o;
        }

        Object result(PyTuple_New(slicelength));
        if (!result)
            return 0;
        for (Py_ssize_t i = 0, index = start; i < slicelength; i++, index += step)
        {
            PyTuple_SET_ITEM(result.Get(), i, row->apValues[index]);
            Py_INCREF(row->apValues[index]);
        }
        return result.Detach();
    }

    return PyErr_Format(PyExc_TypeError, "row indices must be integers, not %.200s", Py_TYPE(key)->tp_name);
}