Пример #1
0
Файл: type.c Проект: zillow/ctds
static int SqlNVarChar_init(PyObject* self, PyObject* args, PyObject* kwargs)
{
    const char* utf8bytes = NULL;
    size_t nutf8bytes = 0;
    PyObject* encoded;
    enum TdsType tdstype;

    PyObject* unicode = NULL;
    size_t nchars = 0;
    Py_ssize_t size = (Py_ssize_t)-1;
    static char* s_kwlist[] =
    {
        "value",
        "size",
        NULL
    };
    /* Z# would be ideal here, but is not supported prior to Python 3. */
    if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O|n", s_kwlist, &unicode, &size))
    {
        return -1;
    }

    if (Py_None == unicode)
    {
        /* `None` passed as argument. */
        encoded = PyTuple_GET_ITEM(args, 0);
        Py_INCREF(encoded);
        utf8bytes = NULL;
    }
    else if (PyUnicode_Check(unicode))
    {
        encoded = encode_for_dblib(unicode, &utf8bytes, &nutf8bytes, &nchars);
        if (!encoded)
        {
            return -1;
        }
    }
    else
    {
        PyErr_SetObject(PyExc_TypeError, unicode);
        return -1;
    }
    /*
        FreeTDS doesn't have good support for NCHAR types prior
        to 0.95. Fallback to VARCHAR with somewhat crippled
        functionality.
    */
#if defined(CTDS_USE_NCHARS)
    tdstype = (nchars > TDS_NCHAR_MAX_SIZE) ? TDSNTEXT : TDSNVARCHAR;
#else /* if defined(CTDS_USE_NCHARS) */
    tdstype = (nchars > TDS_CHAR_MAX_SIZE) ? TDSTEXT : TDSVARCHAR;
#endif /* else if defined(CTDS_USE_NCHARS) */

    SqlType_init_variable(self,
                          encoded,
                          tdstype,
                          /*
                              If the size is not explicitly specified, infer it from the value.
                              The NVARCHAR type size must be >= 1.
                          */
                          (int)MAX(1, (((Py_ssize_t)-1 == size) ? nchars : (size_t)size)),
                          (void*)utf8bytes,
                          nutf8bytes,
                          NULL);

    Py_DECREF(encoded);

    return 0;
}
Пример #2
0
static PyObject* do_mkvalue(const char** p_format, va_list* p_va, int flags) noexcept {
    for (;;) {
        switch (*(*p_format)++) {
            case '(':
                return do_mktuple(p_format, p_va, ')', countformat(*p_format, ')'), flags);

            case '[':
                return do_mklist(p_format, p_va, ']', countformat(*p_format, ']'), flags);

            case '{':
                return do_mkdict(p_format, p_va, '}', countformat(*p_format, '}'), flags);

            case 'b':
            case 'B':
            case 'h':
            case 'i':
                return PyInt_FromLong((long)va_arg(*p_va, int));

            case 'H':
                return PyInt_FromLong((long)va_arg(*p_va, unsigned int));

            case 'I': {
                unsigned int n;
                n = va_arg(*p_va, unsigned int);
                if (n > (unsigned long)PyInt_GetMax())
                    return PyLong_FromUnsignedLong((unsigned long)n);
                else
                    return PyInt_FromLong(n);
            }

            case 'n':
#if SIZEOF_SIZE_T != SIZEOF_LONG
                return PyInt_FromSsize_t(va_arg(*p_va, Py_ssize_t));
#endif
            /* Fall through from 'n' to 'l' if Py_ssize_t is long */
            case 'l':
                return PyInt_FromLong(va_arg(*p_va, long));

            case 'd':
                return PyFloat_FromDouble(va_arg(*p_va, double));

            case 'N':
            case 'S':
            case 'O':
                if (**p_format == '&') {
                    typedef PyObject* (*converter)(void*);
                    converter func = va_arg(*p_va, converter);
                    void* arg = va_arg(*p_va, void*);
                    ++*p_format;
                    return (*func)(arg);
                } else {
                    PyObject* v;
                    v = va_arg(*p_va, PyObject*);
                    if (v != NULL) {
                        if (*(*p_format - 1) != 'N')
                            Py_INCREF(v);
                    } else if (!PyErr_Occurred())
                        /* If a NULL was passed
                         * because a call that should
                         * have constructed a value
                         * failed, that's OK, and we
                         * pass the error on; but if
                         * no error occurred it's not
                         * clear that the caller knew
                         * what she was doing. */
                        PyErr_SetString(PyExc_SystemError, "NULL object passed to Py_BuildValue");
                    return v;
                }

            case 's':
            case 'z': {
                PyObject* v;
                char* str = va_arg(*p_va, char*);
                Py_ssize_t n;
                if (**p_format == '#') {
                    ++*p_format;
                    if (flags & FLAG_SIZE_T)
                        n = va_arg(*p_va, Py_ssize_t);
                    else
                        n = va_arg(*p_va, int);
                } else
                    n = -1;
                if (str == NULL) {
                    v = Py_None;
                    Py_INCREF(v);
                } else {
                    if (n < 0) {
                        size_t m = strlen(str);
                        if (m > PY_SSIZE_T_MAX) {
                            PyErr_SetString(PyExc_OverflowError, "string too long for Python string");
                            return NULL;
                        }
                        n = (Py_ssize_t)m;
                    }
                    v = PyString_FromStringAndSize(str, n);
                }
                return v;
            }
Пример #3
0
void initofx(void)
{
  PyObject *mod = Py_InitModule("ofx", PyOFX_Methods);
  
  PyModule_AddIntConstant(mod, "TypeImageEffectHost", ofx::TypeImageEffectHost);
  PyModule_AddIntConstant(mod, "TypeImageEffect", ofx::TypeImageEffect);
  PyModule_AddIntConstant(mod, "TypeImageEffectInstance", ofx::TypeImageEffectInstance);
  PyModule_AddIntConstant(mod, "TypeParameter", ofx::TypeParameter);
  PyModule_AddIntConstant(mod, "TypeParameterInstance", ofx::TypeParameterInstance);
  PyModule_AddIntConstant(mod, "TypeClip", ofx::TypeClip);
  PyModule_AddIntConstant(mod, "TypeImage", ofx::TypeImage);
  
  PyModule_AddIntConstant(mod, "BitDepthNone", ofx::BitDepthNone);
  PyModule_AddIntConstant(mod, "BitDepthByte", ofx::BitDepthByte);
  PyModule_AddIntConstant(mod, "BitDepthShort", ofx::BitDepthShort);
  PyModule_AddIntConstant(mod, "BitDepthFloat", ofx::BitDepthFloat);
#ifdef OFX_API_1_3
  PyModule_AddIntConstant(mod, "BitDepthHalf", ofx::BitDepthHalf);
#endif
  
  PyModule_AddIntConstant(mod, "ImageComponentNone", ofx::ImageComponentNone);
#ifdef OFX_API_1_2
  PyModule_AddIntConstant(mod, "ImageComponentRGB", ofx::ImageComponentRGB);
#endif
  PyModule_AddIntConstant(mod, "ImageComponentRGBA", ofx::ImageComponentRGBA);
  PyModule_AddIntConstant(mod, "ImageComponentAlpha", ofx::ImageComponentAlpha);
  PyModule_AddIntConstant(mod, "ImageComponentYUVA", ofx::ImageComponentYUVA);
  
  PyModule_AddIntConstant(mod, "ImageFieldNone", ofx::ImageFieldNone);
  PyModule_AddIntConstant(mod, "ImageFieldBoth", ofx::ImageFieldBoth);
  PyModule_AddIntConstant(mod, "ImageFieldLower", ofx::ImageFieldLower);
  PyModule_AddIntConstant(mod, "ImageFieldUpper", ofx::ImageFieldUpper);
  
  PyModule_AddIntConstant(mod, "ImageFieldExtractBoth", ofx::ImageFieldExtractBoth);
  PyModule_AddIntConstant(mod, "ImageFieldExtractSingle", ofx::ImageFieldExtractSingle);
  PyModule_AddIntConstant(mod, "ImageFieldExtractDoubled", ofx::ImageFieldExtractDoubled);
  
  PyModule_AddIntConstant(mod, "ImageFieldOrderNone", ofx::ImageFieldOrderNone);
  PyModule_AddIntConstant(mod, "ImageFieldOrderLower", ofx::ImageFieldOrderLower);
  PyModule_AddIntConstant(mod, "ImageFieldOrderUpper", ofx::ImageFieldOrderUpper);
  
  PyModule_AddIntConstant(mod, "ImageOpaque", ofx::ImageOpaque);
  PyModule_AddIntConstant(mod, "ImagePreMultiplied", ofx::ImagePreMultiplied);
  PyModule_AddIntConstant(mod, "ImageUnPreMultiplied", ofx::ImageUnPreMultiplied);
  
  PyModule_AddIntConstant(mod, "ImageEffectContextGenerator", ofx::ImageEffectContextGenerator);
  PyModule_AddIntConstant(mod, "ImageEffectContextFilter", ofx::ImageEffectContextFilter);
  PyModule_AddIntConstant(mod, "ImageEffectContextTransition", ofx::ImageEffectContextTransition);
  PyModule_AddIntConstant(mod, "ImageEffectContextPaint", ofx::ImageEffectContextPaint);
  PyModule_AddIntConstant(mod, "ImageEffectContextGeneral", ofx::ImageEffectContextGeneral);
  PyModule_AddIntConstant(mod, "ImageEffectContextRetimer", ofx::ImageEffectContextRetimer);
  
  PyModule_AddIntConstant(mod, "RenderThreadUnsafe", ofx::RenderThreadUnsafe);
  PyModule_AddIntConstant(mod, "RenderThreadInstanceSafe", ofx::RenderThreadInstanceSafe);
  PyModule_AddIntConstant(mod, "RenderThreadFullySafe", ofx::RenderThreadFullySafe);
  
  PyModule_AddIntConstant(mod, "ParamTypeInteger", ofx::ParamTypeInteger);
  PyModule_AddIntConstant(mod, "ParamTypeDouble", ofx::ParamTypeDouble);
  PyModule_AddIntConstant(mod, "ParamTypeBoolean", ofx::ParamTypeBoolean);
  PyModule_AddIntConstant(mod, "ParamTypeChoice", ofx::ParamTypeChoice);
  PyModule_AddIntConstant(mod, "ParamTypeRGBA", ofx::ParamTypeRGBA);
  PyModule_AddIntConstant(mod, "ParamTypeRGB", ofx::ParamTypeRGB);
  PyModule_AddIntConstant(mod, "ParamTypeDouble2D", ofx::ParamTypeDouble2D);
  PyModule_AddIntConstant(mod, "ParamTypeInteger2D", ofx::ParamTypeInteger2D);
  PyModule_AddIntConstant(mod, "ParamTypeDouble3D", ofx::ParamTypeDouble3D);
  PyModule_AddIntConstant(mod, "ParamTypeInteger3D", ofx::ParamTypeInteger3D);
  PyModule_AddIntConstant(mod, "ParamTypeString", ofx::ParamTypeString);
  PyModule_AddIntConstant(mod, "ParamTypeCustom", ofx::ParamTypeCustom);
  PyModule_AddIntConstant(mod, "ParamTypeGroup", ofx::ParamTypeGroup);
  PyModule_AddIntConstant(mod, "ParamTypePage", ofx::ParamTypePage);
  PyModule_AddIntConstant(mod, "ParamTypePushButton", ofx::ParamTypePushButton);
#ifdef OFX_API_1_2
  PyModule_AddIntConstant(mod, "ParamTypeParametric", ofx::ParamTypeParametric);
#endif
  
  PyModule_AddIntConstant(mod, "ParamInvalidateValueChange", ofx::ParamInvalidateValueChange);
  PyModule_AddIntConstant(mod, "ParamInvalidateValueChangeToEnd", ofx::ParamInvalidateValueChangeToEnd);
  PyModule_AddIntConstant(mod, "ParamInvalidateAll", ofx::ParamInvalidateAll);
  
  PyModule_AddIntConstant(mod, "StringParamSingleLine", ofx::StringParamSingleLine);
  PyModule_AddIntConstant(mod, "StringParamMultiLine", ofx::StringParamMultiLine);
  PyModule_AddIntConstant(mod, "StringParamFilePath", ofx::StringParamFilePath);
  PyModule_AddIntConstant(mod, "StringParamDirectoryPath", ofx::StringParamDirectoryPath);
  PyModule_AddIntConstant(mod, "StringParamLabel", ofx::StringParamLabel);
#ifdef OFX_API_1_3
  PyModule_AddIntConstant(mod, "StringParamRichText", ofx::StringParamRichText);
#endif
  
  PyModule_AddIntConstant(mod, "DoubleParamPlain", ofx::DoubleParamPlain);
  PyModule_AddIntConstant(mod, "DoubleParamAngle", ofx::DoubleParamAngle);
  PyModule_AddIntConstant(mod, "DoubleParamScale", ofx::DoubleParamScale);
  PyModule_AddIntConstant(mod, "DoubleParamTime", ofx::DoubleParamTime);
  PyModule_AddIntConstant(mod, "DoubleParamAbsoluteTime", ofx::DoubleParamAbsoluteTime);
  PyModule_AddIntConstant(mod, "DoubleParamNormalisedX", ofx::DoubleParamNormalisedX);
  PyModule_AddIntConstant(mod, "DoubleParamNormalisedXAbsolute", ofx::DoubleParamNormalisedXAbsolute);
  PyModule_AddIntConstant(mod, "DoubleParamNormalisedY", ofx::DoubleParamNormalisedY);
  PyModule_AddIntConstant(mod, "DoubleParamNormalisedYAbsolute", ofx::DoubleParamNormalisedYAbsolute);
  PyModule_AddIntConstant(mod, "DoubleParamNormalisedXY", ofx::DoubleParamNormalisedXY);
  PyModule_AddIntConstant(mod, "DoubleParamNormalisedXYAbsolute", ofx::DoubleParamNormalisedXYAbsolute);
#ifdef OFX_API_1_2
  PyModule_AddIntConstant(mod, "DoubleParamX", ofx::DoubleParamX);
  PyModule_AddIntConstant(mod, "DoubleParamXAbsolute", ofx::DoubleParamXAbsolute);
  PyModule_AddIntConstant(mod, "DoubleParamY", ofx::DoubleParamY);
  PyModule_AddIntConstant(mod, "DoubleParamYAbsolute", ofx::DoubleParamYAbsolute);
  PyModule_AddIntConstant(mod, "DoubleParamXY", ofx::DoubleParamXY);
  PyModule_AddIntConstant(mod, "DoubleParamXYAbsolute", ofx::DoubleParamXYAbsolute);
#endif
  
#ifdef OFX_API_1_2
  PyModule_AddIntConstant(mod, "CoordinatesCanonical", ofx::CoordinatesCanonical);
  PyModule_AddIntConstant(mod, "CoordinatesNormalised", ofx::CoordinatesNormalised);
#endif
  
  PyModule_AddIntConstant(mod, "KeyDirectionPrev", ofx::KeyDirectionPrev);
  PyModule_AddIntConstant(mod, "KeyDirectionExact", ofx::KeyDirectionExact);
  PyModule_AddIntConstant(mod, "KeyDirectionNext", ofx::KeyDirectionNext);
  
  PyModule_AddIntConstant(mod, "MessageTypeFatal", ofx::MessageTypeFatal);
  PyModule_AddIntConstant(mod, "MessageTypeError", ofx::MessageTypeError);
  PyModule_AddIntConstant(mod, "MessageTypeMessage", ofx::MessageTypeMessage);
  PyModule_AddIntConstant(mod, "MessageTypeLog", ofx::MessageTypeLog);
  PyModule_AddIntConstant(mod, "MessageTypeQuestion", ofx::MessageTypeQuestion);
#ifdef OFX_API_1_2
  PyModule_AddIntConstant(mod, "MessageTypeWarning", ofx::MessageTypeWarning);
#endif
  
  PyModule_AddIntConstant(mod, "ChangeUserEdited", ofx::ChangeUserEdited);
  PyModule_AddIntConstant(mod, "ChangePluginEdited", ofx::ChangePluginEdited);
  PyModule_AddIntConstant(mod, "ChangeTime", ofx::ChangeTime);
  
  PyModule_AddIntConstant(mod, "ActionLoad", ofx::ActionLoad);
  PyModule_AddIntConstant(mod, "ActionInteractLoseFocus", ofx::ActionInteractLoseFocus);
  PyModule_AddIntConstant(mod, "ActionInteractGainFocus", ofx::ActionInteractGainFocus);
  PyModule_AddIntConstant(mod, "ActionInteractKeyRepeat", ofx::ActionInteractKeyRepeat);
  PyModule_AddIntConstant(mod, "ActionInteractKeyUp", ofx::ActionInteractKeyUp);
  PyModule_AddIntConstant(mod, "ActionInteractKeyDown", ofx::ActionInteractKeyDown);
  PyModule_AddIntConstant(mod, "ActionInteractPenUp", ofx::ActionInteractPenUp);
  PyModule_AddIntConstant(mod, "ActionInteractPenDown", ofx::ActionInteractPenDown);
  PyModule_AddIntConstant(mod, "ActionInteractPenMotion", ofx::ActionInteractPenMotion);
  PyModule_AddIntConstant(mod, "ActionInteractDraw", ofx::ActionInteractDraw);
  PyModule_AddIntConstant(mod, "ActionImageEffectGetTimeDomain", ofx::ActionImageEffectGetTimeDomain);
  PyModule_AddIntConstant(mod, "ActionImageEffectGetClipPreferences", ofx::ActionImageEffectGetClipPreferences);
  PyModule_AddIntConstant(mod, "ActionImageEffectEndSequenceRender", ofx::ActionImageEffectEndSequenceRender);
  PyModule_AddIntConstant(mod, "ActionImageEffectBeginSequenceRender", ofx::ActionImageEffectBeginSequenceRender);
  PyModule_AddIntConstant(mod, "ActionImageEffectRender", ofx::ActionImageEffectRender);
  PyModule_AddIntConstant(mod, "ActionImageEffectIsIdentity", ofx::ActionImageEffectIsIdentity);
  PyModule_AddIntConstant(mod, "ActionImageEffectGetFramesNeeded", ofx::ActionImageEffectGetFramesNeeded);
  PyModule_AddIntConstant(mod, "ActionImageEffectGetRoI", ofx::ActionImageEffectGetRoI);
  PyModule_AddIntConstant(mod, "ActionImageEffectGetRoD", ofx::ActionImageEffectGetRoD);
  PyModule_AddIntConstant(mod, "ActionImageEffectDescribeInContext", ofx::ActionImageEffectDescribeInContext);
  PyModule_AddIntConstant(mod, "ActionEndInstanceEdit", ofx::ActionEndInstanceEdit);
  PyModule_AddIntConstant(mod, "ActionBeginInstanceEdit", ofx::ActionBeginInstanceEdit);
  PyModule_AddIntConstant(mod, "ActionUnload", ofx::ActionUnload);
  PyModule_AddIntConstant(mod, "ActionDescribe", ofx::ActionDescribe);
  PyModule_AddIntConstant(mod, "ActionCreateInstance", ofx::ActionCreateInstance);
  PyModule_AddIntConstant(mod, "ActionDestroyInstance", ofx::ActionDestroyInstance);
  PyModule_AddIntConstant(mod, "ActionInstanceChanged", ofx::ActionInstanceChanged);
  PyModule_AddIntConstant(mod, "ActionBeginInstanceChanged", ofx::ActionBeginInstanceChanged);
  PyModule_AddIntConstant(mod, "ActionEndInstanceChanged", ofx::ActionEndInstanceChanged);
  PyModule_AddIntConstant(mod, "ActionPurgeCaches", ofx::ActionPurgeCaches);
  PyModule_AddIntConstant(mod, "ActionSyncPrivateData", ofx::ActionSyncPrivateData);
#ifdef OFX_API_1_3
  PyModule_AddIntConstant(mod, "ActionOpenGLContextAttached", ofx::ActionOpenGLContextAttached);
  PyModule_AddIntConstant(mod, "ActionOpenGLContextDetached", ofx::ActionOpenGLContextAttached);
#endif
  
  PyModule_AddIntConstant(mod, "SequentialRenderNotNeeded", ofx::SequentialRenderNotNeeded);
  PyModule_AddIntConstant(mod, "SequentialRenderRequired", ofx::SequentialRenderRequired);
  PyModule_AddIntConstant(mod, "SequentialRenderUnknown", ofx::SequentialRenderUnknown);
  PyModule_AddIntConstant(mod, "SequentialRenderAlways", ofx::SequentialRenderAlways);
#ifdef OFX_API_1_2
  PyModule_AddIntConstant(mod, "SequentialRenderIfPossible", ofx::SequentialRenderIfPossible);
  PyModule_AddIntConstant(mod, "SequentialRenderSometimes", ofx::SequentialRenderSometimes);
#endif

  PyModule_AddIntConstant(mod, "StatOK", kOfxStatOK);
  PyModule_AddIntConstant(mod, "StatFailed", kOfxStatFailed);
  PyModule_AddIntConstant(mod, "StatErrFatal", kOfxStatErrFatal);
  PyModule_AddIntConstant(mod, "StatErrUnknown", kOfxStatErrUnknown);
  PyModule_AddIntConstant(mod, "StatErrMissingHostFeature", kOfxStatErrMissingHostFeature);
  PyModule_AddIntConstant(mod, "StatErrUnsupported", kOfxStatErrUnsupported);
  PyModule_AddIntConstant(mod, "StatErrExists", kOfxStatErrExists);
  PyModule_AddIntConstant(mod, "StatErrFormat", kOfxStatErrFormat);
  PyModule_AddIntConstant(mod, "StatErrMemory", kOfxStatErrMemory);
  PyModule_AddIntConstant(mod, "StatErrBadHandle", kOfxStatErrBadHandle);
  PyModule_AddIntConstant(mod, "StatErrBadIndex", kOfxStatErrBadIndex);
  PyModule_AddIntConstant(mod, "StatErrValue", kOfxStatErrValue);
  PyModule_AddIntConstant(mod, "StatErrImageFormat", kOfxStatErrImageFormat);
  PyModule_AddIntConstant(mod, "StatReplyYes", kOfxStatReplyYes);
  PyModule_AddIntConstant(mod, "StatReplyNo", kOfxStatReplyNo);
  PyModule_AddIntConstant(mod, "StatReplyDefault", kOfxStatReplyDefault);
#ifdef OFX_API_1_3
  PyModule_AddIntConstant(mod, "StatGLOutOfMemory", kOfxStatGLOutOfMemory);
  PyModule_AddIntConstant(mod, "StatGLRenderFailed", kOfxStatGLRenderFailed);
#endif
  
  PyModule_AddStringConstant(mod, "PageSkipRow", kOfxParamPageSkipRow);
  PyModule_AddStringConstant(mod, "PageSkipColumn", kOfxParamPageSkipColumn);
  
  PyModule_AddIntConstant(mod, "MajorVersion", ofx::MajorVersion);
  PyModule_AddIntConstant(mod, "MinorVersion", ofx::MinorVersion);
  PyModule_AddIntConstant(mod, "PatchVersion", ofx::PatchVersion);
  PyModule_AddStringConstant(mod, "Version", ofx::Version);
  
  INIT_TYPE(PyOFXActionArgumentsType, "ofx.ActionArguments", PyOFXActionArguments);
  PyOFXActionArgumentsType.tp_flags = Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE;
  PyOFXActionArgumentsType.tp_new = PyOFXActionArguments_New;
  PyOFXActionArgumentsType.tp_init = PyOFXActionArguments_Init;
  PyOFXActionArgumentsType.tp_dealloc = PyOFXActionArguments_Delete;
  PyOFXActionArgumentsType.tp_setattro = PyOFXActionArguments_SetAttr; //PyObject_GenericSetAttr;
  PyOFXActionArgumentsType.tp_getattro = PyOFXActionArguments_GetAttr; //PyObject_GenericGetAttr;
  if (PyType_Ready(&PyOFXActionArgumentsType) < 0)
  {
    std::cerr << "Failed to intiialize ofx.ActionArguments class" << std::endl;
    Py_DECREF(mod);
    return;
  }
  
  INIT_TYPE(PyOFXRectIType, "ofx.RectI", PyOFXRectI);
  PyOFXRectIType.tp_flags = Py_TPFLAGS_DEFAULT;
  PyOFXRectIType.tp_new = PyOFXRectI_New;
  PyOFXRectIType.tp_init = PyOFXRectI_Init;
  PyOFXRectIType.tp_dealloc = PyOFXRectI_Delete;
  PyOFXRectIType.tp_getset = PyOFXRectI_GetSeters;
  if (PyType_Ready(&PyOFXRectIType) < 0)
  {
    std::cerr << "Failed to intiialize ofx.RectI class" << std::endl;
    Py_DECREF(mod);
    return;
  }
  
  INIT_TYPE(PyOFXRectDType, "ofx.RectD", PyOFXRectD);
  PyOFXRectDType.tp_flags = Py_TPFLAGS_DEFAULT;
  PyOFXRectDType.tp_new = PyOFXRectD_New;
  PyOFXRectDType.tp_init = PyOFXRectD_Init;
  PyOFXRectDType.tp_dealloc = PyOFXRectD_Delete;
  PyOFXRectDType.tp_getset = PyOFXRectD_GetSeters;
  if (PyType_Ready(&PyOFXRectDType) < 0)
  {
    std::cerr << "Failed to intiialize ofx.RectD class" << std::endl;
    Py_DECREF(mod);
    return;
  }
  
  INIT_TYPE(PyOFXRangeIType, "ofx.RangeI", PyOFXRangeI);
  PyOFXRangeIType.tp_flags = Py_TPFLAGS_DEFAULT;
  PyOFXRangeIType.tp_new = PyOFXRangeI_New;
  PyOFXRangeIType.tp_init = PyOFXRangeI_Init;
  PyOFXRangeIType.tp_dealloc = PyOFXRangeI_Delete;
  PyOFXRangeIType.tp_getset = PyOFXRangeI_GetSeters;
  if (PyType_Ready(&PyOFXRangeIType) < 0)
  {
    std::cerr << "Failed to intiialize ofx.RangeI class" << std::endl;
    Py_DECREF(mod);
    return;
  }
  
  INIT_TYPE(PyOFXRangeDType, "ofx.RangeD", PyOFXRangeD);
  PyOFXRangeDType.tp_flags = Py_TPFLAGS_DEFAULT;
  PyOFXRangeDType.tp_new = PyOFXRangeD_New;
  PyOFXRangeDType.tp_init = PyOFXRangeD_Init;
  PyOFXRangeDType.tp_dealloc = PyOFXRangeD_Delete;
  PyOFXRangeDType.tp_getset = PyOFXRangeD_GetSeters;
  if (PyType_Ready(&PyOFXRangeDType) < 0)
  {
    std::cerr << "Failed to intiialize ofx.RangeD class" << std::endl;
    Py_DECREF(mod);
    return;
  }
  
  Py_INCREF(&PyOFXActionArgumentsType);
  PyModule_AddObject(mod, "ActionArguments", (PyObject*)&PyOFXActionArgumentsType);
  
  Py_INCREF(&PyOFXRectIType);
  PyModule_AddObject(mod, "RectI", (PyObject*)&PyOFXRectIType);
  
  Py_INCREF(&PyOFXRectDType);
  PyModule_AddObject(mod, "RectD", (PyObject*)&PyOFXRectDType);
  
  Py_INCREF(&PyOFXRangeIType);
  PyModule_AddObject(mod, "RangeI", (PyObject*)&PyOFXRangeIType);
  
  Py_INCREF(&PyOFXRangeDType);
  PyModule_AddObject(mod, "RangeD", (PyObject*)&PyOFXRangeDType);
  
  Py_INCREF(&PyOFXRangeDType);
  PyModule_AddObject(mod, "FrameRange", (PyObject*)&PyOFXRangeDType);
  
  if (!PyOFX_InitException(mod))
  {
    std::cerr << "Failed to intiialize exception classes" << std::endl;
    Py_DECREF(mod);
    return;
  }
  
  if (!PyOFX_InitHandle(mod))
  {
    std::cerr << "Failed to intiialize handle classes" << std::endl;
    Py_DECREF(mod);
    return;
  }
  
  if (!PyOFX_InitPixel(mod))
  {
    std::cerr << "Failed to intiialize pixel classes" << std::endl;
    Py_DECREF(mod);
    return;
  }
  
  if (!PyOFX_InitMessage(mod))
  {
    std::cerr << "Failed to intiialize message classes" << std::endl;
    Py_DECREF(mod);
    return;
  }
  
  if (!PyOFX_InitMemory(mod))
  {
    std::cerr << "Failed to intiialize memory classes" << std::endl;
    Py_DECREF(mod);
    return;
  }
  
  if (!PyOFX_InitProgress(mod))
  {
    std::cerr << "Failed to intiialize progress classes" << std::endl;
    Py_DECREF(mod);
    return;
  }
  
  if (!PyOFX_InitTimeLine(mod))
  {
    std::cerr << "Failed to intiialize timeline classes" << std::endl;
    Py_DECREF(mod);
    return;
  }
  
  if (!PyOFX_InitProperty(mod))
  {
    std::cerr << "Failed to intiialize property classes" << std::endl;
    Py_DECREF(mod);
    return;
  }
  
  if (!PyOFX_InitParameter(mod))
  {
    std::cerr << "Failed to intiialize parameter classes" << std::endl;
    Py_DECREF(mod);
    return;
  }
  
  if (!PyOFX_InitParameterSet(mod))
  {
    std::cerr << "Failed to intiialize parameterset classes" << std::endl;
    Py_DECREF(mod);
    return;
  }
  
  if (!PyOFX_InitHost(mod))
  {
    std::cerr << "Failed to intiialize host classes" << std::endl;
    Py_DECREF(mod);
    return;
  }
  
  if (!PyOFX_InitImage(mod))
  {
    std::cerr << "Failed to intiialize image classes" << std::endl;
    Py_DECREF(mod);
    return;
  }
  
  if (!PyOFX_InitClip(mod))
  {
    std::cerr << "Failed to intiialize clip classes" << std::endl;
    Py_DECREF(mod);
    return;
  }
  
  if (!PyOFX_InitInteract(mod))
  {
    std::cerr << "Failed to intiialize interact classes" << std::endl;
    Py_DECREF(mod);
    return;
  }
  
  if (!PyOFX_InitImageEffect(mod))
  {
    std::cerr << "Failed to intiialize imageeffect classes" << std::endl;
    Py_DECREF(mod);
    return;
  }
  
  if (!PyOFX_InitPlugin(mod))
  {
    std::cerr << "Failed to intiialize plugin classes" << std::endl;
    Py_DECREF(mod);
    return;
  }
  
  if (!PyOFX_InitTest(mod))
  {
    std::cerr << "Failed to intiialize test classes" << std::endl;
    Py_DECREF(mod);
    return;
  }
}
Пример #4
0
static int __pyx_tp_clear_5cache_Cache(PyObject *o) {
  struct __pyx_obj_5cache_Cache *p = (struct __pyx_obj_5cache_Cache *)o;
  Py_XDECREF(p->list);
  p->list = Py_None; Py_INCREF(p->list);
  return 0;
}
Пример #5
0
		PyObject* AddRef() {
			if(p) {
				Py_INCREF(p);
			}
			return p;
		}
Пример #6
0
/*
 * bitfields extension:
 * bitsize != 0: this is a bit field.
 * pbitofs points to the current bit offset, this will be updated.
 * prev_desc points to the type of the previous bitfield, if any.
 */
PyObject *
CField_FromDesc(PyObject *desc, Py_ssize_t index,
		Py_ssize_t *pfield_size, int bitsize, int *pbitofs,
		Py_ssize_t *psize, Py_ssize_t *poffset, Py_ssize_t *palign,
		int pack, int big_endian)
{
	CFieldObject *self;
	PyObject *proto;
	Py_ssize_t size, align, length;
	SETFUNC setfunc = NULL;
	GETFUNC getfunc = NULL;
	StgDictObject *dict;
	int fieldtype;
#define NO_BITFIELD 0
#define NEW_BITFIELD 1
#define CONT_BITFIELD 2
#define EXPAND_BITFIELD 3

	self = (CFieldObject *)PyObject_CallObject((PyObject *)&CField_Type,
						   NULL);
	if (self == NULL)
		return NULL;
	dict = PyType_stgdict(desc);
	if (!dict) {
		PyErr_SetString(PyExc_TypeError,
				"has no _stginfo_");
		Py_DECREF(self);
		return NULL;
	}
	if (bitsize /* this is a bitfield request */
	    && *pfield_size /* we have a bitfield open */
#ifdef MS_WIN32
	    /* MSVC, GCC with -mms-bitfields */
	    && dict->size * 8 == *pfield_size
#else
	    /* GCC */
	    && dict->size * 8 <= *pfield_size 
#endif
	    && (*pbitofs + bitsize) <= *pfield_size) {
		/* continue bit field */
		fieldtype = CONT_BITFIELD;
#ifndef MS_WIN32
	} else if (bitsize /* this is a bitfield request */
	    && *pfield_size /* we have a bitfield open */
	    && dict->size * 8 >= *pfield_size
	    && (*pbitofs + bitsize) <= dict->size * 8) {
		/* expand bit field */
		fieldtype = EXPAND_BITFIELD;
#endif
	} else if (bitsize) {
		/* start new bitfield */
		fieldtype = NEW_BITFIELD;
		*pbitofs = 0;
		*pfield_size = dict->size * 8;
	} else {
		/* not a bit field */
		fieldtype = NO_BITFIELD;
		*pbitofs = 0;
		*pfield_size = 0;
	}

	size = dict->size;
	length = dict->length;
	proto = desc;

	/*  Field descriptors for 'c_char * n' are be scpecial cased to
	    return a Python string instead of an Array object instance...
	*/
	if (ArrayTypeObject_Check(proto)) {
		StgDictObject *adict = PyType_stgdict(proto);
		StgDictObject *idict;
		if (adict && adict->proto) {
			idict = PyType_stgdict(adict->proto);
			if (!idict) {
				PyErr_SetString(PyExc_TypeError,
						"has no _stginfo_");
				Py_DECREF(self);
				return NULL;
			}
			if (idict->getfunc == getentry("c")->getfunc) {
				struct fielddesc *fd = getentry("s");
				getfunc = fd->getfunc;
				setfunc = fd->setfunc;
			}
#ifdef CTYPES_UNICODE
			if (idict->getfunc == getentry("u")->getfunc) {
				struct fielddesc *fd = getentry("U");
				getfunc = fd->getfunc;
				setfunc = fd->setfunc;
			}
#endif
		}
	}

	self->setfunc = setfunc;
	self->getfunc = getfunc;
	self->index = index;

	Py_INCREF(proto);
	self->proto = proto;

	switch (fieldtype) {
	case NEW_BITFIELD:
		if (big_endian)
			self->size = (bitsize << 16) + *pfield_size - *pbitofs - bitsize;
		else
			self->size = (bitsize << 16) + *pbitofs;
		*pbitofs = bitsize;
		/* fall through */
	case NO_BITFIELD:
		if (pack)
			align = min(pack, dict->align);
		else
			align = dict->align;
		if (align && *poffset % align) {
			Py_ssize_t delta = align - (*poffset % align);
			*psize += delta;
			*poffset += delta;
		}

		if (bitsize == 0)
			self->size = size;
		*psize += size;

		self->offset = *poffset;
		*poffset += size;

		*palign = align;
		break;

	case EXPAND_BITFIELD:
		*poffset += dict->size - *pfield_size/8;
		*psize += dict->size - *pfield_size/8;

		*pfield_size = dict->size * 8;

		if (big_endian)
			self->size = (bitsize << 16) + *pfield_size - *pbitofs - bitsize;
		else
			self->size = (bitsize << 16) + *pbitofs;

		self->offset = *poffset - size; /* poffset is already updated for the NEXT field */
		*pbitofs += bitsize;
		break;

	case CONT_BITFIELD:
		if (big_endian)
			self->size = (bitsize << 16) + *pfield_size - *pbitofs - bitsize;
		else
			self->size = (bitsize << 16) + *pbitofs;

		self->offset = *poffset - size; /* poffset is already updated for the NEXT field */
		*pbitofs += bitsize;
		break;
	}

	return (PyObject *)self;
}
Пример #7
0
static PyObject *
structseq_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
    PyObject *arg = NULL;
    PyObject *dict = NULL;
    PyObject *ob;
    PyStructSequence *res = NULL;
    Py_ssize_t len, min_len, max_len, i, n_unnamed_fields;
    static char *kwlist[] = {"sequence", "dict", 0};

    if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O:structseq",
                                     kwlist, &arg, &dict))
        return NULL;

    arg = PySequence_Fast(arg, "constructor requires a sequence");

    if (!arg) {
        return NULL;
    }

    if (dict && !PyDict_Check(dict)) {
        PyErr_Format(PyExc_TypeError,
                     "%.500s() takes a dict as second arg, if any",
                     type->tp_name);
        Py_DECREF(arg);
        return NULL;
    }

    len = PySequence_Fast_GET_SIZE(arg);
    min_len = VISIBLE_SIZE_TP(type);
    max_len = REAL_SIZE_TP(type);
    n_unnamed_fields = UNNAMED_FIELDS_TP(type);

    if (min_len != max_len) {
        if (len < min_len) {
            PyErr_Format(PyExc_TypeError,
           "%.500s() takes an at least %zd-sequence (%zd-sequence given)",
                                 type->tp_name, min_len, len);
                    Py_DECREF(arg);
                    return NULL;
        }

        if (len > max_len) {
            PyErr_Format(PyExc_TypeError,
           "%.500s() takes an at most %zd-sequence (%zd-sequence given)",
                                 type->tp_name, max_len, len);
                    Py_DECREF(arg);
                    return NULL;
        }
    }
    else {
        if (len != min_len) {
            PyErr_Format(PyExc_TypeError,
           "%.500s() takes a %zd-sequence (%zd-sequence given)",
                                 type->tp_name, min_len, len);
                    Py_DECREF(arg);
                    return NULL;
        }
    }

    res = (PyStructSequence*) PyStructSequence_New(type);
    if (res == NULL) {
        return NULL;
    }
    for (i = 0; i < len; ++i) {
        PyObject *v = PySequence_Fast_GET_ITEM(arg, i);
        Py_INCREF(v);
        res->ob_item[i] = v;
    }
    for (; i < max_len; ++i) {
        if (dict && (ob = PyDict_GetItemString(
            dict, type->tp_members[i-n_unnamed_fields].name))) {
        }
        else {
            ob = Py_None;
        }
        Py_INCREF(ob);
        res->ob_item[i] = ob;
    }

    Py_DECREF(arg);
    return (PyObject*) res;
}
Пример #8
0
Файл: msaio.c Проект: Wyss/ProDy
static int parseLabel(PyObject *labels, PyObject *mapping, char *line,
                      int length) {

    /* Append label to *labels*, extract identifier, and index label
       position in the list. Return 1 when successful, 0 on failure. */

    int i, ch, slash = 0, dash = 0;//, ipipe = 0, pipes[4] = {0, 0, 0, 0};

    for (i = 0; i < length; i++) {
        ch = line[i];
        if (ch < 32 && ch != 20)
            break;
        else if (ch == '/' && slash == 0 && dash == 0)
            slash = i;
        else if (ch == '-' && slash > 0 && dash == 0)
            dash = i;
        //else if (line[i] == '|' && ipipe < 4)
        //    pipes[ipipe++] = i;
    }

    PyObject *label, *index;
    #if PY_MAJOR_VERSION >= 3
    label = PyUnicode_FromStringAndSize(line, i);
    index = PyLong_FromSsize_t(PyList_Size(labels));
    #else
    label = PyString_FromStringAndSize(line, i);
    index = PyInt_FromSsize_t(PyList_Size(labels));
    #endif

    if (!label || !index || PyList_Append(labels, label) < 0) {
        PyObject *none = Py_None;
        PyList_Append(labels, none);
        Py_DECREF(none);

        Py_XDECREF(index);
        Py_XDECREF(label);
        return 0;
    }

    if (slash > 0 && dash > slash) {
        Py_DECREF(label);
        #if PY_MAJOR_VERSION >= 3
        label = PyUnicode_FromStringAndSize(line, slash);
        #else
        label = PyString_FromStringAndSize(line, slash);
        #endif
    }

    if (PyDict_Contains(mapping, label)) {
        PyObject *item = PyDict_GetItem(mapping, label); /* borrowed */
        if (PyList_Check(item)) {
            PyList_Append(item, index);
            Py_DECREF(index);
        } else {
            PyObject *list = PyList_New(2); /* new reference */
            PyList_SetItem(list, 0, item);
            Py_INCREF(item);
            PyList_SetItem(list, 1, index); /* steals reference, no DECREF */
            PyDict_SetItem(mapping, label, list);
            Py_DECREF(list);
        }
    } else {
        PyDict_SetItem(mapping, label, index);
        Py_DECREF(index);
    }

    Py_DECREF(label);
    return 1;
}
Пример #9
0
CompiledPythonFragment * getCompiledCode( Table * table, int pkey, const QString & pCode, const QString & codeName )
{
	CompiledPythonFragment * ret = 0;
	ensurePythonInitialized();
	// Create the key for looking up the code fragment in the cache
	QPair<Table*,int> codeKey = qMakePair(table,pkey);

	// Return the cached code fragment, if the code still matches
	if( codeCache.contains( codeKey ) ) {
		CompiledPythonFragment * frag = &codeCache[codeKey];
		// This should actually be very fast because of QString's
		// implicit sharing, should usually just be a pointer comparison
		if( frag->codeString == pCode )
			return frag;

		// Remove from cache if the fragment is out of date
		// TODO: This should free any references and remove the module
		// this isn't a big deal though, since code fragments won't
		// change very often during program execution
		codeCache.remove( codeKey );
	}

	if( pCode.isEmpty() )
		return 0;

	// Compile the code
	CompiledPythonFragment frag;
	frag.codeString = pCode;
	SIP_BLOCK_THREADS
	frag.code = (PyCodeObject*)Py_CompileString( pCode.toLatin1(), codeName.toLatin1(), Py_file_input );
	SIP_UNBLOCK_THREADS
	if( !frag.code )
	{
		PyErr_Print();
		LOG_5( "PathTemplate:getCompiledCode: Error Compiling Python code for: " + table->schema()->tableName() + " " + QString::number( pkey ) + " " + codeName );
		return 0;
	}

	// Load the code into a module
	// This is the only way i could figure out how to make the globals work properly
	// before i was using PyEval_EvalCode, passing the __main__ dict as the globals
	// but this wasn't working properly when calling the functions later, because
	// the import statements were lost.
	// This method works great and takes less code.
	
	// Generate a unique module name
	QString moduleName = "__" + table->schema()->tableName() + "__" + QString::number(pkey) + "__";
	// Returns a NEW ref
	SIP_BLOCK_THREADS
	PyObject * module = PyImport_ExecCodeModule(moduleName.toLatin1().data(),(PyObject*)frag.code);
	if( !module ) {
		PyErr_Print();
		LOG_3( "Unable to execute code module" );
	}

	// Save the modules dict, so we can lookup the function later
	else {
		frag.locals = PyModule_GetDict(module);
		Py_INCREF(frag.locals);
		codeCache[codeKey] = frag;
		ret = &codeCache[codeKey];
	}
	SIP_UNBLOCK_THREADS

	return ret;
}
Пример #10
0
static int
tok_stdin_decode(struct tok_state *tok, char **inp)
{
    PyObject *enc, *sysstdin, *decoded, *utf8;
    const char *encoding;
    char *converted;

    if (PySys_GetFile((char *)"stdin", NULL) != stdin)
        return 0;
    sysstdin = PySys_GetObject("stdin");
    if (sysstdin == NULL || !PyFile_Check(sysstdin))
        return 0;

    enc = ((PyFileObject *)sysstdin)->f_encoding;
    if (enc == NULL || !PyString_Check(enc))
        return 0;
    Py_INCREF(enc);

    encoding = PyString_AsString(enc);
    decoded = PyUnicode_Decode(*inp, strlen(*inp), encoding, NULL);
    if (decoded == NULL)
        goto error_clear;

    utf8 = PyUnicode_AsEncodedString(decoded, "utf-8", NULL);
    Py_DECREF(decoded);
    if (utf8 == NULL)
        goto error_clear;

    assert(PyString_Check(utf8));
    converted = new_string(PyString_AS_STRING(utf8),
                           PyString_GET_SIZE(utf8));
    Py_DECREF(utf8);
    if (converted == NULL)
        goto error_nomem;

    PyMem_FREE(*inp);
    *inp = converted;
    if (tok->encoding != NULL)
        PyMem_FREE(tok->encoding);
    tok->encoding = new_string(encoding, strlen(encoding));
    if (tok->encoding == NULL)
        goto error_nomem;

    Py_DECREF(enc);
    return 0;

error_nomem:
    Py_DECREF(enc);
    tok->done = E_NOMEM;
    return -1;

error_clear:
    Py_DECREF(enc);
    if (!PyErr_ExceptionMatches(PyExc_UnicodeDecodeError)) {
        tok->done = E_ERROR;
        return -1;
    }
    /* Fallback to iso-8859-1: for backward compatibility */
    PyErr_Clear();
    return 0;
}
Пример #11
0
static PyObject *
complex_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
	PyObject *r, *i, *tmp, *f;
	PyNumberMethods *nbr, *nbi = NULL;
	Py_complex cr, ci;
	int own_r = 0;
	int cr_is_complex = 0;
	int ci_is_complex = 0;
	static PyObject *complexstr;
	static char *kwlist[] = {"real", "imag", 0};

	r = Py_False;
	i = NULL;
	if (!PyArg_ParseTupleAndKeywords(args, kwds, "|OO:complex", kwlist,
					 &r, &i))
		return NULL;

	/* Special-case for a single argument when type(arg) is complex. */
	if (PyComplex_CheckExact(r) && i == NULL &&
	    type == &PyComplex_Type) {
		/* Note that we can't know whether it's safe to return
		   a complex *subclass* instance as-is, hence the restriction
		   to exact complexes here.  If either the input or the
		   output is a complex subclass, it will be handled below 
		   as a non-orthogonal vector.  */
		Py_INCREF(r);
		return r;
	}
	if (PyUnicode_Check(r)) {
		if (i != NULL) {
			PyErr_SetString(PyExc_TypeError,
					"complex() can't take second arg"
					" if first is a string");
			return NULL;
		}
		return complex_subtype_from_string(type, r);
	}
	if (i != NULL && PyUnicode_Check(i)) {
		PyErr_SetString(PyExc_TypeError,
				"complex() second arg can't be a string");
		return NULL;
	}

	/* XXX Hack to support classes with __complex__ method */
	if (complexstr == NULL) {
		complexstr = PyUnicode_InternFromString("__complex__");
		if (complexstr == NULL)
			return NULL;
	}
	f = PyObject_GetAttr(r, complexstr);
	if (f == NULL)
		PyErr_Clear();
	else {
		PyObject *args = PyTuple_New(0);
		if (args == NULL)
			return NULL;
		r = PyEval_CallObject(f, args);
		Py_DECREF(args);
		Py_DECREF(f);
		if (r == NULL)
			return NULL;
		own_r = 1;
	}
	nbr = r->ob_type->tp_as_number;
	if (i != NULL)
		nbi = i->ob_type->tp_as_number;
	if (nbr == NULL || nbr->nb_float == NULL ||
	    ((i != NULL) && (nbi == NULL || nbi->nb_float == NULL))) {
		PyErr_SetString(PyExc_TypeError,
			   "complex() argument must be a string or a number");
		if (own_r) {
			Py_DECREF(r);
		}
		return NULL;
	}

	/* If we get this far, then the "real" and "imag" parts should
	   both be treated as numbers, and the constructor should return a
	   complex number equal to (real + imag*1j).

 	   Note that we do NOT assume the input to already be in canonical
	   form; the "real" and "imag" parts might themselves be complex
	   numbers, which slightly complicates the code below. */
	if (PyComplex_Check(r)) {
		/* Note that if r is of a complex subtype, we're only
		   retaining its real & imag parts here, and the return
		   value is (properly) of the builtin complex type. */
		cr = ((PyComplexObject*)r)->cval;
		cr_is_complex = 1;
		if (own_r) {
			Py_DECREF(r);
		}
	}
	else {
		/* The "real" part really is entirely real, and contributes
		   nothing in the imaginary direction.  
		   Just treat it as a double. */
		tmp = PyNumber_Float(r);
		if (own_r) {
			/* r was a newly created complex number, rather
			   than the original "real" argument. */
			Py_DECREF(r);
		}
		if (tmp == NULL)
			return NULL;
		if (!PyFloat_Check(tmp)) {
			PyErr_SetString(PyExc_TypeError,
					"float(r) didn't return a float");
			Py_DECREF(tmp);
			return NULL;
		}
		cr.real = PyFloat_AsDouble(tmp);
		cr.imag = 0.0; /* Shut up compiler warning */
		Py_DECREF(tmp);
	}
	if (i == NULL) {
		ci.real = 0.0;
	}
	else if (PyComplex_Check(i)) {
		ci = ((PyComplexObject*)i)->cval;
		ci_is_complex = 1;
	} else {
		/* The "imag" part really is entirely imaginary, and
		   contributes nothing in the real direction.
		   Just treat it as a double. */
		tmp = (*nbi->nb_float)(i);
		if (tmp == NULL)
			return NULL;
		ci.real = PyFloat_AsDouble(tmp);
		Py_DECREF(tmp);
	}
	/*  If the input was in canonical form, then the "real" and "imag"
	    parts are real numbers, so that ci.imag and cr.imag are zero.
	    We need this correction in case they were not real numbers. */

	if (ci_is_complex) {
		cr.real -= ci.imag;
	}
	if (cr_is_complex) {
		ci.real += cr.imag;
	}
	return complex_subtype_from_doubles(type, cr.real, ci.real);
}
Пример #12
0
static PyObject *
gen_send_ex(PyGenObject *gen, PyObject *arg, int exc)
{
	PyThreadState *tstate = PyThreadState_GET();
	PyFrameObject *f = gen->gi_frame;
	PyObject *result;

	if (gen->gi_running) {
		PyErr_SetString(PyExc_ValueError,
				"generator already executing");
		return NULL;
	}
	if (f==NULL || f->f_stacktop == NULL) {
		/* Only set exception if called from send() */
		if (arg && !exc)
			PyErr_SetNone(PyExc_StopIteration);
		return NULL;
	}

	if (f->f_lasti == -1) {
		if (arg && arg != Py_None) {
			PyErr_SetString(PyExc_TypeError,
					"can't send non-None value to a "
					"just-started generator");
			return NULL;
		}
	} else {
		/* Push arg onto the frame's value stack */
		result = arg ? arg : Py_None;
	        Py_INCREF(result);
	        *(f->f_stacktop++) = result;
	}

	/* Generators always return to their most recent caller, not
	 * necessarily their creator. */
	Py_XINCREF(tstate->frame);
	assert(f->f_back == NULL);
	f->f_back = tstate->frame;

	gen->gi_running = 1;
	result = PyEval_EvalFrameEx(f, exc);
	gen->gi_running = 0;

	/* Don't keep the reference to f_back any longer than necessary.  It
	 * may keep a chain of frames alive or it could create a reference
	 * cycle. */
	assert(f->f_back == tstate->frame);
	Py_CLEAR(f->f_back);

	/* If the generator just returned (as opposed to yielding), signal
	 * that the generator is exhausted. */
	if (result == Py_None && f->f_stacktop == NULL) {
		Py_DECREF(result);
		result = NULL;
		/* Set exception if not called by gen_iternext() */
		if (arg)
			PyErr_SetNone(PyExc_StopIteration);
	}

	if (!result || f->f_stacktop == NULL) {
		/* generator can't be rerun, so release the frame */
		Py_DECREF(f);
		gen->gi_frame = NULL;
	}

	return result;
}
Пример #13
0
static PyObject *
gen_throw(PyGenObject *gen, PyObject *args)
{
	PyObject *typ;
	PyObject *tb = NULL;
	PyObject *val = NULL;

	if (!PyArg_UnpackTuple(args, "throw", 1, 3, &typ, &val, &tb))
		return NULL;

	/* First, check the traceback argument, replacing None with
	   NULL. */
	if (tb == Py_None)
		tb = NULL;
	else if (tb != NULL && !PyTraceBack_Check(tb)) {
		PyErr_SetString(PyExc_TypeError,
			"throw() third argument must be a traceback object");
		return NULL;
	}

	Py_INCREF(typ);
	Py_XINCREF(val);
	Py_XINCREF(tb);

	if (PyExceptionClass_Check(typ)) {
		PyErr_NormalizeException(&typ, &val, &tb);
	}

	else if (PyExceptionInstance_Check(typ)) {
		/* Raising an instance.  The value should be a dummy. */
		if (val && val != Py_None) {
			PyErr_SetString(PyExc_TypeError,
			  "instance exception may not have a separate value");
			goto failed_throw;
		}
		else {
			/* Normalize to raise <class>, <instance> */
			Py_XDECREF(val);
			val = typ;
			typ = PyExceptionInstance_Class(typ);
			Py_INCREF(typ);
		}
	}
	else {
		/* Not something you can raise.  throw() fails. */
		PyErr_Format(PyExc_TypeError,
			     "exceptions must be classes, or instances, not %s",
			     typ->ob_type->tp_name);
			goto failed_throw;
	}

	PyErr_Restore(typ, val, tb);
	return gen_send_ex(gen, Py_None, 1);

failed_throw:
	/* Didn't use our arguments, so restore their original refcounts */
	Py_DECREF(typ);
	Py_XDECREF(val);
	Py_XDECREF(tb);
	return NULL;
}
Пример #14
0
PyMODINIT_FUNC
init_billiard(void)
{
    PyObject *module, *temp, *value;

    /* Initialize module */
    module = Py_InitModule("_billiard", Billiard_module_methods);
    if (!module)
        return;

    /* Get copy of objects from pickle */
    temp = PyImport_ImportModule(PICKLE_MODULE);
    if (!temp)
        return;
    Billiard_pickle_dumps = PyObject_GetAttrString(temp, "dumps");
    Billiard_pickle_loads = PyObject_GetAttrString(temp, "loads");
    Billiard_pickle_protocol = PyObject_GetAttrString(temp, "HIGHEST_PROTOCOL");
    Py_XDECREF(temp);

    /* Get copy of BufferTooShort */
    temp = PyImport_ImportModule("billiard");
    if (!temp)
        return;
    Billiard_BufferTooShort = PyObject_GetAttrString(temp, "BufferTooShort");
    Py_XDECREF(temp);

    /* Add connection type to module */
    if (PyType_Ready(&BilliardConnectionType) < 0)
        return;
    Py_INCREF(&BilliardConnectionType);
    PyModule_AddObject(module, "Connection", (PyObject*)&BilliardConnectionType);

#if defined(MS_WINDOWS) ||                                              \
  (defined(HAVE_SEM_OPEN) && !defined(POSIX_SEMAPHORES_NOT_ENABLED))
    /* Add SemLock type to module */
    if (PyType_Ready(&BilliardSemLockType) < 0)
        return;
    Py_INCREF(&BilliardSemLockType);
    PyDict_SetItemString(BilliardSemLockType.tp_dict, "SEM_VALUE_MAX",
                         Py_BuildValue("i", SEM_VALUE_MAX));
    PyModule_AddObject(module, "SemLock", (PyObject*)&BilliardSemLockType);
#endif

#ifdef MS_WINDOWS
    /* Add PipeConnection to module */
    if (PyType_Ready(&BilliardPipeConnectionType) < 0)
        return;
    Py_INCREF(&BilliardPipeConnectionType);
    PyModule_AddObject(module, "PipeConnection",
                       (PyObject*)&BilliardPipeConnectionType);

    /* Initialize win32 class and add to multiprocessing */
    temp = create_win32_namespace();
    if (!temp)
        return;
    PyModule_AddObject(module, "win32", temp);

    /* Initialize the event handle used to signal Ctrl-C */
    sigint_event = CreateEvent(NULL, TRUE, FALSE, NULL);
    if (!sigint_event) {
        PyErr_SetFromWindowsErr(0);
        return;
    }
    if (!SetConsoleCtrlHandler(ProcessingCtrlHandler, TRUE)) {
        PyErr_SetFromWindowsErr(0);
        return;
    }
#endif

    /* Add configuration macros */
    temp = PyDict_New();
    if (!temp)
        return;
#define ADD_FLAG(name)                                            \
    value = Py_BuildValue("i", name);                             \
    if (value == NULL) { Py_DECREF(temp); return; }               \
    if (PyDict_SetItemString(temp, #name, value) < 0) {           \
        Py_DECREF(temp); Py_DECREF(value); return; }              \
    Py_DECREF(value)

#if defined(HAVE_SEM_OPEN) && !defined(POSIX_SEMAPHORES_NOT_ENABLED)
    ADD_FLAG(HAVE_SEM_OPEN);
#endif
#ifdef HAVE_SEM_TIMEDWAIT
    ADD_FLAG(HAVE_SEM_TIMEDWAIT);
#endif
#ifdef HAVE_FD_TRANSFER
    ADD_FLAG(HAVE_FD_TRANSFER);
#endif
#ifdef HAVE_BROKEN_SEM_GETVALUE
    ADD_FLAG(HAVE_BROKEN_SEM_GETVALUE);
#endif
#ifdef HAVE_BROKEN_SEM_UNLINK
    ADD_FLAG(HAVE_BROKEN_SEM_UNLINK);
#endif
    if (PyModule_AddObject(module, "flags", temp) < 0)
        return;
}
Пример #15
0
static PyObject* tuplerichcompare(PyObject* v, PyObject* w, int op) noexcept {
    BoxedTuple* vt, *wt;
    Py_ssize_t i;
    Py_ssize_t vlen, wlen;

    if (!PyTuple_Check(v) || !PyTuple_Check(w)) {
        Py_INCREF(Py_NotImplemented);
        return Py_NotImplemented;
    }

    vt = (BoxedTuple*)v;
    wt = (BoxedTuple*)w;

    vlen = Py_SIZE(vt);
    wlen = Py_SIZE(wt);

    /* Note:  the corresponding code for lists has an "early out" test
     * here when op is EQ or NE and the lengths differ.  That pays there,
     * but Tim was unable to find any real code where EQ/NE tuple
     * compares don't have the same length, so testing for it here would
     * have cost without benefit.
     */

    /* Search for the first index where items are different.
     * Note that because tuples are immutable, it's safe to reuse
     * vlen and wlen across the comparison calls.
     */
    for (i = 0; i < vlen && i < wlen; i++) {
        int k = PyObject_RichCompareBool(vt->elts[i], wt->elts[i], Py_EQ);
        if (k < 0)
            return NULL;
        if (!k)
            break;
    }

    if (i >= vlen || i >= wlen) {
        /* No more items to compare -- compare sizes */
        int cmp;
        PyObject* res;
        switch (op) {
            case Py_LT:
                cmp = vlen < wlen;
                break;
            case Py_LE:
                cmp = vlen <= wlen;
                break;
            case Py_EQ:
                cmp = vlen == wlen;
                break;
            case Py_NE:
                cmp = vlen != wlen;
                break;
            case Py_GT:
                cmp = vlen > wlen;
                break;
            case Py_GE:
                cmp = vlen >= wlen;
                break;
            default:
                return NULL; /* cannot happen */
        }
        if (cmp)
            res = Py_True;
        else
            res = Py_False;
        Py_INCREF(res);
        return res;
    }

    /* We have an item that differs -- shortcuts for EQ/NE */
    if (op == Py_EQ) {
        Py_INCREF(Py_False);
        return Py_False;
    }
    if (op == Py_NE) {
        Py_INCREF(Py_True);
        return Py_True;
    }

    /* Compare the final item again using the proper operator */
    return PyObject_RichCompare(vt->elts[i], wt->elts[i], op);
}
Пример #16
0
PyObject * sipWrapRecord( Record * r, bool makeCopy, TableSchema * defaultType )
{
	PyObject * ret = 0;
	// First we convert to Record using sip methods
	static sipTypeDef * recordType = getRecordType( "blur.Stone", "Record" );
	sipTypeDef * type = recordType;
	if( type ) {
		if( makeCopy )
			ret = getSipAPI()->api_convert_from_new_type( new Record(*r), type, NULL );
		else {
			ret = getSipAPI()->api_convert_from_type( r, type, Py_None );
		}
	} else {
		LOG_1( "Stone.Record not found" );
		return 0;
	}

	Table * table = r->table();

	TableSchema * tableSchema = 0;
	
	if( table )
		tableSchema = table->schema();
	else if( defaultType )
		tableSchema = defaultType;
	else
		return ret;

	bool isErr = false;
	if( tableSchema ) {
		QString className = tableSchema->className();
	
		// Then we try to find the python class for the particular schema class type
		// from the desired module set using addSchemaCastModule
		// BORROWED ref
		PyObject * dict = getSchemaCastModule( tableSchema->schema() );
		if( dict ) {
			SIP_BLOCK_THREADS
			// BORROWED ref
			PyObject * klass = PyDict_GetItemString( dict, className.toLatin1().constData() );
			if( klass ) {
				PyObject * tuple = PyTuple_New(1);
				// Tuple now holds only ref to ret
				PyTuple_SET_ITEM( tuple, 0, ret );
				PyObject * result = PyObject_CallObject( klass, tuple );
				if( result ) {
					if( PyObject_IsInstance( result, klass ) == 1 ) {
						ret = result;
					} else {
						LOG_1( "Cast Ctor Result is not a subclass of " + className );
						Py_INCREF( ret );
						Py_DECREF( result );
					}
				} else {
					LOG_1( "runPythonFunction: Execution Failed, Error Was:\n" );
					PyErr_Print();
					isErr = true;
				}
				Py_DECREF( tuple );
			}
			SIP_UNBLOCK_THREADS
			if( isErr ) return 0;
		} else LOG_1( "No cast module set for schema" );
	} else LOG_1( "Table has no schema" );
Пример #17
0
static PyObject *
Z_set(void *ptr, PyObject *value, Py_ssize_t size)
{
	if (value == Py_None) {
		*(wchar_t **)ptr = NULL;
		Py_INCREF(value);
		return value;
	}
	if (PyString_Check(value)) {
		value = PyUnicode_FromEncodedObject(value,
						    conversion_mode_encoding,
						    conversion_mode_errors);
		if (!value)
			return NULL;
	} else if (PyInt_Check(value) || PyLong_Check(value)) {
#if SIZEOF_VOID_P == SIZEOF_LONG_LONG
		*(wchar_t **)ptr = (wchar_t *)PyInt_AsUnsignedLongLongMask(value);
#else
		*(wchar_t **)ptr = (wchar_t *)PyInt_AsUnsignedLongMask(value);
#endif
		Py_INCREF(Py_None);
		return Py_None;
	} else if (!PyUnicode_Check(value)) {
		PyErr_Format(PyExc_TypeError,
			     "unicode string or integer address expected instead of %s instance",
			     value->ob_type->tp_name);
		return NULL;
	} else
		Py_INCREF(value);
#ifdef HAVE_USABLE_WCHAR_T
	/* HAVE_USABLE_WCHAR_T means that Py_UNICODE and wchar_t is the same
	   type.  So we can copy directly.  Hm, are unicode objects always NUL
	   terminated in Python, internally?
	 */
	*(wchar_t **)ptr = PyUnicode_AS_UNICODE(value);
	return value;
#else
	{
		/* We must create a wchar_t* buffer from the unicode object,
		   and keep it alive */
		PyObject *keep;
		wchar_t *buffer;

		int size = PyUnicode_GET_SIZE(value);
		size += 1; /* terminating NUL */
		size *= sizeof(wchar_t);
		buffer = (wchar_t *)PyMem_Malloc(size);
		if (!buffer)
			return PyErr_NoMemory();
		memset(buffer, 0, size);
		keep = PyCObject_FromVoidPtr(buffer, PyMem_Free);
		if (!keep) {
			PyMem_Free(buffer);
			return NULL;
		}
		*(wchar_t **)ptr = (wchar_t *)buffer;
		if (-1 == PyUnicode_AsWideChar((PyUnicodeObject *)value,
					       buffer, PyUnicode_GET_SIZE(value))) {
			Py_DECREF(value);
			Py_DECREF(keep);
			return NULL;
		}
		Py_DECREF(value);
		return keep;
	}
#endif
}
Пример #18
0
static void createModuleConstants( void )
{
    const_str_digest_21e3197080ed8d0f61f6ff49385794d5 = UNSTREAM_STRING( &constant_bin[ 193296 ], 54, 0 );
    const_str_digest_9ab39f5577ab9cb8dd91d9f4aa4267d8 = UNSTREAM_STRING( &constant_bin[ 193296 ], 42, 0 );
    const_list_str_digest_9ab39f5577ab9cb8dd91d9f4aa4267d8_list = PyList_New( 1 );
    PyList_SET_ITEM( const_list_str_digest_9ab39f5577ab9cb8dd91d9f4aa4267d8_list, 0, const_str_digest_9ab39f5577ab9cb8dd91d9f4aa4267d8 ); Py_INCREF( const_str_digest_9ab39f5577ab9cb8dd91d9f4aa4267d8 );

    constants_created = true;
}
Пример #19
0
void
PyStructSequence_InitType(PyTypeObject *type, PyStructSequence_Desc *desc)
{
    PyObject *dict;
    PyMemberDef* members;
    int n_members, n_unnamed_members, i, k;

#ifdef Py_TRACE_REFS
    /* if the type object was chained, unchain it first
       before overwriting its storage */
    if (type->ob_base.ob_base._ob_next) {
        _Py_ForgetReference((PyObject*)type);
    }
#endif

    n_unnamed_members = 0;
    for (i = 0; desc->fields[i].name != NULL; ++i)
        if (desc->fields[i].name == PyStructSequence_UnnamedField)
            n_unnamed_members++;
    n_members = i;

    memcpy(type, &_struct_sequence_template, sizeof(PyTypeObject));
    type->tp_base = &PyTuple_Type;
    type->tp_name = desc->name;
    type->tp_doc = desc->doc;

    members = PyMem_NEW(PyMemberDef, n_members-n_unnamed_members+1);
    if (members == NULL)
        return;

    for (i = k = 0; i < n_members; ++i) {
        if (desc->fields[i].name == PyStructSequence_UnnamedField)
            continue;
        members[k].name = desc->fields[i].name;
        members[k].type = T_OBJECT;
        members[k].offset = offsetof(PyStructSequence, ob_item)
          + i * sizeof(PyObject*);
        members[k].flags = READONLY;
        members[k].doc = desc->fields[i].doc;
        k++;
    }
    members[k].name = NULL;

    type->tp_members = members;

    if (PyType_Ready(type) < 0)
        return;
    Py_INCREF(type);

    dict = type->tp_dict;
#define SET_DICT_FROM_INT(key, value)                           \
    do {                                                        \
        PyObject *v = PyLong_FromLong((long) value);            \
        if (v != NULL) {                                        \
            PyDict_SetItemString(dict, key, v);                 \
            Py_DECREF(v);                                       \
        }                                                       \
    } while (0)

    SET_DICT_FROM_INT(visible_length_key, desc->n_in_sequence);
    SET_DICT_FROM_INT(real_length_key, n_members);
    SET_DICT_FROM_INT(unnamed_fields_key, n_unnamed_members);
}
Пример #20
0
static PyObject *
PLy_function_build_args(FunctionCallInfo fcinfo, PLyProcedure *proc)
{
	PyObject   *volatile arg = NULL;
	PyObject   *volatile args = NULL;
	int			i;

	PG_TRY();
	{
		args = PyList_New(proc->nargs);
		for (i = 0; i < proc->nargs; i++)
		{
			if (proc->args[i].is_rowtype > 0)
			{
				if (fcinfo->argnull[i])
					arg = NULL;
				else
				{
					HeapTupleHeader td;
					Oid			tupType;
					int32		tupTypmod;
					TupleDesc	tupdesc;
					HeapTupleData tmptup;

					td = DatumGetHeapTupleHeader(fcinfo->arg[i]);
					/* Extract rowtype info and find a tupdesc */
					tupType = HeapTupleHeaderGetTypeId(td);
					tupTypmod = HeapTupleHeaderGetTypMod(td);
					tupdesc = lookup_rowtype_tupdesc(tupType, tupTypmod);

					/* Set up I/O funcs if not done yet */
					if (proc->args[i].is_rowtype != 1)
						PLy_input_tuple_funcs(&(proc->args[i]), tupdesc);

					/* Build a temporary HeapTuple control structure */
					tmptup.t_len = HeapTupleHeaderGetDatumLength(td);
					tmptup.t_data = td;

					arg = PLyDict_FromTuple(&(proc->args[i]), &tmptup, tupdesc);
					ReleaseTupleDesc(tupdesc);
				}
			}
			else
			{
				if (fcinfo->argnull[i])
					arg = NULL;
				else
				{
					arg = (proc->args[i].in.d.func) (&(proc->args[i].in.d),
													 fcinfo->arg[i]);
				}
			}

			if (arg == NULL)
			{
				Py_INCREF(Py_None);
				arg = Py_None;
			}

			if (PyList_SetItem(args, i, arg) == -1)
				PLy_elog(ERROR, "PyList_SetItem() failed, while setting up arguments");

			if (proc->argnames && proc->argnames[i] &&
			PyDict_SetItemString(proc->globals, proc->argnames[i], arg) == -1)
				PLy_elog(ERROR, "PyDict_SetItemString() failed, while setting up arguments");
			arg = NULL;
		}

		/* Set up output conversion for functions returning RECORD */
		if (proc->result.out.d.typoid == RECORDOID)
		{
			TupleDesc	desc;

			if (get_call_result_type(fcinfo, NULL, &desc) != TYPEFUNC_COMPOSITE)
				ereport(ERROR,
						(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
						 errmsg("function returning record called in context "
								"that cannot accept type record")));

			/* cache the output conversion functions */
			PLy_output_record_funcs(&(proc->result), desc);
		}
	}
	PG_CATCH();
	{
		Py_XDECREF(arg);
		Py_XDECREF(args);

		PG_RE_THROW();
	}
	PG_END_TRY();

	return args;
}
Пример #21
0
static PyObject *__pyx_f_5cache_5Cache_add(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) {
  PyObject *__pyx_v_ps = 0;
  unsigned short __pyx_v_ncol;
  int __pyx_v_fsiz;
  char (*__pyx_v_s);
  int __pyx_v_bitset;
  PyObject *__pyx_v_row;
  PyObject *__pyx_v_i;
  PyObject *__pyx_r;
  char (*__pyx_1);
  PyObject *__pyx_2 = 0;
  long __pyx_3;
  int __pyx_4;
  PyObject *__pyx_5 = 0;
  PyObject *__pyx_6 = 0;
  static char *__pyx_argnames[] = {"ps",0};
  if (!PyArg_ParseTupleAndKeywords(__pyx_args, __pyx_kwds, "O", __pyx_argnames, &__pyx_v_ps)) return 0;
  Py_INCREF(__pyx_v_self);
  Py_INCREF(__pyx_v_ps);
  __pyx_v_row = Py_None; Py_INCREF(__pyx_v_row);
  __pyx_v_i = Py_None; Py_INCREF(__pyx_v_i);

  /* "/usr/home/jamwt/devel/pgasync/pgasync/cache.pyx":44 */
  __pyx_1 = PyString_AsString(__pyx_v_ps); if (PyErr_Occurred()) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 44; goto __pyx_L1;}
  __pyx_v_s = __pyx_1;

  /* "/usr/home/jamwt/devel/pgasync/pgasync/cache.pyx":46 */
  __pyx_2 = PyList_New(0); if (!__pyx_2) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 46; goto __pyx_L1;}
  Py_DECREF(__pyx_v_row);
  __pyx_v_row = __pyx_2;
  __pyx_2 = 0;

  /* "/usr/home/jamwt/devel/pgasync/pgasync/cache.pyx":47 */
  __pyx_v_ncol = convertUShort(__pyx_v_s);

  /* "/usr/home/jamwt/devel/pgasync/pgasync/cache.pyx":49 */
  __pyx_v_s = (&(__pyx_v_s[2]));

  /* "/usr/home/jamwt/devel/pgasync/pgasync/cache.pyx":51 */
  for (__pyx_3 = 0; __pyx_3 < __pyx_v_ncol; ++__pyx_3) {
    __pyx_2 = PyInt_FromLong(__pyx_3); if (!__pyx_2) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 51; goto __pyx_L1;}
    Py_DECREF(__pyx_v_i);
    __pyx_v_i = __pyx_2;
    __pyx_2 = 0;

    /* "/usr/home/jamwt/devel/pgasync/pgasync/cache.pyx":52 */
    __pyx_v_fsiz = convertInt(__pyx_v_s);

    /* "/usr/home/jamwt/devel/pgasync/pgasync/cache.pyx":54 */
    __pyx_v_s = (&(__pyx_v_s[4]));

    /* "/usr/home/jamwt/devel/pgasync/pgasync/cache.pyx":56 */
    __pyx_4 = (__pyx_v_fsiz <= 0);
    if (__pyx_4) {

      /* "/usr/home/jamwt/devel/pgasync/pgasync/cache.pyx":57 */
      __pyx_2 = PyObject_GetAttr(__pyx_v_row, __pyx_n_append); if (!__pyx_2) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 57; goto __pyx_L1;}
      __pyx_5 = PyTuple_New(1); if (!__pyx_5) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 57; goto __pyx_L1;}
      Py_INCREF(Py_None);
      PyTuple_SET_ITEM(__pyx_5, 0, Py_None);
      __pyx_6 = PyObject_CallObject(__pyx_2, __pyx_5); if (!__pyx_6) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 57; goto __pyx_L1;}
      Py_DECREF(__pyx_2); __pyx_2 = 0;
      Py_DECREF(__pyx_5); __pyx_5 = 0;
      Py_DECREF(__pyx_6); __pyx_6 = 0;

      /* "/usr/home/jamwt/devel/pgasync/pgasync/cache.pyx":58 */
      goto __pyx_L2;
      goto __pyx_L4;
    }
    __pyx_L4:;

    /* "/usr/home/jamwt/devel/pgasync/pgasync/cache.pyx":60 */
    while (1) {
      __pyx_L5:;
      __pyx_4 = ((__pyx_v_fsiz + 1) > ((struct __pyx_obj_5cache_Cache *)__pyx_v_self)->blen);
      if (!__pyx_4) break;

      /* "/usr/home/jamwt/devel/pgasync/pgasync/cache.pyx":61 */
      __pyx_2 = PyObject_GetAttr(__pyx_v_self, __pyx_n_realloc); if (!__pyx_2) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 61; goto __pyx_L1;}
      __pyx_5 = PyTuple_New(0); if (!__pyx_5) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 61; goto __pyx_L1;}
      __pyx_6 = PyObject_CallObject(__pyx_2, __pyx_5); if (!__pyx_6) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 61; goto __pyx_L1;}
      Py_DECREF(__pyx_2); __pyx_2 = 0;
      Py_DECREF(__pyx_5); __pyx_5 = 0;
      Py_DECREF(__pyx_6); __pyx_6 = 0;
    }
    __pyx_L6:;

    /* "/usr/home/jamwt/devel/pgasync/pgasync/cache.pyx":63 */
    strncpy(((struct __pyx_obj_5cache_Cache *)__pyx_v_self)->buffer,__pyx_v_s,__pyx_v_fsiz);

    /* "/usr/home/jamwt/devel/pgasync/pgasync/cache.pyx":64 */
    (((struct __pyx_obj_5cache_Cache *)__pyx_v_self)->buffer[__pyx_v_fsiz]) = 0;

    /* "/usr/home/jamwt/devel/pgasync/pgasync/cache.pyx":65 */
    __pyx_2 = PyObject_GetAttr(__pyx_v_row, __pyx_n_append); if (!__pyx_2) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 65; goto __pyx_L1;}
    __pyx_5 = PyString_FromString(((struct __pyx_obj_5cache_Cache *)__pyx_v_self)->buffer); if (!__pyx_5) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 65; goto __pyx_L1;}
    __pyx_6 = PyTuple_New(1); if (!__pyx_6) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 65; goto __pyx_L1;}
    PyTuple_SET_ITEM(__pyx_6, 0, __pyx_5);
    __pyx_5 = 0;
    __pyx_5 = PyObject_CallObject(__pyx_2, __pyx_6); if (!__pyx_5) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 65; goto __pyx_L1;}
    Py_DECREF(__pyx_2); __pyx_2 = 0;
    Py_DECREF(__pyx_6); __pyx_6 = 0;
    Py_DECREF(__pyx_5); __pyx_5 = 0;

    /* "/usr/home/jamwt/devel/pgasync/pgasync/cache.pyx":66 */
    __pyx_v_s = (&(__pyx_v_s[__pyx_v_fsiz]));
    __pyx_L2:;
  }
  __pyx_L3:;

  /* "/usr/home/jamwt/devel/pgasync/pgasync/cache.pyx":68 */
  __pyx_2 = PyObject_GetAttr(((struct __pyx_obj_5cache_Cache *)__pyx_v_self)->list, __pyx_n_append); if (!__pyx_2) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 68; goto __pyx_L1;}
  __pyx_6 = PyTuple_New(1); if (!__pyx_6) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 68; goto __pyx_L1;}
  Py_INCREF(__pyx_v_row);
  PyTuple_SET_ITEM(__pyx_6, 0, __pyx_v_row);
  __pyx_5 = PyObject_CallObject(__pyx_2, __pyx_6); if (!__pyx_5) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 68; goto __pyx_L1;}
  Py_DECREF(__pyx_2); __pyx_2 = 0;
  Py_DECREF(__pyx_6); __pyx_6 = 0;
  Py_DECREF(__pyx_5); __pyx_5 = 0;

  __pyx_r = Py_None; Py_INCREF(__pyx_r);
  goto __pyx_L0;
  __pyx_L1:;
  Py_XDECREF(__pyx_2);
  Py_XDECREF(__pyx_5);
  Py_XDECREF(__pyx_6);
  __Pyx_AddTraceback("cache.Cache.add");
  __pyx_r = 0;
  __pyx_L0:;
  Py_DECREF(__pyx_v_row);
  Py_DECREF(__pyx_v_i);
  Py_DECREF(__pyx_v_self);
  Py_DECREF(__pyx_v_ps);
  return __pyx_r;
}
Пример #22
0
static PyObject *
PLy_trigger_build_args(FunctionCallInfo fcinfo, PLyProcedure *proc, HeapTuple *rv)
{
	TriggerData *tdata = (TriggerData *) fcinfo->context;
	PyObject   *pltname,
			   *pltevent,
			   *pltwhen,
			   *pltlevel,
			   *pltrelid,
			   *plttablename,
			   *plttableschema;
	PyObject   *pltargs,
			   *pytnew,
			   *pytold;
	PyObject   *volatile pltdata = NULL;
	char	   *stroid;

	PG_TRY();
	{
		pltdata = PyDict_New();
		if (!pltdata)
			PLy_elog(ERROR, "could not create new dictionary while building trigger arguments");

		pltname = PyString_FromString(tdata->tg_trigger->tgname);
		PyDict_SetItemString(pltdata, "name", pltname);
		Py_DECREF(pltname);

		stroid = DatumGetCString(DirectFunctionCall1(oidout,
							   ObjectIdGetDatum(tdata->tg_relation->rd_id)));
		pltrelid = PyString_FromString(stroid);
		PyDict_SetItemString(pltdata, "relid", pltrelid);
		Py_DECREF(pltrelid);
		pfree(stroid);

		stroid = SPI_getrelname(tdata->tg_relation);
		plttablename = PyString_FromString(stroid);
		PyDict_SetItemString(pltdata, "table_name", plttablename);
		Py_DECREF(plttablename);
		pfree(stroid);

		stroid = SPI_getnspname(tdata->tg_relation);
		plttableschema = PyString_FromString(stroid);
		PyDict_SetItemString(pltdata, "table_schema", plttableschema);
		Py_DECREF(plttableschema);
		pfree(stroid);

		if (TRIGGER_FIRED_BEFORE(tdata->tg_event))
			pltwhen = PyString_FromString("BEFORE");
		else if (TRIGGER_FIRED_AFTER(tdata->tg_event))
			pltwhen = PyString_FromString("AFTER");
		else if (TRIGGER_FIRED_INSTEAD(tdata->tg_event))
			pltwhen = PyString_FromString("INSTEAD OF");
		else
		{
			elog(ERROR, "unrecognized WHEN tg_event: %u", tdata->tg_event);
			pltwhen = NULL;		/* keep compiler quiet */
		}
		PyDict_SetItemString(pltdata, "when", pltwhen);
		Py_DECREF(pltwhen);

		if (TRIGGER_FIRED_FOR_ROW(tdata->tg_event))
		{
			pltlevel = PyString_FromString("ROW");
			PyDict_SetItemString(pltdata, "level", pltlevel);
			Py_DECREF(pltlevel);

			if (TRIGGER_FIRED_BY_INSERT(tdata->tg_event))
			{
				pltevent = PyString_FromString("INSERT");

				PyDict_SetItemString(pltdata, "old", Py_None);
				pytnew = PLyDict_FromTuple(&(proc->result), tdata->tg_trigtuple,
										   tdata->tg_relation->rd_att);
				PyDict_SetItemString(pltdata, "new", pytnew);
				Py_DECREF(pytnew);
				*rv = tdata->tg_trigtuple;
			}
			else if (TRIGGER_FIRED_BY_DELETE(tdata->tg_event))
			{
				pltevent = PyString_FromString("DELETE");

				PyDict_SetItemString(pltdata, "new", Py_None);
				pytold = PLyDict_FromTuple(&(proc->result), tdata->tg_trigtuple,
										   tdata->tg_relation->rd_att);
				PyDict_SetItemString(pltdata, "old", pytold);
				Py_DECREF(pytold);
				*rv = tdata->tg_trigtuple;
			}
			else if (TRIGGER_FIRED_BY_UPDATE(tdata->tg_event))
			{
				pltevent = PyString_FromString("UPDATE");

				pytnew = PLyDict_FromTuple(&(proc->result), tdata->tg_newtuple,
										   tdata->tg_relation->rd_att);
				PyDict_SetItemString(pltdata, "new", pytnew);
				Py_DECREF(pytnew);
				pytold = PLyDict_FromTuple(&(proc->result), tdata->tg_trigtuple,
										   tdata->tg_relation->rd_att);
				PyDict_SetItemString(pltdata, "old", pytold);
				Py_DECREF(pytold);
				*rv = tdata->tg_newtuple;
			}
			else
			{
				elog(ERROR, "unrecognized OP tg_event: %u", tdata->tg_event);
				pltevent = NULL;	/* keep compiler quiet */
			}

			PyDict_SetItemString(pltdata, "event", pltevent);
			Py_DECREF(pltevent);
		}
		else if (TRIGGER_FIRED_FOR_STATEMENT(tdata->tg_event))
		{
			pltlevel = PyString_FromString("STATEMENT");
			PyDict_SetItemString(pltdata, "level", pltlevel);
			Py_DECREF(pltlevel);

			PyDict_SetItemString(pltdata, "old", Py_None);
			PyDict_SetItemString(pltdata, "new", Py_None);
			*rv = NULL;

			if (TRIGGER_FIRED_BY_INSERT(tdata->tg_event))
				pltevent = PyString_FromString("INSERT");
			else if (TRIGGER_FIRED_BY_DELETE(tdata->tg_event))
				pltevent = PyString_FromString("DELETE");
			else if (TRIGGER_FIRED_BY_UPDATE(tdata->tg_event))
				pltevent = PyString_FromString("UPDATE");
			else if (TRIGGER_FIRED_BY_TRUNCATE(tdata->tg_event))
				pltevent = PyString_FromString("TRUNCATE");
			else
			{
				elog(ERROR, "unrecognized OP tg_event: %u", tdata->tg_event);
				pltevent = NULL;	/* keep compiler quiet */
			}

			PyDict_SetItemString(pltdata, "event", pltevent);
			Py_DECREF(pltevent);
		}
		else
			elog(ERROR, "unrecognized LEVEL tg_event: %u", tdata->tg_event);

		if (tdata->tg_trigger->tgnargs)
		{
			/*
			 * all strings...
			 */
			int			i;
			PyObject   *pltarg;

			pltargs = PyList_New(tdata->tg_trigger->tgnargs);
			for (i = 0; i < tdata->tg_trigger->tgnargs; i++)
			{
				pltarg = PyString_FromString(tdata->tg_trigger->tgargs[i]);

				/*
				 * stolen, don't Py_DECREF
				 */
				PyList_SetItem(pltargs, i, pltarg);
			}
		}
		else
		{
			Py_INCREF(Py_None);
			pltargs = Py_None;
		}
		PyDict_SetItemString(pltdata, "args", pltargs);
		Py_DECREF(pltargs);
	}
	PG_CATCH();
	{
		Py_XDECREF(pltdata);
		PG_RE_THROW();
	}
	PG_END_TRY();

	return pltdata;
}
Пример #23
0
static CYTHON_INLINE PyObject* __Pyx_PyNumber_Int(PyObject* x) {
  PyNumberMethods *m;
  const char *name = NULL;
  PyObject *res = NULL;
#if PY_MAJOR_VERSION < 3
  if (PyInt_Check(x) || PyLong_Check(x))
#else
  if (PyLong_Check(x))
#endif
    return Py_INCREF(x), x;
  m = Py_TYPE(x)->tp_as_number;
#if PY_MAJOR_VERSION < 3
  if (m && m->nb_int) {
    name = "int";
    res = PyNumber_Int(x);
  }
  else if (m && m->nb_long) {
    name = "long";
    res = PyNumber_Long(x);
  }
#else
  if (m && m->nb_int) {
    name = "int";
    res = PyNumber_Long(x);
  }
#endif
  if (res) {
#if PY_MAJOR_VERSION < 3
    if (!PyInt_Check(res) && !PyLong_Check(res)) {
#else
    if (!PyLong_Check(res)) {
#endif
      PyErr_Format(PyExc_TypeError,
                   "__%.4s__ returned non-%.4s (type %.200s)",
                   name, name, Py_TYPE(res)->tp_name);
      Py_DECREF(res);
      return NULL;
    }
  }
  else if (!PyErr_Occurred()) {
    PyErr_SetString(PyExc_TypeError,
                    "an integer is required");
  }
  return res;
}

#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3
 #if CYTHON_USE_PYLONG_INTERNALS
  #include "longintrepr.h"
 #endif
#endif
static CYTHON_INLINE Py_ssize_t __Pyx_PyIndex_AsSsize_t(PyObject* b) {
  Py_ssize_t ival;
  PyObject *x;
#if PY_MAJOR_VERSION < 3
  if (likely(PyInt_CheckExact(b)))
      return PyInt_AS_LONG(b);
#endif
  if (likely(PyLong_CheckExact(b))) {
    #if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3
     #if CYTHON_USE_PYLONG_INTERNALS
       switch (Py_SIZE(b)) {
       case -1: return -(sdigit)((PyLongObject*)b)->ob_digit[0];
       case  0: return 0;
       case  1: return ((PyLongObject*)b)->ob_digit[0];
       }
     #endif
    #endif
  #if PY_VERSION_HEX < 0x02060000
    return PyInt_AsSsize_t(b);
  #else
    return PyLong_AsSsize_t(b);
  #endif
  }
  x = PyNumber_Index(b);
  if (!x) return -1;
  ival = PyInt_AsSsize_t(x);
  Py_DECREF(x);
  return ival;
}
Пример #24
0
static HeapTuple
PLy_modify_tuple(PLyProcedure *proc, PyObject *pltd, TriggerData *tdata,
				 HeapTuple otup)
{
	PyObject   *volatile plntup;
	PyObject   *volatile plkeys;
	PyObject   *volatile plval;
	HeapTuple	rtup;
	int			natts,
				i,
				attn,
				atti;
	int		   *volatile modattrs;
	Datum	   *volatile modvalues;
	char	   *volatile modnulls;
	TupleDesc	tupdesc;
	ErrorContextCallback plerrcontext;

	plerrcontext.callback = plpython_trigger_error_callback;
	plerrcontext.previous = error_context_stack;
	error_context_stack = &plerrcontext;

	plntup = plkeys = plval = NULL;
	modattrs = NULL;
	modvalues = NULL;
	modnulls = NULL;

	PG_TRY();
	{
		if ((plntup = PyDict_GetItemString(pltd, "new")) == NULL)
			ereport(ERROR,
					(errmsg("TD[\"new\"] deleted, cannot modify row")));
		Py_INCREF(plntup);
		if (!PyDict_Check(plntup))
			ereport(ERROR,
					(errmsg("TD[\"new\"] is not a dictionary")));

		plkeys = PyDict_Keys(plntup);
		natts = PyList_Size(plkeys);

		modattrs = (int *) palloc(natts * sizeof(int));
		modvalues = (Datum *) palloc(natts * sizeof(Datum));
		modnulls = (char *) palloc(natts * sizeof(char));

		tupdesc = tdata->tg_relation->rd_att;

		for (i = 0; i < natts; i++)
		{
			PyObject   *platt;
			char	   *plattstr;

			platt = PyList_GetItem(plkeys, i);
			if (PyString_Check(platt))
				plattstr = PyString_AsString(platt);
			else if (PyUnicode_Check(platt))
				plattstr = PLyUnicode_AsString(platt);
			else
			{
				ereport(ERROR,
						(errmsg("TD[\"new\"] dictionary key at ordinal position %d is not a string", i)));
				plattstr = NULL;	/* keep compiler quiet */
			}
			attn = SPI_fnumber(tupdesc, plattstr);
			if (attn == SPI_ERROR_NOATTRIBUTE)
				ereport(ERROR,
						(errmsg("key \"%s\" found in TD[\"new\"] does not exist as a column in the triggering row",
								plattstr)));
			atti = attn - 1;

			plval = PyDict_GetItem(plntup, platt);
			if (plval == NULL)
				elog(FATAL, "Python interpreter is probably corrupted");

			Py_INCREF(plval);

			modattrs[i] = attn;

			if (tupdesc->attrs[atti]->attisdropped)
			{
				modvalues[i] = (Datum) 0;
				modnulls[i] = 'n';
			}
			else if (plval != Py_None)
			{
				PLyObToDatum *att = &proc->result.out.r.atts[atti];

				modvalues[i] = (att->func) (att,
											tupdesc->attrs[atti]->atttypmod,
											plval);
				modnulls[i] = ' ';
			}
			else
			{
				modvalues[i] =
					InputFunctionCall(&proc->result.out.r.atts[atti].typfunc,
									  NULL,
									proc->result.out.r.atts[atti].typioparam,
									  tupdesc->attrs[atti]->atttypmod);
				modnulls[i] = 'n';
			}

			Py_DECREF(plval);
			plval = NULL;
		}

		rtup = SPI_modifytuple(tdata->tg_relation, otup, natts,
							   modattrs, modvalues, modnulls);
		if (rtup == NULL)
			elog(ERROR, "SPI_modifytuple failed: error %d", SPI_result);
	}
	PG_CATCH();
	{
		Py_XDECREF(plntup);
		Py_XDECREF(plkeys);
		Py_XDECREF(plval);

		if (modnulls)
			pfree(modnulls);
		if (modvalues)
			pfree(modvalues);
		if (modattrs)
			pfree(modattrs);

		PG_RE_THROW();
	}
	PG_END_TRY();

	Py_DECREF(plntup);
	Py_DECREF(plkeys);

	pfree(modattrs);
	pfree(modvalues);
	pfree(modnulls);

	error_context_stack = plerrcontext.previous;

	return rtup;
}
Пример #25
0
static PyObject *tibiaauto_tibiaauto_registerPlugin(PyObject *self, PyObject *args)
{
	registerPluginCount++;

	CPythonScript *pythonScript = new CPythonScript();
	CPythonEngine pythonEngine;


	PyObject *pluginClass = NULL;
	if (!PyArg_ParseTuple(args, "O", &pluginClass))
		return NULL;

	Py_XINCREF(pluginClass);
	pythonScript->setPluginClass(pluginClass);

	PyObject *pluginObject = PyInstance_New(pluginClass, NULL, NULL);
	if (pluginObject == NULL)
	{
		AfxMessageBox("registerObject() takes class as an argument");
		Py_XDECREF(pluginClass);
		return NULL;
	}
	Py_XINCREF(pluginObject);
	pythonScript->setPluginObject(pluginObject);

	// getName
	PyObject *result = PyObject_CallMethod(pluginObject, "getName", "()");
	pythonScript->setName(PyString_AsString(result));
	Py_XDECREF(result);

	// getVersion
	result = PyObject_CallMethod(pluginObject, "getVersion", "()");
	pythonScript->setVersion(PyString_AsString(result));
	Py_XDECREF(result);


	// getFunDef
	int nr;
	for (nr = 0;; nr++)
	{
		int type, interval;
		char *matchExpr = NULL;
		int regLen;
		PyObject *periodicalFun;

		result = PyObject_CallMethod(pluginObject, "getFunDef", "(i)", nr);
		if (result == NULL)
		{
			AfxMessageBox("getFunDef() call failed");
			return NULL;
		}

		//nested if statements are for trying to read the two possible sets of parameters
		type = -255;
		if (PyArg_ParseTuple(result, "|iiO", &type, &interval, &periodicalFun))
		{
			if (type != -255)
				pythonScript->addFunDef(type, interval, periodicalFun);
			else
				break;
		}
		else
		{
			PyErr_Clear();
			if (PyArg_ParseTuple(result, "|is#O", &type, &matchExpr, &regLen, &periodicalFun))
			{
				if (type != -255)
					pythonScript->addFunDef(type, matchExpr, regLen, periodicalFun);
				else
					break;
			}
			else
			{
				Py_XDECREF(result);
				return NULL;
			}
		}


		Py_XDECREF(result);
	}
	// getConfigParam
	for (nr = 0;; nr++)
	{
		char *name = NULL, *description = NULL;
		result = PyObject_CallMethod(pluginObject, "getConfigParam", "(i)", nr);
		if (result == NULL)
		{
			AfxMessageBox("getConfigParam() call failed");
			return NULL;
		}
		if (PyArg_ParseTuple(result, "|ss", &name, &description))
		{
			if (name != NULL && description != NULL)
				pythonScript->addParamDef(name, description);
			else
				break;
		}
		else
		{
			Py_XDECREF(result);
			return NULL;
		}
		Py_XDECREF(result);
	}


	Py_XDECREF(pluginObject);
	Py_XDECREF(pluginClass);

	Py_INCREF(Py_None);

	return Py_None;
}
Пример #26
0
static PyObject* connect_to_apctl(PyObject *self, PyObject *args, PyObject *kwargs)
{
    int err, config = 1;
    int stateLast = -1;
    int timeout = -1;
    PyObject *callback = NULL, *ret;

    time_t started;

    static char* kwids[] = { "config", "callback", "timeout", NULL };

    if (PyErr_CheckSignals())
       return NULL;

    time(&started);

    if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|iOi", kwids,
                                     &config, &callback, &timeout))
       return NULL;

    if (callback)
    {
       if (!PyCallable_Check(callback))
       {
          PyErr_SetString(PyExc_TypeError, "callback must be callable");
          return NULL;
       }
    }

    Py_BEGIN_ALLOW_THREADS
       err = sceNetApctlConnect(config);
    Py_END_ALLOW_THREADS

    if (err != 0)
    {
       PyErr_Format(net_error, "sceNetApctlConnect returns %08x\n", err);
       return NULL;
    }

    while (1)
    {
       int state;

       if (PyErr_CheckSignals())
          return NULL;

       Py_BEGIN_ALLOW_THREADS
          err = sceNetApctlGetState(&state);
       Py_END_ALLOW_THREADS

       if (err != 0)
       {
          PyErr_Format(net_error, "sceNetApctlGetState returns %08x\n", err);
          return NULL;
       }

       if (state > stateLast)
       {
          if (callback)
          {
             ret = PyObject_CallFunction(callback, "i", state);
             if (!ret)
                return NULL;
             Py_XDECREF(ret);
          }

          stateLast = state;
       }

       if (state == 4)
          break;  // connected with static IP

       // wait a little before polling again
       Py_BEGIN_ALLOW_THREADS
          sceKernelDelayThread(50 * 1000); // 50ms
       Py_END_ALLOW_THREADS

       if (timeout > 0)
       {
          time_t now;

          time(&now);
          if ((int)(now - started) >= timeout)
          {
             PyErr_SetString(net_error, "Timeout while trying to connect");
             return NULL;
          }
       }
    }

    if (callback)
    {
       ret = PyObject_CallFunction(callback, "i", -1);
       if (!ret)
          return NULL;
       Py_XDECREF(ret);
    }

    Py_INCREF(Py_None);
    return Py_None;
}
Пример #27
0
static PyObject *t_repository__getRepository(t_repository *self, void *data)
{
    Py_INCREF(self);
    return (PyObject *) self;
}
Пример #28
0
static int simple_init(simple *self, PyObject *args, PyObject *kwds)
{
    PyObject *server=NULL, *name=NULL, *device=NULL, *direction=NULL,
             *description=NULL, *sample_spec=NULL, *channel_map=NULL,
             *buffer_attr=NULL, *tmp;

    static char *kwlist[] = {"server", "name", "direction", "device", "description",
                            "sample_spec", "channel_map", "buffer_attr", NULL};

    if (! PyArg_ParseTupleAndKeywords(args, kwds, "|OOOOOOO", kwlist,
                                      &server, &name, &direction, &device,
                                      &description, &sample_spec, &channel_map,
                                      &buffer_attr))
        return -1;

    if (server) {
        tmp = self->server;
        Py_INCREF(server);
        self->server = server;
        Py_XDECREF(tmp);
    }

//    printf("name: %s\n", PyBytes_AS_STRING(name));
    if (name) {
        tmp = self->name;
        Py_INCREF(name);
        self->name = name;
        Py_XDECREF(tmp);
    }

    if (direction) {
        tmp = self->stream_direction;
        Py_INCREF(direction);
        self->stream_direction = direction;
        Py_XDECREF(tmp);
    }

    if (device) {
        tmp = self->device;
        Py_INCREF(device);
        self->device = device;
        Py_XDECREF(tmp);
    }

    if (description) {
        tmp = self->description;
        Py_INCREF(description);
        self->description = description;
        Py_XDECREF(tmp);
    }

    if (sample_spec) {
        tmp = self->sample_spec;
        Py_INCREF(sample_spec);
        self->sample_spec = sample_spec;
        Py_XDECREF(tmp);
    }

    if (channel_map) {
        tmp = self->channel_map;
        Py_INCREF(channel_map);
        self->channel_map = channel_map;
        Py_XDECREF(tmp);
    }

    if (buffer_attr) {
        tmp = self->buffer_attr;
        Py_INCREF(buffer_attr);
        self->buffer_attr = buffer_attr;
        Py_XDECREF(tmp);
    }

    return 0;
}
Пример #29
0
// The module function definitions.
static PyObject *impl_function_1_new_of_module_Crypto$Random( Nuitka_FunctionObject *self, PyObject *_python_par_args, PyObject *_python_par_kwargs )
{
    // No context is used.

    // Local variable declarations.
    PyObjectLocalVariable par_args; par_args.object = _python_par_args;
    PyObjectLocalVariable par_kwargs; par_kwargs.object = _python_par_kwargs;
    PyObject *exception_type = NULL, *exception_value = NULL;
    PyTracebackObject *exception_tb = NULL;
    PyObject *tmp_dircall_arg1_1;
    PyObject *tmp_dircall_arg2_1;
    PyObject *tmp_dircall_arg3_1;
    PyObject *tmp_frame_locals;
    PyObject *tmp_return_value;
    PyObject *tmp_source_name_1;
    tmp_return_value = NULL;

    // Actual function code.
    static PyFrameObject *cache_frame_function = NULL;
    MAKE_OR_REUSE_FRAME( cache_frame_function, codeobj_133c4414c20d7de5bf4cbf02f8208534, module_Crypto$Random );
    PyFrameObject *frame_function = cache_frame_function;

    // Push the new frame as the currently active one.
    pushFrameStack( frame_function );

    // Mark the frame object as in use, ref count 1 will be up for reuse.
    Py_INCREF( frame_function );
    assert( Py_REFCNT( frame_function ) == 2 ); // Frame stack

#if PYTHON_VERSION >= 340
    frame_function->f_executing += 1;
#endif

    // Framed code:
    tmp_source_name_1 = GET_STRING_DICT_VALUE( moduledict_Crypto$Random, (Nuitka_StringObject *)const_str_plain__UserFriendlyRNG );

    if (unlikely( tmp_source_name_1 == NULL ))
    {
        tmp_source_name_1 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain__UserFriendlyRNG );
    }

    if ( tmp_source_name_1 == NULL )
    {

        exception_type = INCREASE_REFCOUNT( PyExc_NameError );
        exception_value = UNSTREAM_STRING( &constant_bin[ 6196 ], 45, 0 );
        exception_tb = NULL;

        frame_function->f_lineno = 33;
        goto frame_exception_exit_1;
    }

    tmp_dircall_arg1_1 = LOOKUP_ATTRIBUTE( tmp_source_name_1, const_str_plain_new );
    if ( tmp_dircall_arg1_1 == NULL )
    {
        assert( ERROR_OCCURED() );

        PyErr_Fetch( &exception_type, &exception_value, (PyObject **)&exception_tb );


        frame_function->f_lineno = 33;
        goto frame_exception_exit_1;
    }
    tmp_dircall_arg2_1 = par_args.object;

    if ( tmp_dircall_arg2_1 == NULL )
    {
        Py_DECREF( tmp_dircall_arg1_1 );
        exception_type = INCREASE_REFCOUNT( PyExc_UnboundLocalError );
        exception_value = UNSTREAM_STRING( &constant_bin[ 201 ], 50, 0 );
        exception_tb = NULL;

        frame_function->f_lineno = 33;
        goto frame_exception_exit_1;
    }

    tmp_dircall_arg3_1 = par_kwargs.object;

    if ( tmp_dircall_arg3_1 == NULL )
    {
        Py_DECREF( tmp_dircall_arg1_1 );
        exception_type = INCREASE_REFCOUNT( PyExc_UnboundLocalError );
        exception_value = UNSTREAM_STRING( &constant_bin[ 251 ], 52, 0 );
        exception_tb = NULL;

        frame_function->f_lineno = 33;
        goto frame_exception_exit_1;
    }

    tmp_return_value = impl_function_3_complex_call_helper_star_list_star_dict_of_module___internal__( tmp_dircall_arg1_1, INCREASE_REFCOUNT( tmp_dircall_arg2_1 ), INCREASE_REFCOUNT( tmp_dircall_arg3_1 ) );
    if ( tmp_return_value == NULL )
    {
        assert( ERROR_OCCURED() );

        PyErr_Fetch( &exception_type, &exception_value, (PyObject **)&exception_tb );


        frame_function->f_lineno = 33;
        goto frame_exception_exit_1;
    }
    goto frame_return_exit_1;

#if 0
    RESTORE_FRAME_EXCEPTION( frame_function );
#endif
    // Put the previous frame back on top.
    popFrameStack();
#if PYTHON_VERSION >= 340
    frame_function->f_executing -= 1;
#endif
    Py_DECREF( frame_function );
    goto frame_no_exception_1;
    frame_return_exit_1:;
#if 0
    RESTORE_FRAME_EXCEPTION( frame_function );
#endif
    popFrameStack();
#if PYTHON_VERSION >= 340
    frame_function->f_executing -= 1;
#endif
    Py_DECREF( frame_function );
    goto function_return_exit;
    frame_exception_exit_1:;
#if 0
    RESTORE_FRAME_EXCEPTION( frame_function );
#endif

    if ( exception_tb == NULL )
    {
        exception_tb = MAKE_TRACEBACK( INCREASE_REFCOUNT( frame_function ) );
    }
    else if ( exception_tb->tb_frame != frame_function )
    {
        PyTracebackObject *traceback_new = (PyTracebackObject *)MAKE_TRACEBACK( INCREASE_REFCOUNT( frame_function ) );
        traceback_new->tb_next = exception_tb;
        exception_tb = traceback_new;
    }


    tmp_frame_locals = PyDict_New();
    if ((par_args.object != NULL))
    {
        PyDict_SetItem(
            tmp_frame_locals,
            const_str_plain_args,
            par_args.object
        );

    }
    if ((par_kwargs.object != NULL))
    {
        PyDict_SetItem(
            tmp_frame_locals,
            const_str_plain_kwargs,
            par_kwargs.object
        );

    }
    detachFrame( exception_tb, tmp_frame_locals );


    popFrameStack();

#if PYTHON_VERSION >= 340
    frame_function->f_executing -= 1;
#endif
    Py_DECREF( frame_function );

    // Return the error.
    goto function_exception_exit;
    frame_no_exception_1:;


    // Return statement must be present.
    assert(false);
function_exception_exit:
    assert( exception_type );
    PyErr_Restore( exception_type, exception_value, (PyObject *)exception_tb );
    return NULL;
function_return_exit:
    return tmp_return_value;

}
Пример #30
0
Файл: type.c Проект: zillow/ctds
PyObject* encode_for_dblib(PyObject* unicode, const char** utf8bytes, size_t* nutf8bytes, size_t* width)
{
    PyObject* encoded = NULL;

    do
    {
#if PY_MAJOR_VERSION >= 3
        Py_ssize_t size;
#endif /* if PY_MAJOR_VERSION >= 3 */

        PyObject* encodable;

#if defined(CTDS_USE_UTF16)
        size_t ix;

        /* FreeTDS supports encoding to UTF-16, so the whole string is encodable. */
        encodable = unicode;
        Py_INCREF(encodable);
#else /* if defined(CTDS_USE_UTF16) */
        /*
            FreeTDS will only convert strings to UCS-2, so translate all
            strings to UCS-2 prior to binding.
        */
        encodable = translate_to_ucs2(unicode);
        if (!encodable)
        {
            break;
        }
        /*
            If the string was translated to UCS-2, the SQL NCHAR width is simply
            the string length.
        */
#  if PY_VERSION_HEX >= 0x03030000
        *width = (size_t)PyUnicode_GET_LENGTH(encodable);
#  else
        *width = (size_t)PyUnicode_GET_SIZE(encodable);
#  endif
#endif /* else if defined(CTDS_USE_UTF16) */

#if PY_MAJOR_VERSION < 3
        encoded = PyUnicode_AsUTF8String(encodable);
        Py_DECREF(encodable);
        if (!encoded)
        {
            break;
        }

        *utf8bytes = PyString_AS_STRING(encoded);
        *nutf8bytes = (size_t)PyString_GET_SIZE(encoded);
#else /* if PY_MAJOR_VERSION < 3 */
        encoded = encodable; /* steal reference */

        *utf8bytes = PyUnicode_AsUTF8AndSize(encoded, &size);
        *nutf8bytes = (size_t)size;
#endif /* else if PY_MAJOR_VERSION < 3 */

#if defined(CTDS_USE_UTF16)
        /*
            Compute the SQL type width, which is really the number of UTF-16
            sequences.
        */
#define IS_UTF8_SINGLE_BYTE(b)       (((b) & 0x80) == 0)
#define IS_UTF8_CONTINUATION_BYTE(b) (((b) & 0xC0) == 0x80)
#define IS_UTF8_FIRST_BYTE_OF_2(b)   (((b) & 0xE0) == 0xC0)
#define IS_UTF8_FIRST_BYTE_OF_3(b)   (((b) & 0xF0) == 0xE0)
#define IS_UTF8_FIRST_BYTE_OF_4(b)   (((b) & 0xF8) == 0xF0)

        *width = 0;
        for (ix = 0; ix < *nutf8bytes;)
        {
            if (IS_UTF8_SINGLE_BYTE((*utf8bytes)[ix]))
            {
                ++(*width);
                ix += 1;
            }
            else if (IS_UTF8_FIRST_BYTE_OF_2((*utf8bytes)[ix]))
            {
                ++(*width);
                ix += 2;
            }
            else if (IS_UTF8_FIRST_BYTE_OF_3((*utf8bytes)[ix]))
            {
                ++(*width);
                ix += 3;
            }
            else
            {
                /* Two-byte UTF-16 sequences require double the width. */
                assert(IS_UTF8_FIRST_BYTE_OF_4((*utf8bytes)[ix]));
                (*width) += 2;
                ix += 4;
            }
        }
#endif /* if defined(CTDS_USE_UTF16) */

    }
    while (0);

    return encoded;
}