IOS Swift 2D Array Sort - ios

Using Swift i would like to sort the below array using the country name [0][1] instead of country code. Not sure how to achieve this.
let prefixCodes = [["AD", "Andorra"], ["AE", "United Arab Emirates"], ["AF", "Afghanistan"], ["AG", "Antigua & Barbuda"], ["AI", "Anguilla"], ["AL", "Albania"], ["AM", "Armenia"], ["AO", "Angola"], ["AQ", "Antarctica"], ["AR", "Argentina"], ["AS", "American Samoa"], ["AT", "Austria"], ["AU", "Australia"], ["AW", "Aruba"], ["AX", "Åland Islands"], ["AZ", "Azerbaijan"], ["BA", "Bosnia & Herzegovina"], ["BB", "Barbados"], ["BD", "Bangladesh"], ["BE", "Belgium"], ["BF", "Burkina Faso"], ["BG", "Bulgaria"], ["BH", "Bahrain"], ["BI", "Burundi"], ["BJ", "Benin"], ["BL", "St. Barthélemy"], ["BM", "Bermuda"], ["BN", "Brunei"], ["BO", "Bolivia"], ["BQ", "Caribbean Netherlands"], ["BR", "Brazil"], ["BS", "Bahamas"], ["BT", "Bhutan"], ["BV", "Bouvet Island"], ["BW", "Botswana"], ["BY", "Belarus"], ["BZ", "Belize"], ["CA", "Canada"], ["CC", "Cocos (Keeling) Islands"], ["CD", "Congo - Kinshasa"], ["CF", "Central African Republic"], ["CG", "Congo - Brazzaville"], ["CH", "Switzerland"], ["CI", "Côte d’Ivoire"], ["CK", "Cook Islands"], ["CL", "Chile"], ["CM", "Cameroon"], ["CN", "China"], ["CO", "Colombia"], ["CR", "Costa Rica"], ["CU", "Cuba"], ["CV", "Cape Verde"], ["CW", "Curaçao"], ["CX", "Christmas Island"], ["CY", "Cyprus"], ["CZ", "Czech Republic"], ["DE", "Germany"], ["DJ", "Djibouti"], ["DK", "Denmark"], ["DM", "Dominica"], ["DO", "Dominican Republic"], ["DZ", "Algeria"], ["EC", "Ecuador"], ["EE", "Estonia"], ["EG", "Egypt"], ["EH", "Western Sahara"], ["ER", "Eritrea"], ["ES", "Spain"], ["ET", "Ethiopia"], ["FI", "Finland"], ["FJ", "Fiji"], ["FK", "Falkland Islands"], ["FM", "Micronesia"], ["FO", "Faroe Islands"], ["FR", "France"], ["GA", "Gabon"], ["GB", "United Kingdom"], ["GD", "Grenada"], ["GE", "Georgia"], ["GF", "French Guiana"], ["GG", "Guernsey"], ["GH", "Ghana"], ["GI", "Gibraltar"], ["GL", "Greenland"], ["GM", "Gambia"], ["GN", "Guinea"], ["GP", "Guadeloupe"], ["GQ", "Equatorial Guinea"], ["GR", "Greece"], ["GS", "So. Georgia & So. Sandwich Isl."], ["GT", "Guatemala"], ["GU", "Guam"], ["GW", "Guinea-Bissau"], ["GY", "Guyana"], ["HK", "Hong Kong SAR China"], ["HM", "Heard & McDonald Islands"], ["HN", "Honduras"], ["HR", "Croatia"], ["HT", "Haiti"], ["HU", "Hungary"], ["ID", "Indonesia"], ["IE", "Ireland"], ["IL", "Israel"], ["IM", "Isle of Man"], ["IN", "India"], ["IO", "British Indian Ocean Territory"], ["IQ", "Iraq"], ["IR", "Iran"], ["IS", "Iceland"], ["IT", "Italy"], ["JE", "Jersey"], ["JM", "Jamaica"], ["JO", "Jordan"], ["JP", "Japan"], ["KE", "Kenya"], ["KG", "Kyrgyzstan"], ["KH", "Cambodia"], ["KI", "Kiribati"], ["KM", "Comoros"], ["KN", "St. Kitts & Nevis"], ["KP", "North Korea"], ["KR", "South Korea"], ["KW", "Kuwait"], ["KY", "Cayman Islands"], ["KZ", "Kazakhstan"], ["LA", "Laos"], ["LB", "Lebanon"], ["LC", "St. Lucia"], ["LI", "Liechtenstein"], ["LK", "Sri Lanka"], ["LR", "Liberia"], ["LS", "Lesotho"], ["LT", "Lithuania"], ["LU", "Luxembourg"], ["LV", "Latvia"], ["LY", "Libya"], ["MA", "Morocco"], ["MC", "Monaco"], ["MD", "Moldova"], ["ME", "Montenegro"], ["MF", "St. Martin"], ["MG", "Madagascar"], ["MH", "Marshall Islands"], ["MK", "Macedonia"], ["ML", "Mali"], ["MM", "Myanmar (Burma)"], ["MN", "Mongolia"], ["MO", "Macau SAR China"], ["MP", "Northern Mariana Islands"], ["MQ", "Martinique"], ["MR", "Mauritania"], ["MS", "Montserrat"], ["MT", "Malta"], ["MU", "Mauritius"], ["MV", "Maldives"], ["MW", "Malawi"], ["MX", "Mexico"], ["MY", "Malaysia"], ["MZ", "Mozambique"], ["NA", "Namibia"], ["NC", "New Caledonia"], ["NE", "Niger"], ["NF", "Norfolk Island"], ["NG", "Nigeria"], ["NI", "Nicaragua"], ["NL", "Netherlands"], ["NO", "Norway"], ["NP", "Nepal"], ["NR", "Nauru"], ["NU", "Niue"], ["NZ", "New Zealand"], ["OM", "Oman"], ["PA", "Panama"], ["PE", "Peru"], ["PF", "French Polynesia"], ["PG", "Papua New Guinea"], ["PH", "Philippines"], ["PK", "Pakistan"], ["PL", "Poland"], ["PM", "St. Pierre & Miquelon"], ["PN", "Pitcairn Islands"], ["PR", "Puerto Rico"], ["PS", "Palestinian Territories"], ["PT", "Portugal"], ["PW", "Palau"], ["PY", "Paraguay"], ["QA", "Qatar"], ["RE", "Réunion"], ["RO", "Romania"], ["RS", "Serbia"], ["RU", "Russia"], ["RW", "Rwanda"], ["SA", "Saudi Arabia"], ["SB", "Solomon Islands"], ["SC", "Seychelles"], ["SD", "Sudan"], ["SE", "Sweden"], ["SG", "Singapore"], ["SH", "St. Helena"], ["SI", "Slovenia"], ["SJ", "Svalbard & Jan Mayen"], ["SK", "Slovakia"], ["SL", "Sierra Leone"], ["SM", "San Marino"], ["SN", "Senegal"], ["SO", "Somalia"], ["SR", "Suriname"], ["SS", "South Sudan"], ["ST", "São Tomé & Príncipe"], ["SV", "El Salvador"], ["SX", "Sint Maarten"], ["SY", "Syria"], ["SZ", "Swaziland"], ["TC", "Turks & Caicos Islands"], ["TD", "Chad"], ["TF", "French Southern Territories"], ["TG", "Togo"], ["TH", "Thailand"], ["TJ", "Tajikistan"], ["TK", "Tokelau"], ["TL", "Timor-Leste"], ["TM", "Turkmenistan"], ["TN", "Tunisia"], ["TO", "Tonga"], ["TR", "Turkey"], ["TT", "Trinidad & Tobago"], ["TV", "Tuvalu"], ["TW", "Taiwan"], ["TZ", "Tanzania"], ["UA", "Ukraine"], ["UG", "Uganda"], ["UM", "U.S. Outlying Islands"], ["US", "United States"], ["UY", "Uruguay"], ["UZ", "Uzbekistan"], ["VA", "Vatican City"], ["VC", "St. Vincent & Grenadines"], ["VE", "Venezuela"], ["VG", "British Virgin Islands"], ["VI", "U.S. Virgin Islands"], ["VN", "Vietnam"], ["VU", "Vanuatu"], ["WF", "Wallis & Futuna"], ["WS", "Samoa"], ["YE", "Yemen"], ["YT", "Mayotte"], ["ZA", "South Africa"], ["ZM", "Zambia"], ["ZW", "Zimbabwe"]]
Thank you in advance.

With sort and the shorthand arguments you can order the second element in your 2D array like this:
let sortedAfterCountryNames = prefixCodes.sort{ $0[1] < $1[1] }
print(sortedAfterCountryNames)
// [["AF", "Afghanistan"], ["AL", "Albania"], ["DZ", "Algeria"], ["AS", "American Samoa"], ...

Hope this will help you.
let sortedArray = prefixCodes.sort { (first, second) -> Bool in
return first.last < second.last
}

You should use the sort method to sort your array.
Let's first create an unsorted array:
var arr = [["A", "Hello world"],
["C", "Bye world"],
["B", "idk what to say here"]]
Now let's look at what arguments the sort method needs. Apparently it needs a closure of the following signature:
([String], [String]) -> Bool
The most straightforward (but not so swifty) approach would be to write a function with that signature:
func myFunction (first: [String], second: [String]) -> Bool {
}
In that function, you need to decide whether the algorithm should swap the two arguments. If it should not, return true, otherwise false. I think if you want to sort in alphabetical order, you should just compare the two strings
return first[1] < second[1]
You access the element at index 1 because that is where you store the country names, right?
Then, call sort with the function
arr = arr.sort(myFunction)
However, that is not very swifty. To make this the most swifty, you can do this:
arr.sort {
$0[1] < $1[1]
}
Much better!

You may do the following:
prefixCodes.sort { $0[1] < $1[1] }
But to be safer, I think that you should define a Country struct like this:
struct Country {
let code: String
let name: String
init(_ code: String, _ name: String) {
self.code = code
self.name = name
}
}
let countries = [Country("AD", "Andorra"), Country("AE", "United Arab Emirates"), Country("BQ", "Caribbean Netherlands")]
print(countries.sort { $0.name < $1.name })
So that if you want to add more details to your countries, you will not have a chance to break your sort closure.
Or if you want to keep things simple but still enforce strong typing, you could use tuples:
let countries = [("AD", "Andorra"), ("AE", "United Arab Emirates"), ("BQ", "Caribbean Netherlands")]
print(countries.sort { $0.1 < $1.1 })
If you mix different tuple lengths in your array:
let countries = [("AD", "Andorra"), ("toto"), ("tata", "titi", "tutu")]
Swift will return this error:
error: type of expression is ambiguous without more context

Related

How to get the value from a List using Rest Assured?

I am trying to grab the first value of courseNumber for studenId=123 using Rest Assured.
When I using
.body("students.courseList.courseNumber[0]",equalTo(1000000000))
I am getting:
Expected: <1000000000>
Actual: [1000000000, 1000000001, 1000000002, 1000000003, ...........]
There are more than 10 courseList for studentId 123.
Also is it possible to use regex to grab a particular element from JSON Response or how do I get the path of an element when I have a few thousand lines of JSON Response.
Sample Response -
{
"students": [
{
"studentId": "ABC",
"studentName": "Abcd Abcd",
"courseDescription": "AAJSHKJASSJAK LASNLKASA KJk;;K K;;KK;K;KL;K;",
"creditRemaining": 100,
"classStartDate": "20191220"
},
{
"studentId": "123",
"studentName": "DEFG, VBNH",
"courseDescription": "AAJSHKJASSJAK LASNLKASA KJk;;K K;;KK;K;KL;K;",
"classSchedule": 2,
"classStartDate": "20191220",
"slotsRemaining": 10,
"courseList": [
{
"courseNumber": 1000000000,
"courseName": "Chemistry",
"courseInstructor": "HGJ IOUIOU"
"courseCity": "New York",
"courseLevel": 100,
"description": "GJKJLKJLafgdhgf ljkllklk klyiyy mnbbnkljlkj
yttiuyuyuyoyo
jhlkjkljkl"},
{
"courseNumber": 1000000001,
"courseName": "History",
"courseInstructor": "HGJ IOUIOU"
"courseCity": "New York",
"courseLevel": 100,
"description": "GJKJLKJLafgdhgf ljkllklk klyiyy mnbbnkljlkj yttiuyuyuyoyo
jhlkjkljkl"},
]
}
students.courseList.courseNumber[0][0] --> will give 1000000000
students.courseList.courseNumber[0][1] --> will give 1000000001

i want to fetch product_description but it contain html so i m getting confuse that how to get proper format from it

JSON:
{ "wishlist": [ { "wishlist": 0 } ], "cart": [ { "cart": 1 } ], "product": [ { "promo_id": 0, "avals": 0, "dis": null, "mp_product_id": 252, "mp_category_id": 113, "product_name": "Pink Soft Net Fabric Kids Angel Lehenga Choli", "product_description": "
This Pink Coloured Traditional Soft Net Fabric Lehenga Choli gives a beautifull look to your child. This Outfit come with Brocket Fabric Lehenga and Top has Soft Net Fabric with Silk Lining come along with Soft Net Dupatta .\r\n\r\n
You can make your kids wear this outfit for parties and functions.\r\n\r\n
Type :\r\n\r\n
*Semi-Stitched*\r\n\r\n
FABRIC :\r\n\r\n
Top : Unstitched Designer Brocade fabric
\r\nBottom : stitched Soft Net fabric
\r\nDupatta : Soft Net fabric
\r\nInner : Silk fabric\r\n\r\n
Size Chart :\r\n\r\n
1 to 5 year : 30 inches
\r\n6 to 8 year : 32 inches
\r\n9 to 10 year : 34 inches
\r\n10 to 15 year: 36 inches\r\n\r\n
Care
\r\nDry Clean\r\n", "sku_number": "Angel_3_Pink", "qty": 25, "likes_count": 0, "list_price": 2082, "selling_price": 1249, "discount": 41 } ], "image": [ { "image_name": "Sweet Angel Vol3-Pink.jpg" } ], "variant": [ { "Color": "PINK", "Size": "S,M,L,XL", "Occasion": "Party" } ], "related": [ { "mp_product_id": 231, "mp_category_id": 113, "product_name": "White Peacock Kids Indo Western ", "product_description": "
This White Coloured Traditional Banglory Top Fabrics Indo Western gives a beautifull look to your child. This Outfit come with Paper Silk Fabric Lehenga and Top has Banglory Fabric.\r\n\r\n
You can make your kids wear this outfit for parties and functions.\r\n\r\n
Type :\r\n\r\n
*Stitched*\r\n\r\n
FABRIC :\r\n\r\n
Top - Banglory (foam seat work),\r\n\r\n
Lehenga - Paper silk,\r\n\r\n
Size Chart :\r\n\r\n
6 to 12 year : 34 inches\r\n\r\n
Care
\r\nDry Clean\r\n", "product_image": "", "seller_product_code": "White_Peacock", "system_product_code": 0, "sku_number": "White_Peacock", "status": "A", "is_features": 0, "list_price": 2271, "selling_price": 1249, "qty": 25, "weight": "700", "cod_charge": "0", "shipping_charge": "0", "likes_count": 0, "create_date": "2017-06-26 12:38:51", "modify_date": "2017-06-26 12:39:37", "main_order": 14, "set_order": 0, "image_name": "Peacock White Kids \u00a0--- CKL 216 --- Rs. 625.jpg" }
Yes you are doing the same thing, but your code is prone to crashes as you are forcefully trying to unwrap optionals. Try this instead
Alamofire.request(APIProductDetail, method: .get, parameters: params, encoding: URLEncoding.default, headers: nil).responseJSON { (response) in
switch response.result {
case .success(let responseResultValue):
if let responseResult = responseResultValue as? [String:Any] {
if let productsList = responseResult["product"] as? [[String:Any]] {
for product in productsList {
if let productDescription = product["product_description"] as? String {
print(productDescription) //Here you will get the product description
}
}
}
}
case .failure(let error):
//handle any error here
print(error.localizedDescription)
}
}

Can I search countries by country_code in AdWords API v201603?

I want to estimate searches for a keyword, limited to a country.
A similar question was asked about 4 years ago: Can I search countries by country_code in AdWords API v201109?.
The accepted answer was: it is not currently possible.
We are now at version v201603, and I wonder if there is a change.
In my specific case I code in Java, but will appreciate the answer in any language, I'll be able to find the relevant Java counterpart.
Update:
To add to the accepted answer, here is the list of the country codes extracted from AdWords CSV file.
private static HashMap<String, Long> COUNTRIES = new HashMap<String, Long>() {
{
put("ad",2020L); //,Andorra
put("ae",2784L); //,United Arab Emirates
put("af",2004L); //,Afghanistan
put("ag",2028L); //,Antigua and Barbuda
put("al",2008L); //,Albania
put("am",2051L); //,Armenia
put("ao",2024L); //,Angola
put("aq",2010L); //,Antarctica
put("ar",2032L); //,Argentina
put("as",2016L); //,American Samoa
put("at",2040L); //,Austria
put("au",2036L); //,Australia
put("az",2031L); //,Azerbaijan
put("ba",2070L); //,Bosnia and Herzegovina
put("bb",2052L); //,Barbados
put("bd",2050L); //,Bangladesh
put("be",2056L); //,Belgium
put("bf",2854L); //,Burkina Faso
put("bg",2100L); //,Bulgaria
put("bh",2048L); //,Bahrain
put("bi",2108L); //,Burundi
put("bj",2204L); //,Benin
put("bn",2096L); //,Brunei
put("bo",2068L); //,Bolivia
put("br",2076L); //,Brazil
put("bs",2044L); //,The Bahamas
put("bt",2064L); //,Bhutan
put("bw",2072L); //,Botswana
put("by",2112L); //,Belarus
put("bz",2084L); //,Belize
put("ca",2124L); //,Canada
put("cc",2166L); //,Cocos (Keeling) Islands
put("cd",2180L); //,Democratic Republic of the Congo
put("cf",2140L); //,Central African Republic
put("cg",2178L); //,Republic of the Congo
put("ch",2756L); //,Switzerland
put("ci",2384L); //,Cote d'Ivoire
put("ck",2184L); //,Cook Islands
put("cl",2152L); //,Chile
put("cm",2120L); //,Cameroon
put("cn",2156L); //,China
put("co",2170L); //,Colombia
put("cr",2188L); //,Costa Rica
put("cv",2132L); //,Cape Verde
put("cx",2162L); //,Christmas Island
put("cy",2196L); //,Cyprus
put("cz",2203L); //,Czech Republic
put("de",2276L); //,Germany
put("dj",2262L); //,Djibouti
put("dk",2208L); //,Denmark
put("dm",2212L); //,Dominica
put("do",2214L); //,Dominican Republic
put("dz",2012L); //,Algeria
put("ec",2218L); //,Ecuador
put("ee",2233L); //,Estonia
put("eg",2818L); //,Egypt
put("er",2232L); //,Eritrea
put("es",2724L); //,Spain
put("et",2231L); //,Ethiopia
put("fi",2246L); //,Finland
put("fj",2242L); //,Fiji
put("fm",2583L); //,Federated States of Micronesia
put("fr",2250L); //,France
put("ga",2266L); //,Gabon
put("gb",2826L); //,United Kingdom
put("gd",2308L); //,Grenada
put("ge",2268L); //,Georgia
put("gh",2288L); //,Ghana
put("gm",2270L); //,The Gambia
put("gn",2324L); //,Guinea
put("gq",2226L); //,Equatorial Guinea
put("gr",2300L); //,Greece
put("gs",2239L); //,South Georgia and the South Sandwich Islands
put("gt",2320L); //,Guatemala
put("gu",2316L); //,Guam
put("gw",2624L); //,Guinea-Bissau
put("gy",2328L); //,Guyana
put("hm",2334L); //,Heard Island and McDonald Islands
put("hn",2340L); //,Honduras
put("hr",2191L); //,Croatia
put("ht",2332L); //,Haiti
put("hu",2348L); //,Hungary
put("id",2360L); //,Indonesia
put("ie",2372L); //,Ireland
put("il",2376L); //,Israel
put("in",2356L); //,India
put("iq",2368L); //,Iraq
put("is",2352L); //,Iceland
put("it",2380L); //,Italy
put("jm",2388L); //,Jamaica
put("jo",2400L); //,Jordan
put("jp",2392L); //,Japan
put("ke",2404L); //,Kenya
put("kg",2417L); //,Kyrgyzstan
put("kh",2116L); //,Cambodia
put("ki",2296L); //,Kiribati
put("km",2174L); //,Comoros
put("kn",2659L); //,Saint Kitts and Nevis
put("kr",2410L); //,South Korea
put("kw",2414L); //,Kuwait
put("kz",2398L); //,Kazakhstan
put("la",2418L); //,Laos
put("lb",2422L); //,Lebanon
put("lc",2662L); //,Saint Lucia
put("li",2438L); //,Liechtenstein
put("lk",2144L); //,Sri Lanka
put("lr",2430L); //,Liberia
put("ls",2426L); //,Lesotho
put("lt",2440L); //,Lithuania
put("lu",2442L); //,Luxembourg
put("lv",2428L); //,Latvia
put("ly",2434L); //,Libya
put("ma",2504L); //,Morocco
put("mc",2492L); //,Monaco
put("md",2498L); //,Moldova
put("me",2499L); //,Montenegro
put("mg",2450L); //,Madagascar
put("mh",2584L); //,Marshall Islands
put("mk",2807L); //,Macedonia (fyroM)
put("ml",2466L); //,Mali
put("mn",2496L); //,Mongolia
put("mp",2580L); //,Northern Mariana Islands
put("mr",2478L); //,Mauritania
put("mt",2470L); //,Malta
put("mu",2480L); //,Mauritius
put("mv",2462L); //,Maldives
put("mw",2454L); //,Malawi
put("mx",2484L); //,Mexico
put("my",2458L); //,Malaysia
put("mz",2508L); //,Mozambique
put("na",2516L); //,Namibia
put("nc",2540L); //,New Caledonia
put("ne",2562L); //,Niger
put("nf",2574L); //,Norfolk Island
put("ng",2566L); //,Nigeria
put("ni",2558L); //,Nicaragua
put("nl",2528L); //,Netherlands
put("no",2578L); //,Norway
put("np",2524L); //,Nepal
put("nr",2520L); //,Nauru
put("nu",2570L); //,Niue
put("nz",2554L); //,New Zealand
put("om",2512L); //,Oman
put("pa",2591L); //,Panama
put("pe",2604L); //,Peru
put("pf",2258L); //,French Polynesia
put("pg",2598L); //,Papua New Guinea
put("ph",2608L); //,Philippines
put("pk",2586L); //,Pakistan
put("pl",2616L); //,Poland
put("pm",2666L); //,Saint Pierre and Miquelon
put("pn",2612L); //,Pitcairn Islands
put("pt",2620L); //,Portugal
put("pw",2585L); //,Palau
put("py",2600L); //,Paraguay
put("qa",2634L); //,Qatar
put("ro",2642L); //,Romania
put("rs",2688L); //,Serbia
put("ru",2643L); //,Russia
put("rw",2646L); //,Rwanda
put("sa",2682L); //,Saudi Arabia
put("sb",2090L); //,Solomon Islands
put("sc",2690L); //,Seychelles
put("se",2752L); //,Sweden
put("sg",2702L); //,Singapore
put("sh",2654L); //,Saint Helena
put("si",2705L); //,Slovenia
put("sk",2703L); //,Slovakia
put("sl",2694L); //,Sierra Leone
put("sm",2674L); //,San Marino
put("sn",2686L); //,Senegal
put("so",2706L); //,Somalia
put("sr",2740L); //,Suriname
put("st",2678L); //,Sao Tome and Principe
put("sv",2222L); //,El Salvador
put("sz",2748L); //,Swaziland
put("td",2148L); //,Chad
put("tf",2260L); //,French Southern and Antarctic Lands
put("tg",2768L); //,Togo
put("th",2764L); //,Thailand
put("tj",2762L); //,Tajikistan
put("tk",2772L); //,Tokelau
put("tl",2626L); //,Timor-Leste
put("tm",2795L); //,Turkmenistan
put("tn",2788L); //,Tunisia
put("to",2776L); //,Tonga
put("tr",2792L); //,Turkey
put("tt",2780L); //,Trinidad and Tobago
put("tv",2798L); //,Tuvalu
put("tz",2834L); //,Tanzania
put("ua",2804L); //,Ukraine
put("ug",2800L); //,Uganda
put("um",2581L); //,United States Minor Outlying Islands
put("us",2840L); //,United States
put("uy",2858L); //,Uruguay
put("uz",2860L); //,Uzbekistan
put("va",2336L); //,Vatican City
put("vc",2670L); //,Saint Vincent and the Grenadines
put("ve",2862L); //,Venezuela
put("vn",2704L); //,Vietnam
put("vu",2548L); //,Vanuatu
put("wf",2876L); //,Wallis and Futuna
put("ws",2882L); //,Samoa
put("ye",2887L); //,Yemen
put("za",2710L); //,South Africa
put("zm",2894L); //,Zambia
put("zw",2716L); //,Zimbabwe
}
};
Yes - you can use the Targeting Idea Service to specify any location code (which includes countries, regions, cities, etc) for a Search Volume based query.
I am unfamiliar with the Java client library but I am sure it will be similar to the .NET one. The C# code below outputs the search volume for the terms 'blue fedora' and 'red fedora' for queries based in Canada.
var targettingIdeaSvc = (TargetingIdeaService)awUser.GetService(AdWordsService.v201601.TargetingIdeaService);
var searchQueries = new string[] { "blue fedora", "red fedora" };
var ideasPg = targettingIdeaSvc.get(new TargetingIdeaSelector
{
ideaType = IdeaType.KEYWORD,
requestType = RequestType.STATS,
requestedAttributeTypes = new AttributeType[]
{
AttributeType.SEARCH_VOLUME
},
searchParameters = new SearchParameter[]
{
new RelatedToQuerySearchParameter
{
queries = searchQueries,
},
new LocationSearchParameter
{
locations = new Location[]
{
new Location
{
id = 2124 // This is the location id for Canada - comprehensive list of location ids is available here https://developers.google.com/adwords/api/docs/appendix/geotargeting
}
}
},
},
paging = new Paging
{
numberResults = 5,
startIndex = 0
}
});
for (var i = 0; i < searchQueries.Length; i++)
{
var searchVolume = (ideasPg.entries[i].data.First().value as LongAttribute).value;
Console.WriteLine($#"Search Term: ""{searchQueries[i]}"" has search volume of {searchVolume} in Canada");
}
This service uses a location id. You can look up a specific id from the AdWords Geo-Location reference page (or even access this list programatically if you need to)

How to get a RESX string by passing culture, not using thread culture

I have several strings in a range of RESX files for 5 cultures/languages. I have an MVC view where different parts of the view will need to display different languages (it is an invoice print roll which contains multiple invoices, each of which will be in one of 5 languages).
Is there any way for me to get RESX strings by key with the ability to define the culture explicitly rather than relying on the thread culture?
I cannot use the thread because my single view will need to display multiple languages at different points.
I want to do something like this:
#MyRESX.String1("de-DE")
#MyRESX.String1("fr-FR")
I can code this up manually using HTML helpers and had coding the strings (I only have about 20 strings), but that feels nasty
I think I have now figured this out via a Helper method.
1) Add your RESX files and set them to have 'public' access modifier
2) Create a helper function which looks something like this where 'MyNamepsace.ResourceClass' is the full path to the class beneath your default RESX file. You can find this by looking at the *.Designer.cs file beneath your RESX
public static class Lang
{
public static string GetGlobalString(string key, string language)
{
CultureInfo ci = new CultureInfo(language);
ResourceManager rm = new ResourceManager(typeof(MyNamespace.ResourceClass)));
return rm.GetString(key, ci);
}
}
3) In my MVC view, I can now do something like this:
#Lang.GetGlobalString("String1", "de-DE")
or
#Lang.GetGlobalString("String1", "en-GB")
public static string GetImplementedCulture(string name)
{
// make sure it's not null
if (string.IsNullOrEmpty(name))
return GetDefaultCulture(); // return Default culture
// make sure it is a valid culture first
if (_validCultures.Where(c => c.Equals(name, StringComparison.InvariantCultureIgnoreCase)).Count() == 0)
return GetDefaultCulture(); // return Default culture if it is invalid
// if it is implemented, accept it
if (_cultures.Where(c => c.Equals(name, StringComparison.InvariantCultureIgnoreCase)).Count() > 0)
return name; // accept it
// Find a close match. For example, if you have "en-US" defined and the user requests "en-GB",
// the function will return closes match that is "en-US" because at least the language is the same (ie English)
var n = GetNeutralCulture(name);
foreach (var c in _cultures)
if (c.StartsWith(n))
return c;
// else
// It is not implemented
return GetDefaultCulture(); // return Default culture as no match found
}
This is a nice code i have found, Im using it in my projects all the time, you just add a List of Languages or Cultures you support like this:
private static readonly List<string> _validCultures = new List<string> { "af", "af-ZA", "sq", "sq-AL", "gsw-FR", "am-ET", "ar", "ar-DZ", "ar-BH", "ar-EG", "ar-IQ", "ar-JO", "ar-KW", "ar-LB", "ar-LY", "ar-MA", "ar-OM", "ar-QA", "ar-SA", "ar-SY", "ar-TN", "ar-AE", "ar-YE", "hy", "hy-AM", "as-IN", "az", "az-Cyrl-AZ", "az-Latn-AZ", "ba-RU", "eu", "eu-ES", "be", "be-BY", "bn-BD", "bn-IN", "bs-Cyrl-BA", "bs-Latn-BA", "br-FR", "bg", "bg-BG", "ca", "ca-ES", "zh-HK", "zh-MO", "zh-CN", "zh-Hans", "zh-SG", "zh-TW", "zh-Hant", "co-FR", "hr", "hr-HR", "hr-BA", "cs", "cs-CZ", "da", "da-DK", "prs-AF", "div", "div-MV", "nl", "nl-BE", "nl-NL", "en", "en-AU", "en-BZ", "en-CA", "en-029", "en-IN", "en-IE", "en-JM", "en-MY", "en-NZ", "en-PH", "en-SG", "en-ZA", "en-TT", "en-GB", "en-US", "en-ZW", "et", "et-EE", "fo", "fo-FO", "fil-PH", "fi", "fi-FI", "fr", "fr-BE", "fr-CA", "fr-FR", "fr-LU", "fr-MC", "fr-CH", "fy-NL", "gl", "gl-ES", "ka", "ka-GE", "de", "de-AT", "de-DE", "de-LI", "de-LU", "de-CH", "el", "el-GR", "kl-GL", "gu", "gu-IN", "ha-Latn-NG", "he", "he-IL", "hi", "hi-IN", "hu", "hu-HU", "is", "is-IS", "ig-NG", "id", "id-ID", "iu-Latn-CA", "iu-Cans-CA", "ga-IE", "xh-ZA", "zu-ZA", "it", "it-IT", "it-CH", "ja", "ja-JP", "kn", "kn-IN", "kk", "kk-KZ", "km-KH", "qut-GT", "rw-RW", "sw", "sw-KE", "kok", "kok-IN", "ko", "ko-KR", "ky", "ky-KG", "lo-LA", "lv", "lv-LV", "lt", "lt-LT", "wee-DE", "lb-LU", "mk", "mk-MK", "ms", "ms-BN", "ms-MY", "ml-IN", "mt-MT", "mi-NZ", "arn-CL", "mr", "mr-IN", "moh-CA", "mn", "mn-MN", "mn-Mong-CN", "ne-NP", "no", "nb-NO", "nn-NO", "oc-FR", "or-IN", "ps-AF", "fa", "fa-IR", "pl", "pl-PL", "pt", "pt-BR", "pt-PT", "pa", "pa-IN", "quz-BO", "quz-EC", "quz-PE", "ro", "ro-RO", "rm-CH", "ru", "ru-RU", "smn-FI", "smj-NO", "smj-SE", "se-FI", "se-NO", "se-SE", "sms-FI", "sma-NO", "sma-SE", "sa", "sa-IN", "sr", "sr-Cyrl-BA", "sr-Cyrl-SP", "sr-Latn-BA", "sr-Latn-SP", "nso-ZA", "tn-ZA", "si-LK", "sk", "sk-SK", "sl", "sl-SI", "es", "es-AR", "es-BO", "es-CL", "es-CO", "es-CR", "es-DO", "es-EC", "es-SV", "es-GT", "es-HN", "es-MX", "es-NI", "es-PA", "es-PY", "es-PE", "es-PR", "es-ES", "es-US", "es-UY", "es-VE", "sv", "sv-FI", "sv-SE", "syr", "syr-SY", "tg-Cyrl-TJ", "tzm-Latn-DZ", "ta", "ta-IN", "tt", "tt-RU", "te", "te-IN", "th", "th-TH", "bo-CN", "tr", "tr-TR", "tk-TM", "ug-CN", "uk", "uk-UA", "wen-DE", "ur", "ur-PK", "uz", "uz-Cyrl-UZ", "uz-Latn-UZ", "vi", "vi-VN", "cy-GB", "wo-SN", "sah-RU", "ii-CN", "yo-NG" };
and use this to change your culture. if you need more details just ask.

swift - how to parse this JSON object

// Get the #1 app name from iTunes and SwiftyJSON
DataManager.getTopAppsDataFromItunesWithSuccess { (iTunesData) -> Void in
let json = JSON(data: iTunesData)
println(json)
how to access all the elements of["venues"]["pub city"]["venue"] ?
{
"venues":{
"cityuser":"Beirut",
"venue-usernewplace":{
"star":[
],
"idcat":[
],
"namecat":[
],
"name":[
],
"id":[
],
"phone":[
],
"address":[
],
"crossStreet":[
],
"lat":[
],
"lng":[
],
"cc":[
]
},
"placesofpeople":{
"star":"false",
"nameplace":"B0 18",
"idplace":"4b52670df964a520847b27e3",
"count":"4",
"cc":"LB",
"phone":"01580018",
"crossStreet":"Main Highway",
"lat":"33.898404713314",
"lng":"35.534128372291",
"address":"Karantina"
},
"pubcity":{
"venue":[
{
"id":"4fe75b17e4b032d653ce50fd",
"idcat":"4bf58dd8d48988d11e941735",
"name":"Cl\u00e9 Cafe-Lounge Bar",
"phone":"71200712",
"address":"Mohammed Abdel Baki Street, Clemenceau",
"crossStreet":"Hamra, Facing Najjar Hospital",
"lat":"33.897185328966",
"lng":"35.487202808518",
"cc":"LB",
"count":"0",
"namecat":"Cocktail Bar",
"star":"false"
},
{
"id":"4e3e7533fa76455375c56a33",
"idcat":"4bf58dd8d48988d11f941735",
"name":"Skybar",
"phone":"03939191",
"address":"Biel",
"crossStreet":"Downtown Beirut",
"lat":"33.90610643966",
"lng":"35.510663636771",
"cc":"LB",
"count":"0",
"namecat":"Nightclub",
"star":"false"
},
{
"id":"4b52670df964a520847b27e3",
"idcat":"4bf58dd8d48988d11f941735",
"name":"B 018",
"phone":"01580018",
"address":"Karantina",
"crossStreet":"Main Highway",
"lat":"33.898404713314",
"lng":"35.534128372291",
"cc":"LB",
"count":"0",
"namecat":"Nightclub",
"star":"false"
},
There's two methods I know of.
1 Post that wall of text into a JSON formatter which makes that blob more readable. In which case you can then inspect which keys you can pull out from it.
2 Check the documentation.
Using swiftyJson:
if let venues = json["venues"]["pubcity"]["venue"].array {
//venue is an array of the dictionaries.
for venue in venues {
//just printing the name, but you have the whole dictioary of each venue here.
println(venue["name"].string!)
}
}

Resources