text
stringlengths
1
2.12k
source
dict
c#, async-await, task-parallel-library But this is basically the same as providing the above pattern to the ToString, which is my recommendation: ToString("yyyy-MM-ddThh-mm-ss-ffffffZ") UPDATE #2 Finally, AsTask().Wait() is the simplest way I found to apply DRY, I don't like it very much, hence why I asked for a code review :) There are multiple ways to solve to address this: At very least prefer .GetAwaiter().GetResult() over .Wait() It is not mandatory to implement both interfaces But if you do then you can perform casting to call the proper Dispose or DisposeAsync method on a given resource Since FileHistory does not own any resources this suggestion is not applicable for your code Since you have stated that this design is meant for small files that's why using only the synchronous file operations might be fine var data = File.ReadAllBytes(name); ... File.WriteAllBytes(path, Data); ... return ValueTask.CompletedTask; And last but not least you can do some branching inside the DisposeAsyncCore. It feels like a bit dirty but it does its job correctly var data = isSync ? File.ReadAllBytes(name) : await File.ReadAllBytesAsync(name); ... if (isSync) File.WriteAllBytes(path, Data); else await File.WriteAllBytesAsync(path, Data);
{ "domain": "codereview.stackexchange", "id": 44290, "lm_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#, async-await, task-parallel-library", "url": null }
c Title: Safe and portable way to write a file in C Question: I've read that fopen() is deprecated, and fopen_s() is recommended in its place. But there are many posts outlining the problems with fopen_s() in Linux. Several tutorials just avoid mentioning that issue, and show how to use both functions. With that in mind, how should I change this basic function to operate in a manner that is safe and portable? int writeFile( char *fileName, char *textToWrite ) { FILE *filePointer; filePointer = fopen( fileName, "w" ); if( filePointer == NULL ) { printf( "Unable to open '%s'.\n", fileName ); return 0; } fputs( textToWrite, filePointer ); fclose( filePointer ); return 1; } Since fopen_s has sketchy adoption in Linux, I would like to avoid it if possible. Answer: The C spec has not deprecated fopen(). Use const for referenced data when possible. It conveys code's intent and allows for greater use. Check return value of I/O functions. Error messages better sent on stderr. Define and initialize together as able. Sometimes code should return quickly like on fopen() failure and other times, still need to proceed like to call fclose() after fputs() failure. Consider changing the return value as 0 for success and use various non-zero values to indicate the reason for the error. (Not done below.). Consider named or enumerated return values rather than 0, 1. Good use of sentinels, ' in this case, when printing the file name. IMO, all strings that may contribute to an error deserve sentinels to highlight their beginning and end. Beginning or end might include hard to perceive white-space. As a general rule, You may want to print errno on error. Research perror(), strerror(). Also review file name, line number and function name for more informative output. Consider documenting in code, at least, the overall function goal.
{ "domain": "codereview.stackexchange", "id": 44291, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c", "url": null }
c Consider documenting in code, at least, the overall function goal. // Write the string to the file. // Return 1 on success, otherwise 0. int writeFile(const char *fileName, const char *textToWrite) { int retval = 1; // Success FILE *filePointer = fopen(fileName, "w"); if (filePointer == NULL) { fprintf( stderr, "Unable to open '%s'.\n", fileName); return 0; } if (fputs(textToWrite, filePointer) == EOF) { fprintf( stderr, "Unable to write '%s'.\n", fileName); retval = 0; } if (fclose(filePointer)) { fprintf( stderr, "Unable to close '%s'.\n", fileName); retval = 0; } return retval; }
{ "domain": "codereview.stackexchange", "id": 44291, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c", "url": null }
c++, beginner, game, tic-tac-toe Title: Tic-Tac-Toe game in C++ Question: My friend is kind of new to coding and he decided to write a console tic-tac-toe game. He then showed me his code and I thought it would be cool to optimize it a bit and rewrite in my own way. I tried my best but I'm pretty new to C++ and I'm not super experienced in optimizing things so I'd like to know about ways to improve my code in both performance and/or readability with the preference being on performance. #include <iostream> #include <stdlib.h> #include <sstream> using namespace std; char board[3][3] = {{'1', '2', '3'}, {'4', '5', '6'}, {'7', '8', '9'}}; string choice; int row, rows[3], col, columns[3], diagonal, anti_diagonal, intchoice; bool turn = true; // True = X turn, False = O turn void display_board() { cout << "\nPlayer 1[X] Player 2[O]\n"; cout << " | | \n"; cout << " " << board[0][0] << " | " << board[0][1] << " | " << board[0][2] << " \n"; cout << "_____|_____|_____\n"; cout << " | | \n"; cout << " " << board[1][0] << " | " << board[1][1] << " | " << board[1][2] << " \n"; cout << "_____|_____|_____\n"; cout << " | | \n"; cout << " " << board[2][0] << " | " << board[2][1] << " | " << board[2][2] << " \n"; cout << " | | \n"; } bool isint(string str) // Input check for an int value { for (int i = 0; i < str.length(); i++) if (!isdigit(str[i])) return false; return true; }
{ "domain": "codereview.stackexchange", "id": 44292, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, beginner, game, tic-tac-toe", "url": null }
c++, beginner, game, tic-tac-toe void player_turn() { while (true) { if (turn) cout << "Player - 1 [X] turn : "; else if (!turn) cout << "Player - 2 [0] turn : "; getline(cin, choice); // Prevents multiple turns in one input if (!isint(choice)) continue; stringstream(choice) >> intchoice; switch (intchoice) { case 1: row = 0; col = 0;break; case 2: row = 0; col = 1; break; case 3: row = 0; col = 2; break; case 4: row = 1; col = 0; break; case 5: row = 1; col = 1; break; case 6: row = 1; col = 2; break; case 7: row = 2; col = 0; break; case 8: row = 2; col = 1; break; case 9: row = 2; col = 2; break; default: cout << "Invalid Move\n"; continue; } if (board[row][col] == 'X' || board[row][col] == 'O') cout << "Occupied cell\n"; else { int change = turn ? 1 : -1; // Increment or Decrement value for win check board[row][col] = turn ? 'X' : 'O'; rows[row] += change; columns[col] += change; if (row == col) diagonal += change; if (row == (2 - col)) anti_diagonal += change; turn = !turn; // Switch turns return; } } } bool gameover() { for (int i = 0; i < 3; i++) if (rows[i] > 2 || rows[i] < -2 || columns[i] > 2 || columns[i] < -2 || diagonal > 2 || diagonal < -2 || anti_diagonal > 2 || anti_diagonal < -2) return true; return false; } int main() { cout << "T I C K -- T A C -- T O E -- G A M E"; display_board(); for (int i = 0; i < 9; i++) { player_turn(); display_board(); if (gameover()) break; } if (!gameover()) cout << "Draw"; else if (turn) cout << "Player 'O' has won"; else if (!turn) cout << "Player 'X' has won"; }
{ "domain": "codereview.stackexchange", "id": 44292, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, beginner, game, tic-tac-toe", "url": null }
c++, beginner, game, tic-tac-toe Here's a couple changes I myself made: I changed turn to a bool value to make it easy to invert and compare (before it was a char containing either 'X' or 'O'). I removed bool draw and instead I check if the game isn't over after there are no turns left (before it was a part of gameover() function and changed values each time the function was called). Instead of checking the whole input to be made out of digits I search for the closest non-digit value and go back to the start of the loop. Instead of comparing all the values from the board array I created 4 extra variables: rows[3], columns[3], diagonal, anti_diagonal. Those variables change their value each time a turn is made by incrementing (if it's X's turn) or decrementing (if O's turn). At the end those values are used to check for win conditions. For example rows[0] would represent the 1st row and the value can only be > 2 if there are 3 X's or < -2 if there are 3 O's. Those are all the major changes I made alongside some minor cleanup like removing unnecessary repeating checks. P.S. At the time of writing this question I noticed that in my gameover() function the if statement inside of the for loop also checks for diagonal and anti_diagonal values even tho they only need to be checked once so that might be something worth changing. Answer: I think the only 'major' change I might make is to replace the switch..case with if...else to remove duplicate code and actually use intchoice if (intchoice >= 1 && intchoice <= 9) { col = (intchoice - 1) % 3; row = (intchoice - 1) / 3; } else { cout << "Invalid Move\n"; continue; } In gameover you could check diagonal after row and column check for (int i = 0; i < 3; i++) if (rows[i] > 2 || rows[i] < -2 || columns[i] > 2 || columns[i] < -2) return true; if (diagonal > 2 || diagonal < -2 || anti_diagonal > 2 || anti_diagonal < -2) return true; return false;
{ "domain": "codereview.stackexchange", "id": 44292, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, beginner, game, tic-tac-toe", "url": null }
python, object-oriented Title: Voting application - OOP Question: I am developing an API and I have some questions about variables from another class. Here is an example (reduced code to be more assertive): File user.py from ..db_func import * from flaks import jsonify class User(): def __init__ (self, P_id_user = None, P_login = None, P_nome = None): self.id_user = P_id_user self.login = P_login self.nome = P_nome @property def id_user(self): return self._id_user @id_user.setter def id_user(self, value): self._id_user = value @property def login(self): return self._login @login.setter def login(self, value): self._login = value @property def nome(self): return self._nome @nome.setter def nome(self, value): self._nome = value #user functions here File campaign.py from ..db_func import * from .vote import * from ..uac.classes.groups import * class Campaign(): def __init__ (self, P_id_campaign = None, P_name_campaign = None, P_description = None): self.id_campaign = P_id_campaign self.name_campaign = P_name_campaign self.description = P_description @property def id_campaign(self): return self._id_campaign @id_campaign.setter def id_campaign(self, value): self._id_campaign = value @property def name_campaign(self): return self._name_campaign @name_campaign.setter def name_campaign(self, value): self._name_campaign = value @property def description(self): return self._description @description.setter def description(self, value): self._description = value #campaign functions here File vote.py from .campaign import * from ..db_func import *
{ "domain": "codereview.stackexchange", "id": 44293, "lm_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, object-oriented", "url": null }
python, object-oriented #campaign functions here File vote.py from .campaign import * from ..db_func import * class Vote(Campaign): def __init__ (self, P_id_vote = None, P_description = None): self.id_vote= P_id_vote self.description = P_description @property def id_vote(self): return self._id_vote @id_vote.setter def id_vote(self, value): self._id_vote = value @property def description(self): return self._description @description.setter def description(self, value): self._description = value def insert_vote(self, id_campaign, vote): #vote is a JSON self.id_campaign = id_campaign self.description = vote['description_vote'] id_user = vote['user'] self.id_vote = db().execute_query('insert into tb_vote (id_campaign, desc, id_user) values (%s, %s, %s)'), [self.id_campaign, self.description, id_user] return jsonify({'mensagem' : 'Success!', 'data' : 'Vote computed!', 'id_vote' : self.id_vote}), 201 # other vote functions here Routes.py from .classes.campaign import * from .classes.vote import * from ...uac.classes.user import * from flask_jwt_extended import jwt_required from . import cadastro from flask import request @cadastro.get('/campaign') @jwt_required() def get_campaigns(subdomain): return Campaign().get_campaigns() #example of route @cadastro.post('/campaign/<id_campaign>/votes') @jwt_required() def create_campaign_vote(id_campaign): json_vote = request.get_json() if not json_vote: return jsonify({'mensagem' : 'Error!', 'data' : 'Invalid payload!'}), 400 return Vote().insert_vote(id_campaign, json_vote) # The route of the question
{ "domain": "codereview.stackexchange", "id": 44293, "lm_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, object-oriented", "url": null }
python, object-oriented I have three classes: User, Campaign and Vote. With these three classes, I call an endpoint(/api/campaigns/<id_campaign>/votes) to insert the user's vote in a campaign; the id_user is sent in the application generated JSON. Question: Is using id_user = vote['user'] (without self) in the insert_vote function a good practice in OOP? Do I need to extend User or simply declare the self.id_user in Vote class? I am learning OOP and declarations and references of this type are new to me. I didn't found any example like this to use as reference or help. Answer: I would do neither but rather go with an MVC architecture if you are using Flask. Here's an example I wrote a while back that's dated but has the pattern: https://github.com/cdennison/flask-rest-example/blob/master/flask_rest_api/problems/views.py Or Google MVC architecture and get something like this: https://plainenglish.io/blog/flask-crud-application-using-mvc-architecture
{ "domain": "codereview.stackexchange", "id": 44293, "lm_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, object-oriented", "url": null }
c++, lookup Title: Optimize the FFT calculation in C++ without creating even/odd arrays Question: Here is my code: typedef std::complex<double> Complex; typedef std::valarray<Complex> CArray; void FFT(CArray& x) { const size_t N = x.size(); if (N <= 1) return; CArray even = x[std::slice(0, N/2, 2)]; CArray odd = x[std::slice(1, N/2, 2)]; FFT(even); FFT(odd); for (size_t k = 0; k < N/2; ++k) { Complex t = std::polar(1.0, -2 * M_PI * k / N) * odd[k]; x[k] = even[k] + t; x[k+N/2] = even[k] - t; } } As you can see Cooley-Tukey FFT approach is divide and conquer algorithm. But in each iteration, we are creating new arrays even/odd. Even if I tried the use directly give the slicing parts as FFT arguments like FFT(x[std::slice(0, N/2, 2)]), it does not work. What I want is, use directly the index values for even and odd part rather creating them, which are more memory-expensive. Moreover, In the for loop, there is the part, Complex t = std::polar(1.0, -2 * M_PI * k / N) * odd[k]; How to optimize this to use a lookup table or precomputed values. Answer: Avoiding allocating extra arrays You can't avoid allocating extra arrays if you use this particular FFT method. While with C++23 you could pass views and use std::ranges::stride_view, the problem is that you are modifying the array in the last part of FFT(). If you would directly modify the original array, a higher level of recursion will corrupt the array for the lower levels of recursion. You can do an in-place FFT transform though using bit-reversed counters, see this article that ALX23z mentioned. Precalculate the roots of unity How to optimize this to use a lookup table or precomputed values. Yes, just do that. You can split your function into two: static void FFT_internal(CArray& x, CArray& roots, ...) { … Complex t = roots[k * roots.size() / x.size()] * odd[k]; … } void FFT(CArray& x) { CArray roots; roots.reserve(x.size());
{ "domain": "codereview.stackexchange", "id": 44294, "lm_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++, lookup", "url": null }
c++, lookup void FFT(CArray& x) { CArray roots; roots.reserve(x.size()); for (std::size_t k = 0; k < x.size(); ++k) { roots.push_back(std::polar(1.0, -2 * M_PI * k / N)); } FFT_internal(x, roots); } Of course, if you are going to call FFT() often with the same size array, then that still is wasted effort, and you should explicitly have the caller precalculate the roots once, and then reuse those values for every call to FFT(). Note that it is also possible to recursively calculate those roots, and you can reuse your existing recursive structure for this. I don't think it will gain you any performance though. Avoid the typedefs While a typedef is handy in several situations, don't use it just to avoid some typing on your keyboard. Creating an abbreviation makes it harder for someone else to understand what the actual type is. Often, you can use auto to avoid having to write a type explicitly. For example: void FFT(std::valarray<std::complex<double>>& x) { … auto even = x[std::slice(0, N/2, 2)]; auto odd = x[std::slice(1, N/2, 2)]; … auto t = std::polar(1.0, -2 * M_PI * k / N) * odd[k]; … }
{ "domain": "codereview.stackexchange", "id": 44294, "lm_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++, lookup", "url": null }
c, matrix, mpi, linear-algebra Title: Matrix-vector multiplication with block-column distribution and MPI_Reduce_scatter Question: I'm studying MPI and I'm trying to solve the exercise (number 3.5) taken from Pacheco's book Introduction to parallel programming. Essentially the exercise is: Write an MPI program that computes the matrix vector product Ax using a block-column distribution for A. Look at what the function MPI_Reduce_scatter does. Assume that the number of processes p divides the sizes of the matrix. Given a m by n matrix A, and p processes, I have as usual that local_m = m/pand local_n = n/p. Then: I have p - 1 rectangular sub-matrices of size m by local_n. Each rank will multiply its m by local_n with the vector x I'll end up with p - 1 vectors, one per process, whose sum gives the desired result y. Here it's written that this MPI function applies a reduction on the vector and then scatters each segment to each process. In the following there's my code. I tested it with different matrices and it seems to work just fine. The vector x is living on every process. #include <assert.h> #include <mpi.h> #include <stdio.h> int main(int argc, char *argv[]) { const int m = 12; const int n = 12; double matrix[m][n]; double x[n]; // vector // Store the actual matrix and vector for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { matrix[i][j] = i + j; } x[i] = 1. + i; } int rank, p; int local_m, local_n; MPI_Init(&argc, &argv); MPI_Comm_rank(MPI_COMM_WORLD, &rank); MPI_Comm_size(MPI_COMM_WORLD, &p); assert(n % p == 0 && m % p == 0); local_m = m / p; local_n = n / p; double local_matrix[m][local_n]; double local_y[m]; // the result on each process double y[m]; // the vector that will store the correct result after summing // from each process int recvcounts[p]; for (int i = 0; i < p; i++) { recvcounts[i] = m; }
{ "domain": "codereview.stackexchange", "id": 44295, "lm_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, matrix, mpi, linear-algebra", "url": null }
c, matrix, mpi, linear-algebra int recvcounts[p]; for (int i = 0; i < p; i++) { recvcounts[i] = m; } // Store on each process the local (rectangular matrix) and the local part of // x for (int i = 0; i < m; i++) { // get all the rows now for (int j = 0; j < local_n; j++) { // only local_n columns local_matrix[i][j] = matrix[i][j + rank * local_n]; } } // Compute the local mat-vec product, the result is a vector of length m on // each process. for (int i = 0; i < m; i++) { local_y[i] = 0.; for (int j = 0; j < local_n; j++) { local_y[i] += local_matrix[i][j] * x[j + rank * local_n]; } } MPI_Reduce_scatter(local_y, y, recvcounts, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD); if (rank == 0) { printf("The expected result is \n"); double result[n]; for (int i = 0; i < m; i++) { result[i] = 0.; for (int j = 0; j < n; j++) { result[i] += matrix[i][j] * x[j]; } printf("result[%d] is %lf \n", i, result[i]); } printf("The result obtained is being printed on process %d: \n", rank); for (int i = 0; i < m; i++) printf("y[%d] = %lf \n", i, y[i]); } MPI_Finalize(); return 0; }
{ "domain": "codereview.stackexchange", "id": 44295, "lm_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, matrix, mpi, linear-algebra", "url": null }
c, matrix, mpi, linear-algebra MPI_Finalize(); return 0; } Answer: Observe that each process only multiplies with a small part of x, so you should declare x[local_n]. Next, think about context. If you are doing a power method or so, your output functions as the input for the next matrix-vector multiplication. So inductively, if you start out using only part of x as input, you need only part of y as output, because that will be your next input. (You could also make the argument that one should never store redundant information unless strictly necessary.) In other words: your recvcounts vector should be filled with local_m, not the global m. (This way you are actually doing more of a "reduce-bcast" than a reduce scatter, which you could've done with an allreduce.) Aside: you are using static allocation, which goes on the stack. It is better to do dynamic allocation on the heap. But otherwise, nicely done. Finally, let me remark that Pacheco's book is quite old by now. May I suggest https://theartofhpc.com/pcse.html ?
{ "domain": "codereview.stackexchange", "id": 44295, "lm_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, matrix, mpi, linear-algebra", "url": null }
strings, formatting, typescript Title: Optimizing - formatting a person's name Question: I need to take a user's name and format it 'lastName, firstName middleName'. If firstName and middleName are not present then the comma should not be included with lastName. Below is what I came up with and I'm wondering if there are ways I can make this better. The code was adapted from another function written by a senior developer at my company. I'm trying to expand my way of problem-solving for conditional situations. export function getLastNameFirstNameFullUserName( user: { firstName?: string; lastName?: string; middleName?: string }, includeMiddleName = false, ): string { const { firstName, lastName, middleName } = user; const userNameArray: string[] = []; if (isNotEmptyString(lastName)) { useLastNameWithComma(firstName, includeMiddleName, middleName) ? userNameArray.push(`${lastName},`) : userNameArray.push(`${lastName}`); } isNotEmptyString(firstName) && userNameArray.push(`${firstName}`); includeMiddleName && isNotEmptyString(middleName) && userNameArray.push(`${middleName}`); return userNameArray.join(' '); } function useLastNameWithComma(firstName: string, includeMiddleName: boolean, middleName?: string): boolean { if (isNotEmptyString(firstName)) { return true; } if (includeMiddleName && isNotEmptyString(middleName)) { return true; } return false; } export function isNotEmptyString(item: string | null | undefined): boolean { return !['', null, undefined].includes(item); } Answer: This was the solution I ended up using with the help of a coworker and the answer above. Using if-statements with normal truthy checks removes the need to cast the optional parameters to string. Adding the last name at the end allowed me to remove the helper function that determines if a comma needs to be added.
{ "domain": "codereview.stackexchange", "id": 44296, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "strings, formatting, typescript", "url": null }
strings, formatting, typescript Instead, we can just check that the array has an item already (first or middle name pushed) to know if we need to include the comma with the last name. Then we can use unshift to add it to the front of the array. I think this is a marked improvement in readability and reducing lines compared to the first version. export function getLastNameFirstNameFullUserName( user: { firstName?: string; lastName?: string; middleName?: string }, includeMiddleName = false, ): string { const { firstName, lastName, middleName } = user; const userNameArray: string[] = []; if (firstName) { userNameArray.push(firstName); } if (includeMiddleName && middleName) { userNameArray.push(middleName); } if (lastName) { const formattedLastName: string = userNameArray.length > 0 ? `${lastName},` : lastName; userNameArray.unshift(formattedLastName); } return userNameArray.join(' '); }
{ "domain": "codereview.stackexchange", "id": 44296, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "strings, formatting, typescript", "url": null }
python, pandas Title: Write a Python script to generate a random DataFrame based on specific inputs Question: I found myself many times in the past trying to generate fake DataFrames in pandas. I decided just for fun, to write a script that I can specify some inputs and generate that DataFrame for me. Here you can find the code: import random import pandas as pd from faker import Faker def generate_dummy_dataframe(int_cols, float_cols, bool_cols, string_cols, datetime_cols, rows): """ Generates a dummy dataframe with the specified number of columns and rows for each data type. Parameters ---------- int_cols : int The number of integer columns to create. float_cols : int The number of float columns to create. bool_cols : int The number of boolean columns to create. string_cols : int The number of string columns to create. datetime_cols : int The number of datetime columns to create. rows : int The number of rows to create. Returns ------- df : pandas.DataFrame A dataframe with the specified number of columns and rows for each data type, filled with sample data. Raises ------ ValueError If any of the inputs is not an integer greater than 0. """ # Check that input is valid if not all(isinstance(i, int) and i > 0 for i in [int_cols, float_cols, bool_cols, string_cols, datetime_cols, rows]): raise ValueError("All inputs must be integers greater than 0.") # Create empty dataframe df = pd.DataFrame() # Create instance of Faker fake = Faker()
{ "domain": "codereview.stackexchange", "id": 44297, "lm_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, pandas", "url": null }
python, pandas # Create empty dataframe df = pd.DataFrame() # Create instance of Faker fake = Faker() # Add integer columns for i in range(int_cols): df['int_col_{}'.format(i)] = [random.randint(0, 100) for _ in range(rows)] # Add float columns for i in range(float_cols): df['float_col_{}'.format(i)] = [random.uniform(0, 100) for _ in range(rows)] # Add boolean columns for i in range(bool_cols): df['bool_col_{}'.format(i)] = [random.choice([1, 0]) for _ in range(rows)] # Add string columns for i in range(string_cols): df['string_col_{}'.format(i)] = [fake.word() for _ in range(rows)] # Add datetime columns for i in range(datetime_cols): df['datetime_col_{}'.format(i)] = [fake.date_time() for _ in range(rows)] return df Then you can call the function like this: generate_dummy_dataframe(2, 2, 2, 2, 2, 10) And generate the output as this: int_col_0 int_col_1 float_col_0 float_col_1 bool_col_0 bool_col_1 \ 0 26 13 51.154902 74.562551 1 1 1 84 6 94.790006 22.036552 1 1 2 90 23 53.832429 29.791543 0 0 3 64 94 4.101628 18.442224 0 0 4 85 21 17.637843 51.384612 1 0 5 16 62 43.132250 99.989500 0 0 6 7 61 29.019135 90.812649 0 0 7 7 44 32.686915 80.988226 0 1 8 75 41 89.628566 5.697429 0 0 9 95 32 46.610747 19.376951 0 1
{ "domain": "codereview.stackexchange", "id": 44297, "lm_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, pandas", "url": null }
python, pandas string_col_0 string_col_1 datetime_col_0 datetime_col_1 0 fish network 2012-12-30 11:15:50 2002-09-14 08:39:36 1 industry rich 2004-09-21 13:26:07 1972-01-18 22:55:46 2 coach feel 2018-12-08 03:25:36 1998-06-19 18:18:27 3 image price 2017-07-16 19:37:53 2014-02-17 03:10:18 4 anything place 2015-01-19 20:45:41 2003-06-08 06:37:41 5 century possible 2004-06-02 02:35:25 1992-03-29 06:26:31 6 other expert 1985-04-14 16:27:21 2008-09-30 11:43:44 7 sound approach 1975-07-05 03:48:37 1978-03-20 00:08:46 8 information very 1989-10-15 15:52:22 2001-10-17 14:38:37 9 us more 1990-09-26 09:19:54 1975-01-11 12:07:19 Areas that I could improve this: Performance It's clear that the more rows I ask for, it will take even more time. import time def test_execution_time(rows): start = time.time() df = generate_dummy_dataframe(5, 5, 5, 5, 5, rows) end = time.time() print("Number of rows: {}".format(rows)) print("Execution time: {} seconds".format(end - start)) # Test execution time for different number of rows test_execution_time(100) test_execution_time(1000) test_execution_time(10000) test_execution_time(100000) test_execution_time(1000000) Number of rows: 100 Execution time: 0.05393719673156738 seconds Number of rows: 1000 Execution time: 0.12861156463623047 seconds Number of rows: 10000 Execution time: 1.0118906497955322 seconds Number of rows: 100000 Execution time: 9.85063910484314 seconds Number of rows: 1000000 Execution time: 98.54737830162048 seconds Less libraries Get rid of faker. The string columns doesn't have to be valid words. Just a dummy short text. Similar for datetime. I guess I can do that without faker. Readability Not sure here. Is there anything that can be done to make it more Pythonic and better formatted?
{ "domain": "codereview.stackexchange", "id": 44297, "lm_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, pandas", "url": null }
python, pandas Answer: Re. performance: you're (forgive me) going about it all wrong. Performant code requires that you allocate memory contiguously whenever possible use the vectorisation capabilities of your libraries, in this case Numpy, rather than loops That requires a rewrite, which I will partially demonstrate. Otherwise: Use PEP484 typehints and pull that information away from the docstring. The docstring is repetitive. If the description and Returns say the same thing, scrap the description and keep the Returns. Your validation hides the specific problem. Loop through and include the name of the problematic column in your error message. I demonstrate a method to generate datetimes without Faker. Strings are also possible but I leave this as an exercise to the reader. The parameters are both too verbose and not generic enough. You can reframe this as a single dictionary (or, if you want, kwargs) of dtypes to column counts. This will be called like df = generate_dummy_df( cols={ np.uint8: 4, np.bool_: 1, np.float64: 2, 'datetime64[s]': 1, 'datetime64[ms]': 1, 'datetime64[ns]': 1, }, rows=20, ) Suggested On my nothing-special computer, this generates 10,000,000 rows in 1.3 seconds. Mind you it's not apples-to-apples because I don't include strings. from timeit import timeit from typing import Optional, Union import numpy as np import pandas as pd from numpy.random import default_rng def generate_dummy_df(cols: dict[Union[str, np.dtype], int], rows: int, seed: Optional[int] = None) -> pd.DataFrame: """ Parameters ---------- cols The number of columns to create for each given datatype. rows The number of rows to create. seed Provided to the random generator. Returns ------- df A dummy dataframe filled with random data. Raises ------ ValueError If any of the inputs is not an integer greater than 0. """
{ "domain": "codereview.stackexchange", "id": 44297, "lm_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, pandas", "url": null }
python, pandas for dtype, n in cols.items(): if not isinstance(n, int) or n < 1: raise ValueError(f"{dtype} must have a positive column count") if not isinstance(rows, int) or rows < 1: raise ValueError(f'{rows} is not a valid row count') rand = default_rng(seed) def make_cols(): y20_in_ns = 20 * 365.2425 * 24 * 60 * 60 * 1e9 start = np.datetime64('2000-01-01', 'ns') end = start + np.timedelta64(int(y20_in_ns), 'ns') for dtype, n in cols.items(): shape = n, rows mode = dict(size=shape, dtype=dtype) if np.issubdtype(dtype, np.integer): array = rand.integers(**mode, low=0, high=100) elif np.issubdtype(dtype, np.floating): # uniform() does not support dtype. Also, this will only work with float32 or float64. # For something more exotic, you need a separate branch. array = rand.random(**mode)*100. elif np.issubdtype(dtype, np.bool_): array = rand.integers(**mode, low=0, high=1, endpoint=True) elif np.issubdtype(dtype, np.datetime64): array = rand.integers( size=shape, dtype=np.int64, low=start, high=end ).astype('datetime64[ns]').astype(dtype) else: raise ValueError(f'Type {dtype.__name__} is not supported') for i, col in enumerate(array): if isinstance(dtype, str): type_name = dtype else: type_name = dtype.__name__ yield f'{type_name}_col_{i}', col return pd.DataFrame(dict(make_cols())) def run_test(): return generate_dummy_df( cols={ np.int64: 5, np.float64: 5, np.bool_: 5, 'datetime64[ns]': 5, }, rows=10_000_000, ) t = timeit(run_test, number=1) print(t)
{ "domain": "codereview.stackexchange", "id": 44297, "lm_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, pandas", "url": null }
beginner, c Title: Write a program to print all input lines that are longer than 80 characters Question: Like many posts before, I'm going through The C Programming Language, 2nd Edition, by Kernighan and Ritchie. I am very new to the c programming language. While I have a somewhat decent understanding of programming basics, I'm most looking forward to learning about memory management in c. Anyway, I'm looking for feedback on my latest exercise solution from the book. Exercise 1-17. Write a program to print all input lines that are longer than 80 characters. My initial solution: #include <stdio.h> #include <string.h> #define MINCHARS 80 #define MAXLINE 1000 int getLine(char line[], int size); int main() { char line[MAXLINE]; char minCharsLine[MAXLINE][MAXLINE]; int lineCharCount[MAXLINE]; int c; int len; int lineCount; len = 0; lineCount = 0; while ((c = getchar()) != EOF) { line[len] = c; len++; if (len > MINCHARS) { if (c == '\n') { lineCount++; strcpy(minCharsLine[lineCount], line); lineCharCount[lineCount] = len; len = 0; } } else if (c == '\n') { len = 0; } } if (lineCount > 0 ) { for (int i = 0; i < lineCount + 1; i++) { for (int j = 0; j < lineCharCount[i]; j++) { printf("%c", minCharsLine[i][j]); } } } else { printf("No lines over 80 characters\n"); } }
{ "domain": "codereview.stackexchange", "id": 44298, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "beginner, c", "url": null }
beginner, c Answer: Nice layout/formatting Object names are reasonable. Saving more than about 80 characters is not needed Once the "80" line length is reach, print the first 80 characters and then the rest of incoming characters until end-of-line/end-of-file. char minCharsLine[MAXLINE][MAXLINE], int lineCharCount[MAXLINE] not needed. Good that code saved the return value of getchar() in an int getchar() returns 257 different values*1. Saving in a char can lose information. Function signature For this student exercise, int getLine(char line[], int size); is OK - but curiously never defined? In C, array indexes can exceed INT_MAX. The unsigned type size_t is size to accommodate all array indexing and object sizing. Consider size_t getLine(char line[], size_t size); // or size_t getLine(size_t size, char line[]); The first form is more common. Advanced: The 2nd has an advantage when coded as size_t getLine(size_t size, char line[size]); Yet for various portability concerns, this needs to wait until C2x. Must the last line contain a '\n'? Your design choice. Best to be clear about what code does if it received an EOF following a non-'\n'. That is, the last line did not end with a '\n'. A text stream is an ordered sequence of characters composed into lines, each line consisting of zero or more characters plus a terminating new-line character. Whether the last line requires a terminating new-line character is implementation-defined. C17dr § 7.21.2 2 MAXLINE is not necessarily the same as LINECOUNT_N Better as: // char minCharsLine[MAXLINE][MAXLINE]; #define LINECOUNT_N 1024 char minCharsLine[LINECOUNT_N][MAXLINE]; MAXLINE versus alternates Many off-by-one errors stem from not being clear. MAXLINE sounds like the maximum returned strlen(line). To achieve that length, the array size needed is MAXLINE + 1. Perhaps: #define MAXLINE 80 #define LINE_SIZE (MAXLINE + 1) char line[LINE_SIZE]; // or #define MAXLINE 80 char line[MAXLINE + 1];
{ "domain": "codereview.stackexchange", "id": 44298, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "beginner, c", "url": null }
beginner, c // or #define MAXLINE 80 char line[MAXLINE + 1]; Line counts can be large Code performs minCharsLine[lineCount] without ever checking if lineCount is too high. Better to exit with an error message than go on. The line count of a file is not limited to INT_MAX. I'd use unsigned long or uintmax_t for the line count. Of course even that is not the upper bound, just a safer bet. Simplification OP's code is OK and does handle the unexpected reading of null characters and "prints" them with: for (int j = 0; j < lineCharCount[i]; j++) { printf("%c", minCharsLine[i][j]); } Simplier to use: fwrite(minCharsLine[i], lineCharCount[i], 1, stdout); If code does not need to support reading null characters, make sure minCharsLine[i] is 1 wider, append a null character to minCharsLine[i],and use the below: fputs(minCharsLine[i], stdout); Simplify?? Along time ago printf("%c", minCharsLine[i][j]) was considered inefficient versus the simpler putchar(minCharsLine[i][j]). That still applies to some compilers today, yet good compilers are smart and will emit efficient code either way. Using putchar(minCharsLine[i][j]) is typically better, yet for such linear optimization cases as this over that, do consider clarity of code and let the compiler cope with optimizations. fgets() fgets() is mostly a drop in replacement for this exercise, yet it has functional difference in special cases. *1 EOF and [0...UCHAR_MAX]. This may be more than 257 different values when UCHAR_MAX is more than 255.
{ "domain": "codereview.stackexchange", "id": 44298, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "beginner, c", "url": null }
c++, json, c++17 Title: JSON value with std::variant Question: For learning purposes, I wanted to implement a class that could hold JSON data with std::variant. Most of the implementations I found online were using incomplete types as template arguments for map, which is -at least according to my understanding- not C++17 compliant and implementation dependant (sometimes not compiling). Instead, I used a recursive wrapper with std::unique_ptr to bypass this limitation. I plan to add a parser/serializer and more features like iterators to make it more useful (with the same kind of interface as excellent Nlohmann's library). But before going further, I'd like to know if there is a massive flaw in my design. I am also interested in any optimizations I could make to prevent extra copies for example. json.hpp #pragma once #include <memory> #include <stdexcept> #include <string> #include <type_traits> #include <unordered_map> #include <variant> #include <vector> namespace Json { namespace Internal { template<typename T> class RecursiveWrapper { public: RecursiveWrapper(const RecursiveWrapper& r) : p(std::make_unique<T>(*r.p)) {} RecursiveWrapper(RecursiveWrapper&& r) noexcept : p(std::move(r.p)) {} RecursiveWrapper(const T& r) : p(std::make_unique<T>(r)) {} ~RecursiveWrapper() = default; operator const T& () const { return *p.get(); } operator T& () { return *p.get(); } RecursiveWrapper& operator=(const RecursiveWrapper& other) { if (other.p) p = std::make_unique<T>(*other.p); else p.reset(); return *this; } private: std::unique_ptr<T> p; }; } class Array; class Object; using Value = std::variant< std::monostate, Internal::RecursiveWrapper<Object>, Internal::RecursiveWrapper<Array>, std::string, bool, long long int, double >;
{ "domain": "codereview.stackexchange", "id": 44299, "lm_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++, json, c++17", "url": null }
c++, json, c++17 class Json : protected Value { using Value::Value; public: Json(std::nullptr_t = nullptr); Json(std::initializer_list<Json> init); Json(const char* s); // prevent "string" to be casted to bool template< typename T, std::enable_if_t<!std::is_convertible_v<T, Value> && !std::is_same_v<T, bool>&& std::is_integral_v<T>, bool> = true > Json(const T i) : Value(static_cast<long long int>(i)) { } // Cast other int types to long long int template<typename T> const T& get() const { if constexpr (std::is_same_v<T, void>) throw std::runtime_error("Json value is empty"); else if constexpr (std::is_same_v<T, Object>) return static_cast<const Object&>(std::get<Internal::RecursiveWrapper<Object>>(*this)); else if constexpr (std::is_same_v<T, Array>) return static_cast<const Array&>(std::get<Internal::RecursiveWrapper<Array>>(*this)); else return std::get<T>(static_cast<const Value&>(*this)); } template<typename T> T& get() { if constexpr (std::is_same_v<T, void>) throw std::runtime_error("Json value is empty"); else if constexpr (std::is_same_v<T, Object>) return static_cast<Object&>(std::get<Internal::RecursiveWrapper<Object>>(*this)); else if constexpr (std::is_same_v<T, Array>) return static_cast<Array&>(std::get<Internal::RecursiveWrapper<Array>>(*this)); else return std::get<T>(static_cast<Value&>(*this)); } template<typename T> bool is() const { if constexpr (std::is_same_v<T, Object>) return std::holds_alternative<Internal::RecursiveWrapper<Object>>(*this); else if constexpr (std::is_same_v<T, Array>) return std::holds_alternative<Internal::RecursiveWrapper<Array>>(*this); else return std::holds_alternative<T>(*this); } Json& operator[](const std::string& s); const Json& operator[](const std::string& s) const;
{ "domain": "codereview.stackexchange", "id": 44299, "lm_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++, json, c++17", "url": null }
c++, json, c++17 Json& operator[](const std::string& s); const Json& operator[](const std::string& s) const; Json& operator[](const size_t i); const Json& operator[](const size_t i) const; }; class Array : public std::vector<Json> { using std::vector<Json>::vector; }; class Object : public std::unordered_map<std::string, Json> { using std::unordered_map<std::string, Json>::unordered_map; }; } json.cpp #include "json.hpp" namespace Json { Value JsonFromInitList(std::initializer_list<Json> init) { if (init.size() == 2 && init.begin()->is<std::string>()) return Object({ { init.begin()->get<std::string>(), *(init.begin() + 1) } }); // If all elements are pairs and first element is a string, // this is an object, otherwise it's an array for (const auto& j : init) { if (!j.is<Object>() || j.get<Object>().size() != 1) return Array(init); } Object output; for (const auto& j : init) { output.insert(*j.get<Object>().begin()); } return output; } Json::Json(std::nullptr_t) { } Json::Json(std::initializer_list<Json> init) : Value(JsonFromInitList(init)) { } Json::Json(const char* s) : Value(std::string(s)) { } Json& Json::operator[](const std::string& s) { // If empty, convert it to object if (std::holds_alternative<std::monostate>(*this)) *this = Object(); if (!std::holds_alternative<Internal::RecursiveWrapper<Object>>(*this)) throw std::runtime_error("Json value is not an object"); return get<Object>()[s]; } const Json& Json::operator[](const std::string& s) const { if (!std::holds_alternative<Internal::RecursiveWrapper<Object>>(*this)) throw std::runtime_error("Json value is not an object"); return get<Object>().at(s); } Json& Json::operator[](const size_t i) { if (!std::holds_alternative<Internal::RecursiveWrapper<Array>>(*this)) throw std::runtime_error("Json value is not an array"); return get<Array>()[i]; }
{ "domain": "codereview.stackexchange", "id": 44299, "lm_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++, json, c++17", "url": null }
c++, json, c++17 return get<Array>()[i]; } const Json& Json::operator[](const size_t i) const { if (!std::holds_alternative<Internal::RecursiveWrapper<Array>>(*this)) throw std::runtime_error("Json value is not an array"); return get<Array>().at(i); } } main.cpp #include <cassert> #include "json.hpp" int main(int argc, char* argv[]) { const Json::Json json = { {"pi", 3.141}, {"happy", true}, {"nothing", nullptr}, { "answer", { {"everything", 42} } }, {"list", {1, 0, 2}}, { "object", { {"currency", "USD"}, {"value", 42.99} } } }; assert(json.is<Json::Object>()); assert(json.get<Json::Object>().size() == 6); assert(json["happy"].is<bool>()); assert(json["nothing"].is<std::monostate>()); assert(json["answer"].is<Json::Object>()); assert(json["answer"].get<Json::Object>().size() == 1); assert(json["answer"]["everything"].is<long long int>()); assert(json["answer"]["everything"].get<long long int>() == 42); assert(json["list"].is<Json::Array>()); assert(json["list"].get<Json::Array>().size() == 3); assert(json["list"][2].get<long long int>() == 2); assert(json["object"].is<Json::Object>()); assert(json["object"].get<Json::Object>().size() == 2); Json::Json json2 = {}; assert(json2.is<std::monostate>()); json2["key"] = json; assert(json2.is<Json::Object>()); assert(json2["key"].is<Json::Object>()); const Json::Json json3 = "Hello"; assert(json3.is<std::string>()); assert(json3.get<std::string>() == "Hello"); const Json::Json json4 = 3.5f; assert(json4.is<double>()); return 0; } Answer: RecursiveWrapper(const RecursiveWrapper& r) : p(std::make_unique<T>(*r.p)) {} Might be dereferencing a null ptr? RecursiveWrapper(const T& r) : p(std::make_unique<T>(r)) {} Should be explicit to prevent accidents. We probably want a move version too: RecursiveWrapper(T&& r) p(std::make_unique<T>(std::move(r))) {}
{ "domain": "codereview.stackexchange", "id": 44299, "lm_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++, json, c++17", "url": null }
c++, json, c++17 operator const T& () const { return *p.get(); } operator T& () { return *p.get(); } It would be safer to provide get() functions instead of implicit (!!) conversion operators (!). Again, we might be dereferencing a null ptr. We could add an assert to clearly indicate that we're aware of the issue, and that it's the caller's responsibility to avoid it. class Json : protected Value { using Value::Value; I think there are more downsides than upsides to inheriting from std::variant (and most other std types). Especially here, where we don't actually want any of the functionality to be public. It's much simpler to use an ordinary member variable. Json(std::nullptr_t = nullptr); Json(std::initializer_list<Json> init); Json(const char* s); // prevent "string" to be casted to bool template< typename T, std::enable_if_t<!std::is_convertible_v<T, Value> && !std::is_same_v<T, bool> && std::is_integral_v<T>, bool> = true > Json(const T i) : Value(static_cast<long long int>(i)) { } // Cast other int types to long long int You'll need a lot of testing with various different types to make sure there aren't any unexpected conversions due to the implicit constructors here. Inheriting from std::variant makes this especially (and unnecessarily?) complicated. I'm actually a bit suprised that a Json can be constructed from a bool or double. (How? Maybe that's worth a comment in the code if it's intentional). if constexpr (std::is_same_v<T, void>) throw std::runtime_error("Json value is empty"); Perhaps we should make this a compile time error instead of a runtime error? else if constexpr (std::is_same_v<T, Object>) return static_cast<const Object&>(std::get<Internal::RecursiveWrapper<Object>>(*this)); else if constexpr (std::is_same_v<T, Array>) return static_cast<const Array&>(std::get<Internal::RecursiveWrapper<Array>>(*this)); else return std::get<T>(static_cast<const Value&>(*this));
{ "domain": "codereview.stackexchange", "id": 44299, "lm_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++, json, c++17", "url": null }
c++, json, c++17 std::get will throw a std::bad_variant_access if we get the type wrong, but I'm not sure we want to expose the user to std::variant. We might check the type ourselves, and throw a std::runtime_error with a more useful message instead. Json& operator[](const std::string& s); const Json& operator[](const std::string& s) const; Json& operator[](const size_t i); const Json& operator[](const size_t i) const; Hmmmmmmmmmm... If you start down this route, you'll probably end up providing the entire map and vector interfaces in the Json object. For example, what use is operator[] without being able to call .size()? And then we should provide iterator access, right? And why only provide the interfaces for arrays and maps, when we could allow the user to use operator+ directly on integer values?! etc. It's a rather deep rabbit hole. It might be more verbose to make the user write j.get<Array>()[0] instead of j[0], but that may prove simpler and easier (for both you and the user) in the long run. class Array : public std::vector<Json> { using std::vector<Json>::vector; }; class Object : public std::unordered_map<std::string, Json> { using std::unordered_map<std::string, Json>::unordered_map; }; Can these not be simple typedefs? I think we can do all that with forward declaration: class Json; using Array = std::vector<Json>; using Object = std::unordered_map<Json>; class Json { ... using Value = std::variant<..., Array, Object>; Value value; }; The Value typedef and all the variant shenanigans can then be neatly hidden inside Json, and not something the user has to care about. Value JsonFromInitList(std::initializer_list<Json> init) { if (init.size() == 2 && init.begin()->is<std::string>()) return Object({ { init.begin()->get<std::string>(), *(init.begin() + 1) } });
{ "domain": "codereview.stackexchange", "id": 44299, "lm_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++, json, c++17", "url": null }
c++, json, c++17 // If all elements are pairs and first element is a string, // this is an object, otherwise it's an array for (const auto& j : init) { if (!j.is<Object>() || j.get<Object>().size() != 1) return Array(init); } Object output; for (const auto& j : init) { output.insert(*j.get<Object>().begin()); } return output; } I don't think this is correct (or at least, there are lots of ambiguities), e.g.: Are 2 strings really always an object, never an array? Why can't we have an array of pairs, where the first value of each pair is a string? We probably need separate Array and Object constructors for Json instead of a single initializer_list constructor. (And I don't think there's any reasonable way to avoid putting the burden of specifying Array / Object types on the user, but I also don't think that's a problem. We can't use [] and {} to differentiate arrays and objects in C++ code). So, for example: const Json::Json json = Json::Object { {"pi", 3.141}, // we're initializing a std::map<string, variant> now, so this shouldn't need the type specified {"happy", true}, {"nothing", nullptr}, { "answer", Json::Object{ // specify the type {"everything", 42} } }, {"list", Json::Array{1, 0, 2}}, // specify the type { "object", Json::Object{ // specify the type {"currency", "USD"}, {"value", 42.99} } } }; Json& Json::operator[](const std::string& s) { // If empty, convert it to object if (std::holds_alternative<std::monostate>(*this)) *this = Object(); if (!std::holds_alternative<Internal::RecursiveWrapper<Object>>(*this)) throw std::runtime_error("Json value is not an object"); return get<Object>()[s]; }
{ "domain": "codereview.stackexchange", "id": 44299, "lm_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++, json, c++17", "url": null }
c++, json, c++17 return get<Object>()[s]; } Ehhhhhhh... That cast to Object seems kinda sus. I'm not sure a "null" should be treated the same way as an "empty Object" in JSON (and why not as an empty Array instead / too?). If the user wanted an empty "Object", they could have created one. If they go to the bother of explicitly creating a null value, then they probably want the type safety to go with it. (Which maybe indicates that we shouldn't actually have a default constructor for the Json class, because we need the user to specify the type).
{ "domain": "codereview.stackexchange", "id": 44299, "lm_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++, json, c++17", "url": null }
java, performance, multithreading, thread-safety Title: Multiplayer queue optimisation Question: I currently have code that is working but I think it can be optimised. The code waits until a player joins and adds the player to a BlockingQueue if there is not already a Player waiting then it starts a game. The code also allows for multiple games to be played at the same time. The Players are two different threads that need to get the same answer about the game outcome. PlayerQueue import java.util.concurrent.*; public class PlayerQueue { private final BlockingQueue<String> blockingQueue = new LinkedBlockingQueue<>(1); private final ConcurrentMap<String, String> userIdToResponse = new ConcurrentHashMap<>(); public String battle(String user) { String opponent = null; try { boolean stopLoop = false; while (!stopLoop) { if (blockingQueue.remainingCapacity() > 0) { stopLoop = blockingQueue.offer(user, 1, TimeUnit.SECONDS); } else { opponent = blockingQueue.poll(500, TimeUnit.MILLISECONDS); if (opponent != null) { System.out.println("starting game"); String outcome = match(user, opponent); userIdToResponse.put(opponent, outcome); return outcome; } } } } catch (InterruptedException e) { e.printStackTrace(); return "SOMETHING WENT WRONG"; } if (opponent == null) { while (!userIdToResponse.containsKey(user)) { } return userIdToResponse.get(user); } return "ERROR"; } private String match(String user1, String user2) { return user1 + " vs. " + user2; } } Main import java.util.concurrent.Executor; import java.util.concurrent.Executors; public class Main {
{ "domain": "codereview.stackexchange", "id": 44300, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, performance, multithreading, thread-safety", "url": null }
java, performance, multithreading, thread-safety public class Main { public static void main(String[] args) { PlayerQueue playerQueue = new PlayerQueue(); Executor executor = Executors.newFixedThreadPool(10); for (int i = 0; i < 10; ++i) { String user = "user" + Integer.toString(i); executor.execute(() -> System.out.println(playerQueue.battle(user))); } } } Step-by-Step Game Example: Player 1 Thread calls the battle and passes the User its user instance which will be stored in the Queue Player 2 Thread calls the battle since there is a player in the queue it starts a game The game ends the Player 2 Thread puts the Game result into the Map Player 1 Thread finds their User.id in the map gets the response and returns to the Response to the thread Concerns: Infinity while loop on the map and no possibility to stop thread 1 Overall performance because of the while loop Answer: Method battle is doing way too much. It is adding first player and waiting for second. It is adding the second and then playing and getting response. This all should have separate methods for clearer code. Infinite loop can be handled by multiple ways. The simplest would be to use wait + notify. That way the first thread just waits and the second thread notifies the first one and wakes him up. I will describe imho better ways later. In fact your whole infinite loop looks incorrect, because you are catching InterruptedException (for blockingQueue.offer and poll) outside your while-loop. Makes sense to put try-catch within your first loop. But I would get rid of the whole loop and try-catch completely and choose reasonable timeouts. You are never removing items from userIdToResponse. That leads to memory leaks and possibly bugs.
{ "domain": "codereview.stackexchange", "id": 44300, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, performance, multithreading, thread-safety", "url": null }
java, performance, multithreading, thread-safety You are never removing items from userIdToResponse. That leads to memory leaks and possibly bugs. Your code is not thread-safe and sometimes players joining can fail. Imagine your first condition succeeds, because remainingCapacity() is greater than 0, but there are 2 threads there and one thread calls offer inbetween so one thread ends up being without anything in the queue and fails on the timeout. The fact, that this is synchronous code smells. You call one method, that joins the queue, battle and returns results of the game. Is very likely to be bad in real life. I see getting results more like asynchronous callback called in the end for both players. It also gets rid of the second infinite loop that you have there. For me this seems like ideal case for producer-consumer scenario. It deals with all of the problems I described above. You can have multiple producers (game clients) and single consumer that handles game ("server"). Whenever a player wants to join, he will be added to player queue and battles will be handled by consumer, that will always require 2 players. This will also clearly separate code, that handles players waiting to join and players that are starting the game. Then you can for example do some kind of matchmaking and match players together based on their rating easily by choosing how to take player pairs from the current queue.
{ "domain": "codereview.stackexchange", "id": 44300, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, performance, multithreading, thread-safety", "url": null }
python, numpy, pandas, machine-learning, data-visualization Title: Multithreaded HD Image Processing + Logistic reg. Classifier + Visualization Question: [I'm awaiting suggestions for improvement/optimization/more speed/general feedback ...] This code takes a label and a folder path of subfolders as input that have certain labels ex: trees, cats with each folder containing a list of HD photos corresponding to the folder name, then a multithreaded image processor converts data to .h5 format and classifies photos with the given label (75% accuracy with default parameters but might get better or worse). It's a very simple algorithm using logistic regression model(implementation) not sklearn's LogisticRegression() and some visualizations using matplotlib(read the docs). The following link has the code as well as the necessary .h5 files to make it work and demonstrate an example on classifying dog photos but feel free to test with your own image data. https://drive.google.com/open?id=1b5uWn4-a7T_B3d_A67AhjS8x2PIv6SCb Running the example in the code with the random seed set to 127 should give these results: Labeled predicted images(sample): The following figure represents n samples of the correct predicted results and displays 1 for dog and 0 for non-dog images. Learning curve with the given parameters: This is the cost function/degree of error with respect to gradient descent iteration number (max_iter=3000) Code: from concurrent.futures import ThreadPoolExecutor, as_completed import matplotlib.pyplot as plt from time import perf_counter import pandas as pd import numpy as np import cv2 import os def read_and_resize(img, new_size): """ Read and resize image. Args: img: Image path. new_size: New image size. Return: Resized Image. """ img = cv2.imread(img) return cv2.resize(img, new_size)
{ "domain": "codereview.stackexchange", "id": 44301, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, numpy, pandas, machine-learning, data-visualization", "url": null }
python, numpy, pandas, machine-learning, data-visualization def folder_to_hdf(folder_path, label, new_size, threads=5): """ Save a folder images to hdf format. Args: folder_path: Path to folder containing images. label: Data label. new_size: New image size(tuple). threads: Number of parallel threads. Return: None """ data, resized = pd.DataFrame(), [] with ThreadPoolExecutor(max_workers=threads) as executor: future_resized_images = { executor.submit(read_and_resize, folder_path + img, new_size): img for img in os.listdir(folder_path) if img != '.DS_Store' } for future in as_completed(future_resized_images): result = future.result() resized.append(result) print(f'Processing ({label})-{future_resized_images[future]} ... done.') del future_resized_images[future] data['Images'] = resized data['Label'] = label data.to_hdf(folder_path + label + '.h5', label) def folders_to_hdf(folder_path, new_size, threads=5): """ Save folders containing images to hdf format. Args: folder_path: Path to folder containing folders containing images. new_size: New image size(tuple). threads: Number of parallel threads. Return: None """ for folder_name in os.listdir(folder_path): if folder_name != '.DS_Store': path = ''.join([folder_path, folder_name, '/']) folder_to_hdf(path, folder_name, new_size, threads) def clear_hdf(folder_path): """ Delete .h5 files in every sub-folder in folder_path. Args: folder_path: A folder containing folders of images and their .h5.
{ "domain": "codereview.stackexchange", "id": 44301, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, numpy, pandas, machine-learning, data-visualization", "url": null }
python, numpy, pandas, machine-learning, data-visualization Return: None """ for folder_name in os.listdir(folder_path): if folder_name != '.DS_Store': file_name = ''.join([folder_path, folder_name, '/', folder_name, '.h5']) os.remove(file_name) print(f'Removed {file_name.split("/")[-1]}') def load_hdf(folder_path, label, random_seed=None): """ Load all classification data. Args: folder_path: Folder containing folders with respective images. label: Label to set to 1. random_seed: int, representing the random seed. Return: X and Y as numpy arrays and frames. """ if random_seed: np.random.seed(random_seed) file_names = [ ''.join([folder_path, folder_name, '/', folder_name, '.h5']) for folder_name in os.listdir(folder_path) if folder_name != '.DS_Store' ] frames = [pd.read_hdf(file_name) for file_name in file_names] frames = pd.concat(frames) frames['Classification'] = 0 frames.loc[frames['Label'] == label, 'Classification'] = 1 new_index = np.random.permutation(frames.index) frames.index = new_index frames.sort_index(inplace=True) image_data, labels = ( np.array(list(frames['Images'])), np.array(list(frames['Classification'])), ) return image_data, labels, frames def pre_process( data, test_size, label, max_pixel=255, display_images=None, show_details=False ): """ Split the data into train and test sets and prepare the data for further processing. Args: data: X and Y as numpy arrays and frames. test_size: Percentage of test set. label: label to classify. max_pixel: The maximum value of a pixel channel. display_images: A tuple (n_images, rows, columns) show_details: If True, details about the sizes will be displayed.
{ "domain": "codereview.stackexchange", "id": 44301, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, numpy, pandas, machine-learning, data-visualization", "url": null }
python, numpy, pandas, machine-learning, data-visualization Return: x_train, y_train, x_test, y_test, frames. """ image_data, labels, frames = data total_images = len(image_data) if display_images: fig = plt.figure() plt.title( f'Initial(before prediction) {display_images[1]} x {display_images[2]} ' f'data sample (Classification of {label})' ) rows, columns = display_images[1], display_images[2] for i in range(display_images[0]): img = image_data[i] fig.add_subplot(rows, columns, i + 1) plt.imshow(img) plt.show() image_data = image_data.reshape(total_images, -1) / max_pixel labels = labels.reshape(total_images, -1) separation_index = int(test_size * total_images) x_train = image_data[separation_index:].T y_train = labels[separation_index:].T x_test = image_data[:separation_index].T y_test = labels[:separation_index].T if show_details: print(f'Total number of images: {total_images}') print(f'x_train shape: {x_train.shape}') print(f'y_train shape: {y_train.shape}') print(f'x_test shape: {x_test.shape}') print(f'y_test shape: {y_test.shape}') return x_train, y_train, x_test, y_test, frames def sigmoid(x): """ Calculate sigmoid function. Args: x: Image data in the following shape(pixels * pixels * 3, number of images). Return: sigmoid(x). """ return 1 / (1 + np.exp(-x)) def compute_cost(w, b, x, y): """ Compute cost function using forward and back propagation. Args: w: numpy array of weights(also called Theta). b: Bias(int) x: Image data in the following shape(pixels * pixels * 3, number of images) y: Label numpy array of labels(0s and 1s)
{ "domain": "codereview.stackexchange", "id": 44301, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, numpy, pandas, machine-learning, data-visualization", "url": null }
python, numpy, pandas, machine-learning, data-visualization Return: Cost and gradient(dw and db). """ total_images = x.shape[1] activation = sigmoid(np.dot(w.T, x) + b) cost = (-1 / total_images) * ( np.sum(y * np.log(activation) + (1 - y) * np.log(1 - activation)) ) cost = np.squeeze(cost) dw = (1 / total_images) * np.dot(x, (activation - y).T) db = (1 / total_images) * np.sum(activation - y) return cost, dw, db def g_descent(w, b, x, y, max_iter, learning_rate, iteration_number=None): """ Optimize weights and bias using gradient descent algorithm. Args: w: numpy array of weights(also called Theta). b: Bias(int) x: Image data in the following shape(pixels * pixels * 3, number of images) y: Label numpy array of labels(0s and 1s) max_iter: Maximum number of iterations learning_rate: The rate of learning. iteration_number: Display iteration and current cost every n. Return: w, b, dw, db, costs """ dw, db, costs = 0, 0, [] for iteration in range(max_iter): cost, dw, db = compute_cost(w, b, x, y) w -= dw * learning_rate b -= db * learning_rate costs.append(cost) if iteration_number and iteration % iteration_number == 0: print(f'Iteration number: {iteration} out of {max_iter} iterations') print(f'Current cost: {cost}\n') return w, b, dw, db, costs def predict(w, b, x): """ Predict labels of x. Args: w: numpy array of weights(also called Theta). b: Bias(int) x: Image data in the following shape(pixels * pixels * 3, number of images) Return: Y^ numpy array of predictions. """ w = w.reshape(x.shape[0], 1) activation = sigmoid(np.dot(w.T, x) + b) activation[activation > 0.5] = 1 activation[activation <= 0.5] = 0 return activation
{ "domain": "codereview.stackexchange", "id": 44301, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, numpy, pandas, machine-learning, data-visualization", "url": null }
python, numpy, pandas, machine-learning, data-visualization def predict_from_folder( folder_path, target_label, test_size=0.2, max_iter=3000, learning_rate=0.0001, random_seed=None, max_pixel=255, display_initial_images=None, show_initial_details=False, create_hdf=False, threads=5, new_image_sizes=(150, 150), display_results=False, iteration_number=100, plot_learning_curve=False, photo_results=None, ): """ Classify a target label from different folders containing HD images in a way that each folder contains only images that represent the folder name/label. Args: folder_path: A folder path that contains other folders named according to what label they contain. target_label: One of the folder labels in folder_path. test_size: Test size in percentage ex: 0.7 max_iter: Maximum number of iterations for gradient descent. learning_rate: Learning rate for gradient descent, random_seed: int, representing a random seed. max_pixel: The maximum value of a pixel channel. display_initial_images: A tuple (n_images, rows, columns) show_initial_details: If True, details about the initial sizes will be displayed. create_hdf: If True, old .h5 files found in the labeled folders will be cleared(if any) and new ones will be created. threads: int, representing the number of parallel threads for .h5 creation process. new_image_sizes: New dimensions to store in .h5 files. display_results: If True, training accuracy will be calculated and displayed. iteration_number: Display gradient descent iteration number and current cost. plot_learning_curve: If True, learning curve will be plotted. photo_results: A tuple (n_photos, rows, columns) to display n labeled results. Return: pandas DataFrame with the results. """ start_time = perf_counter() if create_hdf: clear_hdf(folder_path)
{ "domain": "codereview.stackexchange", "id": 44301, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, numpy, pandas, machine-learning, data-visualization", "url": null }
python, numpy, pandas, machine-learning, data-visualization """ start_time = perf_counter() if create_hdf: clear_hdf(folder_path) folders_to_hdf(folder_path, new_image_sizes, threads) data = load_hdf(folder_path, target_label, random_seed) x_train, y_train, x_test, y_test, frames = pre_process( data, test_size, target_label, max_pixel, display_initial_images, show_initial_details, ) w, b = np.zeros((len(x_train), 1)), 0 w, b, dw, db, costs = g_descent( w, b, x_train, y_train, max_iter, learning_rate, iteration_number ) train_predictions = predict(w, b, x_train) test_predictions = predict(w, b, x_test) all_predictions = np.append(train_predictions, test_predictions) training_accuracy = 100 - np.mean(np.abs(train_predictions - y_train)) * 100 test_accuracy = 100 - np.mean(np.abs(test_predictions - y_test)) * 100 frames['Predictions'] = all_predictions frames['Accuracy'] = 0 frames.loc[frames['Predictions'] == frames['Classification'], 'Accuracy'] = 1 if display_results: print(f'Training accuracy: {training_accuracy}%') print(f'Test accuracy: {test_accuracy}%') print(f'Train predictions: \n{train_predictions}') print(f'Train actual: \n{y_train}') print(f'Test predictions: \n{test_predictions}') print(f'Test actual: \n{y_test}') if plot_learning_curve: plt.title('Learning curve') plt.plot(range(max_iter), costs) plt.xlabel('Iterations') plt.ylabel('Cost') if photo_results: to_display = frames[frames['Accuracy'] == 1][['Images', 'Predictions']].head( photo_results[0] ) images = np.array(list(to_display['Images'])) predictions = np.array(list(to_display['Predictions'])) fig = plt.figure() plt.title(f'Classification of {target_label} results sample') rows, columns = photo_results[1], photo_results[2]
{ "domain": "codereview.stackexchange", "id": 44301, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, numpy, pandas, machine-learning, data-visualization", "url": null }
python, numpy, pandas, machine-learning, data-visualization rows, columns = photo_results[1], photo_results[2] for i in range(photo_results[0]): img = images[i] ax = fig.add_subplot(rows, columns, i + 1) ax.title.set_text(f'Prediction: {predictions[i]}') plt.imshow(img) plt.show() end_time = perf_counter() print(f'Time: {end_time - start_time} seconds.') return frames
{ "domain": "codereview.stackexchange", "id": 44301, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, numpy, pandas, machine-learning, data-visualization", "url": null }
python, numpy, pandas, machine-learning, data-visualization if __name__ == '__main__': folder = 'test_photos/' target = 'Dog' photo_display_size = (10, 2, 5) predict_from_folder( folder, target, display_initial_images=photo_display_size, show_initial_details=True, display_results=True, plot_learning_curve=True, photo_results=photo_display_size, random_seed=127 ) Answer: I'm not especially fond of 1st identifier here: def read_and_resize(img, new_size): Identifiers in a public API have greater documentation burden than private methods or local temp vars. Better to spell it out, as img_path or image_path. Also, optional type hinting in the signature wouldn't hurt. That said, the docstring is pretty clear on the details. It did take me a while to navigate up to predict_from_folder and learn that new_image_sizes=(150, 150) is the recommended default. We pass this parameter through many function calls. Consider turning some functions into methods, and making that image size a self. object attribute. BTW, some of the docstrings explain it's a tuple, while others seem to suggest it could be a scalar integer. I don't find that this tuple unpack helps aid human comprehension: data, resized = pd.DataFrame(), [] Prefer to init data down below the loop, just prior to assigning its columns. You might choose to pass in resized and label in the creation call. I don't understand why this is valuable: del future_resized_images[future] The entire list will go out-of-scope after just a few source lines. Do we truly not have room for 2x storage for a moment? If that's true, consider pre-populating the dataframe with a bunch of None values, and overwrite them as you iterate. Plus, I'm skeptical we even see 2x RAM consumption. Isn't it just a pair of pointers to same underlying image data? Premature optimization is the root of all evil (p.268).
{ "domain": "codereview.stackexchange", "id": 44301, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, numpy, pandas, machine-learning, data-visualization", "url": null }
python, numpy, pandas, machine-learning, data-visualization In folders_to_hdf you chose not to use os.walk(). Ok, that's fine. But I don't understand this test: if folder_name != '.DS_Store': Based on the identifier name, surely the relevant test would be is_dir? for folder_name in Path(folder_path).glob("*"): if folder_name.is_dir(): No? (I observe that folder_name.is_file() will be True for ".DS_Store".) In clear_hdf I counsel DRY. It seems like this and the previous method might call a common helper. We see a call to pre_process(data, test_size, ... ). The data identifier is sometimes warranted, but it is super vague. Here, I would rather see a call of (*data, ... and a signature of: def pre_process(image_data, labels, frames, test_size, ... ): Rather than rows, columns = display_images[1], display_images[2] prefer _, rows, columns = display_images Oh, wait, we have a range() in the next line! It's not an ignored parameter. So prefer n_images, rows, columns = display_images Consider Extract Helper for that whole if display_images: clause. Or maybe even evict it entirely -- caller can call the helper separately if desired. It is unclear to me how the stuff within that clause supports this method's Single Responsibility. Kudos on throwing max_pixel=255, into the signature; I really like that usage. No magic numbers here, good. The rest of the code is extremely clear. Similarly, g_descent is very clear. Nice decomposition into helpers. I am reading this: photo_display_size = (10, 2, 5) It seems a bit redundant. Consider making it a named tuple. Consider deriving the initial 10 from 2 * 5. Maybe "layout" instead of "size"? LGTM. Ship it!
{ "domain": "codereview.stackexchange", "id": 44301, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, numpy, pandas, machine-learning, data-visualization", "url": null }
python, performance, programming-challenge, recursion, matrix Title: Codewars: N-dimensional Von Neumann Neighborhood in a matrix Question: Task: For creating this challenge on Codewars I need a very performant function that calculates Von Neumann Neighborhood in a N-dimensional array. This function will be called about 2000 times The basic recursive approach: calculate the index span influenced by the distance if the index is in the range of the matrix go one step deeper into the next dimension if max dimension is reached - append the value to the global neigh list isCenter is just a token that helps to NOT INCLUDE the cell itself to the neighbourhood. There is also remaining_distance that reduce the span. You probably do not need to understand the process of this deep math so good. But maybe someone Python experienced can point me to some basic performance upgrade potential the code has. Questions: What I am curious about. Is .append inefficient? I heard list comprehensions are better than append. Would not (0 <= dimensions_coordinate < len(arr)) changed to len(arr) <= dimensions_coordinate or dimensions_coordinate < 0) boost the code? Are there performance differences between == and is? Is dimensions = len(coordinates)... if curr_dim == dimensions:... slower than if curr_dim == len(coordinates)? if you understood the math do you see a way to do it iterative? Because I heard recursions are slower in python and theoretical informatics says "Everything recursive can be iterative" The whole code: matrix is a N-dimensional matrix coordinates of the cell is a N-length tuple distance is the reach of the neighbourhood def get_neighbourhood(matrix, coordinates, distance=1): dimensions = len(coordinates) neigh = [] app = neigh.append def recc_von_neumann(arr, curr_dim=0, remaining_distance=distance, isCenter=True): #the breaking statement of the recursion if curr_dim == dimensions: if not isCenter: app(arr) return
{ "domain": "codereview.stackexchange", "id": 44302, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, performance, programming-challenge, recursion, matrix", "url": null }
python, performance, programming-challenge, recursion, matrix dimensions_coordinate = coordinates[curr_dim] if not (0 <= dimensions_coordinate < len(arr)): return dimesion_span = range(dimensions_coordinate - remaining_distance, dimensions_coordinate + remaining_distance + 1) for c in dimesion_span: if 0 <= c < len(arr): recc_von_neumann(arr[c], curr_dim + 1, remaining_distance - abs(dimensions_coordinate - c), isCenter and dimensions_coordinate == c) return recc_von_neumann(matrix) return neigh Answer: As far as lo <= x < hi expressions go, my advice is to keep them as-is. The meaning is clear, and "optimizing" such an expression can at best bring only minimal gains. (With the cPython interpreter, the only place I tend to deviate from such advice is turning an expression like x in [a, b, c] into x in (a, b, c), since the bytecode treats that triple as a constant rather than as a dynamically allocated data structure.) tiny nit: PEP-8 asks that you spell it is_center. Whatever. In the code for c in dimesion_span: if 0 <= c < len(arr): recc_von_neumann(arr[c], curr_dim + 1, remaining_distance - abs(dimensions_coordinate - c), isCenter and dimensions_coordinate == c) return please elide the final return, since we're just falling off the end of the function there. LGTM. Ship it!
{ "domain": "codereview.stackexchange", "id": 44302, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, performance, programming-challenge, recursion, matrix", "url": null }
php Title: Multi step form onboarding with sessions and cookies using PHP Question: My goal is to create a really seamless multi step form for onboarding with only PHP. It stores in sessions and cookies, and retrieves the session data from the cookie if it is stored. This is what I came up with but I feel it is pretty messy, and the more steps I have the messier it gets. I'm sure there are cleaner ways to do this. //Sets session & cookie to post if (isset($_POST['name'])){ $_SESSION['name'] = $_POST['name']; setcookie("name", $_POST['name']); } if (isset($_POST['address'])){ $_SESSION['address'] = $_POST['address']; setcookie("address", $_POST['address']); } if (isset($_POST['city'])){ $_SESSION['city'] = $_POST['city']; setcookie("city", $_POST['city']); } // Sets session to cookie if (isset($_COOKIE['name'])){ $_SESSION['name'] = $_COOKIE['name']; } if (isset($_COOKIE['address'])){ $_SESSION['address'] = $_COOKIE['address']; } if (isset($_COOKIE['city'])){ $_SESSION['city'] = $_COOKIE['city']; } //Sets post to session if (isset($_SESSION['name'])){ $_POST['name'] = $_SESSION['name']; } if (isset($_SESSION['address'])){ $_POST['address'] = $_SESSION['address']; } if (isset($_SESSION['city'])){ $_POST['city'] = $_SESSION['city']; } if(!isset($_POST['name']) || !isset($_SESSION['name']) ): ?> <h2>name</h2> <form method="post" autocomplete="off"> <input type="text" name="name" autocomplete="off" placeholder="name"><br> <input value="submit" type="submit"> </form> <?php elseif (!isset($_POST['address']) || !isset($_SESSION['address']) ): ?> <h2>address</h2> <form method="post" autocomplete="off"> <input type="text" name="address" autocomplete="off" placeholder="address"><br> <input value="submit" type="submit"> </form>
{ "domain": "codereview.stackexchange", "id": 44303, "lm_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", "url": null }
php <?php elseif (!isset($_POST['city']) || !isset($_SESSION['city']) ): ?> <h2>city</h2> <form method="post" autocomplete="off"> <input type="text" name="city" autocomplete="off" placeholder="city"><br> <input value="submit" type="submit"> </form> <?php endif ?> <form method="post" autocomplete="off"> <input type="text" name="clear_session" value="1" hidden><br> <input value="clear_session" type="submit"> </form> <form method="post" autocomplete="off"> <input type="text" name="clear_cookies" value="1" hidden><br> <input value="clear_cookies" type="submit"> </form> Answer: The most obvious and simple fix is to D.R.Y. your code. You can easily see structures where only the string name changes occur but the process stays the same. To separate your HTML markup from your processing code, it will look very tidy to declare HTML template strings. These can be declared as variables, but I'll use constants since they have no reason to change during processing. I'm using 'HEREDOC' syntax so that the numbered placeholders are not rendered as an undeclared variable $s. My opinion is that $_POST should have one-way population in that its contents should always represent the pure, unadulterated version of the user's submission payload. In my script below, I've removed the process where $_POST is populated by cached data. Although a departure from your original script (and I hope it is an acceptable alteration), I recommend that you not make successive if statements which may overwrite previous processes. You should determine which data points take priority over other and order your if-elseif-else logic accordingly.
{ "domain": "codereview.stackexchange", "id": 44303, "lm_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", "url": null }
php Suggested Code: (Demo) define('FIELDS', ['name', 'address', 'city']); define( 'HTML_FIELD_FORM', <<<'HTML' <h2>%1$s</h2> <form method="post" autocomplete="off"> <input type="text" name="%1$s" autocomplete="off" placeholder="%1$s"><br> <input value="submit" type="submit"> </form> HTML ); define( 'HTML_CLEAR_FORM', <<<'HTML' <form method="post" autocomplete="off"> <input type="text" name="%1$s" value="1" hidden><br> <input value="%1$s" type="submit"> </form> HTML ); foreach (FIELDS as $field) { if (isset($_POST[$field])) { // Set session & cookie from post $_SESSION[$field] = $_POST[$field]; setcookie($field, $_POST[$field]); } elseif (isset($_COOKIE[$field])) { // Set session from cookie $_SESSION[$field] = $_COOKIE[$field]; } elseif (!isset($_SESSION[$field])) { // Present individual field form printf(HTML_FIELD_FORM, $field); } } // Present nuking forms foreach (['clear_session', 'clear_cookies'] as $action) { printf(HTML_CLEAR_FORM, $action); }
{ "domain": "codereview.stackexchange", "id": 44303, "lm_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", "url": null }
c++, c++11, logging Title: C++ code for a simple single header logging library Question: I have been working out on C++ code lately just for fun and decided to make a simple logger in it. The code works fine, but it would be great if someone more knowledgeable could point out any mistakes/bad practices I would have carried along in my code. Also was curious on how I can go about writing testcases for the same and future code. #ifndef ACE_LOGGER_HEADER #define ACE_LOGGER_HEADER #include<chrono> #include<string> #include<iostream> #include<fstream> #include<mutex> enum LogLevel { FATAL = 4, ERROR = 3, WARN = 2, INFO = 1, DEBUG = 0 }; class Logger { public: static void init(LogLevel priority_level = INFO,bool save_to_file = false,bool console_output = true,std::string log_file_path = ""); static void Fatal(std::string message); static void Error(std::string message); static void Warn (std::string message); static void Info (std::string message); static void Debug(std::string message); private: static bool initialized; static bool console_output; static bool save_to_file; static LogLevel priority_level; static std::string log_file_path; static std::mutex logger_mutex; Logger(){} static Logger get_instance(); static void log(LogLevel log_level,std::string message); }; #ifdef ACE_LOGGER_IMPLEMENTATION bool Logger::initialized = false; bool Logger::console_output = true; bool Logger::save_to_file = false; LogLevel Logger::priority_level = LogLevel::INFO; std::string Logger::log_file_path = "LOG.txt"; std::mutex Logger::logger_mutex; Logger Logger::get_instance() { static Logger instance; return instance; }
{ "domain": "codereview.stackexchange", "id": 44304, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, c++11, logging", "url": null }
c++, c++11, logging Logger Logger::get_instance() { static Logger instance; return instance; } void Logger::init(LogLevel priority_level,bool save_to_file,bool console_output,std::string log_file_path) { if(console_output == false && save_to_file == false) { //Both console and file outputs disabled. Exiting logger; return; } if(save_to_file) { // Logging to file enabled if(log_file_path != "") { get_instance().log_file_path = log_file_path; } get_instance().save_to_file = true; } get_instance().console_output = console_output; get_instance().priority_level = priority_level; get_instance().initialized = true; } void Logger::log(LogLevel log_level,std::string message) { if (log_level >= get_instance().priority_level && get_instance().initialized) { logger_mutex.lock(); bool time_format_avail = false; typedef std::chrono::system_clock clock; auto now = clock::now(); auto seconds = std::chrono::time_point_cast<std::chrono::seconds>(now); auto fraction = now - seconds; std::time_t cnow = clock::to_time_t(now); auto milliseconds = std::chrono::duration_cast<std::chrono::milliseconds>(fraction); char time_str[100]; if (std::strftime(time_str, sizeof(time_str), "%H:%M:%S:", std::localtime(&cnow))) { time_format_avail = true; } if (get_instance().console_output) { if (time_format_avail) { std::cout << time_str << milliseconds.count() << " "; } std::cout << message << std::endl; }
{ "domain": "codereview.stackexchange", "id": 44304, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, c++11, logging", "url": null }
c++, c++11, logging if (get_instance().save_to_file) { std::ofstream file(log_file_path, std::ios_base::app); if (time_format_avail) { file << time_str << milliseconds.count() << " "; } file << message << std::endl; file.close(); } logger_mutex.unlock(); } } void Logger::Fatal(std::string message) { log(LogLevel::FATAL,"[FATAL]\t"+message); } void Logger::Error(std::string message) { log(LogLevel::ERROR,"[ERROR]\t"+message); } void Logger::Warn(std::string message) { log(LogLevel::WARN,"[WARN] \t"+message); } void Logger::Info(std::string message) { log(LogLevel::INFO,"[INFO] \t"+message); } void Logger::Debug(std::string message) { log(LogLevel::DEBUG,"[DEBUG]\t"+message); } #endif #endif Answer: Use enum class By default, C-like enum put their enumerators in the enclosing namespace. And that's not great at all. From C++11 on, you can use enum class instead, to scope those enumerators within the enum itself. And you can also take the opportunity to specify the storage type, so that instead of a 4 bytes int, you can specify std::uint8_t. Singleton, or not You are mixing static variables, a static instance returned by value, and by-instance static variable access... and that's not how a singleton is done. At all. You need to pick one of: Either static variables. Or instance variables with a global instance. Do beware that in either case you need to think about the static initialization (and destruction) order fiasco. I would advise going with a proper singleton as it avoids defining static variables separately. Avoid redundant parameters At the moment, you can have 4 distinct combinations of save_to_file and log_file_path in init: false and an empty path: OK true and a non-empty path: OK false and a non-empty path: What does that mean? true and an empty path: What does that mean?
{ "domain": "codereview.stackexchange", "id": 44304, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, c++11, logging", "url": null }
c++, c++11, logging You've created woes for yourself and your users by allowing nonsensical combinations to slip through. Instead, just take a log_file_path argument: If it's empty, don't log to file. If it's non-empty, log to the specified file. Use Guard Style Instead of opening an if block at the beginning of the function, indenting the entire content of it, and closing it at the end, it's better to inverse the boolean and exit early: if (<not activated>) { return; } // Do the logging
{ "domain": "codereview.stackexchange", "id": 44304, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, c++11, logging", "url": null }
c++, c++11, logging // Do the logging It avoids losing yourself in humpfteens levels of indentation, and makes it clear from the get go that nothing happens if not activated. Stop opening and closing that file every single damn time Opening and closing a file are NOT lightweight operations. Instead of using a std::string log_file_path data member, just use a std::ofstream log_file one: open it during init, and it'll close itself on destruction. As a bonus, you don't need a save_to_file boolean member either! If the ofstream is not open, << is a no-op, so no test needed. Time is always available You are using strftime with a fixed-width formatting pattern, hence you know in advance exactly how many characters it'll format -- and you could assert it for checking in debug that you're right. As a result, there's no need for the time_format_avail variable: it's always available. Avoid catenating strings Your logging code is inefficient -- taking a string parameter even when not logging -- but that's not a reason to add insult to injury and create another string on top. Your log method already receives the log-level, to test whether to log or not, override operator<< for LogLevel and be done with it. Allow deferred formatting after the check Sometimes, formatting the log string is expensive (and doubly so when allocating a string). In those cases, it's nice to have the ability to check whether the result will be used. The simple way is to offer a IsEnabled(LogLevel level) method. Starting from C++11, it's possible to leverage lambdas: template <typename T> static void LogLambda(LogLevel level, T&& lambda) { if (<not activated>) { return; } std::ostringstream stream; lambda(static_cast<std::ostream&>(stream)); log(level, stream.str()); }
{ "domain": "codereview.stackexchange", "id": 44304, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, c++11, logging", "url": null }
c++, c++11, logging log(level, stream.str()); } Not Thread-Safe, despite the mutex The most glaring issue is that your init function doesn't lock the mutex. So if one thread calls init while another is logging, who knows what happens... Another issue is that you read the is_initialized and priority_level variables prior to locking. It's a good idea to do so... but then they need to be atomic (and you can use relaxed loads). Locked too early Your mutex is locked too early. In general, it's best to try and minimize the amount of time for which a mutex is locked. This means calculating as much as possible beforehand, and only locking at the last moment. In your case, this means formatting the time first and only then locking before printing to console and file. Logging doesn't go to stdout By convention, stdout is for application output, which logging isn't. Instead, logging goes to stderr, which for this purpose is best accessed via the aptly named std::clog. Note: The main difference between std::cerr and std::clog is that std::clog is NOT tied to other streams and it's not automatically flushed on end-of-lines. Should you use std::endl? std::endl has 2 effects: It pushes a newline character. It flushes the stream. Flushing is not necessarily wrong for logging, but it's expensive so it bears thinking about it. My recommendation would be to flush based on the level: Fatal and Error flush, as they are important. Other levels don't, they'll appear soon enough. You could even make this parameterizable, so that for debugging a crashing application, one can activate flushing for all logs.
{ "domain": "codereview.stackexchange", "id": 44304, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, c++11, logging", "url": null }
performance, haskell, bioinformatics, genetic-algorithm Title: Slow Bioinformatics algorithm - Clump finding algorithm in Haskell Question: I'm working on the famous clump finding problem to learn Haskell. Part of the problem involve breaking nucleotide sequences, called kmers, into subsequences as follows: ACTGCA -> [ACT,CTG,GCA] This sliding window generates all possible kmers of length k, 3 in the above example. The problem is my very simple algorithm is too slow to work on the E. Coli genome. Other algorithms in slower languages can generate the kmer list in seconds. Here is what I wrote: kmerBreak k genome@(x : xs) | k <= length genome = take k genome : kmerBreak k xs | otherwise = [] I would love some feedback on how to improve the performance of this simple algorithm. As well as my use of Haskell in general. Answer: Simple mistake: a list does not contain its length, so length traverses the list to compute the length. This means that kmerBreak runs in time quadratic in the size of the input. A simple fix is to check instead that take k genome is indeed of length k, assuming that k is small. Or you can keep track of the length of genome as an extra parameter to the recursive function.
{ "domain": "codereview.stackexchange", "id": 44305, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "performance, haskell, bioinformatics, genetic-algorithm", "url": null }
c++, performance, template-meta-programming Title: Is there a more elegant solution to store and process different types using templates? Question: I'm trying to create some system for profiling and I need to track different data types (double, float int). I have a container that can hold some base type, and then perform actions on the concrete type by switching on the enum or something similar. I need to have a base type so the data can be copied/passed around if necessary. I wanted to stay with a templated approach since there are only a handful of types and all of the initial data and types are known at compile time, but open to others. This makes it easier at call-sites where users can pass in the concrete types to the container to add to the storage. container.Add(ConcreteType, value) I can't use the modern variations of variant/boost::any, and I'm using c++17. Here is a minimal example that compiles #include <cstdio> #include <stdint.h> enum DataType { DOUBLE, FLOAT, INT }; template <typename T> struct WrappedType { void Add(T value) { m_value += value; } T m_value{}; //... }; template <typename T> struct TypeStorage { WrappedType<T> m_wrapper; //... }; struct BaseTypeInfo { DataType m_type; uint32_t m_index; //... }; struct DoubleType : public BaseTypeInfo { using type = double; }; struct FloatType : public BaseTypeInfo { using type = float; }; struct IntType : public BaseTypeInfo { using type = int; }; struct Data { union { TypeStorage<double> m_double{}; TypeStorage<float> m_float; TypeStorage<int> m_int; }; const BaseTypeInfo* m_info; //contains DataType }; template <int SIZE> struct Container { void Add(const DoubleType& type, double value) { Data& data = m_data[type.m_index]; data.m_info = &type; data.m_double.m_wrapper.Add(value); }
{ "domain": "codereview.stackexchange", "id": 44306, "lm_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++, performance, template-meta-programming", "url": null }
c++, performance, template-meta-programming void Add(const FloatType &type, float value) { Data& data = m_data[type.m_index]; data.m_info = &type; data.m_float.m_wrapper.Add(value); } void Add(const IntType& type, int value) { Data& data = m_data[type.m_index]; data.m_info = &type; data.m_int.m_wrapper.Add(value); } template <typename T> void GetData(const Data& data, T&& callable) { switch (data.m_info->m_type) { case DOUBLE: callable(data.m_double.m_wrapper); break; case FLOAT: callable(data.m_float.m_wrapper); break; case INT: callable(data.m_int.m_wrapper); break; } } Data m_data[SIZE]; }; static BaseTypeInfo infos[32]; static uint32_t numInfos = 0; const DoubleType& AddDoubleType(const char* name) { uint32_t index = numInfos++; BaseTypeInfo& info = infos[index]; info.m_type = DOUBLE; info.m_index = index; //.. return static_cast<const DoubleType&>(info); } const FloatType& AddFloatType(const char* name) { uint32_t index = numInfos++; BaseTypeInfo& info = infos[index]; info.m_type = FLOAT; info.m_index = index; //.. return static_cast<const FloatType&>(info); } const IntType& AddIntType(const char* name) { uint32_t index = numInfos++; BaseTypeInfo& info = infos[index]; info.m_type = INT; info.m_index = index; //.. return static_cast<const IntType&>(info); } const DoubleType& doubleType = AddDoubleType(""); const FloatType& floatType = AddFloatType(""); const IntType& intType = AddIntType(""); struct PrintFunctor { PrintFunctor(const Data* data) : m_data(data) {} template <typename T> void operator()(const WrappedType<T>& wrappedType) { Print(wrappedType.m_value); }
{ "domain": "codereview.stackexchange", "id": 44306, "lm_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++, performance, template-meta-programming", "url": null }
c++, performance, template-meta-programming private: void Print(double value) { printf("DOUBLE: %f\n", value); } void Print(float value) { printf("FLOAT: %f\n", value); } void Print(int value) { printf("INT: %d\n", value); } const Data* m_data; }; int main() { static constexpr uint32_t CONTAINER_SIZE = 32; Container<CONTAINER_SIZE> container; container.Add(doubleType, 5.0); container.Add(floatType, 10.0f); container.Add(intType, 15); for (uint32_t i = 0; i < 3; ++i) { Data& data = container.m_data[i]; //could switch on type here, but want to hide it away as much as possible as there are a few places iterating the list //opt 1 lambda, but template arg lambdas are not in c++17, would have to pass a dummy argument to use decltype, to get the actual type in the wrapper? auto lambda = [](auto& wrapped_type) //type should be WrappedType<T>, need to obtain T to then pass to some print function? { // }; container.GetData(data, lambda); //opt 2 functor, user code still needs to do some switching on type, can get messy PrintFunctor func(&data); container.GetData(data, func); } } There are some comments in the main function, haven't managed to get the lambda working in c++17, and the functors are getting messy. Is there a nicer way to achieve this with my limitations? Answer: Implement your own variant type I can't use the modern variations of variant/boost::any, and I'm using c++17. Weird, since C++17 includes std::variant, but perhaps you are on some restricted system that doesn't have the full C++17 library support. Reinderien showed one possible approach that uses inheritance, but you said: Ideally looking for an approach without using dynamic dispatch
{ "domain": "codereview.stackexchange", "id": 44306, "lm_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++, performance, template-meta-programming", "url": null }
c++, performance, template-meta-programming Ideally looking for an approach without using dynamic dispatch Then std::variant really does look like the best solution for you, so if you cannot use the STL's implementation, I suggest you implement your own (as well as a corresponding std::visit()). Because that way, you can just write: using Data = my_variant<double, float, int>; int main() { std::array<Data, 3> container = {5.0, 10.0f, 15}; for (auto &d: container) { my_visit([](auto& d) { std::cout << typeid(d).name() << ": " << d << '\n'; }, d); } } There are plenty of examples on the Internet that describe how to create your own variant type.
{ "domain": "codereview.stackexchange", "id": 44306, "lm_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++, performance, template-meta-programming", "url": null }
c#, object-oriented, design-patterns, inheritance, serialization Title: Abstract base class for binary serialization Question: Ensuring that some logic is always being run before the user's overriding methods. I'm writing a library and I have some abstract classes that can be binary serialized (and users can subclass them and further implement their serialization logic) e.g. abstract class Base { protected int id; public virtual void Serialize(BinaryWriter writer) { writer.Write(id); } } class SomeonesClass : Base { public override void Serialize(BinaryWriter writer) { base.Serialize(writer); // ... } } Now, because writing the id is so important for all Base objects, I want to ensure (force) that writer.Write(id) gets called even in the subclasses written by users. So I don't even want to give them the option of calling base.Serialize(writer). One way that I've done it was to split it into two methods: abstract class Base { protected int id; public void Serialize(BinaryWriter writer) { writer.Write(id); InternalSerialize(writer); } protected virtual void InternalSerialize(BinaryWriter writer) { } } class SomeonesClass : Base { protected override void InternalSerialize(BinaryWriter writer) { } } The user could still avoid it by overriding Serialize using the new keyword etc, but at that point I'm fine to accept it. Is this the best approach to achieve my intended design? The design being: send a very strong message to the users of the library that the id must be the first thing to be written. Answer: Basically you have implemented the template method design pattern. In your case your Serialize method acts as the template method. It contains certain commands (before and/or after) the customisation points (usually referred as steps). So, the answer for your question is yes, you have implemented it in a correct way.
{ "domain": "codereview.stackexchange", "id": 44307, "lm_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#, object-oriented, design-patterns, inheritance, serialization", "url": null }
c#, object-oriented, design-patterns, inheritance, serialization Just a tiny note: It might make sense to declare your InternalSerialize as abstract rather than virtual. Also you could work on its naming to better express your intent.
{ "domain": "codereview.stackexchange", "id": 44307, "lm_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#, object-oriented, design-patterns, inheritance, serialization", "url": null }
c++, bitwise Title: Less redundant and clearer implementation of action triggers from two modules Question: (Before I even start: For reasons beyond my control, this code base is constrained to C++98 (so, no =delete, no auto etc., but that's also not the gist of this question). The code cannot use templates or the STL.) I inherited code that combines calls from two distinct modules which both have the ability to set and remove "triggers" for certain actions. An action should be started if the trigger is set by one module while it is not set by the other; and the action should be stopped when the trigger is removed by one module, again while it was not set by the other. A module can set or remove the same trigger multiple times in succession; setting or removing an already set/removed trigger by the same module is a NOP. Whether one of the other triggers is set is irrelevant. In other words, the action should be started if and only if a given module sets the given trigger first and be stopped if and only if the given module removes the given trigger last. The logic is contained in a class which keeps track of the triggers currently set for each module and exposes just two public functions: Set/unset a trigger for one of the two modules. The possible triggers are passed in as a bit in a bit field (implemented as an unsigned int) and stored in an unsigned int for each module. Only one trigger can be present in a call. The old implementation is unnecessarily complicated and redundant: Among other things, a third bitfield is stored that redundantly keeps track of the OR-ed state of each bit/trigger and must be updated along with the bitfield for each module. I found it hard to understand and verify in a review, wondered how a more concise and elegant solution might look, and gave it a try. The reasons I'm posting my attempt (together with the old code):
{ "domain": "codereview.stackexchange", "id": 44308, "lm_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++, bitwise", "url": null }
c++, bitwise Most importantly: Is the new code correct, that is: functionally equivalent? We perform module tests beyond the cursory test presented in Main.cpp below, which pass, but I'm still not sure. That I'm not sure about the correctness of the code makes me wonder how I could make it easier to understand. All functions are short now (so short that they can all be inline), I have tried to come up with better names, and still it is not perfectly trivial. I'm trying to be concise. An expression like (mTriggersByModule[module] &= ~trigger) != oldReason is pretty dense. It is using an assignment as an expression and is old-school C style; people familiar with bit manipulation will readily recognize the &= ~x pattern, others will not. Of course one could introduce temporary variables. Would a less dense style be better? Would you actually use C++ bit fields, making each flag a member? In all reality there is no need to use (explicit or implicit) bit fields internally, one could as well use a bunch of booleans (not a vector though, because of project constraints). My code design principles:
{ "domain": "codereview.stackexchange", "id": 44308, "lm_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++, bitwise", "url": null }
c++, bitwise My code design principles: Remove redundancy: Eliminate the "combined" bit field, eliminate parallel code (see next point). Compute rather than branch: I use the parameter specifying the module as an index into an array (mTriggersByModule[module] instead of using it to choose paths with different variables (if (isFromModule2) ...). The code is now branch-less. The former point also made the interface type safe: Because ActionTriggerT is actually an unsigned integer, StartAction(const ActionTriggerT trigger, const bool isFromModule2) could actually be called with the arguments swapped. This is not possible any longer now that the second parameter has been made an enum (there is a default conversion integer->bool but not integer->enum). Use better identifier names to make intent clearer (e.g. the old StopAction() does not actually stop anything but removes a trigger and returns whether it should be stopped, reflected by the new name RemoveTriggerAndCheckStop()). OK, let's see some code. There is a godbolt project with the files below to see it live. The bit flags and typedef for the trigger This is more elaborate in the real project and simply acts as a minimal stand-in here. #ifndef ACTIONTRIGGERS_H #define ACTIONTRIGGERS_H #include <cstdint> typedef uint32_t ActionTriggerT; // In reality, there are more of them where these come from. const ActionTriggerT NO_TRIGGER = 0; const ActionTriggerT TRIGGER1 = 1; const ActionTriggerT TRIGGER2 = 2; const ActionTriggerT TRIGGER3 = 4; #endif // ndef ACTIONTRIGGERS_H Old class definition #ifndef TWOSETSOFTRIGGERS_H #define TWOSETSOFTRIGGERS_H #include "ActionTriggers.h"
{ "domain": "codereview.stackexchange", "id": 44308, "lm_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++, bitwise", "url": null }
c++, bitwise #ifndef TWOSETSOFTRIGGERS_H #define TWOSETSOFTRIGGERS_H #include "ActionTriggers.h" /** * @brief This class coordinates action triggers from two modules. * StartAction() starts an action related to the trigger * if the trigger was not active from either module before, and StopAction() * stops it when the trigger was removed from one module and was not active from the other. * */ class TwoSetsOfTriggersT { public: /** * @brief Constructor. */ TwoSetsOfTriggersT(); /** * @brief Checks if the action has to be stopped after a module has * stopped the specific trigger. * * @param trigger the action trigger that was stopped by the module. * @param isFromModule2 @c true if module 2 did release the trigger, * @c false otherwise * * @return @c true if the trigger is set for the action by us, but should * now be stopped, @c false if either the trigger was not set * by us or it should not yet be stopped. */ bool StopAction(ActionTriggerT trigger, bool isFromModule2 = true); /** * @brief Checks if the action has to be started after a module has * started the trigger. * * @param trigger the trigger that was started by the module. * @param isFromModule2 @c true if a module 2 did apply the trigger, * @c false otherwise * * @return @c true if the trigger is not yet set for the action by us, but * should now be started, @c false if either the trigger is * already started by us or it should not be started. */ bool StartAction(ActionTriggerT trigger, bool isFromModule2 = true); private: /// Current triggers for module 1 ActionTriggerT mModuleTriggers; /// Current triggers for module 2 ActionTriggerT mModule2Triggers; /// Current triggers for all modules combined ActionTriggerT mCombinedTriggers; }; #endif // TWOSETSOFTRIGGERS_H Old class implementation #include "TwoSetsOfTriggersT.h"
{ "domain": "codereview.stackexchange", "id": 44308, "lm_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++, bitwise", "url": null }
c++, bitwise #endif // TWOSETSOFTRIGGERS_H Old class implementation #include "TwoSetsOfTriggersT.h" /*****************************************************************************/ TwoSetsOfTriggersT::TwoSetsOfTriggersT() : mModuleTriggers(NO_TRIGGER), mModule2Triggers(NO_TRIGGER), mCombinedTriggers(NO_TRIGGER) { } /*****************************************************************************/ bool TwoSetsOfTriggersT::StopAction(const uint32_t trigger, const bool isFromModule2) { // Was it a change bool isChanged = false; if (isFromModule2) { if (trigger == (mModule2Triggers & trigger)) { mModule2Triggers &= ~trigger; isChanged = true; } } else { if (trigger == (mModuleTriggers & trigger)) { mModuleTriggers &= ~trigger; isChanged = true; } } // Return value bool isToBe = false; if (isChanged) { if (trigger == (mCombinedTriggers & trigger)) { if ((0 == (mModuleTriggers & trigger)) && (0 == (mModule2Triggers & trigger))) { mCombinedTriggers &= ~trigger; isToBe = true; } } } return isToBe; } /*****************************************************************************/ bool TwoSetsOfTriggersT::StartAction(const ActionTriggerT trigger, const bool isFromModule2) { // Was it a change bool isChanged = false; if (isFromModule2) { if (0 == (mModule2Triggers & trigger)) { mModule2Triggers |= trigger; isChanged = true; } } else { if (0 == (mModuleTriggers & trigger)) { mModuleTriggers |= trigger; isChanged = true; } } // Return value bool isToBe = false; if (isChanged) { if (0 == (mCombinedTriggers & trigger)) { mCombinedTriggers |= trigger; isToBe = true; } } return isToBe; } New class definition, with inline functions #ifndef TWOSETSOFTRIGGERSNEW_H #define TWOSETSOFTRIGGERSNEW_H #include "ActionTriggers.h"
{ "domain": "codereview.stackexchange", "id": 44308, "lm_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++, bitwise", "url": null }
c++, bitwise #include "ActionTriggers.h" /** * This class coordinates triggers which can be set by two modules to start and stop actions. * Both modules can set and remove the same set of triggers. * An action is started/stopped when a trigger is actually set/removed from one module * while it was not present from the other. */ class TwoSetsOfTriggersNewT { public: /** * @brief The enum values are used as type-safe parameters in the public API, * and as an index into the trigger bit field array. */ enum Module_E { MODULE_1, MODULE_2 }; /** * @brief Start with no trigger active. */ TwoSetsOfTriggersNewT() // cannot initialize array in C++98 or C++03 { mTriggersByModule[MODULE_1] = mTriggersByModule[MODULE_2] = NO_TRIGGER; } /** * @brief Checks if the action should be stopped * after a module has removed the given trigger. * * @param trigger the action trigger that is removed by the module. * @param module MODULE_1 or MODULE_2, indicating the module removing the trigger. * * @return @c true if the trigger from the given module was * active before and is now removed, and if that trigger is not active for the * other module. */ bool RemoveTriggerAndCheckStop(ActionTriggerT trigger, Module_E module = MODULE_2) { return TryDelete(trigger, module) && !TriggerIsActive(trigger, OtherModule(module)); } /** * @brief Checks if the action has to be started after a module has * activated the given trigger. * * @param trigger the trigger that was activated by the module. * @param module MODULE_1 or MODULE_2, indicating the calling module. * * @return @c true if the trigger was not yet set from either module * and the action should be started */ bool AddTriggerAndCheckStart(ActionTriggerT trigger, Module_E module = MODULE_2) { return TryAdd(trigger, module) && !TriggerIsActive(trigger, OtherModule(module)); }
{ "domain": "codereview.stackexchange", "id": 44308, "lm_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++, bitwise", "url": null }
c++, bitwise private: /** * @brief Return the "other" module. * @param module the module for which we want to obtain the other module. * @return MODULE_1 if the argument was MODULE_2 and vice versa. */ static Module_E OtherModule(Module_E module) { // This is much faster than a ternary conditional which may need a jump. return static_cast<Module_E>(!module); } /** * @brief Delete, if necessary, the given trigger for the given module * and return whether it was set before * @param trigger One of the triggers (a bit in a 32 bit field) * @param module MODULE_1 or MODULE_2, indicating the calling module. * @return Whether the given trigger was set before for the given module */ bool TryDelete(ActionTriggerT trigger, Module_E module) { ActionTriggerT oldReason = mTriggersByModule[module]; return (mTriggersByModule[module] &= ~trigger) != oldReason; } /** * @brief Set the given trigger for the given module and return whether it * was unset before * @param trigger One of the triggers (a bit in a 32 bit field) * @param module MODULE_1 or MODULE_2, indicating the calling module * @return Whether the given trigger was unset before for the given module */ bool TryAdd(ActionTriggerT trigger, Module_E module) { ActionTriggerT oldReason = mTriggersByModule[module]; return (mTriggersByModule[module] |= trigger) != oldReason; } /** * @brief Check whether the given trigger is active for the given module * but do not change it. * @param trigger One of the triggers (a bit in a 32 bit field) * @param module MODULE_1 or MODULE_2, indicating the calling module * @return whether the given trigger is active for the given module */ bool TriggerIsActive(ActionTriggerT trigger, Module_E module) const { return mTriggersByModule[module] & trigger; }
{ "domain": "codereview.stackexchange", "id": 44308, "lm_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++, bitwise", "url": null }
c++, bitwise /// Current triggers for module 1 and module 2 as a bit field. /// Reasons from module 1 are are in mTriggersByModule[MODULE_1], for module 2 in mTriggersByModule[MODULE_2] ActionTriggerT mTriggersByModule[2]; }; #endif // ndef TWOSETSOFTRIGGERSNEW_H Main.cpp, a cursory test #include "TwoSetsOfTriggersT.h" #include "TwoSetsOfTriggersNewT.h" #include <assert.h> int main() { { TwoSetsOfTriggersT tsot; assert(tsot.StartAction(TRIGGER1)); assert(!tsot.StartAction(TRIGGER1)); // already started assert(!tsot.StartAction(TRIGGER1, false)); // already started by other source assert(tsot.StartAction(TRIGGER2, false)); assert(!tsot.StartAction(TRIGGER2)); assert(!tsot.StartAction(TRIGGER2)); assert(!tsot.StopAction(TRIGGER3)); // was not started, cannot be stopped assert(!tsot.StopAction(TRIGGER1)); // still started by other source assert(tsot.StopAction(TRIGGER1, false)); // now yes assert(!tsot.StopAction(TRIGGER2, false)); // still started by other source assert(tsot.StopAction(TRIGGER2)); // now yes } { TwoSetsOfTriggersNewT tsot; assert(tsot.AddTriggerAndCheckStart(TRIGGER1)); assert(!tsot.AddTriggerAndCheckStart(TRIGGER1)); // already started assert(!tsot.AddTriggerAndCheckStart(TRIGGER1, TwoSetsOfTriggersNewT::MODULE_1)); // already started by other source assert(tsot.AddTriggerAndCheckStart(TRIGGER2, TwoSetsOfTriggersNewT::MODULE_1)); assert(!tsot.AddTriggerAndCheckStart(TRIGGER2)); assert(!tsot.AddTriggerAndCheckStart(TRIGGER2)); assert(!tsot.RemoveTriggerAndCheckStop(TRIGGER3)); // was not started, cannot be stopped assert(!tsot.RemoveTriggerAndCheckStop(TRIGGER1)); // still started by other source assert(tsot.RemoveTriggerAndCheckStop(TRIGGER1, TwoSetsOfTriggersNewT::MODULE_1)); // now yes
{ "domain": "codereview.stackexchange", "id": 44308, "lm_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++, bitwise", "url": null }
c++, bitwise assert(!tsot.RemoveTriggerAndCheckStop(TRIGGER2, TwoSetsOfTriggersNewT::MODULE_1)); // still started by other source assert(tsot.RemoveTriggerAndCheckStop(TRIGGER2)); // now yes } } Answer: About the constraints For reasons beyond my control, this code base is constrained to C++98 (so, no =delete, no auto etc., but that's also not the gist of this question. The code cannot use templates or the STL. I'll address this anyway: alarm bells should be ringing if you are constrained to use a 25 year old version of C++, and not even the full version at that. Are you compiling for some rare embedded CPU for which no compilers were written that support later versions? Make constants static In ActionTriggers.h, the constants should probably be made static. This will allow the compiler to optimize the storage away, and also prevents compilation failures if that header file gets included in multiple source files that are linked into the same executable. Avoiding branches Since you want to avoid branches, consider that && has short-cut semantics and thus also might cause a conditional jump. You can even avoid that: bool AddTriggerAndCheckStart(ActionTriggerT trigger, Module_E module = MODULE_2) { bool shouldStart = !((mTriggersByModule[0] | mTriggersByModule[1]) & trigger); mTriggersByModule[module] |= trigger; return shouldStart; } bool RemoveTriggerAndCheckStop(ActionTriggerT trigger, Module_E module = MODULE_2) { bool shouldStop = mTriggersByModule[module] & ~mTriggersByModule[OtherModule(module)] & trigger; mTriggersByModule[module] &= ~trigger; return shouldStop; } What if trigger is not a power of two? If you pass in a value for trigger that is a combination of two or more TRIGGER* constants, then these functions will do something unexpected. You might want to add assert()s to catch that. Answers to your questions
{ "domain": "codereview.stackexchange", "id": 44308, "lm_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++, bitwise", "url": null }
c++, bitwise Most importantly: Is the new code correct, that is: functionally equivalent? We perform module tests beyond the cursory test presented in Main.cpp below, which pass, but I'm still not sure. I think it is. But if this is running on a billion dollar space probe, pacemaker or on a nuclear reactor, don't take my word for it. Would you actually use C++ bit fields, making each flag a member? In all reality there is no need to use (explicit or implicit) bit fields internally, one could as well use a bunch of booleans (not a vector though, because of project constraints). I actually thought that bit fields would be a good idea at first, but that isn't a great match for your use case. An array of booleans might be possible, and then pass an index into that array to RemoveTriggerAndCheckStop() and AddTriggerAndCheckStart(). It will use more storage though. An expression like (mTriggersByModule[module] &= ~trigger) != oldReason is pretty dense. It is using an assignment as an expression and is old-school C style; people familiar with bit manipulation will readily recognize the &= ~x pattern, others will not. Of course one could introduce temporary variables. Would a less dense style be better? I don't think it is that dense, and if people don't know bit manipulation, maybe they shouldn't be touching the code? At some point you should be able to rely on knowledge of the language. Also, your code has much fewer lines, so that makes it less complex than the original. That said, using an array of bools would probably be even easier to understand. Swap the array and the bitmask Instead of using two array of bools, one for each module, you could consider making a bitmask for the modules, and having one array of those bitmasks: enum ActionTrigger_E { TRIGGER1; // = 0 TRIGGER2; TRIGGER3; };
{ "domain": "codereview.stackexchange", "id": 44308, "lm_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++, bitwise", "url": null }
c++, bitwise static const std::size_t NUM_TRIGGERS = 3; … class TwoSetsOfTriggersT { enum Module_E { MODULE_1 = 1; // 1 << 0 MODULE_2 = 2; }; … std::uint8_t mModulesByTrigger[NUM_TRIGGERS]; }; This way, you can write: bool AddTriggerAndCheckStart(ActionTrigger_E trigger, Module_E module = MODULE_2) { bool shouldStart = !mModulesByTrigger[trigger]; mModulesByTrigger[trigger] |= module; return shouldStart; } bool RemoveTriggerAndCheckStop(ActionTrigger_E trigger, Module_E module = MODULE_2) { bool shouldStop = mModulesByTrigger[trigger] == module; mModulesByTrigger[trigger] &= ~module; return shouldStop; }
{ "domain": "codereview.stackexchange", "id": 44308, "lm_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++, bitwise", "url": null }
performance, algorithm, parsing, regex, go Title: Parsing shortcodes out of a string Question: I wrote this shortcode parsing and it runs in \$O(N^2)\$. Is there a way to better optimize this? package shortcodes import ( "regexp" "strings" ) var ( shortcodesRegex = regexp.MustCompile(`\[\S+(?:\s+[^="]+(|="[^"\]\s]+"))+\]`) ) func Parse(content string) []map[string]string { results := make([]map[string]string, 0) indexes := shortcodesRegex.FindAllIndex([]byte(content), -1) for _, matches := range indexes { result := make(map[string]string) shortcode := string(content[matches[0]+1 : matches[1]-1]) parts := strings.Fields(shortcode) for i, part := range parts { if i == 0 { result["id"] = part continue } pair := strings.Split(part, "=") if len(pair) > 1 { result[pair[0]] = pair[1][1 : len(pair[1])-1] } else { result[pair[0]] = "" } } results = append(results, result) } return results }
{ "domain": "codereview.stackexchange", "id": 44309, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "performance, algorithm, parsing, regex, go", "url": null }
performance, algorithm, parsing, regex, go results = append(results, result) } return results } Here is one of the test cases I have written. { name: "basic", args: args{`First shortcode is [fraction num="1" denom="2"] and the second is [square-root content="456"] which we will pass into a function which will return these IDs and all their values in a map`}, want: []map[string]string{ { "id": "fraction", "num": "1", "denom": "2", }, { "id": "square-root", "content": "456", }, }, }, Answer: Thank you for the unit tests! They were invaluable; they really helped me to understand the problem you're tackling. I am reading this \[\S+(?:\s+[^="]+(|="[^"\]\s]+"))+\] and I am not pleased with it, for several reasons. There should be a comment illustrating the kind of text we seek to match. (The SMS reference was not helpful.) The matching task seems fairly simple, yet this expression is relatively opaque. I do not find that it is a good means of communicating a technical idea to collaborators. The ?: non-capturing group seems odd, and risks triggering excessive backtracking in the regex engine, which may be where your quadratic running time comes from. Further down in the code we find that the string is parsed using regex using blank-delimited Fields using =-delimited Split
{ "domain": "codereview.stackexchange", "id": 44309, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "performance, algorithm, parsing, regex, go", "url": null }
performance, algorithm, parsing, regex, go using regex using blank-delimited Fields using =-delimited Split Surely a single regex with capturing groups could have picked out what we needed in one fell swoop? If there is a specification for a valid Shortcode, please cite its URL. As written, this code is willing to accept e.g. a great deal of $%^&* punctuation, which I suspect is not part of the intended business use case. Consider using a regex that looks more like this: ^\[([\w-]+)(\s+\w+="\d+")+\]$ Or perhaps with fine-grained capturing groups: \[([\w-]+)(\s+(\w+)="(\d+)")+\] If e.g. [a b-c="7"] is valid input, then turn \w+ into [\w-]+. The Fields and Split logic is vanilla enough, with +/- 1 index offsets to strip punctuation. The logic is tightly bound to the regex, which validates that proper punctuation was found. I would be happier to see some of that logic pushed down into the regex, to keep it all in one place and make it more likely that maintainers will properly coordinate changes. Using fine-grained capturing groups seems a natural way to accomplish that. Since "excessive running time" has been a challenge that this code has faced in the past, please add a unit test to address that and verify no regressions. Please add code that offers "very long" input strings to be parsed, and that notes elapsed wallclock time.
{ "domain": "codereview.stackexchange", "id": 44309, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "performance, algorithm, parsing, regex, go", "url": null }
python, performance, python-3.x, pandas, vectorization Title: How to make my groupby and transpose operations efficient? Question: I have a DataFrame of size 3,745,802 rows and 30 columns. I would like to perform certain groupby and transpose operations which will finally end up with more (unimaginable) columns/features. I also tried parallel processing,Dask,Modin and the pandarallel package, but couldn't do this because all these packages don't support unstack operation yet. The sample dataframe is the same as my real dataframe but the record count is small (as I cannot share the real data). Please find the sample dataframe (subset of real dataframe) df = pd.DataFrame({ 'subject_id':[1,1,1,1,2,2,2,2,3,3,4,4,4,4,4], 'readings' : ['READ_1','READ_2','READ_1','READ_3','READ_1','READ_5','READ_6','READ_8','READ_10','READ_12','READ_11','READ_14','READ_09','READ_08','READ_07'], 'val' :[5,6,7,11,5,7,16,12,13,56,32,13,45,43,46], }) N=2 # dividing into two dataframes for parallel processing. dfs = [x for _,x in df.groupby(pd.factorize(df['subject_id'])[0] // N)] Please find dummy huge dataframe for testing (only the column names match but the data inside is random) df_size = int(3e7) N = 30000000 s_arr = pd.util.testing.rands_array(10, N) df = pd.DataFrame(dict(subject_id=np.random.randint(1, 1000, df_size), readings = s_arr, val=np.random.rand(df_size) )) Code (with the help of SO users) import multiprocessing as mp def transpose_ope(df): #this function does the transformation like I want df_op = (df.groupby(['subject_id','readings'])['val'] .describe() .unstack() .swaplevel(0,1,axis=1) .reindex(df['readings'].unique(), axis=1, level=0)) df_op.columns = df_op.columns.map('_'.join) df_op = df_op.reset_index() return df_op def main(): with mp.Pool(mp.cpu_count()) as pool: res = pool.map(transpose_ope, [df for df in dfs]) if __name__=='__main__': main()
{ "domain": "codereview.stackexchange", "id": 44310, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, performance, python-3.x, pandas, vectorization", "url": null }
python, performance, python-3.x, pandas, vectorization if __name__=='__main__': main() What transpose_ope does? It works like this. A subject can have n number of readings. Instead of having his n readings as row, I would like to create the summary statistics of each unique reading as a column. So, subject_id = 1 has 4 readings in total (but 3 unique readings). So, instead of having 4 rows for 1 subject, I would like create features/columns for the readings. But again, instead of readings, I would like to have summary statistics of the readings (MIN,MAX,STDDEV,COUNT,MEAN) etc. So each reading will have 5 columns. So subject_id = 1 will have 15 column in total Though this code works fine on the sample dataframe, in real life my data has more than four million rows and 30 columns. Moreover, when I apply the transformation of my interest as shown in the code, the column count can go up to 955,500. I'm basically trying to reduce the row count (but increasing the column count). Can you help? Answer: A few months after this question was posted, Modin added support for .unstack(). So that's the simplest technical approach to solving this. https://modin.readthedocs.io/en/stable/supported_apis/series_supported.html
{ "domain": "codereview.stackexchange", "id": 44310, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, performance, python-3.x, pandas, vectorization", "url": null }
c++, performance, graphics, opengl Title: OpenGL: Rendering the same sprite several times Question: I've been trying to make refactor really simple 2d sprite engine in OpenGL. As a start, I'm trying to use instanced rendering to render several copies of the same sprite in a square formation across my screen. The code works fine but it is quite slow; I am getting about 20 frames a second when rendering 25600 copies. Really would apppreciate any insight into how to improve it. main.cpp: int instances = 25600; float* data = new float[instances*sprite.getFloats()]; //sprite.getFloats just returns how much data each sprite pushes to the pipeline while (!quit) { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); for (int i = 0; i < instances; ++i) { sprite.loadData(data,SpriteParameter(glm::vec4(i%(screenWidth/dimen)*dimen,i/(screenWidth/dimen)*dimen,dimen,dimen)),i*sprite.getFloats()); //this part fills an array of floats with transfomration data } sprite.draw(RenderProgram::basicProgram,data,instances); //now we actually draw the sprites in one go SDL_GL_SwapWindow(window); } The main drawing loop is pretty simple. I'm not sure there's much room for optimization here. render.h: struct SpriteParameter //stores a bunch of information regarding how to render the sprite { glm::vec4 rect = {0,0,0,0}; float radians = 0; RenderEffect effect = NONE; //effects to do. (mirror, flip, etc) glm::vec4 tint = {1,1,1,1}; float z = 0; glm::vec4 portion = {0,0,1,1}; };
{ "domain": "codereview.stackexchange", "id": 44311, "lm_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++, performance, graphics, opengl", "url": null }
c++, performance, graphics, opengl SpriteParameter is a class that represents a bunch of effects I can use to change how my sprite is rendered, like what angle to rotate it at, what tint I should give it, as well as the position and dimensions it should be rendered at (rect). The "rect" field is the only one that's really of relevance in my code right now. I'm not really sure how else to pass in a bunch of rendering instructions to a function, so I've been using SpriteParameter for years now. Open to new suggestions render.cpp: void Sprite::loadData(GLfloat* data, const SpriteParameter& parameter, int index) //given a sprite parameter, write it's data into an array { if (data!= nullptr) { glm::mat4 matt = glm::mat4(1.0f); //matt represents the transformation matrix matt = glm::translate(matt,{parameter.rect.x + (parameter.rect.z)/2,parameter.rect.y + (parameter.rect.a)/2,0}); matt = glm::rotate(matt, parameter.radians, glm::vec3(0,0,1)); matt = glm::scale(matt, {parameter.rect.z/2, parameter.rect.a/2,1}); for (int j = 0; j < 16; j++) { data[j+index] = matt[j/4][j%4]; //copy matrix } data[index + 16]= parameter.effect; //load the rest of the data into our array data[index + 16 + 1] = parameter.tint.x; data[index + 16 + 2] = parameter.tint.y; data[index + 16 + 3] = parameter.tint.z; data[index + 16 + 4] = parameter.tint.a; data[index + 20 + 1] = parameter.z; data[index + 20 + 2] = parameter.portion.x; data[index + 20 + 3] = parameter.portion.y; data[index + 20 + 4] = parameter.portion.z; data[index + 20 + 5] = parameter.portion.a;
{ "domain": "codereview.stackexchange", "id": 44311, "lm_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++, performance, graphics, opengl", "url": null }
c++, performance, graphics, opengl } else { throw new std::invalid_argument("null buffer"); } } void Sprite::draw(RenderProgram& program, GLfloat* data, int instances) //once we've written the data with Sprite::loadData, we draw it with Sprite::draw { glBindVertexArray(VAO); glBindTexture(GL_TEXTURE_2D,texture); glBindBuffer(GL_ARRAY_BUFFER,modVBO); GLsizei vec4Size = 4*floatSize; int stride = floatSize*floats; glBufferData(GL_ARRAY_BUFFER,stride*instances,data,GL_DYNAMIC_DRAW); glVertexAttribPointer(3, 4, GL_FLOAT, GL_FALSE, stride, (void*)0); //3-6 inclusive are the transformation matrix glVertexAttribPointer(4, 4, GL_FLOAT, GL_FALSE, stride, (void*)(vec4Size)); glVertexAttribPointer(5, 4, GL_FLOAT, GL_FALSE, stride, (void*)(2 * vec4Size)); glVertexAttribPointer(6, 4, GL_FLOAT, GL_FALSE, stride, (void*)(3 * vec4Size)); glVertexAttribPointer(7, 1, GL_FLOAT, GL_FALSE, stride, (void*)(4*vec4Size)); //effect glVertexAttribPointer(8, 4, GL_FLOAT, GL_FALSE, stride, (void*)(4*vec4Size + floatSize)); //color glVertexAttribPointer(9, 1,GL_FLOAT, GL_FALSE, stride, (void*)((floats-5)*floatSize)); //z glVertexAttribPointer(10, 4, GL_FLOAT, GL_FALSE, stride, (void*)((floats-4)*floatSize)); //portion glEnableVertexAttribArray(3); glEnableVertexAttribArray(4); glEnableVertexAttribArray(5); glEnableVertexAttribArray(6); glEnableVertexAttribArray(7); glEnableVertexAttribArray(8); glEnableVertexAttribArray(9); glEnableVertexAttribArray(10); glVertexAttribDivisor(3, 1); glVertexAttribDivisor(4, 1); glVertexAttribDivisor(5, 1); glVertexAttribDivisor(6, 1); glVertexAttribDivisor(7, 1); glVertexAttribDivisor(8, 1); glVertexAttribDivisor(9, 1); glVertexAttribDivisor(10, 1); glUseProgram(basicProgram); glDrawElementsInstanced(GL_TRIANGLES,6,GL_UNSIGNED_INT,indices,instances); glBindVertexArray(0); glBindBuffer(GL_ARRAY_BUFFER,0); }
{ "domain": "codereview.stackexchange", "id": 44311, "lm_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++, performance, graphics, opengl", "url": null }
c++, performance, graphics, opengl Sprite class loads data into an array and then ships it off to the rendering pipeline. That's pretty much it. From my tests, the main bottleneck is with Sprite::loadData, but I'm not really sure how to make that any faster since all it's doing is writing data to an array. Any help would be very appreciated! Answer: Expected performance The code works fine but it is quite slow; I am getting about 20 frames a second when rendering 25600 copies. Really would apppreciate any insight into how to improve it. 20 fps is of course low, you want 60 fps or more to get fluid motion on screen. But it's instructive to ask yourself: what performance did you expect? That's not the same as the performance you want. If you have 25600 objects and 20 fps, then that's 512000 objects per second to handle. Assuming roughly an 1 GHz CPU (it's probably the right order of magnitude), you have \$10^9 / 25600 / 20 \approx 2000\$ cycles per object to do whatever needs to be done. 2000 cycles seems like a lot, but let's look at what you are doing per object: You create a SpriteParameter, and initialize it with a glm::vec4 that has 4 division operations in it. Divisions are slow; even if the throughput of 32-bit integer divisions on the latest CPUs is now just a handful of cycles, it still has tens of cycles of latency. In loadData() you do 3 operations on a 4 by 4 matrix. That's actually a lot of floating point operations, especially because of glm::rotate(), which uses trigonometric functions behind the scenes. These operations together easily use hundreds of cycles. A lot of data is being generated: at least 26 floats, or 104 bytes. Remember, this needs to multiplied by 512000 to get the bandwidth per second: about 507 MB/s. And then it has to be read by the GPU as well, so you have to double that number to 1014 MB/s.
{ "domain": "codereview.stackexchange", "id": 44311, "lm_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++, performance, graphics, opengl", "url": null }
c++, performance, graphics, opengl Did you compile your code with optimizations enabled? If not, then that would explain a lot. If you are running on an older CPU or on a laptop or mobile phone, then even with compiler optimizations this might explain the framerate you see. Move more work into the vertex shader You are doing a lot of work on the CPU that could be done by the GPU. If you know you are CPU-bound, then that is what I would try to do first. Consider that the GPU can do all these matrix transformations for you. Also, when doing instanced rendering, you can use gl_InstanceID in the vertex shader to know which instance you are rending. Thus, it can even calculate the rect. If you have certain effects, like tint varying gradually based on position and time, you can also let the vertex shader calculate that based on gl_InstanceID, and pass the time as a uniform to the shader. Ideally, you don't have data[]; you just pass the minimum amount of uniforms to the shader to have it calculate everything you want, so the amount of calculations necessary and the amount of bandwidth needed is minimal. If you still need per-instance data that cannot be calculated per-frame on the GPU, then at least try to minimize the amount of data that the CPU has to generate and pass to the shader. What if you are GPU-bound? The above assumes the bottleneck is the CPU. It could also be that it is the GPU that is the bottleneck. How big are the sprites? How many fragments does it need to render per second? How complex is the fragment shader? You could do some rough estimations again to see if your GPU can actually handle the load. Use a profiling tool I recommend that you use a profiling tool to figure out exactly where the bottlenecks are in your code. Linux perf is a good way to do this, assuming you are running on Linux of course. If the bottleneck is the GPU, then you might have to look for profiling tools from your GPU's vendor.
{ "domain": "codereview.stackexchange", "id": 44311, "lm_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++, performance, graphics, opengl", "url": null }
javascript, unit-testing, ecmascript-6 Title: Test the log in functionality of a web page with incorrect credentials Question: I'm new to playwright, so I'm unsure if this is the correct or best way to go about testing. I basically want multiple tests on the same webpage. I've been able to successfully accomplish this using test.beforeAll: test.describe("sign in with an invalid email/password combination", () => { let page; test.beforeAll(async ({ browser }) => { const context = await browser.newContext(); page = await context.newPage(); await page.goto("https://www.example.com"); await page.getByRole('link', { name: 'Sign In' }).click(); const username = "user@gmail.com"; const password = "verysecure"; const userField = page.getByLabel("Email or phone number"); const passwordField = page.getByLabel("Password"); await userField.fill(username); await passwordField.fill(password); await page.getByRole('button', { name: 'Sign in' }).click(); }); test("one", async () => { await expect(page).toHaveTitle("Title"); }); test("two", async () => { await expect(page.locator('[data-uia="text"]')).toHaveText( "Incorrect password. Please try again or you can reset your password." ); }) }) Reading through the docs it states: Redoing login for every test can slow down test execution. To mitigate that, reuse existing authentication state instead. And I found this stack overflow post on how to share the same page across multiple tests. My confusion is whether or not my code is opening new pages and attempting to sign in for each test. Also, if I should be using storageState, or if beforeEach is appropriate in this situation? I only plan on testing pieces of the webpage, not actually ever logging in.
{ "domain": "codereview.stackexchange", "id": 44312, "lm_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, unit-testing, ecmascript-6", "url": null }
javascript, unit-testing, ecmascript-6 Answer: To figure out whether your code is being run twice, you should be able to put a console.log in and see what's going on. Because of the complexity of the setup (that you are seeing), in-browser tests require a different approach than unit tests. Whereas in unit tests you want to isolate logic, in these tests you will likely go through a whole flow for a user, and include multiple assertions throughout. I have read the advice about using existing authentication state that you are quoting, and it seems like you're asking the right question. You can create a global setup (which I have done), and run your tests in sequence. I tend to not do this, though, as it couples the tests together, and if something goes wrong in one test, it can affect another. For me, a very important principal in test maintenance is test isolation. If the tests are linked like that, I ask, why not make just one longer test? It will be clearer to future readers what is happening. So I tend to write longer tests that are isolated from each other. Playwright will nicely parallelize these and save time. I would recommend avoiding the advice you are quoting until speed is a real issue for your test suite. This happens periodically with a large, slow test suite, at which point sharing auth may (or may not) be the right choice. Thanks for sharing! I'm not sure why the downvotes are there.
{ "domain": "codereview.stackexchange", "id": 44312, "lm_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, unit-testing, ecmascript-6", "url": null }
javascript, node.js, error-handling, repository Title: Command handlers in node.js Question: Description This javascript code uses tmi.js to listen for chat messages in a Twitch chat and perform certain actions depending on their content. In the sample code provided, if the message starts with !add, !taskadd, !addtask or !taska it will call the addTask command handler which tries to add the task to a list of tasks. If the user who typed the message has a task already, it will not allow that and if the task is empty it will respond with an informative message. const options = { options: { debug: true }, connection: { reconnect: true, secure: true }, identity: { username: TWITCH_BOT_USERNAME, password: TWITCH_BOT_PASSWORD }, channels: [TWITCH_CHANNEL] }; const client = new Client(options); client.connect().catch(console.error); const extractCommandAndMessage = (message) => { const index = message.trim().indexOf(' '); if (index === -1) { return { command: message, message: '' }; } return { command: message.trim().substring(0, index), message: message.substring(index + 1) }; }; const addTaskCommands = ['!add', '!taskadd', '!addtask', '!taska']; const twitchMessageHandler = async (channel, user, message, self) => { if (self) return; const { command, message: text } = extractCommandAndMessage(message); if (!command) return; const lowerCaseCommand = command.toLowerCase(); const username = user['display-name']; // Tasks if (addTaskCommands.includes(lowerCaseCommand)) { addTask(channel, text, username, client); } if (editTaskCommands.includes(lowerCaseCommand)) { editTask(channel, username, client, text); } if (completeTaskCommands.includes(lowerCaseCommand)) { completeTask(channel, username, client); } } const tasks = {}; const addTask = (channel, task, username, client) => { if (!task) { client.say(channel, 'Try adding a task after the command.'); return; }
{ "domain": "codereview.stackexchange", "id": 44313, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript, node.js, error-handling, repository", "url": null }
javascript, node.js, error-handling, repository if (username in tasks) { client.say(channel, 'You need to !complete or !edit your current task.'); return; } client.say(channel, `@${username}, adding "${task}" to the list...`); tasks[username] = task; }; const editTask = (channel, username, client, task) => { if (!(username in tasks)) { client.say(channel, 'You need to add a task in order to edit it.'); return; } if (!task) { client.say(channel, 'You need to include a description of your new task'); return; } client.say(channel, `Okay ${username}, your task now says "${task}"`); tasks[username] = task; }; const completeTask = (channel, username, client) => { if (!(username in tasks)) { client.say(channel, 'You need to add a task first.'); return; } delete tasks[username]; taskCounter++; if (!(username in individualcounters)) { individualcounters[username] = 1; } else { individualcounters[username] += 1; } const userTaskCount = individualcounters[username]; client.say( channel, `BOOM ${username}! You completed your task! You have kicked ${userTaskCount} goal${ userTaskCount === 1 ? '' : 's' } this stream!` ); individualcounters[username] = userTaskCount; }; client.on('message', twitchMessageHandler); Specific issues Message handler vs command handler responsibility The addTask command handler is responsible for adding the task and responding with the client, when in reality its core and only function should be adding tasks as its name suggests. Is it a good idea to instead throw exceptions or return a Result object from the addTask function and handle them in the higher level message handler? Something more like; const twitchMessageHandler = async (channel, user, message, self) => { ... if (addTaskCommands.includes(lowerCaseCommand)) { if (!text) { client.say(channel, 'Try adding a task after the command.'); }
{ "domain": "codereview.stackexchange", "id": 44313, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript, node.js, error-handling, repository", "url": null }
javascript, node.js, error-handling, repository try { addTask(channel, text, username, client); client.say(channel, `@${username}, adding "${text}" to the list...`); } catch (ex) { if (ex.name === 'UsernameAlreadyHasTask') { client.say( channel, 'You need to !complete or !edit your current task.' ); } console.log(ex) } } ... } const addTask = (task, username) => { if (!task) { throw NoTaskProvided(); } if (username in tasks) { throw UsernameAlreadyHasTask(); } tasks[username] = task; }; Perhaps theres a better way to separate the concerns from here? Persistence It's pretty obvious that the persistence method for tasks is a simple in memory JS object. Would it make sense to introduce a repository to handle task persistence something like; // repository/task.js const saveTask = (user, task) => { // DB implementation or the in memory option } Conclusion Besides those two specific questions, any other general improvements and tips would be greatly appreciated. I don't like how the twitchMessageHandler function works, but it was the simplest method to implement. I am fairly new to javascript and the learning I have been doing have been towards a functional-like method which is very new to me so there are some learning difficulties. Answer: General comments Your code is clean and you use up-to-date JavaScript: async const/let, no var object deconstruction Naming is decent and you don't have any unnecessary comments in the code. One thing that caught my eye is the "if ladder" to check which command was issued. This: if (addTaskCommands.includes(lowerCaseCommand)) { addTask(channel, text, username, client); } if (editTaskCommands.includes(lowerCaseCommand)) { editTask(channel, username, client, text); } if (completeTaskCommands.includes(lowerCaseCommand)) { completeTask(channel, username, client); }
{ "domain": "codereview.stackexchange", "id": 44313, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript, node.js, error-handling, repository", "url": null }
javascript, node.js, error-handling, repository if (completeTaskCommands.includes(lowerCaseCommand)) { completeTask(channel, username, client); } Even if the first one, adding a task, matches, it still checks the two other ones. You could use an else if instead. This is not a big thing, but it stood out enough to comment on. Alternatively, you could build a map from keyword to command handler, look up the correct handler and invoke it. Something like this: const addTask = (user, task) => { // implementation here }; const editTask = (user, task) => { // implementation here }; const completeTask = (user, task) => { // implementation here }; // map command keywords to handler functions above. const commandMap = { "!add": addTask, "!taskadd": addTask, "!addtask": addTask, "!taska": addTask, "!edit": editTask, "!taskedit": editTask, "!edittask": editTask, "!taske": editTask, "!complete": completeTask, "!taskcomplete": completeTask, "!completetask": completeTask, "!taskc": completeTask }; const keywords = Object.keys(commandMap); const twitchMessageHandler = async (channel, user, message, self) => { if (self) return; const { command, message: text } = extractCommandAndMessage(message); if (!command) return; if (!keywords.includes(command)) { client.say(channel, `Unknown command ${command}`); return; } const {error, result} = await commandMap[command](user, text); if (error) { client.say(channel, `Something went wrong: ${error}`); } else { client.say(channel, result); }
{ "domain": "codereview.stackexchange", "id": 44313, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript, node.js, error-handling, repository", "url": null }
javascript, node.js, error-handling, repository Here we first, create a mapping commandMap of all the keywords pointing to their respective command handler function. We also extract all the keywords to an array keywords using Object.keys. In the main Twitch handler, the message is parsed to split the keyword from the arguments. If the command is in the keyword list, we call it, receive our results object (see below), and answer to the Twitch chat. This has the advantage that you can add commands without touching the main message handler: just create the command handler function and add it to commandMap. Command handler Is it exceptional that users would provide invalid data, such as a missing task description? Unfortunately not... So I think a results object would be more appropriate here than try-catch with custom exceptions. Save the exceptions for truly exceptional states, like network or database issues. The result can be a simple object literal with properties error and result. If error is null (or absent), the operation was successful. Otherwise, it would contain the error description. If error is non-null, no guarantees are made that the result property exists and it should not be used. Object deconstruction makes this quite neat: const addTask = (user, task) => { if (!task) { return {error: "Please provide a task description"} } // save the task return {result: `Task "${task}" saved successfully` }; // below would be in the Twitch message handler const {error, result} = addTask("john doe", "do the laundry"); if (error) { console.error(`Something went wrong: ${error}`); } else { console.log(result); }
{ "domain": "codereview.stackexchange", "id": 44313, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript, node.js, error-handling, repository", "url": null }
javascript, node.js, error-handling, repository Persistence With in-memory storage, you lose all tasks when you restart the server. If this is okay for your use case, why bother with other storage? If not, you obviously need to store the tasks somewhere out-of-process. Files, SQLite, Redis, Postgresql, ... I've used Knex.js and like it. It's a query builder, not an ORM, so it doesn't introduce a lot of "magic" into the project. If you want a higher-level solution, have a look at e.g. Sequelize, an ORM.
{ "domain": "codereview.stackexchange", "id": 44313, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript, node.js, error-handling, repository", "url": null }
c++, vectorization, eigen Title: Implementation of Iterative Closest Point in C++ Question: Here, is my implementation of Iterative Closest Point algorithm in C++. The code is written using the Eigen library. I have tried to implement an efficient coding methodology best to my knowledge however, I believe there are still improvements that can be made in terms of vectorizing the code and getting rid of for loops. For further information: GitHub #include<iostream> #include<eigen3/Eigen/Dense> #include<eigen3/Eigen/Core> #include<eigen3/Eigen/SVD> #include<fstream> #include<vector> // Run using: g++ -std=c++17 -I/usr/include/eigen3 ICP.cpp -o ICP -O2 -DNDEBUG using namespace Eigen; struct Tyx { MatrixXd Rot; VectorXd trans; }; // Rigid Registration. Tyx ComputeOptimalRigidRegistration(MatrixXd X, MatrixXd Y, MatrixXi C) { Tyx T; // Calculate the point cloud centroids. MatrixXd x_subset = X(C.col(0), Eigen::placeholders::all); MatrixXd y_subset = Y(C.col(1), Eigen::placeholders::all); VectorXd x_centroid = x_subset.colwise().mean(); VectorXd y_centroid = y_subset.colwise().mean(); // Calculate the deviation of X and Y. MatrixXd x_deviation = x_subset.rowwise() - x_centroid.transpose(); MatrixXd y_deviation = y_subset.rowwise() - y_centroid.transpose(); // Calculate covariance. MatrixXd W = x_deviation.transpose() * y_deviation; //std::cout << "W covarieance matrix: " << W << std::endl; //Calculate the SVD. JacobiSVD<MatrixXd> svd(W, Eigen::ComputeFullU | Eigen::ComputeFullV); MatrixXd U = svd.matrixU(); MatrixXd V = svd.matrixV(); //std::cout << "U = " << U << std::endl; //std::cout << "V = " << V << std::endl; // Construct optimal rotation T.Rot = U * V.transpose(); //std::cout << "T.Rot = " << T.Rot << std::endl; // Construct Optimal translation T.trans = y_centroid - (x_centroid.transpose()*T.Rot).transpose(); //std::cout << "T.trans = " << T.trans << std::endl; return T; }
{ "domain": "codereview.stackexchange", "id": 44314, "lm_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++, vectorization, eigen", "url": null }
c++, vectorization, eigen return T; } // Get the correspondences. MatrixXi EstimateCorrespondences(MatrixXd X, MatrixXd Y, Vector3d t, Matrix3d R, double d_max) { //Initialize C as empty. MatrixXi C(0,2); int N = X.rows(); MatrixXd transposed_x(N,3); int index; VectorXd norm(N); for(int i = 0; i < X.rows(); i++) { transposed_x.row(i) = X.row(i) * R + t.transpose(); } // Find the indexes in the least square sense. for(int i =0; i < transposed_x.rows(); i++) { // diff = Y.rowwise() - transposed_x.row(i); // norm = diff.rowwise().norm(); norm = (Y.rowwise() - transposed_x.row(i)).rowwise().norm(); // Print the first 10 elements of the norm vector. Debugging purposes. // if (i == 0) // { // std::cout << "X = " << X.row(0) << std::endl; // std::cout << "Y = " << Y.row(0) << std::endl; // std::cout << "transposed_x = " << transposed_x.row(0) << std::endl; // std::cout << norm.head(10) << std::endl; // } norm.minCoeff(&index); if (norm.coeff(index) < d_max) { C.conservativeResize(C.rows()+1, Eigen::NoChange); C.row(C.rows()-1) << i,index; } } return C; } Tyx ICP_algo(MatrixXd X, MatrixXd Y, Vector3d t0, Matrix3d R0, double d_max, int max_iter) { int iter = 0; Tyx T; MatrixXi C; while(true) { C = EstimateCorrespondences(X , Y , t0 , R0 , d_max); T = ComputeOptimalRigidRegistration(X, Y, C); t0 = T.trans; R0 = T.Rot; iter = iter +1; if (iter == max_iter) { std::cout << "Max iterations reached " << iter << std::endl; break; } } T.Corresp = C; return T; } int main() {
{ "domain": "codereview.stackexchange", "id": 44314, "lm_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++, vectorization, eigen", "url": null }
c++, vectorization, eigen return T; } int main() { // Create a vector of vector std::vector<std::vector<double>> data; double value; //Open the text file. std::ifstream file("pclX.txt"); //Read the data from the file to the matrix while(file >> value) { data.push_back({value}); while (file.peek() == ' ') { file >> value; data.back().push_back(value); } } file.close(); int n_rows = data.size(); int n_cols = data[0].size(); MatrixXd pcl_X(n_rows,n_cols); for (int i = 0; i < n_rows; ++i) { for (int j =0; j < n_cols; ++j) { pcl_X(i,j) = data[i][j]; } } file.close(); // Similarly for pcl_Y std::ifstream file_y("pclY.txt"); //Read the data from the file to the matrix // Clear the data vector data.clear(); while(file_y >> value) { data.push_back({value}); while (file_y.peek() == ' ') { file_y >> value; data.back().push_back(value); } } file_y.close(); n_rows = data.size(); n_cols = data[0].size(); MatrixXd pcl_Y(n_rows,n_cols); for (int i = 0; i < n_rows; i++) { for (int j =0; j < n_cols; j++) { pcl_Y(i,j) = data[i][j]; } } // Initial translational vector and Rotational matrix Vector3d t = Vector3d::Zero(); Matrix3d R = Matrix3d::Identity(); // Create a identity matrix. double d_max = 0.25; int iter = 30; Tyx result; // std::cout << "pcl_X = " << pcl_X.row(0) << std::endl; // std::cout << "pcl_Y = " << pcl_Y.row(0) << std::endl; clock_t begin = clock(); result = ICP_algo(pcl_X, pcl_Y, t, R, d_max, iter); clock_t end = clock(); double elapsed_secs = double(end - begin) / CLOCKS_PER_SEC; std::cout << "Time taken : " << elapsed_secs << std::endl;
{ "domain": "codereview.stackexchange", "id": 44314, "lm_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++, vectorization, eigen", "url": null }
c++, vectorization, eigen std::cout << "\n Translation vector: " << result.trans << std::endl; std::cout << "-----------------------------" << std::endl; std::cout << "Rotation matrix: " << result.Rot << std::endl; MatrixXd result_pt_cloud(pcl_X.rows(),3); for(int i = 0; i < pcl_X.rows(); i++) { result_pt_cloud.row(i) = pcl_X.row(i) * result.Rot + result.trans.transpose(); } // Write the result point cloud to a text file. std::ofstream file_result("result.txt"); for(int i = 0; i < result_pt_cloud.rows(); i++) { file_result << result_pt_cloud(i,0) << " " << result_pt_cloud(i,1) << " " << result_pt_cloud(i,2) << std::endl; } return 0; } Answer: General Observations Code that contains commented out executable code (debug code) such as // std::cout << "pcl_X = " << pcl_X.row(0) << std::endl; // std::cout << "pcl_Y = " << pcl_Y.row(0) << std::endl;
{ "domain": "codereview.stackexchange", "id": 44314, "lm_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++, vectorization, eigen", "url": null }
c++, vectorization, eigen is not ready to be reviewed. Please keep this in mind for future code reviews. DRY Code There is a programming principle called the Don't Repeat Yourself Principle sometimes referred to as DRY code. If you find yourself repeating the same code multiple times it is better to encapsulate it in a function. If it is possible to loop through the code that can reduce repetition as well. The code to read the data from the files into the matrices is repeated, the code can be turned into a function which takes the file name as in input parameter and returns the data vector. There are 2 possible functions here, one returns the data vector and the other returns the matrix. Data Only static std::vector<std::vector<double>> getFileData(std::string fileName) { std::vector<std::vector<double>> data; double value; //Open the text file. std::ifstream file(fileName); //Read the data from the file to the matrix while (file >> value) { data.push_back({ value }); while (file.peek() == ' ') { file >> value; data.back().push_back(value); } } file.close(); return data; } Matrix static MatrixXd getMatrixFromFile(std::string fileName) { std::vector<std::vector<double>> data; double value; //Open the text file. std::ifstream file(fileName); //Read the data from the file to the matrix while (file >> value) { data.push_back({ value }); while (file.peek() == ' ') { file >> value; data.back().push_back(value); } } file.close(); int n_rows = data.size(); int n_cols = data[0].size(); MatrixXd pcl_X(n_rows, n_cols); for (int i = 0; i < n_rows; ++i) { for (int j = 0; j < n_cols; ++j) { pcl_X(i, j) = data[i][j]; } } return pcl_X; }
{ "domain": "codereview.stackexchange", "id": 44314, "lm_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++, vectorization, eigen", "url": null }
c++, vectorization, eigen return pcl_X; } Complexity The function main() is too complex (does too much). As programs grow in size the use of main() should be limited to calling functions that parse the command line, calling functions that set up for processing, calling functions that execute the desired function of the program, and calling functions to clean up after the main portion of the program. There is also a programming principle called the Single Responsibility Principle that applies here. The Single Responsibility Principle states: that every module, class, or function should have responsibility over a single part of the functionality provided by the software, and that responsibility should be entirely encapsulated by that module, class or function. In part this complexity can be reduced with DRY Code above. Something else to keep in mind is that a general rule of thumb in programming or software engineering is that no function should be larger than one screen in an IDE or editor, if it gets larger than this it is difficult to read, write and maintain. The main() function is currently over 90 lines of code, most IDEs present 55 lines or less in the screen. Timing Excution The clock() function that the code currently uses is a wall clock function which returns the current time of day. There are more accurate ways to time a function() using std::chrono functions. This is a class I put together for this purpose, you can find it in one of my questions. Creating an instance starts the timer, calling stopTimerAndReport() reports the result. #ifndef CC_UTILITY_TIMER_H #define CC_UTILITY_TIMER_H #include <chrono> #include <ctime> #include <iomanip> #include <iostream> #include <string_view> class UtilityTimer { public: using clock = std::chrono::steady_clock; void startTimer() noexcept { start = clock::now(); } void stopTimerAndReport(std::string_view whatIsBeingTimed) noexcept { clock::time_point end = clock::now();
{ "domain": "codereview.stackexchange", "id": 44314, "lm_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++, vectorization, eigen", "url": null }
c++, vectorization, eigen std::chrono::duration<double> elapsed_seconds = end - start; double ElapsedTimeForOutPut = elapsed_seconds.count(); using std::chrono::system_clock; auto const now = system_clock::to_time_t(system_clock::now()); std::clog << "finished " << whatIsBeingTimed << std::put_time(std::localtime(&now), "%c") << "\nelapsed time in seconds: " << ElapsedTimeForOutPut << "\n\n\n"; } private: clock::time_point start = clock::now(); }; #endif // CC_UTILITY_TIMER_H
{ "domain": "codereview.stackexchange", "id": 44314, "lm_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++, vectorization, eigen", "url": null }
python, python-3.x Title: Automate the Boring Stuff with Python 2nd Edition - Chapter 8 - Sandwich Maker Project Question: I am learning Python through Automate the Boring Stuff. And I was trying to do the practice project Sandwich Maker in Chapter 8, although I somehow already solved the problem but I encountered some issue in the coding process. Here is my code: import pyinputplus as pyip bread_type = { "Wheat":2.2,"White":1.2,"Sourdough":4.6} protein_type = { "Chicken":3.3,"Turkey":5.9,"Ham":4.9,"Tofu":1.2} cheese_type = { "Cheddar":2.2,"Swiss":1.2,"Mozzarella":4.6,"No cheese":0.0} add_on_type = { "Mayo":1.0,"Mustard":0.8,"Lettuce":1.4,"Tomato":1.6,"No add-ons":0.0} prompts=['What bread do you want?\n', 'What protein do you want?\n', 'Do you want cheese in your sandwich?\n', 'What type of cheese do you want?\n' 'Do you want some add ons to your sandwich?\n', 'What add-ons do you want?\n', 'How many of this sandwich do you want?\n'] def bread_order(): prompt=prompts[0] bread_choice=bread_type.keys() return pyip.inputMenu(list(bread_choice),prompt=prompt,numbered=True) def protein_order(): prompt=prompts[1] protein_choice=protein_type.keys() return pyip.inputMenu(list(protein_choice),prompt=prompt,numbered=True) def cheese_order(): yes_no_prompt=prompts[2] prompt=prompts[3] cheese_choice=list(cheese_type.keys()) yes_no_cheese=pyip.inputYesNo(prompt=yes_no_prompt) if yes_no_cheese=='no': return'No cheese' elif yes_no_cheese=='yes': return pyip.inputMenu(cheese_choice,prompt=prompt,numbered=True) def add_ons_order(): yes_no_prompt=prompts[4] prompt=prompts[5] add_ons_choice=list(add_on_type.keys()) yes_no_add_ons=pyip.inputYesNo(prompt=yes_no_prompt) if yes_no_add_ons == 'No add_ons' : return 'No add-ons' elif yes_no_add_ons=='yes': return pyip.inputMenu(add_ons_choice,prompt=prompt,numbered=True)
{ "domain": "codereview.stackexchange", "id": 44315, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, python-3.x", "url": null }