How to get first n rows in-memory from realm - realm

I want to get only first 10 or possibly n rows in-memory as java list using copyFromRealm method. Consider like this:
RealmResults<RecentViewItem> results = realm.where(RecentViewItem.class).findAllSorted("updatedAt", Sort.DESCENDING);
// This will load all rows in-memory list
List<RecentViewItem> list = realm.copyFromRealm(results);
// But I want only first n rows without running any loop.
UPDATE:
Since RealmResult extends AbstractList -
RealmResults<RecentViewItem> results =
realm.where(RecentViewItem.class)
.findAllSorted("updatedAt", Sort.DESCENDING);
List<RecentViewItem> temp = results.subList(0, maxNoRecentViewItem); // Still list of RealmProxyObject
List<RecentViewItem> list = realm.copyFromRealm(temp); // List of RecentViewItem Object

Related

How to save result from loop and save them in a new array?

I am trying to save the results of loop in a new array, then plot them.
But now I can only save the last value comes from the loop. How can I save all the results from the loop?
for j=1,200 do begin
h = where(o eq j,ct3)
if (ct3 ne 0) then begin
mag = a1[h].imag
bcg = min(mag)
deltay = pqq[plu2[j]]
bcg1 = float(bcg)
u = where(bcg1*deltay ne 0)
bcg2 = bcg1[u]
deltay1 = deltay[u]
print,deltay1,bcg2
plot,bcg2,deltay1,psym=5
endif
endfor
To store a variable number of values each time through your loop, I would use a list and then the toArray method when you want the final array to plot.
For example, at the beginning of your code create a list to store the results in:
deltay_list = list()
Then in your loop, add elements to your list:
deltay_list->add, deltay1, /extract
The EXTRACT keyword indicates that you should add the individual elements of deltay1, not add deltay as a single element of the list. When you want to plot, then do:
deltay_array = deltay_list->toArray()
obj_destroy, deltay_list
plot, deltay_array

How to use S4 object programming in R

What's wrong with my R script? I'm trying to use a vector of user-defined objects (here a vector of "Page" objects) within another user-defined object (here a "Book" object)
setClass("Page",
slots = c(PageNo = "numeric", #scalar
Contents = "character") #vector of strings
)
setClass("Book",
slots = c(Pages = "vector", # Something wrong here? vector of pages ? "Page" or vector" or "list"
Title = "character") #vector of strings
)
setGeneric(name="AddPage", def=function(aBook, pageNo){standardGeneric("AddPage")})
setMethod(f="AddPage", signature="Book",
definition=function(aBook, pageNo)
{
page1 = new("Page")
page1#PageNo = pageNo
aBook#Pages = c(aBook#Pages, page1) # Something wrong here?
}
)
book1 = new("Book")
book1#Title = "Sample Book"
book1
book1#Pages
AddPage(book1, 1)
AddPage(book1, 2)
book1#Pages
Remember that R does not use reference semantics, so AddPage(book1, 1) creates a copy of book1, and updates that. In the method you don't return the updated object, and book1 remains unchanged.
Update the method so that it returns the modified object
setMethod(f="AddPage", signature="Book",
definition=function(aBook, pageNo)
{
page1 = new("Page")
page1#PageNo = pageNo
aBook#Pages = c(aBook#Pages, page1) # Something wrong here?
aBook
}
)
and assign the return value to the old variable
book1 = AddPage(book1, 1)
But this is a very inefficient approach -- the line aBook#Pages = c(aBook#Pages, page1) makes a copy of all existing pages (on the right-hand side, to create a longer vector; this will scale with the square of the number of Pages added to the book) and then copies the entire Book (for the assignment). In addition, creating individual objects is expensive and does not exploit R's 'vectorization'. A first step is to think of the object 'Page' as instead 'Pages', where the object models the columns rather than rows of a data frame. 'Book' then doesn't have vector of Page objects, but a single Pages object. This also implies a different approach to creating your 'book'.

QTableView.setColumnHidden() alternative

Let's suppose I have a table with 30 columns, and want to use QSqlTableModel/QTableView and show only 5 columns. Is there some other way besides 25 times calling a setColumnHidden() function?
model = QSqlTableModel(self)
model.setTable("table")
...
view = QTableView()
view.setModel(model)
...
#insane:
view.setColumnHidden(0, True)
view.setColumnHidden(4, True)
view.setColumnHidden(6, True)
view.setColumnHidden(7, True)
view.setColumnHidden(9, True)
view.setColumnHidden(10, True)
view.setColumnHidden(11, True)
...
view.setColumnHidden(29, True)
And what if DBA add some new columns that I don't want user to see. Making changes to all installed apps to add some new view.setColumnHidden(n, True) rows? Not so practical.
Maybe there is some Qt function like view.setColumnsShown([1,2,3,5,8]) I'm not aware of?
You could define your own setColumnsShown() function:
from sets import Set
def setColumnsShown(view, showcols):
allcols = Set(range(0, view.model().columnCount()))
for col in allcols.difference(showcols):
view.setColumnHidden(col, True)
To handle the case where new columns may be added, you could connect the columnsInserted() signal of QSqlTableModel to a handler function that re-calls setColumnsShown.
I think that there isn't this function, but if you want do this automatically you can write your own function or code snippet, whick will work as you want. Unfortunately I don't familiar with Qt+Python but in C++ it can be done with this code. It is a few loops, so I think that you be able to write same code with Python syntaxis. Also I wrote comments, to show how exactly this code works.
QList<int> list;//create list where we set number of columns to be shown
list<< 1<<2;//write in list numbers of columns
int c = ui->tableView->model()->columnCount();//get count of columns
for (int i = 0; i < c; ++i)
{
ui->tableView->setColumnHidden(i,true);//hide all columns
}
for (int i = 0; i < list.length(); ++i)
{
if(list.at(i) < c)
ui->tableView->setColumnHidden(list.at(i),false);//show columns which we want
}

scilab submatrix incorrectly defined

I am stuck at creating a matrix of a matrix (vector in this case)
What I have so far
index = zeros(size(A)) // This is some matrix but isn't important to the question
indexIndex = 1;
for rows=1:length(R)
for columns=1:length(K)
if(A(rows,columns)==x)
V=[rows columns]; // I create a vector holding the row + column
index(indexIndex) = V(1,2) // I want to store all these vectors
indexIndex = indexIndex + 1
end
end
end
I have tried various ways of getting the information out of V (such as V(1:2)) but nothing seems to work correctly.
In other words, I'm trying to get an array of points.
Thanks in advance
I do not understand your question exactly. What is the size of A? What is x, K and R? But under some assumptions,
Using list
You could use a list
// Create some matrix A
A = zeros(8,8)
//initialize the list
index = list();
// Get the dimensions of A
rows = size(A,1);
cols = size(A,2);
x = 0;
for row=1:rows
for col=1:cols
if(A(row,col)==x)
// Create a vector holding row and col
V=[row col];
// Append it to list using $ (last index) + 1
index($+1) = V
end
end
end
Single indexed matrices
Another approach would be to make use of the fact an multi-dimensional matrix can also be indexed by a single value.
For instance create a random matrix named a:
-->a = rand(3,3)
a =
0.6212882 0.5211472 0.0881335
0.3454984 0.2870401 0.4498763
0.7064868 0.6502795 0.7227253
Access the first value:
-->a(1)
ans =
0.6212882
-->a(1,1)
ans =
0.6212882
Access the second value:
-->a(2)
ans =
0.3454984
-->a(2,1)
ans =
0.3454984
So that proves how the single indexing works. Now to apply it to your problem and knocking out a for-loop.
// Create some matrix A
A = zeros(8,8)
//initialize the array of indices
index = [];
// Get the dimensions of A
rows = size(A,1);
cols = size(A,2);
x = 0;
for i=1:length(A)
if(A(i)==x)
// Append it to list using $ (last index) + 1
index($+1) = i;
end
end
Without for-loop
If you just need the values that adhere to a certain condition you could also do something like this
values = A(A==x);
Be carefull when comparing doubles, these are not always (un)equal when you expect.

Lua Table Comparisons Within Tables

So I have a table that holds references to other tables like:
local a = newObject()
a.collection = {}
for i = 1, 100 do
local b = newObject()
a[#a + 1] = b
end
Now if I want to see if a particular object is within "a" I have to use pairs like so:
local z = a.collection[ 99 ]
for i,j in pairs( a.collection ) do
if j == z then
return true
end
end
The z object is in the 99th spot and I would have to wait for pairs to iterate all the way throughout the other 98 objects. This set up is making my program crawl. Is there a way to make some sort of key that isn't a string or a table to table comparison that is a one liner? Like:
if a.collection[{z}] then return true end
Thanks in advance!
Why are you storing the object in the value slot and not the key slot of the table?
local a = newObject()
a.collection = {}
for i = 1, 100 do
local b = newObject()
a.collection[b] = i
end
to see if a particular object is within "a"
return a.collection[b]
If you need integer indexed access to the collection, store it both ways:
local a = newObject()
a.collection = {}
for i = 1, 100 do
local b = newObject()
a.collection[i] = b
a.collection[b] = i
end
Finding:
local z = a.collection[99]
if a.collection[z] then return true end
Don't know if it's faster or not, but maybe this helps:
Filling:
local a = {}
a.collection = {}
for i = 1, 100 do
local b = {}
a.collection[b] = true -- Table / Object as index
end
Finding:
local z = a.collection[99]
if a.collection[z] then return true end
If that's not what you wanted to do you can break your whole array into smaller buckets and use a hash to keep track which object belongs to which bucket.
you might want to consider switching from using pairs() to using a regular for loop and indexing the table, pairs() seems to be slower on larger collections of tables.
for i=1, #a.collection do
if a.collection[i] == z then
return true
end
end
i compared the speed of iterating through a collection of 1 million tables using both pairs() and table indexing, and the indexing was a little bit faster every time. try it yourself using os.clock() to profile your code.
i can't really think of a faster way of your solution other than using some kind of hashing function to set unique indexes into the a.collection table. however, doing this would make getting a specific table out a non-trivial task (you wouldn't just be able to do a.collection[99], you'd have to iterate through until you found one you wanted. but then you could easily test if the table was in a.collection by doing something like a.collection[hashFunc(z)] ~= nil...)

Resources