Exemplo n.º 1
0
static PyObject *nil_new(PyTypeObject *type,
			 PyObject *args, PyObject *kwds) {

  if (PyTuple_Size(args) || (kwds && PyDict_Size(kwds))) {
    PyErr_SetString(PyExc_TypeError, "NilType takes no arguments");
    return NULL;
  }

  Py_INCREF(SibNil);
  return SibNil;
}
Exemplo n.º 2
0
	inline void  pack_sub_obj(unsigned char * strbuf, int & count, PyObject * obj, PyObject * func){
		if (PyDict_Check(obj)){
			int len = PyDict_Size(obj);

			if (len <= 15){
				strbuf[count++] = 0x80 | len;
			}
			else if (len <= 65535){
				strbuf[count++] = 0xde;
				strbuf[count++] = (len & 0xff00) >> 8;
				strbuf[count++] = len & 0xff;
			}
			else if (len <= 4294967296){
Exemplo n.º 3
0
static PyObject *
function_call(PyObject *func, PyObject *arg, PyObject *kw)
{
    PyObject *result;
    PyObject *argdefs;
    PyObject *kwtuple = NULL;
    PyObject **d, **k;
    Py_ssize_t nk, nd;

    argdefs = PyFunction_GET_DEFAULTS(func);
    if (argdefs != NULL && PyTuple_Check(argdefs)) {
        d = &PyTuple_GET_ITEM((PyTupleObject *)argdefs, 0);
        nd = PyTuple_GET_SIZE(argdefs);
    }
    else {
        d = NULL;
        nd = 0;
    }

    if (kw != NULL && PyDict_Check(kw)) {
        Py_ssize_t pos, i;
        nk = PyDict_Size(kw);
        kwtuple = PyTuple_New(2*nk);
        if (kwtuple == NULL)
            return NULL;
        k = &PyTuple_GET_ITEM(kwtuple, 0);
        pos = i = 0;
        while (PyDict_Next(kw, &pos, &k[i], &k[i+1])) {
            Py_INCREF(k[i]);
            Py_INCREF(k[i+1]);
            i += 2;
        }
        nk = i/2;
    }
    else {
        k = NULL;
        nk = 0;
    }

    result = PyEval_EvalCodeEx(
        PyFunction_GET_CODE(func),
        PyFunction_GET_GLOBALS(func), (PyObject *)NULL,
        &PyTuple_GET_ITEM(arg, 0), PyTuple_GET_SIZE(arg),
        k, nk, d, nd,
        PyFunction_GET_KW_DEFAULTS(func),
        PyFunction_GET_CLOSURE(func));

    Py_XDECREF(kwtuple);

    return result;
}
Exemplo n.º 4
0
void get_arg::get_arg_base::finished() {
    // are there more keywords than we used?
    if(UNLIKELY(kwds && kcount < PyDict_Size(kwds))) {
        PyObject *key;
        Py_ssize_t pos = 0;
        while(PyDict_Next(kwds,&pos,&key,NULL)){
            if(!PYSTR(Check)(key)) {
                PyErr_SetString(PyExc_TypeError,"keywords must be strings");
                throw py_error_set();
            }
#if PY_MAJOR_VERSION >= 3
  #if PY_MINOR_VERSION >= 3
            const char *kstr = PyUnicode_AsUTF8(key);
            if(!kstr) throw py_error_set();
  #else
            PyObject *kstr_obj = PyUnicode_AsUTF8String(key);
            if(!kstr_obj) throw py_error_set();
            
            struct deleter {
                PyObject *ptr;
                deleter(PyObject *ptr) : ptr(ptr) {}
                ~deleter() { Py_DECREF(ptr); }
            } _(kstr_obj);
            
            const char *kstr = PyBytes_AS_STRING(kstr_obj);
  #endif
#else
            const char *kstr = PyBytes_AS_STRING(key);
#endif
            if(names) {
                for(const char **name = names; *name; ++name) {
                    if(strcmp(kstr,*name) == 0) goto match;
                }
            }
                
            PyErr_Format(PyExc_TypeError,"'%s' is an invalid keyword argument for %s%s",
                kstr,
                fname ? fname : "this function",
                fname ? "()" : "");
            throw py_error_set();
            
        match:
            ;
        }
        
        // should never reach here
        assert(false);
    }
}
static void createModuleConstants( void )
{
    const_tuple_str_plain_LookupDict_tuple = PyTuple_New( 1 );
    PyTuple_SET_ITEM( const_tuple_str_plain_LookupDict_tuple, 0, const_str_plain_LookupDict ); Py_INCREF( const_str_plain_LookupDict );
    const_str_plain__codes = UNSTREAM_STRING( &constant_bin[ 201532 ], 6, 1 );
    const_dict_19730b058f28080932defca1165e072e = PyMarshal_ReadObjectFromString( (char *)&constant_bin[ 495296 ], 2320 );
    const_str_digest_edc503ce8640402b515eac9b4be2e49c = UNSTREAM_STRING( &constant_bin[ 497616 ], 69, 0 );
    const_str_digest_7407a472cb7f92da9dfbd02c8e685bfe = UNSTREAM_STRING( &constant_bin[ 497685 ], 33, 0 );
    const_dict_38252060f20256dc080a28c7e1fb8512 = _PyDict_NewPresized( 1 );
    PyDict_SetItem( const_dict_38252060f20256dc080a28c7e1fb8512, const_str_plain_name, const_str_plain_status_codes );
    assert( PyDict_Size( const_dict_38252060f20256dc080a28c7e1fb8512 ) == 1 );
    const_str_plain_titles = UNSTREAM_STRING( &constant_bin[ 497718 ], 6, 1 );

    constants_created = true;
}
Exemplo n.º 6
0
Arquivo: lists.c Projeto: rhn/snakeoil
static PyObject *
snakeoil_iflatten_instance_new(PyTypeObject *type,
							   PyObject *args, PyObject *kwargs)
{
	snakeoil_iflatten_instance *self;
	PyObject *l=NULL, *skip_flattening=(PyObject*)&PyBaseString_Type;
	int res;

	if (kwargs && PyDict_Size(kwargs)) {
		PyErr_SetString(PyExc_TypeError,
						"iflatten_instance takes no keyword arguments");
		return NULL;
	}
	if (!PyArg_UnpackTuple(args, "iflatten_instance", 1, 2,
						   &l, &skip_flattening)) {
		return NULL;
	}

	/* Check if we got a single argument that should be skipped. */
	res = PyObject_IsInstance(l, skip_flattening);
	if (res == -1) {
		return NULL;
	} else if (res) {
		PyObject *tuple = PyTuple_Pack(1, l);
		if (!tuple) {
			return NULL;
		}
		PyObject *iter = PyObject_GetIter(tuple);
		Py_DECREF(tuple);
		return iter;
	}

	self = (snakeoil_iflatten_instance *)type->tp_alloc(type, 0);
	if (!self)
		return NULL;

	self->in_iternext = 0;

	if (!(self->iterables = build_initial_iterables(l))) {
		Py_DECREF(self);
		return NULL;
	}

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

	return (PyObject *)self;
}
// Some functions
static int boostedMachine_init(
  BoostedMachineObject* self,
  PyObject* args,
  PyObject* kwargs
)
{
  Py_ssize_t argument_count = (args ? PyTuple_Size(args) : 0) + (kwargs ? PyDict_Size(kwargs) : 0);

  try{
    switch (argument_count){
      case 1:{
        char*  kwlist[] = {c("hdf5"), NULL};
        PyBobIoHDF5FileObject* file = 0;
        if (
          PyArg_ParseTupleAndKeywords(args, kwargs,
              "O&", kwlist,
              PyBobIoHDF5File_Converter, &file
          )
        ){
          // construct from HDF5File
          auto _ = make_safe(file);
          self->base.reset(new bob::learn::boosting::BoostedMachine(*file->f));
          return 0;
        }
        boostedMachine_doc.print_usage();
        return -1;
      } break;

      case 0:{
        self->base.reset(new bob::learn::boosting::BoostedMachine());
        return 0;
      }
      default:
        boostedMachine_doc.print_usage();
        PyErr_Format(PyExc_RuntimeError, "number of arguments mismatch - %s requires 0 or 1 arguments, but you provided %" PY_FORMAT_SIZE_T "d", Py_TYPE(self)->tp_name, argument_count);
        return -1;
    }
  } catch (std::exception& ex) {
    PyErr_SetString(PyExc_RuntimeError, ex.what());
    return -1;
  }
  catch (...) {
    PyErr_Format(PyExc_RuntimeError, "cannot create new object of type `%s' - unknown exception thrown", Py_TYPE(self)->tp_name);
    return -1;
  }

  return 0;
}
Exemplo n.º 8
0
 /*static PyObject * c2py(std::map<K,V> &m) {
  PyObject * d = PyDict_New();
  for (auto & x : m) {
   pyref k = py_converter<K>::c2py(x.first);
   pyref v = py_converter<V>::c2py(x.second);   
   if (PyDict_SetItem(d,k,v) == -1) { Py_DECREF(d); return NULL;} // error
  }
  return d;
 }*/
 static bool is_convertible(PyObject *ob, bool raise_exception) {
  if (!PyDict_Check(ob)) goto _false;
  {
   pyref keys = PyDict_Keys(ob);
   pyref values = PyDict_Values(ob);
   int len = PyDict_Size(ob);
   for (int i = 0; i < len; i++) {
     if (!py_converter<K>::is_convertible(PyList_GET_ITEM((PyObject*)keys, i),raise_exception)) goto _false; //borrowed ref
     if (!py_converter<V>::is_convertible(PyList_GET_ITEM((PyObject*)values, i),raise_exception)) goto _false; //borrowed ref
   }
   return true;
  }
  _false:
  if (raise_exception) { PyErr_SetString(PyExc_TypeError, "Cannot convert to std::map");}
  return false;
 }
Exemplo n.º 9
0
/* number of elements, not the table size. */
static size_t MapPySize(const SMap *self, s_erc *error)
{
	SMapPy *pMap = (SMapPy*)self;
	size_t size;


	S_CLR_ERR(error);
	S_CHECK_PY_MAP(pMap, "MapPyValKeys");

	size = PyDict_Size(S_PY_DICT(pMap));
	return size;

	/* for S_CHECK_PY_MAP */
failure:
	return 0;
}
Exemplo n.º 10
0
static PyObject *
cnter_normalize(cnterobject *dd)
{
	Py_ssize_t i;
	PyObject *key, *value;
	double sum = 0.0;

	i = 0;
	while (PyDict_Next((PyObject*)dd, &i, &key, &value)) {
		sum += PyFloat_AsDouble(value);
	}
	
	if (sum == 0.0) {
	  Py_ssize_t len = PyDict_Size((PyObject*)dd);
	  PyObject *uniform = PyFloat_FromDouble(1.0 / (double)len);

	  i = 0;
	  while (PyDict_Next((PyObject*)dd, &i, &key, &value)) {
		int ok;

		ok = PyDict_SetItem((PyObject*)dd, key, uniform);
		if (ok < 0) {
		  Py_DECREF(uniform);
		  return NULL;
		}
	  }
	  Py_DECREF(uniform);

	  Py_INCREF(Py_None);
	  return Py_None;
	}

	i = 0;
	while (PyDict_Next((PyObject*)dd, &i, &key, &value)) {
	  int ok;

	  PyObject *newValue = PyFloat_FromDouble(PyFloat_AsDouble(value) / sum);
	  ok = PyDict_SetItem((PyObject*)dd, key, newValue);
	  Py_DECREF(newValue);

	  if (ok < 0) return NULL;
	}
	
	Py_INCREF(Py_None);
	return Py_None;
}
Exemplo n.º 11
0
//============================================================================
// FUNCTION : PYSIZE
//============================================================================
int PYSIZE( PyObject* object )
{
	if (object == NULL) return -1;
    if (PyDict_Check(object))
    {
    	return PyDict_Size(object);
    }
    else if (PyList_Check(object))
    {
    	return PyList_Size(object);
    }
    else if (PyString_Check(object))
    {
    	return PyString_Size(object);
    }
    return -1;
};
Exemplo n.º 12
0
static PyObject *
partial_call(partialobject *pto, PyObject *args, PyObject *kw)
{
    PyObject *ret;
    PyObject *argappl, *kwappl;

    assert (PyCallable_Check(pto->fn));
    assert (PyTuple_Check(pto->args));
    assert (PyDict_Check(pto->kw));

    if (PyTuple_GET_SIZE(pto->args) == 0) {
        argappl = args;
        Py_INCREF(args);
    } else if (PyTuple_GET_SIZE(args) == 0) {
        argappl = pto->args;
        Py_INCREF(pto->args);
    } else {
        argappl = PySequence_Concat(pto->args, args);
        if (argappl == NULL)
            return NULL;
        assert(PyTuple_Check(argappl));
    }

    if (PyDict_Size(pto->kw) == 0) {
        kwappl = kw;
        Py_XINCREF(kwappl);
    } else {
        kwappl = PyDict_Copy(pto->kw);
        if (kwappl == NULL) {
            Py_DECREF(argappl);
            return NULL;
        }
        if (kw != NULL) {
            if (PyDict_Merge(kwappl, kw, 1) != 0) {
                Py_DECREF(argappl);
                Py_DECREF(kwappl);
                return NULL;
            }
        }
    }

    ret = PyObject_Call(pto->fn, argappl, kwappl);
    Py_DECREF(argappl);
    Py_XDECREF(kwappl);
    return ret;
}
Exemplo n.º 13
0
get_arg::get_arg_base::get_arg_base(PyObject *args,PyObject *kwds,Py_ssize_t arg_len,const char **names,const char *fname)
        : args(args), kwds(kwds), names(names), fname(fname), kcount(0) {
    assert(args != NULL && PyTuple_Check(args));
    assert(kwds == NULL || PyDict_Check(kwds));
    
    Py_ssize_t given = PyTuple_GET_SIZE(args);
    if(kwds) given += PyDict_Size(kwds);
    if(UNLIKELY(given > arg_len)) {
        PyErr_Format(PyExc_TypeError, "%s%s takes at most %zd argument%s (%zd given)",
            fname ? fname : "function",
            fname ? "()" : "",
            arg_len,
            (arg_len == 1) ? "" : "s",
            given);
        throw py_error_set();
    }
}
Exemplo n.º 14
0
static PyObject *pair_new(PyTypeObject *type,
			  PyObject *args, PyObject *kwds) {

  // checked

  PyObject *head = NULL;
  PyObject *tail = NULL;

  if (kwds && PyDict_Size(kwds)) {
    PyErr_SetString(PyExc_TypeError, "pair takes no named arguments");
    return NULL;
  }

  if (! PyArg_ParseTuple(args, "OO:pair", &head, &tail))
    return NULL;

  return SibPair_New(head, tail);
}
Exemplo n.º 15
0
/*
  Actually create a new AudioDevice object
*/
static PyObject*
py_ao_new(PyObject *self, PyObject *args, PyObject *kwargs)
{
  uint_32 overwrite, driver_id;
  const char *filename = NULL;
  PyObject *py_options = NULL;
  ao_option *c_options = NULL;
  ao_device *dev;
  ao_sample_format sample_format;
  ao_Object *retobj;

  if (!parse_args(args, kwargs, 
		  &sample_format, &py_options,
		  &filename, &driver_id, &overwrite))
    return NULL;

  if (py_options && PyDict_Size(py_options) > 0) {
    /* dict_to_options returns NULL on error, so you can't pass
       an empty dictionary. We can skip this then anyway. */

    c_options = dict_to_options(py_options);
    if (!c_options) {
      return NULL;
    }
  }
 
  if (filename == NULL) {
    dev = ao_open_live(driver_id, &sample_format, c_options);
  } else {
    dev = ao_open_file(driver_id, filename, overwrite, 
		       &sample_format, c_options);
  }
  ao_free_options(c_options);

  if (dev == NULL) {
    PyErr_SetString(Py_aoError, "Error opening device.");
    return NULL;
  }

  retobj = (ao_Object *) PyObject_NEW(ao_Object, &ao_Type);
  retobj->dev = dev;
  retobj->driver_id = driver_id;
  return (PyObject *) retobj;
}
Exemplo n.º 16
0
static PyObject *
unarywrapper_call(callablewrapper *self, PyObject *args, PyObject *kwargs)
{
    if (kwargs && PyDict_Size(kwargs)) {
        PyErr_SetString(PyExc_TypeError,
                        "callable does not accept keyword arguments");
        return NULL;
    }

    if (PyTuple_GET_SIZE(args) != 1) {
        PyErr_Format(PyExc_TypeError,
                     "callable expects 1 argument, passed %zd",
                     PyTuple_GET_SIZE(args));
        return NULL;
    }

    return ((PyObject *(*)(PyObject*)) self->wr_func)(
        PyTuple_GET_ITEM(args, 0));
}
Exemplo n.º 17
0
/* should not be used, should be private, defensive copy
 * _struct_new is used internally because it borrows the kw argument
 * which save a PyDict_Copy
 */
static int struct_init(PyObject *self, PyObject *args, PyObject *kw)
{
	StructObject * const that = (StructObject*) self;
	that->dict = NULL;
	that->repr = NULL;

	if(args && !PyArg_ParseTuple(args, ""))
		return -1;

	if(kw == NULL || PyDict_Size(kw) == 0) {
		PyErr_SetString(PyExc_ValueError, "Struct is empty");
		return -1;
	}

	/* TODO: check for valid member names ^[a-zA-Z_] */
	that->dict = PyDict_Copy(kw);

	return 0;
}
Exemplo n.º 18
0
static int PyBobSpIDCT1D_Init(PyBobSpIDCT1DObject* self,
    PyObject* args, PyObject* kwds) {

  Py_ssize_t nargs = (args?PyTuple_Size(args):0) + (kwds?PyDict_Size(kwds):0);

  switch (nargs) {

    case 1:

      {

        PyObject* arg = 0; ///< borrowed (don't delete)
        if (PyTuple_Size(args)) arg = PyTuple_GET_ITEM(args, 0);
        else {
          PyObject* tmp = PyDict_Values(kwds);
          auto tmp_ = make_safe(tmp);
          arg = PyList_GET_ITEM(tmp, 0);
        }

        if (PyBob_NumberCheck(arg)) {
          return PyBobSpIDCT1D_InitShape(self, args, kwds);
        }

        if (PyBobSpIDCT1D_Check(arg)) {
          return PyBobSpIDCT1D_InitCopy(self, args, kwds);
        }

        PyErr_Format(PyExc_TypeError, "cannot initialize `%s' with `%s' (see help)", Py_TYPE(self)->tp_name, Py_TYPE(arg)->tp_name);

      }

      break;

    default:

      PyErr_Format(PyExc_RuntimeError, "number of arguments mismatch - %s requires 1 argument, but you provided %" PY_FORMAT_SIZE_T "d (see help)", Py_TYPE(self)->tp_name, nargs);

  }

  return -1;

}
Exemplo n.º 19
0
static long _adbobj_have_possible_break(AdbObject *self, PyFrameObject *frame)
{
    PyObject *filename;
    PyObject *tuple;
    int haveFileBP;

#ifdef DEBUG_PRINT
    fprintf(stderr, "_adbobj_have_possible_break...\n");
#endif
    if (PyDict_Size(__adb_breakpointList) < 1) {
        // no breakpoints, no possible break
        return 0;
    }
    
    if (PyMapping_HasKey(__adb_canonicCache, frame->f_code->co_filename)==0) {
        // filename has not been mapped, so force a call to effective
        return 1;
    }

    filename = PyDict_GetItem(__adb_canonicCache, frame->f_code->co_filename);
    if (PyMapping_HasKey(__adb_breakpointFileList, filename)==1) {
        // we have breakpoints for this file, do we have one for this line
        // or a file global breakpoint?

        tuple = Py_BuildValue("(Oi)", filename, frame->f_lineno);
        haveFileBP = PyDict_GetItem(__adb_breakpointList, tuple) != NULL;
        Py_DECREF(tuple);
        if (haveFileBP) {
            return 1;
        }

        // check for file global breakpoints
        tuple = Py_BuildValue("(Oi)", filename, 0);
        haveFileBP = PyDict_GetItem(__adb_breakpointList, tuple) != NULL;
        Py_DECREF(tuple);
        if (haveFileBP) {
            return 1;
        }
    }
    // check for global breakpoints
    return PyMapping_HasKeyString(__adb_breakpointFileList, "");
}
Exemplo n.º 20
0
static PyObject *
wrap_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
    PyObject *result = NULL;
    PyObject *object;

    if (PyArg_UnpackTuple(args, "__new__", 1, 1, &object)) {
        if (kwds != NULL && PyDict_Size(kwds) != 0) {
            PyErr_SetString(PyExc_TypeError,
                            "proxy.__new__ does not accept keyword args");
            return NULL;
        }
        result = PyType_GenericNew(type, args, kwds);
        if (result != NULL) {
            ProxyObject *wrapper = (ProxyObject *) result;
            Py_INCREF(object);
            wrapper->proxy_object = object;
        }
    }
    return result;
}
Exemplo n.º 21
0
// XorMaskerNull - tp_init
static int XorMaskerNull_tp_init(XorMaskerNull *self, PyObject *args, PyObject *kwargs)
{
    /* Check if there is at most 1 argument given */
    int num_args = PyTuple_Size(args);

    if (kwargs && PyDict_Check(kwargs))
        num_args += PyDict_Size(kwargs);

    if (num_args > 1)
    {
        PyErr_Format(PyExc_TypeError,
                     "XorMaskerNull.__init__() takes at most 1 argument (%d given)",
                     num_args);
        return -1;
    }

    /* Initialize the xor masker */
    self->ptr = 0;

    return 0;
}
static PyObject *fparse_function_1_get_wsgi_application_of_module_django__core__wsgi( Nuitka_FunctionObject *self, PyObject **args, Py_ssize_t args_size, PyObject *kw )
{
    assert( kw == NULL || PyDict_Check( kw ) );

    NUITKA_MAY_BE_UNUSED Py_ssize_t kw_size = kw ? PyDict_Size( kw ) : 0;
    NUITKA_MAY_BE_UNUSED Py_ssize_t kw_found = 0;
    NUITKA_MAY_BE_UNUSED Py_ssize_t kw_only_found = 0;
    Py_ssize_t args_given = args_size;

    if (unlikely( args_given + kw_size > 0 ))
    {
#if PYTHON_VERSION < 330
        PyErr_Format( PyExc_TypeError, "get_wsgi_application() takes no arguments (%zd given)", args_given + kw_size );
#else
        if ( kw_size == 0 )
        {
           PyErr_Format( PyExc_TypeError, "get_wsgi_application() takes 0 positional arguments but %zd was given", args_given );
        }
        else
        {
           PyObject *tmp_iter = PyObject_GetIter( kw );
           PyObject *tmp_arg_name = PyIter_Next( tmp_iter );
           Py_DECREF( tmp_iter );

           PyErr_Format( PyExc_TypeError, "get_wsgi_application() got an unexpected keyword argument '%s'", Nuitka_String_AsString( tmp_arg_name ) );

           Py_DECREF( tmp_arg_name );
        }
#endif
        goto error_exit;
    }


    return impl_function_1_get_wsgi_application_of_module_django__core__wsgi( self );

error_exit:;


    return NULL;
}
Exemplo n.º 23
0
static int PyBobLearnEMGMMMachine_init(PyBobLearnEMGMMMachineObject* self, PyObject* args, PyObject* kwargs) {
  BOB_TRY

  // get the number of command line arguments
  int nargs = (args?PyTuple_Size(args):0) + (kwargs?PyDict_Size(kwargs):0);

  switch (nargs) {

    case 0: //default initializer ()
      self->cxx.reset(new bob::learn::em::GMMMachine());
      return 0;

    case 1:{
      //Reading the input argument
      PyObject* arg = 0;
      if (PyTuple_Size(args))
        arg = PyTuple_GET_ITEM(args, 0);
      else {
        PyObject* tmp = PyDict_Values(kwargs);
        auto tmp_ = make_safe(tmp);
        arg = PyList_GET_ITEM(tmp, 0);
      }

      // If the constructor input is Gaussian object
     if (PyBobLearnEMGMMMachine_Check(arg))
       return PyBobLearnEMGMMMachine_init_copy(self, args, kwargs);
      // If the constructor input is a HDF5
     else if (PyBobIoHDF5File_Check(arg))
       return PyBobLearnEMGMMMachine_init_hdf5(self, args, kwargs);
    }
    case 2:
      return PyBobLearnEMGMMMachine_init_number(self, args, kwargs);
    default:
      PyErr_Format(PyExc_RuntimeError, "number of arguments mismatch - %s requires 0, 1 or 2 arguments, but you provided %d (see help)", Py_TYPE(self)->tp_name, nargs);
      GMMMachine_doc.print_usage();
      return -1;
  }
  BOB_CATCH_MEMBER("cannot create GMMMachine", -1)
  return 0;
}
Exemplo n.º 24
0
static int
update_ufd_array(pollObject *self)
{
	int i, pos;
	PyObject *key, *value;

	self->ufd_len = PyDict_Size(self->dict);
	PyMem_Resize(self->ufds, struct pollfd, self->ufd_len);
	if (self->ufds == NULL) {
		PyErr_NoMemory();
		return 0;
	}

	i = pos = 0;
	while (PyDict_Next(self->dict, &pos, &key, &value)) {
		self->ufds[i].fd = PyInt_AsLong(key);
		self->ufds[i].events = (short)PyInt_AsLong(value);
		i++;
	}
	self->ufd_uptodate = 1;
	return 1;
}
Exemplo n.º 25
0
int
Index_init(Index *self, PyObject *args, PyObject *kwds)
{
    char *path;
    int err;

    if (kwds && PyDict_Size(kwds) > 0) {
        PyErr_SetString(PyExc_TypeError, "Index takes no keyword arguments");
        return -1;
    }

    if (!PyArg_ParseTuple(args, "s", &path))
        return -1;

    err = git_index_open(&self->index, path);
    if (err < 0) {
        Error_set_str(err, path);
        return -1;
    }

    return 0;
}
Exemplo n.º 26
0
static int PyBobSpFFT2D_Init(PyBobSpFFT2DObject* self,
    PyObject* args, PyObject* kwds) {

  Py_ssize_t nargs = (args?PyTuple_Size(args):0) + (kwds?PyDict_Size(kwds):0);

  switch (nargs) {

    case 1:
      return PyBobSpFFT2D_InitCopy(self, args, kwds);

    case 2:
      return PyBobSpFFT2D_InitShape(self, args, kwds);

    default:

      PyErr_Format(PyExc_RuntimeError, "number of arguments mismatch - %s requires 1 argument, but you provided %" PY_FORMAT_SIZE_T "d (see help)", Py_TYPE(self)->tp_name, nargs);

  }

  return -1;

}
Exemplo n.º 27
0
static PyObject* new_check(PyObject* args)
{
    // We don't support a normal constructor, so only allow this for unpickling.  There should be a single arg that was
    // returned by Row_reduce.  Make sure the sizes match.  The desc and map should have one entry per column, which
    // should equal the number of remaining items.

    if (PyTuple_GET_SIZE(args) < 3)
        return 0;

    PyObject* desc = PyTuple_GET_ITEM(args, 0);
    PyObject* map  = PyTuple_GET_ITEM(args, 1);

    if (!PyTuple_CheckExact(desc) || !PyDict_CheckExact(map))
        return 0;

    Py_ssize_t cols = PyTuple_GET_SIZE(desc);

    if (PyDict_Size(map) != cols || PyTuple_GET_SIZE(args) - 2 != cols)
        return 0;

    PyObject** apValues = (PyObject**)pyodbc_malloc(sizeof(PyObject*) * cols);
    if (!apValues)
        return 0;

    for (int i = 0; i < cols; i++)
    {
        apValues[i] = PyTuple_GET_ITEM(args, i+2);
        Py_INCREF(apValues[i]);
    }

    // Row_Internal will incref desc and map.

    PyObject* self = (PyObject*)Row_InternalNew(desc, map, cols, apValues);
    if (!self)
        pyodbc_free(apValues);

    return self;
}
Exemplo n.º 28
0
/* ----------------------------------mathutils.Quaternion() -------------- */
static PyObject *Quaternion_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
	PyObject *seq = NULL;
	double angle = 0.0f;
	float quat[QUAT_SIZE] = {0.0f, 0.0f, 0.0f, 0.0f};

	if (kwds && PyDict_Size(kwds)) {
		PyErr_SetString(PyExc_TypeError,
		                "mathutils.Quaternion(): "
		                "takes no keyword args");
		return NULL;
	}

	if (!PyArg_ParseTuple(args, "|Od:mathutils.Quaternion", &seq, &angle))
		return NULL;

	switch (PyTuple_GET_SIZE(args)) {
		case 0:
			break;
		case 1:
			if (mathutils_array_parse(quat, QUAT_SIZE, QUAT_SIZE, seq, "mathutils.Quaternion()") == -1)
				return NULL;
			break;
		case 2:
		{
			float axis[3];
			if (mathutils_array_parse(axis, 3, 3, seq, "mathutils.Quaternion()") == -1)
				return NULL;
			angle = angle_wrap_rad(angle); /* clamp because of precision issues */
			axis_angle_to_quat(quat, axis, angle);
			break;
			/* PyArg_ParseTuple assures no more than 2 */
		}
	}
	return Quaternion_CreatePyObject(quat, Py_NEW, type);
}
Exemplo n.º 29
0
static int PyBobLearnEMISVMachine_init(PyBobLearnEMISVMachineObject* self, PyObject* args, PyObject* kwargs) {
  BOB_TRY

  // get the number of command line arguments
  int nargs = (args?PyTuple_Size(args):0) + (kwargs?PyDict_Size(kwargs):0);

  if(nargs == 1){
    //Reading the input argument
    PyObject* arg = 0;
    if (PyTuple_Size(args))
      arg = PyTuple_GET_ITEM(args, 0);
    else {
      PyObject* tmp = PyDict_Values(kwargs);
      auto tmp_ = make_safe(tmp);
      arg = PyList_GET_ITEM(tmp, 0);
    }

    // If the constructor input is Gaussian object
    if (PyBobLearnEMISVMachine_Check(arg))
      return PyBobLearnEMISVMachine_init_copy(self, args, kwargs);
    // If the constructor input is a HDF5
    else if (PyBobIoHDF5File_Check(arg))
      return PyBobLearnEMISVMachine_init_hdf5(self, args, kwargs);
    // If the constructor input is a JFABase Object
    else
      return PyBobLearnEMISVMachine_init_isvbase(self, args, kwargs);
  }
  else{
    PyErr_Format(PyExc_RuntimeError, "number of arguments mismatch - %s requires only 1 argument, but you provided %d (see help)", Py_TYPE(self)->tp_name, nargs);
    ISVMachine_doc.print_usage();
    return -1;
  }
  
  BOB_CATCH_MEMBER("cannot create ISVMachine", -1)
  return 0;
}
Exemplo n.º 30
0
static PyObject *
g_switch(PyGreenlet* target, PyObject* args, PyObject* kwargs)
{
	/* _consumes_ a reference to the args tuple and kwargs dict,
	   and return a new tuple reference */
	PyObject* run_info;

	/* check ts_current */
	if (!STATE_OK) {
		Py_XDECREF(args);
		Py_XDECREF(kwargs);
		return NULL;
	}
	run_info = green_statedict(target);
	if (run_info == NULL || run_info != ts_current->run_info) {
		Py_XDECREF(args);
		Py_XDECREF(kwargs);
		PyErr_SetString(PyExc_GreenletError, run_info
				? "cannot switch to a different thread"
				: "cannot switch to a garbage collected greenlet");
		return NULL;
	}

	ts_passaround_args = args;
	ts_passaround_kwargs = kwargs;

	/* find the real target by ignoring dead greenlets,
	   and if necessary starting a greenlet. */
	while (target) {
		if (PyGreenlet_ACTIVE(target)) {
			ts_target = target;
			if (g_switchstack() < 0) {
				g_passaround_clear();
				return NULL;
			}
			break;
		}
		if (!PyGreenlet_STARTED(target)) {
			int err;
			void* dummymarker;
			ts_target = target;
			err = g_initialstub(&dummymarker);
			if (err == 1) {
				continue; /* retry the switch */
			}
			else if (err < 0) {
				g_passaround_clear();
				return NULL;
			}
			break;
		}
		target = target->parent;
	}

	/* We need to figure out what values to pass to the target greenlet
	   based on the arguments that have been passed to greenlet.switch(). If
	   switch() was just passed an arg tuple, then we'll just return that.
	   If only keyword arguments were passed, then we'll pass the keyword
	   argument dict. Otherwise, we'll create a tuple of (args, kwargs) and
	   return both. */
	if (ts_passaround_kwargs == NULL)
	{
		g_passaround_return_args();
	}
	else if (PyDict_Size(ts_passaround_kwargs) == 0)
	{
		g_passaround_return_args();
	}
	else if (PySequence_Length(ts_passaround_args) == 0)
	{
		g_passaround_return_kwargs();
	}
	else
	{
		PyObject *tuple = PyTuple_New(2);
		if (tuple == NULL) {
			g_passaround_clear();
			return NULL;
		}
		PyTuple_SET_ITEM(tuple, 0, ts_passaround_args);
		PyTuple_SET_ITEM(tuple, 1, ts_passaround_kwargs);
		ts_passaround_args = NULL;
		ts_passaround_kwargs = NULL;
		return tuple;
	}
}