text stringlengths 1 2.12k | source dict |
|---|---|
python, template, tkinter, gui, factory-method
"category": "Nichtmetalle",
"group": 16,
"period": 3,
"block": "p",
"mass": 32.06,
"phase": "fest",
"density": 2.07,
"electronegativity": 2.58
},
{
"symbol": "Cl",
"name": "Chlor",
"number": 17,
"category": "Halogene",
"group": 17,
"period": 3,
"block": "p",
"mass": 35.45,
"phase": "gasförmig",
"density": 3.22,
"electronegativity": 3.16
},
{
"symbol": "Ar",
"name": "Argon",
"number": 18,
"category": "Edelgase",
"group": 18,
"period": 3,
"block": "p",
"mass": 39.95,
"phase": "gasförmig",
"density": 1.78,
"electronegativity": null
},
{
"symbol": "K",
"name": "Kalium",
"number": 19,
"category": "Alkalimetalle",
"group": 1,
"period": 4,
"block": "s",
"mass": 39.09,
"phase": "fest",
"density": 0.86,
"electronegativity": 0.82
},
{
"symbol": "Ca",
"name": "Calicium",
"number": 20,
"category": "Erdalkalimetalle",
"group": 2,
"period": 4,
"block": "s",
"mass": 40.08,
"phase": "fest",
"density": 1.55,
"electronegativity": 1.0
},
{
"symbol": "Sc",
"name": "Scandium",
"number": 21,
"category": "Übergangsmetalle",
"group": 3,
"period": 4,
"block": "d",
"mass": 44.96,
"phase": "fest",
"density": 2.99,
"electronegativity": 1.36
},
{
"symbol": "Ti",
"name": "Titan",
"number": 22,
"category": "Übergangsmetalle",
"group": 4,
"period": 4,
"block": "d",
"mass": 47.87,
"phase": "fest",
"density": 4.5,
"electronegativity": 1.54
},
{
"symbol": "V",
"name": "Vandium",
"number": 23,
"category": "Übergangsmetalle",
"group": 5,
"period": 4,
"block": "d",
"mass": 50.94,
"phase": "fest",
"density": 6.11,
"electronegativity": 1.63
},
{
"symbol": "Cr",
"name": "Chrom",
"number": 24,
"category": "Übergangsmetalle", | {
"domain": "codereview.stackexchange",
"id": 42679,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, template, tkinter, gui, factory-method",
"url": null
} |
python, template, tkinter, gui, factory-method
{
"symbol": "Cr",
"name": "Chrom",
"number": 24,
"category": "Übergangsmetalle",
"group": 6,
"period": 4,
"block": "d",
"mass": 51.99,
"phase": "fest",
"density": 7.14,
"electronegativity": 1.66
},
{
"symbol": "Mn",
"name": "Mangan",
"number": 25,
"category": "Übergangsmetalle",
"group": 7,
"period": 4,
"block": "d",
"mass": 54.94,
"phase": "fest",
"density": 7.43,
"electronegativity": 1.55
},
{
"symbol": "Fe",
"name": "Eisen",
"number": 26,
"category": "Übergangsmetalle",
"group": 8,
"period": 4,
"block": "d",
"mass": 55.85,
"phase": "fest",
"density": 7.87,
"electronegativity": 1.83
},
{
"symbol": "Co",
"name": "Cobalt",
"number": 27,
"category": "Übergangsmetalle",
"group": 9,
"period": 4,
"block": "d",
"mass": 58.93,
"phase": "fest",
"density": 8.9,
"electronegativity": 1.88
},
{
"symbol": "Ni",
"name": "Nickel",
"number": 28,
"category": "Übergangsmetalle",
"group": 10,
"period": 4,
"block": "d",
"mass": 58.69,
"phase": "fest",
"density": 8.9,
"electronegativity": 1.91
},
{
"symbol": "Cu",
"name": "Kupfer",
"number": 29,
"category": "Übergangsmetalle",
"group": 11,
"period": 4,
"block": "d",
"mass": 63.54,
"phase": "fest",
"density": 8.92,
"electronegativity": 1.9
},
{
"symbol": "Zn",
"name": "Zink",
"number": 30,
"category": "Übergangsmetalle",
"group": 12,
"period": 4,
"block": "d",
"mass": 65.38,
"phase": "fest",
"density": 7.14,
"electronegativity": 1.65
},
{
"symbol": "Ga",
"name": "Gallium",
"number": 31,
"category": "Metalle",
"group": 13,
"period": 4,
"block": "p",
"mass": 69.72,
"phase": "fest",
"density": 5.9,
"electronegativity": 1.81
},
{
"symbol": "Ge", | {
"domain": "codereview.stackexchange",
"id": 42679,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, template, tkinter, gui, factory-method",
"url": null
} |
python, template, tkinter, gui, factory-method
"phase": "fest",
"density": 5.9,
"electronegativity": 1.81
},
{
"symbol": "Ge",
"name": "Germanium",
"number": 32,
"category": "Halbmetalle",
"group": 14,
"period": 4,
"block": "p",
"mass": 72.63,
"phase": "fest",
"density": 5.32,
"electronegativity": 2.01
},
{
"symbol": "As",
"name": "Arsen",
"number": 33,
"category": "Halbmetalle",
"group": 15,
"period": 4,
"block": "p",
"mass": 74.92,
"phase": "fest",
"density": 5.73,
"electronegativity": 2.18
},
{
"symbol": "Se",
"name": "Selen",
"number": 34,
"category": "Halbmetalle",
"group": 16,
"period": 4,
"block": "p",
"mass": 78.97,
"phase": "fest",
"density": 4.82,
"electronegativity": 2.55
},
{
"symbol": "Br",
"name": "Brom",
"number": 35,
"category": "Halogene",
"group": 17,
"period": 4,
"block": "p",
"mass": 79.9,
"phase": "flüssig",
"density": 3.12,
"electronegativity": 2.96
},
{
"symbol": "Kr",
"name": "Krypton",
"number": 36,
"category": "Edelgase",
"group": 18,
"period": 4,
"block": "p",
"mass": 83.8,
"phase": "gasförmig",
"density": 3.75,
"electronegativity": 3.0
},
{
"symbol": "Rb",
"name": "Rubidium",
"number": 37,
"category": "Alkalimetalle",
"group": 1,
"period": 5,
"block": "s",
"mass": 85.47,
"phase": "fest",
"density": 1.53,
"electronegativity": 0.82
},
{
"symbol": "Sr",
"name": "Strontium",
"number": 38,
"category": "Erdalkalimetalle",
"group": 2,
"period": 5,
"block": "s",
"mass": 87.62,
"phase": "fest",
"density": 2.63,
"electronegativity": 0.95
},
{
"symbol": "Y",
"name": "Yttrium",
"number": 39,
"category": "Übergangsmetalle",
"group": 3,
"period": 5,
"block": "d",
"mass": 88.91,
"phase": "fest",
"density": 4.47, | {
"domain": "codereview.stackexchange",
"id": 42679,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, template, tkinter, gui, factory-method",
"url": null
} |
python, template, tkinter, gui, factory-method
"period": 5,
"block": "d",
"mass": 88.91,
"phase": "fest",
"density": 4.47,
"electronegativity": 1.22
},
{
"symbol": "Zr",
"name": "Zirconium",
"number": 40,
"category": "Übergangsmetalle",
"group": 4,
"period": 5,
"block": "d",
"mass": 91.22,
"phase": "fest",
"density": 6.5,
"electronegativity": 1.33
},
{
"symbol": "Nb",
"name": "Niob",
"number": 41,
"category": "Übergangsmetalle",
"group": 5,
"period": 5,
"block": "d",
"mass": 92.9,
"phase": "fest",
"density": 8.57,
"electronegativity": 1.6
},
{
"symbol": "Mo",
"name": "Molybdän",
"number": 42,
"category": "Übergangsmetalle",
"group": 6,
"period": 5,
"block": "d",
"mass": 95.95,
"phase": "fest",
"density": 10.28,
"electronegativity": 2.16
},
{
"symbol": "Tc",
"name": "Technetium",
"number": 43,
"category": "Übergangsmetalle",
"group": 7,
"period": 5,
"block": "d",
"mass": 98.9,
"phase": "fest",
"density": 11.5,
"electronegativity": 1.9
},
{
"symbol": "Ru",
"name": "Ruthenium",
"number": 44,
"category": "Übergangsmetalle",
"group": 8,
"period": 5,
"block": "d",
"mass": 101.07,
"phase": "fest",
"density": 12.37,
"electronegativity": 2.2
},
{
"symbol": "Rh",
"name": "Rhodium",
"number": 45,
"category": "Übergangsmetalle",
"group": 9,
"period": 5,
"block": "d",
"mass": 102.9,
"phase": "fest",
"density": 12.38,
"electronegativity": 2.28
},
{
"symbol": "Pd",
"name": "Palladium",
"number": 46,
"category": "Übergangsmetalle",
"group": 10,
"period": 5,
"block": "d",
"mass": 106.42,
"phase": "fest",
"density": 11.99,
"electronegativity": 2.2
},
{
"symbol": "Ag",
"name": "Silber",
"number": 47,
"category": "Übergangsmetalle",
"group": 11, | {
"domain": "codereview.stackexchange",
"id": 42679,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, template, tkinter, gui, factory-method",
"url": null
} |
python, template, tkinter, gui, factory-method
"name": "Silber",
"number": 47,
"category": "Übergangsmetalle",
"group": 11,
"period": 5,
"block": "d",
"mass": 107.87,
"phase": "fest",
"density": 10.49,
"electronegativity": 1.93
},
{
"symbol": "Cd",
"name": "cadmium",
"number": 48,
"category": "Übergangsmetalle",
"group": 12,
"period": 5,
"block": "d",
"mass": 112.41,
"phase": "fest",
"density": 8.65,
"electronegativity": 1.69
},
{
"symbol": "In",
"name": "Indium",
"number": 49,
"category": "Metalle",
"group": 13,
"period": 5,
"block": "p",
"mass": 114.82,
"phase": "fest",
"density": 7.31,
"electronegativity": 1.78
},
{
"symbol": "Sn",
"name": "Zinn",
"number": 50,
"category": "Metalle",
"group": 14,
"period": 5,
"block": "p",
"mass": 118.71,
"phase": "fest",
"density": 5.77,
"electronegativity": 1.96
},
{
"symbol": "Sb",
"name": "Antimon",
"number": 51,
"category": "Halbmetalle",
"group": 15,
"period": 5,
"block": "p",
"mass": 121.76,
"phase": "fest",
"density": 6.7,
"electronegativity": 2.05
},
{
"symbol": "Te",
"name": "Tellur",
"number": 52,
"category": "Halbmetalle",
"group": 16,
"period": 5,
"block": "p",
"mass": 127.6,
"phase": "fest",
"density": 6.24,
"electronegativity": 2.1
},
{
"symbol": "I",
"name": "Iod",
"number": 53,
"category": "Halogene",
"group": 17,
"period": 5,
"block": "p",
"mass": 126.9,
"phase": "fest",
"density": 4.94,
"electronegativity": 2.66
},
{
"symbol": "Xe",
"name": "Xenon",
"number": 54,
"category": "Edelgase",
"group": 18,
"period": 5,
"block": "p",
"mass": 131.29,
"phase": "gasförmig",
"density": 5.9,
"electronegativity": 2.6
},
{
"symbol": "Cs",
"name": "Caesium",
"number": 55, | {
"domain": "codereview.stackexchange",
"id": 42679,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, template, tkinter, gui, factory-method",
"url": null
} |
python, template, tkinter, gui, factory-method
"electronegativity": 2.6
},
{
"symbol": "Cs",
"name": "Caesium",
"number": 55,
"category": "Alkalimetalle",
"group": 1,
"period": 6,
"block": "s",
"mass": 132.91,
"phase": "fest",
"density": 1.9,
"electronegativity": 0.79
},
{
"symbol": "Ba",
"name": "Barium",
"number": 56,
"category": "Erdalkalimetalle",
"group": 2,
"period": 6,
"block": "s",
"mass": 137.33,
"phase": "fest",
"density": 3.62,
"electronegativity": 0.89
},
{
"symbol": "La",
"name": "Lanthan",
"number": 57,
"category": "Übergangsmetalle",
"group": 3,
"period": 6,
"block": "d",
"mass": 138.9,
"phase": "fest",
"density": 6.17,
"electronegativity": 1.1
},
{
"symbol": "Ce",
"name": "Cer",
"number": 58,
"category": "Lanthanoide",
"group": "La",
"period": 6,
"block": "f",
"mass": 140.12,
"phase": "fest",
"density": 6.77,
"electronegativity": 1.12
},
{
"symbol": "Pr",
"name": "Praseodym",
"number": 59,
"category": "Lanthanoide",
"group": "La",
"period": 6,
"block": "f",
"mass": 140.91,
"phase": "fest",
"density": 6.48,
"electronegativity": 1.13
},
{
"symbol": "Nd",
"name": "Neodym",
"number": 60,
"category": "Lanthanoide",
"group": "La",
"period": 6,
"block": "f",
"mass": 144.24,
"phase": "fest",
"density": 7.0,
"electronegativity": 1.14
},
{
"symbol": "Pm",
"name": "Promethium",
"number": 61,
"category": "Lanthanoide",
"group": "La",
"period": 6,
"block": "f",
"mass": 146.91,
"phase": "fest",
"density": 7.2,
"electronegativity": null
},
{
"symbol": "Sm",
"name": "Samarium",
"number": 62,
"category": "Lanthanoide",
"group": "La",
"period": 6,
"block": "f",
"mass": 150.36,
"phase": "fest",
"density": 7.54, | {
"domain": "codereview.stackexchange",
"id": 42679,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, template, tkinter, gui, factory-method",
"url": null
} |
python, template, tkinter, gui, factory-method
"period": 6,
"block": "f",
"mass": 150.36,
"phase": "fest",
"density": 7.54,
"electronegativity": 1.17
},
{
"symbol": "Eu",
"name": "Europium",
"number": 63,
"category": "Lanthanoide",
"group": "La",
"period": 6,
"block": "f",
"mass": 151.96,
"phase": "fest",
"density": 5.25,
"electronegativity": null
},
{
"symbol": "Gd",
"name": "Gadolinium",
"number": 64,
"category": "Lanthanoide",
"group": "La",
"period": 6,
"block": "f",
"mass": 157.25,
"phase": "fest",
"density": 7.89,
"electronegativity": 1.2
},
{
"symbol": "Tb",
"name": "Terbium",
"number": 65,
"category": "Lanthanoide",
"group": "La",
"period": 6,
"block": "f",
"mass": 158.93,
"phase": "fest",
"density": 8.25,
"electronegativity": null
},
{
"symbol": "Dy",
"name": "Dysprosium",
"number": 66,
"category": "Lanthanoide",
"group": "La",
"period": 6,
"block": "f",
"mass": 162.5,
"phase": "fest",
"density": 8.56,
"electronegativity": 1.22
},
{
"symbol": "Ho",
"name": "Holmium",
"number": 67,
"category": "Lanthanoide",
"group": "La",
"period": 6,
"block": "f",
"mass": 164.93,
"phase": "fest",
"density": 8.78,
"electronegativity": 1.23
},
{
"symbol": "Er",
"name": "Erbium",
"number": 68,
"category": "Lanthanoide",
"group": "La",
"period": 6,
"block": "f",
"mass": 167.26,
"phase": "fest",
"density": 9.05,
"electronegativity": 1.24
},
{
"symbol": "Tm",
"name": "Thulium",
"number": 69,
"category": "Lanthanoide",
"group": "La",
"period": 6,
"block": "f",
"mass": 168.93,
"phase": "fest",
"density": 9.32,
"electronegativity": 1.25
},
{
"symbol": "Yb",
"name": "Ytterbium",
"number": 70,
"category": "Lanthanoide",
"group": "La",
"period": 6, | {
"domain": "codereview.stackexchange",
"id": 42679,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, template, tkinter, gui, factory-method",
"url": null
} |
python, template, tkinter, gui, factory-method
"number": 70,
"category": "Lanthanoide",
"group": "La",
"period": 6,
"block": "f",
"mass": 173.05,
"phase": "fest",
"density": 6.97,
"electronegativity": null
},
{
"symbol": "Lu",
"name": "Lutetium",
"number": 71,
"category": "Lanthanoide",
"group": "La",
"period": 6,
"block": "f",
"mass": 174.97,
"phase": "fest",
"density": 9.84,
"electronegativity": 1.27
},
{
"symbol": "Hf",
"name": "Hafnium",
"number": 72,
"category": "Übergangsmetalle",
"group": 4,
"period": 6,
"block": "d",
"mass": 178.49,
"phase": "fest",
"density": 13.28,
"electronegativity": 1.3
},
{
"symbol": "Ta",
"name": "Tantal",
"number": 73,
"category": "Übergangsmetalle",
"group": 5,
"period": 6,
"block": "d",
"mass": 180.95,
"phase": "fest",
"density": 16.65,
"electronegativity": 1.5
},
{
"symbol": "W",
"name": "Wolfram",
"number": 74,
"category": "Übergangsmetalle",
"group": 6,
"period": 6,
"block": "d",
"mass": 183.84,
"phase": "fest",
"density": 19.25,
"electronegativity": 2.36
},
{
"symbol": "Re",
"name": "Rhenium",
"number": 75,
"category": "Übergangsmetalle",
"group": 7,
"period": 6,
"block": "d",
"mass": 186.21,
"phase": "fest",
"density": 21.0,
"electronegativity": 1.9
},
{
"symbol": "Os",
"name": "Osmium",
"number": 76,
"category": "Übergangsmetalle",
"group": 8,
"period": 6,
"block": "d",
"mass": 190.23,
"phase": "fest",
"density": 22.59,
"electronegativity": 2.2
},
{
"symbol": "Ir",
"name": "Irdium",
"number": 77,
"category": "Übergangsmetalle",
"group": 9,
"period": 6,
"block": "d",
"mass": 192.22,
"phase": "fest",
"density": 22.56,
"electronegativity": 2.2
},
{
"symbol": "Pt",
"name": "Platin", | {
"domain": "codereview.stackexchange",
"id": 42679,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, template, tkinter, gui, factory-method",
"url": null
} |
python, template, tkinter, gui, factory-method
"electronegativity": 2.2
},
{
"symbol": "Pt",
"name": "Platin",
"number": 78,
"category": "Übergangsmetalle",
"group": 10,
"period": 6,
"block": "d",
"mass": 195.08,
"phase": "fest",
"density": 21.45,
"electronegativity": 2.2
},
{
"symbol": "Au",
"name": "Gold",
"number": 79,
"category": "Übergangsmetalle",
"group": 11,
"period": 6,
"block": "d",
"mass": 196.97,
"phase": "fest",
"density": 19.32,
"electronegativity": 2.54
},
{
"symbol": "Hg",
"name": "Quecksilber",
"number": 80,
"category": "Übergangsmetalle",
"group": 12,
"period": 6,
"block": "d",
"mass": 200.59,
"phase": "flüssig",
"density": 13.55,
"electronegativity": 2.0
},
{
"symbol": "Tl",
"name": "Thalium",
"number": 81,
"category": "Metalle",
"group": 13,
"period": 6,
"block": "p",
"mass": 204.38,
"phase": "fest",
"density": 11.85,
"electronegativity": 1.62
},
{
"symbol": "Pb",
"name": "Blei",
"number": 82,
"category": "Metalle",
"group": 14,
"period": 6,
"block": "p",
"mass": 207.2,
"phase": "fest",
"density": 11.34,
"electronegativity": 2.33
},
{
"symbol": "Bi",
"name": "Bismut",
"number": 83,
"category": "Metalle",
"group": 15,
"period": 6,
"block": "p",
"mass": 208.98,
"phase": "fest",
"density": 9.78,
"electronegativity": 2.02
},
{
"symbol": "Po",
"name": "Polonium",
"number": 84,
"category": "Metalle",
"group": 16,
"period": 6,
"block": "p",
"mass": 209.98,
"phase": "fest",
"density": 9.2,
"electronegativity": 2.0
},
{
"symbol": "At",
"name": "Astat",
"number": 85,
"category": "Halogene",
"group": 17,
"period": 6,
"block": "p",
"mass": 209.99,
"phase": "fest",
"density": null,
"electronegativity": 2.2
},
{ | {
"domain": "codereview.stackexchange",
"id": 42679,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, template, tkinter, gui, factory-method",
"url": null
} |
python, template, tkinter, gui, factory-method
"mass": 209.99,
"phase": "fest",
"density": null,
"electronegativity": 2.2
},
{
"symbol": "Rn",
"name": "Radon",
"number": 86,
"category": "Edelgase",
"group": 18,
"period": 6,
"block": "p",
"mass": 222.0,
"phase": "gasförmig",
"density": 9.73,
"electronegativity": null
},
{
"symbol": "Fr",
"name": "Francium",
"number": 87,
"category": "Alkalimetalle",
"group": 1,
"period": 7,
"block": "s",
"mass": 223.02,
"phase": "fest",
"density": null,
"electronegativity": 0.7
},
{
"symbol": "Ra",
"name": "Radium",
"number": 88,
"category": "Erdalkalimetalle",
"group": 2,
"period": 7,
"block": "s",
"mass": 226.03,
"phase": "fest",
"density": 5.5,
"electronegativity": 0.9
},
{
"symbol": "Ac",
"name": "Actinium",
"number": 89,
"category": "Übergangsmetalle",
"group": 3,
"period": 7,
"block": "d",
"mass": 227.03,
"phase": "fest",
"density": 10.07,
"electronegativity": 1.1
},
{
"symbol": "Th",
"name": "Thorium",
"number": 90,
"category": "Actinoide",
"group": "Ac",
"period": 7,
"block": "f",
"mass": 232.04,
"phase": "fest",
"density": 11.72,
"electronegativity": 1.3
},
{
"symbol": "Pa",
"name": "Protactinium",
"number": 91,
"category": "Actinoide",
"group": "Ac",
"period": 7,
"block": "f",
"mass": 231.04,
"phase": "fest",
"density": 15.37,
"electronegativity": 1.5
},
{
"symbol": "U",
"name": "Uran",
"number": 92,
"category": "Actinoide",
"group": "Ac",
"period": 7,
"block": "f",
"mass": 238.03,
"phase": "fest",
"density": 19.16,
"electronegativity": 1.38
},
{
"symbol": "Np",
"name": "Neptunium",
"number": 93,
"category": "Actinoide",
"group": "Ac",
"period": 7,
"block": "f",
"mass": 237.05, | {
"domain": "codereview.stackexchange",
"id": 42679,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, template, tkinter, gui, factory-method",
"url": null
} |
python, template, tkinter, gui, factory-method
"group": "Ac",
"period": 7,
"block": "f",
"mass": 237.05,
"phase": "fest",
"density": 20.45,
"electronegativity": 1.36
},
{
"symbol": "Pu",
"name": "Plutonium",
"number": 94,
"category": "Actinoide",
"group": "Ac",
"period": 7,
"block": "f",
"mass": 244.06,
"phase": "fest",
"density": 19.82,
"electronegativity": 1.28
},
{
"symbol": "Am",
"name": "Americium",
"number": 95,
"category": "Actinoide",
"group": "Ac",
"period": 7,
"block": "f",
"mass": 243.06,
"phase": "fest",
"density": 13.67,
"electronegativity": 1.3
},
{
"symbol": "Cm",
"name": "Curium",
"number": 96,
"category": "Actinoide",
"group": "Ac",
"period": 7,
"block": "f",
"mass": 247.07,
"phase": "fest",
"density": 13.51,
"electronegativity": 1.3
},
{
"symbol": "Bk",
"name": "Berkelium",
"number": 97,
"category": "Actinoide",
"group": "Ac",
"period": 7,
"block": "f",
"mass": 247,
"phase": "fest",
"density": 14.78,
"electronegativity": 1.3
},
{
"symbol": "Cf",
"name": "Californium",
"number": 98,
"category": "Actinoide",
"group": "Ac",
"period": 7,
"block": "f",
"mass": 251,
"phase": "fest",
"density": 15.1,
"electronegativity": 1.3
},
{
"symbol": "Es",
"name": "Einsteinium",
"number": 99,
"category": "Actinoide",
"group": "Ac",
"period": 7,
"block": "f",
"mass": 252,
"phase": "fest",
"density": 8.84,
"electronegativity": null
},
{
"symbol": "Fm",
"name": "Fermium",
"number": 100,
"category": "Actinoide",
"group": "Ac",
"period": 7,
"block": "f",
"mass": 257.1,
"phase": "fest",
"density": null,
"electronegativity": null
},
{
"symbol": "Md",
"name": "Medelevium",
"number": 101,
"category": "Actinoide",
"group": "Ac", | {
"domain": "codereview.stackexchange",
"id": 42679,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, template, tkinter, gui, factory-method",
"url": null
} |
python, template, tkinter, gui, factory-method
"name": "Medelevium",
"number": 101,
"category": "Actinoide",
"group": "Ac",
"period": 7,
"block": "f",
"mass": 258,
"phase": "fest",
"density": null,
"electronegativity": null
},
{
"symbol": "No",
"name": "Nobelium",
"number": 102,
"category": "Actinoide",
"group": "Ac",
"period": 7,
"block": "f",
"mass": 259,
"phase": "fest",
"density": null,
"electronegativity": null
},
{
"symbol": "Lr",
"name": "Lawrencium",
"number": 103,
"category": "Actinoide",
"group": "Ac",
"period": 7,
"block": "f",
"mass": 266,
"phase": "fest",
"density": null,
"electronegativity": null
},
{
"symbol": "Rf",
"name": "Rutherfordium",
"number": 104,
"category": "Übergangsmetalle",
"group": 4,
"period": 7,
"block": "d",
"mass": 261.11,
"phase": "fest",
"density": 17.0,
"electronegativity": null
},
{
"symbol": "Db",
"name": "Dubnium",
"number": 105,
"category": "Übergangsmetalle",
"group": 5,
"period": 7,
"block": "d",
"mass": 262.11,
"phase": null,
"density": null,
"electronegativity": null
},
{
"symbol": "Sg",
"name": "Seaborgium",
"number": 106,
"category": "Übergangsmetalle",
"group": 6,
"period": 7,
"block": "d",
"mass": 263.12,
"phase": null,
"density": null,
"electronegativity": null
},
{
"symbol": "Bh",
"name": "Bohrium",
"number": 107,
"category": "Übergangsmetalle",
"group": 7,
"period": 7,
"block": "d",
"mass": 262.12,
"phase": null,
"density": null,
"electronegativity": null
},
{
"symbol": "Hs",
"name": "Hassium",
"number": 108,
"category": "Übergangsmetalle",
"group": 8,
"period": 7,
"block": "d",
"mass": 265,
"phase": null,
"density": null,
"electronegativity": null
},
{
"symbol": "Mt", | {
"domain": "codereview.stackexchange",
"id": 42679,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, template, tkinter, gui, factory-method",
"url": null
} |
python, template, tkinter, gui, factory-method
"phase": null,
"density": null,
"electronegativity": null
},
{
"symbol": "Mt",
"name": "Meitnerium",
"number": 109,
"category": "Unbekannt",
"group": 9,
"period": 7,
"block": "d",
"mass": 268,
"phase": null,
"density": null,
"electronegativity": null
},
{
"symbol": "Ds",
"name": "Darmstadtium",
"number": 110,
"category": "Unbekannt",
"group": 10,
"period": 7,
"block": "d",
"mass": 281,
"phase": null,
"density": null,
"electronegativity": null
},
{
"symbol": "Rg",
"name": "Roentgenium",
"number": 111,
"category": "Unbekannt",
"group": 11,
"period": 7,
"block": "d",
"mass": 280,
"phase": null,
"density": null,
"electronegativity": null
},
{
"symbol": "Cn",
"name": "Copernicium",
"number": 112,
"category": "Unbekannt",
"group": 12,
"period": 7,
"block": "d",
"mass": 277,
"phase": null,
"density": null,
"electronegativity": null
},
{
"symbol": "Nh",
"name": "Nihonium",
"number": 113,
"category": "Unbekannt",
"group": 13,
"period": 7,
"block": "p",
"mass": 287,
"phase": null,
"density": null,
"electronegativity": null
},
{
"symbol": "Fl",
"name": "Flerovium",
"number": 114,
"category": "Unbekannt",
"group": 14,
"period": 7,
"block": "p",
"mass": 289,
"phase": null,
"density": null,
"electronegativity": null
},
{
"symbol": "Mc",
"name": "Moscovium",
"number": 115,
"category": "Unbekannt",
"group": 15,
"period": 7,
"block": "p",
"mass": 288,
"phase": null,
"density": null,
"electronegativity": null
},
{
"symbol": "Lv",
"name": "Livermorium",
"number": 116,
"category": "Unbekannt",
"group": 16,
"period": 7,
"block": "p",
"mass": 293,
"phase": null,
"density": null, | {
"domain": "codereview.stackexchange",
"id": 42679,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, template, tkinter, gui, factory-method",
"url": null
} |
python, template, tkinter, gui, factory-method
"period": 7,
"block": "p",
"mass": 293,
"phase": null,
"density": null,
"electronegativity": null
},
{
"symbol": "Ts",
"name": "Tenness",
"number": 117,
"category": "Unbekannt",
"group": 17,
"period": 7,
"block": "p",
"mass": 292,
"phase": null,
"density": null,
"electronegativity": null
},
{
"symbol": "Og",
"name": "Oganesson",
"number": 118,
"category": "Unbekannt",
"group": 18,
"period": 7,
"block": "p",
"mass": 294,
"phase": "fest",
"density": 6.6,
"electronegativity": null
}
] | {
"domain": "codereview.stackexchange",
"id": 42679,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, template, tkinter, gui, factory-method",
"url": null
} |
python, template, tkinter, gui, factory-method
Python
import json
import tkinter as tk
import webbrowser
from locale import setlocale, LC_ALL, format_string
from typing import Optional, Union, Iterable, Iterator, NamedTuple
class Element(NamedTuple):
symbol: str
name: str
number: int
category: str
group: Union[str, int]
period: int
block: str
mass: float
phase: Optional[str]
density: Optional[float]
electronegativity: Optional[float]
class PlacedElement(NamedTuple):
row: int
column: int
element: Element
def format_float(s: Optional[float]) -> str:
if s is None:
return 'n.A'
return format_string('%.2f', s)
def place_elements(elements: Iterable[Element]) -> Iterator[PlacedElement]:
OFFSET = 2
la_offset = 2
ac_offset = 2
for element in elements:
period, group_name = element.period, element.group
if group_name == 'La':
group = la_offset + OFFSET
la_offset += 1
period += OFFSET
elif group_name == 'Ac':
group = ac_offset + OFFSET
ac_offset += 1
period += OFFSET
else:
group = group_name
yield PlacedElement(row=period - 1, column=group - 1, element=element)
def load_json(filename: str = 'elements.json') -> Iterator[Element]:
with open(filename, encoding='utf-8') as f:
for element_dict in json.load(f):
yield Element(**element_dict)
class ElementButton:
BORDER = 3
CATEGORY_COLORS = {
'Alkalimetalle': '#fe6f61',
'Erdalkalimetalle': '#6791a7',
'Übergangsmetalle': '#83b8d0',
'Metalle': '#cae2ed',
'Halbmetalle': '#a7d6bc',
'Nichtmetalle': '#ffde66',
'Halogene': '#e9aa63',
'Edelgase': '#e29136',
'Unbekannt': '#cec0bf',
'Lanthanoide': '#696071',
'Actinoide': '#5b4c68',
} | {
"domain": "codereview.stackexchange",
"id": 42679,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, template, tkinter, gui, factory-method",
"url": null
} |
python, template, tkinter, gui, factory-method
PHASE_COLORS = {
'fest': 'black',
'flüssig': 'blue',
'gasförmig': 'red',
None: 'grey',
}
def __init__(self, parent: tk.Widget, placed_element: PlacedElement) -> None:
self.element = placed_element.element
self.background = self.CATEGORY_COLORS[self.element.category]
self.frame = frame = tk.Frame(
parent, relief=tk.RAISED,
name=f'frame_{self.element.symbol}',
background=self.background,
border=self.BORDER,
)
self.frame.grid_columnconfigure(1, weight=2)
self.frame.grid(row=placed_element.row, column=placed_element.column, sticky=tk.EW)
self.populate()
frame.bind('<ButtonPress-1>', self.press)
frame.bind('<ButtonRelease-1>', self.release)
for child in frame.winfo_children():
child.bindtags((frame,))
def populate(self) -> None:
prefix = f'label_{self.element.symbol}_'
tk.Label(
self.frame, name=prefix + 'number',
text=self.element.number, background=self.background,
).grid(row=0, column=0, sticky=tk.NW)
tk.Label(
self.frame, name=prefix + 'mass',
text=format_float(self.element.mass), background=self.background,
).grid(row=0, column=2, sticky=tk.NE)
tk.Label(
self.frame, name=prefix + 'name',
text=self.element.name, background=self.background,
).grid(row=1, column=0, sticky=tk.EW, columnspan=3)
tk.Label(
self.frame, name=prefix + 'symbol',
text=self.element.symbol, font='bold', background=self.background,
foreground=self.PHASE_COLORS[self.element.phase],
).grid(row=2, column=0, sticky=tk.EW, columnspan=3) | {
"domain": "codereview.stackexchange",
"id": 42679,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, template, tkinter, gui, factory-method",
"url": null
} |
python, template, tkinter, gui, factory-method
tk.Label(
self.frame, name=prefix + 'electronegativity',
text=format_float(self.element.electronegativity), background=self.background,
).grid(row=3, column=0, sticky=tk.SW)
tk.Label(
self.frame, name=prefix + 'density',
text=format_float(self.element.density), background=self.background,
).grid(row=3, column=2, sticky=tk.SE)
def press(self, event: tk.Event) -> None:
self.frame.configure(relief='sunken')
def release(self, event: tk.Event) -> None:
self.frame.configure(relief='raised')
webbrowser.open(
url=f'https://de.wikipedia.org/wiki/{self.element.name}',
new=2,
)
def main() -> None:
setlocale(LC_ALL, 'de-DE.UTF-8')
root = tk.Tk()
root.title('Periodensystem der Elemente')
frame = tk.Frame(root, name='grid_container')
frame.pack_configure(fill=tk.BOTH)
elements = tuple(place_elements(load_json()))
for element in elements:
ElementButton(frame, element)
columns = {elm.column for elm in elements}
for x in columns:
frame.grid_columnconfigure(index=x, weight=1)
root.mainloop()
if __name__ == '__main__':
main() | {
"domain": "codereview.stackexchange",
"id": 42679,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, template, tkinter, gui, factory-method",
"url": null
} |
python, performance, random, statistics, simulation
Title: Monte-carlo simulation code - simple exercise
Question: I created a quick monte-carlo simulation which seems to do what I want (simple version below). The code basically simulates a Poisson distribution, say this results in a simulation of 10. it would then simulate 10 values from a lognormal distribution. It then applies two parameters to the results of that simulation, lim and xs, sums up the results and then stores it in a results matrix. The code then takes the mean of each simulation.
import numpy as np
import os
import scipy.stats as sp
sigma = 0.5
u = 10
mu = 100
no_sim = int(10e3)
no_col = 2
mat_res = np.zeros((no_sim,no_col)) #results matrix holder
lim = 40e3 # parameter 1 - needs to vary
xs = 2000 # parameter 2 - needs to vary
for i in range(1,no_sim):
no_clm = sp.poisson.rvs(mu=mu,size=1)
clm_sev = sp.lognorm.rvs(s=sigma,scale=np.exp(u),size=no_clm)
temp_mat = np.zeros((np.size(clm_sev),2)) # temp matrix for calculations
temp_mat[:,0] = clm_sev
temp_mat[:,1] = np.minimum(lim,np.maximum(0,temp_mat[:,0]-xs)) #want to expand this step for various values of lim and xs, e.g. 5 different options
mat_res[i,0] = np.sum(temp_mat[:,0])
mat_res[i,1] = np.sum(temp_mat[:,1])
#want these mean values for various different lim and xs values which are predefined
print("mean 1 is %s" % np.mean(mat_res[:,0]),
"mean 2 is %s" % np.mean(mat_res[:,1]))
I am trying to do two things:
Speed up the code. I will need to run over a million simulations in reality so want to do this in the best way possible - currently it takes a five minutes or so to run a million simulations
Expand the code in an efficient way so that I can vary the parameters lim and xs and get a new result - i.e. right now I have lim = 40e3 and xs = 2000 | {
"domain": "codereview.stackexchange",
"id": 42680,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, random, statistics, simulation",
"url": null
} |
python, performance, random, statistics, simulation
but I would also want to run it with say lim = 50e3 and xs = 1000 and then return back the mean value in the print (along with the original mean for the original lim and xs parameters). One solution is to wrap the for-loop into a function with the parameters I require, however as I only use the lim and xs parameters in one line in the monte carlo simulation I don't think it's efficient to run the whole simulation again from scratch, but I can't think of any good way to build it into the for-loop as it stands. | {
"domain": "codereview.stackexchange",
"id": 42680,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, random, statistics, simulation",
"url": null
} |
python, performance, random, statistics, simulation
Answer: sigma, mu and u should be capitalised because they're constant (if they remain as constant globals; however, in my suggested code I show them instead as function parameters that are lower-case).
Move your simulation out of the global namespace into a function.
Consider adding numerical tests. I have only shown a regression test and cannot vouch for its accuracy. For this to work you need to send a constant seed to Numpy's random generator.
Don't overabbreviate simulation to sim or column to clm. I do not know what sev stands for.
Don't create a temp_mat - you don't need it.
Your main, outer for loop is tricky to vectorise, because - due to no_clm - your inner arrays are jagged. You can work around this by populating a fully square matrix and then zeroing out partial rows parametrically.
Fundamentally, you cannot represent mat_res as a matrix with two columns, because the first result variable is non-parametric and the second one is parametric, so they will have different shapes.
Don't use zeros - everywhere that you've used it, empty is more appropriate.
To parametrise the way you want, make lim and xs three-dimensional arrays where two of the dimensions are size-1; have clm_sev be a three-dimensional array where the non-1 dimension is in a different position. Then, most operations in Numpy that combine the two will use broadcasting. The first part of a Monte Carlo function could be to assert that these parameter arrays are of the same length, and reshape them to be suitable for broadcasting.
Don't use min and max; use clip.
Your range(1, doesn't seem correct to me - you were skipping your first row and leaving it zero, executing one fewer case than you specified, and skewing your mean. Just let it start from 0.
Suggested
import numpy as np
import scipy.stats as sp | {
"domain": "codereview.stackexchange",
"id": 42680,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, random, statistics, simulation",
"url": null
} |
python, performance, random, statistics, simulation
def monte_carlo(
lim: np.ndarray,
xs: np.ndarray,
sigma: float = 0.5,
u: float = 10,
mu: float = 100,
n_simulations: int = 1000,
) -> tuple[np.float64, np.ndarray]:
# Put the parameters into shapes usable by our broadcasting
lim = lim.reshape((1, 1, -1))
xs = xs.reshape((1, 1, -1))
n_parameters = lim.shape[-1]
# Assert that the parameter lengths are the same
if xs.shape[-1] != n_parameters:
raise ValueError('Parameter shape mismatch')
# Column-vector, for each simulation, of simulation row widths
n_columns = sp.poisson.rvs(mu=mu, size=(n_simulations, 1, 1))
# The maximum width of any simulation
width = n_columns.max()
# Row-vector of simple indices over the width of the simulation matrix
x_index = np.arange(width)[np.newaxis, :, np.newaxis]
# "Sev" (whatever that is) of random values, one row per simulation
sev = sp.lognorm.rvs(s=sigma, scale=np.exp(u), size=(n_simulations, width, 1))
# Zero out any simulation value beyond the Poisson-determined width
sev[x_index >= n_columns] = 0
# Parametric clipping will yield a three-dimensional matrix: n_simulations * width * n_parameters
clipped = np.clip(a=sev - xs, a_min=0, a_max=lim)
result_1 = sev.sum(axis=1).mean()
result_2 = clipped.sum(axis=1).mean(axis=0)
return result_1, result_2
def test() -> None:
np.random.seed(0) # to reproduce the same results
lim = np.linspace(start=38e3, stop=42e3, num=5)
xs = np.linspace(start=1800, stop=2200, num=5)
mean_1, mean_2 = monte_carlo(lim, xs)
tol = {'rtol': 0, 'atol': 1e-8}
assert np.isclose(mean_1, 2505180.2094949023, **tol)
assert np.all(
np.isclose(
mean_2,
(
2177820.61316294,
2180250.94121704,
2181574.66242172,
2181868.23243192,
2181257.68169412,
),
**tol,
)
) | {
"domain": "codereview.stackexchange",
"id": 42680,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, random, statistics, simulation",
"url": null
} |
python, performance, random, statistics, simulation
if __name__ == '__main__':
test() | {
"domain": "codereview.stackexchange",
"id": 42680,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, random, statistics, simulation",
"url": null
} |
beginner, rust
Title: How do I get the unique list of values from a hashmap in rust?
Question: I have the following code which finds all the unique values from a hashmap of String to Vec. I cobbled it together (eventually as I was getting various borrow errors along the way), but it looks a mess to me and I'm looking for a more idiomatic way of doing it in rust.
fn main() {
let mut my_map: HashMap<String, Vec<String>> = HashMap::new();
my_map.insert("option1".to_string(), vec![String::from("sarah"), String::from("john")]);
my_map.insert("option2".to_string(), vec![String::from("john"), String::from("mark")]);
let x: Vec<String> = my_map.values().flat_map(|x| x).cloned().collect();
// or use flatten() instead of flat_map(|x| x)
let y: HashSet<&String> = HashSet::from_iter(x.iter());
let mut z = y.iter().collect::<Vec<_>>();
z.sort();
println!("{:?}", z);
}
My idea was to flatmap the values from the map down into a simple vector, and then find the unique values (putting everything into a hashset), then converting back to a vector of strings.
The output is the sorted list of all unique names in the Vectors:
["john", "mark", "sarah"]
What would be a better implementation of this in rust?
Answer: You can collect into a different collection type, such as HashSet or BTreeSet. Both of these will eliminate duplicates, but entries in a HashSet will be in a random order (because the hash is randomized) while entries in a BTreeSet will be ordered (based on the Ord implementation for the element type).
use std::collections::{BTreeSet, HashMap};
fn main() {
let mut my_map: HashMap<String, Vec<String>> = HashMap::new();
my_map.insert("option1".to_string(), vec![String::from("sarah"), String::from("john")]);
my_map.insert("option2".to_string(), vec![String::from("john"), String::from("mark")]);
let b: BTreeSet<_> = my_map.values().flatten().collect();
println!("{:?}", b);
} | {
"domain": "codereview.stackexchange",
"id": 42681,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, rust",
"url": null
} |
beginner, rust
let b: BTreeSet<_> = my_map.values().flatten().collect();
println!("{:?}", b);
}
Note that instead of annotating the variable type, you can use the "turbofish" to specify the collection type to collect into:
let b = my_map.values().flatten().collect::<BTreeSet<_>>();
itertools is a crate that provides lots of extension methods for iterators. Relevant here are methods such as unique and sorted_unstable.
use std::collections::HashMap;
use itertools::Itertools; // 0.10.3
fn main() {
let mut my_map: HashMap<String, Vec<String>> = HashMap::new();
my_map.insert("option1".to_string(), vec![String::from("sarah"), String::from("john")]);
my_map.insert("option2".to_string(), vec![String::from("john"), String::from("mark")]);
let x: Vec<_> = my_map.values().flatten().unique().sorted_unstable().collect();
println!("{:?}", x);
} | {
"domain": "codereview.stackexchange",
"id": 42681,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, rust",
"url": null
} |
programming-challenge, rust
Title: Project Euler problem 11 in Rust: largest product of consecutive elements in a grid
Question: I wrote the following Rust code for euler project problem 11. It works and a small test is included, but I am not very happy about the code.
At first I wanted to chain together iterators for all the lines that need to be checked, but I could not make that work:
// FIXME: this doesn't work, so learn more Rust to DRY
// let all = horizontal
// .chain(vertical)
// .chain(top_to_bottom_right)
// .chain(left_to_bottom_right)
// .chain(top_to_bottom_left)
// .chain(right_to_bottom_left);
// all.map(|line| largest_adjacent_product_of_length(&line.map(|idx| grid[idx]).collect::<Vec<_>>(), n))
// .max()
// .unwrap()
So I ended up duplicating a lot of code. Six copies of this:
// let max_h = horizontal
// .map(|line| {
// largest_adjacent_product_of_length(&line.map(|idx| grid[idx]).collect::<Vec<_>>(), n)
// })
// .max()
// .unwrap();
Then I abstracted this pattern with a function, but look at those absurd trait bounds:
fn max_of_lines<Iter: Iterator>(grid: &[usize], n: usize, lines: Iter) -> usize
where
<Iter as Iterator>::Item: Iterator,
<<Iter as Iterator>::Item as Iterator>::Item: SliceIndex<[usize]>,
<<<Iter as Iterator>::Item as Iterator>::Item as SliceIndex<[usize]>>::Output: Copy + Sized,
Vec<usize>: FromIterator<
<<<Iter as Iterator>::Item as Iterator>::Item as SliceIndex<[usize]>>::Output,
>,
{
lines
.map(|line| {
largest_adjacent_product_of_length(
&line.map(|idx| grid[idx]).collect::<Vec<usize>>(),
n,
)
})
.max()
.unwrap()
} | {
"domain": "codereview.stackexchange",
"id": 42682,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "programming-challenge, rust",
"url": null
} |
programming-challenge, rust
Is there a way of fixing this?
Full code (also on playground):
#[test]
fn test_it() {
let grid_str = "\
1 2 3 4 5
1 2 3 4 5
6 2 3 4 3
1 2 4 3 5";
let grid = &read_grid(grid_str);
assert_eq!(largest_product_in_grid(grid, 5, 1), 6);
assert_eq!(largest_product_in_grid(grid, 5, 2), 5 * 5);
assert_eq!(largest_product_in_grid(grid, 5, 3), 5 * 4 * 4);
}
pub fn largest_product_in_grid_str(grid: &str, width: usize, n: usize) -> usize {
largest_product_in_grid(&read_grid(grid), width, n)
}
pub fn largest_product_in_grid(grid: &[usize], width: usize, n: usize) -> usize {
use std::slice::SliceIndex;
fn max_of_lines<Iter: Iterator>(grid: &[usize], n: usize, lines: Iter) -> usize
where
<Iter as Iterator>::Item: Iterator,
<<Iter as Iterator>::Item as Iterator>::Item: SliceIndex<[usize]>,
<<<Iter as Iterator>::Item as Iterator>::Item as SliceIndex<[usize]>>::Output: Copy + Sized,
Vec<usize>: FromIterator<
<<<Iter as Iterator>::Item as Iterator>::Item as SliceIndex<[usize]>>::Output,
>,
{
lines
.map(|line| {
largest_adjacent_product_of_length(
&line.map(|idx| grid[idx]).collect::<Vec<usize>>(),
n,
)
})
.max()
.unwrap()
} | {
"domain": "codereview.stackexchange",
"id": 42682,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "programming-challenge, rust",
"url": null
} |
programming-challenge, rust
use std::cmp::min;
// idea: create list of indices, map into list of elements, problem 8
grid.chunks_exact(width);
let height = grid.len() / width;
// search horizontally; this is problem 8 for each row
let horizontal = (0..height).map(|row| {
let rw = row * width;
rw..rw + width
});
// search vertically; should make this problem 8 too
let vertical = (0..width).map(|col| (0..height).map(move |n| col + n * width));
// search diagonally-top-left-bottom-right
let diag = min(width, height);
let top_to_bottom_right =
(0..width).map(|col| (0..min(diag, width - col)).map(move |n| col + n * (width + 1)));
let left_to_bottom_right =
(0..height).map(|row| (0..min(diag, height - row)).map(move |n| width * (row + n) + n));
// search diagonally-bottom-left-top-right
let top_to_bottom_left =
(0..width).map(|col| (0..min(diag, col)).map(move |n| col + n * (width - 1)));
let right_to_bottom_left = (0..height).map(|row| {
(0..min(diag, height - row)).map(move |n| {
let m = n + 1;
width * (row + m) - m
})
});
// FIXME: this doesn't work, so learn more Rust to DRY
// let all = horizontal
// .chain(vertical)
// .chain(top_to_bottom_right)
// .chain(left_to_bottom_right)
// .chain(top_to_bottom_left)
// .chain(right_to_bottom_left);
let max_h = max_of_lines(grid, n, horizontal);
// let max_h = horizontal
// .map(|line| {
// largest_adjacent_product_of_length(&line.map(|idx| grid[idx]).collect::<Vec<_>>(), n)
// })
// .max()
// .unwrap();
let max_v = max_of_lines(grid, n, vertical);
// let max_v = vertical
// .map(|line| {
// largest_adjacent_product_of_length(&line.map(|idx| grid[idx]).collect::<Vec<_>>(), n)
// })
// .max()
// .unwrap(); | {
"domain": "codereview.stackexchange",
"id": 42682,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "programming-challenge, rust",
"url": null
} |
programming-challenge, rust
let max_ttbr = max_of_lines(grid, n, top_to_bottom_right);
// let max_ttbr = top_to_bottom_right
// .map(|line| {
// largest_adjacent_product_of_length(&line.map(|idx| grid[idx]).collect::<Vec<_>>(), n)
// })
// .max()
// .unwrap();
let max_ltbr = max_of_lines(grid, n, left_to_bottom_right);
// let max_ltbr = left_to_bottom_right
// .map(|line| {
// largest_adjacent_product_of_length(&line.map(|idx| grid[idx]).collect::<Vec<_>>(), n)
// })
// .max()
// .unwrap();
let max_ttbl = max_of_lines(grid, n, top_to_bottom_left);
// let max_ttbl = top_to_bottom_left
// .map(|line| {
// largest_adjacent_product_of_length(&line.map(|idx| grid[idx]).collect::<Vec<_>>(), n)
// })
// .max()
// .unwrap();
let max_rtbl = max_of_lines(grid, n, right_to_bottom_left);
// let max_rtbl = right_to_bottom_left
// .map(|line| {
// largest_adjacent_product_of_length(&line.map(|idx| grid[idx]).collect::<Vec<_>>(), n)
// })
// .max()
// .unwrap();
vec![max_h, max_v, max_ttbr, max_ltbr, max_ttbl, max_rtbl]
.into_iter()
.max()
.unwrap()
// all.map(|line| largest_adjacent_product_of_length(&line.map(|idx| grid[idx]).collect::<Vec<_>>(), n))
// .max()
// .unwrap()
} | {
"domain": "codereview.stackexchange",
"id": 42682,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "programming-challenge, rust",
"url": null
} |
programming-challenge, rust
fn largest_adjacent_product_of_length(nums: &[usize], n: usize) -> usize {
fn largest_adjacent_product_of_length_no_zeros(nums: &[usize], n: usize) -> usize {
if nums.len() < n {
return 0;
}
let mut product: usize = nums[0..n].iter().product();
let mut max_product = product;
for i in n..nums.len() {
product = product * nums[i] / nums[i - n];
max_product = max_product.max(product);
}
max_product
}
nums.split(|&n| n == 0)
.map(|s| largest_adjacent_product_of_length_no_zeros(s, n))
.max()
.unwrap()
}
pub fn read_grid(grid: &str) -> Vec<usize> {
grid.split_whitespace()
.map(|s| s.parse().unwrap_or(0))
.collect()
}
Answer: max_of_lines
The signature can be made somewhat readable by naming all of the types so that you can refer to them more naturally:
fn max_of_lines<A, B, C, D>(grid: &[usize], n: usize, lines: A) -> usize
where
A: Iterator<Item=B>,
B: Iterator<Item=C>,
C: SliceIndex<[usize], Output=D>,
D: Copy + Sized,
Vec<usize>: FromIterator<D>,
However, you might have fallen victim to over-generalization here. You only ever use the functions with iterators returning usize, so you could make the signature even cleaner by making that explicit:
fn max_of_lines<A, B>(grid: &[usize], n: usize, lines: A) -> usize
where
A: Iterator<Item=B>,
B: Iterator<Item=usize>, | {
"domain": "codereview.stackexchange",
"id": 42682,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "programming-challenge, rust",
"url": null
} |
programming-challenge, rust
chain
As you noted in your question, the real way to improve the code is to make use of chain. The reason you cannot use it currently is because the signature requires both iterators to return items of the same type, while each one of your returns a different type as every closure has a unique type.
You could solve this by Boxing the inner iterators to create trait objects.
However, eventually you end up converting the inner iterator to Vec<usize> anyway, so it makes sense to do it immediately, e.g. with vertical:
let vertical = (0..width).map(|col| {
(0..height)
.map(move |n| grid[col + n * width])
.collect::<Vec<usize>>()
});
Converting the rest similarly, you will be able to use your initial idea with chain and get rid of the max_of_lines function completely.
Error handling
While for Project Euler handling errors robustly is not necessary, I would stress that you shouldn't silently ignore errors as that can easily introduce subtle bugs.
In particular, in read_grid,
.map(|s| s.parse().unwrap_or(0))
will silently ignore any parsing error and pretend it found 0.
You should use the following instead which will explicitly throw an error
.map(|s| s.parse().expect("couldn't parse grid element"))
largest_adjacent_product_of_length
Your implementation of this function can be improved to only need a single pass through the array, instead of one for split and another one for the actual calculation.
let (mut product, mut max) = (1, 0);
let mut len = 0;
for i in 0..nums.len() {
if nums[i] == 0 {
product = 1;
len = 0;
} else {
product *= nums[i];
if len < n {
len += 1;
} else {
product /= nums[i - len];
}
max = max.max(product);
}
}
max
Alternatively, if n is small, you could go for a slower but more readable approach.
nums.windows(n)
.map(|arr| arr.iter().product())
.max()
.unwrap_or(0) | {
"domain": "codereview.stackexchange",
"id": 42682,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "programming-challenge, rust",
"url": null
} |
programming-challenge, rust
Final code playground
Grid representation
You chose to represent the grid as a one-dimensional array. While this is potentially better for performance, it makes the code more difficult to read and reason about so I would suggest using Vec<Vec<usize>> instead; I'll leave that as an exercise to you :) | {
"domain": "codereview.stackexchange",
"id": 42682,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "programming-challenge, rust",
"url": null
} |
c++, windows
Title: C++ Determine if a file is older than int hours
Question: I have an MFC application where I need to determine if a file's last write time is older than n hours.
I thought there was a method to get total seconds from either system or file time, but I ended up coding this method which works, but there might be a leaner method.
bool FileOlderThanHours(HANDLE hFile, int hours)
{
FILETIME ftCreate, ftLastAccess, ftLastWrite;
SYSTEMTIME stNow, stFile;
GetSystemTime(&stNow);
if (!GetFileTime(hFile, &ftCreate, &ftLastAccess, &ftLastWrite))
return false;
if (!FileTimeToSystemTime(&ftLastWrite, &stFile))
return false;
COleDateTime oleNow(stNow.wYear, stNow.wMonth, stNow.wDay, stNow.wHour,
stNow.wMinute, stNow.wSecond);
COleDateTime oleFile(stFile.wYear, stFile.wMonth, stFile.wDay, stFile.wHour,
stFile.wMinute, stFile.wSecond);
COleDateTimeSpan timeDiff = oleNow - oleFile;
double totHours = timeDiff.GetTotalHours();
return (totHours > hours);
}
If someone knows a leaner way, please let me know, thanks.
Answer: In MFC, the CFile::GetStatus method lets you query the creation, modification or access time of a file.
Code to use it would look something like:
CTime getModificationTIme(const LPCTSTR filename)
/* Returns the last modification time of the requested file. The
* filename must be a null-terminated wide string.
*/
{
CFileStatus inputFileStatus;
if (!CFile::GetStatus( filename, inputFileStatus )) {
// Handle the error, perhaps by throwing an exception. E.g.,
THROW((CException*) new CCustomException(filename));
}
return inputFileStatus.m_mtime;
} | {
"domain": "codereview.stackexchange",
"id": 42683,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, windows",
"url": null
} |
c++, windows
In current versions of Windows, the filename is a null-terminated wide string. Future versions might un-deprecate the char* version to accept a UTF-8 filename.
Visual Studio 2017 and up support the standard library’s <filesystem> header, of which you can find an example of usage at cppreference.
One major difference between Windows and other systems is that, on Windows, the <filesystem> API uses wide strings to create a std::filesystem::path. | {
"domain": "codereview.stackexchange",
"id": 42683,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, windows",
"url": null
} |
rust
Title: Rust Cacher implementation (chapter 13 of the Book)
Question: In https://doc.rust-lang.org/book/ch13-01-closures.html the author recommended to try to implement Cacher that:
Stores values in a HashMap
Allows the closure to be defined with various input/output types.
Here's my implementation of it:
use std::hash::Hash;
use std::collections::HashMap;
fn main() {
println!("Hello, world!");
}
struct Cacher<ClosureType, ParamType, ReturnType>
where
ClosureType: Fn(ParamType) -> ReturnType,
ParamType: Hash + Eq,
{
calculation: ClosureType,
values: HashMap<ParamType, ReturnType>,
}
impl<ClosureType, ParamType, ReturnType> Cacher<ClosureType, ParamType, ReturnType>
where
ClosureType: Fn(ParamType) -> ReturnType,
ParamType: Hash + Eq + Copy,
{
fn new(calculation: ClosureType) -> Cacher<ClosureType, ParamType, ReturnType> {
Cacher {
calculation,
values: HashMap::new(),
}
}
fn value(&mut self, arg: ParamType) -> &ReturnType {
if self.values.contains_key(&arg) {
self.values.get(&arg).unwrap()
} else {
let result = (self.calculation)(arg);
self.values.insert(arg, result);
self.values.get(&arg).unwrap()
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn cacher_works_with_multiple_values() {
let mut cacher = Cacher::new(|a: i32| -> i32 { a + 1 });
let value = cacher.value(5);
assert_eq!(6, value.clone());
let value = cacher.value(10);
assert_eq!(11, value.clone());
}
}
The second task was much more "engaging" and I had some doubts about it: | {
"domain": "codereview.stackexchange",
"id": 42684,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "rust",
"url": null
} |
rust
The second task was much more "engaging" and I had some doubts about it:
As soon as I made Cacher generic with 3 type parameters, HashMap started to complain that it does not accept all the types. By guessing I figured I'll add trait bounds around the ParamType (that type will be the key in HashMap) to require both Hash and Eq traits' How do I make sure in such situation what trait bounds are necessary? I tried to find the source code of Rust's HashMap to see exactly which bounds they have defined for K and V, but I couldn't find that source code. I only found this, but it refers to some base, which I did not understand.
I was wondering if the value() method should accept an owned type or maybe a reference? Also, I was wondering if it should return an owned type or a reference. In the end I went with owned type on input and a reference on output. Is it a good design?
Answer: Your code looks very nice! First, answering your questions:
Q1: How do I make sure in such situation what trait bounds are necessary?
It is a combination of reading the documentation and intuition. If we Google something like "hashmap rust", we get to the documentation page, which tells us what we need to know:
It is required that the keys implement the Eq and Hash traits, although this can frequently be achieved by using #[derive(PartialEq, Eq, Hash)]. | {
"domain": "codereview.stackexchange",
"id": 42684,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "rust",
"url": null
} |
rust
If you know how a hashmap works, this also makes sense. Keys in the hashmap have to be hashed to find their place in the table, which means the key type must implement Hash. Additionally, if two keys collide (have the same location in the table), we need to know if they are the same key, or different. Hence, the key type must also implement Eq. PartialEq is a requirement for Eq as it is a weaker version.
So you should be requiring Eq and PartialEq, but NOT Copy. As a general rule of thumb, avoid Copy as it is intended for easily-copyable types and makes your code less generic. Instead, use Clone which requires you to explicitly clone a value.
Removing the Copy trait
So, above I said you should remove the Copy trait bound on ParamType, as it's not required by HashMap and should be avoided.
Unfortunately, removing Copy usually requires you to think harder about where ownership flows in your program, but fortunately, it's a helpful exercise. :)
Once you replace + Copy with + Clone, the Rust compiler will complain about these lines:
let result = (self.calculation)(arg);
self.values.insert(arg, result);
self.values.get(&arg).unwrap()
What's happening here? In the first line, self.calculation is a function type that takes as input a ParamType (NOT a reference). So it needs to take ownership. So, we've already given away our value after the first line! We still need it around, so instead of giving it away, we should make a clone.
Similarly, the second line needs ownership in order to insert the parameter arg into the cache self.values. So we need two .clone() calls to please the compiler:
let result = (self.calculation)(arg.clone());
self.values.insert(arg.clone(), result);
self.values.get(&arg).unwrap() | {
"domain": "codereview.stackexchange",
"id": 42684,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "rust",
"url": null
} |
rust
Are two clones necessary?
Clones can be expensive -- you should be imagining that arg might be something large, like a string or a vector -- so we should make sure we aren't cloning unnecessarily.
It turns out the answer here is that you should be able to do it with one clone, but it's tricky, so I will not discuss it here.
You would need to use a special feature of hashmaps called the Entry API.
However, there's an easier way: we can realize that the input parameter, arg is not used at the end of the function (it's been cloned twice, but the original owned value is not needed). So, we can be more efficient by accepting an &arg instead of arg. Here is our final code:
pub fn value(&mut self, arg: &ParamType) -> &ReturnType {
if self.values.contains_key(arg) {
self.values.get(arg).unwrap()
} else {
let result = (self.calculation)(arg.clone());
self.values.insert(arg.clone(), result);
self.values.get(arg).unwrap()
}
}
Additionally, cargo clippy has some helpful suggestions for how to simplify this. We end up with this final version of the code (and we also have to update the unit tests appropriately).
pub fn value(&mut self, arg: &ParamType) -> &ReturnType {
if !self.values.contains_key(arg) {
let result = (self.calculation)(arg.clone());
self.values.insert(arg.clone(), result);
}
self.values.get(arg).unwrap()
}
That leads us to your second question:
Q2: Is it better to accept/return an owned type or a reference? How can I tell?
If the type is Copy, just accept/return an owned type (copy means creating copies is easy). However now that we have made the code better to require Clone, this doesn't apply.
Here are two good questions to ask: | {
"domain": "codereview.stackexchange",
"id": 42684,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "rust",
"url": null
} |
rust
If you are accepting an owned value, are you using it? If no, you should accept a reference instead. The answer here was no: we were .clone()ing the argument twice, but discarding it at the end. So we switched to a reference.
If you are accepting a reference, are you cloning it exactly once? If yes, you should likely accept an owned value instead and avoid the clone. Here, we are cloning twice, not just once, so this doesn't apply.
If you are returning a reference, could you instead return a value (is there a value in the function body that's available to return)? If yes, return the value instead. Here, the answer is no: the return value is stored inside the cache, so we can't take ownership over it without removing it from the cache. So, we can't return a value and can only return a reference.
A general rule of thumb is that read-only methods accept and return references, whereas methods which insert into a data structure accept owned values, and methods which delete from a data structure return owned values.
Here, the "data structure" is the cache, so your signature makes sense: it accepts an owned value because it's inserting into the cache, and it returns a reference to the return value in the cache.
Further advice
I realize this got a bit long, but a couple other things:
Always try to remove warnings and run cargo clippy. Your code has some unused function errors, which it's best to avoid by making your data structure public: pub struct Cacher, pub fn new, pub fn value.
Finally, you have a useless fn main() function. In this case, what you are writing is more of a library than a binary, so what you probably want is to rename main.rs to lib.rs. Then you can get rid of the main function.
Entry API
Since you are interested -- here's how to do it with Entry:
pub fn value(&mut self, arg: ParamType) -> &ReturnType {
let result = (self.calculation)(&arg);
self.values.entry(arg).or_insert(result)
} | {
"domain": "codereview.stackexchange",
"id": 42684,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "rust",
"url": null
} |
rust
We can now remove Clone, but need to accept an owned ParamType rather than a reference (as in your new code) since we need an owned value to insert into the cache. | {
"domain": "codereview.stackexchange",
"id": 42684,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "rust",
"url": null
} |
c++, template-meta-programming, c++20
Title: c++20 compile time string utility v2
Question: This is a follow up on c++20 compile time string utility, as suggested by G. Sliepen posted as a new question, so it can be reviewed on its own.
The following code has suggested improvements from the original question integrated, another round of polishing, and a bit extra.
substr is added as an exercise to conform "string utility" to its name, but mostly to highlight the main limitation of this particular implementation: it's not "transparently constexpr" anymore.
The problem with it arises from the fact that string length is a non-type template parameter, where substr bounds (pos and count) should be preferably function parameters, if we are sticking to the constexpr paradigm. But that's not easy to return meta::string<new_length> from the substr this way, as function arguments are dynamic beings, thus limiting their use in a constant expression, which is required to instantiate a return value. Ultimately bumping us out from the function parameters (constexpr) level to the template parameters level.
Right now substr is effectively a generated family of functions, bound by implicit in-memory map to respective values with static storage duration. (Isn't it a "tag-dispatch" in a nutshell?)
That's a huge gap between the "constexpr" world and "conventional" C++ template metaprogramming.
Is there some clever trick to get it "back to constexpr" in this case?
Or we should wait for something like "constexpr function parameter qualifier" or similar? or else?
Live @godbolt [with comments coming back from previous question]
Live @godbolt [distilled, without comments]
Please, ignore excessive use of this-> and std::endl. It has some reasoning behind it, though irrelevant to template-meta-programming
#ifndef META_STRING_H_INCLUDED
#define META_STRING_H_INCLUDED
#include <cstddef>
#include <type_traits>
#include <algorithm>
#include <functional>
#include <tuple>
#include <stdexcept>
namespace meta
{ | {
"domain": "codereview.stackexchange",
"id": 42685,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, template-meta-programming, c++20",
"url": null
} |
c++, template-meta-programming, c++20
namespace meta
{
struct string_base
{
using size_type = std::size_t;
using char_type = char;
static constexpr size_type npos = size_type(-1);
};
template <string_base::size_type N> requires (N >= 1)
class string;
template <typename>
struct is_string : std::false_type {};
template <string_base::size_type N>
struct is_string<meta::string<N>> : std::true_type {};
template <typename>
struct is_string_constructible : std::false_type{};
// why do we get here??? template argument type decays during deduction from a constructor?
template <string_base::size_type N>
struct is_string_constructible<string_base::char_type [N]> : std::true_type {};
// shouldn't it be like this? looks like a possible bug
// struct is_string_constructible<const string_base::char_type (&)[N]> : std::true_type {};
// anyway we construct from a const&, so it shouldn't be big of a deal?
template <string_base::size_type N>
struct is_string_constructible<meta::string<N>> : std::true_type {};
template <template <typename...> typename container, typename... T>
requires ((is_string_constructible<T>::value && ...))
struct is_string_constructible<container<T...>> : std::true_type {};
template <typename T>
inline constexpr bool is_string_constructible_v = is_string_constructible<T>::value;
template <typename T>
concept string_constructible = is_string_constructible_v<T>;
template <string_base::size_type N> requires (N >= 1)
class string : public string_base
{
public:
char elems[N];
// string() { elems[N - 1] = '\0'; } // was used for CTAD guide for tuples. now we avoid object construction there
string() = delete;
constexpr string(const char_type (&s)[N])
{
std::copy_n(s, N, this->elems);
} | {
"domain": "codereview.stackexchange",
"id": 42685,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, template-meta-programming, c++20",
"url": null
} |
c++, template-meta-programming, c++20
constexpr string(const char_type (&s)[N])
{
std::copy_n(s, N, this->elems);
}
template <size_type Ni, size_type pos = 0, size_type count = npos>
constexpr string(const string<Ni> (&s), std::integral_constant<size_type, pos>, std::integral_constant<size_type, count>)
{
*std::copy_n(
&s.elems[std::min(pos, Ni - 1)],
std::min(count, Ni - 1 - std::min(pos, Ni - 1)),
this->elems
) = '\0';
}
// removed
// constexpr string(const std::array<char_type, N> (&s))
// {
// std::copy_n(s.data(), N, this->elems);
// }
template <string_constructible... T>
constexpr string(const T&... input)
{
// how silly of me was to enjoy this awkward symmetry between invoke and apply
// while complely overlooking the main goal of the expression
// std::invoke([this](const auto&... s) constexpr { this->copy_from(s...); }, detail::to_string(input)...);
this->copy_from(meta::string(input)...);
}
template <template <typename...> typename container, string_constructible... T>
constexpr string(const container<T...>& input)
{
// will not always compile without this-> inside the lambda
// e.g. @goldbolt x86-64 clang 13.0.0 with --std=c++20 -O3 -pedantic -Wall -Wextra -Werror
// std::apply([this](const auto&... s) constexpr { copy_from(meta::string(s)...); }, input);
std::apply([this](const auto&... s) constexpr {
this->copy_from(meta::string(s)...);
}, input);
}
constexpr auto operator + (const auto& rhs) const
{
return meta::string(*this, meta::string(rhs));
}
static constexpr size_type size_static() noexcept
{ return N; }
constexpr size_type size() const noexcept
{ return N; }
constexpr bool empty() const noexcept
{ return N == 1; }
constexpr const char_type* data() const noexcept
{ return this->elems; } | {
"domain": "codereview.stackexchange",
"id": 42685,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, template-meta-programming, c++20",
"url": null
} |
c++, template-meta-programming, c++20
constexpr const char_type* data() const noexcept
{ return this->elems; }
constexpr operator const char_type* () const noexcept
{ return this->elems; }
constexpr operator std::string_view () const
{ return std::string_view{ this->elems, N }; }
constexpr const char_type& at(size_type pos) const
{
if(pos >= N - 1)
throw std::out_of_range("out of bounds");
return this->elems[pos];
}
constexpr const char_type& operator [] (size_type pos) const
{ return this->at(pos); }
constexpr const char_type& front() const noexcept
{ return this->elems[0]; }
constexpr const char_type& back() const noexcept
{ return this->elems[N - 1]; }
template <size_type pos = 0, size_type count = npos>
constexpr auto substr() const
{
return meta::string(*this, std::integral_constant<size_type, pos>{}, std::integral_constant<size_type, count>{});
}
constexpr size_type copy(char_type* dest, size_type count = npos, size_type pos = 0) const
{
if(pos >= N)
throw std::out_of_range("out of bounds");
return std::copy_n(&this->elems[pos], std::min(count, N - 1 - std::min(pos, N - 1)), dest) - dest;
}
private:
template <size_type... Ni>
constexpr void copy_from(const string<Ni> (&... input))
{
auto pos = this->elems;
((pos = std::copy_n(input.elems, Ni - 1, pos)), ...);
*pos = 0;
}
};
namespace detail {
// constexpr auto to_string(const auto& input) { return string(input); }
// was mostly used to escape infinite recusion in CTAD...
// ...now replaced with
template <string_constructible... T>
constexpr inline string_base::size_type string_length = ((decltype(string(std::declval<T>()))::size_static() - 1) + ... + 1);
} // namespace detail
template <string_base::size_type N>
string(const string_base::char_type (&)[N])
-> string<N>; | {
"domain": "codereview.stackexchange",
"id": 42685,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, template-meta-programming, c++20",
"url": null
} |
c++, template-meta-programming, c++20
template <string_base::size_type N>
string(const string_base::char_type (&)[N])
-> string<N>;
template <string_base::size_type Ni, string_base::size_type pos, string_base::size_type count>
string(const string<Ni> (&), std::integral_constant<string_base::size_type, pos>, std::integral_constant<string_base::size_type, count>)
-> string<std::min(count, Ni - 1 - std::min(pos, Ni - 1)) + 1>;
// removed
// template <string_base::size_type N>
// string(const std::array<string_base::char_type, N>& input)
// -> string<N>;
template <string_constructible... T>
string(const T&...) // input)
// -> string<((sizeof(detail::to_string(input).elems) - 1) + ... + 1)>; // original
// -> string<((decltype(detail::to_string(input))::size_static() - 1) + ... + 1)>; // avoiding external sizeof and accessing class member variable
-> string<detail::string_length<T...>>; // with detail::to_string removed
template <template <typename...> typename container, string_constructible... T>
string(const container<T...>&)
// -> string<((sizeof(detail::to_string(T()).elems) - 1) + ... + 1)>; // original
// -> string<((sizeof(T) - 1) + ... + 1)>; // @G. Sliepen's suggestion, will not work for nested tuples, and unfortunately dangerous on it's own
// -> string<((decltype(detail::to_string(T()))::size_static() - 1) + ... + 1)>; // avoiding external sizeof and accessing class member variable
// -> string<((decltype(detail::to_string(std::declval<T>()))::size_static() - 1) + ... + 1)>; // finally deleted default constructor
-> string<detail::string_length<T...>>; // with detail::to_string removed
inline namespace meta_string_literals {
template <string ms>
inline constexpr auto operator"" _ms() noexcept
{
return ms;
}
} // inline namespace meta_string_literals
} // namespace meta
#endif // META_STRING_H_INCLUDED
//////////////////////////////////////////////////////////////////////
// #include "meta_string.h"
#include <iostream> | {
"domain": "codereview.stackexchange",
"id": 42685,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, template-meta-programming, c++20",
"url": null
} |
c++, template-meta-programming, c++20
// #include "meta_string.h"
#include <iostream>
template<meta::string str>
struct X
{
static constexpr auto value = str;
operator const char* () { return str.elems; }
};
template <auto value>
constexpr inline auto constant = value;
int main()
{
using namespace meta::meta_string_literals;
X<"a message"> xxx;
X<"a massage"> yyy;
X<meta::string(xxx.value, " is not ", yyy.value)> zzz;
X<"a message"_ms + " is " + "a massage"> zzz2;
std::cout << xxx << std::endl;
std::cout << yyy << std::endl;
std::cout << zzz << std::endl;
std::cout << zzz2 << std::endl;
static constexpr auto x = meta::string("1"_ms, "22");
static constexpr auto y = meta::string("11", "22");
static constexpr auto z = meta::string(std::tuple{"1xx1"_ms, "2qqq2"_ms});
static constexpr auto z2 = meta::string(std::tuple{meta::string(std::tuple{"1xx1"_ms, "2qqq2"_ms}), "2qqq2"_ms});
static constexpr auto z3 = meta::string(std::tuple{std::tuple{"1xx1"_ms, "2qqq2"_ms}, "2qqq2"_ms});
// static constexpr auto zx = meta::string(std::tuple{"1xx1"_ms, std::array<char, 6>{"2qqq2"}}); // construction from array is removed
std::cout << sizeof(x.elems) << ": " << x << std::endl;
std::cout << sizeof(y.elems) << ": " << y << std::endl;
std::cout << sizeof(z.elems) << ": " << z << std::endl;
std::cout << sizeof(z2.elems) << ": " << z2 << std::endl;
std::cout << sizeof(z3.elems) << ": " << z3 << std::endl;
static constexpr auto a = "1"_ms;
static constexpr auto b = a + "22"_ms;
std::cout << b << std::endl;
// TODO: Can't the next line be implicitly forced to constexpr?
std::cout << meta::string("this one "_ms, "is not ", "constant evaluated"_ms) << std::endl;
std::cout << constant<meta::string("this one "_ms, "is ", "constant evaluated"_ms)> << std::endl; | {
"domain": "codereview.stackexchange",
"id": 42685,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, template-meta-programming, c++20",
"url": null
} |
c++, template-meta-programming, c++20
std::cout << constant<"0123456789"_ms[9]> << std::endl;
// std::cout << constant<"0123456789"_ms[-1]> << std::endl; // will throw std::out_of_range
// std::cout << constant<"0123456789"_ms[10]> << std::endl; // will throw std::out_of_range
static constexpr auto sv_test = "string_view cast"_ms;
static constexpr std::string_view sv1 { sv_test.elems, sv_test.size() };
static constexpr std::string_view sv2 = sv_test;
static constexpr std::string_view sv3 = constant<"string_view cast in-place"_ms>;
// static constexpr std::string_view sv4 = "error: is not a constant expression"_ms; // will not compile
std::cout << sv1 << std::endl;
std::cout << sv2 << std::endl;
std::cout << sv3 << std::endl;
char copy_test_dest[30] = {}; // to ensure zero-termination
static constexpr auto copy_test_src = "01234"_ms;
std::size_t char_copy_count =
copy_test_src.copy(©_test_dest[0], 1, 1) +
copy_test_src.copy(©_test_dest[1], -1, 3)
;
// copy_test_src.copy(©_test_dest[1], -1 , 6); // will throw std::out_of_range
std::cout << char_copy_count << ": " << copy_test_dest << std::endl;
static constexpr auto test_substr_src = "01234"_ms;
static constexpr auto test_substr_1 = test_substr_src.substr<2, 0>();
static constexpr auto test_substr_2 = test_substr_src.substr<2, 1>();
static constexpr auto test_substr_3 = test_substr_src.substr<2, 2>();
static constexpr auto test_substr_4 = test_substr_src.substr<2, 3>();
static constexpr auto test_substr_5 = test_substr_src.substr<2, 222>();
std::cout << test_substr_1.size() << ": " << test_substr_1 << std::endl;
std::cout << test_substr_2.size() << ": " << test_substr_2 << std::endl;
std::cout << test_substr_3.size() << ": " << test_substr_3 << std::endl;
std::cout << test_substr_4.size() << ": " << test_substr_4 << std::endl;
std::cout << test_substr_5.size() << ": " << test_substr_5 << std::endl; | {
"domain": "codereview.stackexchange",
"id": 42685,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, template-meta-programming, c++20",
"url": null
} |
c++, template-meta-programming, c++20
std::cout << (meta::is_string_constructible<decltype("100"_ms)>::value ? "true" : "false") << std::endl;
return 0;
} | {
"domain": "codereview.stackexchange",
"id": 42685,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, template-meta-programming, c++20",
"url": null
} |
c++, template-meta-programming, c++20
return 0;
}
Answer: N and the terminating NUL character
While it is very convenient to ensure there is always a terminating NUL character at the end of the string, the question is whether N should count that NUL or not. Consider that std::string does not do that in its API, and also that strlen() will report the length minus the NUL character.
Ideally, I would make it so N does not count the NUL character. But if it does, then make sure size() and size_static() return N - 1. Also consider that your operator std::string_view() currently behaves in a surprising way, and your back() always returns '\0'.
operator[] should not call at()
The standard semantics for operator[] is that it doesn't do bounds checking, and hence is noexcept, whereas at() does bounds checking and can throw.
elems[] should be an array of char_type
Since you use char_type everywhere, it should also be used when declaring the array elems[].
Throw std::out_of_range in the constructors
std::string will throw a std::out_of_range exception in its constructor that take a pos argument, if pos is out of range. You can do the same in your code, and then it will catch those errors at compile time. You should be able to get rid of all the std::min(pos, ...) calls this way.
On a related note, don't use std::min() in the deduction guides. These should just forward all the parameters unchanged to the class itself, so that the constructors can do all the error checking.
Go all in on concepts?
I see you use SFINAE template classes to provide traits like is_string and is_string_constructible. It might be possible to rewrite them purely as concepts (see this StackOverflow question), although there is nothing wrong with keeping it as it is.
You can however use concepts in regular code as well, so instead of using meta::is_string_constructible<...>::value, you can use meta::string_constructible<...>, like so:
std::cout << (meta::string_constructible<decltype("100"_ms)> ? "true" : "false") << '\n'; | {
"domain": "codereview.stackexchange",
"id": 42685,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, template-meta-programming, c++20",
"url": null
} |
c++, template-meta-programming, c++20
Unnecessary use of this->
It is almost never necessary to write this-> in C++. I would remove its use everywhere. As discussed before and as mentioned by user17732522 in his comment above, some compilers might not like it, but that is a bug in the compiler.
Avoid using std::endl
Prefer using \n instead of std::endl; the latter is equivalent to the former, but also forces the output to be flushed, which is usually unnecessary and hurts performance. | {
"domain": "codereview.stackexchange",
"id": 42685,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, template-meta-programming, c++20",
"url": null
} |
c++, beginner, math-expression-eval
Title: C++ calculator supporting five operators
Question: Recently I started learning c++ and I had an idea to make a calculator, that can take any imaginable number and I wrote this code:
#include <iostream>
#include <string>
#include <vector>
// Advanced calculator by xxnoflz;
// This calculator works best with summation, subtraction and multiplication
// and can work with numbers with ricilous amout of digits;
// But division and modulo works worse because of principle how division works;
void pause() {
std::cout << '\n' << "Press <Enter> to continue...";
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
//std::cin.get(); // Use when not debug
} // PAUSE
int find_first_digit(std::vector<int>& vctr) {
int iter{ int(vctr.size())-1 }; // Get the position of last number of array
while (vctr[iter] == 0 && iter > 0) { --iter; } // Iterate while numbers are zeroes
return iter;
} // Function to find and return the position of the first digit that is not zero
std::vector<int> operator+(std::vector<int>& first, std::vector<int>& second) {
int f1{ find_first_digit(first) }; // Position of first digit of first num
int f2{ find_first_digit(second) }; // Position of first digit of second num
int first_digit_pos{ (f1 > f2) ? f1 : f2 }; // Get the largest number first position
for (int iter{}; iter <= first_digit_pos; ++iter) { // Don't need to iterate through zeroes, just the numbers that matter
first[iter] += second[iter];
if (first[iter] >= 10) { // Overflow control
first[iter] -= 10;
first[iter + 1]++;
}
}
return first;
} | {
"domain": "codereview.stackexchange",
"id": 42686,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, beginner, math-expression-eval",
"url": null
} |
c++, beginner, math-expression-eval
std::vector<int> operator-(std::vector<int>& first, std::vector<int>& second) {
bool negative{ false }; // Bool for negative check
int size{ int(first.size()) };
int f1{ find_first_digit( first ) }; // Position of first digit of first num
int f2{ find_first_digit( second )}; // Position of first digit of second num
int check{(f1 > f2) ? f1 : f2}; // Get the largest number first position
if (first[check] < second[check]) { std::swap(first, second); negative = true; } // If the first num is smaller the second then result is negative
for (int iter{}; iter <= check; ++iter) { // Don't need to iterate through zeroes, just the numbers that matter
if (first[iter] - second[iter] < 0) {
first[iter] += 10;
first[iter+1]--;
}
first[iter] -= second[iter];
}
if (negative) { first[find_first_digit(first)] *= -1; } // Add to the first significant digit negative sign if number should be negative
return first;
} | {
"domain": "codereview.stackexchange",
"id": 42686,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, beginner, math-expression-eval",
"url": null
} |
c++, beginner, math-expression-eval
std::vector<int> operator*(std::vector<int>& first, std::vector<int>& second) {
int size{ int(first.size()) };
int f1{ find_first_digit(first) }; // Position of first digit of first num
int f2{ find_first_digit(second) }; // Position of first digit of second num
std::vector<int> result(size); // Create a vector to store answer in it
for (int second_it{}; second_it <= f2; ++second_it) { // First: iterate through the second number to last significant digit
int pos{ second_it }; // Create an integer with first position to add answer to
for (int first_it{}; first_it <= f1 && pos < size; ++first_it, ++pos) { // Second: iterate through the first number to last significant digit
result[pos] += first[first_it] * second[second_it]; // And add the multiply of first and second digit to result with start position
if (result[pos] >= 10) { // Overflow control
result[pos + 1] += result[pos] / 10;
result[pos] %= 10;
}
}
}
return result;
}
std::vector<int> operator/(std::vector<int>& first, std::vector<int>& second) {
std::vector<int> result(first.size());
bool stop{ true }; // Check to continue the subtraction or not
while (stop) {
first = first - second; // Subtract the second number from first
stop = false;
for (int digit : first) { if (digit > 0) { stop = true; } if (digit < 0) { return result; } } // If even one digit is positive then continue, but if one is negative return the
result[0]++; // answer, and if all digits are zeroes then add 1 to answer and then return
for (int iter{}; iter < result.size(); ++iter) { //Overflow control with check of every digit
if (result[iter] >= 10) {
result[iter] -= 10;
result[iter+1]++;
}
}
}
return result;
} | {
"domain": "codereview.stackexchange",
"id": 42686,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, beginner, math-expression-eval",
"url": null
} |
c++, beginner, math-expression-eval
return result;
}
std::vector<int> operator%(std::vector<int>& first, std::vector<int>& second) {
std::vector<int> check{ second }; std::vector<int> zero{0}; // Interesting feature here that I noticed is that when number evenly divides by another the second number
first = first / second; // stays unchanged, but when there is remainder it is stored in the second number. Pretty neat, huh!
return (second == check) ? zero : second; // All we need to do here is compare the values of second number, when unchanged return zeroes but when changed
} // return the second number.
int main() {
int extra_carry{ 10 }; // If some error happens it can be that amount of extra carry is insufficient
std::string input{};
std::getline(std::cin,input); // Get input
std::string nums{ "0123456789" };
std::string first_num{ input.begin(),input.begin() + input.find_first_not_of(nums)};
std::string second_num{ input.begin() + input.find_first_of(nums,input.find_first_not_of(nums)), input.end() };
char oprt{input[input.find_first_of("+-*/%")]};
int size{ int((first_num.size() > second_num.size()) ? first_num.size() : second_num.size()) + extra_carry }; // Parse input into first and second numbers and operator | {
"domain": "codereview.stackexchange",
"id": 42686,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, beginner, math-expression-eval",
"url": null
} |
c++, beginner, math-expression-eval
std::vector<int> first(size);
std::vector<int> second(size);
std::reverse(first_num.begin(),first_num.end()); std::reverse(second_num.begin(), second_num.end()); // Reverse in order to do calculations
for (int it{}; it < first_num.length(); ++it) { first[it] = first_num[it] - '0'; }
for (int it{}; it < second_num.length(); ++it) {second[it] = second_num[it] - '0'; } // Convert string to vector to do the calculations
std::vector<int> result(size);
switch (oprt) {
case '+':
result = first+second;
break;
case '-':
result = first-second;
break;
case '*':
result = first*second;
break;
case '/':
result = first/second;
break;
case '%':
result = first%second;
break;
default:
std::cout << "Uknown operator!\n";
break;
}
int start{ find_first_digit(result) }; // Find the first digit of result
for (; start >= 0; --start) {
std::cout << result[start];
} // Print in reverse
pause();
return 0;
}
I know it's a little big, but I will take any suggestions to improve this code, thanks!
PS: The the divide and modulo function works slow | {
"domain": "codereview.stackexchange",
"id": 42686,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, beginner, math-expression-eval",
"url": null
} |
c++, beginner, math-expression-eval
Answer: This looks like a nice start! I’m going to post something belated, and long, not because your code is especially bad but because I was sick at home and found myself writing a lot of examples.
I agree with @JDlugosz that you should name your Bignum class, and should refactor your library into functions.
Additionally, there are some changes you should make for efficiency.
Use the Right Data Type
Currently, you’re storing decimal digits in an array. This was historically common (and instructions for a form of it, Binary-Coded Decimal, are still in the x86_64 architecture).
The most efficient format for a computer, or to output in hex/octal/binary/base64, is probably to store your number as uint32_t. (If you ever are called upon to roll your own bignum library on some mainframe from the ’70s that supports modern C++ but not an exact 32-bit type, feel free to ask for an update.) This is half as fast as it theoretically might be on a 64-bit machine, but makes it much, much easier to get the high bits of multiplication than if you tried to use 64-bit words.
If you care about quickly converting to decimal digits, the most memory-efficient way of storing your Bignum is to encode digits in both the upper and lower four bits of each byte (historically called packed BCD). Decent compromises are storing one decimal digit in a char, or storing nine decimal digits in a uint_least32_t. | {
"domain": "codereview.stackexchange",
"id": 42686,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, beginner, math-expression-eval",
"url": null
} |
c++, beginner, math-expression-eval
You want to store the digits in little-endian order, that is, from lowest digit to highest. This vastly simplifies addition, subtraction and multiplication. Think of your implementation as base 10, one that packs 9 decimal digits into a 32-bit word as base 1,000,000,000, and one that uses 32-bit binary arithmetic as using base 4,294,967,296. Then every little-endian bignum n is equal to the sum of the products n[i] times B to the power of i, for all indices i. Then the product of bignums m and n is the sum of m[i]*n[j] times B to the power of i+j for all indices i in m and j in n, and this just means iterating over both containers and storing the lower digit of each product in position [i+j] and the upper digit in position [i+j+1]. (Because (B**i * m_i) * (B**j * n_j) = B**(i+j) * m_i * n_j, and the product of the bignums is the sum of all such products of their chunks.)
To print the digits, you would iterate backwards, starting from the highest digit at rbegin(), until you reach rend(). Speaking of which,
Use const for Inputs You Don’t Modify
When I tried to write a few simple examples using constants, they didn’t compile, because your API doesn’t accept const Bignum.
Have a Function to Serialize Bignums
This is typically a member function named .to_string(), but you can also write a std::ostream& operator<< (ostream&, const Bignum&), which will make cout << someBignum; work.
But, to add a member function, you need to
Make Bignum a Class
In this case, you don’t want a Bignum to be a vector of int, you want it to have a vector of some kind of data. The rest of the application doesn’t need to know about this, and in fact, not exposing the rest of the program to implementation details makes it much easier for you to make changes that don’t break anything.
The skeleton of a Bignum class might look like this:
class Bignum {
public:
/* A Bignum can be initialized from the widest signed integral type
* in <cstdint>, and defaults to 0.
*/ | {
"domain": "codereview.stackexchange",
"id": 42686,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, beginner, math-expression-eval",
"url": null
} |
c++, beginner, math-expression-eval
* in <cstdint>, and defaults to 0.
*/
Bignum() : Bignum(0) {};
Bignum(std::intmax_t);
// By the rule of 5:
Bignum(const Bignum&) = default;
Bignum(Bignum&&) = default;
Bignum& operator= (const Bignum&) = default;
Bignum& operator= (Bignum&&) = default;
~Bignum() = default; | {
"domain": "codereview.stackexchange",
"id": 42686,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, beginner, math-expression-eval",
"url": null
} |
c++, beginner, math-expression-eval
When I tried an implementation, I added data members and several helper functions to the private: section of the class. Part of this was:
private:
using value_type = unsigned char;
using buffer_type = std::vector<value_type>;
using iterator = buffer_type::iterator;
using const_iterator = buffer_type::const_iterator;
using reverse_iterator = buffer_type::reverse_iterator;
using const_reverse_iterator = buffer_type::const_reverse_iterator;
bool is_negative; // Sign-and-magnitude representation.
buffer_type buffer; // Each byte holds one base-10 digit, in little-endian order.
I also added a bit of syntactic sugar to simplify iterating through the container:
// Utility functions to simplify buffer access.
std::size_t size() const noexcept { return buffer.size(); }
value_type& operator[] (const std::size_t i) { return buffer[i]; }
const value_type& operator[] (const std::size_t i) const {return buffer[i];}
constexpr const_iterator begin() const noexcept { return buffer.begin(); }
constexpr const_iterator end() const noexcept { return buffer.end(); }
constexpr const_reverse_iterator rbegin() const noexcept { return buffer.rbegin(); }
constexpr const_reverse_iterator rend() const noexcept { return buffer.rend(); }
The following should now work, within a friend or member:
for ( size_t i - 0; i < num.size() && num[i] == 0; ++i )
for ( auto it = num.begin(); it != num.end() && *it == 0; ++it )
With this as a class, your helper functions can now be either friends or members. I ended up making the helper functions for arithmetic members that were always called on the result object.
Your Code Goes Out of Bounds. Use Iterators.
I’m not going to make a comprehensive list of bugs, but here’s one that jumped out at me. find_first_digit has the lines
int iter{ int(vctr.size())-1 }; // Get the position of last number of array
while (vctr[iter] == 0 && iter > 0) | {
"domain": "codereview.stackexchange",
"id": 42686,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, beginner, math-expression-eval",
"url": null
} |
c++, beginner, math-expression-eval
The vctr argument is a std::vector<int>, so its .size() can be 0. When that happens, iter is set to -1. You then use this value in the expression vctr[iter] before you check iter > 0. Inside the brackets, -1 actually converts to a huge size_t value. This will probably crash your program.
One suggestion: if a Bignum is another class that has a vector of the appropriate type, your constructor can maintain the invariant that every Bignum has at least one word of storage, and zero size cannot happen.
You would be better off writing this function with an iterator than with an index, but storing in little-endian order probably means you don’t need it at all.
Use Correct Semantics
This holds for all the binary operators. Let’s look at + for example.
std::vector<int> operator+(std::vector<int>& first, std::vector<int>& second)
Let’s pretend we implemented the accepted answer’s suggestion and put in a Bignum class. This section doesn’t depend on implementation details. As a quick-and-dirty fix, you can add using Bignum = std::vector<int>; to get this to compile.
Bignum operator+( Bignum& first, Bignum& second )
This is incorrect. The following code does not compile:
const Bignum one = {1}, two = one + one;
On Clang++ 13.0.0, I get the error,
error: invalid operands to binary expression ('const Bignum' (aka 'const vector<int>') and 'const Bignum')
note: candidate function not viable: 1st argument ('const Bignum' (aka 'const vector<int>')) would lose const qualifier
std::vector<int> operator+(std::vector<int>& first, std::vector<int>& second) {
Why is it giving us this error? You’re trying to add a constant Bignum, and your code doesn’t allow that. It doesn’t accept const Bignum arguments.
Why doesn’t it? If you remove the const from that declaration to get
Bignum one = {1}, two = one + one; | {
"domain": "codereview.stackexchange",
"id": 42686,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, beginner, math-expression-eval",
"url": null
} |
c++, beginner, math-expression-eval
This line of code sets one equal to 2. (Like the old version of IBM Fortran where procedures could change the value of the constant 1 to -1 and make all the loops run backwards.)
Why does it change one to 2? You’re attempting to implement += instead of +. It would be a good idea to have +=. But the semantics are not quite right for that, either. You would write that as
Bignum& operator+= (Bignum& first, const Bignum& second)
You’ll notice two differences here. the right-hand-side is now a const Bignum&, so it will accept counter += one;. The left-hand side now has a & after the return type. This is huge: with that, you’re returning a reference to an existing Bignum. Without, you’re making a new copy of a Bignum. And a Bignum can get big. Clobbering the left-hand side and then making an extra copy is the worst of both worlds!
Let’s compile this version of operator+ and see what kind of code we get (clang++ 13.0.0 for Linux with -Os -march=x86-64-v4). We’ll look only at the code at the end of the function, since that’s what we’ll be tweaking:
.LBB1_11:
mov rdi, r14
call std::vector<int, std::allocator<int> >::vector(std::vector<int, std::allocator<int> > const&) [base object constructor]
mov rax, r14
add rsp, 8
pop rbx
pop r14
ret
Of particular importance is the call instruction. That invokes the copy constructor to create a deep copy of your Bignum, as well as needing a fair amount of glue around it. If your Bignum is big, this time and memory could really add up.
Let’s now take the same code and change only the type signatures, to
Bignum& operator+=( Bignum& first, const Bignum& second )
and to make find_first_digit, which does not modify its input, take a const Bignum& as input.
The end of the function now compiles to
.LBB1_11:
ret | {
"domain": "codereview.stackexchange",
"id": 42686,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, beginner, math-expression-eval",
"url": null
} |
c++, beginner, math-expression-eval
This is a major optimization! I’m going to leave aside for the moment how to improve the calculations themselves. But let’s look at how we might use this as a bulding block. The code for -=, *= and /= can be similar.
The following will now compile successfully.
const Bignum one = {1};
Bignum counter = {0};
counter += one;
Use Move and Copy
So, we’ve refactored slightly and now have the same code as before in a +=` operator that works. How can we get this to work?
const Bignum two = one + one;
You’ll recall that your original implementation used the same code as +=, but returned a copy of the first argument. Let’s do that, but modify the copy, instead of the first operand. We end up with,
Bignum operator+ ( const Bignum& first, const Bignum& second )
{
Bignum to_return = first;
to_return += second;
return to_return;
}
You might have noticed that I still don’t have a & after the return type, so I’m still not returning by reference. Does this mean my program is making a copy of the copy? It turns out, the answer used to be yes, this was the classic example of how it could bite you. There were various tricks I would use back in the ’90s to work around it. This aggravated enough programmers that, today, compilers are required to be smart enough to figure out that to_return (or whatever it’s named) is really just an alias for the return object, and not make a copy of it. So that code works just fine.
But we’re stuck making that one copy—except when we don’t have to. The only reason we couldn’t get away with overwriting one was that we might need it later, so we made a temporary copy and overwrote that instead. But what if our first argument were already a temporary copy that would never be used by anything else again? Then we’d be free to clobber it. And C++ has a syntax for that, Bignum&&. So, we can add an overload,
Bignum operator+ ( Bignum&& first, const Bignum& second )
{
first += second;
return first;
} | {
"domain": "codereview.stackexchange",
"id": 42686,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, beginner, math-expression-eval",
"url": null
} |
c++, beginner, math-expression-eval
Now, if we compile the line
Bignum four = one + one + one + one;
we see only a single copy get made, followed by three calls to +=. The first call to + had two constants as arguments, so it called the version that makes a copy of the first argument and calls += on the copy. It then returns that temporary copy. That means, each time we write + one again, the compiler sees that the first operand is an expiring temporary copy that it can overwrite, so it calls the optimized version.
Since addition is commutative, we can also do this when the second operand is a temporary copy, likr
Bignum w = x * (y + z);
The function signature here is
Bignum Operator+ ( const Bignum& first, Bignum&& second )
However, this line now breaks, because the compiler can’t tell whether to use the version that clobbers the left operand, or the right.
const Bignum four = (one + one) + (one + one);
To solve this, we need to provide one other overload:
Bignum operator+ ( Bignum&& first, Bignum&& second )
Writing these out as friend declarations for a class, we get:
// Arithmetic functions can be friends of the class.
friend Bignum& operator+= (Bignum&, const Bignum&);
friend Bignum operator+ (const Bignum&, const Bignum&);
friend Bignum operator+ (Bignum&&, const Bignum&);
friend Bignum operator+ (const Bignum&, Bignum&&);
friend Bignum operator+ (Bignum&&, Bignum&&);
friend Bignum& operator-= (Bignum&, const Bignum&);
friend Bignum operator- (const Bignum&, const Bignum&);
friend Bignum operator- (Bignum&&, const Bignum&);
friend Bignum operator- (const Bignum&, Bignum&&);
friend Bignum operator- (Bignum&&, Bignum&&);
friend Bignum& operator*= (Bignum&, const Bignum&);
friend Bignum operator* (const Bignum&, const Bignum&);
friend Bignum operator* (Bignum&&, const Bignum&);
friend Bignum operator* (const Bignum&, Bignum&&);
friend Bignum operator* (Bignum&&, Bignum&&); | {
"domain": "codereview.stackexchange",
"id": 42686,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, beginner, math-expression-eval",
"url": null
} |
c++, beginner, math-expression-eval
friend Bignum& operator/= (Bignum&, const Bignum&);
friend Bignum operator/ (const Bignum&, const Bignum&);
friend Bignum operator/ (Bignum&&, const Bignum&);
friend Bignum operator/ (const Bignum&, Bignum&&);
friend Bignum operator/ (Bignum&&, Bignum&&);
Nearly all of these can be implemented in terms of another function, so you only need to write an addition or multiplication loop once.
Compute the Quotient and Remainder at the Same Time
Most division algorithms will give you both, and this is one of the longest computations to have to restart all over again. See, for example, div_t.
You Can Optimize in Other Ways
Since you know in advance what the maximum size of any arithmetic result will be, you might reserve sufficient space for your buffer to be sure that it won’t need to resize. To reclaim the memory, you can shrink_to_fit. You might not necessarily want to do this if you have a lot of addition or multiplication by tiny numbers, or if you have a long chain of operations where it would be wasteful to reserve and shrink the buffer over and over again. | {
"domain": "codereview.stackexchange",
"id": 42686,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, beginner, math-expression-eval",
"url": null
} |
c#, .net, error-handling
Title: How much error handling is too much?
Question: I have the following C# code (.NET 6):
public async Task<IEnumerable<Foobar>> RetrieveFoobar(string accessToken, CancellationToken cancellationToken)
{
try
{
using var httpClient = new HttpClient(new HttpClientHandler())
{
BaseAddress = new Uri(_baseUrl)
};
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
var response = await httpClient.GetAsync("/path", cancellationToken);
if (!response.IsSuccessStatusCode)
{
Log.Error($"Foobar failed: {response.StatusCode} - {await response.Content.ReadAsStringAsync(cancellationToken)}");
return null;
}
var results = await JsonSerializer.DeserializeAsync<FooBarWrapper>(await response.Content.ReadAsStreamAsync(cancellationToken), cancellationToken: cancellationToken);
if (results == null)
{
Log.Error("Json deserialisation failed when parsing Foobar results");
return null;
}
if (!results.Success)
{
Log.Error("Foobar response was marked as unsuccessful.");
return null;
}
return results.Records;
}
catch (Exception e)
{
Log.Error(e, "Foobar retrieval failed");
return null;
}
}
It's a fairly simple function that retrieves some results from a REST call.
The problem is, only around 8 of these 40 lines of code provide the core functionality, the rest is essentially error handling. Most of the code is like this, when reading through it I have to wade through blocks of error handling.
I'm writing this code in a service in which reliability and robustness are extremely important.
Is this normal? Or am I going overboard? Is this a good thing? Should readability be sacrificed in the name of robustness? Is there a better way of doing this? | {
"domain": "codereview.stackexchange",
"id": 42687,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, .net, error-handling",
"url": null
} |
c#, .net, error-handling
Answer: Let's start with a code review. Your style is pleasant with good naming and indentation. About the only thing I would suggest is that method RetrieveFoobar could be named RetrieveFoobarAsync.
The reason you log things is to help you diagnose problems after the fact. If an exception is thrown, you log "Foobar retrieval failed". Is that log message by itself sufficient for someone to take corrective action? I would suggest you would also want to log the the actual exception in the catch block. Keep in mind it could be a composite exception, so you may need to unpeel it a bit more.
I think it is proper to have all the extra code to log the non-exceptional issues (!response.IsSuccessStatusCode, results == null, and !results.Success). This enables customized, very specific messages that should direct the person reading the log to a more immediate remedy than a vague, generic message. | {
"domain": "codereview.stackexchange",
"id": 42687,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, .net, error-handling",
"url": null
} |
c#, beginner, winforms
Title: Verify that 5 Textboxes have some content
Question: I'm new to C#. I have created a form that has 5 text boxes and this function checks to see if every text box has text in the box. If not, then it displays a message box saying "Error (Add Text)".
I wanted to see if there was a way to simplify this, or if this is the best way of completing this task :)
private bool ValidInput()
{
bool isValid = true;
//Check Title
if (string.IsNullOrEmpty(titleText.Text))
{
//Message Box Pass Through Title
MB("The Title can't be blank!", "Error!", MessageBoxIcon.Error);
titleText.Focus();
isValid = false;
}
//Check Artist
else if (string.IsNullOrEmpty(artistText.Text))
{
//Message Box Pass Through Artist
MB("The Artist can't be blank!", "Error!", MessageBoxIcon.Error);
artistText.Focus();
isValid = false;
}
//Check Genre
else if (string.IsNullOrEmpty(genreText.Text))
{
//Message Box Pass Through Genre
MB("The Genre can't be blank!", "Error!", MessageBoxIcon.Error);
genreText.Focus();
isValid = false;
}
//Check Year
else if (string.IsNullOrEmpty(yearText.Text))
{
//Message Box Pass Through Year
MB("The Year can't be blank!", "Error!", MessageBoxIcon.Error);
yearText.Focus();
isValid = false;
}
//Check URL
else if (string.IsNullOrEmpty(urlText.Text))
{
//Message Box Pass Through URl
MB("The URL can't be blank!", "Error!", MessageBoxIcon.Error);
urlText.Focus();
isValid = false;
}
return isValid;
} | {
"domain": "codereview.stackexchange",
"id": 42688,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, beginner, winforms",
"url": null
} |
c#, beginner, winforms
Answer: Try something like this:
private bool ValidInput()
{
bool isValid = true;
List<string[]> controlList = new List<string[]>(); //Control name, then display name.
controlList.Add(new[] { "titleText", "Title"});
controlList.Add(new[] { "artistText", "Artist" });
controlList.Add(new[] { "genreText", "Genre" });
controlList.Add(new[] { "yearText", "Year" });
controlList.Add(new[] { "urlText", "URL" });
for (int i = 0; i < controlList.Count; i++)
{
if (string.IsNullOrEmpty(this.Controls[controlList[i][0]].Text))
{
MB("The " + controlList[i][1] + " can't be blank!", "Error!", MessageBoxIcon.Error);
this.Controls[controlList[i][0]].Focus();
isValid = false;
break;
}
}
return isValid;
} | {
"domain": "codereview.stackexchange",
"id": 42688,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, beginner, winforms",
"url": null
} |
haskell
Title: Haskell Twitter Thread Follower
Question: I'm learning Haskell and even though I have experience with Functional Programming the Typesystem has been a challenge. I did this yesterday (after like 2 days) and I would like to know whether this is idiomatic Haskell. What this does is basically receive a Tweet ID and if the Tweet is replying to something then it pull all tweets in the thread and prints them to the screen. Here's a recording of the functionality https://asciinema.org/a/459103
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE OverloadedStrings #-}
module Main where
import Configuration.Dotenv (defaultConfig, loadFile)
import Control.Monad (void)
import Data.Aeson (FromJSON (..) ToJSON (..), Value, decode, withObject, (.:), (.:?))
import Data.Aeson.Types (Parser (..))
import qualified Data.ByteString as BS
import qualified Data.ByteString.Char8 as BS8
import Data.Maybe (fromJust)
import GHC.Generics
import Network.HTTP.Client
( Request (method, requestBody, requestHeaders),
RequestBody (RequestBodyLBS),
Response (..),
httpLbs,
newManager,
setQueryString,
)
import Network.HTTP.Client.Conduit (applyBearerAuth)
import Network.HTTP.Client.TLS (tlsManagerSettings)
import Network.HTTP.Simple (getResponseBody, parseRequest)
import System.Environment (getArgs, getEnv)
data TweetUser = TweetUser
{ name :: String,
username :: String
}
deriving (Generic, Show)
data Tweet = Tweet
{ tweetId :: String,
statusIdReply :: Maybe String,
text :: String,
user :: TweetUser
}
deriving (Generic, Show)
instance FromJSON Tweet where
parseJSON = tweetParser
instance FromJSON TweetUser where
parseJSON = tweetUserParser | {
"domain": "codereview.stackexchange",
"id": 42689,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "haskell",
"url": null
} |
haskell
instance FromJSON TweetUser where
parseJSON = tweetUserParser
tweetParser :: Value -> Parser Tweet
tweetParser = withObject "Tweet" $ \obj -> do
tweetId <- obj .: "id_str"
statusIdReply <- obj .:? "in_reply_to_status_id_str"
text <- obj .: "full_text"
user <- obj .: "user"
pure (Tweet {tweetId = tweetId, statusIdReply = statusIdReply, text = text, user = user})
tweetUserParser :: Value -> Parser TweetUser
tweetUserParser = withObject "TweetUser" $ \obj -> do
name <- obj .: "name"
username <- obj .: "screen_name"
pure (TweetUser {name = name, username = username})
bearerToken :: IO (BS.ByteString)
bearerToken = do
tokenEnv <- getEnv "BEARER_TOKEN"
return $ BS8.pack tokenEnv
baseUrl :: String
baseUrl = "https://api.twitter.com/1.1/statuses/show.json"
applyQueryStringAndAuth :: String -> BS.ByteString -> Request -> Request
applyQueryStringAndAuth tweetId token request = queryStr $ authReq
where
idParam = ("id", Just (BS8.pack tweetId))
tweetMode = ("tweet_mode", Just "extended")
queryStr = setQueryString [idParam, tweetMode]
authReq = applyBearerAuth token request
tweetResponse :: String -> IO (Tweet)
tweetResponse tweetId = do
manager <- newManager tlsManagerSettings
nakedRequest <- parseRequest baseUrl
token <- bearerToken
let request = applyQueryStringAndAuth tweetId token nakedRequest
response <- httpLbs request manager
return $ fromJust $ decode $ getResponseBody response
-- Based on the reply id (Whether a tweet is replying to another one)
-- we're asking for more tweets and putting them in an accumulator
moreTweets :: Maybe String -> [Tweet] -> IO ([Tweet])
moreTweets Nothing accTweets = return accTweets
moreTweets (Just replyId) accTweets = do
newTweet <- tweetResponse replyId
moreTweets (statusIdReply newTweet) (newTweet : accTweets) | {
"domain": "codereview.stackexchange",
"id": 42689,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "haskell",
"url": null
} |
haskell
parseTweets :: [Tweet] -> [String]
parseTweets = map convertToStr
where
convertToStr x = "\nusername: @" ++ (username $ user x) ++ "\nname: " ++ (name $ user x) ++ "\ntext: " ++ text x ++ "\n---"
-- Just follows a thread by Tweet ID
getThread :: String -> IO ()
getThread tweetId = do
tweet <- tweetResponse tweetId
tweets <- moreTweets (statusIdReply tweet) [tweet]
let parsedTweets = parseTweets tweets
mapM_ putStrLn parsedTweets
main :: IO ()
main = do
void $ loadFile defaultConfig
[tweetId] <- getArgs
getThread tweetId
I'd appreciate any feedback, this language is awesome so I would like to do it correctly :)
Answer: Big disclaimer: Whilst I review a lot of code, I'm not even close to a Haskell expert, so some of these ideas are probably not perfect, or even plain wrong, so take as starter points. | {
"domain": "codereview.stackexchange",
"id": 42689,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "haskell",
"url": null
} |
haskell
A few style ideas
Reduce imports
There are lots of redundant imports there. Tidying imports, like in most languages is important, but perhaps a bit harder in Haskell due to the nuances of importing. Good linters / IDEs can help here (see below).
Ditch unnecessary extensions
There are so many powerful extensions in Haskell that it's important to keep on top of what you need and what you don't need (there are linters that can help)
In particular, you don't need Generic (and so {-# LANGUAGE DeriveGeneric #-})
for JSON if you're defining your own parsers.
Use hlint
hlint is probably the best linter (well, static analyser really) I have used in 12+ languages. Due to the strong typing and guarantees in Haskell, it can provide deep insights using various laws, and as a beginner (and now intermediate) I learned -- and helped colleagues learn -- a lot of Haskell just from listening to its wonderful suggestions.
Also a linter
stylish-haskell is great IMO, but if you want a more opinionated linter, try Ormolu (or Fourmolu) or Brittany
Code changes
Scoping
Beware of global scope of records! Coming from other languages (as I did) this is hard to understand. tweetId in your Haskell module is now a function (of Tweet -> String) that you get "for free" by defining that record type Tweet. This means, whilst it works as is, there's scope overriding going on every time you use a binding called tweetId later on. One day this will bite you hard...
Consequently, annoyingly, it's idiomatic to prefix record fields with a bit, e.g. tweetId, tweetStatusIdReply, tweetText etc, though there are strong opinions around this, and actually things with record accessing are now changing
Use stronger types
Strings are useful, but type blindness is all too easy with say, foo :: String -> String -> String -> Int - i.e. mixing up the order is a common bug. By defining custom data types or using newtype (to wrap strings), you get much stronger guarantees for very little overhead: | {
"domain": "codereview.stackexchange",
"id": 42689,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "haskell",
"url": null
} |
haskell
getTweetResponse :: String -> IO Tweet
-- vs
getTweetResponse :: TweetID -> IO Tweet | {
"domain": "codereview.stackexchange",
"id": 42689,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "haskell",
"url": null
} |
haskell
See https://mmhaskell.com/liftoff/data-types for some good background reading.
Ditch partial functions
It's often said that partial functions should be avoided
For example, fromJust is evil - It blows up at runtime just by giving it a Nothing!
Much better is to pass around this uncertainty (Maybe) and make it part of your data / control flow e.g.
tweetResponse :: String -> IO (Maybe Tweet)
Ditch partial pattern matches too!
Your pattern match:
[tweetId] <- getArgs
blows up with a runtime error (!) if there are zero args, or two or more args.
Better to handle this with case (or various other ways). This makes code more lengthy but it's totally worth it.
Use decodeEither for nicer messages
Aeson's decode just gives you a result or Nothing. By using eitherDecode, you can get a helpful error message when things go wrong.
Handle non-200 responses
Currently the code parses any HTTP response the same (e.g. 401), even if it's an error. This will produce errors that are very confusing when things go wrong
Unwrap function parameters
It's often not that helpful to do the container processing ("unwrapping") - just keep it simple!
e.g. why have parseTweets which takes a list of tweets and gives you a list of their strings; rather, just define parseTweet and let the user call map (or maybe fmap etc, i.e. using some other container type). The code looks simpler this way too:
parseTweet :: Tweet -> String
parseTweet x = "\nusername: @" ++ userUsername (tweetUser x) ++ "\nname: " ++ userFullName (tweetUser x) ++ "\ntext: " ++ tweetText x ++ "\n---"
Likewise, with Maybes:
moreTweets :: Maybe String -> [Tweet] -> IO ([Tweet]) | {
"domain": "codereview.stackexchange",
"id": 42689,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "haskell",
"url": null
} |
haskell
Likewise, with Maybes:
moreTweets :: Maybe String -> [Tweet] -> IO ([Tweet])
Why process a Nothing to a Nothing manually?... just call it moreTweets :: String -> [Tweet] -> IO ([Tweet]) leave it to fmap (or maybeToList), or...
Neater recursion
It seems the current code has tweetResponse, getThread
moreTweets, all of which are various twists on taking tweetID and getting back tweets. Do we need all of these, or perhaps they could be combined?...
Use list methods for neatness
intercalate is very useful for turning a list of strings into, say, lines of text (avoiding all the \ns, and lists are much easier to read in code).
Reduce reliance on IO side-effects
IO in Haskell is clever and different, but looking back was maybe a slight mistake that so many things operate in it.
This often results in the IO Monad "polluting" code if not kept in check. But this is sometimes not necessary, and you should aim to keep all functions pure wherever possible (in many languages, arguably); makes testing and reasoning easier. Even when not doing that, it's nice to pass data around, so perhaps getThread :: String -> IO () should be getThread :: String -> IO [String] i.e. it returns a list of strings that the caller could print if they want (or ignore, or write to a DB, etc etc). In short, avoid IO () especially.
In fact, if you're interested to go deeper, read about Monad Transformers
Consider using Data.Text
It's annoying but eventually as a project gets bigger you should make the switch to Text (or something similar) from String. Some reading:
A good post on string types
Data-text-vs-string
Related: I like using <> (mappend) instead of ++ as it works on more types of data, including, say, Text...
A refactored version
FWIW, here's an updated version I did. Lots more improvements could be done no doubt but hopefully this illustrates all the points above (and a few more naming things):
{-# LANGUAGE OverloadedStrings #-}
module Main where | {
"domain": "codereview.stackexchange",
"id": 42689,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "haskell",
"url": null
} |
haskell
module Main where
import Configuration.Dotenv (defaultConfig, loadFile)
import Data.Aeson (FromJSON (..), eitherDecode,
withObject, (.:), (.:?))
import qualified Data.ByteString as BS
import qualified Data.ByteString.Char8 as BS8
import Data.List (intercalate)
import Network.HTTP.Client (Request, applyBearerAuth, httpLbs,
newManager, parseRequest,
setQueryString)
import Network.HTTP.Client.TLS (tlsManagerSettings)
import Network.HTTP.Simple (getResponseBody,
getResponseStatusCode)
import System.Environment (getArgs, getEnv)
newtype TweetID = TweetID String
deriving (Show, Eq)
newtype Token = Token BS.ByteString
deriving (Show, Eq)
data User = User
{ userFullName :: String,
userUsername :: String
}
deriving (Show, Eq)
data Tweet = Tweet
{ tweetId :: TweetID,
tweetInReplyToId :: Maybe TweetID,
tweetText :: String,
tweetUser :: User
}
deriving (Show, Eq)
instance FromJSON Tweet where
parseJSON = withObject "Tweet" $ \obj -> do
tid <- obj .: "id_str"
statusIdReply <- obj .:? "in_reply_to_status_id_str"
text <- obj .: "full_text"
user <- obj .: "user"
pure (Tweet {tweetId = TweetID tid, tweetInReplyToId = TweetID <$> statusIdReply, tweetText = text, tweetUser = user})
instance FromJSON User where
parseJSON = withObject "TweetUser" $ \obj -> do
name <- obj .: "name"
username <- obj .: "screen_name"
pure $ User name username
getBearerToken :: IO Token
getBearerToken = do
tokenEnv <- getEnv "BEARER_TOKEN"
(return . Token . BS8.pack) tokenEnv
baseUrl :: String
baseUrl = "https://api.twitter.com/1.1/statuses/show.json" | {
"domain": "codereview.stackexchange",
"id": 42689,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "haskell",
"url": null
} |
haskell
baseUrl :: String
baseUrl = "https://api.twitter.com/1.1/statuses/show.json"
applyQueryStringAndAuth :: Token -> TweetID -> Request -> Request
applyQueryStringAndAuth (Token rawToken) (TweetID tid) request = queryStr authReq
where
idParam = ("id", Just (BS8.pack tid))
tweetMode = ("tweet_mode", Just "extended")
queryStr = setQueryString [idParam, tweetMode]
authReq = applyBearerAuth rawToken request
-- | Gets a Tweet by ID from the API
getTweetResponse :: Token -> TweetID -> IO (Either String Tweet)
getTweetResponse token tid = do
manager <- newManager tlsManagerSettings
nakedRequest <- parseRequest baseUrl
let request = applyQueryStringAndAuth token tid nakedRequest
response <- httpLbs request manager
let body = getResponseBody response
return $
case getResponseStatusCode response of
200 -> eitherDecode body
badCode -> Left ("Got Bad status code: HTTP " <> show badCode <> ": " <> show body)
-- | Get all tweets in a thread, accumulating to the given list
getTweetThread :: Token -> TweetID -> IO [Tweet]
getTweetThread token = recurse []
where
recurse tweets tid = do
response <- getTweetResponse token tid
case response of
Right replyTweet ->
let allTweets = replyTweet : tweets
maybeReplyId = tweetInReplyToId replyTweet
in maybe (return allTweets) (recurse allTweets) maybeReplyId
Left message -> error message
renderTweet :: Tweet -> String
renderTweet tweet = intercalate "\n" fields
where
fields =
[ "username: @" <> userUsername user,
"name: " <> userFullName user,
"text: " <> tweetText tweet
]
user = tweetUser tweet
main :: IO ()
main = do
_ <- loadFile defaultConfig
token <- getBearerToken
args <- getArgs
case args of
[tid] -> do
tweets <- getTweetThread token (TweetID tid)
putStrLn $ intercalate "\n---\n" (renderTweet <$> tweets)
_ -> error "Usage: shrink <TWEET ID>" | {
"domain": "codereview.stackexchange",
"id": 42689,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "haskell",
"url": null
} |
python, python-3.x, client
Title: API client to retrieve traffic news
Question: I reverse engineered the API from adac.de and wrote a client to query it for traffic news (constructions sites, traffic jams etc.).
Here 's what I came up with:
#! /usr/bin/env python3
"""ADAC traffic news API Client."""
from argparse import ArgumentParser, Namespace
from functools import cache
from hashlib import md5
from json import dumps
from typing import Any
from requests import post
__all__ = ['get_traffic_news']
URL = 'https://www.adac.de/bff'
QUERY = '''query TrafficNews($filter: TrafficNewsFilterInput!) {
trafficNews(filter: $filter) {
...TrafficNewsItems
__typename
}
}
fragment TrafficNewsItems on TrafficNews {
size
items {
...TrafficNewsItem
__typename
}
__typename
}
fragment TrafficNewsItem on TrafficNewsItem {
id
type
details
street
timeLoss
streetSign {
streetNumber
country
__typename
}
headline {
__typename
...TrafficNewsDirectionHeadline
...TrafficNewsNonDirectionHeadline
}
__typename
}
fragment TrafficNewsDirectionHeadline on TrafficNewsDirectionHeadline {
from
to
__typename
}
fragment TrafficNewsNonDirectionHeadline on TrafficNewsNonDirectionHeadline {
text
__typename
}
'''
@cache
def md5hash(string: str) -> str:
"""Hashes the given string and return the hex digest."""
return md5(string.encode()).hexdigest()
def get_headers(query: dict[str, Any]) -> dict[str, str]:
"""Returns the headers for the request."""
return {
'content-type': 'application/json',
# We need to provide a hash to distinguish queries with different
# parameters from each other. Otherwise the API will return the result
# of last query regardless of the sent parameters.
'x-graphql-query-hash': md5hash(dumps(query))
} | {
"domain": "codereview.stackexchange",
"id": 42690,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, client",
"url": null
} |
python, python-3.x, client
def news_query(state: str, *, country: str = 'D', street: str = '',
construction_sites: bool = False, traffic_news: bool = True,
page_number: int = 1) -> dict[str, str]:
"""Returns a traffic news query."""
return {
'operationName': 'TrafficNews',
'variables': {
'filter': {
'country': {
'country': country,
'federalState': state,
'street': street,
'showConstructionSites': construction_sites,
'showTrafficNews': traffic_news,
'pageNumber': page_number
}
}
},
'query': QUERY
}
def get_traffic_news(
state: str, *, country: str = 'D', street: str = '',
construction_sites: bool = False, traffic_news: bool = True,
page_number: int = 1) -> dict[str, Any]:
"""Returns a traffic news dict."""
query = news_query(
state, country=country, street=street, traffic_news=traffic_news,
construction_sites=construction_sites, page_number=page_number
)
return post(URL, json=query, headers=get_headers(query)).json()
def get_args(*, description: str = __doc__) -> Namespace:
"""Return the parsed command line arguments."""
parser = ArgumentParser(description=description)
parser.add_argument('state')
parser.add_argument('-C', '--country', metavar='country', default='D')
parser.add_argument('-s', '--street', metavar='street')
parser.add_argument('-n', '--no-traffic-news', action='store_true')
parser.add_argument('-c', '--construction-sites', action='store_true')
parser.add_argument('-p', '--page', type=int, metavar='n', default=1)
return parser.parse_args()
def main() -> None:
"""Runs the script.""" | {
"domain": "codereview.stackexchange",
"id": 42690,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, client",
"url": null
} |
python, python-3.x, client
def main() -> None:
"""Runs the script."""
args = get_args()
json = get_traffic_news(
args.state, country=args.country, street=args.street,
traffic_news=not args.no_traffic_news, page_number=args.page,
construction_sites=args.construction_sites
)
print(dumps(json, indent=2))
if __name__ == '__main__':
main()
Any feedback is welcome. | {
"domain": "codereview.stackexchange",
"id": 42690,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, client",
"url": null
} |
python, python-3.x, client
Answer: Caching your MD5 hash is premature optimisation, and indeed there are more important things you should be caring about. For instance, you're serialising JSON twice; instead you should use a Requests prepared request that does the serialisation once. Even this is insignificant in comparison to the time in flight on the network.
I don't know that __all__ is all that important to define for something that isn't a module. If you made a proper module with an __init__.py and __main__.py perhaps that would change.
QUERY can be condensed somewhat while still staying legible, since whitespace is insignificant in GraphQL.
Don't set content-type - Requests does that for you when it sees the json kwarg.
The number of parameters on news_query is bordering on needing a class instance for convenience. A named tuple will be lightweight for this purpose.
It's marginally less common to differentiate command-line switches by capitalisation and more common to just choose a different letter from the long-form argument name.
Add some help for arguments that need it, particularly country.
I don't know why you've set state as a mandatory parameter, because it doesn't seem that way in the API.
Either as an alternative, or as a straight-up replacement, your command-line program should be outputting results in human-friendly, localised text rather than machine-friendly JSON. I'm on the fence as to whether the command-line arguments should also be localised to German; for now I've left them as English but (perhaps incongruously) shown the result headers in German.
Remove the space on the inside of your shebang line.
Remove your redundant metavar declarations.
Add first-class support for a Requests Session, even if you only use it once here. It will make writing a library easier, if that ever happens.
Page number is an internal API implementation detail and should not be exposed to the user. Instead, offer them an optional max-items count, and depaginate. | {
"domain": "codereview.stackexchange",
"id": 42690,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, client",
"url": null
} |
python, python-3.x, client
Note that you're not forming your hash the way this site does. This site hashes the result of the following expression in https://www.adac.de/assets/ui/client....js:
JSON.stringify({
operationName: i,
variables: a,
query: o,
uri: c,
environment: e,
previewMode: n,
noCacheValue: l
}) | {
"domain": "codereview.stackexchange",
"id": 42690,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, client",
"url": null
} |
python, python-3.x, client
which produces (after reformatting)
{
"operationName": "StreetSuggestions",
"variables": {
"filter": "A12",
"country": "D",
"type": "Highway"
},
"query": {
"kind": "Document",
"definitions": [
{
"kind": "OperationDefinition",
"operation": "query",
"name": {
"kind": "Name",
"value": "StreetSuggestions"
},
"variableDefinitions": [
{
"kind": "VariableDefinition",
"variable": {
"kind": "Variable",
"name": {
"kind": "Name",
"value": "filter"
}
},
"type": {
"kind": "NonNullType",
"type": {
"kind": "NamedType",
"name": {
"kind": "Name",
"value": "String"
}
}
},
"directives": []
},
{
"kind": "VariableDefinition",
"variable": {
"kind": "Variable",
"name": {
"kind": "Name",
"value": "country"
}
},
"type": {
"kind": "NonNullType",
"type": {
"kind": "NamedType",
"name": {
"kind": "Name",
"value": "String"
}
}
},
"directives": []
},
{
"kind": "VariableDefinition",
"variable": {
"kind": "Variable",
"name": {
"kind": "Name",
"value": "type"
}
},
"type": {
"kind": "NonNullType",
"type": {
"kind": "NamedType",
"name": {
"kind": "Name",
"value": "StreetType"
}
} | {
"domain": "codereview.stackexchange",
"id": 42690,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, client",
"url": null
} |
python, python-3.x, client
"value": "StreetType"
}
}
},
"directives": []
}
],
"directives": [],
"selectionSet": {
"kind": "SelectionSet",
"selections": [
{
"kind": "Field",
"name": {
"kind": "Name",
"value": "streets"
},
"arguments": [
{
"kind": "Argument",
"name": {
"kind": "Name",
"value": "filter"
},
"value": {
"kind": "Variable",
"name": {
"kind": "Name",
"value": "filter"
}
}
},
{
"kind": "Argument",
"name": {
"kind": "Name",
"value": "country"
},
"value": {
"kind": "Variable",
"name": {
"kind": "Name",
"value": "country"
}
}
},
{
"kind": "Argument",
"name": {
"kind": "Name",
"value": "type"
},
"value": {
"kind": "Variable",
"name": {
"kind": "Name",
"value": "type"
}
}
}
],
"directives": [],
"selectionSet": {
"kind": "SelectionSet",
"selections": [
{
"kind": "FragmentSpread",
"name": {
"kind": "Name", | {
"domain": "codereview.stackexchange",
"id": 42690,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, client",
"url": null
} |
python, python-3.x, client
"name": {
"kind": "Name",
"value": "StreetSuggestion"
},
"directives": []
},
{
"kind": "Field",
"name": {
"kind": "Name",
"value": "__typename"
}
}
]
}
}
]
}
},
{
"kind": "FragmentDefinition",
"name": {
"kind": "Name",
"value": "StreetSuggestion"
},
"typeCondition": {
"kind": "NamedType",
"name": {
"kind": "Name",
"value": "Street"
}
},
"directives": [],
"selectionSet": {
"kind": "SelectionSet",
"selections": [
{
"kind": "Field",
"name": {
"kind": "Name",
"value": "name"
},
"arguments": [],
"directives": []
},
{
"kind": "Field",
"name": {
"kind": "Name",
"value": "type"
},
"arguments": [],
"directives": []
},
{
"kind": "Field",
"name": {
"kind": "Name",
"value": "country"
},
"arguments": [],
"directives": []
},
{
"kind": "Field",
"name": {
"kind": "Name",
"value": "__typename"
}
}
]
}
}
],
"loc": {
"start": 0,
"end": 264
}
},
"environment": "prod",
"previewMode": false
} | {
"domain": "codereview.stackexchange",
"id": 42690,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, client",
"url": null
} |
python, python-3.x, client
This might not matter.
Suggested
#!/usr/bin/env python3
"""ADAC traffic news API Client."""
from argparse import ArgumentParser, Namespace
from hashlib import md5
from itertools import count, islice
from sys import stdout
from typing import Any, NamedTuple, Optional, Iterator, TextIO
from requests import Session, Request
GRAPHQL = '''query TrafficNews($filter: TrafficNewsFilterInput!) {
trafficNews(filter: $filter) {...TrafficNewsItems}
}
fragment TrafficNewsItems on TrafficNews {
size
items {...TrafficNewsItem}
}
fragment TrafficNewsItem on TrafficNewsItem {
id type details street timeLoss
streetSign {streetNumber country}
headline {
...TrafficNewsDirectionHeadline
...TrafficNewsNonDirectionHeadline
}
}
fragment TrafficNewsDirectionHeadline on TrafficNewsDirectionHeadline {
from to
}
fragment TrafficNewsNonDirectionHeadline on TrafficNewsNonDirectionHeadline {
text
}
'''
class NewsRequest(NamedTuple):
country: str = 'D'
state: str = ''
street: str = ''
construction_sites: bool = False
traffic_news: bool = True
@classmethod
def from_args(cls, args: Namespace) -> 'NewsRequest':
return cls(
country=args.country,
state=args.state,
street=args.street,
construction_sites=args.construction_sites,
)
def query(self, page: int) -> dict[str, Any]:
return {
'operationName': 'TrafficNews',
'variables': {
'filter': {
'country': {
'country': self.country,
'federalState': self.state,
'street': self.street,
'showConstructionSites': self.construction_sites,
'showTrafficNews': self.traffic_news,
'pageNumber': page,
}
}
},
'query': GRAPHQL,
} | {
"domain": "codereview.stackexchange",
"id": 42690,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, client",
"url": null
} |
python, python-3.x, client
class NewsResponse(NamedTuple):
id: int
type: str
country: Optional[str]
street: str
street_number: Optional[str]
headline: Optional[str]
details: str
@classmethod
def from_json(cls, json: dict[str, Any]) -> 'NewsResponse':
street_info = json.get('streetSign') or {}
return cls(
id=json['id'],
type=json['type'],
details=json['details'],
street_number=street_info.get('streetNumber'),
street=json['street'],
country=street_info.get('country'),
headline=json['headline'].get('text'),
)
def print(self, f: TextIO = stdout) -> None:
print(f'Sorte: {self.type}', file=f)
if self.country:
print(f'Land: {self.country}', file=f)
if self.street_number:
print(f'Straße: {self.street_number} {self.street}', file=f)
else:
print(f'Straße: {self.street}', file=f)
if self.headline:
print(f'Überschrift: {self.headline}', file=f)
print(f'Einzelheiten: {self.details}\n', file=f)
def get_traffic_news_page(
session: Session,
news_request: NewsRequest,
page: int,
) -> dict[str, Any]:
request = Request(
method='POST',
url='https://www.adac.de/bff',
headers={'Accept': 'application/json'},
json=news_request.query(page),
)
prepared = session.prepare_request(request)
prepared.headers['x-graphql-query-hash'] = md5(prepared.body).hexdigest()
with session.send(prepared) as response:
response.raise_for_status()
return response.json()['data']['trafficNews']
def get_traffic_news(
session: Session,
request: NewsRequest,
) -> Iterator[NewsResponse]:
# There are apparently 10 items per page, but let's not need to rely on this
n_items = 0 | {
"domain": "codereview.stackexchange",
"id": 42690,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, client",
"url": null
} |
python, python-3.x, client
for page in count(1):
data = get_traffic_news_page(session, request, page)
for news in data['items']:
yield NewsResponse.from_json(news)
n_items += 1
if n_items >= data['size']:
break
def get_args(*, description: str = __doc__) -> Namespace:
parser = ArgumentParser(description=description)
parser.add_argument(
'-c', '--country', default='D',
help='Country, one of: D (Germany), A (Austria), I (Italy), CH (Switzerland)',
)
parser.add_argument('-s', '--state')
parser.add_argument('-r', '--street')
parser.add_argument('-t', '--traffic-news', action='store_true')
parser.add_argument('-o', '--construction-sites', action='store_true')
parser.add_argument('-m', '--max-items', type=int)
return parser.parse_args()
def main() -> None:
args = get_args()
request = NewsRequest.from_args(args)
with Session() as session:
all_news = get_traffic_news(session, request)
if args.max_items is not None:
all_news = islice(all_news, args.max_items)
for news in all_news:
news.print()
if __name__ == '__main__':
main()
Output
This is the fully-depaginated output with all default arguments.
Sorte: verkehrsmeldung
Land: Deutschland
Straße: 1 A1
Einzelheiten: Zwischen Köln-Lövenich und Köln-Bocklemünd, Gefahr durch defektes Fahrzeug auf der rechten Seite liegengebliebenes Motorrad
Sorte: verkehrsmeldung
Land: Deutschland
Straße: 1 A1
Überschrift: Dortmund - Köln
Einzelheiten: In beiden Richtungen, Leverkusener Brücke, gesperrt für LKW über 3.5 t, vorübergehende Begrenzung der Breite auf 2.3 m, bis 31.12.2025
Sorte: verkehrsmeldung
Land: Deutschland
Straße: 1 A1
Einzelheiten: Zwischen Lengerich und Kreuz Lotte/Osnabrück, Gefahr durch ein totes Tier auf der Fahrbahn | {
"domain": "codereview.stackexchange",
"id": 42690,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, client",
"url": null
} |
python, python-3.x, client
Sorte: verkehrsmeldung
Land: Deutschland
Straße: 2 A2
Einzelheiten: Ausfahrt zur Raststätte Schafstrift, Tank- und Rastanlage, Raststätte geschlossen, bis 28.02.2022 ca. 18:00 Uhr Wasserschaden in der Raststätte
Sorte: verkehrsmeldung
Land: Deutschland
Straße: 3 A3
Einzelheiten: Zwischen Anschlussstelle Goldbach und Anschlussstelle Aschaffenburg-Ost, Verkehrsstörung, mittlere Geschwindigkeit 30 km/h
Sorte: verkehrsmeldung
Land: Deutschland
Straße: 3 A3
Einzelheiten: Zwischen Aschaffenburg-Ost und Aschaffenburg-West, Unfall mit mehreren Fahrzeugen, linker Fahrstreifen blockiert, mittlerer Fahrstreifen blockiert, Kräfte zur Störungsbeseitigung sind vor Ort, langsam fahren
Sorte: stau
Land: Deutschland
Straße: 5 A5
Einzelheiten: Zwischen Kronau und Kreuz Walldorf, 3 km Stau
Sorte: verkehrsmeldung
Land: Deutschland
Straße: 8 A8
Einzelheiten: Zwischen Dreieck Friedrichsthal und Elversberg, linker Fahrstreifen gesperrt, bis 05.02.2022 Mitternacht
Sorte: verkehrsmeldung
Land: Deutschland
Straße: 8 A8
Einzelheiten: Zwischen Grenzübergang Bad Reichenhall und Anschlussstelle Bad Reichenhall, Verkehrsstörung, mittlere Geschwindigkeit 30 km/h
Sorte: stau
Land: Deutschland
Straße: 8 A8
Einzelheiten: Zwischen Anschlussstelle Irschenberg und Anschlussstelle Weyarn, 6 km Stau, Verkehrsstörung, mittlere Geschwindigkeit 10 km/h, mindestens 33 Minuten Zeitverlust
Sorte: verkehrsmeldung
Land: Deutschland
Straße: 9 A9
Einzelheiten: Zwischen Rudolphstein und Bad Lobenstein, defekter LKW auf dem Standstreifen, bitte vorsichtig fahren
Sorte: verkehrsmeldung
Land: Deutschland
Straße: 24 A24
Einzelheiten: Zwischen Neuruppin und Neuruppin-Süd, 1 defekter PKW auf dem Standstreifen, Gefahr durch 2 Personen auf dem Standstreifen
Sorte: verkehrsmeldung
Land: Deutschland
Straße: 43 A43
Überschrift: Recklinghausen - Wuppertal
Einzelheiten: In beiden Richtungen, zwischen Kreuz Recklinghausen und Kreuz Herne, gesperrt für LKW über 3.5 t | {
"domain": "codereview.stackexchange",
"id": 42690,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, client",
"url": null
} |
python, python-3.x, client
Sorte: verkehrsmeldung
Land: Deutschland
Straße: 44 A44
Einzelheiten: Ausfahrt Heiligenhaus, Unfall, Ausfahrt gesperrt
Sorte: stau
Land: Deutschland
Straße: 45 A45
Einzelheiten: Zwischen Anschlussstelle Hagen-Süd und Anschlussstelle Lüdenscheid-Nord, 1 km Stau, Verkehrsstörung, mittlere Geschwindigkeit 10 km/h, mindestens 5 Minuten Zeitverlust
Sorte: verkehrsmeldung
Land: Deutschland
Straße: 73 A73
Einzelheiten: Einfahrt Buttenheim, Unfall im Kurvenbereich
Sorte: stau
Land: Deutschland
Straße: 95 A95
Einzelheiten: Zwischen Anschlussstelle München-Fürstenried und Anschlussstelle München-Sendling-Süd, 3 km stockender Verkehr, Verkehrsstörung, mittlere Geschwindigkeit 30 km/h, mindestens 3 Minuten Zeitverlust
Sorte: verkehrsmeldung
Straße: B1
Überschrift: Potsdam Glienicker Brücke
Einzelheiten: Gefahr durch 1 Person auf der Fahrbahn, fahren Sie bitte besonders vorsichtig
Sorte: stau
Straße: B2
Einzelheiten: Tunnel Farchant, Stau, Blockabfertigung
Sorte: verkehrsmeldung
Straße: B2
Einzelheiten: Zwischen Garmisch-Partenkirchen Nord und Übergang Anschluss A95, dichter Verkehr, mindestens 11 Minuten Zeitverlust
Sorte: vollsperrung
Straße: B2
Überschrift: B5 Berlin, Straße des 17. Juni
Einzelheiten: Zwischen Kreisverkehr Großer Stern und Scheidemannstraße gesperrt, Veranstaltung, bis 02.01.2022 23:59 Uhr
Sorte: verkehrsmeldung
Straße: B2
Überschrift: B2, Ebertstraße
Einzelheiten: Zwischen Einmündung Dorotheenstraße und Friedrichstraße, dichter Verkehr, mindestens 6 Minuten Zeitverlust
Sorte: vollsperrung
Straße: B2
Überschrift: Berlin, Greifswalder Straße
Einzelheiten: Zwischen Storkower Straße und Thomas-Mann-Straße gesperrt, Wasserrohrbruch
Sorte: verkehrsmeldung
Straße: B5
Überschrift: B5, Barmbeker Straße
Einzelheiten: Zwischen Kreuzung Borgweg und Weidestraße, dichter Verkehr, mindestens 3 Minuten Zeitverlust | {
"domain": "codereview.stackexchange",
"id": 42690,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, client",
"url": null
} |
python, python-3.x, client
Sorte: vollsperrung
Straße: B5
Überschrift: Straße des 17. Juni zwischen Yitzhak-Rabin-Straße und Scheidemannstraße in beiden Richtungen
Einzelheiten: Gesperrt, Veranstaltung, bis 02.01.2022 23:59 Uhr
Sorte: verkehrsmeldung
Straße: B9
Einzelheiten: Ausfahrt Waldsee, Gefahr durch Gegenstände auf der Fahrbahn (ein PKW-Rad)
Sorte: verkehrsmeldung
Straße: B9
Einzelheiten: Ausfahrt Limburgerhof-Neuhofen, Gefahr durch Gegenstände auf der Fahrbahn (ein PKW-Rad)
Sorte: verkehrsmeldung
Straße: B10
Überschrift: B10, Uferstraße
Einzelheiten: Zwischen Anschlussstelle Stuttgart-Ost und Rosensteinbrücke, dichter Verkehr, mindestens 10 Minuten Zeitverlust
Sorte: verkehrsmeldung
Straße: B19
Einzelheiten: Zwischen Fischen und Anschlussstelle Sonthofen, dichter Verkehr, mindestens 8 Minuten Zeitverlust
Sorte: verkehrsmeldung
Straße: B23
Einzelheiten: Zwischen Grainau und Garmisch-Partenkirchen, dichter Verkehr, mindestens 7 Minuten Zeitverlust
Sorte: verkehrsmeldung
Straße: B42
Einzelheiten: Zwischen Königswinter und Anschlussstelle Oberdollendorf, dichter Verkehr, mindestens 4 Minuten Zeitverlust
Sorte: verkehrsmeldung
Straße: B59
Überschrift: B59, Venloer Straße
Einzelheiten: Zwischen Kreuzung Innere Kanalstraße und Äußere Kanalstraße, dichter Verkehr, mindestens 5 Minuten Zeitverlust
Sorte: verkehrsmeldung
Straße: B73
Überschrift: B73, Buxtehuder Straße
Einzelheiten: Zwischen Kreuzung Schloßmühlendamm und Moorburger Straße, dichter Verkehr, mindestens 9 Minuten Zeitverlust
Sorte: verkehrsmeldung
Straße: B246
Einzelheiten: Zwischen Schönhagen und Berliner Straße, dichter Verkehr, mindestens 3 Minuten Zeitverlust
Sorte: verkehrsmeldung
Straße: B292
Überschrift: Sinsheim - Mosbach
Einzelheiten: Zwischen Bahnhof Finkenhof und B27, B37, Mosbacher Kreuz/Abzweig B37, in beiden Richtungen, die Geschwindigkeit ist begrenzt, zulässige Höchstgeschwindigkeit von 30 km/h, vorübergehende Begrenzung der Fahrbahnbreite auf 3,50 m, Straßenschäden auf Brücken, bis 03.01.2022 Mitternacht | {
"domain": "codereview.stackexchange",
"id": 42690,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, client",
"url": null
} |
python, python-3.x, client
Sorte: verkehrsmeldung
Straße: B96a
Überschrift: Berlin Elsenbrücke
Einzelheiten: In beiden Richtungen, Fahrbahn auf einen Fahrstreifen verengt, Staugefahr Brückenschäden
Sorte: vollsperrung
Straße:
Überschrift: Berlin
Einzelheiten: Conrad-Blenkle-Straße zwischen Kniprodestraße und Erich-Boltze-Straße in beiden Richtungen, gesperrt, Wasserrohrbruch, bis 31.03.2022
Sorte: vollsperrung
Straße:
Überschrift: Stadtgebiet Hamburg
Einzelheiten: Grelckstraße, von Stapelstraße zur Rütersbarg, Richtungsfahrbahn gesperrt, Einbahnstraßenregelung Richtung Stapelstraße, bis 22.04.2022 18:00 Uhr, Mo-Fr zwischen 06:00 Uhr und 18:00 Uhr
Sorte: vollsperrung
Straße:
Überschrift: Stadtgebiet Duisburg
Einzelheiten: Schifferstraße, von Max-Peters-Straße zur Am Innenhof, Richtungsfahrbahn gesperrt, gesperrt für LKW über 7.5 t, Einbahnstraßenregelung Richtung Max-Peters-Straße
Sorte: vollsperrung
Straße:
Überschrift: Stadtgebiet Duisburg
Einzelheiten: An der Cölve, in beiden Richtungen, zwischen Altenbruchstraße und Güterstraße, Brücke gesperrt, eine Umleitung ist eingerichtet, bis auf weiteres
Sorte: verkehrsmeldung
Straße: S2073
Einzelheiten: Zwischen Kleinpienzenau und Weyarn, dichter Verkehr, mindestens 10 Minuten Zeitverlust
Sorte: verkehrsmeldung
Straße: L52
Überschrift: Mecumstraße
Einzelheiten: Zwischen Kreuzung Auf m Hennekamp und Herzogstraße, dichter Verkehr, mindestens 3 Minuten Zeitverlust
Sorte: verkehrsmeldung
Straße: GN2
Überschrift: Würzburger Straße und Fürth-Fürberg
Einzelheiten: In beiden Richtungen, Achtung, Ihnen kommt ein Falschfahrer entgegen, nicht überholen, Vorsicht auf beiden Richtungsfahrbahnen | {
"domain": "codereview.stackexchange",
"id": 42690,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, client",
"url": null
} |
python, python-3.x, client
Sorte: vollsperrung
Straße: GF4
Überschrift: Sachsenhäuserufer bis Schaumainkai
Einzelheiten: Zwischen Alte Brücke und Untermainbrücke gesperrt, bis 03.01.2022 08:00 Uhr Sachsenhausen, Sperrung Sachsenhäuser Ufer und Schaumainkai (südliches Mainufer), Sachsenhäuser Ufer und Schaumainkai zwischen Alter Brücke und Untermainbrücke werden für den Jahreswechsel gesperrt. Verkehrsteilnehmer werden gebeten den genannten Bereich weiträumig zu umfahren. Vom 30.12.2021 bis 03.01.2022 ca. 07:00 Uhr.
Sorte: vollsperrung
Straße: L1070
Überschrift: Ebertstraße zwischen Hannah-Arendt-Straße und Scheidemannstraße in beiden Richtungen
Einzelheiten: Gesperrt, Veranstaltung, bis 02.01.2022 23:59 Uhr
Sorte: verkehrsmeldung
Straße:
Überschrift: Höchst Mainfähre Höchst
Einzelheiten: In beiden Richtungen, Personenfähre außer Betrieb, bis 19.01.2022 Mitternacht
Sorte: verkehrsmeldung
Straße:
Überschrift: Fähre „Arneburg“ bei Arneburg
Einzelheiten: In beiden Richtungen, über die Elbe, Einstellung des Fährbetriebs -Ende der Saison 2021, von 01.12.2021 bis 01.03.2022
Sorte: verkehrsmeldung
Straße: L111
Überschrift: Deutzer Brücke
Einzelheiten: In beiden Richtungen, gesperrt für LKW über 3.5 t, bis auf weiteres
Sorte: verkehrsmeldung
Straße: L1075
Überschrift: Rummelsburger Straße bis Minna-Todenhagen-Straße zwischen Rummelsburger Straße und Minna-Todenhagen-Straße in beiden Richtungen
Einzelheiten: Staugefahr, Verkehrsbehinderung, Baustelle, bis voraussichtlich 31.03.2022 Nur eine Linksabbiegespur von der Rummelsburger Straße auf die Minna-Todenhagen-Straße! Nur eine Rechsabbiegespur von der Minna-Todenhagen-Straße auf die Rummelsburger Straße!
Sorte: vollsperrung
Straße: GHB08
Überschrift: Am Wall
Einzelheiten: Von Kreuzung Ostertorstraße zum Herdentor, Richtungsfahrbahn gesperrt, Einbahnstraßenregelung Richtung Ostertorstraße, bis 31.03.2022 | {
"domain": "codereview.stackexchange",
"id": 42690,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, client",
"url": null
} |
python, python-3.x, client
Sorte: vollsperrung
Straße: GF96
Überschrift: Untermainkai bis Mainkai
Einzelheiten: Zwischen Neue Mainzer Straße und Schöne Aussicht gesperrt, bis 03.01.2022 08:00 Uhr Innenstadt, Sperrung Mainkai und Untermainkai (nördliches Mainufer), Mainkai und Untermainkai zwischen Alter Brücke und Untermainbrücke werden für den Jahreswechsel gesperrt. Verkehrsteilnehmer werden gebeten den genannten Bereich weiträumig zu umfahren. Vom 30.12.2021 bis 03.01.2022 ca. 07:00 Uhr. | {
"domain": "codereview.stackexchange",
"id": 42690,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, client",
"url": null
} |
c#, error-handling, exception
Title: Class to wrap result or exception, similar to the OneOf approach
Question: I recently came across the OneOf<T0,...,Tn> package from mcintyre321 via a video by Nick Chapsas, which presents the idea of holding exception types to be returned in the same object as would hold a successful result; e.g.
public OneOf<User, InvalidEmail, EmailAlreadyExists> CreateUser { /* ... */ }
This made me consider; aside from the expected return type (User), all other types are to cater for exceptions.
Also the caller of the class library (not API) who may only be interested in receiving a valid user or having an exception thrown, now needs to implement that logic for themselves, converting the OneOf approach to their own needs.
I considered the below class; as a way to also allow an expected result class or an Exception to be returned (not thrown).
public class ResultOrException<T>
{
private T _result;
public bool IsException {get {return Exception != null;}}
public Exception Exception {get;private set;}
public ResultOrException(): this(new InvalidOperationException($"A {nameof( ResultOrException<T> )} class has been accessed before it is assigned to.")){}
public ResultOrException(T result)
{
_result = result;
}
public ResultOrException(Exception exception)
{
Exception = exception ?? throw new ArgumentNullException(nameof(exception));
}
public static implicit operator T(ResultOrException<T> value)
{
if (value.IsException)
{
throw value.Exception;
}
return value._result;
}
public static implicit operator ResultOrException<T>(T result)
{
return new ResultOrException<T>(result);
}
} | {
"domain": "codereview.stackexchange",
"id": 42691,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, error-handling, exception",
"url": null
} |
c#, error-handling, exception
This includes implicit conversion to the expected result type; so if the client's expecting a value of type User they don't need to do any heavy lifting to get that; they just rely on implicit conversion. If the returned value was an exception, the exception gets thrown during the conversion so the information in that exception is then accessible to the caller.
However if the caller wants to handle the different exception cases differently (e.g. to return the exception to their API's caller), they can implement their own logic to handle that, without having to catch the thrown exception as they may if working with a more traditional class library.
Here's a simple example of the above class being used in practice:
void Main()
{
var userManager = new UserManager();
var found = false;
var result = new ResultOrException<User>();
while (!found) {
Console.WriteLine("Please enter your username");
var id = Console.ReadLine();
result = userManager.GetById(id);
found = !result.IsException;
if (!found)
{
Console.WriteLine("{0}. Please try again.", result.Exception?.Message);
}
}
User loggedInAs = result;
Console.WriteLine($"You've successfully logged in as '{loggedInAs.Name}'");
User nonExistant = userManager.GetById("simon.borg@example.com");
Console.WriteLine("We'll never get here; as the above line throws an exception");
}
public class UserManager
{
IDictionary<string, User> db;
public UserManager()
{
var users = new []{
new User("anne.droid@example.com", "Anne"),
new User("rob.ott@example.com", "Robert")
};
db = new Dictionary<string, User>();
foreach (var user in users)
{
db.Add(user.Id, user);
}
} | {
"domain": "codereview.stackexchange",
"id": 42691,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, error-handling, exception",
"url": null
} |
c#, error-handling, exception
public ResultOrException<User> GetById (string id)
{
if (db.ContainsKey(id))
{
return db[id];
}
return new ResultOrException<User>(new UserNotFoundException(id));
}
}
public class User
{
public string Id {get; private set;}
public string Name {get; private set;}
public User (string id, string name)
{
Id = id;
Name = name;
}
}
public class NotFoundException: Exception
{
public NotFoundException(string message): base(message){}
}
public class UserNotFoundException: NotFoundException
{
public UserNotFoundException(string userId): base($"No user with id '{userId}' was not found"){}
}
One issue with this approach is that the stack trace shows the error coming from the implicit conversion, rather than from where it's thrown; but I feel like in this context that shouldn't be an issue; as we'd only use this approach for functional exceptions. I.e. I wouldn't propose catching any exception and bundling them into the returned ResultOrException result; only assigning those exceptions which we'd expect a user to handle as part of the normal flow of business logic.
I'd be interested in others' thoughts on this approach.
Answer: Other solutions
There have already been several attempts to create something similar. They were called: Maybe, Failable, Either etc. Here are some examples and you'd find many more:
Struct implementation of immutable Maybe monad
Monad transformers in C# for use in validation
A Failable that allows safe returning of exceptions (especially interesing answer by Eric) | {
"domain": "codereview.stackexchange",
"id": 42691,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, error-handling, exception",
"url": null
} |
c#, error-handling, exception
Own experience
I like experimenting so I was curious how such a Maybe would work in a real project. At the end it turned out create more problems than it solved. In order for this to work reliably and consistently every single function had to implement it. This was the only way to entirely eliminate any exceptions. There were countless extra ifs to check for failed calls and extra returns on all levels where otherwise a single exception somewhere down deep would be enough to break the execution for an entire call chain and cascade to the top level where you'd handle it.
Review
If, however, your goal is not to eliminate exceptions altogether rather than throwing them while accessing the result anyway (like in your solution) then why not just throw them where they occur? This way there is less confusion about the result and you don't wonder why it worked but actually not.
In case you want to suppress exceptions then I find the bool TrySomething(...) pattern more intuitive. Everything else should be allowed and expected to fail. Otherwise you can never really tell when something might go sideways and where you need a try/catch.
Summarizing: I advise sticking to regular exceptions and use TryX for calls that are guaranteed not to fail. | {
"domain": "codereview.stackexchange",
"id": 42691,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, error-handling, exception",
"url": null
} |
python, python-3.x, pandas
Title: Multi-step aggregation of cryptocurrency data with high precision
Question: My goal is to aggregate a DataFrame with several million rows including Decimal('...') columns without any precision loss. My current implementation works - but might there be more efficient ways to get the job done?
Original DataFrame (sample)
game
position
amount
1
a
0.264825920790318533
1
a
0.136255564496617048
1
a
0.708422792050782986
1
b
0.102495961805507297
2
a
0.154110321496056788
2
b
0.281335658017562252
Aggregated DataFrame (sample)
game
amount_a
amount_b
1
1.109504277337718567
0.102495961805507297
2
0.154110321496056788
0.281335658017562252
My current approach
import pandas as pd
import numpy as np
from decimal import Decimal
from uuid import uuid4
# generating some sample DataFrame
df = pd.DataFrame(
data={
"game": [1, 1, 1, 1, 2, 2],
"position": ["a", "a", "a", "b", "a", "b"],
"amount": [
Decimal(f"{uuid4().int}"[:18]) * (Decimal(10) ** -18) for _ in range(6)
],
}
)
# aggregating...
agg_df = df.groupby(["game", "position"], as_index=False).agg(
{
"amount": "sum",
}
)
agg_df["amount_a"] = np.where(agg_df["position"] == "a", agg_df["amount"], 0)
agg_df["amount_b"] = np.where(agg_df["position"] == "b", agg_df["amount"], 0)
agg_df.drop(["amount", "position"], axis=1, inplace=True)
agg_df = agg_df.groupby(["game"], as_index=False).agg(
{
"amount_a": "sum",
"amount_b": "sum",
}
)
As far as I understand Python and Pandas, the biggest slowdown of my approach comes from the Decimal('...') columns in combination with sum. Since I need the precision of 10 ** -18 using the decimal package is my only option, right?
Is there a way in pandas to do the aggregation in fewer steps? | {
"domain": "codereview.stackexchange",
"id": 42692,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, pandas",
"url": null
} |
python, python-3.x, pandas
Answer: Comments above aside (this precision seems unnecessary), since you have a fixed precision you're better off operating in integer math. Numpy's uint64 will not be enough to hold a sum of millions of 18-digit integers, so use Python's built-in arbitrary-precision integers instead.
You jump through a lot of hoops to convert your grouped sum to a column for each position. This seems unnecessary and you should just accept the default multi-level index instead:
from random import seed, randrange
import pandas as pd
import numpy as np
seed(0)
amount = np.array(
[randrange(1e18) for _ in range(6)],
dtype=object,
)
# generating some sample DataFrame
df = pd.DataFrame(
data={
'game': (1, 1, 1, 1, 2, 2),
'position': ('a', 'a', 'a', 'b', 'a', 'b'),
'amount': amount,
}
)
agg_df = df.groupby(['game', 'position']).amount.sum()
print(agg_df)
game position
1 a 1051069403648066180
b 956755259049838137
2 a 412802820832641540
b 251847321245586963
Name: amount, dtype: object | {
"domain": "codereview.stackexchange",
"id": 42692,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, pandas",
"url": null
} |
c++
Title: First C++ Program : Simple Calculator
Question: Usage :
Multiplication
Multipliction is simple, Enter your first digit in (eg. 1)
Enter your operator (x)
Enter your second digit in (eg. 1)
Squaring
Enter your first digit in (eg. 1)
Enter your operator (s)
Cubing
Enter your first digit in (eg. 1)
Enter your operator (c)
Division
Division is also simple, Enter your first digit in (eg. 1)
Enter your operator (/)
Enter your second digit in (eg. 1)
Subtraction
Enter your first digit in (eg. 1)
Enter your operator (-)
Enter your second digit in (eg. 1)
Code:
#include <iostream>
using namespace std;
// Function Declaration
int multiply(int firstnumber, int secondnumber, char operation);
int square(int firstnumber, char operation);
int cube(int firstnumber, char operation);
int divide(int firstnumber, int secondnumber, char operation);
int subtract(int firstnumber, int secondnumber, char operation);
int main(){
// Variable Declaration :
int number1;
int number2;
char operation;
// User Input :
cout << "Enter the first number" << endl;
cin >> number1;
cout << "Enter the operator" << endl;
cin >> operation;
cout << "Enter the second number (leave blank for cube and square)" << endl;
cin >> number2;
cout << "This is your sum." << endl;
cout << number1 << operation << number2 << endl;
// Calculating :
int result;
char m = 'x';
char sq = 's';
char c = 'c';
char d = '/';
char s = '-'; | {
"domain": "codereview.stackexchange",
"id": 42693,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++",
"url": null
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.