Remove item from list in Pybind - pybind11

I am moving CPython calls to pybind. I had the following code:
PyObject* my_list = ...;
PyList_SetSlice(my_list , i, i+1, NULL);
Which was used to remove an item. Now, switching to pybind11, I have
py::list my_list = ...;
And I would like to write something like
my_list.pop(i);
But I didn't find anything to do that. What should I do? Is the following correct:
PyList_SetSlice(my_list.ptr() , i, i+1, NULL);
Or am I leaking the object my_list[i]?

I am not sure why you don't advocate the syntax in #oooyaya's suggestion, but one way to remove an element at a specified index of the list would be to use pop() like
my_list.attr("pop")(index);

Related

Call a PostgreSQL function and get result back with no loop

I have a simple rust program that interacts with a PostgreSQL database.
The actual code is:
for row in &db_client.query("select magic_value from priv.magic_value();", &[]).unwrap()
{
magic_value = row.get("magic_value");
println!("Magic value is = {}", magic_value);
}
And.. it works. But I don't like it: I know this function will return one and only one value.
From the example I found, for example here: https://docs.rs/postgres/latest/postgres/index.html
and here: https://tms-dev-blog.com/postgresql-database-with-rust-how-to/
You always have a recordset to loop on.
Which is the clean way to call a function without looping?
query returns a Result<Vec<Row>, _>. You are already unwrapping the Vec, so you can just use it directly instead of looping. By turning the Vec into an owning iterator yourself, you can even easily obtain a Row instead of a &Row.
magic_value = db_client.query("select magic_value from priv.magic_value();", &[])
.unwrap() // -> Vec<Row>
.into_iter() // -> impl Iterator<Item=Row>
.next() // -> Option<Row>
.unwrap() // -> Row
.get("magic_value");

How to get current position of iterator in ByteString?

I have an instance of ByteString. To read data from it I should use it's iterator() method.
I read some data and then I decide than I need to create a view (separate iterator of some chunk of data).
I can't use slice() of original iterator, because that would make it unusable, because docs says that:
After calling this method, one should discard the iterator it was called on, and use only the iterator that was returned. Using the old
iterator is undefined, subject to change, and may result in changes to
the new iterator as well.
So, it seems that I need to call slice() on ByteString. But slice() has from and until parameters and I don't know from. I need something like this:
ByteString originalByteString = ...; // <-- This is my input data
ByteIterator originalIterator = originalByteString .iterator();
...
read some data from originalIterator
...
int length = 100; // < -- Size of the view
int from = originalIterator.currentPosition(); // <-- I need this
int until = from + length;
ByteString viewOfOriginalByteString = originalByteString.slice(from, until);
ByteIterator iteratorForView = viewOfOriginalByteString.iterator(); // <-- This is my goal
Update:
Tried to do this with duplicate():
ByteIterator iteratorForView = originalIterator.duplicate()._2.take(length);
ByteIterator's from field is private, and none of the methods seems to simply return it. All I can suggest is to use originalIterator.duplicate to get a safe copy, or else to "cheat" by using reflection to read the from field, assuming reflection is available in your deployment environment.

Take nth element of an Iterator

I have a scala Iterator[A]. How can I reference the nth element of it?
For instance:
val myIter: Iterator[Seq[String]] = { .... }
//get the size of the Iterator
val s = myIter.size
//get 3rd element (base 0)
val third:Seq[String] = myIter.get(2) <---- Something like this?
I maybe misreading the docs but can't find a function to do this easily. Thanks for help
If you want to live dangerously,
myIter.drop(2).next
or if you'd rather be safe
myIter.drop(2).take(1).toList.headOption
Quite simple
myIter.slice(n,n+1).toList.headOption
Drop.take will get all elements from the beginning. Slice is much more memory efficient

Gtk, check if GtkTreeView is empty

I have following code to find if row is selected, which is selected and which text is in row of GtkTreeView. Code is in key-release event handler.
char *ntext;
if (gtk_tree_selection_get_selected(treeselen, &modelen ,&iteren))
{
gtk_tree_model_get(modelen, &iteren, cEng, &ntext, -1);
... etc...
This works ok when my view is not empty. But when list is empty I get "segmentation fault".
I think that before this is needed to check if GtkTreeView is empty.
How to do that?
Actually, later I find if list is partially filled with clicking on unfilled area segfault happens too. So I need solution for that too.
From your description, it appears when you say GtkTreeView is empty you mean in model (GtkTreeModel which is implemented by GtkListStore or GtkTreeStore associated with your GtkTreeView) the data rows are added but are empty i.e. data is not set. In that case you need to check the value returned by gtk_tree_model_get (assuming cEng is valid otherwise you will get a warning message while running the program). Problem mostly is in ...etc.... Just add a NULL check to ntext before operating on it.
char *ntext;
if (gtk_tree_selection_get_selected(treeselen, &modelen ,&iteren))
{
gtk_tree_model_get(modelen, &iteren, cEng, &ntext, -1);
if( ntext == NULL )
{
printf("Data is NULL!\n");
/* Handle this case */
}
else
{
.... etc ....
}
}
This could also be the case in you button-press or release callback as well.
Hope this helps!

Sorting Topscorecollector Results in Lucene.net?

I am doing a search operation by using lucene where i was taking my results by using topscorecollector, but i found that it unable to sort my topscorecollector results. I found it quiet odd to sort that. Can we sort the TopscoreCollector results?
My code looks like this
TopScoreDocCollector collector = TopScoreDocCollector.create(100, true);
indexSearch.Search(andSearchQuery, filter, collector);
ScoreDoc[] hits = collector.TopDocs().scoreDocs;
for (int i = 0; i < hits.Length; i++)
{
int docId = hits[i].doc;
float score = hits[i].score;
Lucene.Net.Documents.Document doc = indexSearch.Doc(docId);
document.Add(doc);
}
Can anybody help me?
Also one more doubt
we can sort the search results like this
Hits hits = IndexSearch.search(searchQuery, filter, sort);
But it is showing that Hits become obselete by Lucene 3.0. so i have opted for TopscoreCollector. But now iam very much confused?
If anyother alternate method for Hits, Please pass that to me...
TopScoreDocCollector will return results sorted by score. To get results sorted on a field you will need to use a method overload that returns TopFieldDocs.
IE: IndexSearcher.Search(query, filter, nResults, sort)
If you dont want to limit the number of results use a very large value for the nResults parameter. If i remember correctly passing Int32.MAX_VALUE will make Lucene generate an exception when initializing its PriorityQueue but Int32.MAX_VALUE-1 is fine.