Ejemplo n.º 1
0
int pysqlite_connection_init(pysqlite_Connection* self, PyObject* args, PyObject* kwargs)
{
    static char *kwlist[] = {
        "database", "timeout", "detect_types", "isolation_level",
        "check_same_thread", "factory", "cached_statements", "uri",
        NULL
    };

    char* database;
    int detect_types = 0;
    PyObject* isolation_level = NULL;
    PyObject* factory = NULL;
    int check_same_thread = 1;
    int cached_statements = 100;
    int uri = 0;
    double timeout = 5.0;
    int rc;

    if (!PyArg_ParseTupleAndKeywords(args, kwargs, "s|diOiOip", kwlist,
                                     &database, &timeout, &detect_types,
                                     &isolation_level, &check_same_thread,
                                     &factory, &cached_statements, &uri))
    {
        return -1;
    }

    self->initialized = 1;

    self->begin_statement = NULL;

    self->statement_cache = NULL;
    self->statements = NULL;
    self->cursors = NULL;

    Py_INCREF(Py_None);
    self->row_factory = Py_None;

    Py_INCREF(&PyUnicode_Type);
    self->text_factory = (PyObject*)&PyUnicode_Type;

#ifdef SQLITE_OPEN_URI
    Py_BEGIN_ALLOW_THREADS
    rc = sqlite3_open_v2(database, &self->db,
                         SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE |
                         (uri ? SQLITE_OPEN_URI : 0), NULL);
#else
    if (uri) {
        PyErr_SetString(pysqlite_NotSupportedError, "URIs not supported");
        return -1;
    }
    Py_BEGIN_ALLOW_THREADS
    rc = sqlite3_open(database, &self->db);
#endif
    Py_END_ALLOW_THREADS

    if (rc != SQLITE_OK) {
        _pysqlite_seterror(self->db, NULL);
        return -1;
    }

    if (!isolation_level) {
        isolation_level = PyUnicode_FromString("");
        if (!isolation_level) {
            return -1;
        }
    } else {
        Py_INCREF(isolation_level);
    }
    self->isolation_level = NULL;
    if (pysqlite_connection_set_isolation_level(self, isolation_level) < 0) {
        Py_DECREF(isolation_level);
        return -1;
    }
    Py_DECREF(isolation_level);

    self->statement_cache = (pysqlite_Cache*)PyObject_CallFunction((PyObject*)&pysqlite_CacheType, "Oi", self, cached_statements);
    if (PyErr_Occurred()) {
        return -1;
    }

    self->created_statements = 0;
    self->created_cursors = 0;

    /* Create lists of weak references to statements/cursors */
    self->statements = PyList_New(0);
    self->cursors = PyList_New(0);
    if (!self->statements || !self->cursors) {
        return -1;
    }

    /* By default, the Cache class INCREFs the factory in its initializer, and
     * decrefs it in its deallocator method. Since this would create a circular
     * reference here, we're breaking it by decrementing self, and telling the
     * cache class to not decref the factory (self) in its deallocator.
     */
    self->statement_cache->decref_factory = 0;
    Py_DECREF(self);

    self->inTransaction = 0;
    self->detect_types = detect_types;
    self->timeout = timeout;
    (void)sqlite3_busy_timeout(self->db, (int)(timeout*1000));
#ifdef WITH_THREAD
    self->thread_ident = PyThread_get_thread_ident();
#endif
    if (!check_same_thread && sqlite3_libversion_number() < 3003001) {
        PyErr_SetString(pysqlite_NotSupportedError, "shared connections not available");
        return -1;
    }
    self->check_same_thread = check_same_thread;

    self->function_pinboard = PyDict_New();
    if (!self->function_pinboard) {
        return -1;
    }

    self->collations = PyDict_New();
    if (!self->collations) {
        return -1;
    }

    self->Warning               = pysqlite_Warning;
    self->Error                 = pysqlite_Error;
    self->InterfaceError        = pysqlite_InterfaceError;
    self->DatabaseError         = pysqlite_DatabaseError;
    self->DataError             = pysqlite_DataError;
    self->OperationalError      = pysqlite_OperationalError;
    self->IntegrityError        = pysqlite_IntegrityError;
    self->InternalError         = pysqlite_InternalError;
    self->ProgrammingError      = pysqlite_ProgrammingError;
    self->NotSupportedError     = pysqlite_NotSupportedError;

    return 0;
}
Ejemplo n.º 2
0
static PyObject *fparse_function_1_new_of_module_Crypto$Random( Nuitka_FunctionObject *self, PyObject **args, Py_ssize_t args_size, PyObject *kw )
{
    assert( kw == NULL || PyDict_Check( kw ) );

    NUITKA_MAY_BE_UNUSED Py_ssize_t kw_size = kw ? PyDict_Size( kw ) : 0;
    NUITKA_MAY_BE_UNUSED Py_ssize_t kw_found = 0;
    NUITKA_MAY_BE_UNUSED Py_ssize_t kw_only_found = 0;
    Py_ssize_t args_given = args_size;
    PyObject *_python_par_args = NULL;
    PyObject *_python_par_kwargs = NULL;

    if ( kw == NULL )
    {
        _python_par_kwargs = PyDict_New();
    }
    else
    {
        if ( ((PyDictObject *)kw)->ma_used > 0 )
        {
#if PYTHON_VERSION < 330
            _python_par_kwargs = _PyDict_NewPresized( ((PyDictObject *)kw)->ma_used  );

            for ( int i = 0; i <= ((PyDictObject *)kw)->ma_mask; i++ )
            {
                PyDictEntry *entry = &((PyDictObject *)kw)->ma_table[ i ];

                if ( entry->me_value != NULL )
                {

#if PYTHON_VERSION < 300
                    if (unlikely( !PyString_Check( entry->me_key ) && !PyUnicode_Check( entry->me_key ) ))
#else
                    if (unlikely( !PyUnicode_Check( entry->me_key ) ))
#endif
                    {
                        PyErr_Format( PyExc_TypeError, "new() keywords must be strings" );
                        goto error_exit;
                    }

                    int res = PyDict_SetItem( _python_par_kwargs, entry->me_key, entry->me_value );

                    if (unlikely( res == -1 ))
                    {
                        goto error_exit;
                    }
                }
            }
#else
        if ( _PyDict_HasSplitTable( (PyDictObject *)kw) )
        {
            PyDictObject *mp = (PyDictObject *)kw;

            PyObject **newvalues = PyMem_NEW( PyObject *, mp->ma_keys->dk_size );
            assert (newvalues != NULL);

            PyDictObject *split_copy = PyObject_GC_New( PyDictObject, &PyDict_Type );
            assert( split_copy != NULL );

            split_copy->ma_values = newvalues;
            split_copy->ma_keys = mp->ma_keys;
            split_copy->ma_used = mp->ma_used;

            mp->ma_keys->dk_refcnt += 1;

            Nuitka_GC_Track( split_copy );

            Py_ssize_t size = mp->ma_keys->dk_size;
            for ( Py_ssize_t i = 0; i < size; i++ )
            {
                PyDictKeyEntry *entry = &split_copy->ma_keys->dk_entries[ i ];

                if (unlikely( !PyUnicode_Check( entry->me_key ) ))
                {
                    PyErr_Format( PyExc_TypeError, "new() keywords must be strings" );
                    goto error_exit;
                }

                split_copy->ma_values[ i ] = INCREASE_REFCOUNT_X( mp->ma_values[ i ] );
            }

            _python_par_kwargs = (PyObject *)split_copy;
        }
        else
        {
Ejemplo n.º 3
0
Archivo: dict.c Proyecto: jwilk/Pyrex
/* Implementation of dict */

static PyObject *__pyx_f_4dict_f(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/
static PyObject *__pyx_f_4dict_f(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) {
  PyObject *__pyx_v_adict = 0;
  PyObject *__pyx_v_key1 = 0;
  PyObject *__pyx_v_value1 = 0;
  PyObject *__pyx_v_key2 = 0;
  PyObject *__pyx_v_value2 = 0;
  PyObject *__pyx_r;
  PyObject *__pyx_1 = 0;
  PyObject *__pyx_2 = 0;
  static char *__pyx_argnames[] = {"adict","key1","value1","key2","value2",0};
  if (!PyArg_ParseTupleAndKeywords(__pyx_args, __pyx_kwds, "OOOOO", __pyx_argnames, &__pyx_v_adict, &__pyx_v_key1, &__pyx_v_value1, &__pyx_v_key2, &__pyx_v_value2)) return 0;
  Py_INCREF(__pyx_v_adict);
  Py_INCREF(__pyx_v_key1);
  Py_INCREF(__pyx_v_value1);
  Py_INCREF(__pyx_v_key2);
  Py_INCREF(__pyx_v_value2);

  /* "/Local/Projects/D/Pyrex/Source/Tests/2/dict.pyx":2 */
  __pyx_1 = PyDict_New(); if (!__pyx_1) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2; goto __pyx_L1;}
  Py_DECREF(__pyx_v_adict);
  __pyx_v_adict = __pyx_1;
  __pyx_1 = 0;

  /* "/Local/Projects/D/Pyrex/Source/Tests/2/dict.pyx":3 */
  __pyx_1 = PyDict_New(); if (!__pyx_1) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3; goto __pyx_L1;}
  if (PyDict_SetItem(__pyx_1, __pyx_v_key1, __pyx_v_value1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3; goto __pyx_L1;}
  Py_DECREF(__pyx_v_adict);
  __pyx_v_adict = __pyx_1;
  __pyx_1 = 0;

  /* "/Local/Projects/D/Pyrex/Source/Tests/2/dict.pyx":4 */
  __pyx_1 = PyDict_New(); if (!__pyx_1) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4; goto __pyx_L1;}
  if (PyDict_SetItem(__pyx_1, __pyx_v_key1, __pyx_v_value1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4; goto __pyx_L1;}
  if (PyDict_SetItem(__pyx_1, __pyx_v_key2, __pyx_v_value2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4; goto __pyx_L1;}
  Py_DECREF(__pyx_v_adict);
  __pyx_v_adict = __pyx_1;
  __pyx_1 = 0;

  /* "/Local/Projects/D/Pyrex/Source/Tests/2/dict.pyx":5 */
  __pyx_1 = PyDict_New(); if (!__pyx_1) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 5; goto __pyx_L1;}
  if (PyDict_SetItem(__pyx_1, __pyx_v_key1, __pyx_v_value1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 5; goto __pyx_L1;}
  if (PyDict_SetItem(__pyx_1, __pyx_v_key2, __pyx_v_value2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 5; goto __pyx_L1;}
  Py_DECREF(__pyx_v_adict);
  __pyx_v_adict = __pyx_1;
  __pyx_1 = 0;

  /* "/Local/Projects/D/Pyrex/Source/Tests/2/dict.pyx":6 */
  __pyx_1 = PyDict_New(); if (!__pyx_1) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 6; goto __pyx_L1;}
  if (PyDict_SetItem(__pyx_1, __pyx_n_parrot, __pyx_n_resting) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 6; goto __pyx_L1;}
  __pyx_2 = PyInt_FromLong(42); if (!__pyx_2) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 6; goto __pyx_L1;}
  if (PyDict_SetItem(__pyx_1, __pyx_n_answer, __pyx_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 6; goto __pyx_L1;}
  Py_DECREF(__pyx_2); __pyx_2 = 0;
  Py_DECREF(__pyx_v_adict);
  __pyx_v_adict = __pyx_1;
  __pyx_1 = 0;

  __pyx_r = Py_None; Py_INCREF(Py_None);
  goto __pyx_L0;
  __pyx_L1:;
  Py_XDECREF(__pyx_1);
  Py_XDECREF(__pyx_2);
  __Pyx_AddTraceback("dict.f");
  __pyx_r = 0;
  __pyx_L0:;
  Py_DECREF(__pyx_v_adict);
  Py_DECREF(__pyx_v_key1);
  Py_DECREF(__pyx_v_value1);
  Py_DECREF(__pyx_v_key2);
  Py_DECREF(__pyx_v_value2);
  return __pyx_r;
}
Ejemplo n.º 4
0
dict_base::dict_base()
    : object(detail::new_reference(PyDict_New()))
{}
Ejemplo n.º 5
0
                PyDictKeyEntry *entry = &split_copy->ma_keys->dk_entries[ i ];

                if (unlikely( !PyUnicode_Check( entry->me_key ) ))
                {
                    PyErr_Format( PyExc_TypeError, "new() keywords must be strings" );
                    goto error_exit;
                }

                split_copy->ma_values[ i ] = INCREASE_REFCOUNT_X( mp->ma_values[ i ] );
            }

            _python_par_kwargs = (PyObject *)split_copy;
        }
        else
        {
            _python_par_kwargs = PyDict_New();

            PyDictObject *mp = (PyDictObject *)kw;

            Py_ssize_t size = mp->ma_keys->dk_size;
            for ( Py_ssize_t i = 0; i < size; i++ )
            {
                PyDictKeyEntry *entry = &mp->ma_keys->dk_entries[i];

                // TODO: One of these cases has been dealt with above.
                PyObject *value;
                if ( mp->ma_values )
                {
                    value = mp->ma_values[ i ];
                }
                else
Ejemplo n.º 6
0
Archivo: msaio.c Proyecto: Wyss/ProDy
static PyObject *parseSelex(PyObject *self, PyObject *args) {

    /* Parse sequences from *filename* into the the memory pointed by the
       Numpy array passed as Python object.  */

    char *filename;
    PyArrayObject *msa;

    if (!PyArg_ParseTuple(args, "sO", &filename, &msa))
        return NULL;

    long i = 0, beg = 0, end = 0;
    long size = SELEXLINELEN + 1, iline = 0, seqlen = 0;
    char errmsg[LENLABEL] = "failed to parse SELEX/Stockholm file at line ";

    PyObject *labels = PyList_New(0), *mapping = PyDict_New();
    if (!labels || !mapping)
        return PyErr_NoMemory();
    char *line = malloc(size * sizeof(char));
    if (!line)
        return PyErr_NoMemory();
    char *data = (char *) PyArray_DATA(msa);
    /* figure out where the sequence starts and ends in a line*/
    FILE *file = fopen(filename, "rb");
    while (fgets(line, size, file) != NULL) {
        iline++;
        if (line[0] == '#' || line[0] == '/' || line[0] == '%')
            continue;
        for (i = 0; i < size; i++)
            if (line[i] == ' ')
                break;
        for (; i < size; i++)
            if (line[i] != ' ')
                break;
        beg = i;
        for (; i < size; i++)
            if (line[i] < 32)
                break;
        end = i;
        seqlen = end - beg;
        break;
    }
    iline--;
    fseek(file, - strlen(line), SEEK_CUR);

    long index = 0, count = 0;

    int space = beg - 1; /* index of space character before sequence */
    while (fgets(line, size, file) != NULL) {
        iline++;
        if (line[0] == '#' || line[0] == '/' || line[0] == '%')
            continue;

        if (line[space] != ' ') {
            free(line);
            fclose(file);
            PyErr_SetString(PyExc_IOError, intcat(errmsg, iline));
            return NULL;
        }

        count += parseLabel(labels, mapping, line, space);

        for (i = beg; i < end; i++)
            data[index++] = line[i];
    }
    fclose(file);
    free(line);
    npy_intp dims[2] = {index / seqlen, seqlen};
    PyArray_Dims arr_dims;
    arr_dims.ptr = dims;
    arr_dims.len = 2;
    PyArray_Resize(msa, &arr_dims, 0, NPY_CORDER);
    PyObject *result = Py_BuildValue("(OOOi)", msa, labels, mapping, count);
    Py_DECREF(labels);
    Py_DECREF(mapping);

    return result;
}
Ejemplo n.º 7
0
static PyObject *
PLy_trigger_build_args(FunctionCallInfo fcinfo, PLyProcedure *proc, HeapTuple *rv)
{
	TriggerData *tdata = (TriggerData *) fcinfo->context;
	PyObject   *pltname,
			   *pltevent,
			   *pltwhen,
			   *pltlevel,
			   *pltrelid,
			   *plttablename,
			   *plttableschema;
	PyObject   *pltargs,
			   *pytnew,
			   *pytold;
	PyObject   *volatile pltdata = NULL;
	char	   *stroid;

	PG_TRY();
	{
		pltdata = PyDict_New();
		if (!pltdata)
			PLy_elog(ERROR, "could not create new dictionary while building trigger arguments");

		pltname = PyString_FromString(tdata->tg_trigger->tgname);
		PyDict_SetItemString(pltdata, "name", pltname);
		Py_DECREF(pltname);

		stroid = DatumGetCString(DirectFunctionCall1(oidout,
							   ObjectIdGetDatum(tdata->tg_relation->rd_id)));
		pltrelid = PyString_FromString(stroid);
		PyDict_SetItemString(pltdata, "relid", pltrelid);
		Py_DECREF(pltrelid);
		pfree(stroid);

		stroid = SPI_getrelname(tdata->tg_relation);
		plttablename = PyString_FromString(stroid);
		PyDict_SetItemString(pltdata, "table_name", plttablename);
		Py_DECREF(plttablename);
		pfree(stroid);

		stroid = SPI_getnspname(tdata->tg_relation);
		plttableschema = PyString_FromString(stroid);
		PyDict_SetItemString(pltdata, "table_schema", plttableschema);
		Py_DECREF(plttableschema);
		pfree(stroid);

		if (TRIGGER_FIRED_BEFORE(tdata->tg_event))
			pltwhen = PyString_FromString("BEFORE");
		else if (TRIGGER_FIRED_AFTER(tdata->tg_event))
			pltwhen = PyString_FromString("AFTER");
		else if (TRIGGER_FIRED_INSTEAD(tdata->tg_event))
			pltwhen = PyString_FromString("INSTEAD OF");
		else
		{
			elog(ERROR, "unrecognized WHEN tg_event: %u", tdata->tg_event);
			pltwhen = NULL;		/* keep compiler quiet */
		}
		PyDict_SetItemString(pltdata, "when", pltwhen);
		Py_DECREF(pltwhen);

		if (TRIGGER_FIRED_FOR_ROW(tdata->tg_event))
		{
			pltlevel = PyString_FromString("ROW");
			PyDict_SetItemString(pltdata, "level", pltlevel);
			Py_DECREF(pltlevel);

			if (TRIGGER_FIRED_BY_INSERT(tdata->tg_event))
			{
				pltevent = PyString_FromString("INSERT");

				PyDict_SetItemString(pltdata, "old", Py_None);
				pytnew = PLyDict_FromTuple(&(proc->result), tdata->tg_trigtuple,
										   tdata->tg_relation->rd_att);
				PyDict_SetItemString(pltdata, "new", pytnew);
				Py_DECREF(pytnew);
				*rv = tdata->tg_trigtuple;
			}
			else if (TRIGGER_FIRED_BY_DELETE(tdata->tg_event))
			{
				pltevent = PyString_FromString("DELETE");

				PyDict_SetItemString(pltdata, "new", Py_None);
				pytold = PLyDict_FromTuple(&(proc->result), tdata->tg_trigtuple,
										   tdata->tg_relation->rd_att);
				PyDict_SetItemString(pltdata, "old", pytold);
				Py_DECREF(pytold);
				*rv = tdata->tg_trigtuple;
			}
			else if (TRIGGER_FIRED_BY_UPDATE(tdata->tg_event))
			{
				pltevent = PyString_FromString("UPDATE");

				pytnew = PLyDict_FromTuple(&(proc->result), tdata->tg_newtuple,
										   tdata->tg_relation->rd_att);
				PyDict_SetItemString(pltdata, "new", pytnew);
				Py_DECREF(pytnew);
				pytold = PLyDict_FromTuple(&(proc->result), tdata->tg_trigtuple,
										   tdata->tg_relation->rd_att);
				PyDict_SetItemString(pltdata, "old", pytold);
				Py_DECREF(pytold);
				*rv = tdata->tg_newtuple;
			}
			else
			{
				elog(ERROR, "unrecognized OP tg_event: %u", tdata->tg_event);
				pltevent = NULL;	/* keep compiler quiet */
			}

			PyDict_SetItemString(pltdata, "event", pltevent);
			Py_DECREF(pltevent);
		}
		else if (TRIGGER_FIRED_FOR_STATEMENT(tdata->tg_event))
		{
			pltlevel = PyString_FromString("STATEMENT");
			PyDict_SetItemString(pltdata, "level", pltlevel);
			Py_DECREF(pltlevel);

			PyDict_SetItemString(pltdata, "old", Py_None);
			PyDict_SetItemString(pltdata, "new", Py_None);
			*rv = NULL;

			if (TRIGGER_FIRED_BY_INSERT(tdata->tg_event))
				pltevent = PyString_FromString("INSERT");
			else if (TRIGGER_FIRED_BY_DELETE(tdata->tg_event))
				pltevent = PyString_FromString("DELETE");
			else if (TRIGGER_FIRED_BY_UPDATE(tdata->tg_event))
				pltevent = PyString_FromString("UPDATE");
			else if (TRIGGER_FIRED_BY_TRUNCATE(tdata->tg_event))
				pltevent = PyString_FromString("TRUNCATE");
			else
			{
				elog(ERROR, "unrecognized OP tg_event: %u", tdata->tg_event);
				pltevent = NULL;	/* keep compiler quiet */
			}

			PyDict_SetItemString(pltdata, "event", pltevent);
			Py_DECREF(pltevent);
		}
		else
			elog(ERROR, "unrecognized LEVEL tg_event: %u", tdata->tg_event);

		if (tdata->tg_trigger->tgnargs)
		{
			/*
			 * all strings...
			 */
			int			i;
			PyObject   *pltarg;

			pltargs = PyList_New(tdata->tg_trigger->tgnargs);
			for (i = 0; i < tdata->tg_trigger->tgnargs; i++)
			{
				pltarg = PyString_FromString(tdata->tg_trigger->tgargs[i]);

				/*
				 * stolen, don't Py_DECREF
				 */
				PyList_SetItem(pltargs, i, pltarg);
			}
		}
		else
		{
			Py_INCREF(Py_None);
			pltargs = Py_None;
		}
		PyDict_SetItemString(pltdata, "args", pltargs);
		Py_DECREF(pltargs);
	}
	PG_CATCH();
	{
		Py_XDECREF(pltdata);
		PG_RE_THROW();
	}
	PG_END_TRY();

	return pltdata;
}
Ejemplo n.º 8
0
static PyObject* Majka_tags(const char * tag_string) {
  PyObject* tags = PyDict_New();
  char category = ' ';
  char tmp[] = {'\0', '\0'};
  PyObject* type = PyList_New(0);

  if (*tag_string == 'k') {
    ++tag_string;
    category = *tag_string;
    switch (category) {
      case '1':
        dict_set_string(tags, "pos", "substantive");
        break;
      case '2':
        dict_set_string(tags, "pos", "adjective");
        break;
      case '3':
        dict_set_string(tags, "pos", "pronomina");
        break;
      case '4':
        dict_set_string(tags, "pos", "numeral");
        break;
      case '5':
        dict_set_string(tags, "pos", "verb");
        break;
      case '6':
        dict_set_string(tags, "pos", "adverb");
        break;
      case '7':
        dict_set_string(tags, "pos", "preposition");
        break;
      case '8':
        dict_set_string(tags, "pos", "conjuction");
        break;
      case '9':
        dict_set_string(tags, "pos", "particle");
        break;
      case '0':
        dict_set_string(tags, "pos", "interjection");
        break;
      case 'I':
        dict_set_string(tags, "pos", "punctuation");
        break;
    }
    ++tag_string;
  }

  if (*tag_string == 'e') {
    ++tag_string;
    switch (*tag_string) {
      case 'A':
        PyDict_SetItemString(tags, "negation", Py_False);
        break;
      case 'N':
        PyDict_SetItemString(tags, "negation", Py_True);
        break;
    }
    ++tag_string;
  }

  if (*tag_string == 'a') {
    ++tag_string;
    switch (*tag_string) {
      case 'P':
        dict_set_string(tags, "aspect", "perfect");
        break;
      case 'I':
        dict_set_string(tags, "aspect", "imperfect");
        break;
    }
    ++tag_string;
  }

  if (*tag_string == 'm') {
    ++tag_string;
    switch (*tag_string) {
      case 'F':
        dict_set_string(tags, "mode", "infinitive");
        break;
      case 'I':
        dict_set_string(tags, "mode", "present indicative");
        break;
      case 'R':
        dict_set_string(tags, "mode", "imperative");
        break;
      case 'A':
        dict_set_string(tags, "mode", "active participle");
        break;
      case 'N':
        dict_set_string(tags, "mode", "passive participle");
        break;
      case 'S':
        dict_set_string(tags, "mode", "adverbium participle, present");
        break;
      case 'D':
        dict_set_string(tags, "mode", "adverbium participle, past");
        break;
      case 'B':
        dict_set_string(tags, "mode", "future indicative");
        break;
    }
    ++tag_string;
  }

  if (*tag_string == 'p') {
    ++tag_string;
    tmp[0] = *tag_string;
    dict_set_numeric(tags, "person", tmp);
    ++tag_string;
  }

  if (*tag_string == 'g') {
    ++tag_string;
    switch (*tag_string) {
      case 'M':
        dict_set_string(tags, "gender", "masculine");
        PyDict_SetItemString(tags, "animate", Py_True);
        break;
      case 'I':
        dict_set_string(tags, "gender", "masculine");
        PyDict_SetItemString(tags, "animate", Py_False);
        break;
      case 'F':
        dict_set_string(tags, "gender", "feminine");
        break;
      case 'N':
        dict_set_string(tags, "gender", "neuter");
        break;
    }
    ++tag_string;
  }

  if (*tag_string == 'n') {
    ++tag_string;
    switch (*tag_string) {
      case 'S':
        PyDict_SetItemString(tags, "singular", Py_True);
        break;
      case 'P':
        PyDict_SetItemString(tags, "plural", Py_True);
        break;
    }
    ++tag_string;
  }

  if (*tag_string == 'c') {
    ++tag_string;
    tmp[0] = *tag_string;
    dict_set_numeric(tags, "case", tmp);
    ++tag_string;
  }

  if (*tag_string == 'p') {  // Duplicate
    ++tag_string;
    tmp[0] = *tag_string;
    dict_set_numeric(tags, "person", tmp);
    ++tag_string;
  }

  if (*tag_string == 'd') {
    ++tag_string;
    tmp[0] = *tag_string;
    dict_set_numeric(tags, "degree", tmp);
    ++tag_string;
  }

  if (*tag_string == 'x') {
    ++tag_string;
    switch (category) {
      case '1':
        switch (*tag_string) {
          case 'P':
            list_append_string(type, "half");
            break;
          case 'F':
            list_append_string(type, "family surname");
            break;
        }
        break;
      case '3':
        switch (*tag_string) {
          case 'P':
            list_append_string(type, "personal");
            break;
          case 'O':
            list_append_string(type, "possessive");
            break;
          case 'D':
            list_append_string(type, "demonstrative");
            break;
          case 'T':
            list_append_string(type, "deliminative");
            break;
        }
        break;
      case '4':
        switch (*tag_string) {
          case 'C':
            list_append_string(type, "cardinal");
            break;
          case 'O':
            list_append_string(type, "ordinal");
            break;
          case 'R':
            list_append_string(type, "reproductive");
            break;
        }
        break;
      case '6':
        switch (*tag_string) {
          case 'D':
            list_append_string(type, "demonstrative");
            break;
          case 'T':
            list_append_string(type, "delimitative");
            break;
        }
        break;
      case '8':
        switch (*tag_string) {
          case 'C':
            list_append_string(type, "coordinate");
            break;
          case 'S':
            list_append_string(type, "subordinate");
            break;
        }
        break;
      case 'I':
        switch (*tag_string) {
          case '.':
            list_append_string(type, "stop");
            break;
          case ',':
            list_append_string(type, "semi-stop");
            break;
          case '"':
            list_append_string(type, "parenthesis");
            break;
          case '(':
            list_append_string(type, "opening");
            break;
          case ')':
            list_append_string(type, "closing");
            break;
          case '~':
            list_append_string(type, "other");
            break;
        }
        break;
    }
    ++tag_string;
  }

  if (*tag_string == 'y') {
    ++tag_string;
    switch (*tag_string) {
      case 'F':
        list_append_string(type, "reflective");
        break;
      case 'Q':
        list_append_string(type, "interrogative");
        break;
      case 'R':
        list_append_string(type, "relative");
        break;
      case 'N':
        list_append_string(type, "negative");
        break;
      case 'I':
        list_append_string(type, "indeterminate");
        break;
    }
    ++tag_string;
  }

  if (*tag_string == 't') {
    ++tag_string;
    switch (*tag_string) {
        case 'S':
            list_append_string(type, "status");
            break;
        case 'D':
            list_append_string(type, "modal");
            break;
        case 'T':
            list_append_string(type, "time");
            break;
        case 'A':
            list_append_string(type, "respect");
            break;
        case 'C':
            list_append_string(type, "reason");
            break;
        case 'L':
            list_append_string(type, "place");
            break;
        case 'M':
            list_append_string(type, "manner");
            break;
        case 'Q':
            list_append_string(type, "extent");
            break;
    }
    ++tag_string;
  }

  if (*tag_string == 'z') {
    ++tag_string;
    switch (*tag_string) {
      case 'S':
        dict_set_string(tags, "subclass", "-s enclictic");
        break;
      case 'Y':
        dict_set_string(tags, "subclass", "conditional");
        break;
      case 'A':
        dict_set_string(tags, "subclass", "abbreviation");
        break;
    }
    ++tag_string;
  }

  if (*tag_string == 'w') {
    ++tag_string;
    switch (*tag_string) {
      case 'B':
        dict_set_string(tags, "style", "poeticism");
        break;
      case 'H':
        dict_set_string(tags, "style", "conversational");
        break;
      case 'N':
        dict_set_string(tags, "style", "dialectal");
        break;
      case 'R':
        dict_set_string(tags, "style", "rare");
        break;
      case 'Z':
        dict_set_string(tags, "style", "obsolete");
        break;
    }
    ++tag_string;
  }

  if (*tag_string == '~') {
    ++tag_string;
    tmp[0] = *tag_string;
    dict_set_numeric(tags, "frequency", tmp);
    ++tag_string;
  }

  if (PyList_Size(type)) {
    dict_set(tags, "type", type);
  } else {
    Py_DECREF(type);
  }

  if (*tag_string) {
    dict_set_string(tags, "other", tag_string);
  }

  return tags;
}
Ejemplo n.º 9
0
/*
 * Return a list of tuples for network I/O statistics.
 */
static PyObject *
psutil_net_io_counters(PyObject *self, PyObject *args)
{
    kstat_ctl_t    *kc = NULL;
    kstat_t *ksp;
    kstat_named_t *rbytes, *wbytes, *rpkts, *wpkts, *ierrs, *oerrs;

    PyObject *py_retdict = PyDict_New();
    PyObject *py_ifc_info = NULL;

    if (py_retdict == NULL)
        return NULL;
    kc = kstat_open();
    if (kc == NULL)
        goto error;

    ksp = kc->kc_chain;
    while (ksp != NULL) {
        if (ksp->ks_type != KSTAT_TYPE_NAMED)
            goto next;
        if (strcmp(ksp->ks_class, "net") != 0)
            goto next;
        /*
        // XXX "lo" (localhost) interface makes kstat_data_lookup() fail
        // (maybe because "ifconfig -a" says it's a virtual interface?).
        if ((strcmp(ksp->ks_module, "link") != 0) &&
            (strcmp(ksp->ks_module, "lo") != 0)) {
            goto skip;
        */
        if ((strcmp(ksp->ks_module, "link") != 0)) {
            goto next;
        }

        if (kstat_read(kc, ksp, NULL) == -1) {
            errno = 0;
            continue;
        }

        rbytes = (kstat_named_t *)kstat_data_lookup(ksp, "rbytes");
        wbytes = (kstat_named_t *)kstat_data_lookup(ksp, "obytes");
        rpkts = (kstat_named_t *)kstat_data_lookup(ksp, "ipackets");
        wpkts = (kstat_named_t *)kstat_data_lookup(ksp, "opackets");
        ierrs = (kstat_named_t *)kstat_data_lookup(ksp, "ierrors");
        oerrs = (kstat_named_t *)kstat_data_lookup(ksp, "oerrors");

        if ((rbytes == NULL) || (wbytes == NULL) || (rpkts == NULL) ||
                (wpkts == NULL) || (ierrs == NULL) || (oerrs == NULL))
        {
            PyErr_SetString(PyExc_RuntimeError, "kstat_data_lookup() failed");
            goto error;
        }

#if defined(_INT64_TYPE)
        py_ifc_info = Py_BuildValue("(KKKKkkii)",
                                    rbytes->value.ui64,
                                    wbytes->value.ui64,
                                    rpkts->value.ui64,
                                    wpkts->value.ui64,
                                    ierrs->value.ui32,
                                    oerrs->value.ui32,
#else
        py_ifc_info = Py_BuildValue("(kkkkkkii)",
                                    rbytes->value.ui32,
                                    wbytes->value.ui32,
                                    rpkts->value.ui32,
                                    wpkts->value.ui32,
                                    ierrs->value.ui32,
                                    oerrs->value.ui32,
#endif
                                    0,  // dropin not supported
                                    0   // dropout not supported
                                   );
        if (!py_ifc_info)
            goto error;
        if (PyDict_SetItemString(py_retdict, ksp->ks_name, py_ifc_info))
            goto error;
        Py_DECREF(py_ifc_info);
        goto next;

next:
        ksp = ksp->ks_next;
    }

    kstat_close(kc);
    return py_retdict;

error:
    Py_XDECREF(py_ifc_info);
    Py_DECREF(py_retdict);
    if (kc != NULL)
        kstat_close(kc);
    return NULL;
}
Ejemplo n.º 10
0
/* Returns 0 on error (no new refs), 1 on success */
static int
setup_context(Py_ssize_t stack_level, PyObject **filename, int *lineno,
              PyObject **module, PyObject **registry)
{
    PyObject *globals;

    /* Setup globals and lineno. */
    PyFrameObject *f = PyThreadState_GET()->frame;
    while (--stack_level > 0 && f != NULL)
        f = f->f_back;

    if (f == NULL) {
        globals = PyThreadState_Get()->interp->sysdict;
        *lineno = 1;
    }
    else {
        globals = f->f_globals;
        *lineno = PyFrame_GetLineNumber(f);
    }

    *module = NULL;

    /* Setup registry. */
    assert(globals != NULL);
    assert(PyDict_Check(globals));
    *registry = PyDict_GetItemString(globals, "__warningregistry__");
    if (*registry == NULL) {
        int rc;

        *registry = PyDict_New();
        if (*registry == NULL)
            return 0;

         rc = PyDict_SetItemString(globals, "__warningregistry__", *registry);
         if (rc < 0)
            goto handle_error;
    }
    else
        Py_INCREF(*registry);

    /* Setup module. */
    *module = PyDict_GetItemString(globals, "__name__");
    if (*module == NULL) {
        *module = PyUnicode_FromString("<string>");
        if (*module == NULL)
            goto handle_error;
    }
    else
        Py_INCREF(*module);

    /* Setup filename. */
    *filename = PyDict_GetItemString(globals, "__file__");
    if (*filename != NULL && PyUnicode_Check(*filename)) {
        Py_ssize_t len;
        int kind;
        void *data;

        if (PyUnicode_READY(*filename))
            goto handle_error;

        len = PyUnicode_GetLength(*filename);
        kind = PyUnicode_KIND(*filename);
        data = PyUnicode_DATA(*filename);

#define ascii_lower(c) ((c <= 127) ? Py_TOLOWER(c) : 0)
        /* if filename.lower().endswith((".pyc", ".pyo")): */
        if (len >= 4 &&
            PyUnicode_READ(kind, data, len-4) == '.' &&
            ascii_lower(PyUnicode_READ(kind, data, len-3)) == 'p' &&
            ascii_lower(PyUnicode_READ(kind, data, len-2)) == 'y' &&
            (ascii_lower(PyUnicode_READ(kind, data, len-1)) == 'c' ||
                ascii_lower(PyUnicode_READ(kind, data, len-1)) == 'o'))
        {
            *filename = PyUnicode_Substring(*filename, 0,
                                            PyUnicode_GET_LENGTH(*filename)-1);
            if (*filename == NULL)
                goto handle_error;
        }
        else
            Py_INCREF(*filename);
    }
    else {
        *filename = NULL;
        if (*module != Py_None && PyUnicode_CompareWithASCIIString(*module, "__main__") == 0) {
            PyObject *argv = _PySys_GetObjectId(&PyId_argv);
            /* PyList_Check() is needed because sys.argv is set to None during
               Python finalization */
            if (argv != NULL && PyList_Check(argv) && PyList_Size(argv) > 0) {
                int is_true;
                *filename = PyList_GetItem(argv, 0);
                Py_INCREF(*filename);
                /* If sys.argv[0] is false, then use '__main__'. */
                is_true = PyObject_IsTrue(*filename);
                if (is_true < 0) {
                    Py_DECREF(*filename);
                    goto handle_error;
                }
                else if (!is_true) {
                    Py_DECREF(*filename);
                    *filename = PyUnicode_FromString("__main__");
                    if (*filename == NULL)
                        goto handle_error;
                }
            }
            else {
                /* embedded interpreters don't have sys.argv, see bug #839151 */
                *filename = PyUnicode_FromString("__main__");
                if (*filename == NULL)
                    goto handle_error;
            }
        }
        if (*filename == NULL) {
            *filename = *module;
            Py_INCREF(*filename);
        }
    }

    return 1;

 handle_error:
    /* filename not XDECREF'ed here as there is no way to jump here with a
       dangling reference. */
    Py_XDECREF(*registry);
    Py_XDECREF(*module);
    return 0;
}
Ejemplo n.º 11
0
 PyObject* xPyDict_New(void) {
   PyObject* dict = PyDict_New();
   if (!dict)
     notEnoughMemory();
   return dict;
 }
Ejemplo n.º 12
0
int yara_callback(
    int message,
    YR_RULE* rule,
    void* data)
{
  YR_STRING* string;
  YR_MATCH* m;
  YR_META* meta;
  char* tag_name;
  size_t tag_length;

  PyObject* tag_list = NULL;
  PyObject* string_list = NULL;
  PyObject* meta_list = NULL;
  PyObject* match;
  PyObject* callback_dict;
  PyObject* object;
  PyObject* tuple;
  PyObject* matches = ((CALLBACK_DATA*) data)->matches;
  PyObject* callback = ((CALLBACK_DATA*) data)->callback;
  PyObject* callback_result;
  PyGILState_STATE gil_state;

  int result = CALLBACK_CONTINUE;

  if (message == CALLBACK_MSG_SCAN_FINISHED)
    return CALLBACK_CONTINUE;

  if (message == CALLBACK_MSG_RULE_NOT_MATCHING && callback == NULL)
    return CALLBACK_CONTINUE;

  gil_state = PyGILState_Ensure();

  tag_list = PyList_New(0);
  string_list = PyList_New(0);
  meta_list = PyDict_New();

  if (tag_list == NULL || string_list == NULL || meta_list == NULL)
  {
    Py_XDECREF(tag_list);
    Py_XDECREF(string_list);
    Py_XDECREF(meta_list);
    PyGILState_Release(gil_state);

    return CALLBACK_ERROR;
  }

  tag_name = rule->tags;
  tag_length = tag_name != NULL ? strlen(tag_name) : 0;

  while (tag_length > 0)
  {
    object = PY_STRING(tag_name);
    PyList_Append(tag_list, object);
    Py_DECREF(object);

    tag_name += tag_length + 1;
    tag_length = strlen(tag_name);
  }

  meta = rule->metas;

  while(!META_IS_NULL(meta))
  {
    if (meta->type == META_TYPE_INTEGER)
      object = Py_BuildValue("I", meta->integer);
    else if (meta->type == META_TYPE_BOOLEAN)
      object = PyBool_FromLong(meta->integer);
    else
      object = PY_STRING(meta->string);

    PyDict_SetItemString(meta_list, meta->identifier, object);
    Py_DECREF(object);

    meta++;
  }

  string = rule->strings;

  while (!STRING_IS_NULL(string))
  {
    if (STRING_FOUND(string))
    {
      m = STRING_MATCHES(string).head;

      while (m != NULL)
      {
        object = PyBytes_FromStringAndSize((char*) m->data, m->length);

        tuple = Py_BuildValue(
            "(L,s,O)",
            m->offset,
            string->identifier,
            object);

        PyList_Append(string_list, tuple);

        Py_DECREF(object);
        Py_DECREF(tuple);

        m = m->next;
      }
    }

    string++;
  }

  if (message == CALLBACK_MSG_RULE_MATCHING)
  {
    match = Match_NEW(
        rule->identifier,
        rule->ns->name,
        tag_list,
        meta_list,
        string_list);

    if (match != NULL)
    {
      PyList_Append(matches, match);
      Py_DECREF(match);
    }
    else
    {
      Py_DECREF(tag_list);
      Py_DECREF(string_list);
      Py_DECREF(meta_list);
      PyGILState_Release(gil_state);

      return CALLBACK_ERROR;
    }
  }

  if (callback != NULL)
  {
    Py_INCREF(callback);

    callback_dict = PyDict_New();

    object = PyBool_FromLong(message == CALLBACK_MSG_RULE_MATCHING);
    PyDict_SetItemString(callback_dict, "matches", object);
    Py_DECREF(object);

    object = PY_STRING(rule->identifier);
    PyDict_SetItemString(callback_dict, "rule", object);
    Py_DECREF(object);

    object = PY_STRING(rule->ns->name);
    PyDict_SetItemString(callback_dict, "namespace", object);
    Py_DECREF(object);

    PyDict_SetItemString(callback_dict, "tags", tag_list);
    PyDict_SetItemString(callback_dict, "meta", meta_list);
    PyDict_SetItemString(callback_dict, "strings", string_list);

    callback_result = PyObject_CallFunctionObjArgs(
        callback,
        callback_dict,
        NULL);

    if (callback_result != NULL)
    {
      #if PY_MAJOR_VERSION >= 3
      if (PyLong_Check(callback_result))
      #else
      if (PyLong_Check(callback_result) || PyInt_Check(callback_result))
      #endif
      {
        result = (int) PyLong_AsLong(callback_result);
      }

      Py_DECREF(callback_result);
    }
    else
    {
      result = CALLBACK_ERROR;
    }

    Py_DECREF(callback_dict);
    Py_DECREF(callback);
  }

  Py_DECREF(tag_list);
  Py_DECREF(string_list);
  Py_DECREF(meta_list);
  PyGILState_Release(gil_state);

  return result;
}
Ejemplo n.º 13
0
static int
PyGcc_init_gcc_module(struct plugin_name_args *plugin_info)
{
    int i;

    if (!PyGcc_globals.module) {
        return 0;
    }

    /* Set up int constants for each of the enum plugin_event values: */
    #define DEFEVENT(NAME) \
       PyModule_AddIntMacro(PyGcc_globals.module, NAME);
    # include "plugin.def"
    # undef DEFEVENT

    PyGcc_globals.argument_dict = PyDict_New();
    if (!PyGcc_globals.argument_dict) {
        return 0;
    }

    PyGcc_globals.argument_tuple = PyTuple_New(plugin_info->argc);
    if (!PyGcc_globals.argument_tuple) {
        return 0;
    }

    /* PySys_SetArgvEx(plugin_info->argc, plugin_info->argv, 0); */
    for (i=0; i<plugin_info->argc; i++) {
	struct plugin_argument *arg = &plugin_info->argv[i];
        PyObject *key;
        PyObject *value;
	PyObject *pair;
      
	key = PyGccString_FromString(arg->key);
	if (arg->value) {
            value = PyGccString_FromString(plugin_info->argv[i].value);
	} else {
  	    value = Py_None;
	}
        PyDict_SetItem(PyGcc_globals.argument_dict, key, value);
	// FIXME: ref counts?

	pair = Py_BuildValue("(s, s)", arg->key, arg->value);
	if (!pair) {
  	    return 1;
	}
        PyTuple_SetItem(PyGcc_globals.argument_tuple, i, pair);

    }
    PyModule_AddObject(PyGcc_globals.module, "argument_dict", PyGcc_globals.argument_dict);
    PyModule_AddObject(PyGcc_globals.module, "argument_tuple", PyGcc_globals.argument_tuple);

    /* Pass properties: */
    PyModule_AddIntMacro(PyGcc_globals.module, PROP_gimple_any);
    PyModule_AddIntMacro(PyGcc_globals.module, PROP_gimple_lcf);
    PyModule_AddIntMacro(PyGcc_globals.module, PROP_gimple_leh);
    PyModule_AddIntMacro(PyGcc_globals.module, PROP_cfg);
#if (GCC_VERSION >= 4008)
    /* PROP_referenced_vars went away in GCC 4.8 (in r190067) */
#else
    PyModule_AddIntMacro(PyGcc_globals.module, PROP_referenced_vars);
#endif
    PyModule_AddIntMacro(PyGcc_globals.module, PROP_ssa);
    PyModule_AddIntMacro(PyGcc_globals.module, PROP_no_crit_edges);
    PyModule_AddIntMacro(PyGcc_globals.module, PROP_rtl);
    PyModule_AddIntMacro(PyGcc_globals.module, PROP_gimple_lomp);
    PyModule_AddIntMacro(PyGcc_globals.module, PROP_cfglayout);
    PyModule_AddIntMacro(PyGcc_globals.module, PROP_gimple_lcx);

    PyModule_AddIntMacro(PyGcc_globals.module, GCC_VERSION);

    /* Success: */
    return 1;
}
Ejemplo n.º 14
0
/**
 * Initializes data structures for the _watchdog_fsevents Python module.
 * This function is called by Python initializer functions.
 */
void
Watchdog_FSEvents_Init(void)
{
    g__runloop_for_emitter = PyDict_New();
    g__stream_for_watch = PyDict_New();
}
Ejemplo n.º 15
0
PyObject * AerospikeException_New(void) {
	static struct PyModuleDef moduledef = { PyModuleDef_HEAD_INIT,
			"aerospike.exception", /* m_name */
			"Exception objects", /* m_doc */
			-1, /* m_size */
			NULL, /* m_methods */
			NULL, /* m_reload */
			NULL, /* m_traverse */
			NULL, /* m_clear */
			NULL, /* m_free */
	};
	module = PyModule_Create(&moduledef);

	struct exceptions exceptions_array;

	memset(&exceptions_array, 0, sizeof(exceptions_array));

	struct server_exceptions_struct server_array = { 
		{&exceptions_array.InvalidRequest, &exceptions_array.ServerFull, &exceptions_array.NoXDR, 
			&exceptions_array.UnsupportedFeature, &exceptions_array.DeviceOverload, &exceptions_array.NamespaceNotFound, 
			&exceptions_array.ForbiddenError, &exceptions_array.QueryError, &exceptions_array.ClusterError},
		{"InvalidRequest", "ServerFull", "NoXDR", "UnsupportedFeature", "DeviceOverload", "NamespaceNotFound", 
			"ForbiddenError", "QueryError", "ClusterError"},
		{AEROSPIKE_ERR_REQUEST_INVALID, AEROSPIKE_ERR_SERVER_FULL, AEROSPIKE_ERR_NO_XDR, 
			AEROSPIKE_ERR_UNSUPPORTED_FEATURE, AEROSPIKE_ERR_DEVICE_OVERLOAD, AEROSPIKE_ERR_NAMESPACE_NOT_FOUND,  
			AEROSPIKE_ERR_FAIL_FORBIDDEN, AEROSPIKE_ERR_QUERY, AEROSPIKE_ERR_CLUSTER}
	};

	struct record_exceptions_struct record_array = { 
		{&exceptions_array.RecordKeyMismatch, &exceptions_array.RecordNotFound, &exceptions_array.RecordGenerationError, 
			&exceptions_array.RecordExistsError, &exceptions_array.RecordTooBig, &exceptions_array.RecordBusy, 
			&exceptions_array.BinNameError, &exceptions_array.BinExistsError, &exceptions_array.BinNotFound, 
			&exceptions_array.BinIncompatibleType},
		{"RecordKeyMismatch", "RecordNotFound", "RecordGenerationError", "RecordExistsError", "RecordTooBig", "RecordBusy", 
			"BinNameError", "BinExistsError", "BinNotFound", "BinIncompatibleType"},
		{AEROSPIKE_ERR_RECORD_KEY_MISMATCH, AEROSPIKE_ERR_RECORD_NOT_FOUND, AEROSPIKE_ERR_RECORD_GENERATION, 
			AEROSPIKE_ERR_RECORD_EXISTS, AEROSPIKE_ERR_RECORD_TOO_BIG, AEROSPIKE_ERR_RECORD_BUSY, 
			AEROSPIKE_ERR_BIN_NAME, AEROSPIKE_ERR_BIN_EXISTS, AEROSPIKE_ERR_BIN_NOT_FOUND, 
			AEROSPIKE_ERR_BIN_INCOMPATIBLE_TYPE}
	};

	struct index_exceptions_struct index_array = { 
		{&exceptions_array.IndexNotFound, &exceptions_array.IndexFoundError, &exceptions_array.IndexOOM, 
			&exceptions_array.IndexNotReadable, &exceptions_array.IndexNameMaxLen, &exceptions_array.IndexNameMaxCount},
		{"IndexNotFound", "IndexFoundError", "IndexOOM", "IndexNotReadable", "IndexNameMaxLen", "IndexNameMaxCount"},
		{AEROSPIKE_ERR_INDEX_NOT_FOUND, AEROSPIKE_ERR_INDEX_FOUND, AEROSPIKE_ERR_INDEX_OOM, 
			AEROSPIKE_ERR_INDEX_NOT_READABLE, AEROSPIKE_ERR_INDEX_NAME_MAXLEN, AEROSPIKE_ERR_INDEX_MAXCOUNT}
	};

	struct admin_exceptions_struct admin_array = { 
		{&exceptions_array.SecurityNotSupported, &exceptions_array.SecurityNotEnabled, &exceptions_array.SecuritySchemeNotSupported, 
			&exceptions_array.InvalidCommand, &exceptions_array.InvalidField, &exceptions_array.IllegalState, 
			&exceptions_array.InvalidUser, &exceptions_array.UserExistsError, &exceptions_array.InvalidPassword, 
			&exceptions_array.ExpiredPassword, &exceptions_array.ForbiddenPassword, &exceptions_array.InvalidCredential, 
			&exceptions_array.InvalidRole, &exceptions_array.RoleExistsError, &exceptions_array.RoleViolation, 
			&exceptions_array.InvalidPrivilege, &exceptions_array.NotAuthenticated},
		{"SecurityNotSupported", "SecurityNotEnabled", "SecuritySchemeNotSupported", "InvalidCommand", "InvalidField", 
			"IllegalState", "InvalidUser", "UserExistsError", "InvalidPassword", "ExpiredPassword", "ForbiddenPassword", 
			"InvalidCredential", "InvalidRole", "RoleExistsError", "RoleViolation", "InvalidPrivilege", "NotAuthenticated"},
		{AEROSPIKE_SECURITY_NOT_SUPPORTED, AEROSPIKE_SECURITY_NOT_ENABLED, AEROSPIKE_SECURITY_SCHEME_NOT_SUPPORTED, 
			AEROSPIKE_INVALID_COMMAND, AEROSPIKE_INVALID_FIELD, AEROSPIKE_ILLEGAL_STATE, 
			AEROSPIKE_INVALID_USER, AEROSPIKE_USER_ALREADY_EXISTS, AEROSPIKE_INVALID_PASSWORD, 
			AEROSPIKE_EXPIRED_PASSWORD, AEROSPIKE_FORBIDDEN_PASSWORD, AEROSPIKE_INVALID_CREDENTIAL, 
			AEROSPIKE_INVALID_ROLE, AEROSPIKE_ROLE_ALREADY_EXISTS, AEROSPIKE_ROLE_VIOLATION,  
			AEROSPIKE_INVALID_PRIVILEGE, AEROSPIKE_NOT_AUTHENTICATED}
	};

	struct ldt_exceptions_struct ldt_array = { 
		{&exceptions_array.LargeItemNotFound, &exceptions_array.LDTInternalError, &exceptions_array.LDTNotFound, 
			&exceptions_array.LDTUniqueKeyError, &exceptions_array.LDTInsertError, &exceptions_array.LDTSearchError, 
			&exceptions_array.LDTDeleteError, &exceptions_array.LDTInputParamError, &exceptions_array.LDTTypeMismatch, 
			&exceptions_array.LDTBinNameNull, &exceptions_array.LDTBinNameNotString, &exceptions_array.LDTBinNameTooLong, 
			&exceptions_array.LDTTooManyOpenSubrecs, &exceptions_array.LDTTopRecNotFound, &exceptions_array.LDTSubRecNotFound, 
			&exceptions_array.LDTBinNotFound, &exceptions_array.LDTBinExistsError, &exceptions_array.LDTBinDamaged, 
			&exceptions_array.LDTSubrecPoolDamaged, &exceptions_array.LDTSubrecDamaged, &exceptions_array.LDTSubrecOpenError, 
			&exceptions_array.LDTSubrecUpdateError, &exceptions_array.LDTSubrecCreateError, &exceptions_array.LDTSubrecDeleteError, 
			&exceptions_array.LDTSubrecCloseError, &exceptions_array.LDTToprecUpdateError, &exceptions_array.LDTToprecCreateError, 
			&exceptions_array.LDTFilterFunctionBad, &exceptions_array.LDTFilterFunctionNotFound, &exceptions_array.LDTKeyFunctionBad, 
			&exceptions_array.LDTKeyFunctionNotFound, &exceptions_array.LDTTransFunctionBad, &exceptions_array.LDTTransFunctionNotFound, 
			&exceptions_array.LDTUntransFunctionBad, &exceptions_array.LDTUntransFunctionNotFound, &exceptions_array.LDTUserModuleBad, 
			&exceptions_array.LDTUserModuleNotFound},
		{"LargeItemNotFound", "LDTInternalError", "LDTNotFound", "LDTUniqueKeyError", "LDTInsertError", "LDTSearchError", 
			"LDTDeleteError", "LDTInputParamError", "LDTTypeMismatch", "LDTBinNameNull", "LDTBinNameNotString", "LDTBinNameTooLong", 
			"LDTTooManyOpenSubrecs", "LDTTopRecNotFound", "LDTSubRecNotFound", "LDTBinNotFound", "LDTBinExistsError", "LDTBinDamaged", 
			"LDTSubrecPoolDamaged", "LDTSubrecDamaged", "LDTSubrecOpenError", "LDTSubrecUpdateError", "LDTSubrecCreateError", 
			"LDTSubrecDeleteError", "LDTSubrecCloseError", "LDTToprecUpdateError", "LDTToprecCreateError", "LDTFilterFunctionBad",
			"LDTFilterFunctionNotFound", "LDTKeyFunctionBad", "LDTKeyFunctionNotFound", "LDTTransFunctionBad", "LDTTransFunctionNotFound", 
			"LDTUntransFunctionBad", "LDTUntransFunctionNotFound", "LDTUserModuleBad", "LDTUserModuleNotFound"},
		{AEROSPIKE_ERR_LARGE_ITEM_NOT_FOUND, AEROSPIKE_ERR_LDT_INTERNAL, AEROSPIKE_ERR_LDT_NOT_FOUND, 
			AEROSPIKE_ERR_LDT_UNIQUE_KEY, AEROSPIKE_ERR_LDT_INSERT, AEROSPIKE_ERR_LDT_SEARCH, 
			AEROSPIKE_ERR_LDT_DELETE, AEROSPIKE_ERR_LDT_INPUT_PARM, AEROSPIKE_ERR_LDT_TYPE_MISMATCH, 
			AEROSPIKE_ERR_LDT_NULL_BIN_NAME, AEROSPIKE_ERR_LDT_BIN_NAME_NOT_STRING, AEROSPIKE_ERR_LDT_BIN_NAME_TOO_LONG, 
			AEROSPIKE_ERR_LDT_TOO_MANY_OPEN_SUBRECS, AEROSPIKE_ERR_LDT_TOP_REC_NOT_FOUND, AEROSPIKE_ERR_LDT_SUB_REC_NOT_FOUND, 
			AEROSPIKE_ERR_LDT_BIN_DOES_NOT_EXIST, AEROSPIKE_ERR_LDT_BIN_ALREADY_EXISTS, AEROSPIKE_ERR_LDT_BIN_DAMAGED, 
			AEROSPIKE_ERR_LDT_SUBREC_POOL_DAMAGED, AEROSPIKE_ERR_LDT_SUBREC_DAMAGED, AEROSPIKE_ERR_LDT_SUBREC_OPEN, 
			AEROSPIKE_ERR_LDT_SUBREC_UPDATE, AEROSPIKE_ERR_LDT_SUBREC_CREATE, AEROSPIKE_ERR_LDT_SUBREC_DELETE, 
			AEROSPIKE_ERR_LDT_SUBREC_CLOSE, AEROSPIKE_ERR_LDT_TOPREC_UPDATE, AEROSPIKE_ERR_LDT_TOPREC_CREATE, 
			AEROSPIKE_ERR_LDT_FILTER_FUNCTION_BAD, AEROSPIKE_ERR_LDT_FILTER_FUNCTION_NOT_FOUND, AEROSPIKE_ERR_LDT_KEY_FUNCTION_BAD, 
			AEROSPIKE_ERR_LDT_KEY_FUNCTION_NOT_FOUND, AEROSPIKE_ERR_LDT_TRANS_FUNCTION_BAD, AEROSPIKE_ERR_LDT_TRANS_FUNCTION_NOT_FOUND, 
			AEROSPIKE_ERR_LDT_UNTRANS_FUNCTION_BAD, AEROSPIKE_ERR_LDT_UNTRANS_FUNCTION_NOT_FOUND, AEROSPIKE_ERR_LDT_USER_MODULE_BAD, 
			AEROSPIKE_ERR_LDT_USER_MODULE_NOT_FOUND}
	};

	PyObject *py_code = NULL;
	PyObject *py_dict = PyDict_New();
	PyDict_SetItemString(py_dict, "code", Py_None);
	PyDict_SetItemString(py_dict, "file", Py_None);
	PyDict_SetItemString(py_dict, "msg", Py_None);
	PyDict_SetItemString(py_dict, "line", Py_None);

	exceptions_array.AerospikeError = PyErr_NewException("exception.AerospikeError", NULL, py_dict);
	Py_INCREF(exceptions_array.AerospikeError);
	Py_DECREF(py_dict);
	PyModule_AddObject(module, "AerospikeError", exceptions_array.AerospikeError);
	PyObject_SetAttrString(exceptions_array.AerospikeError, "code", Py_None);

	exceptions_array.ClientError = PyErr_NewException("exception.ClientError", exceptions_array.AerospikeError, NULL);
	Py_INCREF(exceptions_array.ClientError);
	PyModule_AddObject(module, "ClientError", exceptions_array.ClientError);
	py_code = PyInt_FromLong(AEROSPIKE_ERR_CLIENT);
	PyObject_SetAttrString(exceptions_array.ClientError, "code", py_code);
	Py_DECREF(py_code);

	exceptions_array.ServerError = PyErr_NewException("exception.ServerError", exceptions_array.AerospikeError, NULL);
	Py_INCREF(exceptions_array.ServerError);
	PyModule_AddObject(module, "ServerError", exceptions_array.ServerError);
	py_code = PyInt_FromLong(AEROSPIKE_ERR_SERVER);
	PyObject_SetAttrString(exceptions_array.ServerError, "code", py_code);
	Py_DECREF(py_code);

	exceptions_array.TimeoutError = PyErr_NewException("exception.TimeoutError", exceptions_array.AerospikeError, NULL);
	Py_INCREF(exceptions_array.TimeoutError);
	PyModule_AddObject(module, "TimeoutError", exceptions_array.TimeoutError);
	py_code = PyInt_FromLong(AEROSPIKE_ERR_TIMEOUT);
	PyObject_SetAttrString(exceptions_array.TimeoutError, "code", py_code);
	Py_DECREF(py_code);

	//Client Exceptions
	exceptions_array.ParamError = PyErr_NewException("exception.ParamError", exceptions_array.ClientError, NULL);
	Py_INCREF(exceptions_array.ParamError);
	PyModule_AddObject(module, "ParamError", exceptions_array.ParamError);
	py_code = PyInt_FromLong(AEROSPIKE_ERR_PARAM);
	PyObject_SetAttrString(exceptions_array.ParamError, "code", py_code);
	Py_DECREF(py_code);

	exceptions_array.InvalidHostError = PyErr_NewException("exception.InvalidHostError", exceptions_array.ClientError, NULL);
	Py_INCREF(exceptions_array.InvalidHostError);
	PyModule_AddObject(module, "InvalidHostError", exceptions_array.InvalidHostError);
	py_code = PyInt_FromLong(AEROSPIKE_ERR_INVALID_HOST);
	PyObject_SetAttrString(exceptions_array.InvalidHostError, "code", py_code);
	Py_DECREF(py_code);

	//Server Exceptions
	int count = sizeof(server_array.server_exceptions)/sizeof(server_array.server_exceptions[0]);
	int i;
	PyObject **current_exception;
	for(i=0; i < count; i++) {
		current_exception = server_array.server_exceptions[i];
		char * name = server_array.server_exceptions_name[i];
		char prefix[40] = "exception.";
		*current_exception = PyErr_NewException(strcat(prefix, name), exceptions_array.ServerError, NULL);
		Py_INCREF(*current_exception);
		PyModule_AddObject(module, name, *current_exception);
		PyObject *py_code = PyInt_FromLong(server_array.server_exceptions_codes[i]);
		PyObject_SetAttrString(*current_exception, "code", py_code);
		Py_DECREF(py_code);
	}

	exceptions_array.ClusterChangeError = PyErr_NewException("exception.ClusterChangeError", exceptions_array.ClusterError, NULL);
	Py_INCREF(exceptions_array.ClusterChangeError);
	PyModule_AddObject(module, "ClusterChangeError", exceptions_array.ClusterChangeError);
	py_code = PyInt_FromLong(AEROSPIKE_ERR_CLUSTER_CHANGE);
	PyObject_SetAttrString(exceptions_array.ClusterChangeError, "code", py_code);
	Py_DECREF(py_code);

	//Record exceptions
	PyObject *py_record_dict = PyDict_New();
	PyDict_SetItemString(py_record_dict, "key", Py_None);
	PyDict_SetItemString(py_record_dict, "bin", Py_None);

	exceptions_array.RecordError = PyErr_NewException("exception.RecordError", exceptions_array.ServerError, py_record_dict);
	Py_INCREF(exceptions_array.RecordError);
	Py_DECREF(py_record_dict);
	PyModule_AddObject(module, "RecordError", exceptions_array.RecordError);

	//int count = sizeof(record_exceptions)/sizeof(record_exceptions[0]);
	count = sizeof(record_array.record_exceptions)/sizeof(record_array.record_exceptions[0]);
	for(i=0; i < count; i++) {
		current_exception = record_array.record_exceptions[i];
		char * name = record_array.record_exceptions_name[i];
		char prefix[40] = "exception.";
		*current_exception = PyErr_NewException(strcat(prefix, name), exceptions_array.RecordError, NULL);
		Py_INCREF(*current_exception);
		PyModule_AddObject(module, name, *current_exception);
		PyObject *py_code = PyInt_FromLong(record_array.record_exceptions_codes[i]);
		PyObject_SetAttrString(*current_exception, "code", py_code);
		Py_DECREF(py_code);
	}

	//Index exceptions
	PyObject *py_index_dict = PyDict_New();
	PyDict_SetItemString(py_index_dict, "name", Py_None);

	exceptions_array.IndexError = PyErr_NewException("exception.IndexError", exceptions_array.ServerError, py_index_dict);
	Py_INCREF(exceptions_array.IndexError);
	Py_DECREF(py_index_dict);
	PyModule_AddObject(module, "IndexError", exceptions_array.IndexError);

	count = sizeof(index_array.index_exceptions)/sizeof(index_array.index_exceptions[0]);
	for(i=0; i < count; i++) {
		current_exception = index_array.index_exceptions[i];
		char * name = index_array.index_exceptions_name[i];
		char prefix[40] = "exception.";
		*current_exception = PyErr_NewException(strcat(prefix, name), exceptions_array.IndexError, NULL);
		Py_INCREF(*current_exception);
		PyModule_AddObject(module, name, *current_exception);
		PyObject *py_code = PyInt_FromLong(index_array.index_exceptions_codes[i]);
		PyObject_SetAttrString(*current_exception, "code", py_code);
		Py_DECREF(py_code);
	}

	//UDF exceptions
	PyObject *py_udf_dict = PyDict_New();
	PyDict_SetItemString(py_udf_dict, "module", Py_None);	
	PyDict_SetItemString(py_udf_dict, "func", Py_None);	

	exceptions_array.UDFError = PyErr_NewException("exception.UDFError", exceptions_array.ServerError, py_udf_dict);
	Py_INCREF(exceptions_array.UDFError);
	Py_DECREF(py_udf_dict);
	PyModule_AddObject(module, "UDFError", exceptions_array.UDFError);
	py_code = PyInt_FromLong(AEROSPIKE_ERR_UDF);
	PyObject_SetAttrString(exceptions_array.UDFError, "code", py_code);
	Py_DECREF(py_code);

	exceptions_array.UDFNotFound = PyErr_NewException("exception.UDFNotFound", exceptions_array.UDFError, NULL);
	Py_INCREF(exceptions_array.UDFNotFound);
	PyModule_AddObject(module, "UDFNotFound", exceptions_array.UDFNotFound);
	py_code = PyInt_FromLong(AEROSPIKE_ERR_UDF_NOT_FOUND);
	PyObject_SetAttrString(exceptions_array.UDFNotFound, "code", py_code);
	Py_DECREF(py_code);

	exceptions_array.LuaFileNotFound = PyErr_NewException("exception.LuaFileNotFound", exceptions_array.UDFError, NULL);
	Py_INCREF(exceptions_array.LuaFileNotFound);
	PyModule_AddObject(module, "LuaFileNotFound", exceptions_array.LuaFileNotFound);
	py_code = PyInt_FromLong(AEROSPIKE_ERR_LUA_FILE_NOT_FOUND);
	PyObject_SetAttrString(exceptions_array.LuaFileNotFound, "code", py_code);
	Py_DECREF(py_code);

	//Admin exceptions
	exceptions_array.AdminError = PyErr_NewException("exception.AdminError", exceptions_array.ServerError, NULL);
	Py_INCREF(exceptions_array.AdminError);
	PyModule_AddObject(module, "AdminError", exceptions_array.AdminError);

	count = sizeof(admin_array.admin_exceptions)/sizeof(admin_array.admin_exceptions[0]);
	for(i=0; i < count; i++) {
		current_exception = admin_array.admin_exceptions[i];
		char * name = admin_array.admin_exceptions_name[i];
		char prefix[40] = "exception.";
		*current_exception = PyErr_NewException(strcat(prefix, name), exceptions_array.AdminError, NULL);
		Py_INCREF(*current_exception);
		PyModule_AddObject(module, name, *current_exception);
		PyObject *py_code = PyInt_FromLong(admin_array.admin_exceptions_codes[i]);
		PyObject_SetAttrString(*current_exception, "code", py_code);
		Py_DECREF(py_code);
	}

	//Query exceptions
	exceptions_array.QueryQueueFull = PyErr_NewException("exception.QueryQueueFull", exceptions_array.QueryError, NULL);
	Py_INCREF(exceptions_array.QueryQueueFull);
	PyModule_AddObject(module, "QueryQueueFull", exceptions_array.QueryQueueFull);
	py_code = PyInt_FromLong(AEROSPIKE_ERR_QUERY_QUEUE_FULL);
	PyObject_SetAttrString(exceptions_array.QueryQueueFull, "code", py_code);
	Py_DECREF(py_code);

	exceptions_array.QueryTimeout = PyErr_NewException("exception.QueryTimeout", exceptions_array.QueryError, NULL);
	Py_INCREF(exceptions_array.QueryTimeout);
	PyModule_AddObject(module, "QueryTimeout", exceptions_array.QueryTimeout);
	py_code = PyInt_FromLong(AEROSPIKE_ERR_QUERY_TIMEOUT);
	PyObject_SetAttrString(exceptions_array.QueryQueueFull, "code", py_code);
	Py_DECREF(py_code);

	//LDT exceptions
	PyObject *py_ldt_dict = PyDict_New();
	PyDict_SetItemString(py_ldt_dict, "key", Py_None);
	PyDict_SetItemString(py_ldt_dict, "bin", Py_None);
	exceptions_array.LDTError = PyErr_NewException("exception.LDTError", exceptions_array.ServerError, py_ldt_dict);
	Py_INCREF(exceptions_array.LDTError);
	Py_DECREF(py_ldt_dict);
	PyModule_AddObject(module, "LDTError", exceptions_array.LDTError);

	count = sizeof(ldt_array.ldt_exceptions)/sizeof(ldt_array.ldt_exceptions[0]);
	for(i=0; i < count; i++) {
		current_exception = ldt_array.ldt_exceptions[i];
		char * name = ldt_array.ldt_exceptions_name[i];
		char prefix[40] = "exception.";
		*current_exception = PyErr_NewException(strcat(prefix, name), exceptions_array.LDTError, NULL);
		Py_INCREF(*current_exception);
		PyModule_AddObject(module, name, *current_exception);
		PyObject *py_code = PyInt_FromLong(ldt_array.ldt_exceptions_codes[i]);
		PyObject_SetAttrString(*current_exception, "code", py_code);
		Py_DECREF(py_code);
	}
	return module;
}
Ejemplo n.º 16
0
int
PyObject_GenericSetAttr(PyObject *obj, PyObject *name, PyObject *value)
{
	PyTypeObject *tp = obj->ob_type;
	PyObject *descr;
	descrsetfunc f;
	PyObject **dictptr;
	int res = -1;

	if (!PyString_Check(name)){
#ifdef Py_USING_UNICODE
		/* The Unicode to string conversion is done here because the
		   existing tp_setattro slots expect a string object as name
		   and we wouldn't want to break those. */
		if (PyUnicode_Check(name)) {
			name = PyUnicode_AsEncodedString(name, NULL, NULL);
			if (name == NULL)
				return -1;
		}
		else
#endif
		{
			PyErr_Format(PyExc_TypeError,
				     "attribute name must be string, not '%.200s'",
				     name->ob_type->tp_name);
			return -1;
		}
	}
	else
		Py_INCREF(name);

	if (tp->tp_dict == NULL) {
		if (PyType_Ready(tp) < 0)
			goto done;
	}

	descr = _PyType_Lookup(tp, name);
	f = NULL;
	if (descr != NULL &&
	    PyType_HasFeature(descr->ob_type, Py_TPFLAGS_HAVE_CLASS)) {
		f = descr->ob_type->tp_descr_set;
		if (f != NULL && PyDescr_IsData(descr)) {
			res = f(descr, obj, value);
			goto done;
		}
	}

	dictptr = _PyObject_GetDictPtr(obj);
	if (dictptr != NULL) {
		PyObject *dict = *dictptr;
		if (dict == NULL && value != NULL) {
			dict = PyDict_New();
			if (dict == NULL)
				goto done;
			*dictptr = dict;
		}
		if (dict != NULL) {
			Py_INCREF(dict);
			if (value == NULL)
				res = PyDict_DelItem(dict, name);
			else
				res = PyDict_SetItem(dict, name, value);
			if (res < 0 && PyErr_ExceptionMatches(PyExc_KeyError))
				PyErr_SetObject(PyExc_AttributeError, name);
			Py_DECREF(dict);
			goto done;
		}
	}

	if (f != NULL) {
		res = f(descr, obj, value);
		goto done;
	}

	if (descr == NULL) {
		PyErr_Format(PyExc_AttributeError,
			     "'%.100s' object has no attribute '%.200s'",
			     tp->tp_name, PyString_AS_STRING(name));
		goto done;
	}

	PyErr_Format(PyExc_AttributeError,
		     "'%.50s' object attribute '%.400s' is read-only",
		     tp->tp_name, PyString_AS_STRING(name));
  done:
	Py_DECREF(name);
	return res;
}
Ejemplo n.º 17
0
PyMODINIT_FUNC
init_billiard(void)
{
    PyObject *module, *temp, *value;

    /* Initialize module */
    module = Py_InitModule("_billiard", Billiard_module_methods);
    if (!module)
        return;

    /* Get copy of objects from pickle */
    temp = PyImport_ImportModule(PICKLE_MODULE);
    if (!temp)
        return;
    Billiard_pickle_dumps = PyObject_GetAttrString(temp, "dumps");
    Billiard_pickle_loads = PyObject_GetAttrString(temp, "loads");
    Billiard_pickle_protocol = PyObject_GetAttrString(temp, "HIGHEST_PROTOCOL");
    Py_XDECREF(temp);

    /* Get copy of BufferTooShort */
    temp = PyImport_ImportModule("billiard");
    if (!temp)
        return;
    Billiard_BufferTooShort = PyObject_GetAttrString(temp, "BufferTooShort");
    Py_XDECREF(temp);

    /* Add connection type to module */
    if (PyType_Ready(&BilliardConnectionType) < 0)
        return;
    Py_INCREF(&BilliardConnectionType);
    PyModule_AddObject(module, "Connection", (PyObject*)&BilliardConnectionType);

#if defined(MS_WINDOWS) ||                                              \
  (defined(HAVE_SEM_OPEN) && !defined(POSIX_SEMAPHORES_NOT_ENABLED))
    /* Add SemLock type to module */
    if (PyType_Ready(&BilliardSemLockType) < 0)
        return;
    Py_INCREF(&BilliardSemLockType);
    PyDict_SetItemString(BilliardSemLockType.tp_dict, "SEM_VALUE_MAX",
                         Py_BuildValue("i", SEM_VALUE_MAX));
    PyModule_AddObject(module, "SemLock", (PyObject*)&BilliardSemLockType);
#endif

#ifdef MS_WINDOWS
    /* Add PipeConnection to module */
    if (PyType_Ready(&BilliardPipeConnectionType) < 0)
        return;
    Py_INCREF(&BilliardPipeConnectionType);
    PyModule_AddObject(module, "PipeConnection",
                       (PyObject*)&BilliardPipeConnectionType);

    /* Initialize win32 class and add to multiprocessing */
    temp = create_win32_namespace();
    if (!temp)
        return;
    PyModule_AddObject(module, "win32", temp);

    /* Initialize the event handle used to signal Ctrl-C */
    sigint_event = CreateEvent(NULL, TRUE, FALSE, NULL);
    if (!sigint_event) {
        PyErr_SetFromWindowsErr(0);
        return;
    }
    if (!SetConsoleCtrlHandler(ProcessingCtrlHandler, TRUE)) {
        PyErr_SetFromWindowsErr(0);
        return;
    }
#endif

    /* Add configuration macros */
    temp = PyDict_New();
    if (!temp)
        return;
#define ADD_FLAG(name)                                            \
    value = Py_BuildValue("i", name);                             \
    if (value == NULL) { Py_DECREF(temp); return; }               \
    if (PyDict_SetItemString(temp, #name, value) < 0) {           \
        Py_DECREF(temp); Py_DECREF(value); return; }              \
    Py_DECREF(value)

#if defined(HAVE_SEM_OPEN) && !defined(POSIX_SEMAPHORES_NOT_ENABLED)
    ADD_FLAG(HAVE_SEM_OPEN);
#endif
#ifdef HAVE_SEM_TIMEDWAIT
    ADD_FLAG(HAVE_SEM_TIMEDWAIT);
#endif
#ifdef HAVE_FD_TRANSFER
    ADD_FLAG(HAVE_FD_TRANSFER);
#endif
#ifdef HAVE_BROKEN_SEM_GETVALUE
    ADD_FLAG(HAVE_BROKEN_SEM_GETVALUE);
#endif
#ifdef HAVE_BROKEN_SEM_UNLINK
    ADD_FLAG(HAVE_BROKEN_SEM_UNLINK);
#endif
    if (PyModule_AddObject(module, "flags", temp) < 0)
        return;
}
Ejemplo n.º 18
0
PyObject *
PyObject_Dir(PyObject *arg)
{
	/* Set exactly one of these non-NULL before the end. */
	PyObject *result = NULL;	/* result list */
	PyObject *masterdict = NULL;	/* result is masterdict.keys() */

	/* If NULL arg, return the locals. */
	if (arg == NULL) {
		PyObject *locals = PyEval_GetLocals();
		if (locals == NULL)
			goto error;
		result = PyMapping_Keys(locals);
		if (result == NULL)
			goto error;
	}

	/* Elif this is some form of module, we only want its dict. */
	else if (PyModule_Check(arg)) {
		masterdict = PyObject_GetAttrString(arg, "__dict__");
		if (masterdict == NULL)
			goto error;
		if (!PyDict_Check(masterdict)) {
			PyErr_SetString(PyExc_TypeError,
					"module.__dict__ is not a dictionary");
			goto error;
		}
	}

	/* Elif some form of type or class, grab its dict and its bases.
	   We deliberately don't suck up its __class__, as methods belonging
	   to the metaclass would probably be more confusing than helpful. */
	else if (PyType_Check(arg) || PyClass_Check(arg)) {
		masterdict = PyDict_New();
		if (masterdict == NULL)
			goto error;
		if (merge_class_dict(masterdict, arg) < 0)
			goto error;
	}

	/* Else look at its dict, and the attrs reachable from its class. */
	else {
		PyObject *itsclass;
		/* Create a dict to start with.  CAUTION:  Not everything
		   responding to __dict__ returns a dict! */
		masterdict = PyObject_GetAttrString(arg, "__dict__");
		if (masterdict == NULL) {
			PyErr_Clear();
			masterdict = PyDict_New();
		}
		else if (!PyDict_Check(masterdict)) {
			Py_DECREF(masterdict);
			masterdict = PyDict_New();
		}
		else {
			/* The object may have returned a reference to its
			   dict, so copy it to avoid mutating it. */
			PyObject *temp = PyDict_Copy(masterdict);
			Py_DECREF(masterdict);
			masterdict = temp;
		}
		if (masterdict == NULL)
			goto error;

		/* Merge in __members__ and __methods__ (if any).
		   XXX Would like this to go away someday; for now, it's
		   XXX needed to get at im_self etc of method objects. */
		if (merge_list_attr(masterdict, arg, "__members__") < 0)
			goto error;
		if (merge_list_attr(masterdict, arg, "__methods__") < 0)
			goto error;

		/* Merge in attrs reachable from its class.
		   CAUTION:  Not all objects have a __class__ attr. */
		itsclass = PyObject_GetAttrString(arg, "__class__");
		if (itsclass == NULL)
			PyErr_Clear();
		else {
			int status = merge_class_dict(masterdict, itsclass);
			Py_DECREF(itsclass);
			if (status < 0)
				goto error;
		}
	}

	assert((result == NULL) ^ (masterdict == NULL));
	if (masterdict != NULL) {
		/* The result comes from its keys. */
		assert(result == NULL);
		result = PyDict_Keys(masterdict);
		if (result == NULL)
			goto error;
	}

	assert(result);
	if (!PyList_Check(result)) {
		PyErr_Format(PyExc_TypeError,
			"Expected keys() to be a list, not '%.200s'",
			result->ob_type->tp_name);
		goto error;
	}
	if (PyList_Sort(result) != 0)
		goto error;
	else
		goto normal_return;

  error:
	Py_XDECREF(result);
	result = NULL;
	/* fall through */
  normal_return:
  	Py_XDECREF(masterdict);
	return result;
}
Ejemplo n.º 19
0
Archivo: msaio.c Proyecto: Wyss/ProDy
static PyObject *parseFasta(PyObject *self, PyObject *args) {

    /* Parse sequences from *filename* into the memory pointed by the
       Numpy array passed as Python object. */

    char *filename;
    PyArrayObject *msa;
    PyObject *labels = PyList_New(0);
    PyObject *mapping = PyDict_New();
    
    if (!PyArg_ParseTuple(args, "sO", &filename, &msa))
        return NULL;



    if (!labels || !mapping)
        return PyErr_NoMemory();

    char *line = malloc((FASTALINELEN) * sizeof(char));
    if (!line)
        return PyErr_NoMemory();

    char *data = (char *) PyArray_DATA(msa);

    int aligned = 1;
    char ch, errmsg[LENLABEL] = "failed to parse FASTA file at line ";
    long index = 0, count = 0;
    long iline = 0, i, seqlen = 0, curlen = 0;

    FILE *file = fopen(filename, "rb");
    while (fgets(line, FASTALINELEN, file) != NULL) {
        iline++;
        if (line[0] == '>') {
            if (seqlen != curlen) {
                if (seqlen) {
                    aligned = 0;
                    free(line);
                    free(data);
                    fclose(file);
                    PyErr_SetString(PyExc_IOError, intcat(errmsg, iline));
                    return NULL;
                } else
                    seqlen = curlen;
            }
            // `line + 1` is to omit `>` character
            count += parseLabel(labels, mapping, line + 1, FASTALINELEN);
            curlen = 0;
        } else {
            for (i = 0; i < FASTALINELEN; i++) {
                ch = line[i];
                if (ch < 32)
                    break;
                else {
                    data[index++] = ch;
                    curlen++;
                }
            }
        }
    }
    fclose(file);

    free(line);
    if (aligned && seqlen != curlen) {
        PyErr_SetString(PyExc_IOError, intcat(errmsg, iline));
        return NULL;
    }

    npy_intp dims[2] = {index / seqlen, seqlen};
    PyArray_Dims arr_dims;
    arr_dims.ptr = dims;
    arr_dims.len = 2;
    PyArray_Resize(msa, &arr_dims, 0, NPY_CORDER);
    PyObject *result = Py_BuildValue("(OOOi)", msa, labels, mapping, count);
    Py_DECREF(labels);
    Py_DECREF(mapping);
    return result;
}
Ejemplo n.º 20
0
static PyObject*
decode_object(JSONData *jsondata)
{
    PyObject *object, *key, *value;
    int c, expect_key, items, result;
    char *start;

    object = PyDict_New();

    expect_key = True;
    items = 0;
    start = jsondata->ptr;
    jsondata->ptr++;

    while (True) {
        skipSpaces(jsondata);
        c = *jsondata->ptr;
        if (c == 0) {
            PyErr_Format(JSON_DecodeError, "unterminated object starting at "
                         "position " SSIZE_T_F,
                         (Py_ssize_t)(start - jsondata->str));
            goto failure;;
        } else if (c == '}') {
            if (expect_key && items>0) {
                PyErr_Format(JSON_DecodeError, "expecting object property name"
                             " at position " SSIZE_T_F,
                             (Py_ssize_t)(jsondata->ptr - jsondata->str));
                goto failure;
            }
            jsondata->ptr++;
            break;
        } else if (c == ',') {
            if (expect_key) {
                PyErr_Format(JSON_DecodeError, "expecting object property name"
                             "at position " SSIZE_T_F,
                             (Py_ssize_t)(jsondata->ptr - jsondata->str));
                goto failure;
            }
            expect_key = True;
            jsondata->ptr++;
            continue;
        } else {
            if (c != '"') {
                PyErr_Format(JSON_DecodeError, "expecting property name in "
                             "object at position " SSIZE_T_F,
                             (Py_ssize_t)(jsondata->ptr - jsondata->str));
                goto failure;
            }

            key = decode_json(jsondata);
            if (key == NULL)
                goto failure;

            skipSpaces(jsondata);
            if (*jsondata->ptr != ':') {
                PyErr_Format(JSON_DecodeError, "missing colon after object "
                             "property name at position " SSIZE_T_F,
                             (Py_ssize_t)(jsondata->ptr - jsondata->str));
                Py_DECREF(key);
                goto failure;
            } else {
                jsondata->ptr++;
            }

            value = decode_json(jsondata);
            if (value == NULL) {
                Py_DECREF(key);
                goto failure;
            }

            result = PyDict_SetItem(object, key, value);
            Py_DECREF(key);
            Py_DECREF(value);
            if (result == -1)
                goto failure;
            expect_key = False;
            items++;
        }
    }

    return object;

failure:
    Py_DECREF(object);
    return NULL;
}
Ejemplo n.º 21
0
void initregistery(PyObject* m) {
    dict_to = PyDict_New();
    dict_from = PyDict_New();
}
Ejemplo n.º 22
0
int PythonInterface::python_run(const String& ac_name)
{
  // probably need to convert all of the following with SWIG or Boost!!
  // (there is minimal error checking for now)
  // need to cleanup ref counts on Python objects
  int fail_code = 0;

  // probably want to load the modules and functions at construction time, incl.
  // validation and store the objects for later, but need to resolve use of
  // analysisDriverIndex

  // must use empty tuple here to pass to function taking only kwargs
  PyObject *pArgs = PyTuple_New(0);
  PyObject *pDict = PyDict_New();

  // convert DAKOTA data types to Python objects (lists and/or numpy arrays)
  PyObject *cv, *cv_labels, *div, *div_labels, *drv, *drv_labels,
    *av, *av_labels, *asv, *dvv, *an_comps;
  python_convert(xC, &cv);
  python_convert_strlist(xCLabels, &cv_labels);
  python_convert_int(xDI, xDI.length(), &div);
  python_convert_strlist(xDILabels, &div_labels);
  python_convert(xDR, &drv);
  python_convert_strlist(xDRLabels, &drv_labels);
  python_convert(xC, xDI, xDR, &av);
  python_convert(xCLabels, xDILabels, xDRLabels, &av_labels);
  python_convert_int(directFnASV, directFnASV.size(), &asv);
  python_convert_int(directFnDVV, directFnDVV.size(), &dvv);
  // send analysis components, or an empty list
  if (analysisComponents.size() > 0)
    python_convert_strlist(analysisComponents[analysisDriverIndex], &an_comps);
  else
    an_comps = PyList_New(0);

  // assemble everything into a dictionary to pass to user function
  // this should eat references to the objects declared above
  PyDict_SetItem(pDict, PyString_FromString("variables"), 
		 PyInt_FromLong((long) numVars));
  PyDict_SetItem(pDict, PyString_FromString("functions"), 
		 PyInt_FromLong((long) numFns)); 
  PyDict_SetItem(pDict, PyString_FromString("cv"), cv);
  PyDict_SetItem(pDict, PyString_FromString("cv_labels"), cv_labels);
  PyDict_SetItem(pDict, PyString_FromString("div"), div);
  PyDict_SetItem(pDict, PyString_FromString("div_labels"), div_labels);
  PyDict_SetItem(pDict, PyString_FromString("drv"), drv);
  PyDict_SetItem(pDict, PyString_FromString("drv_labels"), drv_labels);
  PyDict_SetItem(pDict, PyString_FromString("av"), av);
  PyDict_SetItem(pDict, PyString_FromString("av_labels"), av_labels);
  PyDict_SetItem(pDict, PyString_FromString("asv"), asv);
  PyDict_SetItem(pDict, PyString_FromString("dvv"), dvv);
  PyDict_SetItem(pDict, PyString_FromString("analysis_components"), an_comps);
  PyDict_SetItem(pDict, PyString_FromString("currEvalId"), 
		 PyInt_FromLong((long) currEvalId));


  // The active analysis_driver is passed in ac_name (in form
  // module:function); could make module optional.  We pass any
  // analysis components as string arguments to the Python function.
  size_t pos = ac_name.find(":");
  std::string module_name = ac_name.substr(0,pos);
  std::string function_name = ac_name.substr(pos+1);
  if (module_name.size() == 0 || function_name.size() == 0) {
    Cerr << "\nError: invalid Python analysis_driver '" << ac_name
	 << "'\n       Should have form 'module:function'." << std::endl;
    abort_handler(-1);
  }

  // import the module and function and test for callable
  PyObject *pModule = PyImport_Import(PyString_FromString(module_name.c_str()));
  if (pModule == NULL) {
    Cerr << "Error (PythonInterface): Failure importing module '" 
	 << module_name  << "'.\n                         Consider setting "
	 << "PYTHONPATH." << std::endl;
    abort_handler(-1);
  }

  PyObject *pFunc = PyObject_GetAttrString(pModule, function_name.c_str());
  if (!pFunc || !PyCallable_Check(pFunc)) {
    Cerr << "Error (PythonInterface): Function '" << function_name  
	 << "' not found or not callable" << std::endl;
    abort_handler(-1);
  }

  // perform analysis
  if (outputLevel > NORMAL_OUTPUT)
    Cout << "Info (PythonInterface): Calling function " << function_name 
	 << " in module " << module_name << "." << std::endl;
  PyObject *retVal = PyObject_Call(pFunc, pArgs, pDict);
  if (!retVal) {
    // TODO: better error reporting from Python
    Cerr << "Error (PythonInterface): Unknown error evaluating python "
	 << "function." << std::endl;
    abort_handler(-1);
  }

  Py_DECREF(pDict);
  Py_DECREF(pArgs);    
  Py_DECREF(pFunc);
  Py_DECREF(pModule);

  // process the return data

  bool fn_flag = false;
  for (int i=0; i<numFns; ++i)
    if (directFnASV[i] & 1) {
      fn_flag = true;
      break;
    }

  // process return type as dictionary, else assume list of functions only
  if (PyDict_Check(retVal)) {
    // or the user may return a dictionary containing entires fns, fnGrads,
    // fnHessians, fnLabels, failure (int)
    // fnGrads, e.g. is a list of lists of doubles
    // this is where Boost or SWIG could really help
    // making a lot of assumptions on types being returned
    PyObject *obj;
    if (fn_flag) {
      if ( !(obj = PyDict_GetItemString(retVal, "fns")) ) {
	Cerr << "Python dictionary must contain list 'fns'" << std::endl;
	Py_DECREF(retVal);
	abort_handler(-1);
      }
      if (!python_convert(obj, fnVals, numFns)) {
	Py_DECREF(retVal);
	abort_handler(-1);
      }
    }
    if (gradFlag) {
      if ( !(obj = PyDict_GetItemString(retVal, "fnGrads")) ) {
	Cerr << "Python dictionary must contain list 'fnGrads'" << std::endl;
	Py_DECREF(retVal);
	abort_handler(-1);
      }
      if (!python_convert(obj, fnGrads)) {
	Py_DECREF(retVal);
	abort_handler(-1);
      }
    }
    if (hessFlag) {
      if ( !(obj = PyDict_GetItemString(retVal, "fnHessians")) ) {
	Cerr << "Python dictionary must contain list 'fnHessians'" << std::endl;
	Py_DECREF(retVal);
	abort_handler(-1);
      }
      if (!python_convert(obj, fnHessians)){
	Py_DECREF(retVal);
	abort_handler(-1);
      }
    }
    // optional returns
    if (obj = PyDict_GetItemString(retVal, "failure"))
      fail_code = PyInt_AsLong(obj);

    if (obj = PyDict_GetItemString(retVal, "fnLabels")) {
      if (!PyList_Check(obj) || PyList_Size(obj) != numFns) {
	Cerr << "'fnLabels' must be list of length numFns." << std::endl;
	Py_DECREF(retVal);
	abort_handler(-1);
      }
      for (int i=0; i<numFns; ++i)
	fnLabels[i] = PyString_AsString(PyList_GetItem(obj, i));
    }
  }
  else {
    // asssume list/numpy array containing only functions
    if (fn_flag)
      python_convert(retVal, fnVals, numFns);
  }
  Py_DECREF(retVal);

  return(fail_code);
}
Ejemplo n.º 23
0
static PyObject* openSPI(PyObject *self, PyObject *args, PyObject *kwargs)
{

	static char* kwlist[] = {"device", "mode", "bits", "speed", "delay", NULL};

	// Adding some sort of mode parsing would probably be a nice idea for the future, so you don't have to specify it as a bitfield
	// stuffed into an int.
	// For the moment the default mode ("0"), will probably work for 99% of people who need a SPI interface, so I'm not working on that
	//


	if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|siiii:keywords", kwlist, &device, &mode, &bits, &speed, &delay))
		return NULL;
	// It's not clearly documented, but it seems that PyArg_ParseTupleAndKeywords basically only modifies the values passed to it if the
	// keyword pertaining to that value is passed to the function. As such, the defaults specified by the variable definition are used
	// unless you pass a kwd argument.
	// Note that there isn't any proper bounds-checking, so if you pass a value that exceeds the variable size, it's just truncated before
	// being stuffed into  the avasilable space. For example, passing a bits-per-word of 500 gets truncated to 244. Unfortunately, the
	// PyArg_ParseTupleAndKeywords function only seems to support ints of 32 bits.

	PyErr_Clear();

	// printf("Mode: %i, Bits: %i, Speed: %i, Delay: %i\n", mode, bits, speed, delay);



	fd = open(device, O_RDWR);
	if (fd < 0)
		pabort("can't open device");

	/*
	 * Setup SPI mode
	 */
	ret = ioctl(fd, SPI_IOC_WR_MODE, &mode);
	if (ret == -1)
		pabort("can't set spi mode");

	ret = ioctl(fd, SPI_IOC_RD_MODE, &mode);
	if (ret == -1)
		pabort("can't get spi mode");

	/*
	 * bits per word
	 */
	ret = ioctl(fd, SPI_IOC_WR_BITS_PER_WORD, &bits);
	if (ret == -1)
		pabort("can't set bits per word");

	ret = ioctl(fd, SPI_IOC_RD_BITS_PER_WORD, &bits);
	if (ret == -1)
		pabort("can't get bits per word");

	/*
	 * max speed hz
	 */
	ret = ioctl(fd, SPI_IOC_WR_MAX_SPEED_HZ, &speed);
	if (ret == -1)
		pabort("can't set max speed hz");

	ret = ioctl(fd, SPI_IOC_RD_MAX_SPEED_HZ, &speed);
	if (ret == -1)
		pabort("can't get max speed hz");

	// Stuff the various initilization parameters into a dict, and return that.
	// Note that the returned values may not be completely real. It seems that, at least for the speed value,
	// the hardware only has several possible settings (250000, 500000, 1000000, etc...) Strangely enough, the
	// ioctl for setting the speed *returns the speed you specify*. However, the hardware seems to default to the
	// closest avalable value *below* the specified rate. (i.e. you will never get a speed faster then you spec),
	// but you may get a slower value.

	//It would probably be a good idea to bin-down the passed arguement to the available values, and return
	// that.

	PyObject* retDict;
	retDict = PyDict_New();

	PyDict_SetItem(retDict, PyString_FromString("mode"), PyInt_FromLong((long)mode));
	PyDict_SetItem(retDict, PyString_FromString("bits"), PyInt_FromLong((long)bits));
	PyDict_SetItem(retDict, PyString_FromString("speed"), PyInt_FromLong((long)speed));
	PyDict_SetItem(retDict, PyString_FromString("delay"), PyInt_FromLong((long)delay));


	return retDict;
}
Ejemplo n.º 24
0
DL_EXPORT(void) initGeoIP(void)
{
    PyObject *m, *d, *tmp, *ccode, *cname, *ccont, *name;
    int i;
    const int total_ccodes = sizeof(GeoIP_country_code) /
        sizeof(GeoIP_country_code[0]);
    GeoIP_GeoIPType.ob_type = &PyType_Type;

    m = Py_InitModule("GeoIP", GeoIP_Class_methods);
    d = PyModule_GetDict(m);

    PyGeoIPError = PyErr_NewException("py_geoip.error", NULL, NULL);
    PyDict_SetItemString(d, "error", PyGeoIPError);

    ccode = PyTuple_New(total_ccodes);
    cname = PyDict_New();
    ccont = PyDict_New();

    for (i = 0; i < total_ccodes; i++) {
        name = PyString_FromString(GeoIP_country_code[i]);
        PyTuple_SET_ITEM(ccode, i, name);

        tmp = PyString_FromString(GeoIP_country_name[i]);
        PyDict_SetItem(cname, name, tmp);
        Py_DECREF(tmp);

        tmp = PyString_FromString(GeoIP_country_continent[i]);
        PyDict_SetItem(ccont, name, tmp);
        Py_DECREF(tmp);
    }

    PyDict_SetItemString(d, "country_codes", ccode);
    Py_DECREF(ccode);
    PyDict_SetItemString(d, "country_names", cname);
    Py_DECREF(cname);
    PyDict_SetItemString(d, "country_continents", ccont);
    Py_DECREF(ccont);

    tmp = PyInt_FromLong(GEOIP_STANDARD);
    PyDict_SetItemString(d, "GEOIP_STANDARD", tmp);
    Py_DECREF(tmp);

    tmp = PyInt_FromLong(GEOIP_MEMORY_CACHE);
    PyDict_SetItemString(d, "GEOIP_MEMORY_CACHE", tmp);
    Py_DECREF(tmp);

    tmp = PyInt_FromLong(GEOIP_CHECK_CACHE);
    PyDict_SetItemString(d, "GEOIP_CHECK_CACHE", tmp);
    Py_DECREF(tmp);

    tmp = PyInt_FromLong(GEOIP_INDEX_CACHE);
    PyDict_SetItemString(d, "GEOIP_INDEX_CACHE", tmp);
    Py_DECREF(tmp);

    tmp = PyInt_FromLong(GEOIP_CHARSET_ISO_8859_1);
    PyDict_SetItemString(d, "GEOIP_CHARSET_ISO_8859_1", tmp);
    Py_DECREF(tmp);

    tmp = PyInt_FromLong(GEOIP_CHARSET_UTF8);
    PyDict_SetItemString(d, "GEOIP_CHARSET_UTF8", tmp);
    Py_DECREF(tmp);

    tmp = PyInt_FromLong(GEOIP_UNKNOWN_SPEED);
    PyDict_SetItemString(d, "GEOIP_UNKNOWN_SPEED", tmp);
    Py_DECREF(tmp);

    tmp = PyInt_FromLong(GEOIP_DIALUP_SPEED);
    PyDict_SetItemString(d, "GEOIP_DIALUP_SPEED", tmp);
    Py_DECREF(tmp);

    tmp = PyInt_FromLong(GEOIP_CABLEDSL_SPEED);
    PyDict_SetItemString(d, "GEOIP_CABLEDSL_SPEED", tmp);
    Py_DECREF(tmp);

    tmp = PyInt_FromLong(GEOIP_CORPORATE_SPEED);
    PyDict_SetItemString(d, "GEOIP_CORPORATE_SPEED", tmp);
    Py_DECREF(tmp);
}
Ejemplo n.º 25
0
// The module function definitions.
static PyObject *impl_function_1_new_of_module_Crypto$Random( Nuitka_FunctionObject *self, PyObject *_python_par_args, PyObject *_python_par_kwargs )
{
    // No context is used.

    // Local variable declarations.
    PyObjectLocalVariable par_args; par_args.object = _python_par_args;
    PyObjectLocalVariable par_kwargs; par_kwargs.object = _python_par_kwargs;
    PyObject *exception_type = NULL, *exception_value = NULL;
    PyTracebackObject *exception_tb = NULL;
    PyObject *tmp_dircall_arg1_1;
    PyObject *tmp_dircall_arg2_1;
    PyObject *tmp_dircall_arg3_1;
    PyObject *tmp_frame_locals;
    PyObject *tmp_return_value;
    PyObject *tmp_source_name_1;
    tmp_return_value = NULL;

    // Actual function code.
    static PyFrameObject *cache_frame_function = NULL;
    MAKE_OR_REUSE_FRAME( cache_frame_function, codeobj_133c4414c20d7de5bf4cbf02f8208534, module_Crypto$Random );
    PyFrameObject *frame_function = cache_frame_function;

    // Push the new frame as the currently active one.
    pushFrameStack( frame_function );

    // Mark the frame object as in use, ref count 1 will be up for reuse.
    Py_INCREF( frame_function );
    assert( Py_REFCNT( frame_function ) == 2 ); // Frame stack

#if PYTHON_VERSION >= 340
    frame_function->f_executing += 1;
#endif

    // Framed code:
    tmp_source_name_1 = GET_STRING_DICT_VALUE( moduledict_Crypto$Random, (Nuitka_StringObject *)const_str_plain__UserFriendlyRNG );

    if (unlikely( tmp_source_name_1 == NULL ))
    {
        tmp_source_name_1 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain__UserFriendlyRNG );
    }

    if ( tmp_source_name_1 == NULL )
    {

        exception_type = INCREASE_REFCOUNT( PyExc_NameError );
        exception_value = UNSTREAM_STRING( &constant_bin[ 6196 ], 45, 0 );
        exception_tb = NULL;

        frame_function->f_lineno = 33;
        goto frame_exception_exit_1;
    }

    tmp_dircall_arg1_1 = LOOKUP_ATTRIBUTE( tmp_source_name_1, const_str_plain_new );
    if ( tmp_dircall_arg1_1 == NULL )
    {
        assert( ERROR_OCCURED() );

        PyErr_Fetch( &exception_type, &exception_value, (PyObject **)&exception_tb );


        frame_function->f_lineno = 33;
        goto frame_exception_exit_1;
    }
    tmp_dircall_arg2_1 = par_args.object;

    if ( tmp_dircall_arg2_1 == NULL )
    {
        Py_DECREF( tmp_dircall_arg1_1 );
        exception_type = INCREASE_REFCOUNT( PyExc_UnboundLocalError );
        exception_value = UNSTREAM_STRING( &constant_bin[ 201 ], 50, 0 );
        exception_tb = NULL;

        frame_function->f_lineno = 33;
        goto frame_exception_exit_1;
    }

    tmp_dircall_arg3_1 = par_kwargs.object;

    if ( tmp_dircall_arg3_1 == NULL )
    {
        Py_DECREF( tmp_dircall_arg1_1 );
        exception_type = INCREASE_REFCOUNT( PyExc_UnboundLocalError );
        exception_value = UNSTREAM_STRING( &constant_bin[ 251 ], 52, 0 );
        exception_tb = NULL;

        frame_function->f_lineno = 33;
        goto frame_exception_exit_1;
    }

    tmp_return_value = impl_function_3_complex_call_helper_star_list_star_dict_of_module___internal__( tmp_dircall_arg1_1, INCREASE_REFCOUNT( tmp_dircall_arg2_1 ), INCREASE_REFCOUNT( tmp_dircall_arg3_1 ) );
    if ( tmp_return_value == NULL )
    {
        assert( ERROR_OCCURED() );

        PyErr_Fetch( &exception_type, &exception_value, (PyObject **)&exception_tb );


        frame_function->f_lineno = 33;
        goto frame_exception_exit_1;
    }
    goto frame_return_exit_1;

#if 0
    RESTORE_FRAME_EXCEPTION( frame_function );
#endif
    // Put the previous frame back on top.
    popFrameStack();
#if PYTHON_VERSION >= 340
    frame_function->f_executing -= 1;
#endif
    Py_DECREF( frame_function );
    goto frame_no_exception_1;
    frame_return_exit_1:;
#if 0
    RESTORE_FRAME_EXCEPTION( frame_function );
#endif
    popFrameStack();
#if PYTHON_VERSION >= 340
    frame_function->f_executing -= 1;
#endif
    Py_DECREF( frame_function );
    goto function_return_exit;
    frame_exception_exit_1:;
#if 0
    RESTORE_FRAME_EXCEPTION( frame_function );
#endif

    if ( exception_tb == NULL )
    {
        exception_tb = MAKE_TRACEBACK( INCREASE_REFCOUNT( frame_function ) );
    }
    else if ( exception_tb->tb_frame != frame_function )
    {
        PyTracebackObject *traceback_new = (PyTracebackObject *)MAKE_TRACEBACK( INCREASE_REFCOUNT( frame_function ) );
        traceback_new->tb_next = exception_tb;
        exception_tb = traceback_new;
    }


    tmp_frame_locals = PyDict_New();
    if ((par_args.object != NULL))
    {
        PyDict_SetItem(
            tmp_frame_locals,
            const_str_plain_args,
            par_args.object
        );

    }
    if ((par_kwargs.object != NULL))
    {
        PyDict_SetItem(
            tmp_frame_locals,
            const_str_plain_kwargs,
            par_kwargs.object
        );

    }
    detachFrame( exception_tb, tmp_frame_locals );


    popFrameStack();

#if PYTHON_VERSION >= 340
    frame_function->f_executing -= 1;
#endif
    Py_DECREF( frame_function );

    // Return the error.
    goto function_exception_exit;
    frame_no_exception_1:;


    // Return statement must be present.
    assert(false);
function_exception_exit:
    assert( exception_type );
    PyErr_Restore( exception_type, exception_value, (PyObject *)exception_tb );
    return NULL;
function_return_exit:
    return tmp_return_value;

}
Ejemplo n.º 26
0
static int
psyco_errors_init(void)
{
    /* the names of the exceptions here reflect the oranization of the
       psycopg2 module and not the fact the the original error objects
       live in _psycopg */

    int i;
    PyObject *dict = NULL;
    PyObject *base;
    PyObject *str = NULL;
    PyObject *descr = NULL;
    int rv = -1;

#if PY_VERSION_HEX >= 0x02050000
    static PyMethodDef psyco_error_reduce_ex_def =
        {"__reduce_ex__", psyco_error_reduce_ex, METH_VARARGS, "pickle helper"};
#endif

    for (i=0; exctable[i].name; i++) {
        if (!(dict = PyDict_New())) { goto exit; }

        if (exctable[i].docstr) {
            if (!(str = Text_FromUTF8(exctable[i].docstr))) { goto exit; }
            if (0 != PyDict_SetItemString(dict, "__doc__", str)) { goto exit; }
            Py_CLEAR(str);
        }

        if (exctable[i].base == 0) {
            #if PY_MAJOR_VERSION < 3
            base = PyExc_StandardError;
            #else
            /* StandardError is gone in 3.0 */
            base = NULL;
            #endif
        }
        else
            base = *exctable[i].base;

        if (!(*exctable[i].exc = PyErr_NewException(
                exctable[i].name, base, dict))) {
            goto exit;
        }
        Py_CLEAR(dict);
    }

    /* Make pgerror, pgcode and cursor default to None on psycopg
       error objects.  This simplifies error handling code that checks
       these attributes. */
    PyObject_SetAttrString(Error, "pgerror", Py_None);
    PyObject_SetAttrString(Error, "pgcode", Py_None);
    PyObject_SetAttrString(Error, "cursor", Py_None);

    /* install __reduce_ex__ on Error to make all the subclasses picklable.
     *
     * Don't install it on Py 2.4: it is not used by the pickle
     * protocol, and if called manually fails in an unsettling way,
     * probably because the exceptions were old-style classes. */
#if PY_VERSION_HEX >= 0x02050000
    if (!(descr = PyDescr_NewMethod((PyTypeObject *)Error,
            &psyco_error_reduce_ex_def))) {
        goto exit;
    }
    if (0 != PyObject_SetAttrString(Error,
            psyco_error_reduce_ex_def.ml_name, descr)) {
        goto exit;
    }
#endif

    rv = 0;

exit:
    Py_XDECREF(descr);
    Py_XDECREF(str);
    Py_XDECREF(dict);
    return rv;
}
Ejemplo n.º 27
0
static PyObject *parse_qs(PyObject *self, PyObject *args)
{

    PyObject *pairs, *dict;
    int i, n, len, lsize;
    char *qs;
    int keep_blank_values = 0;
    int strict_parsing = 0; /* XXX not implemented */

    if (! PyArg_ParseTuple(args, "s|ii", &qs, &keep_blank_values, 
                           &strict_parsing)) 
        return NULL; /* error */

    /* split query string by '&' and ';' into a list of pairs */
    /* PYTHON 2.5: 'PyList_New' uses Py_ssize_t for input parameters */ 
    pairs = PyList_New(0);
    if (pairs == NULL)
        return NULL;

    i = 0;
    len = strlen(qs);

    while (i < len) {

        PyObject *pair;
        char *cpair;
        int j = 0;

        /* PYTHON 2.5: 'PyString_FromStringAndSize' uses Py_ssize_t for input parameters */ 
        pair = PyString_FromStringAndSize(NULL, len);
        if (pair == NULL)
            return NULL;

        /* split by '&' or ';' */
        cpair = PyString_AS_STRING(pair);
        while ((qs[i] != '&') && (qs[i] != ';') && (i < len)) {
            /* replace '+' with ' ' */
            cpair[j] = (qs[i] == '+') ? ' ' : qs[i];
            i++;
            j++;
        }

        if (j) {
            /* PYTHON 2.5: '_PyString_Resize' uses Py_ssize_t for input parameters */ 
            _PyString_Resize(&pair, j);
            if (pair)
                PyList_Append(pairs, pair);
        }

        Py_XDECREF(pair);
        i++;
    }

    /*
     * now we have a list of "abc=def" string (pairs), let's split 
     * them all by '=' and put them in a dictionary.
     */
    
    dict = PyDict_New();
    if (dict == NULL)
        return NULL;

    /* PYTHON 2.5: 'PyList_Size' uses Py_ssize_t for input parameters */ 
    lsize = PyList_Size(pairs);
    n = 0;

    while (n < lsize) {

        PyObject *pair, *key, *val;
        char *cpair, *ckey, *cval;
        int k, v;

        pair = PyList_GET_ITEM(pairs, n);
        cpair = PyString_AS_STRING(pair);

        len = strlen(cpair);
        /* PYTHON 2.5: 'PyString_FromStringAndSize' uses Py_ssize_t for input parameters */ 
        key = PyString_FromStringAndSize(NULL, len);
        if (key == NULL) 
            return NULL;
        /* PYTHON 2.5: 'PyString_FromStringAndSize' uses Py_ssize_t for input parameters */ 
        val = PyString_FromStringAndSize(NULL, len);
        if (val == NULL) 
            return NULL;

        ckey = PyString_AS_STRING(key);
        cval = PyString_AS_STRING(val);

        i = 0;
        k = 0;
        v = 0;
        while (i < len) {
            if (cpair[i] != '=') {
                ckey[k] = cpair[i];
                k++;
                i++;
            }
            else {
                i++;      /* skip '=' */
                while (i < len) {
                    cval[v] = cpair[i];
                    v++;
                    i++;
                }
            }
        }

        ckey[k] = '\0';
        cval[v] = '\0';

        if (keep_blank_values || (v > 0)) {

            ap_unescape_url(ckey);
            ap_unescape_url(cval);

            /* PYTHON 2.5: '_PyString_Resize' uses Py_ssize_t for input parameters */ 
            _PyString_Resize(&key, strlen(ckey));
            /* PYTHON 2.5: '_PyString_Resize' uses Py_ssize_t for input parameters */ 
            _PyString_Resize(&val, strlen(cval));

            if (key && val) {

                ckey = PyString_AS_STRING(key);
                cval = PyString_AS_STRING(val);
        
                if (PyMapping_HasKeyString(dict, ckey)) {
                    PyObject *list;
                    list = PyDict_GetItem(dict, key);
                    PyList_Append(list, val);
                    /* PyDict_GetItem is a borrowed ref, no decref */
                }
                else {
                    PyObject *list;
                    list = Py_BuildValue("[O]", val);
                    PyDict_SetItem(dict, key, list);
                    Py_DECREF(list);
                }
            }
        }

        Py_XDECREF(key);
        Py_XDECREF(val);

        n++;
    }

    Py_DECREF(pairs);
    return dict;
}
Ejemplo n.º 28
0
PyMODINIT_FUNC
INIT_MODULE(_psycopg)(void)
{
#if PY_VERSION_HEX < 0x03020000
    static void *PSYCOPG_API[PSYCOPG_API_pointers];
    PyObject *c_api_object;
#endif

    PyObject *module = NULL, *dict;

#ifdef PSYCOPG_DEBUG
    if (getenv("PSYCOPG_DEBUG"))
        psycopg_debug_enabled = 1;
#endif

    Dprintf("initpsycopg: initializing psycopg %s", PSYCOPG_VERSION);

    /* initialize all the new types and then the module */
    Py_TYPE(&connectionType) = &PyType_Type;
    Py_TYPE(&cursorType)     = &PyType_Type;
    Py_TYPE(&typecastType)   = &PyType_Type;
    Py_TYPE(&qstringType)    = &PyType_Type;
    Py_TYPE(&binaryType)     = &PyType_Type;
    Py_TYPE(&isqlquoteType)  = &PyType_Type;
    Py_TYPE(&pbooleanType)   = &PyType_Type;
    Py_TYPE(&pintType)       = &PyType_Type;
    Py_TYPE(&pfloatType)     = &PyType_Type;
    Py_TYPE(&pdecimalType)   = &PyType_Type;
    Py_TYPE(&asisType)       = &PyType_Type;
    Py_TYPE(&listType)       = &PyType_Type;
    Py_TYPE(&chunkType)      = &PyType_Type;
    Py_TYPE(&NotifyType)     = &PyType_Type;
    Py_TYPE(&XidType)        = &PyType_Type;

    if (PyType_Ready(&connectionType) == -1) goto exit;
    if (PyType_Ready(&cursorType) == -1) goto exit;
    if (PyType_Ready(&typecastType) == -1) goto exit;
    if (PyType_Ready(&qstringType) == -1) goto exit;
    if (PyType_Ready(&binaryType) == -1) goto exit;
    if (PyType_Ready(&isqlquoteType) == -1) goto exit;
    if (PyType_Ready(&pbooleanType) == -1) goto exit;
    if (PyType_Ready(&pintType) == -1) goto exit;
    if (PyType_Ready(&pfloatType) == -1) goto exit;
    if (PyType_Ready(&pdecimalType) == -1) goto exit;
    if (PyType_Ready(&asisType) == -1) goto exit;
    if (PyType_Ready(&listType) == -1) goto exit;
    if (PyType_Ready(&chunkType) == -1) goto exit;
    if (PyType_Ready(&NotifyType) == -1) goto exit;
    if (PyType_Ready(&XidType) == -1) goto exit;

#ifdef PSYCOPG_EXTENSIONS
    Py_TYPE(&lobjectType)    = &PyType_Type;
    if (PyType_Ready(&lobjectType) == -1) goto exit;
#endif

    /* import mx.DateTime module, if necessary */
#ifdef HAVE_MXDATETIME
    Py_TYPE(&mxdatetimeType) = &PyType_Type;
    if (PyType_Ready(&mxdatetimeType) == -1) goto exit;
    if (0 != mxDateTime_ImportModuleAndAPI()) {
        PyErr_Clear();

        /* only fail if the mx typacaster should have been the default */
#ifdef PSYCOPG_DEFAULT_MXDATETIME
        PyErr_SetString(PyExc_ImportError,
            "can't import mx.DateTime module (requested as default adapter)");
        goto exit;
#endif
    }
#endif

    /* import python builtin datetime module, if available */
    pyDateTimeModuleP = PyImport_ImportModule("datetime");
    if (pyDateTimeModuleP == NULL) {
        Dprintf("initpsycopg: can't import datetime module");
        PyErr_SetString(PyExc_ImportError, "can't import datetime module");
        goto exit;
    }

    /* Initialize the PyDateTimeAPI everywhere is used */
    PyDateTime_IMPORT;
    if (psyco_adapter_datetime_init()) { goto exit; }

    Py_TYPE(&pydatetimeType) = &PyType_Type;
    if (PyType_Ready(&pydatetimeType) == -1) goto exit;

    /* import psycopg2.tz anyway (TODO: replace with C-level module?) */
    pyPsycopgTzModule = PyImport_ImportModule("psycopg2.tz");
    if (pyPsycopgTzModule == NULL) {
        Dprintf("initpsycopg: can't import psycopg2.tz module");
        PyErr_SetString(PyExc_ImportError, "can't import psycopg2.tz module");
        goto exit;
    }
    pyPsycopgTzLOCAL =
        PyObject_GetAttrString(pyPsycopgTzModule, "LOCAL");
    pyPsycopgTzFixedOffsetTimezone =
        PyObject_GetAttrString(pyPsycopgTzModule, "FixedOffsetTimezone");

    /* initialize the module and grab module's dictionary */
#if PY_MAJOR_VERSION < 3
    module = Py_InitModule("_psycopg", psycopgMethods);
#else
    module = PyModule_Create(&psycopgmodule);
#endif
    if (!module) { goto exit; }

    dict = PyModule_GetDict(module);

    /* initialize all the module's exported functions */
    /* PyBoxer_API[PyBoxer_Fake_NUM] = (void *)PyBoxer_Fake; */

    /* Create a CObject containing the API pointer array's address */
    /* If anybody asks for a PyCapsule we'll deal with it. */
#if PY_VERSION_HEX < 0x03020000
    c_api_object = PyCObject_FromVoidPtr((void *)PSYCOPG_API, NULL);
    if (c_api_object != NULL)
        PyModule_AddObject(module, "_C_API", c_api_object);
#endif

    /* other mixed initializations of module-level variables */
    if (!(psycoEncodings = PyDict_New())) { goto exit; }
    if (0 != psyco_encodings_fill(psycoEncodings)) { goto exit; }
    psyco_null = Bytes_FromString("NULL");
    if (!(psyco_DescriptionType = psyco_make_description_type())) { goto exit; }

    /* set some module's parameters */
    PyModule_AddStringConstant(module, "__version__", PSYCOPG_VERSION);
    PyModule_AddStringConstant(module, "__doc__", "psycopg PostgreSQL driver");
    PyModule_AddObject(module, "apilevel", Text_FromUTF8(APILEVEL));
    PyModule_AddObject(module, "threadsafety", PyInt_FromLong(THREADSAFETY));
    PyModule_AddObject(module, "paramstyle", Text_FromUTF8(PARAMSTYLE));

    /* put new types in module dictionary */
    PyModule_AddObject(module, "connection", (PyObject*)&connectionType);
    PyModule_AddObject(module, "cursor", (PyObject*)&cursorType);
    PyModule_AddObject(module, "ISQLQuote", (PyObject*)&isqlquoteType);
    PyModule_AddObject(module, "Notify", (PyObject*)&NotifyType);
    PyModule_AddObject(module, "Xid", (PyObject*)&XidType);
#ifdef PSYCOPG_EXTENSIONS
    PyModule_AddObject(module, "lobject", (PyObject*)&lobjectType);
#endif

    /* encodings dictionary in module dictionary */
    PyModule_AddObject(module, "encodings", psycoEncodings);

#ifdef HAVE_MXDATETIME
    /* If we can't find mx.DateTime objects at runtime,
     * remove them from the module (and, as consequence, from the adapters). */
    if (0 != psyco_adapter_mxdatetime_init()) {
        PyDict_DelItemString(dict, "DateFromMx");
        PyDict_DelItemString(dict, "TimeFromMx");
        PyDict_DelItemString(dict, "TimestampFromMx");
        PyDict_DelItemString(dict, "IntervalFromMx");
    }
#endif
    /* initialize default set of typecasters */
    if (0 != typecast_init(dict)) { goto exit; }

    /* initialize microprotocols layer */
    microprotocols_init(dict);
    if (0 != psyco_adapters_init(dict)) { goto exit; }

    /* create a standard set of exceptions and add them to the module's dict */
    if (0 != psyco_errors_init()) { goto exit; }
    psyco_errors_fill(dict);

    /* Solve win32 build issue about non-constant initializer element */
    cursorType.tp_alloc = PyType_GenericAlloc;
    binaryType.tp_alloc = PyType_GenericAlloc;
    isqlquoteType.tp_alloc = PyType_GenericAlloc;
    pbooleanType.tp_alloc = PyType_GenericAlloc;
    pintType.tp_alloc = PyType_GenericAlloc;
    pfloatType.tp_alloc = PyType_GenericAlloc;
    pdecimalType.tp_alloc = PyType_GenericAlloc;
    connectionType.tp_alloc = PyType_GenericAlloc;
    asisType.tp_alloc = PyType_GenericAlloc;
    qstringType.tp_alloc = PyType_GenericAlloc;
    listType.tp_alloc = PyType_GenericAlloc;
    chunkType.tp_alloc = PyType_GenericAlloc;
    pydatetimeType.tp_alloc = PyType_GenericAlloc;
    NotifyType.tp_alloc = PyType_GenericAlloc;
    XidType.tp_alloc = PyType_GenericAlloc;

#ifdef PSYCOPG_EXTENSIONS
    lobjectType.tp_alloc = PyType_GenericAlloc;
#endif

#ifdef HAVE_MXDATETIME
    mxdatetimeType.tp_alloc = PyType_GenericAlloc;
#endif

    Dprintf("initpsycopg: module initialization complete");

exit:
#if PY_MAJOR_VERSION > 2
    return module;
#else
    return;
#endif
}
Ejemplo n.º 29
0
// Convert a C++ object at an arbitary address to Python.
PyObject *Chimera::toPyObject(void *cpp) const
{
    if (_metatype == PyQt_PyObject::metatype)
    {
        if (_type)
        {
            // SIP knows the type (therefore it isn't really wrapped in a
            // PyQt_PyObject) but it's not registered with Qt.
            if (_name.endsWith('*'))
                cpp = *reinterpret_cast<void **>(cpp);

            return sipConvertFromType(cpp, _type, 0);
        }
        else
        {
            // Otherwise unwrap the Python object.
            PyQt_PyObject *pyobj_wrapper = reinterpret_cast<PyQt_PyObject *>(cpp);

            if (!pyobj_wrapper->pyobject)
            {
                PyErr_SetString(PyExc_TypeError,
                        "unable to convert a QVariant back to a Python object");

                return 0;
            }

            Py_INCREF(pyobj_wrapper->pyobject);

            return pyobj_wrapper->pyobject;
        }
    }

    PyObject *py = 0;

    switch (_metatype)
    {
    case QMetaType::Bool:
        py = PyBool_FromLong(*reinterpret_cast<bool *>(cpp));
        break;

    case QMetaType::Int:
        if (isFlag())
        {
            py = sipConvertFromType(cpp, _type, 0);
        }
        else if (isEnum())
        {
            py = sipConvertFromEnum(*reinterpret_cast<int *>(cpp), _type);
        }
        else
        {
            py = SIPLong_FromLong(*reinterpret_cast<int *>(cpp));
        }

        break;

    case QMetaType::UInt:
        {
            long ui = *reinterpret_cast<unsigned int *>(cpp);

            if (ui < 0)
                py = PyLong_FromUnsignedLong((unsigned long)ui);
            else
                py = SIPLong_FromLong(ui);

            break;
        }

    case QMetaType::Double:
        py = PyFloat_FromDouble(*reinterpret_cast<double *>(cpp));
        break;

    case QMetaType::VoidStar:
        py = sipConvertFromVoidPtr(*reinterpret_cast<void **>(cpp));
        break;

    case QMetaType::Long:
        py = SIPLong_FromLong(*reinterpret_cast<long *>(cpp));
        break;

    case QMetaType::LongLong:
        py = PyLong_FromLongLong(*reinterpret_cast<qlonglong *>(cpp));
        break;

    case QMetaType::Short:
        py = SIPLong_FromLong(*reinterpret_cast<short *>(cpp));
        break;

    case QMetaType::Char:
    case QMetaType::UChar:
        py = SIPBytes_FromStringAndSize(reinterpret_cast<char *>(cpp), 1);
        break;

    case QMetaType::ULong:
        py = PyLong_FromUnsignedLong(*reinterpret_cast<unsigned long *>(cpp));
        break;

    case QMetaType::ULongLong:
        py = PyLong_FromUnsignedLongLong(*reinterpret_cast<qulonglong *>(cpp));
        break;

    case QMetaType::UShort:
        py = SIPLong_FromLong(*reinterpret_cast<unsigned short *>(cpp));
        break;

    case QMetaType::Float:
        py = PyFloat_FromDouble(*reinterpret_cast<float *>(cpp));
        break;

    case QMetaType::QObjectStar:
        py = sipConvertFromType(*reinterpret_cast<void **>(cpp),
                sipType_QObject, 0);
        break;

    case QMetaType::QWidgetStar:
        if (sipType_QWidget)
            py = sipConvertFromType(*reinterpret_cast<void **>(cpp),
                    sipType_QWidget, 0);

        break;

    case QMetaType::QVariantList:
        {
            QVariantList *ql = reinterpret_cast<QVariantList *>(cpp);

            py = PyList_New(ql->size());

            if (py)
            {
                for (int i = 0; i < ql->size(); ++i)
                {
                    PyObject *val_obj = toAnyPyObject(ql->at(i));

                    if (!val_obj)
                    {
                        Py_DECREF(py);
                        py = 0;

                        break;
                    }

                    PyList_SET_ITEM(py, i, val_obj);
                }
            }

            break;
        }

    case QMetaType::QVariantMap:
        {
            py = PyDict_New();

            if (py)
            {
                QVariantMap *qm = reinterpret_cast<QVariantMap *>(cpp);

                for (QVariantMap::const_iterator it = qm->constBegin(); it != qm->constEnd(); ++it)
                    if (!add_variant_to_dict(py, it.key(), it.value()))
                    {
                        Py_DECREF(py);
                        py = 0;

                        break;
                    }
            }

            break;
        }

#if QT_VERSION >= 0x040500
    case QMetaType::QVariantHash:
        {
            py = PyDict_New();

            if (py)
            {
                QVariantHash *qh = reinterpret_cast<QVariantHash *>(cpp);

                for (QVariantHash::const_iterator it = qh->constBegin(); it != qh->constEnd(); ++it)
                    if (!add_variant_to_dict(py, it.key(), it.value()))
                    {
                        Py_DECREF(py);
                        py = 0;

                        break;
                    }
            }

            break;
        }
#endif

    case -1:
        {
            char *s = *reinterpret_cast<char **>(cpp);

            if (s)
            {
                py = SIPBytes_FromString(s);
            }
            else
            {
                Py_INCREF(Py_None);
                py = Py_None;
            }

            break;
        }

    default:
        if (_type)
        {
            if (_name.endsWith('*'))
            {
                py = sipConvertFromType(*reinterpret_cast<void **>(cpp),
                        _type, 0);
            }
            else
            {
                // Make a copy as it is a value type.
                void *copy = QMetaType::construct(_metatype, cpp);

                py = sipConvertFromNewType(copy, _type, 0);

                if (!py)
                    QMetaType::destroy(_metatype, copy);
            }
        }
    }

    if (!py)
        PyErr_Format(PyExc_TypeError,
                "unable to convert a C++ '%s' instance to a Python object",
                _name.constData());

    return py;
}
Ejemplo n.º 30
0
  /* "/home/abhinav/projects/fb-puzzles/breathalyzer/levenshtein.pyx":5
 * 
 * def levenshtein(char* s1, char* s2):
 *     return levenshtein_distance(s1, s2)             # <<<<<<<<<<<<<<
 */
  __Pyx_XDECREF(__pyx_r);
  __pyx_t_1 = PyInt_FromLong(levenshtein_distance(__pyx_v_s1, __pyx_v_s2)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 5; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
  __Pyx_GOTREF(__pyx_t_1);
  __pyx_r = __pyx_t_1;
  __pyx_t_1 = 0;
  goto __pyx_L0;

  __pyx_r = Py_None; __Pyx_INCREF(Py_None);
  goto __pyx_L0;
  __pyx_L1_error:;
  __Pyx_XDECREF(__pyx_t_1);
  __Pyx_AddTraceback("levenshtein.levenshtein");
  __pyx_r = NULL;
  __pyx_L0:;
  __Pyx_XGIVEREF(__pyx_r);
  __Pyx_RefNannyFinishContext();
  return __pyx_r;
}

static struct PyMethodDef __pyx_methods[] = {
  {__Pyx_NAMESTR("levenshtein"), (PyCFunction)__pyx_pf_11levenshtein_levenshtein, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(0)},
  {0, 0, 0, 0}
};

static void __pyx_init_filenames(void); /*proto*/

#if PY_MAJOR_VERSION >= 3
static struct PyModuleDef __pyx_moduledef = {
    PyModuleDef_HEAD_INIT,
    __Pyx_NAMESTR("levenshtein"),
    0, /* m_doc */
    -1, /* m_size */
    __pyx_methods /* m_methods */,
    NULL, /* m_reload */
    NULL, /* m_traverse */
    NULL, /* m_clear */
    NULL /* m_free */
};
#endif

static __Pyx_StringTabEntry __pyx_string_tab[] = {
  {&__pyx_n_s____main__, __pyx_k____main__, sizeof(__pyx_k____main__), 0, 0, 1, 1},
  {&__pyx_n_s____test__, __pyx_k____test__, sizeof(__pyx_k____test__), 0, 0, 1, 1},
  {&__pyx_n_s__s1, __pyx_k__s1, sizeof(__pyx_k__s1), 0, 0, 1, 1},
  {&__pyx_n_s__s2, __pyx_k__s2, sizeof(__pyx_k__s2), 0, 0, 1, 1},
  {0, 0, 0, 0, 0, 0, 0}
};
static int __Pyx_InitCachedBuiltins(void) {
  return 0;
  return -1;
}

static int __Pyx_InitGlobals(void) {
  if (__Pyx_InitStrings(__pyx_string_tab) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;};
  return 0;
  __pyx_L1_error:;
  return -1;
}

#if PY_MAJOR_VERSION < 3
PyMODINIT_FUNC initlevenshtein(void); /*proto*/
PyMODINIT_FUNC initlevenshtein(void)
#else
PyMODINIT_FUNC PyInit_levenshtein(void); /*proto*/
PyMODINIT_FUNC PyInit_levenshtein(void)
#endif
{
  PyObject *__pyx_t_1 = NULL;
  #if CYTHON_REFNANNY
  void* __pyx_refnanny = NULL;
  __Pyx_RefNanny = __Pyx_RefNannyImportAPI("refnanny");
  if (!__Pyx_RefNanny) {
      PyErr_Clear();
      __Pyx_RefNanny = __Pyx_RefNannyImportAPI("Cython.Runtime.refnanny");
      if (!__Pyx_RefNanny)
          Py_FatalError("failed to import 'refnanny' module");
  }
  __pyx_refnanny = __Pyx_RefNanny->SetupContext("PyMODINIT_FUNC PyInit_levenshtein(void)", __LINE__, __FILE__);
  #endif
  __pyx_init_filenames();
  __pyx_empty_tuple = PyTuple_New(0); if (unlikely(!__pyx_empty_tuple)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
  #if PY_MAJOR_VERSION < 3
  __pyx_empty_bytes = PyString_FromStringAndSize("", 0); if (unlikely(!__pyx_empty_bytes)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
  #else
  __pyx_empty_bytes = PyBytes_FromStringAndSize("", 0); if (unlikely(!__pyx_empty_bytes)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
  #endif
  /*--- Library function declarations ---*/
  /*--- Threads initialization code ---*/
  #if defined(__PYX_FORCE_INIT_THREADS) && __PYX_FORCE_INIT_THREADS
  #ifdef WITH_THREAD /* Python build with threading support? */
  PyEval_InitThreads();
  #endif
  #endif
  /*--- Module creation code ---*/
  #if PY_MAJOR_VERSION < 3
  __pyx_m = Py_InitModule4(__Pyx_NAMESTR("levenshtein"), __pyx_methods, 0, 0, PYTHON_API_VERSION);
  #else
  __pyx_m = PyModule_Create(&__pyx_moduledef);
  #endif
  if (!__pyx_m) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;};
  #if PY_MAJOR_VERSION < 3
  Py_INCREF(__pyx_m);
  #endif
  __pyx_b = PyImport_AddModule(__Pyx_NAMESTR(__Pyx_BUILTIN_MODULE_NAME));
  if (!__pyx_b) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;};
  if (__Pyx_SetAttrString(__pyx_m, "__builtins__", __pyx_b) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;};
  /*--- Initialize various global constants etc. ---*/
  if (unlikely(__Pyx_InitGlobals() < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
  if (__pyx_module_is_main_levenshtein) {
    if (__Pyx_SetAttrString(__pyx_m, "__name__", __pyx_n_s____main__) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;};
  }
  /*--- Builtin init code ---*/
  if (unlikely(__Pyx_InitCachedBuiltins() < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
  /*--- Global init code ---*/
  /*--- Function export code ---*/
  /*--- Type init code ---*/
  /*--- Type import code ---*/
  /*--- Function import code ---*/
  /*--- Execution code ---*/

  /* "/home/abhinav/projects/fb-puzzles/breathalyzer/levenshtein.pyx":1
 * cdef extern from "levenshtein_distance.h":             # <<<<<<<<<<<<<<
 *      int levenshtein_distance(char *s,char *t)
 * 
 */
  __pyx_t_1 = PyDict_New(); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
  __Pyx_GOTREF(((PyObject *)__pyx_t_1));
  if (PyObject_SetAttr(__pyx_m, __pyx_n_s____test__, ((PyObject *)__pyx_t_1)) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
  __Pyx_DECREF(((PyObject *)__pyx_t_1)); __pyx_t_1 = 0;
  goto __pyx_L0;
  __pyx_L1_error:;
  __Pyx_XDECREF(__pyx_t_1);
  if (__pyx_m) {
    __Pyx_AddTraceback("init levenshtein");
    Py_DECREF(__pyx_m); __pyx_m = 0;
  } else if (!PyErr_Occurred()) {
    PyErr_SetString(PyExc_ImportError, "init levenshtein");
  }
  __pyx_L0:;
  __Pyx_RefNannyFinishContext();
  #if PY_MAJOR_VERSION < 3
  return;
  #else
  return __pyx_m;
  #endif
}