text
stringlengths
1
2.12k
source
dict
c++, brainfuck std::vector<I> stack; for (I loop = begin; loop != end; ++loop) { switch (*loop) { case '>': dp = (dp + 1) % memory.size(); break; case '<': dp = std::max(memory.size() -1, dp - 1); break; case '+': ++memory[dp];break; case '-': --memory[dp];break; case '.': std::cout << memory[dp];break; case ',': std::cin >> memory[dp];break; case '[': if (memory[dp]) { // Enter the loop. // So remember where to jump back to. stack.emplace_back(loop); } else { // Ignore the loop. // So find the end (the ++loop) will take // us to the next instruction. loop = findMatchingClose(loop); } case ']': if (memory[dp]) { // Next loop iteration. // Set loop to start of the inner most loop. // Note ++loop will take us to the first instruction. loop = stack.back(); } else { // Exit the inner most loop. stack.pop_back(); } break; default: continue; } } } main.cpp #include "bf.h" #include <iostream> #include <fstream> #include <iterator> int main(int argc, char* argv[]) { std::cout << (-11 % 10) << "\n"; if (argc <= 1) { std::cerr << "No input file\n"; return -1; } BF bf; for (int loop = 1; loop < argc; ++loop) { std::ifstream file(argv[loop]); std::string program(std::istream_iterator<char>{file}, std::istream_iterator<char>{});
{ "domain": "codereview.stackexchange", "id": 45219, "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++, brainfuck", "url": null }
c++, brainfuck bf.reset(); bf.run(std::begin(program), std::end(program)); } } Answer: template<typename I> // Not sure how to specify that `I` is limited to allow random access. // Suppose I could re-write to allow slips back and forward. void run(I begin, I end); I think you're looking for #include <iterator> template<std::random_access_iterator I> void run(I begin, I end); That said, I'd include <ranges> and write void run(std::ranges::random_access_range auto range); I think that the template definitions in bf.cpp should be in the header file, so that they can be instantiated by client code. BF::BF(std::size_t defaultMemorySize) Is that really a default size for this instance, or is it the actual size? I don't see any way to change the size after this point. findMatchingClose() is unbounded for malformed programs - there's nothing to stop loop reaching its matching end iterator, and causing Undefined Behaviour. Is the fallthrough from case '[' to case ']' intentional? If it is, then please add [[fallthrough]] and a comment to explain why. case '<': dp = std::max(memory.size() -1, dp - 1); break; Missing include of <algorithm>. I don't think this is a very clear wraparound implementation (I only realised that dp-1 becomes greater than memory.size() when dp is zero because of the preceding modular calculation - I'd find it clearer to have (dp > 0 ? dp : memory.size()) - 1 or similar). else { // Exit the inner most loop. stack.pop_back(); I don't see any check for underflow here - needs a comment to explain why that can't happen. std::cout << (-11 % 10) << "\n"; Leftover diagnostic? if (argc <= 1) { std::cerr << "No input file\n"; return -1; } Normally, we return small positive values from main() such as EXIT_FAILURE. Negative values are likely to be transformed by the runtime environment and OS; for example, POSIX specifies that
{ "domain": "codereview.stackexchange", "id": 45219, "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++, brainfuck", "url": null }
c++, brainfuck only the least significant 8 bits (that is, status & 0377) shall be available from wait() and waitpid(); But why are we failing in this case at all? Couldn't we read from std::cin? That would be a user's reasonable expectation. (I guess the program couldn't then use the , command, of course.)
{ "domain": "codereview.stackexchange", "id": 45219, "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++, brainfuck", "url": null }
c++, serialization Title: Integer endianness types for protocol structures, take 2 Question: Motivation When working with storage or wire protocols, we often read or write structures containing integers with specific byte-ordering (e.g. big-endian for Internet Protocol, or little-endian for USB). It's common to use functions such as the htons() family to convert values, but it's easy to miss a conversion (particularly if the protocol is the same endianness as the development system). Instead, I prefer to use the type system to distinguish host integers from their representations' protocol byte-order. Known limitations (non-goals): I haven't had a need to handle floating-point values, so only integers are handled here. It's not suitable for protocols such as IIOP or X11 where one of the hosts chooses at run-time which endianness to use. Example usage I'm currently using this when sending values over the wire. A simplified example, with all the error handling removed, looks something like: struct Response { BigEndian<std::uint16_t> seq_no; BigEndian<std::uint16_t> sample_value; }; We send by assigning (which implicitly converts our integer value to big-endian byte sequence) and then writing the structure: void send_result(std::uint16_t value) { Response r; r.seq_no = counter++; r.sample_value = value; write(fd, &r, sizeof r); } On the receive side, we read the wire representation into the same structure (so it's bitwise identical to the sending side) and then use the conversion operator to access the data in native form: std::uint16_t recv_result() { Response r; read(fd, &r, sizeof r); // ignore seq_no, for now return r.sample_value; } Changes since previous version Since version 1, I've changed the following:
{ "domain": "codereview.stackexchange", "id": 45220, "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++, serialization", "url": null }
c++, serialization Changes since previous version Since version 1, I've changed the following: Renamed the views which give us access to the storage in the desired order, and added comments to make it clearer. This was previously giving the impression that round-trip would byte-reverse the value, which is not the case. Uniformly scatter/gather to native char size (in units of CHAR_BIT). Added warning for non-8-bit platforms to encourage audit of octet-orientated code. Optimised for reading/writing native-endian values directly with no wrapper class (will do the Right Thing for unicorn/dinosaur platforms such as mixed-endian or no-endian). Split out the default constructor, since serialising zero is a no-op. Added constexpr to conversion operations. Demonstrate plain old round-trip in the tests, rather than modifying the storage. I think this makes the tests clearer. Implementation #ifndef ENDIAN_HPP #define ENDIAN_HPP #include <array> #include <bit> #include <climits> #include <concepts> #include <ranges> #include <type_traits> #ifndef ENDIAN_SUPPORT_NON_8BIT static_assert(CHAR_BIT == 8, "This header splits into chars, not octets. " "Define ENDIAN_SUPPORT_NON_8BIT to enable."); #endif namespace endian { namespace detail { template<std::integral T, // type to represent auto BigFirst, // view that presents MSB first auto LittleFirst> // view that presents LSB first struct Endian { // We use unsigned T for bitwise operations using U = std::make_unsigned_t<T>; // The underlying storage std::array<unsigned char, sizeof (T)> data = {}; constexpr Endian() = default;
{ "domain": "codereview.stackexchange", "id": 45220, "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++, serialization", "url": null }
c++, serialization constexpr Endian() = default; // implicit conversion from T constexpr Endian(T value) { // unpack value starting with the least-significant bits auto uval = static_cast<U>(value); for (auto& c: data | LittleFirst) { c = static_cast<unsigned char>(uval); uval >>= CHAR_BIT; } } // implicit conversion to T constexpr operator T() const { // compose value starting with most-significant bits U value = 0; for (auto c: data | BigFirst) { value <<= CHAR_BIT; value |= c; } return static_cast<T>(value); } }; } template<std::integral T> using BigEndian = std::conditional_t<std::endian::native == std::endian::big, T, // no conversion needed detail::Endian<T, std::views::all, std::views::reverse>>; template<std::integral T> using LittleEndian = std::conditional_t<std::endian::native == std::endian::little, T, // no conversion needed detail::Endian<T, std::views::reverse, std::views::all>>; } #endif // ENDIAN_HPP Unit Tests using endian::BigEndian; using endian::LittleEndian; #include <gtest/gtest.h> #include <cstdint> #include <cstring> // Ensure there's no padding static_assert(sizeof (BigEndian<int>) == sizeof (int)); static_assert(sizeof (LittleEndian<int>) == sizeof (int)); // Helper function to inspect representation template<typename T> auto byte_array(const T& t) { std::array<unsigned char, sizeof t> bytes; std::memcpy(bytes.data(), &t, sizeof t); return bytes; }
{ "domain": "codereview.stackexchange", "id": 45220, "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++, serialization", "url": null }
c++, serialization // Now the tests themselves TEST(big_endian, uint8) { const std::uint8_t x = 2; auto be = BigEndian<std::uint8_t>{x}; std::array<unsigned char, 1> expected{{2}}; EXPECT_EQ(byte_array(be), expected); // round trip back to native std::uint8_t y = be; EXPECT_EQ(y, x); } TEST(little_endian, uint8) { const std::uint8_t x = 2; auto le = LittleEndian<std::uint8_t>{x}; std::array<unsigned char, 1> expected{{2}}; EXPECT_EQ(byte_array(le), expected); std::uint8_t y = le; EXPECT_EQ(y, x); } TEST(big_endian, uint16) { const std::uint16_t x = 0x1234; BigEndian<std::uint16_t> be = x; std::array<unsigned char, 2> expected{{0x12, 0x34}}; EXPECT_EQ(byte_array(be), expected); std::uint16_t y = be; EXPECT_EQ(y, x); } TEST(little_endian, uint16) { const std::uint16_t x = 0x1234; auto le = LittleEndian<std::uint16_t>{x}; std::array<unsigned char, 2> expected{{0x34, 0x12}}; EXPECT_EQ(byte_array(le), expected); std::uint16_t y = le; EXPECT_EQ(y, x); } TEST(big_endian, uint32) { const std::uint32_t x = 0x12345678; auto be = BigEndian<std::uint32_t>{x}; std::array<unsigned char, 4> expected{{ 0x12, 0x34, 0x56, 0x78 }}; EXPECT_EQ(byte_array(be), expected); std::uint32_t y = be; EXPECT_EQ(y, x); } TEST(little_endian, uint32) { const std::uint32_t x = 0x12345678; auto le = LittleEndian<std::uint32_t>{x}; std::array<unsigned char, 4> expected{{ 0x78, 0x56, 0x34, 0x12 }}; EXPECT_EQ(byte_array(le), expected); std::uint32_t y = le; EXPECT_EQ(y, x); } Answer: This looks very good! About the limitations I haven't had a need to handle floating-point values, so only integers are handled here.
{ "domain": "codereview.stackexchange", "id": 45220, "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++, serialization", "url": null }
c++, serialization I haven't had a need to handle floating-point values, so only integers are handled here. If you did want to support floating-point values, and perhaps other types that might have an endianness, then your approach falls apart, or at least it would require some reinterpret_casting (or std::bit_casting since C++20) from the non-integer to the integer types, and it would still only work for types whose sizes match those of integers. Another way to solve the issue would be to reinterpret the value as std::bytes, and just rearrange them into the std::array as necessary for the desired endianness. It's not suitable for protocols such as IIOP or X11 where one of the hosts chooses at run-time which endianness to use. You could add a template parameter that would switch between a statically chosen endianness and one that can be changed at run-time, analogous to std::span's std::dynamic_extent. Add support for alignment You did ask about this in your previous version, and I think it is still important to consider this: you probably want to make sure your Endian<T> has the same alignment as T. Consider that you have a struct like this: struct Foo { char bar; uint16_t baz; uint32_t quux; }; And now you want to ensure the endianness is fixed, so you just add your wrappers: struct Foo { LittleEndian<char> bar; LittleEndian<uint16_t> baz; LittleEndian<uint32_t> quux; }; Before, sizeof(Foo) == 8 and all variables have their natural alignment. Afterwards sizeof(Foo) == 7, and baz and quux are incorrectly aligned. The compiler will see that, and will no longer be able to optimize the loads and stores to these variables on a little-endian machine. So I would do something like: template<std::integral T, // type to represent auto BigFirst, // view that presents MSB first auto LittleFirst, // view that presents LSB first std::size_t Align> // alignment requirement struct alignas(Align) Endian { … };
{ "domain": "codereview.stackexchange", "id": 45220, "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++, serialization", "url": null }
c++, serialization template<std::integral T, std::size_t Align = alignof(T)> using LittleEndian = std::conditional_t<std::endian::native == std::endian::little, T, // no conversion needed detail::Endian<T, std::views::reverse, std::views::all>, Align>; … Improvements to the unit tests I haven't used this myself, but I believe GoogleTest has some support for testing templated code, which allows you to get rid of a lot of code duplication. Even before you do that, it might be a good exercise to rewrite the tests a bit so that the actual type you want to test is only mentioned once, and that you have a generic way to generate test values. For example: TEST(little_endian, uint16_t) { using T = std::uint16_t; constexpr T x = static_cast<T>(0x12345678); constexpr LittleEndian<T> le = x; std::array<unsigned_char, 4> expected_full({0x78, 0x56, 0x34, 0x12}); decltype(byte_array(le)) expected; std::copy_n(expected.end() - sizeof(T), sizeof(T), expected.begin()); EXPECT_EQ(byte_array(le), expected); constexpr T y = le; EXPECT_EQ(y, x); } Also consider adding support for 64-bit integers. You also want to test whether you can use your class correctly in a constexpr environment. If you add alignment, you should also test that.
{ "domain": "codereview.stackexchange", "id": 45220, "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++, serialization", "url": null }
verilog, fpga, hdl Title: Design and stimulus for a simple Mealy finite state machine Question: I am trying to code a state machine for the given state diagram: I module mealy(input x_in,rst_n,clk, output reg y_out); parameter s0 = 2'b00, s1 = 2'b01 , s2 = 2'b10,s3 = 2'b11; reg [1:0] p_state,n_state; always@(posedge clk,negedge rst_n) begin if(!rst_n) p_state = s0; else if(clk) p_state <= n_state; end always@(x_in,p_state) begin case (p_state) s0: n_state = x_in ? s2 : s1; s1: n_state = x_in ? s2 : s1; s2: n_state = x_in ? s2 : s1; s3: n_state = s3; endcase end always@(x_in,p_state) begin case (p_state) s0: y_out = 1'b0; s1: y_out = x_in ? 1'b1 : 1'b0; s2: y_out = !x_in ? 1'b1 : 1'b0; s3: y_out = 1'b0; endcase end endmodule module mealy_tb; reg x_in,rst_n,clk; wire y_out; mealy dut(x_in,rst_n,clk,y_out); initial begin clk = 1'b0; repeat(7) #10 clk = ~clk; end initial begin rst_n = 1'b0; #20; rst_n = 1'b1; x_in = 1'b0; #10; x_in = 1'b1; #10; x_in = 1'b0; #10; x_in = 1'b1; #10; x_in = 1'b1; end always@(posedge clk,negedge rst_n) $monitor($time," rst_n = %b clk = %b x_in = %b y_out = %b ",rst_n,clk,x_in,y_out); endmodule If rst_n is low, then I reset my state machine to its origin state s0, else make the present state to the next state. Then I followed the diagram. I use case statements to show the present state and next state. Finally, I setup output according to the state and input. In the testbench, I tried a small sample case. This is my first time writing a state machine, so I need some guidance on the errors that I have made and the things that I can improve upon.
{ "domain": "codereview.stackexchange", "id": 45221, "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": "verilog, fpga, hdl", "url": null }
verilog, fpga, hdl Answer: You have done an excellent job of partitioning your design code from your testbench code into different modules. Similarly, you used good partioning between your sequential logic and combinational logic into separate always blocks. You made good use of parameters for constants, and on the whole, the code layout is good (indentation, etc.). In the sequential logic block, you should not use the following line: if(clk) While the code may simulate as desired, it is not needed, and it is not a common way to code sequential logic. It may cause a problem if you want to synthesize the code. You should use nonblocking assignments (<=) to p_state in the sequential logic block. For the combinational logic blocks, it is preferable to use the implicit sensitivity list instead of explicitly listing each signal by name. This is less error-prone: always @* This avoids problems with synthesis (having to maintain an explicit list). In the testbench, it is preferable to make connections to the dut instance ports by name instead of by port order: mealy dut ( .clk (clk), .rst_n (rst_n), .x_in (x_in), .y_out (y_out) ); While it is more verbose, it avoids another common Verilog error of connecting signals up in the wrong order. The $monitor statement is intended to be called once in an initial block, instead of every time an event occurs in an always block. You should drive the synchronous x_in input signal using nonblocking assignments (<=) and at the posedge clk to avoid simulation race conditions. Here is the code with the recommended changes: module mealy ( input x_in, rst_n, clk, output reg y_out ); parameter s0 = 2'b00, s1 = 2'b01, s2 = 2'b10, s3 = 2'b11; reg [1:0] p_state, n_state; always @(posedge clk, negedge rst_n) begin if (!rst_n) p_state <= s0; else p_state <= n_state; end
{ "domain": "codereview.stackexchange", "id": 45221, "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": "verilog, fpga, hdl", "url": null }
verilog, fpga, hdl always @* begin case (p_state) s0: n_state = x_in ? s2 : s1; s1: n_state = x_in ? s2 : s1; s2: n_state = x_in ? s2 : s1; s3: n_state = s3; endcase end always @* begin case (p_state) s0: y_out = 1'b0; s1: y_out = x_in ? 1'b1 : 1'b0; s2: y_out = !x_in ? 1'b1 : 1'b0; s3: y_out = 1'b0; endcase end endmodule module mealy_tb; reg x_in, rst_n, clk; wire y_out; mealy dut ( .clk (clk), .rst_n (rst_n), .x_in (x_in), .y_out (y_out) ); initial begin clk = 1'b0; repeat (7) #10 clk = ~clk; end initial begin $monitor($time," rst_n = %b clk = %b x_in = %b y_out = %b ", rst_n, clk, x_in, y_out); rst_n = 0; #20; rst_n = 1; @(posedge clk); x_in <= 0; @(posedge clk); x_in <= 1; @(posedge clk); x_in <= 0; @(posedge clk); x_in <= 1; @(posedge clk); x_in <= 1; @(posedge clk); end endmodule
{ "domain": "codereview.stackexchange", "id": 45221, "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": "verilog, fpga, hdl", "url": null }
java, backtracking, box-puzzle Title: Positioning boxes in a box with backtracking in Java Question: A large cube-shaped box has the dimensions 5x5x5. This box is to be completely filled with smaller boxes. Possible candidates are: 1x1x1, 5-fold 1x2x4, 6-fold 2x2x3, 6-fold An additional "magic" box with the dimensions 1x1x1 should always be placed in the middle/center of the large box. This should be solved with backtracking in Java. My attempt works correctly (i hope), but for example n=2,... and n=20 the algorithm don't stops. I am looking for a way to improve it. Thanks. import java.util.Arrays; public class Box { final int len = 5; final int empty = -1; final int max; int[][][] solution = new int[len][len][len]; int[][] candidates = { {2, 2, 3}, {1, 2, 4}, {1, 1, 1}, }; int[] taken = new int[candidates.length]; int freeSpace = len * len * len; Box(final int max, final boolean withMagicCuboid) { for (int i = 0; i < len; i++) { for (int j = 0; j < len; j++) { for (int k = 0; k < len; k++) { solution[i][j][k] = empty; } } } this.max = max; if (withMagicCuboid) { // insert magic cuboid solution[2][2][2] = 2; taken[2]++; freeSpace--; } solve(0, 0); }
{ "domain": "codereview.stackexchange", "id": 45222, "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": "java, backtracking, box-puzzle", "url": null }
java, backtracking, box-puzzle boolean insert(final int c, final int x, final int y, final int z, final int dir) { if (taken[c] >= max) { return false; } int[] a = candidates[c]; for (int i = 0; i < a[0]; i++) { for (int j = 0; j < a[1]; j++) { for (int k = 0; k < a[2]; k++) { int x2 = x; int y2 = y; int z2 = z; if (dir == 0) { x2 += i; y2 += j; z2 += k; } if (dir == 1) { x2 += i; y2 += k; z2 += j; } if (dir == 2) { x2 += j; y2 += i; z2 += k; } if (dir == 3) { x2 += j; y2 += k; z2 += i; } if (dir == 4) { x2 += k; y2 += i; z2 += j; } if (dir == 5) { x2 += k; y2 += j; z2 += i; } if (x2 < 0 || x2 >= len || y2 < 0 || y2 >= len || z2 < 0 || z2 >= len) { return false; } if (solution[x2][y2][z2] != empty) { return false; } } } } for (int i = 0; i < a[0]; i++) { for (int j = 0; j < a[1]; j++) { for (int k = 0; k < a[2]; k++) { int x2 = x; int y2 = y; int z2 = z; if (dir == 0) { x2 += i;
{ "domain": "codereview.stackexchange", "id": 45222, "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": "java, backtracking, box-puzzle", "url": null }
java, backtracking, box-puzzle int z2 = z; if (dir == 0) { x2 += i; y2 += j; z2 += k; } if (dir == 1) { x2 += i; y2 += k; z2 += j; } if (dir == 2) { x2 += j; y2 += i; z2 += k; } if (dir == 3) { x2 += j; y2 += k; z2 += i; } if (dir == 4) { x2 += k; y2 += i; z2 += j; } if (dir == 5) { x2 += k; y2 += j; z2 += i; } solution[x2][y2][z2] = c; freeSpace--; } } } taken[c]++; return true; }
{ "domain": "codereview.stackexchange", "id": 45222, "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": "java, backtracking, box-puzzle", "url": null }
java, backtracking, box-puzzle void remove(final int c, final int x, final int y, final int z, final int dir) { int[] a = candidates[c]; for (int i = 0; i < a[0]; i++) { for (int j = 0; j < a[1]; j++) { for (int k = 0; k < a[2]; k++) { int x2 = x; int y2 = y; int z2 = z; if (dir == 0) { x2 += i; y2 += j; z2 += k; } if (dir == 1) { x2 += i; y2 += k; z2 += j; } if (dir == 2) { x2 += j; y2 += i; z2 += k; } if (dir == 3) { x2 += j; y2 += k; z2 += i; } if (dir == 4) { x2 += k; y2 += i; z2 += j; } if (dir == 5) { x2 += k; y2 += j; z2 += i; } solution[x2][y2][z2] = empty; freeSpace++; } } } taken[c]--; } boolean isSolution() { return freeSpace <= 0; } boolean hasSolution() { return freeSpace > 0; }
{ "domain": "codereview.stackexchange", "id": 45222, "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": "java, backtracking, box-puzzle", "url": null }
java, backtracking, box-puzzle boolean hasSolution() { return freeSpace > 0; } boolean solve(final int c, final int n) { if (c >= candidates.length || n >= max || !hasSolution()) { return false; } for (int i = 0; i < len; i++) { for (int j = 0; j < len; j++) { for (int k = 0; k < len; k++) { if (c == 2) { // take a abbreviation if (insert(c, i, j, k, 0)) { if (isSolution()) { return true; } if (hasSolution() && (solve(c, n + 1) || solve(c + 1, 0))) { return true; } remove(c, i, j, k, 0); } } else { // take all directions for (int d = 0; d < 6; d++) { if (insert(c, i, j, k, d)) { if (isSolution()) { return true; } if (hasSolution() && (solve(c, n + 1) || solve(c + 1, 0))) { return true; } remove(c, i, j, k, d); } } } } } } return false; }
{ "domain": "codereview.stackexchange", "id": 45222, "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": "java, backtracking, box-puzzle", "url": null }
java, backtracking, box-puzzle public static void main(final String[] args) { for (int n = 25; n >= 21; n--) { System.out.println("n = " + n); Box box = new Box(n, true); System.out.println(box.isSolution()); System.out.println(Arrays.toString(box.taken)); System.out.println(Arrays.deepToString(box.solution)); } // The problematic cases: { int n = 20; System.out.println("n = " + n); Box box = new Box(n, true); System.out.println(box.isSolution()); System.out.println(Arrays.toString(box.taken)); System.out.println(Arrays.deepToString(box.solution)); } for (int n = 1; n <= 6; n++) { System.out.println("n = " + n); Box box = new Box(n, true); System.out.println(box.isSolution()); System.out.println(Arrays.toString(box.taken)); System.out.println(Arrays.deepToString(box.solution)); } } } Answer: simple constructor In my opinion this ctor is doing too much: Box( ... ) { ... solve(0, 0); } The class invariant appears to be: "We always have a valid solved cube." Or put another way, there is no invariant we can reason about for most of this code, because it executes prior to completion of the ctor. Worse, solve could potentially return False, which we ignore, so caller could get almost anything back. Just leave the final solve call out, let the caller worry about that. Having an unsolved instance that unit tests can pass around can be very helpful during initial development. Then you'd be able to add automated unit tests to this submission. problem statement An additional "magic" box with the dimensions 1x1x1 ... if (withMagicCuboid) { ... taken[2]++;
{ "domain": "codereview.stackexchange", "id": 45222, "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": "java, backtracking, box-puzzle", "url": null }
java, backtracking, box-puzzle if (withMagicCuboid) { ... taken[2]++; My interpretation of the problem is we're free to place five tiny cubes anywhere we want, and the magic one is a sixth cube with constrained position. So I wouldn't bump the taken count here. meaningful identifiers The constructor accepts a max parameter, which could be a fine name. But you really need to /** tell us */ what it means. boolean solve(final int c, final int n) { That is the wrong signature to offer a reviewer. Both numbers are super important, and you haven't told a reviewer how to interpret them, what they mean. You absolutely positively need to add at least one sentence of /** javadoc */ to this method. Consider renaming c to some longer abbreviation or perhaps go all the way to candidate. Perhaps n describes our current level within the search tree? if (c == 2) { // take a abbreviation It's unclear why we need to special case this. Explaining why would be a helpful comment. Maybe it's a symmetry argument? Which leaves me wondering if other candidates exhibit relevant symmetries. Rather than a hardcoded magic index of "candidate number two" here, you might prefer to special case on "volume == 1". // take all directions Thank you for helpfully pointing out that d denotes "direction". Consider renaming to dir. Aha! I see you did that down in insert. May as well do it up in the caller, as well. Defining hasSolution to be not isSolution is surprising. Consider renaming to isNotSolved, isUnsolved, or isSolvable. linear algebra Yikes! This is tedious. if (dir == 0) { ... if (dir == 1) { ... if (dir == 2) { ... if (dir == 3) { ... if (dir == 4) { ... if (dir == 5) {
{ "domain": "codereview.stackexchange", "id": 45222, "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": "java, backtracking, box-puzzle", "url": null }
java, backtracking, box-puzzle We see 3! permuations of the 3 coordinate axes. Representing direction as a single small integer turned out to be inconvenient. An alternative representation would show it as a unit vector pointing along one of the axes: {0, 0, 1}, {0, 1, 0}, {1, 0, 0}, perhaps with another three pointing in the negative direction, or more cleanly by using a ±1 coefficient to show we're going the other way. Alternatively you might list the three (or six) cases with permutations of {0, 1, 2} axis indices instead of permuting {i, j, k} variables. if (dir == 0) { ... if (dir == 1) { ... if (dir == 2) { ... if (dir == 3) { ... if (dir == 4) { ... if (dir == 5) { zomg we're doing it again?!? It seems pretty clear that we really want a helper here, which accepts a 3-space Point plus a direction, and returns the desired {x2, y2, z2} Point. remove would use the same helper, so it's no longer copy-pasta taken from insert. single responsibility insert does two things: check whether candidate in given orientation will fit at all place the candidate Break out at least one helper to reflect that. debugability solution[x2][y2][z2] = c;
{ "domain": "codereview.stackexchange", "id": 45222, "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": "java, backtracking, box-puzzle", "url": null }
java, backtracking, box-puzzle debugability solution[x2][y2][z2] = c; Certainly this is correct. It doesn't seem very convenient. Any value besides empty would do. Suppose solve returns a solution to your colleague, or to a unit test. Each of them is playing the role of Verifier. Why should the Verifier believe the solution is accurate? Both verification and graphical display would be much easier if we wrote a distinct value for each piece placed. We could associate 18 indexes with our six + six + six pieces. Or we could use (candidateType, candidateSerialNumber) tuples. Alternate representations of a tuple include array of complex numbers, and array of floats where integer portion denotes serial number and decimal fraction denotes type. algorithm Consider choosing a random candidate oriented in a random direction at each step. It would be helpful to be able to prove theorems about a puzzle in progress. For example, if an empty slab will require 1 x ... pieces to fill it, and its volume exceeds total volume of such pieces that remain, then we know it's time to backtrack. Keeping track of occupancy, the fraction full, at each of five layers may help prioritize using appropriate piece. Early on we see low occupancy and anything goes. With more pieces placed, it becomes increasingly important that a placed piece should exactly fit so it goes all the way to the 5x5x5 boundary. "Volume remaining", the empty volume, would be an admissible heuristic for A* search. This code achieves many of its design goals. I would be willing to delegate or accept maintenance tasks on it.
{ "domain": "codereview.stackexchange", "id": 45222, "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": "java, backtracking, box-puzzle", "url": null }
python-3.x, datetime Title: Python: Return list of keys if current time is within the range Question: This is the program I have written to return the list of keys if the current hour is present within the range provided. # time_mapping has data in key:value pair # where value consists of time range in 24 Hr format. # For key 'abc', the time range is 6AM (i.e. 6) to 3PM (i.e. 15) # For key 'def', the time range is 2PM (i.e. 14) to 11PM (i.e. 23) # For key 'pqr', the time range is 5PM (i.e. 17) to 2AM (i.e. 2) # For key 'xyz', the time range is 10PM (i.e. 22) to 7AM (i.e. 7) time_mapping = {'abc': ((6,), (15,)), 'def': ((14,), (23,)), 'pqr': ((17, 24), (0, 2)), 'xyz': ((22, 24), (0, 7))} def get_keys(current_time_in_hr): list_of_keys = [] for key, time_range in time_mapping.items(): if len(time_range[0]) == 1 and len(time_range[1]) == 1: if time_range[0][0] <= int(current_time_in_hr) < time_range[1][0]: list_of_keys.append(key) elif len(time_range[0]) == 2 and len(time_range[1]) == 2: if (time_range[0][0] <= int(current_time_in_hr) < time_range[0][1]) \ or (time_range[1][0] <= int(current_time_in_hr) < time_range[1][1]): list_of_keys.append(key) return list_of_keys if __name__ == "__main__": current_hour = datetime.now().strftime("%H") # if 15 print(get_keys(current_hour)) # Then print ['def', 'pqr'] Basically, if the current hour is 2 PM i.e. 14 then it will return ['abc', 'def']. Well, the program works but I am not happy the way I have written it. I will be glad if someone can review it and share some pointers with me to improve it. Thank you.
{ "domain": "codereview.stackexchange", "id": 45223, "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-3.x, datetime", "url": null }
python-3.x, datetime Answer: time_mapping is data lasagna. Whereas it's good that you've added documentation, it's not enough - the elements are still untyped. The more helpful thing to do is represent it as a simple sequence (immutable tuple) of well-typed, immutable class instances (NamedTuple is easiest). Representing it as a dictionary is not useful because you never actually perform a key lookup. get_keys should probably not accept a current time in hours as an integer, but instead, a datetime.time. It can be further simplified by acting as an iterator instead of materializing a list. Don't hard-code for the two cases with either one or two ranges. Instead, just code for an arbitrary number of ranges. Don't strftime to get the hour from a datetime. Suggested import datetime from typing import NamedTuple, Iterator class TimePair(NamedTuple): key: str hour_ranges: tuple[range] @classmethod def from_hours(cls, key: str, start: int, end: int) -> 'TimePair': """ :param key: Passed verbatim to TimePair.key :param start: Starting hour, inclusive. :param end: Ending hour, inclusive. If the next day, implies two ranges. """ if start <= end: ranges = (range(start, 1 + end), ) else: ranges = (range(start, 24), range(0, 1 + end)) return cls(key, ranges) def __contains__(self, time: datetime.time) -> bool: return any(time.hour in trange for trange in self.hour_ranges) time_mapping = ( TimePair.from_hours('abc', 6, 15), TimePair.from_hours('def', 14, 23), TimePair.from_hours('pqr', 17, 2), TimePair.from_hours('xyz', 22, 7), ) def get_keys(current_time: datetime.time) -> Iterator[str]: for tmap in time_mapping: if current_time in tmap: yield tmap.key def main() -> None: time = datetime.datetime.now().time() for key in get_keys(time): print(key) if __name__ == '__main__': main()
{ "domain": "codereview.stackexchange", "id": 45223, "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-3.x, datetime", "url": null }
python-3.x, datetime if __name__ == '__main__': main() Indexing Depending on a lot of things, it may be worthwhile collapsing the time mapping to an index sequence. This will accelerate lookup at the cost of a small amount of memory and a small amount of startup time: import datetime from collections import defaultdict from typing import NamedTuple, Iterable class TimePair(NamedTuple): key: str hour_ranges: tuple[range] @classmethod def from_hours(cls, key: str, start: int, end: int) -> 'TimePair': """ :param key: Passed verbatim to TimePair.key :param start: Starting hour, inclusive. :param end: Ending hour, inclusive. If the next day, implies two ranges. """ if start <= end: ranges = (range(start, 1 + end), ) else: ranges = (range(start, 24), range(0, 1 + end)) return cls(key, ranges) def __contains__(self, time: datetime.time) -> bool: return any(time.hour in trange for trange in self.hour_ranges) def make_index(time_mapping: Iterable[TimePair]) -> tuple[str]: index = tuple([] for _ in range(24)) for tmap in time_mapping: for trange in tmap.hour_ranges: for hour in trange: index[hour].append(tmap.key) return index time_mapping = ( TimePair.from_hours('abc', 6, 15), TimePair.from_hours('def', 14, 23), TimePair.from_hours('pqr', 17, 2), TimePair.from_hours('xyz', 22, 7), ) time_index = make_index(time_mapping) def get_keys(current_time: datetime.time) -> list[str]: return time_index[current_time.hour] def main() -> None: time = datetime.datetime.now().time() for key in get_keys(time): print(key) if __name__ == '__main__': main()
{ "domain": "codereview.stackexchange", "id": 45223, "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-3.x, datetime", "url": null }
python-3.x, datetime if __name__ == '__main__': main() time_index looks like (['pqr', 'xyz'], ['pqr', 'xyz'], ['pqr', 'xyz'], ['xyz'], ['xyz'], ['xyz'], ['abc', 'xyz'], ['abc', 'xyz'], ['abc'], ['abc'], ['abc'], ['abc'], ['abc'], ['abc'], ['abc', 'def'], ['abc', 'def'], ['def'], ['def', 'pqr'], ['def', 'pqr'], ['def', 'pqr'], ['def', 'pqr'], ['def', 'pqr'], ['def', 'pqr', 'xyz'], ['def', 'pqr', 'xyz'])
{ "domain": "codereview.stackexchange", "id": 45223, "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-3.x, datetime", "url": null }
php, strings, file, html5, network-file-transfer Title: Image file uploader webpage in HTML5 and PHP Question: I am trying to make a webpage for uploading an image file and storing the uploaded file on server. There are several features in this implementation: There is a drag & drop zone on the webpage. You can drag the file to be uploaded to this zone and drop. Also, you can click this zone and select the file to be uploaded. After selecting a file, you can check the selected filename on the webpage. Finally, you can click "Upload To Server" button to perform the upload process. There is a progress bar for displaying the upload progress. On the server side, the uploaded files are placed in folder /var/www/html/uploads/ and filenames are updated with $date_time prefix. The experimental implementation index.html: main page for selecting and uploading file <!DOCTYPE html> <html> <head> <style> html { font-family: sans-serif; } div#drop_zone { height: 400px; width: 400px; border: 2px dotted black; display: flex; justify-content: center; flex-direction: column; align-items: center; font-family: monospace; } </style> </head> <body> <h2>Upload File Page</h2> <!╌ https://stackoverflow.com/a/14806776/6667035 ╌> <input type="file" name="file_to_upload" id="file_to_upload" accept=".bmp, .jpg, .png" style="display: none;" multiples> <h3>Drag & Drop a File</h3> <div id="drop_zone"> DROP HERE </div> <hr> Selected filename: <p id="file_name"></p> <progress id="progress_bar" value="0" max="100" style="width:400px;"></progress> <p id="progress_status"></p> <input type="button" value="Upload To Server" id="upload_file_button">
{ "domain": "codereview.stackexchange", "id": 45224, "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": "php, strings, file, html5, network-file-transfer", "url": null }
php, strings, file, html5, network-file-transfer <script type="text/javascript"> document.getElementById('file_to_upload').addEventListener('change', (event) => { window.selectedFile = event.target.files[0]; document.getElementById('file_name').innerHTML = window.selectedFile.name; }); document.getElementById('upload_file_button').addEventListener('click', (event) => { // Reference: https://stackoverflow.com/a/154068/6667035 if (document.getElementById('file_name').innerHTML === "") { // Reference: https://stackoverflow.com/a/10462885/6667035 var check = confirm("Please select a file!"); if (check == true) { return true; } else { return false; } } else { uploadFile(window.selectedFile); } }); const dropZone = document.getElementById('drop_zone'); //Getting our drop zone by ID dropZone.addEventListener("click", drop_zone_on_click); // Regist on click event if (window.FileList && window.File) { dropZone.addEventListener('dragover', event => { event.stopPropagation(); event.preventDefault(); event.dataTransfer.dropEffect = 'copy'; //Adding a visual hint that the file is being copied to the window }); dropZone.addEventListener('drop', event => { event.stopPropagation(); event.preventDefault(); const files = event.dataTransfer.files; //Accessing the files that are being dropped to the window window.selectedFile = files[0]; //Getting the file from uploaded files list (only one file in our case) document.getElementById('file_name').innerHTML = window.selectedFile.name; //Assigning the name of file to our "file_name" element }); }
{ "domain": "codereview.stackexchange", "id": 45224, "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": "php, strings, file, html5, network-file-transfer", "url": null }
php, strings, file, html5, network-file-transfer // ---- function definition ---- async function drop_zone_on_click(){ //document.getElementById('input_file').click(); let files = await selectFile("image/*", true); window.selectedFile = files[0]; document.getElementById('file_name').innerHTML = files[0].name; } // Reference: https://stackoverflow.com/a/52757538/6667035 function selectFile (contentType, multiple){ return new Promise(resolve => { let input = document.createElement('input'); input.type = 'file'; input.multiple = multiple; input.accept = contentType; input.onchange = _ => { let files = Array.from(input.files); if (multiple) resolve(files); else resolve(files[0]); }; input.click(); }); } function uploadFile(file) { var formData = new FormData(); formData.append('file_to_upload', file); var ajax = new XMLHttpRequest(); ajax.upload.addEventListener("progress", progressHandler, false); ajax.open('POST', 'uploader.php', true); ajax.send(formData); } function progressHandler(event) { var percent = (event.loaded / event.total) * 100; document.getElementById("progress_bar").value = Math.round(percent); document.getElementById("progress_status").innerHTML = Math.round(percent) + "% uploaded"; } </script> </body> </html>
{ "domain": "codereview.stackexchange", "id": 45224, "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": "php, strings, file, html5, network-file-transfer", "url": null }
php, strings, file, html5, network-file-transfer </html> uploader.php: performing the storing files in the back-end. <?php $file_name = $_FILES["file_to_upload"]["name"]; $uploaddir = '/var/www/html/uploads/'; // Reference: https://stackoverflow.com/a/8320892/6667035 // Reference: https://stackoverflow.com/a/18929210/6667035 // Reference: https://stackoverflow.com/a/27961373 $time = date("Y-m-d_H-i-s_"); $file_name_on_server = $uploaddir . $time . basename($file_name); $file_temp_location = $_FILES["file_to_upload"]["tmp_name"]; if (!$file_temp_location) { echo "ERROR: No file has been selected"; exit(); } if ($_FILES["file"]["error"] > 0) { echo "Return Code: " . $_FILES["file"]["error"] . "<br />"; exit(); } if(move_uploaded_file($file_temp_location, $file_name_on_server)){ echo "$file_name upload is complete"; // Reference: https://www.php.net/manual/en/function.system.php $last_line = system('ls', $retval); } else { echo 'Error code' . $_FILES['file_to_upload']['error'] . '<br/>'; echo "A server was unable to move the file"; } return NoContent(); ?> The webpage screenshot All suggestions are welcome. Answer: Back end code Add file type checking As this comment on PHP.net mentions: A note of security: Don't ever trust $_FILES["image"]["type"]. It takes whatever is sent from the browser, so don't trust this for the image type. I recommend using finfo_open (http://www.php.net/manual/en/function.finfo-open.php) to verify the MIME type of a file. It will parse the MAGIC in the file and return it's type...this can be trusted (you can also use the "file" program on Unix, but I would refrain from ever making a System call with your PHP code...that's just asking for problems).
{ "domain": "codereview.stackexchange", "id": 45224, "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": "php, strings, file, html5, network-file-transfer", "url": null }
php, strings, file, html5, network-file-transfer The front-end code uses the accept attribute on the file input, however that does not prevent a user from submitting the form with a file of another type. A user could modify the HTML using a browser console or change the file selector interface to show all files instead of image files - see the animation below for a demonstration. I was able to change the interface to allow selecting a file of any type both in Mac OS and Windows. The request to the back-end could also be made from another page or a tool like cURL, Postman, etc. finfo_open() can be used to ensure the uploaded file is an image, though there is a simpler solution in this review using exif_imagetype(). Unused variables can be removed The implementation of NoContent is not included so we can only guess at what it does. Unless it uses $last_line or $retval then those variables can be eliminated. Brace styles are inconsistent There are three if statements. The block for the second one has the curly brace starting on a new line. Perhaps this is a familiar pattern in other programming languages but idiomatic PHP typically only has braces on the same line after an if statement. One is not required to follow a style guide but a popular one for PHP is PSR-12. Section 5.1 covers if statements. Front end code Please promise to remove excess promises It is nice that the code uses async and await along with dynamic creation of the <input> element, however that isn't necessary. The click method can be called in the hidden file input. It appears an attempt may have been made to achieve this, given the first line within drop_zone_on_click. That commented line appears to reference an element that does not have an id attribute with value input_file. A reference could be stored for the hidden file input: const file_upload_element = document.getElementById('file_to_upload'); Then the click event listener could be added to the drop zone: dropZone.addEventListener("click", () => file_upload_element.click());
{ "domain": "codereview.stackexchange", "id": 45224, "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": "php, strings, file, html5, network-file-transfer", "url": null }
php, strings, file, html5, network-file-transfer The event listener could also be added using the function bind() method: dropZone.addEventListener("click", file_upload_element.click.bind(file_upload_element)); Then functions drop_zone_on_click and selectFile can be eliminated. Logic can be simplified Above the line where check is declared in the event handler callback for the element with id upload_file_button there is a reference to a Stack Overflow answer: // Reference: https://stackoverflow.com/a/10462885/6667035 var check = confirm("Please select a file!"); That answer has multiple comments. You can replace if(check == true) with if(check). – Anonymous Apr 1, 2020 at 21:05 please just return confirm("Are you sure you want to leave?"); and save 6 lines. – Florian F Jun 15 at 12:35 Both comments are valid. Then again the return value from the call to confirm is not really used. One could simply use alert() instead of confirm(), then simply have a return statement with no return value. As explained in this review some users could disable alerts in a browser setting so a different technique like using the HTML5 <dialog> element. Attribute multiples can be removed from file input The file input has an attribute multiples specified. Such an attribute does not exist though there is a multiple attribute that could be applied. The code simply uploads a single file so it does not seem like there is any use for that attribute.
{ "domain": "codereview.stackexchange", "id": 45224, "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": "php, strings, file, html5, network-file-transfer", "url": null }
java Title: FieldInspector: an API for deep object comparison and null checking Question: Here's my FieldInspector. It compares objects by field values and performs deep null checking. What do you think? It works, but I'm not happy with how it looks. I don't believe it's an example of clean code. How can I improve it? That "memorizing" was my solution to cyclic dependencies. Otherwise, you get StackOverflowError when jumping back and forth from one element in an object graph to another package by.afinny.credit.unit.testUtil; import by.afinny.credit.testUtil.fieldInspector.BasicFieldInspector; import by.afinny.credit.testUtil.fieldInspector.FieldInspector; import lombok.NoArgsConstructor; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.math.BigDecimal; import java.math.RoundingMode; import java.util.Collections; import java.util.Set; import static org.assertj.core.api.AssertionsForClassTypes.assertThat; class BasicFieldInspectorTest { private FieldInspector fieldInspector; @BeforeEach void setUp() { fieldInspector = new BasicFieldInspector(); } @Test void testIsFullyInitialized_withoutDeepInspection() { ClassA classA = new ClassA(); classA.string = "test string"; classA.bigDecimal = BigDecimal.ONE; classA.classB = new ClassB(); assertThat(fieldInspector.isFullyInitialized(classA)).isTrue(); } @Test void testIsFullyInitialized_withDeepInspection_withoutFullInitialization() { fieldInspector.setDeepInspectionCandidates(Set.of(ClassB.class)); ClassA classA = new ClassA(); classA.string = "test string"; classA.bigDecimal = BigDecimal.ONE; classA.classB = new ClassB(); assertThat(fieldInspector.isFullyInitialized(classA)).isFalse(); }
{ "domain": "codereview.stackexchange", "id": 45225, "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": "java", "url": null }
java assertThat(fieldInspector.isFullyInitialized(classA)).isFalse(); } @Test void testIsFullyInitialized_withDeepInspection_withFullInitialization_cyclicDependenciesResolved() { fieldInspector.setDeepInspectionCandidates(Set.of(ClassB.class)); ClassA classA = new ClassA(); classA.string = "classA test string"; classA.bigDecimal = BigDecimal.ONE; ClassB classB = new ClassB(); classB.string = "classB test string"; classB.bigDecimal = BigDecimal.TEN; classB.classA = classA; classA.classB = classB; assertThat(fieldInspector.isFullyInitialized(classA)).isTrue(); } @Test void testIsFullyInitialized_withDeepInspection_afterMethodInvocation_cacheInvalidated() { fieldInspector.setDeepInspectionCandidates(Set.of(ClassA.class, ClassB.class)); ClassA classA = new ClassA(); classA.string = "classA test string"; classA.bigDecimal = BigDecimal.ONE; ClassB classB = new ClassB(); classB.string = "classB test string"; classB.bigDecimal = BigDecimal.TEN; classB.classA = classA; classA.classB = classB; assertThat(fieldInspector.isFullyInitialized(classA)).isTrue(); classA.string = null; assertThat(fieldInspector.isFullyInitialized(classB)).isFalse(); } @Test void testDoHaveEqualFields_withoutDeepInspection() { ClassB classB = new ClassB(); ClassA classA = new ClassA(); classA.string = "classA test string"; classA.bigDecimal = BigDecimal.ONE; classA.classB = classB; ClassB anotherClassB = new ClassB(); ClassA anotherClassA = new ClassA(); anotherClassA.string = "classA test string"; anotherClassA.bigDecimal = BigDecimal.ONE; anotherClassA.classB = anotherClassB; assertThat(fieldInspector.doHaveEqualFields(classA, anotherClassA)).isFalse(); }
{ "domain": "codereview.stackexchange", "id": 45225, "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": "java", "url": null }
java assertThat(fieldInspector.doHaveEqualFields(classA, anotherClassA)).isFalse(); } @Test void testDoHaveEqualFields_withoutDeepInspection_comparesBigDecimalsIgnoringScaleByDefault() { ClassA classA = new ClassA(); classA.bigDecimal = BigDecimal.ONE.setScale(1, RoundingMode.HALF_UP); ClassA anotherClassA = new ClassA(); anotherClassA.bigDecimal = BigDecimal.ONE.setScale(2, RoundingMode.HALF_UP); assertThat(fieldInspector.doHaveEqualFields(classA, anotherClassA)).isTrue(); } @Test void testDoHaveEqualFields_withoutDeepInspection_withDefaultOverridden_comparesBigDecimalsWithScale() { fieldInspector.setClassesWithCustomEqualityChecks(Collections.emptyMap()); ClassA classA = new ClassA(); classA.bigDecimal = BigDecimal.ONE.setScale(1, RoundingMode.HALF_UP); ClassA anotherClassA = new ClassA(); anotherClassA.bigDecimal = BigDecimal.ONE.setScale(2, RoundingMode.HALF_UP); assertThat(fieldInspector.doHaveEqualFields(classA, anotherClassA)).isFalse(); } @Test void testDoHaveEqualFields_withDeepInspection_withEqualFields() { fieldInspector.setDeepInspectionCandidates(Set.of(ClassB.class)); ClassB classB = new ClassB(); ClassA classA = new ClassA(); classA.string = "classA test string"; classA.bigDecimal = BigDecimal.ONE; classA.classB = classB; ClassB anotherClassB = new ClassB(); ClassA anotherClassA = new ClassA(); anotherClassA.string = "classA test string"; anotherClassA.bigDecimal = BigDecimal.ONE; anotherClassA.classB = anotherClassB; assertThat(fieldInspector.doHaveEqualFields(classA, anotherClassA)).isTrue(); } @Test void testDoHaveEqualFields_withDeepInspection_withUnequalFields() { fieldInspector.setDeepInspectionCandidates(Set.of(ClassB.class));
{ "domain": "codereview.stackexchange", "id": 45225, "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": "java", "url": null }
java ClassB classB = new ClassB(); classB.string = "classB test string"; ClassA classA = new ClassA(); classA.string = "classA test string"; classA.bigDecimal = BigDecimal.ONE; classA.classB = classB; ClassB anotherClassB = new ClassB(); anotherClassB.string = "another classB test string"; ClassA anotherClassA = new ClassA(); anotherClassA.string = "classA test string"; anotherClassA.bigDecimal = BigDecimal.ONE; anotherClassA.classB = anotherClassB; assertThat(fieldInspector.doHaveEqualFields(classA, anotherClassA)).isFalse(); } @Test void testDoHaveEqualFields_withDeepInspection_withEqualFields_cyclicDependenciesResolved() { fieldInspector.setDeepInspectionCandidates(Set.of(ClassB.class)); ClassB classB = new ClassB(); ClassA classA = new ClassA(); classA.classB = classB; ClassA anotherClassA = new ClassA(); anotherClassA.classB = classB; classB.classA = classA; assertThat(fieldInspector.doHaveEqualFields(classA, anotherClassA)).isTrue(); } @Test void testDoHaveEqualFields_withDeepInspection_withEqualFields_afterMethodInvocation_cacheInvalidated() { fieldInspector.setDeepInspectionCandidates(Set.of(ClassA.class, ClassB.class)); ClassB classB = new ClassB(); ClassA classA = new ClassA(); classA.classB = classB; classB.classA = classA; ClassB anotherClassB = new ClassB(); ClassA anotherClassA = new ClassA(); anotherClassA.classB = anotherClassB; anotherClassB.classA = anotherClassA; assertThat(fieldInspector.doHaveEqualFields(classA, anotherClassA)).isTrue(); classB.string = "test string"; assertThat(fieldInspector.doHaveEqualFields(classA, anotherClassA)).isFalse(); }
{ "domain": "codereview.stackexchange", "id": 45225, "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": "java", "url": null }
java assertThat(fieldInspector.doHaveEqualFields(classA, anotherClassA)).isFalse(); } @NoArgsConstructor @SuppressWarnings("UnusedDeclaration") // to suppress "field never accessed" private static class ClassA { private String string; private BigDecimal bigDecimal; private ClassB classB; } @NoArgsConstructor @SuppressWarnings("UnusedDeclaration") // to suppress "field never accessed" private static class ClassB { private String string; private BigDecimal bigDecimal; private ClassA classA; } } package by.afinny.credit.testUtil.fieldInspector; import java.util.Map; import java.util.Set; import java.util.function.BiPredicate; public interface FieldInspector { <T> boolean doHaveEqualFields(T firstObject, T secondObject); void setDeepInspectionCandidates(Set<Class<?>> deepInspectionCandidates); void setClassesWithCustomEqualityChecks(Map<Class<?>, BiPredicate<Object, Object>> classesWithCustomEqualityChecks); <T> boolean isFullyInitialized(T generatedObject); } package by.afinny.credit.testUtil.fieldInspector; import by.afinny.credit.util.BigDecimalUtils; import org.springframework.util.ReflectionUtils; import java.lang.reflect.Field; import java.math.BigDecimal; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.function.BiPredicate; import java.util.stream.Stream; public class BasicFieldInspector implements FieldInspector { private final Set<Class<?>> deepInspectionCandidates; private final Map<Class<?>, BiPredicate<Object, Object>> classesWithCustomEqualityChecks; private final Set<Object> inspectedObjects = new HashSet<>(); private final Map<Object, Object> comparedPairs = new HashMap<>();
{ "domain": "codereview.stackexchange", "id": 45225, "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": "java", "url": null }
java public BasicFieldInspector() { this.deepInspectionCandidates = new HashSet<>(); this.classesWithCustomEqualityChecks = new HashMap<>(); classesWithCustomEqualityChecks.put(BigDecimal.class, (bd1, bd2) -> BigDecimalUtils.areEqual((BigDecimal) bd1, (BigDecimal) bd2)); } public BasicFieldInspector(Set<Class<?>> deepInspectionCandidates) { this.deepInspectionCandidates = deepInspectionCandidates; this.classesWithCustomEqualityChecks = new HashMap<>(); } @Override public void setDeepInspectionCandidates(Set<Class<?>> deepInspectionCandidates) { this.deepInspectionCandidates.clear(); this.deepInspectionCandidates.addAll(deepInspectionCandidates); } @Override public void setClassesWithCustomEqualityChecks(Map<Class<?>, BiPredicate<Object, Object>> classesWithCustomEqualityChecks) { this.classesWithCustomEqualityChecks.clear(); this.classesWithCustomEqualityChecks.putAll(classesWithCustomEqualityChecks); } @Override public <T> boolean isFullyInitialized(T object) { boolean isFullyInitialized = isFullyInitialized0(object); inspectedObjects.clear(); return isFullyInitialized; } private <T> boolean isFullyInitialized0(T object) { Set<Object> memorizedObjects = new HashSet<>(); for (Field field : object.getClass().getDeclaredFields()) { field.setAccessible(true); Object fieldValue = ReflectionUtils.getField(field, object); if (fieldValue == null) { return false; } if (shouldBeDeepInspected(fieldValue)) { memorizedObjects.add(fieldValue); } } inspectedObjects.add(object); for (Object memorizedObject : memorizedObjects) { if (!isFullyInitialized0(memorizedObject)) { return false; } } return true; }
{ "domain": "codereview.stackexchange", "id": 45225, "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": "java", "url": null }
java private boolean shouldBeDeepInspected(Object fieldValue) { return fieldValue != null && !inspectedObjects.contains(fieldValue) && deepInspectionCandidates.contains(fieldValue.getClass()); } @Override public <T> boolean doHaveEqualFields(T firstObject, T secondObject) { boolean doHaveEqualFields = doHaveEqualFields0(firstObject, secondObject); comparedPairs.clear(); return doHaveEqualFields; } private <T> boolean doHaveEqualFields0(T firstObject, T secondObject) { Map<Object, Object> memorizedPairs = new HashMap<>(); for (Field field : firstObject.getClass().getDeclaredFields()) { field.setAccessible(true); Object firstObjectFieldValue = ReflectionUtils.getField(field, firstObject); Object secondObjectFieldValue = ReflectionUtils.getField(field, secondObject); if (shouldBeCompared(firstObjectFieldValue, secondObjectFieldValue)) { if (deepInspectionCandidates.contains(field.getType())) { memorizedPairs.put(firstObjectFieldValue, secondObjectFieldValue); } else { if (areNotEqual(firstObjectFieldValue, secondObjectFieldValue)) { return false; } } } } comparedPairs.put(firstObject, secondObject); for (Map.Entry<Object, Object> pair : memorizedPairs.entrySet()) { if (!(doHaveEqualFields0(pair.getKey(), pair.getValue()))) { return false; } } return true; } private boolean shouldBeCompared(Object fieldValue, Object anotherFieldValue) { return !comparedPairs.containsKey(fieldValue) || !comparedPairs.get(fieldValue).equals(anotherFieldValue); }
{ "domain": "codereview.stackexchange", "id": 45225, "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": "java", "url": null }
java private <T> boolean areNotEqual(T firstObjectFieldValue, T secondObjectFieldValue) { if (firstObjectFieldValue == null && secondObjectFieldValue == null) { return false; } Class<?> type = Stream.of(firstObjectFieldValue, secondObjectFieldValue) .filter(Objects::nonNull) .findAny() .get() .getClass(); if (classesWithCustomEqualityChecks.containsKey(type)) { BiPredicate<Object, Object> customEquals = classesWithCustomEqualityChecks.get(type); return !customEquals.test(firstObjectFieldValue, secondObjectFieldValue); } else { return !Objects.equals(firstObjectFieldValue, secondObjectFieldValue); } } } package by.afinny.credit.util; import java.math.BigDecimal; public class BigDecimalUtils { private BigDecimalUtils() { } /** * Compares two instances of {@code BigDecimal} ignoring scale. If both instances * are {@code null}, returns true * * @return {@code true} if two decimals are equal, {@code false} otherwise */ public static boolean areEqual(BigDecimal firstDecimal, BigDecimal secondDecimal) { return (firstDecimal == null) ? (secondDecimal == null) : (secondDecimal != null) && (firstDecimal.compareTo(secondDecimal) == 0); } }
{ "domain": "codereview.stackexchange", "id": 45225, "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": "java", "url": null }
java Answer: The abstract method and fied naming with the lack of documentation makes the review quite difficult. Naming should describe their purpose accurately. My first guess about "deep inspection candidates" was that the name refers to objects that are to be inspected. I had to look at the type of the field to realize that it's the types that are to be inspected. That field should be renamed to typesToInspect. "Deep inspection candidate" feels like there was a subconcious desire to create fancy terminology. I've done it too and it's something a programmer should be aware of. Don't try to create unnecessary new names for things that can have mundane and easy to understand names. :) isFullyInitializded should be renamed to allFieldsAreNonNull or areAllFieldsNonNull because that's literally what the method does. Also, what "full initialization" means depends on the purpose of the class being inspected so in general you shouldn't automatically assume that a field being null makes an object uninitialized. "Memorized objects" doesn't tell why the objects are being memorized (memorizing is not a known computing term). A better term could be "referencesToBeInspected". You should extract the code that finds the references from an object into a separate method named private Set<Object> findReferencesToInspect(Object source). The set of already inspected objects doesn't need to be a class member. You can instantiate that set in isFullyInitialized and pass it as a parameter to the private recursive function. Keeping state in a class member makes the class thread unsafe and means you can't share an instance of your utility for example when running tests in parallel. And you don't have to worry about clearing the set (or worry about the memory leak that happens when the inspection fails with an exception and the set doesn't get cleared).
{ "domain": "codereview.stackexchange", "id": 45225, "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": "java", "url": null }
java The equality check and the null check should be split into separate classes (single responsibility principle). Separating these features makes the code easier to follow as the reader doesn't have to guess whichs fields and methods are related to which feature. Also you won't then be starting yet another big mess of utility methods. Those classes are a menace for maintenance. Names should not contain negations such as areNotEqual. Those lead to statements with duble negatives like if (! areNotEqual(...)) which are hard for humans to follow. So make it areEqual and if (! areEqual(...)).
{ "domain": "codereview.stackexchange", "id": 45225, "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": "java", "url": null }
algorithm, kotlin, heap Title: Dynamic Priority Heap - Kotlin Question: open class Heap<T>: Iterable<Heap.Data<T>> { data class Data<T>(val item: T, var priority: Int) { operator fun compareTo(other:Data<T>): Int { return priority - other.priority } } protected var positions = mutableMapOf<T, Int>() protected var data: Array<Data<T>?> protected var heap_size:Int = 0 override fun iterator(): Iterator<Heap.Data<T>> { return object : Iterator<Heap.Data<T>> { var index = 0 override fun hasNext() = index < heap_size override fun next() = data[index++]!! } } constructor() { data = arrayOfNulls(1) } private fun swap(a:Int, b:Int) { val tmp = data[a] data[a] = data[b] data[b] = tmp positions[data[a]!!.item] = a positions[data[b]!!.item] = b } private fun left(root: Int) = (2 * root) + 1 private fun right(root: Int) = (2 * root) + 2 private fun parent(root: Int) = (root - 1) / 2 fun insert(item: T, priority: Int) { insert(Data(item, priority)) } protected fun insert(item: Data<T>) { if (heap_size == data.size) data = resize_arr(data.size * 2) var index = heap_size change_val(index, item) heap_size++ } protected fun change_val(root: Int, new_val: Data<T>) { data[root] = new_val var index = root if (index != 0) { while (index != 0 && data[parent(index)]!! > data[index]!!) { swap(parent(index), index) index = parent(index) } } else positions[new_val.item] = root } fun pop(): Data<T>? { if (heap_size == 1) return data[--heap_size]!! if (heap_size == data.size / 4) { val new_size = if (data.size / 2 == 0) 2 else data.size / 2 data = resize_arr(new_size) }
{ "domain": "codereview.stackexchange", "id": 45226, "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": "algorithm, kotlin, heap", "url": null }
algorithm, kotlin, heap val root = data[0] data[0] = data[heap_size - 1] heap_size-- heapify(0) return root } private fun resize_arr(new_size: Int): Array<Data<T>?> { val new_arr = arrayOfNulls<Data<T>>(new_size) var index = 0 while (index < heap_size) { new_arr[index] = data[index] index++ } return new_arr } protected fun heapify(root: Int) { var left:Int var right:Int var min = root var _root = root while (true) { left = left(_root) right = right(_root) if (left < heap_size && data[left]!! < data[_root]!!) min = left if (right < heap_size && data[right]!! < data[min]!!) min = right if (min != _root) { swap(min, _root) _root = min min = _root continue } break } } fun change_priority(item: T, new_priority: Int) { val tmp = data[positions[item]!!]!! tmp.priority = new_priority data[positions[item]!!] = data[heap_size - 1] data[heap_size - 1] = null heap_size-- heapify(positions[item]!!) insert(tmp) } } fun main(args:Array<String>) { val min_heap = Heap<String>() min_heap.insert("A", 5) min_heap.insert("B", 6) min_heap.insert("C", 7) min_heap.change_priority("A", 8) min_heap.change_priority("C", 1) min_heap.insert("D", 0) println(min_heap.pop()) println(min_heap.pop()) println(min_heap.pop()) println(min_heap.pop()) } Output is: Data(item=D, priority=0) Data(item=C, priority=1) Data(item=B, priority=6) Data(item=A, priority=8)
{ "domain": "codereview.stackexchange", "id": 45226, "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": "algorithm, kotlin, heap", "url": null }
algorithm, kotlin, heap Am I doing this right? Is this implementation bad? Any helpful tips and tricks for this newbie? I wanted to implement a PriorityQueue that you can change values with. This is my attempt at it. Any feedback would be great. Answer: I am at a loss about the role of change values/change_val(), lack of in-code documentation contributing - there is KDoc. It may be due to not using the common names sift-up&sift-down. insert(item, priority) might check whether item already is in positions. This may be a good place to design and specify exceptions. In pop(), resize after decreasing size. In change_priority(), one could compare old and new priority and let the item stay in place, sift-up or sift-down accordingly. change_val() and heapify() do avoidable assignments of "the moving" Data to indices where it doesn't stay. You don't need continue in heapify(): if (min == _root) break swap(min, _root) _root = min min = _root But I think the loop termination indirect anyway: /** Set data and keep position */ private fun put(item:Data<T>?, at:Int) { data[at] = item positions[item!!.item] = at }
{ "domain": "codereview.stackexchange", "id": 45226, "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": "algorithm, kotlin, heap", "url": null }
algorithm, kotlin, heap protected fun heapify(root: Int) { var left = left(root) val sinking = data[root]!! // pick up var _root = root // an index to bubble up to // two conditions to quit looping: while (left < heap_size) { // 1: at leaf var min = left var minData = data[left]!! val right = right(_root) if (right < heap_size) { val rightData = data[right]!! if (rightData < minData) { min = right minData = rightData } } if (sinking <= minData) // 2: sunk deep enough break put(minData, _root) // bubble up _root = min left = left(_root) } if (root != _root) put(sinking, _root) // put down } Dynamic priority heap suggests removal as a useful extension.
{ "domain": "codereview.stackexchange", "id": 45226, "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": "algorithm, kotlin, heap", "url": null }
c#, wpf, sqlite Title: My Drawing Finder Question: I developed this application for the company I work for. It became increasingly challenging to locate drawings within the myriad of folders, especially when searching for the most up-to-date versions. I have another app that generates an index of files, boasting over 90 thousand entries. The index includes the name, format, path, and date of each file. The finder application reads this file, and when you input the part number of a drawing, it opens the desired format for you. I utilized SQLite to create the .db file for this purpose. I'm seeking feedback on this code—wondering if there are any potential improvements or if there's already a more efficient program available for the same task. using System; using System.Collections.Generic; using System.Data.SQLite; using System.Diagnostics; using System.IO; using System.Linq; using System.Windows; using System.Windows.Input; namespace Finder { public enum ErrorType { InvalidPartNumber, FilesNotFound, FolderNotFound, FailedToOpenFile, FailedToOpenFolder, OpenFolder, OpenFile } public partial class MainWindow : Window { public ICommand ClearInputFieldsCommand { get; } private const int minimum = 8; private string sourceDir; private FileSystemWatcher watcher; private SQLiteConnection connection; public MainWindow() { InitializeComponent(); ClearInputFieldsCommand = new RelayCommand(ClearInputFieldsButton); DataContext = this; string documentsPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); string folderPath = Path.Combine(documentsPath, "FinderDatabase"); Directory.CreateDirectory(folderPath); string sourceFileName = Path.GetFileName(@""); sourceDir = Path.Combine(folderPath, sourceFileName);
{ "domain": "codereview.stackexchange", "id": 45227, "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#, wpf, sqlite", "url": null }
c#, wpf, sqlite string sourceFilePath = @""; if (File.Exists(sourceDir)) { File.Delete(sourceDir); } File.Copy(sourceFilePath, sourceDir); string killFolder = @""; string killFile = "killkey.txt"; watcher = new FileSystemWatcher(killFolder, killFile); watcher.Created += WatcherCreated; watcher.EnableRaisingEvents = true; string killFilePath = Path.Combine(killFolder, killFile); if (File.Exists(killFilePath)) { Close(); } string connectionString = $"DataSource={sourceDir};Version=3;"; connection = new SQLiteConnection(connectionString, true); connection.Open(); } private void WatcherCreated(object sender, FileSystemEventArgs e) { if (e.Name == "killkey.txt") { Close(); } } private void btnAbrirArquivo_Click(object sender, RoutedEventArgs e) { string pesquisa = txtPesquisa.Text.Trim(); if (!IsValid(pesquisa)) { ShowPopup(ErrorType.InvalidPartNumber); return; } string[] extensoesSelecionadas = GetSelectedExtensions(); List<ArquivoEncontrado> arquivosEncontrados = BuscarArquivos(pesquisa, extensoesSelecionadas); if (arquivosEncontrados.Count > 0) { ArquivoEncontrado arquivoParaAbrir = arquivosEncontrados.OrderByDescending(arquivo => File.GetLastWriteTime(arquivo.Path)).First(); OpenFile(arquivoParaAbrir.Path); } else { ShowPopup(ErrorType.FilesNotFound); } } private bool IsValid(string query) { if (query.Length < minimum) { return false; }
{ "domain": "codereview.stackexchange", "id": 45227, "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#, wpf, sqlite", "url": null }
c#, wpf, sqlite foreach (char c in query) { if (!char.IsDigit(c) && c != '-') { return false; } } string[] parts = query.Split('-'); foreach (string part in parts) { if (!int.TryParse(part, out _)) { return false; } } return true; } private void btnAbrirPasta_Click(object sender, RoutedEventArgs e) { string pesquisa = txtPesquisa.Text.Trim(); if (!IsValid(pesquisa)) { ShowPopup(ErrorType.InvalidPartNumber); return; } string[] extensoesSelecionadas = GetSelectedExtensions(); List<ArquivoEncontrado> arquivoEncontrados = BuscarArquivos(pesquisa, extensoesSelecionadas); if (arquivoEncontrados.Count > 0) { string pastaParaAbrir = Path.GetDirectoryName(arquivoEncontrados[0].Path); OpenFolder(pastaParaAbrir); } else { ShowPopup(ErrorType.FolderNotFound); } } private string[] GetSelectedExtensions() { List<string> selectedExtensions = new List<string>(); if (chkPdf.IsChecked == true) selectedExtensions.Add(".pdf"); if (chkStp.IsChecked == true) selectedExtensions.Add(".stp"); if (chkDwg.IsChecked == true) selectedExtensions.Add(".dwg"); if (chkJt.IsChecked == true) selectedExtensions.Add(".jt"); return selectedExtensions.ToArray(); } private List<ArquivoEncontrado> BuscarArquivos(string pesquisa, string[] extensoesSelecionadas) { if (string.IsNullOrEmpty(pesquisa)) return new List<ArquivoEncontrado>();
{ "domain": "codereview.stackexchange", "id": 45227, "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#, wpf, sqlite", "url": null }
c#, wpf, sqlite List<ArquivoEncontrado> arquivosEncontrados = new List<ArquivoEncontrado>(); string connectionString = $"Data Source={sourceDir};Version=3;"; using (SQLiteConnection connection = new SQLiteConnection(connectionString, true)) { connection.Open(); string query = "SELECT Name, Extension, Path FROM Files WHERE Name LIKE @pesquisa AND Extension IN ({0})"; string extensionsPlaceholder = string.Join(",", extensoesSelecionadas.Select(e => $"'{e}'")); query = string.Format(query, extensionsPlaceholder); using (SQLiteCommand command = new SQLiteCommand(query, connection)) { command.Parameters.AddWithValue("@pesquisa", $"%{pesquisa}%"); using (SQLiteDataReader reader = command.ExecuteReader()) { while (reader.Read()) { string nomeArquivo = reader.GetString(0); string extensaoArquivo = reader.GetString(1); string caminhoArquivo = reader.GetString(2); arquivosEncontrados.Add(new ArquivoEncontrado { Name = nomeArquivo, Extension = extensaoArquivo, Path = caminhoArquivo, }); } } } } return arquivosEncontrados; }
{ "domain": "codereview.stackexchange", "id": 45227, "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#, wpf, sqlite", "url": null }
c#, wpf, sqlite private void OpenFile(string filePath) { try { using (Process process = new Process()) { process.StartInfo.FileName = filePath; process.StartInfo.UseShellExecute = true; process.Start(); } } catch (Exception ex) { ShowPopup(ErrorType.FailedToOpenFile, ex); } } private void OpenFolder(string folderPath) { try { using (Process process = new Process()) { process.StartInfo.FileName = "explorer.exe"; process.StartInfo.Arguments = $"/select, \"{SelectFile(folderPath)}\""; process.Start(); } } catch (Exception ex) { ShowPopup(ErrorType.FailedToOpenFolder, ex); } } private string SelectFile(string folderPath) { string pesquisa = txtPesquisa.Text.Trim(); string[] extensoesSelecionadas = GetSelectedExtensions(); List<ArquivoEncontrado> arquivoEncontrados = BuscarArquivos(pesquisa, extensoesSelecionadas); if (arquivoEncontrados.Count > 0) { if (Path.GetDirectoryName(arquivoEncontrados[0].Path) == folderPath) { return arquivoEncontrados[0].Path; } } return folderPath; } private void ShowPopup(ErrorType errorType, Exception exception = null) { string errorMessage = GetErrorMessage(errorType); string exceptionMessage = exception?.Message; PopupErro popup = new PopupErro(errorMessage + " " + exceptionMessage); popup.Owner = this; popup.ShowDialog(); }
{ "domain": "codereview.stackexchange", "id": 45227, "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#, wpf, sqlite", "url": null }
c#, wpf, sqlite private string GetErrorMessage(ErrorType errorType) { switch (errorType) { case ErrorType.InvalidPartNumber: return "Part number inválido."; case ErrorType.FilesNotFound: return "Arquivo não encontrado."; case ErrorType.FolderNotFound: return "Pasta não encontrada."; case ErrorType.FailedToOpenFile: return "Erro ao abrir o arquivo."; case ErrorType.FailedToOpenFolder: return "Erro ao abrir pasta."; default: return string.Empty; } } private void ClearInputFieldsButton() { txtPesquisa.Text = string.Empty; } public class RelayCommand : ICommand { private readonly Action _execute; public event EventHandler CanExecuteChanged; public RelayCommand(Action execute) { _execute = execute; } public bool CanExecute(object parameter) { return true; } public void Execute(object parameter) { _execute(); } } } public class ArquivoEncontrado { public string Name { get; set; } public string Extension { get; set; } public string Path { get; set; } } } Answer: informative identifier namespace Finder Maybe a bit on the vague side? Consider DrawingFinder or even FileFinder. private const int minimum = 8;
{ "domain": "codereview.stackexchange", "id": 45227, "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#, wpf, sqlite", "url": null }
c#, wpf, sqlite That's just super vague, it's unhelpful. Definitely rename to minimumQueryLength. Contrast it with some of your other name choices which were excellent, such as sourceDir. We don't appear to be using ALL_CAPS here for manifest constants. I assume that's what your project wants, that's fine. case ErrorType.FilesNotFound: return "Arquivo não encontrado."; It appears this enum should be singular: FileNotFound odd idiom It's unclear why you habitually write the empty string as @"", since there's no \ backwhack (or indeed any) characters where we need to worry about escaping. If you're trying to adhere to some coding standard that requires this, mention it in comments near the top, or in the project's ReadMe.md, or in Code Review context prose near top of posting. Prefer to write something informative like ELIDED if the source code you posted is deliberately censoring sensitive information which appeared in the original source code. Consider putting such strings in an .ini config file rather than using embedded hard-code values. pick a language Your "button open file click" callback inexplicably switches to Portuguese identifiers. Similarly down in btnAbrirPasta_Click, which should share code via a helper function rather than being copy-pasta code. Also BuscarArquivos and ArquivoEncontrado. Your project should have a ReadMe that describes which linter / prettyprinter we use, and what natural language we use for identifiers. During code review, revise proposed edits which don't conform to the project's policy. comments I found IsValid trickier to understand than necessary. At first blush it appears to be looking for integers. Eventually it becomes clear that the final loop is really looking for empty strings such as these invalid part numbers: -123-456 123--456 123-456-
{ "domain": "codereview.stackexchange", "id": 45227, "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#, wpf, sqlite", "url": null }
c#, wpf, sqlite -123-456 123--456 123-456- If you retain the code as written, tack on a comment which explains the why behind that final loop. Or have the code explicitly test for empty strings, rather than relying on integer parse of empty string to fail. (Or was there some other requirement here, like components shall be less than four billion? Then say it!) concise boolean expressions In GetSelectedExtensions prefer if (chkPdf.IsChecked), without the == True. frequent re-open of DB In BuscarArquivos, kudos on properly using bind variables in the query, so as to evade Little Bobby Tables. Perhaps we close and re-open the database more often than is desirable, discarding cached rows and parsed schemas more often than necessary. Consider opening the DB just once, either at app startup or upon initial query. Your SELECT query should have an ORDER BY clause, since it's the first result that will be opened. Also we like to see a stable order for reproducible results, though it appears the way you've structured your code it would be difficult to bolt on automated integration or unit tests. disabled index I assume you want to quickly retrieve one matching part number from 10**5 entries. The current SELECT uses leading % wildcard. So even if there's an index on Name, it won't be used. It's not like there's some full-text search feature of the backend that's being used here. Consider sticking with just a trailing % wildcard if your use case allows it, since that plays nicely with indexes. But suppose you do need it. Without resorting to creation of full-text search indexes, there's at least two ways to finesse this.
{ "domain": "codereview.stackexchange", "id": 45227, "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#, wpf, sqlite", "url": null }
c#, wpf, sqlite Issue an "easy" 1234-567% prefix query which might return early, and if no results then fall back to a "tablescan" %1234-567% retry query. Store a hundred million reversed part number strings in a ReversedName column, which is indexed. Let your suffix retry query exploit that index when it looks for 765-4321%. If that fails, final fall back is still that original double-percent tablescan. This codebase appears to achieve its design goals. It would benefit from an automated test suite, and reduced code duplication via extracting helpers. I would not be willing to accept maintenance tasks on it. I would be willing to delegate maintenance tasks to colleagues who have a working knowledge of both Portuguese and English.
{ "domain": "codereview.stackexchange", "id": 45227, "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#, wpf, sqlite", "url": null }
performance, algorithm, c, memory-management, mergesort Title: another Merge Sort Question: I've tried to implement merge sort in c with varying degrees of success, one was correctly sorting the array but leaking memory, one was neither sorting the array and leaking memory. The following was an attempt at implementing the algorithm again with these points in mind: Memory must be freed in the scope it was allocated Pointers must not be reassigned without freeing the memory it was pointing to. Is there any other good practices that I've missed to follow in my try? Are there any improvements that can be made in terms of readability, memory management, etc? #include <stddef.h> #include <stdio.h> #include <stdlib.h> #include <string.h> void merge(int *sorted_array, const int *left_array, const int *right_array, const size_t left_size, const size_t right_size) { size_t l = 0; size_t r = 0; size_t i = 0; while (l < left_size && r < right_size) { if (left_array[l] >= right_array[r]) { sorted_array[i++] = right_array[r++]; } else { sorted_array[i++] = left_array[l++]; } } if (l < left_size) { memcpy(sorted_array + i, left_array + l, sizeof(int) * (left_size - l)); } if (r < right_size) { memcpy(sorted_array + i, right_array + r, sizeof(int) * (right_size - r)); } } void merge_sort(int *sorted_array, const int *array, const size_t size) { if (size == 1) { memcpy(sorted_array, array, sizeof(int)); return; } const size_t middle = size / 2; int *left_sorted = malloc(sizeof(int) * middle); int *right_sorted = malloc(sizeof(int) * (size - middle)); merge_sort(left_sorted, array, middle); merge_sort(right_sorted, array + middle, (size - middle)); merge(sorted_array, left_sorted, right_sorted, middle, size - middle); free(left_sorted); free(right_sorted); } int main(void) { const int array[] = {1, 0, 2, 9, 3, 8, 4, 7, 5, 6}; int *sorted_array = malloc(sizeof(int) * (sizeof(array) / sizeof(int)));
{ "domain": "codereview.stackexchange", "id": 45228, "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": "performance, algorithm, c, memory-management, mergesort", "url": null }
performance, algorithm, c, memory-management, mergesort merge_sort(sorted_array, array, sizeof(array) / sizeof(int)); for (int i = 0; i < sizeof(array) / sizeof(int); i++) { printf("%d ", sorted_array[i]); } printf("\n"); free(sorted_array); return 0; } Answer: Three things pop out to me: This is not a stable sort. Probably does not matter, as you currently only support integers. This only support integer sorts. If you look at the standard qsort you will see it takes a function that allows you to sort elements of any type. Would be nice to extend your function in that direction (stable sort becomes more important). Memory management. Looks correct, but not optimal. The trouble is that you do a lot of malloc()/free() operations. You could allocate enough space at the top level and re-use that space in all your recursive calls. Just make sure different branches of the recursion use difference sections of the single allocated buffer.
{ "domain": "codereview.stackexchange", "id": 45228, "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": "performance, algorithm, c, memory-management, mergesort", "url": null }
python, python-3.x, mysql Title: delete rows based on references to other tables in a mysql database? Question: I have a database with the following hierarchy. A dataset can have multiple scans (foreign key scan.id_dataset -> dataset.id) A scan can have multiple labels (foreign key label.id_scan -> scan.id) A label has a labeltype (foreign key label.id_labeltype-> labeltype.id) The dataset, scan and labeltype tables all have a name column I want to delete a label based on the names of the dataset, scan and labeltype. Here is my working code using the python mysql-connector: def delete_by_labeltype( self, dataset_name: str, scan_name, labeltype_name: str ) -> int: sql = ( "DELETE l.* FROM label l " "INNER JOIN labeltype lt " "ON l.id_labeltype = lt.id " "WHERE lt.name = %s AND l.id_scan = (" " SELECT scan.id FROM scan " " INNER JOIN dataset " " ON dataset.id = scan.id_dataset " " WHERE scan.name = %s AND dataset.name = %s" ");" ) with self.connection.cursor() as cursor: cursor.execute( sql, ( labeltype_name, scan_name, dataset_name, ), ) self.connection.commit() return cursor.rowcount The function is within a class handling access to the label table so connection is already established (and later closed correctly). I am simply wondering if the query is the best way to do this, since I am not working with SQL too often.
{ "domain": "codereview.stackexchange", "id": 45229, "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, mysql", "url": null }
python, python-3.x, mysql Answer: nit: For consistency with scan.id I would choose the column name scan_id instead of id_scan, meh, whatever. Kudos on correctly using bind variables, keeping Little Bobby Tables out of your hair. The %s, %s, %s in the query don't seem especially convenient, for matching up against {label, scan, ds} names in a tuple. Prefer to use three distinct names, and pass in a dict. If you do that habitually, then when a query grows to mention half a dozen parameters, and some newly hired maintenance engineer adds a seventh one, you won't be sorry. And I like the explicit COMMIT. best way to do this? Looks good to me. I didn't hear you complaining about "too slow!" or reliability / flakiness. You didn't say that EXPLAIN PLAN showed some index was being ignored. Including an ERD entity-relationship diagram would have been helpful, or at least the CREATE TABLE DDL including FK definitions. Let me try to organize your prose. Here's what I heard. label --> labeltype label --> scan --> dataset
{ "domain": "codereview.stackexchange", "id": 45229, "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, mysql", "url": null }
python, python-3.x, mysql label --> labeltype label --> scan --> dataset It's not obvious to me why scan and dataset should be in a subquery rather than at same level -- it just arbitrarily came out that way, no biggie. The l.id_scan = ( fragment suggests to me that there's enough UNIQUE indexes on {scan, ds} name to ensure we get no more than one result row from the subquery, else you would have mentioned l.id_scan IN ( .... It's perfectly fine the way it is. Maybe JOIN label against labeltype and also against scan? (And then scan against ds.) If I was chicken, I would do all the JOINing in SELECT statements, obtain an id that I could do a sanity check on, and then send a simple DELETE single row command. But you're braver than me, and it works, so that's cool. When reasoning about complex JOINs I often find it convenient to bury some of the complexity behind a VIEW. Minimally you would want to define a scan_dataset_v view so you never have to type the name of the "dataset" table again. CREATE VIEW scan_dataset_v AS SELECT s.*, ds.* FROM scan s JOIN dataset ds ON ds.id = s.id_dataset; Now label has just two relationships to worry about. (And, the * stars probably have at least one conflicting column name -- just write them all out. Absent the DDL, I don't know what all the columns are.) You might possibly find it convenient to produce a view that JOINs them both to label, and another that JOINs labeltype to label. It just saves some typing during interactive queries. There's no efficiency hit -- think of it as the backend doing a macro expansion before issuing the query. Summary: Any improvements? Nope, not really, LGTM.
{ "domain": "codereview.stackexchange", "id": 45229, "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, mysql", "url": null }
c++, template-meta-programming, optional, duplicate-code Title: Partial specialization of class template with minimal code duplication Question: I have a class template that stores an std::optional<T>. A very reduced version of the class template looks like this: template <typename T> class param { public: param() = default; param(T const& t) : m_value(t) {} bool is_valid() const { return m_value.has_value(); } T const& value() const { if (!is_valid()) { /* snip */ assert(is_valid()); } return m_value.value(); } private: std::optional<T> m_value; }; Note that the class is meant for lazy evaluation and caching, so in the line containing the comment /* snip */ I omitted a bunch of code irrevelevant to my question. The point of the optional is that a param instance can be in a valid or invalid state and the valid state can be triggered via evaluation. Now I want the class template to work also with references. This is useful for instance if I want to lazily access a class member. Since std::optional does not allow the usage of references, I believe I need a partial specialization of param for T&. The partial specialization must store an std::optional<std::reference_wrapper<T>>. But this leads to a lot of code duplicaton, since I really only need to modify the constructor, one line in value and the member definition. Note that here I am showing just a minimal example. In production code, param has much more code, but even there I only need to modify a small percentage of the code in the partial specialization. template <typename T> class param<T&> { public: param() = default; param(T& t) : m_value(std::ref(t)) {} bool is_valid() const { return m_value.has_value(); } T const& value() const { if (!is_valid()) { /* snip */ assert(is_valid()); } return m_value.value().get(); } private: std::optional<std::reference_wrapper<T>> m_value; };
{ "domain": "codereview.stackexchange", "id": 45230, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, template-meta-programming, optional, duplicate-code", "url": null }
c++, template-meta-programming, optional, duplicate-code Live Code One way to avoid this unnecessary duplication of code is to use inheritence: template <typename T> class param<T&> : public param<std::reference_wrapper<T>> { using Base = param<std::reference_wrapper<T>>; public: param(T& t) : Base(std::ref(t)) {} T const& value() const { return Base::value().get(); } }; I explicitly did not add a virtual destructor to param<T>, because I want to avoid vtable lookups. I don't intent to ever use the specialization polymorphically. That being said, the class template is in the public API of the library and experience says that if you give a user the possiblity of doing something wrong, some user will eventually do something wrong. In addition, what happens if I add protected members to the unspecialized class template? So my questions regarding the above code are Are there any other (better?) approaches to supporting references and avoiding code duplication? Are there any pros and cons of the two approaches I listed that I have missed? Which way should I go? Addendum: Here is yet another option using if constexpr and std::conditional that does not require specialization at all. But IMHO overall the readibility suffers. template <typename T> class param { public: param() = default; param(T const& t) : m_value( [&](){ if constexpr (std::is_reference_v<T>){ return std::ref(t); } else { return t; } }() ) {} bool is_valid() const { return m_value.has_value(); } T const& value() const { if (!is_valid()) { /* snip */ assert(is_valid()); }
{ "domain": "codereview.stackexchange", "id": 45230, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, template-meta-programming, optional, duplicate-code", "url": null }
c++, template-meta-programming, optional, duplicate-code if constexpr (std::is_reference_v<T>) { return m_value.value().get(); } else { return m_value.value(); } } private: using CacheType = std::conditional_t< !std::is_reference_v<T>, std::optional<T>, std::optional<std::reference_wrapper<std::remove_reference_t<T>>> >; CacheType m_value; }; Godbolt link Answer: I would avoid inheritance and go for the implementation in the addendum. However, you can significantly simplify it: It's fine to unconditionally use std::ref() in the constructor. If T is not a reference, then temporarily making a std::reference_wrapper for it will not change how m_value is initialized. Similarly, you can unconditionally return m_value.value() in value(), since if it was a std::reference_wrapper, it will invoke the implicit operator T&() that is equivalent to calling .get(). You can hoist std::optional out of CacheType. In summary, you can rewrite your code as: template <typename T> class param { public: param() = default; param(T const& t) : m_value(std::ref(t)) {} bool is_valid() const { return m_value.has_value(); } T const& value() const { if (!is_valid()) { /* snip */ assert(is_valid()); } return m_value.value(); } private: using ValueType = std::conditional_t< !std::is_reference_v<T>, T, std::reference_wrapper<std::remove_reference<T>> >; std::optional<ValueType> m_value; }; The using statement is now the only extra line you had to write to support both values and references.
{ "domain": "codereview.stackexchange", "id": 45230, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, template-meta-programming, optional, duplicate-code", "url": null }
c, octree Title: Iterating the octree while keeping track of the positive neighboring nodes Question: Review context can be found here: 32x32x32 Units Octree With 15-Bit Voxels: Second Edition The above question and the self answer include information such as the definition of the Octree and Node8 data structures, MAX_LEVEL, DATA_MASK, and FLAG_MASK macros, and an overall description of this system. They only include an octree_get() function to query a node at a given location and octree_set() function to set a node in a given location. The only difference is that the base field of Octree is now in the beginning and not the end. But just for good measure I will include them here also: #include <stdlib.h> #include <string.h> #include <stdint.h> #include <assert.h> #include <stdio.h> #define FLAG_MASK 0x8000 #define DATA_MASK 0x7FFF #define MAX_LEVEL 5 #define node_to_set(ptr) ((Node8 *)((uintptr_t)(ptr)&-sizeof(Node8))) typedef union Node2 { uint16_t x[2]; uint32_t z; } Node2; typedef union Node4 { uint16_t x[4]; Node2 z[2]; uint64_t y; } Node4; typedef union Node8 { uint16_t x[8]; Node2 z[4]; Node4 y[2]; } Node8; typedef union Ptr { union Ptr *p; uint64_t u; } Ptr; typedef struct Octree { uint16_t base, data_size, set_size; uint8_t data_alloc, set_alloc; Ptr data; Node8 set[]; } Octree; The reason for the difference is so then an Octree pointer and the pointer to the base are the same and can be treated interchangeably. No need to initialize a new array with addresses of the base fields of the Octree pointers in octree_next because then octree_next can be used directly for this purpose.
{ "domain": "codereview.stackexchange", "id": 45231, "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, octree", "url": null }
c, octree I have created new code loosely based on the Iter() function in my even older question: 32x32x32 units octree, that supports 15-bit data units I have taken this a step further. Instead of simply descending each branch and printing out the value of each node, the descent process involves recording all the neighbors. The code should print not only the value of each node (3 times), but also the value of the node immediately to the East of (positive X-axis), to the North of (positive Z-axis), and above (positive Y-axis) then current node. I also included the xzy array to keep track of the spatial coordinates of the current node. More specifically, of the Southwest bottom corner of the node, where the North/East/upwards extent of the node is simply 32>>level. This is somewhat confusing, because in my previous question with the octree_get/octree_set() functions, level == 0 represents the bottom/most subdivided layer of the tree, and not the top/least subdivided layers. Note: next in identifiers in the code refers to 'neighboring.' They have similar meanings and the former is easier to type. The function itself is called octree_render() because iterating the structure while keeping track of the neighboring nodes is the first step in actually rendering the voxels onscreen, because this is needed to find all the exposed voxel faces in the region. I am not at that point yet but I would like to make sure I have a solid foundation before continuing. The first iteration runs unconditionally to make sure that the root node is processed. Then, if no descent has occurred (level is still 0), the loop is broken. When the loop is ascended (once index reaches zero and all descents have either not existed or already been handled), the level is checked before continuing, to avoid revisiting the same nodes infinity times. void octree_render(const Octree *const octree, const Octree *const octree_next[const static 3]) {
{ "domain": "codereview.stackexchange", "id": 45231, "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, octree", "url": null }
c, octree void octree_render(const Octree *const octree, const Octree *const octree_next[const static 3]) { const uint16_t **next_ptr = (const uint16_t **)octree_next, *next_stack[MAX_LEVEL][3]; const Node8 *set_ptr = (const Node8 *)octree, *set_stack[MAX_LEVEL]; unsigned level = 0, index = 0, index_stack[MAX_LEVEL], xzy[3] = {0}; for (;;) { for (;;) { const unsigned node = set_ptr->x[index]; if (node&FLAG_MASK && level < MAX_LEVEL) { set_stack[level] = set_ptr; set_ptr += node&DATA_MASK; index_stack[level] = index; index = 7; memcpy(next_stack+(level++), next_ptr, sizeof(*next_stack)); goto update; } for (unsigned dim = 2;; --dim) { printf("%d %d %d\n", node, *next_ptr[dim], xzy[dim]); if (!dim) break; } if (!index) break; --index; update: for (uint_fast8_t dim = (index&1)<<(index>>1&1);; --dim) { // The weird expression that dim is initialized to makes sure that only the values that have to be updated are updated // The X values have to be updated twice as often as the Z values, which have to be updated twice as often as the Y values xzy[dim] ^= 32>>level; const unsigned bit = 1<<dim; const uint16_t *const next_dim = next_stack[level-1][dim]; next_ptr[dim] = index&bit ? *next_dim&0x8000 // The neighboring node is in the neighboring set ? // The next set has to be descended (node_to_set(next_dim)+(*next_dim&0x7FFF))->x+(index&~bit) : next_dim : set_ptr->x+(index|bit); // The neighboring node is in the current set if (!dim) break; } } done: if (!level)
{ "domain": "codereview.stackexchange", "id": 45231, "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, octree", "url": null }
c, octree break; } } done: if (!level) break; if (!(index = index_stack[--level])) goto done; --index; set_ptr = set_stack[level]; memcpy(next_ptr, next_stack+level, sizeof(*next_stack)); goto update; } }
{ "domain": "codereview.stackexchange", "id": 45231, "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, octree", "url": null }
c, octree I have tested the function and it gives expected results for several test cases including this one: Octree *octree = memset(malloc(sizeof(Octree)), 0, sizeof(Octree)); octree = octree_set(octree, 1, 1, 0, 0); octree = octree_set(octree, 2, 2, 0, 0); Octree *blank = &(Octree){0}; octree_render(octree, (const Octree *const []){blank, blank, blank}); free(octree); Some concerns: Spaghetti code: I find my code difficult to follow due to the nested loops and goto statements, but this is the only way I figured out how to achieve the logic that does not involve any redundant tests. Is there a clearer way to express the loop logic? If goto is still needed that is OK but its current state seems unnecessarily complex. How can I avoid having to modify octree_next (as pointed to by next_ptr) and how can I avoid having to use memcpy to copy data to and from next_ptr and next_stack? There should be a way to change next_ptr to reference the top of next_stack somehow but I could not get that to work out. (The initial value it points to might (?) not be needed after the first iteration).
{ "domain": "codereview.stackexchange", "id": 45231, "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, octree", "url": null }
c, octree Answer: Using the right tool for the job When I first wrote this, I insisted on using an iterative approach, because I was rote taught that iteration is faster than recursion. However, an octree is a recursive data structure by nature. Using actual recursion instead of iteration-emulated recursion reflects the structure of the octree much more cleanly. All the really convoluted loop logic complete with goto statements can be avoided entirely, and the resulting code is much shorter, and the underlying logic is much easier to see. I have also, as suggested, added spacing between all binary arithmetic operators. A possible implementation of this for my purposes looks like this (untested): struct Scope { void *const buf; unsigned count; uint_fast16_t node; uint_fast8_t dim, quad_level, xzy[3], level; }; static void quad_render(struct Scope *const scope, const uint16_t *ptr) { // TODO: Emit vertices for quads printf("%d %d %d\n", scope->node, *ptr, scope->xzy[dim]); } struct Next { const uint16_t *ptr[3]; }; static void cube_render(struct Scope *const scope, const uint16_t *restrict ptr, struct Next next) { if (*ptr & FLAG_MASK && scope->level) { ptr = enter(ptr)->x; uint_fast8_t mask[3]; for (uint_fast8_t dim = 0; dim < 3; ++dim) mask[dim] = *next.ptr[dim] & FLAG_MASK ? next.ptr[dim] = enter(next.ptr[dim])->x, (1 << dim) ^ 7 : 0; --scope->level; for (uint_fast8_t i = 0; i < 8; ++i) { cube_render(scope, ptr + i, (struct Next){ i & 1 ? next.ptr[0] + (i & mask[0]) : ptr + (i | 1), i & 2 ? next.ptr[1] + (i & mask[1]) : ptr + (i | 2), i & 4 ? next.ptr[2] + (i & mask[2]) : ptr + (i | 4) }); scope->xzy[0] ^= 1 << scope->level; scope->xzy[1] ^= (i & 1) << scope->level; scope->xzy[2] ^= ((i & 3) == 3) << scope->level; } ++scope->level; return; }
{ "domain": "codereview.stackexchange", "id": 45231, "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, octree", "url": null }
c, octree } ++scope->level; return; } for (scope->node = *ptr, scope->dim = 0, scope->quad_level = scope->level; scope->dim < 3; ++scope->dim) quad_render(scope, next.ptr[scope->dim]); } void octree_render(const Octree *const restrict octree, const Octree *const next[const restrict static 3]) { struct Scope scope = { /* ... */ }; cube_render(&scope, &octree->base, (struct Next){&next[0]->base, &next[1]->base, &next[2]->base}); }
{ "domain": "codereview.stackexchange", "id": 45231, "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, octree", "url": null }
c++, game, rock-paper-scissors Title: "Rock Paper Scissors" game Question: I have created a rock paper scissors game in C++. #include <iostream> #include <map> #include <vector> #include <time.h> std::vector<std::string> gameOptions {"Rock", "Paper", "Scissors"}; // Map of Key as winner and Value as loser std::map<std::string, std::string> gameRules { {"Rock", "Scissors"}, {"Scissors", "Paper"}, {"Paper", "Rock"} }; std::string checkWinner(const std::string& playerSelection, const std::string& pcSelection) { if (playerSelection == pcSelection) return "Draw!"; if (gameRules[playerSelection] == pcSelection) return "Player Wins!"; return "PC Wins!"; } bool isUserInputValid(const std::string& playerSelection) { for (std::string option : gameOptions) { if (playerSelection == option) return true; } return false; } void promptUserInput() { std::cout << "Game Started! Enter your choice from below:" << std::endl; std::cout << "Rock" << std::endl; std::cout << "Paper" << std::endl; std::cout << "Scissors" << std::endl; } int main() { promptUserInput(); std::string playerSelection; std::cin >> playerSelection; while (!isUserInputValid(playerSelection)) { promptUserInput(); std::cin >> playerSelection; } std::string pcSelection; srand(time(NULL)); int random = rand(); pcSelection = gameOptions[random % 3]; std::cout<< "The result is: " << checkWinner(playerSelection, pcSelection) << std::endl; std::cout<< "Player Selection:\t" << playerSelection << std::endl; std::cout<< "PC Selection:\t" << pcSelection << std::endl; } Are there any parts that can be improved on?
{ "domain": "codereview.stackexchange", "id": 45232, "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++, game, rock-paper-scissors", "url": null }
c++, game, rock-paper-scissors Are there any parts that can be improved on? Answer: Overview I don't like how you are simply passing strings around for the values. Its simple but not very optimal. I would create some enum types to represent the different states (Win, Lose, Draw) and/or (Rock, Paper, Scissors). You can then convert these to string values if you need to present them on a console like interface. Code Review Sure: std::vector<std::string> gameOptions {"Rock", "Paper", "Scissors"}; But would be nice to be able to convert these to an enum for easy comparison. std::map<std::string, std::string> gameRules { {"Rock", "Scissors"}, {"Scissors", "Paper"}, {"Paper", "Rock"} };
{ "domain": "codereview.stackexchange", "id": 45232, "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++, game, rock-paper-scissors", "url": null }
c++, game, rock-paper-scissors Sure: But this representation can just as easily be represented by a switch. If you really want to represent the states and how they play against each other I would create an array that allows you to map to hands into a decision that wins/loses/draws. I would do this: enum State {Win, Lose, Draw}; enum Move {Rock, Paper, Scissors}; State challenge[3][3] = {{Draw, Lose, Win }, {Win, Draw, Lose}, {Lose, Win, Draw } }; int main() { Move human = Rock; Move pc = Scissors; State humanState = challenge[human][pc]; // You can convert the state to a string by overloading // operator << for the type State. std::cout << humanState << "\n"; }
{ "domain": "codereview.stackexchange", "id": 45232, "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++, game, rock-paper-scissors", "url": null }
c++, game, rock-paper-scissors This is very expensive using strings. std::string checkWinner(const std::string& playerSelection, const std::string& pcSelection) { if (playerSelection == pcSelection) return "Draw!"; if (gameRules[playerSelection] == pcSelection) return "Player Wins!"; return "PC Wins!"; } Much better using an enum. Then you could do a switch. Or you could do the challenge matrix I used above. prefer to use standard algorithms rather than a manual loop: bool isUserInputValid(const std::string& playerSelection) { for (std::string option : gameOptions) { if (playerSelection == option) return true; } return false; } I would write it like this: bool isUserInputValid(const std::string& playerSelection) { return std::find(std::begin(option), std::end(option), playerSelection) != std::end(option); } I should not use std::endl when "\n" is enough. The difference is that std::endl will flush the output buffer (Which is not needed, the standard library will flush when it needs to). This is the source of most speed concerns from new learners. There is no need for multiple statements. You can use a single statement (with one string per line) or a single raw string. void promptUserInput() { std::cout << "Game Started! Enter your choice from below:" << std::endl; std::cout << "Rock" << std::endl; std::cout << "Paper" << std::endl; std::cout << "Scissors" << std::endl; } I would write like this: void promptUserInput() { std::cout << "Game Started! Enter your choice from below:\n" << " Rock\n" << " Paper\n" << " Scissors\n"; } Or with raw string literal. void promptUserInput() { std::cout << R"( Game Started! Enter your choice from below: Rock Paper Scissors )"; } Note: srand() should only be called once in an application. srand(time(NULL)); int random = rand();
{ "domain": "codereview.stackexchange", "id": 45232, "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++, game, rock-paper-scissors", "url": null }
c++, game, rock-paper-scissors But really you should stop using this. It is after all a C library. There is a better C++ library. Example here.
{ "domain": "codereview.stackexchange", "id": 45232, "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++, game, rock-paper-scissors", "url": null }
python, combinatorics Title: Find the list of combination (with repetition) given rank and number of items. (Lexicographic ordering) Question: The problem involves the fastest possible method to generate a list of combinations which repeats from all the possible combinations with repetition allowed. I know there needs to be a way to calculate n from gamma(n,r)=v given r and v in order to get the fastest possible approach, but it's probably not solvable, so to the realm of what we have now. So, this means from a list of 3 items and maximum of 5 repetition, and rank, the list would look something like this: Rank - Combinations 0 - 0,0,0,0,0 1 - 0,0,0,0,1 2 - 0,0,0,0,2 .... 20 - 2,2,2,2,2 At the moment, my Python code to this problem: import math def calc_approximate_n(v,r): return max(r,int((v*math.factorial(r)-r)**(1/r))) NUMBER_OF_ITEMS=3 REPETITIONS=5 DECREMENT_REPETITIONS=REPETITIONS-1 NUMBER_OF_COMBS=math.comb(NUMBER_OF_ITEMS+REPETITIONS-1,REPETITIONS) MAX_COMB_RANK=NUMBER_OF_COMBS-1 rank=7 rank %= NUMBER_OF_COMBS Tc=NUMBER_OF_ITEMS-1 if rank==0: print([0]*REPETITIONS) elif rank==MAX_COMB_RANK: print([Tc]*REPETITIONS) elif rank<NUMBER_OF_ITEMS: output_list=[0]*REPETITIONS output_list[-1]=rank print(output_list) else: output_list=[0]*REPETITIONS while True: Tn=calc_approximate_n(rank,Tc) FTn=Tn-Tc+1 last_n=math.comb(Tn,Tc) ncr_val=last_n while ncr_val<rank: Tn += 1 ncr_val=math.comb(Tn,Tc) if ncr_val<=rank: last_n=ncr_val FTn += 1 rank -= last_n Tc -= 1 insertion_pos=DECREMENT_REPETITIONS for _ in range(FTn): output_list[insertion_pos] += 1 insertion_pos -= 1 if rank==0 or Tc==0: break print(output_list)
{ "domain": "codereview.stackexchange", "id": 45233, "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, combinatorics", "url": null }
python, combinatorics So, with 3 items and maximum repetition of 5 and rank 7, I get this combination => [0, 0, 1, 1, 2] Now, with 5 items, and maximum repetition of 12 and rank 1700, I get this combination => [1, 2, 2, 3, 3, 3, 3, 3, 4, 4, 4, 4] Answer: First Take Your code gets the job done and is correct as far as I can tell. It would be more convenient if it was converted to a function. I have taken the liberty to do so as follow: import math def calc_approximate_n(v,r): return max(r,int((v*math.factorial(r)-r)**(1/r))) def unrank(NUMBER_OF_ITEMS, REPETITIONS, rank): DECREMENT_REPETITIONS=REPETITIONS-1 NUMBER_OF_COMBS=math.comb(NUMBER_OF_ITEMS+REPETITIONS-1,REPETITIONS) MAX_COMB_RANK=NUMBER_OF_COMBS-1 rank %= NUMBER_OF_COMBS Tc=NUMBER_OF_ITEMS-1 . . . # Add returns as well And put it in a file called unrank_comb.py. So now the user can do the following in the console or script: import unrank_comb as urc urc.unrank(5, 12, 1700) [1, 2, 2, 3, 3, 3, 3, 3, 4, 4, 4, 4] Code Style Your code could be improved with more consistent spacing, especially around variable assignment. When I run pycodestyle on your code I get many departures from PEP8 standards: % pycodestyle unrank_comb.py unrank_comb.py:3:1: E302 expected 2 blank lines, found 1 unrank_comb.py:3:25: E231 missing whitespace after ',' unrank_comb.py:4:17: E231 missing whitespace after ',' . . . unrank_comb.py:48:20: E225 missing whitespace around operator unrank_comb.py:48:29: E225 missing whitespace around operator unrank_comb.py:50:1: W293 blank line contains whitespace If this was the only function in your script/library, then I would add a bunch of sanitizing checks to ensure the code will run properly. I'm assuming all of this is taken care of outside of this function so I will skip this part. Efficiency We can speed up your code quite a bit by avoiding calls to math.comb using a little algebra. For unranking, we will have to do the following tasks multiple times:
{ "domain": "codereview.stackexchange", "id": 45233, "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, combinatorics", "url": null }
python, combinatorics Start with \$ {n + r - 1 \choose r} = \frac{(n + r - 1)!}{r! \cdot (n - 1)!} \$ Then we want to calculate \$ {n + r - 2 \choose r} = \frac{(n + r - 2)!}{r! \cdot (n - 2)!} \$ In order to avoid the second call to math.comb we can do the following: \$ \frac{(n + r - 1)!}{r \cdot (n - 1)!} \cdot (n - 1) = \frac{(n + r - 1)!}{r \cdot (n - 2)!}\$ \$ \frac{(n + r - 1)!}{r \cdot (n - 2)! \cdot (n + r - 1)} = \frac{(n + r - 2)!}{r! \cdot (n - 2)!} \$ We see that instead of calling math.comb a second time, we simply multiply the previous result by n - 1 and then divide by n + r - 2. The code below is a simple implementation that does just that: def unrank_fast(n, r, rank): ''' Returns the lexicographic combination with repetition of n items of length r corresponding to a given rank. Parameters: n (int): The number of items r (int): The length of the combination rank (int): The nth lexicographic result Returns: output_list (list): A list of integers ''' output_list = [0] * r temp = int(math.comb(n + r - 2, r - 1)) r -= 1 j = 0 for k in range(r + 1): while temp <= rank: rank -= temp temp *= (n - 1) temp //= (n + r - 1) n -= 1 j += 1 temp *= r if n + r > 2: temp //= (n + r - 1) output_list[k] = j r -= 1 return output_list It is quite fast. Observe the following: import timeit timeit.timeit("urc.unrank(20, 200, 782090539377703617347883590)", "import unrank_comb as urc", number = 10000) 1.774310542000002 timeit.timeit("urc.unrank_fast(20, 200, 782090539377703617347883590)", "import unrank_comb as urc", number = 10000) 0.2731890419999985 Over 6x faster! It gives the correct results as well. import itertools as it import unrank_comb as urc combs_it = [list(cmb) for cmb in it.combinations_with_replacement(range(5), 12)] combs_fast = [] combs_op = []
{ "domain": "codereview.stackexchange", "id": 45233, "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, combinatorics", "url": null }
python, combinatorics combs_fast = [] combs_op = [] for k in range(1820): combs_fast.append(urc.unrank_fast(5, 12, k)) combs_op.append(urc.unrank(5, 12, k)) combs_op == combs_it True combs_fast == combs_it True
{ "domain": "codereview.stackexchange", "id": 45233, "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, combinatorics", "url": null }
python, performance, formatting Title: Python (API requests) Question: I'm somewhat new to python and I'm creating a script that requests to a certain API and then uses the response to populate a local DB, so far I have the following: Project Structure ├─── logs │ ├─── app-logs.log │ └─── err-logs.log │ ├─── secrets │ └─── config.ini │ ├─── src │ ├─── api │ │ └─── send_request.py │ ├─── interface │ │ └─── ... │ └───templates │ ├─── main.py send_request.py # send_request.py """ Module used to handle API requests. """ __version__ = '0.1' __author__ = 'Me' # Standard lib imports from collections import namedtuple # Third-party lib imports import requests from icecream import ic # Class used to handle requests class HandleRequest(): # Only for debug ic("Starting request") # Initial parameters def __init__(self) -> None: self.get_response = namedtuple('GET_Response', 'status_code response') super().__init__() def make_request(self, url: str, params: dict): request = requests.Request( method = 'GET', url = url, params = params ).prepare() # Log request ic(request) # Get response with requests.Session() as session: response = session.send(request) # Log response & status code ic(response, response.status_code) # Verify response status if (response.status_code >= 200 and response.status_code <= 299): return self.get_response(status_code = response.status_code, response = response.json()) else: return self.get_response(status_code = response.status_code, response = None) main.py # main.py __version__ = '0.1' __author__ = 'Me' # Third-party lib imports import configparser from icecream import ic # Local application imports from src.api.send_request import HandleRequest # Get secrets secrets = configparser.ConfigParser() secrets.read('secrets/config.ini')
{ "domain": "codereview.stackexchange", "id": 45234, "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, formatting", "url": null }
python, performance, formatting # Get secrets secrets = configparser.ConfigParser() secrets.read('secrets/config.ini') # Define constants TOKEN = secrets.get('API', 'token') URL = secrets.get('API', 'api_url') def can_connect(table: str) -> bool: """ Test API connection Parameters ---------- table : str the name of the table you want to access/test. Returns ------- bool True if response status code equals to 200 & isn't empty, False otherwise. """ skip = 0 params = { "token": TOKEN, "$skip": skip } handler = HandleRequest() request = handler.make_request(URL + table, params) if (request.status_code == 200 and len(request.response) > 0): return True return False ic(can_connect('persons')) with a valid api token/url inside config.ini I can verify its working as intended, what I'd like to know with this post is if there's anything I could/should change in my code cause I don't really know if the way I did is the "best" way to do it.. It would be amazing for me if someone with more experience could make observations about things I should/shouldn't do. Answer: In a pathname like logs/err-logs.log, the -logs suffix seems redudnant. one level down Based on from src.api.send_request import ..., it seems that main.py belongs one level down, within src/. The "src" doesn't tell us anything, since all python libraries are composed of some source code. Of course, api is on the vague side -- feel free to name it foo_api or whatever marketing name your project is using. Similarly for vague calls like secrets.get('API', ...). """ Module used to handle API requests. """ Yay, we have a module-level docstring! Good. Same critique, rephrase as "to handle FOO API...". isort # Standard lib imports from ... # Third-party lib imports
{ "domain": "codereview.stackexchange", "id": 45234, "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, formatting", "url": null }
python, performance, formatting isort # Standard lib imports from ... # Third-party lib imports Both comments are redundant with PEP-8. Just let isort sort it for you, and such concerns disappear, you needn't give it a moment's thought. fluff comments # Class used to handle requests class HandleRequest(): Ok, now we're being silly. Just delete that, it isn't shedding any new light on things, it doesn't help a maintainer, any more than this would: i += 1 # Increment the integer index i by a certain quantity, by not less than one, and by no greater. We write code to explain the how to human reviewers, and write # comments to explain the why. clean import ic("Starting request") Avoid print or other side effecting calls at import time. The unit test or other caller won't appreciate it. Wait till we're within __init__ or a method. define classes at module level def __init__(self) -> None: self.get_response = namedtuple('GET_Response', 'status_code response') PEP-8 explains that this is spelled wrong. Plus, we don't need a new named tuple type for every instance of HandleRequest. Prefer: GetResponse = namedtuple('GetResponse', 'status_code response') Calling super (object) init isn't helping you here, may as well delete that line. EDIT Class definitions belong at module level. Avoid nesting one class within another. Especially avoid creating N class definitions (of a namedtuple) for N object instances. when trying to rename self.get_response to GetResponse I get the warning "Remove the unused local variable GetResponse" The linter is correct, it is giving you good advice. Don't create a new local GetResponse class object and then discard it unused when __init__ exits. Define the GetResponse class up at the module level, not nested within another class. when trying to rename self.get_response to self.GetResponse I get the warning: "Rename this field ... to match the regular expression ^[_a-z][_a-z0-9]*$" respectively.
{ "domain": "codereview.stackexchange", "id": 45234, "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, formatting", "url": null }
python, performance, formatting The linter is correct, it is giving you good advice. Class objects start with initial capital letter. We typically don't create a new class object as an object field, so the regex is rightly pointing out that you're (A.) doing something weird, and (B.) not following my original advice. "Module level" means "don't indent", not even a little. Zero indent. Please define the class at module level, in this way: GetResponse = namedtuple("GetResponse", "status_code response") class HandleRequest: ... type hint FTW def make_request(self, url: str, params: dict): This is beautiful and I thank you for it, it is helpful. I haven't tried running mypy over this, but I imagine it would be more informative if we spell out def ... , params: dict[str, str] ... Also, as long as we're at it, it wouldn't hurt to -> point out we always return a GetResponse. redundant comment # Log request ic(request) # Get response ... # Log response & status code ... # Verify response status These aren't telling us anything, as the code already stated it eloquently. Delete. Invent a well-named helper function if you want to point out that we log_response_and_status_code(). Ok, if the issue arises again I will just bite my tongue, assuming you know it's best to elide such fluff. raise_for_status if (response.status_code >= 200 and response.status_code <= 299): This is kind of OK. But conventional usage would be simply response.raise_for_status()
{ "domain": "codereview.stackexchange", "id": 45234, "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, formatting", "url": null }
python, performance, formatting This is kind of OK. But conventional usage would be simply response.raise_for_status() and if we survive that with no fatal error, then we go on to merrily pick apart the response fields. You made a design decision to return response=None rather than raise the customary exception. I've not yet read enough of the code to decide whether bucking the trend will pay off in some way. Certainly, no # comment explained the underlying reasoning. Similarly down in can_connect. There's more than one success status. Plus, a 300-series redirect is definitely not a failure. EDIT The thing about response=None. I did that cause I didn't know what would happen if I got an error as the response, I thought the code would just stop/exit If I tried getting the response as a json() in case of an error. Excellent, a teaching moment! Cool, we get to learn about Exceptions today. They're not scary "crash and burn!" things. They're actually your friend. Used wisely, they can make your code more robust, not less. Let's look at the call site, to see how this is being used. def can_connect( ... ) -> bool: ... request = handler.make_request( ... )
{ "domain": "codereview.stackexchange", "id": 45234, "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, formatting", "url": null }
python, performance, formatting And then we do some testing to figure out what the predicate should return. Now, the status testing you do down in make_request isn't exactly wrong, it isn't so bad. But it isn't exactly right, failing to account for some additional "things are working!" status codes, and it's repeated. Worse, some of that logic is repeated up in the caller, but in a different form. It would be better for the "error?" decision to be made just once. And it's convenient to delegate that decision to the requests library, by calling response.raise_for_status(). Doing that would change the Public API contract of make_request. Currently it offers a contract that is on the weak side. How can we tell? Because caller is burdened with doing some checks before making a potentially dangerous access of the response field, which might be None. A stronger contract would say, "I will return a valid webserver response, dammit!" Now of course, not all wishes come true, and not all web requests end well. Sometimes the contract cannot be fulfilled. And that's ok. Things go wrong all the time, and not just on the web, that's life. So caller must be able to cope with some level of misery anyway. If there's no way to successfully complete the contract, we just call the whole thing off by raising HTTPError. It's as if we were never called, all bets are off. If the caller doesn't know what to do, then by default the exception will bubble up the call stack to main level, where it will typically be displayed in a call trace and then we exit. If caller does know some appropriate way to recover from the error, perhaps by ignoring it, or by incrementing an error counter, then it can catch the error and deal with it. from requests import HTTPError def can_connect( ... ) -> bool: ... try: request = handler.make_request( ... ) except HTTPError: return False ... ```
{ "domain": "codereview.stackexchange", "id": 45234, "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, formatting", "url": null }
javascript, security Title: Is this string-comparison function safe against timing attacks? Question: Here's a JavaScript function that check the equality of input and secret strings, trying to do that without leaking information about secret: function timeSafeEqual(input, secret) { let equal = input.length === secret.length for (let i = 0; i < input.length; ++i) { const ofInput = input[i] const ofSecret = secret[i] if (ofInput !== ofSecret) { equal = false } } return equal } The function seems to always run in O(input.length) time. Would you consider it to be timing-safe? This code runs on Node.js Maybhe the time to compare undefined string values might be different than the time to compare string and string in V8? Answer: Is it safe? No. bug let equal = input.length === secret.length In the happy path we assign True and life is good. When we assign False, then de-referencing input[i] and secret[i] is trouble. Minimally, the attempted de-reference will consume a perceptibly different amount of delay. If we get an undefined back, then XORing it will be trouble. Assume we assigned equal = True above. timing of a conditional if (ofInput !== ofSecret) { equal = false } This is just Bad. We perform N comparisons, so that much is fine, there's no early exit. But for M out of N mis-matches, we're performing an extra M assignments which an adversary armed with a stopwatch can observe. Total failure. fix Compute and store N xor's. In the case that the strings are equal, we store N zeros. Sum the xor results and return that. Non-zero means the strings don't match. Consider hashing both strings initially, then compare the hashes. One advantage is you're guaranteed to be comparing hashes of identical length. Another is that you have flexibility to pre-hash on a different host or at a previous time.
{ "domain": "codereview.stackexchange", "id": 45235, "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, security", "url": null }
javascript, security random jitter Your adversary's ability to observe what's happening is impacted by random noisy delays caused by router queues and host scheduler queues. Roll a random number and sleep that long before returning a boolean result. That way the adversary has less effective signalling bandwidth for his observations, so effective attacks will take much longer.
{ "domain": "codereview.stackexchange", "id": 45235, "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, security", "url": null }
python, cryptography Title: Password database: saving and loading encrypted files Question: I'm writing a password manager application, mostly with the goal of learning about proper handling of encryption. Here is my code responsible for encrypting/decrypting passwords and loading to/from file. The PasswordDataBase class is pretty bare as is, but will incorporate more functionality going further (such as filtering records based on name or tags). I just want to make sure this more sensitive aspect of the code is done right before building upon it. Dependencies: this code depends on the pyaes module, which you can find on PyPI. passworddb.py: from dataclasses import dataclass, field from hashlib import scrypt import pickle import secrets from typing import List import uuid import pyaes class InvalidPasswordException(Exception): pass class PasswordDataBase: SALT_LENGTH = 16 @dataclass class Record: name: str = field(default='') login: str = field(default='') password: str = field(default='') uid: uuid.UUID = field(default_factory=uuid.uuid4) tags: List[str] = field(default_factory=list) def __init__(self): self.records = [] def save_to_file(self, path: str, password: str): """ Save the current instance to a file. Parameters ---------- path : str Path of the file to save. password : str The master password used for encryption. Returns ------- None. """ password = bytes(password, encoding='utf-8') salt = secrets.token_bytes(self.SALT_LENGTH) key = scrypt(password, n=2**14, r=8, p=1, salt=salt, dklen=32) cipher = pyaes.AESModeOfOperationCTR(key) with open(path, 'wb') as file: file.write(salt) file.write(cipher.encrypt(pickle.dumps(self)))
{ "domain": "codereview.stackexchange", "id": 45236, "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, cryptography", "url": null }
python, cryptography @classmethod def load_from_file(cls, path: str, password: str): """ Load an encrypted password database from a file. Parameters ---------- path : str Path to the file to load. password : str Master password used to decrypt the file. Raises ------ InvalidPasswordException The provided password was invalid. Returns ------- PasswordDataBase A PasswordDatabase instance containing the decrypted data. """ password = bytes(password, encoding='utf-8') with open(path, 'rb') as file: salt = file.read(cls.SALT_LENGTH) data = file.read() key = scrypt(password, n=2**14, r=8, p=1, salt=salt, dklen=32) cipher = pyaes.AESModeOfOperationCTR(key) try: return pickle.loads(cipher.decrypt(data)) except pickle.UnpicklingError as error: raise InvalidPasswordException("Invalid password") from error def generate_password(length: int, charset: str) -> str: """ Generate a securely random password. Parameters ---------- length : int Generated password length. charset : str Allowable characters for password generation. Returns ------- str The generated password. """ return ''.join(secrets.choice(charset) for _ in range(length)) passworddb_tests.py: """ Unit tests for the password_manager modules """ import os from string import ascii_letters, digits, punctuation import tempfile import unittest from passworddb import (PasswordDataBase, InvalidPasswordException, generate_password) ALL_CHARS = ascii_letters + digits + punctuation class PasswordDataBaseTests(unittest.TestCase):
{ "domain": "codereview.stackexchange", "id": 45236, "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, cryptography", "url": null }
python, cryptography ALL_CHARS = ascii_letters + digits + punctuation class PasswordDataBaseTests(unittest.TestCase): def test_roundtrip(self): """ Verify that a password database written to a file is correctly recovered upon loading. """ original = PasswordDataBase() original.records.append( PasswordDataBase.Record(name='foo', login='bar', password=generate_password(64, ALL_CHARS))) original.records.append( PasswordDataBase.Record(name='ga', login='bu', password=generate_password(64, ALL_CHARS), tags=['zo', 'meu'])) original.records.append(PasswordDataBase.Record()) password = "Secr3t" with tempfile.TemporaryDirectory() as temp_dir: path = os.path.join(temp_dir, 'test') original.save_to_file(path, password) recovered = PasswordDataBase.load_from_file(path, password) for expected, actual in zip(original.records, recovered.records): self.assertEqual(expected, actual) def test_roundtrip_empty(self): """ Verify that an empty password database written to a file is correctly recovered upon loading. """ original = PasswordDataBase() password = "Secr3t" with tempfile.TemporaryDirectory() as temp_dir: path = os.path.join(temp_dir, 'test') original.save_to_file(path, password) recovered = PasswordDataBase.load_from_file(path, password) for expected, actual in zip(original.records, recovered.records): self.assertEqual(expected, actual)
{ "domain": "codereview.stackexchange", "id": 45236, "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, cryptography", "url": null }
python, cryptography def test_load_fails_with_wrong_password(self): """ Ensure that records written to a file can't be recovered using an incorrect password. """ database = PasswordDataBase() database.records.append( PasswordDataBase.Record(name='foo', login='bar', password=generate_password(64, ALL_CHARS))) database.records.append( PasswordDataBase.Record(name='ga', login='bu', password=generate_password(64, ALL_CHARS), tags=['zo', 'meu'])) database.records.append(PasswordDataBase.Record()) with tempfile.TemporaryDirectory() as temp_dir: path = os.path.join(temp_dir, 'test') database.save_to_file(path, 'right') self.assertRaises(InvalidPasswordException, lambda: PasswordDataBase.load_from_file(path, 'wrong')) if __name__ == '__main__': unittest.main() My main concerns are: Does this code follow best practices when it comes to security? Is the test coverage good enough? I feel like it could be improved, but I find it hard to come up with additional meaningful tests. Any other remarks about my code are also welcome, of course. Answer: Does this code follow best practices when it comes to security? No. This is SOTA from a few decades ago. Passwords have low entropy, typically much less than 256 bits. Modern implementations will prefer to frustrate an attacker by using a deliberately slow password stretcher, such as argon2id. Even with that, if the end user chose a word from a dictionary that the attacker has, or chose a word that a simple generator is likely to stumble upon, then there's no saving the scheme. Argon2 merely slows down such an attack, making it take much longer to succeed.
{ "domain": "codereview.stackexchange", "id": 45236, "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, cryptography", "url": null }
python, cryptography partial type annotation Consider telling mypy that save_to_file returns -> None: Not sure why your docstring redundantly mentions types, since the signature already revealed them. The ... , path: str, ... is nice enough, but declaring it path: Path would be nicer, more informative. password = bytes(password, encoding='utf-8') Consider assigning to password1 here, or some other identifier. Yes, python lets you dynamically change type. But that tends to make it harder to reason about the code. This bit of code is trivial, it's no big deal, but when a conditional changes the type for some inputs yet not all, that leads to complexity and bugs. It's just a habit, preserving type stability, that you may want to get into. Kudos on using a with context manager when you open a file for writing. pickle file.write(cipher.encrypt(pickle.dumps(self))) This is convenient. There's nothing wrong with it, exactly. But consider using a stable pack / unpack approach to serialization. Too often I have written a pickle using library v2, then it revs to v3, and I see unpickle fail :-( Data files often last longer than a public API will. tests I imagine your tests achieve good code coverage. Verify by using pytest --cov. There's probably one or two error cases you've not exercised. And you know what they say, "A line of code that never ran is likely a buggy line." The notion of round-tripping is very nice. You can think of it as an oracle, which can tell whether the right thing happened. This is the perfect setup for my favorite advanced testing library: hypothesis. Let it torture test your code for a bit, looking for edge cases like "empty passphrase", "super long passphrase", "passphrase that tries to use unicode characters", and so on. You have already written some nice target code that checks for such things, but you'd be surprised what hypothesis may manage to dig up. Certainly it has surprised me when I ran it against my own code.
{ "domain": "codereview.stackexchange", "id": 45236, "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, cryptography", "url": null }
python, cryptography This code accomplishes a subset of its design goals. It should not be merged down to main until it adopts a "slow" password stretcher such as argon2id. I would be willing to delegate or accept maintenance tasks on this codebase.
{ "domain": "codereview.stackexchange", "id": 45236, "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, cryptography", "url": null }
python Title: Simplifying and enhancing readability in time angle calculation Question: Is the following Python code, which calculates hand angles based on current time, simple and readable? What alternative approaches can enhance simplicity and readability? Are there concise one-liner solutions worth considering? def calculate_angles(current_time: List[int]) -> List[float]: ''' Calculates hands angles ''' hours, minutes, seconds = current_time return [hours_angle(hours, minutes), minutes_angle(minutes), seconds_angle(seconds)] Answer: This isn't bad, it's perfectly serviceable code. The docstring should be an English sentence. Each sentence ends with a . period. Representing current_time as a sequence rather than a time object is perhaps suspect. You might want to reconsider that design choice. Thank you kindly for including those optional type annotations. The signature ends with ... List[int]) -> List[float]:, which arguably is wrong, or at least not pythonic. We prefer to use a tuple (a 3-tuple, here) rather than a list of arbitrary length to represent what amounts to a C struct. While you're at it, make it a namedtuple. The rule is pretty simple. Use a tuple when position dictates meaning, e.g. unpacking h, m, s. Use a list for variable number of "the same kind" of thing, for example a bunch of h,m,s transaction timestamps.
{ "domain": "codereview.stackexchange", "id": 45237, "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", "url": null }
python Let's talk about computing those angles. The hours_angle and minutes_angle signatures look a little suspect to me. They omit seconds, or rather they implicitly treat it as zero seconds. I guess that for some clocks that's the appearance they offer. I would be happier if we were passing a time object into these helpers and letting each helper decide if it implements a clock style which prohibits movement of the other hands for sixty seconds. Usually I'm a big fan of "make it smaller!", "extract more helpers!". But here I wonder if we've maybe gone too far in that direction. Computing total seconds can look a bit like Horner's method: seconds_since_midnight = ((h) * 60 + m) * 60 + s With that representation in hand we might multiply by a conversion factor of six: degrees_since_midnight = seconds_since_midnight * 360 / 60 and then reverse the process to pick out h,m,s degrees. A single helper that returns a 3-tuple might be more convenient and accurate than the three helpers that OP proposes.
{ "domain": "codereview.stackexchange", "id": 45237, "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", "url": null }
python Title: Refactoring random time values list generator function Question: This function outputs random values in a list. Although I was happy to craft this solution from a more complex version, and it looks really cool to me, I wonder if it is an example of clean code. How can it be improved, and what are other ways to write it? def random_time_values() -> List[int]: ''' Generates random [hours, minutes, seconds] ''' return [randint(*time) for time in [(0, 11), (0, 59), (0, 59)]] Answer: What you've described and what you've written are two different things. You've described a function that outputs random times in a list, but it actually outputs a list of hour-minute tuple values randomly selected from a small, fixed set. Those can't both be true, so let's choose one - your description, of generating random times. Why not: write a generator function that doesn't take an opinion on how many outputs you want; that way it can generate them lazily and the consumer can use e.g. islice make truly random times, with random hour, minute, second and microsecond fields, rather than choosing from a set This could be as simple as: import datetime import random from itertools import islice from typing import Iterator def random_time_values() -> Iterator[datetime.time]: base = datetime.datetime(1, 1, 1) while True: delta = datetime.timedelta(days=random.random()) yield (base + delta).time() def demo(n: int = 25) -> None: for t in islice(random_time_values(), n): print(t) if __name__ == '__main__': demo() 22:09:36.696135 11:23:34.522248 00:09:56.177813 05:24:03.343375 22:25:56.346006 03:48:09.863071 20:48:27.955984 18:06:57.958131 00:15:05.198247 04:12:29.939244 09:50:25.152160 17:16:13.000451 10:51:36.054653 20:21:09.080549 02:00:15.132786 20:53:58.105197 08:25:13.088035 17:01:38.471288 04:14:28.054855 12:39:29.076931 07:13:03.665626 19:23:39.066675 15:46:20.652315 14:34:02.837399 13:34:33.400851
{ "domain": "codereview.stackexchange", "id": 45238, "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", "url": null }
c++, collections, c++17, circular-list, constant-expression Title: C++ ring buffer using some C++ 17 and coming C++ 20 std::span Question: When I heard about the new Linux I/O interface io_uring I searched about the ring buffer. I then thought I may replace my safe queue which is base on C++ 11 std::queue with a ring buffer to avoid repeated memory allocation during producing and consuming the packets between threads. So I wanted to implement it as an exercise and started to look for some C++ implementations and found Boost's circular buffer. I didn't look at its source code much but looked at the functionality it provides and tried to implement most of them but I still lack some. So here is what I came up with: #pragma once #include <utility> #include <optional> #include "span.h" #include <memory> #define PROVIDE_CONTAINER_TYPES(T) \ using value_type = T;\ using pointer = T * ;\ using const_pointer = const T *;\ using reference = T & ;\ using const_reference = const T &; \ using size_type = std::size_t; \ using difference_type = std::ptrdiff_t struct no_init_t {}; constexpr no_init_t no_init; class ring_buffer_index { size_t index; public: ring_buffer_index() : index{0} {} ring_buffer_index(size_t pos) : index{pos} {} ring_buffer_index& operator++() { ++index; return *this; } ring_buffer_index& operator--() { --index; return *this; } ring_buffer_index operator+(size_t pos) const { return ring_buffer_index{index + pos}; } size_t operator-(ring_buffer_index other) const { return index - other.index; } bool operator==(ring_buffer_index other) const { return index == other.index; } bool operator!=(ring_buffer_index other) const { return index != other.index; } void operator+=(size_t times) { index += times; } void operator-=(size_t times) { index -= times; } void reset() { index = 0; }
{ "domain": "codereview.stackexchange", "id": 45239, "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++, collections, c++17, circular-list, constant-expression", "url": null }
c++, collections, c++17, circular-list, constant-expression void operator-=(size_t times) { index -= times; } void reset() { index = 0; } size_t as_index(size_t N) const { size_t pos = index; pos %= N; return pos; } }; template <class T> class uninitialized_array { std::unique_ptr<unsigned char> raw_buffer; public: uninitialized_array() noexcept = default; uninitialized_array(size_t N) : raw_buffer{ new unsigned char[sizeof(T) * N] } {} uninitialized_array(uninitialized_array&& other) noexcept = default; uninitialized_array& operator=(uninitialized_array&& other) noexcept = default; void copy(const uninitialized_array& other, size_t N) { raw_buffer.reset(); if (other.raw_buffer && N) { raw_buffer.reset(new unsigned char[sizeof(T) * N]); std::uninitialized_copy(other.ptr(), other.ptr() + N, ptr()); } } void resize(size_t N) { raw_buffer.reset( new unsigned char[sizeof(T) * N] ); } T * ptr() noexcept { return reinterpret_cast<T*>(raw_buffer.get()); } const T * ptr() const noexcept { return reinterpret_cast<const T*>(raw_buffer.get()); } T& operator[](size_t pos) noexcept { return ptr()[pos]; } }; template <class T, bool reverse = false, bool const_iter = false> class ring_buffer_iterator { T *ptr; ring_buffer_index index; size_t N; public: PROVIDE_CONTAINER_TYPES(T); using iterator_category = std::random_access_iterator_tag; ring_buffer_iterator(T *ptr, ring_buffer_index index, size_t N) : ptr{ ptr }, index{ index }, N{ N } {} ring_buffer_iterator& operator++() { if constexpr (!reverse) ++index; else --index; return *this; }
{ "domain": "codereview.stackexchange", "id": 45239, "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++, collections, c++17, circular-list, constant-expression", "url": null }
c++, collections, c++17, circular-list, constant-expression ring_buffer_iterator& operator+=(size_t n) { index += n; return *this; } ring_buffer_iterator& operator-=(size_t n) { return operator+=(-n); } template <bool citer = const_iter, std::enable_if_t<!citer, bool> = true> reference operator*() const { return ptr[index.as_index(N)]; } template <bool citer = const_iter, std::enable_if_t<citer, bool> = true> const_reference operator*() const { return ptr[index.as_index(N)]; } template <bool citer = const_iter, std::enable_if_t<!citer, bool> = true> reference operator[](difference_type n) { return *(*this + n); } const_reference operator[](difference_type n) const { return *(*this + n); } bool operator!=(ring_buffer_iterator other) const { return index != other.index; } bool operator==(ring_buffer_iterator other) const { return index == other.index; } friend ring_buffer_iterator operator+(const ring_buffer_iterator& iter, size_t times) { return ring_buffer_iterator{iter.ptr, iter.index + times, iter.N}; } friend ring_buffer_iterator operator+(size_t times, const ring_buffer_iterator& iter) { return ring_buffer_iterator{ iter.ptr, iter.index + times, iter.N }; } friend ring_buffer_iterator operator-(const ring_buffer_iterator& lhs, size_t times) { return ring_buffer_iterator{lhs.ptr, lhs.index - times, lhs.N}; } friend difference_type operator-(const ring_buffer_iterator& lhs, const ring_buffer_iterator& rhs) { return static_cast<difference_type>(lhs.index - rhs.index); } }; template <class T> class ring_buffer { size_t N; mutable uninitialized_array<T> raw_buffer; ring_buffer_index read_pos, write_pos; T& read_ptr() const { return raw_buffer[read_pos.as_index(N)]; }
{ "domain": "codereview.stackexchange", "id": 45239, "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++, collections, c++17, circular-list, constant-expression", "url": null }
c++, collections, c++17, circular-list, constant-expression T& read_ptr() const { return raw_buffer[read_pos.as_index(N)]; } T& write_ptr() const { return raw_buffer[write_pos.as_index(N)]; } bool will_remain_linearized(size_t num) { ring_buffer_index last_elem = write_pos + num - 1; return last_elem.as_index(N) >= read_pos.as_index(N); } public: PROVIDE_CONTAINER_TYPES(T); using iterator = ring_buffer_iterator<T>; using const_iterator = ring_buffer_iterator<T, false, true>; using reverse_iterator = ring_buffer_iterator<T, true>; using const_reverse_iterator = const ring_buffer_iterator<T, true, true>; /* contrtuctors and assignment operators */ ring_buffer() : N{0} {} ring_buffer(size_t size) : N{ size }, raw_buffer { size } {} ring_buffer(ring_buffer&&) noexcept = default; ring_buffer(const ring_buffer& other) { clear(); N = other.N; read_pos = other.read_pos; write_pos = other.write_pos; raw_buffer.copy(other.raw_buffer, N); } ring_buffer(std::initializer_list<value_type> init) : ring_buffer(init.size()) { std::uninitialized_copy(init.begin(), init.end(), raw_buffer.ptr()); } template <class InputIterator> ring_buffer(InputIterator first, InputIterator last) : ring_buffer(static_cast<size_type>(std::distance(first, last))) { std::uninitialized_copy(first, last, raw_buffer.ptr()); write_pos += capacity(); } ring_buffer& operator=(ring_buffer&& other) noexcept { clear(); N = other.N; read_pos = other.read_pos; write_pos = other.write_pos; raw_buffer = std::move(other.raw_buffer); return *this; }
{ "domain": "codereview.stackexchange", "id": 45239, "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++, collections, c++17, circular-list, constant-expression", "url": null }
c++, collections, c++17, circular-list, constant-expression } ring_buffer& operator=(const ring_buffer& other) { clear(); N = other.N; read_pos = other.read_pos; write_pos = other.write_pos; raw_buffer.copy(other.raw_buffer, N); return *this; } ~ring_buffer() { clear(); } /* addition methods */ /* add at the back of the buffer , this is usually used rather than add at the front */ void push_back_without_checks(const value_type& value) { emplace_back_without_checks(value); } void push_back_without_checks(value_type&& value) { emplace_back_without_checks(std::move(value)); } bool try_push_back(const value_type& value) { return try_emplace_back(value); } bool try_push_back(value_type&& value) { return try_emplace_back(std::move(value)); } void push_back(const value_type& value) { emplace_back(value); } void push_back(value_type&& value) { emplace_back(std::move(value)); } template <class ...Args> void emplace_back_without_checks(Args&& ... args) { new(&write_ptr()) T(std::forward<Args>(args)...); ++write_pos; } template <class ...Args> bool try_emplace_back(Args&& ... args) { if (full()) return false; emplace_back_without_checks(std::forward<Args>(args)...); return true; } template <class ...Args> void emplace_back(Args&& ... args) { if (full()) pop_front(); emplace_back_without_checks(std::forward<Args>(args)...); }
{ "domain": "codereview.stackexchange", "id": 45239, "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++, collections, c++17, circular-list, constant-expression", "url": null }