GetStream- How to sort the feed activity by descending order of likes? - getstream-io

I have 10 activity feeds, each feed as a different likes count, need to show the activity feed in descending order by likes count,
how to implement that?

Reaction counts are available for enriched activities. At the moment Stream doesn't support feed ranking based on reaction data but you can sort the activities yourself after you retrieved them from server:
List<EnrichedActivity> activities = client.flatFeed("user", "alice")
.getEnrichedActivities(new EnrichmentFlags().withReactionCounts())
.get();
activities.sort((a, b) -> {
int aLikes = a.getReactionCounts().getOrDefault("like", 0).intValue();
int bLikes = b.getReactionCounts().getOrDefault("like", 0).intValue();
return aLikes - bLikes;
});

Related

Get the number of linked documents to a collection in Arangodb

i have a collection called "channels" and it has documents linked to it in a collection called "posts".
Instead of getting the actual documents, how can i just get a number of how many they are. so i can print out
"this channel has # amount of posts"
FOR c IN channels
LET posts= (FOR p IN posts
FILTER c._key== p.channel_key
RETURN p)
RETURN merge(channels,{posts})
Based on your example, it might be as simple as to group by the channel_key and count how many posts fall into each group:
FOR p IN posts
COLLECT channel = p.channel_key WITH COUNT INTO count
RETURN { channel, count }

In Core Data, how sort an NSFetchRequest depending on the sum of an attribute of a child entity? (SwiftUI)

I am building an iOS app in SwiftUI for which I have a Core Data model with two entities:
CategoryEntity with attribute: name (String)
ExpenseEntity with attributes: name (String) and amount (Double)
There is a To-many relationship between CategoryEntity and ExpenseEntity (A category can have many expenses).
I’m fetching the categories and showing them in a list together with the sum of the expenses for each category as follows: Link to app screenshot
I would like to add a sort to the fetch request so the categories appear in order depending on the total amount of their expenses. In the example of the previous picture, the order of appearance that I would like to get would be: Tech, Clothes, Food and Transport. I don’t know how to approach this problem. Any suggestions?
In my current implementation of the request, the sorted is done alphabetically:
// My current implementation for fetching the categories
func fetchCategories() {
let request = NSFetchRequest<CategoryEntity>(entityName: "CategoryEntity")
let sort = NSSortDescriptor(keyPath: \CategoryEntity.name, ascending: true)
request.sortDescriptors = [sort]
do {
fetchedCategories = try manager.context.fetch(request)
} catch let error {
print("Error fetching. \(error.localizedDescription)")
}
}
You don't have to make another FetchRequest, you can just sort in a computed property like this:
(I assume your fetched results come into a var called fetchedCategories.)
var sortedCategories: [CategoryEntity] {
return fetchedCategories.sorted(by: { cat1, cat2 in
cat1.expensesArray.reduce(0, { $0 + $1.amount }) >
cat2.expensesArray.reduce(0, { $0 + $1.amount })
})
}
So this sorts the fetchedCategories array by a comparing rule, that looks at the sum of all cat1.expenses and compares it with the sum of cat2.expenses. The >says we want the large sums first.
You put the computed var directly in the View where you use it!
And where you used fetchedCategories before in your view (e.g. a ForEach), you now use sortedCategories.
This will update in the same way as the fetched results do.
One approach would be to include a derived attribute in your CategoryEntity model description which keeps the totals for you. For example, to sum the relevant values from the amount column within an expenses relation:
That attribute should be updated whenever you save your managed object context. You'll then be able to sort it just as you would any other attribute, without the performance cost of calculating the expense sum for each category whenever you sort.
Note that this option only really works if you don't have to do any filtering on expenses; for example, if you're looking at sorting based on expenses just in 2022, but your core data store also has seconds in 2021, the derived attribute might not give you the sort order you want.

How do I read write a content item in a separate database transaction to that of the request

I have a Purchase Order content type in my Orchard application. Among other properties it has a PurchaseOrderNumber. The purchase order number is assigned when the user saves the purchase order for the first time. I use a custom controller and views for implementing the purchase order CRUD operations.
I have a purchase order number definition part which is attached to a company content type where the next purchase order number, a prefix and padding is saved. So when the system generates the next purchase order number, the prefix (e.g. PO) is used together with the next number (e.g. 123) and the padding (e.g. 5) to generate a string - e.g. PO00123.
When the purchase order number is generated the next purchase order number stored in the purchase order definition part attached to the company content item is incremented and saved so that when a user creates another purchase order it will be assigned the next number.
My challenge here is to prevent duplicate purchase order numbers from being assigned if two users create a new purchase order at the same time.
I was thinking of creating an ISingletonDependency that uses lock (_lock) {...} to wrap code that will generate the next number. This way multiple request can ask for the next number and always get the next unique number. How do I implement this though? I can't figure out how to get access to an IContentManager that has its own database transaction.
Or is there a different pattern that I should rather use?
I figured it out after looking at the Orchard.Tasks.Locking.Services.DistributedLockService class. You need to take a dependency on ILifetimeScope and then resolve ITransactionManager and IContentManager.
lock (_lock) {
using (var childLifetimeScope = _lifetimeScope.BeginLifetimeScope()) {
var transactionManager = childLifetimeScope.Resolve<ITransactionManager>();
var contentManager = childLifetimeScope.Resolve<IContentManager>();
try {
transactionManager.RequireNew(IsolationLevel.Serializable);
var contentItem = contentManager.GetLatest(contentItemId);
var number = CompileNewNumber(contentItem);
contentManager.Publish(contentItem);
return number;
}
catch (Exception exception) {
Logger.Error(exception, "Error compiling next number.");
transactionManager.Cancel();
return "";
}
}
}

ServiceStack OrmLite - Is it possible to do a group by and have a reference to a list of the non-grouped fields?

It may be I'm still thinking in the Linq2Sql mode, but I'm having a hard time translating this to OrmLite.
I have a customers table and a loyalty card table.
I want to get a list of customers and for each customer, have a list of express cards.
My strategy is to select customers, join to loyalty cards, group by whole customer table, and then map the cards to a single property on customer as a list.
Things are not named by convention, so I don't think I can take advantage of the implicit joins.
Thanks in advance for any help.
Here is the code I have now that doesn't work:
query = query.Join<Customer, LoyaltyCard>((c, lc) => c.CustomerId == lc.CustomerId)
.GroupBy(x => x).Select((c) => new { c, Cards = ?? What goes here? });
Edit: I thought maybe this method:
var q = db.From<Customer>().Take(1);
q = q.Join<Customer, LoyaltyCard>().Select();
var customer = db.SelectMulti<Customer,LoyaltyCard>(q);
But this is giving me an ArgumentNullException on parameter "key."
It's not clear from the description or your example code what you're after, but you can fix your SelectMulti Query with:
var q = db.From<Customer>()
.Join<Customer, LoyaltyCard>();
var results = db.SelectMulti<Customer,LoyaltyCard>(q);
foreach (var tuple in results)
{
Customer customer = tuple.Item1;
LoyaltyCard custCard = tuple.Item2;
}

Select parts of a nlobjSearchResult

I have a large nlobjSearchResultSet object with over 18,000 "results".
Each result is a pricing record for a customer. There may be multiple records for a single customer.
As 18000+ records is costly in governance points to do mass changes, I'm migrating to a parent (customer) record and child records (items) so I can make changes to the item pricing as a sublist.
As part of this migration, is there a simple command to select only the nlapiSearchResult objects within the big object, which match certain criteria (ie. the customer id).
This would allow me to migrate the data with only the one search, then only subsequent create/saves of the new record format.
IN a related manner, is there a simple function call to return to number of records contained in a given netsuite record? For % progress context.
Thanks in advance.
you can actually get the number of rows by running the search with an added aggregate column. A generic way to do this for a saved search that doesn't have any aggregate columns is shown below:
var res = nlapiSearchRecord('salesorder', 'customsearch29', null,
[new nlobjSearchColumn('formulanumeric', null, 'sum').setFormula('1')]);
var rowCount = res[0].getValue('formulanumeric', null, 'sum');
console.log(rowCount);
To get the total number of records, the only way is do a saved search, an ideal way to do such search is using nlobjSearch
Below is a sample code for getting infinite search Results and number of records
var search = nlapiLoadSearch(null, SAVED_SEARCH_ID).runSearch();
var res = [],
currentRes;
var i = 0;
while(i % 1000 === 0){
currentRes = (search.getResults(i, i+1000) || []);
res = res.concat(currentRes );
i = i + currentRes.length;
}
res.length or i will give you the total number of records and res will give you all the results.

Resources