Remove common value from two different array of dictionaries - swift4.2

I have 2 array of dictionary:
serverContactsDict = [["name": “Miya”,”number": “4178547852”],
[“name": “Simon”,”number": “2458741458”],
["name": “Pio”,”number": “7414785236”]]
and
phoneContactsDict = [["name": “Miya”,”number": “4178547852”],
[“name": “Simon”,”number": “2458741458”],
["name": “Pio”,”number": “7414785236”],
["name": “Kayle”,”number": “2547859632”],
["name": “Hoya”,”number": “7485965841”]]
and
DesiredDict = [["name": “Kayle”,”number": “2547859632”],
["name": “Hoya”,”number": “7485965841”]]
Tried so much but doesn't get the desired result.

let desiredDict = phoneContactsDict.filter {
let dict = $0
return !serverContactsDict.contains{ dict == $0 }
}

Related

Mutate results with multiple variables using for loop

I have this dataframe
structure(list(plate = c("A", "A", "A", "A", "A", "B", "B", "B",
"B", "B", "C", "C", "C", "C", "C"), marker = c("IL-1", "IL-2",
"IL-3", "IL-4", "IL-5", "IL-1", "IL-2", "IL-3", "IL-4", "IL-5",
"IL-1", "IL-2", "IL-3", "IL-4", "IL-5"), sample = c(1, 2, 3,
4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15), result = c(1.94000836127381,
0.426353706529969, 2.07418521661429, 1.58200029160696, 0.812685661255674,
0.546681932009987, 0.199532997122114, 0.100208840148698, 0.720956738045624,
0.444814277410285, 2.25080298569014, 1.61429066532657, 1.1066027850052,
0.927880542016121, 4.1487948134003), LOD = c(0.810456546400942,
0.614177278086376, 0.98739611371029, 0.315142822914328, 0.221497734151459,
0.0191136249820546, 0.364139946842526, 0.983763479804491, 0.982034953153209,
0.851687364910033, 0.893324689832074, 0.978609354294382, 0.62613140416969,
0.0310439168600307, 0.729966088361143)), class = c("tbl_df",
"tbl", "data.frame"), row.names = c(NA, -15L))
As you can see I have different LOD values, for each marker in each plate. So I calculate the mean LOD for each marker using
lod <- dummy_2 |>
group_by (marker) |>
summarise(lod = mean(LOD))
which results in the following mean LOD per marker for all plates
structure(list(marker = c("IL-1", "IL-2", "IL-3", "IL-4", "IL-5"
), lod = c(0.57429828707169, 0.652308859741095, 0.865763665894824,
0.442740564309189, 0.601050395807545)), class = c("tbl_df", "tbl",
"data.frame"), row.names = c(NA, -5L))
So far so good. Now I want to check if the result of my markers are above or below my mean LOD. If it is above my mean LOD, the results must not be changed, if it is below my LOD, the result must be changed in the LOD/2.
I tried to use for loop and mutate in combination with ifelse, but that did not work. I also saw the accross function, but that also did not work. My latest try was...
marker <- unique(dummy_2$marker)
for (i in marker){
dummy_2 <- mutate(result = ifelse(i %in% dummy_2$result < dummy_2$LOD, (i %in% lod$LOD)/2), dummy_2$result)}
Is for loop the right way to go, or is there a better solution?
Any help would be appreciated..
Already found a solution by creating a new dataframe with my mean values and linked this together using left_join to my dataset. Still like to know if this could be possible with a for loop. But for now, problem solved....

Loop for with the same key value(LUA)

local config = {
['dog'] = {amount = 500},
['dog'] = {amount = 600},
['dog'] = {amount = 700},
}
for k,v in pairs(config) do
print(v)
end
Output: table:0x244b890 - (500)
How to output all values from the table? Is it possible with the same keys?
I don't think it's possible, because in Lua tables, the keys are unique. So, I am afraid you have to use another way to represent your data.
local config = {
{ 'dog', amount = 500 },
{ 'dog', amount = 600 },
{ 'dog', amount = 700 }
}
for Index = 1, #config do
print(config[Index].amount)
end
The result will be:
500
600
700

Extracting Email Domain in MyPlayground

I'm developing a chat application. Users will be required to sign up using a university email address.
My app will heavily rely on compartmentalizing users using a UnivID (University ID) which will be the '#' symbol along with the email domain. For example, if a user signs up using any of the following email addresses : jsmith#mail.havard.edu, jsmith#havard.edu, or jsmith#student.havard.edu. The UnivID = '#havard.edu'
I'm new to coding so I hope not to insult your intelligence if this is easy to implement.
Cheers
Here is an algorithm I created to parse the domain and extension from an email address. I used a hardcoded list of the most common domain suffixes to help ensure I don't return just the suffix part of the email if it has a 2 part domain suffix, like "co.uk" or "ca.gov".
You would just need to prepend "#" onto the resulting domain for your use case.
class func parseDomain(fromEmail email: String) -> String? {
let suffixList = ["com", "edu", "gov", "int", "mil", "net", "org", "xyz", "biz", "info", "ai", "io", "co", "ly", "eu", "cn", "ru", "nl", "de", "uk"]
guard let emailDomains = email.components(separatedBy: "#").last else {
return nil
}
let domainParts = emailDomains.components(separatedBy: ".")
guard domainParts.count >= 2 else {
return nil
}
var domain = domainParts[domainParts.count - 2] + "." + domainParts[domainParts.count - 1]
let secondLastComponent = domainParts[domainParts.count - 2]
if suffixList.contains(secondLastComponent) && domainParts.count >= 3 {
// we want to avoid returning things like co.uk, or com.au,
// so if the 2nd last component is a common suffix, return the last 3 parts instead.
domain = domainParts[domainParts.count - 3] + "." + domainParts[domainParts.count - 2] + "." + domainParts[domainParts.count - 1]
}
return domain
}
Latest 2020, Swift 5.2, XCode 11.4.1
Code that works for all inputs
let example = "email_id#gmail.com"
let components = example.components(separatedBy: "#")
if components.count > 1 {
let domain = components[1]
// domain has value gmail.com
}
I assume that you actually want everything after the ampersand. If that is the case then this code will work.
let example = "jsmith#student.harvard.edu"
let univId = "#" + example.componentsSeparatedByString("#")[1]
// "#student.harvard.edu"
If you really only want the last two parts of an extended domain string then this will work.
let example = "jsmith#student.harvard.edu"
let domain = example.componentsSeparatedByString("#")
let parts = domain.componentsSeparatedByString(".")
let univId = "#" + parts[parts.count - 2] + "." + parts[parts.count - 1]
// #harvard.edu

Count number of dictionarys in dictionary in swift

I have a buch of accounts stored in a string dictionary and i would like to count the number of accounts existing, so basicly a ".count" but to find the number of dictionaries created.
var dictionary: [String : [ String ]] = ["" : []]
let storeString = "StoreString"
func addUpdateArray(strings: [String], index: Int) {
let locator = storeString + index.description
dictionary[locator] = strings
}
addUpdateArray(["Account1", "Hy"], 1)
addUpdateArray(["Account2", "Hey"], 3)
and now I would like to see how many accounts are have created of the kind dictionary, is ther a way?
Something like this?
var accounts = [String:[String:String]]() // or whatever your structure is
accounts["Edmund"] = [
"amount": "23.87",
"curreny": "dollars"
]
accounts["Baldrick"] = [
"amount": "23.87",
"curreny": "dollars"
]
accounts["Percy"] = [
"amount": "87.00",
"curreny": "peso"
]
println(accounts.keys.array.count) // 3
If you have dictionary of dictionaries and you want to count the number of actual values inside, you can do it like this:
var accounts = [
"accountsGroup1" : ["account1", "account2", "account3", "account4"],
"accountsGroup2" : ["account1", "account2"],
"accountsGroup3" : ["account1", "account2", "account3", "account4"]
]
let accountsCount = accounts.values.map { $0.count }
let numberOfAllAccounts = reduce(accountsCount, 0) { $0 + $1 }
println(numberOfAllAccounts)

creating nested dictionary from flat list with python

i have a list of file in this form:
base/images/graphs/one.png
base/images/tikz/two.png
base/refs/images/three.png
base/one.txt
base/chapters/two.txt
i would like to convert them to a nested dictionary of this sort:
{ "name": "base" , "contents":
[{"name": "images" , "contents":
[{"name": "graphs", "contents":[{"name":"one.png"}] },
{"name":"tikz", "contents":[{"name":"two.png"}]}
]
},
{"name": "refs", "contents":
[{"name":"images", "contents": [{"name":"three.png"}]}]
},
{"name":"one.txt", },
{"name": "chapters", "contents":[{"name":"two.txt"}]
]
}
trouble is, my attempted solution, given some input like images/datasetone/grapha.png" ,"images/datasetone/graphb.png" each one of them will end up in a different dictionary named "datasetone" however i'd like both to be in the same parent dictionary as they are in the same directory, how do i create this nested structure without duplicating parent dictionaries when there's more than one file in a common path?
here is what i had come up with and failed:
def path_to_tree(params):
start = {}
for item in params:
parts = item.split('/')
depth = len(parts)
if depth > 1:
if "contents" in start.keys():
start["contents"].append(create_base_dir(parts[0],parts[1:]))
else:
start ["contents"] = [create_base_dir(parts[0],parts[1:]) ]
else:
if "contents" in start.keys():
start["contents"].append(create_leaf(parts[0]))
else:
start["contents"] =[ create_leaf(parts[0]) ]
return start
def create_base_dir(base, parts):
l={}
if len(parts) >=1:
l["name"] = base
l["contents"] = [ create_base_dir(parts[0],parts[1:]) ]
elif len(parts)==0:
l = create_leaf(base)
return l
def create_leaf(base):
l={}
l["name"] = base
return l
b=["base/images/graphs/one.png","base/images/graphs/oneb.png","base/images/tikz/two.png","base/refs/images/three.png","base/one.txt","base/chapters/two.txt"]
d =path_to_tree(b)
from pprint import pprint
pprint(d)
In this example you can see we end up with as many dictionaries named "base" as there are files in the list, but only one is necessary, the subdirectories should be listed in the "contents" array.
This does not assume that all paths start with the same thing, so we need a list for it:
from pprint import pprint
def addBits2Tree( bits, tree ):
if len(bits) == 1:
tree.append( {'name':bits[0]} )
else:
for t in tree:
if t['name']==bits[0]:
addBits2Tree( bits[1:], t['contents'] )
return
newTree = []
addBits2Tree( bits[1:], newTree )
t = {'name':bits[0], 'contents':newTree}
tree.append( t )
def addPath2Tree( path, tree ):
bits = path.split("/")
addBits2Tree( bits, tree )
tree = []
for p in b:
print p
addPath2Tree( p, tree )
pprint(tree)
Which produces the following for your example path list:
[{'contents': [{'contents': [{'contents': [{'name': 'one.png'},
{'name': 'oneb.png'}],
'name': 'graphs'},
{'contents': [{'name': 'two.png'}],
'name': 'tikz'}],
'name': 'images'},
{'contents': [{'contents': [{'name': 'three.png'}],
'name': 'images'}],
'name': 'refs'},
{'name': 'one.txt'},
{'contents': [{'name': 'two.txt'}], 'name': 'chapters'}],
'name': 'base'}]
Omitting the redundant name tags, you can go on with :
import json
result = {}
records = ["base/images/graphs/one.png", "base/images/tikz/two.png",
"base/refs/images/three.png", "base/one.txt", "base/chapters/two.txt"]
recordsSplit = map(lambda x: x.split("/"), records)
for record in recordsSplit:
here = result
for item in record[:-1]:
if not item in here:
here[item] = {}
here = here[item]
if "###content###" not in here:
here["###content###"] = []
here["###content###"].append(record[-1])
print json.dumps(result, indent=4)
The # characters are used for uniqueness (there could be a folder which name was content in the hierarchy). Just run it and see the result.
EDIT : Fixed a few typos, added the output.

Resources