static PyObject *qdbusargument_add(QDBusArgument *arg, PyObject *obj, int mtype) { int iserr = 0; if (PyLong_CheckExact(obj) #if PY_MAJOR_VERSION < 3 || PyInt_CheckExact(obj) #endif ) { if (mtype == QMetaType::UChar || mtype == QMetaType::UShort || mtype == QMetaType::UInt || mtype == QMetaType::ULongLong) { // Handle the unsigned values. #if defined(HAVE_LONG_LONG) unsigned PY_LONG_LONG v = PyLong_AsUnsignedLongLongMask(obj); #else unsigned long v = PyLong_AsUnsignedLongMask(obj); #endif switch (mtype) { case QMetaType::UChar: *arg << (uchar)v; break; case QMetaType::UShort: *arg << (ushort)v; break; case QMetaType::UInt: *arg << (uint)v; break; case QMetaType::ULongLong: *arg << (qulonglong)v; break; } } else if (mtype == QMetaType::Short || mtype == QMetaType::Int || mtype == QMetaType::LongLong) { // Handle the signed values. #if defined(HAVE_LONG_LONG) PY_LONG_LONG v = PyLong_AsLongLong(obj); #else long v = PyLong_AsLong(obj); #endif switch (mtype) { case QMetaType::Short: *arg << (short)v; break; case QMetaType::Int: *arg << (int)v; break; case QMetaType::LongLong: *arg << (qlonglong)v; break; } } else { PyErr_Format(PyExc_ValueError, "%d is an invalid QMetaType::Type for an interger object", mtype); iserr = 1; } } else if (mtype == QMetaType::QStringList) { // A QStringList has to be handled explicitly to prevent it being seen // as a vialiant list. int value_state; QStringList *qsl = reinterpret_cast<QStringList *>( sipForceConvertToType(obj, sipType_QStringList, 0, SIP_NOT_NONE, &value_state, &iserr)); if (!iserr) { arg->beginArray(QMetaType::QString); for (int i = 0; i < qsl->count(); ++i) *arg << qsl->at(i); arg->endArray(); sipReleaseType(qsl, sipType_QStringList, value_state); } } else { int value_state; QVariant *qv = reinterpret_cast<QVariant *>( sipForceConvertToType(obj, sipType_QVariant, 0, SIP_NOT_NONE, &value_state, &iserr)); if (!iserr) { // This is an internal method. If it proves to be a problem then we // will have to handle each type explicitly. arg->appendVariant(*qv); sipReleaseType(qv, sipType_QVariant, value_state); } } if (iserr) return 0; Py_INCREF(Py_None); return Py_None; }
void set_integer_array_from_python(char* function, int* function_len, int* dim, int* nodes, double x[], double y[], double z[], double* t, int* result, int* stat) { #ifndef HAVE_PYTHON int i; strncpy(function, "No Python support!\n", (size_t) *function_len); for (i=0; i < *function_len; i++) { if (function[i] == '\0') function[i] = ' '; } *stat=1; return; #else PyObject *pMain, *pGlobals, *pLocals, *pFunc, *pCode, *pResult, *pArgs, *pPos, *px, *pT; char *function_c; int i; // the function string passed down from Fortran needs terminating, // so make a copy and fiddle with it (remember to free it) function_c = (char *)malloc(*function_len+3); memcpy( function_c, function, *function_len ); function_c[*function_len] = 0; // Get a reference to the main module and global dictionary pMain = PyImport_AddModule("__main__"); pGlobals = PyModule_GetDict(pMain); // Global and local namespace dictionaries for our code. pLocals=PyDict_New(); // Execute the user's code. pCode=PyRun_String(function_c, Py_file_input, pGlobals, pLocals); // Extract the function from the code. pFunc=PyDict_GetItemString(pLocals, "val"); // Clean up memory from null termination. free(function_c); // Check for errors in executing user code. if (PyErr_Occurred()){ PyErr_Print(); *stat=1; return; } // Python form of time variable. pT=PyFloat_FromDouble(*t); // Tuple containing the current position vector. pPos=PyTuple_New(*dim); // Tuple of arguments to function; pArgs=PyTuple_New(2); PyTuple_SetItem(pArgs, 1, pT); PyTuple_SetItem(pArgs, 0, pPos); // Check for a Python error in the function call if (PyErr_Occurred()){ PyErr_Print(); *stat=1; return; } for (i = 0; i < *nodes; i++){ px=PyFloat_FromDouble(x[i]); PyTuple_SetItem(pPos, 0, px); if (*dim>1) { px=PyFloat_FromDouble(y[i]); PyTuple_SetItem(pPos, 1, px); if (*dim>2) { px=PyFloat_FromDouble(z[i]); PyTuple_SetItem(pPos, 2, px); } } pResult=PyObject_CallObject(pFunc, pArgs); // Check for a Python error in the function call if (PyErr_Occurred()){ PyErr_Print(); *stat=1; return; } result[i]=PyLong_AsLong(pResult); // Check for a Python error in result. if (PyErr_Occurred()){ PyErr_Print(); *stat=1; return; } Py_DECREF(pResult); } // Clean up Py_DECREF(pArgs); Py_DECREF(pLocals); Py_DECREF(pCode); // Force a garbage collection PyGC_Collect(); *stat=0; return; #endif }
static PyObject * BaseRowProxy_subscript(BaseRowProxy *self, PyObject *key) { PyObject *processors, *values; PyObject *processor, *value, *processed_value; PyObject *row, *record, *result, *indexobject; PyObject *exc_module, *exception; char *cstr_key; long index; int key_fallback = 0; int tuple_check = 0; if (PyInt_CheckExact(key)) { index = PyInt_AS_LONG(key); } else if (PyLong_CheckExact(key)) { index = PyLong_AsLong(key); if ((index == -1) && PyErr_Occurred()) /* -1 can be either the actual value, or an error flag. */ return NULL; } else if (PySlice_Check(key)) { values = PyObject_GetItem(self->row, key); if (values == NULL) return NULL; processors = PyObject_GetItem(self->processors, key); if (processors == NULL) { Py_DECREF(values); return NULL; } result = BaseRowProxy_processvalues(values, processors, 1); Py_DECREF(values); Py_DECREF(processors); return result; } else { record = PyDict_GetItem((PyObject *)self->keymap, key); if (record == NULL) { record = PyObject_CallMethod(self->parent, "_key_fallback", "O", key); if (record == NULL) return NULL; key_fallback = 1; } indexobject = PyTuple_GetItem(record, 2); if (indexobject == NULL) return NULL; if (key_fallback) { Py_DECREF(record); } if (indexobject == Py_None) { exc_module = PyImport_ImportModule("sqlalchemy.exc"); if (exc_module == NULL) return NULL; exception = PyObject_GetAttrString(exc_module, "InvalidRequestError"); Py_DECREF(exc_module); if (exception == NULL) return NULL; cstr_key = PyString_AsString(key); if (cstr_key == NULL) return NULL; PyErr_Format(exception, "Ambiguous column name '%.200s' in result set! " "try 'use_labels' option on select statement.", cstr_key); return NULL; } index = PyInt_AsLong(indexobject); if ((index == -1) && PyErr_Occurred()) /* -1 can be either the actual value, or an error flag. */ return NULL; } processor = PyList_GetItem(self->processors, index); if (processor == NULL) return NULL; row = self->row; if (PyTuple_CheckExact(row)) { value = PyTuple_GetItem(row, index); tuple_check = 1; } else { value = PySequence_GetItem(row, index); tuple_check = 0; } if (value == NULL) return NULL; if (processor != Py_None) { processed_value = PyObject_CallFunctionObjArgs(processor, value, NULL); if (!tuple_check) { Py_DECREF(value); } return processed_value; } else { if (tuple_check) { Py_INCREF(value); } return value; } }
/** ****************************************************************************************************** * Returns data for a particular request string to AerospikeClient_InfoNode * * @param self AerospikeClient object * @param request_str_p Request string sent from the python client * @param py_host Optional host sent from the python client * @param py_policy The policy sent from the python client * * Returns information about a host. ********************************************************************************************************/ static PyObject * AerospikeClient_InfoNode_Invoke( AerospikeClient * self, PyObject * py_request_str, PyObject * py_host, PyObject * py_policy) { PyObject * py_response = NULL; PyObject * py_ustr = NULL; PyObject * py_ustr1 = NULL; as_policy_info info_policy; as_policy_info* info_policy_p = NULL; char* address = (char *) self->as->config.hosts[0].addr; long port_no = self->as->config.hosts[0].port; char* response_p = NULL; as_status status = AEROSPIKE_OK; as_error err; as_error_init(&err); if (!self || !self->as) { as_error_update(&err, AEROSPIKE_ERR_PARAM, "Invalid aerospike object"); goto CLEANUP; } if (!self->is_conn_16) { as_error_update(&err, AEROSPIKE_ERR_CLUSTER, "No connection to aerospike cluster"); goto CLEANUP; } if (py_policy) { if( PyDict_Check(py_policy) ) { pyobject_to_policy_info(&err, py_policy, &info_policy, &info_policy_p, &self->as->config.policies.info); if (err.code != AEROSPIKE_OK) { goto CLEANUP; } } else { as_error_update(&err, AEROSPIKE_ERR_PARAM, "Policy should be a dictionary"); goto CLEANUP; } } if ( py_host ) { if ( PyTuple_Check(py_host) && PyTuple_Size(py_host) == 2) { PyObject * py_addr = PyTuple_GetItem(py_host,0); PyObject * py_port = PyTuple_GetItem(py_host,1); if ( PyStr_Check(py_addr) ) { address = PyStr_AsString(py_addr); } else if (PyUnicode_Check(py_addr)) { py_ustr = PyUnicode_AsUTF8String(py_addr); address = PyStr_AsString(py_ustr); } if ( PyInt_Check(py_port) ) { port_no = (uint16_t) PyInt_AsLong(py_port); } else if ( PyLong_Check(py_port) ) { port_no = (uint16_t) PyLong_AsLong(py_port); } } else if ( !PyTuple_Check(py_host)){ as_error_update(&err, AEROSPIKE_ERR_PARAM, "Host should be a specified in form of Tuple."); goto CLEANUP; } } char * request_str_p = NULL; if (PyUnicode_Check(py_request_str)) { py_ustr1 = PyUnicode_AsUTF8String(py_request_str); request_str_p = PyStr_AsString(py_ustr1); } else if (PyStr_Check(py_request_str)) { request_str_p = PyStr_AsString(py_request_str); } else { as_error_update(&err, AEROSPIKE_ERR_PARAM, "Request should be of string type"); goto CLEANUP; } Py_BEGIN_ALLOW_THREADS status = aerospike_info_host(self->as, &err, info_policy_p, (const char *) address, (uint16_t) port_no, request_str_p, &response_p); Py_END_ALLOW_THREADS if( err.code == AEROSPIKE_OK ) { if (response_p && status == AEROSPIKE_OK){ py_response = PyStr_FromString(response_p); free(response_p); } else if ( response_p == NULL){ as_error_update(&err, AEROSPIKE_ERR_CLIENT, "Invalid info operation"); goto CLEANUP; } else if ( status != AEROSPIKE_OK ){ as_error_update(&err, status, "Info operation failed"); goto CLEANUP; } } else { as_error_update(&err, err.code, NULL); goto CLEANUP; } CLEANUP: if (py_ustr) { Py_DECREF(py_ustr); } if (py_ustr1) { Py_DECREF(py_ustr1); } if ( err.code != AEROSPIKE_OK ) { PyObject * py_err = NULL; error_to_pyobject(&err, &py_err); PyObject *exception_type = raise_exception(&err); PyErr_SetObject(exception_type, py_err); Py_DECREF(py_err); return NULL; } return py_response; }
static npy_intp PyArray_PyIntAsIntp_ErrMsg(PyObject *o, const char * msg) { #if (NPY_SIZEOF_LONG < NPY_SIZEOF_INTP) long long long_value = -1; #else long long_value = -1; #endif PyObject *obj, *err; if (!o) { PyErr_SetString(PyExc_TypeError, msg); return -1; } /* Be a bit stricter and not allow bools, np.bool_ is handled later */ if (PyBool_Check(o)) { if (DEPRECATE("using a boolean instead of an integer" " will result in an error in the future") < 0) { return -1; } } /* * Since it is the usual case, first check if o is an integer. This is * an exact check, since otherwise __index__ is used. */ #if !defined(NPY_PY3K) if (PyInt_CheckExact(o)) { #if (NPY_SIZEOF_LONG <= NPY_SIZEOF_INTP) /* No overflow is possible, so we can just return */ return PyInt_AS_LONG(o); #else long_value = PyInt_AS_LONG(o); goto overflow_check; #endif } else #endif if (PyLong_CheckExact(o)) { #if (NPY_SIZEOF_LONG < NPY_SIZEOF_INTP) long_value = PyLong_AsLongLong(o); #else long_value = PyLong_AsLong(o); #endif return (npy_intp)long_value; } /* Disallow numpy.bool_. Boolean arrays do not currently support index. */ if (PyArray_IsScalar(o, Bool)) { if (DEPRECATE("using a boolean instead of an integer" " will result in an error in the future") < 0) { return -1; } } /* * The most general case. PyNumber_Index(o) covers everything * including arrays. In principle it may be possible to replace * the whole function by PyIndex_AsSSize_t after deprecation. */ obj = PyNumber_Index(o); if (obj) { #if (NPY_SIZEOF_LONG < NPY_SIZEOF_INTP) long_value = PyLong_AsLongLong(obj); #else long_value = PyLong_AsLong(obj); #endif Py_DECREF(obj); goto finish; } else { /* * Set the TypeError like PyNumber_Index(o) would after trying * the general case. */ PyErr_Clear(); } /* * For backward compatibility check the number C-Api number protcol * This should be removed up the finish label after deprecation. */ if (Py_TYPE(o)->tp_as_number != NULL && Py_TYPE(o)->tp_as_number->nb_int != NULL) { obj = Py_TYPE(o)->tp_as_number->nb_int(o); if (obj == NULL) { return -1; } #if (NPY_SIZEOF_LONG < NPY_SIZEOF_INTP) long_value = PyLong_AsLongLong(obj); #else long_value = PyLong_AsLong(obj); #endif Py_DECREF(obj); } #if !defined(NPY_PY3K) else if (Py_TYPE(o)->tp_as_number != NULL && Py_TYPE(o)->tp_as_number->nb_long != NULL) { obj = Py_TYPE(o)->tp_as_number->nb_long(o); if (obj == NULL) { return -1; } #if (NPY_SIZEOF_LONG < NPY_SIZEOF_INTP) long_value = PyLong_AsLongLong(obj); #else long_value = PyLong_AsLong(obj); #endif Py_DECREF(obj); } #endif else { PyErr_SetString(PyExc_TypeError, msg); return -1; } /* Give a deprecation warning, unless there was already an error */ if (!error_converting(long_value)) { if (DEPRECATE("using a non-integer number instead of an integer" " will result in an error in the future") < 0) { return -1; } } finish: if (error_converting(long_value)) { err = PyErr_Occurred(); /* Only replace TypeError's here, which are the normal errors. */ if (PyErr_GivenExceptionMatches(err, PyExc_TypeError)) { PyErr_SetString(PyExc_TypeError, msg); } return -1; } overflow_check: #if (NPY_SIZEOF_LONG < NPY_SIZEOF_INTP) #if (NPY_SIZEOF_LONGLONG > NPY_SIZEOF_INTP) if ((long_value < NPY_MIN_INTP) || (long_value > NPY_MAX_INTP)) { PyErr_SetString(PyExc_OverflowError, "Python int too large to convert to C numpy.intp"); return -1; } #endif #else #if (NPY_SIZEOF_LONG > NPY_SIZEOF_INTP) if ((long_value < NPY_MIN_INTP) || (long_value > NPY_MAX_INTP)) { PyErr_SetString(PyExc_OverflowError, "Python int too large to convert to C numpy.intp"); return -1; } #endif #endif return long_value; }
static PyObject * obf_encode_circuit(PyObject *self, PyObject *args) { PyObject *py_state, *py_ys, *py_xdegs; mpz_t tmp, c_star; mpz_t *alphas, *betas; int n, m, ydeg; int *indices, *pows; char *circuit, *fname; int fnamelen = sizeof(int) + 5; int idx_set_size; struct state *s; if (!PyArg_ParseTuple(args, "OsOOiii", &py_state, &circuit, &py_ys, &py_xdegs, &ydeg, &n,&m)){ fprintf(stderr,"!!!!!!!! NOT PARSING !!!!!!!!!!!!!!!!\n"); return NULL;} s = (struct state *) PyCapsule_GetPointer(py_state, NULL); if (s == NULL) return NULL; fname = (char *) malloc(sizeof(char) * fnamelen); if (fname == NULL) return NULL; int ierr,rank,world_size; ierr = MPI_Comm_rank ( MPI_COMM_WORLD, &rank ); ierr = MPI_Comm_size(MPI_COMM_WORLD,&world_size); struct clt_mlm_ser_enc* sent_mlm = stat_ser(&(s->mlm)); //broadcast_clt_mlm_ser_enc(sent_mlm); ser_stat( sent_mlm,&(s->mlm) ); mpz_init_set(s->nev, s->mlm.gs[0]); mpz_init_set(s->nchk, s->mlm.gs[1]); mpz_inits(c_star, tmp, NULL); rank = 0; world_size =1; int start_n_loop = rank*n/world_size; int stop_n_loop = (rank+1)*n/world_size; //int size_n_loop = start_n_loop - stop_n_loop; int start_m_loop = rank*m/world_size; int stop_m_loop = (rank+1)*m/world_size; //int size_m_loop = start_m_loop; alphas = (mpz_t *) malloc(sizeof(mpz_t) * n); #pragma omp parallel for for (int i = 0; i < n; ++i) { mpz_init(alphas[i]); mpz_urandomm(alphas[i], s->mlm.rng, s->nchk); } betas = (mpz_t *) malloc(sizeof(mpz_t) * m); #pragma omp parallel for for (int i = 0; i < m; ++i) { mpz_init(betas[i]); mpz_urandomm(betas[i], s->mlm.rng, s->nchk); } std::vector<std::vector<char> > alpha_send = mpz_arr_to_vec(alphas, n); std::vector<std::vector<char> > beta_send = mpz_arr_to_vec(betas, m); //broadcast_vec_vec(&alpha_send); //broadcast_vec_vec(&beta_send); vec_to_mpz_array(alphas,alpha_send); vec_to_mpz_array(betas,beta_send); fprintf(stderr,"Process %d has g[0] = %lu\n",rank,mpz_get_ui(s->mlm.gs[0])); fprintf(stderr,"Process %d has pzt = %lu\n",rank,mpz_get_ui(s->mlm.pzt)); fprintf(stderr,"Process %d has alpha = %lu\n",rank,mpz_get_ui(alphas[2])); // The index set is laid out as follows: // - The first 2 * n entries contain X_i,0 and X_i,1 // - The next n entries contain Z_i // - The next n entries contain W_i // - The final entry contains Y idx_set_size = 4 * n + 1; indices = (int *) malloc(sizeof(int) * idx_set_size); pows = (int *) malloc(sizeof(int) * idx_set_size); //MR fprintf(stderr, "m: %d , n: %d \n ", m,n); for (int i = start_n_loop; i <stop_n_loop ; ++i) { fprintf(stderr,"In loop: %d\n",i); mpz_t out, elems[2]; int deg; mpz_inits(out, elems[0], elems[1], NULL); deg = PyLong_AsLong(PyList_GET_ITEM(py_xdegs, i)); //MR //fprintf(stderr, "%d, " ,deg); set_indices_pows(indices, pows, 1, 2 * i, 1); mpz_set_ui(elems[0], 0); mpz_set(elems[1], alphas[i]); clt_mlm_encode(&s->mlm, out, 2, elems, 1, indices, pows); (void) snprintf(fname, fnamelen, "x_%d_0", i); (void) write_element(s->dir, out, fname); fprintf(stderr,"Past 1st encode In loop: %d\n",i); set_indices_pows(indices, pows, 1, 2 * i, 1); mpz_set_ui(elems[0], 1); mpz_set_ui(elems[1], 1); clt_mlm_encode(&s->mlm, out, 2, elems, 1, indices, pows); (void) snprintf(fname, fnamelen, "u_%d_0", i); (void) write_element(s->dir, out, fname); set_indices_pows(indices, pows, 1, 2 * i + 1, 1); mpz_set_ui(elems[0], 1); mpz_set(elems[1], alphas[i]); clt_mlm_encode(&s->mlm, out, 2, elems, 1, indices, pows); fprintf(stderr,"Past Third encode In loop: %d\n",i); (void) snprintf(fname, fnamelen, "x_%d_1", i); (void) write_element(s->dir, out, fname); set_indices_pows(indices, pows, 1, 2 * i + 1, 1); mpz_set_ui(elems[0], 1); mpz_set_ui(elems[1], 1); clt_mlm_encode(&s->mlm, out, 2, elems, 1, indices, pows); (void) snprintf(fname, fnamelen, "u_%d_1", i); (void) write_element(s->dir, out, fname); mpz_urandomm(elems[0], s->mlm.rng, s->nev); mpz_urandomm(elems[1], s->mlm.rng, s->nchk); set_indices_pows(indices, pows, 3, 2 * i + 1, deg, 2 * n + i, 1, 3 * n + i, 1); clt_mlm_encode(&s->mlm, out, 2, elems, 3, indices, pows); (void) snprintf(fname, fnamelen, "z_%d_0", i); (void) write_element(s->dir, out, fname); set_indices_pows(indices, pows, 1, 3 * n + i, 1); mpz_set_ui(elems[0], 0); clt_mlm_encode(&s->mlm, out, 2, elems, 1, indices, pows); (void) snprintf(fname, fnamelen, "w_%d_0", i); (void) write_element(s->dir, out, fname); mpz_urandomm(elems[0], s->mlm.rng, s->nev); mpz_urandomm(elems[1], s->mlm.rng, s->nchk); set_indices_pows(indices, pows, 3, 2 * i, deg, 2 * n + i, 1, 3 * n + i, 1); clt_mlm_encode(&s->mlm, out, 2, elems, 3, indices, pows); (void) snprintf(fname, fnamelen, "z_%d_1", i); (void) write_element(s->dir, out, fname); set_indices_pows(indices, pows, 1, 3 * n + i, 1); mpz_set_ui(elems[0], 0); clt_mlm_encode(&s->mlm, out, 2, elems, 1, indices, pows); (void) snprintf(fname, fnamelen, "w_%d_1", i); (void) write_element(s->dir, out, fname); mpz_clears(out, elems[0], elems[1], NULL); } set_indices_pows(indices, pows, 1, 4 * n, 1); for (int i = start_m_loop; i < stop_m_loop; ++i) { mpz_t out, elems[2]; mpz_inits(out, elems[0], elems[1], NULL); py_to_mpz(elems[0], PyList_GET_ITEM(py_ys, i)); if (mpz_sgn(elems[0]) == -1) { mpz_mod(elems[0], elems[0], s->nev); } mpz_set(elems[1], betas[i]); clt_mlm_encode(&s->mlm, out, 2, elems, 1, indices, pows); (void) snprintf(fname, fnamelen, "y_%d", i); (void) write_element(s->dir, out, fname); mpz_clears(out, elems[0], elems[1], NULL); } if(rank==0) { mpz_t elems[2]; mpz_init_set_ui(elems[0], 1); mpz_init_set_ui(elems[1], 1); clt_mlm_encode(&s->mlm, tmp, 2, elems, 1, indices, pows); (void) write_element(s->dir, tmp, "v"); mpz_clears(elems[0], elems[1], NULL); } if(rank==0){ struct circuit *c; c = circ_parse(circuit); { int circnamelen; char *circname; circnamelen = strlen(s->dir) + strlen("/circuit") + 2; circname = (char *) malloc(sizeof(char) * circnamelen); (void) snprintf(circname, circnamelen, "%s/circuit", s->dir); (void) circ_copy_circuit(circuit, circname); free(circname); } (void) circ_evaluate(c, alphas, betas, c_star, s->mlm.q); circ_cleanup(c); } //GET ALPHAS AND BETAS BACK TO ROOT! Maybe with a gather? if(rank==0){ { mpz_t elems[2]; // The C* encoding contains everything but the W_i symbols. // Here we calculate the appropriate indices and powers. for (int i = 0; i < n; ++i) { int deg; deg = PyLong_AsLong(PyList_GET_ITEM(py_xdegs, i)); // X_i,0^deg(x_i) indices[2 * i] = 2 * i; pows[2 * i] = deg; // X_i,1^deg(x_i) indices[2 * i + 1] = 2 * i + 1; pows[2 * i + 1] = deg; // Z_i indices[2 * n + i] = 2 * n + i; pows[2 * n + i] = 1; } // Y^deg(y) indices[3 * n] = 4 * n; pows[3 * n] = ydeg; // Encode against these indices/powers mpz_init_set_ui(elems[0], 0); mpz_init_set(elems[1], c_star); clt_mlm_encode(&s->mlm, tmp, 2, elems, 3 * n + 1, indices, pows); } (void) write_element(s->dir, tmp, "c_star"); } mpz_clears(c_star, tmp, NULL); fprintf(stderr,"QSIZE= %d\n",(mpz_sizeinbase(s->mlm.q, 2))); fprintf(stderr,"Process %d has finished its encoding work!\n",rank); MPI_Barrier(MPI_COMM_WORLD); Py_RETURN_NONE; }
static int convert_binary(struct srd_decoder_inst *di, PyObject *obj, struct srd_proto_data *pdata) { struct srd_proto_data_binary *pdb; PyObject *py_tmp; Py_ssize_t size; int bin_class; char *class_name, *buf; /* Should be a tuple of (binary class, bytes). */ if (!PyTuple_Check(obj)) { srd_err("Protocol decoder %s submitted SRD_OUTPUT_BINARY with " "%s instead of tuple.", di->decoder->name, obj->ob_type->tp_name); return SRD_ERR_PYTHON; } /* Should have 2 elements. */ if (PyTuple_Size(obj) != 2) { srd_err("Protocol decoder %s submitted SRD_OUTPUT_BINARY tuple " "with %d elements instead of 2", di->decoder->name, PyList_Size(obj)); return SRD_ERR_PYTHON; } /* The first element should be an integer. */ py_tmp = PyTuple_GetItem(obj, 0); if (!PyLong_Check(py_tmp)) { srd_err("Protocol decoder %s submitted SRD_OUTPUT_BINARY tuple, " "but first element was not an integer.", di->decoder->name); return SRD_ERR_PYTHON; } bin_class = PyLong_AsLong(py_tmp); if (!(class_name = g_slist_nth_data(di->decoder->binary, bin_class))) { srd_err("Protocol decoder %s submitted SRD_OUTPUT_BINARY with " "unregistered binary class %d.", di->decoder->name, bin_class); return SRD_ERR_PYTHON; } /* Second element should be bytes. */ py_tmp = PyTuple_GetItem(obj, 1); if (!PyBytes_Check(py_tmp)) { srd_err("Protocol decoder %s submitted SRD_OUTPUT_BINARY tuple, " "but second element was not bytes.", di->decoder->name); return SRD_ERR_PYTHON; } /* Consider an empty set of bytes a bug. */ if (PyBytes_Size(py_tmp) == 0) { srd_err("Protocol decoder %s submitted SRD_OUTPUT_BINARY " "with empty data set.", di->decoder->name); return SRD_ERR_PYTHON; } if (!(pdb = g_try_malloc(sizeof(struct srd_proto_data_binary)))) return SRD_ERR_MALLOC; if (PyBytes_AsStringAndSize(py_tmp, &buf, &size) == -1) return SRD_ERR_PYTHON; pdb->bin_class = bin_class; pdb->size = size; if (!(pdb->data = g_try_malloc(pdb->size))) return SRD_ERR_MALLOC; memcpy((void *)pdb->data, (const void *)buf, pdb->size); pdata->data = pdb; return SRD_OK; }
static int format_long_internal(PyObject *value, const InternalFormatSpec *format, _PyUnicodeWriter *writer) { int result = -1; Py_UCS4 maxchar = 127; PyObject *tmp = NULL; Py_ssize_t inumeric_chars; Py_UCS4 sign_char = '\0'; Py_ssize_t n_digits; /* count of digits need from the computed string */ Py_ssize_t n_remainder = 0; /* Used only for 'c' formatting, which produces non-digits */ Py_ssize_t n_prefix = 0; /* Count of prefix chars, (e.g., '0x') */ Py_ssize_t n_total; Py_ssize_t prefix = 0; NumberFieldWidths spec; long x; /* Locale settings, either from the actual locale or from a hard-code pseudo-locale */ LocaleInfo locale = STATIC_LOCALE_INFO_INIT; /* no precision allowed on integers */ if (format->precision != -1) { PyErr_SetString(PyExc_ValueError, "Precision not allowed in integer format specifier"); goto done; } /* special case for character formatting */ if (format->type == 'c') { /* error to specify a sign */ if (format->sign != '\0') { PyErr_SetString(PyExc_ValueError, "Sign not allowed with integer" " format specifier 'c'"); goto done; } /* error to request alternate format */ if (format->alternate) { PyErr_SetString(PyExc_ValueError, "Alternate form (#) not allowed with integer" " format specifier 'c'"); goto done; } /* taken from unicodeobject.c formatchar() */ /* Integer input truncated to a character */ x = PyLong_AsLong(value); if (x == -1 && PyErr_Occurred()) goto done; if (x < 0 || x > 0x10ffff) { PyErr_SetString(PyExc_OverflowError, "%c arg not in range(0x110000)"); goto done; } tmp = PyUnicode_FromOrdinal(x); inumeric_chars = 0; n_digits = 1; maxchar = Py_MAX(maxchar, (Py_UCS4)x); /* As a sort-of hack, we tell calc_number_widths that we only have "remainder" characters. calc_number_widths thinks these are characters that don't get formatted, only copied into the output string. We do this for 'c' formatting, because the characters are likely to be non-digits. */ n_remainder = 1; } else { int base; int leading_chars_to_skip = 0; /* Number of characters added by PyNumber_ToBase that we want to skip over. */ /* Compute the base and how many characters will be added by PyNumber_ToBase */ switch (format->type) { case 'b': base = 2; leading_chars_to_skip = 2; /* 0b */ break; case 'o': base = 8; leading_chars_to_skip = 2; /* 0o */ break; case 'x': case 'X': base = 16; leading_chars_to_skip = 2; /* 0x */ break; default: /* shouldn't be needed, but stops a compiler warning */ case 'd': case 'n': base = 10; break; } if (format->sign != '+' && format->sign != ' ' && format->width == -1 && format->type != 'X' && format->type != 'n' && !format->thousands_separators && PyLong_CheckExact(value)) { /* Fast path */ return _PyLong_FormatWriter(writer, value, base, format->alternate); } /* The number of prefix chars is the same as the leading chars to skip */ if (format->alternate) n_prefix = leading_chars_to_skip; /* Do the hard part, converting to a string in a given base */ tmp = _PyLong_Format(value, base); if (tmp == NULL || PyUnicode_READY(tmp) == -1) goto done; inumeric_chars = 0; n_digits = PyUnicode_GET_LENGTH(tmp); prefix = inumeric_chars; /* Is a sign character present in the output? If so, remember it and skip it */ if (PyUnicode_READ_CHAR(tmp, inumeric_chars) == '-') { sign_char = '-'; ++prefix; ++leading_chars_to_skip; } /* Skip over the leading chars (0x, 0b, etc.) */ n_digits -= leading_chars_to_skip; inumeric_chars += leading_chars_to_skip; } /* Determine the grouping, separator, and decimal point, if any. */ if (get_locale_info(format->type == 'n' ? LT_CURRENT_LOCALE : (format->thousands_separators ? LT_DEFAULT_LOCALE : LT_NO_LOCALE), &locale) == -1) goto done; /* Calculate how much memory we'll need. */ n_total = calc_number_widths(&spec, n_prefix, sign_char, tmp, inumeric_chars, inumeric_chars + n_digits, n_remainder, 0, &locale, format, &maxchar); /* Allocate the memory. */ if (_PyUnicodeWriter_Prepare(writer, n_total, maxchar) == -1) goto done; /* Populate the memory. */ result = fill_number(writer, &spec, tmp, inumeric_chars, inumeric_chars + n_digits, tmp, prefix, format->fill_char, &locale, format->type == 'X'); done: Py_XDECREF(tmp); free_locale_info(&locale); return result; }
PygtsVertex * pygts_vertex_from_sequence(PyObject *tuple) { guint i,N; gdouble x=0,y=0,z=0; PyObject *obj; GtsVertex *v; PygtsVertex *vertex; /* Convert list into tuple */ if(PyList_Check(tuple)) { tuple = PyList_AsTuple(tuple); } else { Py_INCREF(tuple); } if(!PyTuple_Check(tuple)) { Py_DECREF(tuple); PyErr_SetString(PyExc_TypeError,"expected a list or tuple of vertices"); return NULL; } /* Get the tuple size */ if( (N = PyTuple_Size(tuple)) > 3 ) { PyErr_SetString(PyExc_RuntimeError, "expected a list or tuple of up to three floats"); Py_DECREF(tuple); return NULL; } /* Get the coordinates */ for(i=0;i<N;i++) { obj = PyTuple_GET_ITEM(tuple,i); if(!PyFloat_Check(obj) && !PyLong_Check(obj)) { PyErr_SetString(PyExc_TypeError,"expected a list or tuple of floats"); Py_DECREF(tuple); return NULL; } if(i==0) { if(PyFloat_Check(obj)) x = PyFloat_AsDouble(obj); else x = (double)PyLong_AsLong(obj); } if(i==1) { if(PyFloat_Check(obj)) y = PyFloat_AsDouble(obj); else y = (double)PyLong_AsLong(obj); } if(i==2) { if(PyFloat_Check(obj)) z = PyFloat_AsDouble(obj); else z = (double)PyLong_AsLong(obj); } } Py_DECREF(tuple); /* Create the vertex */ if( (v = gts_vertex_new(gts_vertex_class(),x,y,z)) == NULL ) { PyErr_SetString(PyExc_MemoryError,"could not create Vertex"); } if( (vertex = pygts_vertex_new(v)) == NULL ) { gts_object_destroy(GTS_OBJECT(v)); return NULL; } return vertex; }
std::shared_ptr<MI::MIValue> Py2MI(PyObject* pyValue, MI_Type valueType) { if (pyValue == Py_None) { return std::make_shared<MI::MIValue>(valueType); } if (PyObject_IsInstance(pyValue, reinterpret_cast<PyObject*>(&PyBool_Type))) { return MI::MIValue::FromBoolean(PyObject_IsTrue(pyValue) ? MI_TRUE : MI_FALSE); } else if (PyObject_IsInstance(pyValue, reinterpret_cast<PyObject*>(&PyLong_Type))) { switch (valueType) { case MI_BOOLEAN: return MI::MIValue::FromBoolean(PyLong_AsLong(pyValue) != 0); case MI_UINT8: return MI::MIValue::FromUint8((MI_Uint8)PyLong_AsUnsignedLong(pyValue)); case MI_SINT8: return MI::MIValue::FromSint8((MI_Sint8)PyLong_AsLong(pyValue)); case MI_UINT16: return MI::MIValue::FromUint16((MI_Uint16)PyLong_AsUnsignedLong(pyValue)); case MI_SINT16: return MI::MIValue::FromSint16((MI_Sint16)PyLong_AsLong(pyValue)); case MI_CHAR16: return MI::MIValue::FromChar16((MI_Char16)PyLong_AsLong(pyValue)); case MI_UINT32: return MI::MIValue::FromUint32(PyLong_AsUnsignedLong(pyValue)); case MI_SINT32: return MI::MIValue::FromSint32(PyLong_AsLong(pyValue)); case MI_UINT64: return MI::MIValue::FromUint64(PyLong_AsUnsignedLongLong(pyValue)); case MI_SINT64: return MI::MIValue::FromSint64(PyLong_AsLongLong(pyValue)); case MI_REAL32: return MI::MIValue::FromReal32((MI_Real32)PyLong_AsDouble(pyValue)); case MI_REAL64: return MI::MIValue::FromReal64(PyLong_AsDouble(pyValue)); case MI_STRING: return Py2StrMIValue(pyValue); default: throw MI::TypeConversionException(); } } #ifndef IS_PY3K else if (PyObject_IsInstance(pyValue, reinterpret_cast<PyObject*>(&PyInt_Type))) { switch (valueType) { case MI_BOOLEAN: return MI::MIValue::FromBoolean(PyInt_AsLong(pyValue) != 0); case MI_UINT8: return MI::MIValue::FromUint8((MI_Uint8)PyInt_AsLong(pyValue)); case MI_SINT8: return MI::MIValue::FromSint8((MI_Sint8)PyInt_AsLong(pyValue)); case MI_UINT16: return MI::MIValue::FromUint16((MI_Uint16)PyInt_AsLong(pyValue)); case MI_SINT16: return MI::MIValue::FromSint16((MI_Sint16)PyInt_AsLong(pyValue)); case MI_CHAR16: return MI::MIValue::FromChar16((MI_Char16)PyLong_AsLong(pyValue)); case MI_UINT32: return MI::MIValue::FromUint32((MI_Uint32)PyInt_AsLong(pyValue)); case MI_SINT32: return MI::MIValue::FromSint32((MI_Sint32)PyInt_AsLong(pyValue)); case MI_UINT64: return MI::MIValue::FromUint64((MI_Uint64)PyInt_AsLong(pyValue)); case MI_SINT64: return MI::MIValue::FromSint64((MI_Sint64)PyInt_AsLong(pyValue)); case MI_REAL32: return MI::MIValue::FromReal32((MI_Real32)PyInt_AsLong(pyValue)); case MI_REAL64: return MI::MIValue::FromReal64((MI_Real64)PyInt_AsLong(pyValue)); case MI_STRING: return Py2StrMIValue(pyValue); default: throw MI::TypeConversionException(); } } else if (PyObject_IsInstance(pyValue, reinterpret_cast<PyObject*>(&PyString_Type))) { switch (valueType) { case MI_STRING: return MI::MIValue::FromString(std::string(PyString_AsString(pyValue))); case MI_SINT8: case MI_UINT8: case MI_SINT16: case MI_UINT16: case MI_CHAR16: case MI_SINT32: case MI_UINT32: case MI_SINT64: case MI_UINT64: case MI_REAL32: case MI_REAL64: return Str2PyLong2MI(PyString_AsString(pyValue), valueType); default: throw MI::TypeConversionException(); } } #endif else if (PyObject_IsInstance(pyValue, reinterpret_cast<PyObject*>(&PyUnicode_Type))) { switch (valueType) { case MI_STRING: return MI::MIValue::FromString(Py2WString(pyValue)); case MI_SINT8: case MI_UINT8: case MI_SINT16: case MI_UINT16: case MI_CHAR16: case MI_SINT32: case MI_UINT32: case MI_SINT64: case MI_UINT64: case MI_REAL32: case MI_REAL64: { auto str = Py2WString(pyValue); std::wstring_convert<std::codecvt_utf8<wchar_t>, wchar_t> cv; return Str2PyLong2MI((char*)cv.to_bytes(str).c_str(), valueType); } default: throw MI::TypeConversionException(); } } else if (PyObject_IsInstance(pyValue, reinterpret_cast<PyObject*>(&InstanceType))) { switch (valueType) { case MI_INSTANCE: // TODO: Set the same ScopeContextOwner as the container instance / class return MI::MIValue::FromInstance(*((Instance*)pyValue)->instance); case MI_REFERENCE: // TODO: Set the same ScopeContextOwner as the container instance / class return MI::MIValue::FromReference(*((Instance*)pyValue)->instance); default: throw MI::TypeConversionException(); } } else if (PyObject_IsInstance(pyValue, reinterpret_cast<PyObject*>(&PyTuple_Type)) || PyObject_IsInstance(pyValue, reinterpret_cast<PyObject*>(&PyList_Type))) { bool isTuple = PyObject_IsInstance(pyValue, reinterpret_cast<PyObject*>(&PyTuple_Type)) != 0; Py_ssize_t size = 0; if (isTuple) { size = PyTuple_Size(pyValue); } else { size = PyList_Size(pyValue); } MI_Type itemType = (MI_Type)(valueType ^ MI_ARRAY); auto value = MI::MIValue::CreateArray((unsigned)size, valueType); for (Py_ssize_t i = 0; i < size; i++) { PyObject* pyObj = NULL; if (isTuple) { pyObj = PyTuple_GetItem(pyValue, i); } else { pyObj = PyList_GetItem(pyValue, i); } auto& tmpValue = Py2MI(pyObj, itemType); value->SetArrayItem(*tmpValue, (unsigned)i); } return value; } else { switch (valueType) { case MI_STRING: return Py2StrMIValue(pyValue); default: throw MI::TypeConversionException(); } } }
int PyMember_SetOne(char *addr, PyMemberDef *l, PyObject *v) { PyObject *oldv; if ((l->flags & READONLY) || l->type == T_STRING #ifdef macintosh || l->type == T_PSTRING #endif ) { PyErr_SetString(PyExc_TypeError, "readonly attribute"); return -1; } // if ((l->flags & WRITE_RESTRICTED) && PyEval_GetRestricted()) { // PyErr_SetString(PyExc_RuntimeError, "restricted attribute"); // return -1; // } if (v == NULL && l->type != T_OBJECT_EX && l->type != T_OBJECT) { PyErr_SetString(PyExc_TypeError, "can't delete numeric/char attribute"); return -1; } addr += l->offset; switch (l->type) { case T_BYTE: case T_UBYTE: if (!PyInt_Check(v)) { PyErr_BadArgument(); return -1; } *(char*)addr = (char) PyInt_AsLong(v); break; case T_SHORT: case T_USHORT: if (!PyInt_Check(v)) { PyErr_BadArgument(); return -1; } *(short*)addr = (short) PyInt_AsLong(v); break; case T_UINT: case T_INT: if (!PyInt_Check(v)) { PyErr_BadArgument(); return -1; } *(int*)addr = (int) PyInt_AsLong(v); break; case T_LONG: if (!PyInt_Check(v)) { PyErr_BadArgument(); return -1; } *(long*)addr = PyInt_AsLong(v); break; case T_ULONG: if (PyInt_Check(v)) *(long*)addr = PyInt_AsLong(v); else if (PyLong_Check(v)) *(long*)addr = PyLong_AsLong(v); else { PyErr_BadArgument(); return -1; } break; case T_FLOAT: if (PyInt_Check(v)) *(float*)addr = (float) PyInt_AsLong(v); else if (PyFloat_Check(v)) *(float*)addr = (float) PyFloat_AsDouble(v); else { PyErr_BadArgument(); return -1; } break; case T_DOUBLE: if (PyInt_Check(v)) *(double*)addr = (double) PyInt_AsLong(v); else if (PyFloat_Check(v)) *(double*)addr = PyFloat_AsDouble(v); else { PyErr_BadArgument(); return -1; } break; case T_OBJECT: case T_OBJECT_EX: Py_XINCREF(v); oldv = *(PyObject **)addr; *(PyObject **)addr = v; Py_XDECREF(oldv); break; case T_CHAR: if (PyString_Check(v) && PyString_Size(v) == 1) { *(char*)addr = PyString_AsString(v)[0]; } else { PyErr_BadArgument(); return -1; } break; default: PyErr_Format(PyExc_SystemError, "bad memberdescr type for %s", l->name); return -1; } return 0; }
Nature::EdgeNature EdgeNature_from_BPy_Nature(PyObject *obj) { return static_cast<Nature::EdgeNature>(PyLong_AsLong(obj)); }
Stroke::MediumType MediumType_from_BPy_MediumType(PyObject *obj) { return static_cast<Stroke::MediumType>(PyLong_AsLong(obj)); }
IntegrationType IntegrationType_from_BPy_IntegrationType(PyObject *obj) { return static_cast<IntegrationType>(PyLong_AsLong(obj)); }
PyObject * ufunc_fromfunc(PyObject *NPY_UNUSED(dummy), PyObject *args) { // unsigned long func_address; // unused int nin, nout; int nfuncs, ntypes, ndata; PyObject *func_list; PyObject *type_list; PyObject *data_list; PyObject *func_obj; PyObject *type_obj; PyObject *data_obj; PyObject *object=NULL; /* object to hold on to while ufunc is alive */ PyObject *dispatcher = NULL; int i, j; int custom_dtype = 0; PyUFuncGenericFunction *funcs; int *types; void **data; PyObject *ufunc; if (!PyArg_ParseTuple(args, "O!O!iiO|OO", &PyList_Type, &func_list, &PyList_Type, &type_list, &nin, &nout, &data_list, &dispatcher, &object)) { return NULL; } if (dispatcher == Py_None) dispatcher = NULL; nfuncs = PyList_Size(func_list); ntypes = PyList_Size(type_list); if (ntypes != nfuncs) { PyErr_SetString(PyExc_TypeError, "length of types list must be same as length of function pointer list"); return NULL; } ndata = PyList_Size(data_list); if (ndata != nfuncs) { PyErr_SetString(PyExc_TypeError, "length of data pointer list must be same as length of function pointer list"); return NULL; } funcs = PyArray_malloc(nfuncs * sizeof(PyUFuncGenericFunction)); if (funcs == NULL) { return NULL; } /* build function pointer array */ for (i = 0; i < nfuncs; i++) { func_obj = PyList_GetItem(func_list, i); /* Function pointers are passed in as long objects. Is there a better way to do this? */ if (PyLong_Check(func_obj)) { funcs[i] = (PyUFuncGenericFunction)PyLong_AsVoidPtr(func_obj); } else { PyErr_SetString(PyExc_TypeError, "function pointer must be long object, or None"); return NULL; } } types = PyArray_malloc(nfuncs * (nin+nout) * sizeof(int)); if (types == NULL) { return NULL; } /* build function signatures array */ for (i = 0; i < nfuncs; i++) { type_obj = PyList_GetItem(type_list, i); if (!type_obj) return NULL; for (j = 0; j < (nin+nout); j++) { int dtype_num; PyObject *dtype_num_obj = PyList_GetItem(type_obj, j); if (!dtype_num_obj) return NULL; SENTRY_VALID_LONG( types[i*(nin+nout) + j] = PyLong_AsLong(dtype_num_obj) ); dtype_num = PyLong_AsLong(PyList_GetItem(type_obj, j)); SENTRY_VALID_LONG(dtype_num); if (dtype_num >= NPY_USERDEF) { custom_dtype = dtype_num; } } } data = PyArray_malloc(nfuncs * sizeof(void *)); if (data == NULL) { return NULL; } /* build function data pointers array */ for (i = 0; i < nfuncs; i++) { if (PyList_Check(data_list)) { data_obj = PyList_GetItem(data_list, i); if (PyLong_Check(data_obj)) { data[i] = PyLong_AsVoidPtr(data_obj); } else if (data_obj == Py_None) { data[i] = NULL; } else { PyErr_SetString(PyExc_TypeError, "data pointer must be long object, or None"); return NULL; } } else if (data_list == Py_None) { data[i] = NULL; } else { PyErr_SetString(PyExc_TypeError, "data pointers argument must be a list of void pointers, or None"); return NULL; } } if (!custom_dtype) { char *char_types = PyArray_malloc(nfuncs * (nin+nout) * sizeof(char)); for (i = 0; i < nfuncs; i++) { for (j = 0; j < (nin+nout); j++) { char_types[i*(nin+nout) + j] = (char)types[i*(nin+nout) + j]; } } PyArray_free(types); ufunc = PyDynUFunc_FromFuncAndData((PyUFuncGenericFunction*) funcs, data, (char*) char_types, nfuncs, nin, nout, PyUFunc_None, "ufunc", (char*) "ufunc", object, dispatcher); } else { ufunc = PyDynUFunc_FromFuncAndData(0, 0, 0, 0, nin, nout, PyUFunc_None, "ufunc", (char*) "ufunc", object, dispatcher); PyUFunc_RegisterLoopForType((PyUFuncObject*)ufunc, custom_dtype, funcs[0], types, 0); PyArray_free(funcs); PyArray_free(types); PyArray_free(data); } return ufunc; }
int BL_ArmatureConstraint::py_attr_setattr(void *self_v, const struct KX_PYATTRIBUTE_DEF *attrdef, PyObject *value) { BL_ArmatureConstraint* self = static_cast<BL_ArmatureConstraint*>(self_v); bConstraint* constraint = self->m_constraint; bKinematicConstraint* ikconstraint = (constraint && constraint->type == CONSTRAINT_TYPE_KINEMATIC) ? (bKinematicConstraint*)constraint->data : NULL; int attr_order = attrdef-Attributes; int ival; double dval; // char* sval; SCA_LogicManager *logicmgr = KX_GetActiveScene()->GetLogicManager(); KX_GameObject *oval; if (!constraint) { PyErr_SetString(PyExc_AttributeError, "constraint is NULL"); return PY_SET_ATTR_FAIL; } switch (attr_order) { case BCA_ENFORCE: dval = PyFloat_AsDouble(value); if (dval < 0.0 || dval > 1.0) { /* also accounts for non float */ PyErr_SetString(PyExc_AttributeError, "constraint.enforce = float: BL_ArmatureConstraint, expected a float between 0 and 1"); return PY_SET_ATTR_FAIL; } constraint->enforce = dval; return PY_SET_ATTR_SUCCESS; case BCA_HEADTAIL: dval = PyFloat_AsDouble(value); if (dval < 0.0 || dval > 1.0) { /* also accounts for non float */ PyErr_SetString(PyExc_AttributeError, "constraint.headtail = float: BL_ArmatureConstraint, expected a float between 0 and 1"); return PY_SET_ATTR_FAIL; } constraint->headtail = dval; return PY_SET_ATTR_SUCCESS; case BCA_TARGET: if (!ConvertPythonToGameObject(logicmgr, value, &oval, true, "constraint.target = value: BL_ArmatureConstraint")) return PY_SET_ATTR_FAIL; // ConvertPythonToGameObject sets the error self->SetTarget(oval); return PY_SET_ATTR_SUCCESS; case BCA_SUBTARGET: if (!ConvertPythonToGameObject(logicmgr, value, &oval, true, "constraint.subtarget = value: BL_ArmatureConstraint")) return PY_SET_ATTR_FAIL; // ConvertPythonToGameObject sets the error self->SetSubtarget(oval); return PY_SET_ATTR_SUCCESS; case BCA_ACTIVE: ival = PyObject_IsTrue( value ); if (ival == -1) { PyErr_SetString(PyExc_AttributeError, "constraint.active = bool: BL_ArmatureConstraint, expected True or False"); return PY_SET_ATTR_FAIL; } self->m_constraint->flag = (self->m_constraint->flag & ~CONSTRAINT_OFF) | ((ival)?0:CONSTRAINT_OFF); return PY_SET_ATTR_SUCCESS; case BCA_IKWEIGHT: case BCA_IKDIST: case BCA_IKMODE: if (!ikconstraint) { PyErr_SetString(PyExc_AttributeError, "constraint is not of IK type"); return PY_SET_ATTR_FAIL; } switch (attr_order) { case BCA_IKWEIGHT: dval = PyFloat_AsDouble(value); if (dval < 0.0 || dval > 1.0) { /* also accounts for non float */ PyErr_SetString(PyExc_AttributeError, "constraint.weight = float: BL_ArmatureConstraint, expected a float between 0 and 1"); return PY_SET_ATTR_FAIL; } ikconstraint->weight = dval; return PY_SET_ATTR_SUCCESS; case BCA_IKDIST: dval = PyFloat_AsDouble(value); if (dval < 0.0) { /* also accounts for non float */ PyErr_SetString(PyExc_AttributeError, "constraint.ik_dist = float: BL_ArmatureConstraint, expected a positive float"); return PY_SET_ATTR_FAIL; } ikconstraint->dist = dval; return PY_SET_ATTR_SUCCESS; case BCA_IKMODE: ival = PyLong_AsLong(value); if (ival < 0) { PyErr_SetString(PyExc_AttributeError, "constraint.ik_mode = integer: BL_ArmatureConstraint, expected a positive integer"); return PY_SET_ATTR_FAIL; } ikconstraint->mode = ival; return PY_SET_ATTR_SUCCESS; } // should not come here break; } PyErr_SetString(PyExc_AttributeError, "constraint unknown attribute"); return PY_SET_ATTR_FAIL; }
/*static*/ PyObject * MultiCurveAttributes_SetChangedColors(PyObject *self, PyObject *args) { MultiCurveAttributesObject *obj = (MultiCurveAttributesObject *)self; unsignedCharVector &vec = obj->data->GetChangedColors(); PyObject *tuple; if(!PyArg_ParseTuple(args, "O", &tuple)) return NULL; if(PyTuple_Check(tuple)) { vec.resize(PyTuple_Size(tuple)); for(int i = 0; i < PyTuple_Size(tuple); ++i) { int c; PyObject *item = PyTuple_GET_ITEM(tuple, i); if(PyFloat_Check(item)) c = int(PyFloat_AS_DOUBLE(item)); else if(PyInt_Check(item)) c = int(PyInt_AS_LONG(item)); else if(PyLong_Check(item)) c = int(PyLong_AsDouble(item)); else c = 0; if(c < 0) c = 0; if(c > 255) c = 255; vec[i] = (unsigned char)(c); } } else if(PyFloat_Check(tuple)) { vec.resize(1); int c = int(PyFloat_AS_DOUBLE(tuple)); if(c < 0) c = 0; if(c > 255) c = 255; vec[0] = (unsigned char)(c); } else if(PyInt_Check(tuple)) { vec.resize(1); int c = int(PyInt_AS_LONG(tuple)); if(c < 0) c = 0; if(c > 255) c = 255; vec[0] = (unsigned char)(c); } else if(PyLong_Check(tuple)) { vec.resize(1); int c = PyLong_AsLong(tuple); if(c < 0) c = 0; if(c > 255) c = 255; vec[0] = (unsigned char)(c); } else return NULL; // Mark the changedColors in the object as modified. obj->data->SelectChangedColors(); Py_INCREF(Py_None); return Py_None; }
PyObject* scribus_setproperty(PyObject* /*self*/, PyObject* args, PyObject* kw) { PyObject* objArg = NULL; char* propertyName = NULL; PyObject* objValue = NULL; char* kwargs[] = {const_cast<char*>("object"), const_cast<char*>("property"), const_cast<char*>("value"), NULL}; if (!PyArg_ParseTupleAndKeywords(args, kw, "OesO", kwargs, &objArg, "ascii", &propertyName, &objValue)) return NULL; // We're going to hang on to the value object for a while, so // claim a reference to it. Py_INCREF(objValue); // Get the QObject* the object argument refers to QObject* obj = getQObjectFromPyArg(objArg); if (!obj) return NULL; objArg = NULL; // no need to decref, it's borrowed const char* propertyTypeName = getpropertytype(obj, propertyName, true); if (propertyTypeName == NULL) return NULL; QString propertyType = QString::fromLatin1(propertyTypeName); // Did we know how to convert the value argument to the right type? bool matched = false; // Did the set call succceed? bool success = false; // Check the C++ type of the property, and try to convert the passed // PyObject to something sensible looking for it. // FIXME: handle enums/sets // NUMERIC TYPES // These are unfortuately a TOTAL PITA because of the multitude of // C and Python numeric types. TODO This needs to be broken out into a subroutine. if (propertyType == "bool") { matched = true; if (PyObject_IsTrue(objValue) == 0) success = obj->setProperty(propertyName, 0); else if (PyObject_IsTrue(objValue) == 1) success = obj->setProperty(propertyName, 1); else if (PyInt_Check(objValue)) success = obj->setProperty(propertyName, PyInt_AsLong(objValue) == 0); else if (PyLong_Check(objValue)) success = obj->setProperty(propertyName, PyLong_AsLong(objValue) == 0); else matched = false; } else if (propertyType == "int") { matched = true; if (PyObject_IsTrue(objValue) == 0) success = obj->setProperty(propertyName, 0); else if (PyObject_IsTrue(objValue) == 1) success = obj->setProperty(propertyName, 1); else if (PyInt_Check(objValue)) success = obj->setProperty(propertyName, (int)PyInt_AsLong(objValue)); else if (PyLong_Check(objValue)) success = obj->setProperty(propertyName, (int)PyLong_AsLong(objValue)); else matched = false; } else if (propertyType == "double") { matched = true; // FIXME: handle int, long and bool too if (PyFloat_Check(objValue)) success = obj->setProperty(propertyName, PyFloat_AsDouble(objValue)); else matched = false; } // STRING TYPES else if (propertyType == "QString") { matched = true; if (PyString_Check(objValue)) success = obj->setProperty(propertyName, QString::fromUtf8(PyString_AsString(objValue))); else if (PyUnicode_Check(objValue)) { // Get a pointer to the internal buffer of the Py_Unicode object, which is UCS2 formatted const unsigned short * ucs2Data = (const unsigned short *)PyUnicode_AS_UNICODE(objValue); // and make a new QString from it (the string is copied) success = obj->setProperty(propertyName, QString::fromUtf16(ucs2Data)); } else matched = false; } else if (propertyType == "QCString") { matched = true; if (PyString_Check(objValue)) { // FIXME: should raise an exception instead of mangling the string when // out of charset chars present. QString utfString = QString::fromUtf8(PyString_AsString(objValue)); success = obj->setProperty(propertyName, utfString.toAscii()); } else if (PyUnicode_Check(objValue)) { // Get a pointer to the internal buffer of the Py_Unicode object, which is UCS2 formatted const unsigned short * utf16Data = (const unsigned short *)PyUnicode_AS_UNICODE(objValue); // and make a new QString from it (the string is copied) success = obj->setProperty(propertyName, QString::fromUtf16(utf16Data).toAscii()); } else matched = false; } // HIGHER ORDER TYPES // ... which I can't be stuffed supporting yet. FIXME. else { Py_DECREF(objValue); PyErr_SetString(PyExc_TypeError, QObject::tr("Property type '%1' not supported").arg(propertyType).toLocal8Bit().constData()); return NULL; } // If `matched' is false, we recognised the C type but weren't able to // convert the passed Python value to anything suitable. if (!matched) { // Get a string representation of the object PyObject* objRepr = PyObject_Repr(objValue); Py_DECREF(objValue); // We're done with it now if (!objRepr) return NULL; // Extract the repr() string QString reprString = QString::fromUtf8(PyString_AsString(objRepr)); Py_DECREF(objRepr); // And return an error PyErr_SetString(PyExc_TypeError, QObject::tr("Couldn't convert '%1' to property type '%2'").arg(reprString).arg(propertyType).toLocal8Bit().constData()); return NULL; } // `success' is the return value of the setProperty() call if (!success) { Py_DECREF(objValue); PyErr_SetString(PyExc_ValueError, QObject::tr("Types matched, but setting property failed.").toLocal8Bit().constData()); return NULL; } Py_DECREF(objValue); // Py_INCREF(Py_None); // return Py_None; Py_RETURN_NONE; }
static int convert_annotation(struct srd_decoder_inst *di, PyObject *obj, struct srd_proto_data *pdata) { PyObject *py_tmp; struct srd_pd_output *pdo; struct srd_proto_data_annotation *pda; int ann_format; char **ann_text; /* Should be a list of [annotation format, [string, ...]]. */ if (!PyList_Check(obj) && !PyTuple_Check(obj)) { srd_err("Protocol decoder %s submitted %s instead of list.", di->decoder->name, obj->ob_type->tp_name); return SRD_ERR_PYTHON; } /* Should have 2 elements. */ if (PyList_Size(obj) != 2) { srd_err("Protocol decoder %s submitted annotation list with " "%d elements instead of 2", di->decoder->name, PyList_Size(obj)); return SRD_ERR_PYTHON; } /* * The first element should be an integer matching a previously * registered annotation format. */ py_tmp = PyList_GetItem(obj, 0); if (!PyLong_Check(py_tmp)) { srd_err("Protocol decoder %s submitted annotation list, but " "first element was not an integer.", di->decoder->name); return SRD_ERR_PYTHON; } ann_format = PyLong_AsLong(py_tmp); if (!(pdo = g_slist_nth_data(di->decoder->annotations, ann_format))) { srd_err("Protocol decoder %s submitted data to unregistered " "annotation format %d.", di->decoder->name, ann_format); return SRD_ERR_PYTHON; } /* Second element must be a list. */ py_tmp = PyList_GetItem(obj, 1); if (!PyList_Check(py_tmp)) { srd_err("Protocol decoder %s submitted annotation list, but " "second element was not a list.", di->decoder->name); return SRD_ERR_PYTHON; } if (py_strseq_to_char(py_tmp, &ann_text) != SRD_OK) { srd_err("Protocol decoder %s submitted annotation list, but " "second element was malformed.", di->decoder->name); return SRD_ERR_PYTHON; } if (!(pda = g_try_malloc(sizeof(struct srd_proto_data_annotation)))) return SRD_ERR_MALLOC; pda->ann_format = ann_format; pda->ann_text = ann_text; pdata->data = pda; return SRD_OK; }
static PyObject * range_reverse(PyObject *seq) { rangeobject *range = (rangeobject*) seq; longrangeiterobject *it; PyObject *one, *sum, *diff, *len = NULL, *product; long lstart, lstop, lstep; /* XXX(nnorwitz): do the calc for the new start/stop first, then if they fit, call the proper iter()? */ assert(PyRange_Check(seq)); /* If all three fields convert to long, use the int version */ lstart = PyLong_AsLong(range->start); if (lstart != -1 || !PyErr_Occurred()) { lstop = PyLong_AsLong(range->stop); if (lstop != -1 || !PyErr_Occurred()) { lstep = PyLong_AsLong(range->step); if (lstep != -1 || !PyErr_Occurred()) { /* XXX(nnorwitz): need to check for overflow and simplify. */ long len = get_len_of_range(lstart, lstop, lstep); long new_start = lstart + (len - 1) * lstep; long new_stop = lstart; if (lstep > 0) new_stop -= 1; else new_stop += 1; return int_range_iter(new_start, new_stop, -lstep); } } } PyErr_Clear(); it = PyObject_New(longrangeiterobject, &PyLongRangeIter_Type); if (it == NULL) return NULL; /* start + (len - 1) * step */ len = range_length_obj(range); if (!len) goto create_failure; one = PyLong_FromLong(1); if (!one) goto create_failure; diff = PyNumber_Subtract(len, one); Py_DECREF(one); if (!diff) goto create_failure; product = PyNumber_Multiply(len, range->step); if (!product) goto create_failure; sum = PyNumber_Add(range->start, product); Py_DECREF(product); it->start = sum; if (!it->start) goto create_failure; it->step = PyNumber_Negative(range->step); if (!it->step) { Py_DECREF(it->start); PyObject_Del(it); return NULL; } /* Steal reference to len. */ it->len = len; it->index = PyLong_FromLong(0); if (!it->index) { Py_DECREF(it); return NULL; } return (PyObject *)it; create_failure: Py_XDECREF(len); PyObject_Del(it); return NULL; }
static PyObject* cstuff_find_low_density_blobs(PyObject *self, PyObject *args) { PyObject *obj, *list1, *list2; int row, col; int stride; double vmax, vmin, vtmp, vavg; double vcount; doublemap *density_map; if (!PyArg_ParseTuple(args, "OO", &obj, &list1)) { return NULL; } if (!(density_map = create_doublemap(g_rows, g_cols))) { RAISE("Can't malloc for density map!"); return NULL; } set_doublemap(density_map, 0.0); if (paint_radials_around_ants(density_map, g_dmap_density, obj)) { RAISE("'Painting' density failed!"); free_doublemap(density_map); return NULL; } if (g_avg_density_map == NULL) { g_avg_density_map = density_map; } else { fade_maps(g_avg_density_map, density_map, 0.6); free_doublemap(density_map); } vmin = vmax = g_avg_density_map->values[0]; for (row=0; row<g_rows; row++) { stride = row * g_cols; for (col=0; col<g_cols; col++) { vtmp = g_avg_density_map->values[stride+col]; if (vtmp > vmax) vmax = vtmp; } } vcount = 0; vavg = 0; for (row=0; row<g_rows; row++) { list2 = PyList_GetItem(list1, row); stride = row * g_cols; for (col=0; col<g_cols; col++) { if (PyLong_AsLong(PyList_GetItem(list2, col)) == -2) { g_avg_density_map->values[stride+col] = vmax; } else { vavg += g_avg_density_map->values[stride+col]; vcount += 1; } } } vavg /= vcount; if (g_avg_density_avg < 0) { g_avg_density_avg = vavg; } else { g_avg_density_avg = 0.9*g_avg_density_avg + 0.1*vavg; } for (row=0; row<g_rows; row++) { stride = row * g_cols; for (col=0; col<g_cols; col++) { vtmp = g_avg_density_map->values[stride+col]; if (vtmp < vmin) vmin = vtmp; } } if (g_avg_density_min < 0) { g_avg_density_min = vmin; } else { g_avg_density_min = 0.9*g_avg_density_min + 0.1*vmin; } vtmp = g_avg_density_min + 0.1*(g_avg_density_avg-g_avg_density_min); list1 = PyList_New(g_rows); for (row=0; row<g_rows; row++) { stride = row * g_cols; list2 = PyList_New(g_cols); for (col=0; col<g_cols; col++) { PyList_SetItem(list2, col, PyLong_FromLong((g_avg_density_map->values[stride+col] <= vtmp)?-1:-2)); } PyList_SetItem(list1, row, list2); } return list1; }
PyObject * ot_pvw_receive(PyObject *self, PyObject *args) { PyObject *py_state, *py_choices, *py_return = NULL; struct dm_ddh_crs crs; struct dm_ddh_pk pk; struct ddh_sk sk; struct ddh_ctxt ctxt; struct state *st; int num_ots; unsigned int N, msglength, err = 0; double start, end; if (!PyArg_ParseTuple(args, "OOII", &py_state, &py_choices, &N, &msglength)) return NULL; st = (struct state *) PyCapsule_GetPointer(py_state, NULL); if (st == NULL) return NULL; if (N != 2) { PyErr_SetString(PyExc_RuntimeError, "N must be 2"); return NULL; } if ((num_ots = PySequence_Length(py_choices)) == -1) return NULL; start = current_time(); // FIXME: choice of mode should not be hardcoded dm_ddh_crs_setup(&crs, EXT, &st->p); end = current_time(); fprintf(stderr, "CRS setup: %f\n", end - start); dm_ddh_pk_setup(&pk); ddh_sk_setup(&sk); ddh_ctxt_setup(&ctxt); py_return = PyTuple_New(num_ots); start = current_time(); for (int j = 0; j < num_ots; ++j) { unsigned int choice; // double start, end; choice = PyLong_AsLong(PySequence_GetItem(py_choices, j)); // start = current_time(); dm_ddh_keygen(&pk, &sk, choice, &crs, &st->p); // end = current_time(); // fprintf(stderr, "ddh keygen: %f\n", end - start); // start = current_time(); send_dm_ddh_pk(&pk, st); // end = current_time(); // fprintf(stderr, "send dm ddh pk: %f\n", end - start); for (unsigned int b = 0; b <= 1; ++b) { char *msg; PyObject *str; // start = current_time(); receive_ddh_ctxt(&ctxt, st); // end = current_time(); // fprintf(stderr, "receive dm ddh ctxt: %f\n", end - start); // start = current_time(); msg = dm_ddh_dec(&sk, &ctxt, &st->p); // end = current_time(); // fprintf(stderr, "decrypt ddh ctxt: %f\n", end - start); str = PyString_FromStringAndSize(msg, msglength); free(msg); if (str == NULL) { err = 1; goto cleanup; } if (choice == b) { PyTuple_SetItem(py_return, j, str); } } } end = current_time(); fprintf(stderr, "OT: %f\n", end - start); cleanup: ddh_ctxt_cleanup(&ctxt); ddh_sk_cleanup(&sk); dm_ddh_pk_cleanup(&pk); dm_ddh_crs_cleanup(&crs); if (err) return NULL; else return py_return; }
static PyObject * Byte_new(PyTypeObject *cls, PyObject *args, PyObject *kwargs) { PyObject *obj; PyObject *tuple; long variantness = 0; static char *argnames[] = {"variant_level", NULL}; if (PyTuple_Size(args) > 1) { PyErr_SetString(PyExc_TypeError, "Byte constructor takes no more " "than one positional argument"); return NULL; } if (!PyArg_ParseTupleAndKeywords(dbus_py_empty_tuple, kwargs, "|l:__new__", argnames, &variantness)) return NULL; if (variantness < 0) { PyErr_SetString(PyExc_ValueError, "variant_level must be non-negative"); return NULL; } /* obj is a borrowed reference. It gets turned into an owned reference on * the good-path of the if-statements below. */ obj = PyTuple_GetItem(args, 0); if (PyBytes_Check(obj)) { /* string of length 1, we hope */ if (PyBytes_GET_SIZE(obj) != 1) { goto bad_arg; } obj = NATIVEINT_FROMLONG((unsigned char)(PyBytes_AS_STRING(obj)[0])); if (!obj) goto bad_arg; } else if (INTORLONG_CHECK(obj)) { /* on Python 2 this accepts either int or long */ long i = PyLong_AsLong(obj); long my_variant_level; if (i == -1 && PyErr_Occurred()) goto bad_arg; #ifdef PY3 my_variant_level = dbus_py_variant_level_get(obj); if (my_variant_level < 0) return NULL; #else my_variant_level = ((DBusPyIntBase *)obj)->variant_level; #endif if (Py_TYPE(obj) == cls && my_variant_level == variantness) { Py_INCREF(obj); return obj; } if (i < 0 || i > 255) goto bad_range; /* else make it a new reference */ Py_INCREF(obj); } else { goto bad_arg; } /* The tuple steals the reference to obj. */ tuple = Py_BuildValue("(N)", obj); if (!tuple) return NULL; obj = DBUS_PY_BYTE_BASE.tp_new(cls, tuple, kwargs); Py_CLEAR(tuple); return obj; bad_arg: PyErr_SetString(PyExc_TypeError, "Expected a bytes or str of length 1, " "or an int in the range 0-255"); return NULL; bad_range: PyErr_SetString(PyExc_ValueError, "Integer outside range 0-255"); return NULL; }
static PyObject * range_reverse(PyObject *seq) { rangeobject *range = (rangeobject*) seq; longrangeiterobject *it; PyObject *sum, *diff, *product; long lstart, lstop, lstep, new_start, new_stop; unsigned long ulen; assert(PyRange_Check(seq)); /* reversed(range(start, stop, step)) can be expressed as range(start+(n-1)*step, start-step, -step), where n is the number of integers in the range. If each of start, stop, step, -step, start-step, and the length of the iterator is representable as a C long, use the int version. This excludes some cases where the reversed range is representable as a range_iterator, but it's good enough for common cases and it makes the checks simple. */ lstart = PyLong_AsLong(range->start); if (lstart == -1 && PyErr_Occurred()) { PyErr_Clear(); goto long_range; } lstop = PyLong_AsLong(range->stop); if (lstop == -1 && PyErr_Occurred()) { PyErr_Clear(); goto long_range; } lstep = PyLong_AsLong(range->step); if (lstep == -1 && PyErr_Occurred()) { PyErr_Clear(); goto long_range; } /* check for possible overflow of -lstep */ if (lstep == LONG_MIN) goto long_range; /* check for overflow of lstart - lstep: for lstep > 0, need only check whether lstart - lstep < LONG_MIN. for lstep < 0, need only check whether lstart - lstep > LONG_MAX Rearrange these inequalities as: lstart - LONG_MIN < lstep (lstep > 0) LONG_MAX - lstart < -lstep (lstep < 0) and compute both sides as unsigned longs, to avoid the possibility of undefined behaviour due to signed overflow. */ if (lstep > 0) { if ((unsigned long)lstart - LONG_MIN < (unsigned long)lstep) goto long_range; } else { if (LONG_MAX - (unsigned long)lstart < 0UL - lstep) goto long_range; } ulen = get_len_of_range(lstart, lstop, lstep); if (ulen > (unsigned long)LONG_MAX) goto long_range; new_stop = lstart - lstep; new_start = (long)(new_stop + ulen * lstep); return fast_range_iter(new_start, new_stop, -lstep); long_range: it = PyObject_New(longrangeiterobject, &PyLongRangeIter_Type); if (it == NULL) return NULL; it->index = it->start = it->step = NULL; /* start + (len - 1) * step */ it->len = range->length; Py_INCREF(it->len); diff = PyNumber_Subtract(it->len, _PyLong_One); if (!diff) goto create_failure; product = PyNumber_Multiply(diff, range->step); Py_DECREF(diff); if (!product) goto create_failure; sum = PyNumber_Add(range->start, product); Py_DECREF(product); it->start = sum; if (!it->start) goto create_failure; it->step = PyNumber_Negative(range->step); if (!it->step) goto create_failure; it->index = _PyLong_Zero; Py_INCREF(it->index); return (PyObject *)it; create_failure: Py_DECREF(it); return NULL; }
// @pymethod int|PyITypeInfo|GetIDsOfNames|Maps between member names and member IDs, and parameter names and parameter IDs. static PyObject *typeinfo_getidsofnames(PyObject *self, PyObject *args) { // XXX - todo - merge this code with PyIDispatch::GetIDsOfNames ITypeInfo *pti = PyITypeInfo::GetI(self); if (pti==NULL) return NULL; UINT i; int argc = PyTuple_GET_SIZE(args); if ( argc < 1 ) { PyErr_SetString(PyExc_TypeError, "At least one argument must be supplied"); return NULL; } LCID lcid = LOCALE_SYSTEM_DEFAULT; UINT offset = 0; if ( argc > 1 ) { PyObject *ob = PyTuple_GET_ITEM(args, 0); lcid=PyLong_AsLong(ob); if (lcid==-1 && PyErr_Occurred()){ PyErr_Clear(); lcid=LOCALE_SYSTEM_DEFAULT; } else offset = 1; } UINT cNames = argc - offset; OLECHAR FAR* FAR* rgszNames = new LPOLESTR[cNames]; for ( i = 0 ; i < cNames; ++i ) { PyObject *ob = PyTuple_GET_ITEM(args, i + offset); if (!PyWinObject_AsBstr(ob, rgszNames+i)) { for (;i>0;i--) PyWinObject_FreeBstr(rgszNames[i-1]); delete [] rgszNames; return NULL; } } DISPID FAR* rgdispid = new DISPID[cNames]; PY_INTERFACE_PRECALL; HRESULT hr = pti->GetIDsOfNames(rgszNames, cNames, rgdispid); PY_INTERFACE_POSTCALL; for (i=0;i<cNames;i++) PyWinObject_FreeBstr(rgszNames[i]); delete [] rgszNames; if ( FAILED(hr) ){ delete [] rgdispid; return PyCom_BuildPyException(hr, pti, IID_ITypeInfo); } PyObject *result; /* if we have just one name, then return a single DISPID (int) */ if ( cNames == 1 ) { result = PyInt_FromLong(rgdispid[0]); } else { result = PyTuple_New(cNames); if ( result ) { for ( i = 0; i < cNames; ++i ) { PyObject *ob = PyInt_FromLong(rgdispid[i]); if ( !ob ) { delete [] rgdispid; return NULL; } PyTuple_SET_ITEM(result, i, ob); } } } delete [] rgdispid; return result; }
TCAX_Py_Error_Code tcaxlib_tcas_list_append_pix(PyObject *self, PyObject *args) { PyObject *pyArg1, *pyArg2, *pyArg3, *pyArg4, *pyArg5, *pyArg6, *pyArg7; int start, end; double diffX, diffY; unsigned long layer_type_pair; PyObject *tcasList; TCAX_Pix pix; int w, h, index; unsigned long color; int alpha; int posX, posY, initPosX, initPosY; PyObject *pixDip; /* store a dynamic isolated pixel of PIX temporary */ if (PyTuple_GET_SIZE(args) < 7) { PyErr_SetString(PyExc_RuntimeError, "tcas_main error, too less parameters - `(TCAS_BUF, PIX, Start, End, DiffX, DiffY, Layer)'\n"); return NULL; } pyArg1 = PyTuple_GET_ITEM(args, 0); if (!PyList_Check(pyArg1)) { PyErr_SetString(PyExc_RuntimeError, "tcas_main error, the 1st param should be a list - `TCAS_BUF'\n"); return NULL; } pyArg2 = PyTuple_GET_ITEM(args, 1); if (!PyTuple_Check(pyArg2)) { PyErr_SetString(PyExc_RuntimeError, "tcas_main error, the 2nd param should be a tuple - `PIX'\n"); return NULL; } pyArg3 = PyTuple_GET_ITEM(args, 2); if (!PyLong_Check(pyArg3) && !PyFloat_Check(pyArg3)) { PyErr_SetString(PyExc_RuntimeError, "tcas_main error, the 3rd param should be an integer - `start'\n"); return NULL; } pyArg4 = PyTuple_GET_ITEM(args, 3); if (!PyLong_Check(pyArg4) && !PyFloat_Check(pyArg4)) { PyErr_SetString(PyExc_RuntimeError, "tcas_main error, the 4th param should be an integer - `end'\n"); return NULL; } pyArg5 = PyTuple_GET_ITEM(args, 4); if (!PyLong_Check(pyArg5) && !PyFloat_Check(pyArg5)) { PyErr_SetString(PyExc_RuntimeError, "tcas_main error, the 5th param should be a float - `initX'\n"); return NULL; } pyArg6 = PyTuple_GET_ITEM(args, 5); if (!PyLong_Check(pyArg6) && !PyFloat_Check(pyArg6)) { PyErr_SetString(PyExc_RuntimeError, "tcas_main error, the 6th param should be a float - `initY'\n"); return NULL; } pyArg7 = PyTuple_GET_ITEM(args, 6); if (!PyLong_Check(pyArg7) && !PyFloat_Check(pyArg7)) { PyErr_SetString(PyExc_RuntimeError, "tcas_main error, the 7th param should be an integer - `layer'\n"); return NULL; } start = (int)PyLong_AsLong(pyArg3); end = (int)PyLong_AsLong(pyArg4); if (start > end) return Py_BuildValue("i", -1); tcasList = pyArg1; /* note: we needn't use Py_CLEAR(tcasList) or Py_INCREF(tcasList) */ tcaxlib_convert_py_pix((const TCAX_PyPix)pyArg2, &pix); diffX = PyFloat_AsDouble(pyArg5); diffY = PyFloat_AsDouble(pyArg6); //layer = (0x0000000F && (unsigned long)PyLong_AsLong(pyArg7)); layer_type_pair = (unsigned long)PyLong_AsUnsignedLong(pyArg7); initPosX = (int)floor(diffX + pix.initX); /* Note: no we don't use (int)(fDiffX + fInitX + 0.5) */ initPosY = (int)floor(diffY + pix.initY); for (h = 0; h < pix.height; h++) { posY = initPosY + h; for (w = 0; w < pix.width; w++) { posX = initPosX + w; index = (h * pix.width + w) << 2; color = MAKERGB(pix.buf[index], pix.buf[index + 1], pix.buf[index + 2]); alpha = pix.buf[index + 3]; if (0 != alpha) { pixDip = PyTuple_New(7); PyTuple_SET_ITEM(pixDip, 0, PyLong_FromLong(start)); PyTuple_SET_ITEM(pixDip, 1, PyLong_FromLong(end)); PyTuple_SET_ITEM(pixDip, 2, PyLong_FromUnsignedLong(layer_type_pair)); PyTuple_SET_ITEM(pixDip, 3, PyLong_FromLong(posX)); PyTuple_SET_ITEM(pixDip, 4, PyLong_FromLong(posY)); PyTuple_SET_ITEM(pixDip, 5, PyLong_FromLong(color)); PyTuple_SET_ITEM(pixDip, 6, PyLong_FromLong(alpha)); PyList_Append(tcasList, pixDip); Py_CLEAR(pixDip); } } } free(pix.buf); return PyLong_FromLong(0); }
static PyObject * io_open(PyObject *self, PyObject *args, PyObject *kwds) { char *kwlist[] = {"file", "mode", "buffering", "encoding", "errors", "newline", "closefd", NULL}; PyObject *file; char *mode = "r"; int buffering = -1, closefd = 1; char *encoding = NULL, *errors = NULL, *newline = NULL; unsigned i; int reading = 0, writing = 0, appending = 0, updating = 0; int text = 0, binary = 0, universal = 0; char rawmode[5], *m; int line_buffering, isatty; PyObject *raw, *modeobj = NULL, *buffer = NULL, *wrapper = NULL; if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|sizzzi:open", kwlist, &file, &mode, &buffering, &encoding, &errors, &newline, &closefd)) { return NULL; } if (!PyUnicode_Check(file) && !PyBytes_Check(file) && !PyNumber_Check(file)) { PyObject *repr = PyObject_Repr(file); if (repr != NULL) { PyErr_Format(PyExc_TypeError, "invalid file: %s", PyString_AS_STRING(repr)); Py_DECREF(repr); } return NULL; } /* Decode mode */ for (i = 0; i < strlen(mode); i++) { char c = mode[i]; switch (c) { case 'r': reading = 1; break; case 'w': writing = 1; break; case 'a': appending = 1; break; case '+': updating = 1; break; case 't': text = 1; break; case 'b': binary = 1; break; case 'U': universal = 1; reading = 1; break; default: goto invalid_mode; } /* c must not be duplicated */ if (strchr(mode+i+1, c)) { invalid_mode: PyErr_Format(PyExc_ValueError, "invalid mode: '%s'", mode); return NULL; } } m = rawmode; if (reading) *(m++) = 'r'; if (writing) *(m++) = 'w'; if (appending) *(m++) = 'a'; if (updating) *(m++) = '+'; *m = '\0'; /* Parameters validation */ if (universal) { if (writing || appending) { PyErr_SetString(PyExc_ValueError, "can't use U and writing mode at once"); return NULL; } reading = 1; } if (text && binary) { PyErr_SetString(PyExc_ValueError, "can't have text and binary mode at once"); return NULL; } if (reading + writing + appending > 1) { PyErr_SetString(PyExc_ValueError, "must have exactly one of read/write/append mode"); return NULL; } if (binary && encoding != NULL) { PyErr_SetString(PyExc_ValueError, "binary mode doesn't take an encoding argument"); return NULL; } if (binary && errors != NULL) { PyErr_SetString(PyExc_ValueError, "binary mode doesn't take an errors argument"); return NULL; } if (binary && newline != NULL) { PyErr_SetString(PyExc_ValueError, "binary mode doesn't take a newline argument"); return NULL; } /* Create the Raw file stream */ raw = PyObject_CallFunction((PyObject *)&PyFileIO_Type, "Osi", file, rawmode, closefd); if (raw == NULL) return NULL; modeobj = PyUnicode_FromString(mode); if (modeobj == NULL) goto error; /* buffering */ { PyObject *res = PyObject_CallMethod(raw, "isatty", NULL); if (res == NULL) goto error; isatty = PyLong_AsLong(res); Py_DECREF(res); if (isatty == -1 && PyErr_Occurred()) goto error; } if (buffering == 1 || (buffering < 0 && isatty)) { buffering = -1; line_buffering = 1; } else line_buffering = 0; if (buffering < 0) { buffering = DEFAULT_BUFFER_SIZE; #ifdef HAVE_STRUCT_STAT_ST_BLKSIZE { struct stat st; long fileno; PyObject *res = PyObject_CallMethod(raw, "fileno", NULL); if (res == NULL) goto error; fileno = PyInt_AsLong(res); Py_DECREF(res); if (fileno == -1 && PyErr_Occurred()) goto error; if (fstat(fileno, &st) >= 0 && st.st_blksize > 1) buffering = st.st_blksize; } #endif } if (buffering < 0) { PyErr_SetString(PyExc_ValueError, "invalid buffering size"); goto error; } /* if not buffering, returns the raw file object */ if (buffering == 0) { if (!binary) { PyErr_SetString(PyExc_ValueError, "can't have unbuffered text I/O"); goto error; } Py_DECREF(modeobj); return raw; } /* wraps into a buffered file */ { PyObject *Buffered_class; if (updating) Buffered_class = (PyObject *)&PyBufferedRandom_Type; else if (writing || appending) Buffered_class = (PyObject *)&PyBufferedWriter_Type; else if (reading) Buffered_class = (PyObject *)&PyBufferedReader_Type; else { PyErr_Format(PyExc_ValueError, "unknown mode: '%s'", mode); goto error; } buffer = PyObject_CallFunction(Buffered_class, "Oi", raw, buffering); } Py_CLEAR(raw); if (buffer == NULL) goto error; /* if binary, returns the buffered file */ if (binary) { Py_DECREF(modeobj); return buffer; } /* wraps into a TextIOWrapper */ wrapper = PyObject_CallFunction((PyObject *)&PyTextIOWrapper_Type, "Osssi", buffer, encoding, errors, newline, line_buffering); Py_CLEAR(buffer); if (wrapper == NULL) goto error; if (PyObject_SetAttrString(wrapper, "mode", modeobj) < 0) goto error; Py_DECREF(modeobj); return wrapper; error: Py_XDECREF(raw); Py_XDECREF(modeobj); Py_XDECREF(buffer); Py_XDECREF(wrapper); return NULL; }
PyObject *tcaxlib_tcas_list_parse(PyObject *self, PyObject *args) { PyObject *pyArg1, *pyArg2, *pyArg3, *pyArg4, *pyArg5; tcas_u16 width, height; double fps; int layer; tcas_u32 fpsNumerator, fpsDenominator; tcas_unit *tcasBuf; tcas_unit *compTcasBuf; tcas_u32 count, chunks, units; TCAS_StreamParser parser; VectorPtr chunksVector; PyObject *retTcasBuf; if (PyTuple_GET_SIZE(args) < 5) { PyErr_SetString(PyExc_RuntimeError, "tcas_parse error, too less parameters - `(TCAS_BUF, width, height, fps, layer)'\n"); return NULL; } pyArg1 = PyTuple_GET_ITEM(args, 0); if (!PyList_Check(pyArg1)) { PyErr_SetString(PyExc_RuntimeError, "tcas_parse error, the 1st param should be a list - `TCAS_BUF'\n"); return NULL; } if (PyList_GET_SIZE(pyArg1) == 0) { PyErr_SetString(PyExc_RuntimeWarning, "tcas_parse warning, empty list `TCAS_BUF'\n"); return PyLong_FromLong(-1); } pyArg2 = PyTuple_GET_ITEM(args, 1); if (!PyLong_Check(pyArg2) && !PyFloat_Check(pyArg2)) { PyErr_SetString(PyExc_RuntimeError, "tcas_parse error, the 2nd param should be an integer - `width'\n"); return NULL; } pyArg3 = PyTuple_GET_ITEM(args, 2); if (!PyLong_Check(pyArg3) && !PyFloat_Check(pyArg3)) { PyErr_SetString(PyExc_RuntimeError, "tcas_parse error, the 3rd param should be an integer - `height'\n"); return NULL; } pyArg4 = PyTuple_GET_ITEM(args, 3); if (!PyLong_Check(pyArg4) && !PyFloat_Check(pyArg4)) { PyErr_SetString(PyExc_RuntimeError, "tcas_parse error, the 4th param should be a float - `fps'\n"); return NULL; } pyArg5 = PyTuple_GET_ITEM(args, 4); if (!PyLong_Check(pyArg5) && !PyFloat_Check(pyArg5)) { PyErr_SetString(PyExc_RuntimeError, "tcas_parse error, the 5th param should be an integer - `layer'\n"); return NULL; } tcaxlib_convert_tcas_list_to_buf(pyArg1, &tcasBuf, &count); libtcas_compress_raw_chunks((const TCAS_pRawChunk)tcasBuf, count, TCAS_FALSE, &compTcasBuf, &chunks, &units); free(tcasBuf); width = (tcas_u16)PyLong_AsLong(pyArg2); height = (tcas_u16)PyLong_AsLong(pyArg3); fps = PyFloat_AsDouble(pyArg4); layer = (int)PyLong_AsLong(pyArg5); _tcaxlib_get_fps_n_d(fps, &fpsNumerator, &fpsDenominator); vector_create(&chunksVector, sizeof(TCAS_Chunk), 0, NULL, NULL); libtcas_stream_parser_init(compTcasBuf, chunks, fpsNumerator, fpsDenominator, width, height, &parser); libtcas_stream_parser_parse(&parser, chunksVector); libtcas_stream_parser_fin(&parser); free(compTcasBuf); retTcasBuf = _tcaxlib_convert_chunks_vector_to_tcas_list(chunksVector, layer); vector_destroy(chunksVector); return retTcasBuf; }
/* Copies a Python int or long object to a signed 64-bit value * Returns 1 if successful or -1 on error */ int pysmraw_integer_signed_copy_to_64bit( PyObject *integer_object, int64_t *value_64bit, libcerror_error_t **error ) { static char *function = "pysmraw_integer_signed_copy_to_64bit"; int result = 0; #if defined( HAVE_LONG_LONG ) PY_LONG_LONG long_value = 0; #else long long_value = 0; #endif if( integer_object == NULL ) { libcerror_error_set( error, LIBCERROR_ERROR_DOMAIN_ARGUMENTS, LIBCERROR_ARGUMENT_ERROR_INVALID_VALUE, "%s: invalid integer object.", function ); return( -1 ); } PyErr_Clear(); result = PyObject_IsInstance( integer_object, (PyObject *) &PyLong_Type ); if( result == -1 ) { pysmraw_error_fetch( error, LIBCERROR_ERROR_DOMAIN_RUNTIME, LIBCERROR_RUNTIME_ERROR_GET_FAILED, "%s: unable to determine if integer object is of type long.", function ); return( -1 ); } else if( result != 0 ) { PyErr_Clear(); #if defined( HAVE_LONG_LONG ) long_value = PyLong_AsLongLong( integer_object ); #else long_value = PyLong_AsLong( integer_object ); #endif } #if PY_MAJOR_VERSION < 3 if( result == 0 ) { PyErr_Clear(); result = PyObject_IsInstance( integer_object, (PyObject *) &PyInt_Type ); if( result == -1 ) { pysmraw_error_fetch( error, LIBCERROR_ERROR_DOMAIN_RUNTIME, LIBCERROR_RUNTIME_ERROR_GET_FAILED, "%s: unable to determine if integer object is of type int.", function ); return( -1 ); } else if( result != 0 ) { PyErr_Clear(); long_value = PyInt_AsLong( integer_object ); } } #endif /* PY_MAJOR_VERSION < 3 */ if( result == 0 ) { libcerror_error_set( error, LIBCERROR_ERROR_DOMAIN_RUNTIME, LIBCERROR_RUNTIME_ERROR_GET_FAILED, "%s: unsupported integer object type.", function ); return( -1 ); } if( PyErr_Occurred() ) { pysmraw_error_fetch( error, LIBCERROR_ERROR_DOMAIN_RUNTIME, LIBCERROR_RUNTIME_ERROR_GET_FAILED, "%s: unable to convert integer object to long.", function ); return( -1 ); } #if defined( HAVE_LONG_LONG ) && ( SIZEOF_LONG_LONG > 8 ) if( ( long_value < (PY_LONG_LONG) INT64_MIN ) || ( long_value > (PY_LONG_LONG) INT64_MAX ) ) { libcerror_error_set( error, LIBCERROR_ERROR_DOMAIN_RUNTIME, LIBCERROR_RUNTIME_ERROR_VALUE_OUT_OF_BOUNDS, "%s: invalid long value out of bounds.", function ); return( -1 ); } #elif ( SIZEOF_LONG > 8 ) if( ( long_value > (long) INT64_MIN ) || ( long_value > (long) INT64_MAX ) ) { libcerror_error_set( error, LIBCERROR_ERROR_DOMAIN_RUNTIME, LIBCERROR_RUNTIME_ERROR_VALUE_OUT_OF_BOUNDS, "%s: invalid long value out of bounds.", function ); return( -1 ); } #endif *value_64bit = (int64_t) long_value; return( 1 ); }
/** ******************************************************************************************************* * Callback for as_info_foreach(). * * @param err The as_error to be populated by the function * with the encountered error if any. * @param node The current as_node object for which the * callback is fired by c client. * @param req The info request string. * @param res The info response string for current node. * @pram udata The callback udata containing the host_lookup * array and the return zval to be populated with * an entry for current node's info response with * the node's ID as the key. * * Returns true if callback is successful, Otherwise false. ******************************************************************************************************* */ static bool AerospikeClient_Info_each(as_error * err, const as_node * node, const char * req, char * res, void * udata) { PyObject * py_err = NULL; PyObject * py_ustr = NULL; PyObject * py_out = NULL; foreach_callback_info_udata* udata_ptr = (foreach_callback_info_udata *) udata; struct sockaddr_in* addr = NULL; if ( err && err->code != AEROSPIKE_OK ) { as_error_update(err, err->code, NULL); goto CLEANUP; } else if ( res != NULL ) { char * out = strchr(res,'\t'); if ( out != NULL ) { out++; py_out = PyString_FromString(out); } else { py_out = PyString_FromString(res); } } if ( py_err == NULL ) { Py_INCREF(Py_None); py_err = Py_None; } if ( py_out == NULL ) { Py_INCREF(Py_None); py_out = Py_None; } PyObject * py_res = PyTuple_New(2); PyTuple_SetItem(py_res, 0, py_err); PyTuple_SetItem(py_res, 1, py_out); if(udata_ptr->host_lookup_p) { PyObject * py_hosts = (PyObject *)udata_ptr->host_lookup_p; if ( py_hosts && PyList_Check(py_hosts) ) { addr = as_node_get_address((as_node *)node); int size = (int) PyList_Size(py_hosts); for ( int i = 0; i < size && i < AS_CONFIG_HOSTS_SIZE; i++ ) { char * host_addr = NULL; int port = -1; PyObject * py_host = PyList_GetItem(py_hosts, i); if ( PyTuple_Check(py_host) && PyTuple_Size(py_host) == 2 ) { PyObject * py_addr = PyTuple_GetItem(py_host,0); PyObject * py_port = PyTuple_GetItem(py_host,1); if (PyUnicode_Check(py_addr)) { py_ustr = PyUnicode_AsUTF8String(py_addr); host_addr = PyString_AsString(py_ustr); } else if ( PyString_Check(py_addr) ) { host_addr = PyString_AsString(py_addr); } else { as_error_update(&udata_ptr->error, AEROSPIKE_ERR_PARAM, "Host address is of type incorrect"); if (py_res) { Py_DECREF(py_res); } return false; } if ( PyInt_Check(py_port) ) { port = (uint16_t) PyInt_AsLong(py_port); } else if ( PyLong_Check(py_port) ) { port = (uint16_t) PyLong_AsLong(py_port); } else { break; } char ip_port[IP_PORT_MAX_LEN]; inet_ntop(addr->sin_family, &(addr->sin_addr), ip_port, INET_ADDRSTRLEN); if( (!strcmp(host_addr,ip_port)) && (port == ntohs(addr->sin_port))) { PyObject * py_nodes = (PyObject *) udata_ptr->udata_p; PyDict_SetItemString(py_nodes, node->name, py_res); } } } } else if ( !PyList_Check( py_hosts )){ as_error_update(&udata_ptr->error, AEROSPIKE_ERR_PARAM, "Hosts should be specified in a list."); goto CLEANUP; } } else { PyObject * py_nodes = (PyObject *) udata_ptr->udata_p; PyDict_SetItemString(py_nodes, node->name, py_res); } Py_DECREF(py_res); CLEANUP: if ( udata_ptr->error.code != AEROSPIKE_OK ) { PyObject * py_err = NULL; error_to_pyobject( &udata_ptr->error, &py_err); PyObject *exception_type = raise_exception(&udata_ptr->error); PyErr_SetObject(exception_type, py_err); Py_DECREF(py_err); return NULL; } if ( err->code != AEROSPIKE_OK ) { PyObject * py_err = NULL; error_to_pyobject(err, &py_err); PyObject *exception_type = raise_exception(err); PyErr_SetObject(exception_type, py_err); Py_DECREF(py_err); return NULL; } return true; }