Esempio n. 1
0
static PyObject * Rules_match(
    PyObject *self,
    PyObject *args,
    PyObject *keywords)
{
  static char *kwlist[] = {
      "filepath", "pid", "data", "externals",
      "callback", "fast", "timeout", NULL
      };

  char* filepath = NULL;
  char* data = NULL;

  int pid = 0;
  int timeout = 0;
  int length;
  int error = ERROR_SUCCESS;
  int fast_mode = FALSE;

  PyObject *externals = NULL;
  PyObject *fast = NULL;

  Rules* object = (Rules*) self;

  CALLBACK_DATA callback_data;

  callback_data.matches = NULL;
  callback_data.callback = NULL;

  if (PyArg_ParseTupleAndKeywords(
        args,
        keywords,
        "|sis#OOOi",
        kwlist,
        &filepath,
        &pid,
        &data,
        &length,
        &externals,
        &callback_data.callback,
        &fast,
        &timeout))
  {
    if (filepath == NULL && data == NULL && pid == 0)
    {
      return PyErr_Format(
          PyExc_TypeError,
          "match() takes at least one argument");
    }

    if (callback_data.callback != NULL)
    {
      if (!PyCallable_Check(callback_data.callback))
      {
        return PyErr_Format(
            YaraError,
            "callback must be callable");
      }
    }

    if (externals != NULL)
    {
      if (PyDict_Check(externals))
      {
        if (!process_match_externals(externals, object->rules))
        {
          // Restore original externals provided during compiling.
          process_match_externals(object->externals, object->rules);

          return PyErr_Format(
              PyExc_TypeError,
              "external values must be of type integer, boolean or string");
        }
      }
      else
      {
        return PyErr_Format(
            PyExc_TypeError,
            "'externals' must be a dictionary");
      }
    }

    if (fast != NULL)
    {
      fast_mode = (PyObject_IsTrue(fast) == 1);
    }

    if (filepath != NULL)
    {
      callback_data.matches = PyList_New(0);

      Py_BEGIN_ALLOW_THREADS

      error = yr_rules_scan_file(
          object->rules,
          filepath,
          yara_callback,
          &callback_data,
          fast_mode,
          timeout);

      Py_END_ALLOW_THREADS
    }
    else if (data != NULL)
Esempio n. 2
0
File: msaio.c Progetto: Wyss/ProDy
static PyObject *writeSelex(PyObject *self, PyObject *args, PyObject *kwargs) {

    /* Write MSA where inputs are: labels in the form of Python lists
    and sequences in the form of Python numpy array and write them in
    SELEX (default) or Stockholm format in the specified filename.*/

    char *filename;
    PyObject *labels;
    PyArrayObject *msa;
    int stockholm;
    int label_length = 31;

    static char *kwlist[] = {"filename", "labels", "msa", "stockholm",
                             "label_length", NULL};

    if (!PyArg_ParseTupleAndKeywords(args, kwargs, "sOO|ii", kwlist, &filename,
                                     &labels, &msa, &stockholm, &label_length))
        return NULL;

    /* make sure to have a contiguous and well-behaved array */
    msa = PyArray_GETCONTIGUOUS(msa);

    long numseq = PyArray_DIMS(msa)[0], lenseq = PyArray_DIMS(msa)[1];

    if (numseq != PyList_Size(labels)) {
        PyErr_SetString(PyExc_ValueError,
                        "size of labels and msa array does not match");
        return NULL;
    }

    FILE *file = fopen(filename, "wb");

    int i, j;
    int pos = 0;
    char *seq = PyArray_DATA(msa);
    if (stockholm)
        fprintf(file, "# STOCKHOLM 1.0\n");

    char *outline = (char *) malloc((label_length + lenseq + 2) *
                                    sizeof(char));

    outline[label_length + lenseq] = '\n';
    outline[label_length + lenseq + 1] = '\0';

    #if PY_MAJOR_VERSION >= 3
    PyObject *plabel;
    #endif
    for (i = 0; i < numseq; i++) {
        #if PY_MAJOR_VERSION >= 3
        plabel = PyUnicode_AsEncodedString(
                PyList_GetItem(labels, (Py_ssize_t) i), "utf-8",
                               "label encoding");
        char *label =  PyBytes_AsString(plabel);
        Py_DECREF(plabel);
        #else
        char *label = PyString_AsString(PyList_GetItem(labels, (Py_ssize_t)i));
        #endif
        int labelbuffer = label_length - strlen(label);

        strcpy(outline, label);

        if (labelbuffer > 0)
            for(j = strlen(label); j < label_length; j++)
                outline[j] = ' ';

        for (j = label_length; j < (lenseq + label_length); j++)
            outline[j] = seq[pos++];

        fprintf(file, "%s", outline);
    }

    if (stockholm)
        fprintf(file, "//\n");

    free(outline);
    fclose(file);
    return Py_BuildValue("s", filename);
}
Esempio n. 3
0
static PyObject* symbolic(PyObject *self, PyObject *args,
    PyObject *kwrds)
{
    spmatrix *A;
    cholmod_sparse *Ac = NULL;
    cholmod_factor *L;
    matrix *P=NULL;
#if PY_MAJOR_VERSION >= 3
    int uplo_='L';
#endif
    char uplo='L';
    int n;
    char *kwlist[] = {"A", "p", "uplo", NULL};

    if (!set_options()) return NULL;

#if PY_MAJOR_VERSION >= 3
    if (!PyArg_ParseTupleAndKeywords(args, kwrds, "O|OC", kwlist, &A,
        &P, &uplo_)) return NULL;
    uplo = (char) uplo_;
#else
    if (!PyArg_ParseTupleAndKeywords(args, kwrds, "O|Oc", kwlist, &A,
        &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);

    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, "p is 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);
    CHOL(free_sparse)(&Ac, &Common);

    if (Common.status != CHOLMOD_OK){
        if (Common.status == CHOLMOD_OUT_OF_MEMORY)
            return PyErr_NoMemory();
        else{
            PyErr_SetString(PyExc_ValueError, "symbolic factorization "
                "failed");
            return NULL;
        }
    }
#if PY_MAJOR_VERSION >= 3
    return (PyObject *) PyCapsule_New((void *) L, SP_ID(A)==DOUBLE ?  
        (uplo == 'L' ?  "CHOLMOD FACTOR D L" : "CHOLMOD FACTOR D U") :
        (uplo == 'L' ?  "CHOLMOD FACTOR Z L" : "CHOLMOD FACTOR Z U"),
        (PyCapsule_Destructor) &cvxopt_free_cholmod_factor); 
#else
    return (PyObject *) PyCObject_FromVoidPtrAndDesc((void *) L,
        SP_ID(A)==DOUBLE ?  
        (uplo == 'L' ?  "CHOLMOD FACTOR D L" : "CHOLMOD FACTOR D U") :
        (uplo == 'L' ?  "CHOLMOD FACTOR Z L" : "CHOLMOD FACTOR Z U"),
	cvxopt_free_cholmod_factor);
#endif
}
Esempio n. 4
0
File: type.c Progetto: 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;
}
Esempio n. 5
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);
}
Esempio n. 6
0
// @pymethod |win32ts|WTSSetUserConfig|Changes user configuration
static PyObject *PyWTSSetUserConfig(PyObject *self, PyObject *args, PyObject *kwargs)
{
	static char *keywords[]={"ServerName","UserName","WTSConfigClass","Buffer",NULL};
	WCHAR *ServerName=NULL, *UserName=NULL;
	PyObject *obServerName, *obUserName, *obBuffer, *ret=NULL;
	WTS_CONFIG_CLASS WTSConfigClass;
	LPWSTR buf;
	WCHAR *wcharbuf=NULL;
	DWORD dwordbuf;
	DWORD bufsize;

	if (!PyArg_ParseTupleAndKeywords(args, kwargs, "OOkO:WTSSetUserConfig", keywords,
		&obServerName,	// @pyparm <o PyUnicode>|ServerName||Name ot terminal server
		&obUserName,	// @pyparm <o PyUnicode>|UserName||Name of user
		&WTSConfigClass,// @pyparm int|ConfigClass||Type of information to be set, win32ts.WTSUserConfig*
		&obBuffer))	
		return NULL;
	if (!PyWinObject_AsWCHAR(obServerName, &ServerName, TRUE))
		goto cleanup;
	if (!PyWinObject_AsWCHAR(obUserName, &UserName, FALSE))
		goto cleanup;

	switch(WTSConfigClass){
		// @flagh ConfigClass|Type of data required
		case WTSUserConfigInitialProgram:				// @flag WTSUserConfigInitialProgram|Unicode string, program to be run when user logs on
		case WTSUserConfigWorkingDirectory:				// @flag WTSUserConfigWorkingDirectory|Unicode string, working dir for initial program
		case WTSUserConfigModemCallbackPhoneNumber:		// @flag WTSUserConfigModemCallbackPhoneNumber|Unicode string
		case WTSUserConfigTerminalServerProfilePath:	// @flag WTSUserConfigTerminalServerProfilePath|Unicode string
		case WTSUserConfigTerminalServerHomeDir:		// @flag WTSUserConfigTerminalServerHomeDir|Unicode string
		case WTSUserConfigTerminalServerHomeDirDrive:	// @flag WTSUserConfigTerminalServerHomeDirDrive|Unicode string
			if (!PyWinObject_AsWCHAR(obBuffer, &wcharbuf, FALSE, &bufsize))
				goto cleanup;
			buf=wcharbuf;
			bufsize++;	// apparently has to include null terminator
			break;
		case WTSUserConfigfInheritInitialProgram:		// @flag WTSUserConfigfInheritInitialProgram|Int
		case WTSUserConfigfAllowLogonTerminalServer:	// @flag WTSUserConfigfAllowLogonTerminalServer|Int, 1 if user can log on thru Terminal Service
		case WTSUserConfigTimeoutSettingsConnections:	// @flag WTSUserConfigTimeoutSettingsConnections |Int, max connection time (ms)
		case WTSUserConfigTimeoutSettingsDisconnections:// @flag WTSUserConfigTimeoutSettingsDisconnections|Int
		case WTSUserConfigTimeoutSettingsIdle:			// @flag WTSUserConfigTimeoutSettingsIdle|Int, max idle time (ms)
		case WTSUserConfigfDeviceClientDrives:			// @flag WTSUserConfigfDeviceClientDrives|Int
		case WTSUserConfigfDeviceClientPrinters:		// @flag WTSUserConfigfDeviceClientPrinters|Int
		case WTSUserConfigfDeviceClientDefaultPrinter:	// @flag WTSUserConfigfDeviceClientDefaultPrinter|Int
		case WTSUserConfigBrokenTimeoutSettings:		// @flag WTSUserConfigBrokenTimeoutSettings|Int
		case WTSUserConfigReconnectSettings:			// @flag WTSUserConfigReconnectSettings|Int
		case WTSUserConfigModemCallbackSettings:		// @flag WTSUserConfigModemCallbackSettings|Int
		case WTSUserConfigShadowingSettings:			// @flag WTSUserConfigShadowingSettings|Int, indicates if user's session my be monitored
		case WTSUserConfigfTerminalServerRemoteHomeDir:	// @flag WTSUserConfigfTerminalServerRemoteHomeDir|Int,
			dwordbuf=PyLong_AsUnsignedLong(obBuffer);
			if (dwordbuf==(DWORD)-1 && PyErr_Occurred())
				goto cleanup;
			buf=(LPWSTR)&dwordbuf;
			bufsize=sizeof(dwordbuf);
			break;
		default:
			PyErr_SetString(PyExc_NotImplementedError,"Config class not supported yet");
			goto cleanup;
		}
	if (!WTSSetUserConfig(ServerName, UserName, WTSConfigClass, buf, bufsize))
		PyWin_SetAPIError("WTSQueryUserConfig");
	else{
		Py_INCREF(Py_None);
		ret=Py_None;
		}

	cleanup:
	PyWinObject_FreeWCHAR(ServerName);
	PyWinObject_FreeWCHAR(UserName);
	PyWinObject_FreeWCHAR(wcharbuf);
	return ret;
}
Esempio n. 7
0
File: player.cpp Progetto: foen/xbmc
  // play a file or python playlist
  PyObject* Player_Play(Player *self, PyObject *args, PyObject *kwds)
  {
    PyObject *pObject = NULL;
    PyObject *pObjectListItem = NULL;
    char bWindowed = false;
    static const char *keywords[] = { "item", "listitem", "windowed", NULL };

    if (!PyArg_ParseTupleAndKeywords(
      args,
      kwds,
      (char*)"|OOb",
      (char**)keywords,
      &pObject,
      &pObjectListItem,
      &bWindowed))
    {
      return NULL;
    }

    // set fullscreen or windowed
    g_settings.m_bStartVideoWindowed = (0 != bWindowed);

    // force a playercore before playing
    g_application.m_eForcedNextPlayer = self->playerCore;

    if (pObject == NULL)
    {
      // play current file in playlist
      if (g_playlistPlayer.GetCurrentPlaylist() != self->iPlayList)
      {
        g_playlistPlayer.SetCurrentPlaylist(self->iPlayList);
      }
      g_application.getApplicationMessenger().PlayListPlayerPlay(g_playlistPlayer.GetCurrentSong());
    }
    else if ((PyString_Check(pObject) || PyUnicode_Check(pObject)) && pObjectListItem != NULL && ListItem_CheckExact(pObjectListItem))
    {
      // an optional listitem was passed
      ListItem* pListItem = NULL;
      pListItem = (ListItem*)pObjectListItem;

      // set m_strPath to the passed url
      pListItem->item->m_strPath = PyString_AsString(pObject);

      g_application.getApplicationMessenger().PlayFile((const CFileItem)*pListItem->item, false);
    }
    else if (PyString_Check(pObject) || PyUnicode_Check(pObject))
    {
      CFileItem item(PyString_AsString(pObject), false);
      g_application.getApplicationMessenger().MediaPlay(item.m_strPath);
    }
    else if (PlayList_Check(pObject))
    {
      // play a python playlist (a playlist from playlistplayer.cpp)
      PlayList* pPlayList = (PlayList*)pObject;
      self->iPlayList = pPlayList->iPlayList;
      g_playlistPlayer.SetCurrentPlaylist(pPlayList->iPlayList);
      g_application.getApplicationMessenger().PlayListPlayerPlay();
    }

    Py_INCREF(Py_None);
    return Py_None;
  }
Esempio n. 8
0
static PyObject* 
PyGSL_multimin_set_f(PyGSL_solver *self, PyObject *pyargs, PyObject *kw) 
{

     PyObject* func = NULL, * args = Py_None, * x = NULL, * steps = NULL;
     PyArrayObject * xa = NULL, * stepsa = NULL;
     int n=0, flag=GSL_EFAILED;
     PyGSL_array_index_t stride_recalc;
     gsl_vector_view gsl_x;
     gsl_vector_view gsl_steps;
     gsl_multimin_function * c_sys = NULL;
     static const char *kwlist[] = {"f", "x0", "args", "steps", NULL};

     FUNC_MESS_BEGIN();
     assert(PyGSL_solver_check(self));     
     if (self->solver == NULL) {
	  pygsl_error("Got a NULL Pointer of min.f",  filename, __LINE__ - 3, GSL_EFAULT);
	  return NULL;
     }

     assert(pyargs);
     /* arguments PyFunction, Parameters, start Vector, step Vector */
     if (0==PyArg_ParseTupleAndKeywords(pyargs,kw,"OOOO", (char **)kwlist, &func,
					&x,&args,&steps))
	  return NULL;

     if(!PyCallable_Check(func)){
	  pygsl_error("First argument must be callable",  filename, __LINE__ - 3, GSL_EBADFUNC);
	  return NULL;	  
     }
     n=self->problem_dimensions[0]; 
     xa  = PyGSL_vector_check(x, n, PyGSL_DARRAY_INPUT(4), &stride_recalc, NULL);
     if (xa == NULL){
	  PyGSL_add_traceback(module, filename, __FUNCTION__, __LINE__ - 1);
	  goto fail;
     }

     gsl_x = gsl_vector_view_array_with_stride((double *)(xa->data), stride_recalc, xa->dimensions[0]);
     stepsa =  PyGSL_vector_check(steps, n, PyGSL_DARRAY_INPUT(5), &stride_recalc, NULL);
     if (stepsa == NULL){
	  PyGSL_add_traceback(module, filename, __FUNCTION__, __LINE__ - 1);
	  goto fail;
     }
     gsl_steps = gsl_vector_view_array_with_stride((double *)(stepsa->data), stride_recalc, stepsa->dimensions[0]);

     if (self->c_sys != NULL) {
	  /* free the previous function and args */
	  c_sys = self->c_sys;
     } else {
	  /* allocate function space */
	  c_sys=calloc(1, sizeof(gsl_multimin_function));
	  if (c_sys == NULL) {
	       pygsl_error("Could not allocate the object for the minimizer function", 
			 filename, __LINE__ - 3, GSL_ENOMEM);
	       goto fail;
	  }
     }
     DEBUG_MESS(3, "Everything allocated args = %p", args);
     /* add new function  and parameters */

     if(PyGSL_solver_func_set(self, args, func, NULL, NULL) != GSL_SUCCESS)
	  goto fail;
     
     /* initialize the function struct */
     c_sys->n=n;
     c_sys->f=PyGSL_multimin_function_f;
     c_sys->params=(void*)self;
     
     DEBUG_MESS(3, "Setting jmp buffer isset = % d", self->isset);
     if((flag = setjmp(self->buffer)) == 0){
	  self->isset = 1;
	  flag = gsl_multimin_fminimizer_set(self->solver,c_sys, &gsl_x.vector, &gsl_steps.vector);
	  if(PyGSL_ERROR_FLAG(flag) != GSL_SUCCESS){
	       goto fail;
	  }
     } else {
	  goto fail;
     }
     DEBUG_MESS(4, "Set evaluated. flag = %d", flag);
     self->c_sys = c_sys;
     Py_DECREF(xa);
     Py_DECREF(stepsa);
     self->set_called = 1;

     Py_INCREF(Py_None);
     self->isset = 0;
     FUNC_MESS_END();
     return Py_None;

     
 fail:
     FUNC_MESS("Fail");
     PyGSL_ERROR_FLAG(flag);
     self->isset = 0;
     Py_XDECREF(xa);
     Py_XDECREF(stepsa);
     return NULL;
     
}
Esempio n. 9
0
static PyObject* 
PyGSL_multimin_set_fdf(PyGSL_solver *self, PyObject *pyargs, PyObject *kw) 
{

     PyObject * f = NULL, * df = NULL, * fdf = NULL, * args = Py_None,
	      * x = NULL;
     PyArrayObject * xa = NULL;
     int n=0, flag=GSL_EFAILED;
     PyGSL_array_index_t stride_recalc=-1;
     double step=0.01, tol=1e-4;
     gsl_vector_view gsl_x;
     gsl_multimin_function_fdf * c_sys;
     static const char *kwlist[] = {"f", "df", "fdf",  "x0", "args", "step", "tol", NULL};

     FUNC_MESS_BEGIN();
     assert(PyGSL_solver_check(self));     
     if (self->solver == NULL) {
	  pygsl_error("Got a NULL Pointer of min.fdf", filename, __LINE__ - 3, GSL_EFAULT);
	       return NULL;
	  }	  

     /* arguments PyFunction, Parameters, start Vector, step Vector */
     if (0==PyArg_ParseTupleAndKeywords(pyargs, kw, "OOOO|Odd", (char **)kwlist, 
					&f, &df, &fdf, &x, &args, &step, &tol))
	  return NULL;

     n=self->problem_dimensions[0];
     xa  = PyGSL_vector_check(x, n, PyGSL_DARRAY_INPUT(4), &stride_recalc, NULL);
     if (xa == NULL){
	  PyGSL_add_traceback(module, filename, __FUNCTION__, __LINE__ - 1);
	  goto fail;
     }
     gsl_x = gsl_vector_view_array_with_stride((double *)(xa->data), stride_recalc, xa->dimensions[0]);


     if (self->c_sys != NULL) {
	  /* free the previous function and args */
	  c_sys = self->c_sys;
     } else {
	  /* allocate function space */
	  c_sys=malloc(sizeof(gsl_multimin_function_fdf));
	  if (c_sys==NULL) {
	       pygsl_error("Could not allocate the object for the minimizer function", 
			 filename, __LINE__ - 3, GSL_ENOMEM);
	       goto fail;
	  }
     }
     if(PyGSL_solver_func_set(self, args, f, df, fdf) != GSL_SUCCESS)
	  goto fail;
     
     /* initialize the function struct */
     c_sys->n=n;
     c_sys->f  =PyGSL_multimin_function_f;
     c_sys->df =PyGSL_multimin_function_df;  
     c_sys->fdf=PyGSL_multimin_function_fdf;
     c_sys->params=(void*)self;

     if((flag = setjmp(self->buffer)) == 0){
	  self->isset = 1;	  
	  flag = gsl_multimin_fdfminimizer_set(self->solver, c_sys, &gsl_x.vector, step, tol);
	  if(PyGSL_ERROR_FLAG(flag) != GSL_SUCCESS){
	       goto fail;
	  }
     }else{
	  goto fail;
     }
     self->c_sys = c_sys;
     self->isset = 0;
     Py_DECREF(xa);
     self->set_called = 1;

     Py_INCREF(Py_None);
     FUNC_MESS_END();
     return Py_None;

 fail:
     PyGSL_ERROR_FLAG(flag);
     self->isset = 0;
     Py_XDECREF(xa);
     return NULL;
     
}
Esempio n. 10
0
static PyObject *
pylzma_calculate_key(PyObject *self, PyObject *args, PyObject *kwargs)
{
    char *password;
    int pwlen;
    int cycles;
    PyObject *pysalt=NULL;
    char *salt;
    int saltlen;
    char *digest="sha256";
    char key[32];
    // possible keywords for this function
    static char *kwlist[] = {"password", "cycles", "salt", "digest", NULL};

    if (!PyArg_ParseTupleAndKeywords(args, kwargs, "s#i|Os", kwlist, &password, &pwlen, &cycles, &pysalt, &digest))
        return NULL;
    
    if (pysalt == Py_None) {
        pysalt = NULL;
    } else if (!PyString_Check(pysalt)) {
        PyErr_Format(PyExc_TypeError, "salt must be a string, got a %s", pysalt->ob_type->tp_name);
        return NULL;
    }
    
    if (strcmp(digest, "sha256") != 0) {
        PyErr_Format(PyExc_TypeError, "digest %s is unsupported", digest);
        return NULL;
    }
    
    if (pysalt != NULL) {
        salt = PyString_AS_STRING(pysalt);
        saltlen = PyString_Size(pysalt);
    } else {
        salt = NULL;
        saltlen = 0;
    }
    
    if (cycles == 0x3f) {
        int pos;
        int i;
        for (pos = 0; pos < saltlen; pos++)
            key[pos] = salt[pos];
        for (i = 0; i<pwlen && pos < 32; i++)
            key[pos++] = password[i];
        for (; pos < 32; pos++)
            key[pos] = 0;
    } else {
        CSha256 sha;
        long round;
        int i;
        long rounds = (long) 1 << cycles;
        unsigned char temp[8] = { 0,0,0,0,0,0,0,0 };
        Py_BEGIN_ALLOW_THREADS
        Sha256_Init(&sha);
        for (round = 0; round < rounds; round++) {
            Sha256_Update(&sha, (Byte *) salt, saltlen);
            Sha256_Update(&sha, (Byte *) password, pwlen);
            Sha256_Update(&sha, (Byte *) temp, 8);
            for (i = 0; i < 8; i++)
                if (++(temp[i]) != 0)
                    break;
        }
        Sha256_Final(&sha, (Byte *) &key);
        Py_END_ALLOW_THREADS
    }
    
    return PyString_FromStringAndSize(key, 32);
}
Esempio n. 11
0
static PyObject *py_parse_tree(PyObject *self, PyObject *args, PyObject *kw)
{
    char *text, *start, *end;
    int len, namelen, strict;
    PyObject *ret, *item, *name, *sha, *py_strict = NULL;
    static char *kwlist[] = {"text", "strict", NULL};

    if (!PyArg_ParseTupleAndKeywords(args, kw, "s#|O", kwlist,
                                     &text, &len, &py_strict))
        return NULL;
    strict = py_strict ?  PyObject_IsTrue(py_strict) : 0;
    /* TODO: currently this returns a list; if memory usage is a concern,
     * consider rewriting as a custom iterator object */
    ret = PyList_New(0);
    if (ret == NULL) {
        return NULL;
    }
    start = text;
    end = text + len;
    while (text < end) {
        long mode;
        if (strict && text[0] == '0') {
            PyErr_SetString(object_format_exception_cls,
                            "Illegal leading zero on mode");
            Py_DECREF(ret);
            return NULL;
        }
        mode = strtol(text, &text, 8);
        if (*text != ' ') {
            PyErr_SetString(PyExc_ValueError, "Expected space");
            Py_DECREF(ret);
            return NULL;
        }
        text++;
        namelen = strnlen(text, len - (text - start));
        name = PyString_FromStringAndSize(text, namelen);
        if (name == NULL) {
            Py_DECREF(ret);
            return NULL;
        }
        if (text + namelen + 20 >= end) {
            PyErr_SetString(PyExc_ValueError, "SHA truncated");
            Py_DECREF(ret);
            Py_DECREF(name);
            return NULL;
        }
        sha = sha_to_pyhex((unsigned char *)text+namelen+1);
        if (sha == NULL) {
            Py_DECREF(ret);
            Py_DECREF(name);
            return NULL;
        }
        item = Py_BuildValue("(NlN)", name, mode, sha);
        if (item == NULL) {
            Py_DECREF(ret);
            Py_DECREF(sha);
            Py_DECREF(name);
            return NULL;
        }
        if (PyList_Append(ret, item) == -1) {
            Py_DECREF(ret);
            Py_DECREF(item);
            return NULL;
        }
        Py_DECREF(item);
        text += namelen+21;
    }
    return ret;
}
Esempio n. 12
0
static PyObject * enz_vnmpocnp(PyObject *self, PyObject *args,
			       PyObject *keywds)
{
	static char *kwlist[] = { "r",		 "f",		"n",	       "m",	"L_max",
				  "bessel_name", "ncpus",	"verb",	       NULL };
	long syscpus = sysconf(_SC_NPROCESSORS_ONLN);

	PyObject *r_o, *f_o, *n_o, *m_o;
	PyObject *r = NULL;
	PyObject *f = NULL;
	PyObject *n = NULL;
	PyObject *m = NULL;
	const char *error = NULL;
	npy_intp r_n, f_n, beta_n;

	PyObject *vnm = NULL;
	npy_intp vnm_dims[3];

	double *datar = NULL;
	complex double *dataf = NULL;
	int *datan = NULL;
	int *datam = NULL;
	complex double *datap = NULL;

	int kL_max = 35;
	int kncpus = -1;
	int kverb = 0;
	char *kbessel_name = "jn";
	int ret;

	if (syscpus <= 0)
		syscpus = 1;

	if (!PyArg_ParseTupleAndKeywords(args, keywds, "O!O!O!O!|isii",
					 kwlist,
					 &PyArray_Type, &r_o,
					 &PyArray_Type, &f_o,
					 &PyArray_Type, &n_o,
					 &PyArray_Type, &m_o,
					 &kL_max, &kbessel_name, &kncpus, &kverb)) {
		PyErr_SetString(PyExc_SyntaxError, "failed to parse args");
		return NULL;
	}

	r = PyArray_FROM_OTF(r_o, NPY_FLOAT64, NPY_ARRAY_IN_ARRAY);
	f = PyArray_FROM_OTF(f_o, NPY_COMPLEX128, NPY_ARRAY_IN_ARRAY);
	n = PyArray_FROM_OTF(n_o, NPY_INT64, NPY_ARRAY_IN_ARRAY);
	m = PyArray_FROM_OTF(m_o, NPY_INT64, NPY_ARRAY_IN_ARRAY);

	if (!r) {
		PyErr_SetString(PyExc_ValueError, "cannot convert r to PyArray");
		return NULL;
	}
	if (!f) {
		PyErr_SetString(PyExc_ValueError, "cannot convert f to PyArray");
		return NULL;
	}
	if (!n) {
		PyErr_SetString(PyExc_ValueError, "cannot convert n to PyArray");
		return NULL;
	}
	if (!m) {
		PyErr_SetString(PyExc_ValueError, "cannot convert m to PyArray");
		return NULL;
	}

	if (!r || not_vect(r) || PyArray_TYPE((PyArrayObject*)r) != NPY_FLOAT64) {
		error = "r is not a vector of doubles";
		goto exit_decrement;
	}
	r_n = PyArray_DIM((PyArrayObject*)r, 0);

	if (!f || not_vect(f) ||
	    PyArray_TYPE((PyArrayObject*)f) != NPY_COMPLEX128) {
		error = "f is not a vector of complex numbers";
		goto exit_decrement;
	}
	f_n = PyArray_DIM((PyArrayObject*)f, 0);

	if (!n || not_vect(n) || PyArray_TYPE((PyArrayObject*)n) != NPY_INT64) {
		error = "n is not a vector of integers";
		goto exit_decrement;
	}
	if (!m || not_vect(m) || PyArray_TYPE((PyArrayObject*)m) != NPY_INT64) {
		error = "m is not a vector of integers";
		goto exit_decrement;
	}
	if (PyArray_DIM((PyArrayObject*)n, 0) !=
	    PyArray_DIM((PyArrayObject*)m, 0)) {
		error = "n and m must have the same length";
		goto exit_decrement;
	}
	beta_n = PyArray_DIM((PyArrayObject*)n, 0);

	vnm_dims[0] = r_n;
	vnm_dims[1] = f_n;
	vnm_dims[2] = beta_n;

	vnm = PyArray_New(&PyArray_Type, 3, vnm_dims, NPY_COMPLEX128, NULL, NULL,
			  0, NPY_ARRAY_F_CONTIGUOUS | NPY_ARRAY_ALIGNED, NULL);

	if (!vnm) {
		error = "cannot create vnm";
		goto exit_decrement;
	}

	PyArray_CLEARFLAGS((PyArrayObject*)vnm, NPY_ARRAY_C_CONTIGUOUS);

	assert(PyArray_Size(vnm) == (r_n * f_n * beta_n));
	assert(PyArray_NBYTES(vnm) == (r_n * f_n * beta_n * sizeof(double complex)));
	datap = PyArray_DATA((PyArrayObject*)vnm);

	if (kncpus < 0)
		kncpus = beta_n < syscpus ? beta_n : syscpus;
	else
		kncpus = kncpus > syscpus ? syscpus : kncpus;

	if ((r_n * f_n * beta_n) != 0) {
		datar = PyArray_DATA((PyArrayObject*)r);
		dataf = PyArray_DATA((PyArrayObject*)f);
		datan = PyArray_DATA((PyArrayObject*)n);
		datam = PyArray_DATA((PyArrayObject*)m);
		Py_BEGIN_ALLOW_THREADS
			ret = vnmpocnp(r_n, datar,
				       f_n, dataf,
				       beta_n,
				       datan, datam,
				       kL_max, kbessel_name,
				       kncpus,
				       kverb, datap, &error);
		Py_END_ALLOW_THREADS
		if (ret) {
			Py_XDECREF(vnm);
			goto exit_decrement;
		}
	}
Esempio n. 13
0
static PyObject* openSPI(PyObject *self, PyObject *args, PyObject *kwargs)
{

	static char* kwlist[] = {"device", "mode", "bits", "speed", "delay", NULL};

	// Adding some sort of mode parsing would probably be a nice idea for the future, so you don't have to specify it as a bitfield
	// stuffed into an int.
	// For the moment the default mode ("0"), will probably work for 99% of people who need a SPI interface, so I'm not working on that
	//


	if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|siiii:keywords", kwlist, &device, &mode, &bits, &speed, &delay))
		return NULL;
	// It's not clearly documented, but it seems that PyArg_ParseTupleAndKeywords basically only modifies the values passed to it if the
	// keyword pertaining to that value is passed to the function. As such, the defaults specified by the variable definition are used
	// unless you pass a kwd argument.
	// Note that there isn't any proper bounds-checking, so if you pass a value that exceeds the variable size, it's just truncated before
	// being stuffed into  the avasilable space. For example, passing a bits-per-word of 500 gets truncated to 244. Unfortunately, the
	// PyArg_ParseTupleAndKeywords function only seems to support ints of 32 bits.

	PyErr_Clear();

	printf("Mode: %i, Bits: %i, Speed: %i, Delay: %i\n", mode, bits, speed, delay);



	fd = open(device, O_RDWR);
	if (fd < 0)
		pabort("can't open device");

	/*
	 * Setup SPI mode
	 */
	ret = ioctl(fd, SPI_IOC_WR_MODE, &mode);
	if (ret == -1)
		pabort("can't set spi mode");

	ret = ioctl(fd, SPI_IOC_RD_MODE, &mode);
	if (ret == -1)
		pabort("can't get spi mode");

	/*
	 * bits per word
	 */
	ret = ioctl(fd, SPI_IOC_WR_BITS_PER_WORD, &bits);
	if (ret == -1)
		pabort("can't set bits per word");

	ret = ioctl(fd, SPI_IOC_RD_BITS_PER_WORD, &bits);
	if (ret == -1)
		pabort("can't get bits per word");

	/*
	 * max speed hz
	 */
	ret = ioctl(fd, SPI_IOC_WR_MAX_SPEED_HZ, &speed);
	if (ret == -1)
		pabort("can't set max speed hz");

	ret = ioctl(fd, SPI_IOC_RD_MAX_SPEED_HZ, &speed);
	if (ret == -1)
		pabort("can't get max speed hz");

	// Stuff the various initilization parameters into a dict, and return that.
	// Note that the returned values may not be completely real. It seems that, at least for the speed value,
	// the hardware only has several possible settings (250000, 500000, 1000000, etc...) Strangely enough, the
	// ioctl for setting the speed *returns the speed you specify*. However, the hardware seems to default to the
	// closest avalable value *below* the specified rate. (i.e. you will never get a speed faster then you spec),
	// but you may get a slower value.

	//It would probably be a good idea to bin-down the passed arguement to the available values, and return
	// that.

	PyObject* retDict;
	retDict = PyDict_New();

	PyDict_SetItem(retDict, PyString_FromString("mode"), PyInt_FromLong((long)mode));
	PyDict_SetItem(retDict, PyString_FromString("bits"), PyInt_FromLong((long)bits));
	PyDict_SetItem(retDict, PyString_FromString("speed"), PyInt_FromLong((long)speed));
	PyDict_SetItem(retDict, PyString_FromString("delay"), PyInt_FromLong((long)delay));


	return retDict;
}
Esempio n. 14
0
static PyObject *
warnings_warn_explicit(PyObject *self, PyObject *args, PyObject *kwds)
{
    static char *kwd_list[] = {"message", "category", "filename", "lineno",
                                "module", "registry", "module_globals", 0};
    PyObject *message;
    PyObject *category;
    PyObject *filename;
    int lineno;
    PyObject *module = NULL;
    PyObject *registry = NULL;
    PyObject *module_globals = NULL;

    if (!PyArg_ParseTupleAndKeywords(args, kwds, "OOUi|OOO:warn_explicit",
                kwd_list, &message, &category, &filename, &lineno, &module,
                &registry, &module_globals))
        return NULL;

    if (module_globals) {
        _Py_IDENTIFIER(get_source);
        _Py_IDENTIFIER(splitlines);
        PyObject *tmp;
        PyObject *loader;
        PyObject *module_name;
        PyObject *source;
        PyObject *source_list;
        PyObject *source_line;
        PyObject *returned;

        if ((tmp = _PyUnicode_FromId(&PyId_get_source)) == NULL)
            return NULL;
        if ((tmp = _PyUnicode_FromId(&PyId_splitlines)) == NULL)
            return NULL;

        /* Check/get the requisite pieces needed for the loader. */
        loader = PyDict_GetItemString(module_globals, "__loader__");
        module_name = PyDict_GetItemString(module_globals, "__name__");

        if (loader == NULL || module_name == NULL)
            goto standard_call;

        /* Make sure the loader implements the optional get_source() method. */
        if (!_PyObject_HasAttrId(loader, &PyId_get_source))
                goto standard_call;
        /* Call get_source() to get the source code. */
        source = PyObject_CallMethodObjArgs(loader, PyId_get_source.object,
                                            module_name, NULL);
        if (!source)
            return NULL;
        else if (source == Py_None) {
            Py_DECREF(Py_None);
            goto standard_call;
        }

        /* Split the source into lines. */
        source_list = PyObject_CallMethodObjArgs(source,
                                                 PyId_splitlines.object,
                                                 NULL);
        Py_DECREF(source);
        if (!source_list)
            return NULL;

        /* Get the source line. */
        source_line = PyList_GetItem(source_list, lineno-1);
        if (!source_line) {
            Py_DECREF(source_list);
            return NULL;
        }

        /* Handle the warning. */
        returned = warn_explicit(category, message, filename, lineno, module,
                                 registry, source_line);
        Py_DECREF(source_list);
        return returned;
    }

 standard_call:
    return warn_explicit(category, message, filename, lineno, module,
                         registry, NULL);
}
Esempio n. 15
0
static PyObject*
faulthandler_enable(PyObject *self, PyObject *args, PyObject *kwargs)
{
    static char *kwlist[] = {"file", "all_threads", NULL};
    PyObject *file = NULL;
    int all_threads = 0;
    unsigned int i;
    fault_handler_t *handler;
#ifdef HAVE_SIGACTION
    struct sigaction action;
#endif
    int err;
    int fd;

    if (!PyArg_ParseTupleAndKeywords(args, kwargs,
        "|Oi:enable", kwlist, &file, &all_threads))
        return NULL;

    file = faulthandler_get_fileno(file, &fd);
    if (file == NULL)
        return NULL;

    Py_XDECREF(fatal_error.file);
    Py_INCREF(file);
    fatal_error.file = file;
    fatal_error.fd = fd;
    fatal_error.all_threads = all_threads;

    if (!fatal_error.enabled) {
        fatal_error.enabled = 1;

        for (i=0; i < faulthandler_nsignals; i++) {
            handler = &faulthandler_handlers[i];
#ifdef HAVE_SIGACTION
            action.sa_sigaction = faulthandler_fatal_error;
            sigemptyset(&action.sa_mask);
            /* Do not prevent the signal from being received from within
               its own signal handler */
            action.sa_flags = SA_NODEFER;
#ifdef HAVE_SIGALTSTACK
            if (stack.ss_sp != NULL) {
                /* Call the signal handler on an alternate signal stack
                   provided by sigaltstack() */
                action.sa_flags |= SA_ONSTACK;
            }
#endif
            err = sigaction(handler->signum, &action, &handler->previous);
#else
            handler->previous = signal(handler->signum,
                                       faulthandler_fatal_error);
            err = (handler->previous == SIG_ERR);
#endif
            if (err) {
                PyErr_SetFromErrno(PyExc_RuntimeError);
                return NULL;
            }
            handler->enabled = 1;
        }
    }
    Py_RETURN_NONE;
}
Esempio n. 16
0
/*! 02.01.2007 - 05.01.2007 : Joachim Neu : Create a paragraph style.
			Special thanks go to avox for helping me! */
PyObject *scribus_createparagraphstyle(PyObject* /* self */, PyObject* args, PyObject* keywords)
{
	//TODO - new paragraph properties for bullets and numbering
	char* keywordargs[] = {
			const_cast<char*>("name"),
			const_cast<char*>("linespacingmode"),
			const_cast<char*>("linespacing"),
			const_cast<char*>("alignment"),
			const_cast<char*>("leftmargin"),
			const_cast<char*>("rightmargin"),
			const_cast<char*>("gapbefore"),
			const_cast<char*>("gapafter"),
			const_cast<char*>("firstindent"),
			const_cast<char*>("hasdropcap"),
			const_cast<char*>("dropcaplines"),
			const_cast<char*>("dropcapoffset"),
			const_cast<char*>("charstyle"),
			NULL};
	char *Name = const_cast<char*>(""), *CharStyle = const_cast<char*>("");
	int LineSpacingMode = 0, Alignment = 0, DropCapLines = 2, HasDropCap = 0;
	double LineSpacing = 15.0, LeftMargin = 0.0, RightMargin = 0.0;
	double GapBefore = 0.0, GapAfter = 0.0, FirstIndent = 0.0, PEOffset = 0;
	if (!PyArg_ParseTupleAndKeywords(args, keywords, "es|ididddddiides",
		 keywordargs, "utf-8", &Name, &LineSpacingMode, &LineSpacing, &Alignment,
		&LeftMargin, &RightMargin, &GapBefore, &GapAfter, &FirstIndent,
		&HasDropCap, &DropCapLines, &PEOffset, "utf-8", &CharStyle))
		return NULL;
	if(!checkHaveDocument())
		return NULL;
	if (strlen(Name) == 0)
	{
		PyErr_SetString(PyExc_ValueError, QObject::tr("Cannot have an empty paragraph style name.","python error").toLocal8Bit().constData());
		return NULL;
	}

	ParagraphStyle TmpParagraphStyle;
	TmpParagraphStyle.setName(Name);
	TmpParagraphStyle.setLineSpacingMode((ParagraphStyle::LineSpacingMode)LineSpacingMode);
	TmpParagraphStyle.setLineSpacing(LineSpacing);
	TmpParagraphStyle.setAlignment((ParagraphStyle::AlignmentType)Alignment);
	TmpParagraphStyle.setLeftMargin(LeftMargin);
	TmpParagraphStyle.setFirstIndent(FirstIndent);
	TmpParagraphStyle.setRightMargin(RightMargin);
	TmpParagraphStyle.setGapBefore(GapBefore);
	TmpParagraphStyle.setGapAfter(GapAfter);
	if(HasDropCap == 0)
		TmpParagraphStyle.setHasDropCap(false);
	else if(HasDropCap == 1)
		TmpParagraphStyle.setHasDropCap(true);
	else
	{
		PyErr_SetString(PyExc_ValueError, QObject::tr("hasdropcap has to be 0 or 1.","python error").toLocal8Bit().constData());
		return NULL;
	}
	TmpParagraphStyle.setDropCapLines(DropCapLines);
	TmpParagraphStyle.setParEffectOffset(PEOffset);
	TmpParagraphStyle.charStyle().setParent(CharStyle);

	StyleSet<ParagraphStyle> TmpStyleSet;
	TmpStyleSet.create(TmpParagraphStyle);
	ScCore->primaryMainWindow()->doc->redefineStyles(TmpStyleSet, false);
	// PV - refresh the Style Manager window.
	// I thought that this can work but it doesn't:
	// ScCore->primaryMainWindow()->styleMgr()->reloadStyleView();
	// So the brute force setDoc is called...
	ScCore->primaryMainWindow()->styleMgr()->setDoc(ScCore->primaryMainWindow()->doc);

	Py_RETURN_NONE;
}
Esempio n. 17
0
static PyObject*
faulthandler_register(PyObject *self,
                      PyObject *args, PyObject *kwargs)
{
    static char *kwlist[] = {"signum", "file", "all_threads", NULL};
    int signum;
    PyObject *file = NULL;
    int all_threads = 0;
    int fd;
    user_signal_t *user;
    _Py_sighandler_t previous;
#ifdef HAVE_SIGACTION
    struct sigaction action;
#endif
    PyThreadState *tstate;
    int err;

    if (!PyArg_ParseTupleAndKeywords(args, kwargs,
        "i|Oi:register", kwlist,
        &signum, &file, &all_threads))
        return NULL;

    if (!check_signum(signum))
        return NULL;

    /* The caller holds the GIL and so PyThreadState_Get() can be used */
    tstate = PyThreadState_Get();
    if (tstate == NULL) {
        PyErr_SetString(PyExc_RuntimeError,
                        "unable to get the current thread state");
        return NULL;
    }

    file = faulthandler_get_fileno(file, &fd);
    if (file == NULL)
        return NULL;

    if (user_signals == NULL) {
        user_signals = calloc(NSIG, sizeof(user_signal_t));
        if (user_signals == NULL)
            return PyErr_NoMemory();
    }
    user = &user_signals[signum];

    if (!user->enabled) {
#ifdef HAVE_SIGACTION
        action.sa_handler = faulthandler_user;
        sigemptyset(&action.sa_mask);
        /* if the signal is received while the kernel is executing a system
           call, try to restart the system call instead of interrupting it and
           return EINTR */
        action.sa_flags = SA_RESTART;
#ifdef HAVE_SIGALTSTACK
        if (stack.ss_sp != NULL) {
            /* Call the signal handler on an alternate signal stack
               provided by sigaltstack() */
            action.sa_flags |= SA_ONSTACK;
        }
#endif
        err = sigaction(signum, &action, &previous);
#else
        previous = signal(signum, faulthandler_user);
        err = (previous == SIG_ERR);
#endif
        if (err) {
            PyErr_SetFromErrno(PyExc_OSError);
            return NULL;
        }
    }

    Py_XDECREF(user->file);
    Py_INCREF(file);
    user->file = file;
    user->fd = fd;
    user->all_threads = all_threads;
    user->previous = previous;
    user->interp = tstate->interp;
    user->enabled = 1;

    Py_RETURN_NONE;
}
Esempio n. 18
0
/*! 03.01.2007 - 05.01.2007 : Joachim Neu : Create a char style.
			Special thanks go to avox for helping me! */
PyObject *scribus_createcharstyle(PyObject* /* self */, PyObject* args, PyObject* keywords)
{
	char* keywordargs[] = {
					  							const_cast<char*>("name"),
					  							const_cast<char*>("font"),
					  							const_cast<char*>("fontsize"),
												const_cast<char*>("fontfeatures"),
					  							const_cast<char*>("features"),
					  							const_cast<char*>("fillcolor"),
					  							const_cast<char*>("fillshade"),
					  							const_cast<char*>("strokecolor"),
					  							const_cast<char*>("strokeshade"),
					  							const_cast<char*>("baselineoffset"),
					  							const_cast<char*>("shadowxoffset"),
					  							const_cast<char*>("shadowyoffset"),
					  							const_cast<char*>("outlinewidth"),
					  							const_cast<char*>("underlineoffset"),
					  							const_cast<char*>("underlinewidth"),
					  							const_cast<char*>("strikethruoffset"),
					  							const_cast<char*>("strikethruwidth"),
					  							const_cast<char*>("scaleh"),
					  							const_cast<char*>("scalev"),
					  							const_cast<char*>("tracking"),
					  							const_cast<char*>("language"),
					  						NULL};
	char *Name = const_cast<char*>(""), *Font = const_cast<char*>("Times"), *Features = const_cast<char*>("inherit"), *FillColor = const_cast<char*>("Black"), *FontFeatures = const_cast<char*>(""), *StrokeColor = const_cast<char*>("Black"), *Language = const_cast<char*>("");
	double FontSize = 200, FillShade = 1, StrokeShade = 1, ScaleH = 1, ScaleV = 1, BaselineOffset = 0, ShadowXOffset = 0, ShadowYOffset = 0, OutlineWidth = 0, UnderlineOffset = 0, UnderlineWidth = 0, StrikethruOffset = 0, StrikethruWidth = 0, Tracking = 0;
	if (!PyArg_ParseTupleAndKeywords(args, keywords, "es|esdesesdesddddddddddddes", keywordargs,
																									"utf-8", &Name, "utf-8", &Font, &FontSize, "utf-8", &Features,
																									"utf-8", &FillColor, &FillShade, "utf-8", &StrokeColor, &StrokeShade, &BaselineOffset, &ShadowXOffset,
																									&ShadowYOffset, &OutlineWidth, &UnderlineOffset, &UnderlineWidth, &StrikethruOffset, &StrikethruWidth,
																									&ScaleH, &ScaleV, &Tracking, "utf-8", &Language))
		return NULL;
	if(!checkHaveDocument())
		return NULL;
	if (strlen(Name) == 0)
	{
		PyErr_SetString(PyExc_ValueError, QObject::tr("Cannot have an empty char style name.","python error").toLocal8Bit().constData());
		return NULL;
	}

	QStringList FeaturesList = QString(Features).split(QString(","));

	CharStyle TmpCharStyle;
	TmpCharStyle.setName(Name);
	TmpCharStyle.setFont((*ScCore->primaryMainWindow()->doc->AllFonts)[QString(Font)]);
	TmpCharStyle.setFontSize(FontSize * 10);
	TmpCharStyle.setFontFeatures(FontFeatures);
	TmpCharStyle.setFeatures(FeaturesList);
	TmpCharStyle.setFillColor(QString(FillColor));
	TmpCharStyle.setFillShade(FillShade * 100);
	TmpCharStyle.setStrokeColor(QString(StrokeColor));
	TmpCharStyle.setStrokeShade(StrokeShade * 100);
	TmpCharStyle.setBaselineOffset(BaselineOffset);
	TmpCharStyle.setShadowXOffset(ShadowXOffset);
	TmpCharStyle.setShadowYOffset(ShadowYOffset);
	TmpCharStyle.setOutlineWidth(OutlineWidth);
	TmpCharStyle.setUnderlineOffset(UnderlineOffset);
	TmpCharStyle.setUnderlineWidth(UnderlineWidth);
	TmpCharStyle.setStrikethruOffset(StrikethruOffset);
	TmpCharStyle.setStrikethruWidth(StrikethruWidth);
	TmpCharStyle.setScaleH(ScaleH * 1000);
	TmpCharStyle.setScaleV(ScaleV * 1000);
	TmpCharStyle.setTracking(Tracking);
	TmpCharStyle.setLanguage(QString(Language));

	StyleSet<CharStyle> TmpStyleSet;
	TmpStyleSet.create(TmpCharStyle);
	ScCore->primaryMainWindow()->doc->redefineCharStyles(TmpStyleSet, false);
	// PV - refresh the Style Manager window.
	// I thought that this can work but it doesn't:
	// ScCore->primaryMainWindow()->styleMgr()->reloadStyleView();
	// So the brute force setDoc is called...
	ScCore->primaryMainWindow()->styleMgr()->setDoc(ScCore->primaryMainWindow()->doc);

	Py_RETURN_NONE;
}
Esempio n. 19
0
// @pymethod |win32ts|WTSQuerySessionInformation|Returns information about a terminal services session
static PyObject *PyWTSQuerySessionInformation(PyObject *self, PyObject *args, PyObject *kwargs)
{
	static char *keywords[]={"Server","SessionId","WTSInfoClass", NULL};
	HANDLE h;
	PyObject *obh, *ret=NULL;
	DWORD SessionId;
	WTS_INFO_CLASS WTSInfoClass;
	LPWSTR buf=NULL;
	DWORD bufsize;

	if (!PyArg_ParseTupleAndKeywords(args, kwargs, "Okk:WTSQuerySessionInformation", keywords,
		&obh,			// @pyparm <o PyHANDLE>|Server||Handle to a terminal server as returned by <om win32ts.WTSOpenServer>
		&SessionId,		// @pyparm int|SessionId||Terminal services session id as returned by <om win32ts.WTSEnumerateSessions>
		&WTSInfoClass))	// @pyparm int|WTSInfoClass||Type of information requested, from WTS_INFO_CLASS enum
		return NULL;

	if (!PyWinObject_AsHANDLE(obh, &h))
		return NULL;
	if (!WTSQuerySessionInformation(h, SessionId, WTSInfoClass, &buf, &bufsize)){
		PyWin_SetAPIError("WTSQuerySessionInformation");
		goto cleanup;
		}
	// @flagh InfoClass|Returned value
	switch (WTSInfoClass){
		case WTSApplicationName:		// @flag WTSApplicationName|Unicode string
		case WTSClientDirectory:		// @flag WTSClientDirectory|Unicode string
		case WTSClientName:				// @flag WTSClientName|Unicode string
		case WTSDomainName:				// @flag WTSDomainName|Unicode string
		case WTSInitialProgram:			// @flag WTSInitialProgram|Unicode string
		case WTSOEMId:					// @flag WTSOEMId|Unicode string
		case WTSUserName:				// @flag WTSUserName|Unicode string
		case WTSWinStationName:			// @flag WTSWinStationName|Unicode string
		case WTSWorkingDirectory:		// @flag WTSWorkingDirectory|Unicode string
			ret=PyWinObject_FromWCHAR(buf);
			break;
		// USHORTs
		case WTSClientProtocolType:		// @flag WTSClientProtocolType|Int, one of WTS_PROTOCOL_TYPE_CONSOLE,WTS_PROTOCOL_TYPE_ICA,WTS_PROTOCOL_TYPE_RDP
		case WTSClientProductId:		// @flag WTSClientProductId|Int
			ret=PyInt_FromLong(*(USHORT *)buf);
			break;
		// ULONGs
		case WTSClientBuildNumber:		// @flag WTSClientBuildNumber|Int
		case WTSClientHardwareId:		// @flag WTSClientHardwareId|Int
		case WTSSessionId:				// @flag WTSSessionId|Int
			ret=PyLong_FromUnsignedLong(*(ULONG *)buf);
			break;
		case WTSConnectState:			// @flag WTSConnectState|Int, from WTS_CONNECTSTATE_CLASS
			ret=PyInt_FromLong(*(INT *)buf);
			break;
		case WTSClientDisplay:{			// @flag WTSClientDisplay|Dict containing client's display settings
			WTS_CLIENT_DISPLAY *wcd=(WTS_CLIENT_DISPLAY *)buf;
			ret=Py_BuildValue("{s:k, s:k, s:k}",
				"HorizontalResolution", wcd->HorizontalResolution,
				"VerticalResolution",	wcd->VerticalResolution,
				"ColorDepth",			wcd->ColorDepth);
			break;
			}
		case WTSClientAddress:{			// @flag WTSClientAddress|Dict containing type and value of client's IP address (None if console session)
			PyObject *obaddress;
			size_t address_cnt, address_ind;
			WTS_CLIENT_ADDRESS *wca=(WTS_CLIENT_ADDRESS *)buf;
			// ??? According to MSDN, buffer may be NULL for console session. (but I don't see it in practice) ???
			if (wca==NULL){
				Py_INCREF(Py_None);
				ret=Py_None;
				break;
				}
			address_cnt=ARRAYSIZE(wca->Address);
			obaddress=PyTuple_New(address_cnt);
			if (obaddress!=NULL)
				for (address_ind=0; address_ind < address_cnt; address_ind++){
					PyObject *obaddress_element=PyInt_FromLong(wca->Address[address_ind]);
					if (obaddress_element==NULL){
						Py_DECREF(obaddress);
						obaddress=NULL;
						break;
						}
					PyTuple_SET_ITEM(obaddress, address_ind, obaddress_element);
					}
			if (obaddress!=NULL)
				ret=Py_BuildValue("{s:k, s:N}",
					"AddressFamily", wca->AddressFamily,
					"Address", obaddress);
			break;
			}
		default:
			PyErr_Format(PyExc_NotImplementedError, "InfoClass %d not yet supported", WTSInfoClass);
		} 
		
	cleanup:
	if (buf)
		WTSFreeMemory(buf);
	return ret;
}
Esempio n. 20
0
static PyObject *Py_write_png(PyObject *self, PyObject *args, PyObject *kwds)
{
    numpy::array_view<unsigned char, 3> buffer;
    PyObject *filein;
    double dpi = 0;
    const char *names[] = { "buffer", "file", "dpi", NULL };

    if (!PyArg_ParseTupleAndKeywords(args,
                                     kwds,
                                     "O&O|d:write_png",
                                     (char **)names,
                                     &buffer.converter,
                                     &buffer,
                                     &filein,
                                     &dpi)) {
        return NULL;
    }

    png_uint_32 width = (png_uint_32)buffer.dim(1);
    png_uint_32 height = (png_uint_32)buffer.dim(0);
    std::vector<png_bytep> row_pointers(height);
    for (png_uint_32 row = 0; row < (png_uint_32)height; ++row) {
        row_pointers[row] = (png_bytep)buffer[row].data();
    }

    FILE *fp = NULL;
    mpl_off_t offset = 0;
    bool close_file = false;
    bool close_dup_file = false;
    PyObject *py_file = NULL;

    png_structp png_ptr = NULL;
    png_infop info_ptr = NULL;
    struct png_color_8_struct sig_bit;

    if (buffer.dim(2) != 4) {
        PyErr_SetString(PyExc_ValueError, "Buffer must be RGBA NxMx4 array");
        goto exit;
    }

    if (PyBytes_Check(filein) || PyUnicode_Check(filein)) {
        if ((py_file = mpl_PyFile_OpenFile(filein, (char *)"wb")) == NULL) {
            goto exit;
        }
        close_file = true;
    } else {
        py_file = filein;
    }

    if ((fp = mpl_PyFile_Dup(py_file, (char *)"wb", &offset))) {
        close_dup_file = true;
    } else {
        PyErr_Clear();
        PyObject *write_method = PyObject_GetAttrString(py_file, "write");
        if (!(write_method && PyCallable_Check(write_method))) {
            Py_XDECREF(write_method);
            PyErr_SetString(PyExc_TypeError,
                            "Object does not appear to be a 8-bit string path or "
                            "a Python file-like object");
            goto exit;
        }
        Py_XDECREF(write_method);
    }

    png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
    if (png_ptr == NULL) {
        PyErr_SetString(PyExc_RuntimeError, "Could not create write struct");
        goto exit;
    }

    info_ptr = png_create_info_struct(png_ptr);
    if (info_ptr == NULL) {
        PyErr_SetString(PyExc_RuntimeError, "Could not create info struct");
        goto exit;
    }

    if (setjmp(png_jmpbuf(png_ptr))) {
        PyErr_SetString(PyExc_RuntimeError, "Error setting jumps");
        goto exit;
    }

    if (fp) {
        png_init_io(png_ptr, fp);
    } else {
        png_set_write_fn(png_ptr, (void *)py_file, &write_png_data, &flush_png_data);
    }
    png_set_IHDR(png_ptr,
                 info_ptr,
                 width,
                 height,
                 8,
                 PNG_COLOR_TYPE_RGB_ALPHA,
                 PNG_INTERLACE_NONE,
                 PNG_COMPRESSION_TYPE_BASE,
                 PNG_FILTER_TYPE_BASE);

    // Save the dpi of the image in the file
    if (dpi > 0.0) {
        png_uint_32 dots_per_meter = (png_uint_32)(dpi / (2.54 / 100.0));
        png_set_pHYs(png_ptr, info_ptr, dots_per_meter, dots_per_meter, PNG_RESOLUTION_METER);
    }

    // this a a color image!
    sig_bit.gray = 0;
    sig_bit.red = 8;
    sig_bit.green = 8;
    sig_bit.blue = 8;
    /* if the image has an alpha channel then */
    sig_bit.alpha = 8;
    png_set_sBIT(png_ptr, info_ptr, &sig_bit);

    png_write_info(png_ptr, info_ptr);
    png_write_image(png_ptr, &row_pointers[0]);
    png_write_end(png_ptr, info_ptr);

exit:

    if (png_ptr && info_ptr) {
        png_destroy_write_struct(&png_ptr, &info_ptr);
    }

    if (close_dup_file) {
        mpl_PyFile_DupClose(py_file, fp, offset);
    }

    if (close_file) {
        mpl_PyFile_CloseFile(py_file);
        Py_DECREF(py_file);
    }

    if (PyErr_Occurred()) {
        return NULL;
    } else {
        Py_RETURN_NONE;
    }
}
Esempio n. 21
0
static PyObject *
image_resample(PyObject *self, PyObject* args, PyObject *kwargs)
{
    PyObject *py_input_array = NULL;
    PyObject *py_output_array = NULL;
    PyObject *py_transform = NULL;
    resample_params_t params;
    int resample_;

    PyArrayObject *input_array = NULL;
    PyArrayObject *output_array = NULL;
    PyArrayObject *transform_mesh_array = NULL;

    params.transform_mesh = NULL;

    const char *kwlist[] = {
        "input_array", "output_array", "transform", "interpolation",
        "resample", "alpha", "norm", "radius", NULL };

    if (!PyArg_ParseTupleAndKeywords(
            args, kwargs, "OOO|iiddd:resample", (char **)kwlist,
            &py_input_array, &py_output_array, &py_transform,
            &params.interpolation, &resample_, &params.alpha, &params.norm,
            &params.radius)) {
        return NULL;
    }

    if (params.interpolation < 0 || params.interpolation >= _n_interpolation) {
        PyErr_Format(PyExc_ValueError, "invalid interpolation value %d",
                     params.interpolation);
        goto error;
    }

    params.resample = (resample_ != 0);

    input_array = (PyArrayObject *)PyArray_FromAny(
        py_input_array, NULL, 2, 3, NPY_ARRAY_C_CONTIGUOUS, NULL);
    if (input_array == NULL) {
        goto error;
    }

    output_array = (PyArrayObject *)PyArray_FromAny(
        py_output_array, NULL, 2, 3, NPY_ARRAY_C_CONTIGUOUS, NULL);
    if (output_array == NULL) {
        goto error;
    }

    if (py_transform == NULL || py_transform == Py_None) {
        params.is_affine = true;
    } else {
        PyObject *py_is_affine;
        int py_is_affine2;
        py_is_affine = PyObject_GetAttrString(py_transform, "is_affine");
        if (py_is_affine == NULL) {
            goto error;
        }

        py_is_affine2 = PyObject_IsTrue(py_is_affine);
        Py_DECREF(py_is_affine);

        if (py_is_affine2 == -1) {
            goto error;
        } else if (py_is_affine2) {
            if (!convert_trans_affine(py_transform, &params.affine)) {
                goto error;
            }
            params.is_affine = true;
        } else {
            transform_mesh_array = _get_transform_mesh(
                py_transform, PyArray_DIMS(output_array));
            if (transform_mesh_array == NULL) {
                goto error;
            }
            params.transform_mesh = (double *)PyArray_DATA(transform_mesh_array);
            params.is_affine = false;
        }
    }

    if (PyArray_NDIM(input_array) != PyArray_NDIM(output_array)) {
        PyErr_Format(
            PyExc_ValueError,
            "Mismatched number of dimensions. Got %d and %d.",
            PyArray_NDIM(input_array), PyArray_NDIM(output_array));
        goto error;
    }

    if (PyArray_TYPE(input_array) != PyArray_TYPE(output_array)) {
        PyErr_SetString(PyExc_ValueError, "Mismatched types");
        goto error;
    }

    if (PyArray_NDIM(input_array) == 3) {
        if (PyArray_DIM(output_array, 2) != 4) {
            PyErr_SetString(
                PyExc_ValueError,
                "Output array must be RGBA");
            goto error;
        }

        if (PyArray_DIM(input_array, 2) == 4) {
            switch(PyArray_TYPE(input_array)) {
            case NPY_BYTE:
            case NPY_UINT8:
                Py_BEGIN_ALLOW_THREADS
                resample(
                    (agg::rgba8 *)PyArray_DATA(input_array),
                    PyArray_DIM(input_array, 1),
                    PyArray_DIM(input_array, 0),
                    (agg::rgba8 *)PyArray_DATA(output_array),
                    PyArray_DIM(output_array, 1),
                    PyArray_DIM(output_array, 0),
                    params);
                Py_END_ALLOW_THREADS
                break;
            case NPY_FLOAT32:
                Py_BEGIN_ALLOW_THREADS
                resample(
                    (agg::rgba32 *)PyArray_DATA(input_array),
                    PyArray_DIM(input_array, 1),
                    PyArray_DIM(input_array, 0),
                    (agg::rgba32 *)PyArray_DATA(output_array),
                    PyArray_DIM(output_array, 1),
                    PyArray_DIM(output_array, 0),
                    params);
                Py_END_ALLOW_THREADS
                break;
            case NPY_FLOAT64:
                Py_BEGIN_ALLOW_THREADS
                resample(
                    (agg::rgba64 *)PyArray_DATA(input_array),
                    PyArray_DIM(input_array, 1),
                    PyArray_DIM(input_array, 0),
                    (agg::rgba64 *)PyArray_DATA(output_array),
                    PyArray_DIM(output_array, 1),
                    PyArray_DIM(output_array, 0),
                    params);
                Py_END_ALLOW_THREADS
                break;
            default:
                PyErr_SetString(
                    PyExc_ValueError,
                    "3-dimensional arrays must be of dtype unsigned byte, "
                    "float32 or float64");
                goto error;
            }
        } else {
            PyErr_Format(
                PyExc_ValueError,
                "If 3-dimensional, array must be RGBA.  Got %d.",
                PyArray_DIM(input_array, 2));
            goto error;
        }
    } else { // NDIM == 2
static PyObject *Consumer_commit (Handle *self, PyObject *args,
                                  PyObject *kwargs) {
	rd_kafka_resp_err_t err;
	PyObject *msg = NULL, *offsets = NULL, *async_o = NULL;
	rd_kafka_topic_partition_list_t *c_offsets;
	int async = 1;
	static char *kws[] = { "message", "offsets",
                               "async", "asynchronous", NULL };
        rd_kafka_queue_t *rkqu = NULL;
        struct commit_return commit_return;
        PyThreadState *thread_state;

        if (!self->rk) {
                PyErr_SetString(PyExc_RuntimeError,
                                "Consumer closed");
                return NULL;
        }

	if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|OOOO", kws,
					 &msg, &offsets, &async_o, &async_o))
		return NULL;

	if (msg && offsets) {
		PyErr_SetString(PyExc_ValueError,
				"message and offsets are mutually exclusive");
		return NULL;
	}

	if (async_o)
		async = PyObject_IsTrue(async_o);


	if (offsets) {

		if (!(c_offsets = py_to_c_parts(offsets)))
			return NULL;
	} else if (msg) {
		Message *m;
                PyObject *uo8;

		if (PyObject_Type((PyObject *)msg) !=
		    (PyObject *)&MessageType) {
			PyErr_Format(PyExc_TypeError,
				     "expected %s", MessageType.tp_name);
			return NULL;
		}

		m = (Message *)msg;

		c_offsets = rd_kafka_topic_partition_list_new(1);
		rd_kafka_topic_partition_list_add(
			c_offsets, cfl_PyUnistr_AsUTF8(m->topic, &uo8),
			m->partition)->offset =m->offset + 1;
                Py_XDECREF(uo8);

	} else {
		c_offsets = NULL;
	}

        if (async) {
                /* Async mode: Use consumer queue for offset commit
                 *             served by consumer_poll() */
                rkqu = self->u.Consumer.rkqu;

        } else {
                /* Sync mode: Let commit_queue() trigger the callback. */
                memset(&commit_return, 0, sizeof(commit_return));

                /* Unlock GIL while we are blocking. */
                thread_state = PyEval_SaveThread();
        }

        err = rd_kafka_commit_queue(self->rk, c_offsets, rkqu,
                                    async ?
                                    Consumer_offset_commit_cb :
                                    Consumer_offset_commit_return_cb,
                                    async ?
                                    (void *)self : (void *)&commit_return);

        if (c_offsets)
                rd_kafka_topic_partition_list_destroy(c_offsets);

        if (!async) {
                /* Re-lock GIL */
                PyEval_RestoreThread(thread_state);

                /* Honour inner error (richer) from offset_commit_return_cb */
                if (commit_return.err)
                        err = commit_return.err;
        }

        if (err) {
                /* Outer error from commit_queue() */
                if (!async && commit_return.c_parts)
                        rd_kafka_topic_partition_list_destroy(commit_return.c_parts);

                cfl_PyErr_Format(err,
                                 "Commit failed: %s", rd_kafka_err2str(err));
                return NULL;
        }

        if (async) {
                /* async commit returns None when commit is in progress */
                Py_RETURN_NONE;

        } else {
                PyObject *plist;

                /* sync commit returns the topic,partition,offset,err list */
                assert(commit_return.c_parts);

                plist = c_parts_to_py(commit_return.c_parts);
                rd_kafka_topic_partition_list_destroy(commit_return.c_parts);

                return plist;
        }
}
Esempio n. 23
0
File: type.c Progetto: zillow/ctds
static int SqlDecimal_init(PyObject* self, PyObject* args, PyObject* kwargs)
{
    struct SqlDecimal* decimal = (struct SqlDecimal*)self;

    DBINT size;
    PyObject* value;
    Py_ssize_t precision = DECIMAL_DEFAULT_PRECISION;
    Py_ssize_t scale = DECIMAL_DEFAULT_SCALE;
    static char* s_kwlist[] =
    {
        "value",
        "precision",
        "scale",
        NULL
    };
    if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O|nn", s_kwlist, &value, &precision, &scale))
    {
        return -1;
    }
    if (!((1 <= precision) && (precision <= DECIMAL_MAX_PRECISION)))
    {
        PyErr_Format(PyExc_ValueError, "invalid precision: %ld", precision);
        return -1;
    }
    if (!((0 <= scale) && (scale <= precision)))
    {
        PyErr_Format(PyExc_ValueError, "invalid scale: %ld", scale);
        return -1;
    }

    if (Py_None != value)
    {
        PyObject* ostr = PyObject_Str(value);
        if (ostr)
        {
            DBTYPEINFO dbtypeinfo;
            Py_ssize_t nutf8;
#if PY_MAJOR_VERSION < 3
            const char* str = PyString_AS_STRING(ostr);
            nutf8 = PyString_GET_SIZE(ostr);
#else /* if PY_MAJOR_VERSION < 3 */
            const char* str = PyUnicode_AsUTF8AndSize(ostr, &nutf8);
#endif /* else if PY_MAJOR_VERSION < 3 */

            dbtypeinfo.precision = (DBINT)precision;
            dbtypeinfo.scale = (DBINT)scale;

            size = dbconvert_ps(NULL,
                                TDSCHAR,
                                (BYTE*)str,
                                (DBINT)nutf8,
                                TDSDECIMAL,
                                (BYTE*)&decimal->dbdecimal,
                                sizeof(decimal->dbdecimal),
                                &dbtypeinfo);
            if (-1 == size)
            {
                PyErr_Format(PyExc_RuntimeError, "failed to convert '%s'", str);
            }
            Py_DECREF(ostr);
        }

        if (PyErr_Occurred())
        {
            return -1;
        }
    }
    else
    {
        decimal->dbdecimal.precision = (BYTE)precision;
        decimal->dbdecimal.scale = (BYTE)scale;
    }

    SqlType_init_fixed(self,
                       value,
                       TDSDECIMAL,
                       decimal->dbdecimal);

    return 0;
}
static PyObject *Consumer_store_offsets (Handle *self, PyObject *args,
						PyObject *kwargs) {
#if RD_KAFKA_VERSION < 0x000b0000
	PyErr_Format(PyExc_NotImplementedError,
		     "Consumer store_offsets require "
		     "confluent-kafka-python built for librdkafka "
		     "version >=v0.11.0 (librdkafka runtime 0x%x, "
		     "buildtime 0x%x)",
		     rd_kafka_version(), RD_KAFKA_VERSION);
	return NULL;
#else
	rd_kafka_resp_err_t err;
	PyObject *msg = NULL, *offsets = NULL;
	rd_kafka_topic_partition_list_t *c_offsets;
	static char *kws[] = { "message", "offsets", NULL };

        if (!self->rk) {
                PyErr_SetString(PyExc_RuntimeError,
                                "Consumer closed");
                return NULL;
        }

	if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|OO", kws,
					 &msg, &offsets))
		return NULL;

	if (msg && offsets) {
		PyErr_SetString(PyExc_ValueError,
				"message and offsets are mutually exclusive");
		return NULL;
	}

	if (!msg && !offsets) {
		PyErr_SetString(PyExc_ValueError,
				"expected either message or offsets");
		return NULL;
	}

	if (offsets) {

		if (!(c_offsets = py_to_c_parts(offsets)))
			return NULL;
	} else {
		Message *m;
		PyObject *uo8;

		if (PyObject_Type((PyObject *)msg) !=
		    (PyObject *)&MessageType) {
			PyErr_Format(PyExc_TypeError,
				     "expected %s", MessageType.tp_name);
			return NULL;
		}

		m = (Message *)msg;

		c_offsets = rd_kafka_topic_partition_list_new(1);
		rd_kafka_topic_partition_list_add(
			c_offsets, cfl_PyUnistr_AsUTF8(m->topic, &uo8),
			m->partition)->offset = m->offset + 1;
		Py_XDECREF(uo8);
	}


	err = rd_kafka_offsets_store(self->rk, c_offsets);
	rd_kafka_topic_partition_list_destroy(c_offsets);



	if (err) {
		cfl_PyErr_Format(err,
				 "StoreOffsets failed: %s", rd_kafka_err2str(err));
		return NULL;
	}

	Py_RETURN_NONE;
#endif
}
Esempio n. 25
0
File: msaio.c Progetto: Wyss/ProDy
static PyObject *writeFasta(PyObject *self, PyObject *args, PyObject *kwargs) {

    /* Write MSA where inputs are: labels in the form of Python lists
    and sequences in the form of Python numpy array and write them in
    FASTA format in the specified filename.*/

    char *filename;
    int line_length = 60;
    PyObject *labels;
    PyArrayObject *msa;

    static char *kwlist[] = {"filename", "labels", "msa", "line_length", NULL};

    if (!PyArg_ParseTupleAndKeywords(args, kwargs, "sOO|i", kwlist,
                                     &filename, &labels, &msa, &line_length))
        return NULL;

    /* make sure to have a contiguous and well-behaved array */
    msa = PyArray_GETCONTIGUOUS(msa);

    long numseq = PyArray_DIMS(msa)[0], lenseq = PyArray_DIMS(msa)[1];

    if (numseq != PyList_Size(labels)) {
        PyErr_SetString(PyExc_ValueError,
            "size of labels and msa array does not match");
        return NULL;
    }

    FILE *file = fopen(filename, "wb");

    int nlines = lenseq / line_length;
    int remainder = lenseq - line_length * nlines;
    int i, j, k;
    int count = 0;
    char *seq = PyArray_DATA(msa);
    int lenmsa = strlen(seq);
    #if PY_MAJOR_VERSION >= 3
    PyObject *plabel;
    #endif
    for (i = 0; i < numseq; i++) {
        #if PY_MAJOR_VERSION >= 3
        plabel = PyUnicode_AsEncodedString(
                PyList_GetItem(labels, (Py_ssize_t) i), "utf-8",
                               "label encoding");
        char *label =  PyBytes_AsString(plabel);
        Py_DECREF(plabel);
        #else
        char *label =  PyString_AsString(PyList_GetItem(labels,
                                                        (Py_ssize_t) i));
        #endif
        fprintf(file, ">%s\n", label);

        for (j = 0; j < nlines; j++) {
            for (k = 0; k < 60; k++)
                if (count < lenmsa)
                    fprintf(file, "%c", seq[count++]);
            fprintf(file, "\n");
        }
        if (remainder)
            for (k = 0; k < remainder; k++)
                if (count < lenmsa)
                    fprintf(file, "%c", seq[count++]);

        fprintf(file, "\n");

    }
    fclose(file);
    return Py_BuildValue("s", filename);
}
static PyObject *Consumer_consume (Handle *self, PyObject *args,
                                        PyObject *kwargs) {
        unsigned int num_messages = 1;
        double tmout = -1.0f;
        static char *kws[] = { "num_messages", "timeout", NULL };
        rd_kafka_message_t **rkmessages;
        PyObject *msglist;
        rd_kafka_queue_t *rkqu = self->u.Consumer.rkqu;
        CallState cs;
        Py_ssize_t i, n;

        if (!self->rk) {
                PyErr_SetString(PyExc_RuntimeError,
                                "Consumer closed");
                return NULL;
        }

        if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|Id", kws,
					 &num_messages, &tmout))
		return NULL;

	if (num_messages > 1000000) {
	        PyErr_SetString(PyExc_ValueError,
	                        "num_messages must be between 0 and 1000000 (1M)");
	        return NULL;
	}

        CallState_begin(self, &cs);

        rkmessages = malloc(num_messages * sizeof(rd_kafka_message_t *));

        n = (Py_ssize_t)rd_kafka_consume_batch_queue(rkqu,
                tmout >= 0 ? (int)(tmout * 1000.0f) : -1,
                rkmessages,
                num_messages);

        if (!CallState_end(self, &cs)) {
                for (i = 0; i < n; i++) {
                        rd_kafka_message_destroy(rkmessages[i]);
                }
                free(rkmessages);
                return NULL;
        }

        if (n < 0) {
                free(rkmessages);
                cfl_PyErr_Format(rd_kafka_last_error(),
                                 "%s", rd_kafka_err2str(rd_kafka_last_error()));
                return NULL;
        }

        msglist = PyList_New(n);

        for (i = 0; i < n; i++) {
                PyObject *msgobj = Message_new0(self, rkmessages[i]);
#ifdef RD_KAFKA_V_HEADERS
                // Have to detach headers outside Message_new0 because it declares the
                // rk message as a const
                rd_kafka_message_detach_headers(rkmessages[i], &((Message *)msgobj)->c_headers);
#endif
                PyList_SET_ITEM(msglist, i, msgobj);
                rd_kafka_message_destroy(rkmessages[i]);
        }

        free(rkmessages);

        return msglist;
}
Esempio n. 27
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;
}
static PyObject *Consumer_subscribe (Handle *self, PyObject *args,
					 PyObject *kwargs) {

	rd_kafka_topic_partition_list_t *topics;
	static char *kws[] = { "topics", "on_assign", "on_revoke", NULL };
	PyObject *tlist, *on_assign = NULL, *on_revoke = NULL;
	Py_ssize_t pos = 0;
	rd_kafka_resp_err_t err;

        if (!self->rk) {
                PyErr_SetString(PyExc_RuntimeError,
                                "Consumer closed");
                return NULL;
        }

	if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O|OO", kws,
					 &tlist, &on_assign, &on_revoke))
		return NULL;

	if (!PyList_Check(tlist)) {
		PyErr_Format(PyExc_TypeError,
			     "expected list of topic unicode strings");
		return NULL;
	}

	if (on_assign && !PyCallable_Check(on_assign)) {
		PyErr_Format(PyExc_TypeError,
			     "on_assign expects a callable");
		return NULL;
	}

	if (on_revoke && !PyCallable_Check(on_revoke)) {
		PyErr_Format(PyExc_TypeError,
			     "on_revoke expects a callable");
		return NULL;
	}

	topics = rd_kafka_topic_partition_list_new((int)PyList_Size(tlist));
	for (pos = 0 ; pos < PyList_Size(tlist) ; pos++) {
		PyObject *o = PyList_GetItem(tlist, pos);
		PyObject *uo, *uo8;
		if (!(uo = cfl_PyObject_Unistr(o))) {
			PyErr_Format(PyExc_TypeError,
				     "expected list of unicode strings");
			rd_kafka_topic_partition_list_destroy(topics);
			return NULL;
		}
		rd_kafka_topic_partition_list_add(topics,
						  cfl_PyUnistr_AsUTF8(uo, &uo8),
						  RD_KAFKA_PARTITION_UA);
                Py_XDECREF(uo8);
		Py_DECREF(uo);
	}

	err = rd_kafka_subscribe(self->rk, topics);

	rd_kafka_topic_partition_list_destroy(topics);

	if (err) {
		cfl_PyErr_Format(err,
				 "Failed to set subscription: %s",
				 rd_kafka_err2str(err));
		return NULL;
	}

	/*
	 * Update rebalance callbacks
	 */
	if (self->u.Consumer.on_assign) {
		Py_DECREF(self->u.Consumer.on_assign);
		self->u.Consumer.on_assign = NULL;
	}
	if (on_assign) {
		self->u.Consumer.on_assign = on_assign;
		Py_INCREF(self->u.Consumer.on_assign);
	}

	if (self->u.Consumer.on_revoke) {
		Py_DECREF(self->u.Consumer.on_revoke);
		self->u.Consumer.on_revoke = NULL;
	}
	if (on_revoke) {
		self->u.Consumer.on_revoke = on_revoke;
		Py_INCREF(self->u.Consumer.on_revoke);
	}

	Py_RETURN_NONE;
}
Esempio n. 29
0
static PyObject* solve(PyObject *self, PyObject *args, PyObject *kwrds)
{
    matrix *B;
    PyObject *F;
    int i, n, oB=0, ldB=0, nrhs=-1, sys=0;
#if PY_MAJOR_VERSION >= 3
    const char *descr;
#else
    char *descr;
#endif
    char *kwlist[] = {"F", "B", "sys", "nrhs", "ldB", "offsetB", NULL};
    int sysvalues[] = { CHOLMOD_A, CHOLMOD_LDLt, CHOLMOD_LD,
        CHOLMOD_DLt, CHOLMOD_L, CHOLMOD_Lt, CHOLMOD_D, CHOLMOD_P,
        CHOLMOD_Pt };

    if (!set_options()) return NULL;

    if (!PyArg_ParseTupleAndKeywords(args, kwrds, "OO|iiii", kwlist,
        &F, &B, &sys, &nrhs, &ldB, &oB)) return NULL;

#if PY_MAJOR_VERSION >= 3
    if (!PyCapsule_CheckExact(F) || !(descr = PyCapsule_GetName(F)))
        err_CO("F");
    if (strncmp(descr, "CHOLMOD FACTOR", 14))
        PY_ERR_TYPE("F is not a CHOLMOD factor");
    cholmod_factor *L = (cholmod_factor *) PyCapsule_GetPointer(F, descr);
#else
    if (!PyCObject_Check(F)) err_CO("F");
    descr = PyCObject_GetDesc(F);
    if (!descr || strncmp(descr, "CHOLMOD FACTOR", 14))
        PY_ERR_TYPE("F is not a CHOLMOD factor");
    cholmod_factor *L = (cholmod_factor *) PyCObject_AsVoidPtr(F);
#endif
    if (L->xtype == CHOLMOD_PATTERN)
        PY_ERR(PyExc_ValueError, "called with symbolic factor");

    n = L->n;
    if (L->minor<n) PY_ERR(PyExc_ArithmeticError, "singular matrix");

    if (sys < 0 || sys > 8)
         PY_ERR(PyExc_ValueError, "invalid value for sys");

    if (!Matrix_Check(B) || MAT_ID(B) == INT ||
        (MAT_ID(B) == DOUBLE && L->xtype == CHOLMOD_COMPLEX) ||
        (MAT_ID(B) == COMPLEX && L->xtype == CHOLMOD_REAL))
            PY_ERR_TYPE("B must a dense matrix of the same numerical "
                "type as F");

    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");

    cholmod_dense *x;
    cholmod_dense *b = CHOL(allocate_dense)(n, 1, n,
        (MAT_ID(B) == DOUBLE ? CHOLMOD_REAL : CHOLMOD_COMPLEX),
        &Common);
    if (Common.status == CHOLMOD_OUT_OF_MEMORY) return PyErr_NoMemory();

    void *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) (sysvalues[sys], L, b, &Common);
        if (Common.status != CHOLMOD_OK){
            PyErr_SetString(PyExc_ValueError, "solve step failed");
            CHOL(free_dense)(&x, &Common);
            CHOL(free_dense)(&b, &Common);
	    return NULL;
	}
	memcpy(b->x, x->x, n*E_SIZE[MAT_ID(B)]);
        CHOL(free_dense)(&x, &Common);
    }
    b->x = b_old;
    CHOL(free_dense)(&b, &Common);

    return Py_BuildValue("");
}
Esempio n. 30
0
static PyObject* resonate(PyObject *self, PyObject *args, PyObject *keywds)
{
    static char *kwlist[] = {"signal", "sr", "freqs", "damping",
                             "rms_window", "return_response", NULL};
    PyObject *pysignal;
    int sr;
    PyObject *pyfreqs;
    double damping;
    int rms_window;
    int return_response;
    int siglen;
    int nfreqs;
    double w;
    double *x, *x1, *x2;
    double *a1, *a2, *b1;
    PyObject *signal;
    PyObject **response;
    PyObject *response_list;
    double *rms_moving;
    PyObject **rms;
    PyObject *rms_list;
    PyObject *out;
    double rms_val;
    PyObject *item;
    double freq;
    long freq_long;
    double sample;
    int i, t;

    if(!PyArg_ParseTupleAndKeywords(args, keywds, "OiOdi|i", kwlist,
                                    &pysignal, &sr, &pyfreqs, &damping,
                                    &rms_window, &return_response)) {
        return NULL;
    }

    if(!PySequence_Check(pyfreqs)) {
        PyErr_SetString(PyExc_TypeError, "freqs: expected sequence of numbers");
        return NULL;
    }

    nfreqs = PySequence_Size(pyfreqs);
    signal = PySequence_Fast(pysignal, "signal: expected sequence of floats");
    siglen = PySequence_Size(signal);

    x = alloca(nfreqs * sizeof(double));
    x1 = alloca(nfreqs * sizeof(double));
    x2 = alloca(nfreqs * sizeof(double));
    a1 = alloca(nfreqs * sizeof(double));
    a2 = alloca(nfreqs * sizeof(double));
    b1 = alloca(nfreqs * sizeof(double));
    rms_moving = alloca(nfreqs * sizeof(double));
    rms = alloca(nfreqs * sizeof(PyObject *));

    if(return_response)
        response = alloca(nfreqs * sizeof(PyObject *));

    for(i = 0; i < nfreqs; i ++) {
        item = PySequence_GetItem(pyfreqs, i);
        if(PyInt_Check(item)) {
            freq_long = PyInt_AsLong(item);
            freq = (double)freq_long;
        }
        else if(PyLong_Check(item)) {
            freq = PyLong_AsDouble(item);
        }
        else if(PyFloat_Check(item)) {
            freq = PyFloat_AsDouble(item);
        }
        else {
            Py_DECREF(item);
            PyErr_SetString(PyExc_TypeError, "freqs: expected sequence of numbers");
            return NULL;
        }

        w = (2 * M_PI * freq) / sr;

        a1[i] = (pow(w, 2) - 2) / (1 + damping);
        a2[i] = (1 - damping) / (1 + damping);
        b1[i] = 1 / (1 + damping);

        x[i] = 0;
        x1[i] = 0;
        x2[i] = 0;

        rms_moving[i] = 0;
        rms[i] = PyList_New(siglen / rms_window);

        if(return_response)
            response[i] = PyList_New(siglen);
    }

    for(t = 0; t < siglen; t ++) {
        item = PySequence_Fast_GET_ITEM(signal, t);
        sample = PyFloat_AsDouble(item);

        for(i = 0; i < nfreqs; i ++) {
            x[i] = b1[i] * sample - a1[i] * x1[i] - a2[i] * x2[i];
            rms_moving[i] += pow(x[i], 2);

            if(return_response) {
                item = PyFloat_FromDouble(x[i]);
                PyList_SET_ITEM(response[i], t, item);
            }
        }

        memcpy(x2, x1, nfreqs * sizeof(double));
        memcpy(x1, x, nfreqs * sizeof(double));

        if((t + 1) % rms_window == 0) {
            for(i = 0; i < nfreqs; i ++) {
                rms_val = sqrt(rms_moving[i] / (double)rms_window);
                rms_moving[i] = 0;
                item = PyFloat_FromDouble(rms_val);
                PyList_SET_ITEM(rms[i], t / rms_window, item);
            }
        }
    }
    Py_DECREF(signal);

    rms_list = PyList_New(nfreqs);
    if(return_response)
        response_list = PyList_New(nfreqs);

    for(i = 0; i < nfreqs; i ++) {
        PyList_SET_ITEM(rms_list, i, rms[i]);
        if(return_response)
            PyList_SET_ITEM(response_list, i, response[i]);
    }

    if(return_response)
        return Py_BuildValue("(O,O)", rms_list, response_list);
    else
        return Py_BuildValue("O", rms_list);
}