navigator.language list of all languages

Question: Where i can see the list of languages and their codes?
I want to compare languages and auto-select required language in template.
Are they cross-browser equal?
Any other solution?
Comment: FYI: `navigator.language` for Firefox: http://dxr.mozilla.org/mozilla-central/source/dom/base/Navigator.cpp#l337 (quite straightforward to read), Chromium: https://code.google.com/p/chromium/codesearch#chromium/src/third_party/WebKit/Source/core/page/Navigator.cpp&l=89 (follow the tracks of `defaultLanguage` to `Language.cpp` and continue reading)
Answer: For copy and pasting purposes:
["af", "af-NA", "af-ZA", "agq", "agq-CM", "ak", "ak-GH", "am",
"am-ET", "ar", "ar-001", "ar-AE", "ar-BH", "ar-DJ", "ar-DZ",
"ar-EG", "ar-EH", "ar-ER", "ar-IL", "ar-IQ", "ar-JO", "ar-KM",
"ar-KW", "ar-LB", "ar-LY", "ar-MA", "ar-MR", "ar-OM", "ar-PS",
"ar-QA", "ar-SA", "ar-SD", "ar-SO", "ar-SS", "ar-SY", "ar-TD",
"ar-TN", "ar-YE", "as", "as-IN", "asa", "asa-TZ", "ast", "ast-ES",
"az", "az-Cyrl", "az-Cyrl-AZ", "az-Latn", "az-Latn-AZ", "bas",
"bas-CM", "be", "be-BY", "bem", "bem-ZM", "bez", "bez-TZ", "bg",
"bg-BG", "bm", "bm-ML", "bn", "bn-BD", "bn-IN", "bo", "bo-CN",
"bo-IN", "br", "br-FR", "brx", "brx-IN", "bs", "bs-Cyrl",
"bs-Cyrl-BA", "bs-Latn", "bs-Latn-BA", "ca", "ca-AD", "ca-ES",
"ca-FR", "ca-IT", "ccp", "ccp-BD", "ccp-IN", "ce", "ce-RU", "cgg",
"cgg-UG", "chr", "chr-US", "ckb", "ckb-IQ", "ckb-IR", "cs",
"cs-CZ", "cy", "cy-GB", "da", "da-DK", "da-GL", "dav", "dav-KE",
"de", "de-AT", "de-BE", "de-CH", "de-DE", "de-IT", "de-LI",
"de-LU", "dje", "dje-NE", "dsb", "dsb-DE", "dua", "dua-CM", "dyo",
"dyo-SN", "dz", "dz-BT", "ebu", "ebu-KE", "ee", "ee-GH", "ee-TG",
"el", "el-CY", "el-GR", "en", "en-001", "en-150", "en-AG",
"en-AI", "en-AS", "en-AT", "en-AU", "en-BB", "en-BE", "en-BI",
"en-BM", "en-BS", "en-BW", "en-BZ", "en-CA", "en-CC", "en-CH",
"en-CK", "en-CM", "en-CX", "en-CY", "en-DE", "en-DG", "en-DK",
"en-DM", "en-ER", "en-FI", "en-FJ", "en-FK", "en-FM", "en-GB",
"en-GD", "en-GG", "en-GH", "en-GI", "en-GM", "en-GU", "en-GY",
"en-HK", "en-IE", "en-IL", "en-IM", "en-IN", "en-IO", "en-JE",
"en-JM", "en-KE", "en-KI", "en-KN", "en-KY", "en-LC", "en-LR",
"en-LS", "en-MG", "en-MH", "en-MO", "en-MP", "en-MS", "en-MT",
"en-MU", "en-MW", "en-MY", "en-NA", "en-NF", "en-NG", "en-NL",
"en-NR", "en-NU", "en-NZ", "en-PG", "en-PH", "en-PK", "en-PN",
"en-PR", "en-PW", "en-RW", "en-SB", "en-SC", "en-SD", "en-SE",
"en-SG", "en-SH", "en-SI", "en-SL", "en-SS", "en-SX", "en-SZ",
"en-TC", "en-TK", "en-TO", "en-TT", "en-TV", "en-TZ", "en-UG",
"en-UM", "en-US", "en-US-POSIX", "en-VC", "en-VG", "en-VI",
"en-VU", "en-WS", "en-ZA", "en-ZM", "en-ZW", "eo", "es", "es-419",
"es-AR", "es-BO", "es-BR", "es-BZ", "es-CL", "es-CO", "es-CR",
"es-CU", "es-DO", "es-EA", "es-EC", "es-ES", "es-GQ", "es-GT",
"es-HN", "es-IC", "es-MX", "es-NI", "es-PA", "es-PE", "es-PH",
"es-PR", "es-PY", "es-SV", "es-US", "es-UY", "es-VE", "et",
"et-EE", "eu", "eu-ES", "ewo", "ewo-CM", "fa", "fa-AF", "fa-IR",
"ff", "ff-CM", "ff-GN", "ff-MR", "ff-SN", "fi", "fi-FI", "fil",
"fil-PH", "fo", "fo-DK", "fo-FO", "fr", "fr-BE", "fr-BF", "fr-BI",
"fr-BJ", "fr-BL", "fr-CA", "fr-CD", "fr-CF", "fr-CG", "fr-CH",
"fr-CI", "fr-CM", "fr-DJ", "fr-DZ", "fr-FR", "fr-GA", "fr-GF",
"fr-GN", "fr-GP", "fr-GQ", "fr-HT", "fr-KM", "fr-LU", "fr-MA",
"fr-MC", "fr-MF", "fr-MG", "fr-ML", "fr-MQ", "fr-MR", "fr-MU",
"fr-NC", "fr-NE", "fr-PF", "fr-PM", "fr-RE", "fr-RW", "fr-SC",
"fr-SN", "fr-SY", "fr-TD", "fr-TG", "fr-TN", "fr-VU", "fr-WF",
"fr-YT", "fur", "fur-IT", "fy", "fy-NL", "ga", "ga-IE", "gd",
"gd-GB", "gl", "gl-ES", "gsw", "gsw-CH", "gsw-FR", "gsw-LI", "gu",
"gu-IN", "guz", "guz-KE", "gv", "gv-IM", "ha", "ha-GH", "ha-NE",
"ha-NG", "haw", "haw-US", "he", "he-IL", "hi", "hi-IN", "hr",
"hr-BA", "hr-HR", "hsb", "hsb-DE", "hu", "hu-HU", "hy", "hy-AM",
"id", "id-ID", "ig", "ig-NG", "ii", "ii-CN", "is", "is-IS", "it",
"it-CH", "it-IT", "it-SM", "it-VA", "ja", "ja-JP", "jgo",
"jgo-CM", "jmc", "jmc-TZ", "ka", "ka-GE", "kab", "kab-DZ", "kam",
"kam-KE", "kde", "kde-TZ", "kea", "kea-CV", "khq", "khq-ML", "ki",
"ki-KE", "kk", "kk-KZ", "kkj", "kkj-CM", "kl", "kl-GL", "kln",
"kln-KE", "km", "km-KH", "kn", "kn-IN", "ko", "ko-KP", "ko-KR",
"kok", "kok-IN", "ks", "ks-IN", "ksb", "ksb-TZ", "ksf", "ksf-CM",
"ksh", "ksh-DE", "kw", "kw-GB", "ky", "ky-KG", "lag", "lag-TZ",
"lb", "lb-LU", "lg", "lg-UG", "lkt", "lkt-US", "ln", "ln-AO",
"ln-CD", "ln-CF", "ln-CG", "lo", "lo-LA", "lrc", "lrc-IQ",
"lrc-IR", "lt", "lt-LT", "lu", "lu-CD", "luo", "luo-KE", "luy",
"luy-KE", "lv", "lv-LV", "mas", "mas-KE", "mas-TZ", "mer",
"mer-KE", "mfe", "mfe-MU", "mg", "mg-MG", "mgh", "mgh-MZ", "mgo",
"mgo-CM", "mk", "mk-MK", "ml", "ml-IN", "mn", "mn-MN", "mr",
"mr-IN", "ms", "ms-BN", "ms-MY", "ms-SG", "mt", "mt-MT", "mua",
"mua-CM", "my", "my-MM", "mzn", "mzn-IR", "naq", "naq-NA", "nb",
"nb-NO", "nb-SJ", "nd", "nd-ZW", "nds", "nds-DE", "nds-NL", "ne",
"ne-IN", "ne-NP", "nl", "nl-AW", "nl-BE", "nl-BQ", "nl-CW",
"nl-NL", "nl-SR", "nl-SX", "nmg", "nmg-CM", "nn", "nn-NO", "nnh",
"nnh-CM", "nus", "nus-SS", "nyn", "nyn-UG", "om", "om-ET",
"om-KE", "or", "or-IN", "os", "os-GE", "os-RU", "pa", "pa-Arab",
"pa-Arab-PK", "pa-Guru", "pa-Guru-IN", "pl", "pl-PL", "ps",
"ps-AF", "pt", "pt-AO", "pt-BR", "pt-CH", "pt-CV", "pt-GQ",
"pt-GW", "pt-LU", "pt-MO", "pt-MZ", "pt-PT", "pt-ST", "pt-TL",
"qu", "qu-BO", "qu-EC", "qu-PE", "rm", "rm-CH", "rn", "rn-BI",
"ro", "ro-MD", "ro-RO", "rof", "rof-TZ", "ru", "ru-BY", "ru-KG",
"ru-KZ", "ru-MD", "ru-RU", "ru-UA", "rw", "rw-RW", "rwk",
"rwk-TZ", "sah", "sah-RU", "saq", "saq-KE", "sbp", "sbp-TZ", "se",
"se-FI", "se-NO", "se-SE", "seh", "seh-MZ", "ses", "ses-ML", "sg",
"sg-CF", "shi", "shi-Latn", "shi-Latn-MA", "shi-Tfng",
"shi-Tfng-MA", "si", "si-LK", "sk", "sk-SK", "sl", "sl-SI", "smn",
"smn-FI", "sn", "sn-ZW", "so", "so-DJ", "so-ET", "so-KE", "so-SO",
"sq", "sq-AL", "sq-MK", "sq-XK", "sr", "sr-Cyrl", "sr-Cyrl-BA",
"sr-Cyrl-ME", "sr-Cyrl-RS", "sr-Cyrl-XK", "sr-Latn", "sr-Latn-BA",
"sr-Latn-ME", "sr-Latn-RS", "sr-Latn-XK", "sv", "sv-AX", "sv-FI",
"sv-SE", "sw", "sw-CD", "sw-KE", "sw-TZ", "sw-UG", "ta", "ta-IN",
"ta-LK", "ta-MY", "ta-SG", "te", "te-IN", "teo", "teo-KE",
"teo-UG", "tg", "tg-TJ", "th", "th-TH", "ti", "ti-ER", "ti-ET",
"to", "to-TO", "tr", "tr-CY", "tr-TR", "tt", "tt-RU", "twq",
"twq-NE", "tzm", "tzm-MA", "ug", "ug-CN", "uk", "uk-UA", "ur",
"ur-IN", "ur-PK", "uz", "uz-Arab", "uz-Arab-AF", "uz-Cyrl",
"uz-Cyrl-UZ", "uz-Latn", "uz-Latn-UZ", "vai", "vai-Latn",
"vai-Latn-LR", "vai-Vaii", "vai-Vaii-LR", "vi", "vi-VN", "vun",
"vun-TZ", "wae", "wae-CH", "wo", "wo-SN", "xog", "xog-UG", "yav",
"yav-CM", "yi", "yi-001", "yo", "yo-BJ", "yo-NG", "yue",
"yue-Hans", "yue-Hans-CN", "yue-Hant", "yue-Hant-HK", "zgh",
"zgh-MA", "zh", "zh-Hans", "zh-Hans-CN", "zh-Hans-HK",
"zh-Hans-MO", "zh-Hans-SG", "zh-Hant", "zh-Hant-HK", "zh-Hant-MO",
"zh-Hant-TW", "zu", "zu-ZA"];

Comment: Careful if you are just fast copying. It's just a summarized list of the possible values. A most accurately answer is from @Clement Herreman. For example, I live in Catalonia (Spain) and my result is ca_ES. I found they have an API which returns a JSON with all the codes for copying and pasting. https://www.localeplanet.com/api/codelist.json
Comment: take care this list is outdated! "it-IT" is also missing
Comment: @Raikish The link you provided seems also not accurate. it doesn't include `zh-CN`, which is the result from Chrome 108 in China Mainland.
Comment: @lyh543 I don't know if it is exactly the same, but I think it is the called zh-Hans-CN
Comment: @Raikish `zh-Hans-CN` is more specific, but my Chrome doesn't return this string.
Answer: This list of languages is defined by the ISO : http://en.wikipedia.org/wiki/List_of_ISO_639-1_codes
Example : be for belarus, fr for french.
If you are looking for something more specific, those are not languages, but locale, e.g. "Brazilian Portuguese", or "Canadian French". Those can be found in the ICU project: https://www.localeplanet.com/icu/
Example : pt_BR for Portuguese (Brazil) vs pt_CV for Portuguese (Cape Verde)
Those are the ones available for copy/pasting in dYale answer.
Comment: this does not answers fully, in the link provided one can find language codes, but not country-specific language codes, like fr-fr or fr-ca
Comment: So it's 639-1 column? Is it's the same in all browsers?
Comment: I guess yes, tho I can't 100% certify it.
Comment: I would say the 639-1 column is the one Javascript uses. I asked a few people in other countries to alert out their code and it matched the values in 639-1.
Comment: That is wrong. Mine is pt-BR and is not listed there.
Comment: @LucasBustamante pt_BR is a locale, not a language. pt is the language of the pt_BR locale. See https://www.localeplanet.com/icu/ where they separate those two concepts. I edited my answer to add those :)
Comment: @Clement Herreman thanks for clarifying, I'll check out these two concepts
Answer: If anyone also needs the name of the language for user selection (created from here using query selector so it's accurate):
[
    ['Abkhazian', 'ab'],
    ['Afar', 'aa'],
    ['Afrikaans', 'af'],
    ['Akan', 'ak'],
    ['Albanian', 'sq'],
    ['Amharic', 'am'],
    ['Arabic', 'ar'],
    ['Aragonese', 'an'],
    ['Armenian', 'hy'],
    ['Assamese', 'as'],
    ['Avaric', 'av'],
    ['Avestan', 'ae'],
    ['Aymara', 'ay'],
    ['Azerbaijani', 'az'],
    ['Bambara', 'bm'],
    ['Bashkir', 'ba'],
    ['Basque', 'eu'],
    ['Belarusian', 'be'],
    ['Bengali (Bangla)', 'bn'],
    ['Bihari', 'bh'],
    ['Bislama', 'bi'],
    ['Bosnian', 'bs'],
    ['Breton', 'br'],
    ['Bulgarian', 'bg'],
    ['Burmese', 'my'],
    ['Catalan', 'ca'],
    ['Chamorro', 'ch'],
    ['Chechen', 'ce'],
    ['Chichewa, Chewa, Nyanja', 'ny'],
    ['Chinese', 'zh'],
    ['Chinese (Simplified)', 'zh-Hans'],
    ['Chinese (Traditional)', 'zh-Hant'],
    ['Chuvash', 'cv'],
    ['Cornish', 'kw'],
    ['Corsican', 'co'],
    ['Cree', 'cr'],
    ['Croatian', 'hr'],
    ['Czech', 'cs'],
    ['Danish', 'da'],
    ['Divehi, Dhivehi, Maldivian', 'dv'],
    ['Dutch', 'nl'],
    ['Dzongkha', 'dz'],
    ['English', 'en'],
    ['Esperanto', 'eo'],
    ['Estonian', 'et'],
    ['Ewe', 'ee'],
    ['Faroese', 'fo'],
    ['Fijian', 'fj'],
    ['Finnish', 'fi'],
    ['French', 'fr'],
    ['Fula, Fulah, Pulaar, Pular', 'ff'],
    ['Galician', 'gl'],
    ['Gaelic (Scottish)', 'gd'],
    ['Gaelic (Manx)', 'gv'],
    ['Georgian', 'ka'],
    ['German', 'de'],
    ['Greek', 'el'],
    ['Greenlandic', 'kl'],
    ['Guarani', 'gn'],
    ['Gujarati', 'gu'],
    ['Haitian Creole', 'ht'],
    ['Hausa', 'ha'],
    ['Hebrew', 'he'],
    ['Herero', 'hz'],
    ['Hindi', 'hi'],
    ['Hiri Motu', 'ho'],
    ['Hungarian', 'hu'],
    ['Icelandic', 'is'],
    ['Ido', 'io'],
    ['Igbo', 'ig'],
    ['Indonesian', 'id, in'],
    ['Interlingua', 'ia'],
    ['Interlingue', 'ie'],
    ['Inuktitut', 'iu'],
    ['Inupiak', 'ik'],
    ['Irish', 'ga'],
    ['Italian', 'it'],
    ['Japanese', 'ja'],
    ['Javanese', 'jv'],
    ['Kalaallisut, Greenlandic', 'kl'],
    ['Kannada', 'kn'],
    ['Kanuri', 'kr'],
    ['Kashmiri', 'ks'],
    ['Kazakh', 'kk'],
    ['Khmer', 'km'],
    ['Kikuyu', 'ki'],
    ['Kinyarwanda (Rwanda)', 'rw'],
    ['Kirundi', 'rn'],
    ['Kyrgyz', 'ky'],
    ['Komi', 'kv'],
    ['Kongo', 'kg'],
    ['Korean', 'ko'],
    ['Kurdish', 'ku'],
    ['Kwanyama', 'kj'],
    ['Lao', 'lo'],
    ['Latin', 'la'],
    ['Latvian (Lettish)', 'lv'],
    ['Limburgish ( Limburger)', 'li'],
    ['Lingala', 'ln'],
    ['Lithuanian', 'lt'],
    ['Luga-Katanga', 'lu'],
    ['Luganda, Ganda', 'lg'],
    ['Luxembourgish', 'lb'],
    ['Manx', 'gv'],
    ['Macedonian', 'mk'],
    ['Malagasy', 'mg'],
    ['Malay', 'ms'],
    ['Malayalam', 'ml'],
    ['Maltese', 'mt'],
    ['Maori', 'mi'],
    ['Marathi', 'mr'],
    ['Marshallese', 'mh'],
    ['Moldavian', 'mo'],
    ['Mongolian', 'mn'],
    ['Nauru', 'na'],
    ['Navajo', 'nv'],
    ['Ndonga', 'ng'],
    ['Northern Ndebele', 'nd'],
    ['Nepali', 'ne'],
    ['Norwegian', 'no'],
    ['Norwegian bokmål', 'nb'],
    ['Norwegian nynorsk', 'nn'],
    ['Nuosu', 'ii'],
    ['Occitan', 'oc'],
    ['Ojibwe', 'oj'],
    ['Old Church Slavonic, Old Bulgarian', 'cu'],
    ['Oriya', 'or'],
    ['Oromo (Afaan Oromo)', 'om'],
    ['Ossetian', 'os'],
    ['Pāli', 'pi'],
    ['Pashto, Pushto', 'ps'],
    ['Persian (Farsi)', 'fa'],
    ['Polish', 'pl'],
    ['Portuguese', 'pt'],
    ['Punjabi (Eastern)', 'pa'],
    ['Quechua', 'qu'],
    ['Romansh', 'rm'],
    ['Romanian', 'ro'],
    ['Russian', 'ru'],
    ['Sami', 'se'],
    ['Samoan', 'sm'],
    ['Sango', 'sg'],
    ['Sanskrit', 'sa'],
    ['Serbian', 'sr'],
    ['Serbo-Croatian', 'sh'],
    ['Sesotho', 'st'],
    ['Setswana', 'tn'],
    ['Shona', 'sn'],
    ['Sichuan Yi', 'ii'],
    ['Sindhi', 'sd'],
    ['Sinhalese', 'si'],
    ['Siswati', 'ss'],
    ['Slovak', 'sk'],
    ['Slovenian', 'sl'],
    ['Somali', 'so'],
    ['Southern Ndebele', 'nr'],
    ['Spanish', 'es'],
    ['Sundanese', 'su'],
    ['Swahili (Kiswahili)', 'sw'],
    ['Swati', 'ss'],
    ['Swedish', 'sv'],
    ['Tagalog', 'tl'],
    ['Tahitian', 'ty'],
    ['Tajik', 'tg'],
    ['Tamil', 'ta'],
    ['Tatar', 'tt'],
    ['Telugu', 'te'],
    ['Thai', 'th'],
    ['Tibetan', 'bo'],
    ['Tigrinya', 'ti'],
    ['Tonga', 'to'],
    ['Tsonga', 'ts'],
    ['Turkish', 'tr'],
    ['Turkmen', 'tk'],
    ['Twi', 'tw'],
    ['Uyghur', 'ug'],
    ['Ukrainian', 'uk'],
    ['Urdu', 'ur'],
    ['Uzbek', 'uz'],
    ['Venda', 've'],
    ['Vietnamese', 'vi'],
    ['Volapük', 'vo'],
    ['Wallon', 'wa'],
    ['Welsh', 'cy'],
    ['Wolof', 'wo'],
    ['Western Frisian', 'fy'],
    ['Xhosa', 'xh'],
    ['Yiddish', 'yi, ji'],
    ['Yoruba', 'yo'],
    ['Zhuang, Chuang', 'za'],
    ['Zulu', 'zu'],
]

Answer: In some case, navigator.language can return something like "sr-Latn-RS"
According to MDN (https://developer.mozilla.org/en-US/docs/Web/API/NavigatorLanguage/language) navigator.language can return every value valid in BCP-47: https://tools.ietf.org/html/bcp47
Answer: Or an array of objects with "name" and "code" keys
[
  { code: 'ab', name: 'Abkhazian' },
  { code: 'aa', name: 'Afar' },
  { code: 'af', name: 'Afrikaans' },
  { code: 'ak', name: 'Akan' },
  { code: 'sq', name: 'Albanian' },
  { code: 'am', name: 'Amharic' },
  { code: 'ar', name: 'Arabic' },
  { code: 'an', name: 'Aragonese' },
  { code: 'hy', name: 'Armenian' },
  { code: 'as', name: 'Assamese' },
  { code: 'av', name: 'Avaric' },
  { code: 'ae', name: 'Avestan' },
  { code: 'ay', name: 'Aymara' },
  { code: 'az', name: 'Azerbaijani' },
  { code: 'bm', name: 'Bambara' },
  { code: 'ba', name: 'Bashkir' },
  { code: 'eu', name: 'Basque' },
  { code: 'be', name: 'Belarusian' },
  { code: 'bn', name: 'Bengali (Bangla)' },
  { code: 'bh', name: 'Bihari' },
  { code: 'bi', name: 'Bislama' },
  { code: 'bs', name: 'Bosnian' },
  { code: 'br', name: 'Breton' },
  { code: 'bg', name: 'Bulgarian' },
  { code: 'my', name: 'Burmese' },
  { code: 'ca', name: 'Catalan' },
  { code: 'ch', name: 'Chamorro' },
  { code: 'ce', name: 'Chechen' },
  { code: 'ny', name: 'Chichewa, Chewa, Nyanja' },
  { code: 'zh', name: 'Chinese' },
  { code: 'zh-Hans', name: 'Chinese (Simplified)' },
  { code: 'zh-Hant', name: 'Chinese (Traditional)' },
  { code: 'cv', name: 'Chuvash' },
  { code: 'kw', name: 'Cornish' },
  { code: 'co', name: 'Corsican' },
  { code: 'cr', name: 'Cree' },
  { code: 'hr', name: 'Croatian' },
  { code: 'cs', name: 'Czech' },
  { code: 'da', name: 'Danish' },
  { code: 'dv', name: 'Divehi, Dhivehi, Maldivian' },
  { code: 'nl', name: 'Dutch' },
  { code: 'dz', name: 'Dzongkha' },
  { code: 'en', name: 'English' },
  { code: 'eo', name: 'Esperanto' },
  { code: 'et', name: 'Estonian' },
  { code: 'ee', name: 'Ewe' },
  { code: 'fo', name: 'Faroese' },
  { code: 'fj', name: 'Fijian' },
  { code: 'fi', name: 'Finnish' },
  { code: 'fr', name: 'French' },
  { code: 'ff', name: 'Fula, Fulah, Pulaar, Pular' },
  { code: 'gl', name: 'Galician' },
  { code: 'gd', name: 'Gaelic (Scottish)' },
  { code: 'gv', name: 'Gaelic (Manx)' },
  { code: 'ka', name: 'Georgian' },
  { code: 'de', name: 'German' },
  { code: 'el', name: 'Greek' },
  { code: 'kl', name: 'Greenlandic' },
  { code: 'gn', name: 'Guarani' },
  { code: 'gu', name: 'Gujarati' },
  { code: 'ht', name: 'Haitian Creole' },
  { code: 'ha', name: 'Hausa' },
  { code: 'he', name: 'Hebrew' },
  { code: 'hz', name: 'Herero' },
  { code: 'hi', name: 'Hindi' },
  { code: 'ho', name: 'Hiri Motu' },
  { code: 'hu', name: 'Hungarian' },
  { code: 'is', name: 'Icelandic' },
  { code: 'io', name: 'Ido' },
  { code: 'ig', name: 'Igbo' },
  { code: 'id, in', name: 'Indonesian' },
  { code: 'ia', name: 'Interlingua' },
  { code: 'ie', name: 'Interlingue' },
  { code: 'iu', name: 'Inuktitut' },
  { code: 'ik', name: 'Inupiak' },
  { code: 'ga', name: 'Irish' },
  { code: 'it', name: 'Italian' },
  { code: 'ja', name: 'Japanese' },
  { code: 'jv', name: 'Javanese' },
  { code: 'kl', name: 'Kalaallisut, Greenlandic' },
  { code: 'kn', name: 'Kannada' },
  { code: 'kr', name: 'Kanuri' },
  { code: 'ks', name: 'Kashmiri' },
  { code: 'kk', name: 'Kazakh' },
  { code: 'km', name: 'Khmer' },
  { code: 'ki', name: 'Kikuyu' },
  { code: 'rw', name: 'Kinyarwanda (Rwanda)' },
  { code: 'rn', name: 'Kirundi' },
  { code: 'ky', name: 'Kyrgyz' },
  { code: 'kv', name: 'Komi' },
  { code: 'kg', name: 'Kongo' },
  { code: 'ko', name: 'Korean' },
  { code: 'ku', name: 'Kurdish' },
  { code: 'kj', name: 'Kwanyama' },
  { code: 'lo', name: 'Lao' },
  { code: 'la', name: 'Latin' },
  { code: 'lv', name: 'Latvian (Lettish)' },
  { code: 'li', name: 'Limburgish ( Limburger)' },
  { code: 'ln', name: 'Lingala' },
  { code: 'lt', name: 'Lithuanian' },
  { code: 'lu', name: 'Luga-Katanga' },
  { code: 'lg', name: 'Luganda, Ganda' },
  { code: 'lb', name: 'Luxembourgish' },
  { code: 'gv', name: 'Manx' },
  { code: 'mk', name: 'Macedonian' },
  { code: 'mg', name: 'Malagasy' },
  { code: 'ms', name: 'Malay' },
  { code: 'ml', name: 'Malayalam' },
  { code: 'mt', name: 'Maltese' },
  { code: 'mi', name: 'Maori' },
  { code: 'mr', name: 'Marathi' },
  { code: 'mh', name: 'Marshallese' },
  { code: 'mo', name: 'Moldavian' },
  { code: 'mn', name: 'Mongolian' },
  { code: 'na', name: 'Nauru' },
  { code: 'nv', name: 'Navajo' },
  { code: 'ng', name: 'Ndonga' },
  { code: 'nd', name: 'Northern Ndebele' },
  { code: 'ne', name: 'Nepali' },
  { code: 'no', name: 'Norwegian' },
  { code: 'nb', name: 'Norwegian bokmål' },
  { code: 'nn', name: 'Norwegian nynorsk' },
  { code: 'ii', name: 'Nuosu' },
  { code: 'oc', name: 'Occitan' },
  { code: 'oj', name: 'Ojibwe' },
  { code: 'cu', name: 'Old Church Slavonic, Old Bulgarian' },
  { code: 'or', name: 'Oriya' },
  { code: 'om', name: 'Oromo (Afaan Oromo)' },
  { code: 'os', name: 'Ossetian' },
  { code: 'pi', name: 'Pāli' },
  { code: 'ps', name: 'Pashto, Pushto' },
  { code: 'fa', name: 'Persian (Farsi)' },
  { code: 'pl', name: 'Polish' },
  { code: 'pt', name: 'Portuguese' },
  { code: 'pa', name: 'Punjabi (Eastern)' },
  { code: 'qu', name: 'Quechua' },
  { code: 'rm', name: 'Romansh' },
  { code: 'ro', name: 'Romanian' },
  { code: 'ru', name: 'Russian' },
  { code: 'se', name: 'Sami' },
  { code: 'sm', name: 'Samoan' },
  { code: 'sg', name: 'Sango' },
  { code: 'sa', name: 'Sanskrit' },
  { code: 'sr', name: 'Serbian' },
  { code: 'sh', name: 'Serbo-Croatian' },
  { code: 'st', name: 'Sesotho' },
  { code: 'tn', name: 'Setswana' },
  { code: 'sn', name: 'Shona' },
  { code: 'ii', name: 'Sichuan Yi' },
  { code: 'sd', name: 'Sindhi' },
  { code: 'si', name: 'Sinhalese' },
  { code: 'ss', name: 'Siswati' },
  { code: 'sk', name: 'Slovak' },
  { code: 'sl', name: 'Slovenian' },
  { code: 'so', name: 'Somali' },
  { code: 'nr', name: 'Southern Ndebele' },
  { code: 'es', name: 'Spanish' },
  { code: 'su', name: 'Sundanese' },
  { code: 'sw', name: 'Swahili (Kiswahili)' },
  { code: 'ss', name: 'Swati' },
  { code: 'sv', name: 'Swedish' },
  { code: 'tl', name: 'Tagalog' },
  { code: 'ty', name: 'Tahitian' },
  { code: 'tg', name: 'Tajik' },
  { code: 'ta', name: 'Tamil' },
  { code: 'tt', name: 'Tatar' },
  { code: 'te', name: 'Telugu' },
  { code: 'th', name: 'Thai' },
  { code: 'bo', name: 'Tibetan' },
  { code: 'ti', name: 'Tigrinya' },
  { code: 'to', name: 'Tonga' },
  { code: 'ts', name: 'Tsonga' },
  { code: 'tr', name: 'Turkish' },
  { code: 'tk', name: 'Turkmen' },
  { code: 'tw', name: 'Twi' },
  { code: 'ug', name: 'Uyghur' },
  { code: 'uk', name: 'Ukrainian' },
  { code: 'ur', name: 'Urdu' },
  { code: 'uz', name: 'Uzbek' },
  { code: 've', name: 'Venda' },
  { code: 'vi', name: 'Vietnamese' },
  { code: 'vo', name: 'Volapük' },
  { code: 'wa', name: 'Wallon' },
  { code: 'cy', name: 'Welsh' },
  { code: 'wo', name: 'Wolof' },
  { code: 'fy', name: 'Western Frisian' },
  { code: 'xh', name: 'Xhosa' },
  { code: 'yi, ji', name: 'Yiddish' },
  { code: 'yo', name: 'Yoruba' },
  { code: 'za', name: 'Zhuang, Chuang' },
  { code: 'zu', name: 'Zulu' },
];

Answer: If you need a json of commonly used locales:
{
  "locales": [
    {
      "name": "Afrikaans (South Africa)",
      "code": "af_ZA",
      "region": "South Africa"
    },
    {
      "name": "Albanian (Albania)",
      "code": "sq_AL",
      "region": "Albania"
    },
    {
      "name": "Arabic (Algeria)",
      "code": "ar_DZ",
      "region": "Algeria"
    },
    {
      "name": "Arabic (Bahrain)",
      "code": "ar_BH",
      "region": "Bahrain"
    },
    {
      "name": "Arabic (Egypt)",
      "code": "ar_EG",
      "region": "Egypt"
    },
    {
      "name": "Arabic (Iraq)",
      "code": "ar_IQ",
      "region": "Iraq"
    },
    {
      "name": "Arabic (Jordan)",
      "code": "ar_JO",
      "region": "Jordan"
    },
    {
      "name": "Arabic (Kuwait)",
      "code": "ar_KW",
      "region": "Kuwait"
    },
    {
      "name": "Arabic (Lebanon)",
      "code": "ar_LB",
      "region": "Lebanon"
    },
    {
      "name": "Arabic (Libya)",
      "code": "ar_LY",
      "region": "Libya"
    },
    {
      "name": "Arabic (Morocco)",
      "code": "ar_MA",
      "region": "Morocco"
    },
    {
      "name": "Arabic (Oman)",
      "code": "ar_OM",
      "region": "Oman"
    },
    {
      "name": "Arabic (Qatar)",
      "code": "ar_QA",
      "region": "Qatar"
    },
    {
      "name": "Arabic (Saudi Arabia)",
      "code": "ar_SA",
      "region": "Saudi Arabia"
    },
    {
      "name": "Arabic (Sudan)",
      "code": "ar_SD",
      "region": "Sudan"
    },
    {
      "name": "Arabic (Syria)",
      "code": "ar_SY",
      "region": "Syria"
    },
    {
      "name": "Arabic (Tunisia)",
      "code": "ar_TN",
      "region": "Tunisia"
    },
    {
      "name": "Arabic (United Arab Emirates)",
      "code": "ar_AE",
      "region": "United Arab Emirates"
    },
    {
      "name": "Arabic (Yemen)",
      "code": "ar_YE",
      "region": "Yemen"
    },
    {
      "name": "Armenian (Armenia)",
      "code": "hy_AM",
      "region": "Armenia"
    },
    {
      "name": "Assamese (India)",
      "code": "as_IN",
      "region": "India"
    },
    {
      "name": "Azerbaijani (Azerbaijan)",
      "code": "az_AZ",
      "region": "Azerbaijan"
    },
    {
      "name": "Bengali (Bangladesh)",
      "code": "bn_BD",
      "region": "Bangladesh"
    },
    {
      "name": "Bengali (India)",
      "code": "bn_IN",
      "region": "India"
    },
    {
      "name": "Bosnian (Bosnia and Herzegovina)",
      "code": "bs_BA",
      "region": "Bosnia and Herzegovina"
    },
    {
      "name": "Bulgarian (Bulgaria)",
      "code": "bg_BG",
      "region": "Bulgaria"
    },
    {
      "name": "Catalan (Spain)",
      "code": "ca_ES",
      "region": "Spain"
    },
    {
      "name": "Chinese (Simplified Han)",
      "code": "zh_Hans",
      "region": "China"
    },
    {
      "name": "Chinese (Traditional Han)",
      "code": "zh_Hant",
      "region": "Taiwan"
    },
    {
      "name": "Croatian (Croatia)",
      "code": "hr_HR",
      "region": "Croatia"
    },
    {
      "name": "Czech (Czech Republic)",
      "code": "cs_CZ",
      "region": "Czech Republic"
    },
    {
      "name": "Danish (Denmark)",
      "code": "da_DK",
      "region": "Denmark"
    },
    {
      "name": "Divehi (Maldives)",
      "code": "dv_MV",
      "region": "Maldives"
    },
    {
      "name": "Dutch (Belgium)",
      "code": "nl_BE",
      "region": "Belgium"
    },
    {
      "name": "Dutch (Netherlands)",
      "code": "nl_NL",
      "region": "Netherlands"
    },
    {
      "name": "English (Australia)",
      "code": "en_AU",
      "region": "Australia"
    },
    {
      "name": "English (Canada)",
      "code": "en_CA",
      "region": "Canada"
    },
    {
      "name": "English (India)",
      "code": "en_IN",
      "region": "India"
    },
    {
      "name": "English (Ireland)",
      "code": "en_IE",
      "region": "Ireland"
    },
    {
      "name": "English (New Zealand)",
      "code": "en_NZ",
      "region": "New Zealand"
    },
    {
      "name": "English (South Africa)",
      "code": "en_ZA",
      "region": "South Africa"
    },
    {
      "name": "English (Zimbabwe)",
      "code": "en_ZW",
      "region": "Zimbabwe"
    },
    {
      "name": "Estonian (Estonia)",
      "code": "et_EE",
      "region": "Estonia"
    },
    {
      "name": "Faroese (Faroe Islands)",
      "code": "fo_FO",
      "region": "Faroe Islands"
    },
    {
      "name": "Filipino (Philippines)",
      "code": "fil_PH",
      "region": "Philippines"
    },
    {
      "name": "Finnish (Finland)",
      "code": "fi_FI",
      "region": "Finland"
    },
    {
      "name": "French (Belgium)",
      "code": "fr_BE",
      "region": "Belgium"
    },
    {
      "name": "French (Canada)",
      "code": "fr_CA",
      "region": "Canada"
    },
    {
      "name": "French (Switzerland)",
      "code": "fr_CH",
      "region": "Switzerland"
    },
    {
      "name": "Galician (Spain)",
      "code": "gl_ES",
      "region": "Spain"
    },
    {
      "name": "Georgian (Georgia)",
      "code": "ka_GE",
      "region": "Georgia"
    },
    {
      "name": "German (Austria)",
      "code": "de_AT",
      "region": "Austria"
    },
    {
      "name": "German (Belgium)",
      "code": "de_BE",
      "region": "Belgium"
    },
    {
      "name": "German (Luxembourg)",
      "code": "de_LU",
      "region": "Luxembourg"
    },
    {
      "name": "German (Switzerland)",
      "code": "de_CH",
      "region": "Switzerland"
    },
    {
      "name": "Greek (Cyprus)",
      "code": "el_CY",
      "region": "Cyprus"
    },
    {
      "name": "Greek (Greece)",
      "code": "el_GR",
      "region": "Greece"
    },
    {
      "name": "Gujarati (India)",
      "code": "gu_IN",
      "region": "India"
    },
    {
      "name": "Hebrew (Israel)",
      "code": "he_IL",
      "region": "Israel"
    },
    {
      "name": "Hindi (India)",
      "code": "hi_IN",
      "region": "India"
    },
    {
      "name": "Hungarian (Hungary)",
      "code": "hu_HU",
      "region": "Hungary"
    },
    {
      "name": "Icelandic (Iceland)",
      "code": "is_IS",
      "region": "Iceland"
    },
    {
      "name": "Indonesian (Indonesia)",
      "code": "id_ID",
      "region": "Indonesia"
    },
    {
      "name": "Italian (Italy)",
      "code": "it_IT",
      "region": "Italy"
    },
    {
      "name": "Italian (Switzerland)",
      "code": "it_CH",
      "region": "Switzerland"
    },
    {
      "name": "Japanese (Japan)",
      "code": "ja_JP",
      "region": "Japan"
    },
    {
      "name": "Kannada (India)",
      "code": "kn_IN",
      "region": "India"
    },
    {
      "name": "Kazakh (Kazakhstan)",
      "code": "kk_KZ",
      "region": "Kazakhstan"
    },
    {
      "name": "Khmer (Cambodia)",
      "code": "km_KH",
      "region": "Cambodia"
    },
    {
      "name": "Korean (South Korea)",
      "code": "ko_KR",
      "region": "South Korea"
    },
    {
      "name": "Kurdish (Iraq)",
      "code": "ku_IQ",
      "region": "Iraq"
    },
    {
      "name": "Kyrgyz (Kyrgyzstan)",
      "code": "ky_KG",
      "region": "Kyrgyzstan"
    },
    {
      "name": "Lao (Laos)",
      "code": "lo_LA",
      "region": "Laos"
    },
    {
      "name": "Latvian (Latvia)",
      "code": "lv_LV",
      "region": "Latvia"
    },
    {
      "name": "Lithuanian (Lithuania)",
      "code": "lt_LT",
      "region": "Lithuania"
    },
    {
      "name": "Macedonian (North Macedonia)",
      "code": "mk_MK",
      "region": "North Macedonia"
    },
    {
      "name": "Malay (Brunei)",
      "code": "ms_BN",
      "region": "Brunei"
    },
    {
      "name": "Malay (Malaysia)",
      "code": "ms_MY",
      "region": "Malaysia"
    },
    {
      "name": "Malayalam (India)",
      "code": "ml_IN",
      "region": "India"
    },
    {
      "name": "Maltese (Malta)",
      "code": "mt_MT",
      "region": "Malta"
    },
    {
      "name": "Marathi (India)",
      "code": "mr_IN",
      "region": "India"
    },
    {
      "name": "Mongolian (Mongolia)",
      "code": "mn_MN",
      "region": "Mongolia"
    },
    {
      "name": "Nepali (Nepal)",
      "code": "ne_NP",
      "region": "Nepal"
    },
    {
      "name": "Norwegian Bokmål (Norway)",
      "code": "nb_NO",
      "region": "Norway"
    },
    {
      "name": "Oriya (India)",
      "code": "or_IN",
      "region": "India"
    },
    {
      "name": "Pashto (Afghanistan)",
      "code": "ps_AF",
      "region": "Afghanistan"
    },
    {
      "name": "Persian (Iran)",
      "code": "fa_IR",
      "region": "Iran"
    },
    {
      "name": "Polish (Poland)",
      "code": "pl_PL",
      "region": "Poland"
    },
    {
      "name": "Portuguese (Brazil)",
      "code": "pt_BR",
      "region": "Brazil"
    },
    {
      "name": "Portuguese (Portugal)",
      "code": "pt_PT",
      "region": "Portugal"
    },
    {
      "name": "Punjabi (India)",
      "code": "pa_IN",
      "region": "India"
    },
    {
      "name": "Romanian (Romania)",
      "code": "ro_RO",
      "region": "Romania"
    },
    {
      "name": "Russian (Russia)",
      "code": "ru_RU",
      "region": "Russia"
    },
    {
      "name": "Sanskrit (India)",
      "code": "sa_IN",
      "region": "India"
    },
    {
      "name": "Serbian (Serbia)",
      "code": "sr_RS",
      "region": "Serbia"
    },
    {
      "name": "Sinhala (Sri Lanka)",
      "code": "si_LK",
      "region": "Sri Lanka"
    },
    {
      "name": "Slovak (Slovakia)",
      "code": "sk_SK",
      "region": "Slovakia"
    },
    {
      "name": "Slovenian (Slovenia)",
      "code": "sl_SI",
      "region": "Slovenia"
    },
    {
      "name": "Spanish (Argentina)",
      "code": "es_AR",
      "region": "Argentina"
    },
    {
      "name": "Spanish (Bolivia)",
      "code": "es_BO",
      "region": "Bolivia"
    },
    {
      "name": "Spanish (Chile)",
      "code": "es_CL",
      "region": "Chile"
    },
    {
      "name": "Spanish (Colombia)",
      "code": "es_CO",
      "region": "Colombia"
    },
    {
      "name": "Spanish (Costa Rica)",
      "code": "es_CR",
      "region": "Costa Rica"
    },
    {
      "name": "Spanish (Dominican Republic)",
      "code": "es_DO",
      "region": "Dominican Republic"
    },
    {
      "name": "Spanish (Ecuador)",
      "code": "es_EC",
      "region": "Ecuador"
    },
    {
      "name": "Spanish (El Salvador)",
      "code": "es_SV",
      "region": "El Salvador"
    },
    {
      "name": "Spanish (Guatemala)",
      "code": "es_GT",
      "region": "Guatemala"
    },
    {
      "name": "Spanish (Honduras)",
      "code": "es_HN",
      "region": "Honduras"
    },
    {
      "name": "Spanish (Mexico)",
      "code": "es_MX",
      "region": "Mexico"
    },
    {
      "name": "Spanish (Nicaragua)",
      "code": "es_NI",
      "region": "Nicaragua"
    },
    {
      "name": "Spanish (Panama)",
      "code": "es_PA",
      "region": "Panama"
    },
    {
      "name": "Spanish (Paraguay)",
      "code": "es_PY",
      "region": "Paraguay"
    },
    {
      "name": "Spanish (Peru)",
      "code": "es_PE",
      "region": "Peru"
    },
    {
      "name": "Spanish (Puerto Rico)",
      "code": "es_PR",
      "region": "Puerto Rico"
    },
    {
      "name": "Spanish (Spain)",
      "code": "es_ES",
      "region": "Spain"
    },
    {
      "name": "Spanish (United States)",
      "code": "es_US",
      "region": "United States"
    },
    {
      "name": "Spanish (Uruguay)",
      "code": "es_UY",
      "region": "Uruguay"
    },
    {
      "name": "Spanish (Venezuela)",
      "code": "es_VE",
      "region": "Venezuela"
    },
    {
      "name": "Sundanese (Indonesia)",
      "code": "su_ID",
      "region": "Indonesia"
    },
    {
      "name": "Swahili (Kenya)",
      "code": "sw_KE",
      "region": "Kenya"
    },
    {
      "name": "Swedish (Finland)",
      "code": "sv_FI",
      "region": "Finland"
    },
    {
      "name": "Swedish (Sweden)",
      "code": "sv_SE",
      "region": "Sweden"
    },
    {
      "name": "Tajik (Tajikistan)",
      "code": "tg_TJ",
      "region": "Tajikistan"
    },
    {
      "name": "Tamil (India)",
      "code": "ta_IN",
      "region": "India"
    },
    {
      "name": "Tatar (Russia)",
      "code": "tt_RU",
      "region": "Russia"
    },
    {
      "name": "Telugu (India)",
      "code": "te_IN",
      "region": "India"
    },
    {
      "name": "Thai (Thailand)",
      "code": "th_TH",
      "region": "Thailand"
    },
    {
      "name": "Turkish (Turkey)",
      "code": "tr_TR",
      "region": "Turkey"
    },
    {
      "name": "Turkmen (Turkmenistan)",
      "code": "tk_TM",
      "region": "Turkmenistan"
    },
    {
      "name": "Ukrainian (Ukraine)",
      "code": "uk_UA",
      "region": "Ukraine"
    },
    {
      "name": "Urdu (India)",
      "code": "ur_IN",
      "region": "India"
    },
    {
      "name": "Urdu (Pakistan)",
      "code": "ur_PK",
      "region": "Pakistan"
    },
    {
      "name": "Uyghur (China)",
      "code": "ug_CN",
      "region": "China"
    },
    {
      "name": "Uzbek (Uzbekistan)",
      "code": "uz_UZ",
      "region": "Uzbekistan"
    },
    {
      "name": "Vietnamese (Vietnam)",
      "code": "vi_VN",
      "region": "Vietnam"
    },
    {
      "name": "Welsh (United Kingdom)",
      "code": "cy_GB",
      "region": "United Kingdom"
    },
    {
      "name": "Xhosa (South Africa)",
      "code": "xh_ZA",
      "region": "South Africa"
    },
    {
      "name": "Yiddish (World)",
      "code": "yi",
      "region": "World"
    },
    {
      "name": "Yoruba (Nigeria)",
      "code": "yo_NG",
      "region": "Nigeria"
    },
    {
      "name": "Zulu (South Africa)",
      "code": "zu_ZA",
      "region": "South Africa"
    }
  ]
}

Answer: Or if you need an enum of languages without locale in typescript or plaint object in javascript for copy-paste purposes
export enum ISOLanguages {
  AF = 'af',
  SQ = 'sq',
  AR = 'ar',
  EU = 'eu',
  BG = 'bg',
  BE = 'be',
  CA = 'ca',
  ZH = 'zh',
  HR = 'hr',
  CS = 'cs',
  DA = 'da',
  NL = 'nl',
  EN = 'en',
  ET = 'et',
  FO = 'fo',
  FA = 'fa',
  FI = 'fi',
  FR = 'fr',
  GD = 'gd',
  DE = 'de',
  EL = 'el',
  HE = 'he',
  HI = 'hi',
  HU = 'hu',
  IS = 'is',
  ID = 'id',
  IT = 'it',
  JA = 'ja',
  KO = 'ko',
  LV = 'lv',
  LT = 'lt',
  MK = 'mk',
  MT = 'mt',
  NO = 'no',
  PL = 'pl',
  PT = 'pt',
  RM = 'rm',
  RO = 'ro',
  RU = 'ru',
  SZ = 'sz',
  SR = 'sr',
  SK = 'sk',
  SL = 'sl',
  SB = 'sb',
  ES = 'es',
  SX = 'sx',
  SV = 'sv',
  TH = 'th',
  TS = 'ts',
  TN = 'tn',
  TR = 'tr',
  UK = 'uk',
  UR = 'ur',
  VE = 've',
  VI = 'vi',
  XH = 'xh',
  JI = 'ji',
  ZU = 'zu',
}


Is every closed subgroup of a profinite group contained in a maximal subgroup?

Question: I recently asked this question about whether or not every subgroup of a profinite group is contained in a maximal subgroup. The answer is no, and a counterexample is given by $\mathbb{Z}<\mathbb{Z}_p$. I've noticed that $\mathbb{Z}$ is dense in $\mathbb{Z}_p$, but $\mathbb{Z}\neq\mathbb{Z}_p$. In particular, this means that $\mathbb{Z}$ is not closed in $\mathbb{Z}_p$. Is it true that every closed subgroup of a profinite group is contained in a maximal subgroup?
Note: A maximal subgroup must be either closed and nondense or open and dense: Indeed, if it is closed and dense, then it is the whole group, and if it is open and nondense, then its closure lies above it.
Comment: You mean "closed and non-dense or non-closed and dense". There may be subgroups which are neither closed nor open!
Comment: Please note that open subgroups are always closed, so open and dense implies being the whole group, which means it can't be maximal. I don't know what the general answer to your question is at the moment, but if I were to guess I would say it's no. However in the specific case of the p-adic integers atleast, if I'm not mistaken, all of its closed subgroups are of the form $p^n \mathbb{Z}_p$ for $n \ge 0$. So in that particular case, the answer is positive.
Answer: Suppose $N$ is a proper closed subgroup of the profinite group $G$. Then $G/N$ is non-trivial and profinite (as I pointed out here), so it has a maximal subgroup $M$ of finite index (as Eric explained here). Letting $\pi\colon G\to G/N$ be the quotient map, $\pi^{-1}(M)$ is a proper subgroup of $G$ of finite index containing $N$. Let $M'$ be a subgroup of $G$ of minimal finite index among those proper subgroups containing $N$. Then $M'$ is a maximal subgroup of $G$.


PostgreSQL Sequence Ascending Out of Order

Question: I'm having an issue with Sequences when inserting data into a Postgres table through SQL Alchemy.
All of the data is inserted fine, the id BIGSERIAL PRIMARY KEY column has all unique values which is great.
However when I query the first 10/20 rows etc. of the table, the id values are not ascending in numeric order. There are gaps in the sequence, fine, that's to be expected, I mean rows will go through values randomly not ascending like:
id
15
22
16
833
30
etc...

I've gone through plenty of SO and Postgres forum posts around this and have only found people talking about having huge serial gaps in their sequences, not about incorrect ascending order when being created
Screenshots of examples:

The table itself has being created through standard DDL statement like so:
CREATE TABLE IF NOT EXISTS schema.table_name (
  id                  BIGSERIAL                                   NOT NULL,
  col1                text                                        NOT NULL,
  col2                JSONB[]                                     NOT NULL,
  etc....
  PRIMARY KEY (id)
);

Comment: Tables represent **unordered** sets. The **only** way to guarantee a sorted output is to use `order by`
Answer:
However when I query the first 10/20 rows etc. of the table

Your query has no order by clause, so you  are not selecting the first rows of the table, just an undefined set of rows.
Use order by - you will find out that sequence number are indeed assigned in ascending order (potentially with gaps):
select id from ht_data order by id limit 30

In order to actually check the ordering of the sequence, you would actually need another column that stores the timestamp when each row was created. You could then do:
select id from ht_data order by ts limit 30

Comment: Ah OK gotcha, thanks for clearing that up, I was unaware of the extent of unorderedness in SQL tables
Answer: In general, there is no defined "order" within a SQL table.  If you want to view your data in a certain order, you need an ORDER BY clause:
SELECT *
FROM table_name
ORDER BY id;

As for gaps in the sequence, the contract of an auto increment column generally only guarantees that each newly generated id value with be unique and, most of the time (but not necessarily always), will be increasing.
Comment: Ah I see, thanks for the info. I need to dig a but deeper into understanding ordering (or lack thereof) in SQL, cheers!
Answer: How could you possibly know if the values are "out of order"?  SQL tables represent unordered sets.  The only indication of ordering in your table is the serial value.
The query that you are running has no ORDER BY.  The results are not guaranteed to be in any particular ordering.  Period.  That is a very simply fact about SQL.  That you want the results of a SELECT to be ordered by the primary key or by insertion order is nice, but not how databases work.
The only way you could determine if something were out of order would be if you had a column that separate specified the insert order -- you could have a creation timestamp for instance.
All you have discovered is that SQL lives up to its promise of not guaranteeing ordering unless the query specifically asks for it.


In Lilypond: Can one absorb the sharps and flats in the key, in order to ease typing?

Question: As I understood from the tutorial, the short code

\key d \major
   cis4 d e fis

would generate
.
Is this the only way to type it, or is there a natural way to get the same output by absorbing the
sharps in the key, i.e. since D major already signals that c and f really mean c-sharp and f-sharp, respectively, I'd like to know if it's possible to get the same pdf and midi by typing

\key d \major
   c4 d e f

instead?
P.S. Sorry if this is somewhere else in the tutorial, I'm just trying to produce my hello world in Lilypond.
Answer: The answer is "Yes you can, but doing this is a really bad idea".
It's a bad idea because you will probably soon want to write C natural or F natural with a D major key signature, and if you make "c" mean "c sharp" you won't have a good way to do that. If the key signature changes during the piece, things will quickly get very confusing.
Check out "note names for other languages" in the documentation. For example in English you can use "s" and "f" for sharp and flat, not the Dutch (or Scandinavian) "is" and "es".
If still you want to ignore the above advice and find out how to do it, check the documentation on how Lilypond handles bagpipe music (which is effectively written in the key of D but without a key signature and without accidentals) and look at "bagpipe.ly" to see how the note names are redefined.
Comment: The basic idea is that defining **what** note is to be written is independent of **how** it is written. Some notation doesn't use key signatures (e.g. orchestral horn parts and guitar tablature, as well as bagpipes). You can define non-standard key signatures. You can define a sequence of notes once, not associated with any particular staff or key signature, and use it on several staves with different notation conventions. There is a `\transpose` command. Making all those options work sensibly when the pitch notation depended on the key signature would be a recipe for confusion.
Comment: That  makes sense. I just wanted to be sure whether it was the optimal way. What I, as newbie, expected is: if you are already in, say D-Major, then you will likely write more  **cis** than *c* and more *fis* than *f*, and that therefore anytime you are to play/obtain natural-c that there would be a way to write, **cn** or the like, meaning *C-Becuadro*, *c-becarré, c-Auflösungszeichen*. I guess just practice will tell me that the configuration chosen by LiilyPond developers is optimal.
Answer: You want your Lilypond source file to use the simplest names for the pitches which accord with your key signature. Fine, but if you're going to do that, then, to be consistent with doing that, you should also name the pitches by letters in a way which accords with your key signature. So if you are going to compose in a major key this way, then, in your Lilypond file, type c for your tonic, d for your supertonic, e for your mediant and so on. In other words, type in C major. Then use \transpose to get the correct notation in the sheet music:
\version "2.18"
\language "english"

tune = {
    \key d \major
    \transpose c d'' { b, c d e }
}

\score
{
    \new Staff \tune
    \layout { }
}


How to understand the vertical bar (pipe) in R formulas

Question: I came upon this because I wanted to emulate Welch's t-test using gls. I found the answer here:
https://stats.stackexchange.com/a/144480/141304
and it says to add weights with
gls(y ~ group, data = dat, weights=varIdent(form = ~ 1 | group))
y and group are variables in the model. I don't know what form is. I read through help on gls, glm, weights, etc. but couldn't find anything that addressed the issue.
Some tutorials on R formulas filled me in that the pipe means conditioning, just like in probability. I understand conditioning in probability, but I can't wrap my head around what it means in regression.
Suppose I have four predictor variables A, B, C, D and a response variable X. A and B are continuous; C and D are categorical with two levels.
What would formulas such as the ones below (or any other ones an answerer might want to explain) mean?
X ~ A + A|B
X ~ A + B|C
X ~ A + B + C|D
Answer: Assume there are only two groups: group 1 and group 2.  The gls() call you specified fits two sub-models to your $y$ observations - one sub-model for the $y$ observations in the first group and another sub-model for the $y$ observations in the second group.
The sub-model for the observations $y$ in group 1 postulates that $y = \beta_0 + \epsilon$, where $\epsilon$ denotes a random error term coming from a normal distribution with mean 0 and unknown variance $\sigma_1^2$.  In other words, these observations are grouped about the true group mean $\beta_0$, with their spread about this true group mean being captured by $\sigma_1^2$.
The sub-model for the observations y in group 2 postulates that $y = \beta_0 +  \beta_1 + \epsilon$, where $\epsilon$ denotes a random error term coming from a normal distribution with mean 0 and unknown variance $\sigma_2^2$. In other words, these observations are grouped about the true group mean $\beta_0 + \beta_1$, with their spread about this true group mean being captured by $\sigma_2^2$.
The gls() call you provided allows the spread (or variability) of the y values in the two groups about their respective true group means to be different across groups (that is, it allows $\sigma_1^2$ to be different from $\sigma_2^2$) via the option weights=varIdent(form = ~ 1 | group).


How to achieve this: object->object->property

Question: I see a lot of code where the calls are like this.
An example:
$person->head->eyes->color = "brown";
$person->head->size = 10;
$person->name = "Daniel";

How do I achieve what I wrote above?
Comment: @Daniel I would call it OOP. Method chaining is when a class method returns the class instance so you can call multiple methods on the same object... in a chain. :)
Comment: @ElzoValugi, this is not method chaining
Comment: Try to read These articles:
http://www.techflirt.com/tutorials/oop-in-php/php-method-chaining.html
https://en.wikipedia.org/wiki/Method_chaining
Comment: @swidmann what would you call it?
Comment: @MagnusEriksson thats a goood explation of method chaining :)
Comment: @MagnusEriksson, could not explain it better, thanks ;)
Answer: That just means that $person, $person->head, and $person->eyes each have properties that are other objects. head is a property of $person, eyes is a property of $person->head, and so on.
So, when you set $person->head->size, for example, you are setting the size property of $person->head, meaning $person->head must be an object. Put differently, the statement $person->head->size = 10; means set the size property of the head property of $person to 10.
Example Code:
<?php

class Eyes
{
    var $color = null;
}

class Head
{
    var $eyes = null;
    var $size = null;

    function __construct()
    {
        $this->eyes = new Eyes();
    }
}

class Person
{
    var $head = null;
    var $name = null;

    function __construct()
    {
        $this->head = new Head();
    }
}

$person = new Person();
$person->head->eyes->color = "brown";
$person->head->size = 10;
$person->name = "Daniel";

var_dump($person);

This outputs:
class Person#1 (2) {
  public $head =>
  class Head#2 (2) {
    public $eyes =>
    class Eyes#3 (1) {
      public $color =>
      string(5) "brown"
    }
    public $size =>
    int(10)
  }
  public $name =>
  string(6) "Daniel"
}

Comment: @Daniel I don't think it has a name. It's just a feature of object-oriented programming that you can set an object's property to be another object.
Comment: Looks really good, does this way of doing things have a name?
Comment: actually even if it looks good it can be very messy and is not recommended practice. Properties should be accessed through getter/setter methods not directly
Comment: @ElzoValugi That's actually the topic of some debate, but it's not really part of Daniel's question.
Comment: true, is just a comment relative to his excitement
Answer: First thing: there are no method being called in your example.
To the answer:
This can be achieved by using another objects instances as attributes. Eg:
class Head{
    public $size, $eyes, $etc;
}

class Person{
    public $name, $age, $head;

    public function __construct(){
        $this->head = new Head();
    }
}

$person = new Person();
$person->head->size = 'XL';

This is one way of doing it
You can also cast arrays as objects. This will generate stdClass instances with array indexes as attributes:
$person = array(
    'name' => 'Foo',
    'age' => 20
);

$personObject = (object) $person;
var_dump($personObject);

Answer: PHP method chaning is the secret, return on each getter method $this
class Person
{
    public function head()
    {
        ...
        return $this;
    }

    public function eyes()
    {
        ...
        return $this;
    }
}

$person->head->eyes->color = "brown";

https://en.wikipedia.org/wiki/Method_chaining#PHP
Comment: @mischaZeng - I think the line "How do i achieve this i wrote above?" kinda sets the context to that code.
Comment: this is not quite true. it will be $person->head()->eyes()->color;
Comment: That's not what method chaining is. `head` and `eyes` aren't methods in `$person->head->eyes->color`; they're properties.
Comment: I thought it was a general question, not especially for that code


Getting PySide to work with matplotlib

Question: I have tried running the example code on the SciPy website, but I get this error:
Traceback (most recent call last):
  File ".\matplotlibPySide.py", line 24, in <module>
    win.setCentralWidget(canvas)
TypeError: 'PySide.QtGui.QMainWindow.setCentralWidget' called with wrong argument types:
  PySide.QtGui.QMainWindow.setCentralWidget(FigureCanvasQTAgg)
Supported signatures:
  PySide.QtGui.QMainWindow.setCentralWidget(PySide.QtGui.QWidget)

I am building a simple scientific data logger that will eventually be used in commercial applications, so I really need both the LGPL from PySide and plotting functionality. Does anyone have experience on how to get this to work or alternative plotting packages or ideas?
Thanks in advance.
Comment: Try skipping the example code there and try things with the latest matplotlib git tip.  https://github.com/matplotlib/matplotlib (Note that you'll need to have the various build dependencies. It's not pure python.)  Full PySide support was added to the qt backend a month or so ago, but hasn't come out in a release yet. The code you liked to is just a workaround. Newer versions of matplotlib will fully support pyside.
Answer: The example that you mention:
http://www.scipy.org/Cookbook/Matplotlib/PySide
works, but you might need to suggest the use of PySide:
...
matplotlib.use('Qt4Agg')
matplotlib.rcParams['backend.qt4']='PySide'
import pylab
...

Comment: @JuanPablo No need to import pylab, but I think that you need to configure Matplotlib as much as possible before actually importing pylab or pyplot... suerte!
Comment: In the example http://www.scipy.org/Cookbook/Matplotlib/PySide , why have the `import pylab` ? without this line work fine.
Answer: I had similar goals (LGPL, potential commercial use) and here's how I ended up getting it to work.
Create a matplotlib widget (see here for a more detailed one for PyQt):
import matplotlib

matplotlib.use('Qt4Agg')
matplotlib.rcParams['backend.qt4']='PySide'

from matplotlib.figure import Figure
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas

class MatplotlibWidget(FigureCanvas):

    def __init__(self, parent=None,xlabel='x',ylabel='y',title='Title'):
        super(MatplotlibWidget, self).__init__(Figure())

        self.setParent(parent)
        self.figure = Figure()
        self.canvas = FigureCanvas(self.figure)
        self.axes = self.figure.add_subplot(111)

        self.axes.set_xlabel(xlabel)
        self.axes.set_ylabel(ylabel)
        self.axes.set_title(title)

In Qt Designer I created a blank widget to hold my plot and then when I __init__ the main window I call setupPlot:
def  setupPlot(self):
    # create a matplotlib widget
    self.DataPlot = MatplotlibWidget()
    # create a layout inside the blank widget and add the matplotlib widget
    layout = QtGui.QVBoxLayout(self.ui.widget_PlotArea)
    layout.addWidget(self.DataPlot,1)

Then I call plotDataPoints as needed:
def plotDataPoints(self,x,y):
    self.DataPlot.axes.clear()
    self.DataPlot.axes.plot(x,y,'bo-')
    self.DataPlot.draw()

Note: this clears and redraws the entire plot every time (since the shape of my data keeps changing) and so isn't fast.
Answer: I think you may have posted this on the matplotlib mailing list.  But just in case someone else is looking for the answer.  The best option is to use the master branch on Github, but if you can't or don't know how to work the Github version you can use the following code to render a plot in PySide.
import numpy as np
from matplotlib import use
use('AGG')
from matplotlib.transforms import Bbox
from matplotlib.path import Path
from matplotlib.patches import Rectangle
from matplotlib.pylab import *
from PySide import QtCore,QtGui

rect = Rectangle((-1, -1), 2, 2, facecolor="#aaaaaa")
gca().add_patch(rect)
bbox = Bbox.from_bounds(-1, -1, 2, 2)

for i in range(12):
    vertices = (np.random.random((4, 2)) - 0.5) * 6.0
    vertices = np.ma.masked_array(vertices, [[False, False], [True, True], [False, False], [False, False]])
    path = Path(vertices)
    if path.intersects_bbox(bbox):
        color = 'r'
    else:
        color = 'b'
    plot(vertices[:,0], vertices[:,1], color=color)

app = QtGui.QApplication(sys.argv)
gcf().canvas.draw()

stringBuffer = gcf().canvas.buffer_rgba(0,0)
l, b, w, h = gcf().bbox.bounds

qImage = QtGui.QImage(stringBuffer,
                      w,
                      h,
                      QtGui.QImage.Format_ARGB32)

scene = QtGui.QGraphicsScene()
view = QtGui.QGraphicsView(scene)
pixmap = QtGui.QPixmap.fromImage(qImage)
pixmapItem = QtGui.QGraphicsPixmapItem(pixmap)
scene.addItem(pixmapItem)
view.show()

app.exec_()

Getting PySide to work with matplotlib


Cordova 2.7 prompt message appears on page load

Question: I just upgraded a project from Cordova 2.6 to 2.7 due to a bug in 2.6 with localstorage on Android. Now, on pageload, I'm presented with this nicety, in 3 slightly different ways:

If I click OK, the page crashes. It appears its coming from this:
module.exports = {
  exec: function(service, action, callbackId, argsJson) {
    return prompt(argsJson, 'gap:'+JSON.stringify([service, action, callbackId]));
  },
  setNativeToJsBridgeMode: function(value) {
    prompt(value, 'gap_bridge_mode:');
  },
  retrieveJsMessages: function() {
    return prompt('', 'gap_poll:');
  }
};

How can I prevent this from happening?
Edit: It doesn't appear to happen on Android itself, but it does happen in Chrome, and this application works in both.
Answer: I don't think you should include the Cordova script in your Chrome only distribution. This alert is popping up because internally Cordova for Android uses the alert() mechanism to pass events between the JavaScript and Native code portions of a Cordova app. I'm pretty sure that when you view the app through Chrome, the rest of Cordova never really gets set up (the native portions), so the alert is not captured and instead is actually surfaced to the Chrome browser.
If the application you are developing works in both Chrome and Android (I'm assuming you are packaging it via Cordova into a native .apk?), I'm having a hard time understanding what you are using Cordova for... If you are not using any of the native device functionality that Cordova provides (Camera access, accelerometer, etc.) and are just using it to wrap a web app in a native shell, you might find it easier to just develop (for Chrome) and release the web app as...well, a web app.
Although I do think one of the major benefits of Cordova is much greater distribution potential in the form of native applications. If this is what you are planning on doing, then I'd say just ignore the alert while you test on Chrome. If you plan to release native apps (via Cordova) and the web app, just remove the Cordova script from the production version of the web app.
Comment: The app has additional functionality that is conditionally displayed or used (camera, gps, local storage for offline use) when packaged as cordova and on a mobile device versus when it's run in Chrome. It's a super big code-reuse benefit to share the bulk of the app between the two use-cases. I ended up just also conditionally loaded the cordova script, which was fine, but it was strange as this had never happened before that version (I've been developing cordova apps for about 2 years).


What is the violin's range including all the positions?

Question: What is the violin's range including the positions(1st position, 3rd position, 5th position, 7th position, etc.)?
Answer: The high range of string instruments is subjective, because theoretically they can extend upwards infinitely. The low note is G3 (with subharmonics, however, this isn't an absolute barrier either).
The high range largely depends on context; I wouldn't write a C8 for a high school orchestra, for example.


How to upload videos and play in Drupal 7?

Question: I am trying to upload custom video files to Drupal site and play the video. I have custom videos which are to be uploaded to posts.
Here I am not using any YouTube embedded links, instead I want to upload my own videos into my posts.
I also have installed the media module and the JWplayer but I don't know how to configure the module to upload videos in my posts and play those videos.
I am a newbie to Drupal. Can anyone help me to configure this?
Comment: The most of modules contains file README.txt
You can check it to take some info about configuration and how it works.
Answer: Here is complete Community Documentation about the Media module.
There is another Drupal Video Setup Using Media and Media Youtube
 tutorial about using the [Media] and Media Youtube modules in a Drupal site.
If still you can't get it to work, then you can also check the tutorial Post YouTube Videos with Media + Media: YouTube (from Drupal's Post Installation forum).
Now choice is up to you in which you feel easy.
Answer: You need a module like Video. You can upload and also transcode videos with it. The module adds a new field type, Video, which can be used to upload and view videos. Here you can see how to install and test it out.
Answer: Finally got it working, The tutorial about "Uploading Video Files in Drupal" worked for me. Here is part of what it is about (quote from that link):

If we want a simple approach to uploading and playing our videos inside an HTML5 player, we can use the built-in File field provided in the Drupal core to hold our uploaded video and an added module to provide a player.

Basically what this tutorial explains is this:

Add a field of the 'File' field type to a content type.
Use the Media Element module.

Head over to the tutorial for more details if needed.
Comment: I'm still a Drupal newbie too (compared to "Dries") ... If you want to learn, then make sure to also visit the "tour" around here (link within help, upper right). Looking at your profile it shows you have never done so. Make sure to also visit http://drupal.stackexchange.com/help/someone-answers ... Good luck!
Comment: @Pierre.Vriens thanks for that... but i am still a newbie to drupal... i love learning things like this... cheers :)
Comment: I slightly (?!?!) expanded your answer, mostly by reformatting it a bit, and adding some details about that link. Please review / correct / expand where you think it is appropriate. If you like it, please try to remember it in future answers, ok? Ps: curious if it will help to get your -1 vote removed again ...
Comment: @Pierre.Vriens is correct: Link-only answers are not considered answers on Stack Exchange. Answers need to be useful for future users too, not just for the user who asked the question, and an external link is not warranted to still be valid for all the time the question or the answer exists.
Answer: Apart from the various modules already suggested in the other answers, I think you might also want to look at the Scald: Media Management made easy module, which is more and more considered as an alternative to the Media module.
Here is a quote about the Scald module (from its project page):

... a popular and flexible way to handle media in Drupal.
Scald can handle images, video, audio, tweets and even Flash files. Scald works with YouTube, Vimeo, Soundcloud and other many other providers. You can see a full list on the scald provider's page, you can also read our FAQ.
For end-users Scald is a great option because you can use Scald with popular editing tools such as CKEditor, and with Plupload for multiple file uploads. Scald also has a very user-friendly media library, based on Views.
For developers, one of the best things about Scald is that it treats all files as full-blown fieldable entities.

And yes, it also has quite some Community Documentation.


Fixing a choppy-looking countdown timer

Question: I'm having a bit of trouble getting my countdown timer to look right. As you can see in this JSFiddle, the numbers are moving around a bit as the countdown timer goes down. Is there a way to fix this so that the timer stays in position while the numbers decrease? Thanks in advance.
Also, this is the specific code used to display the timer:
view.displayTimer = function() {
  var count = 500;
  var counter = setInterval(timer, 10);

  function timer() {
    if(count <= 0) {
      clearInterval(counter);
      return;
    }
    count--;
    document.getElementById("timer").innerHTML = count / 100;
  }
};

Comment: FYI, this is not a very accurate way to do a timer because `setInterval()` is only an approximation.  You should record the startTime and then on each interval tick, calculate the elapsed time since the start time.
Answer: Use javascript toFixed function to pad with trailing zeros.
Replace
count / 100;

With
(count / 100).toFixed(2);

Jsfiddle.
Comment: Thank you! So I'm assuming that it was being choppy because the amount of decimal places were changing as the timer went down?
Comment: Yep that's right - by default javascript will give you the shortest float representation of your number. `toFixed` ensures you'll always have a minimum number of numbers shown after the decimal point.
Comment: Yup, just waiting 1 more min til it lets me accept an answer.
Comment: Ahhhh cool that makes sense. Sorry and thanks :) (I forgot there's a limit to how soon you can accept an answer)

Fixing a choppy-looking countdown timer


How do I get consistent sound during Bansuri practice

Question: I am teaching myself Bansuri (23", A scale), using YouTUBE videos.
Just recently I understood the concept of octaves, i.e. blowing sound hard and soft with same closed holes will produce high and low octave, respectively.
I am also practicing SA RE GA MA PA DHA NI SA
For past day or so, I noticed that I have to exert to make same low octave sound. Yesterday I didn't practice, thinking I need to give diaphragm/lungs a rest.
Today when I tried there were times I couldn't make low octave sound. I had to take deep breath from diaphragm and try again.
I am getting anxiety over this .... I really wish to learn Bansuri for hobby.
Question is, how to get consistent sound on Bansuri. Is it possible that I should limit practice to 30 minutes, daily, and take minute break in between.
Answer: Please check if you are closing the holes properly with fingers while trying out lower octave notes. Also Practicing on empty stomach may help producing lower octave notes.
Try to produce long notes initially. My teacher used to make us practice one note per breath ( as long as a minute ) in initial days. Don't worry, keep practicing it will come.
Playing long notes also helps bowing steady without any vibrations. Hope this helps
Comment: Those vibrations are unsettling .... glad these will go away with practice. Interestingly enough, I am always hungry after 30 minute of Bansuri practice!
Comment: How's your practice going on?
Comment: still getting vibration on higher notes. Trying to hold each note for a minute ...


How to find false option related to x mod two integers

Question: I am trying questions of masters of mathematics exam of my Institute and I was unable to solve this particular problem.
Please note that exam is choosing single correct option from 4 MCQ's and so we can devote relatively  less time to a question than subjective exam.
Its image:

Can anyone please tell how to solve this question using some short method.
I am unable to think how to find correct option.
Comment: For an example of an "impossible" pair of congruences, look at something like $n\equiv 5 \pmod {12}$ and $n\equiv 1\pmod 3$.  Try to use the same principle with your problem.
Answer: Here's how I would approach the problem. While I wouldn't know the prime divisors of $6789$, I do know the prime divisors of $1000$: $5$ and $2$. Clearly, 6789 is not divisible by either $5$ or $2$, so by the Chinese remainder theorem, we are guaranteed a solution. Thus, we can eliminate choices (1) and (2).
As for the other two choices, we look at smaller divisors. So if $x\equiv 32 \pmod{1000}$, then x must be divisible by $4$. Therefore, we can look at the other two choices to see which of those would not result in divisibility by $4$.
This is a general procedure for solving the problem, and some may be different.
Answer: Hint: $x\equiv 32\pmod{1000}$ implies $x\equiv 0\pmod 4$, but $x\equiv 54\pmod{9876}$  implies $x\equiv 2\pmod 4$.
Comment: This is true. Therefore, $x\equiv 54\pmod {9876}$ implies $\equiv 54\equiv 2\pmod 4$
Comment: 9876 is completely divisible by 4.


how to get cached data Apache ignite

Question: I am new in Apache ignite. I am trying to populate cache and read from cache. I have created 2 java projects one populates Apache ignite caches and the other one print cached data however printing cache project gives error.
here is the code that I use to populate caches
public void run(String... arg0) throws Exception
{
    try (Ignite ignite = Ignition.start("ignite.xml"))
    {
        int iteration=0;

        while(true)
        {
            iteration++;
            IgniteCache<Object, Object> cache = ignite.getOrCreateCache("test cache " + iteration);
            System.out.println(""+100);
            System.out.println("Caching started for iteration " + iteration);
            printMemory();

            for (int i = 0; i < 100; i++)
            {
                cache.put(i, new CacheObject(i, "Cached integer " + i));
                System.out.println(i);
                Thread.sleep(100);

            }
            //cache.destroy();
            System.out.println("**************************************"+cache.size());
        }

    }

}

this is the code that I use to print cached data
Ignition.setClientMode(true);
    IgniteConfiguration cfg = new IgniteConfiguration();
    cfg.setPeerClassLoadingEnabled(true);
    TcpDiscoveryMulticastIpFinder discoveryMulticastIpFinder = new TcpDiscoveryMulticastIpFinder();
    Set<String> set = new HashSet<>();

    set.add("serverhost:47500..47509");
    discoveryMulticastIpFinder.setAddresses(set);

    TcpDiscoverySpi discoverySpi = new TcpDiscoverySpi();
    discoverySpi.setIpFinder(discoveryMulticastIpFinder);

    cfg.setDiscoverySpi(discoverySpi);

    cfg.setPeerClassLoadingEnabled(true);
    cfg.setIncludeEventTypes(EVTS_CACHE);
    Ignite ignite = Ignition.start(cfg);

    System.out.println("***************************************************\n"+ignite.cacheNames()+"\n****************************");
    CacheConfiguration<String, BinaryObject> cacheConfiguration = new CacheConfiguration<>(CACHE_NAME);
    IgniteCache<String, BinaryObject> cache = ignite.getOrCreateCache(cacheConfiguration).withKeepBinary();

this 2 peace of code in different project so while 1 first project populating cache, I am trying to reach the cache from another project
the error below is occurred when I am trying to reach cached data
Error that returns from the code that reads cache and prints it

Aug 01, 2018 9:25:25 AM org.apache.ignite.logger.java.JavaLogger error
  SEVERE: Failed to start manager: GridManagerAdapter [enabled=true, name=o.a.i.i.managers.discovery.GridDiscoveryManager]
  class org.apache.ignite.IgniteCheckedException: Failed to start SPI: TcpDiscoverySpi [addrRslvr=null, sockTimeout=5000, ackTimeout=5000, reconCnt=10, maxAckTimeout=600000, forceSrvMode=false, clientReconnectDisabled=false]
      at org.apache.ignite.internal.managers.GridManagerAdapter.startSpi(GridManagerAdapter.java:258)
      at org.apache.ignite.internal.managers.discovery.GridDiscoveryManager.start(GridDiscoveryManager.java:660)
      at org.apache.ignite.internal.IgniteKernal.startManager(IgniteKernal.java:1505)
      at org.apache.ignite.internal.IgniteKernal.start(IgniteKernal.java:917)
      at org.apache.ignite.internal.IgnitionEx$IgniteNamedInstance.start0(IgnitionEx.java:1688)
      at org.apache.ignite.internal.IgnitionEx$IgniteNamedInstance.start(IgnitionEx.java:1547)
      at org.apache.ignite.internal.IgnitionEx.start0(IgnitionEx.java:1003)
      at org.apache.ignite.internal.IgnitionEx.start(IgnitionEx.java:534)
      at org.apache.ignite.internal.IgnitionEx.start(IgnitionEx.java:515)
      at org.apache.ignite.Ignition.start(Ignition.java:322)
      at test.App.main(App.java:76)
  Caused by: class org.apache.ignite.spi.IgniteSpiException: Local node's marshaller differs from remote node's marshaller (to make sure all nodes in topology have identical marshaller, configure marshaller explicitly in configuration) [locMarshaller=org.apache.ignite.internal.binary.BinaryMarshaller, rmtMarshaller=org.apache.ignite.marshaller.optimized.OptimizedMarshaller, locNodeAddrs=[192.168.1.71/0:0:0:0:0:0:0:1%lo, /127.0.0.1, /192.168.1.71], locPort=0, rmtNodeAddr=[192.168.1.71/0:0:0:0:0:0:0:1%lo, /127.0.0.1, /192.168.1.71], locNodeId=b41f0d09-5a7f-424b-b3b5-420a5e1acdf6, rmtNodeId=ff436f20-5d4b-477e-aade-837d59b1eaa7]
      at org.apache.ignite.spi.discovery.tcp.TcpDiscoverySpi.checkFailedError(TcpDiscoverySpi.java:1647)
      at org.apache.ignite.spi.discovery.tcp.ClientImpl$MessageWorker.body(ClientImpl.java:1460)
      at org.apache.ignite.spi.IgniteSpiThread.run(IgniteSpiThread.java:62)
Answer:
Caused by: class org.apache.ignite.spi.IgniteSpiException: Local node's marshaller differs from remote node's marshaller (to make sure all nodes in topology have identical marshaller, configure marshaller explicitly in configuration) [locMarshaller=org.apache.ignite.internal.binary.BinaryMarshaller, rmtMarshaller=org.apache.ignite.marshaller.optimized.OptimizedMarshaller

Looks like in ignite.xml you've explicitly set marshaller. Please check  <property name="marshaller"> in xml config file. You should have the same marshaller configured for all nodes in the cluster, or they won't be able to communicate.
Comment: can you share ignite.xml then, so I can reproduce it?
Comment: actually there is no marshaller property in ignite xml.I mean I didnt add it

how to get cached data Apache ignite


Taylor development series

Question: I don't quite understand how to get from:
$$ 3e^{t/3} =  \sum_{n=0}^{\infty} \frac{1}{3^{n-1}n!}t^n$$
to:
$$ 3e^{t/3} -3 - t = \sum_{n=2}^{\infty} \frac{1}{3^{n-1}n!}t^n $$
That is what my teacher did, but I can't figure out where did the -3 and -t go.
Comment: Hint: Write the first two terms of the expansion of $3\mathrm e^{\tfrac{t}3}$.
Comment: They were eaten by the $n=2$.
Answer: The expression$$\sum_{n=0}^{\infty}\frac1{3^{n-1}n!}t^n$$means$$\frac1{3^{-1}}+t+\frac1{3\times2}t^2+\frac1{3^2\times3!}t^3+\cdots$$Its first two terms are $3+t$ and therefore, since$$3e^{t/3}=\sum_{n=0}^{\infty} \frac{1}{3^{n-1}n!}t^n=\frac1{3^{-1}}+t+\frac1{3\times2}t^2+\frac1{3^2\times3!}t^3+\cdots,$$you have$$3e^{t/3}-3-t=\frac1{3\times2}t^2+\frac1{3^2\times3!}t^3+\cdots=\sum_{n=2}^\infty\frac1{3^{n-1}n!}t^n.$$
Answer: Simply, $$\sum_{n=0}^\infty a_n=a_0+\sum_{n=1}^\infty a_n=a_0+a_1+\sum_{n=2}^\infty a_n$$ and
$$\sum_{n=0}^\infty a_n-a_0-a_1=\sum_{n=2}^\infty a_n.$$

Taylor development series


OpenSSL Wrong version number on Ubuntu SSH

Question: I'm setting my nginx to listen to port 8080 here's my config file and it works on when I'm accessing with http e.g http://myweb.com:8080/api/.
server {
    listen 8080;

    location / {
        proxy_pass http://localhost:8080;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_ssl_server_name on;
    }
}

However when I try to access it with https on Insomnia it returns SSL connect error.
When I try  curl https://myweb.com:8080 --verbose
It returns something like this:
*   Trying {myipadress}:8080...
* Connected to myweb.com (ipaddress) port 8080 (#0)
* ALPN: offers h2,http/1.1
* TLSv1.3 (OUT), TLS handshake, Client hello (1):
*  CAfile: /etc/ssl/certs/ca-certificates.crt
*  CApath: none
* OpenSSL/3.0.8: error:0A00010B:SSL routines::wrong version number
* Closing connection 0
curl: (35) OpenSSL/3.0.8: error:0A00010B:SSL routines::wrong version number

I've been configuring for two days and IDK what's wrong, does anybody have similar issue?
Answer: This error is due to simply using https:// on a target and port, which is configured for plain http://.
HTTPS and HTTP are different protocols, which need to be configured on different ports and also need different configuration. Specially support for HTTPS needs also the configuration of certificates on the server side. See nginx documentation for how to configure HTTPS.
Comment: @stanley355: to cite myself with the relevant part in bold: *".... which __need to be configured on different ports__ and also need different configuration"*
Comment: Should I put the ssl_certificate on port 8080 as well ?


Probability that the product of Brownian motion at two dates is positive

Question: Let $(B_t)_{t \ge 0}$ be a standard Brownian motion, $B_0 = 0$.
$0 \le t_1 \le t_2$
As the title says, I am trying to calculate the following probability :
$\text{Pr}(B_{t_1}B_{t_2} \ge 0)$
Any leads ?
Comment: By symmetry, $\mathbb P(B_{t_1}\geqslant 0)=\frac12$. Then
$$
\mathbb P(B_{t_1}\geqslant 0, B_{t_2}\geqslant 0) = \mathbb P(B_{t_2}\geqslant 0\mid B_{t_1}\geqslant 0)\mathbb P(B_{t_1}\geqslant 0).$$
Comment: @Math1000 got that far.

How do you get the following ??

$\mathbb{P}(B_{t_{2}} \ge 0 | B_{t_{1}} \ge 0)$
Answer: Fix $s < t$. By symmetry of Brownian motion, we have $$\mathbb{P}(B_s B_t \geq 0) = \mathbb{P}(B_s \geq 0, B_t \geq 0) + \mathbb{P}(-B_s \geq 0, -B_t \geq 0) = 2 \mathbb{P}(B_s \geq 0, B_t \geq 0).$$ Consequently, it suffices to compute the probability on the right-hand side. Conditioning on $\mathcal{F}_s := \sigma(B_r; r \leq s)$, we find from the Markov property that
$$\mathbb{P}(B_s \geq 0, B_t \geq 0)= \mathbb{E}\left( 1_{\{B_s \geq 0\}} \mathbb{P}(B_{t-s}+x \geq 0) \bigg|_{x=B_s}\right). \tag{1}$$
Denote by $\Phi$ the cdf of the standard Gaussian distribution. Since $B_{t-s}$ is Gaussian with mean $0$ and variance $t-s$, we have
$$\mathbb{P}(B_{t-s}  +x \geq 0) = \mathbb{P}(B_{t-s} \leq x) = \Phi(x/\sqrt{t-s}).$$
Hence, by $(1)$,
$$\mathbb{P}(B_s \geq 0,B_t \geq 0) = \mathbb{E}(1_{\{B_s \geq 0\}} \Phi(B_s/\sqrt{t-s})).$$
If we denote by $\varphi$ the density of the Gaussian distribution, then we can write this equivalently as
$$\mathbb{P}(B_s \geq 0,B_t \geq 0) = \int_0^{\infty} \Phi(\sqrt{s} x/\sqrt{t-s}) \varphi(x) \, dx.$$
The latter integral can be calculated explicitly, see e.g. this answer, and we get
$$\mathbb{P}(B_s \geq 0,B_t \geq 0) = \frac{1}{4} + \frac{1}{2\pi} \arctan \sqrt{\frac{s}{t-s}}.$$
Hence,
$$\mathbb{P}(B_s B_t \geq 0)= \frac{1}{2} + \frac{1}{\pi} \arctan \sqrt{\frac{s}{t-s}}.$$
A short sanity check: For $s=t$ both sides equal $1$ - as they should.
Comment: Great answer, thanks a lot !
Comment: @user135520 Because the distribution of $B_s$ is not standard Gaussian but Gaussian with mean $0$ and variance $s$.
Comment: @Cerberos26 You are welcome.
Comment: @saz Why is $$\mathbb{P}(B_s \geq 0,B_t \geq 0) = \int_0^{\infty} \Phi(\sqrt{s} x/\sqrt{t-s}) \varphi(x) \, dx.$$ and not $$\mathbb{P}(B_s \geq 0,B_t \geq 0) = \int_0^{\infty} \Phi(x/\sqrt{t-s}) \varphi(x) \, dx.$$


Python RegEx nested search and replace

Question: I need to to a RegEx search and replace of all commas found inside of quote blocks.
i.e.
"thing1,blah","thing2,blah","thing3,blah",thing4

needs to become
"thing1\,blah","thing2\,blah","thing3\,blah",thing4

my code:
inFile  = open(inFileName,'r')
inFileRl = inFile.readlines()
inFile.close()

p = re.compile(r'["]([^"]*)["]')
for line in inFileRl:
    pg = p.search(line)
    # found comment block
    if pg:
        q  = re.compile(r'[^\\],')
        # found comma within comment block
        qg = q.search(pg.group(0))
        if qg:
            # Here I want to reconstitute the line and print it with the replaced text
            #print re.sub(r'([^\\])\,',r'\1\,',pg.group(0))

I need to filter only the columns I want based on a RegEx, filter further,
then do the RegEx replace, then reconstitute the line back.
How can I do this in Python?
Comment: @Dragos Toader: Why would you want to replace commas inside quotes?  `csv.reader` has no problems with commas inside quotes.
Comment: not really an answer but before you reimplement one, maybe you could be better served by a CSV parser? That seems the format you are dealing with.
Comment: I'm actually looking to get the data ready for my custom CSV parser csv.register_dialect(
   'escapedExcel'                   ,
   delimiter        = ','           ,
   skipinitialspace = 0             ,
   doublequote      = 1             ,
   quoting          = csv.QUOTE_ALL ,
   quotechar        = '"'           ,
   lineterminator   = '\r\n'        ,
   escapechar       = '\\'          )
Comment: I see, then I believe you want to use the methods `span` and `start` of the match object to get at the stuff that was around it and recompose your line. But I am not sure why a single call to sub after the "selecting" loop would not be ok.
Comment: Adding backslashes just means yet another mechanism for your parser to cope with. Now you will need to backslash all backslashes, too. The proper fix is to teach your CSV parser to ignore commas inside double quotes, or use an existing CSV parser which does.
Comment: I have a csv.reader wrapper that gave me some errors -- so I erroneously thought that csv.reader itself was not able to read internal quoted commas.
Answer: The csv module is perfect for parsing data like this as csv.reader in the default dialect ignores quoted commas.  csv.writer reinserts the quotes due to the presence of commas.  I used StringIO to give a file like interface to a string.
import csv
import StringIO

s = '''"thing1,blah","thing2,blah","thing3,blah"
"thing4,blah","thing5,blah","thing6,blah"'''
source = StringIO.StringIO(s)
dest = StringIO.StringIO()
rdr = csv.reader(source)
wtr = csv.writer(dest)
for row in rdr:
    wtr.writerow([item.replace('\\,',',').replace(',','\\,') for item in row])
print dest.getvalue()

result:
"thing1\,blah","thing2\,blah","thing3\,blah"
"thing4\,blah","thing5\,blah","thing6\,blah"

Comment: +1 But you need to write ``item.replace('\\,',',').replace(',','\\,')`` , otherwise **"thing3\,blah "** is replaced with **"thing3\\,blah "**
Answer: General Edit
There was
"thing1\\,blah","thing2\\,blah","thing3\\,blah",thing4

in the question, and now it is not there anymore.
Moreover, I hadn't remarked r'[^\\],'.
So, I completely rewrite my answer.
"thing1,blah","thing2,blah","thing3,blah",thing4

and
"thing1\,blah","thing2\,blah","thing3\,blah",thing4

being displays of strings (I suppose)
import re

ss = '"thing1,blah","thing2,blah","thing3\,blah",thing4 '

regx = re.compile('"[^"]*"')

def repl(mat, ri = re.compile('(?<!\\\\),') ):
    return ri.sub('\\\\',mat.group())

print ss
print repr(ss)
print
print      regx.sub(repl, ss)
print repr(regx.sub(repl, ss))

result
"thing1,blah","thing2,blah","thing3\,blah",thing4
'"thing1,blah","thing2,blah","thing3\\,blah",thing4 '

"thing1\blah","thing2\blah","thing3\,blah",thing4
'"thing1\\blah","thing2\\blah","thing3\\,blah",thing4 '

Comment: This answer has been upvoted. I would like to know why. I'm also perplexed by the fact that my rep is then diminished of 1 and not 2 points !
Answer: You can try this regex.

>>> re.sub('(?<!"),(?!")', r"\\,",
                     '"thing1,blah","thing2,blah","thing3,blah",thing4')
#Gives "thing1\,blah","thing2\,blah","thing3\,blah",thing4

The logic behind this is to substitute a , with \, if it is not immediately both preceded and followed by a "
Comment: Your solution is better than mine. You just need to write the pattern ``'([^"]+) *, *([^"]+)'`` or even ``'([^"]+)[\t ]*,[\t ]*([^"]+)'`` in case a comma is between blanks
Comment: Added the checks you mentioned. Thanks!
Comment: How does this work with strings with two commas between the quotes?  `"thing1,blah,moreblah"`
Comment: @StevenRumbalski Yes, it does not work in that case. Both lookahead and lookbehind have to be used in that scenario. I will see if i can make those changes.
Comment: How about `re.sub('".+?"', lambda m: m.group(0).replace(',','\\,'), '"th,ing1,blah","thing2,""blah""","thing3,blah",thing4')`?
Comment: I made the required changes. Even the one you specified works like a charm. Thanks for pointing out the error!
Comment: @Steven Rumbalski By Jove , I didn't think to that ! Moreover, with your code, Narendra, ``"thing3\,blah"`` is transformed into ``"thing3\\,blah"`` instead of remaining untouched. Alas, lookahead and lookbehind assertions can't help because ``r"\1\\,\2"`` adds an antislash before a UNIQUE comma (the last one between " " because ``[^"]+`` is greedy) and the other commas remain out of care. I don't see any possibility to improve your pattern with lookbehind and looahead assertions. Sorry , I remove my upvote on this answer. But I put an upvote on another answer of you (regex for anagram)
Comment: @Steven Rumbalski Your replacement transforms ``"thing3\,blah"`` into ``"thing3\\,blah"`` but the OP doesn't want already present slashes to be doubled; see ``r'[^\\],'`` in his code
Answer: I came up with an iterative solution using several regex functions:
finditer(), findall(), group(), start() and end()
There's a way to turn all this into a recursive function that calls itself.
Any takers?
outfile  = open(outfileName,'w')

p = re.compile(r'["]([^"]*)["]')
q = re.compile(r'([^\\])(,)')
for line in outfileRl:
    pg = p.finditer(line)
    pglen = len(p.findall(line))

    if pglen > 0:
        mpgstart = 0;
        mpgend   = 0;

        for i,mpg in enumerate(pg):
            if i == 0:
                outfile.write(line[:mpg.start()])

            qg    = q.finditer(mpg.group(0))
            qglen = len(q.findall(mpg.group(0)))

            if i > 0 and i < pglen:
                outfile.write(line[mpgend:mpg.start()])

            if qglen > 0:
                for j,mqg in enumerate(qg):
                    if j == 0:
                        outfile.write( mpg.group(0)[:mqg.start()]    )

                    outfile.write( re.sub(r'([^\\])(,)',r'\1\\\2',mqg.group(0)) )

                    if j == (qglen-1):
                        outfile.write( mpg.group(0)[mqg.end():]      )
            else:
                outfile.write(mpg.group(0))

            if i == (pglen-1):
                outfile.write(line[mpg.end():])

            mpgstart = mpg.start()
            mpgend   = mpg.end()
    else:
        outfile.write(line)

outfile.close()

Comment: Your code is incredibly tortuous: you are using regexes to do just a tiny part of what the regexes are for, in order to obtain elements of string on which you perform treatments thanks to string methods that are precisely what is done with regexes. By the way, you didn't remarked that your code gives a false result for **"thing3,blah"** that is transformed into **"thingx\x03,blah"** , I don't know how.
Comment: Also, by the way, did you, at any moment, remarked that there were answers and debates concerning the question you precisely put to obtain answers ? You doesn't do the slightestt allusion to other answers that we hoped helpful. Instead of that, you show a code without any interest, as if you haven't read the answers. I find this a little unfair.
Answer: have you looked into str.replace()?

str.replace(old, new[, count])
      Return a copy of the string with all occurrences of substring old
  replaced by new. If the optional argument count is given, only the
  first count occurrences are replaced.

here is some documentation
hope this helps

Python RegEx nested search and replace


Create a dll from a Windows 8.1 / Windows Phone 8.1 application with views and database

Question: I'm creating a Windows Phone 8.1 app that's supposed to act as a Library for other Windows Phone 8.1 applications. In my new apps I can add the Library project to the solution and thus it functions as a kind of external Library and this does what I want it to do.
However, I would like to know if there is some way of exporting my WP Library app to, for example, a .dll that I could add as reference to my new applications. Is there any other way I could accomplish this?
It is worth mentioning that my Library App will have views and even a database, not just methods to deal with the data from the main application.
Answer: Since it is a Windows 8.1 / Windows Phone 8.1.  You can take a look at the Store Apps -> Universal Apps -> Class Library (Portable for Universal Apps).

After compiling it to a dll, just add a reference to said dll to the reference folder.
To use the your library in C# , just type in your namespace that you use to create the library.
using your_namespace_from_library;

To use your Views and what not from XAML, just type in your namespace in the XAML file as well
<Page xmlns:YOUR_AWESOME_TAG="using:your_namespace_from_library">

Then you can use your tags from the library by doing this:
<YOUR_AWESOME_TAG:Your_View>

:)

To solve the Payload problem check out the error message, it should something similar to this:

Look at it very carefully.  It is trying to reference a directory that doesn't exist to get the right files.  The solution (the only one I know of) is to go to that directory and make it.  In my case, it is "C:\Users\Duan\Documents\Visual Studio 2013\Projects\Chubosaurus.Charts_Old2\Chubosaurus.Charts\bin\Debug\Chubosaurus.Charts"
For some reason it decided to create an extra directory in the Debug folder where the dll is compile to.  So create that Folder which is the name of the library.  And this is the part you're not going to like.  Copy the entire content of the Debug folder into that directory you just created (mostly importantly, the Theme folder).
Run your program again, your issues will be resolve.  But unfortunately, you have to do this every time you compile that dll project.  This is why I said just add the library project as part of the solution until you're ready to package it up into NuGet.  Hope that helps.

A Simple Library (Tutorial)
Say I want to make a Portable Library for charting call ChubCharts,  I create the Project and it loads me up with a default Portable library with a file call Class1.cs
First thing I do is delete that file :)
Then I add in a Template Control from Add -> Add New Item -> Templated Control
I name that ChubosaurusCharts it should look like this once it's generated.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Documents;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;

public sealed class ChubosaurusCharts : Control
{
    public ChubosaurusCharts()
    {
        this.DefaultStyleKey = typeof(ChubosaurusCharts);
    }
}

Now I have the most simple control ever.  Lets apply a ContentTemplate to it so I can make into a Composite Control so it will actually have something to do :)
Visual Studios makes a folder call Themes inside the solution.  Inside that folder is a file named "Generic.xaml" which contains our template.

Now I want to edit the content I will be putting in my Custom Control
Generic.xaml

By default it just a plain old <Border> :(,  I don't want that.  Since this is a Charting Library.  I would like a few things added to the Visual Tree, mainly a <Canvas>, so lets change that into:

By now you should of guess you can add as many XAML tags as you want that you need to display your Control correctly.  I just want a <Canvas>.

Now with a little DataBinding Magic, I bind the Canvas to the canvas of my control for easy access :)
public sealed class ChubosaurusCharts : Control
{
    public ChubosaurusCharts()
    {
        this.DefaultStyleKey = typeof(ChubosaurusCharts);
        this.Surface = new Canvas();
    }

    private Canvas surface;

    public Canvas Surface
    {
        get
        {
            return surface;
        }
        set
        {
            surface = value;
        }
    }
}

Now it's ready to use :D
Add the Portable Library to your solution added in the namespace.  Compile.
Omitting crazy grade-school algebra and my RenderFunction (which just adds lines to the canvas)
Add our custom control to MainPage.xaml, you can also drag the control from the Toolbox now :D
<chubo:ChubosaurusCharts x:Name="my_chart">

And the result of your hard work is :

Cheers :D
Comment: I never thought about doing it that way.  I always thought you made your `Class MyTag : Control` and from there you set the style of the `` for said control.  Inside there is where you put your regular XAML tags which constitute your view.  This way anyone using your libraries can override your control template like you can do with ListBox,ListView, etc etc.
Comment: This does compile to a .dll, however when I create a View in my Library and then call in my App, like so: `Page page = ClassLibraryTest.Class1.GetPage();` I get the error: "Payload file '' does not exist". I found this [answer](http://social.msdn.microsoft.com/Forums/windowsapps/en-US/51111470-8a86-44d4-acb8-e268afa7564e/payload-file-does-not-exist-compile-error) although old, it seems plausible. Do you have any suggestion to this?
Comment: Yes, I have a solution to that problem (but you're not going to like it).  If you're not ready to package up a dll file, then it best to add the class library to the solution as well.  Then you can reference it by the project.  There are numerous web articles on how to package up your dll file to NuGet and the like.
Comment: Ok, what you're saying is that I can compile my class library with views and database to a nuget package?
Comment: I think I'm right.  Maybe someone with a little more experience can you give you a definite answer.  I updated my solution for your Payload problem, but I still recommend you add it as part of your solution.  It sucks having 2 visual studios open at the same time.
Comment: I do agree with you, the reference should only be added in the final state of the project for easier debugging and compiling. However, I still have a problem, my views are outside my .dll file and I still have to drag them around. How can I create the .dll with the views inside of it so I only have one file to drag around? Maybe with the NuGet packaging?
Comment: Can you provide a simple example of what you just suggested as an answer, or update yours so I can mark it as answer?
Comment: Sure, but the answer will get very long.  Stay toon.
Comment: @ricochete there you go.  There are numerous articles you can read to make things a bit clearer.  I tried my best.
Comment: Thank you @ChubosaurusSoftware, it does work for what I intend. I still can't compact everything into a single file,  but this is a good start. :)


Probability of rolling 2 and 3 numbers in a sequence when rolling 3, 6 sided dice

Question: I am wondering what the probability is to roll numbers in a sequence with 3, 6 sided dice.
" If 3 fair six-sided dice are rolled. What is the probability that at least two of the numbers will be in a sequence (ex: 1,2 or 5,6). Also, what is the probability that all 3 of them will be in a sequence. These dice are all rolled at one time and can be put in any order."
I've tried solving it but I couldn't get it. What is the probability to get these outcomes.
Comment: Hint for the first question: **converse probability**. What is the probabilty that  none of the outcomes of the three die are in sequence ?
Comment: I'm not sure if I could figure that out I would know the answer to the probability of rolling the desired outcome
Answer: An approach to this problem, a bit lengthy but having the advantage to provide a clear picture,
might be the following.
Start from considering the dice marked.
The set of possible, equi-probable, outcomes is represented by $6^3=216$ triples.
Then consider that you want the outcome of die 2 to be consecutive to the outcome of die 1, while the outcome of die 3 can be whatever
$$
\begin{array}{c|ccc}
   {die} &  &  1 & 2 & 3  \\
   {result} &  &  {1 \le k \le 5} & {k + 1} & \forall   \\
   {prob} &  &  {5/6} & {1/6} & 1  \\
\end{array}
$$
the probability of getting such a scheme is $5/36$.
Now, since in our problem order does not matter, we shall swap (permute) the above configuration.
But we cannot perform that without considering the  value of die 3 (call it $j$) compared with the result of die 1 and 2.
In fact, while e.g. $(1,2,3)$ can be permuted in $6$ ways, $(1,1,3)$ can be permuted in $3$ ways.
Moreover, we shall exclude the permuted triples that  fall within the range of those already considered.
So, the prospect of the possible ordered configurations and number of ways to swap them is the following
$$ \bbox[lightyellow] {
\begin{array}{*{20}c}
   {config.} & {N.\,ordered} & {N.\,swaps} & {Tot.}  \\
\hline
   {\left\{ {k,\;k + 1,\;k + 1 < j} \right\}} & {4 + 3 + 2 + 1} & {3!} & {60}  \\
   {\left\{ {k,\;k + 1,\;k + 1 = j} \right\}} & 5 & 3 & {15}  \\
   {\left\{ {k,\;k + 1,\;k = j} \right\}} & 5 & 3 & {15}  \\
   {\left\{ {k,\;k + 1,\;j = k - 1} \right\}} & 4 & 0 & 0  \\
   {\left\{ {k,\;k + 1,\;j < k - 1} \right\}} & {1 + 2 + 3} & {3!} & {36}  \\
\hline
   {{\rm at}\,{\rm least}\,{\rm 2}\,{\rm consecutive}} & {} & {\rm  = } & {126}  \\
\end{array}
} $$
We see that  the fourth configuration is cancelled as being already included in the first.
The prospect for the complementary case (no consecutive outcomes) will give
$$ \bbox[lightyellow] {
\begin{array}{*{20}c}
   {config.} & {N.\,ordered} & {N.\,swaps} & {Tot.}  \\
\hline
   {\left\{ {k,\;k,\;k} \right\}} & 6 & 1 & 6  \\
   {\left\{ {k,\;k,\; \ge k + 2} \right\}} & {4 + 3 + 2 + 1} & 3 & {30}  \\
   {\left\{ {k,\; \ge k + 2,\; = } \right\}} & {4 + 3 + 2 + 1} & 3 & {30}  \\
   {\left\{ {k,\;k + 2,\; \ge k + 4} \right\}} & {2 + 1} & {3!} & {18}  \\
   {\left\{ {k,\;k + 3,\; \ge k + 5} \right\}} & 1 & {3!} & 6  \\
\hline
   {{\rm none}\,{\rm consecutive}} & {} & {\rm  = } & {90}  \\
\end{array}
} $$
In the case of asking for three consecutive outcomes instead, considering them to be ordered we will have
$$
\begin{array}{c|ccc}
   {die} &  &  1 & 2 & 3  \\
   {result} &  &  {1 \le k \le 4} & {k + 1} & {k + 2}   \\
   {prob} &  &  {4/6} & {1/6} & {1/6}  \\
\end{array}
$$
and since each possible triple has distinct values, we can permute them to obtain:
$$ \bbox[lightyellow] {  p(\text{3 consec.})={4/6} \cdot {1/6} \cdot {1/6} \cdot 6=1/9=24/216 }$$.
You can verify by direct counting that the values above are correct.
Comment: So there would be a 83% chance to roll 2 numbers in a row in a linear sequentiality?
Comment: @Aaron: yes $5/6$, when order is not important
Comment: The person below said there is a 94.4% chance?
Comment: @Aaron: I totally recasted my answer: results have been checked vs. direct computation.
Answer: Sequences with the numbers $1,3,5$ and $2,4,6$ have no consecutive numbers.
$1,3,5$ can be ordered in $3!=6$ ways. Similar for $2,4,6$. In total we have $12$ outcomes where the numbers are not consecutive. And we have overall $6^3=216$ possible outcomes.
Thus the probacbility that the sequence has no consecutive numbers is $P(\overline C)= \frac{12}{216}$.
Consequently the probabbility that the sequence has at least consecutive two numbers is
$P( C)=1-P(\overline C)=1- \frac{12}{216}=\frac{216}{216}-\frac{12}{216}=\frac{204}{216}$
Comment: So there would be a total of 24 rolls that would lead to three numbers in sequence? Meaning that there is a 11.11% chance?
Comment: @Aaron Yeah, or in fractional notation $\frac19$.
Comment: Awesome thanks so much for the help! I thought it was very likely to get 2 in a sequence but wasn't sure how likely. Is there any way you can help with getting three in a row?
Comment: The consecutive sequences has the numbers $(1,2,3), (2,3,4), (3,4,5),(4,5,6)$ They all can be ordered in 6 ways each.  Does it help ?
Comment: @callculus you're forgetting sequences like 1,1,3 and 4,4,6 where one of the numbers is repeated. 24 *is* the right number for 3-sequences.
Answer: Hint - For sequence on two dice.
You have to consider all different cases. If sequence of 2 numbers on 1st and 2nd dice. Then it should not be 6 on first die. Then number on first die $\frac 56$ and on second $\frac 16$ then on last one it can be not in sequence so it can be any of the remaining 5 numbers so $\frac 56$.
Similarly case of sequence on 2nd and 3rd dice.
Answer: The case of 3 sequential numbers is much easier to calculate than the 2 case. There are only 4 possible sequences: 123, 234, 345, 456. Each of them can be rolled 6 different ways: for example, for 345 the dice can be 345, 354, 435, 453, 534, or 543. So there are 24 possible 3-sequences out of 216 possible rolls.
Table of all the possibilities: