text stringlengths 1 2.12k | source dict |
|---|---|
c++, sorting
Title: Introsort implementation
Question: I recently decided to make my own implementation of the Introsort sorting algorithm for educational purposes. Here's what I ended up with (apologies for the lack of comments):
#include <cmath>
#include <functional>
namespace __Introsort
{
template <typename T> using Compare = std::function<bool(T const &, T const &)>;
template <typename Container, typename T = typename Container::value_type>
void insertionSort(Container &arr, Compare<T> comp, size_t start, size_t end)
{
for (size_t i = start + 1; i <= end; i++)
{
T temp = arr[i];
size_t j = i;
if (comp(arr[i], arr[start]))
{
// arr[i] will land at the start. Don't bother to compare values.
// Just shift everything to the right.
for (; j > start; j--)
{
arr[j] = arr[j - 1];
}
arr[j] = temp;
}
else
{
// arr[start] serves as a natural sentinel. Don't bother to test indices.
for (; !comp(arr[j - 1], temp); j--)
{
arr[j] = arr[j - 1];
}
arr[j] = temp;
}
}
}
inline size_t heapNodeParent(size_t offset, size_t node)
{
// Simplification of (node - offset - 1) / 2 + offset
return (node + offset - 1) / 2;
}
inline size_t heapNodeLeftChild(size_t offset, size_t node)
{
// Simplification of 2 * (node - offset) + offset + 1
return 2 * node - offset + 1;
}
template <typename Container, typename T = typename Container::value_type>
void siftDown(Container &arr, Compare<T> comp, size_t offset, size_t start, size_t end)
{
size_t node = start;
while (heapNodeLeftChild(offset, node) <= end)
{
size_t swap = node;
size_t leftChild = heapNodeLeftChild(offset, node); | {
"domain": "codereview.stackexchange",
"id": 43430,
"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++, sorting",
"url": null
} |
c++, sorting
if (comp(arr[swap], arr[leftChild]))
{
swap = leftChild;
}
if (leftChild + 1 <= end && comp(arr[swap], arr[leftChild + 1]))
{
swap = leftChild + 1;
}
if (swap == node)
{
return;
}
std::swap(arr[swap], arr[node]);
node = swap;
}
}
template <typename Container, typename T = typename Container::value_type>
void heapify(Container &arr, Compare<T> comp, size_t start, size_t end)
{
size_t node = heapNodeParent(start, end);
while (node > start)
{
siftDown(arr, comp, start, node, end);
node = node - 1;
}
siftDown(arr, comp, start, node, end);
}
template <typename Container, typename T = typename Container::value_type>
void heapSort(Container &arr, Compare<T> comp, size_t start, size_t end)
{
heapify(arr, comp, start, end);
while (end > start)
{
std::swap(arr[end], arr[start]);
end = end - 1;
siftDown(arr, comp, start, start, end);
}
}
// Uses Hoare's partitioning scheme for quick sort
template <typename Container, typename T = typename Container::value_type>
size_t partition(Container &arr, Compare<T> comp, size_t start, size_t end)
{
// Pivot value
T pivot = arr[(start + end) / 2];
size_t i = start - 1;
size_t j = end + 1;
while (true)
{
do
{
i++;
} while (comp(arr[i], pivot));
do
{
j--;
} while (comp(pivot, arr[j]));
if (i >= j)
{
return j;
}
std::swap(arr[i], arr[j]);
}
} | {
"domain": "codereview.stackexchange",
"id": 43430,
"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++, sorting",
"url": null
} |
c++, sorting
std::swap(arr[i], arr[j]);
}
}
template <typename Container, typename T = typename Container::value_type>
void introSortHelper(Container &arr, Compare<T> comp, size_t start, size_t end, size_t maxdepth)
{
if (end - start + 1 < 16)
{
insertionSort(arr, comp, start, end);
}
else if (maxdepth == 0)
{
heapSort(arr, comp, start, end);
}
else
{
size_t p = partition(arr, comp, start, end);
introSortHelper(arr, comp, start, p, maxdepth - 1);
introSortHelper(arr, comp, p + 1, end, maxdepth - 1);
}
}
template <typename Container, typename T = typename Container::value_type>
void introSort(Container &arr, Compare<T> comp = std::less<T>())
{
introSortHelper(arr, comp, 0, arr.size() - 1, 2 * static_cast<size_t>(std::log2(arr.size())));
}
} // namespace __Introsort
using __Introsort::introSort;
When I tried to benchmark it against std::sort (GNU libstdc++ implementation), I found out that it's on average 4.2 times slower than std::sort. I believe that std::sort generally uses Introsort as well, so I'm not quite sure what's causing this massive slowdown. A minor slowdown like 1.5x is expected, but this is far too big of a slowdown for the same algorithm. It would be nice if someone could help me understand why there's such a big slowdown here.
As an extra note: Earlier this Introsort algorithm used Shellsort instead of Insertion sort when array size was lower than 16, and that turned out to be slower than using Insertion sort, much to my surprise.
For anyone wondering, here's the code I used to benchmark this:
#include "introsort.h"
#include <chrono>
#include <functional>
#include <iostream>
#include <vector>
template <typename T> bool vecEqual(std::vector<T> const &vec1, std::vector<T> const &vec2)
{
if (vec1.size() != vec2.size())
{
return false;
} | {
"domain": "codereview.stackexchange",
"id": 43430,
"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++, sorting",
"url": null
} |
c++, sorting
for (size_t i = 0; i < vec1.size(); i++)
{
if (vec1[i] != vec2[i])
{
return false;
}
}
return true;
} | {
"domain": "codereview.stackexchange",
"id": 43430,
"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++, sorting",
"url": null
} |
c++, sorting
int main()
{
std::vector<int> vec = {
541, 512, 875, 506, 77, 119, 755, 49, 146, 268, 179, 681, 542, 458, 396, 113, 898, 810,
586, 830, 611, 117, 930, 824, 681, 792, 249, 592, 323, 718, 316, 116, 842, 791, 327, 567,
583, 707, 342, 40, 198, 370, 879, 61, 252, 447, 665, 976, 7, 115, 820, 334, 562, 486,
229, 184, 965, 723, 886, 121, 791, 603, 617, 569, 187, 321, 826, 119, 714, 930, 786, 1,
692, 217, 762, 985, 820, 23, 656, 697, 701, 992, 953, 592, 829, 988, 689, 399, 566, 511,
677, 422, 625, 275, 158, 849, 271, 676, 775, 439, 696, 86, 853, 546, 424, 615, 96, 288,
804, 906, 563, 423, 971, 460, 45, 696, 423, 752, 745, 705, 403, 869, 138, 27, 107, 174,
352, 985, 947, 149, 845, 286, 826, 130, 941, 604, 8, 209, 635, 15, 297, 262, 688, 164,
356, 933, 708, 473, 669, 123, 235, 336, 302, 334, 498, 766, 885, 887, 250, 621, 699, 178,
352, 581, 416, 458, 978, 853, 645, 245, 579, 57, 647, 604, 216, 888, 290, 952, 913, 152,
288, 523, 280, 2, 354, 546, 239, 367, 40, 917, 985, 197, 770, 101, 266, 532, 230, 101,
964, 801, 637, 102, 651, 763, 976, 142, 750, 9, 486, 53, 28, 908, 561, 850, 364, 864,
687, 922, 229, 460, 396, 818, 672, 211, 620, 695, 332, 657, 910, 71, 854, 104, 615, 197,
475, 500, 673, 281, 463, 840, 269, 531, 242, 512, 785, 681, 592, 875, 362, 750, 168, 23,
82, 963, 883, 8, 480, 709, 117, 744, 974, 388, 191, 486, 480, 684, 29, 959, 706, 64,
636, 390, 635, 348, 692, 815, 700, 514, 824, 816, 329, 388, 322, 796, 244, 790, 222, 395,
359, 289, 956, 928, 736, 487, 913, 817, 343, 552, 236, 30, 34, 131, 417, 323, 38, 80,
802, 866, 575, 670, 555, 990, 122, 341, 882, 164, 790, 152, 81, 817, 423, 281, 961, 185,
123, 349, 254, 696, 666, 237, 3, 693, 563, 643, 70, 898, 294, 739, 99, 823, 416, 10,
764, 955, 794, 526, 239, 659, 588, 901, 616, 34, 345, 108, 966, 351, 428, 490, 820, 752, | {
"domain": "codereview.stackexchange",
"id": 43430,
"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++, sorting",
"url": null
} |
c++, sorting
764, 955, 794, 526, 239, 659, 588, 901, 616, 34, 345, 108, 966, 351, 428, 490, 820, 752,
567, 949, 109, 758, 215, 219, 56, 237, 500, 678, 887, 515, 24, 961, 42, 220, 314, 226,
293, 499, 943, 392, 192, 271, 98, 164, 169, 3, 196, 721, 71, 617, 311, 5, 219, 292,
863, 970, 341, 567, 956, 940, 81, 525, 28, 646, 908, 489, 448, 27, 857, 221, 580, 132,
586, 613, 287, 127, 823, 618, 271, 16, 335, 72, 501, 808, 435, 293, 268, 755, 244, 722,
205, 192, 419, 424, 244, 70, 633, 593, 601, 111, 916, 738, 503, 729, 439, 77, 981, 563,
281, 370, 972, 701, 914, 167, 305, 27, 192, 298, 603, 744, 701, 323, 519, 438, 712, 587,
253, 485, 455, 379, 499, 852, 21, 336, 939, 502, 70, 539, 291, 56, 705, 357, 289, 655,
573, 887, 771, 1, 981, 70, 57, 580, 526, 557, 397, 324, 14, 372, 378, 439, 488, 663,
515, 951, 586, 927, 876, 956, 115, 620, 663, 480, 768, 793, 949, 797, 244, 585, 901, 949,
51, 614, 456, 89, 742, 883, 970, 462, 630, 553, 948, 205, 290, 969, 442, 705, 970, 537,
498, 625, 524, 152, 681, 833, 114, 388, 427, 548, 409, 641, 463, 614, 208, 741, 458, 548,
319, 971, 547, 240, 552, 489, 917, 527, 776, 114, 47, 58, 836, 551, 197, 69, 315, 450,
616, 408, 318, 146, 55, 969, 757, 654, 162, 82, 369, 636, 766, 267, 191, 324, 946, 779,
652, 463, 879, 623, 575, 370, 678, 983, 567, 256, 258, 619, 115, 745, 214, 268, 468, 372,
399, 691, 164, 282, 398, 627, 328, 465, 263, 407, 252, 546, 399, 608, 285, 572, 485, 665,
176, 401, 767, 658, 121, 906, 87, 713, 556, 698, 295, 245, 144, 882, 938, 514, 431, 190,
614, 559, 842, 273, 476, 90, 700, 92, 682, 46, 33, 445, 9, 482, 369, 909, 180, 985,
346, 985, 899, 213, 831, 48, 327, 507, 724, 509, 990, 335, 198, 643, 54, 82, 164, 811,
71, 362, 416, 738, 715, 32, 53, 621, 79, 664, 988, 998, 185, 985, 210, 109, 214, 487, | {
"domain": "codereview.stackexchange",
"id": 43430,
"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++, sorting",
"url": null
} |
c++, sorting
71, 362, 416, 738, 715, 32, 53, 621, 79, 664, 988, 998, 185, 985, 210, 109, 214, 487,
681, 53, 973, 501, 911, 867, 887, 4, 644, 267, 427, 121, 685, 661, 155, 957, 274, 307,
790, 308, 968, 360, 179, 157, 875, 678, 350, 506, 746, 156, 176, 195, 834, 704, 693, 539,
205, 322, 580, 668, 532, 105, 895, 425, 876, 648, 192, 508, 366, 469, 147, 151, 695, 644,
276, 780, 820, 693, 573, 631, 934, 885, 164, 948, 592, 775, 949, 818, 176, 228, 914, 336,
553, 74, 801, 635, 269, 404, 818, 111, 809, 948, 454, 780, 818, 692, 961, 88, 946, 997,
804, 993, 846, 390, 386, 129, 358, 757, 307, 947, 657, 506, 79, 520, 999, 933, 147, 607,
122, 296, 165, 360, 583, 299, 273, 838, 619, 875, 576, 962, 177, 406, 195, 315, 737, 991,
140, 587, 466, 780, 619, 104, 426, 825, 842, 136, 747, 542, 208, 605, 95, 808, 978, 748,
36, 231, 64, 104, 588, 700, 552, 183, 224, 741, 614, 484, 149, 175, 966, 654, 538, 381,
139, 677, 262, 638, 781, 980, 87, 590, 808, 615, 601, 46, 349, 221, 34, 125, 269, 524,
7, 898, 903, 391, 810, 550, 201, 956, 606, 457, 886, 149, 705, 529, 399, 428, 731, 180,
864, 251, 326, 281, 261, 282, 386, 837, 681, 996, 749, 968, 74, 578, 928, 796, 158, 136,
733, 779, 748, 583, 855, 535, 491, 655, 796, 742, 461, 165, 380, 76, 496, 694, 606, 329,
643, 41, 649, 37, 66, 211, 615, 16, 483, 90, 855, 954, 885, 442, 245, 413, 753, 88,
130, 522, 149, 302, 133, 542, 685, 508, 424, 547, 686, 206, 517, 179, 749, 120, 950, 834,
830, 112, 582, 707, 481, 124, 844, 849, 14, 704, 127, 611, 378, 850, 911, 904, 564, 424,
185, 752, 82, 69, 205, 39, 322, 472, 323, 339
}; | {
"domain": "codereview.stackexchange",
"id": 43430,
"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++, sorting",
"url": null
} |
c++, sorting
std::vector<int> vecTemp;
int runs = 100;
long total = 0;
long avg1;
long avg2;
for (int i = 0; i < runs; i++)
{
vecTemp = vec;
auto start = std::chrono::high_resolution_clock::now();
introSort(vecTemp);
auto end = std::chrono::high_resolution_clock::now();
total += std::chrono::duration_cast<std::chrono::nanoseconds>(end - start).count();
}
avg1 = total / runs;
total = 0;
for (int i = 0; i < runs; i++)
{
vecTemp = vec;
auto start = std::chrono::high_resolution_clock::now();
std::sort(vecTemp.begin(), vecTemp.end());
auto end = std::chrono::high_resolution_clock::now();
total += std::chrono::duration_cast<std::chrono::nanoseconds>(end - start).count();
}
avg2 = total / runs;
std::cout << "Custom Introsort: " << avg1 << "\nC++ Standard Library Sort: " << avg2 << "\n";
}
```
Answer: One of the major reasons the native C++ std::sort() is faster than qsort() inherited from C is that the latter calls the comparator using a pointer.
While that is excellent for reducing binary footprint, it costs a lot, not really due to the indirect call itself, but due to all the optimization opportunities lost because it is not inlined and available for optimization.
While you don't use any raw function-pointers, you use std::function in your interface, which has the same performance implications. Actually, it is a bit more versatile, and thus costs slightly more.
Template your code to accept any callable and use it directly, and performance should improve significantly. | {
"domain": "codereview.stackexchange",
"id": 43430,
"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++, sorting",
"url": null
} |
c++, c++11, compiler, webassembly, aec
Title: AEC-to-WebAssembly compiler in C++
Question: Now that my new compiler is capable of compiling programs such as the Analog Clock in AEC, I've decided to share the code of that compiler with you, to see what you think about it.
File compiler.cpp:
#include "TreeNode.cpp"
#include "bitManipulations.cpp" | {
"domain": "codereview.stackexchange",
"id": 43431,
"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++, c++11, compiler, webassembly, aec",
"url": null
} |
c++, c++11, compiler, webassembly, aec
AssemblyCode convertToInteger32(const TreeNode node,
const CompilationContext context) {
auto originalCode = node.compile(context);
const AssemblyCode::AssemblyType i32 = AssemblyCode::AssemblyType::i32,
i64 = AssemblyCode::AssemblyType::i64,
f32 = AssemblyCode::AssemblyType::f32,
f64 = AssemblyCode::AssemblyType::f64,
null = AssemblyCode::AssemblyType::null;
if (originalCode.assemblyType == null) {
std::cerr
<< "Line " << node.lineNumber << ", Column " << node.columnNumber
<< ", Compiler error: Some part of the compiler attempted to convert \""
<< node.text
<< "\" to \"Integer32\", which makes no sense. This could be an "
"internal compiler error, or there could be something semantically "
"(though not grammatically) very wrong with your program."
<< std::endl;
exit(1);
}
if (originalCode.assemblyType == i32)
return originalCode;
if (originalCode.assemblyType == i64)
return AssemblyCode(
"(i32.wrap_i64\n" + std::string(originalCode.indentBy(1)) + "\n)", i32);
if (originalCode.assemblyType == f32)
return AssemblyCode(
"(i32.trunc_f32_s\n" + std::string(originalCode.indentBy(1)) + "\n)",
i32); // Makes little sense to me (that, when converting to an integer,
// the decimal part of the number is simply truncated), but that's
// how it is done in the vast majority of programming languages.
if (originalCode.assemblyType == f64)
return AssemblyCode("(i32.trunc_f64_s\n" +
std::string(originalCode.indentBy(1)) + "\n)",
i32);
std::cerr << "Line " << node.lineNumber << ", Column " << node.columnNumber
<< ", Compiler error: Internal compiler error, control reached the " | {
"domain": "codereview.stackexchange",
"id": 43431,
"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++, c++11, compiler, webassembly, aec",
"url": null
} |
c++, c++11, compiler, webassembly, aec
<< ", Compiler error: Internal compiler error, control reached the "
"end of the \"convertToInteger32\" function!"
<< std::endl;
exit(-1);
return AssemblyCode("()");
} | {
"domain": "codereview.stackexchange",
"id": 43431,
"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++, c++11, compiler, webassembly, aec",
"url": null
} |
c++, c++11, compiler, webassembly, aec
AssemblyCode convertToInteger64(const TreeNode node,
const CompilationContext context) {
auto originalCode = node.compile(context);
const AssemblyCode::AssemblyType i32 = AssemblyCode::AssemblyType::i32,
i64 = AssemblyCode::AssemblyType::i64,
f32 = AssemblyCode::AssemblyType::f32,
f64 = AssemblyCode::AssemblyType::f64,
null = AssemblyCode::AssemblyType::null;
if (originalCode.assemblyType == null) {
std::cerr
<< "Line " << node.lineNumber << ", Column " << node.columnNumber
<< ", Compiler error: Some part of the compiler attempted to convert \""
<< node.text
<< "\" to \"Integer64\", which makes no sense. This could be an "
"internal compiler error, or there could be something semantically "
"(though not grammatically) very wrong with your program."
<< std::endl;
exit(1);
}
if (originalCode.assemblyType == i32)
return AssemblyCode(
"(i64.extend_i32_s\n" + // If you don't put "_s", JavaScript Virtual
// Machine is going to interpret the argument as
// unsigned, leading to huge positive numbers
// instead of negative ones.
std::string(originalCode.indentBy(1)) + "\n)",
i64);
if (originalCode.assemblyType == i64)
return originalCode;
if (originalCode.assemblyType == f32)
return AssemblyCode("(i64.trunc_f32_s\n" +
std::string(originalCode.indentBy(1)) + "\n)",
i64);
if (originalCode.assemblyType == f64)
return AssemblyCode("(i64.trunc_f64_s\n" +
std::string(originalCode.indentBy(1)) + "\n)",
i64);
std::cerr << "Line " << node.lineNumber << ", Column " << node.columnNumber | {
"domain": "codereview.stackexchange",
"id": 43431,
"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++, c++11, compiler, webassembly, aec",
"url": null
} |
c++, c++11, compiler, webassembly, aec
std::cerr << "Line " << node.lineNumber << ", Column " << node.columnNumber
<< ", Compiler error: Internal compiler error, control reached the "
"end of the \"convertToInteger64\" function!"
<< std::endl;
exit(-1);
return AssemblyCode("()");
} | {
"domain": "codereview.stackexchange",
"id": 43431,
"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++, c++11, compiler, webassembly, aec",
"url": null
} |
c++, c++11, compiler, webassembly, aec
AssemblyCode convertToDecimal32(const TreeNode node,
const CompilationContext context) {
auto originalCode = node.compile(context);
const AssemblyCode::AssemblyType i32 = AssemblyCode::AssemblyType::i32,
i64 = AssemblyCode::AssemblyType::i64,
f32 = AssemblyCode::AssemblyType::f32,
f64 = AssemblyCode::AssemblyType::f64,
null = AssemblyCode::AssemblyType::null;
if (originalCode.assemblyType == null) {
std::cerr
<< "Line " << node.lineNumber << ", Column " << node.columnNumber
<< ", Compiler error: Some part of the compiler attempted to convert \""
<< node.text
<< "\" to \"Decimal32\", which makes no sense. This could be an "
"internal compiler error, or there could be something semantically "
"(though not grammatically) very wrong with your program."
<< std::endl;
exit(1);
}
if (originalCode.assemblyType == i32)
return AssemblyCode(
"(f32.convert_i32_s\n" + // Again, those who designed JavaScript Virtual
// Machine had a weird idea that integers
// should be unsigned unless somebody makes
// them explicitly signed via "_s".
std::string(originalCode.indentBy(1)) + "\n)",
f32);
if (originalCode.assemblyType == i64)
return AssemblyCode("(f32.convert_i64_s\n" +
std::string(originalCode.indentBy(1)) + "\n)",
f32);
if (originalCode.assemblyType == f32)
return originalCode;
if (originalCode.assemblyType == f64)
return AssemblyCode("(f32.demote_f64\n" +
std::string(originalCode.indentBy(1)) + "\n)",
f32); | {
"domain": "codereview.stackexchange",
"id": 43431,
"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++, c++11, compiler, webassembly, aec",
"url": null
} |
c++, c++11, compiler, webassembly, aec
f32);
std::cerr << "Line " << node.lineNumber << ", Column " << node.columnNumber
<< ", Compiler error: Internal compiler error, control reached the "
"end of the \"convertToDecimal32\" function!"
<< std::endl;
exit(-1);
return AssemblyCode("()");
} | {
"domain": "codereview.stackexchange",
"id": 43431,
"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++, c++11, compiler, webassembly, aec",
"url": null
} |
c++, c++11, compiler, webassembly, aec
AssemblyCode convertToDecimal64(const TreeNode node,
const CompilationContext context) {
auto originalCode = node.compile(context);
const AssemblyCode::AssemblyType i32 = AssemblyCode::AssemblyType::i32,
i64 = AssemblyCode::AssemblyType::i64,
f32 = AssemblyCode::AssemblyType::f32,
f64 = AssemblyCode::AssemblyType::f64,
null = AssemblyCode::AssemblyType::null;
if (originalCode.assemblyType == null) {
std::cerr
<< "Line " << node.lineNumber << ", Column " << node.columnNumber
<< ", Compiler error: Some part of the compiler attempted to convert \""
<< node.text
<< "\" to \"Decimal64\", which makes no sense. This could be an "
"internal compiler error, or there could be something semantically "
"(though not grammatically) very wrong with your program."
<< std::endl;
exit(1);
}
if (originalCode.assemblyType == i32)
return AssemblyCode("(f64.convert_i32_s\n" +
std::string(originalCode.indentBy(1)) + "\n)",
f64);
if (originalCode.assemblyType == i64)
return AssemblyCode("(f64.convert_i64_s\n" +
std::string(originalCode.indentBy(1)) + "\n)",
f64);
if (originalCode.assemblyType == f32)
return AssemblyCode("(f64.promote_f32\n" +
std::string(originalCode.indentBy(1)) + "\n)",
f64);
if (originalCode.assemblyType == f64)
return originalCode;
std::cerr << "Line " << node.lineNumber << ", Column " << node.columnNumber
<< ", Compiler error: Internal compiler error, control reached the "
"end of the \"convertToDecimal64\" function!"
<< std::endl;
exit(-1);
return AssemblyCode("()");
} | {
"domain": "codereview.stackexchange",
"id": 43431,
"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++, c++11, compiler, webassembly, aec",
"url": null
} |
c++, c++11, compiler, webassembly, aec
AssemblyCode convertTo(const TreeNode node, const std::string type,
const CompilationContext context) {
if (type == "Character" or type == "Integer16" or type == "Integer32" or
std::regex_search(
type,
std::regex(
"Pointer$"))) // When, in JavaScript Virtual Machine, you can't
// push types of less than 4 bytes (32 bits) onto
// the system stack, you need to convert those to
// Integer32 (i32). Well, makes slightly more sense
// than the way it is in 64-bit x86 assembly, where
// you can put 16-bit values and 64-bit values onto
// the system stack, but you can't put 32-bit
// values.
return convertToInteger32(node, context);
if (type == "Integer64")
return convertToInteger64(node, context);
if (type == "Decimal32")
return convertToDecimal32(node, context);
if (type == "Decimal64")
return convertToDecimal64(node, context);
std::cerr << "Line " << node.lineNumber << ", Column " << node.columnNumber
<< ", Compiler error: Some part of the compiler attempted to get "
"the assembly code for converting \""
<< node.text << "\" into the type \"" << type
<< "\", which doesn't make sense. This could be an internal "
"compiler error, or there could be something semantically "
"(though not grammatically) very wrong with your program."
<< std::endl;
exit(-1);
return AssemblyCode("()");
}
std::string getStrongerType(int, int, std::string,
std::string); // When C++ doesn't support function
// hoisting, like JavaScript does. | {
"domain": "codereview.stackexchange",
"id": 43431,
"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++, c++11, compiler, webassembly, aec",
"url": null
} |
c++, c++11, compiler, webassembly, aec
AssemblyCode TreeNode::compile(CompilationContext context) const {
std::string typeOfTheCurrentNode = getType(context);
if (!mappingOfAECTypesToWebAssemblyTypes.count(typeOfTheCurrentNode)) {
std::cerr
<< "Line " << lineNumber << ", Column " << columnNumber
<< ", Internal compiler error: The function \"getType\" returned \""
<< typeOfTheCurrentNode
<< "\", which is an invalid name of type. Aborting the compilation!"
<< std::endl;
exit(1);
}
AssemblyCode::AssemblyType returnType =
mappingOfAECTypesToWebAssemblyTypes.at(typeOfTheCurrentNode);
auto iteratorOfTheCurrentFunction =
std::find_if(context.functions.begin(), context.functions.end(),
[=](function someFunction) {
return someFunction.name == context.currentFunctionName;
});
if (iteratorOfTheCurrentFunction == context.functions.end()) {
std::cerr
<< "Line " << lineNumber << ", Column " << columnNumber
<< ", Internal compiler error: The \"compile(CompilationContext)\" "
"function was called without setting the current function name, "
"aborting compilation (or else the compiler will segfault)!"
<< std::endl;
exit(1);
}
function currentFunction = *iteratorOfTheCurrentFunction;
std::string assembly;
if (text == "Does" or text == "Then" or text == "Loop" or
text == "Else") // Blocks of code are stored by the parser as child nodes
// of "Does", "Then", "Else" and "Loop".
{
if (text != "Does")
context.stackSizeOfThisScope =
0; //"TreeRootNode" is supposed to set up the arguments in the scope
// before passing the recursion onto the "Does" node.
for (auto childNode : children) {
if (childNode.text == "Nothing")
continue;
else if (basicDataTypeSizes.count(childNode.text)) {
// Local variables declaration. | {
"domain": "codereview.stackexchange",
"id": 43431,
"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++, c++11, compiler, webassembly, aec",
"url": null
} |
c++, c++11, compiler, webassembly, aec
else if (basicDataTypeSizes.count(childNode.text)) {
// Local variables declaration.
for (TreeNode variableName : childNode.children) {
if (variableName.text.back() != '[') { // If it's not an array.
context.localVariables[variableName.text] = 0;
for (auto &pair : context.localVariables)
pair.second += basicDataTypeSizes.at(childNode.text);
context.variableTypes[variableName.text] = childNode.text;
context.stackSizeOfThisFunction +=
basicDataTypeSizes.at(childNode.text);
context.stackSizeOfThisScope +=
basicDataTypeSizes.at(childNode.text);
assembly += "(global.set $stack_pointer\n\t(i32.add (global.get "
"$stack_pointer) (i32.const " +
std::to_string(basicDataTypeSizes.at(childNode.text)) +
")) ;;Allocating the space for the local variable \"" +
variableName.text + "\".\n)\n";
if (variableName.children.size() and
variableName.children[0].text ==
":=") // Initial assignment to local variables.
{
TreeNode assignmentNode = variableName.children[0];
assignmentNode.children.insert(assignmentNode.children.begin(),
variableName);
assembly += assignmentNode.compile(context) + "\n";
}
} else { // If that's a local array declaration.
int arraySizeInBytes =
basicDataTypeSizes.at(childNode.text) *
variableName.children[0]
.interpretAsACompileTimeIntegerConstant();
context.localVariables[variableName.text] = 0;
for (auto &pair : context.localVariables)
pair.second += arraySizeInBytes;
context.variableTypes[variableName.text] = childNode.text; | {
"domain": "codereview.stackexchange",
"id": 43431,
"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++, c++11, compiler, webassembly, aec",
"url": null
} |
c++, c++11, compiler, webassembly, aec
context.variableTypes[variableName.text] = childNode.text;
context.stackSizeOfThisFunction += arraySizeInBytes;
context.stackSizeOfThisScope += arraySizeInBytes;
assembly += "(global.set $stack_pointer\n\t(i32.add (global.get "
"$stack_pointer) (i32.const " +
std::to_string(arraySizeInBytes) +
")) ;;Allocating the space for the local array \"" +
variableName.text + "\".\n)\n";
if (variableName.children.size() == 2 and
variableName.children[1].text == ":=" and
variableName.children[1].children[0].text ==
"{}") // Initial assignments of local arrays.
{
TreeNode initialisationList =
variableName.children[1].children[0];
for (unsigned int i = 0; i < initialisationList.children.size();
i++) {
TreeNode element = initialisationList.children[i];
TreeNode assignmentNode(
":=", variableName.children[1].lineNumber,
variableName.children[1].columnNumber);
TreeNode whereToAssignTheElement(
variableName.text, variableName.lineNumber,
variableName
.columnNumber); // Damn, can you think up a language in
// which writing stuff like this isn't
// as tedious and error-prone as it is
// in C++ or JavaScript? Maybe some
// language in which you can switch
// between a C-like syntax and a
// Lisp-like syntax at will?
whereToAssignTheElement.children.push_back(TreeNode( | {
"domain": "codereview.stackexchange",
"id": 43431,
"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++, c++11, compiler, webassembly, aec",
"url": null
} |
c++, c++11, compiler, webassembly, aec
whereToAssignTheElement.children.push_back(TreeNode(
std::to_string(i), variableName.children[0].lineNumber,
variableName.children[1].columnNumber));
assignmentNode.children.push_back(whereToAssignTheElement);
assignmentNode.children.push_back(element);
assembly += assignmentNode.compile(context) + "\n";
}
}
}
}
} else
assembly += std::string(childNode.compile(context)) + "\n";
}
assembly += "(global.set $stack_pointer (i32.sub (global.get "
"$stack_pointer) (i32.const " +
std::to_string(context.stackSizeOfThisScope) + ")))";
} else if (text.front() == '"')
assembly += "(i32.const " + std::to_string(context.globalVariables[text]) +
") ;;Pointer to " + text;
else if (context.variableTypes.count(text)) {
if (typeOfTheCurrentNode == "Character")
assembly +=
"(i32.load8_s\n" + compileAPointer(context).indentBy(1) + "\n)";
else if (typeOfTheCurrentNode == "Integer16")
assembly +=
"(i32.load16_s\n" + compileAPointer(context).indentBy(1) + "\n)";
else if (typeOfTheCurrentNode == "Integer32" or
std::regex_search(typeOfTheCurrentNode, std::regex("Pointer$")))
assembly += "(i32.load\n" + compileAPointer(context).indentBy(1) + "\n)";
else if (typeOfTheCurrentNode == "Integer64")
assembly += "(i64.load\n" + compileAPointer(context).indentBy(1) + "\n)";
else if (typeOfTheCurrentNode == "Decimal32")
assembly += "(f32.load\n" + compileAPointer(context).indentBy(1) + "\n)";
else if (typeOfTheCurrentNode == "Decimal64")
assembly += "(f64.load\n" + compileAPointer(context).indentBy(1) + "\n)";
else {
std::cerr << "Line " << lineNumber << ", Column " << columnNumber
<< ", Internal compiler error: Compiler got into a forbidden " | {
"domain": "codereview.stackexchange",
"id": 43431,
"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++, c++11, compiler, webassembly, aec",
"url": null
} |
c++, c++11, compiler, webassembly, aec
<< ", Internal compiler error: Compiler got into a forbidden "
"state while compiling the token \""
<< text << "\", aborting the compilation!" << std::endl;
exit(1);
}
} else if (text == ":=") {
TreeNode rightSide;
if (children[1].text == ":=") { // Expressions such as "a:=b:=0" or similar.
TreeNode tmp = children[1]; // In case the "compile" changes the TreeNode
// (which the GNU C++ compiler should forbid,
// but apparently doesn't).
assembly += children[1].compile(context) + "\n";
rightSide = tmp.children[0];
} else
rightSide = children[1];
assembly += ";;Assigning " + rightSide.getLispExpression() + " to " +
children[0].getLispExpression() + ".\n";
if (typeOfTheCurrentNode == "Character")
assembly += "(i32.store8\n" +
children[0].compileAPointer(context).indentBy(1) + "\n" +
convertToInteger32(rightSide, context).indentBy(1) + "\n)";
else if (typeOfTheCurrentNode == "Integer16")
assembly += "(i32.store16\n" +
children[0].compileAPointer(context).indentBy(1) + "\n" +
convertToInteger32(rightSide, context).indentBy(1) + "\n)";
else if (typeOfTheCurrentNode == "Integer32" or
std::regex_search(typeOfTheCurrentNode, std::regex("Pointer$")))
assembly += "(i32.store\n" +
children[0].compileAPointer(context).indentBy(1) + "\n" +
convertToInteger32(rightSide, context).indentBy(1) + "\n)";
else if (typeOfTheCurrentNode == "Integer64")
assembly += "(i64.store\n" +
children[0].compileAPointer(context).indentBy(1) + "\n" +
convertToInteger64(rightSide, context).indentBy(1) + "\n)";
else if (typeOfTheCurrentNode == "Decimal32")
assembly += "(f32.store\n" + | {
"domain": "codereview.stackexchange",
"id": 43431,
"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++, c++11, compiler, webassembly, aec",
"url": null
} |
c++, c++11, compiler, webassembly, aec
else if (typeOfTheCurrentNode == "Decimal32")
assembly += "(f32.store\n" +
children[0].compileAPointer(context).indentBy(1) + "\n" +
convertToDecimal32(rightSide, context).indentBy(1) + "\n)";
else if (typeOfTheCurrentNode == "Decimal64")
assembly += "(f64.store\n" +
children[0].compileAPointer(context).indentBy(1) + "\n" +
convertToDecimal64(rightSide, context).indentBy(1) + "\n)";
else {
std::cerr << "Line " << lineNumber << ", Column " << columnNumber
<< ", Internal compiler error: The compiler got into a "
"forbidden state while compiling the token \""
<< text << "\", aborting the compilation!" << std::endl;
exit(1);
}
} else if (text == "If") {
if (children.size() < 2) {
std::cerr
<< "Line " << lineNumber << ", Column " << columnNumber
<< ", Compiler error: Corrupt AST, the \"If\" node has less than 2 "
"child nodes. Aborting the compilation (or else we will segfault)!"
<< std::endl;
exit(1);
}
if (children[1].text != "Then") {
std::cerr << "Line " << lineNumber << ", Column " << columnNumber
<< ", Compiler error: Corrupt AST, the second child of the "
"\"If\" node isn't named \"Then\". Aborting the compilation "
"(or else we will probably segfault)!"
<< std::endl;
exit(1);
}
if (children.size() >= 3 and children[2].text != "Else") {
std::cerr << "Line " << lineNumber << ", Column " << columnNumber
<< ", Compiler error: Corrupt AST, the third child of the "
"\"If\" node is not named \"Else\", aborting the "
"compilation (or else we will probably segfault)!"
<< std::endl;
exit(1);
}
assembly += "(if\n" + convertToInteger32(children[0], context).indentBy(1) + | {
"domain": "codereview.stackexchange",
"id": 43431,
"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++, c++11, compiler, webassembly, aec",
"url": null
} |
c++, c++11, compiler, webassembly, aec
}
assembly += "(if\n" + convertToInteger32(children[0], context).indentBy(1) +
"\n\t(then\n" + children[1].compile(context).indentBy(2) +
"\n\t)" +
((children.size() == 3)
? "\n\t(else\n" +
children[2].compile(context).indentBy(2) + "\n\t)\n)"
: AssemblyCode("\n)"));
} else if (text == "While") {
if (children.size() < 2 or children[1].text != "Loop") {
std::cerr << "Line " << lineNumber << ", Column " << columnNumber
<< ", Compiler error: Corrupt AST, aborting (or else we will "
"segfault)!"
<< std::endl;
exit(1);
}
assembly += "(block\n\t(loop\n\t\t(br_if 1\n\t\t\t(i32.eqz\n" +
convertToInteger32(children[0], context).indentBy(4) +
"\n\t\t\t)\n\t\t)" + children[1].compile(context).indentBy(2) +
"\n\t\t(br 0)\n\t)\n)";
} else if (std::regex_match(text,
std::regex("(^\\d+$)|(^0x(\\d|[a-f]|[A-F])+$)")))
assembly += "(i64.const " + text + ")";
else if (std::regex_match(text, std::regex("^\\d+\\.\\d*$")))
assembly += "(f64.const " + text + ")";
else if (text == "Return") {
if (currentFunction.returnType != "Nothing") {
if (children.empty()) {
std::cerr << "Line " << lineNumber << ", Column " << columnNumber
<< ", Compiler error: It's not specified what to return from "
"a function that's supposed to return \""
<< currentFunction.returnType
<< "\", aborting the compilation (or else the compiler will "
"segfault)!"
<< std::endl;
exit(1);
}
TreeNode valueToBeReturned = children[0];
if (valueToBeReturned.text == ":=") {
TreeNode tmp =
valueToBeReturned; // The C++ compiler is supposed to forbid | {
"domain": "codereview.stackexchange",
"id": 43431,
"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++, c++11, compiler, webassembly, aec",
"url": null
} |
c++, c++11, compiler, webassembly, aec
TreeNode tmp =
valueToBeReturned; // The C++ compiler is supposed to forbid
// side-effects in the "compile" method, since
// it's declared as "const", but apparently it
// doesn't. It seems to me there is some bug both
// in my code and in GNU C++ compiler (which is
// supposed to warn me about it).
assembly += valueToBeReturned.compile(context) + "\n";
valueToBeReturned = tmp.children[0];
}
assembly +=
";;Setting for returning: " + valueToBeReturned.getLispExpression() +
"\n";
assembly += "(local.set $return_value\n";
assembly +=
convertTo(valueToBeReturned, currentFunction.returnType, context)
.indentBy(1) +
"\n)\n";
}
assembly += "(global.set $stack_pointer (i32.sub (global.get "
"$stack_pointer) (i32.const " +
std::to_string(context.stackSizeOfThisFunction) +
"))) ;;Cleaning up the system stack before returning.\n";
assembly += "(return";
if (currentFunction.returnType == "Nothing")
assembly += ")";
else
assembly += " (local.get $return_value))";
} else if (text == "+") {
std::vector<TreeNode> children =
this->children; // So that compiler doesn't complain about iter_swap
// being called in a constant function.
if (std::regex_search(children[1].getType(context), std::regex("Pointer$")))
std::iter_swap(children.begin(), children.begin() + 1);
std::string firstType = children[0].getType(context);
std::string secondType = children[1].getType(context);
if (std::regex_search(
firstType,
std::regex(
"Pointer$"))) // Multiply the second operand by the numbers of | {
"domain": "codereview.stackexchange",
"id": 43431,
"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++, c++11, compiler, webassembly, aec",
"url": null
} |
c++, c++11, compiler, webassembly, aec
"Pointer$"))) // Multiply the second operand by the numbers of
// bytes the data type that the pointer points to
// takes. That is, be compatible with pointers in
// C and C++, rather than with pointers in
// Assembly (which allows unaligned access).
assembly += "(i32.add\n" +
std::string(children[0].compile(context).indentBy(1)) +
"\n\t(i32.mul (i32.const " +
std::to_string(basicDataTypeSizes.at(firstType.substr(
0, firstType.size() - std::string("Pointer").size()))) +
")\n" + convertToInteger32(children[1], context).indentBy(2) +
"\n\t)\n)";
else
assembly +=
"(" + stringRepresentationOfWebAssemblyType.at(returnType) +
".add\n" +
convertTo(children[0], typeOfTheCurrentNode, context).indentBy(1) +
"\n" +
convertTo(children[1], typeOfTheCurrentNode, context).indentBy(1) +
"\n)";
} else if (text == "-") {
std::string firstType = children[0].getType(context);
std::string secondType = children[1].getType(context);
if (!std::regex_search(firstType, std::regex("Pointer$")) and
std::regex_search(secondType, std::regex("Pointer$"))) {
std::cerr << "Line " << lineNumber << ", Column " << columnNumber
<< ", Compiler error: What exactly does it mean to subtract a "
"pointer from a number? Aborting the compilation!"
<< std::endl;
exit(1);
} else if (std::regex_search(firstType, std::regex("Pointer$")) and
std::regex_search(
secondType,
std::regex("Pointer$"))) // Subtract two pointers as if they
// were two Integer32s. | {
"domain": "codereview.stackexchange",
"id": 43431,
"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++, c++11, compiler, webassembly, aec",
"url": null
} |
c++, c++11, compiler, webassembly, aec
// were two Integer32s.
assembly += "(i32.sub\n" + children[0].compile(context).indentBy(1) +
"\n" + children[1].compile(context).indentBy(1) + "\n)";
else if (std::regex_search(firstType, std::regex("Pointer$")) and
!std::regex_search(secondType, std::regex("Pointer$")))
assembly += "(i32.sub\n" + children[0].compile(context).indentBy(1) +
"\n\t(i32.mul (i32.const " +
std::to_string(basicDataTypeSizes.at(firstType.substr(
0, firstType.size() - std::string("Pointer").size()))) +
")\n" + children[1].compile(context).indentBy(2) +
"\n\t\t)\n\t)\n)";
else
assembly +=
"(" + stringRepresentationOfWebAssemblyType.at(returnType) +
".sub\n" +
convertTo(children[0], typeOfTheCurrentNode, context).indentBy(1) +
"\n" +
convertTo(children[1], typeOfTheCurrentNode, context).indentBy(1) +
"\n)";
} else if (text == "*")
assembly +=
"(" + stringRepresentationOfWebAssemblyType.at(returnType) + ".mul\n" +
convertTo(children[0], typeOfTheCurrentNode, context).indentBy(1) +
"\n" +
convertTo(children[1], typeOfTheCurrentNode, context).indentBy(1) +
"\n)";
else if (text == "/") {
if (returnType == AssemblyCode::AssemblyType::i32 or
returnType == AssemblyCode::AssemblyType::i64)
assembly +=
"(" + stringRepresentationOfWebAssemblyType.at(returnType) +
".div_s\n" +
convertTo(children[0], typeOfTheCurrentNode, context).indentBy(1) +
"\n" +
convertTo(children[1], typeOfTheCurrentNode, context).indentBy(1) +
"\n)";
else
assembly +=
"(" + stringRepresentationOfWebAssemblyType.at(returnType) +
".div\n" +
convertTo(children[0], typeOfTheCurrentNode, context).indentBy(1) + | {
"domain": "codereview.stackexchange",
"id": 43431,
"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++, c++11, compiler, webassembly, aec",
"url": null
} |
c++, c++11, compiler, webassembly, aec
".div\n" +
convertTo(children[0], typeOfTheCurrentNode, context).indentBy(1) +
"\n" +
convertTo(children[1], typeOfTheCurrentNode, context).indentBy(1) +
"\n)";
} else if (text == "<" or text == ">") {
std::string firstType = children[0].getType(context);
std::string secondType = children[1].getType(context);
std::string strongerType;
if (std::regex_search(firstType, std::regex("Pointer$")) and
std::regex_search(secondType, std::regex("Pointer$")))
strongerType =
"Integer32"; // Let's allow people to shoot themselves in the foot by
// comparing pointers of different types.
else
strongerType =
getStrongerType(lineNumber, columnNumber, firstType, secondType);
AssemblyCode::AssemblyType assemblyType =
mappingOfAECTypesToWebAssemblyTypes.at(strongerType);
if (assemblyType == AssemblyCode::AssemblyType::i32 or
assemblyType == AssemblyCode::AssemblyType::i64)
assembly +=
"(" + stringRepresentationOfWebAssemblyType.at(assemblyType) +
(text == "<" ? ".lt_s\n" : ".gt_s\n") +
convertTo(children[0], strongerType, context).indentBy(1) + "\n" +
convertTo(children[1], strongerType, context).indentBy(1) + "\n)";
else
assembly +=
"(" + stringRepresentationOfWebAssemblyType.at(assemblyType) +
(text == "<" ? ".lt\n" : ".gt\n") +
convertTo(children[0], strongerType, context).indentBy(1) + "\n" +
convertTo(children[1], strongerType, context).indentBy(1) + "\n)";
} else if (text == "=") {
std::string firstType = children[0].getType(context);
std::string secondType = children[1].getType(context);
std::string strongerType;
if (std::regex_search(firstType, std::regex("Pointer$")) and
std::regex_search(secondType, std::regex("Pointer$")))
strongerType = "Integer32";
else
strongerType = | {
"domain": "codereview.stackexchange",
"id": 43431,
"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++, c++11, compiler, webassembly, aec",
"url": null
} |
c++, c++11, compiler, webassembly, aec
strongerType = "Integer32";
else
strongerType =
getStrongerType(lineNumber, columnNumber, firstType, secondType);
AssemblyCode::AssemblyType assemblyType =
mappingOfAECTypesToWebAssemblyTypes.at(strongerType);
assembly +=
"(" + stringRepresentationOfWebAssemblyType.at(assemblyType) + ".eq\n" +
convertTo(children[0], strongerType, context).indentBy(1) + "\n" +
convertTo(children[1], strongerType, context).indentBy(1) + "\n)";
} else if (text == "?:")
assembly +=
"(if (result " + stringRepresentationOfWebAssemblyType.at(returnType) +
")\n" + convertToInteger32(children[0], context).indentBy(1) +
"\n\t(then\n" +
convertTo(children[1], typeOfTheCurrentNode, context).indentBy(2) +
"\n\t)\n\t(else\n" +
convertTo(children[2], typeOfTheCurrentNode, context).indentBy(2) +
"\n\t)\n)";
else if (text == "not(")
assembly += "(i32.eqz\n" +
convertToInteger32(children[0], context).indentBy(1) + "\n)";
else if (text == "mod(")
assembly +=
"(" + stringRepresentationOfWebAssemblyType.at(returnType) +
".rem_s\n" +
convertTo(children[0], typeOfTheCurrentNode, context).indentBy(1) +
"\n" +
convertTo(children[1], typeOfTheCurrentNode, context).indentBy(1) +
"\n)";
else if (text == "invertBits(")
assembly += "(i32.xor (i32.const -1)\n" +
convertToInteger32(children[0], context).indentBy(1) + "\n)";
else if (text == "and")
assembly += "(i32.and\n" +
convertToInteger32(children[0], context).indentBy(1) + "\n" +
convertToInteger32(children[1], context).indentBy(1) + "\n)";
else if (text == "or")
assembly += "(i32.or\n" +
convertToInteger32(children[0], context).indentBy(1) + "\n" +
convertToInteger32(children[1], context).indentBy(1) + "\n)";
else if (text.back() == '(' and | {
"domain": "codereview.stackexchange",
"id": 43431,
"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++, c++11, compiler, webassembly, aec",
"url": null
} |
c++, c++11, compiler, webassembly, aec
else if (text.back() == '(' and
basicDataTypeSizes.count(
text.substr(0, text.size() - 1))) // The casting operator.
assembly +=
convertTo(children[0], text.substr(0, text.size() - 1), context);
else if (std::count_if(context.functions.begin(), context.functions.end(),
[=](function someFunction) {
return someFunction.name == text;
})) {
function functionToBeCalled = *find_if(
context.functions.begin(), context.functions.end(),
[=](function someFunction) { return someFunction.name == text; });
assembly += "(call $" + text.substr(0, text.size() - 1) + "\n";
for (unsigned int i = 0; i < children.size(); i++) {
if (i >= functionToBeCalled.argumentTypes.size()) {
std::cerr
<< "Line " << children[i].lineNumber << ", Column "
<< children[i].columnNumber
<< ", Compiler error: Too many arguments passed to the function \""
<< text << "\" (it expects "
<< functionToBeCalled.argumentTypes.size()
<< " arguments). Aborting the compilation (or else the compiler "
"will segfault)!"
<< std::endl;
exit(1);
}
assembly +=
convertTo(children[i], functionToBeCalled.argumentTypes[i], context)
.indentBy(1) +
"\n";
}
for (unsigned int i = children.size();
i < functionToBeCalled.defaultArgumentValues.size(); i++) {
if (!functionToBeCalled.defaultArgumentValues[i])
std::cerr
<< "Line " << lineNumber << ", Column " << columnNumber
<< ", Compiler warning: The argument #" << i + 1 << " (called \""
<< functionToBeCalled.argumentNames[i]
<< "\") of the function named \"" << text
<< "\" isn't being passed to that function, nor does it have some " | {
"domain": "codereview.stackexchange",
"id": 43431,
"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++, c++11, compiler, webassembly, aec",
"url": null
} |
c++, c++11, compiler, webassembly, aec
<< "\" isn't being passed to that function, nor does it have some "
"default value. Your program will very likely crash because of "
"that!"
<< std::endl; // JavaScript doesn't even warn about such errors,
// while C++ refuses to compile a program then. I
// suppose I should take a middle ground here.
assembly +=
convertTo(TreeNode(std::to_string(
functionToBeCalled.defaultArgumentValues[i]),
lineNumber, columnNumber),
functionToBeCalled.argumentTypes[i], context)
.indentBy(1);
}
assembly += ")";
} else if (text == "ValueAt(") {
if (typeOfTheCurrentNode == "Character")
assembly +=
"(i32.load8_s\n" + children[0].compile(context).indentBy(1) + "\n)";
else if (typeOfTheCurrentNode == "Integer16")
assembly +=
"(i32.load16_s\n" + children[0].compile(context).indentBy(1) + "\n)";
else if (typeOfTheCurrentNode == "Integer32" or
std::regex_search(typeOfTheCurrentNode, std::regex("Pointer$")))
assembly +=
"(i32.load\n" + children[0].compile(context).indentBy(1) + "\n)";
else if (typeOfTheCurrentNode == "Integer64")
assembly +=
"(i64.load\n" + children[0].compile(context).indentBy(1) + "\n)";
else if (typeOfTheCurrentNode == "Decimal32")
assembly +=
"(f32.load\n" + children[0].compile(context).indentBy(1) + "\n)";
else if (typeOfTheCurrentNode == "Decimal64")
assembly +=
"(f64.load\n" + children[0].compile(context).indentBy(1) + "\n)";
else {
std::cerr << "Line " << lineNumber << ", Column " << columnNumber
<< ", Internal compiler error: The compiler got into a "
"forbidden state while compiling \"ValueAt\", aborting!"
<< std::endl;
exit(1);
} | {
"domain": "codereview.stackexchange",
"id": 43431,
"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++, c++11, compiler, webassembly, aec",
"url": null
} |
c++, c++11, compiler, webassembly, aec
<< std::endl;
exit(1);
}
} else if (text == "AddressOf(")
return children[0].compileAPointer(context);
else {
std::cerr << "Line " << lineNumber << ", Column " << columnNumber
<< ", Compiler error: No rule to compile the token \"" << text
<< "\", quitting now!" << std::endl;
exit(1);
}
return AssemblyCode(assembly, returnType);
} | {
"domain": "codereview.stackexchange",
"id": 43431,
"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++, c++11, compiler, webassembly, aec",
"url": null
} |
c++, c++11, compiler, webassembly, aec
AssemblyCode TreeNode::compileAPointer(CompilationContext context) const {
if (text == "ValueAt(")
return children[0].compile(context);
if (context.localVariables.count(text) and text.back() != '[')
return AssemblyCode(
"(i32.sub\n\t(global.get $stack_pointer)\n\t(i32.const " +
std::to_string(context.localVariables[text]) + ") ;;" + text +
"\n)",
AssemblyCode::AssemblyType::i32);
if (context.localVariables.count(text) and text.back() == '[') {
if (children.empty()) {
std::cerr << "Line " << lineNumber << ", Column " << columnNumber
<< ", Compiler error: The array \""
<< text.substr(0, text.size() - 1)
<< "\" has no index in the AST. Aborting the compilation, or "
"else the compiler will segfault!"
<< std::endl;
exit(1);
}
return AssemblyCode(
"(i32.add\n\t(i32.sub\n\t\t(global.get "
"$stack_pointer)\n\t\t(i32.const " +
std::to_string(context.localVariables[text]) + ") ;;" + text +
"\n\t)\n\t(i32.mul\n\t\t(i32.const " +
std::to_string(basicDataTypeSizes.at(getType(context))) + ")\n" +
std::string(convertToInteger32(children[0], context).indentBy(2)) +
"\n\t)\n)",
AssemblyCode::AssemblyType::i32);
}
if (context.globalVariables.count(text) and text.back() != '[')
return AssemblyCode("(i32.const " +
std::to_string(context.globalVariables[text]) +
") ;;" + text,
AssemblyCode::AssemblyType::i32);
if (context.globalVariables.count(text) and text.back() == '[') {
if (children.empty()) {
std::cerr << "Line " << lineNumber << ", Column " << columnNumber
<< ", Compiler error: The array \""
<< text.substr(0, text.size() - 1)
<< "\" has no index in the AST. Aborting the compilation, or " | {
"domain": "codereview.stackexchange",
"id": 43431,
"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++, c++11, compiler, webassembly, aec",
"url": null
} |
c++, c++11, compiler, webassembly, aec
<< "\" has no index in the AST. Aborting the compilation, or "
"else the compiler will segfault!"
<< std::endl;
exit(1);
}
return AssemblyCode(
"(i32.add\n\t(i32.const " +
std::to_string(context.globalVariables[text]) + ") ;;" + text +
"\n\t(i32.mul\n\t\t(i32.const " +
std::to_string(basicDataTypeSizes.at(getType(context))) + ")\n" +
std::string(convertToInteger32(children[0], context).indentBy(3)) +
"\n\t)\n)",
AssemblyCode::AssemblyType::i32);
}
std::cerr << "Line " << lineNumber << ", Column " << columnNumber
<< ", Compiler error: Some part of the compiler attempted to get "
"the assembly of the pointer to \""
<< text
<< "\", which makes no sense. This could be an internal compiler "
"error, or there could be something semantically (though not "
"grammatically) very wrong with your program."
<< std::endl;
exit(1);
return AssemblyCode("()");
} | {
"domain": "codereview.stackexchange",
"id": 43431,
"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++, c++11, compiler, webassembly, aec",
"url": null
} |
c++, c++11, compiler, webassembly, aec
std::string getStrongerType(int lineNumber, int columnNumber,
std::string firstType, std::string secondType) {
if (firstType == "Nothing" or secondType == "Nothing") {
std::cerr << "Line " << lineNumber << ", Column " << columnNumber
<< ", Compiler error: Can't add, subtract, multiply or divide "
"with something of the type \"Nothing\"!";
exit(1);
}
if (std::regex_search(firstType, std::regex("Pointer$")) and
!std::regex_search(secondType, std::regex("Pointer$")))
return firstType;
if (std::regex_search(secondType, std::regex("Pointer$")) and
!std::regex_search(firstType, std::regex("Pointer$")))
return secondType;
if (std::regex_search(firstType, std::regex("Pointer$")) and
std::regex_search(secondType, std::regex("Pointer$"))) {
std::cerr
<< "Line " << lineNumber << ", Column " << columnNumber
<< ", Compiler error: Can't add, multiply or divide two pointers!";
}
if (firstType == "Decimal64" or secondType == "Decimal64")
return "Decimal64";
if (firstType == "Decimal32" or secondType == "Decimal32")
return "Decimal32";
if (firstType == "Integer64" or secondType == "Integer64")
return "Integer64";
if (firstType == "Integer32" or secondType == "Integer32")
return "Integer32";
if (firstType == "Integer16" or secondType == "Integer16")
return "Integer16";
return firstType;
} | {
"domain": "codereview.stackexchange",
"id": 43431,
"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++, c++11, compiler, webassembly, aec",
"url": null
} |
c++, c++11, compiler, webassembly, aec
std::string TreeNode::getType(CompilationContext context) const {
if (std::regex_match(text, std::regex("(^\\d+$)|(^0x(\\d|[a-f]|[A-F])+$)")))
return "Integer64";
if (std::regex_match(text, std::regex("^\\d+\\.\\d*$")))
return "Decimal64";
if (text == "AddressOf(") {
if (children.empty()) {
std::cerr << "Line " << lineNumber << ", Column " << columnNumber
<< ", Compiler error: \"AddressOf\" is without the argument!"
<< std::endl;
exit(1);
}
if (children.size() > 1) {
std::cerr
<< "Line " << lineNumber << ", Column " << columnNumber
<< ", Compiler error: Can't take the address of multiple variables!"
<< std::endl;
exit(1);
}
if (children[0].getType(context) == "Nothing") {
std::cerr << "Line " << lineNumber << ", Column " << columnNumber
<< ", Compiler error: \"AddressOf\" has an argument of type "
"\"Nothing\"!"
<< std::endl;
exit(1);
}
return children[0].getType(context) + "Pointer";
}
if (text == "ValueAt(") {
if (children.empty()) {
std::cerr << "Line " << lineNumber << ", Column " << columnNumber
<< ", Compiler error: \"ValueAt\" is without the argument!"
<< std::endl;
exit(1);
}
if (children.size() > 1) {
std::cerr
<< "Line " << lineNumber << ", Column " << columnNumber
<< ", Compiler error: Can't dereference multiple variables at once!"
<< std::endl;
exit(1);
}
if (std::regex_search(children[0].getType(context),
std::regex("Pointer$")) == false) {
std::cerr
<< "Line " << lineNumber << ", Column " << columnNumber
<< ", Compiler error: The argument to \"ValueAt\" is not a pointer!"
<< std::endl;
exit(1);
}
return children[0].getType(context).substr( | {
"domain": "codereview.stackexchange",
"id": 43431,
"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++, c++11, compiler, webassembly, aec",
"url": null
} |
c++, c++11, compiler, webassembly, aec
<< std::endl;
exit(1);
}
return children[0].getType(context).substr(
0, children[0].getType(context).size() - std::string("Pointer").size());
}
if (context.variableTypes.count(text))
return context.variableTypes[text];
if (text[0] == '"') {
std::cerr << "Line " << lineNumber << ", Column " << columnNumber
<< ", Internal compiler error: A pointer to the string " << text
<< " is being attempted to compile before the string itself has "
"been compiled, aborting the compilation!"
<< std::endl;
exit(1);
}
if (text == "and" or text == "or" or text == "<" or text == ">" or
text == "=" or text == "not(" or text == "invertBits(") {
if (children.empty()) {
std::cerr << "Line " << lineNumber << ", Column " << columnNumber
<< ", Compiler error: The operator \"" << text
<< "\" has no operands. Aborting the compilation (or else we "
"will segfault)!"
<< std::endl;
exit(1);
}
if (children.size() < 2 and text != "not(" and text != "invertBits(") {
std::cerr << "Line " << lineNumber << ", Column " << columnNumber
<< ", Compiler error: The binary operator \"" << text
<< "\" has less than two operands. Aborting the compilation "
"(or else we will segfault)!"
<< std::endl;
exit(1);
}
return "Integer32"; // Because "if" and "br_if" in WebAssembly expect a
// "i32", so let's adapt to that.
}
if (text == "mod(") {
if (children.size() != 2) {
std::cerr << "Line " << lineNumber << ", Column " << columnNumber
<< ", Compiler error: \"mod(\" operator requires two integer "
"arguments!"
<< std::endl;
exit(1);
}
if (std::regex_search(children[0].getType(context), | {
"domain": "codereview.stackexchange",
"id": 43431,
"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++, c++11, compiler, webassembly, aec",
"url": null
} |
c++, c++11, compiler, webassembly, aec
exit(1);
}
if (std::regex_search(children[0].getType(context),
std::regex("^Decimal")) or
std::regex_search(children[1].getType(context),
std::regex("^Decimal"))) {
std::cerr << "Line " << lineNumber << ", Column " << columnNumber
<< ", Compiler error: Unfortunately, WebAssembly (unlike x86 "
"assembly) doesn't support computing remaining of division "
"of decimal numbers, so we can't support that either "
"outside of compile-time constants."
<< std::endl;
exit(1);
}
return getStrongerType(lineNumber, columnNumber,
children[0].getType(context),
children[1].getType(context));
}
if (text == "If" or text == "Then" or text == "Else" or text == "While" or
text == "Loop" or text == "Does" or
text == "Return") // Or else the compiler will claim those
// tokens are undeclared variables.
return "Nothing";
if (std::regex_match(text, std::regex("^(_|[a-z]|[A-Z])\\w*\\[?"))) {
std::cerr << "Line " << lineNumber << ", Column " << columnNumber
<< ", Compiler error: The variable name \"" << text
<< "\" is not declared!" << std::endl;
exit(1);
}
if (text == "+" or text == "*" or text == "/") {
if (children.size() != 2) {
std::cerr << "Line " << lineNumber << ", Column " << columnNumber
<< ", Compiler error: The binary operator \"" << text
<< "\" doesn't have exactly two operands. Aborting the "
"compilation (or else we will segfault)!"
<< std::endl;
exit(1);
}
return getStrongerType(lineNumber, columnNumber,
children[0].getType(context),
children[1].getType(context));
}
if (text == "-") { | {
"domain": "codereview.stackexchange",
"id": 43431,
"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++, c++11, compiler, webassembly, aec",
"url": null
} |
c++, c++11, compiler, webassembly, aec
children[1].getType(context));
}
if (text == "-") {
if (children.size() != 2) {
std::cerr << "Line " << lineNumber << ", Column " << columnNumber
<< ", Compiler error: The binary operator \"" << text
<< "\" doesn't have exactly two operands. Aborting the "
"compilation (or else we will segfault)!"
<< std::endl;
exit(1);
}
if (std::regex_search(children[0].getType(context),
std::regex("Pointer$")) and
std::regex_search(children[1].getType(context), std::regex("Pointer$")))
return "Integer32"; // Difference between pointers is an integer of the
// same size as the pointers (32-bit).
return getStrongerType(lineNumber, columnNumber,
children[0].getType(context),
children[1].getType(context));
}
if (text == ":=") {
if (children.size() < 2) {
std::cerr << "Line " << lineNumber << ", Column " << columnNumber
<< ", Compiler error: The assignment operator \":=\" has less "
"than two operands. Aborting the compilation, or else the "
"compiler will segfault."
<< std::endl;
exit(1);
}
if (children[1].getType(context) == "Nothing") {
std::cerr << "Line " << lineNumber << ", Column " << columnNumber
<< ", Compiler error: Attempting to assign something of the "
"type \"Nothing\" to a variable. Aborting the compilation!"
<< std::endl;
}
return children[0].getType(context);
}
auto potentialFunction =
std::find_if(context.functions.begin(), context.functions.end(),
[=](function fn) { return fn.name == text; });
if (potentialFunction != context.functions.end())
return potentialFunction->returnType;
if (text.back() == '(' and | {
"domain": "codereview.stackexchange",
"id": 43431,
"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++, c++11, compiler, webassembly, aec",
"url": null
} |
c++, c++11, compiler, webassembly, aec
return potentialFunction->returnType;
if (text.back() == '(' and
basicDataTypeSizes.count(text.substr(0, text.size() - 1))) // Casting
return text.substr(0, text.size() - 1);
if (text.back() == '(') {
std::cerr << "Line " << lineNumber << ", Column " << columnNumber
<< ", Compiler error: Function \"" << text
<< "\" is not declared!" << std::endl;
exit(1);
}
if (text == "?:")
return getStrongerType(lineNumber, columnNumber,
children[1].getType(context),
children[2].getType(context));
return "Nothing";
} | {
"domain": "codereview.stackexchange",
"id": 43431,
"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++, c++11, compiler, webassembly, aec",
"url": null
} |
c++, c++11, compiler, webassembly, aec
The rest of the code is available on my GitHub profile, it's about 4'000 lines long, and I don't think most of it is relevant here.
Answer: How to create an alias for an enum
I see you are declaring 5 constants, like i32, to avoid having to write out a whole enum name, like AssemblyCode::AssemblyType::i32. In C++20, you can make all enum value names directly accessible in a given scope by writing using enum AssemblyCode::AssemblyType. However, if you are stuck with C++11, then the next best thing is still use using, but then to just declare a short alias for the enum type:
using AT = AssemblyCode::AssemblyType;
And then you can use it like so:
if (originalCode.assemblyType == AT::null) {
...
}
Prefer switch when dealing with enums
Instead of having multiple if-statements when checking the value of an enum type variable, prefer using switch. Apart from resulting in slightly more concise code, the advantage is that the compiler will then check if you covered all the possible values of that enum, and if not it will print a warning. This makes it easy to catch mistakes. So:
switch (originalCode.assemblyType) {
case AT::null:
...;
break;
case AT::i32:
return originalCode;
case AT::i64:
...
case AT::f32:
...
case AT::f64:
...
}; | {
"domain": "codereview.stackexchange",
"id": 43431,
"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++, c++11, compiler, webassembly, aec",
"url": null
} |
c++, c++11, compiler, webassembly, aec
How to handle impossible enum values
Technically, a variable of an enum class type should never have a value that's not one of those listed in the declaration of that enum class type. Some compilers will even assume that it can never happen (Clang), but others (GCC) will require you to write some code after the switch, else they will warn you that there is a possibility to reach the end of the non-void function without a proper return.
Instead of calling exit(-1) though, call abort(). -1 is not even a proper exit code, EXIT_FAILURE is (and it's usually positive 1). But exit() will also call a normal exit from the program, whereas abort() has the benefit of doing an abnormal exit, which can be used to trigger a core dump, or if it's already running inside a debugger, it tells the debugger that a bug happened right there where it was called.
There is no need to call return after a function like exit() or abort(), as the compiler knows that those functions will never return.
Don't use 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 not necessary and will only hurt performance. Note that std::cerr is already unbuffered, so there is no need to flush anything when writing to it.
Possibilities to avoid repeating type names
If you have a function that has a well-defined return type, then in the return statement you don't have to repeat that type; the compiler already knows what it is you have to return. So instead of:
return AssemblyCode("()");
You can just write:
return "()";
And in case you needed to pass multiple arguments to the constructor of AssemblyCode, you can use brace notation:
return {"i32.wrap_i64\n" + std::string(originalCode.indentBy(1)) + "\n)", AT::i32}; | {
"domain": "codereview.stackexchange",
"id": 43431,
"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++, c++11, compiler, webassembly, aec",
"url": null
} |
c++, c++11, compiler, webassembly, aec
Create a user defined literal for AssemblyCode
Since your assembly code is strings, consider adding a user defined literal for AssemblyCode. For example:
AssemblyCode operator"" _asm(const char *code) {
return code;
}
This way you can write:
return {"i32.wrap_i64\n"_asm + originalCode.indentBy(1) + "\n)", AT::i32};
Avoid stringly typed code
Your program already deals a lot with strings, but avoid using them for things where there is a more appropriate type. Consider the parameter type of convertTo(). It can only have a few possible values. Create an enum class for it, just like you did for AssemblyType. This makes the code more type safe, allows you to use switch which has benefits as mentioned above, and avoids your CPU having to do lots of string comparisons at run time.
Avoid regular expressions
“Some people, when confronted with a problem, think "I know, I'll use regular expressions." Now they have two problems.” Jamie Zawinski
Regular expressions can be very powerful, but there are many string parsing problems where they are not the right tool. In particular, it's easy to make mistakes, and they can actually have bad performance. If you want to check if a string ends with some text, then in C++20 you would use ends_with():
if (... or type.ends_with("Pointer")) | {
"domain": "codereview.stackexchange",
"id": 43431,
"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++, c++11, compiler, webassembly, aec",
"url": null
} |
c++, c++11, compiler, webassembly, aec
If you need to support earlier versions of C++, it is quite easy to implement ends_with() yourself without needing regular expressions. Or if you would use an enum class for type, you wouldn't need to deal with strings to begin with.
There are other regular expressions you are using, like the ones for checking if something is a literal integer or floating point value. However, I can already see they are wrong; they don't allow negative values and they don't allow scientific notation. Doing this properly quickly results in huge regular expressions, but there is a much simpler solution: use std::stoi() and std::stof() (or if you can use C++17, std::from_chars() is preferred). These functions try to convert a string to int or float, and you can check whether they succeeded.
Create more helper functions
There is quite a lot of code duplication that can be avoided by writing more helper functions. You repeated the code to check if something is a pointer by writing out the whole std::regex() call. This is a lot of typing, is hard to read, and if you ever change something in how you represent pointer types, you now have to change a lot of code. Consider writing something like:
bool is_pointer(const char *type) {
...
}
Note that if you move from a stringly typed type to an enum class, having such a helper function would make that transitions a lot easier.
You could also create a function (or macro if you want to print line and function numbers and can't use std::source_location yet) for internal compiler errors, so you could write:
if (value != valid) {
ICE("The function foobar() was called with an invalid value");
}
And if you see that ICE() is always called like that within an if-statement, you could make an assert()-like function:
compiler_assert(value == valid, "The function foobar() was called with an invalid value"); | {
"domain": "codereview.stackexchange",
"id": 43431,
"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++, c++11, compiler, webassembly, aec",
"url": null
} |
python, numpy
Title: Numpy way of selecting indices of 2D numpy array if a condition met
Question: I have a snippet of code to get indices of a 2D numpy array if the maximum value of that raw is greater than a number.
index = []
for i in range(np.shape(soft_p)[0]):
if soft_p[i].max() > 0.4:
index.append(i)
I was wondering if there's a better way to do it using numpy conditions and functions
Answer: You should find the maximum value according to the first axis (row), and then select the row number greater than 0.4:
max_vals = soft_p.max(1)
index = (max_vals > 0.4).nonzero()[0]
Example:
>>> ar = np.random.rand(5, 5)
>>> ar
array([[0.46621005, 0.51573283, 0.53287116, 0.82355335, 0.95846324],
[0.76834591, 0.63605015, 0.32834301, 0.15062014, 0.69269814],
[0.94558026, 0.11578385, 0.43292249, 0.08532496, 0.16731557],
[0.14552061, 0.87651804, 0.25594289, 0.22702692, 0.23300077],
[0.19116528, 0.54291561, 0.49146977, 0.98988884, 0.43468107]])
>>> max_vals = ar.max(1)
>>> max_vals
array([0.95846324, 0.76834591, 0.94558026, 0.87651804, 0.98988884])
>>> (max_vals > 0.9).nonzero()[0]
array([0, 2, 4], dtype=int64) | {
"domain": "codereview.stackexchange",
"id": 43432,
"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, numpy",
"url": null
} |
javascript, node.js, io, async-await
Title: Process a binary file by chunk using a read stream in nodejs
Question: I want to process a file chunk by chunk to prevent memory exhaustion. I need to consume the file using a read stream. When trying it, this implementation seems to work fine.
I am asking your expert eyes:
have I overlooked anything or did I forget some case?
have I made a mistake somewhere and it's going to bite me in prod?
could this be improved?
The main code:
async function processFileByChunk(filePath) {
try {
const videoStream = fs.createReadStream(filePath);
const stats = fs.statSync(filePath);
await new Promise((resolve, reject) => {
let bytesRead = 0;
let countCurrentUploads = 0;
videoStream.on("readable", async function () {
while (true) {
await wait(() => countCurrentUploads <= 0, 1000);
const chunk = videoStream.read(16 * 1024 * 1024);
if (!chunk || !chunk.length) {
break;
}
bytesRead += chunk.length;
console.log("bytesRead", bytesRead);
countCurrentUploads++;
await processChunk(chunk);
countCurrentUploads--;
}
if (bytesRead >= stats.size) {
resolve();
}
});
videoStream.on("error", function (error) {
reject(error);
});
});
} catch (error) {
console.log(error);
}
}
Other functions:
async function processChunk(chunk) {
console.log("process chunk...");
await delay(2000);
console.log("process chunk... done");
}
async function wait(fn, ms) {
while (!fn()) {
await delay(ms);
}
}
function delay(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
Applied on a ~63MB file, it prints out:
bytesRead 16777216
process chunk...
process chunk... done
bytesRead 33554432
process chunk...
process chunk... done
bytesRead 50331648
process chunk...
process chunk... done
bytesRead 63598316
process chunk...
process chunk... done | {
"domain": "codereview.stackexchange",
"id": 43433,
"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": "javascript, node.js, io, async-await",
"url": null
} |
javascript, node.js, io, async-await
Answer: ️ Performance Matters, only when it matters
I want to process a file chunk by chunk to prevent memory exhaustion.
Are you sure this is necessary? I would say it's fair to assume almost all computers have (far) more than 1 GB of RAM these days, and most text files never exceed such ridiculous sizes. Don't optimise until you actually need to.
➿ Loops to the rescue
Assuming you really do need to process a file chunk by chunk, you could do so far more easily, using the async iterator that is built into a ReadableStream:
async function processFile(path, handler) {
const stream = fs.createReadStream(path);
for await (const chunk of stream) {
await handle(chunk);
}
}
function delay(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
async function handle(chunk) {
console.log("process chunk...");
await delay(2000);
console.log("process chunk... done");
}
processFile("path/to/file", handleChunk);
That's it really.
async/await vs callbacks
Have I overlooked anything or did I forget some case?
One of the problems you have encountered is the tricky situation of using async/await inside a callback to ReadableStream.on.
When you're subscribing to the data event using stream.on("data", ...), you provide a function to be called for every chunk of that stream. The problem here is that the stream doesn't wait for that callback to complete before reading another chunk.
Using async/await in this callback is only "pausing" the callback, not the stream.
If I understand correctly, you've avoided this with some really weird loops and counters — almost as if you're trying to implement your own scheduling implementation, which is of course completely redundant because Node has its own scheduler.
If you have a look at the documentation for the async iterator for Streams, you can see that using the Symbol.AsyncIterator protocol on a Stream will take care of reading, closing and error handling of a Stream. | {
"domain": "codereview.stackexchange",
"id": 43433,
"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": "javascript, node.js, io, async-await",
"url": null
} |
javascript, node.js, io, async-await
Because you're working in a async control context, any errors will reject the promise returned by the function, so there's no need to wrap it in a try/catch.
Because you're working in a async control context, you can await other async functions inside this body, and the iterator will not continue until the context is "resumed", so the NodeJS scheduler can do its thing for you.
Alternatively, if you don't await the handler, the stream will not pause, which could be desired instead.
The Symbol.AsyncIterator implementation of NodeJS Streams take care of reading the stream and read error handling. No need to define any listeners yourself.
Conclusion
In short, here are my tips to you:
RTFM (excuse the expletive ). You can find out a lot of useful info by browsing the docs a bit before you write some code, although I do commend your creative solution to the scheduling problem.
When using async/await, make sure you're using it everywhere. Only an async context can be paused with await. Promises have been used to circumvent callback hell in (almost) every NodeJS API by now; if you see a method that asks you to provide a callback, there's probably a better method that works with a Promise instead, which you can await. | {
"domain": "codereview.stackexchange",
"id": 43433,
"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": "javascript, node.js, io, async-await",
"url": null
} |
python, python-3.x, strings
Title: Add 'ing' or 'ly' suffix to a string
Question: I have been practising Python Practice questions and came across this question:
Write a Python program to add 'ing' at the end of a given string
(length should be at least 3).
If the given string already ends with 'ing' then add 'ly' instead.
If the string length of the given string is less than 3, leave it
unchanged. Sample String : 'abc'
Expected Result : 'abcing'
Sample String : 'string'
Expected Result : 'stringly'
Here's my code:
string = input()
if len(string) < 3:
print(string)
elif string[-3:] == 'ing':
print(string + 'ly')
else:
print(string + 'ing')
However, something about this code seems wrong: though it works, fine I feel it smells bad. I can't pinpoint why. | {
"domain": "codereview.stackexchange",
"id": 43434,
"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, strings",
"url": null
} |
python, python-3.x, strings
Answer: 1. Python strings have an .endswith() method. Use it.
While string[-3:] == 'ing' isn't particularly hard to read, string.endswith('ing') is even clearer.
Potentially, depending on how it's implemented, .endswith() could even be slightly more efficient, since it doesn't have to copy the last three characters of the string. However, always keep Knuth's maxim in mind. The entire operation of testing whether a string ends with "ing" is so trivial that any performance difference between different ways of doing it will surely be negligible compared to e.g. the time consumed by reading and printing the string. Thus, given two ways to do it, you should choose the most readable and idiomatic way even if it wasn't the most efficient.
2. Separate I/O from computation.
It's common for beginning programmers to litter their code with input() and print() calls in the middle of program logic, simply because those are the only ways of receiving and returning data they're familiar with. But in practice, that's almost always a mistake.(*)
Your main task is to modify a string. Reading the string from standard input and printing the result to standard output are merely auxiliary tasks to that (and may or may not even be strictly necessary, unless the exercise explicitly specifies that particular method of input and output). You shouldn't unnecessarily intermix those auxiliary tasks into your solution for the main task.
The simplest way to do that would be to just pull the print() calls out of the program logic, e.g. like this:
string = input()
if string.endswith('ing'):
string += 'ly'
elif len(string) >= 3:
string += 'ing'
print(string) | {
"domain": "codereview.stackexchange",
"id": 43434,
"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, strings",
"url": null
} |
python, python-3.x, strings
if string.endswith('ing'):
string += 'ly'
elif len(string) >= 3:
string += 'ing'
print(string)
This is OK if you expect to only ever use this code for processing data read from one file (or pipe) and written to another. You're still doing the input, processing and output in one linear program, but at least the processing logic is now grouped together in a single block of code that you can extract from the script if you want to reuse it, and the I/O code is clearly separated from it, making it easy to change to another I/O method later if you need to.
Alternatively, you could go a step further and wrap the program logic in a function that takes the input string as a parameter and returns the output. And, while you're at it, you can use the if __name__ == '__main__' idiom to make your I/O code only run when your script is invoked directly:
def inglify(string):
if len(string) < 3:
return string
elif string.endswith('ing'):
return string + 'ly'
else:
return string + 'ing'
if __name__ == '__main__':
string = input()
print(inglify(string))
The advantage is that now your script file is also usable as a module that you can import into another script to gain access to any functions defined in it without executing the I/O part of the code.
*) So, when is it appropriate to include print() calls directly in your code, then? Off the top of my head, I can think of three or four cases (with some partial overlap between them):
When I/O is the main purpose of your code, with everything not directly relevant to this purpose already split off into reusable functions. For example, print(inglify(input())) really does nothing but read data, call a function and print the result. Obviously, using print() there is not only appropriate but necessary. | {
"domain": "codereview.stackexchange",
"id": 43434,
"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, strings",
"url": null
} |
python, python-3.x, strings
When your code is interactive, i.e. when it prints something to the console, expects the user to reply, then prints something in response, etc. The REPL that you can start by running python with no script file argument is one example of such a program. In this case the input and output are intrinsically part of your program logic and cannot be easily separated from it. That said, you should still try to keep such interactive loops as simple as possible, and split off any parts of your code that don't directly involve interactive I/O into reusable functions or modules.
When you're doing debug printing, i.e. when what you're printing isn't the actual intended output of your program, but merely some metadata to help in tracing its execution. This can sometimes be a very useful ways to find out what your code is actually doing, and it's the one case where putting print() or other I/O calls even deep inside your program logic can be acceptable. Of course, if you're leaving such debug logging in your finished code, you should probably only enable it if requested by the user. (For example, many command-line tools will accept a --verbose or --debug switch to turn on such extra output.) Often it's best to use an actual logging framework designed for this purpose. | {
"domain": "codereview.stackexchange",
"id": 43434,
"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, strings",
"url": null
} |
python, python-3.x, strings
I would also personally include an exception for "simple data processing" scripts that involve nothing more than reading in some data, processing it and printing it out, much like the first rewritten version of your code that I suggested above.
Such scripts are characterized by the fact that they only perform a single task, that this task involves reading, processing and writing data, and that their control flow is simple and mostly linear. That is, such a script might consist of a loop that reads the input, another loop or two to process it, and then a loop to print out the results. Sometimes it might even have a loop that e.g. reads a line of input, processes it, and prints out the result before reading the next line, etc. But what it definitely shouldn't have is print (or, worse yet, input) calls buried deep within conditional code, or in functions whose main purpose isn't obviously to perform I/O.
While such scripts can be refactored to separate the I/O code from the rest of the data processing, often that can actually make the code harder to read, since it breaks up the simple step-by-step program flow into a more complex sequence of function calls. Basically, if your code is naturally structured like a cooking recipe, with nothing but simple sequential steps, it's sometimes better to just keep it like that and not complicate it by needless refactoring. | {
"domain": "codereview.stackexchange",
"id": 43434,
"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, strings",
"url": null
} |
python, python-3.x, http
Title: Python script that pulls in and display a random xkcd comic
Question: This script is supposed to download query xkcd json interface, find the total number of comics till date, pick a random number in that range, use the xkcd json interface again to find the comic image url, download it into /tmp filesystem, and use feh image viewer to display the image.
I'd appreciate it if you could tell me if this program is neatly written
#!/usr/bin/env python
import urllib.request
import json
import random
import subprocess
class Xkcd :
def __init__(self) :
self.url = "https://xkcd.com/info.0.json"
self.num_comics = None
self.random_comic_num = None
self.comic_json_url = None
self.image_url = None
def get_num_comics(self) :
html_data = urllib.request.urlopen(self.url)
json_data = json.loads(html_data.read())
self.num_comics = json_data['num']
def download_image(self) :
urllib.request.urlretrieve(self.image_url, "/tmp/image")
def get_random_comic(self) :
self.get_num_comics()
self.random_comic_num = random.randint(1, self.num_comics)
self.comic_json_url = "https://xkcd.com/%s/info.0.json" %(self.random_comic_num)
html_data = urllib.request.urlopen(self.comic_json_url)
json_data = json.loads(html_data.read())
self.image_url = json_data['img']
self.download_image()
def show_image(self) :
subprocess.Popen(["feh", "/tmp/image"])
exit()
if __name__ == "__main__" :
ob = Xkcd()
ob.get_random_comic()
ob.show_image() | {
"domain": "codereview.stackexchange",
"id": 43435,
"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, http",
"url": null
} |
python, python-3.x, http
Answer: Xkcd as a class isn't particularly well-named: you're actually representing a "site", "session" or "downloader", distinct from an individual comic.
Its members are problematic. url never changes so should be moved to a static, but also url in its current form is only ever used once so instead you should store the base URL as a static and append paths to it as necessary.
Xkcd, upon construction, is broken and not ready to use. Exterior code that assumes that num_comics is valid will fail due to the None. An attempt to call get_random_comic() requires that it calls get_num_comics, and this will occur every single time that a comic is fetched. This should be cached instead.
random_comic_num, comic_json_url and image_url have no business existing as persistent members on the class; they should be passed around on a case-by-case basis as parameters and return values.
Avoid using urllib when requests does a better job.
Hard-coding /tmp/image is problematic: you're guaranteed to steamroll anything else at that path, including files from both your program and other programs that use that path. Also, some operating systems (a) cannot use that directory for temporary files, and (b) cannot infer from the extension-less path what mimetype the image is. The solution is to use the built-in temporary file support in Python and pass it a sane suffix.
It's relatively easy to capture the known properties of a returned JSON comic payload in a well-typed, well-defined class based off of a NamedTuple or dataclass, so do this.
It's also relatively easy to make get_random_comic more generally useful by making the "random" behaviour optional and accepting an optional index number. If that index number is None then the method can fill in a random index. Among other advantages, if the comic count logic is made lazy (which you should do anyway), then it will never be called so long as callers only want pre-defined indices. | {
"domain": "codereview.stackexchange",
"id": 43435,
"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, http",
"url": null
} |
python, python-3.x, http
Don't hard-code feh. If it isn't the default image viewer on your OS, that's a user problem and not a program problem. Instead make an attempt at using the default OS image viewer, though Python doesn't make this entirely easy to be portable: use startfile on Windows, xdg-open on Linux, open on Mac, etc. The latter two should be using subprocess.check_call with shell=False.
Your downloader/site class should have a requests.Session and it should be closeable via context management.
An algorithmic note: your random algorithm is reasonable but is not what the site itself uses. The site offers a link https://c.xkcd.com/random/comic/ that takes your normal GET request and 302-redirects you to a random comic. Given that it requires the same number of network operations and gives you HTML rather than JSON, I think your count-and-choose method is still preferable.
Suggested
#!/usr/bin/env python3
from functools import cache
from mimetypes import guess_type
from os import startfile
from os.path import basename
from random import randint
from shutil import copyfileobj
from subprocess import check_call
from sys import platform
from tempfile import NamedTemporaryFile
from typing import BinaryIO, NamedTuple | {
"domain": "codereview.stackexchange",
"id": 43435,
"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, http",
"url": null
} |
python, python-3.x, http
from requests import Session
class XkcdComic(NamedTuple):
year: str
month: str
day: str
num: int
title: str
safe_title: str
link: str
img: str
news: str
transcript: str
alt: str
@property
def image_name(self) -> str:
return basename(self.img)
@property
def image_mimetype(self) -> str:
# typically image/png or image/jpeg
mimetype, encoding = guess_type(self.img)
return mimetype
class XkcdSite:
BASE_URL = 'https://xkcd.com/'
def __init__(self) -> None:
self.session = Session()
def get_count() -> int:
return self.get_current_comic().num
self.get_num_comics = cache(get_count)
def __enter__(self) -> 'XkcdSite':
return self
def __exit__(self, exc_type, exc_val, exc_tb) -> None:
self.session.close()
def get_image(self, comic: XkcdComic, file: BinaryIO) -> None:
with self.session.get(
url=comic.img,
headers={'Accept': comic.image_mimetype},
stream=True,
) as response:
response.raise_for_status()
copyfileobj(response.raw, file)
def get_comic(self, index: int) -> XkcdComic:
return self._fetch_comic(prefix=f'{index}/')
def get_current_comic(self) -> XkcdComic:
return self._fetch_comic(prefix='')
def get_random_comic(self) -> XkcdComic:
return self.get_comic(index=randint(1, self.get_num_comics()))
def _fetch_comic(self, prefix: str) -> XkcdComic:
with self.session.get(
url=f'{self.BASE_URL}{prefix}info.0.json',
headers={'Accept': 'application/json'},
) as response:
response.raise_for_status()
return XkcdComic(**response.json()) | {
"domain": "codereview.stackexchange",
"id": 43435,
"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, http",
"url": null
} |
python, python-3.x, http
def show_image(self, comic: XkcdComic) -> None:
with NamedTemporaryFile(
# Needed for Windows since startfile() cannot block
delete=False,
# Needed for Windows since it cannot guess mimetypes based on content alone
suffix='_' + comic.image_name,
) as file:
self.get_image(comic, file)
run_file(file.name)
def run_file(path: str) -> None:
if platform == 'win32': # Windows
startfile(path)
else: # assume Linux-like
check_call(('/usr/bin/xdg-open', path), shell=False)
# This does not cover darwin/mac ('open'), etc.
def main() -> None:
with XkcdSite() as site:
comic = site.get_random_comic()
site.show_image(comic)
if __name__ == '__main__':
main() | {
"domain": "codereview.stackexchange",
"id": 43435,
"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, http",
"url": null
} |
c++, c++11, lookup
Title: Any bettter way to achieve this lookup table?
Question: What I need:
I need a lookup table. Once the keywords are all found, then the value of the std::unordered_map is returned.And I don't care about the sequence of the strings in the std::vector.
I think std::unordered_map<std::vector<std::string>, int> could achieve this goal. Any better method to achieve this goal? Or any improvement for this code snippet?
#include <string>
#include <unordered_map>
#include <vector>
#include <iostream>
class Hash
{
public:
std::size_t operator()(const std::vector<std::string>& vec) const
{
std::hash<std::string> hasher;
std::size_t hash_value{};
for(auto itr = vec.begin(); itr!=vec.end(); itr++)
{
hash_value ^= (hasher(*itr)); //Why `hash_value ^= ((hasher(*itr))<<1);` does not influence the output of mp.find(to_search)
}
return hash_value;
}
};
class Equal
{
public:
bool operator()(const std::vector<std::string>& vec1, const std::vector<std::string>& vec2) const
{
bool ret = true;
if(vec1.size() != vec2.size())
{
ret = false;
}
else
{
for(auto itr_outer = vec1.begin(); itr_outer!=vec1.end(); itr_outer++)
{
bool found = false;
for(auto itr_inner = vec1.begin(); itr_inner!=vec2.end(); itr_inner++)
{
if(*itr_outer == *itr_inner)
{
found = true;
break;
}
}
if(!found)
{
ret = false;
break;
}
}
}
return ret;
}
}; | {
"domain": "codereview.stackexchange",
"id": 43436,
"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++, c++11, lookup",
"url": null
} |
c++, c++11, lookup
return ret;
}
};
int main()
{
const std::unordered_map<std::vector<std::string>, int, Hash, Equal> mp = {
{{"hello word"}, 1},
{{"thanks a lot", "I need some help"}, 2},
{{"how to make it better"}, 3},
};
std::vector<std::string> to_search = {"I need some help", "thanks a lot"};
auto itr = mp.find(to_search);
if(itr!=mp.end())
{
std::cout <<"found:" << itr->second << std::endl;
}
else
{
std::cout << "not found" << std::endl;
}
}
```
Answer: It depends what you really need. As @Aganju pointed out that looking up a hash is much faster than looping through strings and comparing.
But for your case, you seems to find out whether a specific sentence contains all the keywords or not, in this case hash does not work indeed. Help that helps. | {
"domain": "codereview.stackexchange",
"id": 43436,
"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++, c++11, lookup",
"url": null
} |
python, design-patterns, web-scraping, pandas, beautifulsoup
Title: Design Pattern: Builder - BeautifulSoup directory navigation and scraping
Question: I wrote a class on top of BeautifulSoup using the builder design pattern that allows for the navigation of the necp data directory.
There are a couple navigation methods navto which just builds upon the base url to return a new instance, and inav useful when the urls are likely to change due to temporal updates.
import time
import re
import pandas as pd
import requests
from bs4 import BeautifulSoup
# for context TSRAGR is TAF code for a thunderstorm with hail
class TSragr:
def __init__(self, base_url: str = None) -> None:
self._baseurl = base_url
r = requests.get(base_url)
r.raise_for_status()
soup = BeautifulSoup(r.content, "lxml").find_all("a")
if soup[0].text == "Parent Directory":
soup = soup[1:]
self._soup = pd.Series([x.text for x in soup])
def __repr__(self) -> str:
return f"{self.url}\n"+ self._soup.__repr__()
def __getitem__(self, args) -> "TSragr":
self._soup = self._soup[args]
return self
@property
def url(self) -> str:
url = self._baseurl
if not url.endswith("/"):
url = url+ "/"
return url
def navto(self, *args: str) -> "TSragr":
return TSragr(self.url + "/".join(args))
def navup(self) -> "TSragr":
return TSragr(re.match(r"^(.*[\/])", self.url).group())
def inav(self, index: int) -> "TSragr":
return TSragr(self.url + self._soup[index])
def download(self, save_to="./", wait: float = 10) -> None:
soup = self._soup.copy()
soup.index = self.url + self._soup | {
"domain": "codereview.stackexchange",
"id": 43437,
"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, design-patterns, web-scraping, pandas, beautifulsoup",
"url": null
} |
python, design-patterns, web-scraping, pandas, beautifulsoup
soup = self._soup.copy()
soup.index = self.url + self._soup
for url, filename in soup.items():
print("DOWNLAODING FILE")
local_filename = save_to + filename
with requests.get(url, stream=True) as r:
r.raise_for_status()
with open(local_filename, "wb") as f:
for chunk in r.iter_content(chunk_size=8192):
f.write(chunk)
print("FILE SAVED")
time.sleep(60 * wait) | {
"domain": "codereview.stackexchange",
"id": 43437,
"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, design-patterns, web-scraping, pandas, beautifulsoup",
"url": null
} |
python, design-patterns, web-scraping, pandas, beautifulsoup
usage
>>> from wxlab.scrape import TSragr
>>> ragr = TSragr("https://nomads.ncep.noaa.gov/pub/data")
>>> ragr
https://nomads.ncep.noaa.gov/pub/data/
0 DSRC
1 nccf/
dtype: object
>>> ragr.navto("nccf")
https://nomads.ncep.noaa.gov/pub/data/nccf/
0 charts/
1 com/
2 dcom/
3 nonoperational/
4 pcom/
5 radar/
dtype: object
>>> ragr.navto("nccf","com")
https://nomads.ncep.noaa.gov/pub/data/nccf/com/
0 557ww/
1 amsu_estimation/
2 aqm/
3 arch/
4 blend/
...
61 uvi/
62 wave/
63 wave_nfcens/
64 wfs/
65 wsa_enlil/
Length: 66, dtype: object
>>> ragr.navto("nccf","com","blend")
https://nomads.ncep.noaa.gov/pub/data/nccf/com/blend/
0 prod/
1 v4.0/
dtype: object
>>> ragr.navto("nccf","com","blend","prod")
https://nomads.ncep.noaa.gov/pub/data/nccf/com/blend/prod/
0 blend.20220604/
1 blend.20220605/
dtype: object
>>> ragr.navto("nccf","com","blend","prod").inav(0)
https://nomads.ncep.noaa.gov/pub/data/nccf/com/blend/prod/blend.20220604/
0 00/
1 01/
2 02/
3 03/
4 04/
5 05/
6 06/
7 07/
8 08/
9 09/
10 10/
11 11/
12 12/
13 13/
14 14/
15 15/
16 16/
17 17/
18 18/
19 19/
20 20/
21 21/
22 22/
23 23/
dtype: object
>>> ragr.navto("nccf","com","blend","prod").inav(0).inav(0)
https://nomads.ncep.noaa.gov/pub/data/nccf/com/blend/prod/blend.20220604/00/
0 core/
1 qmd/
2 text/
dtype: object
>>> ragr.navto("nccf","com","blend","prod").inav(0).inav(0).navto("core")
https://nomads.ncep.noaa.gov/pub/data/nccf/com/blend/prod/blend.20220604/00/core/
0 blend.t00z.core.f001.ak.grib2
1 blend.t00z.core.f001.ak.grib2.idx
2 blend.t00z.core.f001.co.grib2
3 blend.t00z.core.f001.co.grib2.idx
4 blend.t00z.core.f001.gu.grib2 | {
"domain": "codereview.stackexchange",
"id": 43437,
"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, design-patterns, web-scraping, pandas, beautifulsoup",
"url": null
} |
python, design-patterns, web-scraping, pandas, beautifulsoup
3 blend.t00z.core.f001.co.grib2.idx
4 blend.t00z.core.f001.gu.grib2
...
1148 blend.t00z.core.f264.oc.grib2
1149 blend.t00z.core.f264.oc.grib2.idx
1150 blend.t00z.core.f264.pr.grib2
1151 blend.t00z.core.f264.pr.grib2.idx
1152 ls-l
Length: 1153, dtype: object
>>> ragr.navto("nccf","com","blend","prod").inav(0).inav(0).navto("core")[0:6:2]
https://nomads.ncep.noaa.gov/pub/data/nccf/com/blend/prod/blend.20220604/00/core/
0 blend.t00z.core.f001.ak.grib2
2 blend.t00z.core.f001.co.grib2
4 blend.t00z.core.f001.gu.grib2
dtype: object
>>> ragr.navto("nccf","com","blend","prod").inav(0).inav(0).navto("core")[0:6:2].download(save_to="/media/external/data/", wait=1)
DOWNLAODING FILE
FILE SAVED
DOWNLAODING FILE
FILE SAVED | {
"domain": "codereview.stackexchange",
"id": 43437,
"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, design-patterns, web-scraping, pandas, beautifulsoup",
"url": null
} |
python, design-patterns, web-scraping, pandas, beautifulsoup
Answer: Fundamentally you're scraping the default directory listing format for Apache, which is the web server used by this NOAA site.
I see no use for Pandas here; I've removed it in my example code.
You should re-think your class. Rather than attempting to be an eager-fetched directory listing, it's better represented as a lazy-fetched directory listing that can be navigable either to child instances of subdirectories or of files, which amount to a different class. I don't think it's all that helpful to write your magic __getitem__ method; if you have an iterable, represent it directly as an iterable from a .children() method.
Use a soup strainer where applicable to narrow your DOM tree search.
Your Parent Directory check can be carried over to the BeautifulSoup DOM search by use of a regular expression.
I see no reason to wait; delete your sleep.
Suggested code
import re
from itertools import islice
from pathlib import Path
from shutil import copyfileobj
from typing import Iterator, Optional
from urllib.parse import urljoin
from requests import Session
from bs4 import BeautifulSoup
from bs4.element import SoupStrainer
class ApacheNode:
"""
This represents a tree node in the Apache directory page for the NOAA NOMADS site;
for more details see https://nomads.ncep.noaa.gov/
It's used to look up TSRAGR data. TSRAGR is Terminal Aerodrome Forecast (TAF) code
for a thunderstorm with hail.
"""
def __init__(self, session: Session, url: str, name: Optional[str] = None) -> None:
self.session = session
self.url = url
if name is None:
name = url.removesuffix('/').rsplit('/', maxsplit=1)[-1]
self.name = name
def __repr__(self) -> str:
return self.url
class ApacheFile(ApacheNode):
def download(self, save_to: Path) -> None:
print(f'Downloading {self.name}...', end=' ')
local_filename = save_to / self.name | {
"domain": "codereview.stackexchange",
"id": 43437,
"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, design-patterns, web-scraping, pandas, beautifulsoup",
"url": null
} |
python, design-patterns, web-scraping, pandas, beautifulsoup
with self.session.get(self.url, stream=True) as response:
response.raise_for_status()
with local_filename.open('wb') as f:
copyfileobj(response.raw, f)
print('saved')
class ApacheDir(ApacheNode):
pre_strainer = SoupStrainer(name='pre')
# Text has at least one character and cannot contain Parent Directory
link_pattern = re.compile(
'(?i)' # ignore case
'^' # string start
'(?:' # non-capturing group
'(?!parent directory)' # negative lookahead: don't match 'parent directory'
'.' # match any one character
')+' # match one or more of the above chars
'$' # string end
)
def __init__(self, session: Session, url: str, name: Optional[str] = None) -> None:
if not url.endswith('/'):
url += '/'
super().__init__(session, url, name)
def children(self) -> Iterator[ApacheNode]:
with self.session.get(self.url) as response:
response.raise_for_status()
soup = BeautifulSoup(markup=response.text, features='lxml', parse_only=self.pre_strainer)
pre = soup.pre
anchors = pre.find_all(name='a', text=self.link_pattern, recursive=False)
for anchor in anchors:
child_name = anchor['href']
child_url = urljoin(self.url, child_name)
size_text = anchor.next_sibling.strip()
if size_text.endswith('-'):
child_type = ApacheDir
else:
child_type = ApacheFile
yield child_type(self.session, child_url, child_name)
def navto(self, *args: str) -> 'ApacheDir':
url = urljoin(self.url, '/'.join(args))
return ApacheDir(self.session, url=url, name=args[-1]) | {
"domain": "codereview.stackexchange",
"id": 43437,
"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, design-patterns, web-scraping, pandas, beautifulsoup",
"url": null
} |
python, design-patterns, web-scraping, pandas, beautifulsoup
def inav(self, index: int) -> 'ApacheNode':
child, = islice(self.children(), index, index+1)
return child
def test() -> None:
with Session() as session:
ragr = ApacheDir(session, url='https://nomads.ncep.noaa.gov/pub/data')
print(ragr)
print(ragr.navto('nccf'))
print(ragr.navto('nccf', 'com'))
print(ragr.navto('nccf', 'com', 'blend'))
ragr = ragr.navto('nccf', 'com', 'blend', 'prod')
print(ragr)
ragr = ragr.inav(0)
print(ragr)
ragr = ragr.inav(0)
print(ragr)
ragr = ragr.navto('core')
print(ragr)
# anything that doesn't end in idx, first three
first_three_files = islice(
(
child for child in ragr.children()
if not child.name.endswith('idx')
), 3
)
save_to = Path('ragr-test') # '/media/external/data/'
save_to.mkdir(exist_ok=True)
for file in first_three_files:
file.download(save_to)
if __name__ == '__main__':
test()
Output
https://nomads.ncep.noaa.gov/pub/data/
https://nomads.ncep.noaa.gov/pub/data/nccf/
https://nomads.ncep.noaa.gov/pub/data/nccf/com/
https://nomads.ncep.noaa.gov/pub/data/nccf/com/blend/
https://nomads.ncep.noaa.gov/pub/data/nccf/com/blend/prod/
https://nomads.ncep.noaa.gov/pub/data/nccf/com/blend/prod/blend.20220605/
https://nomads.ncep.noaa.gov/pub/data/nccf/com/blend/prod/blend.20220605/00/
https://nomads.ncep.noaa.gov/pub/data/nccf/com/blend/prod/blend.20220605/00/core/
Downloading blend.t00z.core.f001.ak.grib2... saved
Downloading blend.t00z.core.f001.co.grib2... saved
Downloading blend.t00z.core.f001.gu.grib2... saved | {
"domain": "codereview.stackexchange",
"id": 43437,
"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, design-patterns, web-scraping, pandas, beautifulsoup",
"url": null
} |
python, performance, python-3.x, game
Title: Playing a game of ConHex in Python
Question: Background
ConHex is game by Michail Antonow where two players try to create a connected chain of cells from one side of the board to the other side. They do this by claiming one empty position each turn. If a player first possesses at least half of the positions of a cell, the cell belongs to that player. Cells can't be conquered/taken once owned. More info on the game on Boardgame Geek and on Little Golem.
Goal
I programmed a class in Python (version 3.9) that provides an api to play a game of ConHex. The code consists of two Python modules: one with the actual class and code and one with constants. For illustration purposes, I added a main which randomly plays a game until one player wins. You may ignore the main() code for the review.
I'm an amateur Python programmer and seek to learn if (and how) to improve this code. I plan to add a GUI, publish the game on GitHub and train an Alpha Zero deep learning network to play ConHex.
Review questions | {
"domain": "codereview.stackexchange",
"id": 43438,
"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, python-3.x, game",
"url": null
} |
python, performance, python-3.x, game
General review: please let me know if there are any points on which I can improve the working of the code and the code readability.
Specifically review the way I'm using the Python logger. Is this a Pythonic and "good" way to use logging (e.g.: logger initialising, storing a logger object in a class, points where I call the logger, etc.)?
I put all constants and general definitions in a separate constants.py package. Is this a common pattern, or would you recommend organising the code in another way?
Optically, the code seems a bit messy. I tried to adhere to PEP8 and the code passes Flake8. Any suggestions to improve code readability?
Would you consider the class sufficiently documented? Any places where documentation (or code comments) should be added or removed?
Algorithmically, I'm not very happy with the game_won() method. Any suggestions to improve approach, performance and code readability? Specifically keeping in mind that this game will be played hundreds of million times by the Alpha Zero deep learning algorithm, any performance gain will be noticeable...
ConHex board with coordinate system
Illustration of the coordinate system used for points (white circles, coordinates top + left coordinate, e.g.: C2) and for the cells (polygons, right + bottom coordinates, e.g.: 5, 5 is the middle tilted square area):
The file conhex_board.py
import constants as ct
import logging
class Conhex_game:
"""Representation of a Conhex Game and its state during a game
"""
def __init__(self) -> None:
"""Initializes an empty Conhex board | {
"domain": "codereview.stackexchange",
"id": 43438,
"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, python-3.x, game",
"url": null
} |
python, performance, python-3.x, game
def __init__(self) -> None:
"""Initializes an empty Conhex board
Returns: None
"""
self.logger = logging.getLogger(ct.LOGGER)
self.logger.info(f'Started logger for {self.__class__.__name__}')
self.current_player = ct.BoardPosValue.PLAYER1
self._board = {pos: ct.BoardPosValue.EMPTY
for pos in ct.POSITIONS}
self.cells_conquered = {
ct.BoardPosValue.PLAYER1: set(),
ct.BoardPosValue.PLAYER2: set(),
ct.BoardPosValue.EMPTY: set(ct.CELLS)
}
self.winner = ct.BoardPosValue.EMPTY
self.moves = []
self.player_names = dict(ct.DEFAULT_PLAYER_NAMES)
def set_player_names(self, player1_name: str, player2_name: str) -> None:
self.player_names[ct.BoardPosValue.PLAYER1] = player1_name
self.player_names[ct.BoardPosValue.PLAYER2] = player2_name
def next_player(self) -> ct.enum.Enum:
"""Makes the next player the current player
Returns: the new current player
"""
if self.current_player == ct.BoardPosValue.PLAYER1:
self.current_player = ct.BoardPosValue.PLAYER2
else:
self.current_player = ct.BoardPosValue.PLAYER1
self.logger.debug(f'Switched player: {self.current_player=}')
return self.current_player
def play_move(self, position: str) -> bool:
"""Play the given move on the board
Args:
position (str): position - capital letter + numer
MUST be one of ct.POSITIONS
the position on the board MUST be empty
Returns:
bool: True if the game is won; False if it isn't | {
"domain": "codereview.stackexchange",
"id": 43438,
"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, python-3.x, game",
"url": null
} |
python, performance, python-3.x, game
Returns:
bool: True if the game is won; False if it isn't
Raises:
ValueError: if position is not one of ct.POSITIONS
ValueError: if a move is placed at an empty spot
"""
self.logger.debug(f'Playing move: {position=}')
if position not in ct.POSITIONS:
raise ValueError(f'{position} is not a valid position.')
if self._board[position] != ct.BoardPosValue.EMPTY:
raise ValueError(f"Can't play {position}; this position is already"
f" taken by {str(self.board[position])}")
self._board[position] = self.current_player
self.moves.append(position)
self._update_cells_conquered(position)
self.next_player()
return self.game_won()
def undo_move(self) -> None:
"""Undoes one move
"""
if not self.moves:
return
position = self.moves.pop()
self.logger.debug(f'Undoing move: {position}')
self._board[position] = ct.BoardPosValue.EMPTY
self.winner = ct.BoardPosValue.EMPTY
self.next_player()
self._full_update_cells_conquered()
def reset(self) -> None:
"""Resets the board to its initial (empty) position
"""
self.logger.debug('Resetting board')
self.__init__()
def _update_cells_conquered(self, position: str) -> None:
"""Updates the conquered cells after position is played
Args:
position (str): last played position
"""
self.logger.debug(f'Updating conquered cells after playing {position}')
# Check all cells
for cell, cell_poss in ct.CELLS.items():
# If the move is in the cell and the cell is not taken yet...
if (position in cell_poss and
cell not in (self.cells_conquered[ct.BoardPosValue.PLAYER1] |
self.cells_conquered[ct.BoardPosValue.PLAYER2])): | {
"domain": "codereview.stackexchange",
"id": 43438,
"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, python-3.x, game",
"url": null
} |
python, performance, python-3.x, game
# Count the number of positions for current player
positions = sum(self._board[pos] == self._board[position]
for pos in cell_poss)
# If this is more than half of the positions, claim it!
if positions * 2 >= len(cell_poss):
self.cells_conquered[self._board[position]].add(cell)
self.cells_conquered[ct.BoardPosValue.EMPTY].remove(cell)
self.logger.info(
f'After {position=}, {cell=} with points '
f'{cell_poss} is added for {self.current_player}; '
f'player controls {positions=} points of that cell.'
f' Conquered cells are now: {self.cells_conquered=}')
def _full_update_cells_conquered(self) -> None:
"""Makes a full update of the conquered cells by replaying the game
"""
self.logger.debug('Replaying game to update conquered cells...')
stored_moves = list(self.moves)
self.reset()
for move in stored_moves:
self.play_move(move)
def game_won(self) -> bool:
""" Checks if the game is won by one of the players
Winning player is stored in self.winner
Returns:
bool: True if the game is won; False if it isn't
"""
if self.winner is not ct.BoardPosValue.EMPTY:
return True
for player, cell_dim in [(ct.BoardPosValue.PLAYER1, 1),
(ct.BoardPosValue.PLAYER2, 0)]:
self.logger.debug(f'Checking if {player=} has won...')
player_cells = self.cells_conquered[player] | {
"domain": "codereview.stackexchange",
"id": 43438,
"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, python-3.x, game",
"url": null
} |
python, performance, python-3.x, game
# Do a quick check to see if player has a cell in exactly 2 sides
if len({cell[cell_dim] for cell in player_cells
if (cell[cell_dim] <= ct.CELL_LOW_DIM
or cell[cell_dim] >= ct.CELL_HIGH_DIM)}) == 2:
self.logger.debug(f'{player} had no cells at both borders')
continue # go to the next player in the for loop
# Loop over each of the player's cell in the top or left row
for cell in (cell for cell in player_cells
if cell[cell_dim] <= ct.CELL_LOW_DIM):
# Keep adding points to the set of positions that are adjacent
# to the cell until no more cells can be added. Also keep
# track of the connected cells.
connected_cells = set()
pos_cloud = set(ct.CELLS[cell])
cell_count = -1
# Loop while cells are added in the loop
while len(connected_cells) > cell_count:
cell_count = len(connected_cells)
# Loop over all the player's cells
for other_cell in player_cells:
# Loop over all positions of that player's cell
for pos in ct.CELLS[other_cell]:
# check if other_cell is adjacent to the cells
# connected to cell - we check this by matching
# positions iteratively between cell and other_cell
if pos in pos_cloud:
# Add position
pos_cloud |= set(ct.CELLS[other_cell])
# Add cell
connected_cells.add(other_cell)
# Break the loop; cell and pos's already added
break | {
"domain": "codereview.stackexchange",
"id": 43438,
"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, python-3.x, game",
"url": null
} |
python, performance, python-3.x, game
self.logger.debug(f'For {player=}, all points connected to '
f'{cell} are: {connected_cells}')
# Check if we can reach the other side
if any(True for cell in connected_cells
if cell[cell_dim] == ct.CELL_HIGH_DIM):
self.logger.info(f'{player} has won!')
self.winner = player
return True
self.logger.info('None of the players has won yet...')
return False
def free_positions(self) -> list:
"""Gives a list of free (non-empty) positions
Returns:
list: list of positions (capital letter + number)
"""
return [pos for pos in ct.POSITIONS
if self._board[pos] == ct.BoardPosValue.EMPTY]
def __str__(self) -> str:
"""Returns a string representation of the board
Returns:
str: string representation of the board
"""
result = ''
# Generate board and plot positions
for segment, pos in zip(ct.BOARD_ASCII_SEGMENTS, ct.POSITIONS):
result += segment
if self._board[pos] == ct.BoardPosValue.EMPTY:
pos_char = 'O'
else:
pos_char = str(self._board[pos])[-1]
result += pos_char
# Replace cell coordinates with correct string values
for x, y in ct.CELLS:
for owner in ct.BoardPosValue:
if (x, y) in self.cells_conquered[owner]:
result = result.replace(f'{x},{y}', ct.ASCII_CELL[owner])
break # break out of inner for loop
return result + '\n'
def load(self, filename: str) -> None:
"""Loads a game from a txt file in LittleGolem format
Args:
filename (str): file name of the file to be loaded | {
"domain": "codereview.stackexchange",
"id": 43438,
"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, python-3.x, game",
"url": null
} |
python, performance, python-3.x, game
Args:
filename (str): file name of the file to be loaded
Raises:
ValueError: if the signature is not found in the file
ValueError: if file is empty
ValueError: if the player names or moves could not be read
"""
# Only first (and only) line is relevant
with open(filename, 'r') as file:
content = file.readline()
self.logger.debug(f'Read file {filename}: {content}')
if not content:
raise ValueError(f'Could not read file {filename}; no content.')
if ct.READ_MARKERS['SIGNATURE'] not in content:
raise ValueError(f"Signature '{ct.READ_MARKERS['SIGNATURE']}' not "
f"found in file {filename}")
# Parse player names
try:
# Find indices where player names start
player_idx = [content.find(key)
for key in ct.READ_MARKERS['PLAYERS'].values()]
# Extract player names
player_names = [content[idx + 3:content.find(']', idx)]
for idx in player_idx]
self.logger.debug(f'Read player names: {player_names}')
except Exception:
raise ValueError(f'Could not read player names from {filename}')
# Parse moves
try:
# Split the content in fields; then check if the turn markers
# are in a field. If so, extract the move and put it in the list.
# This gives a list of moves like ['H5', 'I7', 'H7']
fields = content.split(ct.READ_MARKERS['FIELD_SEPARATOR'])
moves = [field[2:field.find(']')] for field in fields
if field[:2] in ct.READ_MARKERS['TURNS']]
except Exception:
raise ValueError(f'Could not read moves from {filename}') | {
"domain": "codereview.stackexchange",
"id": 43438,
"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, python-3.x, game",
"url": null
} |
python, performance, python-3.x, game
# File is read. Now set the player names and replay the game
self.reset()
self.set_player_names(*player_names)
for move in moves:
self.play_move(move)
self.logger.info(f'Successfully read file {filename}')
def save(self, filename: str) -> None:
raise NotImplementedError
def main():
import random
b = Conhex_game()
while not b.game_won():
pos = random.choice(b.free_positions())
print(f'Playing {pos=} for {str(b.current_player)}')
b.play_move(pos)
print(f'The game is won by {b.winner}')
print(b)
if __name__ == "__main__":
main()
The file constants.py
import enum
import logging
#
# User adjustable configuration settings
#
LOG_LEVEL = logging.ERROR
#
# Logging
#
LOGGER = 'conhex'
LOG_FORMAT = ('[%(levelname)s] [%(asctime)s] [%(filename)s:(%(lineno)d] '
'%(message)s')
logging.basicConfig(format=LOG_FORMAT, level=LOG_LEVEL) | {
"domain": "codereview.stackexchange",
"id": 43438,
"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, python-3.x, game",
"url": null
} |
python, performance, python-3.x, game
#
# Board layout: cells and positions, board dimensions
#
CELLS = {
(1, 1): ['A1', 'B3', 'C2'],
(1, 3): ['B3', 'B4', 'B5'],
(1, 5): ['B5', 'B6', 'B7'],
(1, 7): ['B7', 'B8', 'B9'],
(1, 9): ['A11', 'B9', 'C10'],
(2, 2): ['B3', 'B4', 'C2', 'C4', 'D2', 'D3'],
(2, 4): ['B4', 'B5', 'B6', 'C4', 'C5', 'C6'],
(2, 6): ['B6', 'B7', 'B8', 'C6', 'C7', 'C8'],
(2, 8): ['B8', 'B9', 'C10', 'C8', 'D10', 'D9'],
(3, 1): ['C2', 'D2', 'E2'],
(3, 3): ['C4', 'C5', 'D3', 'D5', 'E3', 'E4'],
(3, 5): ['C5', 'C6', 'C7', 'D5', 'D6', 'D7'],
(3, 7): ['C7', 'C8', 'D7', 'D9', 'E8', 'E9'],
(3, 9): ['C10', 'D10', 'E10'],
(4, 2): ['D2', 'D3', 'E2', 'E3', 'F2', 'F3'],
(4, 4): ['D5', 'D6', 'E4', 'E6', 'F4', 'F5'],
(4, 6): ['F4', 'F5', 'G4', 'G6', 'H5', 'H6'],
(4, 8): ['D10', 'D9', 'E10', 'E9', 'F10', 'F9'],
(5, 1): ['E2', 'F2', 'G2'],
(5, 3): ['E3', 'E4', 'F3', 'F4', 'G3', 'G4'],
(5, 5): ['E6', 'F5', 'F6', 'F7', 'G6'],
(5, 7): ['E8', 'E9', 'F8', 'F9', 'G8', 'G9'],
(5, 9): ['E10', 'F10', 'G10'],
(6, 2): ['F2', 'F3', 'G2', 'G3', 'H2', 'H3'],
(6, 4): ['D6', 'D7', 'E6', 'E8', 'F7', 'F8'],
(6, 6): ['F7', 'F8', 'G6', 'G8', 'H6', 'H7'],
(6, 8): ['F10', 'F9', 'G10', 'G9', 'H10', 'H9'],
(7, 1): ['G2', 'H2', 'I2'],
(7, 3): ['G3', 'G4', 'H3', 'H5', 'I4', 'I5'],
(7, 5): ['H5', 'H6', 'H7', 'I5', 'I6', 'I7'],
(7, 7): ['G8', 'G9', 'H7', 'H9', 'I7', 'I8'],
(7, 9): ['G10', 'H10', 'I10'],
(8, 2): ['H2', 'H3', 'I2', 'I4', 'J3', 'J4'],
(8, 4): ['I4', 'I5', 'I6', 'J4', 'J5', 'J6'],
(8, 6): ['I6', 'I7', 'I8', 'J6', 'J7', 'J8'],
(8, 8): ['H10', 'H9', 'I10', 'I8', 'J8', 'J9'],
(9, 1): ['I2', 'J3', 'K1'],
(9, 3): ['J3', 'J4', 'J5'],
(9, 5): ['J5', 'J6', 'J7'],
(9, 7): ['J7', 'J8', 'J9'],
(9, 9): ['I10', 'J9', 'K11']
}
POSITIONS = sorted({position for cell in CELLS.values() for position in cell},
key=lambda p: (int(p[1:]), p[0])) | {
"domain": "codereview.stackexchange",
"id": 43438,
"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, python-3.x, game",
"url": null
} |
python, performance, python-3.x, game
CELL_LOW_DIM = 2 # Row/column 1 *and* 2 lie at the border
CELL_HIGH_DIM = 8 # Row/column 8 *and* 9 lie at the border
#
# Players, default player names and possible values of the board positions
#
class BoardPosValue(enum.Enum):
"""Enum class for defining the state of a position on the board
"""
def _generate_next_value_(name: str, *_) -> str:
return name
EMPTY = enum.auto()
PLAYER1 = enum.auto()
PLAYER2 = enum.auto()
DEFAULT_PLAYER_NAMES = {
BoardPosValue.PLAYER1: 'Player 1',
BoardPosValue.PLAYER2: 'Player 2',
} | {
"domain": "codereview.stackexchange",
"id": 43438,
"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, python-3.x, game",
"url": null
} |
python, performance, python-3.x, game
#
# ASCII representation of the board
#
__ASCII_BOARD__ = \
""" A B C D E F G H I J K
1 #-----------+-----------+-----------+-----------+-----------#
| | 3,1 | 5,1 | 7,1 | |
| | | | | |
2 | 1,1 #-----#-----#-----#-----#-----#-----# 9,1 |
| / | 4,2 | 6,2 | \ |
| / | | | \ |
3 +-----# 2,2 #-----#-----#-----#-----# 8,2 #-----+
| | / | 5,3 | \ | |
| | / | | \ | |
4 | 1,3 #-----# 3,3 #-----#-----# 7,3 #-----# 9,3 |
| | | / | \ | | |
| | | / | \ | | |
5 +-----# 2,4 #-----# 4,4 # 6,4 #------# 8,4 #-----+
| | | | / \ | | | |
| | | | / 5,5 \ | | | |
6 | 1,5 #-----# 3,5 #------# # #-----# 7,5 #-----# 9,5 |
| | | | \ / | | | |
| | | | \ / | | | |
7 +-----# 2,6 #-----# 4,6 # 6,6 #------# 8,6 #-----+
| | | \ | / | | |
| | | \ | / | | |
8 | 1,7 #-----# 3,7 #-----#-----# 7,7 #-----# 9,7 |
| | \ | | / | |
| | \ | 5,7 | / | |
9 +-----# 2,8 #-----#-----#-----#-----# 8,8 #-----+
| \ | | | / |
| \ | 4,8 | 6,8 | / |
10 | 1,9 #-----#-----#-----#-----#-----#-----# 9,9 | | {
"domain": "codereview.stackexchange",
"id": 43438,
"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, python-3.x, game",
"url": null
} |
python, performance, python-3.x, game
10 | 1,9 #-----#-----#-----#-----#-----#-----# 9,9 |
| | | | | |
| | 3,9 | 5,9 | 7,9 | |
11 #-----------+-----------+-----------+-----------+-----------#""" \
# noqa: W605 - ignore escape sequence warming for the ascii board | {
"domain": "codereview.stackexchange",
"id": 43438,
"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, python-3.x, game",
"url": null
} |
python, performance, python-3.x, game
BOARD_ASCII_SEGMENTS = __ASCII_BOARD__.split('#')
ASCII_CELL = {
BoardPosValue.PLAYER1: '-1-',
BoardPosValue.PLAYER2: '-2-',
BoardPosValue.EMPTY: ' ',
}
#
# String markers for reading and writing files
#
READ_MARKERS = {
'SIGNATURE': 'FF[CONHEX]VA[CONHEX]EV[conhex.ld.CONHEX]',
'PLAYERS': {
BoardPosValue.PLAYER1: 'PW',
BoardPosValue.PLAYER2: 'PB',
},
'TURNS': ('B[', 'R['),
'FIELD_SEPARATOR': ';',
}
if __name__ == "__main__":
pass
Answer: Overall it's pretty good.
Conventionally Conhex_game would be ConhexGame (UpperCamelCase for classes).
ct is a non-obvious abbreviation for constants, and I don't see a whole lot of value in aliasing it. You can just from constants import ....
The hint -> ct.enum.Enum: doesn't seem right. You're returning a player, which is a BoardPosValue right?
play_move returning a boolean doesn't seem to add a lot of value. It would be more legible on the calling side if you simply don't return anything and force the caller to ask for game_won themselves.
Re. _update_cells_conquered: your outer loop seems like it could be improved in efficiency. You should create an index that, given a position, is able to look up a cell in O(1) time.
game_won is a little nasty and should be decomposed into multiple methods.
This pattern:
except Exception:
raise ValueError(f'Could not read player names from {filename}') | {
"domain": "codereview.stackexchange",
"id": 43438,
"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, python-3.x, game",
"url": null
} |
python, performance, python-3.x, game
is a little problematic. First, you should only be catching the exceptions you reasonably expect, probably IndexError in this case. Second, don't trash the trace. Use except IndexError as e: raise ValueError(...) from e to preserve it. Third, it's probably a better idea to define and raise your own exception types rather than ValueError.
Your type hints are incomplete. main() needs a -> None, and free_positions should return a list[str] I think, assuming position is a string. mypy will tell you these issues when properly configured.
I consider ASCII_BOARD to be large enough that it deserves its own .txt file rather than living in code. Also, don't name it with double underscores; it's a plain-old constant.
There's a formatting problem with your ASCII_BOARD that threw me for a loop. The first line is misaligned and makes the column assignments non-obvious. This will be fixed if you move it to a text file.
You ask:
Specifically review the way I'm using the Python logger. Is this a Pythonic and "good" way to use logging (e.g.: logger initialising, storing a logger object in a class, points where I call the logger, etc.)?
Putting the logger in the class is sketchy, especially in your case since you pull a nasty trick and re-issue calls to __init__ on existing instances. Probably safer to do the usual thing and move it to globals. Consider moving these:
LOGGER = 'conhex'
LOG_FORMAT = ('[%(levelname)s] [%(asctime)s] [%(filename)s:(%(lineno)d] '
'%(message)s')
logging.basicConfig(format=LOG_FORMAT, level=LOG_LEVEL)
into a logger initialisation function called from the global namespace, possibly something like
def config_logger():
logging.basicConfig(
format='[%(levelname)s] [%(asctime)s] [%(filename)s:(%(lineno)d] '
'%(message)s',
level=logging.ERROR,
)
return logging.getLogger('conhex')
logger = config_logger()
You ask: | {
"domain": "codereview.stackexchange",
"id": 43438,
"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, python-3.x, game",
"url": null
} |
python, performance, python-3.x, game
logger = config_logger()
You ask:
Optically, the code seems a bit messy. I tried to adhere to PEP8 and the code passes Flake8. Any suggestions to improve code readability?
Delete Returns: None since that's obvious. And as above, subdivide your longest method into multiple shorter ones. Otherwise the optics are fine.
reset()ting an entire instance, or especially re-calling __init__, is evidence of a kind of mutation that makes debugging and some functional code patterns more difficult. Attempt to migrate to more immutable instances, and if it's possible, instead of reset(), simply abandon the old instance and construct a new one out-of-place. | {
"domain": "codereview.stackexchange",
"id": 43438,
"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, python-3.x, game",
"url": null
} |
python, python-3.x, programming-challenge
Title: Largest product in a series
Question: Problem description:
The four adjacent digits in the 1000-digit number that have the greatest product are 9 × 9 × 8 × 9 = 5832.
73167176531330624919225119674426574742355349194934
96983520312774506326239578318016984801869478851843
85861560789112949495459501737958331952853208805511
12540698747158523863050715693290963295227443043557
66896648950445244523161731856403098711121722383113
62229893423380308135336276614282806444486645238749
30358907296290491560440772390713810515859307960866
70172427121883998797908792274921901699720888093776
65727333001053367881220235421809751254540594752243
52584907711670556013604839586446706324415722155397
53697817977846174064955149290862569321978468622482
83972241375657056057490261407972968652414535100474
82166370484403199890008895243450658541227588666881
16427171479924442928230863465674813919123162824586
17866458359124566529476545682848912883142607690042
24219022671055626321111109370544217506941658960408
07198403850962455444362981230987879927244284909188
84580156166097919133875499200524063689912560717606
05886116467109405077541002256983155200055935729725
71636269561882670428252483600823257530420752963450
Find the thirteen adjacent digits in the 1000-digit number that have the greatest product. What is the value of this product?
How to Find the Largest product in a Series
Review 1
def greatest_product(n):
numbers=[int(value) for value in n]
result=[reduce(lambda x,y: x*y, islice(numbers, i, i+5), 1) for i in range(len(numbers)-4)]
return max(result)
Review 2
def greatest_product(s, m=0):
for i in range(0, len(s)-4):
m = max(m, prod(map(int,s[i:i+5])))
return m
My Solution
This is my solution for problem 8 of Project Euler using Python:
adjacent_length = 13
largest_product = 0
for i in range(0, len(s) - adjacent_length + 1):
product = 1
for j in range(i, i + adjacent_length):
product *= int(s[j: j + 1]) | {
"domain": "codereview.stackexchange",
"id": 43439,
"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, programming-challenge",
"url": null
} |
python, python-3.x, programming-challenge
product = 1
for j in range(i, i + adjacent_length):
product *= int(s[j: j + 1])
if product > largest_product:
largest_product = product
How could my code be improved?
Answer:
Place import names at top of script
I am sure you know if you copy paste your code into a console as is, it will raise NameErrors.
Put the following:
from functools import reduce
from itertools import islice
from math import prod
At the top of script.
Your second function is actually quite effictive, but not as effictive as it can be, you made a simple mistake, max can return the maximum value of more than two numbers, its arguments can be infinitely many or an iterable.
So it should be written as this:
def greatest_product(s):
return max(prod(map(int,s[i:i+4])) for i in range(len(s)-4))
Then, to generalize it, as you can see, if you need max product of 4 numbers the first number is 4, so if you need max product of 13 numbers the first number should be 13, just pass two arguments to the function:
def greatest_product(s, n=13):
return max(prod(map(int,s[i:i+n])) for i in range(len(s)-n))
Full code:
from math import prod
def greatest_product(s, n=13):
return max(prod(map(int,s[i:i+n])) for i in range(len(s)-n)) | {
"domain": "codereview.stackexchange",
"id": 43439,
"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, programming-challenge",
"url": null
} |
c#, mvvm, xamarin
Title: ViewModel for meetings and rentals
Question: I am bringing up to date an old Xamarin app. I am concerned mostly with any design patterns I should be using or anti-patterns I shouldn't be using. This is my first attempt creating a ViewModel from scratch.
public sealed class DetailsViewModel : INotifyPropertyChanged
{
#region Private Fields
private ActivityDto _meeting;
#endregion Private Fields
#region Public Constructors
public DetailsViewModel()
{
Meeting = new ActivityDto();
}
#endregion Public Constructors
#region Public Events
public event PropertyChangedEventHandler PropertyChanged;
#endregion Public Events
#region Public Properties
public string ActivityStatus
{
get => _meeting?.Activity_Status;
set
{
if (value == _meeting.Activity_Status) return;
_meeting.Activity_Status = value;
OnPropertyChanged();
OnPropertyChanged(nameof(IsComplete));
OnPropertyChanged(nameof(IsScheduled));
}
}
public string ActivityType
{
get => _meeting.Activity_Type;
set
{
if (value == _meeting.Activity_Type) return;
_meeting.Activity_Type = value;
OnPropertyChanged();
OnPropertyChanged(nameof(IsRental));
}
}
public string ContactCode
{
get => _meeting.ContactCode;
set
{
if (value == _meeting.ContactCode) return;
_meeting.ContactCode = value;
OnPropertyChanged();
}
}
public DateTime EndDate
{
get => _meeting.End_Date;
set
{
if (value == _meeting.End_Date) return;
_meeting.End_Date = value;
OnPropertyChanged();
}
}
public bool IsComplete => ActivityStatus == "Completed";
public bool IsRental => _meeting?.Activity_Type == "Rental"; | {
"domain": "codereview.stackexchange",
"id": 43440,
"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#, mvvm, xamarin",
"url": null
} |
c#, mvvm, xamarin
public bool IsRental => _meeting?.Activity_Type == "Rental";
public bool IsScheduled => ActivityStatus == "Scheduled";
public string Location
{
get => _meeting.Location;
set
{
if (value == _meeting.Location) return;
_meeting.Location = value;
OnPropertyChanged();
}
}
public string Notes
{
get => _meeting.ResolutionOverrideText;
set
{
if (value == _meeting.ResolutionOverrideText) return;
_meeting.ResolutionOverrideText = value;
OnPropertyChanged();
}
}
public string SerialNumber
{
get => _meeting.SerialNumber;
set
{
if (value == _meeting.SerialNumber) return;
_meeting.SerialNumber = value;
OnPropertyChanged();
}
}
public DateTime StartDate
{
get => _meeting.Start_Date;
set
{
if (value == _meeting.Start_Date) return;
_meeting.Start_Date = value;
OnPropertyChanged();
}
}
#endregion Public Properties
#region Private Properties
private ActivityDto Meeting
{
get => _meeting;
set
{
if (Equals(value, _meeting)) return;
_meeting = value;
OnPropertyChanged();
OnPropertyChanged(nameof(ActivityStatus));
OnPropertyChanged(nameof(ContactCode));
OnPropertyChanged(nameof(Location));
OnPropertyChanged(nameof(Notes));
OnPropertyChanged(nameof(SerialNumber));
OnPropertyChanged(nameof(ActivityType));
OnPropertyChanged(nameof(StartDate));
OnPropertyChanged(nameof(EndDate));
OnPropertyChanged(nameof(IsComplete));
OnPropertyChanged(nameof(IsRental));
OnPropertyChanged(nameof(IsScheduled));
}
}
#endregion Private Properties | {
"domain": "codereview.stackexchange",
"id": 43440,
"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#, mvvm, xamarin",
"url": null
} |
c#, mvvm, xamarin
#endregion Private Properties
#region Public Methods
public async Task GetMeetingAsync(int meetingId)
{
var options = new RestClientOptions(UserSettings.Url)
{
RemoteCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true
};
using (var client = new RestClient(options))
{
const string uri = "data/activity/{meetingId}/";
var request = new RestRequest(uri)
.AddUrlSegment("meetingId", meetingId);
var response = await client.GetAsync<ActivityDto>(request);
Meeting = response;
}
}
#endregion Public Methods
#region Protected Methods
[NotifyPropertyChangedInvocator]
private void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
#endregion Protected Methods
}
Any hints or tips will be appreciated.
Answer: It seems a good solution for me.
I have only just one concern but it is not that objective. I personally don't like the usage of #region because it can fool you by saying that the class is not so big if all regions are collapsed.
It can also become outdated easily. Like in your case the your OnPropertyChanged method is private, but the region says protected.
I rather prefer the usage of partial classes. Like :
DetailsViewModel.PublicProperties.cs
DetailsViewModel.NonPublicMembers.cs
Or name them whatever you like :) | {
"domain": "codereview.stackexchange",
"id": 43440,
"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#, mvvm, xamarin",
"url": null
} |
python, beginner, python-3.x
Title: Calculates delivery charges and number of deliveries
Question: Function:
Calculates delivery charges based on area and also shows number of deliveries (fast food shop).
Created to stop bickering from drivers and for stats.
code:
from decimal import Decimal
# local delivery area £2 being the charge num being number of deliveries
def local(num) -> Decimal:
return Decimal(2 * num)
# City of kinross area £4.5 being the charge, nun being number of deliveries
def kinross(num) -> Decimal:
return Decimal(4.5 * num)
# City of lochgelly area £3.5 being the charge, num being number of deliveries
def lochgelly(num) -> Decimal:
return Decimal(3.5 * num)
# City of Cowdenbeath area £4 being the delivery charge and num the number of deliveries
def cowdenbeath(num) -> Decimal:
return Decimal(4 * num)
loc = local(2)
kin = kinross(3)
gel = lochgelly(2)
cow = cowdenbeath(2)
print(f'local: £{loc}')
print(f'kinross: £{kin}')
print(f'lochgelly: £{gel}')
print(f'cowdenbeath: £{cow}')
# -30 is petrol money
print(f'\nTotal -> £{sum(list((loc, kin, gel, cow, -30)))}')
print(f'Deliveries -> {sum(list((2, 3, 2, 2)))}')
Output:
local: £4
kinross: £13.5
lochgelly: £7
cowdenbeath: £8
Total -> £2.5
Deliveries -> 9
Questions:
How can I format the £ signs to be on the same level?
There is input repetition in the code which is tedious, any ideas? I can’t pass parameters as I’ve coded this on my phone.
I don’t like the way this code is, can you please advice on how I could improve it?
I’m just a beginner so I don’t really know what I’m doing.
Answer: Python has built-in support for showing localised currencies; you might as well use this. It shows to the nearest pence so you don't really have to use Decimal for this application.
It's good that you're trying your hand at functions but you've chosen the wrong thing to capture. You don't need a function for every city.
Consider showing: | {
"domain": "codereview.stackexchange",
"id": 43441,
"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, beginner, python-3.x",
"url": null
} |
python, beginner, python-3.x
a fixed-width-formatted table
headings for item name, unit charge, quantity, and subtotal
petrol as a line item like any other
Don't write literals 2, 3, 2, 2 for your sum. Instead store and re-use the arguments you've passed to your subtotal-calculating routines. A NamedTuple is one convenient way.
Re.
How can I format the £ signs to be on the same level?
It's less important to do this, and much more important to align the decimal places for easy magnitude comparison. You can define one formatting string, bind to its .format() method, and use this for both your header and rows.
Suggested
from locale import setlocale, LC_ALL, currency
from typing import NamedTuple
setlocale(LC_ALL, 'en-GB')
format_row = '{name:>12} {charge:>7} {qty:>3} {subtotal:>8}'.format
class Item(NamedTuple):
name: str
qty: int
charge: float
@property
def subtotal(self) -> float:
return self.qty * self.charge
def format_line(self) -> str:
return format_row(
name=self.name, charge=currency(self.charge),
qty=self.qty, subtotal=currency(self.subtotal),
)
def main() -> None:
deliveries = (
Item('Local', qty=2, charge=2.0),
Item('Kinross', qty=3, charge=4.5),
Item('Lochgelly', qty=2, charge=3.5),
Item('Cowdenbeath', qty=2, charge=4.0),
)
costs = Item('Petrol', qty=1, charge=-30),
items = deliveries + costs
print(format_row(name='Item', charge='Charge', qty='Qty', subtotal='Subtotal'))
print('\n'.join(item.format_line() for item in items))
total = sum(item.subtotal for item in items)
n_deliveries = sum(item.qty for item in deliveries)
print(f'\nTotal -> {currency(total)}')
print(f'Deliveries -> {n_deliveries}')
if __name__ == '__main__':
main() | {
"domain": "codereview.stackexchange",
"id": 43441,
"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, beginner, python-3.x",
"url": null
} |
python, beginner, python-3.x
if __name__ == '__main__':
main()
Output
Item Charge Qty Subtotal
Local £2.00 2 £4.00
Kinross £4.50 3 £13.50
Lochgelly £3.50 2 £7.00
Cowdenbeath £4.00 2 £8.00
Petrol £-30.00 1 £-30.00
Total -> £2.50
Deliveries -> 9
Symbol alignment
If you sorely want aligned currency symbols, it's possible, but you will want to have them left-aligned and keep your charges right-aligned:
from locale import setlocale, LC_ALL, currency, localeconv
from typing import NamedTuple
setlocale(LC_ALL, 'en-GB')
symbol = localeconv()['currency_symbol']
class Item(NamedTuple):
name: str
qty: int
charge: float
@property
def subtotal(self) -> float:
return self.qty * self.charge
def format_line(self) -> str:
return (
f'{self.name:12}'
f' {symbol}{self.charge:6.2f}'
f' {self.qty:>3}'
f' {symbol}{self.subtotal:7.2f}'
)
def main() -> None:
deliveries = (
Item('Local', qty=2, charge=2.0),
Item('Kinross', qty=3, charge=4.5),
Item('Lochgelly', qty=2, charge=3.5),
Item('Cowdenbeath', qty=2, charge=4.0),
)
petrol = Item('Petrol', qty=1, charge=-30)
items = (*deliveries, petrol)
print(f'{"Item":12} {"Charge":>7} {"Qty":>3} {"Subtotal":>8}')
print('\n'.join(item.format_line() for item in items))
total = sum(item.subtotal for item in items)
n_deliveries = sum(item.qty for item in deliveries)
print(f'\nTotal -> {currency(total)}')
print(f'Deliveries -> {n_deliveries}')
if __name__ == '__main__':
main()
Item Charge Qty Subtotal
Local £ 2.00 2 £ 4.00
Kinross £ 4.50 3 £ 13.50
Lochgelly £ 3.50 2 £ 7.00
Cowdenbeath £ 4.00 2 £ 8.00
Petrol £-30.00 1 £ -30.00
Total -> £2.50
Deliveries -> 9 | {
"domain": "codereview.stackexchange",
"id": 43441,
"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, beginner, python-3.x",
"url": null
} |
python, performance, python-3.x
Title: Measure the total runtime of a function in a project
Question: I recently wanted to find out which functions take which amount of time in a project, and calling a timer and printing the difference inside a function that is called multiple times does not scale well.
That's why I created my own little decorator function:
from timeit import default_timer as timer
time_in = dict()
def measure(func):
def saveTime(identifier, time):
global time_in
if identifier not in time_in:
time_in[identifier] = 0
time_in[identifier] += time
def measure_wrapper(*args, **kwargs):
global time_in
start = timer()
value = func(*args, **kwargs)
saveTime(func.__name__, timer() - start)
return value
return measure_wrapper
It works by prepending every function (or method) that should be measured with @measure and then printing the dict at the end of the main function. It works as intended. However, it adds a global variable and I'm sure there must already be a solution like it, I just haven't found it.
So, my questions are:
Is it possible to remove the global variable?
Is there already a solution like this in the standard libs?
Answer: Adressing the question:
Is there already a solution like this in the standard libs?
Unless I am misinterpreting what you want exactly, there are profiling tools available in the standard library.
For instance, given the script
def fib(n):
if n == 0:
return 0
elif n == 1:
return 1
else:
return fib(n - 1) + fib(n - 2)
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n - 1)
def main():
for i in range(30):
fib(i)
for i in range(30):
factorial(i)
if __name__ == '__main__':
main()
you can run:
python -m cProfile test.py
which gives
4357055 function calls (64 primitive calls) in 1.484 seconds
Ordered by: standard name | {
"domain": "codereview.stackexchange",
"id": 43442,
"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, python-3.x",
"url": null
} |
python, performance, python-3.x
Ordered by: standard name
ncalls tottime percall cumtime percall filename:lineno(function)
1 0.000 0.000 1.484 1.484 test.py:1(<module>)
4356586/30 1.484 0.000 1.484 0.049 test.py:1(fib)
465/30 0.000 0.000 0.000 0.000 test.py:11(factorial)
1 0.000 0.000 1.484 1.484 test.py:18(main)
1 0.000 0.000 1.484 1.484 {built-in method builtins.exec}
1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}
This gives a few more statistics than your code currently does. There is also a Python API mentioned in the page that gives a way of using cProfile (or profile) in your python code.
However, if you are more interesting in benchmarks rather than profiling, according to the link above
Note: The profiler modules are designed to provide an execution profile for a given program, not for benchmarking purposes (for that, there is timeit for reasonably accurate results). This particularly applies to benchmarking Python code against C code: the profilers introduce overhead for Python code, but not for C-level functions, and so the C code would seem faster than any Python one. | {
"domain": "codereview.stackexchange",
"id": 43442,
"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, python-3.x",
"url": null
} |
python, matplotlib, data-visualization
Title: Colored bar plots with confidence intervals
Question: I needed to create a bar plot that show:
the mean from some series;
them 95% confidence interval; and,
bars might be colored blue if they are definitely above this value (given the confidence interval), red if they are definitely below this value, or white if they contain this value.
Well, I coded the following lines, but considering I am learning Python, I am always thinking: is this a pythonic way?
You can see this code on here.
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import norm
from matplotlib.cm import ScalarMappable
np.random.seed(12345)
df = pd.DataFrame([np.random.normal(32000,200000,3650),
np.random.normal(43000,100000,3650),
np.random.normal(43500,140000,3650),
np.random.normal(48000,70000,3650)],
index=[1992,1993,1994,1995])
# Y select by user
y_user = 40000
# Creating the plot
fig, ax = plt.subplots()
# Calculating the probabilities
# I definitely believe this could be more readable
colorlist = [norm.sf(40000, loc=df[df.index == year].mean(axis = 1), scale=df[df.index == year].sem(axis = 1)).item(0) for year in df.index]
# Selecting the pallete
my_cmap = plt.cm.get_cmap('RdBu')
colors = my_cmap(colorlist)
# Creating the bars
ax.bar(df.index, df.mean(axis = 1), yerr=df.sem(axis = 1) * norm.ppf(0.975), color=colors, capsize=10)
# Ploting the y choose by user
plt.axhline(y = y_user, color = 'r', linestyle = '--')
# Controling the xticks
plt.xticks(df.index)
# Creating the colorbar
sm = ScalarMappable(cmap=my_cmap)
sm.set_array([])
cbar = plt.colorbar(sm)
cbar.set_label('Probability to contain the value choose ({})'.format(y_user), rotation=270, labelpad=25)
cbar.set_ticks(np.arange(0, 1.1 , 0.1))
fig.savefig("GregOliveira_Week3.png")
plt.show() | {
"domain": "codereview.stackexchange",
"id": 43443,
"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, matplotlib, data-visualization",
"url": null
} |
python, matplotlib, data-visualization
fig.savefig("GregOliveira_Week3.png")
plt.show()
Answer: Sort your imports.
Move your code into functions instead of leaving it in the global namespace.
Don't use np.random; it's deprecated in favour of RNG instances. In my suggested code I use a seed producing data vaguely similar but not equal to yours.
Don't call normal four times; call it once and specify a shape whose outer dimension is 4.
Don't make your dataframe with four rows and 3650 columns; this makes everything more difficult. Your dataframe should be transposed so that the columns correspond to years.
Is y_user actually selected by the user? It seems not. You're using a notebook. Notebooks have input utilities; use one of these (I have not shown this).
I definitely believe this could be more readable
You're absolutely right! Don't use a list comprehension at all; make a single vectorised call to sf().
Avoid plt.axhline when you have an axis reference to use instead. Same for xticks.
Delete set_array(); you don't need it.
Grammar and spelling: Y select by user -> Y selected by user; pallete -> palette; Ploting -> Plotting; Controling -> Controlling; Probability to contain the value choose -> Probability to contain the chosen value.
Delete nearly all of your comments since they're obvious to the average reader. Consider adding comments for non-obvious things, such as spelling out the acronyms for ppf and sem.
I consider the use of arange for your ticks to be more legible as a call to linspace, since the endpoint is included.
mean() and sem() are called multiple times; call these only once and keep a variable.
You need a chart title and axis labels. Other than the obvious "Year" I have not shown these.
Suggested
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from matplotlib.cm import ScalarMappable
from numpy.random import default_rng
from scipy.stats import norm | {
"domain": "codereview.stackexchange",
"id": 43443,
"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, matplotlib, data-visualization",
"url": null
} |
python, matplotlib, data-visualization
def make_data(
n_years: int = 4, first_year: int = 1992, n_samples: int = 3650,
) -> pd.DataFrame:
rand = default_rng(seed=18)
return pd.DataFrame(
rand.normal(
loc =( 32e3, 43e3, 43.5e3, 48e3),
scale=(200e3, 100e3, 140.0e3, 70e3),
size=(n_samples, n_years),
),
columns=range(first_year, first_year + n_years),
)
def make_plot(df: pd.DataFrame, y_user: float) -> plt.Figure:
fig, ax = plt.subplots()
mean = df.mean()
sem = df.sem() # Standard error of mean
color_list = norm.sf(x=y_user, loc=mean, scale=sem) # survival function
my_cmap = plt.cm.get_cmap('RdBu')
colors = my_cmap(color_list)
ax.bar(
df.columns, mean, color=colors, capsize=10,
yerr=sem * norm.ppf(0.975), # percent-point function
)
ax.axhline(y=y_user, color='r', linestyle='--')
ax.set_xticks(df.columns)
ax.set_xlabel('Year')
cbar = plt.colorbar(ScalarMappable(cmap=my_cmap))
cbar.set_label(
f'Probability to contain chosen value ({y_user:.0f})',
rotation=270, labelpad=25,
)
cbar.set_ticks(np.linspace(0, 1, 11))
return fig
def main() -> None:
y_user = 40e3 # selected by user (eventually?)
df = make_data()
make_plot(df, y_user)
plt.show()
if __name__ == '__main__':
main()
Output | {
"domain": "codereview.stackexchange",
"id": 43443,
"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, matplotlib, data-visualization",
"url": null
} |
c++, c++17, pointers
Title: Storing (and retrieving) functions by indexing them by address
Question: I want to implement a "service" of callbacks, where subscribers register or unregister a callback. I was thinking about indexing the callbacks by the function address, so that to unregister one would simply have to pass the same function.
So, disregarding threading issues, the simplest form of my implementation would be
#include <functional>
#include <map>
#include <cstdint>
std::map<std::uintptr_t, std::function<void()>> callbacks;
///https://stackoverflow.com/a/18039824/2436175
namespace {
std::uintptr_t get_address(std::function<void()> f) {
typedef void(function_type)();
function_type** function_pointer = f.template target<function_type*>();
return static_cast<std::uintptr_t>(*function_pointer);
}
}// namespace
void subscribe(std::function<void()>&& callback) {
callbacks.insert(std::make_pair(get_address(callback), std::move(callback)));
}
void unsubscribe(const std::function<void()>& callback) {
callbacks.erase(get_address(callback));
}
void execute() {
for (const auto& callback : callbacks) {
callback.second.operator()();
}
}
On the subscriber side, we would have things like:
void test() {
}
subscribe(test);
unsubscribe(test);
I tested and it would seem to work. See code sample.
Assuming I will only use plain functions like test in this example (no lambdas, no bound methods...), is this a solid mechanism?
Answer: Don't use std::function<> if you are only going to allow plain functions
I would avoid using std::function<> if your code doesn't handle something other than a plain function being bound to it. As Deduplicator mentioned, why not use regular function pointer types to store the callbacks?
Prefer using over typedef
Especially for function pointers, the typedef syntax is a bit hard to read. Prefer using, like so:
using function_type = void(); | {
"domain": "codereview.stackexchange",
"id": 43444,
"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++, c++17, pointers",
"url": null
} |
c++, c++17, pointers
Use reinterpret_cast<> instead of a C-style cast
Avoid C style casts in general, and use the best fitting C++-style cast instead. In this case:
return reinterpret_cast<uintptr_t>(*function_pointer);
Naming things
You named the result of the call to target() function_pointer, but it's not a function pointer; it is a pointer to a function pointer. I would rename it to target_pointer to avoid any confusion.
Don't use an r-value reference in subscribe()
Your use of an r-value reference and subsequent use of std::move() is looking very dodgy. It might be fine if you only pass regular functions to it, but then there is no point of using move semantics, as std::function will not do any allocation then. Furthermore, doing something like:
foo(bar, std::move(bar));
Will resulted in undefined behaviour, as the order of evaluation of the function parameters is undefined. So the compiler is allowed to do the move first, then pass the moved-from bar as the first argument. You could call get_address() first and store the results in a temporary variable, but I would avoid the whole issue altogether and pass the std::function by value.
Use emplace()
You can avoid having to call std::make_pair by using emplace():
callbacks.emplace(get_address(callback), callback);
Consider using structured bindings
Since you tagged the question C++17, consider using structured bindings to avoid having to use first and second if you iterate over a map:
for (const auto&[address, callback]: callbacks) {
callback();
} | {
"domain": "codereview.stackexchange",
"id": 43444,
"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++, c++17, pointers",
"url": null
} |
c++, c++17, pointers
Consider using a std::unordered_set
Since you don't care about the ordering of the callbacks, you can use a std::unordered_map instead. This will allow for faster insertion and removal into callbacks.
However, storing both the address and the function in a map is redundant; you can derive the address from the function as you are already doing. So instead you could use a std::unordered_set. It is a bit more cumbersome to make a std::unordered_set of a std::function, but if you would only store regular function pointers, you can do:
std::unordered_set<void(*)()> callbacks; | {
"domain": "codereview.stackexchange",
"id": 43444,
"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++, c++17, pointers",
"url": null
} |
javascript, performance, html, dom
Title: Remove columns in HTML table where the sum is 0
Question: I have an HTML table, and I would like to remove columns where the sum vertically is 0 dynamically.
let ths_columns = [...document.querySelectorAll("thead tr th")].map(
(th) => th.textContent.trim()
); //first row of table header [ "column_1", "column_2", "column_3", "column_4" ]
let trs = [...document.querySelectorAll("tbody tr")]; // three rows of table tbody [ tr, tr, tr ]
//convert table into 2d-array dimension like matrix: trs_rows [[[10, 0, 5, 0]], [[3, 0, 6, 0]], [[8, 0, 2, 0]]];
const trs_rows = [];
for (let tr of trs) {
trs_rows.push([[...tr.children].map((td) => +td.textContent)]);
}
//make an array looks like ths_columns contains sum of rows vertically
const ths_rows_result = Array.from({ length: ths_columns.length }).fill(
0
);
for (let i = 0; i < trs_rows.length; i++) {
const element = trs_rows[i];
for (let j = 0; j < element.length; j++) {
for (let k = 0; k < element[j].length; k++) {
const td = element[j][k];
//console.log(td);
ths_rows_result[k] += td;
}
}
}
console.log(ths_rows_result); // [21, 0, 13, 0]
// make an array which contains name of columns have
const array_zeros = ths_columns
.map((th, i) => [th, ths_rows_result[i]])
.filter((entries) => entries[1] == 0)
.map((entry) => entry[0]);
//console.log(array_zeros); // ['column_2', 'column_4']
// make the same array but this time contains id instead of column's name
const array_index = [];
for (let i = 0; i < ths_columns.length; i++) {
const element = ths_columns[i];
if (array_zeros.includes(element)) {
array_index.push(i);
}
}
//console.log(array_index); //[1, 3]
//loop over first row and if a cell is in add to a cell class none (in css .none{display: none;})
let ths = [...document.querySelectorAll("thead tr th")];
for (let i = 0; i < ths.length; i++) {
const th = ths[i];
if (array_index.includes(i)) {
th.classList.add("none");
}
} | {
"domain": "codereview.stackexchange",
"id": 43445,
"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": "javascript, performance, html, dom",
"url": null
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.