text:
Q: How to access API response data? I am able to access the ESHA api to return food data. An example of the response is bellow. Previously to access the response I would have nested foreach loops, however, I don't know if that is the best method to get the singluar values from the response since attempting it gave me various errors. Is there some way that I can access the data as an object? or is there a method to get the data without multiple nested foreach loops? Not really used API's much so quite unsure of the best way to go about it. Any help is really appreciated!
API Response:
Array ( [query] => subway [total] => 215 [first_page] => /foods?query=subway [next_page] => /foods?query=subway&start=25 [items] => Array ( [0] => Array ( [id] => urn:uuid:de2ed6f4-0c4e-4b57-b251-0dd7cd969491 [description] => sandwich, turkey breast, with wheat, 6" [category] => Subway [quantity] => 1 [product] => Subway [supplier] => Subway [unit] => urn:uuid:85562e85-ba37-4e4a-8400-da43170204a7 [characteristics] => Array ( [0] => Dairy Free ) [groups] => Array ( [0] => Poultry [1] => Sandwiches ) [units] => Array ( [0] => urn:uuid:85562e85-ba37-4e4a-8400-da43170204a7 [1] => urn:uuid:9eda6d41-4fbb-4a97-b046-46aee8a086de [2] => urn:uuid:e1d79375-15db-4ed7-8ead-f64dc2319091 [3] => urn:uuid:e0ad190a-d48b-443e-b637-e1cf05db2cdb [4] => urn:uuid:3e8384f0-ea47-4fde-b7e1-a12747b28a30 [5] => urn:uuid:d3be684c-ebfa-4861-924f-8840600d1e84 [6] => urn:uuid:0e5f4dd2-3353-477f-9773-0ed116c93e2e ) ) [1] => Array ( [id] => urn:uuid:b96ca582-2393-45b1-99c4-2e965137194c [description] => sandwich, oven roasted chicken, with wheat, 6" [category] => Subway [quantity] => 1 [product] => Subway [supplier] => Subway [unit] => urn:uuid:85562e85-ba37-4e4a-8400-da43170204a7 [characteristics] => Array ( [0] => Dairy Free ) [groups] => Array ( [0] => Poultry [1] => Sandwiches ) [units] => Array ( [0] => urn:uuid:85562e85-ba37-4e4a-8400-da43170204a7 [1] => urn:uuid:9eda6d41-4fbb-4a97-b046-46aee8a086de [2] => urn:uuid:e1d79375-15db-4ed7-8ead-f64dc2319091 [3] => urn:uuid:e0ad190a-d48b-443e-b637-e1cf05db2cdb [4] => urn:uuid:3e8384f0-ea47-4fde-b7e1-a12747b28a30 [5] => urn:uuid:d3be684c-ebfa-4861-924f-8840600d1e84 [6] => urn:uuid:0e5f4dd2-3353-477f-9773-0ed116c93e2e ) ) [2] => Array ( [id] => urn:uuid:07fa8ed2-16f5-4eea-88cd-dbfda56bf7f4 [description] => sandwich, Italian B.M.T., with wheat, 6" [category] => Subway [quantity] => 1 [product] => Subway [supplier] => Subway [unit] => urn:uuid:85562e85-ba37-4e4a-8400-da43170204a7 [groups] => Array ( [0] => Meat [1] => Sandwiches ) [units] => Array ( [0] => urn:uuid:85562e85-ba37-4e4a-8400-da43170204a7 [1] => urn:uuid:9eda6d41-4fbb-4a97-b046-46aee8a086de [2] => urn:uuid:e1d79375-15db-4ed7-8ead-f64dc2319091 [3] => urn:uuid:e0ad190a-d48b-443e-b637-e1cf05db2cdb [4] => urn:uuid:3e8384f0-ea47-4fde-b7e1-a12747b28a30 [5] => urn:uuid:d3be684c-ebfa-4861-924f-8840600d1e84 [6] => urn:uuid:0e5f4dd2-3353-477f-9773-0ed116c93e2e ) ) [3] => Array ( [id] => urn:uuid:04d88d69-7ccd-4367-979e-92e927839ebf [description] => cookie, chocolate chip [category] => Subway [quantity] => 1 [product] => Subway [supplier] => Subway [unit] => urn:uuid:85562e85-ba37-4e4a-8400-da43170204a7 [characteristics] => Array ( [0] => Vegetarian/Lactovo ) [groups] => Array ( [0] => Desserts [1] => Bread & Bakery ) [units] => Array ( [0] => urn:uuid:85562e85-ba37-4e4a-8400-da43170204a7 [1] => urn:uuid:9eda6d41-4fbb-4a97-b046-46aee8a086de [2] => urn:uuid:e1d79375-15db-4ed7-8ead-f64dc2319091 [3] => urn:uuid:e0ad190a-d48b-443e-b637-e1cf05db2cdb [4] => urn:uuid:3e8384f0-ea47-4fde-b7e1-a12747b28a30 [5] => urn:uuid:d3be684c-ebfa-4861-924f-8840600d1e84 [6] => urn:uuid:0e5f4dd2-3353-477f-9773-0ed116c93e2e ) ) [4] => Array ( [id] => urn:uuid:d9a79bf4-fd7b-4de0-aac5-2d54f6e90afe [description] => sandwich, Subway Club, with wheat, 6" [category] => Subway [quantity] => 1 [product] => Subway [supplier] => Subway [unit] => urn:uuid:85562e85-ba37-4e4a-8400-da43170204a7 [characteristics] => Array ( [0] => Dairy Free ) [groups] => Array ( [0] => Meat [1] => Poultry [2] => Sandwiches ) [units] => Array ( [0] => urn:uuid:85562e85-ba37-4e4a-8400-da43170204a7 [1] => urn:uuid:9eda6d41-4fbb-4a97-b046-46aee8a086de [2] => urn:uuid:e1d79375-15db-4ed7-8ead-f64dc2319091 [3] => urn:uuid:e0ad190a-d48b-443e-b637-e1cf05db2cdb [4] => urn:uuid:3e8384f0-ea47-4fde-b7e1-a12747b28a30 [5] => urn:uuid:d3be684c-ebfa-4861-924f-8840600d1e84 [6] => urn:uuid:0e5f4dd2-3353-477f-9773-0ed116c93e2e ) ) [5] => Array ( [id] => urn:uuid:1a36c15e-5005-4f0a-9835-193b19a0847a [description] => sandwich, sweet onion chicken teriyaki, with wheat, 6" [category] => Subway [quantity] => 1 [product] => Subway [supplier] => Subway [unit] => urn:uuid:85562e85-ba37-4e4a-8400-da43170204a7 [characteristics] => Array ( [0] => Dairy Free ) [groups] => Array ( [0] => Poultry [1] => Sandwiches ) [units] => Array ( [0] => urn:uuid:85562e85-ba37-4e4a-8400-da43170204a7 [1] => urn:uuid:9eda6d41-4fbb-4a97-b046-46aee8a086de [2] => urn:uuid:e1d79375-15db-4ed7-8ead-f64dc2319091 [3] => urn:uuid:e0ad190a-d48b-443e-b637-e1cf05db2cdb [4] => urn:uuid:3e8384f0-ea47-4fde-b7e1-a12747b28a30 [5] => urn:uuid:d3be684c-ebfa-4861-924f-8840600d1e84 [6] => urn:uuid:0e5f4dd2-3353-477f-9773-0ed116c93e2e ) ) [6] => Array ( [id] => urn:uuid:15f0d6c6-469c-40f8-b5b8-a7f137b89f20 [description] => sandwich, meatball marinara, with wheat, 6" [category] => Subway [quantity] => 1 [product] => Subway [supplier] => Subway [unit] => urn:uuid:85562e85-ba37-4e4a-8400-da43170204a7 [groups] => Array ( [0] => Meat [1] => Sandwiches ) [units] => Array ( [0] => urn:uuid:85562e85-ba37-4e4a-8400-da43170204a7 [1] => urn:uuid:9eda6d41-4fbb-4a97-b046-46aee8a086de [2] => urn:uuid:e1d79375-15db-4ed7-8ead-f64dc2319091 [3] => urn:uuid:e0ad190a-d48b-443e-b637-e1cf05db2cdb [4] => urn:uuid:3e8384f0-ea47-4fde-b7e1-a12747b28a30 [5] => urn:uuid:d3be684c-ebfa-4861-924f-8840600d1e84 [6] => urn:uuid:0e5f4dd2-3353-477f-9773-0ed116c93e2e ) ) [7] => Array ( [id] => urn:uuid:53cc9b56-c4c2-40d6-a87e-5b5121fa7e5a [description] => cookie, chocolate chunk [category] => Subway [quantity] => 1 [product] => Subway [supplier] => Subway [unit] => urn:uuid:85562e85-ba37-4e4a-8400-da43170204a7 [characteristics] => Array ( [0] => Vegetarian/Lactovo ) [groups] => Array ( [0] => Desserts [1] => Bread & Bakery ) [units] => Array ( [0] => urn:uuid:85562e85-ba37-4e4a-8400-da43170204a7 [1] => urn:uuid:9eda6d41-4fbb-4a97-b046-46aee8a086de [2] => urn:uuid:e1d79375-15db-4ed7-8ead-f64dc2319091 [3] => urn:uuid:e0ad190a-d48b-443e-b637-e1cf05db2cdb [4] => urn:uuid:3e8384f0-ea47-4fde-b7e1-a12747b28a30 [5] => urn:uuid:d3be684c-ebfa-4861-924f-8840600d1e84 [6] => urn:uuid:0e5f4dd2-3353-477f-9773-0ed116c93e2e ) ) [8] => Array ( [id] => urn:uuid:72c4f636-bacc-448b-8afa-6317e2ee1f16 [description] => sandwich, Veggie Delight, with wheat, 6" [category] => Subway [quantity] => 1 [product] => Subway [supplier] => Subway [unit] => urn:uuid:85562e85-ba37-4e4a-8400-da43170204a7 [characteristics] => Array ( [0] => Dairy Free [1] => Vegetarian/Lactovo ) [groups] => Array ( [0] => Vegetables [1] => Sandwiches ) [units] => Array ( [0] => urn:uuid:85562e85-ba37-4e4a-8400-da43170204a7 [1] => urn:uuid:9eda6d41-4fbb-4a97-b046-46aee8a086de [2] => urn:uuid:e1d79375-15db-4ed7-8ead-f64dc2319091 [3] => urn:uuid:e0ad190a-d48b-443e-b637-e1cf05db2cdb [4] => urn:uuid:3e8384f0-ea47-4fde-b7e1-a12747b28a30 [5] => urn:uuid:d3be684c-ebfa-4861-924f-8840600d1e84 [6] => urn:uuid:0e5f4dd2-3353-477f-9773-0ed116c93e2e ) ) [9] => Array ( [id] => urn:uuid:ef79a6be-9b59-42a3-b60e-1784b1171435 [description] => sandwich, turkey breast & black forest ham, with wheat, 6" [category] => Subway [quantity] => 1 [product] => Subway [supplier] => Subway [unit] => urn:uuid:85562e85-ba37-4e4a-8400-da43170204a7 [characteristics] => Array ( [0] => Dairy Free ) [groups] => Array ( [0] => Meat [1] => Poultry [2] => Sandwiches ) [units] => Array ( [0] => urn:uuid:85562e85-ba37-4e4a-8400-da43170204a7 [1] => urn:uuid:9eda6d41-4fbb-4a97-b046-46aee8a086de [2] => urn:uuid:e1d79375-15db-4ed7-8ead-f64dc2319091 [3] => urn:uuid:e0ad190a-d48b-443e-b637-e1cf05db2cdb [4] => urn:uuid:3e8384f0-ea47-4fde-b7e1-a12747b28a30 [5] => urn:uuid:d3be684c-ebfa-4861-924f-8840600d1e84 [6] => urn:uuid:0e5f4dd2-3353-477f-9773-0ed116c93e2e ) ) [10] => Array ( [id] => urn:uuid:2ebea6cc-942a-49b1-8a87-59083b7a50ba [description] => sandwich, steak & cheese, with wheat, 6" [category] => Subway [quantity] => 1 [product] => Subway [supplier] => Subway [unit] => urn:uuid:85562e85-ba37-4e4a-8400-da43170204a7 [groups] => Array ( [0] => Meat [1] => Dairy Products & Subs [2] => Sandwiches ) [units] => Array ( [0] => urn:uuid:85562e85-ba37-4e4a-8400-da43170204a7 [1] => urn:uuid:9eda6d41-4fbb-4a97-b046-46aee8a086de [2] => urn:uuid:e1d79375-15db-4ed7-8ead-f64dc2319091 [3] => urn:uuid:e0ad190a-d48b-443e-b637-e1cf05db2cdb [4] => urn:uuid:3e8384f0-ea47-4fde-b7e1-a12747b28a30 [5] => urn:uuid:d3be684c-ebfa-4861-924f-8840600d1e84 [6] => urn:uuid:0e5f4dd2-3353-477f-9773-0ed116c93e2e ) ) [11] => Array ( [id] => urn:uuid:c429b0b4-44ac-48a1-a6b5-5c857d6e6f49 [description] => sandwich, tuna, with wheat, 6" [category] => Subway [quantity] => 1 [product] => Subway [supplier] => Subway [unit] => urn:uuid:85562e85-ba37-4e4a-8400-da43170204a7 [characteristics] => Array ( [0] => Dairy Free ) [groups] => Array ( [0] => Fish & Seafood [1] => Sandwiches ) [units] => Array ( [0] => urn:uuid:85562e85-ba37-4e4a-8400-da43170204a7 [1] => urn:uuid:9eda6d41-4fbb-4a97-b046-46aee8a086de [2] => urn:uuid:e1d79375-15db-4ed7-8ead-f64dc2319091 [3] => urn:uuid:e0ad190a-d48b-443e-b637-e1cf05db2cdb [4] => urn:uuid:3e8384f0-ea47-4fde-b7e1-a12747b28a30 [5] => urn:uuid:d3be684c-ebfa-4861-924f-8840600d1e84 [6] => urn:uuid:0e5f4dd2-3353-477f-9773-0ed116c93e2e ) ) [12] => Array ( [id] => urn:uuid:61ed9f44-1828-4ff1-9c46-46850496ffb1 [description] => salad, oven roasted chicken breast, without dressing [category] => Subway [quantity] => 1 [product] => Subway [supplier] => Subway [unit] => urn:uuid:85562e85-ba37-4e4a-8400-da43170204a7 [characteristics] => Array ( [0] => Dairy Free [1] => Gluten Free ) [groups] => Array ( [0] => Poultry [1] => Sandwiches ) [units] => Array ( [0] => urn:uuid:85562e85-ba37-4e4a-8400-da43170204a7 [1] => urn:uuid:9eda6d41-4fbb-4a97-b046-46aee8a086de [2] => urn:uuid:e1d79375-15db-4ed7-8ead-f64dc2319091 [3] => urn:uuid:e0ad190a-d48b-443e-b637-e1cf05db2cdb [4] => urn:uuid:3e8384f0-ea47-4fde-b7e1-a12747b28a30 [5] => urn:uuid:d3be684c-ebfa-4861-924f-8840600d1e84 [6] => urn:uuid:0e5f4dd2-3353-477f-9773-0ed116c93e2e ) ) [13] => Array ( [id] => urn:uuid:baccc1a2-6e8d-42d8-b5dd-687b5359e728 [description] => bread, italian, 6" [category] => Subway [quantity] => 1 [product] => Subway [supplier] => Subway [unit] => urn:uuid:85562e85-ba37-4e4a-8400-da43170204a7 [characteristics] => Array ( [0] => Dairy Free [1] => Vegan [2] => Vegetarian/Lactovo ) [groups] => Array ( [0] => Bread & Bakery ) [units] => Array ( [0] => urn:uuid:85562e85-ba37-4e4a-8400-da43170204a7 [1] => urn:uuid:9eda6d41-4fbb-4a97-b046-46aee8a086de [2] => urn:uuid:e1d79375-15db-4ed7-8ead-f64dc2319091 [3] => urn:uuid:e0ad190a-d48b-443e-b637-e1cf05db2cdb [4] => urn:uuid:3e8384f0-ea47-4fde-b7e1-a12747b28a30 [5] => urn:uuid:d3be684c-ebfa-4861-924f-8840600d1e84 [6] => urn:uuid:0e5f4dd2-3353-477f-9773-0ed116c93e2e ) ) [14] => Array ( [id] => urn:uuid:e30e2553-2089-465a-9003-96a194582fe7 [description] => sauce, honey mustard, fat free [category] => Subway [quantity] => 1 [product] => Subway [supplier] => Subway [unit] => urn:uuid:6954ef62-e196-4824-8b70-9de685d75b72 [characteristics] => Array ( [0] => Dairy Free [1] => Gluten Free [2] => Vegetarian/Lactovo ) [groups] => Array ( [0] => Condiments & Sauces ) [units] => Array ( [0] => urn:uuid:6954ef62-e196-4824-8b70-9de685d75b72 [1] => urn:uuid:9eda6d41-4fbb-4a97-b046-46aee8a086de [2] => urn:uuid:e1d79375-15db-4ed7-8ead-f64dc2319091 [3] => urn:uuid:e0ad190a-d48b-443e-b637-e1cf05db2cdb [4] => urn:uuid:3e8384f0-ea47-4fde-b7e1-a12747b28a30 [5] => urn:uuid:d3be684c-ebfa-4861-924f-8840600d1e84 [6] => urn:uuid:0e5f4dd2-3353-477f-9773-0ed116c93e2e ) ) [15] => Array ( [id] => urn:uuid:a5696ff4-0079-41a8-b94f-a0773930f95a [description] => salad, Subway Club, Fresh Fit, without dressing [category] => Subway [quantity] => 1 [product] => Subway [supplier] => Subway [unit] => urn:uuid:85562e85-ba37-4e4a-8400-da43170204a7 [characteristics] => Array ( [0] => Dairy Free [1] => Gluten Free ) [groups] => Array ( [0] => Meat [1] => Dishes & Prepared Foods [2] => Vegetables [3] => Poultry ) [units] => Array ( [0] => urn:uuid:85562e85-ba37-4e4a-8400-da43170204a7 [1] => urn:uuid:9eda6d41-4fbb-4a97-b046-46aee8a086de [2] => urn:uuid:e1d79375-15db-4ed7-8ead-f64dc2319091 [3] => urn:uuid:e0ad190a-d48b-443e-b637-e1cf05db2cdb [4] => urn:uuid:3e8384f0-ea47-4fde-b7e1-a12747b28a30 [5] => urn:uuid:d3be684c-ebfa-4861-924f-8840600d1e84 [6] => urn:uuid:0e5f4dd2-3353-477f-9773-0ed116c93e2e ) ) [16] => Array ( [id] => urn:uuid:1cd754c0-bd45-47d6-b3d9-a5a1a9aca3b5 [description] => cookie, oatmeal raisin [category] => Subway [quantity] => 1 [product] => Subway [supplier] => Subway [unit] => urn:uuid:85562e85-ba37-4e4a-8400-da43170204a7 [characteristics] => Array ( [0] => Vegetarian/Lactovo ) [groups] => Array ( [0] => Desserts [1] => Bread & Bakery ) [units] => Array ( [0] => urn:uuid:85562e85-ba37-4e4a-8400-da43170204a7 [1] => urn:uuid:9eda6d41-4fbb-4a97-b046-46aee8a086de [2] => urn:uuid:e1d79375-15db-4ed7-8ead-f64dc2319091 [3] => urn:uuid:e0ad190a-d48b-443e-b637-e1cf05db2cdb [4] => urn:uuid:3e8384f0-ea47-4fde-b7e1-a12747b28a30 [5] => urn:uuid:d3be684c-ebfa-4861-924f-8840600d1e84 [6] => urn:uuid:0e5f4dd2-3353-477f-9773-0ed116c93e2e ) ) [17] => Array ( [id] => urn:uuid:569b6ec9-a1f6-4f8c-829c-8c05a8feaa0e [description] => salad, Veggie Delight, Fresh Fit, without dressing [category] => Subway [quantity] => 1 [product] => Subway [supplier] => Subway [unit] => urn:uuid:85562e85-ba37-4e4a-8400-da43170204a7 [characteristics] => Array ( [0] => Dairy Free [1] => Gluten Free [2] => Vegetarian/Lactovo ) [groups] => Array ( [0] => Dishes & Prepared Foods [1] => Vegetables ) [units] => Array ( [0] => urn:uuid:85562e85-ba37-4e4a-8400-da43170204a7 [1] => urn:uuid:9eda6d41-4fbb-4a97-b046-46aee8a086de [2] => urn:uuid:e1d79375-15db-4ed7-8ead-f64dc2319091 [3] => urn:uuid:e0ad190a-d48b-443e-b637-e1cf05db2cdb [4] => urn:uuid:3e8384f0-ea47-4fde-b7e1-a12747b28a30 [5] => urn:uuid:d3be684c-ebfa-4861-924f-8840600d1e84 [6] => urn:uuid:0e5f4dd2-3353-477f-9773-0ed116c93e2e ) ) [18] => Array ( [id] => urn:uuid:56766390-6e9f-4d9e-90be-05a32f874336 [description] => sandwich, roast beef, with wheat, 6" [category] => Subway [quantity] => 1 [product] => Subway [supplier] => Subway [unit] => urn:uuid:85562e85-ba37-4e4a-8400-da43170204a7 [characteristics] => Array ( [0] => Dairy Free ) [groups] => Array ( [0] => Meat [1] => Sandwiches ) [units] => Array ( [0] => urn:uuid:85562e85-ba37-4e4a-8400-da43170204a7 [1] => urn:uuid:9eda6d41-4fbb-4a97-b046-46aee8a086de [2] => urn:uuid:e1d79375-15db-4ed7-8ead-f64dc2319091 [3] => urn:uuid:e0ad190a-d48b-443e-b637-e1cf05db2cdb [4] => urn:uuid:3e8384f0-ea47-4fde-b7e1-a12747b28a30 [5] => urn:uuid:d3be684c-ebfa-4861-924f-8840600d1e84 [6] => urn:uuid:0e5f4dd2-3353-477f-9773-0ed116c93e2e ) ) [19] => Array ( [id] => urn:uuid:2b48074e-0c07-44e8-b99e-6d1b4ec58f49 [description] => cookie, sugar [category] => Subway [quantity] => 1 [product] => Subway [supplier] => Subway [unit] => urn:uuid:85562e85-ba37-4e4a-8400-da43170204a7 [characteristics] => Array ( [0] => Vegetarian/Lactovo ) [groups] => Array ( [0] => Desserts [1] => Bread & Bakery ) [units] => Array ( [0] => urn:uuid:85562e85-ba37-4e4a-8400-da43170204a7 [1] => urn:uuid:9eda6d41-4fbb-4a97-b046-46aee8a086de [2] => urn:uuid:e1d79375-15db-4ed7-8ead-f64dc2319091 [3] => urn:uuid:e0ad190a-d48b-443e-b637-e1cf05db2cdb [4] => urn:uuid:3e8384f0-ea47-4fde-b7e1-a12747b28a30 [5] => urn:uuid:d3be684c-ebfa-4861-924f-8840600d1e84 [6] => urn:uuid:0e5f4dd2-3353-477f-9773-0ed116c93e2e ) ) [20] => Array ( [id] => urn:uuid:9369e7ff-8e94-4060-a842-30fcf714dc01 [description] => sandwich, black forest ham, with wheat, 6" [category] => Subway [quantity] => 1 [product] => Subway [supplier] => Subway [unit] => urn:uuid:85562e85-ba37-4e4a-8400-da43170204a7 [characteristics] => Array ( [0] => Dairy Free ) [groups] => Array ( [0] => Meat [1] => Sandwiches ) [units] => Array ( [0] => urn:uuid:85562e85-ba37-4e4a-8400-da43170204a7 [1] => urn:uuid:9eda6d41-4fbb-4a97-b046-46aee8a086de [2] => urn:uuid:e1d79375-15db-4ed7-8ead-f64dc2319091 [3] => urn:uuid:e0ad190a-d48b-443e-b637-e1cf05db2cdb [4] => urn:uuid:3e8384f0-ea47-4fde-b7e1-a12747b28a30 [5] => urn:uuid:d3be684c-ebfa-4861-924f-8840600d1e84 [6] => urn:uuid:0e5f4dd2-3353-477f-9773-0ed116c93e2e ) ) [21] => Array ( [id] => urn:uuid:0a3a05fb-70b2-4a85-9fd3-1e6a20eb7f62 [description] => oil, olive blend [category] => Subway [quantity] => 1 [product] => Subway [supplier] => Subway [unit] => urn:uuid:6954ef62-e196-4824-8b70-9de685d75b72 [characteristics] => Array ( [0] => Dairy Free [1] => Vegan [2] => Gluten Free [3] => Vegetarian/Lactovo ) [groups] => Array ( [0] => Condiments & Sauces ) [units] => Array ( [0] => urn:uuid:6954ef62-e196-4824-8b70-9de685d75b72 [1] => urn:uuid:9eda6d41-4fbb-4a97-b046-46aee8a086de [2] => urn:uuid:e1d79375-15db-4ed7-8ead-f64dc2319091 [3] => urn:uuid:e0ad190a-d48b-443e-b637-e1cf05db2cdb [4] => urn:uuid:3e8384f0-ea47-4fde-b7e1-a12747b28a30 [5] => urn:uuid:d3be684c-ebfa-4861-924f-8840600d1e84 [6] => urn:uuid:0e5f4dd2-3353-477f-9773-0ed116c93e2e ) ) [22] => Array ( [id] => urn:uuid:a2f7ecda-f5f5-4089-af7e-6aa16d17590a [description] => cookie, white chip macadamia [category] => Subway [quantity] => 1 [product] => Subway [supplier] => Subway [unit] => urn:uuid:85562e85-ba37-4e4a-8400-da43170204a7 [characteristics] => Array ( [0] => Vegetarian/Lactovo ) [groups] => Array ( [0] => Desserts [1] => Bread & Bakery ) [units] => Array ( [0] => urn:uuid:85562e85-ba37-4e4a-8400-da43170204a7 [1] => urn:uuid:9eda6d41-4fbb-4a97-b046-46aee8a086de [2] => urn:uuid:e1d79375-15db-4ed7-8ead-f64dc2319091 [3] => urn:uuid:e0ad190a-d48b-443e-b637-e1cf05db2cdb [4] => urn:uuid:3e8384f0-ea47-4fde-b7e1-a12747b28a30 [5] => urn:uuid:d3be684c-ebfa-4861-924f-8840600d1e84 [6] => urn:uuid:0e5f4dd2-3353-477f-9773-0ed116c93e2e ) ) [23] => Array ( [id] => urn:uuid:e3431466-8e88-4584-a946-4d569e4a5df1 [description] => cookie, peanut butter [category] => Subway [quantity] => 1 [product] => Subway [supplier] => Subway [unit] => urn:uuid:85562e85-ba37-4e4a-8400-da43170204a7 [characteristics] => Array ( [0] => Vegetarian/Lactovo ) [groups] => Array ( [0] => Desserts [1] => Bread & Bakery ) [units] => Array ( [0] => urn:uuid:85562e85-ba37-4e4a-8400-da43170204a7 [1] => urn:uuid:9eda6d41-4fbb-4a97-b046-46aee8a086de [2] => urn:uuid:e1d79375-15db-4ed7-8ead-f64dc2319091 [3] => urn:uuid:e0ad190a-d48b-443e-b637-e1cf05db2cdb [4] => urn:uuid:3e8384f0-ea47-4fde-b7e1-a12747b28a30 [5] => urn:uuid:d3be684c-ebfa-4861-924f-8840600d1e84 [6] => urn:uuid:0e5f4dd2-3353-477f-9773-0ed116c93e2e ) ) [24] => Array ( [id] => urn:uuid:5e35f65d-6bb3-4081-a1e2-d7745f93fe8f [description] => salad, black forest ham, without dressing [category] => Subway [quantity] => 1 [product] => Subway [supplier] => Subway [unit] => urn:uuid:85562e85-ba37-4e4a-8400-da43170204a7 [characteristics] => Array ( [0] => Dairy Free [1] => Gluten Free ) [groups] => Array ( [0] => Meat [1] => Dishes & Prepared Foods [2] => Vegetables ) [units] => Array ( [0] => urn:uuid:85562e85-ba37-4e4a-8400-da43170204a7 [1] => urn:uuid:9eda6d41-4fbb-4a97-b046-46aee8a086de [2] => urn:uuid:e1d79375-15db-4ed7-8ead-f64dc2319091 [3] => urn:uuid:e0ad190a-d48b-443e-b637-e1cf05db2cdb [4] => urn:uuid:3e8384f0-ea47-4fde-b7e1-a12747b28a30 [5] => urn:uuid:d3be684c-ebfa-4861-924f-8840600d1e84 [6] => urn:uuid:0e5f4dd2-3353-477f-9773-0ed116c93e2e ) ) ) )

I know the output is not formatted well. I've tried to output it within <pre> tags however this did not work. If theres an easier way to view this data please let me know!
The code to return the data:
$get_data = callAPI('GET', 'https://nutrition-api.esha.com/foods?query=' . urlencode($\_POST\['prodInp'\]) . '&start=0&count=25&spell=true', false);
$response = json_decode($get_data, true);

echo "<pre>" . print_r($response) . "</pre>";

Thanks!!
I have tried using two nested foreach loops, but I couldn't seem to get it to work. I could be doing it wrong or overcomplicating it. I want to be able to access the [id] and [description] of each of the results so I can output them and have a user select which option they require.

A: you can access the items from the response like that :
$response = json_decode($get_data,true);

$items = $response["items"] ?? [] ;

foreach ($items as $item ){
    echo "id :".  $item["id"] . "<br>";
    echo "description :".  $item["description"] . "<br>";
    echo "category :".  $item["category"] . "<br>";
    echo "quantity :".  $item["quantity"] . "<br>";
    echo "product :".  $item["product"] . "<br>";
    echo "supplier :".  $item["supplier"] . "<br>";
    echo "unit :".  $item["unit"] . "<br>";
    echo "characteristics :".  implode(",",$item["characteristics"]) . "<br>";
    echo "groups :".  implode(",",$item["groups"]) . "<br>";
    echo "units :".  implode(",",$item["units"]) . "<br>";
}


text:
Q: How to identify Core Data Managed Object Model -- hash? Is there a method to get a unique hash for a Core Data Managed Object Model, so that I can see if the core data store is up-to-date with a specific model? I am building a core data sync system, and I want to make sure that the core data stores which are being synced are using the same version of the managed object model.

A: The model itself does not have a hash value, but
[managedObjectModel entities]

returns the array of entity descriptions, and each entity description has a versionHash property. You could compare these with the version hashes in the metaData dictionary of the persistent store.
But to check the compatibility of a store with a model you can also use
isConfiguration:compatibleWithStoreMetadata:

as described in "Is Migration Necessary"
in the "Core Data Model Versioning and Data Migration Programming Guide".

redpajama_set_name: RedPajamaStackExchange


text:
Q: Set Face Font in ListView in Android I am unable to set FontFace in a list view.
In buttons or textviews,  I am able to set font like
Typeface typeface=Typeface.createFromAsset(getAssets(),"fonts/Raleway-Medium.ttf");
                button.setTypeface(typeface);
How can I do it for the String appearing in ListView as well?
XML
 <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:id="@+id/linearLayout"
        android:elevation="10dp">
        <ListView
            android:id="@+id/list"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">
        </ListView>
    </LinearLayout>

Java
 ListView listView= (ListView) findViewById(R.id.list);

    // Defined Array values to show in ListView
    String[] values = new String[] { "string 1", "string 2", ..... }
    };

    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, android.R.id.text1, values);

    // Assign adapter to ListView
    listView.setAdapter(adapter);

    // ListView Item Click Listener
    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view,
                                int position, long id) {

            // ListView Clicked item index
            // ListView Clicked item value
            String  itemValue    = (String) listView.getItemAtPosition(position);
            gp.setphrase(itemValue);
            Intent i = new Intent(PhraseListView.this,record.class);
            startActivity(i);
        }});}

:(

A: You can create a customize item.xml layout with fonts in XML which has backward compatibility till API 14
and use ArrayAdapter(Context context, int resource, int textViewResourceId, T[] objects) constructor

A: My personal recommendation is don't.
Use a solution like Calligraphy to handle custom face fonts.
https://github.com/chrisjenx/Calligraphy


text:
Q: What is the order that bison matching the pattern? Description
I want to implement a syntax detector for json file with bison.

*

*I used
Array: LB RB
     | LB Values RB
     | LB Values COMMA RB error
          { puts("extra comma, recovered"); };

to recognize syntax error like ["extra comma",], but it failed. But the similar pattern for Object works. I think it may relate to the pattern order.

*However, when I use
Values: Value
      | Value COMMA Values
      | Value COMMA error
           { puts("extra comma, recovered"); }

it succeeded. I wonder why
Value COMMA error { puts("extra comma, recovered"); }

won't mismatch the text that should be Value COMMA Values?

Source code
syntax.y
%{
    #include"lex.yy.c"
    void yyerror(const char*);
%}

%token LC RC LB RB COLON COMMA
%token STRING NUMBER
%token TRUE FALSE VNULL
%%

Json:
      Value
    ;
Value:
      Object
    | Array
    | STRING
    | NUMBER
    | TRUE
    | FALSE
    | VNULL
    ;
Object:
      LC RC
    | LC Members RC
    | LC Member COMMA RC error { puts("extra comma, recovered"); }
    ;
Members:
      Member
    | Member COMMA Members
    ;
Member:
      STRING COLON Value
    ;
Array:
      LB RB
    | LB Values RB
    | LB Values RC error { puts("unmatched right bracket, recovered"); }
    ;
Values:
      Value
    | Value COMMA Values
    | Value COMMA error { puts("extra comma, recovered"); }
    ;
%%

void yyerror(const char *s){
    printf("syntax error: ");
}

int main(int argc, char **argv){
    if(argc != 2) {
        fprintf(stderr, "Usage: %s <file_path>\n", argv[0]);
        exit(-1);
    }
    else if(!(yyin = fopen(argv[1], "r"))) {
        perror(argv[1]);
        exit(-1);
    }
    yyparse();
    return 0;
}

lex.l
%{
    #include"syntax.tab.h"
%}
%option noyywrap

unic u[0-9a-fA-F]{4}
esc \\([\"\\/bfnrt]|{unic})
scp [^"\\\x00-\x1f]
string \"({esc}|{scp})*\"

int 0|[1-9][0-9]*
frac \.[0-9]+
exp [Ee][+-]?[0-9]+
number -?{int}{frac}?{exp}?

empty [ \n\r\t]

%%

"{" { return LC; }
"}" { return RC; }
"[" { return LB; }
"]" { return RB; }
":" { return COLON; }
"," { return COMMA; }

"true" { return TRUE; }
"false" { return FALSE; }
"null" { return VNULL; }

{string} { return STRING; }
{number} { return NUMBER; }

{empty} {}

. { printf("lexical error: %s\n", yytext); }

A: The error token is produced automatically by the bison parser when it is unable to do anything with the lookahead token. That enables it to make progress by shifting the error token, if the current parser state has such a shift action.
A production which contains the error token cannot be used unless an error token has been produced.
After shifting the error token, the parser will attempt to match the rest of the production containing it. If necessary, it will skip input until it finds a token which can be shifted. That can be used to synchronise the parse. So it's pretty common to see patterns like
Array: '[' Values ']'
     | '[' Values error ']'

which attempts to match the closing bracket.
Alternatively, you might just restart the parse, in a manner similar to your second example. (Here I use left-recursion, which is generally a better choice in case the list is long, since left recursion doesn't require usage of the parse stack):
Values: Value
      | Values ',' Value
      | Values error

If you want to produce a specific error for the case where the input includes a trailing comma, your best approach is to just include a normal rule:
Array: '(' Values ',' ')' { /* Signal the error */ }

Good error recognition is an art, not a science. A certain amount of experimentation is almost always necessary.

In most applications, it would be best to simply reject invalid JSON immediately rather than attempting to produce a meaningful error message and much less to continue the parse. JSON is normally machine-generated and should be correct; if it is not, there is no back channel for sending a meaningful error, and no-one to send it to. Incorrectly formatted interchange strings are often attempts to provoke vulnerabilities, and should be treated as such. (Your application may be an exception, of course. But experience shows that immediate rejection is almost always the best strategy, as well as being the simplest.)


text:
Q: Why are there multiple versions of the date time controls in Office UI Fabric? There is for example a DatePicker and a Calendar control in the main package (office-ui-fabric-react) and in the date-time package as well (installed as @uifabric/date-time). Both APIs seem to be nearly identical, but differ in some properties. For example in Calendar the calendarDayProps property (requested in this issue) is missing in the main package, but only available in the date-time package. I only found this out by searching through the github issues, because there is no official documentation available for the date-time package. The documentation page available only refers to the main package version.
On the other hand, in the already closed issue, it is nowhere mentioned, that this fix only applies to the date-time package version, as if this should be clear somehow. I feel that I missed some information.
So what's the point here? Will the date-time package version at some point in time replace the main package version? Are they intended to be used interchangeably? Why is there no documentation on this? I'm really confused ...


text:
Q: jQuery DOM Ready In the following code snippet:
<form>
    <fieldset>
        <button id="indexGetStarted" class="button" type="submit">Get Started!</button>
    </fieldset>
</form>
<script type="text/javascript">

    $(document).ready(function() {

        $('#indexGetStarted').click(function() {
            $('form').submit();
            return false;
        });

    });

</script>

Is $(document).ready(function() { ... } necessary?

A: Not absolutely, since you have declared your button (and then supposedly your form) before this script is being executed, it'll always be available. but removing that function would make your code dependent on where in the document the script block and the html elements are, in relation to one another.

A: Yes, It is required for writing clean code, but it has a shortcut:
$(function() { .... });
// is the same as
$(document).ready(function() { .... });

The behavior of manipulating DOM objects, attaching events, etc before the DOM Objects have fully loaded will be unpredictable, and often not work at all.
It might work if the elements are declared before the script portions load.

A: Strictly speaking, it is always necessary if you access DOM elements in the enclosed code. $(document).ready() delays the execution of the code until the DOM tree is fully built, which is important, as you access the DOM tree via $('#indexGetStarted'). Practically, it will probably work anyway, but I would not recommend it.

A: No, it's not needed. If you place scripts after the DOM elements in the source, the elements are naturally available. Some tests shows that this will speed up rendering, especially in IE.
You can bind stuff to the 'ready' event earlier in the markup and then run $.ready() before closing the body with the same effect.


text:
Q: Spinning drawable ONLY via XML android I want to implement a splash activity to my app. To do it i have to declare a custom theme for Splash activity on Manifest. I found this guide there: https://www.bignerdranch.com/blog/splash-screens-the-right-way/
So the problem is that i dont know how to implement spinning drawable on this theme (The idea is to place drawable on center and just spin it). But i didn't found any ways to do it: in guides they always use ProgressBar to make it spin.
Is there any way i can do it?


text:
Q: Option to choose reply from address on mail.app in Lion My default position is to stay within the OS X ecosystem unless their is a compelling reason to use use a 3rd party product. Gmail (with Sparrow) has long been keeping me from using mail.app on my desktop, but I'm thinking it's time to reconsider. I'm hoping someone can answer this to save me doing the work just to find out - Can I choose which of my accounts to reply from or am I limited to the address it was sent to ?

A: *

*On the fly in the reply dialog:

*Set default in the preferences:

A: Once you configure multiple accounts, or even different aliases for the same account, you can reply to messages from any account/alias combination, even different from the one that recieved the mail.

A: Yes, that's no problem, you can have multiple accounts, and you get to choose which is the default, as well as reply from a different account on a per-mail basis by choosing from a drop down.  You can even choose different SMTP servers from the same mail account, allowing you to (for example) route the same account through your own SMTP server as email address X, or choose to route it through GMails own SMTP server which allows you to transform your sender address in the Gmail Web App Settings.


text:
Q: Почему срабатывает offset на большом разрешении? В коде стоит col-xs-offset1 почему отступ ставится работает на большом разрешении?

Если убрать xs-offset всё становится красиво

Но тогда страдает мобильная версия

A: Идет наследование offset, чтобы убрать его надо прописать класс col-*-offset-0. Где * это md или lg.


text:
Q: Community: Securely pass attribute to different component on separate page In my community I have an iteration that displays "Open" records from a custom object that shows an overview of their record.
Below the overview is a button that currently goes to the standard record detail page and loads a page layout. I would like to hide the record Id from the URL and pass the id behind the scenes.
I have successfully gotten an event to pass when source cmp and destination cmp are on the same page, but these cmp's need to live on separate pages.
How do I pass the event attr to the destination cmp on a separate page?
event.cmp
    <aura:event type="APPLICATION">
        <aura:attribute name="involvementId" type="Id"/>
    </aura:event>

source.cmp
<lightning:button   onclick="{!c.fireApplicationEvent}"
     name="{!inv.Id}">Click here.</lightning:button>

source.cmp Controller
fireApplicationEvent : function(cmp, event) {
   var appEvent = $A.get("e.c:InvID");
    appEvent.setParams({
        "involvementId" : event.getSource().get("v.name") });
    appEvent.fire();
}

destination.cmp
<aura:attribute name="messageFromEvent" type="Id"/>

   <aura:handler event="c:InvID"
       action="{!c.handleApplicationEvent}"/>

 {!v.messageFromEvent}

destination.cmp Ctlr
handleApplicationEvent : function(cmp, event) {
    var involvementId = event.getParam("involvementId");

    // set the handler attributes based on event data
    cmp.set("v.messageFromEvent", involvementId);

}

A: There are sections in the community (usually the template headers and footer) which are consistent across pages (don't reload, and can be used to store attributes) you can use components in those sections to achieve what you are describing.

A: Based on your comments, it's clear that you're trying to pass the Salesforce record Id to another custom page without letting the user see the Id. While I'm not sure why showing the Salesforce Id in the URL could have confidentiality implications if your sharing model is set up right, it does sound like you have a need to do so.
Since you're going from custom page to custom page, why not keep the user on the same page, but make it look like a second page.  If you put the content for "page 1" and "page 2" in separate divs and show/hide them to make it look like separate pages, then you can avoid passing the Id at all.  That's about as secure as it gets!

A: You can use the SessionStorage to pass the Id between pages without making it public in the url. Additionally you can encrypt these Id and decrypt them in the component. Session storage only persists until you close the browser
Here you can read more: HTML5 Web Storage


text:
Q: How I short out this error Resource Exhausted Error I created a model with 13500 images. During the training time after 1 epoch showing an ERROR: "ResourceExhaustedError".[enter image description here](https://i.stack.imgur.com/5YJxV.png)
My system Ryzen7 AMD  NVIDIA GeForce GTX 1650/120Hz
Image Classification using Tensorflow with Keras.
I enclose MY LAYER below

overall_model = models.Sequential([
    resize_and_rescale,data_augmentation,
    layers.Conv2D(32,(3,3),activation = "relu", input_shape = input_shape),
    layers.MaxPooling2D((2,2)),
    layers.Conv2D(64,kernel_size = (3,3),activation= "relu"),
    layers.MaxPooling2D((2,2)),
    layers.Conv2D(64,kernel_size = (3,3),activation= "relu"),
    layers.MaxPooling2D((2,2)),
    layers.Flatten(),
    layers.Dense(64,activation='relu'),
    layers.Dense(len(class_names),activation='softmax')

])

Batch size = 16
epochs = 5
Thanking you
Help to solve my error.
If I need any corrections or changes in my model let me know...


text:
Q: How to change and insert into new table? This is my query:
SELECT TOP 50
    ch.CharName16, it.OptLevel, obj.ReqLevel1, item.ItemClass
FROM
    _Items as it
LEFT JOIN
    [dbo].[_Inventory] as inv ON it.ID64 = inv.ItemID
LEFT JOIN
    [dbo].[_Char] as ch ON inv.CharID = ch.CharID
LEFT JOIN
    [dbo].[_RefObjCommon] as obj ON it.RefItemID = obj.ID
LEFT JOIN
    [dbo].[_RefObjItem] as item ON obj.Link = item.ID
LEFT JOIN
    [dbo].[_BindingOptionWithItem] as adv ON it.ID64 = adv.nItemDBID
WHERE
    ch.CharName16 IS NOT NULL
    AND CodeName128 NOT LIKE '%stone%'
    AND CharName16 NOT LIKE '%]%'
ORDER BY
    it.OptLevel DESC, obj.ReqLevel1 DESC, item.ItemClass DESC,
    adv.nOptValue DESC

The results of the query:

I want to add these to new table but like this:

How can I do this?

A: You can wrap your query with an Outer Query that performs the necessary aggregations you need to roll the data up as pictured in your desired results (you'll need to remove the ORDER BY if you remove the TOP 50). Then perform your INSERT with the aggregated data. Something like this should work just fine.
INSERT INTO MyTable(
        CharName16
        , OptLevel
        , ReqLevel1
        , ItemClass
        , TotalPoint
        )
SELECT CharName16
        , SUM(OptLevel) AS OptLevel
        , SUM(ReqLevel1) AS ReqLevel1
        , SUM(ItemClass) AS ItemClass
        , SUM(OptLevel) + SUM(ReqLevel1) + SUM(ItemClass) AS TotalPoint
  FROM (
        SELECT TOP 50 ch.CharName16, it.OptLevel, obj.ReqLevel1, item.ItemClass
          FROM _Items as it
          LEFT JOIN [dbo].[_Inventory] as inv ON it.ID64 = inv.ItemID
          LEFT JOIN [dbo].[_Char] as ch ON inv.CharID = ch.CharID
          LEFT JOIN [dbo].[_RefObjCommon] as obj ON it.RefItemID = obj.ID
          LEFT JOIN [dbo].[_RefObjItem] as item ON obj.Link = item.ID
          LEFT JOIN [dbo].[_BindingOptionWithItem] as adv ON it.ID64 = adv.nItemDBID
         WHERE ch.CharName16 IS NOT NULL
           AND CodeName128 NOT LIKE '%stone%'
           AND CharName16 NOT LIKE '%]%'
       ) tbl
 GROUP BY CharName16

A: SELECT TOP 50
    ch.CharName16,
    Sum(it.OptLevel)as OptLevel,
    Sum(obj.ReqLevel1)as ReqLevel1,
    Sum(item.ItemClass) as ItemClass,
    Sum(SUM(it.OptLevel)+ SUM(obj.ReqLevel1)+ SUM(item.ItemClass)) as TotalPoint

 INTO NEWTABLE

FROM
    _Items as it
LEFT JOIN
    [dbo].[_Inventory] as inv ON it.ID64 = inv.ItemID
LEFT JOIN
    [dbo].[_Char] as ch ON inv.CharID = ch.CharID
LEFT JOIN
    [dbo].[_RefObjCommon] as obj ON it.RefItemID = obj.ID
LEFT JOIN
    [dbo].[_RefObjItem] as item ON obj.Link = item.ID
LEFT JOIN
    [dbo].[_BindingOptionWithItem] as adv ON it.ID64 = adv.nItemDBID
WHERE
    ch.CharName16 IS NOT NULL
    AND CodeName128 NOT LIKE '%stone%'
    AND CharName16 NOT LIKE '%]%'
ORDER BY
    it.OptLevel DESC, obj.ReqLevel1 DESC, item.ItemClass DESC,
    adv.nOptValue DESC


text:
Q: How can I make sure that my javascript removes whitespace before adding "..." I have a string variable that looks this:

Årets upplaga av Storsjöcupen, en fotbollsturnering i Östersund för
  ungdomar, fick en trist avrundning när anhängare till ett norskt
  pojklag anklagades för att ha farit ut i rasistiska och
  könsordskryddade tillmälen mot spelare i motståndarlag.

When my javascript is executed it turns the string to:

Årets upplaga av Storsjöcupen, en fotbollsturnering i Östersund för
  ungdomar, fick en trist avrundning när anhängare till ett norskt
  pojklag ...

If you see the three "..." there is a space that I dont want to have.
I want it to be:

pojklag...

My javascript looks like this:
  function TrimLength(text, maxLength) {
          text = $.trim(text);

          if (text.length > maxLength) {
              text = text.substring(0, maxLength - ellipsis.length)
              return text.substring(0, text.lastIndexOf(" ")) + ellipsis;
          }
          else
              return text;
      }

$(document).ready(function () {
          $(".text").each(function () {
              var text = $(this).text();
              $(this).text(TrimLength(text, 150));
          });

How can I make sure that the space gets removed?
Any kind of help is appreciated.

A: Simply change this line:
return text.substring(0, text.lastIndexOf(" ") - 1) + ellipsis;

Your code is finding the last space and removing everything after it.  Simply make the length passed to substring be one character less, and you'll remove the last space as well.

A: I would do it like this:
function trimLength( text, maxLength ) {
    text = $.trim( text );
    if( text.length <= maxLength )
        return text;
    return text
        .slice( 0, maxLength - ellipsis.length )
        .replace( /\s+\S*$/, '' )
        + ellipsis;
}

This should handle all of the cases mentioned in the other comments, including a string with no spaces in it, as well as a string with more than one consecutive space where it breaks.
Also, just as a suggestion, I took the liberty of changing the function name from TrimLength to trimLength because it is not a constructor. Idiomatic JavaScript begins constructor names with a capital letter and other functions and variables with a lowercase letter.


text:
Q: What does Sourcing of eucarc mean? I am trying to setup an on premise cloud by using Eucalyptus. I am following the following link
Now in that guide I am not able to figure out what this means:

ensure that the environment variables necessary for euca2tools to work are set by sourcing the eucarc file:
  . ~/.euca/eucarc

When I type the above command I am not getting any output. Does that mean I am doing somthing wrong.
Also when I try

euca-describe-availability-zones verbose

I am getting error saying

Warning: failed to parse error message from AWS: :1:61: syntax error

And some tracebacks
I am pasting the complete error here. I am struck here and I am trying fr solutions from various forums and no luck. Ny help would be very helpful.

A: The "Bash Prompt HOWTO" has the following information about sourcing a script:
Bash Prompt HOWTO > Chapter 3. Bash Programming and Shell Scripts > 3.5. Sourcing a File
http://tldp.org/HOWTO/Bash-Prompt-HOWTO/x237.html

"When a file is sourced (by typing either source filename or .
  filename at the command line), the lines of code in the file are
  executed as if they were printed at the command line."

In the command you put, you have ". ~/.euca/eucarc". Did you notice the "dot space" at the beginning of the command (before the "tilde")? That "dot space" is the part of the command that is sourcing the "eucarc" script. You could have also typed "source ~/.euca/eucarc" to achieve the same result.
Like "Ladadadada" has commented above, "Running the env command before and after the command with no output (sourcing eucarc) should show you what it did.".
In case you have typed the "dot source" at the beginning of the command, but are still getting the error you mentioned: I don't work with Eucalyptus, but I have looked at the error message you get when you run "euca-describe-availability-zones verbose" ("Warning: failed to parse error message from AWS: :1:61: syntax error"). A web search revealed the following message - in a discussion in the openstack team mailing list - written in 27 Jan 2012, by Vishvananda Ishaya,  that may help:
openstack team mailing list archive > Re: Devstack: euca-describe-availability-zones Warning: failed to parse error message from AWS: :1:0: syntax   error None: None
https://lists.launchpad.net/openstack/msg07083.html
From that message:

" devstack provides a file to source called openrc with all the necessary variables.
  You don't need to create your own novarc file, just source openrc instead. "

I hope this helps. :)


text:
Q: How to connect these 3 programming languages? How to pass information in this flow:
Flash(AS3) -> PHP, using XML -> Database(mysql)
Can anyone write a simple code for that?
Thanks.

A: http://www.kirupa.com/developer/actionscript/flashphpxml_integration.htm
This will tell you most of what you need to know to get started.

A: If you're not already tied to using XML, you might want to look into using AMF.  There's a number of OSS implementations of AMF for PHP, from the obviously named amfphp to an implementation in the Zend Framework.  Hopefully somebody with experience here will come along and provide a better answer.

A: What about WebService SOAP/WSDL?
So you can provide web service on php and send information from Flex/AS3/Flash by calling some webservice method and then store it into mysql db.
Flex has class WebService, so on client side to call server method is as easy as:
var webService:WebService = new WebService();
webService.wsdl = "http://yoursite.com/webservice.wsdl";
webService.loadWSDL();
webService.this_is_method_from_php_server(your_object_serialized_as_xml);

On PHP side I'm sure there are dozen libraries to provide SOAP/WSDL.

A: I would recommend using amfPHP to get information from a MySQL database passed to Flash through php. It is simpler, faster and easier to use than using php to output the database result in xml. Basically what you do with amfPHP is that you can call php functions directly from flash using the LocalConnection class.
I'll simplify some code to illustrate how it works:
//PHP code
//Here's you main php class which all the sql commands will be called

    class Main{
        public function saveUser($username, $password){
            //I'll send in the username and password to insert it into the users column
            $this->db->query("INSERT INTO users VALUES ($username, $password)");
            //I'm using the MDB2 library for sql queries,
            //you write less code when doing queries.
        }
    }

    //Actionscript 3 code

    //To pass parameters to my php function I have to make an array.
    var amfParameters:Array = [];
    amfParameters['username'] = "richard";
    amfParameters['password'] = "123123";

    //Then create a localconnection which will connect to amfphp.
    var localConnection:LocalConnection = new LocalConnection();
    localConnection.connect(gatewayURL); //gatewayURL is the url to the gateway amfphp file
    localConnection.call("testproject.Main.saveUser", loaderResponder, amfParameters);
    //testproject.Main.saveUser is the path for our Main.php file and saveUser is the function
    //loaderResponder is a Responder class which handles the callback from amfphp.

So basically you will call the php function in flash, and you can also return data to flash aswell.
This is just to illustrate a little bit of how amfphp works. It's not meant to be a complete code sample. Just to give a brief idea.
Think about it and if you think it looks interesting go and download amfphp and try it out! You won't be dissappointed.


text:
Q: How to exit docker exec after container has exited? How do I gracefully exit a docker container that I've connected to using docker exec -ti, after the docker I connected to exits?
If I exit the original container, the shell that ran the docker exec command is hung, and the only way I can find to exit back to its shell is to kill the docker exec command from another terminal.
Is there a more graceful way?
This happens whether I start the container with --rm or not.
I'm running docker 19.03.12 under bash 5.0.16 in gnome-terminal 3.26.3 in Ubuntu 20.04.

A: To detach the tty without exiting the shell, use the escape sequence CTRL+P followed by CTRL+Q. More details here.
Additional info from this source:
docker run -t -i → can be detached with Ctrl+P & Ctrl+Q sequece and reattached with docker attach
docker run -i → cannot be detached with Ctrl+P & Ctrl+Q sequence; will disrupt stdin
docker run → cannot be detached with Ctrl+P & Ctrl+Q; can SIGKILL client; can reattach with docker attach
Hope this helps.

A: You first run container with detached mode, not foreground:
docker run --name mynginx -p 80:80 -d nginx

Then you can attach to it with docker exec:
docker exec -it mynginx /bin/sh

Bear in mind that if you want to attach to a container for inspecting, you have to specify --interactive , -i and --tty , -t options, because your container is already running your main process in background from your previous docker run -d command.
That way when you finish inspecting your container, you can gracefully exit from it with ctrl+d or logout command, as you exit from an ordinary shell

A: @Khushal gave me the answer... sort of.  In my case, Ctrl+P & Ctrl+Q  still didn't work even when calling run with -t, but plain old Ctrl+C did.  To provide some context, I'm playing with a Rancher docker container, so YMMV.
To summarize, create the container with:
docker run -t -d --name=thingy ...
Attach as usual with:
docker attach thingy
Detach with good old fashioned Ctrl+C.
By the way, -t, according to the docs, allocates a pseudo-TTY.


text:
Q: Needed jar file's for add event google calendar in android? Hi I am new to android. I need to know the needed jar file's to add the calendar event from my application and where to download that ?

A: I don't think you need any external JARs to access the Google calendar. For example, see this article from Developer.com. They explain how to put the right permission requests in your Android Manifest, and then how to query the calendar database.


text:
Q: What should be the solution for $\dfrac{(x-1)^2}{(x-1)} = 0$ where obviously that x should not be equal to 1? What should be the solution for $\dfrac{(x-1)^2}{(x-1)} = 0$, where it is obvious that x should not be equal to 1?
In this case, when can we only cancel the common factors on the numerator and denominator of a rational expression? Do we need to identify the numbers that are not possible after canceling the common factor?
This might be a simple question but often not properly discussed in most of the math class.
I am studying continuity of a function and I encounter this problem in my head while doing an analysis on determining if a certain function is continuous or not.
Please feel free to share your answers and I would like to thank you in advance for sharing your thoughts about this.

A: There is no solution: $\lim_{x \to 1} \frac{(x-1)^2}{x-1} = 0$ which means the function gets arbitrarily close to $0$, but for no $x$ does $f(x) = 0$.

A: Strictly speaking $\frac{(x-1)^2}{x-1}$ has no solution.
Regarding "cancellation": It's not quite true that $\frac{(x-1)^2}{x-1}=x-1$. What's true is $$\frac{(x-1)^2}{x-1}=x-1\quad(x\ne1).$$

A: The given expression does not have a root, since the numerator vanishes exactly on the same points as the numerator. However we can extend it to the real line in order to make it continuous as follows:
\begin{align*}
f(x) =
\begin{cases}
x-1, & x\neq 1,\\
0, & x = 1
\end{cases}
\end{align*}
The thing is that we are dealing with a removable singularity.
Hopefully this helps!

A: $$ \frac{(x-1)^2}{x-1} = 0 $$
By cancellation it becomes,
$$ x-1=0 $$
However putting x as $1$ will give denominator $0$. Thus this expression has no solution

A: So, if
$$
f(x) = \frac{(x-1)^2}{(x-1)}
$$
then ${f(x)=0}$ does not have any solutions. The thing is, it's not true that ${f(x) = x-1}$; it's true that if ${x\neq 1}$, then ${f(x)=x-1}$, but we cannot perform the cancellation when ${x=1}$, it doesn't make any sense.
Instead, what we can do is "extend" ${f(x)}$ to make sense of it at $1$. It's what's called a "removable singularity". You may notice that
$$
f(x) = \frac{(x-1)^2}{(x-1)}
$$
behaves just like ${x-1}$ around the point ${x=1}$, and even satisfies ${\lim_{x\to 1}f(x) = 0 = (1-1)}$. And so it makes sense to extend ${f(x)}$ to the function ${x-1}$, which will now include ${x=1}$ as a valid part of the domain and it will remain a continuous function. Now you can say ${\tilde{f}(x) = 0}$ has solution ${x=1}$ (I have denoted ${\tilde{f}}$ here to mean "$f$ extended to include $1$"). Hopefully that helps.


text:
Q: How to calculate volume profile between the start and end time? I use price and time inputs specified by the user:
startPrice = input.price(0, inline="StartPoint", confirm=true)
startTime = input.time(0, inline="StartPoint", confirm=true)

endPrice = input.price(0, inline="EndPoint", confirm=true)
endTime = input.time(0, inline="EndPoint", confirm=true)

and I want to calculate the volume profile like the build indicator does. But I can't find a way of doing it. I can calculate the volume profile by any fixed period or using lookback bars count, but how to calculate it using arbitrary start and end times?


text:
Q: How acquire STS credentials for a mobile application to access secured S3 objects? I have deployed the backend service in AWS Fargate. I would like to acquire STS tokens in order to retrieve a set of secured S3 objects from the native mobile app. I use Terraform for creating infrastructure. I already have a Fargate task role task-role created. So for this particular usecase I created a new role native-app-role and assigned the task-role as a trusted relationship with permission to assume the native-app-role.
The following is the Terraform code:
# Fargate Role with trust relationship to ECS

data "aws_iam_policy_document" "fg_task_role_assume_role_policy_doc" {
  statement {
    actions = [
      "sts:AssumeRole"
    ]

    effect = "Allow"

    principals {
      type = "Service"
      identifiers = [
        "ecs-tasks.amazonaws.com"
      ]
    }
  }
}

resource "aws_iam_role" "task_role" {
  name = "${var.application}-${var.namespace}-fargate-task-role"
  assume_role_policy = data.aws_iam_policy_document.fg_task_role_assume_role_policy_doc.json

  tags = {
    Name = "${var.application}-${var.namespace}-fargate-task-role" # virtual-agent-alpha-fargate-task-role
  }
}

# Native app role with trust relationship to Fargate role
data "aws_iam_policy_document" "native_app_iam_policy_doc" {
  statement {
    actions = [
      "sts:AssumeRole"
    ]

    effect = "Allow"

    principals {
      type = "AWS"
      identifiers = [
        aws_iam_role.task_role.arn
      ]
    }
  }
}

resource "aws_iam_role" "virtual_agent_native_iam_role" {
  name = "${var.application}-${var.namespace}-native-application-role"
  assume_role_policy = data.aws_iam_policy_document.native_app_iam_policy_doc.json

  tags = {
    Name = "${var.application}-native-${var.namespace}-role"
  }
}

Then I have use the following Kotlin code to obtain STS credentials:
Note: roleArn is the ARN of the virtual_agent_native_iam_role
fun getS3ReadOnlyTempCredentials(roleArn: String, bucket: String, objectKey: String, expiry: Expiry = Expiry(15, ChronoUnit.MINUTES)): AwsStsCredentials {
        val duration = Duration.of(expiry.duration, expiry.unit).toSeconds().toInt()
        val request = AssumeRoleRequest().apply {
            this.roleArn = roleArn
            roleSessionName = UUID.randomUUID().toString()
            durationSeconds = duration
            policy = """
                {
                  "Id": "${UUID.randomUUID()}",
                  "Version": "2012-10-17",
                  "Statement": [
                    {
                      "Action": [
                        "s3:GetObject"
                      ],
                      "Effect": "Allow",
                      "Resource": "arn:aws:s3:::$bucket/$objectKey",
                      "Principal": {
                        "AWS": [ $roleArn ]
                      }
                    }
                  ]
                }
            """.trimIndent()
        }

        return stsClient.assumeRole(request).credentials.let {
            AwsStsCredentials(it.accessKeyId, it.secretAccessKey, it.sessionToken, ZonedDateTime.now().plusSeconds(duration.toLong()) )
        }

When I execute this I get the following error:
com.amazonaws.services.securitytoken.model.AWSSecurityTokenServiceException: User: arn:aws:sts::913597729265:assumed-role/virtual-agent-alpha-fargate-task-role/c082fba5-3d13-4030-a457-9a18fb105efd is not authorized to perform: sts:AssumeRole on resource: "arn:aws:iam::913597729265:role/virtual-agent-alpha-native-application-role" (Service: AWSSecurityTokenService; Status Code: 403; Error Code: AccessDenied; Request ID: 573630b6-b02a-4185-ae5b-9360d05b4225)
The above error says the virtual-agent-alpha-fargate-task-role does not have permission to assume the virtual-native-role but I have added the trust relationship via the aussumeRole attribute of aws_iam_resource of Terraform.
Could someone please point out what I am doing wrong?

A: I believe your role creation is wrong. The policy that you created inside your code must be part of your virtual_agent_native_iam_role inside your terraform template.
You also don't need to assumeRole inside your code, your can configure your task to use a the execution role that you created in your terraform template. Check here for more information.

A: I can try to help you with two alternatives, but to do that I need to confirm your use case. As I understood, you need to provide access for a specific user to read (during a defined interval of time) a specific s3 object. If this is the case here are my suggestions:
The first alternative would be to try to make your solution to work. But you'll need to test it because I don't have this scenario here: First I would remove the virtual_agent_native_iam_role and keep only the task_role. I would still need to call AssumeRole using the task_role and the specific $bucket/$objectKey. But there is something that is missing in your role configuration. As per assume-role api documentation:

The resulting session's permissions are the intersection of the role's identity-based policy and the session policies.

So to make it work your task_role policies should have permissions to allow more broad access to s3 and your method call would only restrict already existent policies. In that case I would attach a new policy to your task_role in your terraform template to allow the action s3:GetObject to all objects in the bucket (or if needed to all buckets in your account, dependent of your use case).
The AssumeRole call would be used to restrict the access of the temporary credentials to a specific bucket/objectkey.
But there is a second alternative that I believe would be much more simple. But you'll need to evaluate if it is applicable to your use case:
S3 allows you to create a temporary url for a specific object that would allow the user that have the url to get the object during a specific time interval. For that solution, you will also need to add a policy with permissions to s3:GetObject for task_role. But in that case you won't need to call the AssumeRole method in your code. You can just call the method to create the pre-signed url and send it back to your user. You can find more details about this alternative implementation using java-sdk here.
With that scenario, the user will only have access to the selected object. Not the entire bucket.

A: I fixed the issue. The mistake I made was not providing permission to the task_role to with AssumeRole permissions. Everything else stated in the question is done correctly. So in my terraform for task_role I had to attach a custom policy with the correct permissions.
Terraform code:
data "aws_iam_policy_document" "virtual_agent_native_assume_role_policy_doc" {
  statement {
    effect = "Allow"
    actions = ["sts:AssumeRole"]
    resources = ["*"]
  }
}

resource "aws_iam_policy" "virtual_agent_native_assume_role_policy" {
  name = "${var.application}-${var.namespace}-native-role-assume-role-policy"
  policy = data.aws_iam_policy_document.virtual_agent_native_assume_role_policy_doc.json
}

resource "aws_iam_role_policy_attachment" "task_role_virtual_agent_native_assume_role_policy_att" {
  role = aws_iam_role.task_role.name
  policy_arn = aws_iam_policy.virtual_agent_native_assume_role_policy.arn
}


text:
Q: Integration using different substitutions resulting in different answers? I'm going through the MIT online calc course, and I'm trying to find the following from an Integration Problem set:
$$\int \frac{x^2+1}{x^2+2x+2}dx$$
I could use the substitution u = x+1, which results in the correct answer:
$$\int \frac{(u-1)^2+1}{u^2+1}du$$
$$\int 1 + \frac{1}{u^2+1} - \frac{2u}{u^2+1}du$$
$$u + arctan \; u - ln(u^2+1)$$
$$x+1+arctan \; (x+1) - ln(x^2+2x+2)$$
But originally I tried using completing the square and the substitution $(tan \theta = x + 1)$. I get:
$$\int \frac{x^2+1}{(x+1)^2+1}dx$$
$$\int \frac{tan^2 \theta - 2tan \theta + 1 + 1}{sec^2\theta}sec^2\theta d\theta$$
$$\int sec^2\theta - 2tan\theta+1 d\theta$$
$$tan \theta + 2ln(cos \theta) + \theta$$
$$x + 1 - 2ln(x^2+2x+2) + arctan(x+1)$$
There's an extra 2 coefficient there.  I don't think there's a math error, so I'm thinking the ambitious substitution is the cause.  Any ideas?

A: The mistake is in thinking $\cos\theta=x^2+2x+2$.
Remark: I would probably want to divide first, getting $1-\dfrac{2x+1}{(x+1)^2+1}$.
Then write $\dfrac{2x+1}{(x+1)^2+1}$ as $\dfrac{2x+2}{(x+1)^2+1}-\dfrac{1}{(x+1)^2+1}$.


text:
Q: Can we pass parameters to signals in C? I am implementing a Simple Iterative TCP client/server in C. The server is infinitely listing in a loop.
Now if Ctrl+c (SIGINT) occurred at any point of time, how would I free up the resources used in server?
For example, I caught the signal in my own signal handler; how would I get socket descriptors
and buffers used in the program so as to free them?
I new to socket programming; any suggestions would be appreciated.

A: No. The only parameter passed to your signal handler is an int which is the signal number.
The typical way to deal with the situation you describe is having a global variable such as int stopAndExit that your loop is checking. If it gets flipped to 1 by the signal handler you know to clean up and exit.
Edit: For a more thorough discussion prompted by comments below.
One problem with this is if you are in a non-reentrant function when the signal arrives. To deal with this, you actually want to delay (block) signals, then handle them at a point in your main loop that is safe.
Last Edit: Unless you have some external operations occurring that need to be cleaned up before so you guarantee you exit in a clean state ... it doesn't matter. Your socket descriptors and buffers are all going away anyway when you exit. There's no need to clean up anything.

A: Don't install a signal handler. Don't do anything. The default action for SIGINT is to terminate the process, and assuming no other processes have descriptors for your sockets, they'll all naturally be closed and cease to exist when the process terminates.

A: The code in this answer is horrendously unsafe, invokes all kinds of UB, and shouldn't be used in your case. Using setjmp / longjmp in a signal handler is only remotely workable as a way to deal with null pointer dereferences, and even then it needs to be extremely limited in scope to avoid invoking UB.
Here's another possible way of dealing with cleanup:
static jmp_buf buf;
static int ret = 0;

void handle(int sig)
{
    ret = 1;
    longjmp(buf, 1);
}

int func(void)
{
    FILE *f = fopen(/* yadda */);

    void (*orig)(int) = signal(SIGINT, handle);

    if(setjmp(buf)) goto CLEANUP;

    // use f

  CLEANUP:
    fclose(f);
    signal(SIGINT, orig);
    return ret;
}

Of course, doing a whole lot of hard work in a signal handler isn't guaranteed to work by the standard, but I'm sure if you were worried about that you wouldn't be trying to handle the signal.


text:
Q: Saving dynamically generated checkbox state in a ListView My ListView Item contains a TextView and a LinearLayout. The LinearLayout contains dynamically generated CheckBoxes, the number of the checkboxes can be different in each list item. I want to save the state of the checkbox when I scroll the item off the screen, and scroll it back to focus. Right now it's not being saved. Here's my code, could you tell me what I'm doing wrong?
public class ListAdapter extends ArrayAdapter<BaseModel> {

  private ArrayList<CheckboxModel> mCheckboxModels;

  private static class ViewHolder {

    TextView mName;
    LinearLayout mLinearLayout;

  }

  public ListAdapter(Context context, ArrayList<BaseModel> baseModels) {
    super(context, 0, baseModels);
  }

  @NonNull
  @Override
  public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
    final BaseModel currentBaseModel = getItem(position);

    mCheckboxModels = new ArrayList<>();

    View currentRow = convertView;
    ViewHolder viewHolder;

    if (currentRow == null) {
      viewHolder = new ViewHolder();
      LayoutInflater inflater = LayoutInflater.from(getContext());
      currentRow = inflater.inflate(R.layout.list_item, parent, false);
      viewHolder.mName = (TextView) currentRow.findViewById(R.id.idTextView);
      viewHolder.mLinearLayout = (LinearLayout) currentRow.findViewById(R.id.idCheckboxLinearLayout);
      currentRow.setTag(viewHolder);
    } else {
      viewHolder = (ViewHolder) currentRow.getTag();
    }

    if (currentBaseModel != null) {
      viewHolder.mName.setText(currentBaseModel.getName());
      viewHolder.mLinearLayout.removeAllViewsInLayout();

      int numOfButtons = currentBaseModel.getNumOfButtons();

      for (int i = 0; i < numOfButtons; i++) {
        mCheckboxModels.add(new CheckboxModel(new CheckBox(getContext()), false));

        currentBaseModel.setCheckboxModels(mCheckboxModels);
        viewHolder.mLinearLayout.addView(currentBaseModel.getCheckboxModels().get(i).getCheckBox());

        final int j = i;

        currentBaseModel.getCheckboxModels().get(i).getCheckBox().setOnCheckedChangeListener(
            new OnCheckedChangeListener() {
              @Override
              public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                currentBaseModel.getCheckboxModels().get(j).setChecked(isChecked);
              }
            });

        currentBaseModel.getCheckboxModels().get(i).getCheckBox()
            .setChecked(currentBaseModel.getCheckboxModels().get(i).isChecked());
      }

    }

    return currentRow;
  }
}

A: Do not do mCheckboxModels = new ArrayList<>(); in getView()
You have to do:
private ArrayList mCheckboxModels = new ArrayList<>()


text:
Q: How can I transform a single json object into json array? My axios api returns a JSON object in the format as follow.
{
    "GROUP": "Group",
    "NTH_PRODUCT_AFTER_M": "Nth Product After M",
    "CART_DISCOUNT": "Cart Discount",
    "EACH_NTH": "Each Nth",
    "BUYX_GETY": "Buy X Get Y",
    "PRODUCT_SET": "Product set",
    "PRODUCT_DISCOUNT": "Product Discount",
    "GET_Y_EACH_SPENT_X": "Get y Each Spent X"
}

but I need to tranform each element in the JSON object into a JSON object of a JSON array into this format below.
[
              { value: "EACH_NTH", label: "Each Nth" },
              { value: "GROUP", label: "Group" },
              { value: "BUYX_GETY", label: "Buy X Get Y" },
              { value: "CART_DISCOUNT", label: "Cart Discount" },
              { value: "NTH_PRODUCT_AFTER_M", label: "Nth Product After M" },
              { value: "PRODUCT_DISCOUNT", label: "Product Discount" },
              { value: "GET_Y_EACH_SPENT_X", label: "Get Y for Each Spend of X" },
              { value: "PRODUCT_SET", label: "Discount on a Product Set" },
            ];

A: Use Object.entries() to create an array of key / value pairs then map that to the structure you want

const data = {"GROUP":"Group","NTH_PRODUCT_AFTER_M":"Nth Product After M","CART_DISCOUNT":"Cart Discount","EACH_NTH":"Each Nth","BUYX_GETY":"Buy X Get Y","PRODUCT_SET":"Product set","PRODUCT_DISCOUNT":"Product Discount","GET_Y_EACH_SPENT_X":"Get y Each Spent X"};

const arr = Object.entries(data).map(([value, label]) => ({ value, label }));

console.log(arr);
.as-console-wrapper { max-height: 100% !important; }

The array will be sorted in the order of the keys in the original object.

A:

obj = {
      "GROUP": "Group",
      "NTH_PRODUCT_AFTER_M": "Nth Product After M",
      "CART_DISCOUNT": "Cart Discount",
      "EACH_NTH": "Each Nth",
      "BUYX_GETY": "Buy X Get Y",
      "PRODUCT_SET": "Product set",
      "PRODUCT_DISCOUNT": "Product Discount",
      "GET_Y_EACH_SPENT_X": "Get y Each Spent X"
    }

arr=[];
for (k in obj) {arr.push({value:k, label:obj[k]})}

console.log(arr);


text:
Q: How I can make this piece of website responsive?

@import url('https://fonts.googleapis.com/css?family=Roboto');
body {
  margin: 0 auto;
  font-family: 'Roboto', sans-serif;
  font-size: 14px;
}

#grid {
  display: grid;
  grid-template-columns: repeat(12, 1fr);
  grid-auto-rows: minmax(680px, auto);
  grid-template-areas: "header header header header header header header header header header header header";
}

header {
  grid-area: header;
  background: url("https://images3.alphacoders.com/536/thumb-1920-53625.jpg") no-repeat;
  background-size: 100% 100%;
}

nav {
  display: flex;
  background: hsla(0, 0%, 0%, 0.15);
  justify-content: space-between;
  align-items: center;
  position: sticky;
  top: 0;
}

ul>li {
  list-style: none;
  margin: 10px;
}

li>a {
  text-decoration: none;
  color: white;
}

.Facebook,
.Youtube {
  max-width: 40px;
  opacity: 0.5;
}

.Facebook:hover,
.Youtube:hover {
  opacity: 1;
}

#social {
  margin: 20px;
}

ul {
  display: flex;
}

ul>li {
  flex: 1 1 auto;
  flex-wrap: wrap;
}

#button {
  justify-self: center;
  align-self: center;
  border: 3px solid white;
  border-radius: 10%;
  color: white;
  text-align: center;
  padding-left: 50px;
  padding-right: 50px;
  padding-top: 10px;
  padding-bottom: 10px;
  position: relative;
  left: 100px;
}

#button>h4 {
  margin: 0;
}

#button:hover {
  background-color: white;
  color: black;
  cursor: pointer;
  transition: 0.5s;
}

MAKE A RESERVATION

About

Rooms

Activities

Gallery

Contact

I tried flex-wrap on all flex parents' children, it didn't work like I wanted, some items collapsed. I tried to set max or min-width to 100% or something like that to nav. It didn't work. I set flex to 1 1 auto but the button became very wide and it basically didn't work well even when I set 0 1 auto.
I tried to set the grid system to 12 columns(I still apply that as you see) and again, that didn't work a bit.
How I could make it responsive?

A: You can adjust your code like this:
Comments added inside the code

@import url('https://fonts.googleapis.com/css?family=Roboto');
body {
  margin: 0 auto;
  font-family: 'Roboto', sans-serif;
  font-size: 14px;
}

#grid {
  display: grid;
  grid-template-columns: repeat(12, 1fr);
  grid-auto-rows: minmax(680px, auto);
  grid-template-areas: "header header header header header header header header header header header header";
}

header {
  grid-area: header;
  background: url("https://images3.alphacoders.com/536/thumb-1920-53625.jpg") no-repeat;
  background-size: 100% 100%;
}

nav {
  display: flex;
  background: hsla(0, 0%, 0%, 0.15);
  /*justify-content: space-between; removed*/
  justify-content: center; /*added*/
  align-items: center;
  flex-wrap:wrap; /*added*/
  position: sticky;
  top: 0;
}
/*added*/
ul {
  padding:0;
}
/*****/

ul>li {
  list-style: none;
  margin: 10px;
}

li>a {
  text-decoration: none;
  color: white;
}

.Facebook,
.Youtube {
  max-width: 40px;
  opacity: 0.5;
}

.Facebook:hover,
.Youtube:hover {
  opacity: 1;
}

#social {
  margin: 20px;
}

ul {
  display: flex;
}

ul>li {
  flex: 1 1 auto;
  /*flex-wrap: wrap; useless*/
}

#button {
  /*justify-self: center;
  align-self: center; removed*/
  margin:auto; /*added*/
  border: 3px solid white;
  border-radius: 10%;
  color: white;
  text-align: center;
  padding-left: 50px;
  padding-right: 50px;
  padding-top: 10px;
  padding-bottom: 10px;
  /*position: relative;
  left: 100px; removed*/
}

#button>h4 {
  margin: 0;
}

#button:hover {
  background-color: white;
  color: black;
  cursor: pointer;
  transition: 0.5s;
}

MAKE A RESERVATION

About

Rooms

Activities

Gallery

Contact

A: You need to use CSS media tag to make responsive design & you can adjust your design as per your width:-
For Mobile View:-
@media only screen and (max-width:767px) {
/* your css will be here and this code will be working just in mobile device */
}

For iPad View:-
@media only screen and (min-width:768px) and (max-width:1024px) {
/* your css will be here and this code will be working just in iPad device */
}


text:
Q: Центрировать карту на первом результате поиска из searchControl без попапа и метки на карте Возник вопрос по поводу поведения searchControl.
Суть в том, что если я меняю свойство provider на yandex#map, перестаёт работать смена центра карты по результату запроса.
Если я его совсем не задаю или задаю yandex#search, то всё работает. Но поиск по организациям мне не нужен, нужен только по городам/улицам.
В документации сказано, что по умолчанию провайдер yandex#map, хотя судя по всему стоит yandex#search.
Подскажите пожалуйста, yandex#map так и должен себя вести?
Можно как-то оставить функционал центровки карты по первому результату?
Вот код подключения searchControl:

map.controls.add('searchControl', {
    noPopup: true,
    noPlacemark: true,
    noCentering: false,
    provider: "yandex#map"
});

A: Провайдер поиска yandex#map, действительно, провайдер по умолчанию. Указывать его дополнительно не нужно.
Как работает поиск с точки зрения контрола:

*

*Если найден единственный результат, то карта центрируется на нем и ставится метка.

*Если найдено несколько результатов, то появляется попап со списком, из которого пользовать выбирает нужный результат. После этого также центрируется карта и ставится метка.

Что вы делаете в своём коде:
noPopup: true - отключает попап со списком найденных результатов;
noPlacemark: true - отключает отображение метки результата поиска;
noCentering: false - карта должна центрироваться на результате поиска, опцию указывать не нужно, потому что она и так по дефолту false.
provider: "yandex#map" - искать только топонимы, опцию указывать не нужно, потому что она и так по дефолту имеет это значение.
Итого, код должен быть таким:
map.controls.add('searchControl', {
    noPopup: true,
    noPlacemark: true
});

Поскольку вы отключаете попап с результатами поиска, то карта не центрируется, если нашлось более одного результата - ожидается, что пользователь сначала выберет в попапе, а на чем собственно центрироваться.
Варианта у вас два:

*

*Не скрывать попап результатов поиска.

*Самостоятельно выбирать первый результат и центрировать на нём карту. Вот пример.


text:
Q: How to select data from the rows and update them in one pass? I make two queries for one table.
SELECT url FROM links WHERE post = '0' AND keywords = 'key';

Then
UPDATE links SET post='1' WHERE keywords = 'key';

But I get a duplicates because many threads.
How to combine these two requests into one?
Thanks

A: This is called Race Condition, Give following link a read
http://www.sqlines.com/mysql/how-to/select-update-single-statement-race-condition

A: Try this
UPDATE links SET post='1' WHERE keywords = 'key' AND post = '0';

OR
UPDATE links SET post='1' WHERE url in
(SELECT url FROM links WHERE post = '0' AND keywords = 'key');

A: This might work for you.
UPDATE links SET post='1' WHERE keywords in
(SELECT keywords FROM links WHERE post = '0' AND keywords = 'key');


text:
Q: Access imap sever from gmail through a proxy In gmail one can read email from different sources as long as the source provide a pop3 access. My university only allow imap access to email.
I'm thinking about having a proxy that act as an imap client on one side and provide a pop3 access on the other.
Another solution might be to use a third party web mail which can access imap and provide pop3 access.
Anybody knows an existing proxy I could run myself or a third party email service I could use as a proxy ?
+-------------------+
| University mail   |
|     server        |
+-------------------+
    provide imap
         ||
         \/
         ??  <----- Proxy, third party webmail, other idea ?
         /\
         ||
    connect to pop
+---------------------+
| Gmail web interface |
+---------------------+

Any other idea on how that could be done ?

A: I used to have one on my debian box, but I can't find what it was called (now my imap server also has a pop server). If you want to build one from scratch in 20 minutes for three bananas start with:
apt-get install fetchmail pop-server
man fetchmail

then configure a mail server (probably exim which just got installed as a default), and which ever pop-server just got installed (I didn't check) and setup fetchmail, and there you go. as easy as a moon shot.

A: You don't actually need to convert between the two standards, GMail supports both POP3 and IMAP:

To Enable IMAP in your Gmail settings

*

*Sign in to Gmail.

*Click the  gear in the top right.

*Select Settings.

*Click Forwarding and POP/IMAP.

*Select Enable IMAP.

*Click Save Changes.

A: You can't use the gmail.com web interface to connect to your universities IMAP mail server. Gmail permits INCOMMING IMAP and POP connections, your university perhaps only allows incoming IMAP connections only, however this does not mean you can repurpose the gmail.com website to connect to anything other than gmail.com's web/mail servers. Your best bet is to use a gmail android app and attempt a MITM method which may be possible since the gmail app interface most likely operates primarily on your mobile device. With the HTTP version of the gmail web interface, a lot of that code is server side which makes it not possible to accomplish what you are talking about. The truth is even the gmail app certainly has proprietary routines which will only work with a gmail mail server and the usefulness of doing this at all is slim to none unless you have some very specific reason. Besides, you can just forward all your university mail to a gmail account or explore a google apps option offered by your university if they already have or could be convinced of that.


text:
Q: Simple Calculator: Value in Function not defined but is listed in condition After some extensive reading and help from the community I have started to create formulae in the form of calculators to practice my knowledge using my real world influences. I have created this calculator and added an additional condition to the equation but now the working calculator can't define a function which had worked previously.
The value is defined and given at the beginning of the function so I don't understand why it is not longer defined when adding the condition.

var lsaForm = document.forms["lsacalc"],
  days = document.getElementById('days'),
  rlsa = document.getElementById("rlsa"),
  dayRateLsa = document.getElementById("rlsa"),
  rddlsa = document.getElementById("rddlsa"),
  tlsa = document.getElementById('tlsa');

function lsaupdateTotals() {
  var x = rlsa.value;
  var y = dayRateLsa.value;
  if (x == 1 || (y > 1 && y < 281)) {
rdlsa = 7.45;
  } else if (x == 2 || (y > 280 && y < 461)) {
rdlsa = 11.65;
  } else if (x == 3) {
rdlsa = 15.85;
  } else if (x == 4) {
rdlsa = 17.40;
  } else if (x == 5) {
rdlsa = 18.73;
  }
  let total = days.value * rdlsa;
  rddlsa.innerHTML = `Daily rate of LSA £${rdlsa}`;
  tlsa.innerHTML = `Total LSA Enitlement £${total}`;
}

A: I have resolved this by applying the rest of the conditions throughout the function, the console returned an error but unspecified. Theoretically I think that the value of 'RDLSA' returned different with the additional conditions.

function lsaupdateTotals() {
  var x = rlsa.value;
  var y = dayRateLsa.value;

  if (x = 1 || (y > 1 && y < 281)) {
    rdlsa = 7.45;
  } else if (x = 2 || (y > 280 && y < 461)) {
    rdlsa = 11.65;
  } else if (x = 3 || (y > 461 && y < 640)) {
    rdlsa = 15.85;
  } else if (x = 4 || (y > 641 && y < 821)) {
    rdlsa = 17.40;
  } else if (x = 5 || (y > 821 && y < 1001)) {
    rdlsa = 18.73;
  } else if (x = 6 || (y > 1001 && y < 1181)) {
    rdlsa = 20.07;
  } else if (x = 7 || (y > 1181 && y < 1360)) {
    rdlsa = 21.39;
  } else if (x = 8 || (y > 1361 && y < 1540)) {
    rdlsa = 23.40;
  } else if (x = 9 || (y > 1541 && y < 1720)) {
    rdlsa = 24.75;
  } else if (x = 10 || (y > 1721 && y < 1901)) {
    rdlsa = 26.09;
  } else if (x = 11 || (y > 1901 && y < 2081)) {
    rdlsa = 27.42;
  } else if (x = 12 || (y > 2081 && y < 2261)) {
    rdlsa = 28.77;
  } else if (x = 13 || (y > 2261 && y < 2241)) {
    rdlsa = 30.09;
  } else if (x = 14 || (y > 2241 && y < 2801)) {
    rdlsa = 31.43;
  } else if (x = 15 || (y > 2801 && y < 3160)) {
    rdlsa = 32.75;
  } else if (x = 16 || y < 3161) {
    rdlsa = 34.07;
  };

  let total = days.value * rdlsa;

  rddlsa.innerHTML = `Daily rate of LSA £${rdlsa}`;
  tlsa.innerHTML = `Total LSA Enitlement £${total}`;
}


text:
Q: Why app crash when receive push notification from firebase in react native? I am using react-native-firebase for remote push noticification. I am able to recieve noticification when app open or in background. But when I kill the appliction and remove it from memory, once i send message from firestore app crashes in mobile. I followed the complete documentation and implimented as per the documentation. What is the reason of app crash and how I can fix it?
My App.js

import React, {Component} from 'react';
import {Platform, StyleSheet, Text, View} from 'react-native';
import firebase from 'react-native-firebase';
import type { Notification, NotificationOpen } from 'react-native-firebase';
const instructions = Platform.select({
  ios: 'Press Cmd+R to reload,\n' + 'Cmd+D or shake for dev menu',
  android:
    'Double tap R on your keyboard to reload,\n' +
    'Shake or press menu button for dev menu',
});
export default class App extends Component {
    async componentDidMount() {
        const notificationOpen: NotificationOpen = await firebase.notifications().getInitialNotification();
        if (notificationOpen) {
            const action = notificationOpen.action;
            const notification: Notification = notificationOpen.notification;
            var seen = [];
            alert(JSON.stringify(notification.data, function(key, val) {
                if (val != null && typeof val == "object") {
                    if (seen.indexOf(val) >= 0) {
                        return;
                    }
                    seen.push(val);
                }
                return val;
            }));
        }
        const channel = new firebase.notifications.Android.Channel('test-channel', 'Test Channel', firebase.notifications.Android.Importance.Max)
                .setDescription('My apps test channel');
// Create the channel
        firebase.notifications().android.createChannel(channel);
        this.notificationDisplayedListener = firebase.notifications().onNotificationDisplayed((notification: Notification) => {
            // Process your notification as required
            // ANDROID: Remote notifications do not contain the channel ID. You will have to specify this manually if you'd like to re-display the notification.
        });
        this.notificationListener = firebase.notifications().onNotification((notification: Notification) => {
            // Process your notification as required
            notification
                .android.setChannelId('test-channel')
                .android.setSmallIcon('ic_launcher');
            firebase.notifications()
                .displayNotification(notification);

        });
        this.notificationOpenedListener = firebase.notifications().onNotificationOpened((notificationOpen: NotificationOpen) => {
            // Get the action triggered by the notification being opened
            const action = notificationOpen.action;
            // Get information about the notification that was opened
            const notification: Notification = notificationOpen.notification;
            var seen = [];
            alert(JSON.stringify(notification.data, function(key, val) {
                if (val != null && typeof val == "object") {
                    if (seen.indexOf(val) >= 0) {
                        return;
                    }
                    seen.push(val);
                }
                return val;
            }));
            firebase.notifications().removeDeliveredNotification(notification.notificationId);

        });
    }
    componentWillUnmount() {
      console.log("unmount called");
        this.notificationDisplayedListener();
        this.notificationListener();
        this.notificationOpenedListener();
    }

    componentWillMount(){
      if (!firebase.apps.length) {
        firebase.initializeApp({
          clientId: 'my client id-',
          appId: 'my app id',
          apiKey: "my api key",
          authDomain: "fcm-auth domain
          databaseURL: "database url
          projectId: "fcm-app-id,
          storageBucket: "fcm-app-BUCKET
          messagingSenderId: "sender id
        });
      }
      firebase.messaging().getToken()
        .then(fcmToken => {
          if (fcmToken) {
          console.log(fcmToken)
          } else {
            console.log("no token")
          }
      });

      firebase.messaging().hasPermission()
        .then(enabled => {
        if (enabled) {
          // user has permissions
          console.log("user has permission")
        } else {
          // user doesn't have permission
          console.log("user don't has permission")
        }
  });
    }
render() {
    return (
      <View style={styles.container}>
        <Text style={styles.welcome}>Welcome to React Native!</Text>
        <Text style={styles.instructions}>To get started, edit App.js</Text>
        <Text style={styles.instructions}>{instructions}</Text>
      </View>
    );
  }
}
const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
  },
  welcome: {
    fontSize: 20,
    textAlign: 'center',
    margin: 10,
  },
  instructions: {
    textAlign: 'center',
    color: '#333333',
    marginBottom: 5,
  },
});

AndroidManifest.xml

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.fcm">

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
    <uses-permission android:name="android.permission.VIBRATE" />

    <application
      android:name=".MainApplication"
      android:label="@string/app_name"
      android:icon="@mipmap/ic_launcher"
      android:allowBackup="false"
      android:theme="@style/AppTheme">
      <activity
        android:name=".MainActivity"
        android:label="@string/app_name"
        android:configChanges="keyboard|keyboardHidden|orientation|screenSize"
        android:windowSoftInputMode="adjustResize" android:launchMode="singleTop">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
      </activity>
      <activity android:name="com.facebook.react.devsupport.DevSettingsActivity" />
        <service android:name="io.invertase.firebase.messaging.RNFirebaseMessagingService">
            <intent-filter>
                <action android:name="com.google.firebase.MESSAGING_EVENT" />
            </intent-filter>
        </service>
        <service android:name="io.invertase.firebase.messaging.RNFirebaseInstanceIdService">
            <intent-filter>
                <action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
            </intent-filter>
        </service>
        <service android:name="io.invertase.firebase.messaging.RNFirebaseBackgroundMessagingService" />
    </application>

</manifest>

app/build.gradle

apply plugin: "com.android.application"

import com.android.build.OutputFile

/**
 * The react.gradle file registers a task for each build variant (e.g. bundleDebugJsAndAssets
 * and bundleReleaseJsAndAssets).
 * These basically call `react-native bundle` with the correct arguments during the Android build
 * cycle. By default, bundleDebugJsAndAssets is skipped, as in debug/dev mode we prefer to load the
 * bundle directly from the development server. Below you can see all the possible configurations
 * and their defaults. If you decide to add a configuration block, make sure to add it before the
 * `apply from: "../../node_modules/react-native/react.gradle"` line.
 *
 * project.ext.react = [
 *   // the name of the generated asset file containing your JS bundle
 *   bundleAssetName: "index.android.bundle",
 *
 *   // the entry file for bundle generation
 *   entryFile: "index.android.js",
 *
 *   // whether to bundle JS and assets in debug mode
 *   bundleInDebug: false,
 *
 *   // whether to bundle JS and assets in release mode
 *   bundleInRelease: true,
 *
 *   // whether to bundle JS and assets in another build variant (if configured).
 *   // See http://tools.android.com/tech-docs/new-build-system/user-guide#TOC-Build-Variants
 *   // The configuration property can be in the following formats
 *   //         'bundleIn${productFlavor}${buildType}'
 *   //         'bundleIn${buildType}'
 *   // bundleInFreeDebug: true,
 *   // bundleInPaidRelease: true,
 *   // bundleInBeta: true,
 *
 *   // whether to disable dev mode in custom build variants (by default only disabled in release)
 *   // for example: to disable dev mode in the staging build type (if configured)
 *   devDisabledInStaging: true,
 *   // The configuration property can be in the following formats
 *   //         'devDisabledIn${productFlavor}${buildType}'
 *   //         'devDisabledIn${buildType}'
 *
 *   // the root of your project, i.e. where "package.json" lives
 *   root: "../../",
 *
 *   // where to put the JS bundle asset in debug mode
 *   jsBundleDirDebug: "$buildDir/intermediates/assets/debug",
 *
 *   // where to put the JS bundle asset in release mode
 *   jsBundleDirRelease: "$buildDir/intermediates/assets/release",
 *
 *   // where to put drawable resources / React Native assets, e.g. the ones you use via
 *   // require('./image.png')), in debug mode
 *   resourcesDirDebug: "$buildDir/intermediates/res/merged/debug",
 *
 *   // where to put drawable resources / React Native assets, e.g. the ones you use via
 *   // require('./image.png')), in release mode
 *   resourcesDirRelease: "$buildDir/intermediates/res/merged/release",
 *
 *   // by default the gradle tasks are skipped if none of the JS files or assets change; this means
 *   // that we don't look at files in android/ or ios/ to determine whether the tasks are up to
 *   // date; if you have any other folders that you want to ignore for performance reasons (gradle
 *   // indexes the entire tree), add them here. Alternatively, if you have JS files in android/
 *   // for example, you might want to remove it from here.
 *   inputExcludes: ["android/**", "ios/**"],
 *
 *   // override which node gets called and with what additional arguments
 *   nodeExecutableAndArgs: ["node"],
 *
 *   // supply additional arguments to the packager
 *   extraPackagerArgs: []
 * ]
 */

project.ext.react = [
    entryFile: "index.js"
]

apply from: "../../node_modules/react-native/react.gradle"

/**
 * Set this to true to create two separate APKs instead of one:
 *   - An APK that only works on ARM devices
 *   - An APK that only works on x86 devices
 * The advantage is the size of the APK is reduced by about 4MB.
 * Upload all the APKs to the Play Store and people will download
 * the correct one based on the CPU architecture of their device.
 */
def enableSeparateBuildPerCPUArchitecture = false

/**
 * Run Proguard to shrink the Java bytecode in release builds.
 */
def enableProguardInReleaseBuilds = false

android {
    compileSdkVersion rootProject.ext.compileSdkVersion
    buildToolsVersion rootProject.ext.buildToolsVersion

    defaultConfig {
        applicationId "com.fcm"
        minSdkVersion rootProject.ext.minSdkVersion
        targetSdkVersion rootProject.ext.targetSdkVersion
        versionCode 1
        versionName "1.0"
        ndk {
            abiFilters "armeabi-v7a", "x86"
        }
    }
    signingConfigs {
        release {
            if (project.hasProperty('MYAPP_RELEASE_STORE_FILE')) {
                storeFile file(MYAPP_RELEASE_STORE_FILE)
                storePassword MYAPP_RELEASE_STORE_PASSWORD
                keyAlias MYAPP_RELEASE_KEY_ALIAS
                keyPassword MYAPP_RELEASE_KEY_PASSWORD
            }
        }
    }
    splits {
        abi {
            reset()
            enable enableSeparateBuildPerCPUArchitecture
            universalApk false  // If true, also generate a universal APK
            include "armeabi-v7a", "x86"
        }
    }
    buildTypes {
        release {
            minifyEnabled enableProguardInReleaseBuilds
            proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"
            signingConfig signingConfigs.release
        }
    }
    // applicationVariants are e.g. debug, release
    applicationVariants.all { variant ->
        variant.outputs.each { output ->
            // For each separate APK per architecture, set a unique version code as described here:
            // http://tools.android.com/tech-docs/new-build-system/user-guide/apk-splits
            def versionCodes = ["armeabi-v7a":1, "x86":2]
            def abi = output.getFilter(OutputFile.ABI)
            if (abi != null) {  // null for the universal-debug, universal-release variants
                output.versionCodeOverride =
                        versionCodes.get(abi) * 1048576 + defaultConfig.versionCode
            }
        }
    }
}

dependencies {
    implementation project(':react-native-firebase')
    implementation fileTree(dir: "libs", include: ["*.jar"])
    implementation "com.android.support:appcompat-v7:${rootProject.ext.supportLibVersion}"
    implementation "com.facebook.react:react-native:+"  // From node_modules
    implementation "com.google.android.gms:play-services-base:15.0.0"
    implementation "com.google.firebase:firebase-core:15.0.2"
    implementation "com.google.firebase:firebase-messaging:15.0.2"
    implementation 'me.leolin:ShortcutBadger:1.1.21@aar'
}

// Run this once to be able to run the application with BUCK
// puts all compile dependencies into folder libs for BUCK to use
task copyDownloadableDepsToLibs(type: Copy) {
    from configurations.compile
    into 'libs'
}


text:
Q: Using Select Query inside a while loop in php I am trying to Print some data from 2 tables when i try to execute 2nd select query inside while loop its not showing any result
My query is
$query=mysql_query("SELECT * FROM buses");
echo "
";
echo "
";
echo "Sno	";
echo "Route #	";
echo "Bus _Type	";
echo "Timing	";
echo "From	";
echo "
";
while($row=mysql_fetch_array($query)){
echo "
";
echo ""."".$row['sno'].""."	";
echo ""."".$row['Route'].""."	";
echo ""."".$row['Bus_type'].""."	";
echo ""."".substr($row['Timing'],0,5).""."	";
$route=$row['Route'];
$query2=mysql_query("SELECT fromcity FROM routes WHERE Route= '$route' ");
$row2=mysql_fetch_array($query2);
echo ""."".$row2['fromcity'].""."	";

routes Table

buses table

Result

A: You can continue with your solution but for efficiency sake, you shouldn't be doing a SELECT inside a loop, you should be using an SQL JOIN.
Your query should be joining the two tables on the Route field:
SELECT * FROM buses b
INNER JOIN routes r ON b.Route = r.Route;

No extra queries will be needed inside the loop as you'll have access to the fromcity from this query.  You may want to specifically declare the fields in the SELECT rather than using *.


text:
Q: Particular solution of the SOD $D^2y + 6 Dy + 10y = 2 \sin{2x}$
How can we find the particular solution to the following D.E?
$$\frac{\text{d}^2y}{\text{d}x^2} + 6 \frac{\text{d}y}{\text{d}x} + 10y = 2 \sin{2x} \text{ —— (I)} $$
$\text{ at } x = 0, y = \frac{5}{2} \text{——} $ provided $\frac{\text{d}y}{\text{d}x} = \frac{1}{2}$.

Recall that the equations with the form $y'' + P_1y' + P_2y = 0$ are called linear SOD with constant coefficients, where $P_1$ and $P_2$ are constants.
The cited problem is partially identical to the differential equations with constant coefficients, except the RHS is nonzero. In my attempt, taking the trial solution $y = e^{mx}$, we have:
$$Dy = m \cdot e^{mx} \text{ and } D^2y = m^2 \cdot e^{mx}$$
Now, substituting it in (I), we have:
$$e^{mx} (m^2 + 6m + 10) = 2 \sin{2x}$$
We have either $e^{mx} = 2\sin{2x}$ or $m^2 + 6m + 10 = 2\sin{2x}.$

The problem is that I have no idea how to proceed next because:

*

*$e^{mx}$ might not be ignored since RHS is nonzero.

*$m^2 + 6m + 10$ cannot be factorized. Using the quadratic formula, we have $m = −3 \pm i$. Let these values be $\alpha$ and $\beta$ respectively.
When $m$ is a conjugate complex quantities, we define the solution to such ODEs as: $y = Ae^{\alpha x} \cos{(\beta x + B)}$, where $\alpha$ and $\beta$ are the solutions.

A: For the particular solution $y_p(x)$ of the ODE we proceed as follows.
If $$(D^2+6D+10)y_p=2\sin ax \implies y_p= \frac{2\sin 2x}{-2^2+6D+10}=\frac{1}{3} \frac{\sin 2x}{D+1}$$ $$\implies y_p=\frac{1}{3} \frac{D-1}{D^2-1}\sin 2x$$
$$\implies y_p=\frac{1}{3} \frac{D-1}{-2^2-1}\sin 2x=-\frac{1}{15} (D-1)\sin 2x=-\frac{1}{15} (2\cos 2x- \sin 2x)$$
One may check that it satisfies the ODE.
Edit
Now find the general by putting $y=e^{mx}$ in the homogeneous eq.
$$y''+6y'+10y=0 \implies m^2+6m+10=0 \implies m=-3\pm i$$
This gives the general solution $$y_g(x)=e^{-3x}(P \sin x+ Q\cos x)$$
Now the total solution $$y=e^{-3x}(P\sin x+ Q \cos x)-(1/15)(2\cos 2x -\sin 2x)$$ needs to satisfy the given conditions to determine the values of $P$ and $Q$. Finally. by imposing $y(0)=5/2, y'(0)=1/2$, we get $p=248/30, q=79/30$.