How to sort internal and external maps? [duplicate] - dart

This question already has answers here:
Dart - How to sort Map's keys
(5 answers)
Closed 2 years ago.
I have a the following Map:
Map <String,Map<String,dynamic>> _allData = {
"jewishStudies": {'jewish': ['b2019','a2019']},
"socialScience": {'social1': ['a2017','c2014','b2020'],
'social2': ['a2012','c2015','b2011'],
'social3': ['a2010','c2008','b2005']},
"humanities": {'human': ['z2017','c2014','k2020']},
"exactSciences": {'exact': ['d2017','c2014','c2020']},
"engineering": {'eng': ['a2017']},
"lifeScience": {'life1': ['y2017','c2014','d2020'],
'life2': ['t2017','t2014','s2020'],
'life3': ['e2017','c2014','b2020']},
"interStudies": {'inter1':['a2017','c2014','b2020'],
'inter2':['a2017','c2014','b2020']},
"general": {'gen': ['g2017','w2014','b2020']},
};
I want to do:
sort the enteries of the external map : Map <String,Map>
by alphabetical order of the keys of that map (which there type is String).
sort the enteries of the internal map : Map<String,dynamic>
by alphabetical order of the keys of that map (which there type is String).
sort the items in the List of the internal map : Map
by alphabetical order.

You can use SplayTreeMap which iterates the keys in sorted order.
An example from this question(credit to Ilya Kharlamov):
import "dart:collection";
main() {
SplayTreeMap st = new SplayTreeMap<String, dynamic>();
st["yyy"]={"should be":"3rd"};
st["zzz"]={"should be":"last"};
st["aaa"]={"should be":"first"};
st["bbb"]={"should be":"2nd"};
for (String key in st.keys) {
print("$key : ${st[key]}");
}
}
//Output:
//aaa : first
//bbb : 2nd
//yyy : 3rd
//zzz : last

Related

Is there any way to reinitialize a mapping

I am trying to code a smart contract and I am using a mapping (address => bool) ; i make it true when a certain conditions meet. Now for another condition I want my mapping to reset and loose all of its data , i want it to be where it was in the beginning a empty mapping.
CODE IMAGE
Problem statement : I am setting all true for whoever voted using in my Dapp using a mapping ( address => bool ) now after voting is ended i want all my mapping values to be false , is there any efficient way to solve this
Thank you in advance..
Now for another condition I want my mapping to reset and loose all of its data , i want it to be where it was in the beginning a empty mapping.
The only way to reset mapping is to iterate through all the keys and set values to zero. This is not practical in Solidity.
Instead, you probably want to use mapping with the third layer and having data tuple of (version, key, value). Then just increment version when you want to do a full reset.
Alternatively you can do (key, version, value) and compare the version every time the key is read. This approach could be more gas efficient, as you are using the same storage lot when rewriting values.
I have found this as most feasible so far;
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.6.0 <0.9.0;
contract Map {
mapping (uint => uint)[] array;
function allocate(uint newMaps) public {
for (uint i = 0; i < newMaps; i++)
array.push();
}
function writeMap(uint map, uint key, uint value) public {
array[map][key] = value;
}
function readMap(uint map, uint key) public view returns (uint) {
return array[map][key];
}
function eraseMaps() public {
delete array;
}
}

Insert new pair at index 0 to map. ( Dart )

I'm to loop this map. So I would like to be able to insert a pair into this map. How do I do it?
Map<String, String> fruits = {'Apple': 'Golden', 'Orange': 'Orange'};
fruits.insert(0, {'Grape': 'Green'}); // doesn't work
print(fruits); //{Grape: Green, Apple: Golden, Orange: Orange}
Map entries do not have numeric indices (Unless you're working with Map<int, T> of course), and there is no Map.insert method. Instead, the way to add a pair to a map is to assign a value to a key, like so:
fruits['Grape'] = 'Green';
For some additional info, Map is unordered, meaning there is no index 0 - BUT, if you really must have an ordered set of keys and values, you can use List<MapEntry>:
List<MapEntry<String, String>> fruits = [
MapEntry('Apple', 'Golden'),
MapEntry('Orange', 'Orange')
];
fruits.insert(0, MapEntry('Grape', 'Green'));
print(fruits); // [MapEntry(Grape: Green), MapEntry(Apple: Golden), MapEntry(Orange: Orange)]
Even better though, you might consider using a Fruit class, then having a List<Fruit>:
class Fruit {
final String name;
final String color;
Fruit(this.name, this.color});
}
Then:
List<Fruit> fruits = [
Fruit('Apple', 'Golden'),
Fruit('Orange', 'Orange')
];
fruits.insert(0, Fruit('Grape', 'Green'));
print(fruits);
Since the default implementation of a Map is a LinkedHashMap, which preserves the inserting order, you should be able to use this syntax to insert an element either at the start or at the end of a map.
Map<String, String> fruits = {'Apple': 'Golden', 'Orange': 'Orange'};
fruits = {'Grape': 'Green', ...fruits};
print(fruits); //{Grape: Green, Apple: Golden, Orange: Orange}
Be aware that you are actually creating a new Map rather then inserting the element in the existing one.

Easiest way to convert a string into a HashMap

if I have some text in a String like:
"abc=123,def=456,ghi=789"
how could I create a populated HashMap<String,Int> object for it in the easiest, shortest amount of code possible in Kotlin?
I can think of no solution easier than this:
val s = "abc=123,def=456,ghi=789"
val map = s.split(",").associate {
val (left, right) = it.split("=")
left to right.toInt()
}
Or, if you need exactly a HashMap, use .associateTo(HashMap()) { ... }.
Some details:
.associate { ... } receives a function that produces pairs which are then stored into a map as keys and values respectively.
val (left, right) = it.split("=") is the usage of destructuring declarations on the list returned from it.split("="), it takes the first two items from the list.
left to right.toInt() creates a Pair<String, Int> defining a single mapping.
You can map each key/value to a Pair with the to keyword. An iterable of Pair can be mapped to a Map easily with the toMap() extension method.
val s = "abc=123,def=456,ghi=789"
val output = s.split(",")
.map { it.split("=") }
.map { it.first() to it.last().toInt() }
.toMap()

Is there a way to iterate through lua dictionary in order that it's created? [duplicate]

This question already has answers here:
How to iterate through a table in its exact order?
(4 answers)
Closed 7 years ago.
I need to iterate through Lua dictionary in the order that it's created.
For example:
t = {
['some'] = 'xxx',
['random'] = 'xxx',
['data'] = 'xxx',
['in'] = 'xxx',
['table'] = 'xxx',
}
Normal iterating with pairs gives a random sequence order:
for key, val in pairs(t) do
print(key.." : "..val)
end
random : xxx
some : xxx
data : xxx
table : xxx
in : xxx
I need:
some : xxx
random : xxx
data : xxx
in : xxx
table : xxx
EDIT: Changed the answer, the old one is below for reference
-- function definition
function addNewItem(keyTable, myTable, key, value)
table.insert(keyTable, key)
myTable[key] = value
end
To add a new pair into the table:
-- you may need to reset keyTable and myTable before using them
keyTable = { }
myTable = { }
-- to add a new item
addNewItem(keyTable, myTable, "key", "value")
Then, to iterate in the order the keys were added:
for _, k in ipairs(keyTable) do
print(k, myTable[k])
end
OLD ANSWER
Are you the one creating the table (Lua calls these tables and not dictionaries)?? If so, you could try something like the following:
-- tmp is a secondary table
function addNew(A, B, key, value)
table.insert(A, key)
B[key] = value
end
-- then, to browse the pairs
for _,key in ipairs(table) do
print(key, B[key])
done
The idea is that you use two tables. One holds the 'keys' you add (A) and the other (B) the actual values. They look like this:
Since A pairs the keys in a manner like
1 - key1
2 - key2
...
Then ipairs(A) will always return the keys in the order you added them. Then
use these keys to access the data
data = B[key1]

Neo4j and json creating multiple nodes with multiple params

I tried many things but of no use.
I have already raised a question on stackoverflow earlier but I am still facing the same issue.
Here is the link to old stackoverflow question
creating multiple nodes with properties in json in neo4j
Let me try out explaining with a small example
This is the query I want to execute
{
"params" : {
"props" : [
{
"LocalAsNumber" : 0,
"NodeDescription" : "10TiMOS-B-4.0.R2 ",
"NodeId" : "10.227.28.95",
"NodeName" : "BLR_WAO_SARF7"
}
]
},
"query" : "MATCH (n:Router) where n.NodeId = {props}.NodeId RETURN n"}
For simplicity I have added only 1 props array otherwise there are around 5000 props. Now I want to execute the query above but it fails.
I tried using (props.NodeId}, {props[NodeID]} but everything fails.
Is it possbile to access a individual property in neo4j?
My prog is in c++ and I am using jsoncpp and curl to fire my queries.
If you do {props}.nodeId in the query then the props parameter must be a map, but you pass in an array. Do
"props" : {
"LocalAsNumber" : 0,
"NodeDescription" : "10TiMOS-B-4.0.R2 ",
"NodeId" : "10.227.28.95",
"NodeName" : "BLR_WAO_SARF7"
}
You can use an array of maps for parameter either with a simple CREATE statement.
CREATE ({props})
or if you loop through the array to access the individual maps
FOREACH (prop IN {props} |
MERGE (i:Interface {nodeId:prop.nodeId})
ON CREATE SET i = prop
)
Does this query string work for you?
"MATCH (n:Router) RETURN [p IN {props} WHERE n.NodeId = p.NodeId | n];"

Resources