static PyObject *
pygpgme_context_encrypt(PyGpgmeContext *self, PyObject *args)
{
    PyObject *py_recp, *py_plain, *py_cipher, *recp_seq = NULL, *result = NULL;
    int flags, i, length;
    gpgme_key_t *recp = NULL;
    gpgme_data_t plain = NULL, cipher = NULL;
    gpgme_error_t err;

    if (!PyArg_ParseTuple(args, "OiOO", &py_recp, &flags,
                          &py_plain, &py_cipher))
        goto end;

    if (py_recp != Py_None) {
        recp_seq = PySequence_Fast(py_recp, "first argument must be a "
                                   "sequence or None");
        if (recp_seq == NULL)
            goto end;

        length = PySequence_Fast_GET_SIZE(recp_seq);
        recp = malloc((length + 1) * sizeof (gpgme_key_t));
        for (i = 0; i < length; i++) {
            PyObject *item = PySequence_Fast_GET_ITEM(recp_seq, i);

            if (!PyObject_TypeCheck(item, &PyGpgmeKey_Type)) {
                PyErr_SetString(PyExc_TypeError, "items in first argument "
                                "must be gpgme.Key objects");
                goto end;
            }
            recp[i] = ((PyGpgmeKey *)item)->key;
        }
        recp[i] = NULL;
    }

    if (pygpgme_data_new(&plain, py_plain))
        goto end;
    if (pygpgme_data_new(&cipher, py_cipher))
        goto end;

    Py_BEGIN_ALLOW_THREADS;    err = gpgme_op_encrypt(self->ctx, recp, flags, plain, cipher);
    Py_END_ALLOW_THREADS;

    if (pygpgme_check_error(err)) {
        decode_encrypt_result(self);
        goto end;
    }

    Py_INCREF(Py_None);
    result = Py_None;

 end:
    if (recp != NULL)
        free(recp);
    Py_XDECREF(recp_seq);
    if (plain != NULL)
        gpgme_data_release(plain);
    if (cipher != NULL)
        gpgme_data_release(cipher);

    return result;
}
Exemple #2
0
 // is_convertible implementation
 template<int N, typename T, typename... Tail> static bool is_convertible_impl(PyObject *seq, bool raise_exception) {
     return py_converter<T>::is_convertible(PySequence_Fast_GET_ITEM(seq, N), raise_exception) &&
            is_convertible_impl<N+1,Tail...>(seq, raise_exception);
 }
Exemple #3
0
static PyObject *
structseq_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
	PyObject *arg = NULL;
	PyObject *dict = NULL;
	PyObject *ob;
	PyStructSequence *res = NULL;
	Py_ssize_t len, min_len, max_len, i, n_unnamed_fields;
	static char *kwlist[] = {"sequence", "dict", 0};

	if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O:structseq", 
					 kwlist, &arg, &dict))
		return NULL;

	arg = PySequence_Fast(arg, "constructor requires a sequence");

	if (!arg) {				
		return NULL;
	}

	if (dict && !PyDict_Check(dict)) {
		PyErr_Format(PyExc_TypeError, 
			     "%.500s() takes a dict as second arg, if any",
			     type->tp_name);
		Py_DECREF(arg);
		return NULL;
	}

	len = PySequence_Fast_GET_SIZE(arg);
	min_len = VISIBLE_SIZE_TP(type);
	max_len = REAL_SIZE_TP(type);
	n_unnamed_fields = UNNAMED_FIELDS_TP(type);

	if (min_len != max_len) {
		if (len < min_len) {
			PyErr_Format(PyExc_TypeError, 
	       "%.500s() takes an at least %zd-sequence (%zd-sequence given)",
				     type->tp_name, min_len, len);
			Py_DECREF(arg);
			return NULL;
		}

		if (len > max_len) {
			PyErr_Format(PyExc_TypeError, 
	       "%.500s() takes an at most %zd-sequence (%zd-sequence given)",
				     type->tp_name, max_len, len);
			Py_DECREF(arg);
			return NULL;
		}
	} 
	else {
		if (len != min_len) {
			PyErr_Format(PyExc_TypeError, 
	       "%.500s() takes a %zd-sequence (%zd-sequence given)",
				     type->tp_name, min_len, len);
			Py_DECREF(arg);
			return NULL;
		}
	}

	res = (PyStructSequence*) PyStructSequence_New(type);
	if (res == NULL) {
		return NULL;
	}
	for (i = 0; i < len; ++i) {
		PyObject *v = PySequence_Fast_GET_ITEM(arg, i);
		Py_INCREF(v);
		res->ob_item[i] = v;
	}
	for (; i < max_len; ++i) {
		if (dict && (ob = PyDict_GetItemString(
			dict, type->tp_members[i-n_unnamed_fields].name))) {
		}
		else {
			ob = Py_None;
		}
		Py_INCREF(ob);
		res->ob_item[i] = ob;
	}
	
	Py_DECREF(arg);
	return (PyObject*) res;
}
/* returns -1 and sets the Python exception if an error occurred, otherwise
   returns a number >= 0
*/
static int
seq2set(PyObject *seq, fd_set *set, pylist fd2obj[FD_SETSIZE + 1])
{
	int i;
	int max = -1;
	int index = 0;
        int len = -1;
        PyObject* fast_seq = NULL;
	PyObject* o = NULL;

	fd2obj[0].obj = (PyObject*)0;	     /* set list to zero size */
	FD_ZERO(set);

        fast_seq=PySequence_Fast(seq, "arguments 1-3 must be sequences");
        if (!fast_seq)
            return -1;

        len = PySequence_Fast_GET_SIZE(fast_seq);

	for (i = 0; i < len; i++)  {
		SOCKET v;

		/* any intervening fileno() calls could decr this refcnt */
		if (!(o = PySequence_Fast_GET_ITEM(fast_seq, i)))
                    return -1;

		Py_INCREF(o);
		v = PyObject_AsFileDescriptor( o );
		if (v == -1) goto finally;

#if defined(_MSC_VER)
		max = 0;		     /* not used for Win32 */
#else  /* !_MSC_VER */
		if (v < 0 || v >= FD_SETSIZE) {
			PyErr_SetString(PyExc_ValueError,
				    "filedescriptor out of range in select()");
			goto finally;
		}
		if (v > max)
			max = v;
#endif /* _MSC_VER */
		FD_SET(v, set);

		/* add object and its file descriptor to the list */
		if (index >= FD_SETSIZE) {
			PyErr_SetString(PyExc_ValueError,
				      "too many file descriptors in select()");
			goto finally;
		}
		fd2obj[index].obj = o;
		fd2obj[index].fd = v;
		fd2obj[index].sentinel = 0;
		fd2obj[++index].sentinel = -1;
	}
        Py_DECREF(fast_seq);
	return max+1;

  finally:
	Py_XDECREF(o);
        Py_DECREF(fast_seq);
	return -1;
}
// Convert the Python values to a raw array.
static void *convert_values(Array *array, PyObject *values, GLenum gl_type,
                            sipErrorState *estate)
{
#if PY_VERSION_HEX >= 0x02060300
    if (PyObject_GetBuffer(values, &array->buffer, PyBUF_FORMAT) != -1)
    {
        // Check the buffer is compatible with what we need.
        if (array->buffer.ndim != 1)
        {
            PyErr_SetString(PyExc_TypeError, "1-dimensional buffer required");
            *estate = sipErrorFail;
            return 0;
        }

        GLenum array_type;

        switch (*array->buffer.format)
        {
        case 'b':
            array_type = GL_BYTE;
            break;

        case 'B':
            array_type = GL_UNSIGNED_BYTE;
            break;

        case 'h':
            array_type = GL_SHORT;
            break;

        case 'H':
            array_type = GL_UNSIGNED_SHORT;
            break;

        case 'i':
            array_type = GL_INT;
            break;

        case 'I':
            array_type = GL_UNSIGNED_INT;
            break;

        case 'f':
            array_type = GL_FLOAT;
            break;

#if defined(SIP_FEATURE_PyQt_Desktop_OpenGL)
        case 'd':
            array_type = GL_DOUBLE;
            break;
#endif

        default:
            PyErr_Format(PyExc_TypeError, "unsupported buffer type '%s'",
                         array->buffer.format);
            *estate = sipErrorFail;
            return 0;
        }

        if (array_type != gl_type)
        {
            PyErr_SetString(PyExc_TypeError,
                            "the buffer type is not the same as the array type");
            *estate = sipErrorFail;
            return 0;
        }

        return array->buffer.buf;
    }
#else
    PyBufferProcs *bf = Py_TYPE(values)->tp_as_buffer;

    if (bf && bf->bf_getreadbuffer && bf->bf_getsegcount)
    {
        if (bf->bf_getsegcount(values, 0) != 1)
        {
            PyErr_SetString(PyExc_TypeError,
                            "single-segment buffer object expected");
            *estate = sipErrorFail;
            return 0;
        }

        if (bf->bf_getreadbuffer(values, 0, reinterpret_cast<void **>(&array)) < 0)
        {
            *estate = sipErrorFail;
            return 0;
        }

        Py_INCREF(values);
        array->buffer = values;

        return array;
    }
#endif

    PyObject *seq = PySequence_Fast(values,
                                    "array must be a sequence or a buffer");

    if (!seq)
    {
        *estate = sipErrorContinue;
        return 0;
    }

    SIP_SSIZE_T nr_items = PySequence_Fast_GET_SIZE(seq);

    if (nr_items < 1)
    {
        Py_DECREF(seq);

        PyErr_SetString(PyExc_TypeError,
                        "array must have at least one element");
        *estate = sipErrorFail;
        return 0;
    }

    void (*convertor)(PyObject *, void *, SIP_SSIZE_T);
    size_t element_size;

    switch (gl_type)
    {
    case GL_BYTE:
        convertor = convert_byte;
        element_size = sizeof (GLbyte);
        break;

    case GL_UNSIGNED_BYTE:
        convertor = convert_ubyte;
        element_size = sizeof (GLubyte);
        break;

    case GL_SHORT:
        convertor = convert_short;
        element_size = sizeof (GLshort);
        break;

    case GL_UNSIGNED_SHORT:
        convertor = convert_ushort;
        element_size = sizeof (GLushort);
        break;

    case GL_INT:
        convertor = convert_int;
        element_size = sizeof (GLint);
        break;

    case GL_UNSIGNED_INT:
        convertor = convert_uint;
        element_size = sizeof (GLuint);
        break;

    case GL_FLOAT:
        convertor = convert_float;
        element_size = sizeof (GLfloat);
        break;

#if defined(SIP_FEATURE_PyQt_Desktop_OpenGL)
#if GL_DOUBLE != GL_FLOAT
    case GL_DOUBLE:
        convertor = convert_double;
        element_size = sizeof (GLdouble);
        break;
#endif
#endif

    default:
        Py_DECREF(seq);

        PyErr_SetString(PyExc_TypeError, "unsupported GL element type");
        *estate = sipErrorFail;
        return 0;
    }

    void *data = sipMalloc(nr_items * element_size);

    if (!data)
    {
        Py_DECREF(seq);

        *estate = sipErrorFail;
        return 0;
    }

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

        convertor(PySequence_Fast_GET_ITEM(seq, i), data, i);

        if (PyErr_Occurred())
        {
            sipFree(data);
            Py_DECREF(seq);

            *estate = sipErrorFail;
            return 0;
        }
    }

    Py_DECREF(seq);

    array->data = data;

    return data;
}
/*  python interface */
static PyObject* kernel_matrix(PyObject* self, PyObject* args){

  /* input variables */
  PyArrayObject *in_array;
  NpyIter *in_iter;
  NpyIter_IterNextFunc *in_iternext;
  PyObject *klargs;
  PyObject *seq;
  PyObject *item;
  double *data;
  char *kernel = (char*) malloc(20);
  double *kerargs;
  int rows, columns, len;

  /* python output variables */
  PyObject *np_matrix;
  double *matrix;
  double *xi, *xj;
  int vec_dim[1];
  int mat_dim[2];
  int i, j, itr = 0;

  /*  parse numpy array and two integers as argument */
  if (!PyArg_ParseTuple(args, "O!iis|O", 
                        &PyArray_Type, &in_array, // O!, NpArray
                        &rows,                    // i
                        &columns,                 // i
                        &kernel,                  // s, kernel
     /* kernel args */  &klargs)) return NULL;

  /***********************
  * Construct input data *
  ***********************/
  data = (double*) malloc(rows * columns * sizeof(double));
  /*  create the iterators, necessary to access numpy array */
  in_iter = NpyIter_New(in_array, NPY_ITER_READONLY, 
                        NPY_KEEPORDER, NPY_NO_CASTING, NULL);
  /* check input status */
  if (in_iter == NULL)
      goto fail;
  in_iternext = NpyIter_GetIterNext(in_iter, NULL);
  if (in_iternext == NULL) {
      NpyIter_Deallocate(in_iter);
      goto fail;
  }
  /* interator pointer to actual numpy data */
  double **in_dataptr = (double **) 
                           NpyIter_GetDataPtrArray(in_iter);
  /*  iterate over the arrays */
  do {
      data[itr++] = **in_dataptr;
  } while(in_iternext(in_iter));

  /* access python list data */
  seq = PySequence_Fast(klargs, "expected a sequence");
  len = PySequence_Size(klargs);
  kerargs = (double*) malloc(len * sizeof(double));
  for(i=0;i<len;i++){
    item = PySequence_Fast_GET_ITEM(seq, i);
    kerargs[i] = PyFloat_AsDouble(item);
  }
  Py_DECREF(seq);
  /***** end of input data construction *****/

  /**************************
  * construct output matrix *
  **************************/
  matrix = (double *) malloc(rows * rows * sizeof(double));
  mat_dim[0] = rows;
  mat_dim[1] = rows;
  vec_dim[0] = columns;

#pragma omp parallel private(i,j,xi,xj) shared(matrix)
{
  #pragma omp for
  for(i=0;i<rows;i++){
    for(j=i;j<rows;j++){
      xi = (double*) malloc(columns * sizeof(double));
      xj = (double*) malloc(columns * sizeof(double));
      /* construct callback input numpy arrays*/
      getVector(xi, data, i, columns);
      getVector(xj, data, j, columns);
      matrix[j+rows*i] = kerEval(kernel,kerargs,xi,xj,columns);
      if(i!=j) matrix[i+rows*j] = matrix[j+rows*i];
      free(xi);
      free(xj);
    }
  }
}
  np_matrix = PyArray_SimpleNewFromData(2, mat_dim, 
                                        NPY_DOUBLE, matrix);
  /***** end of output matrix construction *****/

  /*********************************
  * clean up and return the result *
  *********************************/
  Py_INCREF(np_matrix);
  return np_matrix;
  NpyIter_Deallocate(in_iter);

  /*  in case bad things happen */
  fail:
      Py_XDECREF(np_matrix);
      return NULL;

  free(data);
  free(matrix);
}
static PyObject* _adjust_players(PyObject* self, PyObject* args) {
	PyObject* list_obj;
	PyObject* seq;
	int size, i = 0;

	// get the list from the arguments
	// note: "O" flag means it's a python object
	if (!PyArg_ParseTuple(args, "O", &list_obj)) {
		return NULL;
	}

	// verify that it's actually a list
	seq = PySequence_Fast(list_obj, "expected a list");
	if (!seq) {
		return NULL;
	}

	// get the list size
	size = PySequence_Size(seq);
	if (size < 0) {
		return NULL;
	}

	// create a vector of players to hold our soon-to-be-created player objects
	std::vector<Player*> players;
	PyObject* py_tuple;
	for (i = 0; i < size; ++i) {
		// create a new player object
		Player* p = new Player();

		// get the current item from the list, which happens to be a tuple (mu, sigma, rank)
		py_tuple = PySequence_Fast_GET_ITEM(seq, i);


		// convert the tuple items into their c types
		p->mu = PyFloat_AsDouble(PyTuple_GetItem(py_tuple, 0));
		p->sigma = PyFloat_AsDouble(PyTuple_GetItem(py_tuple, 1));
		p->rank = (int)PyInt_AsLong(PyTuple_GetItem(py_tuple, 2));

		// add the player to the players vector
		players.push_back(p);
	}

	// run trueskill on the players
	TrueSkill ts;
	ts.adjust_players(players);

	// create the result list
	PyObject* result = PyList_New(size);
	for (i = 0; i < size; ++i) {
		// create a tuple and set it's values for the player
		PyObject* py_tuple;

		py_tuple = PyTuple_New(3);
		PyTuple_SetItem(py_tuple, 0, PyFloat_FromDouble(players[i]->mu));
		PyTuple_SetItem(py_tuple, 1, PyFloat_FromDouble(players[i]->sigma));
		PyTuple_SetItem(py_tuple, 2, PyInt_FromLong((long)players[i]->rank));

		// push the tuple onto the list
		PyList_SetItem(result, i, py_tuple);
	}

	// return the list
	return result;
}
Exemple #8
0
static EnumPropertyItem *enum_items_from_py(PyObject *seq_fast, PyObject *def, int *defvalue, const short is_enum_flag)
{
	EnumPropertyItem *items= NULL;
	PyObject *item;
	int seq_len, i, totitem= 0;
	short def_used= 0;
	const char *def_cmp= NULL;

	seq_len= PySequence_Fast_GET_SIZE(seq_fast);

	if(is_enum_flag) {
		if(seq_len > RNA_ENUM_BITFLAG_SIZE) {
			PyErr_SetString(PyExc_TypeError, "EnumProperty(...): maximum " STRINGIFY(RNA_ENUM_BITFLAG_SIZE) " members for a ENUM_FLAG type property");
			return NULL;
		}
		if(def && !PySet_Check(def)) {
			PyErr_Format(PyExc_TypeError, "EnumProperty(...): default option must be a 'set' type when ENUM_FLAG is enabled, not a '%.200s'", Py_TYPE(def)->tp_name);
			return NULL;
		}
	}
	else {
		if(def) {
			def_cmp= _PyUnicode_AsString(def);
			if(def_cmp==NULL) {
				PyErr_Format(PyExc_TypeError, "EnumProperty(...): default option must be a 'str' type when ENUM_FLAG is disabled, not a '%.200s'", Py_TYPE(def)->tp_name);
				return NULL;
			}
		}
	}

	/* blank value */
	*defvalue= 0;

	for(i=0; i<seq_len; i++) {
		EnumPropertyItem tmp= {0, "", 0, "", ""};

		item= PySequence_Fast_GET_ITEM(seq_fast, i);
		if(PyTuple_Check(item)==0) {
			PyErr_SetString(PyExc_TypeError, "EnumProperty(...): expected a sequence of tuples for the enum items");
			if(items) MEM_freeN(items);
			return NULL;
		}

		if(!PyArg_ParseTuple(item, "sss", &tmp.identifier, &tmp.name, &tmp.description)) {
			PyErr_SetString(PyExc_TypeError, "EnumProperty(...): expected an identifier, name and description in the tuple");
			return NULL;
		}

		if(is_enum_flag) {
			tmp.value= 1<<i;

			if(def && PySet_Contains(def, PyTuple_GET_ITEM(item, 0))) {
				*defvalue |= tmp.value;
				def_used++;
			}
		}
		else {
			tmp.value= i;

			if(def && def_used == 0 && strcmp(def_cmp, tmp.identifier)==0) {
				*defvalue= tmp.value;
				def_used++; /* only ever 1 */
			}
		}

		RNA_enum_item_add(&items, &totitem, &tmp);
	}

	RNA_enum_item_end(&items, &totitem);

	if(is_enum_flag) {
		/* strict check that all set members were used */
		if(def && def_used != PySet_GET_SIZE(def)) {
			MEM_freeN(items);

			PyErr_Format(PyExc_TypeError, "EnumProperty(..., default={...}): set has %d unused member(s)", PySet_GET_SIZE(def) - def_used);
			return NULL;
		}
	}
	else {
		if(def && def_used == 0) {
			MEM_freeN(items);

			PyErr_Format(PyExc_TypeError, "EnumProperty(..., default=\'%s\'): not found in enum members", def);
			return NULL;
		}
	}

	return items;
}
Exemple #9
0
PyObject* xcsoar_encode(PyObject *self, PyObject *args, PyObject *kwargs) {
  PyObject *py_list,
           *py_method = nullptr;
  double floor_to = 1;
  bool delta = true;

  static char *kwlist[] = {"list", "delta", "floor", "method", nullptr};

  if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O|idO", kwlist,
                                   &py_list, &delta, &floor_to, &py_method)) {
    PyErr_SetString(PyExc_AttributeError, "Can't parse argument list.");
    return nullptr;
  }

  if (!PySequence_Check(py_list)) {
    PyErr_SetString(PyExc_TypeError, "Expected a list.");
    return nullptr;
  }

  Py_ssize_t num_items = PySequence_Fast_GET_SIZE(py_list);

  // return empty string if list has no elements
  if (num_items == 0)
    return PyString_FromString("");

  unsigned dimension;
  if (PySequence_Check(PySequence_Fast_GET_ITEM(py_list, 0))) {
    dimension = PySequence_Size(PySequence_Fast_GET_ITEM(py_list, 0));
  } else {
    dimension = 1;
  }

  enum Method { UNSIGNED, SIGNED, DOUBLE } method;

  if (py_method == nullptr)
    method = UNSIGNED;
  else if (PyString_Check(py_method) && strcmp(PyString_AsString(py_method), "unsigned") == 0)
    method = UNSIGNED;
  else if (PyString_Check(py_method) && strcmp(PyString_AsString(py_method), "signed") == 0)
    method = SIGNED;
  else if (PyString_Check(py_method) && strcmp(PyString_AsString(py_method), "double") == 0)
    method = DOUBLE;
  else {
    PyErr_SetString(PyExc_TypeError, "Can't parse method.");
    return nullptr;
  }

  GoogleEncode encoded(dimension, delta, floor_to);

  for (Py_ssize_t i = 0; i < num_items; ++i) {
    PyObject *py_item = PySequence_Fast_GET_ITEM(py_list, i);

    if (dimension > 1) {
      for (unsigned j = 0; j < dimension; ++j) {

        if (method == UNSIGNED) {
          if (!PyNumber_Check(PySequence_Fast_GET_ITEM(py_item, j))) {
            PyErr_SetString(PyExc_TypeError, "Expected numeric value.");
            return nullptr;
          }
          encoded.addUnsignedNumber(PyInt_AsLong(PySequence_Fast_GET_ITEM(py_item, j)));
        } else if (method == SIGNED) {
          if (!PyNumber_Check(PySequence_Fast_GET_ITEM(py_item, j))) {
            PyErr_SetString(PyExc_TypeError, "Expected numeric value.");
            return nullptr;
          }
          encoded.addSignedNumber(PyInt_AsLong(PySequence_Fast_GET_ITEM(py_item, j)));
        } else if (method == DOUBLE) {
          if (!PyNumber_Check(PySequence_Fast_GET_ITEM(py_item, j))) {
            PyErr_SetString(PyExc_TypeError, "Expected numeric value.");
            return nullptr;
          }
          encoded.addDouble(PyFloat_AsDouble(PySequence_Fast_GET_ITEM(py_item, j)));
        }

      }
    } else {

      if (method == UNSIGNED) {
        if (!PyNumber_Check(py_item)) {
          PyErr_SetString(PyExc_TypeError, "Expected numeric value.");
          return nullptr;
        }
        encoded.addUnsignedNumber(PyInt_AsLong(py_item));
      } else if (method == SIGNED) {
        if (!PyNumber_Check(py_item)) {
          PyErr_SetString(PyExc_TypeError, "Expected numeric value.");
          return nullptr;
        }
        encoded.addSignedNumber(PyInt_AsLong(py_item));
      } else if (method == DOUBLE) {
        if (!PyNumber_Check(py_item)) {
          PyErr_SetString(PyExc_TypeError, "Expected numeric value.");
          return nullptr;
        }
        encoded.addDouble(PyFloat_AsDouble(py_item));
      }

    }
  }

  // prepare output
  PyObject *py_result = PyString_FromString(encoded.asString()->c_str());

  return py_result;
}
Exemple #10
0
static struct JsonlangJsonValue *python_to_jsonlang_json(struct JsonlangVm *vm, PyObject *v,
                                                       const char **err_msg)
{
    if (PyString_Check(v)) {
        return jsonlang_json_make_string(vm, PyString_AsString(v));
    } else if (PyUnicode_Check(v)) {
        struct JsonlangJsonValue *r;
        PyObject *str = PyUnicode_AsUTF8String(v);
        r = jsonlang_json_make_string(vm, PyString_AsString(str));
        Py_DECREF(str);
        return r;
    } else if (PyFloat_Check(v)) {
        return jsonlang_json_make_number(vm, PyFloat_AsDouble(v));
    } else if (PyInt_Check(v)) {
        return jsonlang_json_make_number(vm, (double)(PyInt_AsLong(v)));
    } else if (PyBool_Check(v)) {
        return jsonlang_json_make_bool(vm, PyObject_IsTrue(v));
    } else if (v == Py_None) {
        return jsonlang_json_make_null(vm);
    } else if (PySequence_Check(v)) {
        Py_ssize_t len, i;
        struct JsonlangJsonValue *arr;
        // Convert it to a O(1) indexable form if necessary.
        PyObject *fast = PySequence_Fast(v, "python_to_jsonlang_json internal error: not sequence");
        len = PySequence_Fast_GET_SIZE(fast);
        arr = jsonlang_json_make_array(vm);
        for (i = 0; i < len; ++i) {
            struct JsonlangJsonValue *json_el;
            PyObject *el = PySequence_Fast_GET_ITEM(fast, i);
            json_el = python_to_jsonlang_json(vm, el, err_msg);
            if (json_el == NULL) {
                Py_DECREF(fast);
                jsonlang_json_destroy(vm, arr);
                return NULL;
            }
            jsonlang_json_array_append(vm, arr, json_el);
        }
        Py_DECREF(fast);
        return arr;
    } else if (PyDict_Check(v)) {
        struct JsonlangJsonValue *obj;
        PyObject *key, *val;
        Py_ssize_t pos = 0;
        obj = jsonlang_json_make_object(vm);
        while (PyDict_Next(v, &pos, &key, &val)) {
            struct JsonlangJsonValue *json_val;
            const char *key_ = PyString_AsString(key);
            if (key_ == NULL) {
                *err_msg = "Non-string key in dict returned from Python Jsonlang native extension.";
                jsonlang_json_destroy(vm, obj);
                return NULL;
            }
            json_val = python_to_jsonlang_json(vm, val, err_msg);
            if (json_val == NULL) {
                jsonlang_json_destroy(vm, obj);
                return NULL;
            }
            jsonlang_json_object_append(vm, obj, key_, json_val);
        }
        return obj;
    } else {
        *err_msg = "Unrecognized type return from Python Jsonlang native extension.";
        return NULL;
    }
}
static PyObject* graph_embeds(PyObject* self, PyObject* args)
{

    // Making Graphs
    vertex u, v;
    unsigned temp;
    graph (g);
    int gem, countVerteicesProcessed = 0;
    // vertex i, j, u, v; unsigned temp;
    // Finish making graphs
    PyObject* obj;
    PyObject* seq;
    int i, len;
    PyObject* item;
    long arrayValue;
    int embedsBoolean;

    int numberOfVertices = 0;

    if (!PyArg_ParseTuple(args, "O", &obj)) {
        printf("Item is not a list\n");
        // return NULL;
        Py_RETURN_NONE;
    }
    seq = PySequence_Fast(obj, "expected a sequence");
    len = PySequence_Size(obj);
    arrayValue = -5;
    // printf("[\n");
    for (i = 0; i < len; i++) {
        item = PySequence_Fast_GET_ITEM(seq, i);



        if(i == 0) {
            // should add a check to make sure it is an integer!
            numberOfVertices = PyInt_AsLong(item);
            // printf("numberOfVertices: %d\n", numberOfVertices);
            // graph creation
            if ((**g = (char) numberOfVertices) > maxverts - 2) Py_RETURN_NONE;
            // if ((**g = (char) numberOfVertices) > maxverts - 2) return 2;
            // end graph creation
        } else if(i <= numberOfVertices && i > 0) {
            // should add a check to make sure it is a list!
            countVerteicesProcessed++;
            PyObject* obj_adjacency = item;
            PyObject* seq_adjacency;
            int j = 0, len_adjacency;
            PyObject* item_adjacency;
            seq_adjacency = PySequence_Fast(obj_adjacency, "expected a sequence");
            len_adjacency = PySequence_Size(obj_adjacency);

            // make sure object is a sequence and put the for loop inside the conditional
            item_adjacency = PySequence_Fast_GET_ITEM(seq_adjacency, j);
            int degreeOfVertex = PyInt_AsLong(item_adjacency);
            if(degreeOfVertex != len_adjacency - 1) {
                printf("degreeOfVertex %d and length %d not matching!\n", degreeOfVertex, len_adjacency);
            }
            int adjacent[degreeOfVertex];
            // graph creation
            if ((degree (g, i) = (char) degreeOfVertex) > maxdeg - 2) Py_RETURN_NONE;
            // if ((degree (g, i) = (char) degreeOfVertex) > maxdeg - 2) return 4;
            // end graph creation
            for (j = 1; j < len_adjacency; j++) {
                item_adjacency = PySequence_Fast_GET_ITEM(seq_adjacency, j);

                // delete this code!
                PyObject* objectsRepresentation = PyObject_Repr(item);
                const char* s = PyString_AsString(objectsRepresentation);
                // printf("%s\n", s);
                PyObject* objType = PyObject_Type(item);
                PyObject* objTypeString = PyObject_Repr(objType);
                const char* sType = PyString_AsString(objTypeString);
                // printf("%s\n", sType);
                // end delete


                // make sure every object is an int!
                adjacent[j-1] = PyInt_AsLong(item_adjacency);
                // printf("%da\n", adjacent[j-1]);
                // make sure first int is the degree and is the same as the length -1 of the array

                // graph creation
                g [i][j] = (char) PyInt_AsLong(item_adjacency);
                // end graph creation
            }

        } else {
            printf("There is something that should not be here!\n");
            PyObject* objectsRepresentation = PyObject_Repr(item);
            const char* s = PyString_AsString(objectsRepresentation);
            printf("%s\n", s);
            PyObject* objType = PyObject_Type(item);
            PyObject* objTypeString = PyObject_Repr(objType);
            const char* sType = PyString_AsString(objTypeString);
            printf("%s\n", sType);
        }


    }

    if(countVerteicesProcessed < numberOfVertices) Py_RETURN_NONE;

    vertex j;
    // vertex i, j, u, v; unsigned temp;
    for (i = 1; i <= **g; i++) for (j = 1; j <= degree(g, i); j++) {
            // if (g [i][j] > **g) return 6; //this checks that the label of each vertex in the respective adjacency lists
            if (g [i][j] > **g) Py_RETURN_NONE;
            // do not exceed the number of vertices in the graph as listed in the file.
            for (u = g [i][j], v = 1; (v <= degree(g, u)) && (g[u][v] != i); v ++); //this loops through all the vertices
            // adjacent to u and stops whenever it finds the vertex i, or it finishes the list
            // if (v > degree(g, u)) return 7; // if v is greater than the degree, it means vertex i was not found in the
            if (v > degree(g, u)) Py_RETURN_NONE;
            // adjacency list for u, meaning the graph is directed. It seems directed graphs are not acceptable!
        }



    // printf("loop is done!\n");

    char s = 'p';
    gem = gembed (g, s, 1);
    // printf("gembed is done!\n");
    /*  system ("date"); */
    switch (gem) {
    case 0:
        // printf ( "no ");
        // switch (s) {
        //     case 'p' : printf ("projective"); break;
        //     case 't' : printf ("toroidal"); break;
        //     case 's' : printf ("spindle"); break;
        //     default  : printf ("ERROR");
        //     }
        // puts (" embeddings");
        embedsBoolean = 0;
        break;
    case 2:
        // puts ( "graph is planar");
        embedsBoolean = 1;
        break;
    case 1:
    case 3:
        // puts ( "graph embeds");
        embedsBoolean = 1;
        break;
    default:
        puts ( "whoops -- unknown result from gembed()");
        Py_RETURN_NONE;
        break;
    }



    Py_DECREF(seq);
    // printf("]\n");
    // printf("Item is a list!\n");

    if(embedsBoolean) Py_RETURN_TRUE;
    else Py_RETURN_FALSE;

    Py_RETURN_NONE;
}
Exemple #12
0
PyObject *_prepareValues(t_itemvalue *self, PyObject *values)
{
    PyObject *item = PyObject_Call(self->owner, Empty_TUPLE, NULL);
    PyObject *result;
    int i, size;

    if (!item)
        return NULL;

    if (!PySequence_Check(values))
    {
        PyObject *args = PyTuple_Pack(1, values);

        values = PyObject_Call((PyObject *) &PyTuple_Type, args, NULL);
        Py_DECREF(args);
        if (!values)
        {
            Py_DECREF(item);
            return NULL;
        }
    }
    else
    {
        values = PySequence_Fast(values, "not a sequence");
        if (!values)
        {
            Py_DECREF(item);
            return NULL;
        }
    }

    size = PySequence_Fast_GET_SIZE(values);
    if (size < 0)
    {
        Py_DECREF(item);
        Py_DECREF(values);
        return NULL;
    }

    result = PyTuple_New(size);
    if (!result)
    {
        Py_DECREF(item);
        Py_DECREF(values);
        return NULL;
    }

    for (i = 0; i < size; i++) {
        PyObject *value = PySequence_Fast_GET_ITEM(values, i);
        PyObject *v;

        if (!value)
        {
            Py_DECREF(item);
            Py_DECREF(values);
            Py_DECREF(result);
            return NULL;
        }

        v = PyObject_CallMethodObjArgs((PyObject *) self, prepareValue_NAME,
                                        item, self->attribute, value,
                                        Py_False, NULL);
        if (!v)
        {
            Py_DECREF(item);
            Py_DECREF(values);
            Py_DECREF(result);
            return NULL;
        }

        PyTuple_SET_ITEM(result, i, v);
    }
    Py_DECREF(item);
    Py_DECREF(values);

    return result;
}
Exemple #13
0
static PyObject* resonate(PyObject *self, PyObject *args, PyObject *keywds)
{
    static char *kwlist[] = {"signal", "sr", "freqs", "damping",
                             "rms_window", "return_response", NULL};
    PyObject *pysignal;
    int sr;
    PyObject *pyfreqs;
    double damping;
    int rms_window;
    int return_response;
    int siglen;
    int nfreqs;
    double w;
    double *x, *x1, *x2;
    double *a1, *a2, *b1;
    PyObject *signal;
    PyObject **response;
    PyObject *response_list;
    double *rms_moving;
    PyObject **rms;
    PyObject *rms_list;
    PyObject *out;
    double rms_val;
    PyObject *item;
    double freq;
    long freq_long;
    double sample;
    int i, t;

    if(!PyArg_ParseTupleAndKeywords(args, keywds, "OiOdi|i", kwlist,
                                    &pysignal, &sr, &pyfreqs, &damping,
                                    &rms_window, &return_response)) {
        return NULL;
    }

    if(!PySequence_Check(pyfreqs)) {
        PyErr_SetString(PyExc_TypeError, "freqs: expected sequence of numbers");
        return NULL;
    }

    nfreqs = PySequence_Size(pyfreqs);
    signal = PySequence_Fast(pysignal, "signal: expected sequence of floats");
    siglen = PySequence_Size(signal);

    x = alloca(nfreqs * sizeof(double));
    x1 = alloca(nfreqs * sizeof(double));
    x2 = alloca(nfreqs * sizeof(double));
    a1 = alloca(nfreqs * sizeof(double));
    a2 = alloca(nfreqs * sizeof(double));
    b1 = alloca(nfreqs * sizeof(double));
    rms_moving = alloca(nfreqs * sizeof(double));
    rms = alloca(nfreqs * sizeof(PyObject *));

    if(return_response)
        response = alloca(nfreqs * sizeof(PyObject *));

    for(i = 0; i < nfreqs; i ++) {
        item = PySequence_GetItem(pyfreqs, i);
        if(PyInt_Check(item)) {
            freq_long = PyInt_AsLong(item);
            freq = (double)freq_long;
        }
        else if(PyLong_Check(item)) {
            freq = PyLong_AsDouble(item);
        }
        else if(PyFloat_Check(item)) {
            freq = PyFloat_AsDouble(item);
        }
        else {
            Py_DECREF(item);
            PyErr_SetString(PyExc_TypeError, "freqs: expected sequence of numbers");
            return NULL;
        }

        w = (2 * M_PI * freq) / sr;

        a1[i] = (pow(w, 2) - 2) / (1 + damping);
        a2[i] = (1 - damping) / (1 + damping);
        b1[i] = 1 / (1 + damping);

        x[i] = 0;
        x1[i] = 0;
        x2[i] = 0;

        rms_moving[i] = 0;
        rms[i] = PyList_New(siglen / rms_window);

        if(return_response)
            response[i] = PyList_New(siglen);
    }

    for(t = 0; t < siglen; t ++) {
        item = PySequence_Fast_GET_ITEM(signal, t);
        sample = PyFloat_AsDouble(item);

        for(i = 0; i < nfreqs; i ++) {
            x[i] = b1[i] * sample - a1[i] * x1[i] - a2[i] * x2[i];
            rms_moving[i] += pow(x[i], 2);

            if(return_response) {
                item = PyFloat_FromDouble(x[i]);
                PyList_SET_ITEM(response[i], t, item);
            }
        }

        memcpy(x2, x1, nfreqs * sizeof(double));
        memcpy(x1, x, nfreqs * sizeof(double));

        if((t + 1) % rms_window == 0) {
            for(i = 0; i < nfreqs; i ++) {
                rms_val = sqrt(rms_moving[i] / (double)rms_window);
                rms_moving[i] = 0;
                item = PyFloat_FromDouble(rms_val);
                PyList_SET_ITEM(rms[i], t / rms_window, item);
            }
        }
    }
    Py_DECREF(signal);

    rms_list = PyList_New(nfreqs);
    if(return_response)
        response_list = PyList_New(nfreqs);

    for(i = 0; i < nfreqs; i ++) {
        PyList_SET_ITEM(rms_list, i, rms[i]);
        if(return_response)
            PyList_SET_ITEM(response_list, i, response[i]);
    }

    if(return_response)
        return Py_BuildValue("(O,O)", rms_list, response_list);
    else
        return Py_BuildValue("O", rms_list);
}
static PyObject *
pygpgme_context_encrypt_sign(PyGpgmeContext *self, PyObject *args)
{
    PyObject *py_recp, *py_plain, *py_cipher, *recp_seq = NULL, *result = NULL;
    int flags, i, length;
    gpgme_key_t *recp = NULL;
    gpgme_data_t plain = NULL, cipher = NULL;
    gpgme_error_t err;
    gpgme_sign_result_t sign_result;

    if (!PyArg_ParseTuple(args, "OiOO", &py_recp, &flags,
                          &py_plain, &py_cipher))
        goto end;

    recp_seq = PySequence_Fast(py_recp, "first argument must be a sequence");
    if (recp_seq == NULL)
        goto end;

    length = PySequence_Fast_GET_SIZE(recp_seq);
    recp = malloc((length + 1) * sizeof (gpgme_key_t));
    for (i = 0; i < length; i++) {
        PyObject *item = PySequence_Fast_GET_ITEM(recp_seq, i);

        if (!PyObject_TypeCheck(item, &PyGpgmeKey_Type)) {
            PyErr_SetString(PyExc_TypeError, "items in first argument "
                            "must be gpgme.Key objects");
            goto end;
        }
        recp[i] = ((PyGpgmeKey *)item)->key;
    }
    recp[i] = NULL;

    if (pygpgme_data_new(&plain, py_plain))
        goto end;
    if (pygpgme_data_new(&cipher, py_cipher))
        goto end;

    Py_BEGIN_ALLOW_THREADS;
    err = gpgme_op_encrypt_sign(self->ctx, recp, flags, plain, cipher);
    Py_END_ALLOW_THREADS;

    sign_result = gpgme_op_sign_result(self->ctx);

    /* annotate exception */
    if (pygpgme_check_error(err)) {
        PyObject *err_type, *err_value, *err_traceback;
        PyObject *list;
        gpgme_invalid_key_t key;

        decode_encrypt_result(self);

        PyErr_Fetch(&err_type, &err_value, &err_traceback);
        PyErr_NormalizeException(&err_type, &err_value, &err_traceback);

        if (sign_result == NULL)
            goto error_end;

        if (!PyErr_GivenExceptionMatches(err_type, pygpgme_error))
            goto error_end;

        list = PyList_New(0);
        for (key = sign_result->invalid_signers; key != NULL; key = key->next) {
            PyObject *item, *py_fpr, *err;

            if (key->fpr)
                py_fpr = PyUnicode_DecodeASCII(key->fpr, strlen(key->fpr),
                                               "replace");
            else {
                py_fpr = Py_None;
                Py_INCREF(py_fpr);
            }
            err = pygpgme_error_object(key->reason);
            item = Py_BuildValue("(NN)", py_fpr, err);
            PyList_Append(list, item);
            Py_DECREF(item);
        }
        PyObject_SetAttrString(err_value, "invalid_signers", list);
        Py_DECREF(list);

        list = pygpgme_newsiglist_new(sign_result->signatures);
        PyObject_SetAttrString(err_value, "signatures", list);
        Py_DECREF(list);
    error_end:
        PyErr_Restore(err_type, err_value, err_traceback);
        goto end;
    }

    if (sign_result)
        result = pygpgme_newsiglist_new(sign_result->signatures);
    else
        result = PyList_New(0);

 end:
    if (recp != NULL)
        free(recp);
    Py_XDECREF(recp_seq);
    if (plain != NULL)
        gpgme_data_release(plain);
    if (cipher != NULL)
        gpgme_data_release(cipher);

    return result;
}
SVECTOR     *psi(PATTERN x, LABEL y, STRUCTMODEL *sm,
		 STRUCT_LEARN_PARM *sparm)
{
  /* Returns a feature vector describing the match between pattern x
     and label y. The feature vector is returned as a list of
     SVECTOR's. Each SVECTOR is in a sparse representation of pairs
     <featurenumber:featurevalue>, where the last pair has
     featurenumber 0 as a terminator. Featurenumbers start with 1 and
     end with sizePsi. Featuresnumbers that are not specified default
     to value 0. As mentioned before, psi() actually returns a list of
     SVECTOR's. Each SVECTOR has a field 'factor' and 'next'. 'next'
     specifies the next element in the list, terminated by a NULL
     pointer. The list can be though of as a linear combination of
     vectors, where each vector is weighted by its 'factor'. This
     linear combination of feature vectors is multiplied with the
     learned (kernelized) weight vector to score label y for pattern
     x. Without kernels, there will be one weight in sm.w for each
     feature. Note that psi has to match
     find_most_violated_constraint_???(x, y, sm) and vice versa. In
     particular, find_most_violated_constraint_???(x, y, sm) finds
     that ybar!=y that maximizes psi(x,ybar,sm)*sm.w (where * is the
     inner vector product) and the appropriate function of the loss +
     margin/slack rescaling method. See that paper for details. */
  SVECTOR *fvec=NULL;

  /* insert code for computing the feature vector for x and y here */
  PyObject *pFunc, *pValue;

  // Call the relevant Python function.
  pFunc = getFunction(PYTHON_PSI);
  pValue = PyObject_CallFunction
  (pFunc, "OONN", (PyObject*)x.py_x, (PyObject*)y.py_y,
   StructModel_FromStructModel(sm), Sparm_FromSparm(sparm));
  PY_RUNCHECK;
  // Interpret the return value.
  if (Sparse_Check(pValue)) {
    fvec = psi_helper(pValue);
    Py_DECREF(pValue);
  } else {
    // Attempt to treat this like some sort of sequence.
    PyObject *pFast = PySequence_Fast(pValue, "return value not sequence");
    if (pFast==NULL) {
      fprintf(stderr, "%s did not return %s object or sequence\n", PYTHON_PSI,
	      svms_SparseType.tp_name);
      Py_Exit(1);
    }
    int i,size = PySequence_Fast_GET_SIZE(pFast);
    for (i=size-1; i>=0; --i) {
      SVECTOR *fvec_new = psi_helper(PySequence_Fast_GET_ITEM(pFast, i));
      if (fvec_new == NULL) {
	// Hmmm, error creating it.  Dispose of what we have created so far.
	if (fvec) {
	  free_svector(fvec);
	  fvec = NULL;
	}
	break;
      } else {
	// Prepend this vector to the list.
	fvec_new->next = fvec;
	fvec = fvec_new;
      }
    }
    Py_DECREF(pFast);
  }

  if (fvec == NULL) {
    Py_Exit(1);
  }

  return(fvec);
}
Exemple #16
0
int ObjectRow_PyObject__init(ObjectRow_PyObject *self, PyObject *args, PyObject *kwargs)
{
    PyObject *pytmp, *pydesc, *cursor, *row, *o_type, *pickle_dict = 0;
    struct module_state *mstate;
    if (!PyArg_ParseTuple(args, "OO|O!", &cursor, &row, &PyDict_Type, &pickle_dict))
        return -1;

    mstate = GETSTATE_FROMTYPE(self);
    if (pickle_dict) {
        /* If row or cursor weren't specified, then we require the third arg
         * (pickle_dict) be a dictionary, and we basically behave as this dict.
         * We do this for example from Database.add()
         */
        self->pickle = pickle_dict;
        Py_INCREF(self->pickle);
        self->row = Py_None;
        Py_INCREF(self->row);
        self->desc = Py_None;
        Py_INCREF(self->desc);
        return 0;
    }

    /* First argument is the db cursor from which we fetch the row description
     * and object types.  Or, it is a 2-tuple of same.
     */
    if (PyTuple_Check(cursor)) {
        self->desc = PySequence_GetItem(cursor, 0); // new ref
        self->object_types = PySequence_GetItem(cursor, 1); // new ref
    } else if (!PyObject_HasAttrString(cursor, "_db")) {
        PyErr_Format(PyExc_ValueError, "First argument is not a Cursor or tuple object");
        return -1;
    } else {
        PyObject *weak_db = PyObject_GetAttrString(cursor, "_db"); // new ref
        PyObject *db = PyWeakref_GetObject(weak_db); // borrowed ref
        self->object_types = PyObject_GetAttrString(db, "_object_types"); // new ref
        self->desc = PyObject_GetAttrString(cursor, "description"); // new ref
        Py_XDECREF(weak_db);
    }

    self->row = row;

    self->type_name = PySequence_GetItem(row, 0); // new ref
    if (!PyString_Check(self->type_name) && !PyUnicode_Check(self->type_name)) {
        Py_XDECREF(self->desc);
        Py_XDECREF(self->object_types);
        PyErr_Format(PyExc_ValueError, "First element of row must be object type");
        return -1;
    }

    o_type = PyDict_GetItem(self->object_types, self->type_name); // borrowed ref
    self->attrs = PySequence_GetItem(o_type, 1); // new ref
    if (!self->attrs) {
        char *type_name;
#if PY_MAJOR_VERSION >= 3
        PyObject *bytes = PyUnicode_AsUTF8String(self->type_name);
        type_name = strdup(PyBytes_AS_STRING(bytes));
        Py_DECREF(bytes);
#else
        type_name = strdup(PyString_AsString(self->type_name));
#endif
        PyErr_Format(PyExc_ValueError, "Object type '%s' not defined.", type_name);
        free(type_name);
        Py_XDECREF(self->desc);
        Py_XDECREF(self->object_types);
        return -1;
    }

    /* For the queries dict key we use the address of the desc object rather
     * than the desc itself.  desc is a tuple, and if we use it as a key it
     * will result in a hash() on the desc for each row which is much more
     * expensive.  pysqlite passes us the same description tuple object for
     * each row in a query so it is safe to use the address.
     */
    pydesc = PyLong_FromVoidPtr(self->desc);
    pytmp = PyDict_GetItem(mstate->queries, pydesc);
    self->query_info = pytmp ? (QueryInfo *)PyCObject_AsVoidPtr(pytmp) : NULL;
    if (!self->query_info) {
        /* This is a row for a query we haven't seen before, so we need to do
         * some initial setup.  Most of what we do here is convert row and
         * attribute metadata into convenient data structures for later access.
         */

        PyObject **desc_tuple = PySequence_Fast_ITEMS(self->desc);
        PyObject *key, *value;
        int i = 0;
        Py_ssize_t pos = 0;

        self->query_info = (QueryInfo *)malloc(sizeof(QueryInfo));
        self->query_info->refcount = 0;
        self->query_info->pickle_idx = -1;
        self->query_info->idxmap = PyDict_New();

        /* Iterate over the columns from the SQL query and keep track of
         * attribute names and their indexes within the row tuple.  Start at
         * index 2 because index 0 and 1 are internal (the object type name
         * literal and type id).
         */
        for (i = 2; i < PySequence_Length(self->desc); i++) {
            PyObject **desc_col = PySequence_Fast_ITEMS(desc_tuple[i]);
            ObjectAttribute *attr = (ObjectAttribute *)malloc(sizeof(ObjectAttribute));

            attr->pickled = 0;
            attr->index = i;
            if (PyStr_Compare(desc_col[0], "pickle") == 0)
                self->query_info->pickle_idx = i;

            pytmp = PyCObject_FromVoidPtr(attr, free);
            PyDict_SetItem(self->query_info->idxmap, desc_col[0], pytmp);
            Py_DECREF(pytmp);
        }

        /* Now iterate over the kaa.db object attribute dict, storing the
         * type of each attribute, its flags, and figure out whether or not
         * we need to look in the pickle for that attribute.
         */
        while (PyDict_Next(self->attrs, &pos, &key, &value)) {
            pytmp = PyDict_GetItem(self->query_info->idxmap, key);
            ObjectAttribute *attr = pytmp ? (ObjectAttribute *)PyCObject_AsVoidPtr(pytmp) : NULL;

            if (!attr) {
                attr = (ObjectAttribute *)malloc(sizeof(ObjectAttribute));
                attr->index = -1;
                pytmp = PyCObject_FromVoidPtr(attr, free);
                PyDict_SetItem(self->query_info->idxmap, key, pytmp);
                Py_DECREF(pytmp);
            }
            attr->type = PySequence_Fast_GET_ITEM(value, 0);
            attr->flags = PyInt_AsLong(PySequence_Fast_GET_ITEM(value, 1));
            attr->named_ivtidx = PyObject_RichCompareBool(PySequence_Fast_GET_ITEM(value, 2), key, Py_EQ) == 1;
            if (IS_ATTR_INDEXED_IGNORE_CASE(attr->flags) || attr->flags & ATTR_SIMPLE)
                // attribute is set to ignore case, or it's ATTR_SIMPLE, so we
                // need to look in the pickle for this attribute.
                attr->pickled = 1;
            else
                attr->pickled = 0;
        }

        /* Create a hash table that maps object type ids to type names.
         */
        pos = 0;
        self->query_info->type_names = PyDict_New();
        while (PyDict_Next(self->object_types, &pos, &key, &value)) {
            PyObject *type_id = PySequence_Fast_GET_ITEM(value, 0);
            PyDict_SetItem(self->query_info->type_names, type_id, key);
        }
        pytmp = PyCObject_FromVoidPtr(self->query_info, NULL);
        PyDict_SetItem(mstate->queries, pydesc, pytmp);
        Py_DECREF(pytmp);
    }
    Py_DECREF(pydesc);

    self->query_info->refcount++;
    if (self->query_info->pickle_idx >= 0) {
        // Pickle column included in row.  Set _pickle member to True which
        // indicates the pickle data was fetched, but just hasn't yet been
        // unpickled.
        if (PySequence_Fast_GET_ITEM(self->row, self->query_info->pickle_idx) != Py_None)
            self->has_pickle = 1;
        self->pickle = Py_True;
    } else
        self->pickle = Py_False;

    Py_INCREF(self->pickle);
    Py_INCREF(self->row);

    if (pickle_dict && pickle_dict != Py_None) {
        Py_DECREF(self->pickle);
        self->pickle = pickle_dict;
        Py_INCREF(self->pickle);
        self->has_pickle = self->unpickled = 1;
    }
    return 0;
}
Exemple #17
0
PyObject *string_join(PyStringObject *self, PyObject *orig)
{
    char *sep = PyString_AS_STRING(self);
    const Py_ssize_t seplen = PyString_GET_SIZE(self);
    PyObject *res = NULL;
    char *p;
    Py_ssize_t seqlen = 0;
    size_t sz = 0;
    Py_ssize_t i;
    PyObject *seq, *item;

    seq = PySequence_Fast(orig, "");
    if (seq == NULL) {
        return NULL;
    }

    seqlen = PySequence_Size(seq);
    if (seqlen == 0) {
        Py_DECREF(seq);
        return PyString_FromString("");
    }
    if (seqlen == 1) {
        item = PySequence_Fast_GET_ITEM(seq, 0);
        if (PyString_CheckExact(item) || PyUnicode_CheckExact(item)) {
            Py_INCREF(item);
            Py_DECREF(seq);
            return item;
        }
    }

    /* There are at least two things to join, or else we have a subclass
     * of the builtin types in the sequence.
     * Do a pre-pass to figure out the total amount of space we'll
     * need (sz), see whether any argument is absurd, and defer to
     * the Unicode join if appropriate.
     */
    for (i = 0; i < seqlen; i++) {
        const size_t old_sz = sz;
        item = PySequence_Fast_GET_ITEM(seq, i);
        if (!PyString_Check(item)){
#ifdef Py_USING_UNICODE
            if (PyUnicode_Check(item)) {
                /* Defer to Unicode join.
                 * CAUTION:  There's no gurantee that the
                 * original sequence can be iterated over
                 * again, so we must pass seq here.
                 */
                PyObject *result;
                result = PyUnicode_Join((PyObject *)self, seq);
                Py_DECREF(seq);
                return result;
            }
#endif
            PyErr_Format(PyExc_TypeError,
                         "sequence item %zd: expected string,"
                         " %.80s found",
                         i, Py_TYPE(item)->tp_name);
            Py_DECREF(seq);
            return NULL;
        }
        sz += PyString_GET_SIZE(item);
        if (i != 0)
            sz += seplen;
        if (sz < old_sz || sz > PY_SSIZE_T_MAX) {
            PyErr_SetString(PyExc_OverflowError,
                "join() result is too long for a Python string");
            Py_DECREF(seq);
            return NULL;
        }
    }

    /* Allocate result space. */
    res = PyString_FromStringAndSize((char*)NULL, sz);
    if (res == NULL) {
        Py_DECREF(seq);
        return NULL;
    }

    /* Catenate everything. */
    p = PyString_AS_STRING(res);
    for (i = 0; i < seqlen; ++i) {
        size_t n;
        item = PySequence_Fast_GET_ITEM(seq, i);
        n = PyString_GET_SIZE(item);
        Py_MEMCPY(p, PyString_AS_STRING(item), n);
        p += n;
        if (i < seqlen - 1) {
            Py_MEMCPY(p, sep, seplen);
            p += seplen;
        }
    }

    Py_DECREF(seq);
    return res;
}
Exemple #18
0
PyObject *ObjectRow_PyObject__subscript(ObjectRow_PyObject *self, PyObject *key)
{
    ObjectAttribute *attr = 0;
    PyObject *value, *pytmp;

    if (!self->query_info) {
        // If no query_info available, then we work strictly from the pickle
        // dict, which init() requires be available.
        value = PyDict_GetItem(self->pickle, key);
        if (!value) {
            PyErr_SetObject(PyExc_KeyError, key);
            return NULL;
        }
        Py_INCREF(value);
        return value;
    }

    // String is the more common case.
    if (PyString_Check(key)) {
        // Handle some special case attribute names.
        if (PyStr_Compare(key, "type") == 0) {
            // Returns the type name of this object.
            Py_INCREF(self->type_name);
            return self->type_name;

        } else if (PyStr_Compare(key, "parent") == 0) {
            /* Returns a tuple (type_name, id) for this object's parent.  If
             * type_name can't be resolved from the parent_id, then the integer
             * value for the type is used instead.
             */

            if (!self->parent) {
                // Generate the value if it's not available.
                ObjectAttribute *type_attr, *id_attr;
                PyObject *o_type, *o_id, *type_name = 0;

                // Lookup the parent_type and parent_id indexes within the
                // sql row.
                pytmp = PyDict_GetItemString(self->query_info->idxmap, "parent_type");
                type_attr = pytmp ? (ObjectAttribute *)PyCObject_AsVoidPtr(pytmp) : NULL;

                pytmp = PyDict_GetItemString(self->query_info->idxmap, "parent_id");
                id_attr = pytmp ? (ObjectAttribute *)PyCObject_AsVoidPtr(pytmp) : NULL;
                // If neither of these values are available in the row, raise an
                // exception.
                if (!type_attr || !id_attr || type_attr->index == -1 || id_attr->index == -1) {
                    PyErr_Format(PyExc_IndexError, "Parent attribute not available.");
                    return NULL;
                }
                // They're both available, so fetch them.
                o_type = PySequence_Fast_GET_ITEM(self->row, type_attr->index);
                o_id = PySequence_Fast_GET_ITEM(self->row, id_attr->index);
                // Resolve type id to type name.
                if (PyNumber_Check(o_type))
                    type_name = PyDict_GetItem(self->query_info->type_names, o_type);
                // Construct the (name, id) tuple.
                if (type_name)
                    self->parent = Py_BuildValue("(OO)", type_name, o_id);
                else
                    self->parent = Py_BuildValue("(OO)", o_type, o_id);
            }

            Py_INCREF(self->parent);
            return self->parent;
        }
        else if (PyStr_Compare(key, "_row") == 0) {
            Py_INCREF(self->row);
            return(self->row);
        }

        pytmp = PyDict_GetItem(self->query_info->idxmap, key);
        attr = pytmp ? (ObjectAttribute *)PyCObject_AsVoidPtr(pytmp) : NULL;
    }
    // But also support referencing the sql row by index.  (Pickled attributes
    // cannot be accessed this way, though.)
    else if (PyNumber_Check(key)) {
        long index = -1;
        if (PyInt_Check(key))
            index = PyInt_AsLong(key);
        else if (PyLong_Check(key))
            index = PyLong_AsLong(key);

        if (index < 0 || index >= PySequence_Length(self->row)) {
            PyErr_Format(PyExc_IndexError, "index out of range");
            return NULL;
        }
        return PySequence_GetItem(self->row, index);
    }

    //printf("REQUEST: %s attr=%p idx=%d has_pickle=%d pickle_idx=%d\n", skey, attr, attr->index, self->has_pickle, self->query_info->pickle_idx);

    if (attr && attr->index == -1 && !self->has_pickle && self->query_info->pickle_idx != -1) {
        /* Attribute is valid and pickle column exists in sql row, but pickle
         * is None, which means this attribute was never assigned a value, so
         * return suitable default ([] for ivtidx, and None for everything
         * else)
         */
        return get_default_for_attr(attr);
    }

    /* Raise exception if attribute name isn't known, or if the requested
     * attribute, while valid for this object type, can't be obtained given the
     * query that was done.
     */
    if (!attr || (attr->index == -1 && !self->has_pickle && attr->pickled)) {
        PyErr_SetObject(PyExc_KeyError, key);
        return NULL;
    }

    if (!attr->pickled || (IS_ATTR_INDEXED_IGNORE_CASE(attr->flags) && attr->index >= 0 && !self->has_pickle))
        /* If the attribute isn't pickled, we return the value from the row
         * tuple.  Also, if the attribute is ATTR_INDEXED_IGNORE_CASE but we
         * don't have a pickle available, and that attribute exists in the
         * row tuple, return what we have.
         */
        return convert(self, attr, PySequence_Fast_GET_ITEM(self->row, attr->index));

    // If we need to check the pickle but haven't unpickled, do so now.
    if (!self->unpickled && !do_unpickle(self))
        return NULL;

    if (IS_ATTR_INDEXED_IGNORE_CASE(attr->flags)) {
        // ATTR_INDEXED_IGNORE_CASE, these attributes are prefixed with __ in
        // the pickled dict.
        PyObject *newkey = PyString_FromString("__");
        PyString_Concat(&newkey, key);
        key = newkey;
    }
    else
        Py_INCREF(key);

    value = PyDict_GetItem(self->pickle, key);
    Py_DECREF(key);
    if (!value)
        // Attribute isn't stored in pickle, so return suitable default.
        return get_default_for_attr(attr);

    return convert(self, attr, value);
}
Exemple #19
0
static PyObject *integer(PyObject *self, PyObject *args,
    PyObject *kwrds)
{
    matrix *c, *h, *b=NULL, *x=NULL;
    PyObject *G, *A=NULL, *IntSet=NULL, *BinSet = NULL;
    PyObject *t=NULL;
    pyiocp *iocpParm = NULL;;
    glp_iocp *options = NULL;
    glp_prob *lp;
    int m, n, p, i, j, k, nnz, nnzmax, *rn=NULL, *cn=NULL;
    double *a=NULL, val;
    char *kwlist[] = {"c", "G", "h", "A", "b", "I", "B","iocp", NULL};

    if (!PyArg_ParseTupleAndKeywords(args, kwrds, "OOO|OOOOO!", kwlist, &c,
	    &G, &h, &A, &b, &IntSet, &BinSet,iocp_t,&iocpParm)) return NULL;

    if(!iocpParm) 
    {
      iocpParm = (pyiocp*)malloc(sizeof(*iocpParm));
      glp_init_iocp(&(iocpParm->obj));
    }
    if(iocpParm) 
    {
      Py_INCREF(iocpParm);
      options = &iocpParm->obj;
      options->presolve = 1;
    }

    if ((Matrix_Check(G) && MAT_ID(G) != DOUBLE) ||
        (SpMatrix_Check(G) && SP_ID(G) != DOUBLE) ||
        (!Matrix_Check(G) && !SpMatrix_Check(G))){
        PyErr_SetString(PyExc_TypeError, "G must be a 'd' matrix");
        return NULL;
    }
    if ((m = Matrix_Check(G) ? MAT_NROWS(G) : SP_NROWS(G)) <= 0)
        err_p_int("m");
    if ((n = Matrix_Check(G) ? MAT_NCOLS(G) : SP_NCOLS(G)) <= 0)
        err_p_int("n");

    if (!Matrix_Check(h) || h->id != DOUBLE) err_dbl_mtrx("h");
    if (h->nrows != m || h->ncols != 1){
        PyErr_SetString(PyExc_ValueError, "incompatible dimensions");
        return NULL;
    }

    if (A){
        if ((Matrix_Check(A) && MAT_ID(A) != DOUBLE) ||
            (SpMatrix_Check(A) && SP_ID(A) != DOUBLE) ||
            (!Matrix_Check(A) && !SpMatrix_Check(A))){
                PyErr_SetString(PyExc_ValueError, "A must be a dense "
                    "'d' matrix or a general sparse matrix");
                return NULL;
	}
        if ((p = Matrix_Check(A) ? MAT_NROWS(A) : SP_NROWS(A)) < 0)
            err_p_int("p");
        if ((Matrix_Check(A) ? MAT_NCOLS(A) : SP_NCOLS(A)) != n){
            PyErr_SetString(PyExc_ValueError, "incompatible "
                "dimensions");
            return NULL;
	}
    }
    else p = 0;

    if (b && (!Matrix_Check(b) || b->id != DOUBLE)) err_dbl_mtrx("b");
    if ((b && (b->nrows != p || b->ncols != 1)) || (!b && p !=0 )){
        PyErr_SetString(PyExc_ValueError, "incompatible dimensions");
        return NULL;
    }

    if ((IntSet) && (!PyAnySet_Check(IntSet)))
      PY_ERR_TYPE("invalid integer index set");

    if ((BinSet) && (!PyAnySet_Check(BinSet)))
      PY_ERR_TYPE("invalid binary index set");

    lp = glp_create_prob();
    glp_add_rows(lp, m+p);
    glp_add_cols(lp, n);

    for (i=0; i<n; i++){
        glp_set_obj_coef(lp, i+1, MAT_BUFD(c)[i]);
        glp_set_col_bnds(lp, i+1, GLP_FR, 0.0, 0.0);
    }
    for (i=0; i<m; i++)
        glp_set_row_bnds(lp, i+1, GLP_UP, 0.0, MAT_BUFD(h)[i]);
    for (i=0; i<p; i++)
        glp_set_row_bnds(lp, i+m+1, GLP_FX, MAT_BUFD(b)[i],
            MAT_BUFD(b)[i]);

    nnzmax = (SpMatrix_Check(G) ? SP_NNZ(G) : m*n ) +
        ((A && SpMatrix_Check(A)) ? SP_NNZ(A) : p*n);
    a = (double *) calloc(nnzmax+1, sizeof(double));
    rn = (int *) calloc(nnzmax+1, sizeof(int));
    cn = (int *) calloc(nnzmax+1, sizeof(int));
    if (!a || !rn || !cn){
        free(a);  free(rn);  free(cn);  glp_delete_prob(lp);
        return PyErr_NoMemory();
    }

    nnz = 0;
    if (SpMatrix_Check(G)) {
        for (j=0; j<n; j++) for (k=SP_COL(G)[j]; k<SP_COL(G)[j+1]; k++)
            if ((val = SP_VALD(G)[k]) != 0.0){
                a[1+nnz] = val;
                rn[1+nnz] = SP_ROW(G)[k]+1;
                cn[1+nnz] = j+1;
                nnz++;
            }
    }
    else for (j=0; j<n; j++) for (i=0; i<m; i++)
        if ((val = MAT_BUFD(G)[i+j*m]) != 0.0){
            a[1+nnz] = val;
            rn[1+nnz] = i+1;
            cn[1+nnz] = j+1;
            nnz++;
        }

    if (A && SpMatrix_Check(A)){
        for (j=0; j<n; j++) for (k=SP_COL(A)[j]; k<SP_COL(A)[j+1]; k++)
            if ((val = SP_VALD(A)[k]) != 0.0){
                a[1+nnz] = val;
                rn[1+nnz] = m+SP_ROW(A)[k]+1;
                cn[1+nnz] = j+1;
                nnz++;
            }
    }
    else for (j=0; j<n; j++) for (i=0; i<p; i++)
        if ((val = MAT_BUFD(A)[i+j*p]) != 0.0){
            a[1+nnz] = val;
            rn[1+nnz] = m+i+1;
            cn[1+nnz] = j+1;
            nnz++;
        }

    glp_load_matrix(lp, nnz, rn, cn, a);
    free(rn);  free(cn);  free(a);

    if (!(t = PyTuple_New(2))) {
        glp_delete_prob(lp);
        return PyErr_NoMemory();
    }

    if (IntSet) {
      PyObject *iter = PySequence_Fast(IntSet, "Critical error: not sequence");

      for (i=0; i<PySet_GET_SIZE(IntSet); i++) {

	PyObject *tmp = PySequence_Fast_GET_ITEM(iter, i);
#if PY_MAJOR_VERSION >= 3
	if (!PyLong_Check(tmp)) {
#else
	if (!PyInt_Check(tmp)) {
#endif
	  glp_delete_prob(lp);
	  Py_DECREF(iter);
	  PY_ERR_TYPE("non-integer element in I");
	}
#if PY_MAJOR_VERSION >= 3
	int k = PyLong_AS_LONG(tmp);
#else
	int k = PyInt_AS_LONG(tmp);
#endif
	if ((k < 0) || (k >= n)) {
	  glp_delete_prob(lp);
	  Py_DECREF(iter);
	  PY_ERR(PyExc_IndexError, "index element out of range in I");
	}
	glp_set_col_kind(lp, k+1, GLP_IV);
      }

      Py_DECREF(iter);
    }

    if (BinSet) {
      PyObject *iter = PySequence_Fast(BinSet, "Critical error: not sequence");

      for (i=0; i<PySet_GET_SIZE(BinSet); i++) {

	PyObject *tmp = PySequence_Fast_GET_ITEM(iter, i);
#if PY_MAJOR_VERSION >= 3
	if (!PyLong_Check(tmp)) {
#else
	if (!PyInt_Check(tmp)) {
#endif
	  glp_delete_prob(lp);
	  Py_DECREF(iter);
	  PY_ERR_TYPE("non-binary element in I");
	}
#if PY_MAJOR_VERSION >= 3
	int k = PyLong_AS_LONG(tmp);
#else
	int k = PyInt_AS_LONG(tmp);
#endif
	if ((k < 0) || (k >= n)) {
	  glp_delete_prob(lp);
	  Py_DECREF(iter);
	  PY_ERR(PyExc_IndexError, "index element out of range in B");
	}
	glp_set_col_kind(lp, k+1, GLP_BV);
      }

      Py_DECREF(iter);

    }


      switch (glp_intopt(lp,options)){

          case 0:

              x = (matrix *) Matrix_New(n,1,DOUBLE);
              if (!x) {
                  Py_XDECREF(iocpParm);
                  Py_XDECREF(t);
                  glp_delete_prob(lp);
                  return PyErr_NoMemory();
              }
              set_output_string(t,"optimal");
              set_output_string(t,"optimal");

              for (i=0; i<n; i++)
                  MAT_BUFD(x)[i] = glp_mip_col_val(lp, i+1);
              PyTuple_SET_ITEM(t, 1, (PyObject *) x);

              Py_XDECREF(iocpParm);
              glp_delete_prob(lp);
              return (PyObject *) t;

          case GLP_ETMLIM:

              x = (matrix *) Matrix_New(n,1,DOUBLE);
              if (!x) {
                  Py_XDECREF(t);
                  Py_XDECREF(iocpParm);
                  glp_delete_prob(lp);
                  return PyErr_NoMemory();
              }
              set_output_string(t,"time limit exceeded");

              for (i=0; i<n; i++)
                  MAT_BUFD(x)[i] = glp_mip_col_val(lp, i+1);
              PyTuple_SET_ITEM(t, 1, (PyObject *) x);

              Py_XDECREF(iocpParm);
              glp_delete_prob(lp);
              return (PyObject *) t;


          case GLP_EBOUND:
              set_output_string(t,"incorrect bounds");
              break;
          case GLP_EFAIL:
              set_output_string(t,"invalid MIP formulation");
              break;

          case GLP_ENOPFS:
              set_output_string(t,"primal infeasible");
              break;

          case GLP_ENODFS:
              set_output_string(t,"dual infeasible");
              break;

          case GLP_EMIPGAP:
              set_output_string(t,"Relative mip gap tolerance reached");
              break;

              /*case LPX_E_ITLIM:

                set_output_string(t,"maxiters exceeded");
                break;*/

              /*case LPX_E_SING:

                set_output_string(t,"singular or ill-conditioned basis");
                break;*/


          default:

              set_output_string(t,"unknown");
      }

      Py_XDECREF(iocpParm);
    glp_delete_prob(lp);

    PyTuple_SET_ITEM(t, 1, Py_BuildValue(""));
    return (PyObject *) t;
}


static PyMethodDef glpk_functions[] = {
    {"lp", (PyCFunction) simplex, METH_VARARGS|METH_KEYWORDS,
        doc_simplex},
    {"ilp", (PyCFunction) integer, METH_VARARGS|METH_KEYWORDS,
        doc_integer},
    {NULL}  /* Sentinel */
};

#if PY_MAJOR_VERSION >= 3

static PyModuleDef glpk_module_def = {
    PyModuleDef_HEAD_INIT,
    "glpk",
    glpk__doc__,
    -1,
    glpk_functions,
    NULL, NULL, NULL, NULL
};

void addglpkConstants (void)
{
  PyModule_AddIntMacro(glpk_module, GLP_ON);
  PyModule_AddIntMacro(glpk_module,GLP_OFF);

  /* reason codes: */
  PyModule_AddIntMacro(glpk_module,GLP_IROWGEN);
  PyModule_AddIntMacro(glpk_module,GLP_IBINGO);
  PyModule_AddIntMacro(glpk_module,GLP_IHEUR);
  PyModule_AddIntMacro(glpk_module,GLP_ICUTGEN);
  PyModule_AddIntMacro(glpk_module,GLP_IBRANCH);
  PyModule_AddIntMacro(glpk_module,GLP_ISELECT);
  PyModule_AddIntMacro(glpk_module,GLP_IPREPRO);

  /* branch selection indicator: */
  PyModule_AddIntMacro(glpk_module,GLP_NO_BRNCH);
  PyModule_AddIntMacro(glpk_module,GLP_DN_BRNCH);
  PyModule_AddIntMacro(glpk_module,GLP_UP_BRNCH);

  /* return codes: */
  PyModule_AddIntMacro(glpk_module,GLP_EBADB);
  PyModule_AddIntMacro(glpk_module,GLP_ESING);
  PyModule_AddIntMacro(glpk_module,GLP_ECOND);
  PyModule_AddIntMacro(glpk_module,GLP_EBOUND);
  PyModule_AddIntMacro(glpk_module,GLP_EFAIL);
  PyModule_AddIntMacro(glpk_module,GLP_EOBJLL);
  PyModule_AddIntMacro(glpk_module,GLP_EOBJUL);
  PyModule_AddIntMacro(glpk_module,GLP_EITLIM);
  PyModule_AddIntMacro(glpk_module,GLP_ETMLIM);
  PyModule_AddIntMacro(glpk_module,GLP_ENOPFS);
  PyModule_AddIntMacro(glpk_module,GLP_ENODFS);
  PyModule_AddIntMacro(glpk_module,GLP_EROOT);
  PyModule_AddIntMacro(glpk_module,GLP_ESTOP);
  PyModule_AddIntMacro(glpk_module,GLP_EMIPGAP);
  PyModule_AddIntMacro(glpk_module,GLP_ENOFEAS);
  PyModule_AddIntMacro(glpk_module,GLP_ENOCVG);
  PyModule_AddIntMacro(glpk_module,GLP_EINSTAB);
  PyModule_AddIntMacro(glpk_module,GLP_EDATA);
  PyModule_AddIntMacro(glpk_module,GLP_ERANGE);

  /* condition indicator: */
  PyModule_AddIntMacro(glpk_module,GLP_KKT_PE);
  PyModule_AddIntMacro(glpk_module,GLP_KKT_PB);
  PyModule_AddIntMacro(glpk_module,GLP_KKT_DE);
  PyModule_AddIntMacro(glpk_module,GLP_KKT_DB);
  PyModule_AddIntMacro(glpk_module,GLP_KKT_CS);

  /* MPS file format: */
  PyModule_AddIntMacro(glpk_module,GLP_MPS_DECK);
  PyModule_AddIntMacro(glpk_module,GLP_MPS_FILE);

  /* simplex method control parameters */
  /* message level: */
  PyModule_AddIntMacro(glpk_module,GLP_MSG_OFF);
  PyModule_AddIntMacro(glpk_module,GLP_MSG_ERR);
  PyModule_AddIntMacro(glpk_module,GLP_MSG_ON);
  PyModule_AddIntMacro(glpk_module,GLP_MSG_ALL);
  PyModule_AddIntMacro(glpk_module,GLP_MSG_DBG);
  /* simplex method option: */
  PyModule_AddIntMacro(glpk_module,GLP_PRIMAL);
  PyModule_AddIntMacro(glpk_module,GLP_DUALP);
  PyModule_AddIntMacro(glpk_module,GLP_DUAL);
  /* pricing technique: */
  PyModule_AddIntMacro(glpk_module,GLP_PT_STD);
  PyModule_AddIntMacro(glpk_module,GLP_PT_PSE);
  /* ratio test technique: */
  PyModule_AddIntMacro(glpk_module,GLP_RT_STD);
  PyModule_AddIntMacro(glpk_module,GLP_RT_HAR);

  /* interior-point solver control parameters */
  /* ordering algorithm: */
  PyModule_AddIntMacro(glpk_module,GLP_ORD_NONE);
  PyModule_AddIntMacro(glpk_module,GLP_ORD_QMD);
  PyModule_AddIntMacro(glpk_module,GLP_ORD_AMD);
  PyModule_AddIntMacro(glpk_module,GLP_ORD_SYMAMD);
}

PyMODINIT_FUNC PyInit_glpk(void)
{
  if (!(glpk_module = PyModule_Create(&glpk_module_def))) return NULL;
  if (PyType_Ready(&iocp_t) < 0 || (PyType_Ready(&smcp_t) < 0)) return NULL;
  /*  Adding macros */
  addglpkConstants();
  /* Adding  option lists as objects */
  Py_INCREF(&smcp_t);
  PyModule_AddObject(glpk_module,"smcp",(PyObject*)&smcp_t);
  Py_INCREF(&iocp_t);
  PyModule_AddObject(glpk_module,"iocp",(PyObject*)&iocp_t);
  if (import_cvxopt() < 0) return NULL;
  return glpk_module;
}

#else

PyMODINIT_FUNC initglpk(void)
{
    glpk_module = Py_InitModule3("cvxopt.glpk", glpk_functions, 
            glpk__doc__);
    if (PyType_Ready(&iocp_t) < 0 || (PyType_Ready(&smcp_t) < 0)) return NULL;
    addglpkConstants();
    Py_INCREF(&smcp_t);
    PyModule_AddObject(glpk_module,"smcp",(PyObject*)&smcp_t);
    Py_INCREF(&iocp_t);
    PyModule_AddObject(glpk_module,"iocp",(PyObject*)&iocp_t);
    if (import_cvxopt() < 0) return;
}
Exemple #20
0
/* array utility function */
int PyC_AsArray(void *array, PyObject *value, const int length, const PyTypeObject *type, const short is_double, const char *error_prefix)
{
	PyObject *value_fast;
	int value_len;
	int i;

	if(!(value_fast=PySequence_Fast(value, error_prefix))) {
		return -1;
	}

	value_len= PySequence_Fast_GET_SIZE(value_fast);

	if(value_len != length) {
		Py_DECREF(value);
		PyErr_Format(PyExc_TypeError,
		             "%.200s: invalid sequence length. expected %d, got %d",
		             error_prefix, length, value_len);
		return -1;
	}

	/* for each type */
	if(type == &PyFloat_Type) {
		if(is_double) {
			double *array_double= array;
			for(i=0; i<length; i++) {
				array_double[i]= PyFloat_AsDouble(PySequence_Fast_GET_ITEM(value_fast, i));
			}
		}
		else {
			float *array_float= array;
			for(i=0; i<length; i++) {
				array_float[i]= PyFloat_AsDouble(PySequence_Fast_GET_ITEM(value_fast, i));
			}
		}
	}
	else if(type == &PyLong_Type) {
		/* could use is_double for 'long int' but no use now */
		int *array_int= array;
		for(i=0; i<length; i++) {
			array_int[i]= PyLong_AsSsize_t(PySequence_Fast_GET_ITEM(value_fast, i));
		}
	}
	else if(type == &PyBool_Type) {
		int *array_bool= array;
		for(i=0; i<length; i++) {
			array_bool[i]= (PyLong_AsSsize_t(PySequence_Fast_GET_ITEM(value_fast, i)) != 0);
		}
	}
	else {
		Py_DECREF(value_fast);
		PyErr_Format(PyExc_TypeError,
		             "%s: internal error %s is invalid",
		             error_prefix, type->tp_name);
		return -1;
	}

	Py_DECREF(value_fast);

	if(PyErr_Occurred()) {
		PyErr_Format(PyExc_TypeError,
		             "%s: one or more items could not be used as a %s",
		             error_prefix, type->tp_name);
		return -1;
	}

	return 0;
}
Exemple #21
0
static PyObject *
subprocess_fork_exec(PyObject* self, PyObject *args)
{
    PyObject *gc_module = NULL;
    PyObject *executable_list, *py_fds_to_keep;
    PyObject *env_list, *preexec_fn;
    PyObject *process_args, *converted_args = NULL, *fast_args = NULL;
    PyObject *preexec_fn_args_tuple = NULL;
    int p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite;
    int errpipe_read, errpipe_write, close_fds, restore_signals;
    int call_setsid;
    PyObject *cwd_obj, *cwd_obj2;
    const char *cwd;
    pid_t pid;
    int need_to_reenable_gc = 0;
    char *const *exec_array, *const *argv = NULL, *const *envp = NULL;
    Py_ssize_t arg_num;

    if (!PyArg_ParseTuple(
                args, "OOpOOOiiiiiiiiiiO:fork_exec",
                &process_args, &executable_list, &close_fds, &py_fds_to_keep,
                &cwd_obj, &env_list,
                &p2cread, &p2cwrite, &c2pread, &c2pwrite,
                &errread, &errwrite, &errpipe_read, &errpipe_write,
                &restore_signals, &call_setsid, &preexec_fn))
        return NULL;

    if (close_fds && errpipe_write < 3) {  /* precondition */
        PyErr_SetString(PyExc_ValueError, "errpipe_write must be >= 3");
        return NULL;
    }
    if (PySequence_Length(py_fds_to_keep) < 0) {
        PyErr_SetString(PyExc_ValueError, "cannot get length of fds_to_keep");
        return NULL;
    }
    if (_sanity_check_python_fd_sequence(py_fds_to_keep)) {
        PyErr_SetString(PyExc_ValueError, "bad value(s) in fds_to_keep");
        return NULL;
    }

    /* We need to call gc.disable() when we'll be calling preexec_fn */
    if (preexec_fn != Py_None) {
        PyObject *result;
        _Py_IDENTIFIER(isenabled);
        _Py_IDENTIFIER(disable);

        gc_module = PyImport_ImportModule("gc");
        if (gc_module == NULL)
            return NULL;
        result = _PyObject_CallMethodId(gc_module, &PyId_isenabled, NULL);
        if (result == NULL) {
            Py_DECREF(gc_module);
            return NULL;
        }
        need_to_reenable_gc = PyObject_IsTrue(result);
        Py_DECREF(result);
        if (need_to_reenable_gc == -1) {
            Py_DECREF(gc_module);
            return NULL;
        }
        result = _PyObject_CallMethodId(gc_module, &PyId_disable, NULL);
        if (result == NULL) {
            Py_DECREF(gc_module);
            return NULL;
        }
        Py_DECREF(result);
    }

    exec_array = _PySequence_BytesToCharpArray(executable_list);
    if (!exec_array) {
        Py_XDECREF(gc_module);
        return NULL;
    }

    /* Convert args and env into appropriate arguments for exec() */
    /* These conversions are done in the parent process to avoid allocating
       or freeing memory in the child process. */
    if (process_args != Py_None) {
        Py_ssize_t num_args;
        /* Equivalent to:  */
        /*  tuple(PyUnicode_FSConverter(arg) for arg in process_args)  */
        fast_args = PySequence_Fast(process_args, "argv must be a tuple");
        if (fast_args == NULL)
            goto cleanup;
        num_args = PySequence_Fast_GET_SIZE(fast_args);
        converted_args = PyTuple_New(num_args);
        if (converted_args == NULL)
            goto cleanup;
        for (arg_num = 0; arg_num < num_args; ++arg_num) {
            PyObject *borrowed_arg, *converted_arg;
            borrowed_arg = PySequence_Fast_GET_ITEM(fast_args, arg_num);
            if (PyUnicode_FSConverter(borrowed_arg, &converted_arg) == 0)
                goto cleanup;
            PyTuple_SET_ITEM(converted_args, arg_num, converted_arg);
        }

        argv = _PySequence_BytesToCharpArray(converted_args);
        Py_CLEAR(converted_args);
        Py_CLEAR(fast_args);
        if (!argv)
            goto cleanup;
    }

    if (env_list != Py_None) {
        envp = _PySequence_BytesToCharpArray(env_list);
        if (!envp)
            goto cleanup;
    }

    if (preexec_fn != Py_None) {
        preexec_fn_args_tuple = PyTuple_New(0);
        if (!preexec_fn_args_tuple)
            goto cleanup;
        _PyImport_AcquireLock();
    }

    if (cwd_obj != Py_None) {
        if (PyUnicode_FSConverter(cwd_obj, &cwd_obj2) == 0)
            goto cleanup;
        cwd = PyBytes_AsString(cwd_obj2);
    } else {
        cwd = NULL;
        cwd_obj2 = NULL;
    }

    pid = fork();
    if (pid == 0) {
        /* Child process */
        /*
         * Code from here to _exit() must only use async-signal-safe functions,
         * listed at `man 7 signal` or
         * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
         */

        if (preexec_fn != Py_None) {
            /* We'll be calling back into Python later so we need to do this.
             * This call may not be async-signal-safe but neither is calling
             * back into Python.  The user asked us to use hope as a strategy
             * to avoid deadlock... */
            PyOS_AfterFork();
        }

        child_exec(exec_array, argv, envp, cwd,
                   p2cread, p2cwrite, c2pread, c2pwrite,
                   errread, errwrite, errpipe_read, errpipe_write,
                   close_fds, restore_signals, call_setsid,
                   py_fds_to_keep, preexec_fn, preexec_fn_args_tuple);
        _exit(255);
        return NULL;  /* Dead code to avoid a potential compiler warning. */
    }
    Py_XDECREF(cwd_obj2);

    if (pid == -1) {
        /* Capture the errno exception before errno can be clobbered. */
        PyErr_SetFromErrno(PyExc_OSError);
    }
    if (preexec_fn != Py_None &&
            _PyImport_ReleaseLock() < 0 && !PyErr_Occurred()) {
        PyErr_SetString(PyExc_RuntimeError,
                        "not holding the import lock");
    }

    /* Parent process */
    if (envp)
        _Py_FreeCharPArray(envp);
    if (argv)
        _Py_FreeCharPArray(argv);
    _Py_FreeCharPArray(exec_array);

    /* Reenable gc in the parent process (or if fork failed). */
    if (need_to_reenable_gc && _enable_gc(gc_module)) {
        Py_XDECREF(gc_module);
        return NULL;
    }
    Py_XDECREF(preexec_fn_args_tuple);
    Py_XDECREF(gc_module);

    if (pid == -1)
        return NULL;  /* fork() failed.  Exception set earlier. */

    return PyLong_FromPid(pid);

cleanup:
    if (envp)
        _Py_FreeCharPArray(envp);
    if (argv)
        _Py_FreeCharPArray(argv);
    _Py_FreeCharPArray(exec_array);
    Py_XDECREF(converted_args);
    Py_XDECREF(fast_args);
    Py_XDECREF(preexec_fn_args_tuple);

    /* Reenable gc if it was disabled. */
    if (need_to_reenable_gc)
        _enable_gc(gc_module);
    Py_XDECREF(gc_module);
    return NULL;
}
Exemple #22
0
PyObject* dispatch_streams_(PyObject *self, PyObject *args, int (*fun)(FILE**, FILE **, FILE **, uint64_t)){
  /* Parse argument tuple and open FILE* for input and
   * output. This should raise an exception if something fails
   */  
  PyObject* seq = PySequence_Fast(args, "Expected the argument list");
  long num_sources = 0;
  long num_targets_1 = 0;
  long num_targets_2 = 0;
  uint64_t len = PySequence_Size(args);
  if(seq == NULL || len != 3){
    PyErr_SetString(PyExc_ValueError, "Expected exactly three arguments!");
    Py_DECREF(seq);
    return NULL;
  }

  PyObject* py_sources = PySequence_Fast_GET_ITEM(seq, 0);
  if(!PySequence_Check(py_sources)){
    PyErr_SetString(PyExc_ValueError, "Argument 0 is not a list!");
    Py_DECREF(seq);
    return NULL;
  }
  PyObject* py_targets_1 = PySequence_Fast_GET_ITEM(seq, 1);
  if(!PySequence_Check(py_targets_1)){
    PyErr_SetString(PyExc_ValueError, "Argument 1 is not a list!");
    Py_DECREF(seq);
    return NULL;
  }
  PyObject* py_targets_2 = PySequence_Fast_GET_ITEM(seq, 2);
  if(!PySequence_Check(py_targets_2)){
    PyErr_SetString(PyExc_ValueError, "Argument 2 is not a list!");
    Py_DECREF(seq);
    return NULL;
  }
  num_sources = PySequence_Size(py_sources);
  num_targets_1 = PySequence_Size(py_targets_1);
  num_targets_2 = PySequence_Size(py_targets_2);

  FILE** source_f = malloc(num_sources * sizeof(FILE*));
  FILE** target_f_1 = malloc(num_targets_1 * sizeof(FILE*));
  FILE** target_f_2 = malloc(num_targets_2 * sizeof(FILE*));
  
  bool error = false;
  if(!_update_files(py_sources, source_f, num_sources)){
    error = true;
  }
  if(!_update_files(py_targets_1, target_f_1, num_targets_1)){
    error = true;
  }
  if(!_update_files(py_targets_2, target_f_2, num_targets_2)){
    error = true;
  }

  if(!error){
    // for a child process for the dispatcher
    pid_t childPID = fork();
    if(childPID >= 0){
      if(childPID==0){
        // child
        fun(source_f, target_f_1, target_f_2, num_sources);
        free(target_f_1);
        free(target_f_2);
        free(source_f);
        exit(0);
      }
    }else{
      free(target_f_1);
      free(target_f_2);
      free(source_f);
      PyErr_SetString(PyExc_ValueError, "Unable to create dispatcher process");
      error = true;
    }

  }
  // cleanup 
  Py_DECREF(seq);
  if(error) return NULL;
  Py_RETURN_NONE;
}
Exemple #23
0
int BPY_context_member_get(bContext *C, const char *member, bContextDataResult *result)
{
	PyObject *pyctx = (PyObject *)CTX_py_dict_get(C);
	PyObject *item = PyDict_GetItemString(pyctx, member);
	PointerRNA *ptr = NULL;
	int done = 0;

	if (item == NULL) {
		/* pass */
	}
	else if (item == Py_None) {
		/* pass */
	}
	else if (BPy_StructRNA_Check(item)) {
		ptr = &(((BPy_StructRNA *)item)->ptr);

		//result->ptr = ((BPy_StructRNA *)item)->ptr;
		CTX_data_pointer_set(result, ptr->id.data, ptr->type, ptr->data);
		done = 1;
	}
	else if (PySequence_Check(item)) {
		PyObject *seq_fast = PySequence_Fast(item, "bpy_context_get sequence conversion");
		if (seq_fast == NULL) {
			PyErr_Print();
			PyErr_Clear();
		}
		else {
			int len = PySequence_Fast_GET_SIZE(seq_fast);
			int i;
			for (i = 0; i < len; i++) {
				PyObject *list_item = PySequence_Fast_GET_ITEM(seq_fast, i);

				if (BPy_StructRNA_Check(list_item)) {
					/*
					CollectionPointerLink *link = MEM_callocN(sizeof(CollectionPointerLink), "bpy_context_get");
					link->ptr = ((BPy_StructRNA *)item)->ptr;
					BLI_addtail(&result->list, link);
					*/
					ptr = &(((BPy_StructRNA *)list_item)->ptr);
					CTX_data_list_add(result, ptr->id.data, ptr->type, ptr->data);
				}
				else {
					printf("List item not a valid type\n");
				}

			}
			Py_DECREF(seq_fast);

			done = 1;
		}
	}

	if (done == 0) {
		if (item)	printf("PyContext '%s' not a valid type\n", member);
		else		printf("PyContext '%s' not found\n", member);
	}
	else {
		if (G.f & G_DEBUG) {
			printf("PyContext '%s' found\n", member);
		}
	}

	return done;
}
Exemple #24
0
static int
add_all_headers(write_bucket *bucket, PyObject *fast_headers, int hlen, client_t *client)
{
    int i;
    PyObject *tuple = NULL;
    PyObject *obj1 = NULL, *obj2 = NULL;
    PyObject *bytes1 = NULL, *bytes2 = NULL;
    char *name = NULL, *value = NULL;
    Py_ssize_t namelen, valuelen;
#ifdef PY3
    int o;
#endif

    if(likely(fast_headers != NULL)){
        for (i = 0; i < hlen; i++) {

            tuple = PySequence_Fast_GET_ITEM(fast_headers, i);

            if (unlikely( !PyTuple_Check(tuple))) {
                PyErr_Format(PyExc_TypeError, "list of tuple values "
                             "expected, value of type %.200s found",
                             tuple->ob_type->tp_name);
                goto error;
            }


            if (unlikely(PyTuple_GET_SIZE(tuple) != 2)) {
                PyErr_Format(PyExc_ValueError, "tuple of length 2 "
                             "expected, length is %d",
                             (int)PyTuple_Size(tuple));
                goto error;
            }

            obj1 = PyTuple_GET_ITEM(tuple, 0);
            obj2 = PyTuple_GET_ITEM(tuple, 1);
            if(unlikely(!obj1)){
                goto error;
            }
            if(unlikely(!obj2)){
                goto error;
            }
            bytes1 = wsgi_to_bytes(obj1);
            if(unlikely(PyBytes_AsStringAndSize(bytes1, &name, &namelen) == -1)){
                goto error;
            }

            //value
            bytes2 = wsgi_to_bytes(obj2);
            if(unlikely(PyBytes_AsStringAndSize(bytes2, &value, &valuelen) == -1)){
                goto error;
            }

            if (unlikely(strchr(name, ':') != 0)) {
                PyErr_Format(PyExc_ValueError, "header name may not contains ':'"
                             "response header with name '%s' and value '%s'",
                             name, value);
                goto error;
            }

            if (unlikely(strchr(name, '\n') != 0 || strchr(value, '\n') != 0)) {
                PyErr_Format(PyExc_ValueError, "embedded newline in "
                             "response header with name '%s' and value '%s'",
                             name, value);
                goto error;
            }

            if (!strcasecmp(name, "Server") || !strcasecmp(name, "Date")) {
                continue;
            }

            if (client->content_length_set != 1 && !strcasecmp(name, "Content-Length")) {
                char *v = value;
                long l = 0;

                errno = 0;
                l = strtol(v, &v, 10);
                if (*v || errno == ERANGE || l < 0) {
                    PyErr_SetString(PyExc_ValueError,
                                    "invalid content length");
                    goto error;
                }

                client->content_length_set = 1;
                client->content_length = l;
            }
            DEBUG("response header %s:%d : %s:%d",name, (int)namelen, value, (int)valuelen);
            add_header(bucket, name, namelen, value, valuelen);
#ifdef PY3
            //keep bytes string 
            o = PyList_Append(bucket->temp1, bytes1);
            if(o != -1){
                o = PyList_Append(bucket->temp1, bytes2);
                if(o == -1){
                    goto error;
                }
            }else{
                goto error;
            }
#endif
            Py_XDECREF(bytes1);
            Py_XDECREF(bytes2);
        }

    }else{
        RDEBUG("WARN header is lost...");
    }

    return 1;
error:
    if (PyErr_Occurred()){
        /* write_error_log(__FILE__, __LINE__); */
        call_error_logger();
    }
    Py_XDECREF(bytes1);
    Py_XDECREF(bytes2);
    return -1;
}
Exemple #25
0
static int
set_nameservers(Channel *self, PyObject *value)
{
    char *server;
    int i, r, length, ret;
    struct ares_addr_node *servers;
    Py_buffer pbuf;
    PyObject *server_list, *item, *data_fast;

    servers = NULL;
    server_list = value;
    ret = 0;

    if ((data_fast = PySequence_Fast(server_list, "argument 1 must be an iterable")) == NULL) {
        return -1;
    }

    length = PySequence_Fast_GET_SIZE(data_fast);
    if (length > INT_MAX) {
        PyErr_SetString(PyExc_ValueError, "argument 1 is too long");
        Py_DECREF(data_fast);
        return -1;
    }

    if (length == 0) {
        /* c-ares doesn't do anything */
        return 0;
    }

    servers = PyMem_Malloc(sizeof(struct ares_addr_node) * length);
    if (!servers) {
        PyErr_NoMemory();
        ret = -1;
        goto end;
    }

    for (i = 0; i < length; i++) {
        item = PySequence_Fast_GET_ITEM(data_fast, i);
        if (!item || !PyArg_Parse(item, "s*;args contains a non-string value", &pbuf)) {
            Py_XDECREF(item);
            goto end;
        }
        server = pbuf.buf;

        if (ares_inet_pton(AF_INET, server, &servers[i].addr.addr4) == 1) {
            servers[i].family = AF_INET;
        } else if (ares_inet_pton(AF_INET6, server, &servers[i].addr.addr6) == 1) {
            servers[i].family = AF_INET6;
        } else {
            PyErr_SetString(PyExc_ValueError, "invalid IP address");
            PyBuffer_Release(&pbuf);
            ret = -1;
            goto end;
        }

        PyBuffer_Release(&pbuf);

        if (i > 0) {
            servers[i-1].next = &servers[i];
        }

    }

    if (servers) {
        servers[length-1].next = NULL;
    }

    r = ares_set_servers(self->channel, servers);
    if (r != ARES_SUCCESS) {
        RAISE_ARES_EXCEPTION(r);
        ret = -1;
    }

end:
    PyMem_Free(servers);
    return ret;
}
Exemple #26
0
PyObject* xcsoar_Airspaces_addPolygon(Pyxcsoar_Airspaces *self, PyObject *args) {
  PyObject *py_points = nullptr,
           *py_name = nullptr,
           *py_as_class = nullptr,
           *py_base_ref = nullptr,
           *py_top_ref = nullptr;
  double base_alt, top_alt;

  if (!PyArg_ParseTuple(args, "OOOdOdO", &py_points, &py_name, &py_as_class,
                                         &base_alt, &py_base_ref,
                                         &top_alt, &py_top_ref)) {
    return nullptr;
  }

  /* Parse points */
  std::vector<GeoPoint> points;

  if (!PySequence_Check(py_points)) {
    PyErr_SetString(PyExc_ValueError, "First argument is no sequence");
    return nullptr;
  }

  Py_ssize_t num_items = PySequence_Fast_GET_SIZE(py_points);

  for (Py_ssize_t i = 0; i < num_items; ++i) {
    PyObject *py_location = PySequence_Fast_GET_ITEM(py_points, i);

    GeoPoint location = Python::ReadLonLat(py_location);

    if (!location.IsValid()) {
      if (PyErr_Occurred() == nullptr)
        PyErr_SetString(PyExc_RuntimeError, "Unknown error while parsing location");

      return nullptr;
    }

    points.push_back(location);
  }

  if (points.size() < 3) {
    PyErr_SetString(PyExc_ValueError, "Polygon has not enough points");
    return nullptr;
  }

  /* Parse airspace name */
  tstring name;

  if (!Python::PyStringToString(py_name, name)) {
    PyErr_SetString(PyExc_ValueError, "Can't parse airspace name.");
    return nullptr;
  }

  /* Parse airspace class */
  tstring as_class;
  AirspaceClass type = AirspaceClass::OTHER;

  if (!Python::PyStringToString(py_as_class, as_class)) {
    PyErr_SetString(PyExc_ValueError, "Can't parse airspace class.");
    return nullptr;
  }

  for (unsigned i = 0; i < ARRAY_SIZE(airspace_class_strings); i++) {
    if (as_class.compare(airspace_class_strings[i].string) == 0)
      type = airspace_class_strings[i].type;
  }

  /* Parse airspace base and top */
  tstring base_ref, top_ref;
  AirspaceAltitude base, top;

  if (!Python::PyStringToString(py_base_ref, base_ref)) {
    PyErr_SetString(PyExc_ValueError, "Can't parse airspace base reference.");
    return nullptr;
  }

  if (!Python::PyStringToString(py_top_ref, top_ref)) {
    PyErr_SetString(PyExc_ValueError, "Can't parse airspace top reference.");
    return nullptr;
  }

  if (base_ref.compare("MSL") == 0) {
    base.reference = AltitudeReference::MSL;
    base.altitude = base_alt;
  } else if (base_ref.compare("FL") == 0) {
    base.reference = AltitudeReference::STD;
    base.flight_level = base_alt;
  } else if (base_ref.compare("AGL") == 0) {
    base.reference = AltitudeReference::AGL;
    base.altitude_above_terrain = base_alt;
  } else {
    PyErr_SetString(PyExc_ValueError, "Can't parse airspace base.");
    return nullptr;
  }

  if (top_ref.compare("MSL") == 0) {
    top.reference = AltitudeReference::MSL;
    top.altitude = top_alt;
  } else if (top_ref.compare("FL") == 0) {
    top.reference = AltitudeReference::STD;
    top.flight_level = top_alt;
  } else if (top_ref.compare("AGL") == 0) {
    top.reference = AltitudeReference::AGL;
    top.altitude_above_terrain = top_alt;
  } else {
    PyErr_SetString(PyExc_ValueError, "Can't parse airspace top.");
    return nullptr;
  }

  /* Create airspace and save it into the database */
  AbstractAirspace *as = new AirspacePolygon(points);
  as->SetProperties(std::move(name), type, base, top);
  self->airspace_database->Add(as);

  Py_RETURN_NONE;
}
Exemple #27
0
 // py2c implementation
 template<int N, typename T, typename... Tail> static std::tuple<T,Tail...> py2c_impl(PyObject *seq) {
     return std::tuple_cat(std::make_tuple(py_converter<T>::py2c(PySequence_Fast_GET_ITEM(seq, N))),
                           py2c_impl<N+1,Tail...>(seq));
 }
CONSTSET    init_struct_constraints(SAMPLE sample, STRUCTMODEL *sm, 
				    STRUCT_LEARN_PARM *sparm)
{
  /* Initializes the optimization problem. Typically, you do not need
     to change this function, since you want to start with an empty
     set of constraints. However, if for example you have constraints
     that certain weights need to be positive, you might put that in
     here. The constraints are represented as lhs[i]*w >= rhs[i]. lhs
     is an array of feature vectors, rhs is an array of doubles. m is
     the number of constraints. The function returns the initial set
     of constraints. */
  CONSTSET c;
  PyObject *pFunc,*pValue,*pSeq;
  int i;

  // Set defaults of no constraints.
  c.m=0;
  c.lhs=NULL;
  c.rhs=NULL;
  // Call the relevant Python function.
  pFunc = getFunction(PYTHON_INIT_CONSTRAINTS);
  pValue = PyObject_CallFunction(pFunc, "NNN", Sample_FromSample(sample),
				 StructModel_FromStructModel(sm),
				 Sparm_FromSparm(sparm));
  //Py_DECREF(pArgs);
  PY_RUNCHECK;

  // Check for None possibility.
  if (pValue == Py_None) {
    // No constraints if no return value.
    Py_DECREF(pValue);
    return c;
  }
  // Convert this into a sequence.
  pSeq = PySequence_Fast(pValue, "constraints not a sequence");
  Py_DECREF(pValue);
  if (pSeq == NULL) {
    PyErr_Print();
    Py_Exit(1);
  }

  // Read the examples from the sequence.
  c.m = PySequence_Size(pSeq);
  if (c.m==0) {
    // Empty constraint set.
    Py_DECREF(pSeq);
    return c;
  }
  // Initialize the constraint data structures.
  c.lhs = (DOC **)my_malloc(sizeof(DOC*)*c.m);
  c.rhs = (double*)my_malloc(sizeof(double)*c.m);
  bzero(c.lhs, sizeof(DOC*)*c.m);
  bzero(c.rhs, sizeof(double)*c.m);
  // Try to iteratively extract the constraints.
  for (i=0; i<c.m; ++i) {
    PyObject *pConst = PySequence_Fast_GET_ITEM(pSeq, i);
    PyObject *pRHS, *pLHS;
    if (!pConst || !PySequence_Check(pConst) ||
        PySequence_Size(pConst)<2){
      fprintf(stderr, "%s's item %d is not a sequence element of "
              "at least two items!\n", PYTHON_INIT_CONSTRAINTS, i);
      goto error;
    }
    // Extract the right hand side.
    pRHS = PySequence_GetItem(pConst, 1);
    c.rhs[i] = PyFloat_AsDouble(pRHS);
    Py_XDECREF(pRHS);
    if (PyErr_Occurred()) {
      Py_DECREF(pConst);
      goto error;
    }
    // Extract the left hand side.
    pLHS = PySequence_GetItem(pConst, 0);
    c.lhs[i] = Document_AsDocument(pLHS);
    c.lhs[i]->docnum = i;
    Py_XDECREF(pLHS);
    //Py_DECREF(pConst);
    if (PyErr_Occurred()) {
      goto error;
    }
  }
  Py_DECREF(pSeq);
  return(c);

 error:
  // Free what document structures we have copied.
  Py_DECREF(pSeq);
  for (i=0; i<c.m; ++i) {
    if (c.lhs[i]) free_example(c.lhs[i],1);
  }
  free(c.lhs);
  free(c.rhs);
  PY_RUNCHECK;
  fprintf(stderr, PYTHON_INIT_CONSTRAINTS": should not be here\n");
  Py_Exit(2);
  return c;
}
Exemple #29
0
static PyObject *
SpiDev_writebytes(SpiDevObject *self, PyObject *args)
{
	int		status;
	uint16_t	ii, len;
	uint8_t	buf[SPIDEV_MAXPATH];
	PyObject	*obj;
	PyObject	*seq;
	char	wrmsg_text[4096];

	if (!PyArg_ParseTuple(args, "O:write", &obj))
		return NULL;

	seq = PySequence_Fast(obj, "expected a sequence");
	len = PySequence_Fast_GET_SIZE(obj);
	if (!seq || len <= 0) {
		PyErr_SetString(PyExc_TypeError, wrmsg_list0);
		return NULL;
	}

	if (len > SPIDEV_MAXPATH) {
		snprintf(wrmsg_text, sizeof (wrmsg_text) - 1, wrmsg_listmax, SPIDEV_MAXPATH);
		PyErr_SetString(PyExc_OverflowError, wrmsg_text);
		return NULL;
	}

	for (ii = 0; ii < len; ii++) {
		PyObject *val = PySequence_Fast_GET_ITEM(seq, ii);
#if PY_MAJOR_VERSION < 3
		if (PyInt_Check(val)) {
			buf[ii] = (__u8)PyInt_AS_LONG(val);
		} else
#endif
		{
			if (PyLong_Check(val)) {
				buf[ii] = (__u8)PyLong_AS_LONG(val);
			} else {
				snprintf(wrmsg_text, sizeof (wrmsg_text) - 1, wrmsg_val, val);
				PyErr_SetString(PyExc_TypeError, wrmsg_text);
				return NULL;
			}
		}
	}

	Py_DECREF(seq);

	status = write(self->fd, &buf[0], len);

	if (status < 0) {
		PyErr_SetFromErrno(PyExc_IOError);
		return NULL;
	}

	if (status != len) {
		perror("short write");
		return NULL;
	}

	Py_INCREF(Py_None);
	return Py_None;
}
/* This function should probably be changed to not accept bytes() when
 * Python 2.x support is dropped. */
static int
parse_key_patterns(PyObject *py_pattern, char ***patterns)
{
    int result = -1, length, i;
    PyObject *list = NULL;

    *patterns = NULL;
    if (py_pattern == Py_None) {
        result = 0;
    } else if (PyUnicode_Check(py_pattern) || PyBytes_Check(py_pattern)) {
        PyObject *bytes;

        if (PyUnicode_Check(py_pattern)) {
            bytes = PyUnicode_AsUTF8String(py_pattern);
            if (bytes == NULL)
                goto end;
        } else {
            bytes = py_pattern;
            Py_INCREF(bytes);
        }
        *patterns = calloc(2, sizeof (char *));
        if (*patterns == NULL) {
            PyErr_NoMemory();
            Py_DECREF(bytes);
            goto end;
        }
        (*patterns)[0] = strdup(PyBytes_AsString(bytes));
        if ((*patterns)[0] == NULL) {
            PyErr_NoMemory();
            Py_DECREF(bytes);
            goto end;
        }
        result = 0;
    } else {
        /* We must have a sequence of strings. */
        list = PySequence_Fast(py_pattern,
            "first argument must be a string or sequence of strings");
        if (list == NULL)
            goto end;

        length = PySequence_Fast_GET_SIZE(list);
        *patterns = calloc((length + 1), sizeof(char *));
        if (*patterns == NULL) {
            PyErr_NoMemory();
            goto end;
        }
        for (i = 0; i < length; i++) {
            PyObject *item = PySequence_Fast_GET_ITEM(list, i);
            PyObject *bytes;

            if (PyBytes_Check(item)) {
                bytes = item;
                Py_INCREF(bytes);
            } else if (PyUnicode_Check(item)) {
                bytes = PyUnicode_AsUTF8String(item);
                if (bytes == NULL) {
                    goto end;
                }
            } else {
                PyErr_SetString(PyExc_TypeError,
                    "first argument must be a string or sequence of strings");
                goto end;
            }
            (*patterns)[i] = strdup(PyBytes_AsString(bytes));
            if ((*patterns)[i] == NULL) {
                PyErr_NoMemory();
                Py_DECREF(bytes);
                goto end;
            }
        }
        result = 0;
    }
 end:
    Py_XDECREF(list);
    /* cleanup the partial pattern list if there was an error*/
    if (result < 0 && *patterns != NULL) {
        free_key_patterns(*patterns);
        *patterns = NULL;
    }
    return result;
}