コード例 #1
0
ファイル: ModuleSetupCode.c プロジェクト: jramnani/cython
static int __Pyx_check_binary_version(void) {
    char ctversion[4], rtversion[4];
    PyOS_snprintf(ctversion, 4, "%d.%d", PY_MAJOR_VERSION, PY_MINOR_VERSION);
    PyOS_snprintf(rtversion, 4, "%s", Py_GetVersion());
    if (ctversion[0] != rtversion[0] || ctversion[2] != rtversion[2]) {
        char message[200];
        PyOS_snprintf(message, sizeof(message),
                      "compiletime version %s of module '%.100s' "
                      "does not match runtime version %s",
                      ctversion, __Pyx_MODULE_NAME, rtversion);
        #if PY_VERSION_HEX < 0x02050000
        return PyErr_Warn(NULL, message);
        #else
        return PyErr_WarnEx(NULL, message, 1);
        #endif
    }
    return 0;
}
コード例 #2
0
ファイル: pydia-render.c プロジェクト: AmiGanguli/dia
/*!
 * \brief Draw ellipse
 *
 * Not optional on the PyDia side. If not implemented a runtime warning 
 * will be generated when called.
 *
 * \memberof _DiaPyRenderer
 */
static void
draw_ellipse(DiaRenderer *renderer, 
	     Point *center,
	     real width, real height,
	     Color *fill, Color *stroke)
{
  PyObject *func, *res, *arg, *self = PYDIA_RENDERER (renderer);

  func = PyObject_GetAttrString (self, "draw_ellipse");
  if (func && PyCallable_Check(func)) {
    PyObject *opoint = PyDiaPoint_New (center);
    PyObject *fill_po;
    PyObject *stroke_po;
    Py_INCREF(self);
    Py_INCREF(func);
    /* we have to provide a Python object even if there is no color */
    if (fill)
      fill_po = PyDiaColor_New (fill);
    else
      Py_INCREF(Py_None), fill_po = Py_None;
    if (stroke)
      stroke_po = PyDiaColor_New (stroke);
    else
      Py_INCREF(Py_None), stroke_po = Py_None;

    arg = Py_BuildValue ("(OddOO)", opoint, width, height, fill_po, stroke_po);
    if (arg) {
      res = PyEval_CallObject (func, arg);
      ON_RES(res, FALSE);
    }
    Py_XDECREF (arg);
    Py_XDECREF (opoint);
    Py_XDECREF (fill_po);
    Py_XDECREF (stroke_po);
    Py_DECREF(func);
    Py_DECREF(self);
  } else { /* member not optional */
    gchar *msg = g_strdup_printf ("%s.draw_ellipse() implementation missing.",
				  G_OBJECT_CLASS_NAME (G_OBJECT_GET_CLASS (renderer)));
    PyErr_Clear();
    PyErr_Warn (PyExc_RuntimeWarning, msg);
    g_free (msg);
  }
}
コード例 #3
0
ファイル: pygenum.c プロジェクト: muntyan/pygobject-gtk-win32
static PyObject *
pyg_enum_richcompare(PyGEnum *self, PyObject *other, int op)
{
    static char warning[256];

    if (!PYGLIB_PyLong_Check(other)) {
	Py_INCREF(Py_NotImplemented);
	return Py_NotImplemented;
    }

    if (PyObject_TypeCheck(other, &PyGEnum_Type) && ((PyGEnum*)other)->gtype != self->gtype) {
	g_snprintf(warning, sizeof(warning), "comparing different enum types: %s and %s",
		   g_type_name(self->gtype), g_type_name(((PyGEnum*)other)->gtype));
	if (PyErr_Warn(PyExc_Warning, warning))
	    return NULL;
    }

    return pyg_integer_richcompare((PyObject *)self, other, op);
}
コード例 #4
0
ファイル: pydia-render.c プロジェクト: AmiGanguli/dia
/*!
 * \brief Draw string
 *
 * Not optional on the PyDia side. If not implemented a runtime warning 
 * will be generated when called.
 *
 * \memberof _DiaPyRenderer
 */
static void
draw_string(DiaRenderer *renderer,
	    const char *text,
	    Point *pos, Alignment alignment,
	    Color *colour)
{
  PyObject *func, *res, *arg, *self = PYDIA_RENDERER (renderer);

  switch (alignment) {
  case ALIGN_LEFT:
    break;
  case ALIGN_CENTER:
    break;
  case ALIGN_RIGHT:
    break;
  }

  func = PyObject_GetAttrString (self, "draw_string");
  if (func && PyCallable_Check(func)) {
    PyObject *opoint = PyDiaPoint_New (pos);
    PyObject *ocolor = PyDiaColor_New (colour);

    Py_INCREF(self);
    Py_INCREF(func);
    arg = Py_BuildValue ("(sOiO)", text, opoint, alignment, ocolor);
    if (arg) {
      res = PyEval_CallObject (func, arg);
      ON_RES(res, FALSE);
    }
    Py_XDECREF (arg);
    Py_XDECREF (opoint);
    Py_XDECREF (ocolor);
    Py_DECREF(func);
    Py_DECREF(self);
  } else { /* member not optional */
    gchar *msg = g_strdup_printf ("%s.draw_string() implmentation missing.",
				  G_OBJECT_CLASS_NAME (G_OBJECT_GET_CLASS (renderer)));
    PyErr_Clear();
    PyErr_Warn (PyExc_RuntimeWarning, msg);
    g_free (msg);
  }
}
コード例 #5
0
static PyObject *
int_classic_div(PyIntObject *x, PyIntObject *y)
{
	long xi, yi;
	long d, m;
	CONVERT_TO_LONG(x, xi);
	CONVERT_TO_LONG(y, yi);
	if (Py_DivisionWarningFlag &&
	    PyErr_Warn(PyExc_DeprecationWarning, "classic int division") < 0)
		return NULL;
	switch (i_divmod(xi, yi, &d, &m)) {
	case DIVMOD_OK:
		return PyInt_FromLong(d);
	case DIVMOD_OVERFLOW:
		return PyLong_Type.tp_as_number->nb_divide((PyObject *)x,
							   (PyObject *)y);
	default:
		return NULL;
	}
}
コード例 #6
0
static PyObject *
complex_int_div(PyObject *v, PyObject *w)
{
    PyObject *t, *r;
    Py_complex a, b;
    TO_COMPLEX(v, a);
    TO_COMPLEX(w, b);
    if (PyErr_Warn(PyExc_DeprecationWarning,
                   "complex divmod(), // and % are deprecated") < 0)
        return NULL;

    t = complex_divmod(v, w);
    if (t != NULL) {
        r = PyTuple_GET_ITEM(t, 0);
        Py_INCREF(r);
        Py_DECREF(t);
        return r;
    }
    return NULL;
}
コード例 #7
0
ファイル: complexobject.c プロジェクト: santagada/wpython
static PyObject *
complex_classic_div(PyComplexObject *v, PyComplexObject *w)
{
	Py_complex quot;

	if (Py_DivisionWarningFlag >= 2 &&
	    PyErr_Warn(PyExc_DeprecationWarning,
		       "classic complex division") < 0)
		return NULL;

	PyFPE_START_PROTECT("complex_classic_div", return 0)
	errno = 0;
	quot = c_quot(v->cval,w->cval);
	PyFPE_END_PROTECT(quot)
	if (errno == EDOM) {
		PyErr_SetString(PyExc_ZeroDivisionError, "complex division");
		return NULL;
	}
	return PyComplex_FromCComplex(quot);
}
コード例 #8
0
ファイル: complexobject.c プロジェクト: santagada/wpython
static PyObject *
complex_remainder(PyComplexObject *v, PyComplexObject *w)
{
	Py_complex div, mod;

	if (PyErr_Warn(PyExc_DeprecationWarning,
		       "complex divmod(), // and % are deprecated") < 0)
		return NULL;

	errno = 0;
	div = c_quot(v->cval,w->cval); /* The raw divisor value. */
	if (errno == EDOM) {
		PyErr_SetString(PyExc_ZeroDivisionError, "complex remainder");
		return NULL;
	}
	div.real = floor(div.real); /* Use the floor of the real part. */
	div.imag = 0.0;
	mod = c_diff(v->cval, c_prod(w->cval, div));

	return PyComplex_FromCComplex(mod);
}
コード例 #9
0
ファイル: pydia-render.c プロジェクト: AmiGanguli/dia
/*!
 * \brief Set linestyle for later use
 *
 * Optional on the PyDia side.
 *
 * \memberof _DiaPyRenderer
 */
static void
set_linestyle(DiaRenderer *renderer, LineStyle mode, real dash_length)
{
  PyObject *func, *res, *arg, *self = PYDIA_RENDERER (renderer);

  /* line type */
  switch (mode) {
  case LINESTYLE_SOLID:
    break;
  case LINESTYLE_DASHED:
    break;
  case LINESTYLE_DASH_DOT:
    break;
  case LINESTYLE_DASH_DOT_DOT:
    break;
  case LINESTYLE_DOTTED:
    break;
  case LINESTYLE_DEFAULT:
  default:
    PyErr_Warn (PyExc_RuntimeWarning, "DiaPyRenderer : Unsupported fill mode specified!\n");
  }

  func = PyObject_GetAttrString (self, "set_linestyle");
  if (func && PyCallable_Check(func)) {
    Py_INCREF(self);
    Py_INCREF(func);
    arg = Py_BuildValue ("(id)", mode, dash_length);
    if (arg) {
      res = PyEval_CallObject (func, arg);
      ON_RES(res, FALSE);
    }
    Py_XDECREF (arg);
    Py_DECREF(func);
    Py_DECREF(self);
  }
  else /* member optional */
    PyErr_Clear();
}
コード例 #10
0
ファイル: pydia-render.c プロジェクト: AmiGanguli/dia
/*!
 * \brief Draw polygon
 *
 * Optional on the PyDia side. If not implemented fallback to base class member.
 *
 * \memberof _DiaPyRenderer
 */
static void
draw_polygon(DiaRenderer *renderer, 
	     Point *points, int num_points, 
	     Color *fill, Color *stroke)
{
  PyObject *func, *res, *arg, *self = PYDIA_RENDERER (renderer);

  func = PyObject_GetAttrString (self, "draw_polygon");
  if (func && PyCallable_Check(func)) {
    PyObject *optt = PyDiaPointTuple_New (points, num_points);
    PyObject *fill_po, *stroke_po;

    if (fill)
      fill_po = PyDiaColor_New (fill);
    else
      Py_INCREF(Py_None), fill_po = Py_None;
    if (stroke)
      stroke_po = PyDiaColor_New (stroke);
    else
      Py_INCREF(Py_None), stroke_po = Py_None;

    Py_INCREF(self);
    Py_INCREF(func);
    arg = Py_BuildValue ("(OOO)", optt, fill_po, stroke_po);
    if (arg) {
      res = PyEval_CallObject (func, arg);
      ON_RES(res, FALSE);
    }
    Py_XDECREF (arg);
    Py_XDECREF (optt);
    Py_XDECREF (fill_po);
    Py_XDECREF (stroke_po);
    Py_DECREF(func);
    Py_DECREF(self);
  } else { /* fill_polygon was not an optional member */
    PyErr_Warn (PyExc_RuntimeWarning, "DiaPyRenderer : draw_polygon() method missing!\n");
  }
}
コード例 #11
0
ファイル: pydia-render.c プロジェクト: AmiGanguli/dia
/*!
 * \brief Fill arc
 *
 * Not optional on the PyDia side. If not implemented a runtime warning 
 * will be generated when called.
 *
 * \memberof _DiaPyRenderer
 */
static void
fill_arc(DiaRenderer *renderer, 
	 Point *center,
	 real width, real height,
	 real angle1, real angle2,
	 Color *colour)
{
  PyObject *func, *res, *arg, *self = PYDIA_RENDERER (renderer);

  func = PyObject_GetAttrString (self, "fill_arc");
  if (func && PyCallable_Check(func)) {
    PyObject *opoint = PyDiaPoint_New (center);
    PyObject *ocolor = PyDiaColor_New (colour);

    Py_INCREF(self);
    Py_INCREF(func);
    arg = Py_BuildValue ("(OddddO)", opoint,
                                     width, height, angle1, angle2,
                                     ocolor);
    if (arg) {
      res = PyEval_CallObject (func, arg);
      ON_RES(res, FALSE);
    }
    Py_XDECREF (arg);
    Py_XDECREF (opoint);
    Py_XDECREF (ocolor);
    Py_DECREF(func);
    Py_DECREF(self);
  }
  else { /* member not optional */
    gchar *msg = g_strdup_printf ("%s.fill_arc() implmentation missing.",
				  G_OBJECT_CLASS_NAME (G_OBJECT_GET_CLASS (renderer)));
    PyErr_Clear();
    PyErr_Warn (PyExc_RuntimeWarning, msg);
    g_free (msg);
  }
}
コード例 #12
0
VOID CALLBACK
py_win32_timer_callback (HWND hwnd, UINT msg, UINT_PTR timer_id, DWORD time)
{
	CEnterLeavePython _celp;
	PyObject * py_timer_id = PyWinLong_FromVoidPtr((void *)timer_id);
	if (!py_timer_id){
		PyErr_Print();
		return;
		}
	// is this timer id recognized?
	PyObject * callback_function = PyDict_GetItem (timer_id_callback_map, py_timer_id);
	if (!callback_function){
		::KillTimer (NULL, timer_id);
		PyErr_Warn(PyExc_RuntimeWarning, "Unrecognized timer id");
		Py_DECREF(py_timer_id);
		return;
		}
	// call the user's function
	// create a 'death grip' on the callback function, just incase
	// the callback itself removes the function from the map.
	Py_INCREF(callback_function);
	PyObject * callback_args = Py_BuildValue ("(Ok)", py_timer_id, time);
	PyObject * result = PyEval_CallObject (callback_function, callback_args);

	if (!result) {
		// Is this necessary, or will python already have flagged
		// an exception?  Can we even catch exceptions here?
		PyErr_Print();
		}

	// everything's ok, return
	Py_DECREF(callback_function);
	Py_XDECREF(callback_args);
	Py_XDECREF(result);
	Py_DECREF (py_timer_id);
	return;
}
コード例 #13
0
ファイル: Connection.cpp プロジェクト: pedia/zeroc-ice
    void invoke(const string& methodName, const Ice::ConnectionPtr& con)
    {
        AdoptThread adoptThread; // Ensure the current thread is able to call into Python.
#ifndef NDEBUG
        ConnectionObject* c = reinterpret_cast<ConnectionObject*>(_con);
        assert(con == *(c->connection));
#endif
        if(!PyObject_HasAttrString(_cb, STRCAST(methodName.c_str())))
        {
            ostringstream ostr;
            ostr << "connection callback object does not define " << methodName << "()";
            string str = ostr.str();
            PyErr_Warn(PyExc_RuntimeWarning, const_cast<char*>(str.c_str()));
        }
        else
        {
            PyObjectHandle args = Py_BuildValue(STRCAST("(O)"), _con);
            PyObjectHandle method = PyObject_GetAttrString(_cb, STRCAST(methodName.c_str()));
            assert(method.get());
            PyObjectHandle tmp = PyObject_Call(method.get(), args.get(), 0);
            if(PyErr_Occurred())
            {
                PyException ex; // Retrieve it before another Python API call clears it.

                //
                // A callback that calls sys.exit() will raise the SystemExit exception.
                // This is normally caught by the interpreter, causing it to exit.
                // However, we have no way to pass this exception to the interpreter,
                // so we act on it directly.
                //
                ex.checkSystemExit();

                ex.raise();
            }
        }
    }
コード例 #14
0
ファイル: PyADSIUtil.cpp プロジェクト: malrsrch/pywin32
// @object PyADSVALUE|A tuple:
// @tupleitem 0|object|value|The value as a Python object.
// @tupleitem 1|int|type|The AD type of the value.
PyObject *PyADSIObject_FromADSVALUE(ADSVALUE &v)
{
	PyObject *ob = NULL;
	switch (v.dwType) {
		case ADSTYPE_DN_STRING:
			ob = PyWinObject_FromWCHAR(v.DNString);
			break;
		case ADSTYPE_CASE_EXACT_STRING:
			ob = PyWinObject_FromWCHAR(v.CaseExactString);
			break;
		case ADSTYPE_CASE_IGNORE_STRING:
			ob = PyWinObject_FromWCHAR(v.CaseIgnoreString);
			break;
		case ADSTYPE_PRINTABLE_STRING:
			ob = PyWinObject_FromWCHAR(v.PrintableString);
			break;
		case ADSTYPE_NUMERIC_STRING:
			ob = PyWinObject_FromWCHAR(v.NumericString);
			break;
		case ADSTYPE_BOOLEAN:
			ob = v.Boolean ? Py_True : Py_False;
			Py_INCREF(ob);
			break;
		case ADSTYPE_INTEGER:
			ob = PyInt_FromLong(v.Integer);
			break;
		case ADSTYPE_OCTET_STRING:
			{
			void *buf;
			DWORD bufSize = v.OctetString.dwLength;
			if (!(ob=PyBuffer_New(bufSize)))
				return NULL;
			if (!PyWinObject_AsWriteBuffer(ob, &buf, &bufSize)){
				Py_DECREF(ob);
				return NULL;
				}
			memcpy(buf, v.OctetString.lpValue, bufSize);
			}
			break;
		case ADSTYPE_UTC_TIME:
			ob = PyWinObject_FromSYSTEMTIME(v.UTCTime);
			break;
		case ADSTYPE_LARGE_INTEGER:
			ob = PyWinObject_FromLARGE_INTEGER(v.LargeInteger);
			break;
		case ADSTYPE_OBJECT_CLASS:
			ob = PyWinObject_FromWCHAR(v.ClassName);
			break;
		case ADSTYPE_PROV_SPECIFIC:
			{
			void *buf;
			DWORD bufSize = v.ProviderSpecific.dwLength;
			if (!(ob=PyBuffer_New(bufSize)))
				return NULL;
			if (!PyWinObject_AsWriteBuffer(ob, &buf, &bufSize)){
				Py_DECREF(ob);
				return NULL;
			}
			memcpy(buf, v.ProviderSpecific.lpValue, bufSize);
			break;
			}
		case ADSTYPE_NT_SECURITY_DESCRIPTOR:
			{
			// Get a pointer to the security descriptor.
			PSECURITY_DESCRIPTOR pSD = (PSECURITY_DESCRIPTOR)(v.SecurityDescriptor.lpValue);
			DWORD SDSize = v.SecurityDescriptor.dwLength;
			// eeek - we don't pass the length - pywintypes relies on
			// GetSecurityDescriptorLength - make noise if this may bite us.
			if (SDSize != GetSecurityDescriptorLength(pSD))
				PyErr_Warn(PyExc_RuntimeWarning, "Security-descriptor size mis-match");
			ob = PyWinObject_FromSECURITY_DESCRIPTOR(pSD);
			break;
			}
		default:
			{
			char msg[100];
			sprintf(msg, "Unknown ADS type code 0x%x - None will be returned", v.dwType);
			PyErr_Warn(PyExc_RuntimeWarning, msg);
			ob = Py_None;
			Py_INCREF(ob);
		}
	}
	if (ob==NULL)
		return NULL;
	PyObject *ret = Py_BuildValue("Oi", ob, (int)v.dwType);
	Py_DECREF(ob);
	return ret;
}
コード例 #15
0
ファイル: pyjobject.c プロジェクト: Kroisse/jep
// find and call a method on this object that matches the python args.
// typically called by way of pyjmethod when python invokes __call__.
//
// steals reference to self, methodname and args.
PyObject* find_method(JNIEnv *env,
                      PyObject *methodName,
                      Py_ssize_t methodCount,
                      PyObject *attr,
                      PyObject *args) {
    // all possible method candidates
    PyJmethod_Object **cand = NULL;
    Py_ssize_t         pos, i, listSize, argsSize;
    
    pos = i = listSize = argsSize = 0;

    // not really likely if we were called from pyjmethod, but hey...
    if(methodCount < 1) {
        PyErr_Format(PyExc_RuntimeError, "I have no methods.");
        return NULL;
    }

    if(!attr || !PyList_CheckExact(attr)) {
        PyErr_Format(PyExc_RuntimeError, "Invalid attr list.");
        return NULL;
    }
    
    cand = (PyJmethod_Object **)
        PyMem_Malloc(sizeof(PyJmethod_Object*) * methodCount);
    
    // just for safety
    for(i = 0; i < methodCount; i++)
        cand[i] = NULL;
    
    listSize = PyList_GET_SIZE(attr);
    for(i = 0; i < listSize; i++) {
        PyObject *tuple = PyList_GetItem(attr, i);               /* borrowed */

        if(PyErr_Occurred())
            break;
        
        if(!tuple || tuple == Py_None || !PyTuple_CheckExact(tuple))
            continue;

        if(PyTuple_Size(tuple) == 2) {
            PyObject *key = PyTuple_GetItem(tuple, 0);           /* borrowed */
            
            if(PyErr_Occurred())
                break;
            
            if(!key || !PyString_Check(key))
                continue;
            
            if(PyObject_Compare(key, methodName) == 0) {
                PyObject *method = PyTuple_GetItem(tuple, 1);    /* borrowed */
                if(pyjmethod_check(method))
                    cand[pos++] = (PyJmethod_Object *) method;
            }
        }
    }
    
    if(PyErr_Occurred())
        goto EXIT_ERROR;
    
    // makes more sense to work with...
    pos--;
    
    if(pos < 0) {
        // didn't find a method by that name....
        // that shouldn't happen unless the search above is broken.
        PyErr_Format(PyExc_NameError, "No such method.");
        goto EXIT_ERROR;
    }
    if(pos == 0) {
        // we're done, call that one
        PyObject *ret = pyjmethod_call_internal(cand[0], args);
        PyMem_Free(cand);
        return ret;
    }

    // first, find out if there's only one method that
    // has the correct number of args
    argsSize = PyTuple_Size(args);
    {
        PyJmethod_Object *matching = NULL;
        int               count    = 0;
        
        for(i = 0; i <= pos && cand[i]; i++) {
            // make sure method is fully initialized
            if(!cand[i]->parameters) {
                if(!pyjmethod_init(env, cand[i])) {
                    // init failed, that's not good.
                    cand[i] = NULL;
                    PyErr_Warn(PyExc_Warning, "pyjmethod init failed.");
                    continue;
                }
            }

            if(cand[i]->lenParameters == argsSize) {
                matching = cand[i];
                count++;
            }
            else
                cand[i] = NULL; // eliminate non-matching
        }
        
        if(matching && count == 1) {
            PyMem_Free(cand);
            return pyjmethod_call_internal(matching, args);
        }
    } // local scope
    
    for(i = 0; i <= pos; i++) {
        int parmpos = 0;
        
        // already eliminated?
        if(!cand[i])
            continue;
        
        // check if argument types match
        (*env)->PushLocalFrame(env, 20);
        for(parmpos = 0; parmpos < cand[i]->lenParameters; parmpos++) {
            PyObject *param       = PyTuple_GetItem(args, parmpos);
            int       paramTypeId = -1;
            jclass    pclazz;
            jclass    paramType =
                (jclass) (*env)->GetObjectArrayElement(env,
                                                       cand[i]->parameters,
                                                       parmpos);

            if(process_java_exception(env) || !paramType)
                break;
            
            pclazz = (*env)->GetObjectClass(env, paramType);
            if(process_java_exception(env) || !pclazz)
                break;
            
            paramTypeId = get_jtype(env, paramType, pclazz);
            
            if(pyarg_matches_jtype(env, param, paramType, paramTypeId)) {
                if(PyErr_Occurred())
                    break;
                continue;
            }
            
            // args don't match
            break;
        }
        (*env)->PopLocalFrame(env, NULL);
        
        // this method matches?
        if(parmpos == cand[i]->lenParameters) {
            PyObject *ret = pyjmethod_call_internal(cand[i], args);
            PyMem_Free(cand);
            return ret;
        }
    }


EXIT_ERROR:
    PyMem_Free(cand);
    if(!PyErr_Occurred())
        PyErr_Format(PyExc_NameError,
                     "Matching overloaded method not found.");
    return NULL;
}
コード例 #16
0
ファイル: callbacks.c プロジェクト: Oize/pspstacklesspython
/******************************************************************************
 *
 * Call the python object with all arguments
 *
 */
static void _CallPythonObject(void *mem,
			      ffi_type *restype,
			      SETFUNC setfunc,
			      PyObject *callable,
			      PyObject *converters,
			      void **pArgs)
{
	int i;
	PyObject *result;
	PyObject *arglist = NULL;
	int nArgs;
#ifdef WITH_THREAD
	PyGILState_STATE state = PyGILState_Ensure();
#endif

	nArgs = PySequence_Length(converters);
	/* Hm. What to return in case of error?
	   For COM, 0xFFFFFFFF seems better than 0.
	*/
	if (nArgs < 0) {
		PrintError("BUG: PySequence_Length");
		goto Done;
	}

	arglist = PyTuple_New(nArgs);
	if (!arglist) {
		PrintError("PyTuple_New()");
		goto Done;
	}
	for (i = 0; i < nArgs; ++i) {
		/* Note: new reference! */
		PyObject *cnv = PySequence_GetItem(converters, i);
		StgDictObject *dict;
		if (cnv)
			dict = PyType_stgdict(cnv);
		else {
			PrintError("Getting argument converter %d\n", i);
			goto Done;
		}

		if (dict && dict->getfunc && !IsSimpleSubType(cnv)) {
			PyObject *v = dict->getfunc(*pArgs, dict->size);
			if (!v) {
				PrintError("create argument %d:\n", i);
				Py_DECREF(cnv);
				goto Done;
			}
			PyTuple_SET_ITEM(arglist, i, v);
			/* XXX XXX XX
			   We have the problem that c_byte or c_short have dict->size of
			   1 resp. 4, but these parameters are pushed as sizeof(int) bytes.
			   BTW, the same problem occurrs when they are pushed as parameters
			*/
		} else if (dict) {
			/* Hm, shouldn't we use CData_AtAddress() or something like that instead? */
			CDataObject *obj = (CDataObject *)PyObject_CallFunctionObjArgs(cnv, NULL);
			if (!obj) {
				PrintError("create argument %d:\n", i);
				Py_DECREF(cnv);
				goto Done;
			}
			if (!CDataObject_Check(obj)) {
				Py_DECREF(obj);
				Py_DECREF(cnv);
				PrintError("unexpected result of create argument %d:\n", i);
				goto Done;
			}
			memcpy(obj->b_ptr, *pArgs, dict->size);
			PyTuple_SET_ITEM(arglist, i, (PyObject *)obj);
#ifdef MS_WIN32
			TryAddRef(dict, obj);
#endif
		} else {
			PyErr_SetString(PyExc_TypeError,
					"cannot build parameter");
			PrintError("Parsing argument %d\n", i);
			Py_DECREF(cnv);
			goto Done;
		}
		Py_DECREF(cnv);
		/* XXX error handling! */
		pArgs++;
	}

#define CHECK(what, x) \
if (x == NULL) _AddTraceback(what, __FILE__, __LINE__ - 1), PyErr_Print()

	result = PyObject_CallObject(callable, arglist);
	CHECK("'calling callback function'", result);
	if ((restype != &ffi_type_void) && result) {
		PyObject *keep;
		assert(setfunc);
#ifdef WORDS_BIGENDIAN
		/* See the corresponding code in callproc.c, around line 961 */
		if (restype->type != FFI_TYPE_FLOAT && restype->size < sizeof(ffi_arg))
			mem = (char *)mem + sizeof(ffi_arg) - restype->size;
#endif
		keep = setfunc(mem, result, 0);
		CHECK("'converting callback result'", keep);
		/* keep is an object we have to keep alive so that the result
		   stays valid.  If there is no such object, the setfunc will
		   have returned Py_None.

		   If there is such an object, we have no choice than to keep
		   it alive forever - but a refcount and/or memory leak will
		   be the result.  EXCEPT when restype is py_object - Python
		   itself knows how to manage the refcount of these objects.
		*/
		if (keep == NULL) /* Could not convert callback result. */
			PyErr_WriteUnraisable(callable);
		else if (keep == Py_None) /* Nothing to keep */
			Py_DECREF(keep);
		else if (setfunc != getentry("O")->setfunc) {
			if (-1 == PyErr_Warn(PyExc_RuntimeWarning,
					     "memory leak in callback function."))
				PyErr_WriteUnraisable(callable);
		}
	}
	Py_XDECREF(result);
  Done:
	Py_XDECREF(arglist);
#ifdef WITH_THREAD
	PyGILState_Release(state);
#endif
}
コード例 #17
0
static int
pylzma_compfile_init(CCompressionFileObject *self, PyObject *args, PyObject *kwargs)
{
    PyObject *inFile;
    CLzmaEncProps props;
    Byte header[LZMA_PROPS_SIZE];
    size_t headerSize = LZMA_PROPS_SIZE;
    int result = -1;
    
    // possible keywords for this function
    static char *kwlist[] = {"infile", "dictionary", "fastBytes", "literalContextBits",
                             "literalPosBits", "posBits", "algorithm", "eos", "multithreading", "matchfinder", NULL};
    int dictionary = 23;         // [0,28], default 23 (8MB)
    int fastBytes = 128;         // [5,255], default 128
    int literalContextBits = 3;  // [0,8], default 3
    int literalPosBits = 0;      // [0,4], default 0
    int posBits = 2;             // [0,4], default 2
    int eos = 1;                 // write "end of stream" marker?
    int multithreading = 1;      // use multithreading if available?
    char *matchfinder = NULL;    // matchfinder algorithm
    int algorithm = 2;
    int res;
    
    if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O|iiiiiiiis", kwlist, &inFile, &dictionary, &fastBytes,
                                                                 &literalContextBits, &literalPosBits, &posBits, &algorithm, &eos, &multithreading, &matchfinder))
        return -1;
    
    CHECK_RANGE(dictionary,         0,  28, "dictionary must be between 0 and 28");
    CHECK_RANGE(fastBytes,          5, 255, "fastBytes must be between 5 and 255");
    CHECK_RANGE(literalContextBits, 0,   8, "literalContextBits must be between 0 and 8");
    CHECK_RANGE(literalPosBits,     0,   4, "literalPosBits must be between 0 and 4");
    CHECK_RANGE(posBits,            0,   4, "posBits must be between 0 and 4");
    CHECK_RANGE(algorithm,          0,   2, "algorithm must be between 0 and 2");
    
    if (matchfinder != NULL) {
#if (PY_VERSION_HEX >= 0x02050000)
        PyErr_WarnEx(PyExc_DeprecationWarning, "matchfinder selection is deprecated and will be ignored", 1);
#else
        PyErr_Warn(PyExc_DeprecationWarning, "matchfinder selection is deprecated and will be ignored");
#endif
    }
    
    if (PyString_Check(inFile)) {
        // create new cStringIO object from string
        inFile = PycStringIO->NewInput(inFile);
        if (inFile == NULL)
        {
            PyErr_NoMemory();
            return -1;
        }
    } else if (!PyObject_HasAttrString(inFile, "read")) {
        PyErr_SetString(PyExc_ValueError, "first parameter must be a file-like object");
        return -1;
    } else {
        // protect object from being refcounted out...
        Py_INCREF(inFile);
    }
    
    self->encoder = LzmaEnc_Create(&allocator);
    if (self->encoder == NULL) {
        Py_DECREF(inFile);
        PyErr_NoMemory();
        return -1;
    }
    
    LzmaEncProps_Init(&props);
    
    props.dictSize = 1 << dictionary;
    props.lc = literalContextBits;
    props.lp = literalPosBits;
    props.pb = posBits;
    props.algo = algorithm;
    props.fb = fastBytes;
    // props.btMode = 1;
    // props.numHashBytes = 4;
    // props.mc = 32;
    props.writeEndMark = eos ? 1 : 0;
    props.numThreads = multithreading ? 2 : 1;
    LzmaEncProps_Normalize(&props);
    res = LzmaEnc_SetProps(self->encoder, &props);
    if (res != SZ_OK) {
        Py_DECREF(inFile);
        PyErr_Format(PyExc_TypeError, "could not set encoder properties: %d", res);
        return -1;
    }

    self->inFile = inFile;
    CreatePythonInStream(&self->inStream, inFile);
    CreateMemoryOutStream(&self->outStream);

    LzmaEnc_WriteProperties(self->encoder, header, &headerSize);
    if (self->outStream.s.Write(&self->outStream, header, headerSize) != headerSize) {
        PyErr_SetString(PyExc_TypeError, "could not generate stream header");
        goto exit;
    }
    
    LzmaEnc_Prepare(self->encoder, &self->inStream.s, &self->outStream.s, &allocator, &allocator);
    result = 0;
    
exit:
    return result;
}
コード例 #18
0
ファイル: cholmod.c プロジェクト: ChiahungTai/cvxopt
static PyObject* splinsolve(PyObject *self, PyObject *args,
    PyObject *kwrds)
{
    spmatrix *A, *B, *X;
    matrix *P=NULL;
    int n, nnz;
    cholmod_sparse *Ac=NULL, *Bc=NULL, *Xc=NULL;
    cholmod_factor *L=NULL;
#if PY_MAJOR_VERSION >= 3
    int uplo_='L';
#endif
    char uplo='L';
    char *kwlist[] = {"A", "B", "p", "uplo", NULL};

    if (!set_options()) return NULL;
#if PY_MAJOR_VERSION >= 3
    if (!PyArg_ParseTupleAndKeywords(args, kwrds, "OO|OC", kwlist, &A,
        &B, &P, &uplo_)) return NULL;
    uplo = (char) uplo_;
#else
    if (!PyArg_ParseTupleAndKeywords(args, kwrds, "OO|Oc", kwlist, &A,
        &B, &P, &uplo)) return NULL;
#endif

    if (!SpMatrix_Check(A) || SP_NROWS(A) != SP_NCOLS(A))
        PY_ERR_TYPE("A is not a square sparse matrix");
    n = SP_NROWS(A);
    nnz = SP_NNZ(A);

    if (!SpMatrix_Check(B) || SP_ID(A) != SP_ID(B))
        PY_ERR_TYPE("B must be a sparse matrix of the same type as A");
    if (SP_NROWS(B) != n)
        PY_ERR(PyExc_ValueError, "incompatible dimensions for B");

    if (P) {
        if (!Matrix_Check(P) || MAT_ID(P) != INT) err_int_mtrx("p");
        if (MAT_LGT(P) != n) err_buf_len("p");
        if (!CHOL(check_perm)(P->buffer, n, n, &Common))
            PY_ERR(PyExc_ValueError, "not a valid permutation");
    }

    if (uplo != 'U' && uplo != 'L') err_char("uplo", "'L', 'U'");
    if (!(Ac = pack(A, uplo))) return PyErr_NoMemory();

    L = CHOL(analyze_p) (Ac, P ? MAT_BUFI(P): NULL, NULL, 0, &Common);
    if (Common.status != CHOLMOD_OK){
        CHOL(free_factor)(&L, &Common);
        CHOL(free_sparse)(&Ac, &Common);
        if (Common.status == CHOLMOD_OUT_OF_MEMORY)
            return PyErr_NoMemory();
        else {
            PyErr_SetString(PyExc_ValueError, "symbolic factorization "
                "failed");
            return NULL;
        }
    }

    CHOL(factorize) (Ac, L, &Common);
    CHOL(free_sparse)(&Ac, &Common);
    if (Common.status > 0) switch (Common.status) {
        case CHOLMOD_NOT_POSDEF:
            PyErr_SetObject(PyExc_ArithmeticError, Py_BuildValue("i",
                L->minor));
            CHOL(free_factor)(&L, &Common);
            return NULL;
            break;

        case CHOLMOD_DSMALL:
            /* This never happens unless we change the default value
             * of Common.dbound (0.0).  */
            if (L->is_ll)
                PyErr_Warn(PyExc_RuntimeWarning, "tiny diagonal "
                    "elements in L");
            else
                PyErr_Warn(PyExc_RuntimeWarning, "tiny diagonal "
                    "elements in D");
            break;

        default:
            PyErr_Warn(PyExc_UserWarning, "");
    }

    if (L->minor<n) {
        CHOL(free_factor)(&L, &Common);
        PY_ERR(PyExc_ArithmeticError, "singular matrix");
    }
    if (!(Bc = create_matrix(B))) {
      CHOL(free_factor)(&L, &Common);
      return PyErr_NoMemory();
    }

    Xc = CHOL(spsolve)(0, L, Bc, &Common);
    free_matrix(Bc);
    CHOL(free_factor)(&L, &Common);
    if (Common.status != CHOLMOD_OK){
        CHOL(free_sparse)(&Xc, &Common);
        if (Common.status == CHOLMOD_OUT_OF_MEMORY)
            return PyErr_NoMemory();
        else
            PY_ERR(PyExc_ValueError, "solve step failed");
    }

    if (!(X = SpMatrix_New(Xc->nrow, Xc->ncol,
        ((int_t*)Xc->p)[Xc->ncol], SP_ID(A)))) {
        CHOL(free_sparse)(&Xc, &Common);
        return PyErr_NoMemory();
    }
    memcpy(SP_COL(X), (int_t *) Xc->p, (Xc->ncol+1)*sizeof(int_t));
    memcpy(SP_ROW(X), (int_t *) Xc->i,
        ((int_t *) Xc->p)[Xc->ncol]*sizeof(int_t));
    memcpy(SP_VAL(X), (double *) Xc->x,
        ((int_t *) Xc->p)[Xc->ncol]*E_SIZE[SP_ID(X)]);
    CHOL(free_sparse)(&Xc, &Common);
    return (PyObject *) X;
}
コード例 #19
0
ファイル: cholmod.c プロジェクト: ChiahungTai/cvxopt
static PyObject* linsolve(PyObject *self, PyObject *args,
    PyObject *kwrds)
{
    spmatrix *A;
    matrix *B, *P=NULL;
    int i, n, nnz, oB=0, ldB=0, nrhs=-1;
    cholmod_sparse *Ac=NULL;
    cholmod_factor *L=NULL;
    cholmod_dense *x=NULL, *b=NULL;
    void *b_old;
#if PY_MAJOR_VERSION >= 3
    int uplo_ = 'L';
#endif
    char uplo='L';
    char *kwlist[] = {"A", "B", "p", "uplo", "nrhs", "ldB", "offsetB",
        NULL};

    if (!set_options()) return NULL;
#if PY_MAJOR_VERSION >= 3
    if (!PyArg_ParseTupleAndKeywords(args, kwrds, "OO|OCiii", kwlist,
        &A,  &B, &P, &uplo_, &nrhs, &ldB, &oB)) return NULL;
    uplo = (char) uplo_;
#else
    if (!PyArg_ParseTupleAndKeywords(args, kwrds, "OO|Ociii", kwlist,
        &A,  &B, &P, &uplo, &nrhs, &ldB, &oB)) return NULL;
#endif

    if (!SpMatrix_Check(A) || SP_NROWS(A) != SP_NCOLS(A))
        PY_ERR_TYPE("A is not a sparse matrix");
    n = SP_NROWS(A);
    nnz = SP_NNZ(A);

    if (!Matrix_Check(B) || MAT_ID(B) != SP_ID(A))
        PY_ERR_TYPE("B must be a dense matrix of the same numerical "
            "type as A");
    if (nrhs < 0) nrhs = MAT_NCOLS(B);
    if (n == 0 || nrhs == 0) return Py_BuildValue("");
    if (ldB == 0) ldB = MAX(1,MAT_NROWS(B));
    if (ldB < MAX(1,n)) err_ld("ldB");
    if (oB < 0) err_nn_int("offsetB");
    if (oB + (nrhs-1)*ldB + n > MAT_LGT(B)) err_buf_len("B");

    if (P) {
        if (!Matrix_Check(P) || MAT_ID(P) != INT) err_int_mtrx("p");
        if (MAT_LGT(P) != n) err_buf_len("p");
        if (!CHOL(check_perm)(P->buffer, n, n, &Common))
            PY_ERR(PyExc_ValueError, "not a valid permutation");
    }
    if (uplo != 'U' && uplo != 'L') err_char("uplo", "'L', 'U'");

    if (!(Ac = pack(A, uplo))) return PyErr_NoMemory();
    L = CHOL(analyze_p)(Ac, P ? MAT_BUFI(P): NULL, NULL, 0, &Common);
    if (Common.status != CHOLMOD_OK){
        free_matrix(Ac);
        CHOL(free_sparse)(&Ac, &Common);
        CHOL(free_factor)(&L, &Common);
        if (Common.status == CHOLMOD_OUT_OF_MEMORY)
            return PyErr_NoMemory();
        else {
            PyErr_SetString(PyExc_ValueError, "symbolic factorization "
                "failed");
            return NULL;
        }
    }

    CHOL(factorize) (Ac, L, &Common);
    CHOL(free_sparse)(&Ac, &Common);
    if (Common.status < 0) {
        CHOL(free_factor)(&L, &Common);
        switch (Common.status) {
            case CHOLMOD_OUT_OF_MEMORY:
                return PyErr_NoMemory();

            default:
                PyErr_SetString(PyExc_ValueError, "factorization "
                    "failed");
                return NULL;
        }
    }
    if (Common.status > 0) switch (Common.status) {
        case CHOLMOD_NOT_POSDEF:
            PyErr_SetObject(PyExc_ArithmeticError,
                Py_BuildValue("i", L->minor));
            CHOL(free_factor)(&L, &Common);
            return NULL;
            break;

        case CHOLMOD_DSMALL:
            /* This never happens unless we change the default value
             * of Common.dbound (0.0).  */
            if (L->is_ll)
                PyErr_Warn(PyExc_RuntimeWarning, "tiny diagonal "
                    "elements in L");
            else
                PyErr_Warn(PyExc_RuntimeWarning, "tiny diagonal "
                    "elements in D");
            break;

        default:
            PyErr_Warn(PyExc_UserWarning, "");
    }

    if (L->minor<n) {
        CHOL(free_factor)(&L, &Common);
        PY_ERR(PyExc_ArithmeticError, "singular matrix");
    }
    b = CHOL(allocate_dense)(n, 1, n, (MAT_ID(B) == DOUBLE ?
        CHOLMOD_REAL : CHOLMOD_COMPLEX) , &Common);
    if (Common.status == CHOLMOD_OUT_OF_MEMORY) {
        CHOL(free_factor)(&L, &Common);
        CHOL(free_dense)(&b, &Common);
        return PyErr_NoMemory();
    }
    b_old = b->x;
    for (i=0; i<nrhs; i++) {
        b->x = MAT_BUF(B) + (i*ldB + oB)*E_SIZE[MAT_ID(B)];
        x = CHOL(solve) (CHOLMOD_A, L, b, &Common);
        if (Common.status != CHOLMOD_OK){
            PyErr_SetString(PyExc_ValueError, "solve step failed");
            CHOL(free_factor)(&L, &Common);
            b->x = b_old;
            CHOL(free_dense)(&b, &Common);
            CHOL(free_dense)(&x, &Common);
            return NULL;
        }
        memcpy(b->x, x->x, SP_NROWS(A)*E_SIZE[MAT_ID(B)]);
        CHOL(free_dense)(&x, &Common);
    }
    b->x = b_old;
    CHOL(free_dense)(&b, &Common);
    CHOL(free_factor)(&L, &Common);
    return Py_BuildValue("");
}
コード例 #20
0
ファイル: cholmod.c プロジェクト: ChiahungTai/cvxopt
static PyObject* numeric(PyObject *self, PyObject *args)
{
    spmatrix *A;
    PyObject *F;
    cholmod_factor *Lc;
    cholmod_sparse *Ac = NULL;
    char uplo;
#if PY_MAJOR_VERSION >= 3
    const char *descr; 
#else
    char *descr; 
#endif

    if (!set_options()) return NULL;

    if (!PyArg_ParseTuple(args, "OO", &A, &F)) return NULL;

    if (!SpMatrix_Check(A) || SP_NROWS(A) != SP_NCOLS(A))
        PY_ERR_TYPE("A is not a sparse matrix");

#if PY_MAJOR_VERSION >= 3
    if (!PyCapsule_CheckExact(F) || !(descr = PyCapsule_GetName(F)))
        err_CO("F");
#else
    if (!PyCObject_Check(F)) err_CO("F");
    descr = PyCObject_GetDesc(F);
    if (!descr) PY_ERR_TYPE("F is not a CHOLMOD factor");
#endif
    if (SP_ID(A) == DOUBLE){
        if (!strcmp(descr, "CHOLMOD FACTOR D L"))
	    uplo = 'L';
	else if (!strcmp(descr, "CHOLMOD FACTOR D U"))
	    uplo = 'U';
        else
	    PY_ERR_TYPE("F is not the CHOLMOD factor of a 'd' matrix");
    } else {
        if (!strcmp(descr, "CHOLMOD FACTOR Z L"))
	    uplo = 'L';
	else if (!strcmp(descr, "CHOLMOD FACTOR Z U"))
	    uplo = 'U';
        else
	    PY_ERR_TYPE("F is not the CHOLMOD factor of a 'z' matrix");
    }
#if PY_MAJOR_VERSION >= 3
    Lc = (cholmod_factor *) PyCapsule_GetPointer(F, descr);
#else
    Lc = (cholmod_factor *) PyCObject_AsVoidPtr(F);
#endif
    if (!(Ac = pack(A, uplo))) return PyErr_NoMemory();
    CHOL(factorize) (Ac, Lc, &Common);
    CHOL(free_sparse)(&Ac, &Common);

    if (Common.status < 0) switch (Common.status) {
        case CHOLMOD_OUT_OF_MEMORY:
            return PyErr_NoMemory();

        default:
            PyErr_SetString(PyExc_ValueError, "factorization failed");
            return NULL;
    }

    if (Common.status > 0) switch (Common.status) {
        case CHOLMOD_NOT_POSDEF:
            PyErr_SetObject(PyExc_ArithmeticError, Py_BuildValue("i",
                Lc->minor));
            return NULL;
            break;

        case CHOLMOD_DSMALL:
            /* This never happens unless we change the default value
             * of Common.dbound (0.0).  */
            if (Lc->is_ll)
                PyErr_Warn(PyExc_RuntimeWarning, "tiny diagonal "\
                    "elements in L");
            else
                PyErr_Warn(PyExc_RuntimeWarning, "tiny diagonal "\
                    "elements in D");
            break;

        default:
            PyErr_Warn(PyExc_UserWarning, "");
    }

    return Py_BuildValue("");
}
コード例 #21
0
static int
encode_common(PyObject **o, void **buf, size_t *nbuf, lcb_uint32_t flags)
{
    PyObject *bytesobj;
    Py_ssize_t plen;
    int rv;

    if (flags == PYCBC_FMT_UTF8) {
#if PY_MAJOR_VERSION == 2
        if (PyString_Check(*o)) {
#else
        if (0) {
#endif
            bytesobj = *o;
            Py_INCREF(*o);
        } else {
            if (!PyUnicode_Check(*o)) {
                PYCBC_EXC_WRAP_OBJ(PYCBC_EXC_ENCODING,
                                   0, "Must be unicode or string", *o);
                return -1;
            }
            bytesobj = PyUnicode_AsUTF8String(*o);
        }

    } else if (flags == PYCBC_FMT_BYTES) {
        if (PyBytes_Check(*o) || PyByteArray_Check(*o)) {
            bytesobj = *o;
            Py_INCREF(*o);

        } else {
            PYCBC_EXC_WRAP_OBJ(PYCBC_EXC_ENCODING, 0,
                               "Must be bytes or bytearray", *o);
            return -1;
        }

    } else {
        PyObject *args = NULL;
        PyObject *helper;

        if (flags == PYCBC_FMT_PICKLE) {
            helper = pycbc_helpers.pickle_encode;

        } else if (flags == PYCBC_FMT_JSON) {
            helper = pycbc_helpers.json_encode;

        } else {
            PYCBC_EXC_WRAP(PYCBC_EXC_ARGUMENTS, 0, "Unrecognized format");
            return -1;
        }

        args = PyTuple_Pack(1, *o);
        bytesobj = PyObject_CallObject(helper, args);
        Py_DECREF(args);

        if (!bytesobj) {
            PYCBC_EXC_WRAP_OBJ(PYCBC_EXC_ENCODING,
                               0, "Couldn't encode value", *o);
            return -1;
        }

        if (!PyBytes_Check(bytesobj)) {
            PyObject *old = bytesobj;
            bytesobj = convert_to_bytesobj(old);
            Py_DECREF(old);
            if (!bytesobj) {
                return -1;
            }
        }
    }

    if (PyByteArray_Check(bytesobj)) {
        *buf = PyByteArray_AS_STRING(bytesobj);
        plen = PyByteArray_GET_SIZE(bytesobj);
        rv = 0;
    } else {
        rv = PyBytes_AsStringAndSize(bytesobj, (char**)buf, &plen);
    }

    if (rv < 0) {
        Py_DECREF(bytesobj);
        PYCBC_EXC_WRAP(PYCBC_EXC_ENCODING, 0, "Couldn't encode value");
        return -1;
    }

    *nbuf = plen;
    *o = bytesobj;
    return 0;
}

static int
decode_common(PyObject **vp, const char *buf, size_t nbuf, lcb_uint32_t flags)
{
    PyObject *decoded = NULL;
    lcb_U32 c_flags, l_flags;

    c_flags = flags & PYCBC_FMT_COMMON_MASK;
    l_flags = flags & PYCBC_FMT_LEGACY_MASK;

    #define FMT_MATCHES(fmtbase) \
        (c_flags == PYCBC_FMT_COMMON_##fmtbase || l_flags == PYCBC_FMT_LEGACY_##fmtbase)

    if (FMT_MATCHES(UTF8)) {
        decoded = convert_to_string(buf, nbuf, CONVERT_MODE_UTF8_ONLY);
        if (!decoded) {
            return -1;
        }

    } else if (FMT_MATCHES(BYTES)) {
        GT_BYTES:
        decoded = convert_to_string(buf, nbuf, CONVERT_MODE_BYTES_ONLY);
        pycbc_assert(decoded);

    } else {
        PyObject *converter = NULL;
        PyObject *args = NULL;
        PyObject *first_arg = NULL;

        if (FMT_MATCHES(PICKLE)) {
            converter = pycbc_helpers.pickle_decode;
            first_arg = convert_to_string(buf, nbuf, CONVERT_MODE_BYTES_ONLY);
            pycbc_assert(first_arg);

        } else if (FMT_MATCHES(JSON)) {
            converter = pycbc_helpers.json_decode;
            first_arg = convert_to_string(buf, nbuf, CONVERT_MODE_UTF8_ONLY);

            if (!first_arg) {
                return -1;
            }

        } else {
            PyErr_Warn(PyExc_UserWarning, "Unrecognized flags. Forcing bytes");
            goto GT_BYTES;
        }

        pycbc_assert(first_arg);
        args = PyTuple_Pack(1, first_arg);
        decoded = PyObject_CallObject(converter, args);

        Py_DECREF(args);
        Py_DECREF(first_arg);
    }

    if (!decoded) {
        PyObject *bytes_tmp = PyBytes_FromStringAndSize(buf, nbuf);
        PYCBC_EXC_WRAP_OBJ(PYCBC_EXC_ENCODING, 0, "Failed to decode bytes",
                           bytes_tmp);
        Py_XDECREF(bytes_tmp);
        return -1;
    }

    *vp = decoded;
    return 0;

    #undef FMT_MATCHES
}
コード例 #22
0
ファイル: session.c プロジェクト: ZenithDK/pyspotify
static PyObject *
Session_browse_artist(PyObject *self, PyObject *args, PyObject *kwds)
{
    PyErr_Warn(PyExc_DeprecationWarning, "use the artist browser directly.");
    return PyObject_Call((PyObject *)&ArtistBrowserType, args, kwds);
}
コード例 #23
0
ファイル: pygarmin.c プロジェクト: awatry/garmintools
static PyObject* get_runs(PyObject* obj, PyObject* args)
{
  garmin_unit garmin;

  if (!initialize_garmin(&garmin))
    return NULL;
  
  garmin_data * data;

  if ( (data = garmin_get(&garmin, GET_RUNS)) == NULL )
  {
    PyErr_SetString(PyExc_RuntimeError, "Unable to extract any data.");
    return NULL;
  }

  /*
    We should have a list with three elements:
    1) The runs (which identify the track and lap indices)
    2) The laps (which are related to the runs)
    3) The tracks (which are related to the runs)
  */

  garmin_data * tmpdata;
  garmin_list * runs    = NULL;
  garmin_list * laps    = NULL;
  garmin_list * tracks  = NULL;

  tmpdata = garmin_list_data(data, 0);
  if ( tmpdata == NULL )
  {
    PyErr_SetString(PyExc_RuntimeError, "Toplevel data missing element 0 (runs)");
    return NULL;
  }

  runs = tmpdata->data;
  if ( runs == NULL )
  {
    PyErr_SetString(PyExc_RuntimeError, "No runs extracted.");
    return NULL;
  }
    
  tmpdata = garmin_list_data(data, 1);
  if ( tmpdata == NULL )
  {
    PyErr_SetString(PyExc_RuntimeError, "Toplevel data missing element 1 (laps)");
    return NULL;
  }

  laps = tmpdata->data;
  if ( laps == NULL )
  {
    PyErr_SetString(PyExc_RuntimeError, "No laps extracted.");
    return NULL;
  }
  
  tmpdata = garmin_list_data(data, 2);
  if ( tmpdata == NULL )
  {
    PyErr_SetString(PyExc_RuntimeError, "Toplevel data missing element 2 (tracks)");
    return NULL;
  }
  
  tracks = tmpdata->data;
  if ( tracks == NULL )
  {
    PyErr_SetString(PyExc_RuntimeError, "No tracks extracted.");
    return NULL;
  }

  garmin_list_node * n;
  garmin_list_node * m;
  garmin_list_node * o;
  uint32             trk;
  uint32             f_lap;
  uint32             l_lap;
  uint32             l_idx;
  time_type          start;

  /* Print some debug output if requested. */
  if ( verbose != 0 )
  {
    for ( m = laps->head; m != NULL; m = m->next )
    {
      if ( get_lap_index(m->data,&l_idx) != 0 )
        printf("[garmin] lap: index [%d]\n", l_idx);
      else
        printf("[garmin] lap: index [??]\n");
    }
  }
    
  /* For each run, get its laps and track points. */
  
  PyObject* dict = PyDict_New();

  for ( n = runs->head; n != NULL; n = n->next )
  {      
    if ( get_run_track_lap_info(n->data, &trk, &f_lap, &l_lap) != 0 )
    {
      time_type f_lap_start = 0;
      
      PyObject* run = PyDict_New();
      PyObject* rlaps = PyDict_New();

      PyDict_SetItem(run, PyString_FromString("track"), Py_BuildValue("i", trk));
      PyDict_SetItem(run, PyString_FromString("first_lap"), Py_BuildValue("i", f_lap));
      PyDict_SetItem(run, PyString_FromString("last_lap"), Py_BuildValue("i", l_lap));
      PyDict_SetItem(run, PyString_FromString("type"), Py_BuildValue("i", (int)n->data->type));

      /* TODO:
         Implement something similar for the other run types, D1000 and D1010
         See src/run.c get_run_track_lap_info() for more information
       */
      
      if (n->data->type == data_D1009)
      {
        D1009 * d1009;
        d1009 = n->data->data;
        PyDict_SetItem(run, PyString_FromString("multisport"), PyBool_FromLong(d1009->multisport));
        switch (d1009->sport_type)
        {
          case D1000_running:
            PyDict_SetItem(run, PyString_FromString("sport"), PyString_FromString("running"));
            break;
          case D1000_biking:
            PyDict_SetItem(run, PyString_FromString("sport"), PyString_FromString("biking"));
            break;
          case D1000_other:
            PyDict_SetItem(run, PyString_FromString("sport"), PyString_FromString("other"));
            break;            
        }
      }

      if (verbose != 0)
        printf("[garmin] run: track [%d], laps [%d:%d]\n",trk,f_lap,l_lap);
      
      for ( m = laps->head; m != NULL; m = m->next )
      {
        if ( get_lap_index(m->data, &l_idx) != 0 )
        {
          if ( l_idx >= f_lap && l_idx <= l_lap )
          {
            PyObject* lap = PyDict_New();
            
            if (verbose != 0)
              printf("[garmin] lap [%d] falls within laps [%d:%d]\n", l_idx,f_lap,l_lap);
            
            start = 0;
            get_lap_start_time(m->data, &start);

            if (start != 0)
            {
              if (l_idx == f_lap)
                  f_lap_start = start;

              PyDict_SetItem(lap, PyString_FromString("start_time"), Py_BuildValue("i", (int)start));
              PyDict_SetItem(lap, PyString_FromString("type"), Py_BuildValue("i", (int)m->data->type));

              if (m->data->type == data_D1015)
              {
                D1015 * d1015;
                d1015 = m->data->data;
                PyDict_SetItem(lap, PyString_FromString("duration"), Py_BuildValue("i", d1015->total_time));
                PyDict_SetItem(lap, PyString_FromString("distance"), Py_BuildValue("f", d1015->total_dist));
                PyDict_SetItem(lap, PyString_FromString("max_speed"), Py_BuildValue("f", d1015->max_speed));
              }

              PyObject * points = PyList_New(0);
              
              bool have_track = 0;
              bool done = 0;
                
              for ( o = tracks->head; o != NULL; o = o->next )
              {
                if ( o->data != NULL )
                {
                  if (o->data->type == data_D311)
                  {
                    if ( ! have_track )
                    {
                      D311 * d311;
                      d311 = o->data->data;
                      if (  d311->index == trk )
                          have_track = 1;
                    }
                    else /* We've reached the end of the track */
                        done = 1;
                  }
                  
                  else if (o->data->type == data_D304 && have_track)
                  {
                    D304 * d304;
                    d304 = o->data->data;
                    PyObject* point = PyDict_New();
                    
                    if (d304->posn.lat != 2147483647 && d304->posn.lon != 2147483647)
                    {
                      PyDict_SetItem(point, PyString_FromString("position"), Py_BuildValue("(ff)", SEMI2DEG(d304->posn.lat), SEMI2DEG(d304->posn.lon)));
                      PyDict_SetItem(point, PyString_FromString("type"), Py_BuildValue("i", (int)o->data->type));
                      PyDict_SetItem(point, PyString_FromString("time"), Py_BuildValue("f", (float)(d304->time + TIME_OFFSET)));
                      PyDict_SetItem(point, PyString_FromString("distance"), Py_BuildValue("f", d304->distance));
                      PyDict_SetItem(point, PyString_FromString("altitude"), Py_BuildValue("f", d304->alt));
                      PyDict_SetItem(point, PyString_FromString("heart_rate"), Py_BuildValue("i", d304->heart_rate));
                      
                      if (d304->cadence != 255)
                          PyDict_SetItem(point, PyString_FromString("cadence"), Py_BuildValue("i", d304->cadence));
                      
                      PyList_Append(points, Py_BuildValue("N", point));
                    }
                  }
                  
                  else if (have_track)
                      printf("get_track: point type %d invalid!\n",o->data->type);
                  }

                if ( done ) break;
              }
              PyDict_SetItem(lap, PyString_FromString("points"), Py_BuildValue("N", points));
            }
            else
                PyErr_Warn(PyExc_Warning, "Start time of first lap not found.");
            
            PyDict_SetItem(rlaps, PyString_FromFormat("%d", (int)l_idx), Py_BuildValue("N", lap));
          }
        }  
      }
      PyDict_SetItem(run, PyString_FromString("laps"), Py_BuildValue("N", rlaps));
      PyDict_SetItem(dict, PyString_FromFormat("%d", (int)f_lap_start), Py_BuildValue("N", run));
    }
  }

  garmin_free_data(data);
  garmin_close(&garmin);

  return Py_BuildValue("N", dict);  
}
コード例 #24
0
ファイル: misc.c プロジェクト: cvxopt/smcp
static PyObject* sdpa_write
(PyObject *self, PyObject *args, PyObject *kwrds)
{
  int i,Il,Jl,Bl,Ml;
  int_t n;
  spmatrix *A;
  matrix *b,*bstruct;
  PyObject *f;
  PyObject *neg = Py_False;
  char *kwlist[] = {"f","A","b","bstruct","neg",NULL};
  const char* fname;
  double v;

  if (!PyArg_ParseTupleAndKeywords(args,kwrds, "OOOO|O", kwlist, &f, &A, &b, &bstruct,&neg)) return NULL;
  #if PY_MAJOR_VERSION >= 3
  if (PyUnicode_Check(f)) fname = PyUnicode_AsUTF8AndSize(f,NULL);
  #elif PY_MAJOR_VERSION == 2
  if (PyString_Check(f)) fname = PyString_AsString(f);
  #endif
  FILE *fp = fopen(fname,"r");
  if (!fp) {
    Py_DECREF(f);
    return NULL;
  }

  fprintf(fp,"* sparse SDPA data file (created by SMCP)\n");
  fprintf(fp,"%i = m\n",(int) MAT_NROWS(b));
  fprintf(fp,"%i = nBlocks\n", (int) MAT_NROWS(bstruct));
  // compute n and write blockstruct
  n = 0;
  for (i=0;i<MAT_NROWS(bstruct);i++) {
    fprintf(fp,"%i ", (int) MAT_BUFI(bstruct)[i]);
    n += (int_t) labs(MAT_BUFI(bstruct)[i]);
  }
  fprintf(fp,"\n");

  // write vector b
  if (neg == Py_True) {
    for (i=0;i<MAT_NROWS(b);i++)
      fprintf(fp,"%.12g ",-MAT_BUFD(b)[i]);
  }
  else {
    for (i=0;i<MAT_NROWS(b);i++)
      fprintf(fp,"%.12g ",MAT_BUFD(b)[i]);
  }
  fprintf(fp,"\n");

  // Write data matrices A0,A1,A2,...,Am
  for (Ml=0;Ml<=MAT_NROWS(b);Ml++) {
    for (i=0;i<SP_COL(A)[Ml+1]-SP_COL(A)[Ml];i++){

      Jl = 1 + SP_ROW(A)[SP_COL(A)[Ml]+i] / n;
      Il = 1 + SP_ROW(A)[SP_COL(A)[Ml]+i] % n;

      // Skip if element is in strict upper triangle
      if (Jl > Il)
	PyErr_Warn(PyExc_Warning,"Ignored strictly upper triangular element.");

      Bl = 1;
      while ((Il > labs(MAT_BUFI(bstruct)[Bl-1])) && (Jl > labs(MAT_BUFI(bstruct)[Bl-1]))) {
	Il -= (int_t) labs(MAT_BUFI(bstruct)[Bl-1]);
	Jl -= (int_t) labs(MAT_BUFI(bstruct)[Bl-1]);
	Bl += 1;
      }
      /* Error check */
      if ((Il > labs(MAT_BUFI(bstruct)[Bl-1])) || (Jl > labs(MAT_BUFI(bstruct)[Bl-1])))
	printf("Error: Matrix contains elements outside blocks!\n");

      // print upper triangle entries:
      //   <matno> <blkno> <i> <j> <entry>
      v = SP_VALD(A)[SP_COL(A)[Ml]+i];
      if ( v != 0.0) {
	if (neg == Py_True)
	  fprintf(fp,"%i %i %i %i %.12g\n",
		  (int) Ml,(int) Bl,(int) Jl,(int) Il, -v);
	else
	  fprintf(fp,"%i %i %i %i %.12g\n",
		  (int) Ml,(int) Bl,(int) Jl,(int) Il, v);
      }
    }
  }

  fclose(fp);
  Py_DECREF(f);
  Py_RETURN_NONE;
}
コード例 #25
0
ファイル: extobj.c プロジェクト: Juanlu001/numpy
NPY_NO_EXPORT int
_error_handler(int method, PyObject *errobj, char *errtype, int retstatus, int *first)
{
    PyObject *pyfunc, *ret, *args;
    char *name = PyBytes_AS_STRING(PyTuple_GET_ITEM(errobj,0));
    char msg[100];

    NPY_ALLOW_C_API_DEF

    /* don't need C API for a simple print */
    if (method == UFUNC_ERR_PRINT) {
        if (*first) {
            fprintf(stderr, "Warning: %s encountered in %s\n", errtype, name);
            *first = 0;
        }
        return 0;
    }

    NPY_ALLOW_C_API;
    switch(method) {
    case UFUNC_ERR_WARN:
        PyOS_snprintf(msg, sizeof(msg), "%s encountered in %s", errtype, name);
        if (PyErr_Warn(PyExc_RuntimeWarning, msg) < 0) {
            goto fail;
        }
        break;
    case UFUNC_ERR_RAISE:
        PyErr_Format(PyExc_FloatingPointError, "%s encountered in %s",
                errtype, name);
        goto fail;
    case UFUNC_ERR_CALL:
        pyfunc = PyTuple_GET_ITEM(errobj, 1);
        if (pyfunc == Py_None) {
            PyErr_Format(PyExc_NameError,
                    "python callback specified for %s (in " \
                    " %s) but no function found.",
                    errtype, name);
            goto fail;
        }
        args = Py_BuildValue("NN", PyUString_FromString(errtype),
                PyInt_FromLong((long) retstatus));
        if (args == NULL) {
            goto fail;
        }
        ret = PyObject_CallObject(pyfunc, args);
        Py_DECREF(args);
        if (ret == NULL) {
            goto fail;
        }
        Py_DECREF(ret);
        break;
    case UFUNC_ERR_LOG:
        if (first) {
            *first = 0;
            pyfunc = PyTuple_GET_ITEM(errobj, 1);
            if (pyfunc == Py_None) {
                PyErr_Format(PyExc_NameError,
                        "log specified for %s (in %s) but no " \
                        "object with write method found.",
                        errtype, name);
                goto fail;
            }
            PyOS_snprintf(msg, sizeof(msg),
                    "Warning: %s encountered in %s\n", errtype, name);
            ret = PyObject_CallMethod(pyfunc, "write", "s", msg);
            if (ret == NULL) {
                goto fail;
            }
            Py_DECREF(ret);
        }
        break;
    }
    NPY_DISABLE_C_API;
    return 0;

fail:
    NPY_DISABLE_C_API;
    return -1;
}
コード例 #26
0
ファイル: pylzma_compress.c プロジェクト: kungpfui/pylzma
PyObject *
pylzma_compress(PyObject *self, PyObject *args, PyObject *kwargs)
{
    PyObject *result = NULL;
    CLzmaEncProps props;
    CLzmaEncHandle encoder=NULL;
    CMemoryOutStream outStream;
    CMemoryInStream inStream;
    Byte header[LZMA_PROPS_SIZE];
    size_t headerSize = LZMA_PROPS_SIZE;
    int res;    
    // possible keywords for this function
    static char *kwlist[] = {"data", "dictionary", "fastBytes", "literalContextBits",
                             "literalPosBits", "posBits", "algorithm", "eos", "multithreading", "matchfinder", NULL};
    int dictionary = 23;         // [0,27], default 23 (8MB)
    int fastBytes = 128;         // [5,273], default 128
    int literalContextBits = 3;  // [0,8], default 3
    int literalPosBits = 0;      // [0,4], default 0
    int posBits = 2;             // [0,4], default 2
    int eos = 1;                 // write "end of stream" marker?
    int multithreading = 1;      // use multithreading if available?
    char *matchfinder = NULL;    // matchfinder algorithm
    int algorithm = 2;
    char *data;
    int length;

    if (!PyArg_ParseTupleAndKeywords(args, kwargs, "s#|iiiiiiiis", kwlist, &data, &length, &dictionary, &fastBytes,
                                                                  &literalContextBits, &literalPosBits, &posBits, &algorithm, &eos, &multithreading, &matchfinder))
        return NULL;
    
    outStream.data = NULL;
    CHECK_RANGE(dictionary,         0,  27, "dictionary must be between 0 and 27");
    CHECK_RANGE(fastBytes,          5, 273, "fastBytes must be between 5 and 273");
    CHECK_RANGE(literalContextBits, 0,   8, "literalContextBits must be between 0 and 8");
    CHECK_RANGE(literalPosBits,     0,   4, "literalPosBits must be between 0 and 4");
    CHECK_RANGE(posBits,            0,   4, "posBits must be between 0 and 4");
    CHECK_RANGE(algorithm,          0,   2, "algorithm must be between 0 and 2");
    
    if (matchfinder != NULL) {
#if (PY_VERSION_HEX >= 0x02050000)
        PyErr_WarnEx(PyExc_DeprecationWarning, "matchfinder selection is deprecated and will be ignored", 1);
#else
        PyErr_Warn(PyExc_DeprecationWarning, "matchfinder selection is deprecated and will be ignored");
#endif
    }
    
    encoder = LzmaEnc_Create(&allocator);
    if (encoder == NULL)
        return PyErr_NoMemory();
    
    CreateMemoryInStream(&inStream, (Byte *) data, length);
    CreateMemoryOutStream(&outStream);
    
    LzmaEncProps_Init(&props);
    
    props.dictSize = 1 << dictionary;
    props.lc = literalContextBits;
    props.lp = literalPosBits;
    props.pb = posBits;
    props.algo = algorithm;
    props.fb = fastBytes;
    // props.btMode = 1;
    // props.numHashBytes = 4;
    // props.mc = 32;
    props.writeEndMark = eos ? 1 : 0;
    props.numThreads = multithreading ? 2 : 1;
    LzmaEncProps_Normalize(&props);
    res = LzmaEnc_SetProps(encoder, &props);
    if (res != SZ_OK) {
        PyErr_Format(PyExc_TypeError, "could not set encoder properties: %d", res);
        goto exit;
    }

    Py_BEGIN_ALLOW_THREADS
    LzmaEnc_WriteProperties(encoder, header, &headerSize);
    if (outStream.s.Write(&outStream, header, headerSize) != headerSize) {
        res = SZ_ERROR_WRITE;
    } else {
        res = LzmaEnc_Encode(encoder, &outStream.s, &inStream.s, NULL, &allocator, &allocator);
    }
    Py_END_ALLOW_THREADS
    if (res != SZ_OK) {
        PyErr_Format(PyExc_TypeError, "Error during compressing: %d", res);
        goto exit;
    }
    
    result = PyBytes_FromStringAndSize((const char *) outStream.data, outStream.size);
    
exit:
    if (encoder != NULL) {
        LzmaEnc_Destroy(encoder, &allocator, &allocator);
    }
    if (outStream.data != NULL) {
        free(outStream.data);
    }
    
    return result;
}