• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

C++ PyList_Size函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了C++中PyList_Size函数的典型用法代码示例。如果您正苦于以下问题:C++ PyList_Size函数的具体用法?C++ PyList_Size怎么用?C++ PyList_Size使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了PyList_Size函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C++代码示例。

示例1: PyList_Size

unsigned int KPythonList::Size()
{
    PyLockGIL lock;
    return PyList_Size(this->list);
}
开发者ID:hyuni,项目名称:kroll,代码行数:5,代码来源:k_python_list.cpp


示例2: PyErr_SetString

static PyObject *robustLS_to_sdp
(PyObject *self, PyObject *args, PyObject *kwrds) {

  PyObject *Alist,*bt, *Ai;
  spmatrix *A,*b;
  int_t m,n,mp,np,pt,i,j,k,N,nnz=0,ri=0;
  char *kwlist[] = {"Alist","bt",NULL};

  if(!PyArg_ParseTupleAndKeywords(args,kwrds,"OO",kwlist,&Alist,&bt)) return NULL;

  if(!PyList_Check(Alist)) {
    PyErr_SetString(PyExc_TypeError,"Alist must be a list of matrices");
    return NULL;
  }

  // get pt = p + 1
  pt = PyList_Size(Alist);

  // get size of bt
  if(Matrix_Check(bt)){
    m = MAT_NROWS(bt);
    np = MAT_NCOLS(bt);
  }
  else if (SpMatrix_Check(bt)){
    m = SP_NROWS(bt);
    np = SP_NCOLS(bt);
  }
  else {
    PyErr_SetString(PyExc_TypeError,"b must be a vector");
    return NULL;
  }
  if (np!=1) {
    PyErr_SetString(PyExc_TypeError,"b must be a vector");
    return NULL;
  }

  // get n and check A0
  if (!(Ai = PyList_GetItem(Alist,0))) return NULL;
  if (Matrix_Check(Ai)) {
    n = MAT_NCOLS(Ai);
    nnz += m*n;
  }
  else if (SpMatrix_Check(Ai)) {
    n = SP_NCOLS(Ai);
    nnz += SP_NNZ(Ai);
  }
  else {
    PyErr_SetString(PyExc_TypeError,"only spmatrix and matrix types allowed");
    return NULL;
  }

  // check remaining matrices in Alist
  for (i=1;i<pt;i++) {
    if (!(Ai = PyList_GetItem(Alist,i))) return NULL;
    if (Matrix_Check(Ai)) {
      mp = MAT_NROWS(Ai);
      np = MAT_NCOLS(Ai);
      nnz += m*n;
    }
    else if (SpMatrix_Check(Ai)) {
      mp = SP_NROWS(Ai);
      np = SP_NCOLS(Ai);
      nnz += SP_NNZ(Ai);
    }
    else {
      PyErr_SetString(PyExc_TypeError,"only spmatrix and matrix types allowed");
      return NULL;
    }
    if (!(mp==m && np==n)){
      PyErr_SetString(PyExc_TypeError,"matrices in Alist must have same size");
      return NULL;
    }
  }
  nnz += 2*m + pt;

  // generate b
  b = SpMatrix_New(n+2,1,2,DOUBLE);
  if (!b) return PyErr_NoMemory();
  SP_COL(b)[0] = 0;
  SP_VALD(b)[0] = -1;
  SP_ROW(b)[0] = 0;
  SP_VALD(b)[1] = -1;
  SP_ROW(b)[1] = 1;
  SP_COL(b)[1] = 2;

  // generate A
  N = m+pt;
  A = SpMatrix_New(N*N,n+3,nnz,DOUBLE);
  if (!A) return PyErr_NoMemory();

  // build A0
  SP_COL(A)[0] = ri;
  for(i=0;i<m;i++){
    if(SpMatrix_Check(bt)){
      SP_VALD(A)[ri] = -SP_VALD(bt)[i];
      SP_ROW(A)[ri++] = pt+i;
    }
    else{
      SP_VALD(A)[ri] = -MAT_BUFD(bt)[i];
      SP_ROW(A)[ri++] = pt+i;
//.........这里部分代码省略.........
开发者ID:cvxopt,项目名称:smcp,代码行数:101,代码来源:misc.c


示例3: Repository_create_commit

PyObject *
Repository_create_commit(Repository *self, PyObject *args)
{
    Signature *py_author, *py_committer;
    PyObject *py_oid, *py_message, *py_parents, *py_parent;
    PyObject *py_result = NULL;
    char *message = NULL;
    char *update_ref = NULL;
    char *encoding = NULL;
    git_oid oid;
    git_tree *tree = NULL;
    int parent_count;
    git_commit **parents = NULL;
    int err = 0, i = 0;
    size_t len;

    if (!PyArg_ParseTuple(args, "zO!O!OOO!|s",
                          &update_ref,
                          &SignatureType, &py_author,
                          &SignatureType, &py_committer,
                          &py_message,
                          &py_oid,
                          &PyList_Type, &py_parents,
                          &encoding))
        return NULL;

    len = py_oid_to_git_oid(py_oid, &oid);
    if (len == 0)
        goto out;

    message = py_str_to_c_str(py_message, encoding);
    if (message == NULL)
        goto out;

    err = git_tree_lookup_prefix(&tree, self->repo, &oid, len);
    if (err < 0) {
        Error_set(err);
        goto out;
    }

    parent_count = (int)PyList_Size(py_parents);
    parents = malloc(parent_count * sizeof(git_commit*));
    if (parents == NULL) {
        PyErr_SetNone(PyExc_MemoryError);
        goto out;
    }
    for (; i < parent_count; i++) {
        py_parent = PyList_GET_ITEM(py_parents, i);
        len = py_oid_to_git_oid(py_parent, &oid);
        if (len == 0)
            goto out;
        err = git_commit_lookup_prefix(&parents[i], self->repo, &oid, len);
        if (err < 0) {
            Error_set(err);
            goto out;
        }
    }

    err = git_commit_create(&oid, self->repo, update_ref,
                            py_author->signature, py_committer->signature,
                            encoding, message, tree, parent_count,
                            (const git_commit**)parents);
    if (err < 0) {
        Error_set(err);
        goto out;
    }

    py_result = git_oid_to_python(&oid);

out:
    free(message);
    git_tree_free(tree);
    while (i > 0) {
        i--;
        git_commit_free(parents[i]);
    }
    free(parents);
    return py_result;
}
开发者ID:alexband,项目名称:pygit2,代码行数:79,代码来源:repository.c


示例4: _curs_doall

/* _curs_doall() - execute an operation (commit or rollback) on all the cursors 
 * 
 * returns NULL on success, a python dictionary if at least one cursor failed.
 * the dictionary maps key: cursor/cursobject to value:
 * error/PyString.
 * Note: in case the dictionary could not be created (out of memory e.g.),
 *       Py_None is returned instead.
 */
static PyObject*
_curs_doall(connobject *self, int (*operation)(cursobject *) )
{
    int len, i, has_errors = 0;
    cursobject *cursor;

    doall_state_t *cursors = NULL;
    PyObject* errs = NULL;

    Dprintf("curs_doall: acquiring lock\n");
    pthread_mutex_lock(&(self->lock));
    Dprintf("curs_doall: lock acquired\n");

    /* collect all the cursors, so we can use them while not holding the GIL
     * We keep a reference to the cursors, in case the self->cursors changes
     * during the call. */
    len = PyList_Size(self->cursors);
    cursors = (doall_state_t *)malloc(len * sizeof (doall_state_t));
    if (!cursors) {
        pthread_mutex_unlock(&(self->lock));
        Dprintf("curs_doall: lock released\n");
        return PyErr_NoMemory();
    }
    for (i = 0; i < len; i++) {
        cursors[i].cursor = (cursobject *)PyList_GetItem(self->cursors, i);
        assert(cursors[i].cursor);
        Py_INCREF(cursors[i].cursor);
        cursors[i].errmsg = NULL;
    }

    Py_BEGIN_ALLOW_THREADS;
    
    Dprintf("curs_doall: %d cursors\n", len);
    
    /* acquire all the required locks */
    for (i = 0; i < len; i++) {
        cursor = cursors[i].cursor;
        Dprintf("curs_doall: lock/iterating on %p\n", cursor);
        if (cursor->keeper->status == KEEPER_BEGIN
            && cursor->isolation_level > 0){
            pthread_mutex_lock(&(cursor->keeper->lock));
            if (cursor->keeper->status == KEEPER_BEGIN) {
                cursor->keeper->status = KEEPER_CONN_LOCK;
                Dprintf("curs_doall: acquired lock on keeper %p cursor %p\n",
                        cursor->keeper, cursor);
            }
            else {
                pthread_mutex_unlock(&(cursor->keeper->lock));
            }
        }
    }

    /* does all the operations */
    for (i = 0; i < len; i++) {
        int status = 0;

        cursor = cursors[i].cursor;
        Dprintf("curs_doall: iterating on %p\n", cursor);
        if (cursor->keeper->status == KEEPER_CONN_LOCK) {
            Dprintf("curs_doall: operating on cursor %p\n", cursor);
            cursor->keeper->status = KEEPER_BEGIN;
            status = (*operation)(cursor);
            if (status == -1) {
                has_errors = 1;
                if (cursor->critical) {
                    cursors[i].errmsg = strdup(cursor->critical);
                }
            }
            cursor->keeper->status = KEEPER_CONN_READY;
        }
    }

    /* unlocks all the connections */
    for (i = 0; i < len; i++) {
        cursor = cursors[i].cursor;
        if (cursor->keeper->status == KEEPER_CONN_READY) {
            pthread_mutex_unlock(&(cursor->keeper->lock));
            cursor->keeper->status = KEEPER_READY;
            Dprintf("curs_doall: released lock on keeper %p\n",
                    cursor->keeper);
        }
    }

    pthread_mutex_unlock(&(self->lock));
    Dprintf("curs_doall: lock released\n");
    Py_END_ALLOW_THREADS;

    /* if an error occurred, set up the error dictionary (or set errs to
     * None if we can't create the dictionary). */
    if (has_errors) {
        errs = PyDict_New();
        if (errs) {
//.........这里部分代码省略.........
开发者ID:kevinpostal,项目名称:craigsjobs,代码行数:101,代码来源:connection.c


示例5: init_uwsgi_app


//.........这里部分代码省略.........

	}
	else if (interpreter) {
		wi->interpreter = interpreter;
	}
	else {
		wi->interpreter = up.main_thread;
	}

	if (wsgi_req->home_len) {
		set_dyn_pyhome(wsgi_req->home, wsgi_req->home_len);
	}

	if (wsgi_req->touch_reload_len > 0 && wsgi_req->touch_reload_len < 0xff) {
		struct stat trst;
		strncpy(wi->touch_reload, wsgi_req->touch_reload, wsgi_req->touch_reload_len);
		if (!stat(wi->touch_reload, &trst)) {
			wi->touch_reload_mtime = trst.st_mtime;
		}
	}

	wi->callable = up.loaders[loader](arg1);

	if (!wi->callable) {
		uwsgi_log("unable to load app %d (mountpoint='%s') (callable not found or import error)\n", id, wi->mountpoint);
		goto doh;
	}

	// the module contains multiple apps
	if (PyDict_Check((PyObject *)wi->callable)) {
		applications = wi->callable;
		uwsgi_log("found a multiapp module...\n");
		app_list = PyDict_Keys(applications);
		multiapp = PyList_Size(app_list);
		if (multiapp < 1) {
			uwsgi_log("you have to define at least one app in the apllications dictionary\n");
			goto doh;
		}		

		PyObject *app_mnt = PyList_GetItem(app_list, 0);
		if (!PyString_Check(app_mnt)) {
			uwsgi_log("the app mountpoint must be a string\n");
			goto doh;
		}
		char *tmp_mountpoint = PyString_AsString(app_mnt);
		wi->mountpoint_len = strlen(wi->mountpoint) < 0xff ? strlen(wi->mountpoint) : (0xff-1);
		strncpy(wi->mountpoint, tmp_mountpoint, wi->mountpoint_len);
		wsgi_req->appid = wi->mountpoint;
		wsgi_req->appid_len = wi->mountpoint_len;
#ifdef UWSGI_DEBUG
		uwsgi_log("main mountpoint = %s\n", wi->mountpoint);
#endif
		wi->callable = PyDict_GetItem(applications, app_mnt);
		if (PyString_Check((PyObject *) wi->callable)) {
			PyObject *callables_dict = get_uwsgi_pydict((char *)arg1);
			if (callables_dict) {
				wi->callable = PyDict_GetItem(callables_dict, (PyObject *)wi->callable);	
			}
		}
	}

	Py_INCREF((PyObject *)wi->callable);

	wi->environ = malloc(sizeof(PyObject*)*uwsgi.cores);
	if (!wi->environ) {
		uwsgi_error("malloc()");
开发者ID:alb-i986,项目名称:uwsgi,代码行数:67,代码来源:pyloader.c


示例6: AMC_save

static PyObject *
AMC_save (AMC *self, PyObject *args)
{
	char *filename;
	GIOChannel *file;
	int size, frames, i, j, k;
	PyObject *keys;

	// get filename
	if (!PyArg_ParseTuple (args, "s;expected 'string'", &filename))
		return NULL;

	file = g_io_channel_new_file (filename, "w", NULL);
	if (file == NULL) {
		// FIXME - we should be using the GError, not errno
		return PyErr_SetFromErrnoWithFilename (PyExc_IOError, filename);
	}

	// write out comment
	size = PyList_Size (self->comments);
	for (i = 0; i < size; i++) {
		PyObject *line;
		char *cline;

		line = PyList_GetItem (self->comments, i);
		cline = PyString_AsString (line);

		g_io_channel_write_chars (file, cline, strlen (cline), NULL, NULL);
		g_io_channel_write_chars (file, "\n", 1, NULL, NULL);
	}

	// write out format
	size = PyList_Size (self->format);
	if (size == 0)
		g_io_channel_write_chars (file, ":FULLY-SPECIFIED\n:DEGREES\n", strlen (":FULLY-SPECIFIED\n:DEGREES\n"), NULL, NULL);
	for (i = 0; i < size; i++) {
		PyObject *line;
		char *cline;

		line = PyList_GetItem (self->format, i);
		cline = PyString_AsString (line);

		g_io_channel_write_chars (file, cline, strlen (cline), NULL, NULL);
		g_io_channel_write_chars (file, "\n", 1, NULL, NULL);
	}

	// get keys
	keys = PyDict_Keys (self->bones);
	size = PyList_Size (keys);
	if (size == 0)
		// FIXME - throw error
		return Py_False;

	// find # of frames
	{
		PyObject *bone = PyDict_GetItem (self->bones, PyList_GetItem (keys, 0));
		PyArrayObject *array = (PyArrayObject *) bone;
		frames = array->dimensions[0];
	}

	for (j = 0; j < frames; j++) {
		GIOStatus status;
		char *frame;

		// Write out the frame number
		frame = g_strdup_printf ("%d\n", j + 1);
		g_io_channel_write_chars (file, frame, strlen (frame), NULL, NULL);
		g_free (frame);

		for (i = 0; i < size; i++) {
			PyObject *key;
			char *bone_name;
			PyArrayObject *bone;

			// Write the bone name
			key = PyList_GetItem (keys, i);
			bone = (PyArrayObject *) PyDict_GetItem (self->bones, key);
			bone_name = PyString_AsString (key);
			g_io_channel_write_chars (file, bone_name, strlen (bone_name), NULL, NULL);

			// Write out the bone data
			for (k = 0; k < bone->dimensions[1]; k++) {
				char *data = g_strdup_printf (" %f", *((float*) (bone->data + (j * bone->strides[0]) + (k * bone->strides[1]))));
				g_io_channel_write_chars (file, data, strlen (data), NULL, NULL);
				g_free (data);
			}
			 g_io_channel_write_chars (file, "\n", 1, NULL, NULL);
		}
	}

	g_io_channel_shutdown (file, TRUE, NULL);
	g_io_channel_unref (file);

	Py_RETURN_TRUE;
}
开发者ID:mvanderkolff,项目名称:navi-misc,代码行数:95,代码来源:motion.c


示例7: batch_get_aerospike_batch_read

/**
 *******************************************************************************************************
 * This function will get a batch of records from the Aeropike DB.
 *
 * @param err                   as_error object
 * @param self                  AerospikeClient object
 * @param py_keys               The list of keys
 * @param batch_policy_p        as_policy_batch object
 *
 * Returns the record if key exists otherwise NULL.
 *******************************************************************************************************
 */
static PyObject * batch_get_aerospike_batch_read(as_error *err, AerospikeClient * self, PyObject *py_keys, as_policy_batch * batch_policy_p)
{
    PyObject * py_recs = NULL;

    as_batch_read_records records;

    // Initialisation flags
    bool batch_initialised = false;
    as_batch_read_record* record = NULL;

    // Convert python keys list to as_key ** and add it to as_batch.keys
    // keys can be specified in PyList or PyTuple
    if ( py_keys != NULL && PyList_Check(py_keys) ) {
        Py_ssize_t size = PyList_Size(py_keys);

        py_recs = PyList_New(size);
        if (size > MAX_STACK_ALLOCATION) {
            as_batch_read_init(&records, size);
        } else {
            as_batch_read_inita(&records, size);
        }

        // Batch object initialised
        batch_initialised = true;

        for ( int i = 0; i < size; i++ ) {

            PyObject * py_key = PyList_GetItem(py_keys, i);

            if ( !PyTuple_Check(py_key) ) {
                as_error_update(err, AEROSPIKE_ERR_PARAM, "Key should be a tuple.");
                goto CLEANUP;
            }

            record = as_batch_read_reserve(&records);

            pyobject_to_key(err, py_key, &record->key);
            record->read_all_bins = true;

            if ( err->code != AEROSPIKE_OK ) {
                goto CLEANUP;
            }
        }
    }
    else if ( py_keys != NULL && PyTuple_Check(py_keys) ) {
        Py_ssize_t size = PyTuple_Size(py_keys);

        py_recs = PyList_New(size);
        if (size > MAX_STACK_ALLOCATION) {
            as_batch_read_init(&records, size);
        } else {
            as_batch_read_inita(&records, size);
        }
        // Batch object initialised
        batch_initialised = true;

        for ( int i = 0; i < size; i++ ) {
            PyObject * py_key = PyTuple_GetItem(py_keys, i);

            if ( !PyTuple_Check(py_key) ) {
                as_error_update(err, AEROSPIKE_ERR_PARAM, "Key should be a tuple.");
                goto CLEANUP;
            }

            record = as_batch_read_reserve(&records);

            pyobject_to_key(err, py_key, &record->key);
            record->read_all_bins = true;

            if ( err->code != AEROSPIKE_OK ) {
                goto CLEANUP;
            }
        }
    }
    else {
        as_error_update(err, AEROSPIKE_ERR_PARAM, "Keys should be specified as a list or tuple.");
        goto CLEANUP;
    }

    // Invoke C-client API
    Py_BEGIN_ALLOW_THREADS
    aerospike_batch_read(self->as, err, batch_policy_p, &records);
    Py_END_ALLOW_THREADS
    if (err->code != AEROSPIKE_OK)
    {
        goto CLEANUP;
    }
    batch_get_recs(self, err, &records, &py_recs);
//.........这里部分代码省略.........
开发者ID:BeeswaxIO,项目名称:aerospike-client-python,代码行数:101,代码来源:get_many.c


示例8: CLazyLinker_init

static int
CLazyLinker_init(CLazyLinker *self, PyObject *args, PyObject *kwds)
{
    static char *kwlist[] = {
      (char*)"nodes",
      (char*)"thunks",
      (char*)"pre_call_clear",
      (char*)"allow_gc",
      (char*)"call_counts",
      (char*)"call_times",
      (char*)"compute_map_list",
      (char*)"storage_map_list",
      (char*)"base_input_output_list",
      (char*)"node_n_inputs",
      (char*)"node_n_outputs",
      (char*)"node_input_offset",
      (char*)"node_output_offset",
      (char*)"var_owner",
      (char*)"is_lazy_list",
      (char*)"output_vars",
      (char*)"node_prereqs",
      (char*)"node_output_size",
      (char*)"update_storage",
      (char*)"dependencies",
      NULL};

    PyObject *compute_map_list=NULL,
             *storage_map_list=NULL,
             *base_input_output_list=NULL,
             *node_n_inputs=NULL,
             *node_n_outputs=NULL,
             *node_input_offset=NULL,
             *node_output_offset=NULL,
             *var_owner=NULL,
             *is_lazy=NULL,
             *output_vars=NULL,
             *node_prereqs=NULL,
             *node_output_size=NULL,
             *update_storage=NULL,
             *dependencies=NULL;

    assert(!self->nodes);
    if (! PyArg_ParseTupleAndKeywords(args, kwds, "OOOiOOOOOOOOOOOOOOOO", kwlist,
                                      &self->nodes,
                                      &self->thunks,
                                      &self->pre_call_clear,
                                      &self->allow_gc,
                                      &self->call_counts,
                                      &self->call_times,
                                      &compute_map_list,
                                      &storage_map_list,
                                      &base_input_output_list,
                                      &node_n_inputs,
                                      &node_n_outputs,
                                      &node_input_offset,
                                      &node_output_offset,
                                      &var_owner,
                                      &is_lazy,
                                      &output_vars,
                                      &node_prereqs,
                                      &node_output_size,
                                      &update_storage,
                                      &dependencies
                                      ))
        return -1;
    Py_INCREF(self->nodes);
    Py_INCREF(self->thunks);
    Py_INCREF(self->pre_call_clear);
    Py_INCREF(self->call_counts);
    Py_INCREF(self->call_times);

    Py_ssize_t n_applies = PyList_Size(self->nodes);

    self->n_applies = n_applies;
    self->n_vars = PyList_Size(var_owner);

    if (PyList_Size(self->thunks) != n_applies) return -1;
    if (PyList_Size(self->call_counts) != n_applies) return -1;
    if (PyList_Size(self->call_times) != n_applies) return -1;

    // allocated and initialize thunk_cptr_data and thunk_cptr_fn
    if (n_applies)
      {
        self->thunk_cptr_data = (void**)calloc(n_applies, sizeof(void*));
        self->thunk_cptr_fn = (void**)calloc(n_applies, sizeof(void*));
        self->is_lazy = (int*)calloc(n_applies, sizeof(int));
        self->node_prereqs = (Py_ssize_t**)calloc(n_applies, sizeof(Py_ssize_t*));
        self->node_n_prereqs = (Py_ssize_t*)calloc(n_applies, sizeof(Py_ssize_t));
        assert(self->node_prereqs);
        assert(self->node_n_prereqs);
        assert(self->is_lazy);
        assert(self->thunk_cptr_fn);
        assert(self->thunk_cptr_data);

        for (int i = 0; i < n_applies; ++i)
          {
            PyObject * thunk = PyList_GetItem(self->thunks, i);
            //thunk is borrowed
            if (PyObject_HasAttrString(thunk, "cthunk"))
              {
//.........这里部分代码省略.........
开发者ID:Donghuan,项目名称:Theano,代码行数:101,代码来源:lazylinker_c.c


示例9: lazy_rec_eval

static
int lazy_rec_eval(CLazyLinker * self, Py_ssize_t var_idx, PyObject*one, PyObject*zero)
{
  PyObject *rval = NULL;
  int verbose = 0;
  int err = 0;

  if (verbose) fprintf(stderr, "lazy_rec computing %i\n", (int)var_idx);

  if (self->var_computed[var_idx] || !self->var_has_owner[var_idx])
    return 0;

  Py_ssize_t owner_idx = self->var_owner[var_idx];

  // STEP 1: compute the pre-requirements of the node
  // Includes input nodes for non-lazy ops.
  for (int i = 0; i < self->node_n_prereqs[owner_idx]; ++i)
    {
      Py_ssize_t prereq_idx = self->node_prereqs[owner_idx][i];
      if (!self->var_computed[prereq_idx])
        {
          err = lazy_rec_eval(self, prereq_idx, one, zero);
          if (err) return err;
        }
      assert (self->var_computed[prereq_idx]);
    }

  // STEP 2: compute the node itself
  if (self->is_lazy[owner_idx])
    {
      // update the compute_map cells corresponding to the inputs of this thunk
      for (int i = 0; i < self->node_n_inputs[owner_idx]; ++i)
        {
          int in_idx = self->node_inputs[owner_idx][i];
          if (self->var_computed[in_idx])
            {
              Py_INCREF(one);
              err = PyList_SetItem(self->var_computed_cells[in_idx], 0, one);
            }
          else
            {
              Py_INCREF(zero);
              err = PyList_SetItem(self->var_computed_cells[in_idx], 0, zero);
            }
          if (err) goto fail;
        }

      rval = pycall(self, owner_idx, verbose);
      // refcounting - rval is new ref
      //TODO: to prevent infinite loops
      // - consider check that a thunk does not ask for an input that is already computed
      if (rval == NULL)
        {
          assert (PyErr_Occurred());
          err = 1;
          goto fail;
        }

      //update the computed-ness of any output cells
      for (int i = 0; i < self->node_n_outputs[owner_idx]; ++i)
        {
          int out_idx = self->node_outputs[owner_idx][i];
          PyObject * el_i = PyList_GetItem(self->var_computed_cells[out_idx], 0);
          Py_ssize_t N = PyNumber_AsSsize_t(el_i, PyExc_IndexError);
          if (PyErr_Occurred())
            {
              err = -1;
              goto pyfail;
            }
          assert (N==0 || N==1);
          self->var_computed[out_idx] = N;
        }
      if (!self->var_computed[var_idx])
        {
          /*
           * If self is not computed after the call, this means that some
           * inputs are needed.  Compute the ones on the returned list
           * and try to compute the current node again (with recursive call).
           * This allows a node to request more nodes more than once before
           * finally yielding a result.
           */
          if (!PyList_Check(rval))
            {
              //TODO: More helpful error to help find *which node* made this
              // bad thunk
              PyErr_SetString(PyExc_TypeError,
                              "lazy thunk should return a list");
              err = 1;
              goto pyfail;
            }

          if (!PyList_Size(rval))
            {
              PyErr_SetString(PyExc_ValueError,
                              "lazy thunk returned empty list without computing output");
              err = 1;
              goto pyfail;
            }

          for (int i = 0; i < PyList_Size(rval); ++i)
//.........这里部分代码省略.........
开发者ID:Donghuan,项目名称:Theano,代码行数:101,代码来源:lazylinker_c.c


示例10: igraphmodule_EdgeSeq_get_attribute_values

/** \ingroup python_interface_edgeseq
 * \brief Returns the list of values for a given attribute
 */
PyObject* igraphmodule_EdgeSeq_get_attribute_values(igraphmodule_EdgeSeqObject* self, PyObject* o) {
  igraphmodule_GraphObject *gr = self->gref;
  PyObject *result=0, *values, *item;
  long int i, n;

  if (!igraphmodule_attribute_name_check(o))
    return 0;

  PyErr_Clear();
  values=PyDict_GetItem(ATTR_STRUCT_DICT(&gr->g)[ATTRHASH_IDX_EDGE], o);
  if (!values) {
    PyErr_SetString(PyExc_KeyError, "Attribute does not exist");
    return NULL;
  } else if (PyErr_Occurred()) return NULL;

  switch (igraph_es_type(&self->es)) {
    case IGRAPH_ES_NONE:
      n = 0;
      result = PyList_New(0);
      break;

    case IGRAPH_ES_ALL:
      n = PyList_Size(values);
      result = PyList_New(n);
      if (!result) return 0;

      for (i=0; i<n; i++) {
          item = PyList_GET_ITEM(values, i);
          Py_INCREF(item);
          PyList_SET_ITEM(result, i, item);
      }
      break;

    case IGRAPH_ES_VECTOR:
    case IGRAPH_ES_VECTORPTR:
      n = igraph_vector_size(self->es.data.vecptr);
      result = PyList_New(n);
      if (!result) return 0;

      for (i=0; i<n; i++) {
        item = PyList_GET_ITEM(values, (long)VECTOR(*self->es.data.vecptr)[i]);
        Py_INCREF(item);
        PyList_SET_ITEM(result, i, item);
      }
      break;

    case IGRAPH_ES_SEQ:
      n = self->es.data.seq.to - self->es.data.seq.from;
      result = PyList_New(n);
      if (!result) return 0;

      for (i=0; i<n; i++) {
        item = PyList_GET_ITEM(values, (long)self->es.data.seq.from+i);
        Py_INCREF(item);
        PyList_SET_ITEM(result, i, item);
      }
      break;

    default:
      PyErr_SetString(PyExc_RuntimeError, "invalid edge selector");
  }

  return result;
}
开发者ID:bravery,项目名称:python-igraph,代码行数:67,代码来源:edgeseqobject.c


示例11: setup_context

/* Returns 0 on error (no new refs), 1 on success */
static int
setup_context(Py_ssize_t stack_level, PyObject **filename, int *lineno,
              PyObject **module, PyObject **registry)
{
    PyObject *globals;

    /* Setup globals and lineno. */
    PyFrameObject *f = PyThreadState_GET()->frame;
    while (--stack_level > 0 && f != NULL)
        f = f->f_back;

    if (f == NULL) {
        globals = PyThreadState_Get()->interp->sysdict;
        *lineno = 1;
    }
    else {
        globals = f->f_globals;
        *lineno = PyFrame_GetLineNumber(f);
    }

    *module = NULL;

    /* Setup registry. */
    assert(globals != NULL);
    assert(PyDict_Check(globals));
    *registry = PyDict_GetItemString(globals, "__warningregistry__");
    if (*registry == NULL) {
        int rc;

        *registry = PyDict_New();
        if (*registry == NULL)
            return 0;

         rc = PyDict_SetItemString(globals, "__warningregistry__", *registry);
         if (rc < 0)
            goto handle_error;
    }
    else
        Py_INCREF(*registry);

    /* Setup module. */
    *module = PyDict_GetItemString(globals, "__name__");
    if (*module == NULL) {
        *module = PyString_FromString("<string>");
        if (*module == NULL)
            goto handle_error;
    }
    else
        Py_INCREF(*module);

    /* Setup filename. */
    *filename = PyDict_GetItemString(globals, "__file__");
    if (*filename != NULL) {
            Py_ssize_t len = PyString_Size(*filename);
        const char *file_str = PyString_AsString(*filename);
            if (file_str == NULL || (len < 0 && PyErr_Occurred()))
            goto handle_error;

        /* if filename.lower().endswith((".pyc", ".pyo")): */
        if (len >= 4 &&
            file_str[len-4] == '.' &&
            tolower(file_str[len-3]) == 'p' &&
            tolower(file_str[len-2]) == 'y' &&
            (tolower(file_str[len-1]) == 'c' ||
                tolower(file_str[len-1]) == 'o'))
        {
            *filename = PyString_FromStringAndSize(file_str, len-1);
            if (*filename == NULL)
                goto handle_error;
        }
        else
            Py_INCREF(*filename);
    }
    else {
        const char *module_str = PyString_AsString(*module);
        if (module_str && strcmp(module_str, "__main__") == 0) {
            PyObject *argv = PySys_GetObject("argv");
            if (argv != NULL && PyList_Size(argv) > 0) {
                int is_true;
                *filename = PyList_GetItem(argv, 0);
                Py_INCREF(*filename);
                /* If sys.argv[0] is false, then use '__main__'. */
                is_true = PyObject_IsTrue(*filename);
                if (is_true < 0) {
                    Py_DECREF(*filename);
                    goto handle_error;
                }
                else if (!is_true) {
                    Py_DECREF(*filename);
                    *filename = PyString_FromString("__main__");
                    if (*filename == NULL)
                        goto handle_error;
                }
            }
            else {
                /* embedded interpreters don't have sys.argv, see bug #839151 */
                *filename = PyString_FromString("__main__");
                if (*filename == NULL)
                    goto handle_error;
//.........这里部分代码省略.........
开发者ID:GINK03,项目名称:StaticPython,代码行数:101,代码来源:_warnings.c


示例12: PyTesseract_invalidate_iterators

static void PyTesseract_invalidate_iterators(PyTesseract *self) {
	for (Py_ssize_t index = 0; index < PyList_Size(self->iterators); ++index) {
		PyResultIterator *iterator = (PyResultIterator *)PyList_GetItem(self->iterators, index);
		iterator->valid = false;
	}
}
开发者ID:gpjt,项目名称:tesserpy,代码行数:6,代码来源:tesserpy.cpp


示例13: pyjobject_init


//.........这里部分代码省略.........
        //
        // so what i did here was find the methodid using langClass,
        // but then i call the method using clazz. methodIds for java
        // classes are shared....

        methodArray = (jobjectArray) (*env)->CallObjectMethod(env, pyjob->clazz,
                      classGetMethods);
        if (process_java_exception(env) || !methodArray) {
            goto EXIT_ERROR;
        }

        // for each method, create a new pyjmethod object
        // and add to the internal methods list.
        len = (*env)->GetArrayLength(env, methodArray);
        for (i = 0; i < len; i++) {
            PyJMethodObject *pymethod = NULL;
            jobject rmethod = NULL;

            rmethod = (*env)->GetObjectArrayElement(env, methodArray, i);

            // make new PyJMethodObject, linked to pyjob
            if (pyjob->object) {
                pymethod = pyjmethod_new(env, rmethod, pyjob);
            } else {
                pymethod = pyjmethod_new_static(env, rmethod, pyjob);
            }

            if (!pymethod) {
                continue;
            }

            if (pymethod->pyMethodName && PyString_Check(pymethod->pyMethodName)) {
                int multi = 0;
                Py_ssize_t cacheLen = PyList_Size(pyjMethodList);
                int cacheIndex = 0;
                for (cacheIndex = 0; cacheIndex < cacheLen; cacheIndex += 1) {
                    PyObject* cached = PyList_GetItem(pyjMethodList, cacheIndex);
                    if (pyjmethod_check(cached)) {
                        PyJMethodObject* cachedMethod = (PyJMethodObject*) cached;
                        if (PyObject_RichCompareBool(pymethod->pyMethodName, cachedMethod->pyMethodName,
                                                     Py_EQ)) {
                            PyObject* multimethod = PyJmultiMethod_New((PyObject*) pymethod, cached);
                            PyList_SetItem(pyjMethodList, cacheIndex, multimethod);
                            multi = 1;
                            break;
                        }
                    } else if (PyJmultiMethod_Check(cached)) {
                        PyObject* methodName = PyJmultiMethod_GetName(cached);
                        if (PyObject_RichCompareBool(pymethod->pyMethodName, methodName, Py_EQ)) {
                            Py_DECREF(methodName);
                            PyJmultiMethod_Append(cached, (PyObject*) pymethod);
                            multi = 1;
                            break;
                        } else {
                            Py_DECREF(methodName);
                        }
                    }
                }
                if (!multi) {
                    if (PyList_Append(pyjMethodList, (PyObject*) pymethod) != 0) {
                        printf("WARNING: couldn't add method");
                    }
                }
            }

            Py_DECREF(pymethod);
开发者ID:codeApeFromChina,项目名称:jep,代码行数:67,代码来源:pyjobject.c


示例14: features_calculateFeatures

static PyObject* features_calculateFeatures(PyObject *self, PyObject *args) {
    const char *data;
    ULL prim, qmod, win, fmod, val, ppow, fval, mul, add;
    int i, j, min;
    Py_ssize_t amount;
    ULL *best, *features;
    PyObject *pis, *item, *result;
    Py_ssize_t data_len;

    if (!PyArg_ParseTuple(args, "s#KKKKO", &data, &data_len, &prim, &qmod,
                          &win, &fmod, &pis))
        return NULL;

    amount = PyList_Size(pis);
    if (!(best = malloc(2 * amount * sizeof(ULL))))
        return NULL;
    features = best + amount;

    ppow = 1;
    for (i = 1; i < win; i++)
        ppow = (ppow * prim) % qmod;

    val = 0;
    min = (win < data_len) ? win : data_len;
    for (i = 0; i < min; i++)
        val = (val * prim + data[i]) % qmod;

    if (win <= data_len) {
        for (j = 0; j < amount; j++) {
            item = PyList_GET_ITEM(pis, j);
            if (!PyArg_ParseTuple(item, "KK", &mul, &add))
                goto free_best;
            best[j] = (val * mul + add) % fmod;
            features[j] = val;
        }
    }

    for (i = win; i < data_len; i++) {
        val = (val + (qmod - data[i - win]) * ppow) % qmod;
        val = (val * prim + data[i]) % qmod;
        for (j = 0; j < amount; j++) {
            item = PyList_GET_ITEM(pis, j);
            if (!PyArg_ParseTuple(item, "KK", &mul, &add))
                goto free_best;
            fval = (val * mul + add) % fmod;
            if (fval > best[j]) {
                best[j] = fval;
                features[j] = val;
            }
        }
    }

    if (!(result = PyList_New(amount)))
        goto free_best;
    for (i = 0; i < amount; i++) {
        if (!(item = Py_BuildValue("K", features[i])))
            goto free_result;
        PyList_SET_ITEM(result, i, item);
    }
    free(best);
    return result;
free_result:
    Py_DECREF(result);
free_best:
    free(best);
    return NULL;
}
开发者ID:zpp-2014-15,项目名称:deltacompression,代码行数:67,代码来源:features_calculator.c


示例15: throw

void ChPythonEngine::ImportSolidWorksSystem(const char* solidworks_py_file, ChSystem& msystem) throw(ChException)
{
	std::ostringstream sstream;

	//sstream << "from " << std::string(solidworks_py_file) << " import exported_items\n";

	sstream << "import builtins  \n";
	sstream << "import imp  \n";
	sstream << "import os  \n";
	sstream << "mdirname, mmodulename= os.path.split('" << std::string(solidworks_py_file) << "')  \n";
	sstream << "builtins.exported_system_relpath = mdirname + '/'  \n";
	sstream << "fp, pathname, description = imp.find_module(mmodulename,[builtins.exported_system_relpath])  \n";
	sstream << "try:  \n";
	sstream << "    imported_mod = imp.load_module('imported_mod', fp, pathname, description)  \n";
	sstream << "finally:  \n";
	sstream << "    if fp:  \n";
	sstream << "        fp.close()  \n";
	sstream << "exported_items = imported_mod.exported_items  \n";

	this->Run(sstream.str().c_str());
	
	PyObject * module = PyImport_AddModule("__main__"); // borrowed reference
	if (!module)
		throw ChException("ERROR. No Python __main__ module?"); 

	PyObject * dictionary = PyModule_GetDict(module);   // borrowed reference
	if (!dictionary) 
		throw ChException("ERROR. No Python dictionary?");                                 

	PyObject * result = PyDict_GetItemString(dictionary, "exported_items");   // borrowed reference
	if (!result) 
		throw ChException("ERROR. Missing Python object 'exported_items' in SolidWorks file");

	if (PyList_Check(result))
	{
		int nitems = PyList_Size(result);
		//GetLog() << "N.of list items: " << nitems << "\n";
		for (int i = 0; i< nitems; i++)
		{
			PyObject* mobj = PyList_GetItem(result,i);
			if (mobj)
			{	
				// GetLog() << "   Python type: " << mobj->ob_type->tp_name << "\n";
				
				SwigPyObject * mswigobj  = SWIG_Python_GetSwigThis(mobj);
				if (mswigobj) 
				{
					void* objptr = mswigobj->ptr;
					ChSharedPtr<ChPhysicsItem>* pt_to_shp = (ChSharedPtr<ChPhysicsItem>*)objptr;	
				
						/// Add the ChPhysicsItem to the ChSystem
					msystem.Add( (*pt_to_shp) );
				} 
				else
				{
					throw ChException("ERROR. Only shared pointers to ChPhysicsItem subclasses can be inside exported_items.");
				}
			}
		}

		msystem.Setup();
		msystem.Update();

	}
	else
	{
		throw ChException("ERROR. exported_items python object is not a list.");
	}

	
}
开发者ID:DavidHammen,项目名称:chrono,代码行数:71,代码来源:ChPython.cpp


示例16: CLazyLinker_call

PyObject *
CLazyLinker_call(PyObject *_self, PyObject *args, PyObject *kwds)
{
  CLazyLinker * self = (CLazyLinker*)_self;
  static char *kwlist[] = {
    (char*)"time_thunks",
    (char *)"n_calls",
    NULL};
  int n_calls=1;
  if (! PyArg_ParseTupleAndKeywords(args, kwds, "|ii", kwlist,
                                    &self->do_timing,
                                    &n_calls))
    return NULL;
  int err = 0;
  self->position_of_error = -1;
  // create constants used to fill the var_compute_cells
  PyObject * one = PyInt_FromLong(1);
  PyObject * zero = PyInt_FromLong(0);

  // pre-allocate our return value
  Py_INCREF(Py_None);
  PyObject * rval = Py_None;
  //clear storage of pre_call_clear elements
  for (int call_i = 0; call_i < n_calls && (!err); ++call_i)
    {
      Py_ssize_t n_pre_call_clear = PyList_Size(self->pre_call_clear);
      assert(PyList_Check(self->pre_call_clear));
      for (int i = 0; i < n_pre_call_clear; ++i)
        {
          PyObject * el_i = PyList_GetItem(self->pre_call_clear, i);
          Py_INCREF(Py_None);
          PyList_SetItem(el_i, 0, Py_None);
        }
      //clear the computed flag out of all non-input vars
      for (int i = 0; i < self->n_vars; ++i)
        {
          self->var_computed[i] = !self->var_has_owner[i];
          if (self->var_computed[i])
            {
              Py_INCREF(one);
              PyList_SetItem(self->var_computed_cells[i], 0, one);
            }
          else
            {
              Py_INCREF(zero);
              PyList_SetItem(self->var_computed_cells[i], 0, zero);
            }
        }

      for (int i = 0; i < self->n_output_vars && (!err); ++i)
        {
          err = lazy_rec_eval(self, self->output_vars[i], one, zero);
        }

      if (!err)
        {
          // save references to outputs prior to updating storage containers
          assert (self->n_output_vars >= self->n_updates);
          Py_DECREF(rval);
          rval = PyList_New(self->n_output_vars);
          for (int i = 0; i < (self->n_output_vars); ++i)
            {
              Py_ssize_t src = self->output_vars[i];
              PyObject * item = PyList_GetItem(self->var_value_cells[src], 0);
              if (self->var_computed[src] != 1)
                {
                  err = 1;
                  PyErr_Format(PyExc_AssertionError,
                               "The compute map of output %d should contain "
                               "1 at the end of execution, not %d.",
                               i, self->var_computed[src]);
                  break;
                }
              Py_INCREF(item);
              PyList_SetItem(rval, i, item);
            }
        }

      if (!err)
        {
          // Update the inputs that have an update rule
          for (int i = 0; i < self->n_updates; ++i)
            {
              PyObject* tmp = PyList_GetItem(rval, self->n_output_vars - self->n_updates + i);
              Py_INCREF(tmp);
              Py_ssize_t dst = self->update_storage[i];
              PyList_SetItem(self->var_value_cells[dst], 0, tmp);
            }
        }
    }

  /*
    Clear everything that is left and not an output.  This is needed
    for lazy evaluation since the current GC algo is too conservative
    with lazy graphs.
  */
  if (self->allow_gc && !err)
    {
      for (Py_ssize_t i = 0; i < self->n_vars; ++i)
        {
//.........这里部分代码省略.........
开发者ID:Donghuan,项目名称:Theano,

鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C++ PyLong_AsDouble函数代码示例发布时间:2022-05-30
下一篇:
C++ PyList_SetItem函数代码示例发布时间:2022-05-30
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap