本文整理汇总了C++中PyErr_NoMemory函数的典型用法代码示例。如果您正苦于以下问题:C++ PyErr_NoMemory函数的具体用法?C++ PyErr_NoMemory怎么用?C++ PyErr_NoMemory使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了PyErr_NoMemory函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C++代码示例。
示例1: getaddrinfo_cb
static void
getaddrinfo_cb(uv_getaddrinfo_t* req, int status, struct addrinfo* res)
{
PyGILState_STATE gstate = PyGILState_Ensure();
struct addrinfo *ptr;
uv_err_t err;
getaddrinfo_cb_data_t *cb_data;
Loop *loop;
PyObject *callback, *addr, *item, *errorno, *dns_result, *result;
ASSERT(req);
cb_data = (getaddrinfo_cb_data_t *)req->data;
ASSERT(cb_data);
loop = cb_data->loop;
callback = cb_data->cb;
ASSERT(loop);
ASSERT(callback);
if (status != 0) {
err = uv_last_error(loop->uv_loop);
errorno = PyInt_FromLong((long)err.code);
dns_result = Py_None;
Py_INCREF(Py_None);
goto callback;
}
dns_result = PyList_New(0);
if (!dns_result) {
PyErr_NoMemory();
PyErr_WriteUnraisable(Py_None);
errorno = PyInt_FromLong((long)UV_ENOMEM);
dns_result = Py_None;
Py_INCREF(Py_None);
goto callback;
}
for (ptr = res; ptr; ptr = ptr->ai_next) {
addr = makesockaddr(ptr->ai_addr, ptr->ai_addrlen);
if (!addr) {
PyErr_NoMemory();
PyErr_WriteUnraisable(callback);
break;
}
item = PyStructSequence_New(&DNSAddrinfoResultType);
if (!item) {
PyErr_NoMemory();
PyErr_WriteUnraisable(callback);
break;
}
PyStructSequence_SET_ITEM(item, 0, PyInt_FromLong((long)ptr->ai_family));
PyStructSequence_SET_ITEM(item, 1, PyInt_FromLong((long)ptr->ai_socktype));
PyStructSequence_SET_ITEM(item, 2, PyInt_FromLong((long)ptr->ai_protocol));
PyStructSequence_SET_ITEM(item, 3, PYUVString_FromString(ptr->ai_canonname ? ptr->ai_canonname : ""));
PyStructSequence_SET_ITEM(item, 4, addr);
PyList_Append(dns_result, item);
Py_DECREF(item);
}
errorno = Py_None;
Py_INCREF(Py_None);
callback:
result = PyObject_CallFunctionObjArgs(callback, dns_result, errorno, NULL);
if (result == NULL) {
PyErr_WriteUnraisable(callback);
}
Py_XDECREF(result);
Py_DECREF(dns_result);
Py_DECREF(errorno);
Py_DECREF(loop);
Py_DECREF(callback);
uv_freeaddrinfo(res);
PyMem_Free(req);
PyMem_Free(cb_data);
PyGILState_Release(gstate);
}
开发者ID:aventurella,项目名称:pyuv,代码行数:79,代码来源:util.c
示例2: set_nameservers
static int
set_nameservers(Channel *self, PyObject *value)
{
char *server;
int i, r, length, ret;
struct ares_addr_node *servers;
Py_buffer pbuf;
PyObject *server_list, *item, *data_fast;
servers = NULL;
server_list = value;
ret = 0;
if ((data_fast = PySequence_Fast(server_list, "argument 1 must be an iterable")) == NULL) {
return -1;
}
length = PySequence_Fast_GET_SIZE(data_fast);
if (length > INT_MAX) {
PyErr_SetString(PyExc_ValueError, "argument 1 is too long");
Py_DECREF(data_fast);
return -1;
}
if (length == 0) {
/* c-ares doesn't do anything */
return 0;
}
servers = PyMem_Malloc(sizeof(struct ares_addr_node) * length);
if (!servers) {
PyErr_NoMemory();
ret = -1;
goto end;
}
for (i = 0; i < length; i++) {
item = PySequence_Fast_GET_ITEM(data_fast, i);
if (!item || !PyArg_Parse(item, "s*;args contains a non-string value", &pbuf)) {
Py_XDECREF(item);
goto end;
}
server = pbuf.buf;
if (ares_inet_pton(AF_INET, server, &servers[i].addr.addr4) == 1) {
servers[i].family = AF_INET;
} else if (ares_inet_pton(AF_INET6, server, &servers[i].addr.addr6) == 1) {
servers[i].family = AF_INET6;
} else {
PyErr_SetString(PyExc_ValueError, "invalid IP address");
PyBuffer_Release(&pbuf);
ret = -1;
goto end;
}
PyBuffer_Release(&pbuf);
if (i > 0) {
servers[i-1].next = &servers[i];
}
}
if (servers) {
servers[length-1].next = NULL;
}
r = ares_set_servers(self->channel, servers);
if (r != ARES_SUCCESS) {
RAISE_ARES_EXCEPTION(r);
ret = -1;
}
end:
PyMem_Free(servers);
return ret;
}
开发者ID:aguinet,项目名称:pycares,代码行数:77,代码来源:cares.c
示例3: query_mx_cb
static void
query_mx_cb(void *arg, int status,int timeouts, unsigned char *answer_buf, int answer_len)
{
PyGILState_STATE gstate = PyGILState_Ensure();
int parse_status;
struct ares_mx_reply *mx_reply, *mx_ptr;
PyObject *dns_result, *errorno, *tmp, *result, *callback;
mx_reply = NULL;
callback = (PyObject *)arg;
ASSERT(callback);
if (status != ARES_SUCCESS) {
errorno = PyInt_FromLong((long)status);
dns_result = Py_None;
Py_INCREF(Py_None);
goto callback;
}
parse_status = ares_parse_mx_reply(answer_buf, answer_len, &mx_reply);
if (parse_status != ARES_SUCCESS) {
errorno = PyInt_FromLong((long)parse_status);
dns_result = Py_None;
Py_INCREF(Py_None);
goto callback;
}
dns_result = PyList_New(0);
if (!dns_result) {
PyErr_NoMemory();
PyErr_WriteUnraisable(Py_None);
errorno = PyInt_FromLong((long)ARES_ENOMEM);
dns_result = Py_None;
Py_INCREF(Py_None);
goto callback;
}
for (mx_ptr = mx_reply; mx_ptr != NULL; mx_ptr = mx_ptr->next) {
tmp = PyStructSequence_New(&AresQueryMXResultType);
if (tmp == NULL) {
break;
}
PyStructSequence_SET_ITEM(tmp, 0, Py_BuildValue("s", mx_ptr->host));
PyStructSequence_SET_ITEM(tmp, 1, PyInt_FromLong((long)mx_ptr->priority));
PyList_Append(dns_result, tmp);
Py_DECREF(tmp);
}
errorno = Py_None;
Py_INCREF(Py_None);
callback:
result = PyObject_CallFunctionObjArgs(callback, dns_result, errorno, NULL);
if (result == NULL) {
PyErr_WriteUnraisable(callback);
}
Py_XDECREF(result);
Py_DECREF(dns_result);
Py_DECREF(errorno);
if (mx_reply) {
ares_free_data(mx_reply);
}
Py_DECREF(callback);
PyGILState_Release(gstate);
}
开发者ID:aguinet,项目名称:pycares,代码行数:64,代码来源:cares.c
示例4: NI_MinOrMaxFilter
int NI_MinOrMaxFilter(PyArrayObject* input, PyArrayObject* footprint,
PyArrayObject* structure, PyArrayObject* output,
NI_ExtendMode mode, double cvalue, maybelong *origins, int minimum)
{
Bool *pf = NULL;
maybelong fsize, jj, kk, filter_size = 0, border_flag_value;
maybelong *offsets = NULL, *oo, size;
NI_FilterIterator fi;
NI_Iterator ii, io;
char *pi, *po;
int ll;
double *ss = NULL;
Float64 *ps;
/* get the the footprint: */
fsize = 1;
for(ll = 0; ll < footprint->nd; ll++)
fsize *= footprint->dimensions[ll];
pf = (Bool*)PyArray_DATA(footprint);
for(jj = 0; jj < fsize; jj++) {
if (pf[jj]) {
++filter_size;
}
}
/* get the structure: */
if (structure) {
ss = (double*)malloc(filter_size * sizeof(double));
if (!ss) {
PyErr_NoMemory();
goto exit;
}
/* copy the weights to contiguous memory: */
ps = (Float64*)PyArray_DATA(structure);
jj = 0;
for(kk = 0; kk < fsize; kk++)
if (pf[kk])
ss[jj++] = minimum ? -ps[kk] : ps[kk];
}
/* initialize filter offsets: */
if (!NI_InitFilterOffsets(input, pf, footprint->dimensions, origins,
mode, &offsets, &border_flag_value, NULL))
goto exit;
/* initialize filter iterator: */
if (!NI_InitFilterIterator(input->nd, footprint->dimensions,
filter_size, input->dimensions, origins, &fi))
goto exit;
/* initialize input element iterator: */
if (!NI_InitPointIterator(input, &ii))
goto exit;
/* initialize output element iterator: */
if (!NI_InitPointIterator(output, &io))
goto exit;
/* get data pointers an array size: */
pi = (void *)PyArray_DATA(input);
po = (void *)PyArray_DATA(output);
size = 1;
for(ll = 0; ll < input->nd; ll++)
size *= input->dimensions[ll];
/* iterator over the elements: */
oo = offsets;
for(jj = 0; jj < size; jj++) {
double tmp = 0.0;
switch (input->descr->type_num) {
CASE_MIN_OR_MAX_POINT(pi, oo, filter_size, cvalue, Bool,
minimum, tmp, border_flag_value, ss);
CASE_MIN_OR_MAX_POINT(pi, oo, filter_size, cvalue, UInt8,
minimum, tmp, border_flag_value, ss);
CASE_MIN_OR_MAX_POINT(pi, oo, filter_size, cvalue, UInt16,
minimum, tmp, border_flag_value, ss);
CASE_MIN_OR_MAX_POINT(pi, oo, filter_size, cvalue, UInt32,
minimum, tmp, border_flag_value, ss);
#if HAS_UINT64
CASE_MIN_OR_MAX_POINT(pi, oo, filter_size, cvalue, UInt64,
minimum, tmp, border_flag_value, ss);
#endif
CASE_MIN_OR_MAX_POINT(pi, oo, filter_size, cvalue, Int8,
minimum, tmp, border_flag_value, ss);
CASE_MIN_OR_MAX_POINT(pi, oo, filter_size, cvalue, Int16,
minimum, tmp, border_flag_value, ss);
CASE_MIN_OR_MAX_POINT(pi, oo, filter_size, cvalue, Int32,
minimum, tmp, border_flag_value, ss);
CASE_MIN_OR_MAX_POINT(pi, oo, filter_size, cvalue, Int64,
minimum, tmp, border_flag_value, ss);
CASE_MIN_OR_MAX_POINT(pi, oo, filter_size, cvalue, Float32,
minimum, tmp, border_flag_value, ss);
CASE_MIN_OR_MAX_POINT(pi, oo, filter_size, cvalue, Float64,
minimum, tmp, border_flag_value, ss);
default:
PyErr_SetString(PyExc_RuntimeError, "array type not supported");
goto exit;
}
switch (output->descr->type_num) {
CASE_FILTER_OUT(po, tmp, Bool);
CASE_FILTER_OUT(po, tmp, UInt8);
CASE_FILTER_OUT(po, tmp, UInt16);
CASE_FILTER_OUT(po, tmp, UInt32);
#if HAS_UINT64
CASE_FILTER_OUT(po, tmp, UInt64);
#endif
CASE_FILTER_OUT(po, tmp, Int8);
//.........这里部分代码省略.........
开发者ID:mbentz80,项目名称:jzigbeercp,代码行数:101,代码来源:ni_filters.c
示例5: PyArray_NDIM
static PyObject *Py_FindObjects(PyObject *obj, PyObject *args)
{
PyArrayObject *input = NULL;
PyObject *result = NULL, *tuple = NULL, *start = NULL, *end = NULL;
PyObject *slc = NULL;
int jj;
npy_intp max_label;
npy_intp ii, *regions = NULL;
if (!PyArg_ParseTuple(args, "O&n",
NI_ObjectToInputArray, &input, &max_label))
goto exit;
if (max_label < 0)
max_label = 0;
if (max_label > 0) {
if (PyArray_NDIM(input) > 0) {
regions = (npy_intp*)malloc(2 * max_label * PyArray_NDIM(input) *
sizeof(npy_intp));
} else {
regions = (npy_intp*)malloc(max_label * sizeof(npy_intp));
}
if (!regions) {
PyErr_NoMemory();
goto exit;
}
}
if (!NI_FindObjects(input, max_label, regions))
goto exit;
result = PyList_New(max_label);
if (!result) {
PyErr_NoMemory();
goto exit;
}
for(ii = 0; ii < max_label; ii++) {
npy_intp idx =
PyArray_NDIM(input) > 0 ? 2 * PyArray_NDIM(input) * ii : ii;
if (regions[idx] >= 0) {
PyObject *tuple = PyTuple_New(PyArray_NDIM(input));
if (!tuple) {
PyErr_NoMemory();
goto exit;
}
for(jj = 0; jj < PyArray_NDIM(input); jj++) {
start = PyLong_FromSsize_t(regions[idx + jj]);
end = PyLong_FromSsize_t(regions[idx + jj +
PyArray_NDIM(input)]);
if (!start || !end) {
PyErr_NoMemory();
goto exit;
}
slc = PySlice_New(start, end, NULL);
if (!slc) {
PyErr_NoMemory();
goto exit;
}
Py_XDECREF(start);
Py_XDECREF(end);
start = end = NULL;
PyTuple_SetItem(tuple, jj, slc);
slc = NULL;
}
PyList_SetItem(result, ii, tuple);
tuple = NULL;
} else {
Py_INCREF(Py_None);
PyList_SetItem(result, ii, Py_None);
}
}
Py_INCREF(result);
exit:
Py_XDECREF(input);
Py_XDECREF(result);
Py_XDECREF(tuple);
Py_XDECREF(start);
Py_XDECREF(end);
Py_XDECREF(slc);
free(regions);
if (PyErr_Occurred()) {
Py_XDECREF(result);
return NULL;
} else {
return result;
}
}
开发者ID:BranYang,项目名称:scipy,代码行数:90,代码来源:nd_image.c
示例6: psutil_disk_io_counters
PyObject *
psutil_disk_io_counters(PyObject *self, PyObject *args) {
int i, dk_ndrive, mib[3];
size_t len;
struct diskstats *stats;
PyObject *py_retdict = PyDict_New();
PyObject *py_disk_info = NULL;
if (py_retdict == NULL)
return NULL;
mib[0] = CTL_HW;
mib[1] = HW_DISKSTATS;
len = 0;
if (sysctl(mib, 2, NULL, &len, NULL, 0) < 0) {
warn("can't get hw.diskstats size");
PyErr_SetFromErrno(PyExc_OSError);
goto error;
}
dk_ndrive = (int)(len / sizeof(struct diskstats));
stats = malloc(len);
if (stats == NULL) {
warn("can't malloc");
PyErr_NoMemory();
goto error;
}
if (sysctl(mib, 2, stats, &len, NULL, 0) < 0 ) {
warn("could not read hw.diskstats");
PyErr_SetFromErrno(PyExc_OSError);
goto error;
}
for (i = 0; i < dk_ndrive; i++) {
py_disk_info = Py_BuildValue(
"(KKKKLL)",
stats[i].ds_rxfer,
stats[i].ds_wxfer,
stats[i].ds_rbytes,
stats[i].ds_wbytes,
// assume half read - half writes.
// TODO: why?
(long long) PSUTIL_TV2DOUBLE(stats[i].ds_time) / 2,
(long long) PSUTIL_TV2DOUBLE(stats[i].ds_time) / 2);
if (!py_disk_info)
goto error;
if (PyDict_SetItemString(py_retdict, stats[i].ds_name, py_disk_info))
goto error;
Py_DECREF(py_disk_info);
}
free(stats);
return py_retdict;
error:
Py_XDECREF(py_disk_info);
Py_DECREF(py_retdict);
if (stats != NULL)
free(stats);
return NULL;
}
开发者ID:happazk,项目名称:psutil,代码行数:61,代码来源:openbsd.c
示例7: GetDataString
//.........这里部分代码省略.........
else
nTargetType = SQL_C_CHAR;
#else
nTargetType = SQL_C_WCHAR;
#endif
break;
case SQL_WCHAR:
case SQL_WVARCHAR:
case SQL_WLONGVARCHAR:
nTargetType = SQL_C_WCHAR;
break;
default:
nTargetType = SQL_C_BINARY;
break;
}
char tempBuffer[1026]; // Pad with 2 bytes for driver bugs
DataBuffer buffer(nTargetType, tempBuffer, sizeof(tempBuffer)-2);
for (int iDbg = 0; iDbg < 10; iDbg++) // failsafe
{
SQLRETURN ret;
SQLLEN cbData = 0;
Py_BEGIN_ALLOW_THREADS
ret = SQLGetData(cur->hstmt, (SQLUSMALLINT)(iCol+1), nTargetType, buffer.GetBuffer(), buffer.GetRemaining(), &cbData);
Py_END_ALLOW_THREADS;
if (cbData == SQL_NULL_DATA || (ret == SQL_SUCCESS && cbData < 0))
{
// HACK: FreeTDS 0.91 on OS/X returns -4 for NULL data instead of SQL_NULL_DATA (-1). I've traced into the
// code and it appears to be the result of assigning -1 to a SQLLEN:
//
// if (colinfo->column_cur_size < 0) {
// /* TODO check what should happen if pcbValue was NULL */
// *pcbValue = SQL_NULL_DATA;
//
// I believe it will be fine to treat all negative values as NULL for now.
Py_RETURN_NONE;
}
if (!SQL_SUCCEEDED(ret) && ret != SQL_NO_DATA)
return RaiseErrorFromHandle("SQLGetData", cur->cnxn->hdbc, cur->hstmt);
// The SQLGetData behavior is incredibly quirky. It doesn't tell us the total, the total we've read, or even
// the amount just read. It returns the amount just read, plus any remaining. Unfortunately, the only way to
// pick them apart is to subtract out the amount of buffer we supplied.
SQLLEN cbBuffer = buffer.GetRemaining(); // how much we gave SQLGetData
if (ret == SQL_SUCCESS_WITH_INFO)
{
// There is more data than fits in the buffer. The amount of data equals the amount of data in the buffer
// minus a NULL terminator.
SQLLEN cbRead;
SQLLEN cbMore;
if (cbData == SQL_NO_TOTAL)
{
// We don't know how much more, so just guess.
cbRead = cbBuffer - buffer.null_size;
cbMore = 2048;
}
else if (cbData >= cbBuffer)
{
// There is more data. We supplied cbBuffer, but there was cbData (more). We received cbBuffer, so we
// need to subtract that, allocate enough to read the rest (cbData-cbBuffer).
cbRead = cbBuffer - buffer.null_size;
cbMore = cbData - cbRead;
}
else
{
// I'm not really sure why I would be here ... I would have expected SQL_SUCCESS
cbRead = cbData - buffer.null_size;
cbMore = 0;
}
buffer.AddUsed(cbRead);
if (!buffer.AllocateMore(cbMore))
return PyErr_NoMemory();
}
else if (ret == SQL_SUCCESS)
{
// For some reason, the NULL terminator is used in intermediate buffers but not in this final one.
buffer.AddUsed(cbData);
}
if (ret == SQL_SUCCESS || ret == SQL_NO_DATA)
return buffer.DetachValue();
}
// REVIEW: Add an error message.
return 0;
}
开发者ID:Bobspadger,项目名称:pyodbc,代码行数:101,代码来源:getdata.cpp
示例8: PyArray_GETCONTIGUOUS
static PyObject *msameff(PyObject *self, PyObject *args, PyObject *kwargs) {
PyArrayObject *msa,*pythonw;
double theta = 0.0;
int meff_only = 1, refine = 0;
int alignlist[26] = {1, 0, 2, 3, 4, 5, 6, 7, 8, 0, 9, 10, 11, 12,
0, 13, 14, 15, 16, 17, 0, 18, 19, 0, 20, 0};
static char *kwlist[] = {"msa", "theta", "meff_only", "refine", "w", NULL};
if (!PyArg_ParseTupleAndKeywords(args, kwargs, "Odii|O", kwlist,
&msa, &theta, &meff_only, &refine,
&pythonw))
return NULL;
/* make sure to have a contiguous and well-behaved array */
msa = PyArray_GETCONTIGUOUS(msa);
/* check dimensions */
long number = PyArray_DIMS(msa)[0], length = PyArray_DIMS(msa)[1];
long i, j, k, l = 0;
/* get pointers to data */
char *seq = (char *) PyArray_DATA(msa); /*size: number x length */
/*Set ind and get l first.*/
int *ind = malloc(length * sizeof(int));
if (!ind) {
return PyErr_NoMemory();
}
if (!refine){
for (i = 0; i < length; i++){
l += 1;
ind[i] = l;
}
}
else{
for (i = 0; i < length; i++){
if (seq[i] <= 90 && seq[i] >= 65){
l += 1;
ind[i] = l;
}
else
ind[i] = 0;
}
}
/*Use l to set align and w size.*/
int *align = malloc(number * l * sizeof(int));
if (!align) {
free(ind);
return PyErr_NoMemory();
}
for (i = 0; i < number * l; i++){
align[i] = 0;
}
double *w = malloc(number * sizeof(double));
if (!w) {
free(ind);
free(align);
return PyErr_NoMemory();
}
#define align(x,y) align[(x)*l+(y)]
/*Set align matrix*/
for (i = 0; i < number; i++){
for (j = 0; j < length; j++){
if (ind[j] != 0){
if (seq[i*length+j] >= 65 && seq[i*length+j] <= 90)
align(i,ind[j]-1) = alignlist[seq[i*length+j] - 65];
else
align(i,ind[j]-1) = 0;
}
}
}
/*Calculate weight(w) for each sequence, sum of w is Meff*/
for (i = 0; i < number; i++)
w[i] = 1.;
for (i = 0; i < number; i++)
for (j = i+1; j < number; j++){
double temp = 0.;
for (k = 0; k < l; k++){
if (align(i,k) != align(j,k))
temp += 1.;
}
temp /= l;
if (temp < theta){
w[i] += 1.;
w[j] += 1.;
}
}
double meff = 0.0;
for (i = 0; i < number; i++){
w[i] = 1./ w[i];
meff += w[i];
}
#undef align
/*Clean up memory.*/
free(ind);
if (meff_only == 1){
//.........这里部分代码省略.........
开发者ID:chakracs,项目名称:ProDy,代码行数:101,代码来源:msatools.c
示例9: select_select
static PyObject *
select_select(PyObject *self, PyObject *args)
{
#ifdef SELECT_USES_HEAP
pylist *rfd2obj, *wfd2obj, *efd2obj;
#else /* !SELECT_USES_HEAP */
/* XXX: All this should probably be implemented as follows:
* - find the highest descriptor we're interested in
* - add one
* - that's the size
* See: Stevens, APitUE, $12.5.1
*/
pylist rfd2obj[FD_SETSIZE + 1];
pylist wfd2obj[FD_SETSIZE + 1];
pylist efd2obj[FD_SETSIZE + 1];
#endif /* SELECT_USES_HEAP */
PyObject *ifdlist, *ofdlist, *efdlist;
PyObject *ret = NULL;
PyObject *tout = Py_None;
fd_set ifdset, ofdset, efdset;
double timeout;
struct timeval tv, *tvp;
long seconds;
int imax, omax, emax, max;
int n;
/* convert arguments */
if (!PyArg_ParseTuple(args, "OOO|O:select",
&ifdlist, &ofdlist, &efdlist, &tout))
return NULL;
if (tout == Py_None)
tvp = (struct timeval *)0;
else if (!PyNumber_Check(tout)) {
PyErr_SetString(PyExc_TypeError,
"timeout must be a float or None");
return NULL;
}
else {
timeout = PyFloat_AsDouble(tout);
if (timeout == -1 && PyErr_Occurred())
return NULL;
if (timeout > (double)LONG_MAX) {
PyErr_SetString(PyExc_OverflowError,
"timeout period too long");
return NULL;
}
seconds = (long)timeout;
timeout = timeout - (double)seconds;
tv.tv_sec = seconds;
tv.tv_usec = (long)(timeout*1000000.0);
tvp = &tv;
}
#ifdef SELECT_USES_HEAP
/* Allocate memory for the lists */
rfd2obj = PyMem_NEW(pylist, FD_SETSIZE + 1);
wfd2obj = PyMem_NEW(pylist, FD_SETSIZE + 1);
efd2obj = PyMem_NEW(pylist, FD_SETSIZE + 1);
if (rfd2obj == NULL || wfd2obj == NULL || efd2obj == NULL) {
if (rfd2obj) PyMem_DEL(rfd2obj);
if (wfd2obj) PyMem_DEL(wfd2obj);
if (efd2obj) PyMem_DEL(efd2obj);
return PyErr_NoMemory();
}
#endif /* SELECT_USES_HEAP */
/* Convert sequences to fd_sets, and get maximum fd number
* propagates the Python exception set in seq2set()
*/
rfd2obj[0].sentinel = -1;
wfd2obj[0].sentinel = -1;
efd2obj[0].sentinel = -1;
if ((imax=seq2set(ifdlist, &ifdset, rfd2obj)) < 0)
goto finally;
if ((omax=seq2set(ofdlist, &ofdset, wfd2obj)) < 0)
goto finally;
if ((emax=seq2set(efdlist, &efdset, efd2obj)) < 0)
goto finally;
max = imax;
if (omax > max) max = omax;
if (emax > max) max = emax;
Py_BEGIN_ALLOW_THREADS
n = select(max, &ifdset, &ofdset, &efdset, tvp);
Py_END_ALLOW_THREADS
#ifdef MS_WINDOWS
if (n == SOCKET_ERROR) {
PyErr_SetExcFromWindowsErr(SelectError, WSAGetLastError());
}
#else
if (n < 0) {
PyErr_SetFromErrno(SelectError);
}
#endif
else if (n == 0) {
/* optimization */
ifdlist = PyList_New(0);
if (ifdlist) {
//.........这里部分代码省略.........
开发者ID:Oize,项目名称:pspstacklesspython,代码行数:101,代码来源:selectmodule.c
示例10: PyImaging_JpegEncoderNew
PyObject*
PyImaging_JpegEncoderNew(PyObject* self, PyObject* args)
{
ImagingEncoderObject* encoder;
char *mode;
char *rawmode;
int quality = 0;
int progressive = 0;
int smooth = 0;
int optimize = 0;
int streamtype = 0; /* 0=interchange, 1=tables only, 2=image only */
int xdpi = 0, ydpi = 0;
int subsampling = -1; /* -1=default, 0=none, 1=medium, 2=high */
PyObject* qtables=NULL;
unsigned int **qarrays = NULL;
char* extra = NULL;
int extra_size;
char* rawExif = NULL;
int rawExifLen = 0;
if (!PyArg_ParseTuple(args, "ss|iiiiiiiiO"PY_ARG_BYTES_LENGTH""PY_ARG_BYTES_LENGTH,
&mode, &rawmode, &quality,
&progressive, &smooth, &optimize, &streamtype,
&xdpi, &ydpi, &subsampling, &qtables, &extra, &extra_size,
&rawExif, &rawExifLen))
return NULL;
encoder = PyImaging_EncoderNew(sizeof(JPEGENCODERSTATE));
if (encoder == NULL)
return NULL;
if (get_packer(encoder, mode, rawmode) < 0)
return NULL;
qarrays = get_qtables_arrays(qtables);
if (extra && extra_size > 0) {
char* p = malloc(extra_size);
if (!p)
return PyErr_NoMemory();
memcpy(p, extra, extra_size);
extra = p;
} else
extra = NULL;
if (rawExif && rawExifLen > 0) {
char* pp = malloc(rawExifLen);
if (!pp)
return PyErr_NoMemory();
memcpy(pp, rawExif, rawExifLen);
rawExif = pp;
} else
rawExif = NULL;
encoder->encode = ImagingJpegEncode;
((JPEGENCODERSTATE*)encoder->state.context)->quality = quality;
((JPEGENCODERSTATE*)encoder->state.context)->qtables = qarrays;
((JPEGENCODERSTATE*)encoder->state.context)->subsampling = subsampling;
((JPEGENCODERSTATE*)encoder->state.context)->progressive = progressive;
((JPEGENCODERSTATE*)encoder->state.context)->smooth = smooth;
((JPEGENCODERSTATE*)encoder->state.context)->optimize = optimize;
((JPEGENCODERSTATE*)encoder->state.context)->streamtype = streamtype;
((JPEGENCODERSTATE*)encoder->state.context)->xdpi = xdpi;
((JPEGENCODERSTATE*)encoder->state.context)->ydpi = ydpi;
((JPEGENCODERSTATE*)encoder->state.context)->extra = extra;
((JPEGENCODERSTATE*)encoder->state.context)->extra_size = extra_size;
((JPEGENCODERSTATE*)encoder->state.context)->rawExif = rawExif;
((JPEGENCODERSTATE*)encoder->state.context)->rawExifLen = rawExifLen;
return (PyObject*) encoder;
}
开发者ID:AaronAsAChimp,项目名称:Pillow,代码行数:73,代码来源:encode.c
示例11: PyArray_HolidaysConverter
/*
* Converts a Python input into a non-normalized list of holidays.
*
* IMPORTANT: This function can't do the normalization, because it doesn't
* know the weekmask. You must call 'normalize_holiday_list'
* on the result before using it.
*/
NPY_NO_EXPORT int
PyArray_HolidaysConverter(PyObject *dates_in, npy_holidayslist *holidays)
{
PyArrayObject *dates = NULL;
PyArray_Descr *date_dtype = NULL;
npy_intp count;
/* Make 'dates' into an array */
if (PyArray_Check(dates_in)) {
dates = (PyArrayObject *)dates_in;
Py_INCREF(dates);
}
else {
PyArray_Descr *datetime_dtype;
/* Use the datetime dtype with generic units so it fills it in */
datetime_dtype = PyArray_DescrFromType(NPY_DATETIME);
if (datetime_dtype == NULL) {
goto fail;
}
/* This steals the datetime_dtype reference */
dates = (PyArrayObject *)PyArray_FromAny(dates_in, datetime_dtype,
0, 0, 0, dates_in);
if (dates == NULL) {
goto fail;
}
}
date_dtype = create_datetime_dtype_with_unit(NPY_DATETIME, NPY_FR_D);
if (date_dtype == NULL) {
goto fail;
}
if (!PyArray_CanCastTypeTo(PyArray_DESCR(dates),
date_dtype, NPY_SAFE_CASTING)) {
PyErr_SetString(PyExc_ValueError, "Cannot safely convert "
"provided holidays input into an array of dates");
goto fail;
}
if (PyArray_NDIM(dates) != 1) {
PyErr_SetString(PyExc_ValueError, "holidays must be a provided "
"as a one-dimensional array");
goto fail;
}
/* Allocate the memory for the dates */
count = PyArray_DIM(dates, 0);
holidays->begin = PyArray_malloc(sizeof(npy_datetime) * count);
if (holidays->begin == NULL) {
PyErr_NoMemory();
goto fail;
}
holidays->end = holidays->begin + count;
/* Cast the data into a raw date array */
if (PyArray_CastRawArrays(count,
PyArray_BYTES(dates), (char *)holidays->begin,
PyArray_STRIDE(dates, 0), sizeof(npy_datetime),
PyArray_DESCR(dates), date_dtype,
0) != NPY_SUCCEED) {
goto fail;
}
Py_DECREF(dates);
Py_DECREF(date_dtype);
return 1;
fail:
Py_XDECREF(dates);
Py_XDECREF(date_dtype);
return 0;
}
开发者ID:ChrisBarker-NOAA,项目名称:numpy,代码行数:81,代码来源:datetime_busdaycal.c
示例12: Util_func_getaddrinfo
static PyObject *
Util_func_getaddrinfo(PyObject *obj, PyObject *args, PyObject *kwargs)
{
char *name;
char port_str[6];
int port, family, socktype, protocol, flags, r;
struct addrinfo hints;
getaddrinfo_cb_data_t *cb_data = NULL;
uv_getaddrinfo_t* req = NULL;
Loop *loop;
PyObject *callback;
UNUSED_ARG(obj);
static char *kwlist[] = {"loop", "callback", "name", "port", "family", "socktype", "protocol", "flags", NULL};
port = socktype = protocol = flags = 0;
family = AF_UNSPEC;
if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O!sO|iiiii:getaddrinfo", kwlist, &LoopType, &loop, &name, &callback, &port, &family, &socktype, &protocol, &flags)) {
return NULL;
}
if (!PyCallable_Check(callback)) {
PyErr_SetString(PyExc_TypeError, "a callable is required");
return NULL;
}
if (port < 0 || port > 65536) {
PyErr_SetString(PyExc_ValueError, "port must be between 0 and 65536");
return NULL;
}
snprintf(port_str, sizeof(port_str), "%d", port);
req = PyMem_Malloc(sizeof(uv_getaddrinfo_t));
if (!req) {
PyErr_NoMemory();
goto error;
}
cb_data = PyMem_Malloc(sizeof(getaddrinfo_cb_data_t));
if (!cb_data) {
PyErr_NoMemory();
goto error;
}
Py_INCREF(loop);
Py_INCREF(callback);
cb_data->loop = loop;
cb_data->cb = callback;
req->data = (void *)cb_data;
memset(&hints, 0, sizeof(hints));
hints.ai_family = family;
hints.ai_socktype = socktype;
hints.ai_protocol = protocol;
hints.ai_flags = flags;
r = uv_getaddrinfo(loop->uv_loop, req, &getaddrinfo_cb, name, port_str, &hints);
if (r != 0) {
RAISE_UV_EXCEPTION(loop->uv_loop, PyExc_UVError);
goto error;
}
Py_RETURN_NONE;
error:
if (req) {
PyMem_Free(req);
}
return NULL;
}
开发者ID:aventurella,项目名称:pyuv,代码行数:72,代码来源:util.c
示例13: SAFE_FREE
//.........这里部分代码省略.........
SAFE_FREE(g_U);
return retval;
}
} else {
logger("[PyIPOPT] Ipopt will use Hessian approximation.\n");
}
if (applynew != NULL) {
if (PyCallable_Check(applynew)) {
myowndata.apply_new_python = applynew;
} else {
PyErr_SetString(PyExc_TypeError,
"Need a callable object for function applynew.");
retval = NULL;
SAFE_FREE(x_L);
SAFE_FREE(x_U);
SAFE_FREE(g_L);
SAFE_FREE(g_U);
return retval;
}
}
if (m < 0 || n < 0) {
PyErr_SetString(PyExc_TypeError, "m or n can't be negative");
retval = NULL;
SAFE_FREE(x_L);
SAFE_FREE(x_U);
SAFE_FREE(g_L);
SAFE_FREE(g_U);
return retval;
}
x_L = (Number *) malloc(sizeof(Number) * n);
x_U = (Number *) malloc(sizeof(Number) * n);
if (!x_L || !x_U) {
retval = PyErr_NoMemory();
SAFE_FREE(x_L);
SAFE_FREE(x_U);
SAFE_FREE(g_L);
SAFE_FREE(g_U);
return retval;
}
xldata = (double *)xL->data;
xudata = (double *)xU->data;
for (i = 0; i < n; i++) {
x_L[i] = xldata[i];
x_U[i] = xudata[i];
}
g_L = (Number *) malloc(sizeof(Number) * m);
g_U = (Number *) malloc(sizeof(Number) * m);
if (!g_L || !g_U)
PyErr_NoMemory();
gldata = (double *)gL->data;
gudata = (double *)gU->data;
for (i = 0; i < m; i++) {
g_L[i] = gldata[i];
g_U[i] = gudata[i];
}
/* Grab the callback objects because we want to use them later. */
Py_XINCREF(f);
Py_XINCREF(gradf);
Py_XINCREF(g);
Py_XINCREF(jacg);
Py_XINCREF(h);
开发者ID:xuy,项目名称:pyipopt,代码行数:67,代码来源:pyipoptcoremodule.c
示例14: Py_XDECREF
PyObject *solve(PyObject * self, PyObject * args)
{
enum ApplicationReturnStatus status; /* Solve return code */
int i;
int n;
/* Return values */
problem *temp = (problem *) self;
IpoptProblem nlp = (IpoptProblem) (temp->nlp);
DispatchData *bigfield = (DispatchData *) (temp->data);
int m = temp->m_constraints;
/* int dX[1]; */
npy_intp dX[1];
npy_intp dlambda[1];
PyArrayObject *x = NULL, *mL = NULL, *mU = NULL, *lambda = NULL;
Number obj; /* objective value */
PyObject *retval = NULL;
PyArrayObject *x0 = NULL;
PyObject *myuserdata = NULL;
Number *newx0 = NULL;
if (!PyArg_ParseTuple(args, "O!|O", &PyArray_Type, &x0, &myuserdata)) {
retval = NULL;
/* clean up and return */
if (retval == NULL) {
Py_XDECREF(x);
Py_XDECREF(mL);
Py_XDECREF(mU);
Py_XDECREF(lambda);
}
SAFE_FREE(newx0);
return retval;
}
if (x0->nd != 1){ //If x0 is not 1-dimensional then solve will fail and cause a segmentation fault.
logger("[ERROR] x0 must be a 1-dimensional array");
Py_XDECREF(x);
Py_XDECREF(mL);
Py_XDECREF(mU);
Py_XDECREF(lambda);
PyErr_SetString(PyExc_TypeError,
"x0 passed to solve is not 1-dimensional.");
return NULL;
}
if (myuserdata != NULL) {
bigfield->userdata = myuserdata;
/*
* logger("[PyIPOPT] User specified data field to callback
* function.\n");
*/
}
if (nlp == NULL) {
PyErr_SetString(PyExc_TypeError,
"nlp objective passed to solve is NULL\n Problem created?\n");
retval = NULL;
/* clean up and return */
if (retval == NULL) {
Py_XDECREF(x);
Py_XDECREF(mL);
Py_XDECREF(mU);
Py_XDECREF(lambda);
}
SAFE_FREE(newx0);
return retval;
}
if (bigfield->eval_h_python == NULL) {
AddIpoptStrOption(nlp, "hessian_approximation", "limited-memory");
/* logger("Can't find eval_h callback function\n"); */
}
/* allocate space for the initial point and set the values */
npy_intp *dim = ((PyArrayObject *) x0)->dimensions;
n = dim[0];
dX[0] = n;
x = (PyArrayObject *) PyArray_SimpleNew(1, dX, PyArray_DOUBLE);
if (!x) {
retval = PyErr_NoMemory();
/* clean up and return */
if (retval == NULL) {
Py_XDECREF(x);
Py_XDECREF(mL);
Py_XDECREF(mU);
Py_XDECREF(lambda);
}
SAFE_FREE(newx0);
return retval;
}
newx0 = (Number *) malloc(sizeof(Number) * n);
if (!newx0) {
retval = PyErr_NoMemory();
/* clean up and return */
if (retval == NULL) {
Py_XDECREF(x);
Py_XDECREF(mL);
//.........这里部分代码省略.........
开发者ID:xuy,项目名称:pyipopt,代码行数:101,代码来源:pyipoptcoremodule.c
示例15: open_file
/* Function of no arguments returning new Data object */
static PyObject *
open_file(PyObject *self, PyObject *args)
{
char *filename;
int fd;
DataObject *data_obj;
unsigned char file_hdr[2], jpeg_hdr[2] = {0xff,0xd8};
if (!PyArg_ParseTuple(args, "s:new", &filename))
return NULL;
/* check if the file exists first. We close this fd just
* because, but maybe in the future there is a case for
* keeping it around. */
fd = open(filename, O_RDONLY);
if (fd < 0)
return PyErr_SetFromErrnoWithFilename(PyExc_IOError, filename);
/* read the first 2 bytes, and check it looks like a jpeg */
if (read(fd, file_hdr, 2) < 2) {
close(fd);
return PyErr_SetFromErrnoWithFilename(PyExc_IOError, filename);
}
if (memcmp(jpeg_hdr, file_hdr, 2) != 0) {
close(fd);
PyErr_SetString(PyExc_ValueError,
"This file does not appear to be a JPEG file\n");
return NULL;
}
close(fd);
data_obj = newDataObject(args);
if (data_obj == NULL)
return PyErr_NoMemory();
/* save the filename for later */
data_obj->filename = PyString_FromString(filename);
if (!data_obj->filename) {
Py_DECREF(data_obj);
return PyErr_NoMemory();
}
/* firstly, try and get the existing data */
data_obj->d = iptc_data_new_from_jpeg(filename);
if (data_obj->d) {
/* read the existing iptc data into the dataset objects */
int i;
for (i=0; i < data_obj->d->count; i++) {
IptcDataSet *e = data_obj->d->datasets[i];
DataSetObject *ds = newDataSetObject(e);
/* XXX bail out? */
/* dataset objects hold a reference to their
* parent dataobject */
ds->parent = data_obj;
Py_INCREF(data_obj);
ds->state = VALID;
PyList_Append(data_obj->DataSet_list, (PyObject *)ds);
}
} else {
/* create a new, empty data object */
data_obj->d = iptc_data_new();
if (!data_obj->d)
return PyErr_NoMemory();
}
data_obj->state = OPEN;
return (PyObject*)data_obj;
}
开发者ID:OlehKulykov,项目名称:JpegIptcReader,代码行数:73,代码来源:pyiptcdatamod.c
示例16: exceptionlist__initmodule
int
exceptionlist__initmodule(PyObject* module, struct exceptionlist* exclist) {
const struct exceptionlist* exc;
char* longname = NULL;
PyObject* name;
Py_ssize_t size;
Py_ssize_t maxsize;
if ((name = PyObject_GetAttrString(module, "__name__")) == NULL)
return -1;
if (!PyString_Check(name)) {
PyErr_SetString(PyExc_TypeError, "__name__ required an str()");
goto failed;
}
size = PyString_GET_SIZE(name);
for (maxsize = 0, exc = exclist; exc->exc_name != NULL; exc++) {
register int i = strlen(exc->exc_name);
if (i > maxsize)
maxsize = i;
}
if ((longname = PyMem_MALLOC(size + sizeof(".") + maxsize + sizeof("\0"))) == NULL) {
PyErr_NoMemory();
goto failed;
}
memcpy(longname, PyString_AS_STRING(name), size);
Py_DECREF(name);
longname[size++] = '.';
for (exc = exclist; exc->exc_name != NULL; exc++) {
PyObject* dict;
PyObject* s;
if ((dict = PyDict_New()) == NULL)
goto failed;
if ((s = PyString_FromString(exc->exc_doc)) == NULL) {
Py_DECREF(dict);
goto failed;
}
if (PyDict_SetItemString(dict, "__doc__", s) < 0) {
Py_DECREF(dict);
Py_DECREF(s);
goto failed;
}
Py_DECREF(s);
strcpy(&longname[size], exc->exc_name);
if (*exc->exc_this == NULL &&
(*exc->exc_this = PyErr_NewException(longname, *exc->exc_base, dict)) == NULL) {
Py_DECREF(dict);
goto failed;
}
Py_DECREF(dict);
}
PyMem_FREE(longname);
for (exc = exclist; exc->exc_name != NULL; exc++) {
Py_INCREF(*exc->exc_this);
if (PyModule_AddObject(module, exc->exc_name, *exc->exc_this) < 0)
return -1;
}
return 0;
failed:
if (longname != NULL)
PyMem_FREE(longname);
Py_DECREF(name);
return -1;
}
开发者ID:grossho,项目名称:billow,代码行数:64,代码来源:pyexceptionlist.c
示例17: NI_Correlate
int NI_Correlate(PyArrayObject* input, PyArrayObject* weights,
PyArrayObject* output, NI_ExtendMode mode,
double cvalue, maybelong *origins)
{
Bool *pf = NULL;
maybelong fsize, jj, kk, filter_size = 0, border_flag_value;
maybelong *offsets = NULL, *oo, size;
NI_FilterIterator fi;
NI_Iterator ii, io;
char *pi, *po;
Float64 *pw;
Float64 *ww = NULL;
int ll;
/* get the the footprint: */
fsize = 1;
for(ll = 0; ll < weights->nd; ll++)
fsize *= weights->dimensions[ll];
pw = (Float64*)PyArray_DATA(weights);
pf = (Bool*)malloc(fsize * sizeof(Bool));
if (!pf) {
PyErr_NoMemory();
goto exit;
}
for(jj = 0; jj < fsize; jj++) {
if (fabs(pw[jj]) > DBL_EPSILON) {
pf[jj] = 1;
++filter_size;
} else {
pf[jj] = 0;
}
}
/* copy the weights to contiguous memory: */
ww = (Float64*)malloc(filter_size * sizeof(Float64));
if (!ww) {
PyErr_NoMemory();
goto exit;
}
jj = 0;
for(kk = 0; kk < fsize; kk++) {
if (pf[kk]) {
ww[jj++] = pw[kk];
}
}
/* initialize filter offsets: */
if (!NI_InitFilterOffsets(input, pf, weights->dimensions, origins,
mode, &offsets, &border_flag_value, NULL))
goto exit;
/* initialize filter iterator: */
if (!NI_InitFilterIterator(input->nd, weights->dimensions, filter_size,
input->dimensions, origins, &fi))
goto exit;
/* initialize input element iterator: */
if (!NI_InitPointIterator(input, &ii))
goto exit;
/* in
|
请发表评论