I'm trying to sort an Dictionary that contains a lot of Dictionaries inside using Swift 2.
var dicListItems: [String: [String: AnyObject]] = [
"Micke": ["LastName": "Andrius", "Age": 41],
"Brian": ["LastName": "Zini", "Age": 35],
"Frank": ["LastName": "Kramer", "Age": 28],
"Derek": ["LastName": "Allen", "Age": 25]
]
I'd like to sort by some different ways:
1) From LastName:
[
"Derek": ["LastName": "Allen", "Age": 25],
"Micke": ["LastName": "Andrius", "Age": 41],
"Frank": ["LastName": "Kramer", "Age": 28],
"Brian": ["LastName": "Zini", "Age": 35]
]
2) From FirstName:
[
"Brian": ["LastName": "Zini", "Age": 35],
"Derek": ["LastName": "Allen", "Age": 25],
"Frank": ["LastName": "Kramer", "Age": 28],
"Micke": ["LastName": "Andrius", "Age": 41]
]
3) From Age:
[
"Derek": ["LastName": "Allen", "Age": 25],
"Brian": ["LastName": "Zini", "Age": 35],
"Frank": ["LastName": "Kramer", "Age": 28],
"Micke": ["LastName": "Andrius", "Age": 41]
]
There are some problems with your situation:
Dictionary (and Set) is unordered collection (not like Array https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/Swift_Programming_Language/CollectionTypes.html#//apple_ref/doc/uid/TP40014097-CH8-ID105).
Where is your "FirstName" in your demo data?
I suppose that you can convert your data into this kind of things (it's an Array so sortable):
var dicListItems: [[String : AnyObject]] = [
["FirstName" :"Micke", "LastName": "Andrius", "Age": 41],
["FirstName" : "Brian", "LastName": "Zini", "Age": 35],
["FirstName" : "Frank", "LastName": "Kramer", "Age": 28],
["FirstName" : "Derek", "LastName": "Allen", "Age": 25]
]
Then you can use .sort function of swift to sort your Array. For example, this is a sort by FirstName:
let dictListItems: [[String : AnyObject]] = [["FirstName" :"Micke", "LastName": "Andrius", "Age": 41], ["FirstName" : "Brian", "LastName": "Zini", "Age": 35], ["FirstName" : "Frank", "LastName": "Kramer", "Age": 28], ["FirstName" : "Derek", "LastName": "Allen", "Age": 25]]
let sortedList = dictListItems.sort {
item1, item2 in
let firstName1 = item1["FirstName"] as! String
let firstName2 = item2["FirstName"] as! String
return firstName1.compare(firstName2) != NSComparisonResult.OrderedAscending
}
The first problem, it is Objective-C, not Swift.
Second: you can't sort a Dictionary, you should use Array instead.
The solution in Swift 2 is here:
var listItems = [
["FirstName": "Micke", "LastName": "Andrius", "Age": 41],
["FirstName": "Brian", "LastName": "Zini", "Age": 35],
["FirstName": "Frank", "LastName": "Kramer", "Age": 28],
["FirstName": "Derek", "LastName": "Allen", "Age": 25]
]
listItems.sortInPlace( { ($0["FirstName"] as! String) < ($1["FirstName"] as! String)} )
print(listItems)
Obviously you can change the key in the sorting condition.
Related
I am trying to implement my first project in Laravel that will contain APIs, more specifically the Sportmonks API. What is the best way to get the data and display it in my view?
I have managed to display some of the data, but I do not know the correct way to display the data from the "standings", as well as from the tables that it has in it (overall, home, away, total)
API returns
{
"data": [{
"id": 77447501,
"name": "1st Phase",
"league_id": 501,
"season_id": 17141,
"round_id": 195000,
"round_name": 33,
"type": "Group Stage",
"stage_id": 77447501,
"stage_name": "1st Phase",
"resource": "stage",
"standings": {
"data": [{
"position": 1,
"team_id": 62,
"team_name": "Rangers",
"round_id": 195000,
"round_name": 33,
"group_id": null,
"group_name": null,
"overall": {
"games_played": 33,
"won": 28,
"draw": 5,
"lost": 0,
"goals_scored": 78,
"goals_against": 10,
"points": 89
},
"home": {
"games_played": 16,
"won": 16,
"draw": 0,
"lost": 0,
"goals_scored": 47,
"goals_against": 2,
"points": 48
},
"away": {
"games_played": 17,
"won": 12,
"draw": 5,
"lost": 0,
"goals_scored": 31,
"goals_against": 8,
"points": 41
},
"total": {
"goal_difference": "68",
"points": 89
},
"result": "Championship Round",
"points": 89,
"recent_form": "WWWWD",
"status": null
}],....
}
}]
}
Controller
public function index() {
$response = Http::get('apiurl');
$response->json();
$result = json_decode($response, true);
$matches = $result['data'];
return view('/api', compact('matches'));
}
Instead of returning json you can return object
$response = Http::get('apiurl');
$result=$response->object();
$matches=$result->data;
return view('/api', compact('matches'));
then in your view
#foreach($matches as $match)
#foeach($match->standings->data as $standing)
{{$standing->team_name??null}}
#endforeach
#endforeach
I'm beginner in Jmeter. I need to split a string in Beanshell Postprocessor. My String contains :
[{name=Rose, id=2, Job=manag, AGE=45}, {name=Mary, id=3, Job=eng, AGE=67},
{name=Terese, id=4, Job=exe, AGE=20}, {name=George, id=5, Job=eng, AGE=50},
{name=Mathew, id=6, Job=cwit, AGE=30}, {name=jiss, id=7, Job=bd, AGE=49},
{name=Rose, id=8, Job=exe, AGE=36}]
How can I split each value in beanshell like:
- [Rose,2,manag,45]
- [Mary, 3, eng, 67] etc.
First of all, I doubt you should be using Beanshell at all, since JMeter 3.1 it's recommended to go for JSR223 Test Elements and Groovy language for scripting
Are you sure that the string is exactly in that format? I'm asking because it's looks like to be a JSON and if this is the case you're getting response which looks like:
[
{
"name": "Rose",
"id": 2,
"Job": "manag",
"AGE": 45
},
{
"name": "Mary",
"id": 3,
"Job": "eng",
"AGE": 67
},
{
"name": "Terese",
"id": 4,
"Job": "exe",
"AGE": 20
},
{
"name": "George",
"id": 5,
"Job": "eng",
"AGE": 50
},
{
"name": "Mathew",
"id": 6,
"Job": "cwit",
"AGE": 30
},
{
"name": "jiss",
"id": 7,
"Job": "bd",
"AGE": 49
},
{
"name": "Rose",
"id": 8,
"Job": "exe",
"AGE": 36
}
]
You can use JSR223 PostProcessor and the following Groovy code:
new groovy.json.JsonSlurper().parse(prev.getResponseData()).each { entry ->
log.info(entry as String)
}
Demo:
More information:
Apache Groovy - Parsing and producing JSON
Apache Groovy - Why and How You Should Use It
I have the following hash:
{
"itens":
[
{"year": "2018", "data": "id": 1},
{"year": "2018", "data": "id": 2}
]
}
I need to insert another element to the array of hashes. But I can't have a duplicate entry.
So I have to insert this line:
{"year": "2019", "data": "id": 2}
But first I need to remove the previous:
{"year": "2018", "data": "id": 2}
How can I iterate over the hash, find key and value, remove and add the new entry ?
Thanks.
I assume you mean a hash like this:
hash = {
items: [
{year: 2018, data: { id: 1 }},
{year: 2018, data: { id: 2 }}
]
}
Than you can change it for example in this way:
item = {year: 2019, data: { id: 2 }}
hash[:items].delete_if do |stored_hash|
stored_hash[:data][:id] == item[:data][:id]
end
hash[:items] << item
Than it would result in this:
hash
=> {:items=>[{:year=>2018, :data=>{:id=>1}}, {:year=>2019, :data=>{:id=>2}}]}
I hope this answers your question...
Given the variables:
myhash = {
"itens":
[
{"year": "2018", "data": nil, "id": 1},
{"year": "2018", "data": nil, "id": 2}
]
}
insert = {"year": "2019", "data": "something", "id": 2}
remove = {"year": "2018", "data": nil, "id": 2}
If insert and remove have the same keys, you can do:
myhash[:'itens'].find { |h| h[:'id'] == insert[:'id'] }.merge! insert
#=> {:itens=>[{:year=>"2018", :data=>nil, :id=>1}, {:year=>"2019", :data=>"something", :id=>2}]}
I have the following keys in Redis(Spring Data Redis),
localhost>Keys *
"1+ { \"_id":"1", \"Name\" : \"C5796\" , \"Site\" : \"DRG1\"}"
"2+ { \"_id":"2", \"Name\" : \"CX1XE\" , \"Site\" : \"DG1\"}"
"3+ { \"_id":"3", \"Name\" : \"C553\" , \"Site\" : \"DG1\"}"
If I want to sort according to id/name/site, how can I do it in Spring Redis?
List<Object> keys = redistemplate.sort(SortQueryBuilder.sort("Customer").build());
and,
SortQuery<String> sort = SortQueryBuilder.sort(key).noSort().get(field).build();
List<?> keys = redistemplate.boundHashOps(key).getOperations().sort(sort);
are not working.
The code is at the last of the post, if you are familiar with the principle of multi hset keys sort in redis, skip the following content and directly read the code.
Redis Sort is aimed to sort fields inside List/Set/Zset, but this method can be used to sort multi keys base on specified metric we want. We can use "sort" to sort multi hset keys by specified field, but there is limitation about the pattern of hset keys.
For example, if the pattern of hset keys is "hash{i}"(i is an integer), under this condition we can sort it.
127.0.0.1:6379> keys hash*
1) "hash3"
2) "hash2"
3) "hash1"
Take a look at the content of hash1:
127.0.0.1:6379> hgetall hash1
1) "id"
2) "24"
3) "name"
4) "kobe"
Every hash key contains two fields : "id", "name". If we want to sort these hset keys by its id. What should we do ?
First, add a set key named "myset". "myset" is a set key which contains members {"1", "2", "3"}.
127.0.0.1:6379> smembers myset
1) "1"
2) "2"
3) "3"
Then run the following command:
127.0.0.1:6379> SORT myset BY hash*->id GET hash*->id GET hash*->name
1) "3"
2) "wade"
3) "24"
4) "kobe"
5) "30"
6) "curry"
Eureka, sort hash{1-3} by its id.
Here is the code of using Spring Redis to do the job:
public static String getRandomStr() {
return String.valueOf(new Random().nextInt(100));
}
public static void redisTemplateSort(RedisTemplate redisTemplate) {
String sortKey = "sortKey";
StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
redisTemplate.setKeySerializer(stringRedisSerializer);
redisTemplate.setValueSerializer(stringRedisSerializer);
redisTemplate.setHashKeySerializer(stringRedisSerializer);
redisTemplate.setHashValueSerializer(stringRedisSerializer);
redisTemplate.delete(sortKey);
if (!redisTemplate.hasKey(sortKey)) {
for (int i = 0; i < 10; i++) {
redisTemplate.boundSetOps(sortKey).add(String.valueOf(i));
String hashKey = "hash" + i,
strId = String.valueOf(i),
strName = getRandomStr(),
strSite = getRandomStr();
redisTemplate.boundHashOps(hashKey).put("_id", strId);
redisTemplate.boundHashOps(hashKey).put("Name", strName);
redisTemplate.boundHashOps(hashKey).put("Site", strSite);
System.out.printf("%s : {\"_id\": %s, \"Name\": %s, \"Site\", %s}\n",
hashKey, strId, strName, strSite);
}
}
SortQuery<String> sortQuery = SortQueryBuilder.sort(sortKey).by("hash*->Name")
.get("hash*->_id").get("hash*->Name").get("hash*->Site").build();
List<String> sortRslt = redisTemplate.sort(sortQuery);
for (int i = 0; i < sortRslt.size(); ) {
System.out.printf("{\"_id\": %s, \"Name\": %s, \"Site\", %s}\n", sortRslt.get(i+2), sortRslt.get(i+1), sortRslt.get(i));
i += 3;
}
}
Result of running redisTemplateSort(redisTemplate)(as sort by name in the code) :
hash0 : {"_id": 0, "Name": 59, "Site", 60}
hash1 : {"_id": 1, "Name": 37, "Site", 57}
hash2 : {"_id": 2, "Name": 6, "Site", 40}
hash3 : {"_id": 3, "Name": 91, "Site", 58}
hash4 : {"_id": 4, "Name": 39, "Site", 32}
hash5 : {"_id": 5, "Name": 27, "Site", 82}
hash6 : {"_id": 6, "Name": 43, "Site", 10}
hash7 : {"_id": 7, "Name": 17, "Site", 55}
hash8 : {"_id": 8, "Name": 14, "Site", 91}
hash9 : {"_id": 9, "Name": 39, "Site", 91}
{"_id": 40, "Name": 6, "Site", 2}
{"_id": 91, "Name": 14, "Site", 8}
{"_id": 55, "Name": 17, "Site", 7}
{"_id": 82, "Name": 27, "Site", 5}
{"_id": 57, "Name": 37, "Site", 1}
{"_id": 32, "Name": 39, "Site", 4}
{"_id": 91, "Name": 39, "Site", 9}
{"_id": 10, "Name": 43, "Site", 6}
{"_id": 60, "Name": 59, "Site", 0}
{"_id": 58, "Name": 91, "Site", 3}
I don't know about spring data redis. Let me give you a sample to achieve this in naive Redis. Let us say you have hash, which has id, name and site. and i have a list representing the keys of that hash.
My structure will be like :
lpush("Values",1);
hset("hash_1","id","1"),hset("hash_1","Name","C5796"),hset("hash_1","Site","DRG1")
for second hash
lpush("Values",2);
...
Similarly for all the values you want to set in hash. Now for sorting you do like this
SORT "Values" BY hash_*->id get hash_*->id get hash_*->name get hash_*->site
this will return you ascending sorted hashmaps result based on id. similarly you can do for names/site. For more info about sorting in redis : http://redis.io/commands/sort
I've validated the coding and everything works up until I get to the actual parsing function I am unsure as to why I am not able to get any of the values in the array of the json file. I have tried multiple methods of getting every object in the array specified string and still nothing. This is the example code I have.
[ { "Attack": 4, "Card Description": "<b>Deathrattle</b>Deal 2 damage to ALL other characters.", "Card Type": "0", "Class": "10", "Cost": 5, "Health": 4, "Name": "Abomination", "Rarity": 3 },
{ "Class": "1", "Name": "Fiery War Axe", "Cost": 2, "Card Type": 2, "Card Description": "", "Rarity": 5 }, ]
If you use:
json["array"].array
Your JSON must look like:
{
"array": [
{
"Attack": 4,
"Card Description": "DeathrattleDeal 2 damage to ALL other characters.",
"Card Type": "0",
"Class": "10",
"Cost": 5,
"Health": 4,
"Name": "Abomination",
"Rarity": 3
},
{
"Class": "1",
"Name": "Fiery War Axe",
"Cost": 2,
"Card Type": 2,
"Card Description": "",
"Rarity": 5
}
]
}
Because "array" is a key for an array.
Then you can use: (json is your JSON Array)
for obj in json["array"] {
println(obj["Name"].stringValue)
}