static PyObject *
SPI_xfer(SPI *self, PyObject *args)
{
	uint8_t ii, len;
	int status;
	int delay = -1;
	//uint8_t ret = 0;
	PyObject *list;
	struct spi_ioc_transfer *xferptr;
	uint8_t *txbuf, *rxbuf;

	if (!PyArg_ParseTuple(args, "O|i:msg", &list, &delay))
		return NULL;

	if (!PyList_Check(list)) {
		PyErr_SetString(PyExc_TypeError, wrmsg);
		return NULL;
	}

	if ((len = PyList_GET_SIZE(list)) > MAXMSGLEN) {
		PyErr_SetString(PyExc_OverflowError, wrmsg);
		return NULL;
	}

	if (delay == -1) {
		delay = 0;
	}

	xferptr = (struct spi_ioc_transfer*) malloc(sizeof(struct spi_ioc_transfer) * len);
	txbuf = malloc(sizeof(__u8) * len);
	rxbuf = malloc(sizeof(__u8) * len);

	for (ii = 0; ii < len; ii++) {
		PyObject *val = PyList_GET_ITEM(list, ii);
		if (!PyInt_Check(val)) {
			PyErr_SetString(PyExc_TypeError, wrmsg);
			return NULL;
		}
		txbuf[ii] = (__u8)PyInt_AS_LONG(val);
		xferptr[ii].tx_buf = (unsigned long)&txbuf[ii];
		xferptr[ii].rx_buf = (unsigned long)&rxbuf[ii];
		xferptr[ii].len = 1;
		xferptr[ii].delay_usecs = delay;
		xferptr[ii].speed_hz = 0;      
		xferptr[ii].bits_per_word = 0;
	}

	status = ioctl(self->fd, SPI_IOC_MESSAGE(len), xferptr);
	if (status < 0) {
		PyErr_SetFromErrno(PyExc_IOError);
		return NULL;
	}

	for (ii = 0; ii < len; ii++) {
		PyObject *val = Py_BuildValue("l", (long)rxbuf[ii]);
		PyList_SET_ITEM(list, ii, val);
	}

	// WA:
	// in CS_HIGH mode CS isn't pulled to low after transfer, but after read
	// reading 0 bytes doesnt matter but brings cs down
	status = read(self->fd, &rxbuf[0], 0);

	free(txbuf);
	free(rxbuf);
	free(xferptr);

	Py_INCREF(list);
	return list;
}
Example #2
0
/*NUMPY_API*/
NPY_NO_EXPORT intp
PyArray_PyIntAsIntp(PyObject *o)
{
    longlong long_value = -1;
    PyObject *obj;
    static char *msg = "an integer is required";
    PyObject *arr;
    PyArray_Descr *descr;
    intp ret;

    if (!o) {
        PyErr_SetString(PyExc_TypeError, msg);
        return -1;
    }
    if (PyInt_Check(o)) {
        long_value = (longlong) PyInt_AS_LONG(o);
        goto finish;
    } else if (PyLong_Check(o)) {
        long_value = (longlong) PyLong_AsLongLong(o);
        goto finish;
    }

#if SIZEOF_INTP == SIZEOF_LONG
    descr = &LONG_Descr;
#elif SIZEOF_INTP == SIZEOF_INT
    descr = &INT_Descr;
#else
    descr = &LONGLONG_Descr;
#endif
    arr = NULL;

    if (PyArray_Check(o)) {
        if (PyArray_SIZE(o)!=1 || !PyArray_ISINTEGER(o)) {
            PyErr_SetString(PyExc_TypeError, msg);
            return -1;
        }
        Py_INCREF(descr);
        arr = PyArray_CastToType((PyArrayObject *)o, descr, 0);
    }
    else if (PyArray_IsScalar(o, Integer)) {
        Py_INCREF(descr);
        arr = PyArray_FromScalar(o, descr);
    }
    if (arr != NULL) {
        ret = *((intp *)PyArray_DATA(arr));
        Py_DECREF(arr);
        return ret;
    }

#if (PY_VERSION_HEX >= 0x02050000)
    if (PyIndex_Check(o)) {
        PyObject* value = PyNumber_Index(o);
        if (value == NULL) {
            return -1;
        }
        long_value = (longlong) PyInt_AsSsize_t(value);
        goto finish;
    }
#endif
#if !defined(NPY_PY3K)
    if (Py_TYPE(o)->tp_as_number != NULL &&                 \
        Py_TYPE(o)->tp_as_number->nb_long != NULL) {
        obj = Py_TYPE(o)->tp_as_number->nb_long(o);
        if (obj != NULL) {
            long_value = (longlong) PyLong_AsLongLong(obj);
            Py_DECREF(obj);
        }
    }
    else
#endif
    if (Py_TYPE(o)->tp_as_number != NULL &&                 \
             Py_TYPE(o)->tp_as_number->nb_int != NULL) {
        obj = Py_TYPE(o)->tp_as_number->nb_int(o);
        if (obj != NULL) {
            long_value = (longlong) PyLong_AsLongLong(obj);
            Py_DECREF(obj);
        }
    }
    else {
        PyErr_SetString(PyExc_NotImplementedError,"");
    }

 finish:
    if error_converting(long_value) {
            PyErr_SetString(PyExc_TypeError, msg);
            return -1;
        }

#if (SIZEOF_LONGLONG > SIZEOF_INTP)
    if ((long_value < MIN_INTP) || (long_value > MAX_INTP)) {
        PyErr_SetString(PyExc_ValueError,
                        "integer won't fit into a C intp");
        return -1;
    }
#endif
    return (intp) long_value;
}
Example #3
0
int parse_property( unicap_property_t *property, PyObject *obj )
{   
   PyObject *tmp = NULL;

   tmp = PyDict_GetItemString (obj, "identifier");
   if (tmp){
	   strncpy (property->identifier, PyString_AsString(tmp), sizeof (property->identifier)-1);
   }

   tmp = PyDict_GetItemString (obj, "category");
   if (tmp){
	   strncpy (property->category, PyString_AsString(tmp), sizeof (property->category)-1);
   }

   tmp = PyDict_GetItemString (obj, "unit");
   if (tmp){
	   strncpy (property->unit, PyString_AsString(tmp), sizeof (property->unit)-1);
   }

   tmp = PyDict_GetItemString( obj, "flags" );
   if (tmp){
      Py_ssize_t len,index;
      if (!PyList_Check (tmp)){
	 PyErr_SetString (PyExc_TypeError, "Expected a List for 'flags' item");
	 goto err;
      }
      
      len = PyList_Size( tmp );
      property->flags = 0;
      for (index = 0; index < len; index++){
	 PyObject *item = PyList_GetItem( tmp, index );
	 if (!item)
	    goto err;
	 char *str = PyString_AsString (item);
	 if (!str)
	    goto err;
	 if (!strcmp (str, "manual"))
	    property->flags |= UNICAP_FLAGS_MANUAL;
	 else if (!strcmp (str, "one push"))
	    property->flags |= UNICAP_FLAGS_ONE_PUSH;
	 else if (!strcmp (str, "auto"))
	    property->flags |= UNICAP_FLAGS_AUTO;
      }	 
   }
   


   switch( property->type )
   {
      case UNICAP_PROPERTY_TYPE_RANGE:
      case UNICAP_PROPERTY_TYPE_VALUE_LIST:
      {
	      tmp = PyDict_GetItemString( obj, "value" );
	      if( !tmp ){
		      PyErr_SetString (PyExc_ValueError, "Object is missing 'value' key");
		      goto err;
	      }
	      if (PyFloat_Check (tmp))
		      property->value = PyFloat_AsDouble (tmp);
	      else if (PyInt_Check (tmp))
		      property->value = PyInt_AsLong (tmp);
	      else
		      goto err;

	      tmp = PyDict_GetItemString (obj, "range");
	      if (tmp){
		      PyObject *minval = PyTuple_GetItem (tmp, 0);
		      PyObject *maxval = PyTuple_GetItem (tmp, 1);
		      
		      if (minval){
			      if (PyFloat_Check (minval))
				      property->range.min = PyFloat_AsDouble (minval);
			      else if (PyInt_Check (minval))
				      property->range.min = PyInt_AsLong (minval);
			      else
				      goto err;
		      }
		      
		      if (maxval){
			      if (PyFloat_Check (maxval))
				      property->range.max = PyFloat_AsDouble (maxval);
			      else if (PyInt_Check (maxval))
				      property->range.max = PyInt_AsLong (maxval);
			      else
				      goto err;
		      }
	      }
      }
      break;
      
      case UNICAP_PROPERTY_TYPE_MENU:
      {
	 tmp = PyDict_GetItemString( obj, "menu_item" );
	 if( !tmp ){
	    PyErr_SetString( PyExc_ValueError, "Object is missing 'menu_item' key" );
	    goto err;
	 }
	 if( !PyString_Check( tmp ) )
	 {
	    goto err;
	 }
	 
	 strcpy( property->menu_item, PyString_AsString( tmp ) );
      }
      break;

   case UNICAP_PROPERTY_TYPE_DATA:
   {
      tmp = PyDict_GetItemString( obj, "data" );
      if( !tmp ){
	 PyErr_SetString( PyExc_ValueError, "Object is missing 'data' key" );
	 goto err;
      }
      if( !PyString_Check( tmp ) ){
	 goto err;
      }

      Py_ssize_t size;
      PyString_AsStringAndSize( tmp, (char**)&property->property_data, &size );
      property->property_data_size = size;
   }
   break;

   default:
      break;
   }

   return 0;

  err:
   return -1;
}
Example #4
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 #5
0
  int register_df(int dtid, PyObject *py_obj)
  {
    // Already registered?
    if ( dfid >= 0 )
      return dfid;

    memset(&df, 0, sizeof(df));
    df.cbsize = sizeof(df);
    df.ud = this;

    PYW_GIL_CHECK_LOCKED_SCOPE();
    do
    {
      ref_t py_attr;

      // name
      if ( !PyW_GetStringAttr(py_obj, S_NAME, &df_name) )
        break;
      df.name = df_name.c_str();

      // menu_name (optional)
      if ( PyW_GetStringAttr(py_obj, S_MENU_NAME, &df_menu_name) )
        df.menu_name = df_menu_name.c_str();

      // props
      py_attr = PyW_TryGetAttrString(py_obj, S_PROPS);
      if ( py_attr != NULL && PyInt_Check(py_attr.o) )
        df.props = PyInt_AsLong(py_attr.o);

      // hotkey
      if ( PyW_GetStringAttr(py_obj, S_HOTKEY, &df_hotkey) )
        df.hotkey = df_hotkey.c_str();

      // value_size
      py_attr = PyW_TryGetAttrString(py_obj, S_VALUE_SIZE);
      if ( py_attr != NULL && PyInt_Check(py_attr.o) )
        df.value_size = PyInt_AsLong(py_attr.o);

      // text_width
      py_attr = PyW_TryGetAttrString(py_obj, S_TEXT_WIDTH);
      if ( py_attr != NULL && PyInt_Check(py_attr.o) )
        df.text_width = PyInt_AsLong(py_attr.o);

      // print cb
      py_attr = PyW_TryGetAttrString(py_obj, S_PRINTF);
      if ( py_attr != NULL && PyCallable_Check(py_attr.o) )
        df.print = s_print;

      // scan cb
      py_attr = PyW_TryGetAttrString(py_obj, S_SCAN);
      if ( py_attr != NULL && PyCallable_Check(py_attr.o) )
        df.scan = s_scan;

      // analyze cb
      py_attr = PyW_TryGetAttrString(py_obj, S_ANALYZE);
      if ( py_attr != NULL && PyCallable_Check(py_attr.o) )
        df.analyze = s_analyze;

      // Now try to register
      dfid = register_custom_data_format(dtid, &df);
      if ( dfid < 0 )
        break;

      // Hold reference to the PyObject
      Py_INCREF(py_obj);
      py_self = py_obj;

      // Update the format ID
      py_attr = newref_t(PyInt_FromLong(dfid));
      PyObject_SetAttrString(py_obj, S_ID, py_attr.o);
    } while ( false );
    return dfid;
  }
Example #6
0
int _attachsql_QueryObject_Initialize(_attachsql_QueryObject *self, PyObject *args, PyObject *kwargs)
{
  bool ret;
  char *query= NULL;
  int query_length;
  int param_count= 0;
  int i;
  int64_t *tmp_int;
  uint64_t *tmp_uint;
  double *tmp_double;
  attachsql_query_parameter_st *asql_params= NULL;
  PyObject *param_list= NULL;
  PyObject *param_dict= NULL;
  PyObject *type= NULL;
  PyObject *value= NULL;
  PyObject *is_unsigned= NULL;
  attachsql_error_t *error= NULL;
  if (!PyArg_ParseTuple(args, "s#|O!", &query, &query_length, &PyList_Type, &param_list))
  {
    return -1;
  }

  if (!param_list)
  {
    ret= attachsql_query(self->pycon->conn, query_length, query, 0, NULL, &error);
    if (error)
    {
      _attachsql_Exception(error);
      return -1;
    }
    return 0;
  }
  /* For parameters the user should use:
   * .query("SELECT * FROM test WHERE a=? and b=?", [{'type': ESCAPE_TYPE_CHAR, 'data': 'hello'}, {'type': ESCAPE_TYPE_INT, 'data': 1}])
   */
  param_count= PyList_Size(param_list);
  asql_params= (attachsql_query_parameter_st*)malloc(sizeof(attachsql_query_parameter_st) * param_count);
  /* This is ugly, need to find a better way */
  tmp_int= (int64_t*)malloc(sizeof(int64_t) * param_count);
  tmp_uint= (uint64_t*)malloc(sizeof(uint64_t) * param_count);
  tmp_double= (double*)malloc(sizeof(double) * param_count);

  for (i= 0; i < param_count; i++)
  {
    param_dict= PyList_GetItem(param_list, i);
    if (!PyDict_Check(param_dict))
    {
      PyErr_SetString(PyExc_TypeError, "Dict not found in list");
      free(asql_params);
      return -1;
    }
    type= PyDict_GetItemString(param_dict, "type");
    value= PyDict_GetItemString(param_dict, "data");
    is_unsigned= PyDict_GetItemString(param_dict, "is_unsigned");
    if (!type || !value || !PyInt_Check(type))
    {
      PyErr_SetString(PyExc_TypeError, "Bad type or value in dict");
      free(asql_params);
      return -1;
    }
    asql_params[i].type= PyInt_AsLong(type);

    switch (asql_params[i].type)
    {
      case ATTACHSQL_ESCAPE_TYPE_NONE:
        asql_params[i].data= NULL;
        break;
      case ATTACHSQL_ESCAPE_TYPE_CHAR:
      case ATTACHSQL_ESCAPE_TYPE_CHAR_LIKE:
        asql_params[i].data= PyString_AsString(value);
        asql_params[i].length= PyString_Size(value);
        break;
      case ATTACHSQL_ESCAPE_TYPE_INT:
        if (is_unsigned && PyInt_AsLong(is_unsigned))
        {
          if (PyInt_Check(value))
          {
            tmp_uint[i]= PyInt_AsUnsignedLongMask(value);
          }
          else
          {
            tmp_uint[i]= PyLong_AsUnsignedLong(value);
          }
          asql_params[i].data= &tmp_uint[i];
          asql_params[i].is_unsigned= true;
        }
        else
        {
          if (PyInt_Check(value))
          {
            tmp_int[i]= PyInt_AsLong(value);
          }
          else
          {
            tmp_int[i]= PyLong_AsLong(value);
          }
          asql_params[i].data= &tmp_int[i];
          asql_params[i].is_unsigned= false;
        }
        break;
      case ATTACHSQL_ESCAPE_TYPE_BIGINT:
        if (is_unsigned && PyInt_AsLong(is_unsigned))
        {
          if (PyInt_Check(value))
          {
            tmp_uint[i]= PyInt_AsUnsignedLongMask(value);
          }
          else
          {
            tmp_uint[i]= PyLong_AsUnsignedLongLong(value);
          }
          asql_params[i].data= &tmp_uint[i];
          asql_params[i].is_unsigned= true;
        }
        else
        {
          if (PyInt_Check(value))
          {
            tmp_int[i]= PyInt_AsLong(value);
          }
          else
          {
            tmp_int[i]= PyLong_AsLongLong(value);
          }
          asql_params[i].data= &tmp_int[i];
          asql_params[i].is_unsigned= false;
        }
        break;
      case ATTACHSQL_ESCAPE_TYPE_FLOAT:
      case ATTACHSQL_ESCAPE_TYPE_DOUBLE:
        tmp_double[i]= PyFloat_AsDouble(value);
        asql_params[i].data= &tmp_double[i];
        break;
    }
  }
  ret= attachsql_query(self->pycon->conn, query_length, query, param_count, asql_params, &error);
  free(asql_params);
  free(tmp_int);
  free(tmp_uint);
  free(tmp_double);
  if (error)
  {
    _attachsql_Exception(error);
    return -1;
  }
  return 0;
}
/*static*/ PyObject *
MoleculeAttributes_SetBondSingleColor(PyObject *self, PyObject *args)
{
    MoleculeAttributesObject *obj = (MoleculeAttributesObject *)self;

    int c[4];
    if(!PyArg_ParseTuple(args, "iiii", &c[0], &c[1], &c[2], &c[3]))
    {
        c[3] = 255;
        if(!PyArg_ParseTuple(args, "iii", &c[0], &c[1], &c[2]))
        {
            double dr, dg, db, da;
            if(PyArg_ParseTuple(args, "dddd", &dr, &dg, &db, &da))
            {
                c[0] = int(dr);
                c[1] = int(dg);
                c[2] = int(db);
                c[3] = int(da);
            }
            else if(PyArg_ParseTuple(args, "ddd", &dr, &dg, &db))
            {
                c[0] = int(dr);
                c[1] = int(dg);
                c[2] = int(db);
                c[3] = 255;
            }
            else
            {
                PyObject *tuple = NULL;
                if(!PyArg_ParseTuple(args, "O", &tuple))
                    return NULL;

                if(!PyTuple_Check(tuple))
                    return NULL;

                // Make sure that the tuple is the right size.
                if(PyTuple_Size(tuple) < 3 || PyTuple_Size(tuple) > 4)
                    return NULL;

                // Make sure that all elements in the tuple are ints.
                for(int i = 0; i < PyTuple_Size(tuple); ++i)
                {
                    PyObject *item = PyTuple_GET_ITEM(tuple, i);
                    if(PyInt_Check(item))
                        c[i] = int(PyInt_AS_LONG(PyTuple_GET_ITEM(tuple, i)));
                    else if(PyFloat_Check(item))
                        c[i] = int(PyFloat_AS_DOUBLE(PyTuple_GET_ITEM(tuple, i)));
                    else
                        return NULL;
                }
            }
        }
        PyErr_Clear();
    }

    // Set the bondSingleColor in the object.
    ColorAttribute ca(c[0], c[1], c[2], c[3]);
    obj->data->SetBondSingleColor(ca);

    Py_INCREF(Py_None);
    return Py_None;
}
Example #8
0
/* Setter for f_lineno - you can set f_lineno from within a trace function in
 * order to jump to a given line of code, subject to some restrictions.	 Most
 * lines are OK to jump to because they don't make any assumptions about the
 * state of the stack (obvious because you could remove the line and the code
 * would still work without any stack errors), but there are some constructs
 * that limit jumping:
 *
 *  o Lines with an 'except' statement on them can't be jumped to, because
 *    they expect an exception to be on the top of the stack.
 *  o Lines that live in a 'finally' block can't be jumped from or to, since
 *    the END_FINALLY expects to clean up the stack after the 'try' block.
 *  o 'try'/'for'/'while' blocks can't be jumped into because the blockstack
 *    needs to be set up before their code runs, and for 'for' loops the
 *    iterator needs to be on the stack.
 */
static int
frame_setlineno(PyFrameObject *f, PyObject* p_new_lineno)
{
	int new_lineno = 0;		/* The new value of f_lineno */
	int new_lasti = 0;		/* The new value of f_lasti */
	int new_iblock = 0;		/* The new value of f_iblock */
	unsigned short *code = NULL;	/* The bytecode for the frame... */
	Py_ssize_t code_len = 0;	/* ...and its length */
	unsigned char *lnotab = NULL;	/* Iterating over co_lnotab */
	Py_ssize_t lnotab_len = 0;	/* (ditto) */
	int offset = 0;			/* (ditto) */
	int line = 0;			/* (ditto) */
	int addr = 0;			/* (ditto) */
	int min_addr = 0;		/* Scanning the SETUPs and POPs */
	int max_addr = 0;		/* (ditto) */
	int delta_iblock = 0;		/* (ditto) */
	int min_delta_iblock = 0;	/* (ditto) */
	int min_iblock = 0;		/* (ditto) */
	int f_lasti_setup_addr = 0;	/* Policing no-jump-into-finally */
	int new_lasti_setup_addr = 0;	/* (ditto) */
	int blockstack[CO_MAXBLOCKS];	/* Walking the 'finally' blocks */
	int in_finally[CO_MAXBLOCKS];	/* (ditto) */
	int blockstack_top = 0;		/* (ditto) */
	int temp_for_addr_stack[CO_MAXBLOCKS];	/* Temporary target address of
                                               for blocks (no setup) */
	int temp_block_type_stack[CO_MAXBLOCKS];	/* Temporary block kind
                                                   (0 = setup, 1 = for) */
	int temp_for_addr_top = 0;		    /* (ditto) */
	int temp_last_for_addr = -1;        /* (ditto) */
	int temp_block_type_top = 0;	    /* (ditto) */
	int for_addr_stack[CO_MAXBLOCKS];	/* Target address of for blocks
                                           (no setup) */
	int block_type_stack[CO_MAXBLOCKS];	/* Block kind (0 = setup, 1 = for) */
	int for_addr_top;		        /* (ditto) */
	int last_for_addr;	            /* (ditto) */
	int block_type_top;	            /* (ditto) */
	unsigned short setup_op = 0;	/* (ditto) */
	unsigned short op;
    int oparg, target_addr;
	char *tmp;

	/* f_lineno must be an integer. */
	if (!PyInt_Check(p_new_lineno)) {
		PyErr_SetString(PyExc_ValueError,
				"lineno must be an integer");
		return -1;
	}

	/* You can only do this from within a trace function, not via
	 * _getframe or similar hackery. */
	if (!f->f_trace)
	{
		PyErr_Format(PyExc_ValueError,
			     "f_lineno can only be set by a trace function");
		return -1;
	}

	/* Fail if the line comes before the start of the code block. */
	new_lineno = (int) PyInt_AsLong(p_new_lineno);
	if (new_lineno < f->f_code->co_firstlineno) {
		PyErr_Format(PyExc_ValueError,
			     "line %d comes before the current code block",
			     new_lineno);
		return -1;
	}

	/* Find the bytecode offset for the start of the given line, or the
	 * first code-owning line after it. */
	PyString_AsStringAndSize(f->f_code->co_lnotab,
	                         &tmp, &lnotab_len);
	lnotab = (unsigned char *) tmp;
	addr = 0;
	line = f->f_code->co_firstlineno;
	new_lasti = -1;
	for (offset = 0; offset < lnotab_len; offset += 2) {
		addr += lnotab[offset];
		line += lnotab[offset+1];
		if (line >= new_lineno) {
			new_lasti = addr;
			new_lineno = line;
			break;
		}
	}

	/* If we didn't reach the requested line, return an error. */
	if (new_lasti == -1) {
		PyErr_Format(PyExc_ValueError,
			     "line %d comes after the current code block",
			     new_lineno);
		return -1;
	}

	/* We're now ready to look at the bytecode. */
	PyString_AsStringAndSize(f->f_code->co_code, (char **)&code, &code_len);
	code_len >>= 1;
	min_addr = MIN(new_lasti, f->f_lasti);
	max_addr = MAX(new_lasti, f->f_lasti);

	/* You can't jump onto a line with an 'except' statement on it -
	 * they expect to have an exception on the top of the stack, which
	 * won't be true if you jump to them.  They always start with code
	 * that either pops the exception using POP_TOP (plain 'except:'
	 * lines do this) or duplicates the exception on the stack using
	 * DUP_TOP (if there's an exception type specified).  See compile.c,
	 * 'com_try_except' for the full details.  There aren't any other
	 * cases (AFAIK) where a line's code can start with DUP_TOP or
	 * POP_TOP, but if any ever appear, they'll be subject to the same
	 * restriction (but with a different error message). */
	if (code[new_lasti] == CONVERT(DUP_TOP) ||
        code[new_lasti] == CONVERT(POP_TOP)) {
		PyErr_SetString(PyExc_ValueError,
		    "can't jump to 'except' line as there's no exception");
		return -1;
	}

	/* You can't jump into or out of a 'finally' block because the 'try'
	 * block leaves something on the stack for the END_FINALLY to clean
	 * up.	So we walk the bytecode, maintaining a simulated blockstack.
	 * When we reach the old or new address and it's in a 'finally' block
	 * we note the address of the corresponding SETUP_FINALLY.  The jump
	 * is only legal if neither address is in a 'finally' block or
	 * they're both in the same one.  'blockstack' is a stack of the
	 * bytecode addresses of the SETUP_X opcodes, and 'in_finally' tracks
	 * whether we're in a 'finally' block at each blockstack level. */
	f_lasti_setup_addr = -1;
	new_lasti_setup_addr = -1;
	memset(blockstack, '\0', sizeof(blockstack));
	memset(in_finally, '\0', sizeof(in_finally));
	blockstack_top = 0;
	for (addr = 0; addr < code_len; addr++) {
        if (addr == min_addr) { /* Takes a snapshot of the for blocks status */
            memcpy(for_addr_stack, temp_for_addr_stack,
                sizeof(int) * temp_for_addr_top);
            memcpy(block_type_stack, temp_block_type_stack,
                sizeof(int) * temp_for_addr_top);
            for_addr_top = temp_for_addr_top;
            last_for_addr = temp_last_for_addr;
            block_type_top = temp_block_type_top;
        }
        /* Checks if we have found a "virtual" POP_BLOCK/POP_TOP for the
           current for instruction (without SETUP_LOOP). */
        if (addr == temp_last_for_addr) {
            temp_last_for_addr = temp_for_addr_stack[--temp_for_addr_top];
            temp_block_type_top--;
        }
		op = code[addr];
		switch (op) {
		case CONVERT(EXT16(SETUP_LOOP)):
		case CONVERT(EXT16(SETUP_EXCEPT)):
		case CONVERT(EXT16(SETUP_FINALLY)):
		case CONVERT(EXT32(SETUP_LOOP)):
		case CONVERT(EXT32(SETUP_EXCEPT)):
		case CONVERT(EXT32(SETUP_FINALLY)):
			blockstack[blockstack_top++] = addr;
			in_finally[blockstack_top-1] = 0;
			temp_block_type_stack[temp_block_type_top++] = 0;
			break;

		case CONVERT(EXT16(FOR_ITER)):
            oparg = code[addr + 1];
            target_addr = addr + 2 + CONVERT(oparg);
            if (code[target_addr] != CONVERT(POP_FOR_BLOCK)) {
                temp_for_addr_stack[temp_for_addr_top++] = temp_last_for_addr;
                temp_last_for_addr = target_addr;
    			temp_block_type_stack[temp_block_type_top++] = 1;
            }
			break;

		case CONVERT(EXT32(FOR_ITER)):
            oparg = code[addr + 1];
            target_addr = addr + 3 + CONVERT(oparg);
            oparg = code[addr + 2];
            target_addr += CONVERT(oparg) << 16;
            if (code[target_addr] != CONVERT(POP_FOR_BLOCK)) {
                temp_for_addr_stack[temp_for_addr_top++] = temp_last_for_addr;
                temp_last_for_addr = target_addr;
    			temp_block_type_stack[temp_block_type_top++] = 1;
            }
			break;

		case CONVERT(POP_BLOCK):
		case CONVERT(POP_FOR_BLOCK):
			assert(blockstack_top > 0);
			setup_op = code[blockstack[blockstack_top-1]];
			if (MATCHOP(setup_op, SETUP_FINALLY)) {
				in_finally[blockstack_top-1] = 1;
			}
			else {
				blockstack_top--;
                temp_block_type_top--;
			}
			break;

		case CONVERT(END_FINALLY):
        case CONVERT(WITH_CLEANUP):
			/* Ignore END_FINALLYs for SETUP_EXCEPTs - they exist
			 * in the bytecode but don't correspond to an actual
			 * 'finally' block.  (If blockstack_top is 0, we must
			 * be seeing such an END_FINALLY.) */
			if (blockstack_top > 0) {
				setup_op = code[blockstack[blockstack_top-1]];
				if (MATCHOP(setup_op, SETUP_FINALLY)) {
					blockstack_top--;
			        temp_for_addr_top--;
                    temp_block_type_top--;
				}
			}
			break;
		default:
			switch (EXTRACTOP(op)) {
				case SETUP_LOOP:
				case SETUP_EXCEPT:
				case SETUP_FINALLY:
					blockstack[blockstack_top++] = addr;
					in_finally[blockstack_top-1] = 0;
           			temp_block_type_stack[temp_block_type_top++] = 0;
					break;
				case FOR_ITER:
                    target_addr = addr + 1 + EXTRACTARG(op);
                    if (code[target_addr] != CONVERT(POP_FOR_BLOCK)) {
                        temp_for_addr_stack[temp_for_addr_top++] =
                            temp_last_for_addr;
                        temp_last_for_addr = target_addr;
            			temp_block_type_stack[temp_block_type_top++] = 1;
                    }
					break;
			}
		}

		/* For the addresses we're interested in, see whether they're
		 * within a 'finally' block and if so, remember the address
		 * of the SETUP_FINALLY. */
		if (addr == new_lasti || addr == f->f_lasti) {
			int i = 0;
			int setup_addr = -1;
			for (i = blockstack_top-1; i >= 0; i--) {
				if (in_finally[i]) {
					setup_addr = blockstack[i];
					break;
				}
			}

			if (setup_addr != -1) {
				if (addr == new_lasti) {
					new_lasti_setup_addr = setup_addr;
				}

				if (addr == f->f_lasti) {
					f_lasti_setup_addr = setup_addr;
				}
			}
		}

		op = EXTRACTOP(op);
		if (op >= EXTENDED_ARG32)
			addr += 2;
		else if (op >= EXTENDED_ARG16)
			addr += 1;
	}

	/* Verify that the blockstack tracking code didn't get lost. */
	assert(blockstack_top == 0);

	/* After all that, are we jumping into / out of a 'finally' block? */
	if (new_lasti_setup_addr != f_lasti_setup_addr) {
		PyErr_SetString(PyExc_ValueError,
			    "can't jump into or out of a 'finally' block");
		return -1;
	}


	/* Police block-jumping (you can't jump into the middle of a block)
	 * and ensure that the blockstack finishes up in a sensible state (by
	 * popping any blocks we're jumping out of).  We look at all the
	 * blockstack operations between the current position and the new
	 * one, and keep track of how many blocks we drop out of on the way.
	 * By also keeping track of the lowest blockstack position we see, we
	 * can tell whether the jump goes into any blocks without coming out
	 * again - in that case we raise an exception below. */
	for (addr = min_addr; addr < max_addr; addr++) {
        if (addr == last_for_addr) {
            last_for_addr = for_addr_stack[--for_addr_top];
            block_type_top--;
            delta_iblock--;
        }
		op = code[addr];
		switch (op) {
		case CONVERT(EXT16(SETUP_LOOP)):
		case CONVERT(EXT16(SETUP_EXCEPT)):
		case CONVERT(EXT16(SETUP_FINALLY)):
		case CONVERT(EXT32(SETUP_LOOP)):
		case CONVERT(EXT32(SETUP_EXCEPT)):
		case CONVERT(EXT32(SETUP_FINALLY)):
			block_type_stack[block_type_top++] = 0;
            delta_iblock++;
			break;

		case CONVERT(EXT16(FOR_ITER)):
            oparg = code[addr + 1];
            target_addr = addr + 2 + CONVERT(oparg);
            if (code[target_addr] != CONVERT(POP_FOR_BLOCK)) {
                for_addr_stack[for_addr_top++] = last_for_addr;
                last_for_addr = target_addr;
    			block_type_stack[block_type_top++] = 1;
                delta_iblock++;
            }
			break;

		case CONVERT(EXT32(FOR_ITER)):
            oparg = code[addr + 1];
            target_addr = addr + 3 + CONVERT(oparg);
            oparg = code[addr + 2];
            target_addr += CONVERT(oparg) << 16;
            if (code[target_addr] != CONVERT(POP_FOR_BLOCK)) {
                for_addr_stack[for_addr_top++] = last_for_addr;
                last_for_addr = target_addr;
    			block_type_stack[block_type_top++] = 1;
                delta_iblock++;
            }
			break;

        case CONVERT(POP_BLOCK):
        case CONVERT(POP_FOR_BLOCK):
			delta_iblock--;
            block_type_top--;
			break;
		default:
			switch (EXTRACTOP(op)) {
				case SETUP_LOOP:
				case SETUP_EXCEPT:
				case SETUP_FINALLY:
           			block_type_stack[block_type_top++] = 0;
                    delta_iblock++;
					break;
				case FOR_ITER:
                    target_addr = addr + 1 + EXTRACTARG(op);
                    if (code[target_addr] != CONVERT(POP_FOR_BLOCK)) {
                        for_addr_stack[for_addr_top++] = last_for_addr;
                        last_for_addr = target_addr;
            			block_type_stack[block_type_top++] = 1;
                        delta_iblock++;
                    }
					break;
			}
		}

		min_delta_iblock = MIN(min_delta_iblock, delta_iblock);

		op = EXTRACTOP(op);
		if (op >= EXTENDED_ARG32)
			addr += 2;
		else if (op >= EXTENDED_ARG16)
			addr += 1;
	}

    /* Checks if we have a pending FOR_ITER (without SETUP_LOOP). */
    if (addr == last_for_addr) {
        delta_iblock--;
		min_delta_iblock = MIN(min_delta_iblock, delta_iblock);
    }

	/* Derive the absolute iblock values from the deltas. */
	min_iblock = f->f_iblock + min_delta_iblock;
	if (new_lasti > f->f_lasti) {
		/* Forwards jump. */
		new_iblock = f->f_iblock + delta_iblock;
	}
	else {
		/* Backwards jump. */
		new_iblock = f->f_iblock - delta_iblock;
	}

	/* Are we jumping into a block? */
	if (new_iblock > min_iblock) {
		PyErr_SetString(PyExc_ValueError,
				"can't jump into the middle of a block");
		return -1;
	}

	/* Pop any blocks that we're jumping out of. */
	while (f->f_iblock > new_iblock)
        if (block_type_stack[--block_type_top]){
		    PyObject *v = (*--f->f_stacktop);
		    Py_DECREF(v);
            new_iblock++;
        }
        else {
		    PyTryBlock *b = &f->f_blockstack[--f->f_iblock];
		    while ((f->f_stacktop - f->f_valuestack) > b->b_level) {
			    PyObject *v = (*--f->f_stacktop);
			    Py_DECREF(v);
		    }
	    }

	/* Finally set the new f_lineno and f_lasti and return OK. */
	f->f_lineno = new_lineno;
	f->f_lasti = new_lasti;
	return 0;
}
Example #9
0
/**
 *******************************************************************************************************
 * Callback for as_info_foreach().
 *
 * @param err                   The as_error to be populated by the function
 *                              with the encountered error if any.
 * @param node                  The current as_node object for which the
 *                              callback is fired by c client.
 * @param req                   The info request string.
 * @param res                   The info response string for current node.
 * @pram udata                  The callback udata containing the host_lookup
 *                              array and the return zval to be populated with
 *                              an entry for current node's info response with
 *                              the node's ID as the key.
 *
 * Returns true if callback is successful, Otherwise false.
 *******************************************************************************************************
 */
static bool AerospikeClient_Info_each(as_error * err, const as_node * node, const char * req, char * res, void * udata)
{
	PyObject * py_err = NULL;
	PyObject * py_ustr = NULL;
	PyObject * py_out = NULL;
	foreach_callback_info_udata* udata_ptr = (foreach_callback_info_udata *) udata;
	as_address* addr = NULL;

	// Need to make sure we have the GIL since we're back in python land now
	PyGILState_STATE gil_state = PyGILState_Ensure();

	if (err && err->code != AEROSPIKE_OK) {
		as_error_update(err, err->code, NULL);
		goto CLEANUP;
	}
	else if (res) {
		char * out = strchr(res,'\t');
		if (out) {
			out++;
			py_out = PyString_FromString(out);
		}
		else {
			py_out = PyString_FromString(res);
		}
	}

	if (!py_err) {
		Py_INCREF(Py_None);
		py_err = Py_None;
	}

	if (!py_out) {
		Py_INCREF(Py_None);
		py_out = Py_None;
	}

	PyObject * py_res = PyTuple_New(2);
	PyTuple_SetItem(py_res, 0, py_err);
	PyTuple_SetItem(py_res, 1, py_out);

	if (udata_ptr->host_lookup_p) {
		PyObject * py_hosts = (PyObject *)udata_ptr->host_lookup_p;
			if (py_hosts && PyList_Check(py_hosts)) {
				addr = as_node_get_address((as_node *)node);
				int size = (int) PyList_Size(py_hosts);
				for (int i = 0; i < size; i++) {
					char * host_addr = NULL;
					int port = -1;
					PyObject * py_host = PyList_GetItem(py_hosts, i);
					if (PyTuple_Check(py_host) && PyTuple_Size(py_host) == 2) {
						PyObject * py_addr = PyTuple_GetItem(py_host,0);
						PyObject * py_port = PyTuple_GetItem(py_host,1);
						if (PyUnicode_Check(py_addr)) {
							py_ustr = PyUnicode_AsUTF8String(py_addr);
							host_addr = PyBytes_AsString(py_ustr);
						} else if (PyString_Check(py_addr)) {
							host_addr = PyString_AsString(py_addr);
						} else {
							as_error_update(&udata_ptr->error, AEROSPIKE_ERR_PARAM, "Host address is of type incorrect");
							if (py_res) {
								Py_DECREF(py_res);
							}
							PyGILState_Release(gil_state);
							return false;
						}
						if (PyInt_Check(py_port)) {
							port = (uint16_t) PyInt_AsLong(py_port);
						}
						else if (PyLong_Check(py_port)) {
							port = (uint16_t) PyLong_AsLong(py_port);
						} else {
							break;
						}
						char ip_port[IP_PORT_MAX_LEN];
						// If the address is longer than the max length of an ipv6 address, raise an error and exit
						if (strnlen(host_addr, INET6_ADDRSTRLEN) >= INET6_ADDRSTRLEN) {
							as_error_update(&udata_ptr->error, AEROSPIKE_ERR_PARAM, "Host address is too long");
							if (py_res) {
								Py_DECREF(py_res);
							}
							goto CLEANUP;
						}
						sprintf(ip_port, "%s:%d", host_addr, port);
						if ( !strcmp(ip_port, addr->name) ) {
							PyObject * py_nodes = (PyObject *) udata_ptr->udata_p;
							PyDict_SetItemString(py_nodes, node->name, py_res);
						} else {
							sprintf(ip_port, "[%s]:%d", host_addr, port);
							if ( !strcmp(ip_port, addr->name) ) {
								PyObject * py_nodes = (PyObject *) udata_ptr->udata_p;
								PyDict_SetItemString(py_nodes, node->name, py_res);
							}
						}
					}

					if (py_ustr) {
						Py_DECREF(py_ustr);
						py_ustr = NULL;
					}
				}
			} else if (!PyList_Check(py_hosts)) {
				as_error_update(&udata_ptr->error, AEROSPIKE_ERR_PARAM, "Hosts should be specified in a list.");
				goto CLEANUP;
			}
	} else {
		PyObject * py_nodes = (PyObject *) udata_ptr->udata_p;
		PyDict_SetItemString(py_nodes, node->name, py_res);
	}

	Py_DECREF(py_res);

CLEANUP:
	if (py_ustr) {
		Py_DECREF(py_ustr);
	}
	if (udata_ptr->error.code != AEROSPIKE_OK) {
		PyObject * py_err = NULL;
		error_to_pyobject( &udata_ptr->error, &py_err);
		PyObject *exception_type = raise_exception(&udata_ptr->error);
		PyErr_SetObject(exception_type, py_err);
		Py_DECREF(py_err);
		PyGILState_Release(gil_state);
		return NULL;
	}
	if (err->code != AEROSPIKE_OK) {
		PyObject * py_err = NULL;
		error_to_pyobject(err, &py_err);
		PyObject *exception_type = raise_exception(err);
		PyErr_SetObject(exception_type, py_err);
		Py_DECREF(py_err);
		PyGILState_Release(gil_state);
		return NULL;
	}

	PyGILState_Release(gil_state);
	return true;
}
Example #10
0
void pyobj_send(t_outlet*const outlet,PyObject*const value)
{
	if(!value);
	else if(value==Py_True)
		outlet_bang(outlet);
	else if(value==Py_False)
		outlet_symbol(outlet,&s_);
	else if(PyInt_Check(value))
		outlet_float(outlet,PyInt_AsLong(value));
	else if(PyFloat_Check(value))
		outlet_float(outlet,PyFloat_AsDouble(value));
	else if(PyString_Check(value))
		outlet_symbol(outlet,gensym(PyString_AsString(value)));
	else if(PyDict_Check(value))
	{
	}
	else if(PyList_Check(value))
	{
		register int k,K;
		Py_ssize_t size=PyList_Size(value);
		t_atom*atom=(t_atom*)calloc(sizeof(t_atom),size);
		for(k=0,K=size;k<K;++k)
		{
			PyObject*obj=PyList_GetItem(value,k);
			if(!obj)
				SETSYMBOL(atom+k,&s_);
			else if(obj==Py_True)
				SETFLOAT(atom+k,1);
			else if(obj==Py_False)
				SETSYMBOL(atom+k,&s_);
			else if(PyInt_Check(obj))
				SETFLOAT(atom+k,PyInt_AsLong(obj));
			else if(PyFloat_Check(obj))
				SETFLOAT(atom+k,PyFloat_AsDouble(obj));
			else
				SETSYMBOL(atom+k,&s_);
		}
		outlet_list(outlet,gensym("list"),size,atom);
	}
	else if(PyTuple_Check(value))
	{
		register int k,K;
		Py_ssize_t size=PyTuple_Size(value);
		t_atom*atom=(t_atom*)calloc(sizeof(t_atom),size);
		for(k=0,K=size;k<K;++k)
		{
			PyObject*obj=PyTuple_GetItem(value,k);
			if(!obj)
				SETSYMBOL(atom+k,&s_);
			else if(obj==Py_True)
				SETFLOAT(atom+k,1);
			else if(obj==Py_False)
				SETSYMBOL(atom+k,&s_);
			else if(PyInt_Check(obj))
				SETFLOAT(atom+k,PyInt_AsLong(obj));
			else if(PyFloat_Check(obj))
				SETFLOAT(atom+k,PyFloat_AsDouble(obj));
			else
				SETSYMBOL(atom+k,&s_);
		}
		outlet_list(outlet,gensym("list"),size,atom);
	}
}
Example #11
0
static int image_init(PyImage *self,
                      PyObject *args,
                      PyObject *kwargs)
{
    PyObject *initial;
    int location = OSL_IN_VRAM;
    int pf = OSL_PF_8888;

    if (!PyArg_ParseTuple(args, "O|ii:__init__", &initial, &location, &pf))
       return -1;

    self->location = location;

    if (PyString_Check(initial))
    {
       // Load from file

       char *filename = PyString_AsString(initial);

       self->pImg = oslLoadImageFile(filename, location, pf);

       if (!self->pImg)
       {
          PyErr_SetString(osl_Error, "Could not load image.");
          return -1;
       }
    }
    else if (PyTuple_Check(initial))
    {
       int w, h;

       if (PyTuple_Size(initial) != 2)
       {
          PyErr_SetString(PyExc_TypeError, "Image dimension must be a 2-tuple");
          return -1;
       }

       if (!PyInt_Check(PyTuple_GetItem(initial, 0)))
       {
          PyErr_SetString(PyExc_TypeError, "Image width must be an integer");
          return -1;
       }

       if (!PyInt_Check(PyTuple_GetItem(initial, 1)))
       {
          PyErr_SetString(PyExc_TypeError, "Image height must be an integer");
          return -1;
       }

       w = PyInt_AsLong(PyTuple_GetItem(initial, 0));
       h = PyInt_AsLong(PyTuple_GetItem(initial, 1));

       self->pImg = oslCreateImage(w, h, location, pf);

       if (!self->pImg)
       {
          PyErr_SetString(osl_Error, "Could not create image");
          return -1;
       }
    }
    else
    {
       PyErr_SetString(PyExc_TypeError, "First argument must be a filename or a 2-tuple");
       return -1;
    }

    if (location == OSL_IN_VRAM)
    {
       FREEIMG *pFree = (FREEIMG*)malloc(sizeof(FREEIMG));

       pFree->bDelete = 0;
       pFree->pImg = self->pImg;
       pFree->next = (void*)pCurrent;
       pCurrent = pFree;
    }

    return 0;
}
Example #12
0
// Convert a Python object to a QJSValue.
int qpyqml_convertTo_QJSValue(PyObject *py, PyObject *transferObj,
        QJSValue **cpp, int *isErr)
{
    if (PyObject_TypeCheck(py, sipTypeAsPyTypeObject(sipType_QJSValue_SpecialValue)))
    {
        *cpp = new QJSValue((QJSValue::SpecialValue)SIPLong_AsLong(py));

        return sipGetState(transferObj);
    }

    if (PyBool_Check(py))
    {
        *cpp = new QJSValue(py == Py_True);

        return sipGetState(transferObj);
    }

#if PY_MAJOR_VERSION >= 3
    if (PyLong_Check(py))
    {
        *cpp = new QJSValue((int)PyLong_AS_LONG(py));

        return sipGetState(transferObj);
    }
#else
    if (PyInt_Check(py))
    {
        *cpp = new QJSValue((int)PyInt_AS_LONG(py));

        return sipGetState(transferObj);
    }
#endif

    if (PyFloat_Check(py))
    {
        *cpp = new QJSValue((double)PyFloat_AS_DOUBLE(py));

        return sipGetState(transferObj);
    }

    if (sipCanConvertToType(py, sipType_QString, 0))
    {
        int state;
        QString *qs = reinterpret_cast<QString *>(sipConvertToType(py,
                sipType_QString, 0, 0, &state, isErr));

        if (*isErr)
        {
            sipReleaseType(qs, sipType_QString, state);
            return 0;
        }

        *cpp = new QJSValue(*qs);

        sipReleaseType(qs, sipType_QString, state);

        return sipGetState(transferObj);
    }

    *cpp = reinterpret_cast<QJSValue *>(sipConvertToType(py, sipType_QJSValue,
            transferObj, SIP_NO_CONVERTORS, 0, isErr));

    return 0;
}
Example #13
0
static PyObject *
archpy_disassemble (PyObject *self, PyObject *args, PyObject *kw)
{
  static char *keywords[] = { "start_pc", "end_pc", "count", NULL };
  CORE_ADDR start, end = 0;
  CORE_ADDR pc;
  gdb_py_ulongest start_temp;
  long count = 0, i;
  PyObject *result_list, *end_obj = NULL, *count_obj = NULL;
  struct gdbarch *gdbarch = NULL;

  ARCHPY_REQUIRE_VALID (self, gdbarch);

  if (!PyArg_ParseTupleAndKeywords (args, kw, GDB_PY_LLU_ARG "|OO", keywords,
                                    &start_temp, &end_obj, &count_obj))
    return NULL;

  start = start_temp;
  if (end_obj)
    {
      /* Make a long logic check first.  In Python 3.x, internally,
	 all integers are represented as longs.  In Python 2.x, there
	 is still a differentiation internally between a PyInt and a
	 PyLong.  Explicitly do this long check conversion first. In
	 GDB, for Python 3.x, we #ifdef PyInt = PyLong.  This check has
	 to be done first to ensure we do not lose information in the
	 conversion process.  */
      if (PyLong_Check (end_obj))
        end = PyLong_AsUnsignedLongLong (end_obj);
      else if (PyInt_Check (end_obj))
        /* If the end_pc value is specified without a trailing 'L', end_obj will
           be an integer and not a long integer.  */
        end = PyInt_AsLong (end_obj);
      else
        {
          Py_DECREF (end_obj);
          Py_XDECREF (count_obj);
          PyErr_SetString (PyExc_TypeError,
                           _("Argument 'end_pc' should be a (long) integer."));

          return NULL;
        }

      if (end < start)
        {
          Py_DECREF (end_obj);
          Py_XDECREF (count_obj);
          PyErr_SetString (PyExc_ValueError,
                           _("Argument 'end_pc' should be greater than or "
                             "equal to the argument 'start_pc'."));

          return NULL;
        }
    }
  if (count_obj)
    {
      count = PyInt_AsLong (count_obj);
      if (PyErr_Occurred () || count < 0)
        {
          Py_DECREF (count_obj);
          Py_XDECREF (end_obj);
          PyErr_SetString (PyExc_TypeError,
                           _("Argument 'count' should be an non-negative "
                             "integer."));

          return NULL;
        }
    }

  result_list = PyList_New (0);
  if (result_list == NULL)
    return NULL;

  for (pc = start, i = 0;
       /* All args are specified.  */
       (end_obj && count_obj && pc <= end && i < count)
       /* end_pc is specified, but no count.  */
       || (end_obj && count_obj == NULL && pc <= end)
       /* end_pc is not specified, but a count is.  */
       || (end_obj == NULL && count_obj && i < count)
       /* Both end_pc and count are not specified.  */
       || (end_obj == NULL && count_obj == NULL && pc == start);)
    {
      int insn_len = 0;
      char *as = NULL;
      struct ui_file *memfile = mem_fileopen ();
      PyObject *insn_dict = PyDict_New ();

      if (insn_dict == NULL)
        {
          Py_DECREF (result_list);
          ui_file_delete (memfile);

          return NULL;
        }
      if (PyList_Append (result_list, insn_dict))
        {
          Py_DECREF (result_list);
          Py_DECREF (insn_dict);
          ui_file_delete (memfile);

          return NULL;  /* PyList_Append Sets the exception.  */
        }

      TRY
        {
          insn_len = gdb_print_insn (gdbarch, pc, memfile, NULL);
        }
      CATCH (except, RETURN_MASK_ALL)
        {
          Py_DECREF (result_list);
          ui_file_delete (memfile);

	  gdbpy_convert_exception (except);
	  return NULL;
        }
      END_CATCH

      as = ui_file_xstrdup (memfile, NULL);
      if (PyDict_SetItemString (insn_dict, "addr",
                                gdb_py_long_from_ulongest (pc))
          || PyDict_SetItemString (insn_dict, "asm",
                                   PyString_FromString (*as ? as : "<unknown>"))
          || PyDict_SetItemString (insn_dict, "length",
                                   PyInt_FromLong (insn_len)))
        {
          Py_DECREF (result_list);

          ui_file_delete (memfile);
          xfree (as);

          return NULL;
        }

      pc += insn_len;
      i++;
      ui_file_delete (memfile);
      xfree (as);
    }
static PyObject *
SPI_xfer2(SPI *self, PyObject *args)
{
	static char *msg = "Argument must be a list of at least one, "
				"but not more than 1024 integers";
	int status;	
	uint8_t ii, len;
	PyObject *list;
	struct spi_ioc_transfer	xfer;
	uint8_t *txbuf, *rxbuf;

	if (!PyArg_ParseTuple(args, "O:xfer2", &list))
		return NULL;

	if (!PyList_Check(list)) {
		PyErr_SetString(PyExc_TypeError, wrmsg);
		return NULL;
	}

	if ((len = PyList_GET_SIZE(list)) > MAXMSGLEN) {
		PyErr_SetString(PyExc_OverflowError, wrmsg);
		return NULL;
	}

	txbuf = malloc(sizeof(__u8) * len);
	rxbuf = malloc(sizeof(__u8) * len);

	for (ii = 0; ii < len; ii++) {
		PyObject *val = PyList_GET_ITEM(list, ii);
		if (!PyInt_Check(val)) {
			PyErr_SetString(PyExc_TypeError, msg);
			return NULL;
		}
		txbuf[ii] = (__u8)PyInt_AS_LONG(val);
	}

	xfer.tx_buf = (unsigned long)txbuf;
	xfer.rx_buf = (unsigned long)rxbuf;
	xfer.len = len;
	xfer.delay_usecs = 0;
	xfer.speed_hz = 0;      
	xfer.bits_per_word = 0;
	
	status = ioctl(self->fd, SPI_IOC_MESSAGE(1), &xfer);
	if (status < 0) {
		PyErr_SetFromErrno(PyExc_IOError);
		return NULL;
	}

	for (ii = 0; ii < len; ii++) {
		PyObject *val = Py_BuildValue("l", (long)rxbuf[ii]);
		PyList_SET_ITEM(list, ii, val);
	}
	// WA:
	// in CS_HIGH mode CS isnt pulled to low after transfer
	// reading 0 bytes doesn't really matter but brings CS down
	status = read(self->fd, &rxbuf[0], 0);

	free(txbuf);
	free(rxbuf);

	Py_INCREF(list);
	return list;
}
Example #15
0
int uwsgi_python_spooler(char *filename, char *buf, uint16_t len, char *body, size_t body_len) {

	static int random_seed_reset = 0;

	UWSGI_GET_GIL;

	PyObject *spool_dict = PyDict_New();
	PyObject *spool_func, *pyargs, *ret;

	if (!random_seed_reset) {
		uwsgi_python_reset_random_seed();
		random_seed_reset = 1;	
	}

	if (!up.embedded_dict) {
		// ignore
		UWSGI_RELEASE_GIL;
		return 0;
	}

	spool_func = PyDict_GetItemString(up.embedded_dict, "spooler");
	if (!spool_func) {
		// ignore
		UWSGI_RELEASE_GIL;
		return 0;
	}

	if (uwsgi_hooked_parse(buf, len, uwsgi_python_add_item, spool_dict)) {
		// malformed packet, destroy it
		UWSGI_RELEASE_GIL;
		return -2;
	}

	pyargs = PyTuple_New(1);

	PyDict_SetItemString(spool_dict, "spooler_task_name", PyString_FromString(filename));

	if (body && body_len > 0) {
		PyDict_SetItemString(spool_dict, "body", PyString_FromStringAndSize(body, body_len));
	}
	PyTuple_SetItem(pyargs, 0, spool_dict);

	ret = python_call(spool_func, pyargs, 0, NULL);

	if (ret) {
		if (!PyInt_Check(ret)) {
			// error, retry
			UWSGI_RELEASE_GIL;
			return -1;
		}	

		int retval = (int) PyInt_AsLong(ret);
		UWSGI_RELEASE_GIL;
		return retval;
		
	}
	
	if (PyErr_Occurred())
		PyErr_Print();

	// error, retry
	UWSGI_RELEASE_GIL;
	return -1;
}
void
avtPythonExpression::Execute()
{
    //
    // the real outputVariableName is not avalaible until well after
    // ProcessArguments is called - set it here so the filter can use the 
    // the proper output name.
    //
    pyEnv->Filter()->SetAttribute("output_var_name",std::string(outputVariableName));

    // get input data tree to obtain datasets
    avtDataTree_p tree = GetInputDataTree();
    // holds number of datasets
    int nsets;

    // get datasets
    vtkDataSet **data_sets = tree->GetAllLeaves(nsets);

    // get dataset domain ids
    std::vector<int> domain_ids;
    tree->GetAllDomainIds(domain_ids);

    // create a tuple holding to hold the datasets
    PyObject *py_dsets  = PyTuple_New(nsets);
    PyObject *py_domids = PyTuple_New(nsets);

     if(py_dsets == NULL || py_domids == NULL)
     {
            delete [] data_sets;
            PYEXPR_ERROR("avtPythonExpression::Execute Error - "
                         "Unable to create execution input lists");
     }

    // array to hold output leaves
    avtDataTree_p *leaves = new avtDataTree_p[nsets];

    // hand data_sets and domain_ids to the python expression
    for(int i = 0; i < nsets ; i++)
    {
        if(PyTuple_SetItem(py_dsets,i,pyEnv->WrapVTKObject(data_sets[i],"vtkDataSet")) != 0)
        {
            delete [] data_sets;
            PYEXPR_ERROR("avtPythonExpression::Execute Error - "
                         "Unable to add data set to execution input list");
        }
        if(PyTuple_SetItem(py_domids,i,PyInt_FromLong(domain_ids[i])) != 0)
        {
            delete [] data_sets;
            PYEXPR_ERROR("avtPythonExpression::Execute Error - "
                         "Unable to add domain id to execution input list");
        }

    }
    delete [] data_sets;

    // call execute on Filter
    PyObject *py_filter = pyEnv->Filter()->PythonObject();
    if(py_filter == NULL)
        PYEXPR_ERROR("avtPythonExpression::Execute Error - "
                     "Python filter not initialized.");

    // get the execute method
    PyObject *py_exe= PyString_FromString("execute");
    if(py_exe == NULL)
        PYEXPR_ERROR("avtPythonExpression::Execute Error - "
                     "Error preparing for call of 'execute' method.");
    // call with py_dsets, py_domids
    PyObject *py_exe_res = PyObject_CallMethodObjArgs(py_filter,
                                                      py_exe,
                                                      py_dsets,py_domids,
                                                      NULL);
    if(py_exe_res == NULL)
        PYEXPR_ERROR("avtPythonExpression::Execute Error - "
                     "Python Expression 'execute' method failed");
    if(PySequence_Check(py_exe_res) == 0)
        PYEXPR_ERROR("avtPythonExpression::Execute Error - "
                     "Python Expression 'execute' method must return a sequence of "
                     "data sets & a sequence of domain_ids");

    Py_DECREF(py_dsets);
    Py_DECREF(py_domids);
    Py_DECREF(py_exe);


    // result should be a list with datasets and domain ids

    PyObject *py_result_dsets  = PySequence_GetItem(py_exe_res,0);
    PyObject *py_result_domids = PySequence_GetItem(py_exe_res,1);

    

    if(py_result_dsets == NULL || PySequence_Check(py_result_dsets) == 0)
        PYEXPR_ERROR("avtPythonExpression::Execute Error - "
                     "Python Expression execute method must return a sequence of "
                     "data sets & a sequence of domain_ids");

    if(py_result_domids == NULL || PySequence_Check(py_result_domids) == 0)
        PYEXPR_ERROR("avtPythonExpression::Execute Error - "
                     "Python Expression execute method must return a sequence of "
                     "data sets & a sequence of domain_ids");

    PyObject *py_r_dsets  = PySequence_Fast(py_result_dsets,"Expected Sequence");
    PyObject *py_r_domids = PySequence_Fast(py_result_domids,"Expected Sequence");

    if(py_r_dsets == NULL || py_r_domids == NULL)
        PYEXPR_ERROR("avtPythonExpression::Execute Error - "
                     "Unable to obtain result sequences.");


    // int n_r_dsets  = PySequence_Size(py_r_dsets);
    // int n_r_domids = PySequence_Size(py_r_domids);

    // check that the lists are the correct size?

    std::vector<vtkDataSet*> res_dsets;
    std::vector<int>         res_domids;
    
    // process all local sets
    for(int i = 0; i < nsets ; i++)
    {
        // get current set
        vtkDataSet *res_dset = NULL; // fetch each set from vtk output
        int         res_domid = -1;

        PyObject *py_dset  = PySequence_Fast_GET_ITEM(py_r_dsets,i);  // borrowed
        PyObject *py_domid = PySequence_Fast_GET_ITEM(py_r_domids,i); // borrowed
        
        if(py_dset == NULL)
            PYEXPR_ERROR("avtPythonExpression::Execute Error - "
                         "Unable fetch result data set.");

        if(py_dset != Py_None) // allow 'None' as return
        {
            res_dset = (vtkDataSet*) pyEnv->UnwrapVTKObject(py_dset,"vtkDataSet");
            if(res_dset == NULL)
                PYEXPR_ERROR("avtPythonExpression::Execute Error - "
                             "Error unwraping vtkDataSet result.");
             if(py_domid == NULL || PyInt_Check(py_domid) == 0)
                 PYEXPR_ERROR("avtPythonExpression::Execute Error - "
                              "Unable fetch result domain id.");
             res_domid = (int) PyInt_AsLong(py_domid);
        }
        
        res_dsets.push_back(res_dset);
        res_domids.push_back(res_domid);
    }
    
    // if we have no errors, register the datasets & create the output 
    // data tree
    for(int i = 0; i < nsets ; i++)
    {
        if(res_dsets[i]) // add result as new leaf
        {
            res_dsets[i]->Register(NULL);
            leaves[i] = new avtDataTree(res_dsets[i],res_domids[i]);
        }
        else // if the dataset only contained ghost zones we could end up here
            leaves[i] = NULL;
        
    }

    Py_DECREF(py_result_dsets);
    Py_DECREF(py_result_domids);
    Py_DECREF(py_r_dsets);
    Py_DECREF(py_r_domids);
    Py_DECREF(py_exe_res);

    // create output data tree
    avtDataTree_p result_tree = new avtDataTree(nsets,leaves);
    // set output data tree
    SetOutputDataTree(result_tree);

    // cleanup leaves array
    delete [] leaves;

}
Example #17
0
/* Enter the final scope information into the st_symbols dict.
 *
 * All arguments are dicts.  Modifies symbols, others are read-only.
*/
static int
update_symbols(PyObject *symbols, PyObject *scope,
               PyObject *bound, PyObject *free, int classflag)
{
    PyObject *name, *v, *u, *w, *free_value = NULL;
    Py_ssize_t pos = 0;

    while (PyDict_Next(symbols, &pos, &name, &v)) {
        long i, flags;
        assert(PyInt_Check(v));
        flags = PyInt_AS_LONG(v);
        w = PyDict_GetItem(scope, name);
        assert(w && PyInt_Check(w));
        i = PyInt_AS_LONG(w);
        flags |= (i << SCOPE_OFF);
        u = PyInt_FromLong(flags);
        if (!u)
            return 0;
        if (PyDict_SetItem(symbols, name, u) < 0) {
            Py_DECREF(u);
            return 0;
        }
        Py_DECREF(u);
    }

    free_value = PyInt_FromLong(FREE << SCOPE_OFF);
    if (!free_value)
        return 0;

    /* add a free variable when it's only use is for creating a closure */
    pos = 0;
    while (PyDict_Next(free, &pos, &name, &v)) {
        PyObject *o = PyDict_GetItem(symbols, name);

        if (o) {
            /* It could be a free variable in a method of
               the class that has the same name as a local
               or global in the class scope.
            */
            if  (classflag &&
                 PyInt_AS_LONG(o) & (DEF_BOUND | DEF_GLOBAL)) {
                long i = PyInt_AS_LONG(o) | DEF_FREE_CLASS;
                o = PyInt_FromLong(i);
                if (!o) {
                    Py_DECREF(free_value);
                    return 0;
                }
                if (PyDict_SetItem(symbols, name, o) < 0) {
                    Py_DECREF(o);
                    Py_DECREF(free_value);
                    return 0;
                }
                Py_DECREF(o);
            }
            /* else it's not free, probably a cell */
            continue;
        }
        if (!PyDict_GetItem(bound, name))
            continue;       /* it's a global */

        if (PyDict_SetItem(symbols, name, free_value) < 0) {
            Py_DECREF(free_value);
            return 0;
        }
    }
    Py_DECREF(free_value);
    return 1;
}
Example #18
0
// @object PyMAPINAMEIDArray|A sequence (<o PyIID>, string/int) objects
BOOL PyMAPIObject_AsMAPINAMEIDArray(PyObject *ob, MAPINAMEID ***pppNameId, ULONG *pNumIds, BOOL bNoneOK /*= FALSE*/ )
{
    if (bNoneOK && ob==Py_None) {
        *pppNameId = NULL;
        *pNumIds = 0;
        return TRUE;
    }
    PyErr_Clear();
    ULONG len = (ULONG)PySequence_Length(ob);
    if (PyErr_Occurred()) {
        PyErr_Clear();
        PyErr_SetString(PyExc_TypeError, "MAPINAMEID array list be a sequence of tuples");
        return FALSE;
    }
    MAPINAMEID **ppNew = NULL;
    MAPINAMEID *prgIds = NULL;
    IID *pIIDs = NULL;
    HRESULT hr = MAPIAllocateBuffer(len * sizeof(MAPINAMEID *), (void **)&ppNew);
    if (SUCCEEDED(hr)) hr = MAPIAllocateMore(len * sizeof(MAPINAMEID), ppNew, (void **)&prgIds);
    if (SUCCEEDED(hr)) hr = MAPIAllocateMore(len * sizeof(IID), ppNew, (void **)&pIIDs);
    if (FAILED(hr)) {
        MAPIFreeBuffer(ppNew);
        OleSetOleError(hr);
        return FALSE;
    }
    for (ULONG i=0; i<len; i++) {
        ppNew[i] = prgIds+i;
        MAPINAMEID *pNew = prgIds+i;
        PyObject *obIID, *obPropId;
        PyObject *pMe = PySequence_GetItem(ob, i);
        if (pMe==NULL) {
            goto loop_error;
        }
        if (!PyArg_ParseTuple(pMe, "OO", &obIID, &obPropId )) {
            PyErr_Clear();
            PyErr_SetString(PyExc_TypeError, "MAPINAMEIDArray must be a sequence of (iid, string/int) tuples");
            goto loop_error;
        }

        pNew->lpguid = pIIDs+i;
        BSTR bstrVal;
        if (!PyWinObject_AsIID(obIID, pIIDs+i))
            goto loop_error;
        if (PyInt_Check(obPropId)) {
            pNew->ulKind = MNID_ID;
            pNew->Kind.lID = PyInt_AsLong(obPropId);
        } else if (PyWinObject_AsBstr(obPropId, &bstrVal)) {
            // Make a copy of the string
            pNew->ulKind = MNID_STRING;
            DWORD strLen = SysStringLen(bstrVal);
            hr = MAPIAllocateMore(sizeof(WCHAR) * (strLen+1), ppNew, (void **)&pNew->Kind.lpwstrName);
            if (FAILED(hr)) {
                PyWinObject_FreeBstr(bstrVal);
                OleSetOleError(hr);
                goto loop_error;
            }
            wcsncpy(pNew->Kind.lpwstrName, bstrVal, strLen+1);
            PyWinObject_FreeBstr(bstrVal);
        } else {
            PyErr_SetString(PyExc_TypeError, "The type of property ID is invalid - must be string/unicode or int");
            goto loop_error;
        }
        Py_DECREF(pMe);
        continue;
loop_error:
        Py_XDECREF(pMe);
        MAPIFreeBuffer(ppNew);
        return NULL;
    }
    *pppNameId = ppNew;
    *pNumIds = len;
    return TRUE;
}
Example #19
0
static PyObject* mqttv3_connect(PyObject* self, PyObject *args)
{
	MQTTClient c;
	PyObject *pyoptions = NULL, *temp;
	MQTTClient_connectOptions options = MQTTClient_connectOptions_initializer;
	MQTTClient_willOptions woptions = MQTTClient_willOptions_initializer;
	int rc;

	if (!PyArg_ParseTuple(args, "k|O", &c, &pyoptions))
		return NULL;

	printf("connect MQTTClient pointer %p\n", c);
	if (!pyoptions)
		goto skip;

	if (!PyDict_Check(pyoptions))
	{
		PyErr_SetString(PyExc_TypeError, "2nd parameter must be a dictionary");
		return NULL;
	}

	if ((temp = PyDict_GetItemString(pyoptions, "keepAliveInterval")) != NULL)
	{
		if (PyInt_Check(temp))
			options.keepAliveInterval = (int) PyInt_AsLong(temp);
		else
		{
			PyErr_SetString(PyExc_TypeError,
					"keepAliveLiveInterval value must be int");
			return NULL;
		}
	}

	if ((temp = PyDict_GetItemString(pyoptions, "cleansession")) != NULL)
	{
		if (PyInt_Check(temp))
			options.cleansession = (int) PyInt_AsLong(temp);
		else
		{
			PyErr_SetString(PyExc_TypeError, "cleansession value must be int");
			return NULL;
		}
	}

	if ((temp = PyDict_GetItemString(pyoptions, "reliable")) != NULL)
	{
		if (PyInt_Check(temp))
			options.reliable = (int) PyInt_AsLong(temp);
		else
		{
			PyErr_SetString(PyExc_TypeError, "reliable value must be int");
			return NULL;
		}
	}

	if ((temp = PyDict_GetItemString(pyoptions, "will")) != NULL)
	{
		if (PyDict_Check(temp))
		{
			PyObject *wtemp = NULL;
			if ((wtemp = PyDict_GetItemString(temp, "topicName")) == NULL)
			{
				PyErr_SetString(PyExc_TypeError,
						"will topicName value must be set");
				return NULL;
			}
			else
			{
				if (PyString_Check(wtemp))
					woptions.topicName = PyString_AsString(wtemp);
				else
				{
					PyErr_SetString(PyExc_TypeError,
							"will topicName value must be string");
					return NULL;
				}
			}
			if ((wtemp = PyDict_GetItemString(temp, "message")) == NULL)
			{
				PyErr_SetString(PyExc_TypeError,
						"will message value must be set");
				return NULL;
			}
			else
			{
				if (PyString_Check(wtemp))
					woptions.message = PyString_AsString(wtemp);
				else
				{
					PyErr_SetString(PyExc_TypeError,
							"will message value must be string");
					return NULL;
				}
			}
			if ((wtemp = PyDict_GetItemString(temp, "retained")) != NULL)
			{
				if (PyInt_Check(wtemp))
					woptions.retained = (int) PyInt_AsLong(wtemp);
				else
				{
					PyErr_SetString(PyExc_TypeError,
							"will retained value must be int");
					return NULL;
				}
			}
			if ((wtemp = PyDict_GetItemString(temp, "qos")) != NULL)
			{
				if (PyInt_Check(wtemp))
					woptions.qos = (int) PyInt_AsLong(wtemp);
				else
				{
					PyErr_SetString(PyExc_TypeError,
							"will qos value must be int");
					return NULL;
				}
			}
			options.will = &woptions;
		}
		else
		{
			PyErr_SetString(PyExc_TypeError, "will value must be dictionary");
			return NULL;
		}
	}

	if ((temp = PyDict_GetItemString(pyoptions, "username")) != NULL)
	{
		if (PyString_Check(temp))
			options.username = PyString_AsString(temp);
		else
		{
			PyErr_SetString(PyExc_TypeError, "username value must be string");
			return NULL;
		}
	}

	if ((temp = PyDict_GetItemString(pyoptions, "password")) != NULL)
	{
		if (PyString_Check(temp))
			options.username = PyString_AsString(temp);
		else
		{
			PyErr_SetString(PyExc_TypeError, "password value must be string");
			return NULL;
		}
	}

	skip: Py_BEGIN_ALLOW_THREADS rc = MQTTClient_connect(c, &options);
	Py_END_ALLOW_THREADS
	return Py_BuildValue("i", rc);
}
Example #20
0
PyObject*
PyImaging_LibTiffEncoderNew(PyObject* self, PyObject* args)
{
    ImagingEncoderObject* encoder;

    char* mode;
    char* rawmode;
    char* compname;
    char* filename;
    int fp;

    PyObject *dir;
    PyObject *key, *value;
    Py_ssize_t pos = 0;
    int status;

    Py_ssize_t d_size;
    PyObject *keys, *values;


    if (! PyArg_ParseTuple(args, "sssisO", &mode, &rawmode, &compname, &fp, &filename, &dir)) {
        return NULL;
    }

    if (!PyDict_Check(dir)) {
        PyErr_SetString(PyExc_ValueError, "Invalid Dictionary");
        return NULL;
    } else {
        d_size = PyDict_Size(dir);
        TRACE(("dict size: %d\n", (int)d_size));
        keys = PyDict_Keys(dir);
        values = PyDict_Values(dir);
        for (pos=0;pos<d_size;pos++){
            TRACE(("  key: %d\n", (int)PyInt_AsLong(PyList_GetItem(keys,pos))));
        }
        pos = 0;
    }


    TRACE(("new tiff encoder %s fp: %d, filename: %s \n", compname, fp, filename));

    encoder = PyImaging_EncoderNew(sizeof(TIFFSTATE));
    if (encoder == NULL)
        return NULL;

    if (get_packer(encoder, mode, rawmode) < 0)
        return NULL;

    if (! ImagingLibTiffEncodeInit(&encoder->state, filename, fp)) {
        Py_DECREF(encoder);
        PyErr_SetString(PyExc_RuntimeError, "tiff codec initialization failed");
        return NULL;
    }

        // While failes on 64 bit machines, complains that pos is an int instead of a Py_ssize_t
        //    while (PyDict_Next(dir, &pos, &key, &value)) {
        for (pos=0;pos<d_size;pos++){
                key = PyList_GetItem(keys,pos);
                value = PyList_GetItem(values,pos);
        status = 0;
        TRACE(("Attempting to set key: %d\n", (int)PyInt_AsLong(key)));
        if (PyInt_Check(value)) {
            TRACE(("Setting from Int: %d %ld \n", (int)PyInt_AsLong(key),PyInt_AsLong(value)));
            status = ImagingLibTiffSetField(&encoder->state,
                                            (ttag_t) PyInt_AsLong(key),
                                            PyInt_AsLong(value));
        } else if(PyBytes_Check(value)) {
            TRACE(("Setting from Bytes: %d, %s \n", (int)PyInt_AsLong(key),PyBytes_AsString(value)));
            status = ImagingLibTiffSetField(&encoder->state,
                                            (ttag_t) PyInt_AsLong(key),
                                            PyBytes_AsString(value));
        } else if(PyList_Check(value)) {
            int len,i;
            float *floatav;
            int *intav;
            TRACE(("Setting from List: %d \n", (int)PyInt_AsLong(key)));
            len = (int)PyList_Size(value);
            if (len) {
                if (PyInt_Check(PyList_GetItem(value,0))) {
                    TRACE((" %d elements, setting as ints \n", len));
                    intav = malloc(sizeof(int)*len);
                    if (intav) {
                        for (i=0;i<len;i++) {
                            intav[i] = (int)PyInt_AsLong(PyList_GetItem(value,i));
                        }
                        status = ImagingLibTiffSetField(&encoder->state,
                                                        (ttag_t) PyInt_AsLong(key),
                                                        intav);
                        free(intav);
                    }       
                } else {
                    TRACE((" %d elements, setting as floats \n", len));
                    floatav = malloc(sizeof(float)*len);
                    if (floatav) {
                        for (i=0;i<len;i++) {
                            floatav[i] = (float)PyFloat_AsDouble(PyList_GetItem(value,i));
                        }
                        status = ImagingLibTiffSetField(&encoder->state,
                                                        (ttag_t) PyInt_AsLong(key),
                                                        floatav);
                        free(floatav);
                    }
                }
            }
        } else if (PyFloat_Check(value)) {
            TRACE(("Setting from Float: %d, %f \n", (int)PyInt_AsLong(key),PyFloat_AsDouble(value)));
            status = ImagingLibTiffSetField(&encoder->state,
                                            (ttag_t) PyInt_AsLong(key),
                                            (float)PyFloat_AsDouble(value));
        } else {
            TRACE(("Unhandled type for key %d : %s \n",
                   (int)PyInt_AsLong(key),
                   PyBytes_AsString(PyObject_Str(value))));
        }
        if (!status) {
            TRACE(("Error setting Field\n"));
            Py_DECREF(encoder);
            PyErr_SetString(PyExc_RuntimeError, "Error setting from dictionary");
            return NULL;
        }
    }

    encoder->encode  = ImagingLibTiffEncode;

    return (PyObject*) encoder;
}
Example #21
0
static int child_init(int rank)
{
	PyObject *pFunc, *pArgs, *pValue, *pResult;
	int rval;
	char *classname;

	PyEval_AcquireLock();
	PyThreadState_Swap(myThreadState);

	// get instance class name
	classname = get_instance_class_name(handler_obj);
	if (classname == NULL)
	{
		if (!PyErr_Occurred())
			PyErr_Format(PyExc_AttributeError, "'module' instance has no class name");
		python_handle_exception("child_init");
		Py_DECREF(format_exc_obj);
		PyThreadState_Swap(NULL);
		PyEval_ReleaseLock();
		return -1;
	}

	pFunc = PyObject_GetAttrString(handler_obj, child_init_mname.s);

	if (pFunc == NULL) {
		python_handle_exception("child_init");
		Py_XDECREF(pFunc);
		Py_DECREF(format_exc_obj);
		PyThreadState_Swap(NULL);
		PyEval_ReleaseLock();
		return -1;
	}

	if (!PyCallable_Check(pFunc)) {
		if (!PyErr_Occurred())
			PyErr_Format(PyExc_AttributeError, "class object '%s' has is not callable attribute '%s'", !classname ? "None" : classname, mod_init_fname.s);
		python_handle_exception("child_init");
		Py_DECREF(format_exc_obj);
		Py_XDECREF(pFunc);
		PyThreadState_Swap(NULL);
		PyEval_ReleaseLock();
		return -1;
	}

	pArgs = PyTuple_New(1);
	if (pArgs == NULL) {
		python_handle_exception("child_init");
		Py_DECREF(format_exc_obj);
		Py_DECREF(pFunc);
		PyThreadState_Swap(NULL);
		PyEval_ReleaseLock();
		return -1;
	}

	pValue = PyInt_FromLong((long)rank);
	if (pValue == NULL) {
		python_handle_exception("child_init");
		Py_DECREF(format_exc_obj);
		Py_DECREF(pArgs);
		Py_DECREF(pFunc);
		PyThreadState_Swap(NULL);
		PyEval_ReleaseLock();
		return -1;
	}
	PyTuple_SetItem(pArgs, 0, pValue);
	/* pValue has been stolen */

	pResult = PyObject_CallObject(pFunc, pArgs);
	Py_DECREF(pFunc);
	Py_DECREF(pArgs);




	if (PyErr_Occurred()) {
		python_handle_exception("child_init");
		Py_DECREF(format_exc_obj);
		Py_XDECREF(pResult);
		PyThreadState_Swap(NULL);
		PyEval_ReleaseLock();
		return -1;
	}

	if (pResult == NULL) {
		LM_ERR("PyObject_CallObject() returned NULL but no exception!\n");
		PyThreadState_Swap(NULL);
		PyEval_ReleaseLock();
		return -1;
	}

	if (!PyInt_Check(pResult))
	{
		if (!PyErr_Occurred())
			PyErr_Format(PyExc_TypeError, "method '%s' of class '%s' should return 'int' type", child_init_mname.s, !classname ? "None" : classname);
		python_handle_exception("child_init");
		Py_DECREF(format_exc_obj);
		Py_XDECREF(pResult);
		PyThreadState_Swap(NULL);
		PyEval_ReleaseLock();
		return -1;
	}


	rval = PyInt_AsLong(pResult);
	Py_DECREF(pResult);
	PyThreadState_Swap(NULL);
	PyEval_ReleaseLock();

	return rval;
}
Example #22
0
static char *
convertsimple(PyObject *arg, char **p_format, va_list *p_va, char *msgbuf,
              size_t bufsize, PyObject **freelist)
{
    char *format = *p_format;
    char c = *format++;
#ifdef Py_USING_UNICODE
    PyObject *uarg;
#endif

    switch (c) {

    case 'b': { /* unsigned byte -- very short int */
        char *p = va_arg(*p_va, char *);
        long ival;
        if (float_argument_error(arg))
            return converterr("integer<b>", arg, msgbuf, bufsize);
        ival = PyInt_AsLong(arg);
        if (ival == -1 && PyErr_Occurred())
            return converterr("integer<b>", arg, msgbuf, bufsize);
        else if (ival < 0) {
            PyErr_SetString(PyExc_OverflowError,
                            "unsigned byte integer is less than minimum");
            return converterr("integer<b>", arg, msgbuf, bufsize);
        }
        else if (ival > UCHAR_MAX) {
            PyErr_SetString(PyExc_OverflowError,
                            "unsigned byte integer is greater than maximum");
            return converterr("integer<b>", arg, msgbuf, bufsize);
        }
        else
            *p = (unsigned char) ival;
        break;
    }

    case 'B': {
        /* byte sized bitfield - both signed and unsigned
        	      values allowed */
        char *p = va_arg(*p_va, char *);
        long ival;
        if (float_argument_error(arg))
            return converterr("integer<B>", arg, msgbuf, bufsize);
        ival = PyInt_AsUnsignedLongMask(arg);
        if (ival == -1 && PyErr_Occurred())
            return converterr("integer<B>", arg, msgbuf, bufsize);
        else
            *p = (unsigned char) ival;
        break;
    }

    case 'h': {/* signed short int */
        short *p = va_arg(*p_va, short *);
        long ival;
        if (float_argument_error(arg))
            return converterr("integer<h>", arg, msgbuf, bufsize);
        ival = PyInt_AsLong(arg);
        if (ival == -1 && PyErr_Occurred())
            return converterr("integer<h>", arg, msgbuf, bufsize);
        else if (ival < SHRT_MIN) {
            PyErr_SetString(PyExc_OverflowError,
                            "signed short integer is less than minimum");
            return converterr("integer<h>", arg, msgbuf, bufsize);
        }
        else if (ival > SHRT_MAX) {
            PyErr_SetString(PyExc_OverflowError,
                            "signed short integer is greater than maximum");
            return converterr("integer<h>", arg, msgbuf, bufsize);
        }
        else
            *p = (short) ival;
        break;
    }

    case 'H': {
        /* short int sized bitfield, both signed and
        	       unsigned allowed */
        unsigned short *p = va_arg(*p_va, unsigned short *);
        long ival;
        if (float_argument_error(arg))
            return converterr("integer<H>", arg, msgbuf, bufsize);
        ival = PyInt_AsUnsignedLongMask(arg);
        if (ival == -1 && PyErr_Occurred())
            return converterr("integer<H>", arg, msgbuf, bufsize);
        else
            *p = (unsigned short) ival;
        break;
    }

    case 'i': {/* signed int */
        int *p = va_arg(*p_va, int *);
        long ival;
        if (float_argument_error(arg))
            return converterr("integer<i>", arg, msgbuf, bufsize);
        ival = PyInt_AsLong(arg);
        if (ival == -1 && PyErr_Occurred())
            return converterr("integer<i>", arg, msgbuf, bufsize);
        else if (ival > INT_MAX) {
            PyErr_SetString(PyExc_OverflowError,
                            "signed integer is greater than maximum");
            return converterr("integer<i>", arg, msgbuf, bufsize);
        }
        else if (ival < INT_MIN) {
            PyErr_SetString(PyExc_OverflowError,
                            "signed integer is less than minimum");
            return converterr("integer<i>", arg, msgbuf, bufsize);
        }
        else
            *p = ival;
        break;
    }

    case 'I': {
        /* int sized bitfield, both signed and
        	       unsigned allowed */
        unsigned int *p = va_arg(*p_va, unsigned int *);
        unsigned int ival;
        if (float_argument_error(arg))
            return converterr("integer<I>", arg, msgbuf, bufsize);
        ival = PyInt_AsUnsignedLongMask(arg);
        if (ival == -1 && PyErr_Occurred())
            return converterr("integer<I>", arg, msgbuf, bufsize);
        else
            *p = ival;
        break;
    }

    case 'l': {/* long int */
        long *p = va_arg(*p_va, long *);
        long ival;
        if (float_argument_error(arg))
            return converterr("integer<l>", arg, msgbuf, bufsize);
        ival = PyInt_AsLong(arg);
        if (ival == -1 && PyErr_Occurred())
            return converterr("integer<l>", arg, msgbuf, bufsize);
        else
            *p = ival;
        break;
    }

    case 'k': { /* long sized bitfield */
        unsigned long *p = va_arg(*p_va, unsigned long *);
        unsigned long ival;
        if (PyInt_Check(arg))
            ival = PyInt_AsUnsignedLongMask(arg);
        else if (PyLong_Check(arg))
            ival = PyLong_AsUnsignedLongMask(arg);
        else
            return converterr("integer<k>", arg, msgbuf, bufsize);
        *p = ival;
        break;
    }

#ifdef HAVE_LONG_LONG
    case 'L': {/* PY_LONG_LONG */
        PY_LONG_LONG *p = va_arg( *p_va, PY_LONG_LONG * );
        PY_LONG_LONG ival = PyLong_AsLongLong( arg );
        if( ival == (PY_LONG_LONG)-1 && PyErr_Occurred() ) {
            return converterr("long<L>", arg, msgbuf, bufsize);
        } else {
            *p = ival;
        }
        break;
    }

    case 'K': { /* long long sized bitfield */
        unsigned PY_LONG_LONG *p = va_arg(*p_va, unsigned PY_LONG_LONG *);
        unsigned PY_LONG_LONG ival;
        if (PyInt_Check(arg))
            ival = PyInt_AsUnsignedLongMask(arg);
        else if (PyLong_Check(arg))
            ival = PyLong_AsUnsignedLongLongMask(arg);
        else
            return converterr("integer<K>", arg, msgbuf, bufsize);
        *p = ival;
        break;
    }
#endif

    case 'f': {/* float */
        float *p = va_arg(*p_va, float *);
        double dval = PyFloat_AsDouble(arg);
        if (PyErr_Occurred())
            return converterr("float<f>", arg, msgbuf, bufsize);
        else
            *p = (float) dval;
        break;
    }

    case 'd': {/* double */
        double *p = va_arg(*p_va, double *);
        double dval = PyFloat_AsDouble(arg);
        if (PyErr_Occurred())
            return converterr("float<d>", arg, msgbuf, bufsize);
        else
            *p = dval;
        break;
    }

#ifndef WITHOUT_COMPLEX
    case 'D': {/* complex double */
        Py_complex *p = va_arg(*p_va, Py_complex *);
        Py_complex cval;
        cval = PyComplex_AsCComplex(arg);
        if (PyErr_Occurred())
            return converterr("complex<D>", arg, msgbuf, bufsize);
        else
            *p = cval;
        break;
    }
#endif /* WITHOUT_COMPLEX */

    case 'c': {/* char */
        char *p = va_arg(*p_va, char *);
        if (PyString_Check(arg) && PyString_Size(arg) == 1)
            *p = PyString_AS_STRING(arg)[0];
        else
            return converterr("char", arg, msgbuf, bufsize);
        break;
    }

    case 's': {/* string */
        if (*format == '#') {
            void **p = (void **)va_arg(*p_va, char **);
            int *q = va_arg(*p_va, int *);

            if (PyString_Check(arg)) {
                *p = PyString_AS_STRING(arg);
                *q = PyString_GET_SIZE(arg);
            }
#ifdef Py_USING_UNICODE
            else if (PyUnicode_Check(arg)) {
                uarg = UNICODE_DEFAULT_ENCODING(arg);
                if (uarg == NULL)
                    return converterr(CONV_UNICODE,
                                      arg, msgbuf, bufsize);
                *p = PyString_AS_STRING(uarg);
                *q = PyString_GET_SIZE(uarg);
            }
#endif
            else { /* any buffer-like object */
                char *buf;
                int count = convertbuffer(arg, p, &buf);
                if (count < 0)
                    return converterr(buf, arg, msgbuf, bufsize);
                *q = count;
            }
            format++;
        } else {
            char **p = va_arg(*p_va, char **);

            if (PyString_Check(arg))
                *p = PyString_AS_STRING(arg);
#ifdef Py_USING_UNICODE
            else if (PyUnicode_Check(arg)) {
                uarg = UNICODE_DEFAULT_ENCODING(arg);
                if (uarg == NULL)
                    return converterr(CONV_UNICODE,
                                      arg, msgbuf, bufsize);
                *p = PyString_AS_STRING(uarg);
            }
#endif
            else
                return converterr("string", arg, msgbuf, bufsize);
            if ((int)strlen(*p) != PyString_Size(arg))
                return converterr("string without null bytes",
                                  arg, msgbuf, bufsize);
        }
        break;
    }
Example #23
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;
}
Example #24
0
int py_plugin_exec(struct plugin *plugin, int mesg_count,
                   union cwiid_mesg mesg[])
{
	PyObject *PyArgs, *PyMesg, *PyData, *PyButtonData, *PyAxisData, *PyObj;
	int i;

	if (!(PyMesg = ConvertMesgArray(mesg_count, mesg))) {
		PyErr_Print();
		return -1;
	}

	if (!(PyArgs = Py_BuildValue("(O)", PyMesg))) {
		PyErr_Print();
		Py_DECREF(PyMesg);
		return -1;
	}

	Py_DECREF(PyMesg);

	if (!(PyData = PyObject_CallObject(((struct py_plugin *)plugin->p)->exec,
	                                   PyArgs))) {
		PyErr_Print();
		Py_DECREF(PyArgs);
		return -1;
	}

	Py_DECREF(PyArgs);

	if (!PyArg_ParseTuple(PyData, "OO", &PyButtonData, &PyAxisData)) {
		PyErr_Print();
		Py_DECREF(PyData);
		return -1;
	}

	if (!(PySequence_Check(PyButtonData) && PySequence_Check(PyAxisData))) {
		wminput_err("Type error on wminput_exec: exec not sequences");
		Py_DECREF(PyData);
		return -1;
	}

	if (PySequence_Size(PyButtonData) != plugin->info->button_count) {
		wminput_err("Type error on wminput_exec: bad button sequence");
		Py_DECREF(PyData);
		return -1;
	}
	plugin->data->buttons = 0;
	for (i=0; i < plugin->info->button_count; i++) {
		if (!(PyObj = PySequence_GetItem(PyButtonData, i))) {
			PyErr_Print();
			Py_DECREF(PyData);
			return -1;
		}

		if (PyObj == Py_True) {
			plugin->data->buttons |= 1<<i;
		}
		else if (PyObj != Py_False) {
			wminput_err("Type error on wminput_exec: bad button value");
			Py_DECREF(PyObj);
			Py_DECREF(PyData);
			return -1;
		}

		Py_DECREF(PyObj);
	}

	if (PySequence_Size(PyAxisData) != plugin->info->axis_count) {
		wminput_err("Error on wminput_exec: bad axis sequence");
		Py_DECREF(PyData);
		return -1;
	}
	for (i=0; i < plugin->info->axis_count; i++) {
		if (!(PyObj = PySequence_GetItem(PyAxisData, i))) {
			PyErr_Print();
			Py_DECREF(PyData);
			return -1;
		}

		if (PyObj == Py_None) {
			plugin->data->axes[i].valid = 0;
		}
		else if (!PyInt_Check(PyObj)) {
			wminput_err("Type error on wminput_exec: bad axis value");
			Py_DECREF(PyObj);
			Py_DECREF(PyData);
			return -1;
		}
		else {
			plugin->data->axes[i].valid = 1;
			plugin->data->axes[i].value = PyInt_AsLong(PyObj);
		}

		Py_DECREF(PyObj);
	}

	Py_DECREF(PyData);

	return 0;
}
Example #25
0
  int register_dt(PyObject *py_obj)
  {
    PYW_GIL_CHECK_LOCKED_SCOPE();

    // Already registered?
    if ( dtid >= 0 )
      return dtid;

    memset(&dt, 0, sizeof(dt));
    dt.cbsize = sizeof(dt);
    dt.ud = this;

    do
    {
      ref_t py_attr;

      // name
      if ( !PyW_GetStringAttr(py_obj, S_NAME, &dt_name) )
        break;

      dt.name = dt_name.c_str();

      // menu_name (optional)
      if ( PyW_GetStringAttr(py_obj, S_MENU_NAME, &dt_menu_name) )
        dt.menu_name = dt_menu_name.c_str();

      // asm_keyword (optional)
      if ( PyW_GetStringAttr(py_obj, S_ASM_KEYWORD, &dt_asm_keyword) )
        dt.asm_keyword = dt_asm_keyword.c_str();

      // hotkey (optional)
      if ( PyW_GetStringAttr(py_obj, S_HOTKEY, &dt_hotkey) )
        dt.hotkey = dt_hotkey.c_str();

      // value_size
      py_attr = PyW_TryGetAttrString(py_obj, S_VALUE_SIZE);
      if ( py_attr != NULL && PyInt_Check(py_attr.o) )
        dt.value_size = PyInt_AsLong(py_attr.o);
      py_attr = ref_t();

      // props
      py_attr = PyW_TryGetAttrString(py_obj, S_PROPS);
      if ( py_attr != NULL && PyInt_Check(py_attr.o) )
        dt.props = PyInt_AsLong(py_attr.o);
      py_attr = ref_t();

      // may_create_at
      py_attr = PyW_TryGetAttrString(py_obj, S_MAY_CREATE_AT);
      if ( py_attr != NULL && PyCallable_Check(py_attr.o) )
        dt.may_create_at = s_may_create_at;
      py_attr = ref_t();

      // calc_item_size
      py_attr = PyW_TryGetAttrString(py_obj, S_CALC_ITEM_SIZE);
      if ( py_attr != NULL && PyCallable_Check(py_attr.o) )
        dt.calc_item_size = s_calc_item_size;
      py_attr = ref_t();

      // Now try to register
      dtid = register_custom_data_type(&dt);
      if ( dtid < 0 )
        break;

      // Hold reference to the PyObject
      Py_INCREF(py_obj);
      py_self = py_obj;

      py_attr = newref_t(PyInt_FromLong(dtid));
      PyObject_SetAttrString(py_obj, S_ID, py_attr.o);
    } while ( false );
    return dtid;
  }
Example #26
0
PyObject* pysqlite_row_subscript(pysqlite_Row* self, PyObject* idx)
{
    Py_ssize_t _idx;
    char* key;
    int nitems, i;
    char* compare_key;

    char* p1;
    char* p2;

    PyObject* item;

    if (PyInt_Check(idx)) {
        _idx = PyInt_AsLong(idx);
        if (_idx < 0)
           _idx += PyTuple_GET_SIZE(self->data);
        item = PyTuple_GetItem(self->data, _idx);
        Py_XINCREF(item);
        return item;
    } else if (PyLong_Check(idx)) {
        _idx = PyNumber_AsSsize_t(idx, PyExc_IndexError);
        if (_idx == -1 && PyErr_Occurred())
            return NULL;
        if (_idx < 0)
           _idx += PyTuple_GET_SIZE(self->data);
        item = PyTuple_GetItem(self->data, _idx);
        Py_XINCREF(item);
        return item;
    } else if (PyString_Check(idx)) {
        key = PyString_AsString(idx);

        nitems = PyTuple_Size(self->description);

        for (i = 0; i < nitems; i++) {
            compare_key = PyString_AsString(PyTuple_GET_ITEM(PyTuple_GET_ITEM(self->description, i), 0));
            if (!compare_key) {
                return NULL;
            }

            p1 = key;
            p2 = compare_key;

            while (1) {
                if ((*p1 == (char)0) || (*p2 == (char)0)) {
                    break;
                }

                if ((*p1 | 0x20) != (*p2 | 0x20)) {
                    break;
                }

                p1++;
                p2++;
            }

            if ((*p1 == (char)0) && (*p2 == (char)0)) {
                /* found item */
                item = PyTuple_GetItem(self->data, i);
                Py_INCREF(item);
                return item;
            }

        }

        PyErr_SetString(PyExc_IndexError, "No item with that key");
        return NULL;
    } else if (PySlice_Check(idx)) {
        PyErr_SetString(PyExc_ValueError, "slices not implemented, yet");
        return NULL;
    } else {
        PyErr_SetString(PyExc_IndexError, "Index must be int or string");
        return NULL;
    }
}
Example #27
0
int parse_video_format( unicap_format_t *format, PyObject *obj )
{
   PyObject *tmp;

   unicap_void_format( format );
   
   tmp = PyDict_GetItemString( obj, "identifier" );
   if( tmp )
   {
      char *str;
      str = PyString_AsString( tmp );
      if( str )
      {
	 strcpy( format->identifier, str );
      }
      else
      {
	 return -1;
      }
   }
   tmp = PyDict_GetItemString( obj, "fourcc" );
   if( tmp )
   {
      char *str = PyString_AsString( tmp );
      if( str )
      {
	 format->fourcc = ((unsigned int)str[0]) | (((unsigned int)str[1])<<8) | (((unsigned int)str[2])<<16) | (((unsigned int)str[3])<<24);
      }
      else
      {
	 return -1;
      }
   }
   tmp = PyDict_GetItemString( obj, "bpp" );
   if( tmp )
   {
      if( !PyInt_Check( tmp ) )
      {
	 PyErr_SetString( PyExc_TypeError, "'bpp' must be of type Integer" );
	 return -1;
      }
      format->bpp = PyInt_AsLong( tmp );
   }
   tmp = PyDict_GetItemString( obj, "size" );
   if( tmp )
   {
      PyObject *t;
      if( !PyTuple_Check( tmp ) )
      {
	 PyErr_SetString( PyExc_TypeError, "'size' must be a tuple of Integers" );
	 return -1;
      }
      t = PyTuple_GetItem( tmp, 0 );
      if( !t )
	 return -1;
      if( !PyInt_Check( t ) )
      {
	 PyErr_SetString( PyExc_TypeError, "'size' must be a tuple of Integers" );	 
	 return -1;
      }
      format->size.width = PyInt_AsLong( t );
      
      t = PyTuple_GetItem( tmp, 1 );
      if( !t )
	 return -1;
      if( !PyInt_Check( t ) )
      {
	 PyErr_SetString( PyExc_TypeError, "'size' must be a tuple of Integers" );	 
	 return -1;
      }
      
      format->size.height = PyInt_AsLong( t );
   }

   format->buffer_size = format->size.width * format->size.height * format->bpp / 8;
   
   return 0;
}
Example #28
0
 static bool is_convertible(PyObject *ob, bool raise_exception) {
  if (PyComplex_Check(ob) || PyFloat_Check(ob) || PyInt_Check(ob)) return true;
  if (raise_exception) { PyErr_SetString(PyExc_TypeError, "Cannot convert to complex");}
  return false;
 }
Example #29
0
PyObject* PyBobIpBase_histogram(PyObject*, PyObject* args, PyObject* kwargs) {
  BOB_TRY
  char** kwlist1 = s_histogram.kwlist(0);
  char** kwlist2 = s_histogram.kwlist(1);
  char** kwlist3 = s_histogram.kwlist(2);
  char** kwlist4 = s_histogram.kwlist(3);

  PyBlitzArrayObject* src = 0,* hist = 0;
  PyObject* min_max = 0;
  int bins = 0;

  auto src_ = make_xsafe(src), hist_ = make_xsafe(hist);

  // get the number of command line arguments
  Py_ssize_t nargs = (args?PyTuple_Size(args):0) + (kwargs?PyDict_Size(kwargs):0);

  switch (nargs){
    case 1:{
      if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O&|i", kwlist1, &PyBlitzArray_Converter, &src, &bins)) return 0;
      // get the number of bins
      src_ = make_safe(src);
      break;
    }
    case 2:{
      PyObject* k = Py_BuildValue("s", kwlist1[1]);
      auto k_ = make_safe(k);
      if ((args && PyTuple_Size(args) == 2 && PyInt_Check(PyTuple_GET_ITEM(args,1))) || (kwargs && PyDict_Contains(kwargs, k))){
        if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O&|i", kwlist1, &PyBlitzArray_Converter, &src, &bins)) return 0;
      } else {
        if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O&O&", kwlist2, &PyBlitzArray_Converter, &src, &PyBlitzArray_OutputConverter, &hist)) return 0;
      }
      src_ = make_safe(src);
      hist_ = make_xsafe(hist);
      break;
    }
    case 3:{
      // get values for min and max
      PyObject* k = Py_BuildValue("s", kwlist3[2]);
      auto k_ = make_safe(k);
      if ((args && PyTuple_Size(args) == 3 && PyInt_Check(PyTuple_GET_ITEM(args,2))) || (kwargs && PyDict_Contains(kwargs, k))){
        if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O&Oi", kwlist3, &PyBlitzArray_Converter, &src, &min_max, &bins)) return 0;
      } else {
        if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O&OO&", kwlist4, &PyBlitzArray_Converter, &src, &min_max, &PyBlitzArray_OutputConverter, &hist)) return 0;
      }
      src_ = make_safe(src);
      hist_ = make_xsafe(hist);
      break;
    }
    default:
      PyErr_Format(PyExc_ValueError, "'histogram' called with an unsupported number of arguments");
      return 0;
  }

  // check input size
  if (src->ndim != 2){
    PyErr_Format(PyExc_TypeError, "'histogram' : The input image must be 2D.");
    return 0;
  }

  // allocate the output, if needed
  bool return_out = false;
  if (!hist){
    return_out = true;
    // first, get the number of bins
    if (!bins){
      if (src->type_num == NPY_UINT8) bins = std::numeric_limits<uint8_t>::max() + 1;
      else if (src->type_num == NPY_UINT16) bins = std::numeric_limits<uint16_t>::max() + 1;
      else {
        PyErr_Format(PyExc_TypeError, "'histogram' : The given input data type %s is not supported, when no bin count is specified.", PyBlitzArray_TypenumAsString(src->type_num));
        return 0;
      }
    }
    Py_ssize_t n[] = {bins};
    hist = reinterpret_cast<PyBlitzArrayObject*>(PyBlitzArray_SimpleNew(NPY_UINT64, 1, n));
    hist_ = make_safe(hist);
  } else {
    if (hist->type_num != NPY_UINT64){
      PyErr_Format(PyExc_TypeError, "'histogram' : The given hist data type %s is not supported, only uint64 is allowed.", PyBlitzArray_TypenumAsString(src->type_num));
      return 0;
    }
  }

  // now, get the histogram running
  bool res = true;
  if (min_max){
    switch (src->type_num){
      case NPY_UINT8:    res = inner_histogram<uint8_t, 'B'>(src, hist, min_max); break;
      case NPY_UINT16:   res = inner_histogram<uint16_t, 'H'>(src, hist, min_max); break;
      case NPY_UINT32:   res = inner_histogram<uint32_t, 'I'>(src, hist, min_max); break;
      case NPY_UINT64:   res = inner_histogram<uint64_t, 'K'>(src, hist, min_max); break;
      case NPY_INT8:     res = inner_histogram<int8_t, 'b'>(src, hist, min_max); break;
      case NPY_INT16:    res = inner_histogram<int16_t, 'h'>(src, hist, min_max); break;
      case NPY_INT32:    res = inner_histogram<int32_t, 'i'>(src, hist, min_max); break;
      case NPY_INT64:    res = inner_histogram<int64_t, 'L'>(src, hist, min_max); break;
      case NPY_FLOAT32:  res = inner_histogram<float, 'f'>(src, hist, min_max); break;
      case NPY_FLOAT64:  res = inner_histogram<double, 'd'>(src, hist, min_max); break;
      default:
        PyErr_Format(PyExc_TypeError, "'histogram' : The given input data type %s is not supported.", PyBlitzArray_TypenumAsString(src->type_num));
        return 0;
    }
  } else {
    switch (src->type_num){
      case NPY_UINT8:    inner_histogram<uint8_t, 'B'>(src, hist); break;
      case NPY_UINT16:   inner_histogram<uint16_t, 'H'>(src, hist); break;
      case NPY_UINT32:   inner_histogram<uint32_t, 'I'>(src, hist); break;
      case NPY_UINT64:   inner_histogram<uint64_t, 'K'>(src, hist); break;
      default:
        PyErr_Format(PyExc_TypeError, "'histogram' : The given input data type %s is not supported.", PyBlitzArray_TypenumAsString(src->type_num));
        return 0;
    }
  }
  if (!res) return 0;

  // return the histogram, if wanted
  if (return_out){
    return PyBlitzArray_AsNumpyArray(hist, 0);
  } else {
    Py_RETURN_NONE;
  }

  BOB_CATCH_FUNCTION("in histogram", 0)
}
Example #30
0
static int
cnter_init(PyObject *self, PyObject *args, PyObject *kwds)
{
  PyObject *newargs;
  PyObject *newdefault = NULL;

  if (args == NULL || !PyTuple_Check(args))
	newargs = PyTuple_New(0);
  else {
	Py_ssize_t n = PyTuple_GET_SIZE(args);

	if (n == 1) {
	  newdefault = PyTuple_GET_ITEM(args, 0);
	  if (!(PyInt_Check(newdefault) || PyFloat_Check(newdefault) || PyLong_Check(newdefault))) {
		newdefault = NULL;
		newargs = args;
		Py_INCREF(newargs);
	  }
	  else {
		newargs = PyTuple_New(0);
	  }
	} else if (n == 2) {
	  newdefault = PyTuple_GET_ITEM(args, 1);
	  if (!(PyInt_Check(newdefault) || PyFloat_Check(newdefault) || PyLong_Check(newdefault))) {
		PyErr_SetString(PyExc_TypeError,
						"second argument must be float");                           
		return -1;
	  }
	  else {
		newargs = PySequence_GetSlice(args, 0, 1);
	  }
	} else if (n == 0) {
	  newargs = args;
	  Py_INCREF(newargs);
	} else {
		PyErr_SetString(PyExc_TypeError,
						"counter takes at most 2 arguments");                           
		return -1;
	}
  }

  if (newargs == NULL)
	return -1;

  if (kwds == NULL || !PyDict_Check(kwds))
	kwds = PyDict_New();
  else
	Py_INCREF(kwds);

  int result = PyDict_Type.tp_init(self, newargs, kwds);
  Py_DECREF(newargs);
  Py_DECREF(kwds);

  if (newdefault)
	((cnterobject*)self)->default_value = PyFloat_AsDouble(newdefault);
  else
	((cnterobject*)self)->default_value = 0.0;

  ((cnterobject*)self)->frozen = false;

  return result;
}