Dart removeWhere on second/temp variable affects origin - dart

I want to use removeWhere on the second/temp variable without affecting the origin variable.
void main() {
Map<String, dynamic> testMap = {
'first': {'value': 1},
'second': {'value': 2},
'third': {'value': 3},
};
print(testMap);
Map<String, dynamic> tempMap = testMap;
tempMap.removeWhere((k,v) => v['value'] > 1);
print(testMap);
print(tempMap);
}
The output for print will be:
{first: {value: 1}, second: {value: 2}, third: {value: 3}}
{first: {value: 1}}
{first: {value: 1}}
Why is removeWhere affecting the origin variable? When I'm calling it on tempMap
EDIT: As responded in the comment by OMi Shah, the fastest way would be:
Map<String, dynamic> tempMap = {...testMap};

You need to create a new map. In your specific case, we could just create a new map from the original where we at creation will filter out the key-value pairs you don't want.
So something like this:
void main() {
Map<String, dynamic> testMap = {
'first': {'value': 1},
'second': {'value': 2},
'third': {'value': 3},
};
print(testMap); // {first: {value: 1}, second: {value: 2}, third: {value: 3}}
Map<String, dynamic> tempMap = {
for (final entry in testMap.entries)
if (entry.value['value'] <= 1) entry.key: entry.value
};
print(testMap); // {first: {value: 1}, second: {value: 2}, third: {value: 3}}
print(tempMap); // {first: {value: 1}}
}

Use Map.from
Map<String, dynamic> testMap = {
'first': {'value': 1},
'second': {'value': 2},
'third': {'value': 3},
};
Map<String, dynamic> tempMap = Map.from(testMap);
tempMap.removeWhere((k,v) => v['value'] > 1);
print(testMap);
print(tempMap);

Related

Finding the index of an object containing a matching element

I have a List of Objects in the file list.dart:
final itemList = [
ItemData(uuid: 'one', score: '30', title: 'Title One', description: 'mock description'),
ItemData(uuid: 'two', score: '10', title: 'Title Two', description: 'mock description'),
ItemData(uuid: 'three', score: '20', title: 'Title Three', description: 'mock description'),
];
I am calling back UUID: 'one' to another widget in the file edit.dart
return GestureDetector(
onTap: (){
currentItem = item.uuid; //currentItem declared in file edit.dart
DisplayItem(); //callback function to edit.dart
},
child: Card(
My plan is to use the callback function to get the elements with the corresponding uuid. My problem is I can't figure out how to find the index of the object with the element equal to a given uuid. I've tried nesting indexOf() but get exponentially confused.
So if I understand correctly, you have a list of items and you want to find the index of the first item that fulfils a condition (in this case the condition is that the items UUID value is equal to some value)
In order to do something like that, you can use the indexWhere method:
var targetUuid = 'one';
int itemIndex = itemList.indexWhere((item) => item.uuid == targetUuid);
print(itemList[itemIndex]);
you can find the index of object as:
void main() {
final List<Map<String, dynamic>> _people = [
{"id": "c1", "name": "John Doe", "age": 40},
{"id": "c2", "name": "Kindacode.com", "age": 3},
{"id": "c3", "name": "Pipi", "age": 1},
{"id": "c4", "name": "Jane Doe", "age": 99},
];
// Find index of the person whose id = c3
final index1 = _people.indexWhere((element) => element["id"] == "c3");
if (index1 != -1) {
print("Index $index1: ${_people[index1]}");
}
// Find the last index where age > 80
final index2 = _people.lastIndexWhere((element) => element["age"] > 80);
if (index2 != -1) {
print("Index $index2: ${_people[index2]}");
}
}
Output:
Index 2: {id: c3, name: Pipi, age: 1}
Index 3: {id: c4, name: Jane Doe, age: 99}

How to find sum on basis of type and name key in ruby? (ruby array of hashes)

How to find a sum on basis of type and name key in ruby? (ruby array of hashes)
eatables = [{type: "fruit", name: "apple", count: 2},
{type: "vegetable", name: "pumpkin", count: 3},
{type: 'fruit', name: 'apple', count: 1},
{type: "vegetable", name: "pumpkin", count: 2}]
Desired Output
[{type: "fruit", name: "apple", count: 3},
{type: "vegetable", name: "pumpkin", count: 5}]
eatables.group_by { |h| h.slice(:name, :type) }
.map { |key, grouped| key.merge(count: grouped.sum{ |h| h[:count] }) }
The first operation splits the array into groups based on the name and type.
{{:name=>"apple", :type=>"fruit"}=>[{:type=>"fruit", :name=>"apple", :count=>2}, {:type=>"fruit", :name=>"apple", :count=>1}], {:name=>"pumpkin", :type=>"vegetable"}=>[{:type=>"vegetable", :name=>"pumpkin", :count=>3}, {:type=>"vegetable", :name=>"pumpkin", :count=>2}]}
We then map across that hash and return an array of hashes with the type, name, and sum which outputs:
=> [{:name=>"apple", :type=>"fruit", :count=>3}, {:name=>"pumpkin", :type=>"vegetable", :count=>5}]
eatables.inject(Hash.new(0)) { |h, item|
h[item.slice(:type, :name)] += item[:count]
h
}.map { |k, v|
{**k, count: v}
}
This type of problem can be solved with a reduce
output = eatables.reduce({}) do |hsh, current|
if hsh.has_key?(current[:type]+current[:name])
hsh[current[:type]+current[:name]][:count] += current[:count]
else
hsh[current[:type]+current[:name]] = current
end
hsh
end.values

How to calculate the tatal using .reduce on dart map

I have a map like this:
{id2: {quantity: 6, name: NEW NAME}, 1484: {quantity: 1, name: NEW NAME 404}, id: {quantity: 34, name: NEW NAME}}
here I have a key called "quantity" what i need to do is calculate the total quantity , for this example 6+1+34 = 41 , maybe using .reduce method but can't find how to implement it on a map.
I think it make more sense to use fold which you can read about here: https://api.dart.dev/stable/2.10.5/dart-core/Iterable/fold.html
void main() {
final map = {
'id2': {'quantity': 6, 'name': 'NEW NAME'},
1484: {'quantity': 1, 'name': 'NEW NAME 404'},
'id': {'quantity': 34, 'name': 'NEW NAME'}
};
final sum = map.values
.fold(0, (int sum, element) => sum + (element['quantity'] as int));
print(sum); // 41
}
But if you really want to use reduce you can do it like this:
void main() {
final map = {
'id2': {'quantity': 6, 'name': 'NEW NAME'},
1484: {'quantity': 1, 'name': 'NEW NAME 404'},
'id': {'quantity': 34, 'name': 'NEW NAME'}
};
final sum =
map.values.map((e) => e['quantity'] as int).reduce((a, b) => a + b);
print(sum); // 41
}

CALL gds.pagerank.stream problems

:param label => ('Person'); :param relationshipType =>
('HAS_EMAILED'); :param limit => ( 100); :param config =>
({concurrency: 8, direction: 'Outgoing', weightProperty: null,
defaultValue: 1, dampingFactor: 0.85, iterations: 25, writeProperty:
'pagerank'}); //then we calculate pagerank with one simple command
CALL algo.pageRank($label, $relationshipType, $config);
How turn this into a CALL gds.pagerank.stream(...)?
[I saw his on the Bruggen Blog][1]
[1]: https://blog.bruggen.com/2019/12/part-23-revisiting-hillary-clintons.html
My solutions:
:param label => ('Person'); :param relationshipType => ('HAS_EMAILED'); :param limit => ( 100); :param config => ({concurrency: 8, direction: 'Outgoing', weightProperty: null, defaultValue: 1, dampingFactor: 0.85, iterations: 25, writeProperty: 'pagerank'});
CALL gds.graph.create(
'myGraph332',
'Person', { HAS_EMAILED:{orientation:'UNDIRECTED'} })
Then
CALL gds.pageRank.stream('myGraph332')
YIELD nodeId, score
RETURN gds.util.asNode(nodeId).alias AS alias, score
ORDER BY score DESC, alias ASC

Dependent lists no ajax

I'm using select2 v4 and trying to make dependent lists with local (already loaded) choices.
var list1 = [
{id: 42, name: 'xxx'},
{id: 43, name: 'yyy'}
];
var list2 = [
{id: 1, name: 'aaa', list1: 42},
{id: 2, name: 'bbb', list1: 42},
{id: 3, name: 'ccc', list1: 43},
{id: 4, name: 'ddd', list1: 43}
]
I'd like list2 to depend on list1
I tried to use a callback on data:
$('#list1').select2({
data: list1
});
$('#list2').select2({
data: function () {
var list2_filtered = $.grep(list2, function (choice) {
return choice.list1 == $('#list1').val();
});
return list2_filtered;
}
});
but it does not seem to be called.
Why is my callback function never called ?
How can I make these local lists dependent ?
Refreshing a select2 data is a quite known issue.
So I implemented my own "data updater":
function refreshSelect($input, data) {
$input.html($('<option />')); // if a default blank is needed
for (var key in data) {
var $option = $('<option />')
.prop('value', data[key]['id'])
.text(data[key]['text'])
;
$input.append($option)
}
$input.trigger('change');
}
Here is how to use it:
<select id="my_select_input"></select>
var $input = $('#my_select_input');
var data = [
{
id: 42,
text: 'XX'
},
{
id: 43,
text: 'YY'
}
];
refreshSelect($input, data);
It works with and without select2

Resources