本文整理汇总了C++中PyString_AS_STRING函数的典型用法代码示例。如果您正苦于以下问题:C++ PyString_AS_STRING函数的具体用法?C++ PyString_AS_STRING怎么用?C++ PyString_AS_STRING使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了PyString_AS_STRING函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。
示例1: getPythonTraceback
std::string getPythonTraceback()
{
// get exception info
PyObject *type, *value, *traceback;
PyErr_Fetch(&type, &value, &traceback);
PyErr_NormalizeException(&type, &value, &traceback);
std::ostringstream mssg;
if (traceback)
{
PyObject* tracebackModule;
PyObject* tracebackDictionary;
PyObject* tracebackFunction;
tracebackModule = PyImport_ImportModule("traceback");
if (!tracebackModule)
{
throw python_error("unable to load traceback module while importing numpy inside PDAL");
}
tracebackDictionary = PyModule_GetDict(tracebackModule);
tracebackFunction = PyDict_GetItemString(tracebackDictionary, "format_exception");
if (!tracebackFunction)
{
throw python_error("unable to find traceback function while importing numpy inside PDAL");
}
if (!PyCallable_Check(tracebackFunction))
{
throw python_error("invalid traceback function while importing numpy inside PDAL");
}
// create an argument for "format exception"
PyObject* args = PyTuple_New(3);
PyTuple_SetItem(args, 0, type);
PyTuple_SetItem(args, 1, value);
PyTuple_SetItem(args, 2, traceback);
// get a list of string describing what went wrong
PyObject* output = PyObject_CallObject(tracebackFunction, args);
// print error message
int i, n = PyList_Size(output);
#if PY_MAJOR_VERSION >= 3
for (i=0; i<n; i++)
{
PyObject* u = PyUnicode_AsUTF8String(PyList_GetItem(output, i));
const char* p = PyBytes_AsString(u);
mssg << p;
}
#else
for (i=0; i<n; i++) mssg << PyString_AsString(PyList_GetItem(output, i));
#endif
// clean up
Py_XDECREF(args);
Py_XDECREF(output);
}
else if (value != NULL)
{
PyObject *s = PyObject_Str(value);
#if PY_MAJOR_VERSION >= 3
// const char* text = PyUnicode_AS_DATA(s);
PyObject* u = PyUnicode_AsUTF8String(s);
const char* text = PyBytes_AsString(u);
#else
const char* text = PyString_AS_STRING(s);
#endif
Py_DECREF(s);
mssg << text;
}
else
{
mssg << "unknown error that we are unable to get a traceback for. Was it already printed/taken?";
}
Py_XDECREF(value);
Py_XDECREF(type);
Py_XDECREF(traceback);
return mssg.str();
}
示例2: QVariant
QVariant PythonScript::eval()
{
if (!isFunction) compiled = notCompiled;
if (compiled != isCompiled && !compile(true))
return QVariant();
PyObject *pyret;
beginStdoutRedirect();
if (PyCallable_Check(PyCode)){
PyObject *empty_tuple = PyTuple_New(0);
pyret = PyObject_Call(PyCode, empty_tuple, localDict);
Py_DECREF(empty_tuple);
} else
pyret = PyEval_EvalCode((PyCodeObject*)PyCode, env()->globalDict(), localDict);
endStdoutRedirect();
if (!pyret){
if (PyErr_ExceptionMatches(PyExc_ValueError) ||
PyErr_ExceptionMatches(PyExc_ZeroDivisionError)){
PyErr_Clear(); // silently ignore errors
return QVariant("");
} else {
emit_error(env()->errorMsg(), 0);
return QVariant();
}
}
QVariant qret = QVariant();
/* None */
if (pyret == Py_None)
qret = QVariant("");
/* numeric types */
else if (PyFloat_Check(pyret))
qret = QVariant(PyFloat_AS_DOUBLE(pyret));
else if (PyInt_Check(pyret))
qret = QVariant((qlonglong)PyInt_AS_LONG(pyret));
else if (PyLong_Check(pyret))
qret = QVariant((qlonglong)PyLong_AsLongLong(pyret));
else if (PyNumber_Check(pyret)){
PyObject *number = PyNumber_Float(pyret);
if (number){
qret = QVariant(PyFloat_AS_DOUBLE(number));
Py_DECREF(number);
}
/* bool */
} else if (PyBool_Check(pyret))
qret = QVariant(pyret==Py_True, 0);
// could handle advanced types (such as PyList->QValueList) here if needed
/* fallback: try to convert to (unicode) string */
if(!qret.isValid()) {
PyObject *pystring = PyObject_Unicode(pyret);
if (pystring) {
PyObject *asUTF8 = PyUnicode_EncodeUTF8(PyUnicode_AS_UNICODE(pystring), PyUnicode_GET_DATA_SIZE(pystring), 0);
Py_DECREF(pystring);
if (asUTF8) {
qret = QVariant(QString::fromUtf8(PyString_AS_STRING(asUTF8)));
Py_DECREF(asUTF8);
} else if (pystring = PyObject_Str(pyret)) {
qret = QVariant(QString(PyString_AS_STRING(pystring)));
Py_DECREF(pystring);
}
}
}
Py_DECREF(pyret);
if (PyErr_Occurred()){
if (PyErr_ExceptionMatches(PyExc_ValueError) ||
PyErr_ExceptionMatches(PyExc_ZeroDivisionError)){
PyErr_Clear(); // silently ignore errors
return QVariant("");
} else {
emit_error(env()->errorMsg(), 0);
return QVariant();
}
} else
return qret;
}
示例3: req_readline
static PyObject * req_readline(requestobject *self, PyObject *args)
{
int rc, chunk_len, bytes_read;
char *buffer;
PyObject *result;
int copied = 0;
int len = -1;
if (! PyArg_ParseTuple(args, "|i", &len))
return NULL;
if (len == 0) {
return PyString_FromString("");
}
/* is this the first read? */
if (! self->request_rec->read_length) {
/* then do some initial setting up */
rc = ap_setup_client_block(self->request_rec, REQUEST_CHUNKED_ERROR);
if(rc != OK) {
PyObject *val = PyInt_FromLong(rc);
if (val == NULL)
return NULL;
PyErr_SetObject(Mp_ServerReturn, val);
Py_DECREF(val);
return NULL;
}
if (! ap_should_client_block(self->request_rec)) {
/* client has nothing to send */
return PyString_FromString("");
}
}
if (len < 0)
len = self->request_rec->remaining +
(self->rbuff_len - self->rbuff_pos);
/* create the result buffer */
result = PyString_FromStringAndSize(NULL, len);
/* possibly no more memory */
if (result == NULL)
return NULL;
buffer = PyString_AS_STRING((PyStringObject *) result);
/* is there anything left in the rbuff from previous reads? */
if (self->rbuff_pos < self->rbuff_len) {
/* if yes, process that first */
while (self->rbuff_pos < self->rbuff_len) {
buffer[copied++] = self->rbuff[self->rbuff_pos];
if ((self->rbuff[self->rbuff_pos++] == '\n') ||
(copied == len)) {
/* our work is done */
/* resize if necessary */
if (copied < len)
if(_PyString_Resize(&result, copied))
return NULL;
return result;
}
}
}
/* if got this far, the buffer should be empty, we need to read more */
/* create a read buffer */
self->rbuff_len = len > HUGE_STRING_LEN ? len : HUGE_STRING_LEN;
self->rbuff_pos = self->rbuff_len;
self->rbuff = ap_palloc(self->request_rec->pool, self->rbuff_len);
if (! self->rbuff)
return PyErr_NoMemory();
/* set timeout */
ap_soft_timeout("mod_python_read", self->request_rec);
/* read it in */
Py_BEGIN_ALLOW_THREADS
chunk_len = ap_get_client_block(self->request_rec, self->rbuff,
self->rbuff_len);
Py_END_ALLOW_THREADS;
bytes_read = chunk_len;
/* if this is a "short read", try reading more */
while ((chunk_len != 0 ) && (bytes_read + copied < len)) {
Py_BEGIN_ALLOW_THREADS
chunk_len = ap_get_client_block(self->request_rec,
self->rbuff + bytes_read,
self->rbuff_len - bytes_read);
Py_END_ALLOW_THREADS
ap_reset_timeout(self->request_rec);
if (chunk_len == -1) {
//.........这里部分代码省略.........
示例4: if
//.........这里部分代码省略.........
continue;
}
case celServiceEventProgressbar:
{
if (area.width() > 0 && isPlayable && service_info && !service_info->getEvent(*m_cursor, evt))
{
char buffer[15];
snprintf(buffer, sizeof(buffer), "%d %%", (int)(100 * (now - evt->getBeginTime()) / evt->getDuration()));
text = buffer;
flags|=gPainter::RT_HALIGN_RIGHT;
break;
}
continue;
}
}
eRect tmp = area;
int xoffs = 0;
ePtr<gPixmap> piconPixmap;
if (e == celServiceName)
{
//picon stuff
if (isPlayable && PyCallable_Check(m_GetPiconNameFunc))
{
ePyObject pArgs = PyTuple_New(1);
PyTuple_SET_ITEM(pArgs, 0, PyString_FromString(ref.toString().c_str()));
ePyObject pRet = PyObject_CallObject(m_GetPiconNameFunc, pArgs);
Py_DECREF(pArgs);
if (pRet)
{
if (PyString_Check(pRet))
{
std::string piconFilename = PyString_AS_STRING(pRet);
if (!piconFilename.empty())
loadPNG(piconPixmap, piconFilename.c_str());
}
Py_DECREF(pRet);
}
}
xoffs = xoffset;
tmp.setWidth(((!isPlayable || m_column_width == -1 || (!piconPixmap && !m_column_width)) ? tmp.width() : m_column_width) - xoffs);
}
ePtr<eTextPara> para = new eTextPara(tmp);
para->setFont(m_element_font[e]);
para->renderString(text.c_str());
if (e == celServiceName)
{
eRect bbox = para->getBoundBox();
int servicenameWidth = ((!isPlayable || m_column_width == -1 || (!piconPixmap && !m_column_width)) ? bbox.width() : m_column_width);
m_element_position[celServiceInfo].setLeft(area.left() + servicenameWidth + m_items_distances + xoffs);
m_element_position[celServiceInfo].setTop(area.top());
m_element_position[celServiceInfo].setWidth(area.width() - (servicenameWidth + m_items_distances + xoffs));
m_element_position[celServiceInfo].setHeight(area.height());
if (isPlayable)
{
//picon stuff
if (PyCallable_Check(m_GetPiconNameFunc) and (m_column_width || piconPixmap))
{
eRect area = m_element_position[celServiceInfo];
/* PIcons are usually about 100:60. Make it a
* bit wider in case the icons are diffently
示例5: _generic_init_common
/*ARGSUSED*/
static inline PyObject *
_generic_init_common(PyObject *action, PyObject *data, PyObject *attrs)
{
PyObject *key_aname = NULL;
PyObject *key_attr = NULL;
PyObject *path_attr = NULL;
char *path = NULL;
char invalid_path = 0;
/*
* Before doing anything else to the action, action attributes must be
* set as set_data() relies on it.
*/
if (attrs != NULL) {
if (PyObject_SetAttrString(action, "attrs", attrs) == -1)
return (NULL);
} else {
/* Caller didn't specify any keyword arguments. */
if ((attrs = PyDict_New()) == NULL)
return (NULL);
if (PyObject_SetAttrString(action, "attrs", attrs) == -1) {
Py_DECREF(attrs);
return (NULL);
}
Py_DECREF(attrs);
}
if (data == NULL || data == Py_None) {
/* No need to call set_data(); this is much faster. */
if (PyObject_SetAttrString(action, "data", Py_None) == -1)
return (NULL);
} else {
PyObject *res = PyObject_CallMethod(action, "set_data", "(O)",
data);
if (res == NULL)
return (NULL);
Py_DECREF(res);
}
if ((key_aname = PyObject_GetAttrString(action, "key_attr")) == NULL)
return (NULL);
if (key_aname == Py_None) {
Py_DECREF(key_aname);
Py_RETURN_NONE;
}
if ((key_attr = PyDict_GetItem(attrs, key_aname)) == NULL) {
PyObject *aname = PyObject_GetAttrString(action, "name");
char *ns = PyString_AS_STRING(aname);
/*
* set actions allow an alternate value form, so
* AttributeAction.__init__ will fill this in later and raise an
* exception if appropriate.
*
* signature actions can't require their key attribute since the
* value of a signature may not yet be known.
*/
if (strcmp(ns, "set") != 0 && strcmp(ns, "signature") != 0) {
set_invalid_action_error("MissingKeyAttributeError",
action, key_aname);
Py_DECREF(key_aname);
return (NULL);
}
Py_DECREF(key_aname);
Py_RETURN_NONE;
}
if (PyList_CheckExact(key_attr)) {
PyObject *aname = PyObject_GetAttrString(action, "name");
char *ns = PyString_AS_STRING(aname);
int multi_error = 0;
if (strcmp(ns, "depend") != 0) {
/*
* Unless this is a dependency action, multiple values
* are never allowed for key attribute.
*/
multi_error = 1;
} else {
PyObject *dt = PyDict_GetItemString(attrs, "type");
/*
* If dependency type is 'require-any', multiple values
* are allowed for key attribute.
*/
if (dt != NULL) {
char *ts = PyString_AsString(dt);
if (ts == NULL) {
Py_DECREF(key_aname);
Py_DECREF(aname);
return (NULL);
}
if (strcmp(ts, "require-any") != 0)
multi_error = 1;
} else {
multi_error = 1;
}
//.........这里部分代码省略.........
示例6: PyObject_GenericSetAttr
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) {
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);
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;
}
示例7: PyErr_SetString
/* This function is a more-or-less straightforward port of the
* equivalent function in pairwise2. Please see there for algorithm
* documentation.
*/
static PyObject *cpairwise2__make_score_matrix_fast(
PyObject *self, PyObject *args)
{
int i;
int row, col;
PyObject *py_sequenceA, *py_sequenceB, *py_match_fn;
#if PY_MAJOR_VERSION >= 3
PyObject *py_bytesA, *py_bytesB;
#endif
char *sequenceA=NULL, *sequenceB=NULL;
int use_sequence_cstring;
double open_A, extend_A, open_B, extend_B;
int penalize_extend_when_opening, penalize_end_gaps_A, penalize_end_gaps_B;
int align_globally, score_only;
PyObject *py_match=NULL, *py_mismatch=NULL;
double first_A_gap, first_B_gap;
double match, mismatch;
int use_match_mismatch_scores;
int lenA, lenB;
double *score_matrix = NULL;
struct IndexList *trace_matrix = NULL;
PyObject *py_score_matrix=NULL, *py_trace_matrix=NULL;
double *row_cache_score = NULL,
*col_cache_score = NULL;
struct IndexList *row_cache_index = NULL,
*col_cache_index = NULL;
PyObject *py_retval = NULL;
if(!PyArg_ParseTuple(args, "OOOddddi(ii)ii", &py_sequenceA, &py_sequenceB,
&py_match_fn, &open_A, &extend_A, &open_B, &extend_B,
&penalize_extend_when_opening,
&penalize_end_gaps_A, &penalize_end_gaps_B,
&align_globally, &score_only))
return NULL;
if(!PySequence_Check(py_sequenceA) || !PySequence_Check(py_sequenceB)) {
PyErr_SetString(PyExc_TypeError,
"py_sequenceA and py_sequenceB should be sequences.");
return NULL;
}
/* Optimize for the common case. Check to see if py_sequenceA and
py_sequenceB are strings. If they are, use the c string
representation. */
#if PY_MAJOR_VERSION < 3
use_sequence_cstring = 0;
if(PyString_Check(py_sequenceA) && PyString_Check(py_sequenceB)) {
sequenceA = PyString_AS_STRING(py_sequenceA);
sequenceB = PyString_AS_STRING(py_sequenceB);
use_sequence_cstring = 1;
}
#else
py_bytesA = _create_bytes_object(py_sequenceA);
py_bytesB = _create_bytes_object(py_sequenceB);
if (py_bytesA && py_bytesB) {
sequenceA = PyBytes_AS_STRING(py_bytesA);
sequenceB = PyBytes_AS_STRING(py_bytesB);
use_sequence_cstring = 1;
}
else {
Py_XDECREF(py_bytesA);
Py_XDECREF(py_bytesB);
use_sequence_cstring = 0;
}
#endif
if(!PyCallable_Check(py_match_fn)) {
PyErr_SetString(PyExc_TypeError, "py_match_fn must be callable.");
return NULL;
}
/* Optimize for the common case. Check to see if py_match_fn is
an identity_match. If so, pull out the match and mismatch
member variables and calculate the scores myself. */
match = mismatch = 0;
use_match_mismatch_scores = 0;
if(!(py_match = PyObject_GetAttrString(py_match_fn, "match")))
goto cleanup_after_py_match_fn;
match = PyNumber_AsDouble(py_match);
if(PyErr_Occurred())
goto cleanup_after_py_match_fn;
if(!(py_mismatch = PyObject_GetAttrString(py_match_fn, "mismatch")))
goto cleanup_after_py_match_fn;
mismatch = PyNumber_AsDouble(py_mismatch);
if(PyErr_Occurred())
goto cleanup_after_py_match_fn;
use_match_mismatch_scores = 1;
cleanup_after_py_match_fn:
if(PyErr_Occurred())
PyErr_Clear();
if(py_match) {
Py_DECREF(py_match);
}
if(py_mismatch) {
//.........这里部分代码省略.........
示例8: PyString_AS_STRING
char *SortedDict_iterGetName(JSOBJ obj, JSONTypeContext *tc, size_t *outLen)
{
*outLen = PyString_GET_SIZE(GET_TC(tc)->itemName);
return PyString_AS_STRING(GET_TC(tc)->itemName);
}
示例9: malloc
PyObject *_translate_pathtranslate ( PyObject *self, PyObject *args,
PyObject *kwargs )
/*
* Usage: translate ( path, map, sep = "/." )
*/
{
char *path = NULL, *sep = "/.";
PyObject *ret, *dict, *val;
/* Variable length buffer */
size_t i, j = 0, now = 0, end = BUFSIZ;
char *out = malloc ( end ), *s, *ourpath;
char delim;
/* The argument list */
static char *kwlist[] = { "path", "map", "sep", NULL };
if ( !PyArg_ParseTupleAndKeywords ( args, kwargs, "sO!|s", kwlist,
&path, &PyDict_Type, &dict, &sep ) )
return NULL;
/* Path is mutated in process - make a copy */
ourpath = strdup( path );
for ( i = strcspn ( ourpath + j, sep ); i + j <= strlen(path);
i = strcspn ( ourpath + j, sep ))
{
/* Get the separator character */
if ( (delim = ourpath[i+j]) != '\0' )
ourpath[i+j] = '\0';
/* The segment is from path + j to i */
if ( (val = PyDict_GetItemString ( dict, ourpath + j )) )
{
/* Translate and copy */
if ( !(PyString_Check(val)) )
{
PyErr_SetString ( PyExc_ValueError, "mapping should contain "
"string values only" );
return NULL;
}
s = PyString_AS_STRING(val);
}
else
{
/* No translation, plain copy */
s = ourpath + j;
}
/* Reallocate if necessary */
while ( now + strlen(s) + 2 > end )
out = realloc ( out, (end = end + BUFSIZ) );
/* Copy the new value */
strcpy ( out + now, s );
now += strlen(s);
out[now++] = delim; /* Add the separator or '\0'*/
/* Increment j */
j += i + 1;
}
/* Create the return value */
ret = PyString_FromString ( out );
free ( out );
free ( ourpath );
return ret;
}
示例10: Dir_iterNext
int Dir_iterNext(JSOBJ _obj, JSONTypeContext *tc)
{
PyObject *obj = (PyObject *) _obj;
PyObject *itemValue = GET_TC(tc)->itemValue;
PyObject *itemName = GET_TC(tc)->itemName;
PyObject* attr;
PyObject* attrName;
char* attrStr;
if (itemValue)
{
Py_DECREF(GET_TC(tc)->itemValue);
GET_TC(tc)->itemValue = itemValue = NULL;
}
if (itemName)
{
Py_DECREF(GET_TC(tc)->itemName);
GET_TC(tc)->itemName = itemName = NULL;
}
for (; GET_TC(tc)->index < GET_TC(tc)->size; GET_TC(tc)->index ++)
{
attrName = PyList_GET_ITEM(GET_TC(tc)->attrList, GET_TC(tc)->index);
#if PY_MAJOR_VERSION >= 3
attr = PyUnicode_AsUTF8String(attrName);
#else
attr = attrName;
Py_INCREF(attr);
#endif
attrStr = PyString_AS_STRING(attr);
if (attrStr[0] == '_')
{
PRINTMARK();
Py_DECREF(attr);
continue;
}
itemValue = PyObject_GetAttr(obj, attrName);
if (itemValue == NULL)
{
PyErr_Clear();
Py_DECREF(attr);
PRINTMARK();
continue;
}
if (PyCallable_Check(itemValue))
{
Py_DECREF(itemValue);
Py_DECREF(attr);
PRINTMARK();
continue;
}
PRINTMARK();
itemName = attr;
break;
}
if (itemName == NULL)
{
GET_TC(tc)->index = GET_TC(tc)->size;
GET_TC(tc)->itemValue = NULL;
return 0;
}
GET_TC(tc)->itemName = itemName;
GET_TC(tc)->itemValue = itemValue;
GET_TC(tc)->index ++;
PRINTMARK();
return 1;
}
示例11: PRINTMARK
char *Dir_iterGetName(JSOBJ obj, JSONTypeContext *tc, size_t *outLen)
{
PRINTMARK();
*outLen = PyString_GET_SIZE(GET_TC(tc)->itemName);
return PyString_AS_STRING(GET_TC(tc)->itemName);
}
示例12: __Pyx_PyExec3
static PyObject* __Pyx_PyExec3(PyObject* o, PyObject* globals, PyObject* locals) {
PyObject* result;
PyObject* s = 0;
char *code = 0;
if (!globals || globals == Py_None) {
globals = $moddict_cname;
} else if (!PyDict_Check(globals)) {
PyErr_Format(PyExc_TypeError, "exec() arg 2 must be a dict, not %.200s",
Py_TYPE(globals)->tp_name);
goto bad;
}
if (!locals || locals == Py_None) {
locals = globals;
}
if (PyDict_GetItem(globals, PYIDENT("__builtins__")) == NULL) {
if (PyDict_SetItem(globals, PYIDENT("__builtins__"), PyEval_GetBuiltins()) < 0)
goto bad;
}
if (PyCode_Check(o)) {
if (PyCode_GetNumFree((PyCodeObject *)o) > 0) {
PyErr_SetString(PyExc_TypeError,
"code object passed to exec() may not contain free variables");
goto bad;
}
#if PY_VERSION_HEX < 0x030200B1
result = PyEval_EvalCode((PyCodeObject *)o, globals, locals);
#else
result = PyEval_EvalCode(o, globals, locals);
#endif
} else {
PyCompilerFlags cf;
cf.cf_flags = 0;
if (PyUnicode_Check(o)) {
cf.cf_flags = PyCF_SOURCE_IS_UTF8;
s = PyUnicode_AsUTF8String(o);
if (!s) goto bad;
o = s;
#if PY_MAJOR_VERSION >= 3
} else if (!PyBytes_Check(o)) {
#else
} else if (!PyString_Check(o)) {
#endif
PyErr_Format(PyExc_TypeError,
"exec: arg 1 must be string, bytes or code object, got %.200s",
Py_TYPE(o)->tp_name);
goto bad;
}
#if PY_MAJOR_VERSION >= 3
code = PyBytes_AS_STRING(o);
#else
code = PyString_AS_STRING(o);
#endif
if (PyEval_MergeCompilerFlags(&cf)) {
result = PyRun_StringFlags(code, Py_file_input, globals, locals, &cf);
} else {
result = PyRun_String(code, Py_file_input, globals, locals);
}
Py_XDECREF(s);
}
return result;
bad:
Py_XDECREF(s);
return 0;
}
示例13: Node_new
/**
Constructor//Initializer//Destructor.
*/
static PyObject *
Node_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
Node *self;
PyObject *weights = NULL;
self = (Node *)type->tp_alloc(type, 0);
if (self != NULL) {
// Default values
self->weights = NULL;
self->random_range = 1;
self->activation_function = NULL;
self->cached_output = 0;
static char *kwlist[] = {"active", "random_range", "weights", NULL};
if (! PyArg_ParseTupleAndKeywords(args, kwds, "|SdO", kwlist,
&self->activation_function,
&self->random_range,
&weights))
{
PyErr_Format(PyExc_ValueError, "Arguments should be (all optional): string active, double random_range, dict weights");
return NULL;
}
// Weights
if (weights == NULL)
{
self->weights = PyDict_New();
}
else if (PyDict_Check(weights)) {
self->weights = weights;
Py_INCREF(self->weights);
}
else {
// Incorrect object...
PyErr_Format(PyExc_ValueError, "Weights was not a dict!");
return NULL;
}
// Set activation function and derivative
if (self->activation_function != NULL && strcmp (PyString_AS_STRING(self->activation_function), "logsig" ) == 0)
{
Py_INCREF(self->activation_function);
self->function = logsig;
self->derivative = logsig_derivative;
}
else if (self->activation_function != NULL && strcmp (PyString_AS_STRING(self->activation_function), "tanh" ) == 0)
{
Py_INCREF(self->activation_function);
self->function = tanh;
self->derivative = tanh_derivative;
}
else // Linear it is!
{
self->activation_function = (PyStringObject*) PyString_FromString("linear");
self->function = linear;
self->derivative = linear_derivative;
}
} //if !self null
return (PyObject *)self;
}
示例14: growl_PostDictionary
static PyObject * growl_PostDictionary(CFStringRef name, PyObject *self, PyObject *args) {
int i, j;
PyObject *inputDict;
PyObject *pKeys = NULL;
PyObject *pKey, *pValue;
CFMutableDictionaryRef note = CFDictionaryCreateMutable(kCFAllocatorDefault,
/*capacity*/ 0,
&kCFTypeDictionaryKeyCallBacks,
&kCFTypeDictionaryValueCallBacks);
if (!PyArg_ParseTuple(args, "O!", &PyDict_Type, &inputDict))
goto error;
pKeys = PyDict_Keys(inputDict);
for (i = 0; i < PyList_Size(pKeys); ++i) {
CFStringRef convertedKey;
/* Converting the PyDict key to NSString and used for key in note */
pKey = PyList_GetItem(pKeys, i);
if (!pKey)
// Exception already set
goto error;
pValue = PyDict_GetItem(inputDict, pKey);
if (!pValue) {
// XXX Neeed a real Error message here.
PyErr_SetString(PyExc_TypeError," ");
goto error;
}
if (PyUnicode_Check(pKey)) {
convertedKey = CFStringCreateWithBytes(kCFAllocatorDefault,
(const UInt8 *)PyUnicode_AS_DATA(pKey),
PyUnicode_GET_DATA_SIZE(pKey),
kCFStringEncodingUnicode,
false);
} else if (PyString_Check(pKey)) {
convertedKey = CFStringCreateWithCString(kCFAllocatorDefault,
PyString_AsString(pKey),
kCFStringEncodingUTF8);
} else {
PyErr_SetString(PyExc_TypeError,"The Dict keys must be strings/unicode");
goto error;
}
/* Converting the PyDict value to NSString or NSData based on class */
if (PyString_Check(pValue)) {
CFStringRef convertedValue = CFStringCreateWithCString(kCFAllocatorDefault,
PyString_AS_STRING(pValue),
kCFStringEncodingUTF8);
CFDictionarySetValue(note, convertedKey, convertedValue);
CFRelease(convertedValue);
} else if (PyUnicode_Check(pValue)) {
CFStringRef convertedValue = CFStringCreateWithBytes(kCFAllocatorDefault,
(const UInt8 *)PyUnicode_AS_DATA(pValue),
PyUnicode_GET_DATA_SIZE(pValue),
kCFStringEncodingUnicode,
false);
CFDictionarySetValue(note, convertedKey, convertedValue);
CFRelease(convertedValue);
} else if (PyInt_Check(pValue)) {
long v = PyInt_AS_LONG(pValue);
CFNumberRef convertedValue = CFNumberCreate(kCFAllocatorDefault,
kCFNumberLongType,
&v);
CFDictionarySetValue(note, convertedKey, convertedValue);
CFRelease(convertedValue);
} else if (pValue == Py_None) {
CFDataRef convertedValue = CFDataCreate(kCFAllocatorDefault, NULL, 0);
CFDictionarySetValue(note, convertedKey, convertedValue);
CFRelease(convertedValue);
} else if (PyList_Check(pValue)) {
int size = PyList_Size(pValue);
CFMutableArrayRef listHolder = CFArrayCreateMutable(kCFAllocatorDefault,
size,
&kCFTypeArrayCallBacks);
for (j = 0; j < size; ++j) {
PyObject *lValue = PyList_GetItem(pValue, j);
if (PyString_Check(lValue)) {
CFStringRef convertedValue = CFStringCreateWithCString(kCFAllocatorDefault,
PyString_AS_STRING(lValue),
kCFStringEncodingUTF8);
CFArrayAppendValue(listHolder, convertedValue);
CFRelease(convertedValue);
} else if (PyUnicode_Check(lValue)) {
CFStringRef convertedValue = CFStringCreateWithBytes(kCFAllocatorDefault,
(const UInt8 *)PyUnicode_AS_DATA(lValue),
PyUnicode_GET_DATA_SIZE(lValue),
kCFStringEncodingUnicode,
false);
CFArrayAppendValue(listHolder, convertedValue);
CFRelease(convertedValue);
} else {
CFRelease(convertedKey);
PyErr_SetString(PyExc_TypeError,"The lists must only contain strings");
goto error;
}
}
CFDictionarySetValue(note, convertedKey, listHolder);
CFRelease(listHolder);
//.........这里部分代码省略.........
示例15: func_new
static PyObject *
func_new(PyTypeObject* type, PyObject* args, PyObject* kw)
{
PyCodeObject *code;
PyObject *globals;
PyObject *name = Py_None;
PyObject *defaults = Py_None;
PyObject *closure = Py_None;
PyFunctionObject *newfunc;
Py_ssize_t nfree, nclosure;
static char *kwlist[] = {"code", "globals", "name",
"argdefs", "closure", 0};
if (!PyArg_ParseTupleAndKeywords(args, kw, "O!O!|OOO:function",
kwlist,
&PyCode_Type, &code,
&PyDict_Type, &globals,
&name, &defaults, &closure))
return NULL;
if (name != Py_None && !PyString_Check(name)) {
PyErr_SetString(PyExc_TypeError,
"arg 3 (name) must be None or string");
return NULL;
}
if (defaults != Py_None && !PyTuple_Check(defaults)) {
PyErr_SetString(PyExc_TypeError,
"arg 4 (defaults) must be None or tuple");
return NULL;
}
nfree = PyTuple_GET_SIZE(code->co_freevars);
if (!PyTuple_Check(closure)) {
if (nfree && closure == Py_None) {
PyErr_SetString(PyExc_TypeError,
"arg 5 (closure) must be tuple");
return NULL;
}
else if (closure != Py_None) {
PyErr_SetString(PyExc_TypeError,
"arg 5 (closure) must be None or tuple");
return NULL;
}
}
/* check that the closure is well-formed */
nclosure = closure == Py_None ? 0 : PyTuple_GET_SIZE(closure);
if (nfree != nclosure)
return PyErr_Format(PyExc_ValueError,
"%s requires closure of length %zd, not %zd",
PyString_AS_STRING(code->co_name),
nfree, nclosure);
if (nclosure) {
Py_ssize_t i;
for (i = 0; i < nclosure; i++) {
PyObject *o = PyTuple_GET_ITEM(closure, i);
if (!PyCell_Check(o)) {
return PyErr_Format(PyExc_TypeError,
"arg 5 (closure) expected cell, found %s",
o->ob_type->tp_name);
}
}
}
newfunc = (PyFunctionObject *)PyFunction_New((PyObject *)code, globals);
if (newfunc == NULL)
return NULL;
if (name != Py_None) {
func_set_name(newfunc, name);
// Py_INCREF(name);
// Py_DECREF(newfunc->func_name);
// newfunc->func_name = name;
}
if (defaults != Py_None) {
Py_INCREF(defaults);
newfunc->func_defaults = defaults;
}
if (closure != Py_None) {
Py_INCREF(closure);
newfunc->func_closure = closure;
}
return (PyObject *)newfunc;
}