예제 #1
0
//-------------------------------------------------------------------------
Py_ssize_t pyvar_walk_list(
  PyObject *py_list,
  int (*cb)(PyObject *py_item, Py_ssize_t index, void *ud),
  void *ud)
{
  if ( !PyList_CheckExact(py_list) && !PyW_IsSequenceType(py_list) )
    return CIP_FAILED;

  bool is_seq = !PyList_CheckExact(py_list);
  Py_ssize_t size = is_seq ? PySequence_Size(py_list) : PyList_Size(py_list);

  if ( cb == NULL )
    return size;

  Py_ssize_t i;
  for ( i=0; i<size; i++ )
  {
    // Get the item
    PyObject *py_item = is_seq ? PySequence_GetItem(py_list, i) : PyList_GetItem(py_list, i);
    if ( py_item == NULL )
      break;

    int r = cb(py_item, i, ud);

    // Decrement reference (if needed)
    if ( r != CIP_OK_NODECREF && is_seq )
      Py_DECREF(py_item); // Only sequences require us to decrement the reference
    if ( r < CIP_OK )
      break;
  }
  return i;
}
bool BINARY_OPERATION_ADD_OBJECT_LIST_INPLACE(PyObject **operand1, PyObject *operand2) {
    assert(operand1);
    CHECK_OBJECT(*operand1);
    CHECK_OBJECT(operand2);
    assert(PyList_CheckExact(operand2));

    PyObject *result;

    if (PyList_CheckExact(*operand1)) {
        return LIST_EXTEND_FROM_LIST(*operand1, operand2);
    } else if (PySequence_Check(*operand1)) {
        result = PySequence_InPlaceConcat(*operand1, operand2);
    } else {
        result = PyNumber_InPlaceAdd(*operand1, operand2);
    }

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

    // We got an object handed, that we have to release.
    Py_DECREF(*operand1);

    // That's our return value then. As we use a dedicated variable, it's
    // OK that way.
    *operand1 = result;

    return true;
}
예제 #3
0
파일: array.c 프로젝트: python-postgres/be
/*
 * py_list_depth - get the ndims of nested PyLists
 *
 * If the depth exceeds MAXDIM, an error will be thrown.
 * This will protect against recursive lists.
 */
static int
py_list_depth(PyObj seq)
{
	int d = 0;

	Assert(PyList_CheckExact(seq));

	while (PyList_CheckExact(seq))
	{
		++d;
		if (d > MAXDIM)
		{
			ereport(ERROR,
					(errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
					 errmsg("depth of list exceeds the maximum allowed dimensions (%d)",
							MAXDIM),
					 errhint("A recursive list object can also be the cause this error.")));
		}
		if (PyList_GET_SIZE(seq) > 0)
			seq = PyList_GET_ITEM(seq, 0);
		else
		{
			/*
			 * Not a PyList, then it's not a "dimension".
			 */
			break;
		}
	}

	return(d);
}
예제 #4
0
/**
 * Helper function to convert Python objects into a representation that the
 * rrdtool functions can work with.
 *
 * @param command RRDtool command name
 * @param args Command arguments
 * @return Zero if the function succeeds, otherwise -1
 */
static int
convert_args(char *command, PyObject *args)
{
    PyObject *o, *lo;
    int i, j, args_count, argv_count, element_count;

    argv_count = element_count = 0;
    args_count = PyTuple_Size(args);

    for (i = 0; i < args_count; i++) {
        o = PyTuple_GET_ITEM(args, i);

        if (PyRRD_String_Check(o))
            element_count++;
        else if (PyList_CheckExact(o))
            element_count += PyList_Size(o);
        else {
            PyErr_Format(PyExc_TypeError,
                         "Argument %d must be str or a list of str", i);
            return -1;
        }
    }

    rrdtool_argv = PyMem_New(char *, element_count + 1);

    if (rrdtool_argv == NULL)
        return -1;

    for (i = 0; i < args_count; i++) {
        o = PyTuple_GET_ITEM(args, i);

        if (PyRRD_String_Check(o))
            rrdtool_argv[++argv_count] = PyRRD_String_AS_STRING(o);
        else if (PyList_CheckExact(o)) {
            for (j = 0; j < PyList_Size(o); j++) {
                lo = PyList_GetItem(o, j);

                if (PyRRD_String_Check(lo))
                    rrdtool_argv[++argv_count] = PyRRD_String_AS_STRING(lo);
                else {
                    PyMem_Del(rrdtool_argv);
                    PyErr_Format(PyExc_TypeError,
                      "Element %d in argument %d must be str", j, i);
                    return -1;
                }
            }
        } else {
            PyMem_Del(rrdtool_argv);
            PyErr_Format(rrdtool_ProgrammingError,
              "Argument %d must be str or list of str", i);
            return -1;
        }
    }

    rrdtool_argv[0] = command;
    rrdtool_argc = element_count + 1;

    return 0;
}
bool BINARY_OPERATION_ADD_LIST_LIST_INPLACE(PyObject **operand1, PyObject *operand2) {
    assert(operand1);
    CHECK_OBJECT(*operand1);
    CHECK_OBJECT(operand2);
    assert(PyList_CheckExact(*operand1));
    assert(PyList_CheckExact(operand2));

    return LIST_EXTEND_FROM_LIST(*operand1, operand2);
}
예제 #6
0
int DisassembleMatrix(PyObject *pMatrixList, float **pMatrix, int *rows, int *cols){
	// builds a C matrix from a list
	// assumes a row major representation
	// returns 0 on failure
	if( !PyList_CheckExact(pMatrixList) ) return(0);
	*rows = PyList_GET_SIZE(pMatrixList);
	if(*rows == 0){
		*cols = 0;
		*pMatrix = NULL;
		return(1);
	}
	int ii, jj;
	PyObject* rowList;
	PyObject* matrixElement;
	int nColumnsLocal;
	double dVal;
	*cols = -1;
	for(ii = 0; ii < *rows; ii++){
		rowList = PyList_GET_ITEM(pMatrixList, ii);
		if( !PyList_CheckExact(rowList) ) 
			if( *cols != -1 ){
				free(*pMatrix);
				return(0);
			}
		// get the number of columns
		nColumnsLocal = PyList_GET_SIZE(rowList);
		if(*cols == -1){
			*cols = nColumnsLocal;
			*pMatrix = (float*)malloc((*rows)*(*cols)*sizeof(float));
			if(*pMatrix == NULL)
				return(0);
		}
		else if(nColumnsLocal != *cols){
			// the matrix list does not have proper sizes
			free(*pMatrix);
			return(0);
		}
		// copy all list elements into the matrix
		for(jj = 0; jj < *cols; jj++){
			matrixElement = PyList_GET_ITEM(rowList, jj);
			dVal = PyFloat_AsDouble(matrixElement);
			if(dVal == -1.0 && PyErr_Occurred()){
				free(*pMatrix);
				return(0);
			}
			(*pMatrix)[ii * (*cols) + jj] = (float)(dVal);
		}
	}
	return(1);
}
예제 #7
0
파일: array.c 프로젝트: python-postgres/be
/*
 * Concatenate, but subjectively for supporting the distinction drawn by PyList
 * objects.
 */
static PyObj
array_add(PyObj self, PyObj with)
{
	PyObj wrapper, rob;

	if (!PyList_CheckExact(with) && !PyPgObject_Check(with))
	{
		/*
		 * It's probably an element object.
		 */
		wrapper = PyList_New(1);
		if (wrapper == NULL)
			return(NULL);
		PyList_SET_ITEM(wrapper, 0, with);
		Py_INCREF(with);
	}
	else
	{
		wrapper = with;
		Py_INCREF(wrapper);
	}

	rob = PyPgObject_Operate("||", self, wrapper);
	Py_DECREF(wrapper);

	return(rob);
}
예제 #8
0
파일: py_util.c 프로젝트: TheProjecter/jxtl
static void py_variable_to_json_internal( PyObject *obj,
                                          json_writer_t *writer )
{
  if ( PyString_CheckExact( obj ) ) {
    json_writer_write_str( writer, PyString_AS_STRING( obj ) );
  }
  else if ( PyInt_CheckExact( obj ) ) {
    json_writer_write_integer( writer, PyInt_AS_LONG( obj ) );
  }
  else if ( PyFloat_CheckExact( obj ) ) {
    json_writer_write_number( writer, PyFloat_AS_DOUBLE( obj ) );
  }
  else if ( PyBool_Check( obj ) ) {
    json_writer_write_boolean( writer, ( obj == Py_True ) );
  }
  else if ( PyUnicode_CheckExact( obj ) ) {
    /* Create a new string object that is UTF-8 encoded. */
    Py_UNICODE *unicode = PyUnicode_AS_UNICODE( obj );
    Py_ssize_t size = PyUnicode_GET_SIZE( obj );
    PyObject *str_obj = PyUnicode_EncodeUTF8( unicode, size, NULL );
    py_variable_to_json_internal( str_obj, writer );
    PyObject_Free( str_obj );
  }
  else if ( PyDict_CheckExact( obj ) ) {
    py_dict_to_json( obj, writer );
  }
  else if ( PyList_CheckExact( obj ) ) {
    py_list_to_json( obj, writer );
  }
  else if ( PyTuple_CheckExact( obj ) ) {
    py_tuple_to_json( obj, writer ); 
  }
}
// Convert a Python list object to a QList<QObject*> and return true if the
// conversion was successful.  An empty list is never converted and left to the
// QtCore module to handle.
static bool to_QList_QObject(PyObject *obj, QList<QObject *>&cpp)
{
    if (!PyList_CheckExact(obj) || PyList_GET_SIZE(obj) == 0)
        return false;

    for (SIP_SSIZE_T i = 0; i < PyList_GET_SIZE(obj); ++i)
    {
        PyObject *val_obj = PyList_GET_ITEM(obj, i);

        if (!val_obj)
            return false;

        int iserr = 0;

        QObject *val = reinterpret_cast<QObject *>(sipForceConvertToType(
                val_obj, sipType_QObject, 0, SIP_NO_CONVERTORS, 0, &iserr));

        if (iserr)
            return false;

        cpp.append(val);
    }

    return true;
}
예제 #10
0
// Convert a Python list object to a QVariantList and return true if there was
// no error.
bool Chimera::to_QVariantList(PyObject *py, QVariantList &cpp) const
{
    Q_ASSERT(PyList_CheckExact(py));

    for (SIP_SSIZE_T i = 0; i < PyList_GET_SIZE(py); ++i)
    {
        PyObject *val_obj = PyList_GET_ITEM(py, i);

        if (!val_obj)
            return false;

        int val_state, iserr = 0;

        QVariant *val = reinterpret_cast<QVariant *>(sipForceConvertToType(
                val_obj, sipType_QVariant, 0, SIP_NOT_NONE, &val_state,
                &iserr));

        if (iserr)
            return false;

        cpp.append(*val);

        sipReleaseType(val, sipType_QVariant, val_state);
    }

    return true;
}
예제 #11
0
static int
BaseRowProxy_init(BaseRowProxy *self, PyObject *args, PyObject *kwds)
{
    PyObject *parent, *row, *processors, *keymap;

    if (!PyArg_UnpackTuple(args, "BaseRowProxy", 4, 4,
                           &parent, &row, &processors, &keymap))
        return -1;

    Py_INCREF(parent);
    self->parent = parent;

    if (!PySequence_Check(row)) {
        PyErr_SetString(PyExc_TypeError, "row must be a sequence");
        return -1;
    }
    Py_INCREF(row);
    self->row = row;

    if (!PyList_CheckExact(processors)) {
        PyErr_SetString(PyExc_TypeError, "processors must be a list");
        return -1;
    }
    Py_INCREF(processors);
    self->processors = processors;

    if (!PyDict_CheckExact(keymap)) {
        PyErr_SetString(PyExc_TypeError, "keymap must be a dict");
        return -1;
    }
    Py_INCREF(keymap);
    self->keymap = keymap;

    return 0;
}
예제 #12
0
void pb_num_feature::add_feature(
    const std::string& key,
    double value,
    std::vector<std::pair<std::string, double> >& ret_fv) const {
  scoped_gil lk;

  pb_object pkey(pb_unicode_from_string(key));
  PB_CHECK(pkey,
           "cannot convert input key to Python object: " << key);

  pb_object pval(PyFloat_FromDouble(value));
  PB_CHECK(pval,
           "cannot convert input value to Python object for key: " << key);

  pb_object ret(PyObject_CallMethodObjArgs(
      ins_.get(),
      method_.get(),
      pkey.get(),
      pval.get(),
      NULL));
  PB_CHECK(ret,
           name_ << " method cannot be called");
  PB_CHECK(PyList_CheckExact(ret.get()),
           name_ << " method returned non-list type: " << pb_str(ret.get()));

  size_t size = PyList_Size(ret.get());
  for (size_t i = 0; i < size; ++i) {
    PyObject* tpl = PyList_GetItem(ret.get(), i);

    PB_CHECK(tpl,
             "item " << i << " cannot be accessed: "
             << pb_str(ret.get()));
    PB_CHECK(PyTuple_CheckExact(tpl),
             "list must not contain non-tuple: " << pb_str(tpl));
    PB_CHECK(PyTuple_Size(tpl) == 2,
             "tuple length must be 2: " << pb_str(tpl));

    PyObject* f_key = PyTuple_GetItem(tpl, 0);
    PyObject* f_val = PyTuple_GetItem(tpl, 1);

    PB_CHECK(PyUnicode_CheckExact(f_key),
             "feature key must be a unicode string: " << pb_str(tpl));
    PB_CHECK(PyNumber_Check(f_val),
             "feature value must be a number: " << pb_str(tpl));

    pb_object f_key_enc(PyUnicode_AsUTF8String(f_key));
    PB_CHECK(f_key_enc,
             "feature key cannot be encoded as UTF-8: "
             << pb_str(tpl));
    pb_object f_val_float(PyNumber_Float(f_val));
    PB_CHECK(f_val_float,
             "value cannot be converted as float: " << pb_str(tpl));

    ret_fv.push_back(std::make_pair(
        std::string(PyBytes_AsString(f_key_enc.get())),
        PyFloat_AsDouble(f_val_float.get())));
  }
}
예제 #13
0
파일: reader.c 프로젝트: kuno/python-stdnet
static void *tryParentize(const redisReadTask *task, PyObject *obj) {
    PyObject *parent;
    if (task && task->parent) {
        parent = (PyObject*)task->parent->obj;
        assert(PyList_CheckExact(parent));
        PyList_SET_ITEM(parent, task->idx, obj);
    }
    return obj;
}
예제 #14
0
파일: common1.c 프로젝트: brogar/pykdb
static 
PyObject* from_table_kobject(K x){
     /* 
	the strategy is to create a list of tuples these are then
	passed to OrderedDict to retain the order of the columns for
	example OrderedDict([('pear', 1), ('orange', 2), ('banana',
	3), ('apple', 4)]). OrderedDict does not have a c-api so use a
	callback constructor 
     */
     
     PyObject* result ;
     Py_ssize_t i, length;
     PyObject *keys ;
     PyObject *vals ;

     PyObject *collectionsName, *collectionsMod, *OrderedDict, *pDict,
	  *list, *tple, *args;
     keys = from_any_kobject( kK(x->k)[0] );
     vals = from_columns_kobject( kK(x->k)[1] );

     collectionsName = PyUnicode_FromString((char*)"collections");
     collectionsMod  = PyImport_Import(collectionsName);
     Py_DECREF(collectionsName);
     if(collectionsMod != NULL) {
	  /* printf("creating ordered table\n"); */
	  length = PyList_Size(keys);
	  list = PyList_New(length);
	  for(i = 0; i != length; ++i) {
	       /* tple create new ref, pylist_setitem steals it */
	       tple = PyTuple_Pack(2, PyList_GetItem(keys, i), PyList_GetItem(vals, i));
	       PyList_SetItem(list, i, tple);
	  }
	  pDict = PyModule_GetDict(collectionsMod); // borrowed ref
	  OrderedDict = PyDict_GetItemString(pDict, (char*)"OrderedDict"); // borrowed ref
	  args = PyTuple_Pack(1, list); // new ref
	  result = PyObject_CallObject(OrderedDict, args); // new ref

	  Py_DECREF(args);
	  Py_DECREF(collectionsMod);
	  Py_DECREF(list);
     } else {
	  /* printf("creating unordered table\n"); */
	  result = PyDict_New();
	  if( PyList_CheckExact(keys)) {
	       length = PyList_Size(keys);
	       for(i = 0; i != length; ++i) {
		    PyDict_SetItem(result, PyList_GetItem(keys, i), PyList_GetItem(vals, i));
	       }
	  }
     }
     Py_DECREF(keys);
     Py_DECREF(vals);
     return result;
}
예제 #15
0
파일: peephole.c 프로젝트: Jimlan/kbengine
static int
fold_unaryops_on_constants(unsigned char *codestr, PyObject *consts)
{
    PyObject *newconst=NULL, *v;
    Py_ssize_t len_consts;
    int opcode;

    /* Pre-conditions */
    assert(PyList_CheckExact(consts));
    assert(codestr[0] == LOAD_CONST);

    /* Create new constant */
    v = PyList_GET_ITEM(consts, GETARG(codestr, 0));
    opcode = codestr[3];
    switch (opcode) {
        case UNARY_NEGATIVE:
            /* Preserve the sign of -0.0 */
            if (PyObject_IsTrue(v) == 1)
                newconst = PyNumber_Negative(v);
            break;
        case UNARY_INVERT:
            newconst = PyNumber_Invert(v);
            break;
        case UNARY_POSITIVE:
            newconst = PyNumber_Positive(v);
            break;
        default:
            /* Called with an unknown opcode */
            PyErr_Format(PyExc_SystemError,
                 "unexpected unary operation %d on a constant",
                     opcode);
            return 0;
    }
    if (newconst == NULL) {
        if(!PyErr_ExceptionMatches(PyExc_KeyboardInterrupt))
            PyErr_Clear();
        return 0;
    }

    /* Append folded constant into consts table */
    len_consts = PyList_GET_SIZE(consts);
    if (PyList_Append(consts, newconst)) {
        Py_DECREF(newconst);
        return 0;
    }
    Py_DECREF(newconst);

    /* Write NOP LOAD_CONST newconst */
    codestr[0] = NOP;
    codestr[1] = LOAD_CONST;
    SETARG(codestr, 1, len_consts);
    return 1;
}
예제 #16
0
void list_base::insert(ssize_t index, object_cref item)
{
    if (PyList_CheckExact(this->ptr()))
    {
        if (PyList_Insert(this->ptr(), index, item.ptr()) == -1)
            throw_error_already_set();
    }
    else
    {
        this->attr("insert")(index, item);
    }
}
예제 #17
0
void list_base::sort()
{
    if (PyList_CheckExact(this->ptr()))
    {
        if (PyList_Sort(this->ptr()) == -1)
            throw_error_already_set();
    }
    else
    {
        this->attr("sort")();
    }
}
예제 #18
0
void list_base::append(object_cref x)
{
    if (PyList_CheckExact(this->ptr()))
    {
        if (PyList_Append(this->ptr(), x.ptr()) == -1)
            throw_error_already_set();
    }
    else
    {
        this->attr("append")(x);
    }
}
예제 #19
0
void list_base::reverse()
{
    if (PyList_CheckExact(this->ptr()))
    {
        if (PyList_Reverse(this->ptr()) == -1)
            throw_error_already_set();
    }
    else
    {
        this->attr("reverse")();
    }
}
예제 #20
0
파일: peephole.c 프로젝트: Jimlan/kbengine
/* Replace LOAD_CONST c1. LOAD_CONST c2 ... LOAD_CONST cn BUILD_TUPLE n
   with    LOAD_CONST (c1, c2, ... cn).
   The consts table must still be in list form so that the
   new constant (c1, c2, ... cn) can be appended.
   Called with codestr pointing to the first LOAD_CONST.
   Bails out with no change if one or more of the LOAD_CONSTs is missing.
   Also works for BUILD_LIST and BUILT_SET when followed by an "in" or "not in"
   test; for BUILD_SET it assembles a frozenset rather than a tuple.
*/
static int
tuple_of_constants(unsigned char *codestr, Py_ssize_t n, PyObject *consts)
{
    PyObject *newconst, *constant;
    Py_ssize_t i, arg, len_consts;

    /* Pre-conditions */
    assert(PyList_CheckExact(consts));
    assert(codestr[n*3] == BUILD_TUPLE || codestr[n*3] == BUILD_LIST || codestr[n*3] == BUILD_SET);
    assert(GETARG(codestr, (n*3)) == n);
    for (i=0 ; i<n ; i++)
        assert(codestr[i*3] == LOAD_CONST);

    /* Buildup new tuple of constants */
    newconst = PyTuple_New(n);
    if (newconst == NULL)
        return 0;
    len_consts = PyList_GET_SIZE(consts);
    for (i=0 ; i<n ; i++) {
        arg = GETARG(codestr, (i*3));
        assert(arg < len_consts);
        constant = PyList_GET_ITEM(consts, arg);
        Py_INCREF(constant);
        PyTuple_SET_ITEM(newconst, i, constant);
    }

    /* If it's a BUILD_SET, use the PyTuple we just built to create a
      PyFrozenSet, and use that as the constant instead: */
    if (codestr[n*3] == BUILD_SET) {
        PyObject *tuple = newconst;
        newconst = PyFrozenSet_New(tuple);
        Py_DECREF(tuple);
        if (newconst == NULL)
            return 0;
    }

    /* Append folded constant onto consts */
    if (PyList_Append(consts, newconst)) {
        Py_DECREF(newconst);
        return 0;
    }
    Py_DECREF(newconst);

    /* Write NOPs over old LOAD_CONSTS and
       add a new LOAD_CONST newconst on top of the BUILD_TUPLE n */
    memset(codestr, NOP, n*3);
    codestr[n*3] = LOAD_CONST;
    SETARG(codestr, (n*3), len_consts);
    return 1;
}
예제 #21
0
//-------------------------------------------------------------------------
Py_ssize_t pyvar_walk_list(
        const ref_t &py_list,
        int (idaapi *cb)(const ref_t &py_item, Py_ssize_t index, void *ud),
        void *ud)
{
  PYW_GIL_CHECK_LOCKED_SCOPE();

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

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

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

      if ( py_item == NULL || cb(py_item, i, ud) < CIP_OK )
        break;
    }
    size = i;
  } while ( false );
  return size;
}
예제 #22
0
PyObject *
PyTuple_DeepCopy(register PyObject *a)
{
	PyTupleObject *np;
	PyObject **src, **dest;
	register Py_ssize_t i;
	Py_ssize_t len = Py_SIZE(a);
	np = (PyTupleObject *)PyTuple_New(len);
	if (np == NULL)
		return NULL;
	src = ((PyTupleObject *) a)->ob_item;
	dest = np->ob_item;
	for (i = 0; i < len; i++) {
		register PyObject *v = src[i];
		Py_INCREF(v);
		if (PyTuple_CheckExact(v)) {
			PyObject *w = PyTuple_DeepCopy(v);
			Py_DECREF(v);
			if (!w)	{
				Py_DECREF(np);
				return NULL;
			}
			v = w;
		}
		else if (PyList_CheckExact(v)) {
			PyObject *w = PyList_DeepCopy(v);
			Py_DECREF(v);
			if (!w)	{
				Py_DECREF(np);
				return NULL;
			}
			v = w;
		}
		else if (PyDict_CheckExact(v)) {
			PyObject *w = PyDict_DeepCopy(v);
			Py_DECREF(v);
			if (!w)	{
				Py_DECREF(np);
				return NULL;
			}
			v = w;
		}
		dest[i] = v;
	}
	return (PyObject *)np;
}
예제 #23
0
PyObject*
__call__(PyObject* self_, PyObject* args, PyObject**)
{
  PyObject* status_ = nullptr;
  PyObject* headers = nullptr;

  if (!PyArg_ParseTuple(args, "OO", &status_, &headers)) {
    return nullptr;
  }

  // - Extract out the status lines
  auto self = (WsgiStartResponseObject*)self_;
  std::string status(
      PyBytes_AS_STRING(PyUnicode_AsEncodedString(status_, "utf-8", "Error")));

  size_t code;
  std::string message;
  std::tie(code, message) = ParseMessageLine(status);

  // - Extract out the headers
  assert(PyList_CheckExact(headers));

  fcgi::HttpHeader header(code, message);
  for (Py_ssize_t i = 0; i < PyList_Size(headers); ++i) {
    PyObject* pair = PyList_GET_ITEM(headers, i);
    assert(PyTuple_CheckExact(pair));

    PyObject* nameObj  = PyTuple_GET_ITEM(pair, 0);
    PyObject* valueObj = PyTuple_GET_ITEM(pair, 1);

    std::string name(
      PyBytes_AS_STRING(PyUnicode_AsEncodedString(nameObj, "utf-8", "Error")));
    std::string value(
      PyBytes_AS_STRING(PyUnicode_AsEncodedString(valueObj, "utf-8", "Error")));

    Py_DECREF(pair);
    header.Add(name, value);
  }

  // - Send header response
  assert(nullptr != self);
  assert(nullptr != self->res);
  self->res->SetResponse(header);

  Py_RETURN_NONE;
}
예제 #24
0
// void InitializeSelectedGPUs( int *nGPUs, int GPUIds[], int nErr[]);
static PyObject*
ParODE_InitializeSelectedGPUs(PyObject *self, PyObject *args){
	int nErr = 0;
	PyObject* pListGPUs;
	if(!PyArg_ParseTuple(args, "O", &pListGPUs))
		return NULL;
	int nElements;
	int *GPUIds;
	if(!PyList_CheckExact(pListGPUs))
		return NULL;
	nElements = PyList_Size(pListGPUs);
	GPUIds = (int*)malloc(nElements * sizeof(int));
	int ii;
	for(ii = 0; ii < nElements; ii++){
		PyObject* pElement = PyList_GET_ITEM(pListGPUs, ii);
		long value = PyInt_AsLong(pElement);
		if(value == -1 && PyErr_Occurred()){
			free(GPUIds);
			return NULL;
		}
		GPUIds[ii] = (int)value;
	}
	char* strKernelFolder;
	int strSize = strlen(KERNEL_FOLDER);
	strKernelFolder = (char*)malloc( (strSize + 1) * sizeof(char) );
	if(strKernelFolder == NULL){
		free(GPUIds);
		return NULL;
	}
	strcpy(strKernelFolder, KERNEL_FOLDER);
	strSize = strlen( KERNEL_INCLUDE_FOLDER );
	char* strIncludeFolder;
	strIncludeFolder = (char*)malloc((strSize + 1) * sizeof(char));
	if(strIncludeFolder == NULL){
		free(GPUIds);
		free(strKernelFolder);
		return NULL;
	}
	strcpy(strIncludeFolder, KERNEL_INCLUDE_FOLDER);
	InitializeSelectedGPUs( &nElements, GPUIds, strKernelFolder, strIncludeFolder, &nErr );
	free(GPUIds);
	free(strKernelFolder);
	free(strIncludeFolder);
	return Py_BuildValue("i", nErr);
}
예제 #25
0
파일: common.c 프로젝트: JStech/numpy
/*
 * PyArray_GetAttrString_SuppressException:
 *
 * Stripped down version of PyObject_GetAttrString,
 * avoids lookups for None, tuple, and List objects,
 * and doesn't create a PyErr since this code ignores it.
 *
 * This can be much faster then PyObject_GetAttrString where
 * exceptions are not used by caller.
 *
 * 'obj' is the object to search for attribute.
 *
 * 'name' is the attribute to search for.
 *
 * Returns attribute value on success, 0 on failure.
 */
PyObject *
PyArray_GetAttrString_SuppressException(PyObject *obj, char *name)
{
    PyTypeObject *tp = Py_TYPE(obj);
    PyObject *res = (PyObject *)NULL;

    /* We do not need to check for special attributes on trivial types */
    if (obj == Py_None ||
            /* Basic number types */
#if !defined(NPY_PY3K)
            PyInt_CheckExact(obj) ||
#endif
            PyLong_CheckExact(obj) ||
            PyFloat_CheckExact(obj) ||
            /* Basic sequence types */
            PyList_CheckExact(obj) ||
            PyTuple_CheckExact(obj)) {
        return NULL;
    }

    /* Attribute referenced by (char *)name */
    if (tp->tp_getattr != NULL) {
        res = (*tp->tp_getattr)(obj, name);
        if (res == NULL) {
            PyErr_Clear();
        }
    }
    /* Attribute referenced by (PyObject *)name */
    else if (tp->tp_getattro != NULL) {
#if defined(NPY_PY3K)
        PyObject *w = PyUnicode_InternFromString(name);
#else
        PyObject *w = PyString_InternFromString(name);
#endif
        if (w == NULL) {
            return (PyObject *)NULL;
        }
        res = (*tp->tp_getattro)(obj, w);
        Py_DECREF(w);
        if (res == NULL) {
            PyErr_Clear();
        }
    }
    return res;
}
예제 #26
0
NUITKA_MAY_BE_UNUSED static PyObject *LIST_COPY( PyObject *list )
{
    CHECK_OBJECT( list );
    assert( PyList_CheckExact( list ) );

    Py_ssize_t size = PyList_GET_SIZE( list );
    PyObject *result = PyList_New( size );

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

    for ( Py_ssize_t i = 0; i < size; i++ )
    {
        PyList_SET_ITEM( result, i, INCREASE_REFCOUNT( PyList_GET_ITEM( list, i ) ) );
    }

    return result;
}
예제 #27
0
static int
BaseRowProxy_setprocessors(BaseRowProxy *self, PyObject *value, void *closure)
{
    if (value == NULL) {
        PyErr_SetString(PyExc_TypeError,
                        "Cannot delete the 'processors' attribute");
        return -1;
    }

    if (!PyList_CheckExact(value)) {
        PyErr_SetString(PyExc_TypeError,
                        "The 'processors' attribute value must be a list");
        return -1;
    }

    Py_XDECREF(self->processors);
    Py_INCREF(value);
    self->processors = value;

    return 0;
}
예제 #28
0
파일: py_util.c 프로젝트: TheProjecter/jxtl
json_t *py_variable_to_json( apr_pool_t *mp, PyObject *obj )
{
  json_writer_t *writer;
  json_t *json = NULL;
  apr_pool_t *tmp_mp;

  if ( PyDict_CheckExact( obj ) || PyList_CheckExact( obj ) ||
       PyTuple_CheckExact( obj ) ) {
    apr_pool_create( &tmp_mp, NULL );
    writer = json_writer_create( tmp_mp, mp );
    py_variable_to_json_internal( obj, writer );
    json = writer->json;
    apr_pool_destroy( tmp_mp );
  }
  else {
    fprintf( stderr, "Must be an object, list or tuple.\n" );
  }

  return json;

}
예제 #29
0
파일: array.c 프로젝트: python-postgres/be
static void
array_new_datum(PyObj subtype, PyObj ob, int32 mod, Datum *rdatum, bool *isnull)
{
	ArrayType *at;

	if (!PyList_CheckExact(ob))
	{
		/*
		 * If it's a string object, it should never get here.
		 */
		PyErr_SetString(PyExc_TypeError,
			"array constructor requires a list or string object");
		PyErr_RelayException();
	}
	else
	{
		at = array_from_py_list(PyPgType_GetElementType(subtype), ob, mod);
		*rdatum = PointerGetDatum(at);
		*isnull = false;
	}
}
예제 #30
0
static PyObject*
convert_nested(PyObject *ob, convert_func convert_string)
{
    /* dict. */
    if (PyDict_CheckExact(ob)) {
        return convert_dict(ob, convert_string);
    }

    /* sequence. */
    if (PyTuple_CheckExact(ob) || PyList_CheckExact(ob)) {
        return convert_seq(ob, convert_string);
    }

    /* numbers. */
    if (PyInt_CheckExact(ob) || PyLong_CheckExact(ob) || PyFloat_CheckExact(ob)) {
        Py_INCREF(ob);
        return ob;
    }

    /* bool. */
    if (PyBool_Check(ob)) {
        Py_INCREF(ob);
        return ob;
    }

    /* none. */
    if (ob == Py_None) {
        Py_INCREF(ob);
        return ob;
    }

    if (PyString_CheckExact(ob) || PyUnicode_CheckExact(ob)) {
        return convert_string(ob);
    }

    return PyErr_Format(
        PyExc_TypeError,
        "Got wrong type: %s",
        ob->ob_type->tp_name);
}