Flutter Filter List base on Month - list

How I can categorise list based on Month
let say I have example list like below :
Record(
id: '01',
nameFood: 'ravioli',
date : 2021/may/14,
price: 20
),
Record(
id: '02',
nameFood: 'cheese garlic',
date : 2021/june/02,
price: 30,
),
Record(
id: '03',
nameFood: 'steak',
date : 2021/march/21
price 25,
),
I want to Categorize it to like this
June(
nameFood: steak,
total price: 240,
),
and etc
the problem is I dnt know how to filter each List(month) because each month have different length of days like 30,31 and 28

If you store your dates as a DateTime, you can try using the month number. I'm going on a limb here, assuming you have a List of objects of type Record, where Record is.
class Record {
Record(
this.id,
this.price,
this.date,
this.nameFood,
);
final String id;
final double price;
final DateTime date;
final String nameFood;
}
You can loop through your list and do whatever it is you want to do with it, like so.
for (final record in _listOfRecords) {
final _monthOfRecord = record.date.month; // Gives the month number. January = 1, April = 4, etc.
// Do other stuff, based on the current monthNumber
switch (_monthOfRecord) {
case 1:
// Do something
break;
....
default:
break;
}
}

Related

Sum time based chart data

I have a chart which displays data over time (months in my case). The data for this chart is randomly generated by getting any date from now to 500 days in the past (chartDate), and a random number (sales). It generates 500 of these rows.
func dailySales2() -> [(chartDate: Date, year: String, sales: Int)] {
var temp: [(chartDate: Date, year: String, sales: Int)] = []
for _ in 1...500 {
let dateT = Calendar.current.date(byAdding: .day, value: -Int.random(in: 1...500), to: Date())!
temp.append((chartDate: dateT, year: dateT.formatted(.dateTime.year()), sales: Int.random(in: 100...500)))
}
return temp.sorted(by: { $0.chartDate < $1.chartDate })
}
Chart {
ForEach(dailySales2(), id: \.chartDate) { chartD in
BarMark(
x: .value("Day", chartD.chartDate, unit: .month),
y: .value("Sales", chartD.sales)
)
.foregroundStyle(by: .value("Year:", chartD.year))
}
}
The above takes all the rows for each month and totals them, so each bar is a sum of all the sales for each month. If I change this to a LineMark, it displays each row individually, how can I stop this and instead sum all the individual rows into one point for each month? Thanks.
I'm expecting each month column to display a single point which sums all the rows that contains data for that month.

Reuse month columns in SwiftUI Chart

I have a chart which displays data over time (months in my case). The data for this chart is randomly generated by getting any date from now to 500 days in the past (chartDate), and a random number (sales). It generates 500 of these rows.
func dailySales2() -> [(chartDate: Date, year: String, sales: Int)] {
var temp: [(chartDate: Date, year: String, sales: Int)] = []
for _ in 1...500 {
let dateT = Calendar.current.date(byAdding: .day, value: -Int.random(in: 1...500), to: Date())!
temp.append((chartDate: dateT, year: dateT.formatted(.dateTime.year()), sales: Int.random(in: 100...500)))
}
return temp.sorted(by: { $0.chartDate < $1.chartDate })
}
Chart {
ForEach(dailySales2(), id: \.chartDate) { chartD in
BarMark(
x: .value("Day", chartD.chartDate, unit: .month),
y: .value("Sales", chartD.sales)
)
.foregroundStyle(by: .value("Year:", chartD.year))
}
}
.chartXAxis {
AxisMarks(values: .stride(by: .month)) {
AxisValueLabel(format: .dateTime.month(.narrow), centered: true)
}
}
This generates A S O N D J F M A M J J A S O N D columns (August 2021 - December 2021 and then January 2022 - December 2022). How do I go about only having one set of January - December columns and putting both years into these columns (separated by series)? Thanks.
Having 12 columns, one for each month, which any year uses.

I got the from date and to date from the user. I want to return the Sold Product's price and its count in the basis of Daily sold order. how?

models.Order.objects.filter(purchasedate__range=[from_date, to_date])
today_total = 0
quant = 0
for values in daterangeorder:
today_total += values.price
quant += values.quantity
return response.Response({
"from_date": from_date,
"to_date": to_date,
"Amount Sold": str(today_total),
"Count": str(quant)
})
This is the output:
{
"from_date": "2021-11-19",
"to_date": "2021-11-23",
"Amount Sold": "27000",
"Count": "9"
}
I want like this (day by day sold products count):-
{
date: “'2021-10-20”,
count: 20,
total_price_sold: 5000.00
},
{
date: “'2021-10-21”,
count: 4,
total_price_sold: 300.00
}
Instead of solving your problem with Python code, you can let the database handle it for you using aggregation, see the docs: https://docs.djangoproject.com/en/3.2/topics/db/aggregation/#values
from django.db.models import Sum
result = models.Order.objects.values('purchasedate')
.order_by('purchasedate')
.annotate(total_price_sold=Sum('price'), count=Sum('quantity'))
return response.Response(result)

How to count category value of array of List

let's say I have a list like the example below
<Categories>myList = [
Categories(
nameCategory: 'Book',
amount: '20'
),
Categories(
nameCategory: 'Book',
amount: '40'
),
Categories(
nameCategory: 'Food',
amount: '20'
),
Categories(
nameCategory: 'Food',
amount: '15'
),
];
How I can combine the duplicate values of that list and count the value of the list based on name ??
I can combine the list and the count value of the list but that only works just in a general list like sum total
what I want to do is make a new List but only combine several parts that share the same property like the same category or same class like that
this is an example what I want to achieve
<Categories> anotherList= [
Categories(
nameCategory: 'Book',
amount: '60'
),
Categories(
nameCategory: 'Food',
amount: '35'
),
];
I would replace your List<Categories> with a Map<String, Categories>. Then you can easily look up the Categories object given its name and mutate the existing Categories object. For example, something like:
var mergedCategories = <String, Categories>{};
for (var categories in myList) {
var name = categories.nameCategory;
var amount = categories.amount;
(mergedCategories[name] ??= Categories(nameCategory: name, amount: 0))
.amount += amount;
}
You're essentially trying to get an aggregate value from a list, which is what List.fold is meant to help with.
Here's an example of how you might use it:
class Category {
final String name;
int amount;
Category({required this.name, required this.amount});
String toString() => "Category(name: $name, amount: $amount)";
}
void main() {
final categories = [
Category(
name: 'Book',
amount: 20
),
Category(
name: 'Book',
amount: 40
),
Category(
name: 'Food',
amount: 20
),
Category(
name: 'Food',
amount: 15
),
];
/**
* Here is where the aggregation is done
*/
final List<Category> aggregated = categories.fold([], (list, item) {
try {
// Check whether the category is already in the aggregate
final existingCategory = list.firstWhere((c) => c.name == item.name);
// Category is already in the list, so just add the amount of the current item.
existingCategory.amount += item.amount;
return list;
} catch (_) {
// The category has not yet been added - so add it here
list.add(item);
return list;
}
});
print(aggregated);
}
I've changed your category class a bit for simplicity, but the principle should be the same. You can read more about the fold function here: https://api.dart.dev/stable/2.13.4/dart-core/Iterable/fold.html
A pretty straightforward method is by using the groupBy function provided by the collection.dart package.
import 'package:collection/collection.dart';
groupBy<Categories, String>(list, (c) => c.nameCategory).values.map(
(list) => list.reduce(
(a, b) => new Categories(a.nameCategory, a.amount + b.amount)
)
);

RavenDB Map/Reduce with grouping by date

I have to create a query to get a statistic by post per year/month, e.g. group by date. I created an index:
public class Posts_Count : AbstractIndexCreationTask<Post, ArchiveItem>
{
public Posts_Count()
{
Map = posts => from post in posts
select new
{
Year = post.PublishedOn.Year,
Month = post.PublishedOn.Month,
Count = 1
};
Reduce = results => from result in results
group result by new {
result.Year,
result.Month
}
into agg
select new
{
Year = agg.Key.Year,
Month = agg.Key.Month,
Count = agg.Sum(x => x.Count)
};
}
}
In studio I have next map and reduce functions:
Map:
docs.Posts.Select(post => new {Year = post.PublishedOn.Year, Month = post.PublishedOn.Month, Count = 1})
Reduce:
results
.GroupBy(result => new {Year = result.Year, Month = result.Month})
.Select(agg => new {Year = agg.Key.Year, Month = agg.Key.Month, Count = agg.Sum(x => ((System.Int32)(x.Count)))})
But the problem is I alway get a null values of Year and Month properties:
{
"Year": null,
"Month": null,
"Count": "1"
}
Can anybody help me to resolve the issue with my code? Thank You!
Your code looks fine. I tested it and it works in the current unstable build 1.2.2096. There have been some discussion around this lately on the RavenDB google group, so perhaps it was broken previously. Try again with the current build and see if it works for you now.