示例#1
0
static int __Pyx_setup_reduce(PyObject* type_obj) {
    int ret = 0;
    PyObject* builtin_object = NULL;
    static PyObject *object_reduce = NULL;
    static PyObject *object_reduce_ex = NULL;
    PyObject *reduce = NULL;
    PyObject *reduce_ex = NULL;
    PyObject *reduce_cython = NULL;
    PyObject *setstate = NULL;
    PyObject *setstate_cython = NULL;

    if (PyObject_HasAttrString(type_obj, "__getstate__")) goto GOOD;

    if (object_reduce_ex == NULL) {
        __Pyx_setup_reduce_GET_ATTR_OR_BAD(builtin_object, __pyx_b, "object");
        __Pyx_setup_reduce_GET_ATTR_OR_BAD(object_reduce, builtin_object, "__reduce__");
        __Pyx_setup_reduce_GET_ATTR_OR_BAD(object_reduce_ex, builtin_object, "__reduce_ex__");
    }

    __Pyx_setup_reduce_GET_ATTR_OR_BAD(reduce_ex, type_obj, "__reduce_ex__");
    if (reduce_ex == object_reduce_ex) {
        __Pyx_setup_reduce_GET_ATTR_OR_BAD(reduce, type_obj, "__reduce__");
        if (object_reduce == reduce
            || (strcmp(reduce->ob_type->tp_name, "method_descriptor") == 0
                && strcmp(((PyMethodDescrObject*)reduce)->d_method->ml_name, "__reduce_cython__") == 0)) {
            __Pyx_setup_reduce_GET_ATTR_OR_BAD(reduce_cython, type_obj, "__reduce_cython__");
            ret = PyDict_SetItemString(((PyTypeObject*)type_obj)->tp_dict, "__reduce__", reduce_cython); if (ret < 0) goto BAD;
            ret = PyDict_DelItemString(((PyTypeObject*)type_obj)->tp_dict, "__reduce_cython__"); if (ret < 0) goto BAD;

            setstate = PyObject_GetAttrString(type_obj, "__setstate__");
            if (!setstate) PyErr_Clear();
            if (!setstate
                || (strcmp(setstate->ob_type->tp_name, "method_descriptor") == 0
                    && strcmp(((PyMethodDescrObject*)setstate)->d_method->ml_name, "__setstate_cython__") == 0)) {
            __Pyx_setup_reduce_GET_ATTR_OR_BAD(setstate_cython, type_obj, "__setstate_cython__");
                ret = PyDict_SetItemString(((PyTypeObject*)type_obj)->tp_dict, "__setstate__", setstate_cython); if (ret < 0) goto BAD;
                ret = PyDict_DelItemString(((PyTypeObject*)type_obj)->tp_dict, "__setstate_cython__"); if (ret < 0) goto BAD;
            }
            PyType_Modified((PyTypeObject*)type_obj);
        }
    }
    goto GOOD;

BAD:
    if (!PyErr_Occurred()) PyErr_Format(PyExc_RuntimeError, "Unable to initialize pickling for %s", ((PyTypeObject*)type_obj)->tp_name);
    ret = -1;
GOOD:
    Py_XDECREF(builtin_object);
    Py_XDECREF(reduce);
    Py_XDECREF(reduce_ex);
    Py_XDECREF(reduce_cython);
    Py_XDECREF(setstate);
    Py_XDECREF(setstate_cython);
    return ret;
}
示例#2
0
BOOL py_to_PRINTER_INFO_2(PRINTER_INFO_2 *info, PyObject *dict,
			  TALLOC_CTX *mem_ctx)
{
	PyObject *obj, *dict_copy = PyDict_Copy(dict);
	BOOL result = False;

	/* Convert security descriptor - may be NULL */

	info->secdesc = NULL;

	if ((obj = PyDict_GetItemString(dict_copy, "security_descriptor"))) {

		if (!PyDict_Check(obj))
			goto done;

		if (!py_to_SECDESC(&info->secdesc, obj, mem_ctx))
			goto done;

		PyDict_DelItemString(dict_copy, "security_descriptor");
	}

	/* Convert device mode */

	if (!(obj = PyDict_GetItemString(dict_copy, "device_mode"))
	    || !PyDict_Check(obj))
		goto done;

	info->devmode = _talloc(mem_ctx, sizeof(DEVICEMODE));

	if (!py_to_DEVICEMODE(info->devmode, obj))
		goto done;

	PyDict_DelItemString(dict_copy, "device_mode");

	/* Check info level */

	if (!(obj = PyDict_GetItemString(dict_copy, "level")) ||
	    !PyInt_Check(obj))
		goto done;

	PyDict_DelItemString(dict_copy, "level");

	/* Convert remaining elements of dictionary */

	if (!to_struct(info, dict_copy, py_PRINTER_INFO_2))
		goto done;

	result = True;

done:
	Py_DECREF(dict_copy);
	return result;
}
示例#3
0
	bool PDict::DelItem(char* key) {
		if (!this->myObject) { throw new NULLPyObjectException(); }
		if (PyDict_DelItemString(this->myObject, key) == -1) {
			return false;
		}
		return true;
	}
示例#4
0
/*
 * Add an image_id to the dictionary; the module name of the loaded image
 * is the key.  Note that if the key is already in the dict, we unload
 * that image; this should allow reload() to work on dynamically loaded
 * modules (super-keen!).
 */
static void beos_add_dyn( char *name, image_id id )
{
	int retval;
	PyObject *py_id;

	if( beos_dyn_images == NULL ) {
		beos_init_dyn();
	}

#ifdef WITH_THREAD
	retval = PyThread_acquire_lock( beos_dyn_lock, 1 );
#endif

	/* If there's already an object with this key in the dictionary,
	 * we're doing a reload(), so let's nuke it.
	 */
	py_id = PyDict_GetItemString( beos_dyn_images, name );
	if( py_id ) {
		beos_nuke_dyn( py_id );
		retval = PyDict_DelItemString( beos_dyn_images, name );
	}

	py_id = PyInt_FromLong( (long)id );
	if( py_id ) {
		retval = PyDict_SetItemString( beos_dyn_images, name, py_id );
	}

#ifdef WITH_THREAD
	PyThread_release_lock( beos_dyn_lock );
#endif
}
示例#5
0
bool uninstall_py_dlls(void)
{
	PyObject *modules = PyImport_GetModuleDict();
	int i = 0;

	while(true)
	{
		if(g_funs[i] == NULL)
			break;

		DEBUG_MSG(fmt::format("Script::uninstall_py_dlls(): {}\n", g_sfuns[i]));
		PyObject * m = g_importedModules[i++];
		if(m == NULL)
		{
			return false;
		}

		Py_DECREF(m);

		struct PyModuleDef *def;
		def = PyModule_GetDef(m);
		if (!def) {
			PyErr_BadInternalCall();
			return false;
		}

		if (PyState_RemoveModule(def) < 0 || PyDict_DelItemString(modules, def->m_name) < 0)
			return false;
	}

	return true;
}
示例#6
0
// dtor
static void
AtTime_dealloc( PyObject* self ) {
	AtTime * at = (AtTime*)self;
	
	PyObject * tsd = PyThreadState_GetDict();
	PyObject * atd = PyDict_GetItemString(tsd, "_AtTime" );
	if( atd ) {
		PyObject * cur_stack = PyDict_GetItemString( atd, "current_stack" );
		PyObject * time_stack = PyDict_GetItemString( atd, "time_stack" );
		
		Py_ssize_t time_top = PyList_Size(time_stack) - 1;
		PyObject * hashKey = PyLong_FromLong( PyObject_Hash((PyObject*)self) );
		Py_ssize_t pos = PySequence_Index(cur_stack, hashKey);
		Py_DECREF(hashKey);
		
		// Restore the correct time value if we are current
		if( PyList_Size(cur_stack) == pos + 1 ) {
			thread_local(current_time) = PyLong_AsLong( PyList_GetItem( time_stack, time_top ) );
			//PySys_WriteStdout( "Current AtTime object destroyed, restoring thread_local(current_time) to %i\n", thread_local(current_time) );
			PySequence_DelItem(time_stack,time_top);
		} else
			// If we aren't current, then we delete the time at the position one above where we are in the current_stack
			PySequence_DelItem(time_stack,pos+1);
		
		PySequence_DelItem(cur_stack,pos);
		
		// If we are the last AtTime object local to this thread, then remove the _AtTime thread-local dict
		if( PyList_Size(cur_stack) == 0 ) {
			thread_local(use_time_context) = (PyDict_GetItemString( atd, "restore_use_time_context" ) == Py_True) ? TRUE : FALSE;
			//PySys_WriteStdout( "Last AtTime object destroyed, setting thread_local(use_time_context) to FALSE\n" );
			PyDict_DelItemString(tsd, "_AtTime");
		}
	}
	self->ob_type->tp_free(self);
}
示例#7
0
BOOL py_to_DEVICEMODE(DEVICEMODE *devmode, PyObject *dict)
{
	PyObject *obj, *dict_copy = PyDict_Copy(dict);
	BOOL result = False;

	if (!(obj = PyDict_GetItemString(dict_copy, "private")))
		goto done;

	if (!PyString_Check(obj))
		goto done;

	devmode->dev_private = PyString_AsString(obj);
	devmode->driverextra = PyString_Size(obj);

	PyDict_DelItemString(dict_copy, "private");

	if (!to_struct(devmode, dict_copy, py_DEVICEMODE))
		goto done;

	result = True;

done:
	Py_DECREF(dict_copy);
	return result;
}
void CLocaLogicImpl::DeletedL(const TTupleName& aName, const TDesC& aSubName)
{
	if (aName==KLocaScriptTuple) {
		if (aSubName.Length()>0 && aSubName[0]!='_') {
			TInterpreterAutoLock interpr;
			// borrowed
			PyObject* main_module = PyImport_AddModule("__main__");
			if (! main_module ) return;
			// borrowed
			PyObject* global_dict = PyModule_GetDict(main_module);
			if (! global_dict ) return;

			auto_ptr<HBufC8> subname8(HBufC8::NewL(aSubName.Length()+10));
			TPtr8 p=subname8->Des();
			TInt err=KErrNone;
			TInt unconverted=0, unconverted_pos=0;
			err=iCC->ConvertFromUnicode(p, aSubName, unconverted, unconverted_pos);
			if (err!=KErrNone || unconverted!=0) return;
			subname8->Des().Append('\0');

			PyDict_DelItemString(global_dict, (char*)subname8->Ptr());
			TInt pos;
			DeleteFromArrayL(iFunctions, *subname8);
			DeleteFromArrayL(iErrorFunctions, *subname8);
		}
	}
}
示例#9
0
int CaRun_SimpleFileExFlags(FILE* fp, const char* filename, int closeit,
		CaCompilerFlags* flags)
{
#if 0
    PyObject *m, *d, *v;
    const char *ext;
    int set_file_name = 0, len, ret = -1;

    m = PyImport_AddModule("__main__");
    if (m == NULL)
        return -1;
    Py_INCREF(m);
    d = PyModule_GetDict(m);
    if (PyDict_GetItemString(d, "__file__") == NULL) {
        PyObject *f = PyString_FromString(filename);
        if (f == NULL)
            goto done;
        if (PyDict_SetItemString(d, "__file__", f) < 0) {
            Py_DECREF(f);
            goto done;
        }
        set_file_name = 1;
        Py_DECREF(f);
    }
    len = strlen(filename);
    ext = filename + len - (len > 4 ? 4 : 0);
    if (maybe_pyc_file(fp, filename, ext, closeit)) {
        /* Try to run a pyc file. First, re-open in binary */
        if (closeit)
            fclose(fp);
        if ((fp = fopen(filename, "rb")) == NULL) {
            fprintf(stderr, "python: Can't reopen .pyc file\n");
            goto done;
        }
        /* Turn on optimization if a .pyo file is given */
        if (strcmp(ext, ".pyo") == 0)
            Py_OptimizeFlag = 1;
        v = run_pyc_file(fp, filename, d, d, flags);
    } else {
        v = PyRun_FileExFlags(fp, filename, Py_file_input, d, d,
                              closeit, flags);
    }
    if (v == NULL) {
        PyErr_Print();
        goto done;
    }
    Py_DECREF(v);
    if (Py_FlushLine())
        PyErr_Clear();
    ret = 0;
  done:
    if (set_file_name && PyDict_DelItemString(d, "__file__"))
        PyErr_Clear();
    Py_DECREF(m);
    return ret;

#endif
	return 0;
}
/**
 * @brief Removes all the entries from the dictionary related to the given user
 *
 * pythonInit() must have been called before or an error will occur (the module is not loaded)
 * @param user Name of the user whose entries will be removed
 * @return 1 on success, or 0 otherwise
 */
int dictionaryRemoveUserEntries(const char* user){
    PyObject *dictionary;

    if((dictionary = getDictionary()) == Py_None){
        return 0;
    }

    if(PyDict_Contains(PyDict_GetItemString(dictionary, "incoming"), PyUnicode_FromString(user))){
        PyDict_DelItemString(PyDict_GetItemString(dictionary, "incoming"), user);
    }

    if(PyDict_Contains(PyDict_GetItemString(dictionary, "outgoing"), PyUnicode_FromString(user))){
        PyDict_DelItemString(PyDict_GetItemString(dictionary, "outgoing"), user);
    }

    setDictionary(dictionary);
    Py_XDECREF(dictionary);

    return 1;
}
示例#11
0
static void
PLy_function_delete_args(PLyProcedure *proc)
{
	int			i;

	if (!proc->argnames)
		return;

	for (i = 0; i < proc->nargs; i++)
		if (proc->argnames[i])
			PyDict_DelItemString(proc->globals, proc->argnames[i]);
}
示例#12
0
static PyObject *
GlobalHotkey_unbind (GlobalHotkey *self,
                     PyObject     *args)
{
  char *key;

  if (!PyArg_ParseTuple (args, "s", &key))
    return NULL;

  keybinder_unbind (key, caller);
  PyDict_DelItemString (self->binded, key);
  return Py_BuildValue ("");
}
示例#13
0
	avl_tree_setattr(avl_tree_Object * self, char *name, PyObject * v)
{
#ifdef DOCUMENTATION
	if (v == NULL) {
		int rv = PyDict_DelItemString(self->x_attr, name);

		if (rv < 0)
			PyErr_SetString(PyExc_AttributeError,
							"delete non-existing avl_tree attribute");
		return rv;
	}
	return PyDict_SetItemString(self->x_attr, name, v);
#endif							/* DOCUMENTATION */
	return -1;
}
示例#14
0
static int Polygon_setattr(Polygon *self, char *name, PyObject *v) {
    if (self->attr == NULL) {
        self->attr = PyDict_New();
        if (self->attr == NULL)
            return -1;
    }
    if (v == NULL) {
        int rv = PyDict_DelItemString(self->attr, name);
        if (rv < 0)
            PyErr_SetString(PyExc_AttributeError,
                            "delete non-existing Polygon attribute");
        return rv;
    }
    else
        return PyDict_SetItemString(self->attr, name, v);
}
示例#15
0
static int
EC_init(PyTypeObject *self, PyObject *args, PyObject *kw)
{
  PyObject *__class_init__, *r;

  if (PyType_Type.tp_init(OBJECT(self), args, kw) < 0) 
    return -1; 

  if (self->tp_dict != NULL)
    {
      r = PyDict_GetItemString(self->tp_dict, "__doc__");
      if ((r == Py_None) && 
          (PyDict_DelItemString(self->tp_dict, "__doc__") < 0)
          )
        return -1;
    }

  if (EC_init_of(self) < 0)
    return -1;

  /* Call __class_init__ */
  __class_init__ = PyObject_GetAttr(OBJECT(self), str__class_init__);
  if (__class_init__ == NULL)
    {
      PyErr_Clear();
      return 0;
    }

  if (! (PyMethod_Check(__class_init__) 
         && PyMethod_GET_FUNCTION(__class_init__)
         )
      )
    {
      Py_DECREF(__class_init__);
      PyErr_SetString(PyExc_TypeError, "Invalid type for __class_init__");
      return -1;
    }

  r = PyObject_CallFunctionObjArgs(PyMethod_GET_FUNCTION(__class_init__),
                                   OBJECT(self), NULL);
  Py_DECREF(__class_init__);
  if (! r)
    return -1;
  Py_DECREF(r);
  
  return 0;
}
static int PythonSatGraph_setattr(PythonSatGraph *xp, char *name, PyObject *v)
{
	if (xp->x_attr == NULL) {
		xp->x_attr = PyDict_New();
		if (xp->x_attr == NULL)
			return -1;
	}
	if (v == NULL) {
		int rv = PyDict_DelItemString(xp->x_attr, name);
		if (rv < 0)
			PyErr_SetString(PyExc_AttributeError,
                                        "delete non-existing LDPCCode attribute");
		return rv;
	}
	else
		return PyDict_SetItemString(xp->x_attr, name, v);
}
示例#17
0
static int
_librsync_patchmaker_setattr(_librsync_PatchMakerObject *pm,
							 char *name, PyObject *v)
{
  if (pm->x_attr == NULL) {
	pm->x_attr = PyDict_New();
	if (pm->x_attr == NULL) return -1;
  }
  if (v == NULL) {
	int rv = PyDict_DelItemString(pm->x_attr, name);
	if (rv < 0)
	  PyErr_SetString(PyExc_AttributeError,
					  "delete non-existing patchmaker attribute");
	return rv;
  }
  else return PyDict_SetItemString(pm->x_attr, name, v);
}
示例#18
0
static PyObject *
new_(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
  PyObject *o;
  PygtsObject *obj;
  guint alloc_gtsobj = TRUE;

  /* Parse the args */
  if(kwds) {
    o = PyDict_GetItemString(kwds,"alloc_gtsobj");
    if(o==Py_False) {
      alloc_gtsobj = FALSE;
    }
    if(o!=NULL) {
      PyDict_DelItemString(kwds, "alloc_gtsobj");
    }
  }
  if(kwds) {
    Py_INCREF(Py_False);
    PyDict_SetItemString(kwds,"alloc_gtsobj", Py_False);
  }

  /* Chain up */
  obj = PYGTS_OBJECT(PygtsPointType.tp_new(type,args,kwds));

  /* Allocate the gtsobj (if needed) */
  if( alloc_gtsobj ) {
    obj->gtsobj = GTS_OBJECT(gts_vertex_new(gts_vertex_class(),0,0,0));
    if( obj->gtsobj == NULL )  {
      PyErr_SetString(PyExc_MemoryError, "could not create Vertex");
      return NULL;
    }

    /* Create the parent GtsSegment */
    if( (obj->gtsobj_parent=parent(GTS_VERTEX(obj->gtsobj))) == NULL ) {
      gts_object_destroy(obj->gtsobj);
      obj->gtsobj = NULL;
      return NULL;
    }

    pygts_object_register(obj);
  }

  return (PyObject*)obj;
}
PYCURL_INTERNAL int
my_setattr(PyObject **dict, char *name, PyObject *v)
{
    if (v == NULL) {
        int rv = -1;
        if (*dict != NULL)
            rv = PyDict_DelItemString(*dict, name);
        if (rv < 0)
            PyErr_SetString(PyExc_AttributeError, "delete non-existing attribute");
        return rv;
    }
    if (*dict == NULL) {
        *dict = PyDict_New();
        if (*dict == NULL)
            return -1;
    }
    return PyDict_SetItemString(*dict, name, v);
}
示例#20
0
文件: cdefer.c 项目: anrysev/twisted
/* Returns a NEW reference to the callback/errback arg, and to the
 * cbackArgs, but a BORROWED reference to the keywords. In case of
 * error, no references are returned/touched */
static PyObject *extract_cback_args_kw(char *argname,
                                       PyObject *args, PyObject *kwargs,
                                       PyObject **cbackArgs,
                                       PyObject **cbackKeywords) {
    PyObject *cback;

    if (kwargs) {
        (*cbackKeywords) = kwargs;
    } else {
        (*cbackKeywords) = Py_None;
    }
    if (PyTuple_Size(args) > 0) {
        cback = PyTuple_GET_ITEM(args, 0);
        if (!cback) {
            return NULL;
        }
        (*cbackArgs) = PyTuple_GetSlice(args, 1, PyTuple_Size(args));
        if (!(*cbackArgs)) {
            return NULL;
        }
        Py_INCREF(cback);
    } else {
        cback = PyDict_GetItemString((*cbackKeywords), argname);
        if (!cback) {
            PyErr_Format(PyExc_TypeError,
                         "addCallback requires '%s' argument'", argname);
            return NULL;
        }
        (*cbackArgs) = Py_None;
        Py_INCREF(Py_None);

        /* "callback" in the keyword dict may be the only reference to
         * it, and we delete it from the dict, so we must own a
         * reference too */
        Py_INCREF(cback);

        if (PyDict_DelItemString((*cbackKeywords), argname) == -1) {
            Py_DECREF(cback);
            Py_DECREF(Py_None);
            return NULL;
        }
    }
    return cback;
}
示例#21
0
void close_aerospike_object(aerospike *as, as_error *err, char *alias_to_search, PyObject *py_persistent_item)
{
		if (((AerospikeGlobalHosts*)py_persistent_item)->ref_cnt == 1) {
			PyDict_DelItemString(py_global_hosts, alias_to_search);
			AerospikeGlobalHosts_Del(py_persistent_item);
			aerospike_close(as, err);

			/*
			* Need to free memory allocated to host address string
			* in AerospikeClient_Type_Init.
			*/
			for( int i = 0; i < (int)as->config.hosts_size; i++) {
				free((void *) as->config.hosts[i].addr);
			}

			Py_BEGIN_ALLOW_THREADS
			aerospike_destroy(as);
			Py_END_ALLOW_THREADS
		} else {
static int m_setattr(PyObject **dict, char *name, PyObject *v)
{
    if (!v) {
        int rv = -1;
        if (*dict)
            rv = PyDict_DelItemString(*dict, name);
        if (rv < 0) {
            PyErr_SetString(PyExc_AttributeError, 
                            "delete non-existing attribute");
            return rv;
        }
    }
    if (!*dict) {
        *dict = PyDict_New();
        if (!*dict)
            return -1;
    }
    return PyDict_SetItemString(*dict, name, v);
}
示例#23
0
文件: _yappi.c 项目: sumerc/yappi
static PyObject*
clear_stats(PyObject *self, PyObject *args)
{
    PyObject *d;

    if (!yapphavestats) {
        Py_RETURN_NONE;
    }

    current_ctx = NULL;
    prev_ctx = NULL;
    initial_ctx = NULL;

    henum(contexts, _ctxenumdel, NULL);
    htdestroy(contexts);
    contexts = NULL;

    fldestroy(flpit);
    flpit = NULL;

    fldestroy(flctx);
    flctx = NULL;

    yappinitialized = 0;
    yapphavestats = 0;
    ycurfuncindex = 0;
    ycurthreadindex = 0;

    d = PyThreadState_GET()->dict;
    if (PyDict_GetItemString(d, "_yappi_tid")) {
        PyDict_DelItemString(d, "_yappi_tid");
    }

    Py_CLEAR(test_timings);

// check for mem leaks if DEBUG_MEM is specified
#ifdef DEBUG_MEM
    YMEMLEAKCHECK();
#endif

    Py_RETURN_NONE;
}
示例#24
0
BOOL py_to_PRINTER_INFO_1(PRINTER_INFO_1 *info, PyObject *dict)
{
	PyObject *obj, *dict_copy = PyDict_Copy(dict);
	BOOL result = False;

	if (!(obj = PyDict_GetItemString(dict_copy, "level")) ||
	    !PyInt_Check(obj))
		goto done;

	PyDict_DelItemString(dict_copy, "level");

	if (!to_struct(info, dict_copy, py_PRINTER_INFO_1))
		goto done;

	result = True;

done:
	Py_DECREF(dict_copy);
	return result;
}
示例#25
0
static PyObject *BC_connect(BuildingClass *self, PyObject *args)
{
        char *signal_name;
        PyObject *callback;
        if (!PyArg_ParseTuple(args, "sO", &signal_name, &callback))
                return NULL;
        if(callback == Py_None)
        {
                if(PyDict_DelItemString(self->callbacks, signal_name) == -1)
                        PyErr_Clear(); /* No error if key doesn't exist */
                Py_RETURN_NONE;
        }
        if (!PyCallable_Check(callback))
        {
                PyErr_SetString(PyExc_StandardError,
                                "callback must be callable");
                return NULL;
        }
        PyDict_SetItemString(self->callbacks, signal_name, callback);
        Py_RETURN_NONE;
}
示例#26
0
static int
_pygst_element_init (gpointer gclass, PyTypeObject * pyclass)
{
  PyObject *templates, *metadata;

  GST_DEBUG ("_pygst_element_init for gclass %p", gclass);
  templates = PyDict_GetItemString (pyclass->tp_dict, "__gsttemplates__");
  if (templates) {
    if (add_templates (gclass, templates) != 0)
      return -1;
  } else {
    PyErr_Clear ();
  }
  metadata = PyDict_GetItemString (pyclass->tp_dict, "__gstmetadata__");
  if (metadata) {
    if (_pygst_element_set_metadata (gclass, metadata) != 0)
      return -1;
    PyDict_DelItemString (pyclass->tp_dict, "__gstmetadata__");
  } else {
    PyErr_Clear ();
  }

  return 0;
}
示例#27
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;
    if (PyType_Ready(&connectionType) == -1) goto exit;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    Py_TYPE(&errorType) = &PyType_Type;
    errorType.tp_base = (PyTypeObject *)PyExc_StandardError;
    if (PyType_Ready(&errorType) == -1) goto exit;

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

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

    /* initialize libcrypto threading callbacks */
    psyco_libcrypto_threads_init();

    /* 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;

    /* 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_AddIntConstant(module, "__libpq_version__", PG_VERSION_NUM);
    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);
    PyModule_AddObject(module, "Diagnostics", (PyObject*)&diagnosticsType);
    PyModule_AddObject(module, "AsIs", (PyObject*)&asisType);
    PyModule_AddObject(module, "Binary", (PyObject*)&binaryType);
    PyModule_AddObject(module, "Boolean", (PyObject*)&pbooleanType);
    PyModule_AddObject(module, "Decimal", (PyObject*)&pdecimalType);
    PyModule_AddObject(module, "Int", (PyObject*)&pintType);
    PyModule_AddObject(module, "Float", (PyObject*)&pfloatType);
    PyModule_AddObject(module, "List", (PyObject*)&listType);
    PyModule_AddObject(module, "QuotedString", (PyObject*)&qstringType);
    PyModule_AddObject(module, "lobject", (PyObject*)&lobjectType);
    PyModule_AddObject(module, "Column", psyco_DescriptionType);

    /* 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);

    Dprintf("initpsycopg: module initialization complete");

exit:
#if PY_MAJOR_VERSION > 2
    return module;
#else
    return;
#endif
}
示例#28
0
static int
fortran_setattr(PyFortranObject *fp, char *name, PyObject *v) {
    int i,j,flag;
    PyArrayObject *arr = NULL;
    for (i=0,j=1;i<fp->len && (j=strcmp(name,fp->defs[i].name));i++);
    if (j==0) {
        if (fp->defs[i].rank==-1) {
            PyErr_SetString(PyExc_AttributeError,"over-writing fortran routine");
            return -1;
        }
        if (fp->defs[i].func!=NULL) { /* is allocatable array */
            npy_intp dims[F2PY_MAX_DIMS];
            int k;
            save_def = &fp->defs[i];
            if (v!=Py_None) {     /* set new value (reallocate if needed --
                                     see f2py generated code for more
                                     details ) */
                for(k=0;k<fp->defs[i].rank;k++) dims[k]=-1;
                if ((arr = array_from_pyobj(fp->defs[i].type,dims,fp->defs[i].rank,F2PY_INTENT_IN,v))==NULL)
                    return -1;
                (*(fp->defs[i].func))(&fp->defs[i].rank,arr->dimensions,set_data,&flag);
            } else {             /* deallocate */
                for(k=0;k<fp->defs[i].rank;k++) dims[k]=0;
                (*(fp->defs[i].func))(&fp->defs[i].rank,dims,set_data,&flag);
                for(k=0;k<fp->defs[i].rank;k++) dims[k]=-1;
            }
            memcpy(fp->defs[i].dims.d,dims,fp->defs[i].rank*sizeof(npy_intp));
        } else {                     /* not allocatable array */
            if ((arr = array_from_pyobj(fp->defs[i].type,fp->defs[i].dims.d,fp->defs[i].rank,F2PY_INTENT_IN,v))==NULL)
                return -1;
        }
        if (fp->defs[i].data!=NULL) { /* copy Python object to Fortran array */
            npy_intp s = PyArray_MultiplyList(fp->defs[i].dims.d,arr->nd);
            if (s==-1)
                s = PyArray_MultiplyList(arr->dimensions,arr->nd);
            if (s<0 ||
                (memcpy(fp->defs[i].data,arr->data,s*PyArray_ITEMSIZE(arr)))==NULL) {
                if ((PyObject*)arr!=v) {
                    Py_DECREF(arr);
                }
                return -1;
            }
            if ((PyObject*)arr!=v) {
                Py_DECREF(arr);
            }
        } else return (fp->defs[i].func==NULL?-1:0);
        return 0; /* succesful */
    }
    if (fp->dict == NULL) {
        fp->dict = PyDict_New();
        if (fp->dict == NULL)
            return -1;
    }
    if (v == NULL) {
        int rv = PyDict_DelItemString(fp->dict, name);
        if (rv < 0)
            PyErr_SetString(PyExc_AttributeError,"delete non-existing fortran attribute");
        return rv;
    }
    else
        return PyDict_SetItemString(fp->dict, name, v);
}
PyObject * py_cps_get(PyObject *self, PyObject *args) {
    PyObject * param_list;

    cps_api_get_params_t gr;
    if (cps_api_get_request_init (&gr)==cps_api_ret_code_ERR) {
        py_set_error_string("Failed to initialize the get req");
        return nullptr;
    }

    cps_api_get_request_guard rg(&gr);

    PyObject *res_obj;

    if (! PyArg_ParseTuple( args, "O!O", &PyList_Type, &param_list,&res_obj)) {
        py_set_error_string("Failed to parse input args.");
        return nullptr;
    }

    PyObject * lst = NULL;

    if (PyDict_Check(res_obj)) {
        PyObject *l = PyList_New(0);
        PyRef _l(l);
        if (l==NULL) {
            py_set_error_string("Can not create a list.");
            return nullptr;
        }
        PyObject *_prev = PyDict_GetItemString(res_obj,"list");
        if (_prev!=NULL) {
            PyDict_DelItemString(res_obj,"list");
        }

        if (!py_cps_util_set_item_to_dict(res_obj,"list",l)) {
            py_set_error_string("Can not create a list.");
            return nullptr;
        }
        lst = l;
    }
    if (PyList_Check(res_obj)) {
        lst = res_obj;
    }
    if (lst==NULL) {
        py_set_error_string("The return args are invalid.");
        return nullptr;
    }
    Py_ssize_t str_keys = PyList_Size(param_list);
    {
        Py_ssize_t ix = 0;
        for ( ;ix < str_keys ; ++ix ) {
            PyObject *strObj = PyList_GetItem(param_list, ix);
            if (PyString_Check(strObj)) {
                //
                cps_api_object_t o = cps_api_object_list_create_obj_and_append(gr.filters);
                if (o==NULL) {
                    py_set_error_string("Memory allocation error.");
                    return nullptr;
                }
                if (!cps_api_key_from_string(cps_api_object_key(o),PyString_AsString(strObj))) {
                    py_set_error_string("Memory allocation error.");
                    return nullptr;
                }
            }
            if (PyDict_Check(strObj)) {
                cps_api_object_t o = dict_to_cps_obj(strObj);
                if (o==NULL) {
                    py_set_error_string("Can't convert from a python to internal object");
                    return nullptr;
                }
                if (!cps_api_object_list_append(gr.filters,o)) {
                    cps_api_object_delete(o);
                    py_set_error_string("Memory allocation error.");
                    return nullptr;
                }
            }
        }
    }
    gr.keys = NULL;
    gr.key_count = 0;

    cps_api_return_code_t rc;
    {
        NonBlockingPythonContext l;
        rc = cps_api_get(&gr);
    }

    if (rc!=cps_api_ret_code_OK) {
        Py_RETURN_FALSE;
    }

    size_t ix = 0;
    size_t mx = cps_api_object_list_size(gr.list);
    for ( ; ix < mx ; ++ix) {
        cps_api_object_t obj = cps_api_object_list_get(gr.list,ix);
        PyObject *d = cps_obj_to_dict(obj);
        PyRef r(d);
        if (d==NULL) {
            py_set_error_string("Memory allocation error.");
            return nullptr;
        }
        if (PyList_Append(lst,d)) {
            py_set_error_string("Memory allocation error.");
            return nullptr;
        }
    }

    Py_RETURN_TRUE;
}
示例#30
0
文件: pythonrun.c 项目: tiran/cpython
int
PyRun_SimpleFileExFlags(FILE *fp, const char *filename, int closeit,
                        PyCompilerFlags *flags)
{
    PyObject *m, *d, *v;
    const char *ext;
    int set_file_name = 0, ret = -1;
    size_t len;

    m = PyImport_AddModule("__main__");
    if (m == NULL)
        return -1;
    Py_INCREF(m);
    d = PyModule_GetDict(m);
    if (PyDict_GetItemString(d, "__file__") == NULL) {
        PyObject *f;
        f = PyUnicode_DecodeFSDefault(filename);
        if (f == NULL)
            goto done;
        if (PyDict_SetItemString(d, "__file__", f) < 0) {
            Py_DECREF(f);
            goto done;
        }
        if (PyDict_SetItemString(d, "__cached__", Py_None) < 0) {
            Py_DECREF(f);
            goto done;
        }
        set_file_name = 1;
        Py_DECREF(f);
    }
    len = strlen(filename);
    ext = filename + len - (len > 4 ? 4 : 0);
    if (maybe_pyc_file(fp, filename, ext, closeit)) {
        FILE *pyc_fp;
        /* Try to run a pyc file. First, re-open in binary */
        if (closeit)
            fclose(fp);
        if ((pyc_fp = _Py_fopen(filename, "rb")) == NULL) {
            fprintf(stderr, "python: Can't reopen .pyc file\n");
            goto done;
        }

        if (set_main_loader(d, filename, "SourcelessFileLoader") < 0) {
            fprintf(stderr, "python: failed to set __main__.__loader__\n");
            ret = -1;
            fclose(pyc_fp);
            goto done;
        }
        v = run_pyc_file(pyc_fp, filename, d, d, flags);
    } else {
        /* When running from stdin, leave __main__.__loader__ alone */
        if (strcmp(filename, "<stdin>") != 0 &&
            set_main_loader(d, filename, "SourceFileLoader") < 0) {
            fprintf(stderr, "python: failed to set __main__.__loader__\n");
            ret = -1;
            goto done;
        }
        v = PyRun_FileExFlags(fp, filename, Py_file_input, d, d,
                              closeit, flags);
    }
    flush_io();
    if (v == NULL) {
        Py_CLEAR(m);
        PyErr_Print();
        goto done;
    }
    Py_DECREF(v);
    ret = 0;
  done:
    if (set_file_name) {
        if (PyDict_DelItemString(d, "__file__")) {
            PyErr_Clear();
        }
        if (PyDict_DelItemString(d, "__cached__")) {
            PyErr_Clear();
        }
    }
    Py_XDECREF(m);
    return ret;
}