text
stringlengths
1
2.12k
source
dict
javascript - Collision Test complete!`; } // Initialize Collision Tests (async () => { const ulidTestResults = await collisionTest(1000000, randomULID); console.log(ulidTestResults); const mulidTestResults = await collisionTest(1000000, randomMULID); console.log(mulidTestResults); })(); Answer: A short review; this is very interesting, and something I might use on a personal project, it is nice to have sortable UUIDs. There are, however, far too many comments. I mean.. // Get the current timestamp as a BigInt. const timestamp = BigInt(Date.now()); I am not a big fan of randomMULID, UUIDs are meant for local processing, and then when we merge into a larger database/collection there will be no collisions. Incrementing lastRandomValue by 1 will help with the local uniqueness, but I fail to see how this can bring Universal uniqueness. Other than that, very cool, I learned about the crypto object in JS, and the code seems to be lightning fast.
{ "domain": "codereview.stackexchange", "id": 45150, "lm_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", "url": null }
python, raspberry-pi Title: Python script that starts a video recording on a Raspberry Pi using a USB webcam Question: I’d love some critique, pointers or any improvement to my code. My project was mainly to record a video, through a Flask Application (online), then save it and display it on the Flask Application. Will probably do it through Vimeo API or something. It’s just a demo. I still need to remove the timer, so it records until someone clicks stop recording. (But this is being used at the moment to save on storage on my Raspberry Pi) Then I will have to write some new code so that the files don’t overwrite each other. Potentially use datetime or a while loop counter. I am using SSH to control my Raspberry Pi through VSC. The camera is a C920 [HD Pro Webcam C920] that is plugged in with a USB to Raspberry Pi. I tried recording both video and audio at the same time, but I ran into trouble doing that, that’s why I decided to split it into recording separately and combining it later. One potential issue I have noticed is that depending on which USB port I use it can switch the audio output, but that can occur randomly as well, often when a reboot has occurred. My solution might be to disable the other audio outputs, but I don’t know yet. But this again hasn’t been an issue lately. The current code is this: import subprocess import os import time # Directory of files saved output_directory = "/home/pi/Videos" # Start recording def start_recording(): # Filenames for video and audio video_filename = os.path.join(output_directory, "video.mp4") audio_filename = os.path.join(output_directory, "audio.wav") # Start record video start_video = [ "ffmpeg", "-thread_queue_size", "512", "-f", "v4l2", "-input_format", "mjpeg", "-video_size", "1280x720", "-framerate", "10", "-i", "/dev/video0", "-c:v", "libx264", "-maxrate", "1000k", "-bufsize", "128k", "-y", video_filename ]
{ "domain": "codereview.stackexchange", "id": 45151, "lm_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, raspberry-pi", "url": null }
python, raspberry-pi # Start record audio start_audio = [ "ffmpeg", "-f", "alsa", "-acodec", "pcm_s16le", "-ac", "2", "-ar", "44100", "-i", "hw:3,0", # Can sometimes change to hw:1,0 "-y", audio_filename ] # Execute video and audio recording commands in the background video_process = subprocess.Popen(start_video) audio_process = subprocess.Popen(start_audio, stderr=subprocess.PIPE) return video_process, audio_process, video_filename, audio_filename # Stop recording def stop_recording(video_process, audio_process, video_filename, audio_filename): # Terminate video recording process video_process.terminate() # Terminate audio recording process audio_process.terminate() # Wait for the processes to finish video_process.wait() audio_process.wait() # Combine video and audio output_filename = os.path.join(output_directory, "output.mp4") combine_command = [ "ffmpeg", "-i", video_filename, "-i", audio_filename, "-c:v", "copy", "-c:a", "aac", "-strict", "-2", "-y", output_filename ] subprocess.run(combine_command) print("Recording stopped and files merged.") # Start recording when needed (when a button is pressed) video_process, audio_process, video_filename, audio_filename = start_recording() # Sleep for a while (simulating the recording duration) # (For now demo reasons. will be removed) time.sleep(10) # Record for 10 seconds; adjust as needed # Stop recording when needed (when a button is pressed) stop_recording(video_process, audio_process, video_filename, audio_filename) The code is still a WIP as I still need to code that the video itself needs to be uploaded to a site like Vimeo, and then make it to embed it into my Flask-application. There will be start and end record button on said Flask-application. Answer: use Path output_directory = "/home/pi/Videos"
{ "domain": "codereview.stackexchange", "id": 45151, "lm_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, raspberry-pi", "url": null }
python, raspberry-pi Answer: use Path output_directory = "/home/pi/Videos" Prefer to assign ... = Path("~pi/Videos").expanduser(). That way you can compactly refer to output_directory / "audio.wav" without need of a .join(). document the return values def start_recording(): ... return video_process, audio_process, video_filename, audio_filename When we're hacking on a personal project, often there is little need to document tons of details. But here, the return type is complex enough that type annotation would offer benefits, both for human readers and for mypy checking: def start_recording() -> tuple[Popen[bytes], Popen[bytes], str, str]: And tacking on a one-sentence """docstring""" wouldn't hurt. That collection of four related variables is almost big enough that it starts to look ungainly. Consider putting this code in a class so they become self. attributes. Or perhaps a @dataclass. Or a pair of dataclass objects, each holding a Popen and a str. examine the exit status subprocess.run(combine_command) We anticipate that this ffmpeg command typically succeeds. Usually we express such a belief in this way: subprocess.check_call(combine_command) The check_call will raise upon child failure, conveniently showing us a helpful diagnostic message. progress bar time.sleep(10) Or equivalently, assign n = 10 and then it's sleep(n). For such a brief duration there's little room for confusion. But when you start using larger n values, you might want some feedback on whether we're nearly done, using the convenient tqdm library. from tqdm import tqdm ... n = 120 for delay in tqdm([1] * n): sleep(delay)
{ "domain": "codereview.stackexchange", "id": 45151, "lm_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, raspberry-pi", "url": null }
python, raspberry-pi If you wish to offer CLI access to this code, consider using the typer library. The code relies on coupling to some module level / global variables. It would benefit from pushing functions down into class methods. Working out how to capture a combined A/V stream, to avoid synchronization trouble, seems the chief technical challenge to solve. That's outside the scope of this PR. This WIP appears to achieve its current goals. I would be willing to delegate or accept maintenance tasks on this codebase.
{ "domain": "codereview.stackexchange", "id": 45151, "lm_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, raspberry-pi", "url": null }
c++, game, console, tic-tac-toe, windows Title: Tic-tac-toe game for Windows console Question: I am doing C++ for over a year and this is my game I tried making tic-tac-toe. And it's also my first program that uses multiple source files. main.cpp #include"Header.h" #include"GUI.h" #include"UI.h" int main() { int* board = new int[9] {0, 0, 0, 0, 0, 0, 0, 0, 0}; // 1 2 3 // 4 5 6 // 7 8 9 int place{ 0 }; // /\ // || -1 bool turn{ false }; // true = O, false = X bool win{ false }; // flase = no win, true = win int count{ 0 }; // counts ammount of moves while (!win && count < 9) { place = question(board) - 1; system("cls"); turn = change_board(board, turn, place); switch (check_win(board)) { case 0: break; case 1: system("cls"); print(board); change_color(3, 0); cout << "\nPlayer Two won\n"; win = !win; break; case 2: system("cls"); print(board); change_color(4, 0); cout << "\nPlayer one won\n"; win = !win; break; } count++; } if (!win) { system("cls"); print(board); change_color(2, 0); cout << "\nIt's a draw\n"; } change_color(7, 0); return 0; } Header.h using namespace std; #include <iostream> #include<windows.h> GUI.h void change_color(int text, int background); void print(int* board); int question(int* board); GUI.cpp #include"Header.h" char symbols[3]{ ' ', 'X', 'O' }; void change_color(int text, int background) { HANDLE hConsole; int color{ text + 16 * background }; //0 = Black 8 = Gray //1 = Blue 9 = Light Blue //2 = Green a = Light Green //3 = Aqua b = Light Aqua //4 = Red c = Light Red //5 = Purple d = Light Purple //6 = Yellow e = Light Yellow //7 = White f = Bright White
{ "domain": "codereview.stackexchange", "id": 45152, "lm_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, console, tic-tac-toe, windows", "url": null }
c++, game, console, tic-tac-toe, windows hConsole = GetStdHandle(STD_OUTPUT_HANDLE); SetConsoleTextAttribute(hConsole, color); } void color_print(char symbol) { switch (symbol) { case 'X': change_color(4, 0); cout << symbol; change_color(7, 0); break; case 'O': change_color(3, 0); cout << symbol; change_color(7, 0); break; default: cout << ' '; break; } return; } void color_print(int symbol, int place) { switch (symbol) { case 1: change_color(4, 0); cout << 'X'; change_color(7, 0); break; case 2: change_color(3, 0); cout << 'O'; change_color(7, 0); break; default: change_color(2, 0); cout << place + 1; change_color(7, 0); break; } return; } void print(int* board) { for (int column{ 0 }; column < 2; column++) {
{ "domain": "codereview.stackexchange", "id": 45152, "lm_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, console, tic-tac-toe, windows", "url": null }
c++, game, console, tic-tac-toe, windows for (int row{ 0 };row<2;row++) { cout << " "; color_print(symbols[board[3 * column + row]]); cout << " |"; } cout << " "; color_print(symbols[board[3 * column + 2]]); cout << endl; cout << "-----------------\n"; } for (int row{ 0 }; row < 2; row++) { cout << " "; color_print(symbols[board[row + 6]]); cout << " |"; } cout << " "; color_print(symbols[board[8]]); cout << endl; return; } void print_to_ask(int* board) { for (int column{ 0 }; column < 2; column++) { for (int row{ 0 }; row < 2; row++) { cout << " "; color_print(board[3 * column + row], 3 * column + row); cout << " |"; } cout << " "; color_print(board[3 * column + 2], 3 * column + 2); cout << endl; cout << "-----------------\n"; } for (int row{ 0 }; row < 2; row++) { cout << " "; color_print(board[row + 6], row + 6); cout << " |"; } cout << " "; color_print(board[8], 8); cout << endl; return; } int question(int* board) { int place{ 0 }; print_to_ask(board); cout << "\n\n Please, input the place where you want to do your turn: "; cin >> place; if (place < 1 || place > 9 || board[place - 1] != 0) { system("cls"); change_color(0, 4); cout << "Invalid option\nPlease retry\n\n"; change_color(7, 0); place = question(board); } return place; } UI.h bool change_board(int* board, bool turn, int place); int check_win(int* board );
{ "domain": "codereview.stackexchange", "id": 45152, "lm_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, console, tic-tac-toe, windows", "url": null }
c++, game, console, tic-tac-toe, windows UI.h bool change_board(int* board, bool turn, int place); int check_win(int* board ); UI.cpp #include"Header.h" bool change_board(int* board, bool turn, int place) { board[place] = int(turn) + 1; return !turn; } bool check_win_side(int* board, int side) { for (int x{ 0 }; x < 3; x++) { if (board[x] == board[x + 3] && board[x] == board[x + 6] && board[x] == side) return true; } for (int x{ 0 }; x < 3; x++) { if (board[x * 3] == board[x * 3 + 1] && board[x * 3] == board[x * 3 + 2] && board[x * 3] == side) return true; } if ((board[0] == board[4] && board[0] == board[8] && board[0] && board[0] == side) || (board[2] == board[4] && board[2] == board[6] && board[2] == side)) { return true; } return false; } int check_win(int*board) { if (check_win_side(board, 1)) { return 2; } else if (check_win_side(board, 2)) { return 1; } return 0; } Answer: In your check_win function make sure to check if board[0] is not equal to zero before comparing it to side. If board[0] is not equal to zero, it means that this cell is not empty, and you need to check if it belongs to the side player before comparing it. Consider the scenario: board[0] contains 1, indicating that player one (X) has placed their symbol in the top-left cell. Now you want to check if player one (X) has won. In this case, side would be 1 (representing player one). If you didn't check board[0] before comparing it to side, the condition board[0] == side would evaluate to true because 1 (player one's symbol) is indeed equal to 1 (the side being checked). However, this would be incorrect because board[0] already contains a move by player one, and it doesn't necessarily mean they have won yet. Aside from this, the code looks acceptable for test or interview material.
{ "domain": "codereview.stackexchange", "id": 45152, "lm_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, console, tic-tac-toe, windows", "url": null }
c, parsing Title: C-style double expression parser Question: The purpose of this code is to parse any expression as could appear in C that involves doubles or functions that involve only doubles. I have written parsers before: Command line calculator in C Basic recursive descent parser in C
{ "domain": "codereview.stackexchange", "id": 45153, "lm_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, parsing", "url": null }
c, parsing This is an upgraded version that uses more descriptive variable names and structures instead of parallel arrays. This version can also handle functions of varying arity. I was even planning on doing short string optimization here but had to skip that because reasons. #include <math.h> #include <ctype.h> #include <string.h> #include <stdlib.h> typedef struct Symbol { unsigned arity, len; const char *name; union { double func0, (*func1)(double), (*func2)(double, double), (*func3)(double, double, double); }; } Symbol; static int compar(const void *const restrict strp, const void *const restrict p) { const unsigned len = ((const Symbol *)p)->len; const char *const str = *(const char *const *)strp, *const name = ((const Symbol *)p)->name; const int cmp = memcmp(str, name, len); return cmp ? cmp : isalnum((unsigned char)str[len]) || str[len] == '_' ? str[len]-name[len] : (*(const char **)strp += len, 0); } #define SYMBOL(a, n)\ {\ .arity = a,\ .len = sizeof(#n)-1,\ .name = #n,\ .func##a = n\ } static const Symbol symbols[] = { SYMBOL(0, M_1_PI), SYMBOL(0, M_2_PI), SYMBOL(0, M_2_SQRTPI), SYMBOL(0, M_E), SYMBOL(0, M_LN10), SYMBOL(0, M_LN2), SYMBOL(0, M_LOG10E), SYMBOL(0, M_LOG2E), SYMBOL(0, M_PI), SYMBOL(0, M_PI_2), SYMBOL(0, M_PI_4), SYMBOL(0, M_SQRT1_2), SYMBOL(0, M_SQRT2), SYMBOL(1, acos), SYMBOL(1, acosh), SYMBOL(1, asin), SYMBOL(1, asinh), SYMBOL(1, atan), SYMBOL(2, atan2), SYMBOL(1, atanh), SYMBOL(1, cbrt), SYMBOL(1, ceil), SYMBOL(1, cos), SYMBOL(1, cosh), SYMBOL(2, copysign), SYMBOL(1, erf), SYMBOL(1, erfc), SYMBOL(1, exp), SYMBOL(1, exp2), SYMBOL(1, expm1), SYMBOL(1, fabs), SYMBOL(2, fdim), SYMBOL(1, floor), SYMBOL(3, fma), SYMBOL(2, fmax), SYMBOL(2, fmin),
{ "domain": "codereview.stackexchange", "id": 45153, "lm_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, parsing", "url": null }
c, parsing SYMBOL(1, floor), SYMBOL(3, fma), SYMBOL(2, fmax), SYMBOL(2, fmin), SYMBOL(2, fmod), SYMBOL(2, hypot), SYMBOL(1, lgamma), SYMBOL(1, log), SYMBOL(1, log10), SYMBOL(1, log1p), SYMBOL(1, log2), SYMBOL(1, logb), SYMBOL(2, nextafter), SYMBOL(2, pow), SYMBOL(2, remainder), SYMBOL(1, round), SYMBOL(1, sin), SYMBOL(1, sinh), SYMBOL(1, sqrt), SYMBOL(1, tan), SYMBOL(1, tanh), SYMBOL(1, tgamma), SYMBOL(1, trunc) }; static double term(const char **); static double expr(const char **const str, const unsigned level) { *str += level != 0; for (double val = term(str);;) { while (isspace((unsigned char)**str)) ++*str; switch (**str) { case '*': if (level > 2) break; val *= expr(str, 2); continue; case '/': if (level > 2) break; val /= expr(str, 2); continue; case '+': if (level > 1) break; val += expr(str, 1); continue; case '-': if (level > 1) break; val -= expr(str, 1); continue; } return val; } } static double term(const char **const str) { while (isspace((unsigned char)**str)) ++*str; { char *end; const double val = strtod(*str, &end); if (*str != end) { *str = end; return val; } } if (isalpha((unsigned char)**str)) { const Symbol *const symbol = bsearch(str, symbols, sizeof(symbols)/sizeof(Symbol), sizeof(Symbol), compar); if (symbol) { if (!symbol->arity) return symbol->func0; while (isspace((unsigned char)**str)) ++*str; if (*(*str)++ == '(') {
{ "domain": "codereview.stackexchange", "id": 45153, "lm_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, parsing", "url": null }
c, parsing ++*str; if (*(*str)++ == '(') { double vals[symbol->arity]; for (unsigned i = 0;;) { vals[i] = expr(str, 0); if (++i >= symbol->arity) { if (*(*str)++ == ')') switch (symbol->arity) { case 1: return symbol->func1(vals[0]); case 2: return symbol->func2(vals[0], vals[1]); case 3: return symbol->func3(vals[0], vals[1], vals[2]); } } else if (*(*str)++ == ',') continue; break; } } } } else switch (*(*str)++) { case '+': return term(str); case '-': return -term(str); case '(': { const double val = expr(str, 0); if (*(*str)++ == ')') return val; } } return NAN; } #include <stdio.h> int main(int argc, char **argv) { for (int arg = 1; arg < argc; ++arg) if (printf("%g\n", expr(&(const char *){argv[arg]}, 0)) < 0) return EXIT_FAILURE; return EXIT_SUCCESS; }
{ "domain": "codereview.stackexchange", "id": 45153, "lm_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, parsing", "url": null }
c, parsing Answer: Bug memcmp(str, name, len); lets memcmp() compare the first len bytes of the data pointed to by str and name, yet some of those are pointers to a string less than len in size. What code needs is strncmp() (or perhaps even strcmp()) to not compare past the end of the string. Bug The *(const char **)strp += len relies on bsearch() to stop calling cmp() once a return value of 0 occurs. Although this is common, bsearch()is not specified that way. Instead the calling code should advance the pointer, not the compare function. Pedantic Bug str[len]-name[len] in compar() should be an unsigned char compare to well sort symbols that have a character outside the [0...CHAR_MAX] range. Yet since, presently, symbols[] only employs ASCII characters, it does not make a difference. Non-standard macros M_PI and its 13 friends are not part of the C standard. See Using M_PI. Consider #ifndef M_PI #define M_PI 3.1415926535897932384626433832795 #endif Lack of comments Functions deserve at least a little description to indicate its role. Consider long double Consider using the most precise/widest range floating point type available. Use a more precise output Rather than only 6 digits, use the precision of the type: // printf("%g\n", some_double) printf("%.*g\n", DBL_DIG, some_double) Missing break; case '(': { .. deserves a break; at the end of the case or a comment indicating fall-through was desired. double expr() missing return value; TBD code needed to quiet "Problem description: No return, in function returning non-void". Minor: Excessive use of const object object would simplify code presentation in many places where there is only a few lines of code. Example: // const double val = expr(str, 0); double val = expr(str, 0); if (*(*str)++ == ')') return val;
{ "domain": "codereview.stackexchange", "id": 45153, "lm_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, parsing", "url": null }
c, parsing Format to presentation width Use an auto-formatter and present to the display width (e.g. ~82) 1 2 3 4 5 6 7 8 9 1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890 // const Symbol *const symbol = bsearch(str, symbols, sizeof(symbols)/sizeof(Symbol), sizeof(Symbol), compar); const Symbol *const symbol = bsearch(str, symbols, sizeof(symbols)/sizeof(Symbol), sizeof(Symbol), compar); Note the () are not needed with sizeof object. Avoid names that differ only in case // v----v v----v const Symbol *const symbol Vertical spacing Between functions, types, consider a blank line.
{ "domain": "codereview.stackexchange", "id": 45153, "lm_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, parsing", "url": null }
c#, .net, ipc Title: Client disconnection and reconnection in C# NamedPipeServerStream Question: I have written a C# .NET code that utilizes NamedPipeServerStream to send and receive data. My goal is to ensure that when a client disconnects, the server waits and then establishes a new connection when the client reconnects. The code seems to work in my initial tests, but since I'm new to this, I'm unsure if I've implemented it correctly. my main concern is with memory leaks, performance, and the way I handle Named Pipes recovery when a client disconnects. I would greatly appreciate any suggestions or insights on whether this is the proper way to achieve this. Here's the code I've written: using System.IO.Pipes; using System.Text; namespace Service.IPC; public class PipeServer { private NamedPipeServerStream _pipeServer; private readonly string _pipeName; private StreamReader reader; private Thread readThread; private bool threadRunning = false; private readonly ILogger<PWService> _logger; public event EventHandler<DataEventArgs> DataReceived; public PipeServer(string pipeName, ILogger<PWService> logger) { _logger = logger; _pipeName = pipeName; _pipeServer = new NamedPipeServerStream(_pipeName, PipeDirection.InOut, 4, PipeTransmissionMode.Byte, PipeOptions.Asynchronous); _logger.LogInformation("Pipe Name: {pipeName}", pipeName); }
{ "domain": "codereview.stackexchange", "id": 45154, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c#, .net, ipc", "url": null }
c#, .net, ipc public void Start() { Thread thread = new(async () => { while (true) { if (_pipeServer.IsConnected) { if (!threadRunning) { readThread = new Thread(ReadData) { Name = "NamedPipeServerReadThread", IsBackground = true }; readThread.Start(); threadRunning = true; } } else { if (!threadRunning) { _logger.LogInformation("Waiting for connecction..."); await _pipeServer.WaitForConnectionAsync(); _logger.LogInformation("Connected..."); } else { _pipeServer.Dispose(); _pipeServer = new NamedPipeServerStream(_pipeName, PipeDirection.InOut, 4, PipeTransmissionMode.Byte, PipeOptions.Asynchronous); } } } }) { Name = "NamedPipeServerThread", IsBackground = true }; thread.Start(); } public void Stop() { readThread.Interrupt(); _pipeServer.Close(); } private async void ReadData() { byte[] buffer = new byte[1024]; int bytesRead; while (true) { if (_pipeServer.IsConnected) { bytesRead = await _pipeServer.ReadAsync(buffer); if (bytesRead == 0) break;
{ "domain": "codereview.stackexchange", "id": 45154, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c#, .net, ipc", "url": null }
c#, .net, ipc if (bytesRead == 0) break; string data = Encoding.UTF8.GetString(buffer, 0, bytesRead); string[] parts = data.Split(','); if (parts.Length == 2) { DataReceived?.Invoke(this, new DataEventArgs { Title = parts[0], Message = parts[1] }); } } else { break; } } threadRunning = false; } public async void Send(string title, string message) { try { if (_pipeServer.IsConnected) { await _pipeServer.WriteAsync(Encoding.UTF8.GetBytes(title + "," + message)); } } catch (Exception) { } } } ``` Answer: Basics The class owns an object of type NamedPipeServerStream which is IDisposable. IDisposable is a sticky interface - if you own an object that's IDisposable then so are you. Consequently your wrapper needs to be IDisposable. Design Issues I haven't run the code but I'm pretty sure that this path constitutes a busy wait loop that will tie up an entire CPU core when the server has an established connection from a client: while (true) { if (_pipeServer.IsConnected) { if (!threadRunning) { .... } } else { ... }
{ "domain": "codereview.stackexchange", "id": 45154, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c#, .net, ipc", "url": null }
c#, .net, ipc IsConnected will be true and threadRunning will be true so the whole while boils down to a repeated check on the IsConnected flag without any pause. This probably boils down to maybe 3 CPU instructions or so (2 loads and one compare) that get executed as fast as the CPU will go. This seems very wasteful. Also be careful with Thread.Interrupt() - if the thread never blocks it will never get interrupted. In this specific case it's probably safe to assume that bytesRead = await _pipeServer.ReadAsync(buffer); will block at some point but it's not good practice. You should use CancellationTokens to cancel background work - that's what they were made for, especially in the context of async and await. Pretty much all *Async() method accept a CancellationToken. Alternate Approach On the whole I would probably structure the main loop something like this, wrapped in a Task that you can store as a class member: this._cancellationTokenSource = nwe CancellationTokenSource(); this._cancellationToken = _cancellationTokenSource.Token; var shouldQuit = false; while (!shouldQuit) { try { _pipeServer = new NamedPipeServerStream(...); _logger.LogInformation("Waiting for connection..."); await _pipeServer.WaitForConnectionAsync(_cancellationToken); _logger.LogInformation("Connected, starting read loop..."); await ReadDataAsync(_cancellationToken); } catch (OperationCanceledException) { _logger.LogInformation("Shutdown requested..."); shouldQuit = true; } catch (IOException) { _Logger.LogInformation(Broken pipe, client disconnected..."); } } And ReadDataAsync then boils down to something like this: Task ReadDataAsync(CancellationToken cancellationToken) { byte[] buffer = new byte[1024]; int bytesRead; while (true) { bytesRead = await _pipeServer.ReadAsync(buffer, cancellationToken); if (bytesRead == 0) break;
{ "domain": "codereview.stackexchange", "id": 45154, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c#, .net, ipc", "url": null }
c#, .net, ipc if (bytesRead == 0) break; string data = Encoding.UTF8.GetString(buffer, 0, bytesRead); string[] parts = data.Split(','); if (parts.Length == 2) { DataReceived?.Invoke(this, new DataEventArgs { Title = parts[0], Message = parts[1] }); } } } Taking the basics from above into account, the cleanup should happen in Dispose which should cancel the token and then await the main task to finish.
{ "domain": "codereview.stackexchange", "id": 45154, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c#, .net, ipc", "url": null }
c++, validation, c++14 Title: Improved input validation function Question: A week ago I posted this question and after reading the answers and accepting one I decided to refactor my code quite heavily. I would like to get some feedback on this newer version. The changes No more predicates! I'd like it to look exactly like Python's input() function. Always return a string and let the user parse it as needed (just like Python). Keeping 2 of the custom exceptions I made because I want the user to be able to handle them specifically. I know std::ios_base::failure exists but I want to separate it into different exception types. The design choices I stuck with I'd like to keep input() as a function, so I'm not making it a class on purpose. I know it is tightly coupled to std::cin and no other streams and it's on purpose. I'd like any new user to be able to just copy paste this input function and not worry about validation when reading input from the user. I would like to keep this C++14 for now. Validation rationale for std::cin cppref - Look at the code example learncpp - near the end of the lesson Last thoughts If I were to make this a class instead of a function I would just try to implement a Scanner (Java-like) that takes std::istream& which would make it usable with any input stream. But for now I want to keep it std::cin only because it will be shorter and simpler. The code #include <stdexcept> #include <iostream> #include <string> #include <limits> /* Custom exceptions -------------------------------------------------------- */ class StreamFailure final : public std::runtime_error { public: StreamFailure() : std::runtime_error{ "Stream failed (non-recoverable state)" } {} }; class ExtractionFailure final : public std::runtime_error { public: ExtractionFailure() : std::runtime_error{ "Failed to extract value from stream" } {} };
{ "domain": "codereview.stackexchange", "id": 45155, "lm_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++, validation, c++14", "url": null }
c++, validation, c++14 /* Simplified input --------------------------------------------------------- */ std::string input(const std::string& prompt = "") { if(!prompt.empty()) { std::cout << prompt; } std::string temp{}; // <-- unavoidable if i want it to look like python std::getline(std::cin, temp); if(std::cin.eof() || std::cin.bad()) { throw StreamFailure{}; // <--should rarely happen for any type extracted } else if(std::cin.fail()) { std::cin.clear(); std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); throw ExtractionFailure{}; // <-- pretty hard to make this happen with // std::string } return temp; } int main() { while (true) { try { int i = std::stoi(input("Enter an integer: ")); std::cout << i << '\n'; } catch (std::invalid_argument const& e) { std::cerr << "invalid_argument\n"; } catch (std::out_of_range const& e) { std::cerr << "out_of_range\n"; } catch(const std::exception& e) { std::cerr << e.what() << '\n'; break; } } return 0; } Answer: After reading @indi explain what problem I have with my code I've fixed it in accordance with the comments he left. If anyone sees any more problems with it you are welcome to point it out. The new input function: std::string input(const std::string& prompt = "") { if(!prompt.empty()) { std::cout << prompt; } std::string temp{}; std::getline(std::cin, temp); if(!std::cin) { if(std::cin.eof() || std::cin.bad()) { throw StreamFailure{}; } else { std::cin.clear(); std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); throw ExtractionFailure{}; } } return temp; }
{ "domain": "codereview.stackexchange", "id": 45155, "lm_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++, validation, c++14", "url": null }
c++, recursion, template, c++20, constrained-templates Title: A recursive_reduce_string Template Function Implementation in C++ Question: This is a follow-up question for A recursive_sum Template Function Implementation with Unwrap Level in C++, A recursive_reduce_all Template Function Implementation in C++, A recursive_reduce Template Function with Unwrap Level Implementation in C++ and A recursive_depth Function Implementation with Target Type Parameter in C++. Considering the answer provided by G. Sliepen, std::string test cases are mentioned. For dealing with these nested std::string cases, recursive_reduce_string template function is introduced in this post. The experimental implementation recursive_reduce_string template function implementation // recursive_reduce_string template function template<class T> requires(std::same_as<T, std::string>) constexpr auto recursive_reduce_string(const T& input1) { return input1; } template<std::ranges::input_range T> requires (std::same_as<recursive_unwrap_type_t<recursive_depth<T>() - 1, T>, std::string> && recursive_depth<T>() - 1 == 1) constexpr auto recursive_reduce_string(const T& input) { auto output = input.at(0); for(int i = 1; i < std::ranges::size(input); i++) { output+=input.at(i); } return output; } template<std::ranges::input_range T> constexpr auto recursive_reduce_string(const T& input) { auto result = recursive_reduce_string( UL::recursive_transform<recursive_depth<T>() - 2>( input, [](auto&& element){ return recursive_reduce_string(element); }) ); return result; } Full Testing Code The full testing code: // A `recursive_reduce_string` Template Function Implementation in C++ #include <algorithm> #include <array> #include <chrono> #include <concepts> #include <deque> #include <execution> #include <iostream> #include <queue> #include <ranges> #include <string> #include <vector>
{ "domain": "codereview.stackexchange", "id": 45156, "lm_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++, recursion, template, c++20, constrained-templates", "url": null }
c++, recursion, template, c++20, constrained-templates // is_reservable concept template<class T> concept is_reservable = requires(T input) { input.reserve(1); }; // is_sized concept, https://codereview.stackexchange.com/a/283581/231235 template<class T> concept is_sized = requires(T x) { std::size(x); }; // has_arithmetic_operations concept template<class T> concept has_arithmetic_operations = requires(T input) { std::plus<>{}(input, input); std::minus<>{}(input, input); std::multiplies<>{}(input, input); std::divides<>{}(input, input); }; // recursive_depth function implementation template<typename T> constexpr std::size_t recursive_depth() { return std::size_t{0}; } template<std::ranges::input_range Range> constexpr std::size_t recursive_depth() { return recursive_depth<std::ranges::range_value_t<Range>>() + std::size_t{1}; } // recursive_variadic_invoke_result_t implementation template<std::size_t, typename, typename, typename...> struct recursive_variadic_invoke_result { }; template<typename F, class...Ts1, template<class...>class Container1, typename... Ts> struct recursive_variadic_invoke_result<1, F, Container1<Ts1...>, Ts...> { using type = Container1<std::invoke_result_t<F, std::ranges::range_value_t<Container1<Ts1...>>, std::ranges::range_value_t<Ts>...>>; };
{ "domain": "codereview.stackexchange", "id": 45156, "lm_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++, recursion, template, c++20, constrained-templates", "url": null }
c++, recursion, template, c++20, constrained-templates template<std::size_t unwrap_level, typename F, class...Ts1, template<class...>class Container1, typename... Ts> requires ( std::ranges::input_range<Container1<Ts1...>> && requires { typename recursive_variadic_invoke_result< unwrap_level - 1, F, std::ranges::range_value_t<Container1<Ts1...>>, std::ranges::range_value_t<Ts>...>::type; }) // The rest arguments are ranges struct recursive_variadic_invoke_result<unwrap_level, F, Container1<Ts1...>, Ts...> { using type = Container1< typename recursive_variadic_invoke_result< unwrap_level - 1, F, std::ranges::range_value_t<Container1<Ts1...>>, std::ranges::range_value_t<Ts>... >::type>; }; template<std::size_t unwrap_level, typename F, typename T1, typename... Ts> using recursive_variadic_invoke_result_t = typename recursive_variadic_invoke_result<unwrap_level, F, T1, Ts...>::type; // recursive_array_invoke_result implementation template<std::size_t, typename, typename, typename...> struct recursive_array_invoke_result { }; template< typename F, template<class, std::size_t> class Container, typename T, std::size_t N> struct recursive_array_invoke_result<1, F, Container<T, N>> { using type = Container< std::invoke_result_t<F, std::ranges::range_value_t<Container<T, N>>>, N>; };
{ "domain": "codereview.stackexchange", "id": 45156, "lm_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++, recursion, template, c++20, constrained-templates", "url": null }
c++, recursion, template, c++20, constrained-templates template< std::size_t unwrap_level, typename F, template<class, std::size_t> class Container, typename T, std::size_t N> requires ( std::ranges::input_range<Container<T, N>> && requires { typename recursive_array_invoke_result< unwrap_level - 1, F, std::ranges::range_value_t<Container<T, N>>>::type; }) // The rest arguments are ranges struct recursive_array_invoke_result<unwrap_level, F, Container<T, N>> { using type = Container< typename recursive_array_invoke_result< unwrap_level - 1, F, std::ranges::range_value_t<Container<T, N>> >::type, N>; }; template< std::size_t unwrap_level, typename F, template<class, std::size_t> class Container, typename T, std::size_t N> using recursive_array_invoke_result_t = typename recursive_array_invoke_result<unwrap_level, F, Container<T, N>>::type; // recursive_unwrap_type_t struct implementation, https://codereview.stackexchange.com/q/284610/231235 template<std::size_t, typename, typename...> struct recursive_unwrap_type { }; template<class...Ts1, template<class...>class Container1, typename... Ts> struct recursive_unwrap_type<1, Container1<Ts1...>, Ts...> { using type = std::ranges::range_value_t<Container1<Ts1...>>; };
{ "domain": "codereview.stackexchange", "id": 45156, "lm_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++, recursion, template, c++20, constrained-templates", "url": null }
c++, recursion, template, c++20, constrained-templates template<std::size_t unwrap_level, class...Ts1, template<class...>class Container1, typename... Ts> requires ( std::ranges::input_range<Container1<Ts1...>> && requires { typename recursive_unwrap_type< unwrap_level - 1, std::ranges::range_value_t<Container1<Ts1...>>, std::ranges::range_value_t<Ts>...>::type; }) // The rest arguments are ranges struct recursive_unwrap_type<unwrap_level, Container1<Ts1...>, Ts...> { using type = typename recursive_unwrap_type< unwrap_level - 1, std::ranges::range_value_t<Container1<Ts1...>> >::type; }; template<std::size_t unwrap_level, typename T1, typename... Ts> using recursive_unwrap_type_t = typename recursive_unwrap_type<unwrap_level, T1, Ts...>::type; // recursive_array_unwrap_type struct implementation, https://stackoverflow.com/a/76347485/6667035 template<std::size_t, typename> struct recursive_array_unwrap_type { }; template<template<class, std::size_t> class Container, typename T, std::size_t N> struct recursive_array_unwrap_type<1, Container<T, N>> { using type = std::ranges::range_value_t<Container<T, N>>; }; template<std::size_t unwrap_level, template<class, std::size_t> class Container, typename T, std::size_t N> requires ( std::ranges::input_range<Container<T, N>> && requires { typename recursive_array_unwrap_type< unwrap_level - 1, std::ranges::range_value_t<Container<T, N>>>::type; }) // The rest arguments are ranges struct recursive_array_unwrap_type<unwrap_level, Container<T, N>> { using type = typename recursive_array_unwrap_type< unwrap_level - 1, std::ranges::range_value_t<Container<T, N>> >::type; };
{ "domain": "codereview.stackexchange", "id": 45156, "lm_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++, recursion, template, c++20, constrained-templates", "url": null }
c++, recursion, template, c++20, constrained-templates template<std::size_t unwrap_level, class Container> using recursive_array_unwrap_type_t = typename recursive_array_unwrap_type<unwrap_level, Container>::type; // https://codereview.stackexchange.com/a/253039/231235 template<template<class...> class Container = std::vector, std::size_t dim, class T> constexpr auto n_dim_container_generator(T input, std::size_t times) { if constexpr (dim == 0) { return input; } else { return Container(times, n_dim_container_generator<Container, dim - 1, T>(input, times)); } } namespace UL // unwrap_level { template< std::ranges::input_range Container, std::copy_constructible F> requires (std::ranges::view<Container>&& std::is_object_v<F>) constexpr auto make_view(const Container& input, const F& f) noexcept { return std::ranges::transform_view( input, [&f](const auto&& element) constexpr { return recursive_transform(element, f ); } ); } /* Override make_view to catch dangling references. A borrowed range is * safe from dangling.. */ template <std::ranges::input_range T> requires (!std::ranges::borrowed_range<T>) constexpr std::ranges::dangling make_view(T&&) noexcept { return std::ranges::dangling(); }
{ "domain": "codereview.stackexchange", "id": 45156, "lm_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++, recursion, template, c++20, constrained-templates", "url": null }
c++, recursion, template, c++20, constrained-templates // clone_empty_container template function implementation template< std::size_t unwrap_level = 1, std::ranges::input_range Container, std::copy_constructible F> requires (std::ranges::view<Container>&& std::is_object_v<F>) constexpr auto clone_empty_container(const Container& input, const F& f) noexcept { const auto view = make_view(input, f); recursive_variadic_invoke_result<unwrap_level, F, Container> output(std::span{input}); return output; } // recursive_transform template function implementation (the version with unwrap_level template parameter) template< std::size_t unwrap_level = 1, class T, std::copy_constructible F, class Proj = std::identity> requires (unwrap_level <= recursive_depth<T>()&& // handling incorrect unwrap levels more gracefully, https://codereview.stackexchange.com/a/283563/231235 std::ranges::view<T>&& std::is_object_v<F>) constexpr auto recursive_transform(const T& input, const F& f, Proj proj = {} ) { if constexpr (unwrap_level > 0) { auto output = clone_empty_container(input, f); if constexpr (is_reservable<decltype(output)> && is_sized<decltype(input)> && std::indirectly_writable<decltype(output), std::indirect_result_t<F&, std::projected<std::ranges::iterator_t<T>, Proj>>>) { output.reserve(input.size()); std::ranges::transform( input, std::ranges::begin(output), [&f](auto&& element) { return recursive_transform<unwrap_level - 1>(element, f); }, proj ); } else { std::ranges::transform( input,
{ "domain": "codereview.stackexchange", "id": 45156, "lm_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++, recursion, template, c++20, constrained-templates", "url": null }
c++, recursion, template, c++20, constrained-templates else { std::ranges::transform( input, std::inserter(output, std::ranges::end(output)), [&f](auto&& element) { return recursive_transform<unwrap_level - 1>(element, f); }, proj ); } return output; } else if constexpr(std::regular_invocable<F, T>) { return std::invoke(f, std::invoke(proj, input)); } else { static_assert(!std::regular_invocable<F, T>, "Uninvocable?"); } }
{ "domain": "codereview.stackexchange", "id": 45156, "lm_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++, recursion, template, c++20, constrained-templates", "url": null }
c++, recursion, template, c++20, constrained-templates /* This overload of recursive_transform is to support std::array */ template< std::size_t unwrap_level = 1, template<class, std::size_t> class Container, typename T, std::size_t N, typename F > requires (std::ranges::input_range<Container<T, N>>) constexpr auto recursive_transform(const Container<T, N>& input, const F& f) { recursive_array_invoke_result_t<unwrap_level, F, Container, T, N> output{}; if constexpr (unwrap_level > 1) { std::ranges::transform( input, std::ranges::begin(output), [&f](auto&& element) { return recursive_transform<unwrap_level - 1>(element, f); } ); } else { std::ranges::transform( input, std::ranges::begin(output), f ); } return output; }
{ "domain": "codereview.stackexchange", "id": 45156, "lm_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++, recursion, template, c++20, constrained-templates", "url": null }
c++, recursion, template, c++20, constrained-templates // recursive_transform function implementation (the version with unwrap_level, without using view) template<std::size_t unwrap_level = 1, class T, class F> requires (unwrap_level <= recursive_depth<T>()&& // handling incorrect unwrap levels more gracefully, https://codereview.stackexchange.com/a/283563/231235 !std::ranges::view<T>) constexpr auto recursive_transform(const T& input, const F& f) { if constexpr (unwrap_level > 0) { recursive_variadic_invoke_result_t<unwrap_level, F, T> output{}; std::ranges::transform( input, // passing a range to std::ranges::transform() std::inserter(output, std::ranges::end(output)), [&f](auto&& element) { return recursive_transform<unwrap_level - 1>(element, f); } ); return output; } else { return std::invoke(f, input); // use std::invoke() } }
{ "domain": "codereview.stackexchange", "id": 45156, "lm_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++, recursion, template, c++20, constrained-templates", "url": null }
c++, recursion, template, c++20, constrained-templates // recursive_transform implementation (the version with unwrap_level, with execution policy) template<std::size_t unwrap_level = 1, class ExPo, class T, std::copy_constructible F> requires (unwrap_level <= recursive_depth<T>() && // handling incorrect unwrap levels more gracefully, https://codereview.stackexchange.com/a/283563/231235 std::is_execution_policy_v<std::remove_cvref_t<ExPo>>) constexpr auto recursive_transform(ExPo execution_policy, const T& input, const F& f) { if constexpr (unwrap_level > 0) { recursive_variadic_invoke_result_t<unwrap_level, F, T> output{}; output.resize(input.size()); std::mutex mutex; std::transform(execution_policy, std::ranges::cbegin(input), std::ranges::cend(input), std::ranges::begin(output), [&](auto&& element) { std::lock_guard lock(mutex); return recursive_transform<unwrap_level - 1>(execution_policy, element, f); }); return output; } else { return std::invoke(f, input); } }
{ "domain": "codereview.stackexchange", "id": 45156, "lm_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++, recursion, template, c++20, constrained-templates", "url": null }
c++, recursion, template, c++20, constrained-templates // recursive_transform implementation (binary case, the version with unwrap_level) template<std::size_t unwrap_level = 1, class ExPo, std::ranges::input_range R1, std::ranges::input_range R2, std::copy_constructible F> constexpr auto recursive_transform(ExPo execution_policy, const R1& input1, const R2& input2, const F& f) { if constexpr (unwrap_level > 0) { recursive_variadic_invoke_result_t<unwrap_level, F, R1> output{}; output.resize(input1.size()); std::mutex mutex; std::transform(execution_policy, std::ranges::cbegin(input1), std::ranges::cend(input1), std::ranges::cbegin(input2), std::ranges::begin(output), [&](auto&& element1, auto&& element2) { std::lock_guard lock(mutex); return recursive_transform<unwrap_level - 1>(execution_policy, element1, element2, f); }); return output; } else { return std::invoke(f, input1, input2); } } } /* recursive_reduce_all template function performs operation on input container exhaustively https://codereview.stackexchange.com/a/285831/231235 */ template<typename T> // No constraint since we're not reducing anything here! constexpr auto recursive_reduce_all(const T& input) { return input; } template<std::ranges::input_range T> requires (has_arithmetic_operations<recursive_unwrap_type_t<recursive_depth<T>(), T>> && recursive_depth<T>() == 1) constexpr auto recursive_reduce_all(const T& input) { return std::reduce(std::ranges::cbegin(input), std::ranges::cend(input)); }
{ "domain": "codereview.stackexchange", "id": 45156, "lm_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++, recursion, template, c++20, constrained-templates", "url": null }
c++, recursion, template, c++20, constrained-templates // overload for std::array template<template<class, std::size_t> class Container, typename T, std::size_t N> requires (has_arithmetic_operations<recursive_array_unwrap_type_t<recursive_depth<Container<T, N>>(), Container<T, N>>> && recursive_depth<Container<T, N>>() == 1) constexpr auto recursive_reduce_all(const Container<T, N>& input) { return std::reduce(std::ranges::cbegin(input), std::ranges::cend(input)); } template<std::ranges::input_range T> requires (has_arithmetic_operations<recursive_unwrap_type_t<recursive_depth<T>(), T>> && std::ranges::input_range<recursive_unwrap_type_t<1, T>>) constexpr auto recursive_reduce_all(const T& input) { auto result = recursive_reduce_all( UL::recursive_transform<recursive_depth<T>() - 1>(input, [](auto&& element){ return recursive_reduce_all(element); }) ); return result; } // recursive_reduce_all template function with execution policy template<class ExPo, has_arithmetic_operations T> requires (std::is_execution_policy_v<std::remove_cvref_t<ExPo>>) constexpr auto recursive_reduce_all(ExPo execution_policy, const T& input) { return input; } template<class ExPo, std::ranges::input_range T> requires (std::is_execution_policy_v<std::remove_cvref_t<ExPo>> && has_arithmetic_operations<recursive_unwrap_type_t<recursive_depth<T>(), T>> && recursive_depth<T>() == 1) constexpr auto recursive_reduce_all(ExPo execution_policy, const T& input) { return std::reduce(execution_policy, std::ranges::cbegin(input), std::ranges::cend(input)); }
{ "domain": "codereview.stackexchange", "id": 45156, "lm_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++, recursion, template, c++20, constrained-templates", "url": null }
c++, recursion, template, c++20, constrained-templates // recursive_reduce_all template function with execution policy, overload for std::array template<class ExPo, template<class, std::size_t> class Container, typename T, std::size_t N> requires (std::is_execution_policy_v<std::remove_cvref_t<ExPo>> && has_arithmetic_operations<recursive_array_unwrap_type_t<recursive_depth<Container<T, N>>(), Container<T, N>>> && recursive_depth<Container<T, N>>() == 1) constexpr auto recursive_reduce_all(ExPo execution_policy, const Container<T, N>& input) { return std::reduce(execution_policy, std::ranges::cbegin(input), std::ranges::cend(input)); } template<class ExPo, std::ranges::input_range T> requires (std::is_execution_policy_v<std::remove_cvref_t<ExPo>> && has_arithmetic_operations<recursive_unwrap_type_t<recursive_depth<T>(), T>> && std::ranges::input_range<recursive_unwrap_type_t<1, T>>) constexpr auto recursive_reduce_all(ExPo execution_policy, const T& input) { auto result = recursive_reduce_all( UL::recursive_transform<recursive_depth<T>() - 1>( execution_policy, input, [&](auto&& element){ return recursive_reduce_all(execution_policy, element); } ) ); return result; } // recursive_reduce_all template function with initial value template<has_arithmetic_operations T> constexpr auto recursive_reduce_all(const T& input1, const T& input2) { return input1 + input2; } template<std::ranges::input_range T, class TI> requires (has_arithmetic_operations<recursive_unwrap_type_t<recursive_depth<T>(), T>> && std::same_as<recursive_unwrap_type_t<recursive_depth<T>(), T>, TI> && recursive_depth<T>() == 1) constexpr auto recursive_reduce_all(const T& input, TI init) { return std::reduce(std::ranges::cbegin(input), std::ranges::cend(input), init); }
{ "domain": "codereview.stackexchange", "id": 45156, "lm_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++, recursion, template, c++20, constrained-templates", "url": null }
c++, recursion, template, c++20, constrained-templates // recursive_reduce_all template function with initial value, overload for std::array template<template<class, std::size_t> class Container, typename T, std::size_t N, class TI> requires (has_arithmetic_operations<recursive_array_unwrap_type_t<recursive_depth<Container<T, N>>(), Container<T, N>>> && std::same_as<recursive_array_unwrap_type_t<recursive_depth<Container<T, N>>(), Container<T, N>>, TI> && recursive_depth<Container<T, N>>() == 1) constexpr auto recursive_reduce_all(const Container<T, N>& input, TI init) { return std::reduce(std::ranges::cbegin(input), std::ranges::cend(input), init); } template<std::ranges::input_range T, class TI> requires (has_arithmetic_operations<recursive_unwrap_type_t<recursive_depth<T>(), T>> && std::ranges::input_range<recursive_unwrap_type_t<1, T>> && std::same_as<recursive_unwrap_type_t<recursive_depth<T>(), T>, TI>) constexpr auto recursive_reduce_all(const T& input, TI init) { auto result = init + recursive_reduce_all( UL::recursive_transform<recursive_depth<T>() - 1>( input, [&](auto&& element){ return recursive_reduce_all(element); }) ); return result; } // recursive_reduce_all template function with execution policy and initial value template<class ExPo, has_arithmetic_operations T> requires (std::is_execution_policy_v<std::remove_cvref_t<ExPo>>) constexpr auto recursive_reduce_all(ExPo execution_policy, const T& input1, const T& input2) { return input1 + input2; }
{ "domain": "codereview.stackexchange", "id": 45156, "lm_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++, recursion, template, c++20, constrained-templates", "url": null }
c++, recursion, template, c++20, constrained-templates template<class ExPo, std::ranges::input_range T, class TI> requires (std::is_execution_policy_v<std::remove_cvref_t<ExPo>> && has_arithmetic_operations<recursive_unwrap_type_t<recursive_depth<T>(), T>> && std::same_as<recursive_unwrap_type_t<recursive_depth<T>(), T>, TI> && recursive_depth<T>() == 1) constexpr auto recursive_reduce_all(ExPo execution_policy, const T& input, TI init) { return std::reduce(execution_policy, std::ranges::cbegin(input), std::ranges::cend(input), init); } // recursive_reduce_all template function with execution policy and initial value, overload for std::array template<class ExPo, template<class, std::size_t> class Container, typename T, std::size_t N, class TI> requires (std::is_execution_policy_v<std::remove_cvref_t<ExPo>> && has_arithmetic_operations<recursive_array_unwrap_type_t<recursive_depth<Container<T, N>>(), Container<T, N>>> && std::same_as<recursive_array_unwrap_type_t<recursive_depth<Container<T, N>>(), Container<T, N>>, TI> && recursive_depth<Container<T, N>>() == 1) constexpr auto recursive_reduce_all(ExPo execution_policy, const Container<T, N>& input, TI init) { return std::reduce(execution_policy, std::ranges::cbegin(input), std::ranges::cend(input), init); }
{ "domain": "codereview.stackexchange", "id": 45156, "lm_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++, recursion, template, c++20, constrained-templates", "url": null }
c++, recursion, template, c++20, constrained-templates template<class ExPo, std::ranges::input_range T, class TI> requires (std::is_execution_policy_v<std::remove_cvref_t<ExPo>> && has_arithmetic_operations<recursive_unwrap_type_t<recursive_depth<T>(), T>> && std::ranges::input_range<recursive_unwrap_type_t<1, T>> && std::same_as<recursive_unwrap_type_t<recursive_depth<T>(), T>, TI>) constexpr auto recursive_reduce_all(ExPo execution_policy, const T& input, TI init) { auto result = init + recursive_reduce_all( UL::recursive_transform<recursive_depth<T>() - 1>( execution_policy, input, [&](auto&& element){ return recursive_reduce_all(execution_policy, element); }) ); return result; } // recursive_reduce_all template function with initial value and specified operation template<has_arithmetic_operations T, class BinaryOp> requires (std::regular_invocable<BinaryOp, T, T>) constexpr auto recursive_reduce_all(const T& input1, const T& input2, BinaryOp binary_op) { return std::invoke(binary_op, input1, input2); } template<std::ranges::input_range T, class TI, class BinaryOp> requires (has_arithmetic_operations<recursive_unwrap_type_t<recursive_depth<T>(), T>> && std::same_as<recursive_unwrap_type_t<recursive_depth<T>(), T>, TI> && recursive_depth<T>() == 1 && std::regular_invocable< BinaryOp, recursive_unwrap_type_t<recursive_depth<T>(),T>, recursive_unwrap_type_t<recursive_depth<T>(), T>> ) constexpr auto recursive_reduce_all(const T& input, TI init, BinaryOp binary_op) { return std::reduce(std::ranges::cbegin(input), std::ranges::cend(input), init, binary_op); }
{ "domain": "codereview.stackexchange", "id": 45156, "lm_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++, recursion, template, c++20, constrained-templates", "url": null }
c++, recursion, template, c++20, constrained-templates // recursive_reduce_all template function with initial value and specified operation, overload for std::array template<template<class, std::size_t> class Container, typename T, std::size_t N, class TI, class BinaryOp> requires (has_arithmetic_operations<recursive_array_unwrap_type_t<recursive_depth<Container<T, N>>(), Container<T, N>>> && std::same_as<recursive_array_unwrap_type_t<recursive_depth<Container<T, N>>(), Container<T, N>>, TI> && recursive_depth<Container<T, N>>() == 1 && std::regular_invocable< BinaryOp, recursive_array_unwrap_type_t<recursive_depth<Container<T, N>>(), Container<T, N>>, recursive_array_unwrap_type_t<recursive_depth<Container<T, N>>(), Container<T, N>>> ) constexpr auto recursive_reduce_all(const Container<T, N>& input, TI init, BinaryOp binary_op) { return std::reduce(std::ranges::cbegin(input), std::ranges::cend(input), init, binary_op); } template<std::ranges::input_range T, class TI, class BinaryOp> requires (has_arithmetic_operations<recursive_unwrap_type_t<recursive_depth<T>(), T>> && std::ranges::input_range<recursive_unwrap_type_t<1, T>> && std::same_as<recursive_unwrap_type_t<recursive_depth<T>(), T>, TI> && std::regular_invocable< BinaryOp, recursive_unwrap_type_t<recursive_depth<T>(),T>, recursive_unwrap_type_t<recursive_depth<T>(), T>> ) constexpr auto recursive_reduce_all(const T& input, TI init, BinaryOp binary_op) { auto result = init + recursive_reduce_all( UL::recursive_transform<recursive_depth<T>() - 1>( input, [&](auto&& element){ return recursive_reduce_all(element, init, binary_op); }) ); return result; }
{ "domain": "codereview.stackexchange", "id": 45156, "lm_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++, recursion, template, c++20, constrained-templates", "url": null }
c++, recursion, template, c++20, constrained-templates // recursive_reduce_all template function with execution policy, initial value and specified operation template<class ExPo, has_arithmetic_operations T, class BinaryOp> requires (std::is_execution_policy_v<std::remove_cvref_t<ExPo>> && std::regular_invocable<BinaryOp, T, T>) constexpr auto recursive_reduce_all(ExPo execution_policy, const T& input1, const T& input2, BinaryOp binary_op) { return std::invoke(binary_op, input1, input2); } template<class ExPo, std::ranges::input_range T, class TI, class BinaryOp> requires (std::is_execution_policy_v<std::remove_cvref_t<ExPo>> && has_arithmetic_operations<recursive_unwrap_type_t<recursive_depth<T>(), T>> && std::same_as<recursive_unwrap_type_t<recursive_depth<T>(), T>, TI> && recursive_depth<T>() == 1 && std::regular_invocable< BinaryOp, recursive_unwrap_type_t<recursive_depth<T>(),T>, recursive_unwrap_type_t<recursive_depth<T>(), T>> ) constexpr auto recursive_reduce_all(ExPo execution_policy, const T& input, TI init, BinaryOp binary_op) { return std::reduce(execution_policy, std::ranges::cbegin(input), std::ranges::cend(input), init, binary_op); }
{ "domain": "codereview.stackexchange", "id": 45156, "lm_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++, recursion, template, c++20, constrained-templates", "url": null }
c++, recursion, template, c++20, constrained-templates // recursive_reduce_all template function with execution policy, initial value and specified operation, overload for std::array template<class ExPo, template<class, std::size_t> class Container, typename T, std::size_t N, class TI, class BinaryOp> requires (std::is_execution_policy_v<std::remove_cvref_t<ExPo>> && has_arithmetic_operations<recursive_array_unwrap_type_t<recursive_depth<Container<T, N>>(), Container<T, N>>> && std::same_as<recursive_array_unwrap_type_t<recursive_depth<Container<T, N>>(), Container<T, N>>, TI> && recursive_depth<Container<T, N>>() == 1 && std::regular_invocable< BinaryOp, recursive_array_unwrap_type_t<recursive_depth<Container<T, N>>(), Container<T, N>>, recursive_array_unwrap_type_t<recursive_depth<Container<T, N>>(), Container<T, N>>> ) constexpr auto recursive_reduce_all(ExPo execution_policy, const Container<T, N>& input, TI init, BinaryOp binary_op) { return std::reduce(execution_policy, std::ranges::cbegin(input), std::ranges::cend(input), init, binary_op); }
{ "domain": "codereview.stackexchange", "id": 45156, "lm_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++, recursion, template, c++20, constrained-templates", "url": null }
c++, recursion, template, c++20, constrained-templates template<class ExPo, std::ranges::input_range T, class TI, class BinaryOp> requires (std::is_execution_policy_v<std::remove_cvref_t<ExPo>> && has_arithmetic_operations<recursive_unwrap_type_t<recursive_depth<T>(), T>> && std::ranges::input_range<recursive_unwrap_type_t<1, T>> && std::same_as<recursive_unwrap_type_t<recursive_depth<T>(), T>, TI> && std::regular_invocable< BinaryOp, recursive_unwrap_type_t<recursive_depth<T>(),T>, recursive_unwrap_type_t<recursive_depth<T>(), T>> ) constexpr auto recursive_reduce_all(ExPo execution_policy, const T& input, TI init, BinaryOp binary_op) { auto result = init + recursive_reduce_all( UL::recursive_transform<recursive_depth<T>() - 1>( execution_policy, input, [&](auto&& element){ return recursive_reduce_all(execution_policy, element, init, binary_op); }) ); return result; } template<std::size_t wrapped_level = 0, class T> constexpr auto get_wrapped_first_element(const T& input) { if constexpr (wrapped_level > 0) { return get_wrapped_first_element<wrapped_level - 1>(input.at(0)); } else { return input; } } // recursive_reduce_string template function template<class T> requires(std::same_as<T, std::string>) constexpr auto recursive_reduce_string(const T& input1) { return input1; } template<std::ranges::input_range T> requires (std::same_as<recursive_unwrap_type_t<recursive_depth<T>() - 1, T>, std::string> && recursive_depth<T>() - 1 == 1) constexpr auto recursive_reduce_string(const T& input) { auto output = input.at(0); for(int i = 1; i < std::ranges::size(input); i++) { output+=input.at(i); } return output; }
{ "domain": "codereview.stackexchange", "id": 45156, "lm_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++, recursion, template, c++20, constrained-templates", "url": null }
c++, recursion, template, c++20, constrained-templates template<std::ranges::input_range T> constexpr auto recursive_reduce_string(const T& input) { auto result = recursive_reduce_string( UL::recursive_transform<recursive_depth<T>() - 2>( input, [](auto&& element){ return recursive_reduce_string(element); }) ); return result; } void recursive_reduce_string_tests() { std::cout << "Play with std::vectors:\n"; std::vector<std::string> word_vector1 = {"foo", "bar", "baz", "quux"}; std::cout << recursive_reduce_string(word_vector1) << '\n'; std::vector<std::vector<std::string>> word_vector2 = {word_vector1, word_vector1, word_vector1}; std::cout << recursive_reduce_string(word_vector2) << '\n'; std::cout << "Play with std::deque:\n"; std::deque<std::string> word_deque1 = {"1", "2", "3", "4"}; std::cout << recursive_reduce_string(word_deque1) << '\n'; std::deque<std::deque<std::string>> word_deque2 = {word_deque1, word_deque1, word_deque1}; std::cout << recursive_reduce_string(word_deque2) << '\n'; return; } int main() { auto start = std::chrono::system_clock::now(); recursive_reduce_string_tests(); auto end = std::chrono::system_clock::now(); std::chrono::duration<double> elapsed_seconds = end - start; std::time_t end_time = std::chrono::system_clock::to_time_t(end); std::cout << "Computation finished at " << std::ctime(&end_time) << "elapsed time: " << elapsed_seconds.count() << '\n'; return 0; } The output of the test code above: Play with std::vectors: foobarbazquux foobarbazquuxfoobarbazquuxfoobarbazquux Play with std::deque: 1234 123412341234 Computation finished at Tue Oct 17 08:31:04 2023 elapsed time: 0.00128089 Godbolt link is here. All suggestions are welcome. The summary information:
{ "domain": "codereview.stackexchange", "id": 45156, "lm_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++, recursion, template, c++20, constrained-templates", "url": null }
c++, recursion, template, c++20, constrained-templates Godbolt link is here. All suggestions are welcome. The summary information: Which question it is a follow-up to? A recursive_sum Template Function Implementation with Unwrap Level in C++, A recursive_reduce_all Template Function Implementation in C++, A recursive_reduce Template Function with Unwrap Level Implementation in C++ and A recursive_depth Function Implementation with Target Type Parameter in C++. What changes has been made in the code since last question? For dealing with these nested std::string cases, recursive_reduce_string template function is introduced in this post. Why a new review is being asked for? Please review recursive_reduce_string template function implementation and all suggestions are welcome. Answer: There are several issues with this code: Why are you reimplementing a recursive reduce when you already have UL::recursive_reduce()? It is not generic enough. Even if you only wanted it to be limited to strings, consider that std::string is just a type alias for std::basic_string<char>. What about std::wstring, std::u8string, std::pmr::string, std::string_view, C strings and all other kinds of strings? The name implies it is similar to std::reduce(), however it doesn't support a custom reduction operator, doesn't support an initial element, and doesn't support parallelism. If you only want to join strings, then recursive_join() or recursive_concat() would be better names for this function. It will throw an exception if any of the containers is empty. It unnecessarily uses .at() in the for-loop. I would ensure you have a recursive reduce function that has the necessary (template) parameters to do what you want, such that recursive_reduce_string() only needs to be an alias for the generic reduce function.
{ "domain": "codereview.stackexchange", "id": 45156, "lm_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++, recursion, template, c++20, constrained-templates", "url": null }
c#, recursion, entity-framework-core Title: Recursively load all navigation properties of an entity Question: I have a table representing a class hierarchy using the TPH model. Some of those sub classes have navigation properties (collections and/or references). I'm trying to preload them as I know I will need them later in the process. I'm also trying to not have to manually write the casting and loading of all those properties, which would quickly become unmaintainable. All that said, I saw two options, code generation and exploring the navigation properties exposed by the EF Core change tracker. This is my implementation of the second solution: protected async Task LoadRecursiveAsync<TEntityToLoad>(TEntityToLoad entity, CancellationToken cancellationToken) where TEntityToLoad : class, IEntity { // this.Context is of type Microsoft.EntityFrameworkCore.DbContext EntityEntry<TEntityToLoad> entry = this.Context.Entry(entity); foreach (NavigationEntry navigationEntry in entry.Navigations.Where(ne => !ne.IsLoaded)) { cancellationToken.ThrowIfCancellationRequested(); await LoadRecursiveAsyncInternal(navigationEntry); } return; async Task LoadRecursiveAsyncInternal(NavigationEntry navigationEntry) { await navigationEntry.LoadAsync(cancellationToken); object? currentValue = navigationEntry.CurrentValue; switch (currentValue) { case IEntity loadedEntity: { foreach (NavigationEntry navigation in this.Context.Entry(loadedEntity).Navigations.Where(ne => !ne.IsLoaded)) { cancellationToken.ThrowIfCancellationRequested(); await LoadRecursiveAsyncInternal(navigation); }
{ "domain": "codereview.stackexchange", "id": 45157, "lm_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#, recursion, entity-framework-core", "url": null }
c#, recursion, entity-framework-core break; } case null: break; default: { Type type = currentValue.GetType(); if(!type.IsAssignableTo(typeof(IEnumerable))) { return; } if (type.GetGenericArguments() is [{ } entityType] && entityType.IsAssignableTo(typeof(IEntity))) { foreach (IEntity loadedEntity in (IEnumerable)currentValue) { foreach (NavigationEntry navigation in this.Context.Entry(loadedEntity).Navigations.Where(ne => !ne.IsLoaded)) { cancellationToken.ThrowIfCancellationRequested(); await LoadRecursiveAsyncInternal(navigation); } } } break; } } } } For completeness's sake, the IEntity interface: public interface IEntity { long Id { get; set; } } From my limited testing, it appears to work. I'm not too worried about any stack overflow, my model is more large than deep. This is declared and implemented in my base generic repository class, by declaring this method as protected, I want developers to have to think before using this, as they will need to create a new method in the relevant Repository class (and maybe even to create a repository) to use this method. Edit: I've successfully loaded the entirety of my model with this, it was slower than with split queries created by EF Core, but as the objective is only to load fragments, performance is not an issue (yet?) Edit 2: Comparison of manual includes with the above recursive method, made with BenchmarkDotNet (Runtime: .NET 6.0, IterationCount 100) Method Mean Error StdDev Median Ratio RatioSD Gen0 Gen1 Allocated Alloc Ratio
{ "domain": "codereview.stackexchange", "id": 45157, "lm_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#, recursion, entity-framework-core", "url": null }
c#, recursion, entity-framework-core Method Mean Error StdDev Median Ratio RatioSD Gen0 Gen1 Allocated Alloc Ratio LoadExplicitAsync 9.655 ms 0.1228 ms 0.3504 ms 9.509 ms 1.00 0.00 328.1250 140.6250 2.61 MB 1.00 LoadRecursiveAsync 56.355 ms 0.3518 ms 0.9866 ms 56.376 ms 5.85 0.25 700.0000 200.0000 5.85 MB 2.24 Answer: Just focusing on the code structure at hand, the most obvious thing it that the following codeblock is basically repeated three times which violates DRY (Don't Repeat Yourself): foreach (NavigationEntry navigationEntry in entry.Navigations.Where(ne => !ne.IsLoaded)) { cancellationToken.ThrowIfCancellationRequested(); await LoadRecursiveAsyncInternal(navigationEntry); } Also the code trying to convert the value into a bascially an IEnumerable<IEntity> seems a bit more complicated than it ought to be. Pretty sure the baked in dotnet tools like as and ?. and LINQ's OfType should achieve the same but with less verbosity. My suggestion would be something along these lines: protected async Task LoadRecursiveAsync<TEntityToLoad>(TEntityToLoad entity, CancellationToken cancellationToken) where TEntityToLoad : class, IEntity { // this.Context is of type Microsoft.EntityFrameworkCore.DbContext EntityEntry<TEntityToLoad> entry = this.Context.Entry(entity); await LoadNavigations(entry.Navigations);
{ "domain": "codereview.stackexchange", "id": 45157, "lm_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#, recursion, entity-framework-core", "url": null }
c#, recursion, entity-framework-core return; async Task LoadNavigations(IEnumerable<NavigationEntry> navigationEntries) { foreach (var navigationEntry in navigationEntries.Where(ne => !ne.IsLoaded)) { cancellationToken.ThrowIfCancellationRequested(); await navigationEntry.LoadAsync(cancellationToken); object? currentValue = navigationEntry.CurrentValue; foreach (var entity in ValueAsEntities(currentValue)) { await LoadNavigations(this.Context.Entry(entity).Navigations) } } } IEnumerable<IEntity> ValueAsEntities(object currentValue) { var entityVal = currentValue as IEntity; if (entityVal != null) { yield return entityVal; } else { foreach (entityVal in (currentValue as IEnumerable)?.OfType<IEntity>()) { yield return entityVal; } } } } The ValueAsEntities implementation still seems a bit clunky - not sure if that can be solved a bit more elegantly. Saves about 20 LOC's Completely untested obviously.
{ "domain": "codereview.stackexchange", "id": 45157, "lm_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#, recursion, entity-framework-core", "url": null }
python, console, hangman Title: Yet another CLI Hangman game Question: ...with properly packaged/type-hinted code, automated testing, and no dependencies. Do note that this package requires Python 3.12 or later. Only pyproject.toml and non-test .py files are included here; still, there are about 1400 LOC. For non-code files (and/or a better code-reading experience), view the project on GitHub. Please ignore my non-PEP8/PEP257-compliant code style. Other than that, suggestions regarding design patterns, naming conventions, APIs, etc. are all welcomed. The project structure . ├── LICENSE ├── README.md ├── pyproject.toml ├── src │ ├── _hangman │ │ └── runner.py │ └── hangman │ ├── __init__.py │ ├── _lax_enum.py │ ├── _static_reader.py │ ├── assets │ │ ├── gallows.txt │ │ ├── head.txt │ │ ├── instructions.txt │ │ ├── left_arm.txt │ │ ├── left_leg.txt │ │ ├── right_arm.txt │ │ ├── right_leg.txt │ │ ├── title.txt │ │ ├── trunk.txt │ │ └── you_lost.txt │ ├── canvas.py │ ├── choice_list.py │ ├── conversation.py │ ├── game.py │ ├── py.typed │ ├── word.py │ ├── word_list.py │ └── words │ ├── easy.txt │ ├── hard.txt │ ├── medium.txt │ └── unix.txt ├── tests └── tox.ini pyproject.toml [project] name = "hangman" version = "0.2.1" description = "A CLI hangman game" readme = "README.md" requires-python = ">=3.12" license = { text = "Unlicense" } authors = [ { name = "InSyncWithFoo", email = "insyncwithfoo@gmail.com" } ] classifiers = [ "License :: OSI Approved :: The Unlicense (Unlicense)", "Topic :: Games/Entertainment" ] [project.optional-dependencies] dev = [ "build~=1.0.3", "mypy~=1.6.0", "pytest~=7.4.2", "pytest-cov~=4.1.0", "setuptools~=68.2.2", "tox~=4.11.3" ] [project.urls] Homepage = "https://github.com/InSyncWithFoo/hangman"
{ "domain": "codereview.stackexchange", "id": 45158, "lm_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, console, hangman", "url": null }
python, console, hangman [project.urls] Homepage = "https://github.com/InSyncWithFoo/hangman" [project.scripts] hangman = "_hangman.runner:main" [build-system] requires = ["setuptools>=68.0.0", "wheel"] build-backend = "setuptools.build_meta" [tool.setuptools] package-data = { "*" = ["*.txt"] } src/_hangman/runner.py from hangman import Game def main(): Game().start() if __name__ == '__main__': main() src/hangman/init.py from .canvas import Canvas, Layer from .choice_list import ChoiceList, Choices from .conversation import Conversation from .game import Game from .word_list import Level, WordList __all__ = [ 'Game', 'Canvas', 'Choices', 'ChoiceList', 'Conversation', 'Layer', 'Level', 'WordList' ] src/hangman/_lax_enum.py import re from collections.abc import Generator from re import Pattern from typing import ClassVar class LaxEnum(type): ''' Despite its name, a LaxEnum is no different from a normal class except for that it yields every item that is not a dunder when being iterated over. ''' _dunder: ClassVar[Pattern[str]] = re.compile(r'__.+__') def __iter__(cls) -> Generator[object, None, None]: for member_name, member in cls.__dict__.items(): if not cls._dunder.fullmatch(member_name): yield member src/hangman/_static_reader.py from functools import partial from os import PathLike from pathlib import Path package_directory = Path(__file__).resolve().parent assets_directory = package_directory / 'assets' word_list_directory = package_directory / 'words' def _read(base_directory: Path, filename: PathLike[str]) -> str: ''' Read a file and return its contents. :param base_directory: The base directory to look up the file :param filename: The name of the file :return: The contents of the file ''' with open(base_directory / filename) as file: return file.read()
{ "domain": "codereview.stackexchange", "id": 45158, "lm_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, console, hangman", "url": null }
python, console, hangman get_asset = partial(_read, assets_directory) get_word_list = partial(_read, word_list_directory) src/hangman/canvas.py from __future__ import annotations import dataclasses from collections.abc import Collection, Generator, Iterator, Sequence from dataclasses import dataclass from functools import partial from itertools import batched from typing import overload, Self from ._lax_enum import LaxEnum from ._static_reader import get_asset @dataclass(frozen = True) class LayerCell: ''' Represents a layer cell. ``value`` must be a single character. ''' row: int column: int value: str def __post_init__(self) -> None: if len(self.value) != 1: raise ValueError('"value" must be a single character') @property def is_transparent(self) -> bool: ''' Whether the value contains only whitespaces. ''' return self.value.strip() == '' _GridOfStrings = Sequence[Sequence[str]]
{ "domain": "codereview.stackexchange", "id": 45158, "lm_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, console, hangman", "url": null }
python, console, hangman class Layer: r''' A rectangle grid of :class:`LayerCell`\ s. ''' __slots__ = ('_cells', '_height', '_width') _cells: list[LayerCell] _height: int _width: int def __new__(cls, argument: _GridOfStrings) -> 'Self': # PY-62301 ''' Construct a :class:`Layer`. :param argument: A grid of strings. Cannot be a string itself. ''' if isinstance(argument, str): raise TypeError('"rows" must not be a string') instance = super().__new__(cls) grid = [list(row) for row in argument] first_row = grid[0] same_width = all(len(row) == len(first_row) for row in grid) if not same_width: raise ValueError('All rows must have the same width') instance._height = len(grid) instance._width = len(first_row) instance._cells = [] for row_index, row in enumerate(grid): for column_index, cell_value in enumerate(row): cell = LayerCell(row_index, column_index, cell_value) instance._cells.append(cell) return instance def __repr__(self) -> str: horizontal_frame = f'+{'-' * self._width}+' joined_rows = ( f'|{''.join(cell.value for cell in row)}|' for row in self.rows() ) return '\n'.join([ horizontal_frame, *joined_rows, horizontal_frame ]) @overload def __getitem__(self, item: int) -> LayerCell: ... @overload def __getitem__(self, item: tuple[int, int]) -> LayerCell: ... def __getitem__(self, item: int | tuple[int, int]) -> LayerCell: if isinstance(item, int): return self._cells[item] if isinstance(item, tuple) and len(item) == 2:
{ "domain": "codereview.stackexchange", "id": 45158, "lm_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, console, hangman", "url": null }
python, console, hangman return self._cells[item] if isinstance(item, tuple) and len(item) == 2: row_index, column_index = item if row_index >= self._height or column_index >= self._width: raise IndexError('Row or column index is out of bounds') index = self._width * row_index + column_index return self[index] raise TypeError(f'Invalid index') def __iter__(self) -> Iterator[LayerCell]: yield from self._cells def __len__(self) -> int: return len(self._cells) def __eq__(self, other: object) -> bool: if not isinstance(other, Layer): return NotImplemented return self._cells == other._cells def __add__(self, other: Layer) -> Layer: if not isinstance(other, Layer): return NotImplemented copied = self.copy() copied += other return copied def __iadd__(self, other: Layer) -> Self: if not isinstance(other, Layer): return NotImplemented if self.height != other.height or self.width != other.width: raise ValueError( 'To be added, two layers must have the same height and width' ) copy_cell = dataclasses.replace for index, other_cell in enumerate(other): if not other_cell.is_transparent: self._cells[index] = copy_cell(other_cell) return self @property def height(self) -> int: ''' The height of the layer. ''' return self._height @property def width(self) -> int: ''' The width of the layer. ''' return self._width @classmethod def from_text(cls, text: str, width: int | None = None) -> Self: '''
{ "domain": "codereview.stackexchange", "id": 45158, "lm_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, console, hangman", "url": null }
python, console, hangman @classmethod def from_text(cls, text: str, width: int | None = None) -> Self: ''' Construct a :class:`Layer` from a piece of text. :param text: Any string, with one or more lines. :param width: \ The width of the layer. :return: A new :class:`Layer`. ''' if width is None: width = -1 lines = text.splitlines() longest_line_length = max(len(line) for line in lines) width = max([longest_line_length, width]) return cls([line.ljust(width) for line in text.splitlines()]) @classmethod def from_sequence(cls, cells: Sequence[str], width: int) -> Self: ''' Construct a :class:`Layer` from a sequence of strings. :param cells: A :class:`Sequence` of strings. :param width: \ The number of cells per chunk. \ The last chunk is padded with spaces. :return: A new :class:`Layer`. ''' rows = [] for row in batched(cells, width): if len(row) < width: padder = ' ' * (width - len(row)) rows.append([*row, *padder]) else: rows.append(list(row)) return cls(rows) def rows(self) -> Generator[tuple[LayerCell, ...], None, None]: r''' Yield a tuple of :class:`LayerCell`\ s for each row. ''' yield from batched(self._cells, self._width) def columns(self) -> Generator[tuple[LayerCell, ...], None, None]: r''' Yield a tuple of :class:`LayerCell`\ s for each column. ''' for column in zip(*self.rows()): yield column def cells(self) -> Generator[LayerCell, None, None]: ''' Synonym of :meth:`__iter__`. ''' yield from self def copy(self) -> Self: '''
{ "domain": "codereview.stackexchange", "id": 45158, "lm_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, console, hangman", "url": null }
python, console, hangman ''' yield from self def copy(self) -> Self: ''' Construct a new :class:`Layer` from this one. ''' string_cells = [cell.value for cell in self] return self.__class__.from_sequence(string_cells, self._width)
{ "domain": "codereview.stackexchange", "id": 45158, "lm_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, console, hangman", "url": null }
python, console, hangman class Canvas(Collection[Layer]): r''' A collection of :class:`Layers`. Its string representation is that of all its layers merged. ''' __slots__ = ('_height', '_width', '_layers') _height: int _width: int _layers: list[Layer] def __init__(self, height: int, width: int) -> None: ''' Construct a :class:`Canvas` of given height and width. :param height: The height of the canvas. :param width: The width of the canvas. ''' self._height = height self._width = width self._layers = [] def __str__(self) -> str: if not self._layers: return '\n'.join([' ' * self._width] * self._height) first, *others = self._layers flattened = sum(others, start = first) joined_rows = [ ''.join(cell.value for cell in row) for row in flattened.rows() ] return '\n'.join(joined_rows) def __contains__(self, layer: object) -> bool: return layer in self._layers def __iter__(self) -> Iterator[Layer]: return iter(self._layers) def __len__(self) -> int: return len(self._layers) @property def height(self) -> int: ''' The height of the canvas. ''' return self._height @property def width(self) -> int: ''' The width of the canvas. ''' return self._width @property def layers(self) -> Generator[Layer, None, None]: ''' Yield every layer the canvas contains. ''' for layer in self._layers: yield layer @classmethod def from_layer(cls, layer: Layer) -> Self: ''' Construct a :class:`Canvas` from a layer using its height and width. :param layer: A :class:`Layer`.
{ "domain": "codereview.stackexchange", "id": 45158, "lm_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, console, hangman", "url": null }
python, console, hangman using its height and width. :param layer: A :class:`Layer`. :return: A new :class:`Canvas`. ''' canvas = cls(height = layer.height, width = layer.width) canvas.add_layers(layer) return canvas def _fits_layer(self, layer: Layer) -> bool: ''' Whether the layer has same height and width as the canvas. :param layer: A :class:`Layer`. :return: ``True`` if the layer fits, ``False`` otherwise. ''' return self._height == layer.height and self._width == layer.width def add_layers(self, *layers: Layer) -> None: r''' Add one or more :class:`Layer`\ s to the canvas. :param layers: One or more :class:`Layer`\ s. ''' if not all(self._fits_layer(layer) for layer in layers): raise ValueError( 'Layers must have same height and width as canvas' ) self._layers.extend(layers)
{ "domain": "codereview.stackexchange", "id": 45158, "lm_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, console, hangman", "url": null }
python, console, hangman _make_80_wide_layer = partial(Layer.from_text, width = 80) class Component(metaclass = LaxEnum): r''' Pre-built :class:`Layer`\ s to be used in the game. ''' GALLOWS = _make_80_wide_layer(get_asset('gallows.txt')) HEAD = _make_80_wide_layer(get_asset('head.txt')) TRUNK = _make_80_wide_layer(get_asset('trunk.txt')) LEFT_ARM = _make_80_wide_layer(get_asset('left_arm.txt')) RIGHT_ARM = _make_80_wide_layer(get_asset('right_arm.txt')) LEFT_LEG = _make_80_wide_layer(get_asset('left_leg.txt')) RIGHT_LEG = _make_80_wide_layer(get_asset('right_leg.txt')) YOU_LOST = _make_80_wide_layer(get_asset('you_lost.txt')) src/hangman/choice_list.py from __future__ import annotations from collections.abc import Generator from dataclasses import dataclass from typing import Mapping, NamedTuple, Self from ._lax_enum import LaxEnum from .word_list import Level @dataclass(frozen = True, slots = True) class Choice: ''' Represents a valid choice of a :class:`ChoiceList`. ''' shortcut: str description: str aliases: frozenset[str] value: str | None = None def __str__(self) -> str: return f'[{self.shortcut}] {self.description}' _ChoiceDescriptor = tuple[str, set[str], str | None] class ChoiceDescriptor(NamedTuple): ''' Syntactic sugar for a bare tuple containing three elements: ``description``, ``aliases``, and ``value``. ''' description: str aliases: set[str] = set() value: str | None = None
{ "domain": "codereview.stackexchange", "id": 45158, "lm_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, console, hangman", "url": null }
python, console, hangman class _LengthList(list[int]): ''' A list of integers which keeps track of the sum. Meant for internal use only. ''' total: int def __new__(cls) -> 'Self': # PY-62301 instance = super().__new__(cls) instance.total = 0 return instance def append(self, value: int) -> None: ''' Append an integer value to the end of the list and add it the total. :param value: A length. ''' self.total += value super().append(value)
{ "domain": "codereview.stackexchange", "id": 45158, "lm_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, console, hangman", "url": null }
python, console, hangman class ChoiceList: __slots__ = ('_shortcut_map', '_alias_map', 'max_width', 'separator') _shortcut_map: dict[str, Choice] _alias_map: dict[str, Choice] separator: str max_width: int def __new__( cls, /, argument: Mapping[str, _ChoiceDescriptor] | None = None, *, separator: str = ' ', max_width: int = 80, **kwargs: _ChoiceDescriptor ) -> 'Self': # PY-62301 r''' Construct a list of valid choices whose string representation looks like the following:: [A] Foobar bazqux [BAR] Lorem ipsum [C] Consectetur adipiscing elit All shorcuts and aliases are case-insensitive and mapped to their corresponding :class:`Choice`. Shortcuts are uppercased in the string representation. A :class:`Choice` can be chosen by referencing either ``shortcut`` or any of the ``aliases``. ``argument`` and ``kwargs`` are shortcut-to-:class:`ChoiceDescriptor` maps. Each ``shortcut`` *should* be a single character, whereas the ``description``\ s need to be human-readable. ``value`` is the value the choice represents, defaults to ``None``. :param argument: A :class:``collections.abc.Mapping``. :param separator: \ A string to be used as the separator in the string representation. :param max_width: \ The maximum width of the string representation, in characters. :param kwargs: \ Other shortcut-to-descriptor arguments. ''' if isinstance(argument, Mapping): kwargs = {**argument, **kwargs} instance = super().__new__(cls) instance.separator = separator instance.max_width = max_width shortcut_map = instance._shortcut_map = {}
{ "domain": "codereview.stackexchange", "id": 45158, "lm_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, console, hangman", "url": null }
python, console, hangman instance.max_width = max_width shortcut_map = instance._shortcut_map = {} alias_map = instance._alias_map = {} for shortcut, (description, aliases, value) in kwargs.items(): shortcut = shortcut.upper() uppercased_aliases = frozenset(alias.upper() for alias in aliases) choice = Choice( shortcut, description, uppercased_aliases, value ) shortcut_map[shortcut] = choice for alias in uppercased_aliases: alias_map[alias] = choice return instance def __contains__(self, item: object) -> bool: if not isinstance(item, str): return False item = item.upper() return item in self._shortcut_map or item in self._alias_map def __getitem__(self, item: str) -> Choice: item = item.upper() if item in self._shortcut_map: return self._shortcut_map[item] return self._alias_map[item] def __str__(self) -> str: output: list[list[str]] = [[]] lengths: list[_LengthList] = [_LengthList()] for choice in self: choice_stringified = str(choice) choice_length = len(choice_stringified) total_choice_length = lengths[-1].total + choice_length total_separator_length = len(self.separator) * len(lengths[-1]) new_last_row_length = total_choice_length + total_separator_length if new_last_row_length > self.max_width: output.append([]) lengths.append(_LengthList()) output[-1].append(choice_stringified) lengths[-1].append(choice_length) return '\n'.join(self.separator.join(row) for row in output) def __repr__(self) -> str:
{ "domain": "codereview.stackexchange", "id": 45158, "lm_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, console, hangman", "url": null }
python, console, hangman def __repr__(self) -> str: return ( f'{self.__class__.__name__}(' + ', '.join(repr(choice) for choice in self) + f')' ) def __iter__(self) -> Generator[Choice, None, None]: yield from self._shortcut_map.values()
{ "domain": "codereview.stackexchange", "id": 45158, "lm_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, console, hangman", "url": null }
python, console, hangman class Choices(metaclass = LaxEnum): ''' Pre-built instances of :class:`ChoicesList`. ''' CONFIRMATION = ChoiceList( Y = ChoiceDescriptor( description = 'Yes', aliases = {'Yes'}, value = 'YES' ), N = ChoiceDescriptor( description = 'No', aliases = {'No'}, value = 'NO' ) ) LEVEL = ChoiceList( E = ChoiceDescriptor( description = 'Easy (22.5k words)', aliases = {'EASY'}, value = Level.EASY ), M = ChoiceDescriptor( description = 'Medium (74.5k words)', aliases = {'MEDIUM'}, value = Level.MEDIUM ), H = ChoiceDescriptor( description = 'Hard (168k words)', aliases = {'HARD'}, value = Level.HARD ), U = ChoiceDescriptor( description = 'Unix (205k words)', aliases = {'UNIX'}, value = Level.UNIX ) ) src/hangman/conversation.py from __future__ import annotations from collections.abc import Callable, Generator from dataclasses import dataclass from typing import ClassVar, Literal from .choice_list import ChoiceList def _response_is_valid_choice( response: str, choices: ChoiceList | None ) -> bool: ''' Checks if the response is a valid choice. ''' assert choices is not None return response in choices def _no_op(_response: str, _choices: ChoiceList | None) -> Literal[True]: ''' A validator that always returns ``True``. ''' return True
{ "domain": "codereview.stackexchange", "id": 45158, "lm_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, console, hangman", "url": null }
python, console, hangman @dataclass(frozen = True, slots = True, eq = False) class Validator: ''' Callable wrapper for a validator function. The second argument is the warning message to be output when this validator fails. ''' predicate: ResponseValidator warning: str def __call__(self, response: str, choices: ChoiceList | None) -> bool: return self.predicate(response, choices) InputGetter = Callable[[str], str] OutputDisplayer = Callable[[str], None] ResponseValidator = Callable[[str, ChoiceList | None], bool] OneOrManyValidators = Validator | list[Validator] _FailingValidators = Generator[Validator, None, None]
{ "domain": "codereview.stackexchange", "id": 45158, "lm_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, console, hangman", "url": null }
python, console, hangman class Conversation: ''' Protocol for input-output operations. ''' _INVALID_RESPONSE: ClassVar[str] = \ 'Invalid response. Please try again.' _INVALID_CHOICE: ClassVar[str] = \ 'Invalid choice. Please try again.' __slots__ = ('_input', '_output') _input: InputGetter _output: OutputDisplayer def __init__(self, ask: InputGetter, answer: OutputDisplayer) -> None: ''' Construct a :class:`Conversation`. :param ask: A ``input``-like callable to be called for inputs. :param answer: A ``print``-like callable to be called to output. ''' self._input = ask self._output = answer def _get_response(self, prompt: str) -> str: ''' Get a raw response. :param prompt: The prompt to be used. :return: The response, uppercased. ''' return self._input(prompt).upper() def _ask( self, prompt: str, /, choices: ChoiceList | None = None, *, validators: list[Validator] ) -> str: ''' Get a response, then validate it against the validators. Repeat this process until the response passes all validations. ''' failing_validators: Callable[[], _FailingValidators] = lambda: ( validator for validator in validators if not validator(response, choices) ) find_first_failing_validator: Callable[[], Validator | None] = \ lambda: next(failing_validators(), None) response = self._get_response(prompt) while failing_validator := find_first_failing_validator(): self.answer(failing_validator.warning) response = self._get_response(prompt) return response def ask( self, question: str, /, choices: ChoiceList | None = None, *,
{ "domain": "codereview.stackexchange", "id": 45158, "lm_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, console, hangman", "url": null }
python, console, hangman def ask( self, question: str, /, choices: ChoiceList | None = None, *, until: OneOrManyValidators | None = None ) -> str: r''' Thin wrapper around :meth:`_ask`. If ``choices`` is given, it will be included in the prompt text. If ``until`` is ``None``, a default validator will be used to check if the response is a valid choice. If both ``choices`` and ``until`` are ``None``, no validators will be applied. :param question: The question to ask. :param choices: The choices to choose from. Optional. :param until: \ A :class:`Callable`, a :class:`Validator` or a list of :class:`Validator`\ s. Optional. :return: The response of the user. ''' prompt = f'{question}\n' prompt += f'{choices}\n' if choices is not None else '' if choices is None and until is None: validators = [Validator(_no_op, '')] elif until is None: validators = [ Validator(_response_is_valid_choice, self._INVALID_CHOICE) ] else: validators = [until] if callable(until) else until return self._ask( prompt, choices, validators = validators ) def answer(self, answer: str) -> None: ''' Outputs the caller's message. :param answer: The message to output. ''' self._output(answer)
{ "domain": "codereview.stackexchange", "id": 45158, "lm_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, console, hangman", "url": null }
python, console, hangman src/hangman/game.py from __future__ import annotations from typing import ClassVar from ._static_reader import get_asset from .canvas import Canvas, Component, Layer from .choice_list import ChoiceList, Choices from .conversation import ( Conversation, InputGetter, OneOrManyValidators, OutputDisplayer, Validator ) from .word import Word from .word_list import Level, WordList def _response_is_ascii_letter(character: str, _: ChoiceList | None) -> bool: return len(character) == 1 and 'A' <= character <= 'Z'
{ "domain": "codereview.stackexchange", "id": 45158, "lm_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, console, hangman", "url": null }
python, console, hangman class Game: ''' The Hangman game. ''' TITLE: ClassVar[str] = get_asset('title.txt') INSTRUCTIONS: ClassVar[str] = get_asset('instructions.txt') COEFFICENTS: ClassVar[dict[Level, int]] = { Level.EASY: 1, Level.MEDIUM: 2, Level.HARD: 3, Level.UNIX: 4 } _MAX_DISPLAY_WIDTH: ClassVar[int] = 80 __slots__ = ( '_conversation', '_used_words', '_points', '_reward', '_penalty', '_ended' ) _conversation: Conversation _used_words: set[str] _points: int _reward: int _penalty: int _ended: bool def __init__( self, input_getter: InputGetter = input, output_displayer: OutputDisplayer = print, reward: int = 2, penalty: int = -1 ) -> None: ''' Initialize a new game. See :class:`Conversation` for more information on ``input_getter`` and ``output_displayer``. :param input_getter: \ An ``input``-like function. Defaults to ``input``. :param output_displayer: \ A ``print``-like function. Defaults to ``print``. :param reward: \ The number of points to be added to the total on each correct guess. :param penalty: \ The number of points to be subtracted from the total on each incorrect guess. ''' self._used_words = set() self._points = 0 self._reward, self._penalty = reward, penalty self._ended = False self._conversation = Conversation( ask = input_getter, answer = output_displayer ) @property def points(self) -> int: ''' The total points earned in this game. ''' return self._points @points.setter def points(self, value: int) -> None: '''
{ "domain": "codereview.stackexchange", "id": 45158, "lm_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, console, hangman", "url": null }
python, console, hangman @points.setter def points(self, value: int) -> None: ''' Called on operations such as the following: game.points += 1 The number of points cannot be negative. ''' self._points = max(value, 0) def _start(self) -> None: ''' Output the title, the instructions, then start the first :class:`GameRound`. If that round is won and the user wants to continue, start another. Otherwise, if the game has not ended (user did not lose in the latest round), end the game. ''' self._output_game_title() self._output_game_instructions() self._start_round() while not self._ended and self._prompt_for_continue_confirmation(): self._start_round() if not self._ended: self.end() def _output_game_title(self) -> None: ''' Output the title, which is just some fancy ASCII art. ''' self.output(self.TITLE) def _output_game_instructions(self) -> None: ''' Output the instructions. ''' self.output(self.INSTRUCTIONS) def _prompt_for_continue_confirmation(self) -> bool: ''' Ask for a response until it is a yes/no answer. :return: Whether the user wants to continue. ''' answer = self.input('Continue?', Choices.CONFIRMATION) return answer in ('Y', 'YES') def _start_round(self) -> None: ''' Ask for a level, construct a :class:`WordList` and a coefficient from that level, then get a random word that has not been used. Finally, initialize a :class:`GameRound` by passing the word and the coefficent to it. ''' level = self._prompt_for_level()
{ "domain": "codereview.stackexchange", "id": 45158, "lm_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, console, hangman", "url": null }
python, console, hangman ''' level = self._prompt_for_level() word_list = WordList.from_level(level) coefficient = self.COEFFICENTS[level] word = word_list.get_random_word() while word in self._used_words: word = word_list.get_random_word() self._used_words.add(word) game_round = self._initialize_round(word, coefficient) game_round.start() def _initialize_round(self, word: str, coefficient: int) -> GameRound: ''' Pass ``word`` and ``coefficient`` as arguments to :class:`GameRound`. ''' return GameRound(self, word, coefficient) def _prompt_for_level(self) -> Level: ''' Ask for a response until it is a valid level. :return: The corresponding :class:`Level`. ''' choices = Choices.LEVEL response = self._conversation.ask('Choose a level:', choices) value = choices[response].value assert value is not None return Level(value) def start(self) -> None: ''' Start the game. If a :class:`KeyboardInterrupt` is caught, call :meth:`end`. ''' try: self._start() except KeyboardInterrupt: self.end() def end(self) -> None: ''' Switch a boolean flag and call :meth:`output_current_points`. ''' self._ended = True self.output('Game over.'.center(self._MAX_DISPLAY_WIDTH, '-')) self.output_current_points() def input( self, prompt: str, choices: ChoiceList | None = None, validators: OneOrManyValidators | None = None ) -> str: ''' Shorthand for ``self.conversation.ask``. ''' return self._conversation.ask(prompt, choices, until = validators)
{ "domain": "codereview.stackexchange", "id": 45158, "lm_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, console, hangman", "url": null }
python, console, hangman ''' return self._conversation.ask(prompt, choices, until = validators) def output(self, answer: str) -> None: ''' Shorthand for ``self.conversation.answer``. ''' return self._conversation.answer(answer) def output_current_points(self) -> None: ''' Output the total number of points earned. ''' self.output(f'Points: {self._points}') def reward_correct_guess(self, count: int, coefficient: int) -> None: ''' Add ``reward`` multiplied by ``coefficient`` and ``count`` to the number of points. ''' self.points += self._reward * count * coefficient def penalize_incorrect_guess(self, coefficient: int) -> None: ''' Substract ``penalty`` multiplied by ``coefficient`` from the number of points. ''' self.points += self._penalty * coefficient
{ "domain": "codereview.stackexchange", "id": 45158, "lm_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, console, hangman", "url": null }
python, console, hangman class GameRound: ''' A game round. The game ends when a game round ends with a loss. ''' _INVALID_GUESS: ClassVar[str] = \ 'Invalid guess. Please input a letter.' _ALREADY_GUESSED: ClassVar[str] = \ 'You have already guessed this letter. Please try again.' __slots__ = ( '_game', '_canvas', '_layer_stack', '_word', '_coefficient', '_guesses' ) _game: Game _canvas: Canvas _layer_stack: list[Layer] _word: Word _coefficient: int _guesses: set[str] def __init__(self, game: Game, word: str, coefficient: int) -> None: ''' Initialize a game round. There are initially 6 layers in the stack. Each incorrect guess pops one from the stack and adds it to the canvas. When the stack reaches 0, the entire game is over. See :class:`Word` for relevant checking logic. :param game: The game this round belongs to. :param word: The word to guess in this round. :param coefficient: \ The coefficient corresponding to the level of this round. ''' self._game = game self._canvas = Canvas.from_layer(Component.GALLOWS) self._layer_stack = [ Component.HEAD, Component.TRUNK, Component.LEFT_ARM, Component.RIGHT_ARM, Component.LEFT_LEG, Component.RIGHT_LEG ] self._word = Word(word) self._coefficient = coefficient self._guesses = set() @property def lives_left(self) -> int: ''' The number of layers left in the stack. ''' return len(self._layer_stack) def _output_canvas(self) -> None: ''' Output the canvas with all components lost via incorrect guesses. ''' self._game.output(str(self._canvas))
{ "domain": "codereview.stackexchange", "id": 45158, "lm_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, console, hangman", "url": null }
python, console, hangman ''' self._game.output(str(self._canvas)) def _output_current_word_state(self) -> None: ''' Output the word with unknown characters masked. ''' self._game.output(f'Word: {self._word.current_state}') def _output_word(self) -> None: ''' Output the word. Only called when the game is over. ''' self._game.output(f'The word was "{self._word}".') def _start_turn(self) -> None: ''' Call :meth:`_output_canvas` and :meth:`_output_current_word_state`. Ask for a new guess, then check it against the word and handle the result accordingly. ''' self._output_canvas() self._output_current_word_state() guess = self._prompt_for_guess() count = self._word.count(guess) self._guesses.add(guess) if count == 0: self._handle_incorrect_guess() else: self._handle_correct_guess(guess, count) def _handle_incorrect_guess(self) -> None: ''' Output a notice, then call :meth:`Game.penalize_incorrect_guess` and :meth:`Game.output_current_points`. Also call :meth:`_minus_1_life`. If the number of lives left is 0, add :attr:`Component.YOU_LOST` to the canvas. ''' self._game.output('Incorrect guess.') self._game.penalize_incorrect_guess(self._coefficient) self._game.output_current_points() self._minus_1_life() if self.lives_left == 0: self._canvas.add_layers(Component.YOU_LOST) def _handle_correct_guess(self, guess: str, count: int) -> None: ''' Output a notice, then call :meth:`Game.reward_correct_guess` and :meth:`Game.output_current_points`. :param guess: The character guessed.
{ "domain": "codereview.stackexchange", "id": 45158, "lm_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, console, hangman", "url": null }
python, console, hangman :param guess: The character guessed. :param count: The number of that character's appearances in the word. ''' if count == 1: self._game.output(f'There is {count} "{guess}"!') else: self._game.output(f'There are {count} "{guess}"s!') self._game.reward_correct_guess(count, self._coefficient) self._game.output_current_points() def _prompt_for_guess(self) -> str: ''' Ask for a new guess which must be an ASCII letter. :return: The guess. ''' validators = [ Validator(_response_is_ascii_letter, self._INVALID_GUESS), Validator(self._not_previously_guessed, self._ALREADY_GUESSED) ] return self._game.input('Your guess:', validators = validators) def _not_previously_guessed( self, response: str, _choices: ChoiceList | None ) -> bool: ''' Check if ``response`` is a previous guess. Meant to be called in :meth:`_prompt_for_guess`. :param response: The response to check. :return: Whether ``response`` is a previous guess. ''' return response not in self._guesses def _minus_1_life(self) -> None: ''' Pops a layer from the stack and add it to the canvas. ''' self._canvas.add_layers(self._layer_stack.pop(0)) def start(self) -> None: ''' While the word is not completely solved and there are still some lives left, start a turn. If there are no lives left (user lost the game), call :meth:`_output_canvas` and :meth:`_output_word`, then :meth:`Game.end`. Otherwise, :meth:`_output_current_word_state`. ''' while not self._word.all_clear and self.lives_left: self._start_turn()
{ "domain": "codereview.stackexchange", "id": 45158, "lm_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, console, hangman", "url": null }
python, console, hangman while not self._word.all_clear and self.lives_left: self._start_turn() if not self.lives_left: self._output_canvas() self._output_word() self._game.end() else: self._output_current_word_state()
{ "domain": "codereview.stackexchange", "id": 45158, "lm_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, console, hangman", "url": null }
python, console, hangman src/hangman/word.py class Word: ''' A word being guessed. ''' __slots__ = ('value', '_character_indices', '_masked') value: str _masked: list[str] _character_indices: dict[str, list[int]] def __init__(self, value: str) -> None: self.value = value.upper() self._masked = ['_'] * len(value) self._character_indices = {} for index, character in enumerate(self.value): self._character_indices.setdefault(character, []).append(index) def __str__(self) -> str: return self.value def __contains__(self, item: str) -> bool: return item.upper() in self._character_indices @property def current_state(self) -> str: ''' The letters, space-separated; unguessed ones are replaced with underscores. ''' return ' '.join(self._masked) @property def all_clear(self) -> bool: ''' Whether all letters have been guessed correctly. ''' return all(char != '_' for char in self._masked) def count(self, guess: str) -> int: ''' Count the guess's appearances in the word and replace those with underscores in the current state. :param guess: A letter. :return: The number of its appearances. ''' if guess not in self: return 0 indices = self._character_indices[guess] for index in indices: self._masked[index] = guess return len(indices) src/hangman/word_list.py import random from enum import StrEnum from os import PathLike from typing import ClassVar, final, Self from ._static_reader import word_list_directory class Level(StrEnum): EASY = 'EASY' MEDIUM = 'MEDIUM' HARD = 'HARD' UNIX = 'UNIX'
{ "domain": "codereview.stackexchange", "id": 45158, "lm_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, console, hangman", "url": null }
python, console, hangman class Level(StrEnum): EASY = 'EASY' MEDIUM = 'MEDIUM' HARD = 'HARD' UNIX = 'UNIX' @final class WordList: _instances: ClassVar[dict[str, Self]] = {} __slots__ = tuple(['_list']) _list: list[str] def __new__(cls, filename: str | PathLike[str]) -> 'Self': # PY-62301 filename = str(filename) if filename not in cls._instances: cls._instances[filename] = instance = super().__new__(cls) with open(filename) as file: instance._list = file.read().splitlines() return cls._instances[filename] def __len__(self) -> int: return len(self._list) def get_random_word(self) -> str: return random.choice(self._list) @classmethod def from_list(cls, words: list[str]) -> Self: instance = super().__new__(cls) instance._list = words return instance @classmethod def from_level(cls, level: str) -> Self: match level.upper(): case Level.EASY: filename = 'easy.txt' case Level.MEDIUM: filename = 'medium.txt' case Level.HARD: filename = 'hard.txt' case Level.UNIX: filename = 'unix.txt' case _: raise ValueError('No such level') return cls(word_list_directory / filename) Answer: Overall a well-organized and carefully-crafted project that I enjoyed reviewing. The main things that jumped out at me came from conversation.py, so with that in mind here are my points of feedback: ask In ask, the branching behavior based on how the optional parameters are set makes it harder for the reader to understand. The optional parameters also allow the client to use the method in a probably not-intended way, e.g. by passing in both a non-empty choices and non-empty until. Some cleaner alternatives:
{ "domain": "codereview.stackexchange", "id": 45158, "lm_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, console, hangman", "url": null }
python, console, hangman Explicitly create distinct methods, e.g. ask_choices(self, choices: ChoiceList, question: str) and ask_until(until: OneOrManyValidators, question: str). Use functools.singledispatchmethod to implement method overloading based on whether the client gives you a ChoiceList or OneOrManyValidators. As for the case where neither choices or until is provided, since it's a case that's currently not being used anywhere in the project I'd just remove it and not handle it (i.e. YAGNI). ResponseValidator ResponseValidator can and should be simplified from Callable[[str, ChoiceList | None], bool] to Callable[[str], bool], and by doing so we can avoid the ChoiceList | None parameter leaking into other validators and method signatures. To do this, we can create a closure with the list of choices (choices: ChoiceList) baked in. The resulting closure has the signature we want, i.e. Callable[[str], bool]. def create_choice_validator(choices: ChoiceList) -> Callable[[str], bool]: def fn(response: str) -> bool: return response in choices return fn We can then use this closure to create a new Validator: response_is_valid_choice = create_choice_validator(choices) validators = [Validator(response_is_valid_choice, self._INVALID_CHOICE)] _ask While looking over _ask, I had to re-read it several times to pick up on how the updated response within the while loop was getting re-evaluated in the failing_validators lambda. The following has a bit more ceremony with the creation of a closure, but I think it makes it easier to follow the flow of validation checking. def _ask(self, ..., validators: list[Validator]) -> str: def create_validator_checker(validators: list[Validator]) -> Callable[[str], Validator | None]: def fn(response: str) -> Validator | None: for validator in validators: if not validator(response): return validator return fn
{ "domain": "codereview.stackexchange", "id": 45158, "lm_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, console, hangman", "url": null }
python, console, hangman return fn maybe_first_failing_validator = create_validator_checker(validators) response = self._get_response(prompt) while failing_validator := maybe_first_failing_validator(response): self.answer(failing_validator.warning) response = self._get_response(prompt) Testing the Core Business Logic I always love to see tests, so kudos for creating them. Noticeably missing from the collection, however, is a test suite that tests the core business logic of the game, for example: When the player makes a correct guess, the correct corresponding letters in the target word are revealed, and the score is updated accordingly. When the player makes an incorrect guess, no letters in the target word are revealed, 1 life is deducted, and the score is updated accordingly. When the player correctly guesses all the letters in the target word, they win the game. When the player loses all of their lives, they lose the game. This might require refactoring Game and/or GameRound to expose the relevant parts of internal game state so they can be more easily tested, but it will be well worth the effort.
{ "domain": "codereview.stackexchange", "id": 45158, "lm_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, console, hangman", "url": null }
mysql Title: mySQL adjacency list model : Always retrieve parent and children/siblings Question: I’m using mySQL to create and adjacency list model type of table. I have only one level, that is a parent with children, like this: TABLE article (article_id, title, parent_article_id) Here’s a sample data article_id title parent_article_id ------------------------------------- 45 abc null 61 mm null 59 hgg 61 62 sef 61 67 wsr 61 Basically, I want to retrieve the parent and children/siblings depending of the where clause. So, if I select an article_id, let’s say 59, I want to return: article_id title parent_article_id ------------------------------------- 61 mm null 59 hgg 61 62 sef 61 67 wsr 61 That is the parent/top of the node (61), and chidren/sibings (59, 62, 67) If i select an article_id , let’s say 61, I want to return: article_id title parent_article_id ------------------------------------- 61 mm null 59 hgg 61 62 sef 61 67 wsr 61 That is the top of the node(61), and chidren/sibings (59, 62, 67) If i select a article_id , let’s say 45, I want to return: article_id title parent_article_id ------------------------------------- 45 abc null
{ "domain": "codereview.stackexchange", "id": 45159, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "mysql", "url": null }
mysql There is no children/siblings, just the top of the node. I’ve created a query that works, but I wonder if there is a better query to achieve what im looking for. Here’s my query: ( SELECT ar.article_id, ar.parent_article_id parent_article_id, ar.title FROM article ar WHERE ar.article_id = 61 ) UNION ( SELECT c.article_id, c.parent_article_id parent_article_id, c.title FROM article p JOIN article c ON p.parent_article_id = c.parent_article_id OR p.parent_article_id = c.article_id OR c.parent_article_id = p.article_id WHERE p.article_id = 61 ) ORDER BY parent_article_id Answer: Yes, there is a better query to achieve this, with a subquery masquerading as an user-defined variable. I always start simple, and first create a root query: SELECT * FROM article WHERE article_id = 59; This will only give me an article when the article_id itself is 59. This will clearly not do. We also need to find the children of the parent of this article, the siblings. So I first get the parent in a variable: SET @parent_id := (SELECT parent_article_id FROM article WHERE article_id = 59); I use a variable here because it is probably needed again later on. Note that the value of the variable is now 61. Now we can easily get the siblings like this: SELECT article_id FROM article WHERE parent_article_id = @parent_id; This will return articles [59, 62, 67] for article 59. Looks good, but it is still not complete. Notice that you want a result of [59, 61, 62, 67] for article 59 and now we've only got [59 (twice), 62, 67]. What's missing? Well, article 61 is missing, or what you call the "top node". It's not difficult to get this now: SELECT * FROM article WHERE article_id = @parent_id;
{ "domain": "codereview.stackexchange", "id": 45159, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "mysql", "url": null }
mysql This will result in 61 and completes our result. Now I need to put the three queries together, and sort the result: SET @child_id := 59; SET @parent_id := (SELECT parent_article_id FROM article WHERE article_id = @child_id); SELECT * FROM article WHERE parent_article_id IN (@child_id, @parent_id) OR article_id IN (@child_id, @parent_id) ORDER BY article_id; See: http://sqlfiddle.com/#!9/eddab1d/5 Notice how there's one extra query hidden in there: SELECT * FROM article WHERE parent_article_id = @child_id; This is for the case when the article is the "top node". In that case you still want the children.
{ "domain": "codereview.stackexchange", "id": 45159, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "mysql", "url": null }
game, rust, snake-game Title: Recreated Snake in Rust Question: This is my first ever program in Rust. I've made it using only the book, the reference, and any documentation about the crates/functions I was using on the official rust lang website. I have the feeling this could be cleaned up a lot. I'm looking for suggestions. extern crate rand; extern crate device_query; use std::{vec, thread::sleep, time::Duration}; use rand::*; use device_query::{DeviceQuery, DeviceState, Keycode}; fn main(){ let device_state = DeviceState::new(); let mut rows = [['⬛'; 11]; 11]; let mut score: i32 = 0; let mut direction: u8 = 0; // = Up, 1 = Left, 2 = Down, 3= Right let mut positions:Vec<(usize, usize)> = vec![(5,5)]; //every square taken by our slithery friend let mut close_game: bool = false; rows[5][5] = ''; rows[3][5] = ''; while !close_game { print!("\x1B[2J\x1B[1;1H"); direction = input_direction(direction, &device_state); close_game = game_tick(&mut rows, &mut positions, direction, &mut score); draw_game(&rows, &score); sleep(Duration::from_millis(300)); } println!("Game over! Final Score: {}", score); } fn draw_game(a: &[[char;11];11], score: &i32){ println!(""); println!(" Score:{:02} teo.snake", &score); for i in 1..10 { print!(" "); for j in 1..10 { print!("{}", a[i][j]); } println!(""); } } fn game_tick(a: &mut[[char;11];11], vec: &mut Vec<(usize, usize)>, d: u8, s: &mut i32)-> bool { let mut game_over: bool = false; let newpos: (usize, usize)= newposition(d, vec[0], &mut game_over); if game_over == true { return game_over } for i in 0..vec.len() { if newpos == vec[i] { game_over = true; return game_over } } vec.insert(0, newpos); let mut next_fruitx:usize; let mut next_fruity:usize; let mut checkpass: bool;
{ "domain": "codereview.stackexchange", "id": 45160, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "game, rust, snake-game", "url": null }
game, rust, snake-game let mut next_fruitx:usize; let mut next_fruity:usize; let mut checkpass: bool; 'looptillvalid: loop { checkpass = true; next_fruitx = rand::thread_rng().gen_range(1..10); next_fruity = rand::thread_rng().gen_range(1..10); for i in 0..vec.len() { if (next_fruitx, next_fruity) == vec[i] { checkpass = false; break; } } if checkpass == true { break 'looptillvalid; } } let lastpos: (usize, usize) = vec.pop().unwrap(); a[lastpos.0][lastpos.1] = '⬛'; match a[newpos.0][newpos.1] { '' => { vec.push(lastpos); a[newpos.0][newpos.1] = ''; a[lastpos.0][lastpos.1] = ''; *s += 1; game_over = false; a[next_fruitx][next_fruity] = ''; } _ => { a[newpos.0][newpos.1] = ''; game_over = false} } game_over } fn newposition(d: u8, first: (usize, usize), go: &mut bool) -> (usize, usize){ let mut ret: (usize, usize) = (0,0); match d { 0 => { ret.0 = first.0 - 1; ret.1 = first.1} 1 => { ret.0 = first.0; ret.1 = first.1 - 1} 2 => { ret.0 = first.0 + 1; ret.1 = first.1} 3 => { ret.0 = first.0; ret.1 = first.1 + 1} _ => {println!("Invalid Direction")} } if ret.0 < 1 || ret.0 > 9 || ret.1 < 1 || ret.1 > 9 { *go = true; } ret } fn input_direction(d: u8, d_state: &DeviceState) -> u8{ let mut dir: u8 = d; let keys: Vec<Keycode> = d_state.get_keys(); if keys.len() != 0 { match keys[0] { Keycode::Up => {dir = 0} Keycode::Left => {dir = 1} Keycode::Down => {dir = 2} Keycode::Right => {dir = 3} _ => () } } dir }
{ "domain": "codereview.stackexchange", "id": 45160, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "game, rust, snake-game", "url": null }
game, rust, snake-game Answer: Clippy One of the most important tools when writing good rust code is clippy. I recommend to configure your editor to run clippy on-the fly. It has very nice messages and includes an explanation for most lints. Let's go through some of it's suggestions: warning: empty string literal in `println!` --> src/main.rs:31:5 | 31 | println!(""); | ^^^^^^^^^--^ | | | help: remove the empty string | = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#println_empty_string = note: `#[warn(clippy::println_empty_string)]` on by default warning: equality checks against true are unnecessary --> src/main.rs:45:8 | 45 | if game_over == true { | ^^^^^^^^^^^^^^^^^ help: try simplifying it as shown: `game_over` | = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#bool_comparison = note: `#[warn(clippy::bool_comparison)]` on by default This one actually applies to all popular languages. Let's see one more: warning: length comparison to zero --> src/main.rs:115:8 | 115 | if keys.len() != 0 { | ^^^^^^^^^^^^^^^ help: using `!is_empty` is clearer and more explicit: `!keys.is_empty()` | = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#len_zero = note: `#[warn(clippy::len_zero)]` on by default Then, it has many issues related to iteration. In rust, it is unidiomatic to use explicit indexing when you can iterate over the actual values instead: for row in a { print!(" "); for elem in row { print!("{}", elem); } println!(); } for pos in &*vec { if newpos == *pos { game_over = true; return game_over } }
{ "domain": "codereview.stackexchange", "id": 45160, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "game, rust, snake-game", "url": null }
game, rust, snake-game Here, the assignment to game_over is actually useless, because you can just return true directly. Use Rust 2021 The 2021 is the latest edition is the newest and should be used for all new code. If you're following a book or tutorial and it tells you to extern crate, it's very outdated. Control flow logic It may just be me, but I find the control flow of the loop in gametick very confusing. I think it is more readable if written this way: loop { next_fruitx = thread_rng().gen_range(1..10); next_fruity = thread_rng().gen_range(1..10); if vec.contains(&(next_fruitx, next_fruity)) { break; } } vec.contains can also be used in other places. Finding these is an exercise to the reader. At the end of game_tick, both branches of the match (which reads very nicely btw) contain the line game_over = false. They can be removed and replaced with a single false at the end of the function. Constants There are multiple occurrences of various constants in the code. This is both not DRY and also an instance of a magic number. Things I would extract into named constants are 11, 9, and the emojis. This reduces the risk of typos that can become logic errors. Data Structures You use a lot of Tuples for Coordinates, where I think a simple Struct with x and y fields could be more readable. Since direction only has 4 valid values, I would make an enum for it. That way, you can remove the "Invalid direction" error, which should be unreachable. I'd also write a 2-valued enum for the return type of game_tick, as the meaning of true and false aren't very obvious. Thanks for reading all of this. Feel free to make a new post with updated code.
{ "domain": "codereview.stackexchange", "id": 45160, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "game, rust, snake-game", "url": null }
php, object-oriented Title: PHP CSV Parser: Separation of concerns and SOLID principles Question: I implemented a CSV Parser with Separation of concerns and SOLID principles in mind. Does that code match the principles? Here a sample data (CSV): Participant;Eagerness;Education;Stability;Total "John Doe";6.4;"G";1.3;9.0 "John Smith";2.9;"X";1.5;; Main file: <?php require __DIR__ . DIRECTORY_SEPARATOR . 'vendor' . DIRECTORY_SEPARATOR . 'autoload.php'; use XXX\Command\CSVParser; use XXX\Command\ResultPrinter; use XXX\Command\ScoreCalculator; use XXX\Command\ScoreParser; use XXX\Strategy\AverageStrategy; use XXX\Strategy\HighestStrategy; use XXX\Strategy\LowestStrategy; use XXX\Strategy\TypeStrategy; $parser = new ScoreParser(new CSVParser(), new ScoreCalculator([]), new ResultPrinter()); try { if (!isset($argv[1]) || !isset($argv[2])) { throw new Exception('Missing parameter!' . PHP_EOL); } } catch (Exception $e){ die($e->getMessage()); } $what = ucfirst($argv[1]); $whoHow = $argv[2]; $strategy = match ($whoHow) { 'lowest' => new LowestStrategy(), 'highest' => new HighestStrategy(), 'average' => new AverageStrategy(), 'type' => new TypeStrategy(), default => null, }; try { $filePath = 'data' . DIRECTORY_SEPARATOR . 'data.csv'; $parser->processCommand($filePath, $what, $whoHow, $strategy); } catch (Exception $e) { die($e->getMessage()); } CSVParser.php <?php namespace XXX\Command; class CSVParser { public function parse(string $csvFile): array { $lines = file($csvFile); $data = []; foreach ($lines as $line) { $data[] = str_getcsv(trim($line), ';'); } return $data; } } ResultPrinter.php <?php namespace XXX\Command; use XXX\Strategy\CalculationStrategy;
{ "domain": "codereview.stackexchange", "id": 45161, "lm_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, object-oriented", "url": null }
php, object-oriented ResultPrinter.php <?php namespace XXX\Command; use XXX\Strategy\CalculationStrategy; class ResultPrinter { public function printResult(?string $participant, ?string $result, string $header, ?CalculationStrategy $strategy): void { if ($result === null) { $message = "No score found for $header"; } else { if ($result === '') { $message = "$participant has no score for $header"; } else { if ($participant === null) { $message = "The " . strtolower( str_replace('Strategy', '', basename(str_replace('\\', '/', get_class($strategy)))) ) . " score for $header is $result"; } else { $message = "$participant scored $result on $header"; } } } echo $message . PHP_EOL; } } ScoreCalculator.php <?php namespace XXX\Command; use Exception; class ScoreCalculator { private array $data; public function __construct(array $data) { $this->data = $data; } /** * @throws Exception */ public function getColumnValues(string $header): array { $index = $this->getColumnIndex($header); $values = []; foreach ($this->data as $row) { if (isset($row[$index]) && $row[$index] !== '') { $values[] = $row[$index]; } } // Remove header column if exists $index = array_search($header, $values); if ($index !== false) { unset($values[$index]); } return $values; } /** * @throws Exception */ private function getColumnIndex(string $header): int|string { $index = array_search($header, $this->data[0]); if ($index === false) { throw new Exception("Column not found: $header"); } return $index; }
{ "domain": "codereview.stackexchange", "id": 45161, "lm_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, object-oriented", "url": null }
php, object-oriented return $index; } /** * @throws Exception */ public function getParticipantScore(string $participant, string $header) { $participantIndex = $this->getColumnIndex('Participant'); $headerIndex = $this->getColumnIndex($header); foreach ($this->data as $row) { if ($row[$participantIndex] === $participant) { return $row[$headerIndex]; } } return null; } } ScoreParser.php <?php namespace XXX\Command; use Exception; use XXX\Strategy\CalculationStrategy; class ScoreParser { private CSVParser $parser; private ScoreCalculator $calculator; private ResultPrinter $printer; public function __construct(CSVParser $parser, ScoreCalculator $calculator, ResultPrinter $printer) { $this->parser = $parser; $this->calculator = $calculator; $this->printer = $printer; } /** * @throws Exception */ public function processCommand(string $filename, string $what, string $whoHow, ?CalculationStrategy $strategy): void { $participant = null; $data = $this->parser->parse($filename); $this->calculator = new ScoreCalculator($data); $participantIndex = filter_var($whoHow, FILTER_VALIDATE_INT); if ($participantIndex === false) { $values = $this->calculator->getColumnValues($what); try { $result = $strategy->calculate($values); } catch (\Throwable $t) { die($t->getMessage() . PHP_EOL); } } else { if (!isset($data[$participantIndex])) { throw new Exception('Participant not exists!' . PHP_EOL); } $participant = $data[$participantIndex][0]; $result = $this->calculator->getParticipantScore($participant, $what); } $this->printer->printResult($participant, $result, $what, $strategy); } }
{ "domain": "codereview.stackexchange", "id": 45161, "lm_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, object-oriented", "url": null }
php, object-oriented $this->printer->printResult($participant, $result, $what, $strategy); } } CalculationStrategy.php <?php namespace XXX\Strategy; interface CalculationStrategy { public function calculate(array $values): float|string; } AverageStrategy.php <?php namespace XXX\Strategy; class AverageStrategy implements CalculationStrategy { public function calculate(array $values): float { $count = count($values); $sum = array_sum($values); return $sum / $count; } } The other strategies are similar to the Average (implementing the interface CalculationStrategy). I also implemented the unit tests for each class, but it's not the focus now. Answer: Well, issues are so numerous and diverse here that I don't even know where to start. From positioning probably. The title says a "CSV Parser". But the actual parser takes just a couple lines. And the rest being some data analyzer and, for some reason, printer. I would rather call it a CSV Analyzer suite or something. But taking all these different things together you are making them very tightly coupled. SOLID, among other things, means that you can use each class for different purposes. But your parser is only usable with Printer. CSV Parser Speaking of CSV parsers, one has to keep in mind the following landmarks: adherence to standards resource efficiency functionality
{ "domain": "codereview.stackexchange", "id": 45161, "lm_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, object-oriented", "url": null }
php, object-oriented Standards The CSV standard actually allows a line break in the column value. As long it's quoted, any number of line breaks is allowed inside. And of course, your parser will break on them. That's why a dedicated function, fgetcsv() should be used when reading from a file. Yes, in your case, for one particular file format, line breaks is not a problem probably. But then you shouldn't call it a CSV parser, but some specific format parser. However, your best bet here is to actually use fgetcsv() for compatibility and performance reasons. Besides, CSV format allows arbitrary delimiters as well as enclosure and escape characters. Your parser ignores them all, and therefore cannot be called a CSV parser. It cannot even parse actual comma-separated values. fgetcsv() is configurable, accepting a list of parameters. Your parser should allow them as well. Then you can create a decorator, some SpecificFormatParser that can have some defaults hardcoded. Performance Right now your parser is twice memory inefficient. First, it reads the entire file in memory. Although this memory will be freed after parsing, still it burdens your RAM for no reason. And that's another reason why you should use fgetcsv() instead of file()/str_getcsv(). Second, your parser returns an array. And despite the fact that you always need only one line at a time, it reads and returns them all at once. You should avoid such a waste whenever possible. The usual method for that is simply to do your calculations inside of while loop that reads lines one by one. But this method is quite inconvenient, especially with OOP. But luckily, PHP offers you an instrument that can let you "pack" the while loop, carry it away and then use elsewhere, under the guise of foreach. It is called a generator. So a basic implementation could be like this function parse() { $file = new SplFileObject($this->filename); while (!$file->eof()) { yield $file->fgetcsv($this->separator, $this->enclosure, $this->escape);
{ "domain": "codereview.stackexchange", "id": 45161, "lm_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, object-oriented", "url": null }
php, object-oriented yield $file->fgetcsv($this->separator, $this->enclosure, $this->escape); } }
{ "domain": "codereview.stackexchange", "id": 45161, "lm_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, object-oriented", "url": null }
php, object-oriented (I am using SplFileObject just for sake of it, it looks nicer than meddling with fopen()) Then you can add a function that returns a real array, in case it's needed. Functionality Currently your class adds nothing to the existing functionality of str_getcsv() (and even limits it). Why not to add some functionality? Like, reading the header and returning an associative array instead of a list. Or adding a possibility to index the final array by some column's value. Etc. ResultPrinter Shouldn't be really a part of this suite. The purpose of this class is unclear and even why it's a class at all, while it's actually just a function. Besides, no function should actually print anything. Just make it return the value. Which then can be either printed or used any other way - added to a email for example. The calling code. I am genuinely puzzled, why don't you make it just if (!isset($argv[1]) || !isset($argv[2])) { die('Missing parameter!' . PHP_EOL); } I mean, what's the point in throwing here? In the end it's just die with a message. Why bother? The filename shouldn't be hardcoded but provided through arguments
{ "domain": "codereview.stackexchange", "id": 45161, "lm_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, object-oriented", "url": null }
c, file-system, linux Title: Implementation of recursive `ls` utility Question: Recently I wrote my own implementation of a utility for recursive output of the directories' contents, kind of similar to the ls Linux utility with the -Ro flags. As a training, I wrote it in C. I would love to hear your feedback on possible optimizations, better error handling, flaws in implementation, or the code in general. I usually code in C++ and it so happened that I'm not very familiar with C, so maybe some places could have been implemented better, but I need someone experienced to point this out. Thanks! #include <sys/stat.h> #include <dirent.h> #include <pwd.h> #include <unistd.h> #include <stdio.h> #include <stdlib.h> #include <time.h> #include <string.h> #include <errno.h> #include <error.h> #include <locale.h> #include <malloc.h> #include <stddef.h> #define BUF_SIZE 1024 /* initial size of the buffer for storing file information */ #define UNAME_MAX 32 #define DATE_LEN 20 #define PERM_LEN 10 #define MINOR_ERROR 1 #define FATAL_ERROR 2 enum file_type { REGULAR, DIRECTORY, SYMLINK, FIFO, SOCKET, EXECUTABLE, UNKNOWN }; const char *file_type_str[] = { /* for some reason, this works faster than the array of chars. There may be some kind of alignment issues, not sure */ [REGULAR] = "", [DIRECTORY] = "/", [SYMLINK] = "@", [FIFO] = "|", [SOCKET] = "=", [EXECUTABLE] = "*", [UNKNOWN] = "?" }; struct file_info { struct stat st; enum file_type type; char *name; char *path; char *target; }; struct user_info { char name[UNAME_MAX]; uid_t uid; struct user_info *next; }; static struct user_info *user_info_cache; /* cache the results of the expensive getpwuid() calls */ static int exit_status;
{ "domain": "codereview.stackexchange", "id": 45162, "lm_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, file-system, linux", "url": null }
c, file-system, linux static int exit_status; static void init(void) { tzset(); /* call tzset() to initialize the timezone information before call to reentrant localtime_r() according to POSIX.1-2004 */ setlocale(LC_COLLATE, ""); /* set the locale for collation aware string comparison */ } static int compare_file_name(const void *a, const void *b) { return strcoll(((const struct file_info *) a)->name, ((const struct file_info *) b)->name); } static void *xmalloc(size_t size) { void *ptr = malloc(size); if (ptr == NULL) { error(FATAL_ERROR, errno, "malloc"); __builtin_unreachable(); /* if status given to error() is a nonzero value, error() calls exit(3) to terminate the program, so this line is unreachable */ } return ptr; } static void *xrealloc(void *ptr, size_t size) { void *new_ptr = realloc(ptr, size); if (new_ptr == NULL) { error(FATAL_ERROR, errno, "realloc"); __builtin_unreachable(); } return new_ptr; } static void file_error(const char *message, const char *path) { error(0, errno, "%s: %s", message, path); exit_status = MINOR_ERROR; } static void format_permissions(const mode_t mode, char *formatted) { formatted[0] = (mode & S_IRUSR) ? 'r' : '-'; formatted[1] = (mode & S_IWUSR) ? 'w' : '-'; formatted[2] = (mode & S_IXUSR) ? 'x' : '-'; formatted[3] = (mode & S_IRGRP) ? 'r' : '-'; formatted[4] = (mode & S_IWGRP) ? 'w' : '-'; formatted[5] = (mode & S_IXGRP) ? 'x' : '-'; formatted[6] = (mode & S_IROTH) ? 'r' : '-'; formatted[7] = (mode & S_IWOTH) ? 'w' : '-'; formatted[8] = (mode & S_IXOTH) ? 'x' : '-'; formatted[9] = '\0'; } static char *get_owner(uid_t uid) { struct user_info *user_info; for (user_info = user_info_cache; user_info; user_info = user_info->next) { if (user_info->uid == uid) { return user_info->name; } } user_info = xmalloc(sizeof(struct user_info));
{ "domain": "codereview.stackexchange", "id": 45162, "lm_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, file-system, linux", "url": null }
c, file-system, linux user_info = xmalloc(sizeof(struct user_info)); const struct passwd *pwd = getpwuid(uid); if (pwd == NULL) { sprintf(user_info->name, "%u", uid); /* FIXME: known error: if given uid actually exists in the database and it's getpwuid() that just fails to retrieve it, we end up writing wrong username to cache */ } else { strcpy(user_info->name, pwd->pw_name); } user_info->uid = uid; user_info->next = user_info_cache; user_info_cache = user_info; return user_info->name; } static void format_time(const time_t mtime, char *formatted) { struct tm tm_info; localtime_r(&mtime, &tm_info); /* use reentrant version of localtime, as it's not required to call tzset() that causes overhead */ strftime(formatted, 20, "%Y-%m-%d %H:%M:%S", &tm_info); } static int get_file_type(const mode_t st_mode) { switch (st_mode & S_IFMT) { case S_IFDIR: return DIRECTORY; case S_IFLNK: return SYMLINK; case S_IFIFO: return FIFO; case S_IFSOCK: return SOCKET; default: if (st_mode & S_IXUSR) { /* first check for executable bit, as regular files can be executable */ return EXECUTABLE; } else if (S_ISREG(st_mode)) { return REGULAR; } else { return UNKNOWN; } } } static void print_file_info(const struct file_info *file_info, const int owner_w, const int size_w) { char permissions[PERM_LEN]; char date[DATE_LEN]; char *owner; format_permissions(file_info->st.st_mode, permissions); format_time(file_info->st.st_mtime, date); owner = get_owner(file_info->st.st_uid);
{ "domain": "codereview.stackexchange", "id": 45162, "lm_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, file-system, linux", "url": null }
c, file-system, linux printf("%s %*s %*ld %s %s%s", permissions, owner_w, owner, size_w, file_info->st.st_size, date, file_type_str[file_info->type], file_info->name); if (file_info->target != NULL) { printf(" -> %s", file_info->target); } printf("\n"); } static void concat_path(const char *dir_name, const char *file_name, char *full_path) { char *end = stpcpy(full_path, dir_name); if (*(end - 1) != '/' && *file_name != '\0') { *end++ = '/'; } strcpy(end, file_name); } static char *read_link(const char *path, size_t expected_size) { if (expected_size == 0) { /* in some cases lstat() can report zero size for a pseudo-files that behave like symlinks, e.g. /proc/self/exe. We can't rely on this value, so instead fallback to _POSIX_SYMLINK_MAX as a guess to prevent multiple calls to readlink() and realloc() */ expected_size = _POSIX_SYMLINK_MAX; } size_t buf_size = expected_size < PATH_MAX ? expected_size + 1 : PATH_MAX; char *buffer = xmalloc(buf_size); size_t read; while ((read = readlink(path, buffer, buf_size)) >= buf_size) { if (buf_size >= PATH_MAX) { free(buffer); return NULL; } buf_size = buf_size <= PATH_MAX / 2 ? buf_size * 2 : PATH_MAX; buffer = xrealloc(buffer, buf_size); } buffer[read] = '\0'; return buffer; } static int read_file_info(const char *dir_path, const char *file_name, struct file_info *file_info) { char *full_path = xmalloc(strlen(dir_path) + strlen(file_name) + 2); concat_path(dir_path, file_name, full_path); struct stat st; if (lstat(full_path, &st) == -1) { file_error("failed to get information", full_path); free(full_path); return MINOR_ERROR; } file_info->st = st; file_info->type = get_file_type(st.st_mode);
{ "domain": "codereview.stackexchange", "id": 45162, "lm_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, file-system, linux", "url": null }
c, file-system, linux file_info->st = st; file_info->type = get_file_type(st.st_mode); file_info->target = NULL; if (file_info->type == SYMLINK) { file_info->target = read_link(full_path, st.st_size); } const char *real_name = (file_name[0] == '\0') ? dir_path : file_name; file_info->name = strdup(real_name); if (file_info->type == DIRECTORY) { file_info->path = full_path; } else { free(full_path); } return EXIT_SUCCESS; } static void free_file_info(struct file_info *file_info, const int count) { for (int i = 0; i < count; i++) { free(file_info[i].name); if (file_info[i].target != NULL) { free(file_info[i].target); } if (file_info[i].type == DIRECTORY) { free(file_info[i].path); } } } static void list_dir(const char *path) { // NOLINT(*-no-recursion): recursion is required static int first_call = 1; int buf_size = BUF_SIZE; const struct dirent *entry; DIR *dir = opendir(path); if (dir == NULL) { file_error("failed to open directory", path); return; } int owner_w = 0; int size_w = 0; int entry_no = 0; struct file_info *files = xmalloc(buf_size * sizeof(struct file_info)); while ((entry = readdir(dir))) { if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) { continue; } struct file_info info; if (read_file_info(path, entry->d_name, &info) != 0) { continue; } files[entry_no] = info; int owner_len = (int) strlen(get_owner(info.st.st_uid)); int size_len = snprintf(NULL, 0, "%ld", info.st.st_size); owner_w = (owner_len > owner_w) ? owner_len : owner_w; size_w = (size_len > size_w) ? size_len : size_w;
{ "domain": "codereview.stackexchange", "id": 45162, "lm_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, file-system, linux", "url": null }
c, file-system, linux if (entry_no++ == buf_size - 1) { buf_size *= 2; struct file_info *new_files = xrealloc(files, buf_size * sizeof(struct file_info)); files = new_files; } } closedir(dir); qsort(files, entry_no, sizeof(struct file_info), compare_file_name); if (!first_call) { printf("\n"); } first_call = 0; printf("%s:\n", path); for (int i = 0; i < entry_no; i++) { print_file_info(&files[i], owner_w, size_w); } for (int i = 0; i < entry_no; i++) { if (files[i].type == DIRECTORY) { list_dir(files[i].path); } } free_file_info(files, entry_no); free(files); } static int myrls(const char *path) { init(); struct stat st; if (lstat(path, &st) == -1) { file_error("cannot access", path); return MINOR_ERROR; } if (S_ISDIR(st.st_mode)) { list_dir(path); } else { /* if myrls is called against a file, pay the price of double call to lstat() in favor of code simplicity - it would not be executed recursively anyway */ struct file_info info; if ((read_file_info(path, "", &info)) != 0) { return MINOR_ERROR; } print_file_info(&info, 0, 0); free_file_info(&info, 1); } return exit_status; } int main(int argc, char *argv[]) { if (argc > 2) { error(FATAL_ERROR, 0, "too many arguments"); } const char *path = (argc == 2) ? argv[1] : "./"; return myrls(path); }
{ "domain": "codereview.stackexchange", "id": 45162, "lm_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, file-system, linux", "url": null }