text
stringlengths
1
2.12k
source
dict
javascript, performance, algorithm on both cases it is the same as saying (4) (b − a) mod m == 0 if b >= a Let's define the inverse of mod m as invmod_m (5) invmod_m(x mod m) = x (6) invmod_m(x) mod m = x by applying the mod inverse we get infinitely many equations, but that' ok, we can deal with them all at once (7) invmod_m((b − a) mod m) == invmod_m(0) from (5) we can simplify the left side (8) b - a == invmod_m(0) now we can add a to both sides (9) b == a + invmod_m(0) and do mod m of both sides again (10) b mod m == (a + invmod_m(0)) mod m and distribute the m on right side (11) b mod m == a mod m + invmod_m(0) mod m from (6) we see that invmod_m(0) mod m is zero so we have (12) (b mod m) == (a mod m) And so you see, regardless of what the m is, two numbers are a good pair if and only if their remainder mod m is the same. So an algorithm with O(n) time complexity is build histogram R of remainders mod m sum the number of good pairs (R[r] * (R[r] - 1) / 2) for each remainder r in R (with occurence R[r] > 0) type Solution = (numbers: number[], m: number) => number const naiveSolution: Solution = (numbers, m) => { let count = 0 for (let j = 1; j < numbers.length; ++j) { for (let i = 0; i < j; ++i) { const ai = numbers[i] const aj = numbers[j] if (Math.abs(ai - aj) % m === 0) { ++count } } } return count }
{ "domain": "codereview.stackexchange", "id": 44679, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript, performance, algorithm", "url": null }
javascript, performance, algorithm const ezioSolution: Solution = (numbers, m) => { let count = 0; const remainders = new Map(); for (const num of numbers) { const remainder = num % 100; const modifiedNum = (num - remainder) / 100; if (remainders.has(remainder)) { const nums = remainders.get(remainder); for (const num of nums) { if (Math.abs(num - modifiedNum) % 2 === 0) ++count; } nums.push(modifiedNum); } else { remainders.set(remainder, [modifiedNum]); } } return count; } const slepicSolution: Solution = (numbers, m) => { const remainders = new Map/*<number, number>*/() for (let j = 0; j < numbers.length; ++j) { const aj = numbers[j] const r = aj % m remainders.set(r, remainders.has(r) ? remainders.get(r) + 1 : 1) } let total = 0 remainders.forEach((count) => { total += count * (count - 1) / 2 }) return total } const solutionTestSuite = (name: string, solution: Solution): number => { let errors = 0 const solutionTest = (expected:number, numbers: number[], m: number) => { const actual = solution(numbers, m) if (expected !== actual) { console.warn(`${name} returned ${actual} instead of ${expected}`, numbers, `(mod ${m})`) ++errors } else { console.info(`${name} returned ${actual} as expected`, numbers, `(mod ${m})`) } } console.info(`${name} starting`) const start = performance.now() solutionTest(0, [], 200) solutionTest(0, [0], 200) solutionTest(1, [0, 0], 200) solutionTest(1, [105, 505], 200) solutionTest(3, [205, 605, 5], 200) solutionTest(4, [205, 10, 605, 5, 1010], 200) const stop = performance.now() const time = `in ${stop - start} ms` if (errors > 0) { console.warn(`${name} gor ${errors} errors ${time}`) } else { console.info(`${name} OK ${time}`) } return errors }
{ "domain": "codereview.stackexchange", "id": 44679, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript, performance, algorithm", "url": null }
javascript, performance, algorithm const testAll = () => { let errors = 0 errors += solutionTestSuite('naive', naiveSolution) errors += solutionTestSuite('ezio', ezioSolution) errors += solutionTestSuite('slepic', slepicSolution) if (errors > 0) { console.warn(`${errors} errors in total`) } else { console.info(`ALL OK`) } } testAll() Sorry for the typescript; I felt more confident doing it that way, but it should be fine to just remove the typings...
{ "domain": "codereview.stackexchange", "id": 44679, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript, performance, algorithm", "url": null }
design-patterns, groovy Title: Design - prevent multiple nesting in function Question: I have a function written in Groovy which needs to save a record and also return response from the server. Function is working fine, but I am not happy with the design because I have a problem with multiple nesting. This is the function: Map scanAccessRecord(GrailsParameterMap params){ Map response Date currentTime = new Date() String readerEthernetAddress = params.readerMac Reader reader = Reader.findByDeletedAndEthernetAddress(false, readerEthernetAddress) Boolean isAccessIn = (params.isAccessIn == "True") if(reader) { UserSettings userSettings = UserSettings.findByRfidCode(params.rfid.toString()) if(userSettings) { if(userSettings.user.company.id == reader.companyId) { AccessRecord accessRecord = new AccessRecord(reader:reader, userId:userSettings.userId, specificDate:currentTime, isAccessIn: isAccessIn) if(accessRecord.save(flush: true)) { response = [ status: '00', message: 'OK', recordId: accessRecord.id, ] } else { response = [ status: '60', message: 'error' ] } } else { response = [status: '40', message: 'USER AND READER ARE NOT FROM SAME COMPANY'] } } else { response = [status: '10', message: 'UNKNOWN USER'] } } else { response = [status: '50', message: 'READER NOT FOUND'] } return response } What can I do to make this function "cleaner"? Answer: Use optional instead of null. I wrote an article about avoiding nulls if you are interested.
{ "domain": "codereview.stackexchange", "id": 44680, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "design-patterns, groovy", "url": null }
design-patterns, groovy Use early returns to avoid nesting If !reader return [status: '50', message: 'READER NOT FOUND'] If !userSettings return... Rest of the logic I prefer to avoid nulls,so I would choose to call save with failOnError=true and it will throw exception instead of returning null when save fails. I assume you want any exception to return [ status: '60', message: 'error'], if you use save with failOnError=true then the error is handled in one place only. add validation for params.isAccessIn. If by mistake it is nor true or false, it is better to throw error than do something the client didn't intend to. Maybe you should be more flexible with params.isAccessIn and compare strings without case sensitivity.
{ "domain": "codereview.stackexchange", "id": 44680, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "design-patterns, groovy", "url": null }
c, linked-list Title: Dynamic C Linked List Implementation Question: I've started to experiment with (void *) in C, in order to work with Dynamic Data Types, that is, to surpass the need to pass specific type of data. I have implemented this doubly linked list in C and I tried to keep it versatile so it can hold and kind of data type (primitive and non-primitives). I'll be glad to have some feedback and ideas on how to improve my implementation. as part of my path to study this subject I'm trying to create a mini library of common Data Structures like stacks, linked list, binary trees etc that will work with any kind of type. here is the implementation of my doubly linked list. I achieved "Dynamic" data type (I'm not sure if that's the correct term) by asking the user to provide constructor, destructor and comparison function for the objects that he'd like to store in the liist. LinkedList.h /* Implements doubly linked list. ---------- ---------- ---------- | HEAD | <------> | NODE | <------> | TAIL | ---------- ---------- ---------- The linked list is generic and may hold any kind of data (from the same type!) given a proper constructor function for that type. Created by: @BAxBI as part of General DataStructure library for C. */ #ifndef __LINKED__LIST_H_ #define __LINKED__LIST__H_ #include <stdlib.h> /* @brief Linked List item. */ typedef void * LItem; /* @brief Constant Linked List item. */ typedef const void * CLItem; /* @brief Linked List type. */ typedef struct LList * LList;
{ "domain": "codereview.stackexchange", "id": 44681, "lm_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, linked-list", "url": null }
c, linked-list /* @brief Linked List type. */ typedef struct LList * LList; /* Creates a new empty linked list @param ctor Pointer to a constructor function for an element in the list. @param dtor Pointer to a destructor function for an element in the list. @param compare Pointer to a comparison function between two elements in the list @param print Pointer to a print function of an element in the list. @return Pointer to an emty linked list */ LList new_linked_list(LItem (*ctor)(LItem),void (*dtor)(LItem), int (*compare)(LItem, LItem), void (*print)(LItem)); /* Adds a node to the head of the list. @param list The list to add the element to. @param item A pointer to the item to add to the list. */ void add_node(LList list, LItem item); /* Deletes the first occurrence of an item in the list. @param list The list to delete the item from. @param item The item to delete. */ void delete_node(LList list, LItem item); /* Destroys a linked list and frees all the allocated memory. @param list The linked list to destroy. */ void destroy_linked_list(LList list); /* Gets an element from the Linked List. @param list The list to get the element from. @param element The element to get from the list. @return The element from the list if exist NULL otherwise */ LItem get_element_from_LList(LList list, LItem element); /* Gets the number of elements in the linked list. @param list The list the check its number of elements. @return The number of elements in the linked list. */ size_t get_No_elem_LList(LList list); /* Prints the linked list (if given a print function to print a single element!) @param list The linked list to be printed. */ void print_list(LList list); #endif LinkedList.c #include <stdlib.h> #include <stdio.h> #include "LinkedList.h" typedef struct Node{ struct Node *prev_node; struct Node *next_node; LItem node_content; }Node;
{ "domain": "codereview.stackexchange", "id": 44681, "lm_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, linked-list", "url": null }
c, linked-list struct LList { Node *head; Node *tail; size_t NoElements; // Functions provided by the client. LItem (*ctor)(LItem); void (*dtor)(LItem); int (*compare)(LItem, LItem); void (*print)(LItem); }; LList new_linked_list(LItem (*ctor)(LItem),void (*dtor)(LItem), int (*compare)(LItem, LItem), void (*print)(LItem)){ LList new_llist = calloc(1, sizeof(struct LList)); if (!new_llist){ return NULL; } new_llist->head = NULL; new_llist->tail = NULL; new_llist->NoElements = 0; new_llist->ctor = ctor; new_llist->dtor = dtor; new_llist->compare = compare; new_llist->print = print; return new_llist; } void add_node(LList list, LItem item){ Node *new_node = (Node *)malloc(sizeof(Node)); if (!new_node) return; new_node->next_node = NULL; new_node->prev_node = NULL; new_node->node_content = list->ctor(item); /* Empty list*/ if(!list->head){ list->head = new_node; list->tail = new_node; } else { new_node->next_node = list->head; list->head->prev_node = new_node; list->head = new_node; } list->NoElements++; }
{ "domain": "codereview.stackexchange", "id": 44681, "lm_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, linked-list", "url": null }
c, linked-list /* Deletes first occurence of a node in a linked list */ void delete_node(LList list, LItem item){ Node *ptr = list->head; while(ptr != NULL){ if(list->compare(ptr->node_content, item) == 0){ /* First node to be deleted */ if(!ptr->prev_node){ list->head = ptr->next_node; } else if(ptr->prev_node && ptr->next_node){ ptr->next_node->prev_node = ptr->prev_node; ptr->prev_node->next_node = ptr->next_node; } else { ptr->prev_node->next_node = NULL; } if(list->dtor){ list->dtor(ptr->node_content); } free(ptr); list->NoElements--; return; } ptr = ptr->next_node; } } void destroy_linked_list(LList list){ Node *ptr = list->head; while(ptr != NULL){ Node *tmp = ptr; ptr = ptr->next_node; if(list->dtor){ list->dtor(tmp->node_content); } free(tmp); } free(list); } size_t get_No_elem_LList(LList list){ return list->NoElements; } LItem get_element_from_LList(LList list, LItem element){ Node *ptr = list->head; if(!list->head){ printf("The list is empty!\n"); } while(ptr!=NULL){ if(list->compare(ptr->node_content, element) == 0){ return ptr->node_content; } ptr = ptr->next_node; } printf("The element you're looking for is not in the linked list.\n"); return NULL; }
{ "domain": "codereview.stackexchange", "id": 44681, "lm_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, linked-list", "url": null }
c, linked-list void print_list(LList list){ if(!list->print) { printf("The linked list provided doesn't have print function\n"); return; } if (!list->head) { printf("The list is empty!\n"); return; } Node *ptr = list->head; while(ptr){ list->print(ptr->node_content); if(ptr->next_node){ printf(" <---> "); } else{ printf(" ---> "); } ptr = ptr->next_node; } printf("\033[0;31m"); /* Red */ printf("NULL\n"); printf("\033[0m"); /* Reset */ } Answer: I'll be glad to have some feedback and ideas on how to improve my implementation. Overall, A good presentation, yet any linked-list module needs to consider large scale usage. Bug: Incomplete linking update On deletion of the 1st node, code does list->head = ptr->next_node;, but does not update the 2nd nodes .prev_node member. General thought: when a node is deleted, both the left node (or LList) and right node (or LList) need pointer updates, that's 2 links, never 1. Only works with pointers "work with any kind of type" and "asking the user to provide constructor, destructor and comparison function for the objects ..." --> With typedef void * LItem;, user can only use with object pointer types. No pointer type checking is expected against void *. Name space LinkedList.h declares __LINKED__LIST_H_, LItem, CLItem, LList, add_node, ..., print_list. Rather then scatter names, consider DLList.h declares __DLList_H_, DLList_Item, const DLList_Item, DLList, DLList_add, ..., DLList_print. Casting *alloc() Casting the result of *alloc() not needed. Be uniform. LList new_llist = calloc(1, sizeof(struct LList)); // OP did not cast here. // Node *new_node = (Node *)malloc(sizeof(Node)); Node *new_node = malloc(sizeof(Node));
{ "domain": "codereview.stackexchange", "id": 44681, "lm_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, linked-list", "url": null }
c, linked-list Allocation failures not detectable by caller Consider returning a value. //void add_node(LList list, LItem item){ // Node *new_node = (Node *)malloc(sizeof(Node)); // if (!new_node) return; // Return error flag bool add_node(LList list, LItem item){ Node *new_node = (Node *)malloc(sizeof(Node)); if (!new_node) return true; ... return false; } Use const when able // size_t get_No_elem_LList(LList list){ // return list->NoElements; // } size_t get_No_elem_LList(const LList list){ return list->NoElements; } Omit console specialized code from print_list() Delete: printf("\033[0;31m"); /* Red */ printf("\033[0m"); /* Reset */ get_element_from_LList() error return get_element_from_LList() returns NULL when item not found, yet NULL may be a valid object added to the list. Now caller does not distinguish success from failure. I suppose caller could first try get_No_elem_LList(), yet I would prefer a different get interface, something the results in a LItem and a success indication. Use alternative than printf() to indicate errors For general purpose list list code, the functions (aside from print_list()) should not call *printf(). Instead pass back to caller an error indication. Why double linked list?? Tail access nor node deletion from the fail never occurs. What was the point of a double linked list? No success indication I'd expect delete_node() to return something to indicate success/failure. Asymmetric functions .dtor is OK to be NULL with if(list->dtor){ list->dtor(ptr->node_content); }. No such NULL test with new_node->node_content = list->ctor(item); Documentation in .h file does not discuss this. Consider instead with new_linked_list() to NULL test once, rather than repeatedly. // new_llist->dtor = dtor; new_llist->dtor = dtor ? dtor : dummy_function_that_does_nothing; Why struct LList?? Why code LList and struct LList? One is enough. // LList new_llist = calloc(1, sizeof(struct LList));` LList new_llist = calloc(1, sizeof(LList));`
{ "domain": "codereview.stackexchange", "id": 44681, "lm_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, linked-list", "url": null }
c, linked-list Even better, allocate to the size of the referenced object, not type. LList new_llist = calloc(1, sizeof new_llist[0]); // or LList new_llist = calloc(1, sizeof *new_llist); Include LinkedList.h first The order of includes should be irrelevant, yet for xxx.c, the first include should be xxx.h. This is a fine test that xxx.h does not rely on other include files. xxx.h should itself include any needed include files. // #include <stdlib.h> // #include <stdio.h> // #include "LinkedList.h" #include "LinkedList.h" #include <stdlib.h> #include <stdio.h> Missing sample code Consider a main.c that shows example usage. Tolerate destroy_linked_list(NULL) Just as free(NULL) is OK, consider adding NULL test. This simplifies caller usage of destroy_linked_list(). void destroy_linked_list(LList list){ if (list) { ... } **Compare function to take `const` arguments** As LItem is a hidden pointer type (yech), use const so the same function used for qsort() can be used here. // int (*compare)(LItem, LItem); int (*compare)(const LItem, const LItem);
{ "domain": "codereview.stackexchange", "id": 44681, "lm_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, linked-list", "url": null }
python, design-patterns, file-system Title: Class handling file conversion and data manipulation archiving [h5py] Question: I am a physics PhD student who co-developped a python package for file conversion of standard file format used in Scanning Probe Microscopy (SPM) and archiving of data manipulation for tracability. If you want to know more about the package, an article was published there: https://doi.org/10.1016/j.ultramic.2021.113345 In summary, the goal of the project is to have a well defined file structure inside an hdf5 file which will contain three root folder (h5py.Groups): datasets, metadata and process. Datasets will contain raw data extracted from an existing file in a standard SPM format; metadata will contain the existing metadata of the existing file; and process will contain all the data manipulation that have been done on the raw data (or existing processed data), with attributes saving all the necessary information for data manipulation tracability. The initial version of the code was built without thinking too much about best practices and expandability in mind, so I am currently doing a "big rewrite". I am almost done with a class called hyFile which is a wrapper class around h5py.File which will handle: The file conversion (from a standard SPM format to hdf5) The reading and writting of data from the hdf5 file (using the existing package h5py) The tracability of processed data through the apply function, which take an arbitrary function and the path to the data that need processing, and save the result into the process folder. It contains all the necessary dunder methods to write/read data in the hdf5 file, and to be a context manager. It also contains an internal class which allows the manipulation of hdf5 attributes. import h5py import pathlib import warnings from . import ibw_files, gsf_files import inspect import numpy as np from datetime import datetime import types class hyFile: class Attributes: def __init__(self, file): self.file = file
{ "domain": "codereview.stackexchange", "id": 44682, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, design-patterns, file-system", "url": null }
python, design-patterns, file-system class hyFile: class Attributes: def __init__(self, file): self.file = file def __contains__(self, path: str) -> bool: return path in self.file def __getitem__(self, path: str | None = None) -> dict: if path is None: f = self.file[""] if path != "": f = self.file[path] return {key: f.attrs[key] for key in f.attrs.keys()} def __setitem__(self, path: str, attribute: tuple[str, any]) -> None: self.file[path].attrs[attribute[0]] = attribute[1] def __init__(self, path, mode="r+"): if isinstance(path, str): self.path = pathlib.Path(path) else: self.path = path if not self.path.is_file(): self.file = h5py.File(self.path, "a") for group in ["datasets", "metadata", "process"]: self._require_group(group) if mode != "a": self.file.close() self.file = h5py.File(self.path, mode) else: self.file = h5py.File(self.path, mode) root_struct = set(self.file.keys()) if root_struct != {"datasets", "metadata", "process"}: warnings.warn( f"Root structure of the hdf5 file is not composed of 'datasets', 'metadata' and 'process'. \n It may not have been created with Hystorian." ) self.attrs = self.Attributes(self.file) def __enter__(self): return self def __exit__(self, type, value, traceback) -> None: if self.file: self.file.close if value is not None: warnings.warn(f"File closed with the following error: {type} - {value} \n {traceback}") def __getitem__(self, path: str = "") -> h5py.Group | h5py.Dataset: if path == "": return self.file else: return self.file[path]
{ "domain": "codereview.stackexchange", "id": 44682, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, design-patterns, file-system", "url": null }
python, design-patterns, file-system def __setitem__(self, data: tuple[str, any], overwrite=True) -> None: self._create_dataset(data, overwrite) def __delitem__(self, path: str) -> None: if path not in self.file: raise KeyError("Path does not exist in the file.") del self.file[path] def __contains__(self, path: str) -> bool: return path in self.file def read(self, path: str = ""): if path == "": return self.file.keys() else: if isinstance(self.file[path], h5py.Group): return self.file[path].keys() else: return self.file[path][()] def extract_data(self, path: str): conversion_fcts = { ".gsf": gsf_files.extract_gsf, ".ibw": ibw_files.extract_ibw, } if isinstance(path, str): path = pathlib.Path(path) if path.suffix in conversion_fcts: data, metadata, attributes = conversion_fcts[path.suffix](path) self._write_extracted_data(path, data, metadata, attributes) else: raise TypeError(f"{path.suffix} file don't have a conversion function.") def apply( self, function: callable, inputs: list[str] | str, output_names: list[str] | str | None = None, increment_proc: bool = True, **kwargs, ): def convert_to_list(inputs): if isinstance(inputs, list): return inputs return [inputs] inputs = convert_to_list(inputs) if output_names is None: output_names = inputs[0].rsplit("/", 1)[1] output_names = convert_to_list(output_names) result = function(*inputs, **kwargs) if result is None: return None if not isinstance(result, tuple): result = tuple([result])
{ "domain": "codereview.stackexchange", "id": 44682, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, design-patterns, file-system", "url": null }
python, design-patterns, file-system if len(output_names) != len(result): raise Exception("Error: Unequal amount of outputs and output names") num_proc = len(self.read("process")) if increment_proc or f"{str(num_proc).zfill(3)}-{function.__name__}" not in self.read("process"): num_proc += 1 out_folder_location = f"{'process'}/{str(num_proc).zfill(3)}-{function.__name__}" for name, data in zip(output_names, result): self._create_dataset((f"{out_folder_location}/{name}", data)) self._write_generic_attributes(f"{out_folder_location}/{name}", inputs, name, function) self._write_kwargs_as_attributes(f"{out_folder_location}/{name}", function, kwargs, first_kwarg=len(inputs)) def _write_generic_attributes( self, out_folder_location: str, in_paths: list[str] | str, output_name: str, function: callable ) -> None: if not isinstance(in_paths, list): in_paths = [in_paths] operation_name = out_folder_location.split("/")[1] new_attrs = { "path": out_folder_location + output_name, "shape": np.shape(self[out_folder_location]), "name": output_name, } if function.__module__ is None: new_attrs["operation name"] = "None." + function.__name__ else: new_attrs["operation name"] = function.__module__ + "." + function.__name__ if function.__module__ == "__main__": new_attrs["function code"] = inspect.getsource(function) new_attrs["operation number"] = operation_name.split("-")[0] new_attrs["time"] = str(datetime.datetime.now()) new_attrs["source"] = in_paths self.attrs[out_folder_location] = new_attrs
{ "domain": "codereview.stackexchange", "id": 44682, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, design-patterns, file-system", "url": null }
python, design-patterns, file-system self.attrs[out_folder_location] = new_attrs def _write_kwargs_as_attributes( self, path: str, func: callable, all_variables: dict[str, any], first_kwarg: int = 1 ) -> None: attr_dict = {} if isinstance(func, types.BuiltinFunctionType): attr_dict["BuiltinFunctionType"] = True else: signature = inspect.signature(func).parameters var_names = list(signature.keys())[first_kwarg:] for key in var_names: if key in all_variables: value = all_variables[key] elif isinstance(signature[key].default, np._globals._NoValueType): value = "None" else: value = signature[key].default if callable(value): value = value.__name__ elif value is None: value = "None" try: attr_dict[f"kwargs_{key}"] = value except RuntimeError: RuntimeWarning("Attribute was not able to be saved, probably because the attribute is too large") attr_dict["kwargs_" + key] = "None" self.attrs[path] = attr_dict def _require_group(self, name: str): self.file.require_group(name) def _create_dataset(self, data: tuple[str, any], overwrite=True) -> None: if data[0] in self.file: if overwrite: del self.file[data[0]] else: raise KeyError("Key already exist and overwriste is set to False.") self.file.create_dataset(data[0], data=data[1]) def _write_extracted_data(self, path, data, metadata, attributes) -> None: self._require_group(f"datasets/{path.stem}") for d_key, d_value in data.items(): self._create_dataset((f"datasets/{path.stem}/{d_key}", d_value), overwrite=True)
{ "domain": "codereview.stackexchange", "id": 44682, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, design-patterns, file-system", "url": null }
python, design-patterns, file-system for attr in attributes[d_key].items(): self.attrs[f"datasets/{path.stem}/{d_key}"] = attr if isinstance(metadata, dict): for key in metadata: self._create_dataset((f"metadata/{path.stem}/{key}", metadata[key])) else: self._create_dataset((f"metadata/{path.stem}", metadata)) Here is a few of the questions that I have. As it is right now, the class is a context manager, which open the hdf5 file at the creation of the object and it stays open as long as the object exist. It simplifies a lot the manipulation of it, since then I can just pass the file object along. However would this possibly create conflict with the os trying to access the file? I have the feeling that the class is doing too much at the same time: creating file, read/write, conversion, data manipulation. However I am not sure how I would split it into smaller chunck I am not very happy with the apply function. As it is know, it takes a function, the inputs for it, the name of the outputs to be saved, and a list of **kwargs that are passed to the function. I am not sure how to make it as general as possible but not bloated: In theory any kind of function could be passed to it, in practice most of the one passed will manipulate some kind of numpy array, and give as a result also a numpy array. I am also not sure about the extract_data it contains a dict of function that extract data for multiple file formats and always return three dictionnaries : data, metadata and attributes. Is this a good way to do it? Answer: Thank you for your work to advance how folks take images of tiny things! I'd like to comment on something outside of the submission: def m_apply(filename, function, ...): """ Take any function and handles the inputs of the function by looking into the hdf5 file Also write the output of the function into the hdf5.
{ "domain": "codereview.stackexchange", "id": 44682, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, design-patterns, file-system", "url": null }
python, design-patterns, file-system I found the project documentation frustrating, including those two sentences. At first blush it appeared to me that m_apply was central to the project, a core concept that I should understand at once before moving on to other details. I eventually formed the opinion that I should probably be mentally pronouncing it "matrix apply", that is, applying some function to a named input matrix. But I am sad that neither the tutorial, "readthedocs" text, nor this docstring ever mentions that. Moving on, both the tutorial and the (short!) source code explained to me that l_apply should be read as "list apply", which repeatedly invokes m_apply. So that much is kind of cool. Though again, the """docstring""" could be improved. Ok, back to the submitted code. You have a bunch of imports up front. Please run isort *.py to clean them up. Why does conforming to pep-8 matter? Because it makes it easier for the Gentle Reader to see what's going on. Plus, it reduces merge conflicts when two separate feature branches each add their own new deps. It would be more convenient to phrase it this way: from pathlib import Path class hyFile: No. Please spell it HyFile. Do not create a Public API with a misspelled class name. def __init__(self, file): This is astonishing. Perhaps file is the appropriate identifier, I'm not certain about that topic yet. But if you're going to call it file, then you absolutely must add an "optional" type annotation to this signature. As written, I expected that it meant something like def __init__(self, file: Path): or def __init__(self, file: str): or conceivably some open file handle. Explaining it in a """docstring""" would not be enough -- you need to annotate the file: dict type if you want clear communication with your readers. def __contains__(self, path: str) -> bool: I am a little sad we don't see path: Path, but OK, whatever. def __getitem__(self, path: str | None = None) -> dict:
{ "domain": "codereview.stackexchange", "id": 44682, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, design-patterns, file-system", "url": null }
python, design-patterns, file-system def __getitem__(self, path: str | None = None) -> dict: This is lovely. Maybe consider using the recently introduced Optional[str] notation. GvR claims "there should be one obvious way to do it!", and I think that's the form currently preferred. if path is None: f = self.file[""] if path != "": f = self.file[path] return {key: f.attrs[key] for key in f.attrs.keys()} Ok, the technical term for that is "pretty bad". You seem to contemplate that caller might pass in the empty string. And then, when that happens, you dereference uninitialized local f, giving a NameError. I imagine that linting with mypy might have caught that? Haven't tried it yet. self.file[path].attrs[attribute[0]] = attribute[1] This is nice enough. Certainly it works. It would be nicer if you introduced names for those, via tuple unpack: k, v = attribute self.file[path].attrs[k] = v (Or key, val, whatever.) The __init__ constructor is doing kind of a lot of stuff there. Maybe banish some of it to a helper? or two? Think about adding some method .foo() to this class, either you or another maintainer. And think about authoring a new unit test. How hard do we want to make it to add such a test? We need an H5 file before we can even begin to think about testing some utility function. :-( The sticking point seems to be having a valid self.file. Maybe require caller to pass it in? A utility function outside the class could help callers with that. Alternatively, we might have a pair of similar classes, one which accepts a str name, the other accepting an existing file Path. if isinstance(path, str): self.path = pathlib.Path(path) else: self.path = path
{ "domain": "codereview.stackexchange", "id": 44682, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, design-patterns, file-system", "url": null }
python, design-patterns, file-system This seems tediously long-winded. Just unconditionally assign self.path = Path(path) and be done with it. And similarly in .extract_data(). A redundant call of str("abc") will similarly return those three characters unchanged. We have if NOT .is_file(): A else: B. Consider rephrasing it as if .is_file(): B else: A. Humans are better at reasoning about code that lacks negation. (And double negative? Don't even go there.) This .is_file() test does not seem robust, in the sense that H5 and FS have different namespaces, and there could accidentally be a name collision between them. So again, allowing the caller to choose his own adventure might be the better route to follow. A maintainer would probably be grateful if you mention the value of f"{root_structure}" when you .warn(). def __enter__(self): return self Oh, nice, we have a context manager! The class """docstring""" probably should have spelled that out. Certainly this definition is correct. But it's not usual to define such a method, as the contextmanager decorator typically suffices. if self.file: self.file.close I don't understand what's going on here at all. It seems like Author's Intent must have been .close() ? def __exit__(self, type, value, traceback) -> None: I don't understand this signature. Or rather, I don't agree with it, we could easily make it more closely match the documentation. Please don't shadow the builtin type. Prefer to "be boring"; prefer the exc_type mentioned in the docs. if value is not None:
{ "domain": "codereview.stackexchange", "id": 44682, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, design-patterns, file-system", "url": null }
python, design-patterns, file-system This is actually pretty bad. I have participated in many code reviews where hopelessly vague identifiers like this were criticized, though in some contexts a name of value makes perfect sense. Here? Absolutely not! You must use the conventional name of exc_value so it is clear we're dealing with propagation of an EXCeption. Ok, let's come back to that signature. It's annotated to return None, that is, we evaluate for side effects. What?!? The documentation's mention of "should return a true value" makes it clear that ...) -> bool: is the appropriate return type. Did mypy really agree with this code? Sigh! (Yes, I understand, dropping off the end of this method implicitly returns None which is similar to return False. Typically a decorator glosses over these details.) def __getitem__(self, path: str = "") -> h5py.Group | h5py.Dataset: Kudos, that's a very helpful signature, thank you. if path == "": Ok, I'm starting to get the feeling that empty string is special to this class, in the way that None is often a special input parameter to lots of other classes. And that's fine, it may be good design. But it has to be explicitly documented. I haven't seen any """docstring""" call out its special meaning. I don't know the right answer, but it is possible that you might find it convenient and self-documenting to nominate some other special reserved string to play that role. This is all part of the design of a Public API, and I will be the first to confess that (A) it ain't easy, and (B) likely v2 will get it "more" right than the v1 design. raise KeyError("Path does not exist in the file.") Some poor maintainer will read a bug report and then curse you. Prefer: raise KeyError("Path {path} does not exist in the file.") return self.file[path][()]
{ "domain": "codereview.stackexchange", "id": 44682, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, design-patterns, file-system", "url": null }
python, design-patterns, file-system return self.file[path][()] I get the sense we will be returning an h5py.Dataset here. But I'd feel better about this code if an if or an assert was explicit about that. Also, I guess I'm not really understanding what's going on with the optional type annotations in this class. I see them on some methods. Indeed, we see that this method assures us path shall be a str. But what of the return type? I would like to be able to better reason about path and its de-reference. In general, DbC tells us that every method adheres to a loose or a tight contract. Here, I am left wondering what the read() contract is. conversion_fcts = { I mentally read that as "conversion facts". Had I authored the code I likely would have named it conversion_fns. Consider spelling out conversion_functions. It seems pretty clear that extract_data() seeks to impose some post-condition. It is important to explicitly write down that promise. nit, typo: "doesn't" for "...file don't have..." def apply( self, function: callable, inputs: list[str] | str, output_names: list[str] | str | None = None,
{ "domain": "codereview.stackexchange", "id": 44682, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, design-patterns, file-system", "url": null }
python, design-patterns, file-system Thank you for the type annotations. They are clear, beautiful, very helpful. As far as design of Public API goes, I'm not super fond of the whole "could be a list, or maybe a str" thing. Maybe that's the right design, maybe you have it exactly right, and I should pipe down, that's fine. Or maybe your users would be OK with having a singular form, and a plural form, of that method. The concern is this. We want to deliberately design a Public API that is "easy to use", which also means it is "hard to misuse", hard to misinterpret the result if bad things happened along the way. When we admit inputs of diverse types, maybe we are doing the caller a kindness. For example, viewing path: str as equivalent to Path(path) seems harmless enough. The flip side is, insisting on a specific type can reveal bugs as soon as they're authored. For example, a caller of def foo(a, b, c, d, e, f, path=None, g=None): might have 1 too many args, or 1 too few. Insisting that path be of type Path can be helpful to an app engineer who cares about calling it correctly, perhaps by running mypy. In any event the type annotations, such as for output_names, look lovely as written, and I thank you. if len(output_names) != len(result): raise Exception("Error: Unequal amount of outputs and output names") The """docstring""" does not anticipate this possibility, and does not warn the caller of it. How do I know? Because there is no docstring! This is an essential aspect of the Public API, one that must be documented. When a maintainer chases a bug report on this, the "unequal" remark will be less helpful than seeing the two integer lengths within the diagnostic. Do not raise Exception. Either use something more specific like ValueError, or define an app-specific exception class. if increment_proc or f"{str(num_proc).zfill(3)}-{function.__name__}" not in self.read("process"):
{ "domain": "codereview.stackexchange", "id": 44682, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, design-patterns, file-system", "url": null }
python, design-patterns, file-system That's a nice expression. It needs to be extracted into a helper. I can't imagine that's the only place it appears in this codebase. out_folder_location = f"{'process'}/{str(num_proc).zfill(3)}-{function.__name__}" Oh, look! I was right! Same expression, sure enough. for name, data in zip(output_names, result): When we assigned result = function(*inputs, **kwargs) I had no idea what was going on, it was pretty generic. But now it appears the identifier should have been results, since the API contract seems to imply some container of more than one result value. If (e.g. with annotations) you can encourage function to return a certain kind of result value, then please do that. Being specific is better than being vague. It helps us to reason about the code. You define out_folder_location, but then you only reference that plus /name. Consider changing how you assign local vars. "path": out_folder_location + output_name, I don't understand that expression. My reading, which likely is wrong, is that location does not end with a / slash, and name contains no slash. It seems like we want a slash between those two. Sadly this submission contains no unit tests. An example input / output pair would go a long way to documenting the intended behavior of this line of code. DRY. In _write_generic_attributes for the pair of assignments ending with new_attrs["operation name"] = function.__module__ + "." + function.__name__ prefer this single assignment: new_attrs["operation name"] = (function.__module__ or "None") + "." + function.__name__ Some of this method's behavior seems "quirky", such as an assignment conditional on this: if function.__module__ == "__main__": Describing such behavior in a """docstring""" would go a long way toward making this class easy-to-use for newly onboarded engineers just starting to work with this project. Embrace sphinx! Publish a "readthedocs" site.
{ "domain": "codereview.stackexchange", "id": 44682, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, design-patterns, file-system", "url": null }
python, design-patterns, file-system if isinstance(func, types.BuiltinFunctionType): I fail to see why this is of interest. But I'm just flogging the same old horse that carries a banner saying "there's no docs!". You really need to document this code's behavior. value = "None" That str seems a slightly odd choice, compared to assigning None. Ok, whatever. (It's not like a type hint on attr_dict told us to expect str values.) RuntimeWarning("Attribute was not able to be saved, probably because the attribute is too large") I don't understand that line at all. We were storing to a variable of type dict. I'm not aware of a way to provoke such an error. An illuminating # comment would be helpful. attr_dict[f"kwargs_{key}"] = value ... attr_dict["kwargs_" + key] = "None" Gratuitously using two ways to express the same thing is not a kindness to the Gentle Reader. def _create_dataset(self, data: tuple[str, any], overwrite=True) -> None: if data[0] in self.file: ... self.file.create_dataset(data[0], data=data[1]) The identifier data is probably the right name to use, but it is rather vague. And it has structure, as the type annotation explains. Please use an x, y = data tuple unpack, so you can name the elements. (I would offer multi-character names, except that I don't know what appropriate names would be.) In _write_extracted_data, you again might want to assign a path temp var. Here it might be f"datasets/{path.stem}". context manager, ... would this possibly create conflict with the os trying to access the file? No, it there's no conflict. But I agree with you that this class seems to be doing more than one thing. If the submission included a short test suite or other example calls we might be able to tease out two (or more!) distinct use cases that several classes could specialize in. I have the feeling that the class is doing too much
{ "domain": "codereview.stackexchange", "id": 44682, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, design-patterns, file-system", "url": null }
python, design-patterns, file-system I have the feeling that the class is doing too much Yes, I'm inclined to agree. But it's hard to evaluate without seeing the typical call pattern. Unit tests would go a long way toward illuminating that. Possibly a pair of similar classes would make sense, but it's hard for me to tell based on just the OP. not very happy with the apply function. ... in practice most of the ones passed will manipulate some kind of numpy array, and give as a result also a numpy array. I completely agree with that sentiment. Again, it comes down to examining how callers actually use the API. You proposed a pair of restrictions: that a matrix be passed in, and that a matrix be emitted as the result. I agree. Run your test suite, then impose such restrictions, and verify the tests still run Green. not sure about the extract_data ... Is this a good way to do it? Yes, it looked like a good way to parameterize things to me. Again, """docstrings""" and example calls in a test suite will go a long way toward advising new callers about how to take advantage of what your class offers. In particular, you should carefully explain what the contract for a user-defined function is -- how the input matrix relates to the output matrix, must it be a pure function, when to complain with a fatal raise, those sort of concerns. This code achieves some of its design goals. Adding unit tests wouldn't hurt. Adding """docstrings""" is essential. I would not be willing to delegate or accept maintenance tasks on this codebase in its current form. But it goes deeper than that. I would be reluctant to work on code which uses the HyFile class as a dependency. Why? Low quality documentation. As a caller, it is unclear to me what contracts my inputs must adhere to, and what output behavior I can rely on.
{ "domain": "codereview.stackexchange", "id": 44682, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, design-patterns, file-system", "url": null }
python, design-patterns, file-system EDIT It turns out some unit tests are lurking within a feature branch. An attempt import sample (predictably) fails. Altering sys.path at import time is not a Best Practice. Instead, chdir to the right spot before running, and use the PYTHONPATH env var to affect sys.path. After $ poetry add pytest-cov I got this to work: cd hystorian/tests/ && env PYTHONPATH=.. poetry run pytest --cov --cov-report=term-missing test_io.py ====== test session starts ======= platform darwin -- Python 3.10.10, pytest-7.3.1, pluggy-1.0.0 rootdir: hystorian plugins: typeguard-2.13.3, cov-4.0.0 collected 9 items test_io.py ......... --------- coverage: platform darwin, python 3.10.10-final-0 ---------- Name Stmts Miss Cover Missing ------------------------------------------------------------------- hystorian/hystorian/__init__.py 0 0 100% hystorian/hystorian/io/__init__.py 0 0 100% hystorian/hystorian/io/gsf_files.py 34 4 88% 23-24, 59, 61 hystorian/hystorian/io/hyFile.py 154 72 53% 38, 41-46, 74, 97-98, 109, 113, 135, 139, 141, 152, 158, 168-202, 207, 212-231, 236-261, 272 hystorian/hystorian/io/ibw_files.py 44 39 11% 12-65 test_io.py 83 3 96% 115-116, 133 ------------------------------------------------------------------- TOTAL 315 118 63% ===== 9 passed in 1.45s =====
{ "domain": "codereview.stackexchange", "id": 44682, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, design-patterns, file-system", "url": null }
python, design-patterns, file-system I would typically record such a command in a Makefile, so $ make test will conveniently run it and so newly onboarded engineers will see it and learn from it. Similarly, $ make lint in any of my projects will tend to run something like isort . && black -S . && flake8, perhaps followed by a mypy invocation. Sadly, the usual command of $ pytest tests/*.py does not work, since the tests want to be run from one level down. You will want to add tests/test_files/test.hdf5 to .gitignore I briefly looked at a few tests and I like them, as they are short, boring, simple, and direct, just what we want to see in tests. You might wish to assign a popular constant, such as "datasets/test_data", to a variable. (Or not. Copy-n-paste in test code is perfectly fine, it's the one place you can get away with that.) I have not examined the uncovered lines, e.g. lines 23 and 59, and I would not necessarily shoot for 100% coverage. It's up to you. We spend time writing unit tests in order to save time, both to save an individual contributor time and to save the project time. If you feel covering a line of target code is worthwhile, go for it. If not, that's fine, as well. I tend to view coverage through this lens: Do I still need that line of target code? Why is it "hard" to call it, to cover it? Could I alter the Public API so testing is easier?
{ "domain": "codereview.stackexchange", "id": 44682, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, design-patterns, file-system", "url": null }
c++, performance, algorithm Title: Find a solution to a puzzle with tile squares Question: I wrote a C++ program to find the solution to a puzzle board (a custom puzzle from my school). The puzzle board is made from squares - tiles. On the different tile middle, side or corner there are points (random amount of points). The mission is to construct blocks from tiles, so that each block contains one and only one point and that point has to be the point symmetry point of the block. The mission is to make blocks so that there are no tiles left that are not in a block. But my code takes AGES to run with larger inputs (with a board of size 10x10, it runs for hours - literally), and that is definitely because I don't know how to write time and performance efficient C++ code. I am mainly using a lot of vectors and some custom structs. If you know any ways I can improve my code, give a redo of it or post some good documentation regarding this situation, please let me see! #include <iostream> #include <fstream> #include <sstream> #include <array> #include <vector> #include <algorithm> struct Tile { int x {0}; int y {0}; std::vector<Tile> get_adjacent_fTiles(const std::vector<Tile>& fTiles) const { std::vector<Tile> adjacentTiles {}; for(const auto& tile : fTiles) { if((x == tile.x && y == tile.y - 1) || (x == tile.x + 1 && y == tile.y) || (x == tile.x && y == tile.y + 1) || (x == tile.x - 1 && y == tile.y)) { adjacentTiles.push_back(tile); } } return adjacentTiles; } void print() const { std::cout << "\"" << x << "," << y << "\""; } }; bool operator==(const Tile& tile1, const Tile& tile2) { return (tile1.x == tile2.x && tile1.y == tile2.y); } bool operator!=(const Tile& tile1, const Tile& tile2) { return (tile1.x != tile2.x || tile1.y != tile2.y); } Tile operator+(const Tile& tile1, const Tile& tile2) { return Tile{tile1.x + tile2.x, tile1.y + tile2.y}; }
{ "domain": "codereview.stackexchange", "id": 44683, "lm_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, algorithm", "url": null }
c++, performance, algorithm Tile operator*(int num, const Tile& tile) { return Tile{num * tile.x, num * tile.y}; } Tile operator*(const Tile& tile, int num) { return Tile{num * tile.x, num * tile.y}; } Tile operator*(const Tile& tile1, const Tile& tile2) { return Tile{tile1.x * tile1.x, tile2.x * tile2.y}; } Tile operator/(const Tile& tile, int num) { return Tile{tile.x / num, tile.y / num}; } struct Point { int x; int y; int type; Point(int x, int y) : x(x), y(y) { if(x % 2 == 0 && y % 2 == 0) type = 0; else if(x % 2 != 0 && y % 2 != 0) type = 1; else if(x % 2 != 0 && y % 2 == 0) type = 2; else type = 3; } void print() const { std::cout << "Point" << "(" << x << "," << y << " type: " << type << ")"; } }; bool operator==(const Point& point1, const Point& point2) { return (point1.x == point2.x && point1.y == point2.y); } bool operator!=(const Point& point1, const Point& point2) { return (point1.x != point2.x || point1.y != point2.y); } bool operator==(const Point& point, const Tile& tile) { return (point.x == tile.x && point.y == tile.y); } bool operator==(const Tile& tile, const Point& point) { return (point.x == tile.x && point.y == tile.y); } Tile operator*(const Point& point, const Tile& tile) { return Tile{point.x * tile.x, point.y * tile.y}; } Tile operator*(const Tile& tile, const Point& point) { return Tile{point.x * tile.x, point.y * tile.y}; } Tile operator-(const Point& point, const Tile& tile) { return Tile{point.x - tile.x, point.y - tile.y}; } Tile operator-(const Tile& tile, const Point& point) { return Tile{tile.x - point.x, tile.y - point.y}; } struct Block { Point point {0, 0}; std::vector<Tile> tiles {};
{ "domain": "codereview.stackexchange", "id": 44683, "lm_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, algorithm", "url": null }
c++, performance, algorithm struct Block { Point point {0, 0}; std::vector<Tile> tiles {}; Block(Point point) : point(point) { if(point.type == 0) { tiles.push_back({point.x/10, point.y/10}); } else if(point.type == 1) { tiles.push_back({(point.x+5)/10-1, (point.y+5)/10-1}); tiles.push_back({(point.x+5)/10-1, (point.y+5)/10}); tiles.push_back({(point.x+5)/10, (point.y+5)/10-1}); tiles.push_back({(point.x+5)/10, (point.y+5)/10}); } else if(point.type == 2) { tiles.push_back({(point.x+5)/10-1, point.y/10}); tiles.push_back({(point.x+5)/10, point.y/10}); } else { tiles.push_back({point.x/10, (point.y+5)/10-1}); tiles.push_back({point.x/10, (point.y+5)/10}); } } void add_tile(const Tile& tile) { tiles.push_back(tile); //std::cout << "Tile added\n"; } void expand(const Tile& tile) { add_tile(tile); add_tile((point - 5*tile)/5); //std::cout << "Block expanded\n"; } void remove_tile() { tiles.pop_back(); } void remove_eTile_pair() { tiles.pop_back(); tiles.pop_back(); } std::vector<Tile> get_adjacent_fTiles(const std::vector<Tile>& fTiles) const { std::vector<Tile> adjacentFTiles; for(const auto& tile : tiles) { for(const auto& fTile : tile.get_adjacent_fTiles(fTiles)) { if (std::find(adjacentFTiles.begin(), adjacentFTiles.end(), fTile) == adjacentFTiles.end()) { adjacentFTiles.push_back(fTile); } } } return adjacentFTiles; }
{ "domain": "codereview.stackexchange", "id": 44683, "lm_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, algorithm", "url": null }
c++, performance, algorithm std::vector<Tile> get_expandable_tiles(const std::vector<Tile>& fTiles) const { std::vector<Tile>expandableTiles {}; std::vector<Tile> test = get_adjacent_fTiles(fTiles); for(const auto& fTile1 : get_adjacent_fTiles(fTiles)) { for(const auto& fTile2 : get_adjacent_fTiles(fTiles)) { if((fTile1 != fTile2) && point == 5*(fTile1 + fTile2)) { if (std::find(expandableTiles.begin(), expandableTiles.end(), fTile2) == expandableTiles.end()) { expandableTiles.push_back(fTile1); break; } } } } return expandableTiles; } void print() const { point.print(); std::cout << ": "; for(auto& tile : tiles) { tile.print(); std::cout << " "; } } bool operator==(const Block& block) const { if(point != block.point) return false; if(tiles.size() != block.tiles.size()) return false; for(auto i = 0; i < tiles.size(); i++) { if(tiles[i] != block.tiles[i]) return false; } return true; } bool operator!=(const Block& block) const { if(point != block.point) return true; if(tiles.size() != block.tiles.size()) return true; for(auto i = 0; i < tiles.size(); i++) { if(tiles[i] != block.tiles[i]) return true; } return false; } }; struct Board { int x {0}; int y {0}; std::vector<Block> blocks;
{ "domain": "codereview.stackexchange", "id": 44683, "lm_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, algorithm", "url": null }
c++, performance, algorithm struct Board { int x {0}; int y {0}; std::vector<Block> blocks; std::vector<Tile> get_fTiles() { std::vector<Tile> emptyTiles; emptyTiles.reserve(x * y); for(int i = 0; i < x; i++) { for(int j = 0; j < y; j++) { bool found = false; for(const auto& block : blocks) { if(found) break; for(const auto& tile : block.tiles) { if(i == tile.x && j == tile.y) { found = true; break; } } } if(!found) emptyTiles.push_back({i, j}); } } return emptyTiles; } bool is_expandable() { for(const auto& block : blocks) { if(block.get_adjacent_fTiles(get_fTiles()).size() != 0) return true; } return false; } bool is_finished() { int sum = 0; for(const auto& block : blocks) { for(const auto& tile : block.tiles) { sum++; } } return (sum == x * y); } void print() { std::cout << "---Printing board info---\n"; for(auto& block : blocks) { block.print(); std::cout << '\n'; } std::cout << "Empty tiles: "; for(auto& fTile : get_fTiles()) { fTile.print(); std::cout << " "; } std::cout << "\n---Printing finished---\n"; } bool operator==(const Board& board) const { if(blocks.size() != board.blocks.size()) return false; for(auto i = 0; i < blocks.size(); i++) { if(!(blocks[i] == board.blocks[i])) return false; } return true; } };
{ "domain": "codereview.stackexchange", "id": 44683, "lm_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, algorithm", "url": null }
c++, performance, algorithm Board getBoardData(const std::string& filePath) { std::ifstream dataFile(filePath); Board board; if (dataFile.is_open()) { std::string line; //get board size { std::getline(dataFile, line); std::stringstream ss(line); std::string token; std::getline(ss, token, ','); board.x = std::stoi(token); std::getline(ss, token); board.y = std::stoi(token); } //HERE while(std::getline(dataFile, line)) { std::stringstream ss(line); std::string token; int x = 0; int y = 0; std::getline(ss, token, ','); x = std::stoi(token); std::getline(ss, token, ','); y = std::stoi(token); board.blocks.push_back(Block{Point{x, y}}); } dataFile.close(); } return board; } void generateBoard(Board board, Board& solvedBoard, bool& boardFound) { if(boardFound) { std::cout << "\n\n\nFOUND!!!!!!!!\n\n\n"; return; } for(auto& block : board.blocks) { for(auto& eTile : block.get_expandable_tiles(board.get_fTiles())) { block.expand(eTile); if(board.is_finished()) { solvedBoard = board; boardFound = true; return; } if(!board.is_expandable()) { block.remove_eTile_pair(); return; } //board.print(); generateBoard(board, solvedBoard, boardFound); block.remove_eTile_pair(); } } } Board solveBoard(Board board) { static Board solvedBoard; static bool boardFound; if(board.is_finished()) { return board; } if(!board.is_expandable()) return {}; generateBoard(board, solvedBoard, boardFound); return solvedBoard; }
{ "domain": "codereview.stackexchange", "id": 44683, "lm_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, algorithm", "url": null }
c++, performance, algorithm generateBoard(board, solvedBoard, boardFound); return solvedBoard; } int main() { const std::string filePath = "LitFO70"; Board board = getBoardData(filePath); board.print(); Board solvedBoard = solveBoard(board); std::cout << "FINISHED"; if(!solvedBoard.is_finished()) std::cout << "\nNo solved boards found!"; std::cout << "\nSolved board:\n"; board.print(); return 0; } Answer: Enable compiler warnings and fix all of them Your code compiles, but my compiler warns about comparisons between integers of different kinds. This is because of your use of auto i = 0 in several for-loops. The compiler deduces that 0 is an int, but you want a std::size_t here. The easy fix is to just write std::size_t explicitly: for (std::size_t i = 0; i < tiles.size(); ++i) { … } There is one other warning about an unused variable tile in this piece of code: for(const auto& tile : block.tiles) { sum++; } This whole loop can just be replaced with: sum += block.tiles.size(); Code formatting issues While code style is somewhat of a matter of taste, and the most important thing is just to be consistent, there are some things I think you should avoid. In particular, always put the body of if, for and similar statements on a separate line. This makes it easier to visually spot them. For example, instead of: if(!found) emptyTiles.push_back({i, j}); Write: if(!found) emptyTiles.push_back({i, j}); You might also consider always putting braces around the body of such statements: if(!found) { emptyTiles.push_back({i, j}); }
{ "domain": "codereview.stackexchange", "id": 44683, "lm_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, algorithm", "url": null }
c++, performance, algorithm This avoids making mistakes when adding another statement to the body if the if; if there were no braces and you forget to add them, it's not going to do what you expect. Instead of fixing code formatting issues manually, I recommend you use a formatting tool like ClangFormat or Artistic Style. Naming things I think the names you chose for functions, types and variables are mostly fine. However, just like with code formatting, make sure you are consistent. I see some functions names having snake_case (is_finished()), others have camelCase (getBoardData()). Don't abbreviate unnecessarily, but if you do, be consistent. I see both expandable_tiles and eTiles used. I assumed eTiles meant "expandable tiles", or is it "expanded tiles"? That's already a bit confusing, but what I don't know at all is what the f stands for in fTiles. Or was it because it stands for "empty tiles", but you already used the e for something else, and just went for the next letter in the alphabet? If so, that's pretty terrible! x and y are common names for coordinates, so it's fine to use them. However, they are not the right names for sizes. I would use width and height for that. This will make much more sense in get_fTiles(): std::vector<Tile> emptyTiles; emptyTiles.reserve(width * height); for (int x = 0; x < width; ++x) { for (int y = 0; y < height; ++y) { … if (x == tile.x && y == tile.y) { … } … } }
{ "domain": "codereview.stackexchange", "id": 44683, "lm_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, algorithm", "url": null }
c++, performance, algorithm Make more functions const You made some functions const already, but the member functions of Board can all be made const as well. Missing error checking When reading data from a file, many things can go wrong. Even if the file was opened succesfully, there might be a read error later on. Also, the contents of the file might not be what you expect, so even if reading was succesful, you should not blindly trust what you have read. The best way to check that you have read all data correctly is to check whether dataFile.eof() is true after reading in all lines. If it isn't, you know you didn't reach the end of the file succesfully. What if the width or height you read from the first line is zero, or even a negative number? What happens if you read duplicate points? What if parsing a number fails? If you do encounter an error, make sure you throw an exception, or print an error message to std::cerr, and exit the program with EXIT_FAILURE. Overload operator<<() intead of creating print() member functions Instead of calling your own print() functions, wouldn't it be nice if you could just write: std::cout << "Solved board:\n" << board; You can do that by overloading operator<<() instead of creating your print() member functions: struct Board { … friend std::ostream& operator<<(std::ostream& out, const Board& board) { out << "---Printing board info---\n"; for(auto& block : blocks) { out << block << '\n'; } out << "Empty tiles: "; for(auto& fTile : get_fTiles()) { out << fTile << " "; } return out << "\n---Printing finished---\n"; } };
{ "domain": "codereview.stackexchange", "id": 44683, "lm_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, algorithm", "url": null }
c++, performance, algorithm Note how it is independent of std::cout: now you can also print a board to a std::fstream or to a std::stringstream. Don't make local variables static without a reason In solveBoard(), you made solveBoard and boardFound static. There is no reason to do that, and this makes it non-reentrant and not thread-safe. While that might not matter for this program, I would just remove static. Performance But my code takes AGES to run with larger inputs (with a board of size 10x10, it runs for hours - literally), and that is definitely because I don't know how to write time and performance efficient C++ code.
{ "domain": "codereview.stackexchange", "id": 44683, "lm_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, algorithm", "url": null }
c++, performance, algorithm The problem here is not fine-tuning your code to be faster, the problem is in the algorithms you implemented. Consider for example get_fTiles(): you want a list of all the empty tiles. You do this by checking for every possible tile position, if there is a block that contains a tile with that exact position. That's already pretty bad: this takes \$O(W \cdot H \cdot B \cdot T)\$ time, where \$W\$ is width, \$H\$ is height, \$B\$ is the number of blocks and \$T\$ is the number of tiles per block. For a 10 by 10 board, that's probably in the order of 10000 operations. It also has to allocate memory for the vector of empty tiles and put the Tiles in it. Then you call block.get_adjacent_fTiles(get_fTiles()). This checks for every tile in the block, if one of the tiles in the empty list of tiles is adjacent to that tile, and if it wasn't already in adjacentFTiles, adds it. If the block contained just a few tiles, you were checking against many empty tiles that were not even close to it. If there are many tiles in the block, you might see a lot of duplicate adjacent tiles. This adds a few factors of 10 more to the number of opreations to do on a 10 by 10 board. You also created several more vectors to store tiles in. But here comes the kicker: in is_expandable(), you then just check if block.get_adjacent_fTiles(get_fTiles()).size() != 0. So after all that tedious work creating vectors of empty and adjacent tiles, you just wanted to know: was there at least 1 adjactend empty tile? So you didn't actually need to store all that tile information! And then you call is_expandable() inside a double for-loop inside generateBoard(). Every for-loop multiplies the amount of work that needs to be done. This is why your code takes such a huge amount of time to solve just a 10 by 10 board.
{ "domain": "codereview.stackexchange", "id": 44683, "lm_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, algorithm", "url": null }
c++, performance, algorithm So how can you improve this? You have to rethink the way you are doing things, and find algorithms that don't require this many loops, and don't need that many temporary std::vectors to store data in. Consider for example of maintaining an array that stores whether board tiles are empty or not: struct Board { int width{}; int height{}; std::vector<Block> blocks; std::vector<bool> occupied_tiles; … };
{ "domain": "codereview.stackexchange", "id": 44683, "lm_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, algorithm", "url": null }
c++, performance, algorithm Board getBoardData(const std::string& filePath) { … board.occupied_tiles.resize(board.width * board.height); … board.blocks.push_back(Block{Point{x, y}}); occupied_tiles[x + y * board.width] = true; }; Then checking whether a given tile is empty or not is simply reading from occupied_tiles, instead of having go through every tile in every block. This might not be the only thing that can be improved in your code, but this is generally the kind of thinking you have to do in order to get your algorithm to run faster. Create proper classes You created several structs to organize your data, which is great. However, all members are public, and you have several non-member functions that directly modify the member variables of those structs. The problem with that is that is doesn't provide proper encapsulation. Ideally, you create classes (which are just structs where everything is private by default), and only allow the member variabels to be modified via public member functions. These member functions can then ensure the state of an object of that class is always correct. It also forces you to think about what operations are going to be done on objects, and makes it more clear when you perform those operations. For example, instead of getBoardData() directly accessing the member variables, it would be better to write it like so: Board getBoardData(const std::string& filePath) { std::ifstream dataFile(filePath); std::string line; int width; int height; // Get board size { … } Board board(width, height); // Read blocks while(std::getline(dataFile, line)) { … board.add_block(Point{x, y}); } if(!dataFile.eof()) { throw std::runtime_error("Could not read input file!"); } return board; }
{ "domain": "codereview.stackexchange", "id": 44683, "lm_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, algorithm", "url": null }
python, python-3.x, converting, networking Title: Python script that identifies the country code of a given IP address Question: This is a Python script I wrote to identify the country code of a given IP address, using data obtained from tor. It uses geoip.txt to identify country code for IPv4 addresses, and geoip6.txt to do so for IPv6 addresses. This is done by converting the address to an integer, then find the index of the starting IP address of IP ranges for that IP type closest to the integer, by binary search using bisect.bisect. Then check the ending IP address of IP ranges located at that index, if the integer is no greater than the ending IP address, return the corresponding country code located at the index. I wrote the script both as a programming challenge and as a library to be used by later scripts. I have specifically chosen not to use ipaddress module, instead I wrote custom functions to convert IPv4 and IPv6 to int and back. And I have benchmarked my code against ipaddress module, and I found my code to be more time-efficient. The code: import re from bisect import bisect MAX_IPV4 = 2**32-1 MAX_IPV6 = 2**128-1 DIGITS = set('0123456789abcdef') le255 = '(25[0-5]|2[0-4]\d|[01]?\d\d?)' IPV4_PATTERN = re.compile(f'^({le255}\.){{3}}{le255}$') EMPTY = re.compile(r':?\b(?:0\b:?)+') def parse_ipv4(ip: str) -> int: assert isinstance(ip, str) and IPV4_PATTERN.match(ip) a, b, c, d = ip.split('.') return (int(a) << 24) + (int(b) << 16) + (int(c) << 8) + int(d) def to_ipv4(n: int) -> str: assert isinstance(n, int) and 0 <= n <= MAX_IPV4 return ".".join(str(n >> i & 255) for i in range(24, -1, -8))
{ "domain": "codereview.stackexchange", "id": 44684, "lm_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, converting, networking", "url": null }
python, python-3.x, converting, networking def parse_ipv6(ip: str) -> int: assert isinstance(ip, str) and len(ip) <= 39 segments = ip.lower().split(":") l, n, p, fields, compressed = len(segments), 0, 7, 0, False last = l - 1 for i, s in enumerate(segments): assert fields <= 8 and len(s) <= 4 and not set(s) - DIGITS if not s: if i in (0, last): continue assert not compressed p = l - i - 2 compressed = True else: n += int(s, 16) << p*16 p -= 1 fields += 1 return n def to_ipv6(n: int, compress: bool = False) -> str: assert isinstance(n, int) and 0 <= n <= MAX_IPV6 ip = '{:032_x}'.format(n).replace('_', ':') if compress: ip = ':'.join(s.lstrip('0') if s != '0000' else '0' for s in ip.split(':')) longest = max(EMPTY.findall(ip)) if len(longest) > 2: ip = ip.replace(longest, '::', 1) return ip def parse_entry4(e: str) -> tuple: a, b, c = e.split(",") return (int(a), int(b), c) def parse_entry6(e: str) -> tuple: a, b, c = e.split(",") return (parse_ipv6(a), parse_ipv6(b), c) with open("D:/network_guard/geoip.txt", "r") as file: data4 = list(map(parse_entry4, file.read().splitlines())) starts4, ends4, countries4 = zip(*data4) with open("D:/network_guard/geoip6.txt", "r") as file: data6 = list(map(parse_entry6, file.read().splitlines())) starts6, ends6, countries6 = zip(*data6) class IP: parse = [parse_ipv4, parse_ipv6] starts = [starts4, starts6] ends = [ends4, ends6] countries = [countries4, countries6] def geoip_country(ip: str, mode: int=0) -> str: assert mode in {0, 1} n = IP.parse[mode](ip) if not (i := bisect(IP.starts[mode], n)): return False i -= 1 return False if n > IP.ends[mode][i] else IP.countries[mode][i]
{ "domain": "codereview.stackexchange", "id": 44684, "lm_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, converting, networking", "url": null }
python, python-3.x, converting, networking if __name__ == '__main__': ipv6s = [ '2404:6800:4003:c03::88', '2404:6800:4004:80f::200e', '2404:6800:4006:802::200e', '2607:f8b0:4004:800::200e', '2607:f8b0:4005:801::200e', '2607:f8b0:4006:81c::200e', '2607:f8b0:4006:822::200e', '2607:f8b0:4006:823::200e', '2607:f8b0:4006:824::200e', '2607:f8b0:400a:809::200e', '2800:3f0:4001:80b::200e', '2a00:1450:400b:c01::be' ] ipv4s = [ '74.125.24.93', '74.125.24.136', '74.125.24.190', '74.125.68.91', '74.125.68.93', '74.125.68.136', '74.125.193.91', '74.125.193.93', '74.125.193.136', '74.125.193.190', '74.125.200.91', '142.250.64.78' ] for ipv4 in ipv4s: n = parse_ipv4(ipv4) print(ipv4, n, to_ipv4(n), geoip_country(ipv4)) for ipv6 in ipv6s: n = parse_ipv6(ipv6) print(ipv6, n, to_ipv6(n, 1), geoip_country(ipv6, 1))
{ "domain": "codereview.stackexchange", "id": 44684, "lm_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, converting, networking", "url": null }
python, python-3.x, converting, networking Output: 74.125.24.93 1249712221 74.125.24.93 US 74.125.24.136 1249712264 74.125.24.136 US 74.125.24.190 1249712318 74.125.24.190 US 74.125.68.91 1249723483 74.125.68.91 US 74.125.68.93 1249723485 74.125.68.93 US 74.125.68.136 1249723528 74.125.68.136 US 74.125.193.91 1249755483 74.125.193.91 US 74.125.193.93 1249755485 74.125.193.93 US 74.125.193.136 1249755528 74.125.193.136 US 74.125.193.190 1249755582 74.125.193.190 US 74.125.200.91 1249757275 74.125.200.91 US 142.250.64.78 2398765134 142.250.64.78 US 2404:6800:4003:c03::88 47875086426100614638538221612324356232 2404:6800:4003:c03::88 AU 2404:6800:4004:80f::200e 47875086426101804896252833647432835086 2404:6800:4004:80f::200e AU 2404:6800:4006:802::200e 47875086426104222508084389947558076430 2404:6800:4006:802::200e AU 2607:f8b0:4004:800::200e 50552053919386769199309343019258355726 2607:f8b0:4004:800::200e US 2607:f8b0:4005:801::200e 50552053919387978143575701722142613518 2607:f8b0:4005:801::200e US 2607:f8b0:4006:81c::200e 50552053919389187567457406341475213326 2607:f8b0:4006:81c::200e US 2607:f8b0:4006:822::200e 50552053919389187678137870783732523022 2607:f8b0:4006:822::200e US 2607:f8b0:4006:823::200e 50552053919389187696584614857442074638 2607:f8b0:4006:823::200e US 2607:f8b0:4006:824::200e 50552053919389187715031358931151626254 2607:f8b0:4006:824::200e US 2607:f8b0:400a:809::200e 50552053919394022920247727457692557326 2607:f8b0:400a:809::200e US 2800:3f0:4001:80b::200e 53169199713192736830836323499043201038 2800:3f0:4001:80b::200e AR 2a00:1450:400b:c01::be 55827987829231936335941766789076091070 2a00:1450:400b:c01::be IE It is indeed working, but I want my code to be more concise and efficient, and more Pythonic. How can I do so? (P.S. I also generated a version with documentation using mintlify just for the gigs, I am not responsible for most of the docs, I just pressed CTRL+. in Visual Studio Code, but I edited here and there. As it is way too verbose I uploaded it to Google Drive)
{ "domain": "codereview.stackexchange", "id": 44684, "lm_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, converting, networking", "url": null }
python, python-3.x, converting, networking Answer: The syntax for :: IPv6 addresses can be a bit involved. You chose to go it alone, to avoid using an existing well-tested parsing library. I predict you will want to revisit that choice. We see that a Public API has been defined here. But it is not documented, beyond annotated signatures. We need to see """docstrings""" on these. Cite your references. Perhaps there is an RFC you strive to conform to? IPV4_PATTERN = re.compile(f'^({le256}\.){{3}}{le256}$') This is very nice, kudos on DRYing it up. le256 = '(25[0-5]|2[0-4]\d|[01]?\d\d?)' This "less than or equal to 256", OTOH, impresses me as the Wrong approach. Use the right tool for the job. Parse out digits with a regex, and then evaluate whether integer A <= B using other language facilities. The name is definitely wrong and should be fixed -- it appears that Author's Intent was lt256 (or perhaps le255). The DIGITS identifier is kind of OK. But consider renaming it to HEXDIGITS. I'm a little sad that parse_ipv4 and to_ipv4 do not have parallel structure. That is, the parse is accomplished with a manually unrolled loop, while the inverse is a bit more elegant due to the explicit loop. A single assert, executed four times, would be a natural way to express that we want a 0 <= n < 256 byte value. The type annotations are lovely; I thank you. Right, let's parse an IPv6! l, n, p, fields, compressed = len(segments), 0, 7, 0, False
{ "domain": "codereview.stackexchange", "id": 44684, "lm_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, converting, networking", "url": null }
python, python-3.x, converting, networking Right, let's parse an IPv6! l, n, p, fields, compressed = len(segments), 0, 7, 0, False No, please don't do that. Yes, it is shorter. No, it does not help the Gentle Reader understand what's going on. Saving four SLOC just isn't worth it. Also, l is clearly "length", but I don't know how I'm supposed to mentally pronounce p. Maybe rename it to pos for "position"? Could we perhaps find a more specific name? Pep-8 advises you to choose a different spelling for your length variable. Repeatedly asserting not set(s) - DIGITS works. But it seems more convenient to do that character set validation just once on the whole string up front. Consider renaming s to seg. Overall, this just isn't a very nice function to work with. It is doing more than one thing, and those things are interleaved across loop iterations. Consider reworking this function to split work into three phases: check there's only valid characters normalize, so there's no :: abbreviations convert to integer As written, passing in the "" empty string returns zero. I guess that is kind of correct? But I am reluctant to say the empty string is a valid IPv6 address. In any event it certainly isn't the all-zeros broadcast address, since there isn't one, with ff02::1 multicasts taking on that role. When converting back to string, it's not clear that the anti-pattern of checking isinstance(n, int) really does anything for us. Duck typing suffices, given that we immediately compare against zero and then use a hex format. The type annotated signature is spelling this out very clearly for mypy and for humans. Consider embracing the duck, and removing isinstance from four functions. ip = ':'.join(s.lstrip('0') if s != '0000' else '0' for s in ip.split(':'))
{ "domain": "codereview.stackexchange", "id": 44684, "lm_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, converting, networking", "url": null }
python, python-3.x, converting, networking No, this expression is not maintainable. It is correct, sure, but that's uninteresting. Break out a named helper, which can be called by a unit test. This appears to produce the wrong answer, one which is too short: to_ipv6(parse_ipv6("")) It seems that Author's Intent was a format string of '{:039_x}' The entry{4,6} parsing belongs in a separate module, as those functions are about a separate concept. We have moved from generic IP addresses to GeoIP-specific file formats. with open("D:/network_guard/geoip.txt", ... Avoid doing such work at a module's toplevel. Why? So a unit test doing an import of this code cannot fail with FileNotFoundError. Prefer to bury this code in a function that can be called when needed. You (very nicely) wrote a __main__ guard with similar motivation, to avoid side effects at import time. class IP: This is a great class name. Consider creating IPv4 and IPv6 classes which conform to a contract specified by an abstract base class. def geoip_country(ip: str, mode: int=0) -> str: The mode identifier is rather vague. The intent here is ip_type or ip_version. Given that we won't be using the integers 4 or 6, this should probably be an enum. return False No. You just told me, a few lines up, that you shall return str, and bool is not a string. Also, prefer to return None instead of False, if for some reason you feel "" empty string is not a good match for your use case. So the signature would end with: ...) -> Optional[str]: print(ipv6, n, to_ipv6(n, 1), geoip_country(ipv6, 1)) No. You told me in the signature that callers should instead say this: print(ipv6, n, to_ipv6(n, True), geoip_country(ipv6, 1))
{ "domain": "codereview.stackexchange", "id": 44684, "lm_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, converting, networking", "url": null }
python, python-3.x, converting, networking This codebase achieves a subset of its design goals. It works correctly on a portion of the input space. It is less well tested and documented than competing libraries. This codebase curiously avoids a uniform representation of an IP address as a byte vector, preferring to work with strings and large integers. I would be willing to accept, but not delegate, maintenance tasks on this codebase in its current form. Things that should be addressed sooner than later are lack of docstrings lack of unit tests cryptic identifiers I just took a look at the mintlify output. It's a utility I had never heard of. The text it generates is just terrible, similar to i += 1 # increment the value of index i by exactly one Recommend that you not use it in coding projects. Write a single sentence for each docstring, optionally followed by blank line and a paragraph. Do consider using doctest, where you append ">>> some(expression)" and its result. The trouble with comments is that sometimes they lie, they get out of sync with evolving code edits. The brilliant thing about doctest comments is they verifiably tell the truth, even after edits.
{ "domain": "codereview.stackexchange", "id": 44684, "lm_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, converting, networking", "url": null }
c, linked-list Title: Generic Doubly-Linked-Lists C implementation Question: I'm trying to build step by step a C library that will include some of the major Data Structures such as Linked Lists, Stacks, Binary Trees etc., mostly in order to practice my C programming skills and study new concepts. I have posted previously about my implementation of a doubly linked list, and it had a bunch of suggestions on how to improve the code (my last post). I have worked a lot in order to fix them and I would like to recieve a kind of follow up review to be clear that I handled those problems mentioned in the proper way. The major changes are: Removed typedefs that hide pointers. Removed repetetive documentation & improved clarity. Fixed bug on deletion of head. Added a file for testing. Returning values to indicate success or failure of actions such as getting an element deleting etc. Inconsistency in function definitions Naming conventions There are some issues that aren't solved yet, most significant is the lack of meaning to the "doubly" property of the list, but I will add that soon. Though I believe it is enough changes in order to get a feedback. Here's the updated code with the tests file: DLList.h /* Implements doubly linked list. ---------- ---------- ---------- | HEAD | <------> | NODE | <------> | TAIL | ---------- ---------- ---------- The linked list is generic and may hold any kind of pointer (from the same type!) given a proper constructor function for that type. Created by: @BAxBI as part of General DataStructure library for C. */ #ifndef __DLLIST__H_ #define __DLLIST__H_ #include <stddef.h> typedef enum {false = 0, true = 1} bool;
{ "domain": "codereview.stackexchange", "id": 44685, "lm_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, linked-list", "url": null }
c, linked-list typedef enum {false = 0, true = 1} bool; /* Creates a new empty linked list @param ctor Pointer to a constructor function for an element in the list. @param dtor Pointer to a destructor function for an element in the list. @param compare Pointer to a comparison function between two elements in the list @param print Pointer to a print function of an element in the list. @return Pointer to an emty linked list */ struct DLList *DLList_new(void * (*ctor)(void *),void (*dtor)(void *), int (*compare)(const void *, const void *), void (*print)(void *)); /* Adds a node to the head of the list. @returns 1 if added successfuly 0 otherwise. */ int DLList_add(struct DLList *list, void * const item); /* Deletes the first occurrence of an item in the list. @return 1 if deleted successfuly 0 otherwise. */ int DLList_delete(struct DLList *list, void * const item); /* Destroys a linked list and frees all the allocated memory. @return 1 if destroyed successfuly 0 otherwise. */ int DLList_destroy(struct DLList *list); /* Gets an element from the Linked List. @param success A pointer to int, will be set to 1 upon sucess 0 otherwise. */ void * DLList_get_item(const struct DLList *list, void * const element, int *success); /* Gets the number of elements in the linked list. */ size_t DLList_No_items(const struct DLList * const list); /* Prints the linked list (if given a print function to print a single element!) */ void DLList_print(const struct DLList * const list); #endif DDList.c #include "DLList.h" #include <stdlib.h> #include <stdio.h> typedef struct Node{ struct Node *prev_node; struct Node *next_node; void * node_content; }Node; struct DLList { Node *head; Node *tail; size_t NoElements; // Functions provided by the client. void * (*ctor)(void *); void (*dtor)(void *); int (*compare)(const void *, const void *); void (*print)(void *); };
{ "domain": "codereview.stackexchange", "id": 44685, "lm_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, linked-list", "url": null }
c, linked-list struct DLList *DLList_new(void * (*ctor)(void *),void (*dtor)(void *), int (*compare)(const void *, const void *), void (*print)(void *)){ struct DLList *new_dllist = malloc(sizeof(*new_dllist)); if (!new_dllist){ return NULL; } new_dllist->head = NULL; new_dllist->tail = NULL; new_dllist->NoElements = 0; new_dllist->ctor = ctor; new_dllist->dtor = dtor; new_dllist->compare = compare; new_dllist->print = print; return new_dllist; } int DLList_add(struct DLList *list, void * const item){ if(!list->ctor) return false; // If constructor is not provided. Node *new_node = malloc(sizeof(*new_node)); if (!new_node) return false; new_node->next_node = NULL; new_node->prev_node = NULL; new_node->node_content = list->ctor(item); /* Empty list*/ if(!list->head){ list->head = new_node; list->tail = new_node; } else { new_node->next_node = list->head; list->head->prev_node = new_node; list->head = new_node; } list->NoElements++; return true; }
{ "domain": "codereview.stackexchange", "id": 44685, "lm_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, linked-list", "url": null }
c, linked-list /* Deletes first occurence of a node in a linked list */ int DLList_delete(struct DLList *list, void * const item){ Node *ptr = list->head; while(ptr != NULL){ if(list->compare(ptr->node_content, item) == 0){ /* First node to be deleted */ if(!ptr->prev_node){ list->head = ptr->next_node; if(ptr->next_node){ ptr->next_node->prev_node = NULL; } } else if(ptr->prev_node && ptr->next_node){ ptr->next_node->prev_node = ptr->prev_node; ptr->prev_node->next_node = ptr->next_node; } else { ptr->prev_node->next_node = NULL; } if(list->dtor){ list->dtor(ptr->node_content); } free(ptr); list->NoElements--; return true; } ptr = ptr->next_node; } return false; } int DLList_destroy(struct DLList * list){ if(list){ Node *ptr = list->head; while(ptr != NULL){ Node *tmp = ptr; ptr = ptr->next_node; if(list->dtor){ list->dtor(tmp->node_content); } free(tmp); } free(list); return true; } else{ return true; } } void * DLList_get_item(const struct DLList *list, void * const element, int *success){ Node *ptr = list->head; if(!list->head){ printf("The list is empty!\n"); *success = false; } while(ptr!=NULL){ if(list->compare(ptr->node_content, element) == 0){ *success = true; return ptr->node_content; } ptr = ptr->next_node; } *success = false; return NULL; } size_t DLList_No_items(const struct DLList *const list){ return list->NoElements; }
{ "domain": "codereview.stackexchange", "id": 44685, "lm_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, linked-list", "url": null }
c, linked-list size_t DLList_No_items(const struct DLList *const list){ return list->NoElements; } void DLList_print(const struct DLList * const list){ if(!list->print) { printf("The linked list provided doesn't have print function\n"); return; } if (!list->head) { printf("The list is empty!\n"); return; } Node *ptr = list->head; while(ptr){ list->print(ptr->node_content); if(ptr->next_node){ printf(" <---> "); } else{ printf(" ---> "); } ptr = ptr->next_node; } printf("NULL\n"); } DLList_test.c #include "DLList.h" #include <stdio.h> #include <unistd.h> #include <setjmp.h> #include <stdlib.h> #include <string.h> #include <math.h> #include <limits.h> #ifdef assert #undef assert #endif #define assert(x) (result = result && (x)) //Static variables static int result; static int expected_code; static int should_exit; static jmp_buf jump_env; static int done; static int num_tests; static int tests_passed; void test_start(char *name){ num_tests++; result = 1; printf("-- Testing %s ...", name); } void test_end(){ if (result) tests_passed++; printf("%s\n", result ? " success" : " fail"); } void exit(int code){ if (!done){ assert(should_exit==1); assert(expected_code==code); longjmp(jump_env, 1); } else{ _exit(code); } } /** Vector3d for testing **/ struct Vector3d{ /* data */ int x; int y; int z; }; void *ctor(void *item){ struct Vector3d *vector = malloc(sizeof(*vector)); if(vector){ memcpy(vector, item, sizeof(struct Vector3d)); } return vector; } void dtor(void *item){ free(item); }
{ "domain": "codereview.stackexchange", "id": 44685, "lm_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, linked-list", "url": null }
c, linked-list void dtor(void *item){ free(item); } int compare(const void *item1, const void *item2){ struct Vector3d *elem1 = (struct Vector3d *)item1; struct Vector3d *elem2 = (struct Vector3d *)item2; if(elem1 == NULL || elem2 == NULL){ return INT_MIN; } float size1 = sqrt(elem1->x*elem1->x + elem1->y*elem1->y + elem1->z*elem1->z); float size2 = sqrt(elem2->x*elem2->x + elem2->y*elem2->y + elem2->z*elem2->z); return (size1 > size2) - (size1 < size2); } void print_vector3d(void *item){ printf("(%d, %d, %d)", ((struct Vector3d *)item)->x ,((struct Vector3d *)item)->y, ((struct Vector3d *)item)->z); } /*** Testing Cases ***/ // Testing creation of DLList void DLList_new_t(){ int f; struct DLList *my_list = DLList_new(ctor, dtor, compare, print_vector3d); test_start("Creation of DDList"); should_exit = 1; if(my_list) f = 1; assert(f == 1); DLList_destroy(my_list); test_end(); } void destroy_empty_list(){ test_start("Destroy an empty list"); should_exit = 1; assert(DLList_destroy(NULL) == true); test_end(); } void DLList_add_elements(){ struct DLList *my_list = DLList_new(ctor, dtor, compare, print_vector3d); struct Vector3d vector1, vector2; vector1.x = 5, vector1.y = 5, vector1.z = 5; vector2.x = 10, vector2.y = 10, vector2.z = 5; test_start("Add first node"); should_exit = 1; assert(DLList_add(my_list, &vector1) == true); assert(DLList_add(my_list, &vector2) == true); DLList_destroy(my_list); test_end(); } void DLList_delete_head(){ struct DLList *my_list = DLList_new(ctor, dtor, compare, print_vector3d); struct Vector3d vector1 = {0}, vector2 = {0}, vector3 = {0}; vector1.x = 5, vector1.y = 5, vector1.z = 5; vector2.x = 10, vector2.y = 10, vector2.z = 5; vector3.x = 10, vector3.y = 20, vector3.z = 5;
{ "domain": "codereview.stackexchange", "id": 44685, "lm_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, linked-list", "url": null }
c, linked-list test_start("Head deletion"); should_exit = 0; DLList_add(my_list, &vector1); DLList_add(my_list, &vector2); DLList_add(my_list, &vector3); assert(DLList_delete(my_list, &vector3) == true); DLList_destroy(my_list); test_end(); } void DLList_delete_tail(){ struct DLList *my_list = DLList_new(ctor, dtor, compare, print_vector3d); struct Vector3d vector1, vector2, vector3; vector1.x = 5, vector1.y = 5, vector1.z = 5; vector2.x = 10, vector2.y = 10, vector2.z = 5; vector3.x = 10, vector2.y = 20, vector2.z = 5; test_start("Tail deletion"); should_exit = 0; DLList_add(my_list, &vector1); DLList_add(my_list, &vector2); DLList_add(my_list, &vector3); assert(DLList_delete(my_list, &vector1) == true); DLList_destroy(my_list); test_end(); } void DLList_delete_middle(){ struct DLList *my_list = DLList_new(ctor, dtor, compare, print_vector3d); struct Vector3d vector1, vector2, vector3; vector1.x = 5, vector1.y = 5, vector1.z = 5; vector2.x = 10, vector2.y = 10, vector2.z = 5; vector3.x = 10, vector2.y = 20, vector2.z = 5; test_start("Node in the middle deletion"); should_exit = 1; DLList_add(my_list, &vector1); DLList_add(my_list, &vector2); DLList_add(my_list, &vector3); assert(DLList_delete(my_list, &vector2) == true); DLList_destroy(my_list); test_end(); } void DLList_delete_not_in_list(){ struct DLList *my_list = DLList_new(ctor, dtor, compare, print_vector3d); struct Vector3d vector1, vector2, vector3; vector1.x = 5, vector1.y = 5, vector1.z = 5; vector2.x = 10, vector2.y = 10, vector2.z = 5; vector3.x = 10, vector2.y = 120, vector2.z = 5; test_start("Node not in the list deletion"); should_exit = 1; DLList_add(my_list, &vector1); DLList_add(my_list, &vector2); assert(DLList_delete(my_list, &vector3) == false); DLList_destroy(my_list); test_end(); }
{ "domain": "codereview.stackexchange", "id": 44685, "lm_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, linked-list", "url": null }
c, linked-list void DLList_delete_not_matching_obj(){ struct DLList *my_list = DLList_new(ctor, dtor, compare, print_vector3d); struct Vector3d vector1, vector2; vector1.x = 5, vector1.y = 5, vector1.z = 5; vector2.x = 10, vector2.y = 10, vector2.z = 5; test_start("Delete not matching object"); should_exit = 1; DLList_add(my_list, &vector1); DLList_add(my_list, &vector2); int variable = 5; assert(DLList_delete(my_list, &variable) == false); DLList_destroy(my_list); test_end(); } void DLList_add_not_matching_obj(){ struct DLList *my_list = DLList_new(ctor, dtor, compare, print_vector3d); int num = 5; test_start("Add not matching object"); should_exit = 1; assert(DLList_add(my_list, &num) == false); DLList_destroy(my_list); test_end(); } int main(void){ num_tests = 0; tests_passed = 0; done = 0; // Running the tests printf("============================================="); printf("\n--- DLList Tests --- \n"); DLList_new_t(); destroy_empty_list(); DLList_add_elements(); DLList_delete_head(); DLList_delete_tail(); DLList_delete_middle(); DLList_delete_not_in_list(); printf("Total tests passed: %d\n", tests_passed); printf("============================================\n"); done = 1; return !(tests_passed == num_tests); return 0; }
{ "domain": "codereview.stackexchange", "id": 44685, "lm_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, linked-list", "url": null }
c, linked-list return 0; } Answer: Much improvement over early question. Object pointer v. function pointers Goal needs modifications: "The linked list is generic and may hold any kind of pointer ..." --> "The linked list is generic and may hold any kind of object pointer ...". Functions pointers may be wider than void pointers and so lose information when converted to void *. void * is a useful universal object pointer. C lacks a true universal pointer. Why double linked list? So far, no usage of using the link-list in the reverse direction. Use standard bool Rather than typedef enum {false = 0, true = 1} bool;, use bool from <stdbool.h> const parameters not needed in function declarations It is just noise. // void * DLList_get_item(const struct DLList *list, void * const element, int *success); void * DLList_get_item(const struct DLList *list, void * element, int *success); bool functions For functions that return true/false, use bool // int DLList_add(struct DLList *list, void * const item){ bool DLList_add(struct DLList *list, void * const item){ ... return false; ... return true; } Error message vs. error code Rather than print an error message, drop it. Function already conveys the error via *success. void * DLList_get_item(const struct DLList *list, void * const element, int *success){ Node *ptr = list->head; if(!list->head){ // printf("The list is empty!\n"); *success = false; } ... If still wanting an error message, use stderr. // printf("The list is empty!\n"); fprintf(stderr, "The list is empty!\n"); Next: Consider an apply function This applies the passed in function to each list node data. Only stopping early when the function returns non-zero. int DLList_apply(const struct DLList * list, int (*f)(void *state, void *node_content), void *state) { // Pseudo code for each item in the linked list int result = f(state, item->node_content); if (result != 0) return result; } return 0; }
{ "domain": "codereview.stackexchange", "id": 44685, "lm_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, linked-list", "url": null }
c, linked-list This can serve as the basis for a replacement for DLList_print() which only does a particular print. Test code: Avoid casting away const // int compare(const void *item1, const void *item2){ struct Vector3d *elem1 = (struct Vector3d *)item1; struct Vector3d *elem2 = (struct Vector3d *)item2; int compare(const void *item1, const void *item2){ const struct Vector3d *elem1 = item1; const struct Vector3d *elem2 = item2; Test code: Save double to double Unclear why code saves a double to float // float size1 = sqrt(... double size1 = sqrt(... // OR //Preform a `float` calculation float size1 = sqrtf(... Test code: FP math not needed Code risk int overflow. square root not needed. Alternate; long long size1 = 1LL*elem1->x*elem1->x + 1LL*elem1->y*elem1->y + elem1->z*elem1->z; long long size2 = 1LL*elem2->x*elem2->x + 1LL*elem2->y*elem2->y + 1LL*elem2->z*elem2->z;
{ "domain": "codereview.stackexchange", "id": 44685, "lm_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, linked-list", "url": null }
sorting, rust Title: Sort by parity in rust Question: I am learning sorting in rust. I want to sort vector as such that even numbers go first My code is OK. But can it be improved (I want to use sort function)? fn main() { let mut v = vec![1, 2, 10, 4, 3]; v.sort_by(|a, b | { (a % 2).cmp(&(b % 2)) }); println!("{:?}", v); // [1, 2, 10, 4, 3] } Answer: Partition the Array This is the standard example of std::iter::Iterator::partition. There is also a nightly experimental partition_in_place. let (even, odd): (Vec<_>, Vec<_>) = a .into_iter() .partition(|n| n % 2 == 0); This runs in O(N) time, while sorting takes O(N log N) time. If you want the even and odd collections to be sorted (which this doesn’t do), it’s more efficient to partition and then sort the sub-arrays. Sorting has worse-than-linear time complexity, so it’s better to sort two partitions than one large array.
{ "domain": "codereview.stackexchange", "id": 44686, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "sorting, rust", "url": null }
c++, serialization Title: Binary (de)serialization library for c++ Question: A while ago I posted the code for this library I'm working on, and have refactored the code quite a bit ever since. I would appreciate any feedback in regards to what I have so far to see what can I improve still. binaryio/reader.h #include <iostream> #include <ranges> #include <stdexcept> #include <string> #include <vector> #include "binaryio/swap.h" #ifndef BINARYIO_READER_H #define BINARYIO_READER_H namespace binaryio { class BinaryReader { std::istream& is; public: BinaryReader(std::istream& is) : is{is} {} BinaryReader(std::istream& is, endian byte_order) : is{is}, m_endian{byte_order} {} void seek(std::size_t offset, std::ios_base::seekdir seek_dir = std::ios_base::beg) { is.seekg(offset, seek_dir); } std::size_t tell() { return is.tellg(); } template <typename T> T read() requires (!std::is_pointer_v<T> && std::is_trivially_copyable_v<T>) { T val; _do_read(val); return val; } template <typename T> std::vector<T> read_many(const std::size_t count) requires (!std::is_pointer_v<T> && std::is_trivially_copyable_v<T>) { std::vector<T> vals(count); _do_read(vals); return vals; } std::string read_string(const std::string::size_type max_len = std::string::npos) { std::string str; if (max_len == std::string::npos) return str; char arr[max_len]; is.getline(arr, max_len, '\0'); str = arr; return str; } endian endianness() const { return m_endian; } void set_endianness(endian new_endian) { m_endian = new_endian; } void swap_endianness() { if (m_endian == endian::big) m_endian = endian::little; else m_endian = endian::big; } private: endian m_endian {endian::native};
{ "domain": "codereview.stackexchange", "id": 44687, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, serialization", "url": null }
c++, serialization private: endian m_endian {endian::native}; template <typename T> void _do_read(T& val) { if (!is.read(reinterpret_cast<char*>(&val), sizeof val)) throw std::out_of_range("out of bounds read"); swap_if_needed_in_place(val, m_endian); } template <class Range, typename T = typename Range::value_type> void _do_read(Range& vals) requires (std::ranges::output_range<Range, T>) { if (!is.read(reinterpret_cast<char*>(vals.data()), vals.size() * sizeof(T))) throw std::out_of_range("out of bounds read"); for (auto& val : vals) swap_if_needed_in_place(val, m_endian); } }; } // namespace binaryio #endif binaryio/swap.h #include <bit> #include <cstring> #include <tuple> #include <type_traits> #include "binaryio/type_utils.h" #ifndef BINARYIO_SWAP_H #define BINARYIO_SWAP_H namespace binaryio { using endian = std::endian; // Bitswap the bytes of a value template <typename T> constexpr void swap(T& value) { if (sizeof(T) == 1) return; std::array<char, sizeof(T)> data; std::memcpy(data.data(), &value, sizeof(T)); for (int i{0}; i < sizeof(T)/2; ++i) std::swap(data[sizeof(T) - 1 - i], data[i]); std::memcpy(&value, data.data(), sizeof(T)); } /// Swap a value if its endianness is not the same as the machine endianness. /// @param endian The endianness of the value. template <typename T> void swap_if_needed_in_place(T& value, endian endian) { if (endian::native == endian) return; if constexpr (std::is_arithmetic<T>()) { swap(value); } if constexpr (exposes_fields<T>) { std::apply( [endian](auto&... fields) { (swap_if_needed_in_place(fields, endian), ...); }, value.fields()); } if constexpr (is_container<T>) { for (auto& val : value) swap(val); } }
{ "domain": "codereview.stackexchange", "id": 44687, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, serialization", "url": null }
c++, serialization if constexpr (is_container<T>) { for (auto& val : value) swap(val); } } template <typename T> T swap_if_needed(T value, endian endian) { swap_if_needed_in_place(value, endian); return value; } } // namespace binaryio #endif binaryio/type_utils.h #include <string_view> #include <tuple> #include <type_traits> #ifndef BINARYIO_TYPE_UTILS_H #define BINARYIO_TYPE_UTILS_H namespace binaryio { #define BINARYIO_DEFINE_FIELDS(TYPE, ...) \ constexpr auto fields() { return std::tie(__VA_ARGS__); } \ constexpr auto fields() const { return std::tie(__VA_ARGS__); } \ template <typename T> concept exposes_fields = requires (T a) { a.fields(); }; template <typename C> concept is_container = requires (C a) { C::value_type; C::reference; C::const_reference; C::iterator; C::const_iterator; C::difference_type; C::size_type; a.begin(); a.end(); a.cbegin(); a.size(); a.max_size(); a.empty(); }; } // namespace binaryio #endif binaryio/writer.h #include <iostream> #include <string_view> #include <vector> #include "binaryio/swap.h" #ifndef BINARYIO_WRITER_H #define BINARYIO_WRITER_H namespace binaryio { class BinaryWriter { std::ostream& os; public: // Based on // https://github.com/zeldamods/oead/blob/master/src/include/oead/util/binary_reader.h BinaryWriter(std::ostream& os, endian byte_order) : os{os}, m_endian{byte_order} {}; void seek(std::size_t offset, std::ios_base::seekdir seek_dir = std::ios_base::beg) { os.seekp(offset, seek_dir); } std::size_t tell() { return os.tellp(); } template <typename T> void write(T value) requires (!std::is_pointer_v<T> && std::is_trivially_copyable_v<T>) { swap_if_needed_in_place(value, m_endian); os.write(reinterpret_cast<char*>(&value), sizeof(T)); }
{ "domain": "codereview.stackexchange", "id": 44687, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, serialization", "url": null }
c++, serialization template <class Range, typename T = typename Range::value_type> void write_many(Range& values) requires (std::ranges::output_range<Range, T>) { for (auto& value : values) swap_if_needed_in_place(value, m_endian); os.write(reinterpret_cast<char*>(values.begin().base()), values.size() * sizeof(T)); } void write_string(std::string_view str) { os.write(str.data(), str.size()); } endian endianness() { return m_endian; } void set_endianness(endian new_endian) { m_endian = new_endian; } void swap_endianness() { if (m_endian == endian::big) m_endian = endian::little; else m_endian = endian::big; } private: endian m_endian{endian::native}; }; } // namespace binaryio #endif Unit Test #include <filesystem> #include <fstream> #include <iostream> #include "binaryio/reader.h" #include "binaryio/writer.h" struct FileHeader { uint32_t magic; uint32_t fileSize; BINARYIO_DEFINE_FIELDS(FileHeader, magic, fileSize); }; struct WaveFile { FileHeader riffHeader; std::array<uint8_t, 4> magic; std::array<uint8_t, 4> fmt; uint32_t fmtSize; uint16_t audioFormat; uint16_t numChannels; uint32_t sampleRate; uint32_t byteRate; uint16_t blockAlign; uint16_t bitsPerSample; uint8_t pad[0x8a]; std::array<uint8_t, 4> dataMagic; uint32_t dataSize; // Data starts BINARYIO_DEFINE_FIELDS(WaveFile, riffHeader, magic, fmt, fmtSize, audioFormat, numChannels, sampleRate, byteRate, blockAlign, bitsPerSample, dataMagic, dataSize); } __attribute__((packed)); int main(int argc, char** argv) try { // Read from the byte buffer std::ifstream ifs{argv[1]}; binaryio::BinaryReader reader{ifs}; WaveFile wav{reader.read<WaveFile>()}; std::vector<char> data{reader.read_many<char>(wav.dataSize)};
{ "domain": "codereview.stackexchange", "id": 44687, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, serialization", "url": null }
c++, serialization ifs.close(); std::cout << "File 1 read" << '\n'; // Print to stdout to see what was read std::cout << "Riff Magic: " << std::hex << wav.riffHeader.magic << '\n'; std::cout << "Wave Magic: " << wav.magic.data() << '\n'; // Write a new file std::ofstream ofs{"out_litte.wav"}; binaryio::BinaryWriter writer{ofs, binaryio::endian::little}; writer.write(wav); writer.write_many(data); ofs.close(); std::cout << "File 2 written" << '\n'; // Write a different file with its endianness swapped ofs.open("out_big.wav"); writer.swap_endianness(); writer.write(wav); writer.write_many(data); ofs.close(); std::cout << "File 3 written" << '\n'; // Read the new file, and compare the result with the original struct, // treating the new values as big endian, since endianness was swapped ifs.open("out_big.wav"); if (reader.read<uint32_t>() == 0x52494646) { reader.swap_endianness(); ifs.seekg(0); } WaveFile other_wav{reader.read<WaveFile>()}; ifs.close(); std::cout << "File 3 read" << '\n'; std::cout << "Riff Magic: " << std::hex << other_wav.riffHeader.magic << '\n'; std::cout << "Wave Magic: " << other_wav.magic.data() << '\n'; if (wav.sampleRate == other_wav.sampleRate) std::cout << "Data preserved, endianness swapped" << std::endl; else throw std::runtime_error( "Something went wrong and the data was changed"); return 0; } catch (std::runtime_error& err) { std::cerr << err.what() << std::endl; return 1; } ``` Answer: Code Review: Naming: class BinaryReader { std::istream& is; // Lots of methods: endian m_endian {endian::native};
{ "domain": "codereview.stackexchange", "id": 44687, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, serialization", "url": null }
c++, serialization // Lots of methods: endian m_endian {endian::native}; Personal opinion: I like to group all the member variables together (for me this helps me make sure that I set all members in the constructor). Another personal opinion: I don't like your naming scheme. One variable is prefixed by m_ but the other is simply the name (though a bit short - self documenting names is considered a good practice). Pick one style. BinaryReader(std::istream& is, endian byte_order) : is{is}, m_endian{byte_order} {} Why is it called byte_order as a parameter and m_endian as a member? Seems a bit confusing. Not sure I understand the logic of the default parameter here: std::string read_string(const std::string::size_type max_len = std::string::npos) { std::string str; if (max_len == std::string::npos) return str; If you don't provide a parameter it simply returns a string? This is technically not valid C++ (it's a common extension implemented by a lot of compilers): char arr[max_len]; Also you make a copy of the array in a couple of lines: str = arr; Why not skip the copy? Create a string of the correct size and read directly into it. // Code does not include error check. Left as exercise. std::string arr(max_len, '\0'); is.getline(arr.data(), max_len, '\0'); arr.resize(is.gcount()); You are using the wrong Range type here. This is an input function so std::ranges::output_range is incorrect (it should be std::ranges::input_range). template <class Range, typename T = typename Range::value_type> void _do_read(Range& vals) requires (std::ranges::output_range<Range, T>) {
{ "domain": "codereview.stackexchange", "id": 44687, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, serialization", "url": null }
c++, serialization But input_range is still not correct. You are not using the ++ operator to move from one element to the next. You are assuming that all the elements are contiguous to each other. So you should be using std::ranges::contiguous_range<T>. if (!is.read(reinterpret_cast<char*>(vals.data()), vals.size() * sizeof(T))) throw std::out_of_range("out of bounds read"); Note this will only read max_len-1 characters from the stream. is.getline(arr, max_len, '\0'); The last item in the array will be reserved for the null terminator. Sure you can write it like this: if (m_endian == endian::big) m_endian = endian::little; else m_endian = endian::big; Personally, I would do it as: m_endian = (m_endian == endian::big) ? endian::little : endian::big; You copy the data to and from a buffer. Why not swap in place? template <typename T> constexpr void swap(T& value) { if (sizeof(T) == 1) return; std::array<char, sizeof(T)> data; std::memcpy(data.data(), &value, sizeof(T)); for (int i{0}; i < sizeof(T)/2; ++i) std::swap(data[sizeof(T) - 1 - i], data[i]); std::memcpy(&value, data.data(), sizeof(T)); } I would simply do this: template <typename T> constexpr void swap(T& value) { char* data = reinterpret_cast<char*>(&value); for (int i{0}; i < sizeof(T)/2; ++i) std::swap(data[sizeof(T) - 1 - i], data[i]); } This is line is currently beyond me :-) I need to study but assume it is OK. if constexpr (exposes_fields<T>) { std::apply( [endian](auto&... fields) { (swap_if_needed_in_place(fields, endian), ...); }, value.fields()); } To prevent a copy, pass by reference and return the reference. template <typename T> T swap_if_needed(T value, endian endian) { swap_if_needed_in_place(value, endian); return value; }
{ "domain": "codereview.stackexchange", "id": 44687, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, serialization", "url": null }
c++, serialization Hold on. In the read version don't you look for a terminating \0 character? In this case you should write that \0 character to the output stream. void write_string(std::string_view str) { os.write(str.data(), str.size()); // You need + 1 on the size. }
{ "domain": "codereview.stackexchange", "id": 44687, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, serialization", "url": null }
c++, game, socket, tcp Title: Winsock code for lockstep RTS game Question: Summary This is my core networking code for the lockstep RTS game that I am creating. Clients connect to a relay server via a TCP socket, and any packets sent to the relay server are forwarded to all other players. The relay server does not care about the packet contents or game state, it just passes packets around. Clients send a packet every tick containing their commands, and a tick is only processed once clients have received the commands of all other players - this ensures that everyone is running an identical simulation, so all clients remain in-sync. To mitigate lag, commands are scheduled for 'n' ticks in the future (currently set to 10 ticks, or ~166ms). Currently this seems to be working well (at least on Windows). Any feedback is welcome, be it about the code, the architecture, or any other decisions I have made. I am always looking to improve! Socket class The idea is for this to be a cross-platform wrapper around a raw socket that uses RAII to manage the connection. Named factory methods are provided to initialize the socket for a client/server. The send method sends the given buffer, and the receive method blocks until it has filled the given buffer. If an error occurs during initialization, an exception is thrown (I know exceptions aren't popular in game development, but I am using them nonetheless). If an error occurs while sending/receiving data, the socket is closed gracefully. A Socket can be moved, but not copied. Socket.h This contains the class declaration, and should (ideally) be completely platform-agnostic. #pragma once #include <cstdint> #include <memory> #include <string> #include <vector> // Ideally we would not have any platform-specific stuff here, // but this seems unavoidable since we need to know the underlying type! #ifdef _WIN32 #include <winsock2.h> #else // I am only targeting Windows for now, so don't worry too much about this. typedef int SOCKET; #endif namespace Rival {
{ "domain": "codereview.stackexchange", "id": 44688, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, game, socket, tcp", "url": null }
c++, game, socket, tcp namespace Rival { enum class SocketState : std::uint8_t { Open, Closed }; /** * Wrapper class for a native socket. * * Implementation details are platform-specific. */ class Socket { public: /** Creates a listening socket connected to localhost. */ static Socket createServer(int port); /** Creates a socket and attempts to connect it to the given address and port. */ static Socket createClient(const std::string& address, int port); /** Creates a socket that wraps a raw socket handle. The socket is assumed to be open if the handle is valid. */ static Socket wrap(SOCKET rawSocket); ~Socket(); bool Socket::operator==(const Socket& other) const; bool Socket::operator!=(const Socket& other) const; // Allow moving but prevent copying and move-assignment Socket(const Socket& other) = delete; Socket(Socket&& other) noexcept; Socket& operator=(const Socket& other) = delete; Socket& operator=(Socket&& other) = delete; /** Blocking call that waits for a new connection. */ Socket accept(); /** Closes the socket; forces any blocking calls to return. */ void close() noexcept; /** Determines if this socket is valid. */ bool isValid() const; /** Determines if this socket is closed. */ bool isClosed() const; /** Sends data on this socket. */ void send(std::vector<char>& buffer); /** Blocking call that waits for data to arrive and adds it to the given buffer. */ void receive(std::vector<char>& buffer); private: Socket(const std::string& address, int port, bool server); Socket(SOCKET rawSocket); void init(); private: SOCKET sock; SocketState state = SocketState::Closed; }; } // namespace Rival Socket.cpp This contains any socket functionality that is common to all platforms. #include "pch.h" #include "net/Socket.h" namespace Rival { Socket Socket::createServer(int port) { return { "localhost", port, true }; }
{ "domain": "codereview.stackexchange", "id": 44688, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, game, socket, tcp", "url": null }
c++, game, socket, tcp namespace Rival { Socket Socket::createServer(int port) { return { "localhost", port, true }; } Socket Socket::createClient(const std::string& address, int port) { return { address, port, false }; } Socket Socket::wrap(SOCKET rawSocket) { return { rawSocket }; } Socket::Socket(SOCKET rawSocket) : sock(rawSocket) { init(); state = (rawSocket == INVALID_SOCKET) ? SocketState::Closed : SocketState::Open; } Socket::~Socket() { close(); } bool Socket::operator==(const Socket& other) const { return sock == other.sock; } bool Socket::operator!=(const Socket& other) const { return !(*this == other); } bool Socket::isClosed() const { return state == SocketState::Closed; } } // namespace Rival WindowsSocket.cpp This common the Windows-specific socket functionality. #include "pch.h" #ifdef _WIN32 // These comments... #include "net/Socket.h" // ... prevent the auto-formatter from moving the include #include <winsock2.h> #include <ws2tcpip.h> #include <iostream> #include <stdexcept> #include <utility> // std::exchange namespace Rival { Socket::Socket(const std::string& address, int port, bool server) { // Specify socket properties addrinfo hints; ZeroMemory(&hints, sizeof(hints)); hints.ai_family = AF_INET; hints.ai_socktype = SOCK_STREAM; hints.ai_protocol = IPPROTO_TCP; if (server) { hints.ai_flags = AI_PASSIVE; } // Resolve the local address and port to be used by the server addrinfo* addrInfo = nullptr; if (int err = getaddrinfo(address.c_str(), std::to_string(port).c_str(), &hints, &addrInfo)) { throw std::runtime_error("Failed to get net address: " + std::to_string(err)); } // Create the socket sock = INVALID_SOCKET; sock = socket(addrInfo->ai_family, addrInfo->ai_socktype, addrInfo->ai_protocol);
{ "domain": "codereview.stackexchange", "id": 44688, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, game, socket, tcp", "url": null }
c++, game, socket, tcp // Check for errors if (sock == INVALID_SOCKET) { int err = WSAGetLastError(); freeaddrinfo(addrInfo); throw std::runtime_error("Failed to create socket: " + std::to_string(err)); } // Common socket initialization init(); if (server) { // Bind the socket int bindResult = bind(sock, addrInfo->ai_addr, static_cast<int>(addrInfo->ai_addrlen)); if (bindResult == SOCKET_ERROR) { int err = WSAGetLastError(); freeaddrinfo(addrInfo); throw std::runtime_error("Failed to bind socket: " + std::to_string(err)); } // Address info is no longer needed freeaddrinfo(addrInfo); // Listen (server-only) if (listen(sock, SOMAXCONN) == SOCKET_ERROR) { throw std::runtime_error("Failed to listen on socket: " + std::to_string(WSAGetLastError())); } } else { // Connect to server int connectResult = connect(sock, addrInfo->ai_addr, static_cast<int>(addrInfo->ai_addrlen)); int err = WSAGetLastError(); if (connectResult == SOCKET_ERROR) { sock = INVALID_SOCKET; } // Address info is no longer needed freeaddrinfo(addrInfo); if (sock == INVALID_SOCKET) { throw std::runtime_error("Failed to connect to server: " + std::to_string(err)); } } if (isValid()) { state = SocketState::Open; } } Socket::Socket(Socket&& other) noexcept // Reset the source object so its destructor is harmless : sock(std::exchange(other.sock, INVALID_SOCKET)) , state(std::exchange(other.state, SocketState::Closed)) { } void Socket::init() { // Disable Nagle algorithm to ensure packets are not held up BOOL socketOptionValue = TRUE; setsockopt(sock, IPPROTO_TCP, TCP_NODELAY, (char*) (&socketOptionValue), sizeof(BOOL)); }
{ "domain": "codereview.stackexchange", "id": 44688, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, game, socket, tcp", "url": null }
c++, game, socket, tcp void Socket::close() noexcept { if (state == SocketState::Closed) { return; } state = SocketState::Closed; closesocket(sock); } Socket Socket::accept() { SOCKET clientSocket = INVALID_SOCKET; clientSocket = ::accept(sock, nullptr, nullptr); if (clientSocket == INVALID_SOCKET && !isClosed()) { std::cout << "Failed to accept client: " + std::to_string(WSAGetLastError()) << "\n"; } return Socket::wrap(clientSocket); } bool Socket::isValid() const { return sock != INVALID_SOCKET; } void Socket::send(std::vector<char>& buffer) { std::size_t bytesSent = 0; while (bytesSent < buffer.size()) { int bytesRemaining = buffer.size() - bytesSent; int result = ::send(sock, buffer.data() + bytesSent, bytesRemaining, 0); if (result == SOCKET_ERROR) { if (isClosed()) { // Socket has been closed, so just abort the send break; } else { // Socket is still open on our side but may have been closed by the other side std::cerr << "Failed to send on socket: " + std::to_string(WSAGetLastError()) << "\n"; close(); break; } } bytesSent += result; } } void Socket::receive(std::vector<char>& buffer) { std::size_t bytesReceived = 0; while (bytesReceived < buffer.size()) { int bytesExpected = buffer.size() - bytesReceived; int result = ::recv(sock, buffer.data() + bytesReceived, bytesExpected, 0);
{ "domain": "codereview.stackexchange", "id": 44688, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, game, socket, tcp", "url": null }
c++, game, socket, tcp if (result == SOCKET_ERROR) { if (isClosed()) { // Socket has been closed, so just abort the read break; } else { // Socket is still open on our side but may have been closed by the other side std::cerr << "Failed to read from socket: " + std::to_string(WSAGetLastError()) << "\n"; close(); break; } } if (result == 0) { // Connection has been gracefully closed close(); break; } bytesReceived += result; } } } // namespace Rival #endif Reading and relaying packets Without getting too bogged down in the details of the Connection class, here is the code that receives data from the socket. On the client: Received data is parsed into packets by a PacketFactory. Packets are queued until getReceivedPackets is called. On the server: Received packets are wrapped in a RelayedPacket. These are passed to a listener class for forwarding. void Connection::receiveThreadLoop() { while (!socket.isClosed()) { // First read the packet size if (!readFromSocket(Packet::sizeBytes)) { break; } // Extract the packet size from the buffer std::size_t offset = 0; int nextPacketSize = 0; BufferUtils::readFromBuffer(recvBuffer, offset, nextPacketSize); recvBuffer.clear(); // Sanity-check the packet size if (nextPacketSize > maxBufferSize) { throw std::runtime_error("Unexpected packet size: " + std::to_string(nextPacketSize)); } // Now read the packet itself if (!readFromSocket(nextPacketSize)) { break; }
{ "domain": "codereview.stackexchange", "id": 44688, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, game, socket, tcp", "url": null }
c++, game, socket, tcp // If this Connection has no packet factory, then it belongs to the relay server. The relay server doesn't care // about the contents of incoming packets, it just wraps them in RelayedPackets. std::shared_ptr<const Packet> packet = packetFactory ? packetFactory->deserialize(recvBuffer) : std::make_shared<RelayedPacket>(recvBuffer, remoteClientId); if (packet) { // Pass packets directly to the listener if present, otherwise queue them until requested if (listener) { listener->onPacketReceived(*this, packet); } else { std::scoped_lock lock(receivedPacketsMutex); receivedPackets.push_back(packet); } } } } bool Connection::readFromSocket(std::size_t numBytes) { recvBuffer.resize(numBytes); socket.receive(recvBuffer); // The socket may get closed during a call to `receive` bool success = !socket.isClosed(); return success; } std::vector<std::shared_ptr<const Packet>> Connection::getReceivedPackets() { std::vector<std::shared_ptr<const Packet>> packetsToReturn; { std::scoped_lock lock(receivedPacketsMutex); packetsToReturn = receivedPackets; receivedPackets.clear(); } return packetsToReturn; } BufferUtils Finally, here are a couple of utility methods that I use to add data to / extract data from a buffer: #pragma once #include <cstddef> // std::size_t #include <cstring> // std::memcpy #include <stdexcept> #include <vector> namespace Rival { namespace BufferUtils {
{ "domain": "codereview.stackexchange", "id": 44688, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, game, socket, tcp", "url": null }
c++, game, socket, tcp namespace Rival { namespace BufferUtils { /** Adds a value to the end of the given buffer. * This should not be used for anything which manages its own memory (e.g. containers and strings). */ template <typename T> void addToBuffer(std::vector<char>& buffer, const T& val) { // Later, we may need to ensure a certain endianness for cross-platform compatibility. // See: https://stackoverflow.com/questions/544928/reading-integer-size-bytes-from-a-char-array size_t requiredBufferSize = buffer.size() + sizeof(val); if (requiredBufferSize > buffer.capacity()) { throw std::runtime_error("Trying to overfill buffer"); } char* destPtr = buffer.data() + buffer.size(); // Since we are writing to the vector's internal memory we need to manually change the size buffer.resize(requiredBufferSize); std::memcpy(destPtr, &val, sizeof(val)); } /** Reads a value from the given buffer, at some offset. * The value is stored in dest, and the offset is increased by the size of the value. */ template <typename T> void readFromBuffer(const std::vector<char>& buffer, std::size_t& offset, T& dest) { if (offset + sizeof(dest) > buffer.size()) { throw std::runtime_error("Trying to read past end of buffer"); } std::memcpy(&dest, buffer.data() + offset, sizeof(dest)); offset += sizeof(dest); } }} // namespace Rival::BufferUtils Answer: A quick look at your Socket class: Use INVALID_SOCKET to indicate a closed socket SOCKET sock; SocketState state = SocketState::Closed; If you use INVALID_SOCKET to indicate a closed socket, there's no need for the state variable. Using two variables is potentially error-prone, since they can get out of sync. Constructors / assignment Socket(const std::string& address, int port, bool server); Socket(SOCKET rawSocket); I think it's fine to make these public. Socket(Socket&& other) noexcept; Socket& operator=(Socket&& other) = delete;
{ "domain": "codereview.stackexchange", "id": 44688, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, game, socket, tcp", "url": null }
c++, game, socket, tcp Socket(Socket&& other) noexcept; Socket& operator=(Socket&& other) = delete; Not sure why we prevent move assignment. It could be useful and is easy to implement. Especially if we add a default constructor that is simply a closed socket. A single isOpen() function /** Determines if this socket is valid. */ bool isValid() const; /** Determines if this socket is closed. */ bool isClosed() const; If we use INVALID_SOCKET as mentioned above, we only need one of these (I'd probably call it isOpen). Const-correctness void send(std::vector<char>& buffer); Since we don't want to alter buffer, we should pass it by const&, not just &. Refactoring the Socket constructor Socket::Socket(const std::string& address, int port, bool server) { // Specify socket properties addrinfo hints; ZeroMemory(&hints, sizeof(hints)); hints.ai_family = AF_INET; hints.ai_socktype = SOCK_STREAM; hints.ai_protocol = IPPROTO_TCP; if (server) { hints.ai_flags = AI_PASSIVE; } // Resolve the local address and port to be used by the server addrinfo* addrInfo = nullptr; if (int err = getaddrinfo(address.c_str(), std::to_string(port).c_str(), &hints, &addrInfo)) { throw std::runtime_error("Failed to get net address: " + std::to_string(err)); } // Create the socket sock = INVALID_SOCKET; sock = socket(addrInfo->ai_family, addrInfo->ai_socktype, addrInfo->ai_protocol); // Check for errors if (sock == INVALID_SOCKET) { int err = WSAGetLastError(); freeaddrinfo(addrInfo); throw std::runtime_error("Failed to create socket: " + std::to_string(err)); } // Common socket initialization init();
{ "domain": "codereview.stackexchange", "id": 44688, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, game, socket, tcp", "url": null }
c++, game, socket, tcp // Common socket initialization init(); if (server) { // Bind the socket int bindResult = bind(sock, addrInfo->ai_addr, static_cast<int>(addrInfo->ai_addrlen)); if (bindResult == SOCKET_ERROR) { int err = WSAGetLastError(); freeaddrinfo(addrInfo); throw std::runtime_error("Failed to bind socket: " + std::to_string(err)); } // Address info is no longer needed freeaddrinfo(addrInfo); // Listen (server-only) if (listen(sock, SOMAXCONN) == SOCKET_ERROR) { throw std::runtime_error("Failed to listen on socket: " + std::to_string(WSAGetLastError())); } } else { // Connect to server int connectResult = connect(sock, addrInfo->ai_addr, static_cast<int>(addrInfo->ai_addrlen)); int err = WSAGetLastError(); if (connectResult == SOCKET_ERROR) { sock = INVALID_SOCKET; } // Address info is no longer needed freeaddrinfo(addrInfo); if (sock == INVALID_SOCKET) { throw std::runtime_error("Failed to connect to server: " + std::to_string(err)); } } if (isValid()) { state = SocketState::Open; } }
{ "domain": "codereview.stackexchange", "id": 44688, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, game, socket, tcp", "url": null }
c++, game, socket, tcp if (isValid()) { state = SocketState::Open; } } This is a long function, and needs to be split up into separate, reusable parts. If we can make the first two parts (address lookup and opening the socket) less burdensome, we can avoid using the boolean server flag, which is a bit of an anti-pattern, and just write two separate functions. C++ is awkward for handling errors (either returning an error code, or throwing), which can make the code more long-winded. Consider using a std::system_error& parameter as an output parameter. One other thing that can help here is wrapping the address info pointer from getaddrinfo in a unique_ptr with a custom deleter. This removes the burden of calling freeaddrinfo manually. So... you might end up with something very roughly like this: Socket::Socket(): m_socket(INVALID_SOCKET) { } Socket::Socket(SOCKET handle): m_socket(handle) { } Socket::Socket(int domain, int type, int protocol, std::system_error& ec): m_socket(::socket(domain, type, protocol)) { if (!is_open()) ec = std::system_error(std::error_code(::WSAGetLastError(), std::system_category())); } Socket::~Socket() { auto ec = std::system_error(); (void)close(ec); } void Socket::is_open() const { return m_socket != INVALID_SOCKET; } bool Socket::close(std::system_error& ec) { if (!is_open()) return; auto const result = ::closesocket(m_socket); if (result != 0) { ec = std::system_error(std::error_code(::WSAGetLastError(), std::system_category())); return false; } return true; }
{ "domain": "codereview.stackexchange", "id": 44688, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, game, socket, tcp", "url": null }
c++, game, socket, tcp bool Socket::bind(sockaddr const* address, socklen_t address_length, std::system_error& ec) { auto const result = ::bind(m_socket, address, address_length); if (result != 0) { ec = std::system_error(std::error_code(::WSAGetLastError(), std::system_category())); // TODO: abstract into a get_last_error()! return false; } return true; } // listen, connect, etc. left as an exercise for the reader. ... using addrinfo_ptr = std::unique_ptr<::addrinfo, void(*)(::addrinfo*)>; addrinfo_ptr lookup_address(char const* node, char const* service, int domain, int type, int protocol, int flags, std::system_error& ec) { assert(node || service); auto hints = ::addrinfo(); std::memset(&hints, 0, sizeof(::addrinfo)); hints.ai_family = domain; hints.ai_socktype = type; hints.ai_protocol = protocol; hints.ai_flags = flags; auto out = (::addrinfo*)nullptr; auto const result = ::getaddrinfo(node, service, &hints, &out); if (result != 0) { ec = std::system_error(std::error_code(result, std::system_category())); // note: not WSAGetLastError return { }; } assert(out); return addrinfo_ptr(out, &::freeaddrinfo); } addrinfo_ptr get_local_address_info(int domain, int type, int protocol, std::uint16_t port, std::system_error& ec) { auto const port_str = std::to_string(port); int flags = AI_PASSIVE | AI_NUMERICSERV; return lookup_address(nullptr, port_str.data(), domain, type, protocol, flags, ec); } addrinfo_ptr get_address_info(int domain, int type, int protocol, std::string const& node, std::uint16_t port, std::system_error& ec) { auto const port_str = std::to_string(port); int flags = AI_NUMERICSERV; return lookup_address(node.data(), port_str.data(), domain, type, protocol, flags, ec); } ...
{ "domain": "codereview.stackexchange", "id": 44688, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, game, socket, tcp", "url": null }
c++, game, socket, tcp ... Socket create_server(std::uint16_t port) { auto const domain = AF_INET; auto const type = SOCK_STREAM; auto const protocol = IPPROTO_TCP; auto ec = std::system_error(); auto const addrinfoptr = get_local_address_info(domain, type, protocol, port, ec); if (!addrinfoptr) throw std::runtime_error(std::string("Address lookup failed: ") + ec.what()); auto socket = Socket(domain, type, protocol, ec); if (!socket.is_open()) throw std::runtime_error(std::string("Open socket failed: ") + ec.what()); if (!socket.bind(addrinfoptr->ai_addr, addrinfoptr->ai_addrlen, ec)) throw std::runtime_error(std::string("Bind socket failed: ") + ec.what()); if (!socket.listen(SOMAXCONN, ec)) throw std::runtime_error(std::string("Listen failed: ") + ec.what()); return socket; } Socket create_client(std::string const& host, std::uint16_t port) { auto const domain = AF_INET; auto const type = SOCK_STREAM; auto const protocol = IPPROTO_TCP; auto ec = std::system_error(); auto const addrinfoptr = get_address_info(domain, type, protocol, host, port, ec); if (!addrinfoptr) throw std::runtime_error(std::string("Address lookup failed: ") + ec.what()); auto socket = Socket(domain, type, protocol, ec); if (!socket.is_open()) throw std::runtime_error(std::string("Open socket failed: ") + ec.what()); if (!socket.connect(addrinfoptr->ai_addr, addrinfoptr->ai_addrlen, ec)) throw std::runtime_error(std::string("Connect failed: ") + ec.what()); return socket; }
{ "domain": "codereview.stackexchange", "id": 44688, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, game, socket, tcp", "url": null }
c++, game, socket, tcp (Note: not compiled / tested) There are other patterns you could use for dealing with return values / error handling. These include throwing errors (and the more burdensome catching), or using something like std::expected. Things get a little more complicated if you want to handle non-blocking sockets. It just means checking a couple of "error" values (e.g. WSAEWOULDBLOCK) inside our hypothetical Socket::connect() and treating them as success instead. Use std::size_t int bytesRemaining = buffer.size() - bytesSent; ... int bytesExpected = buffer.size() - bytesReceived; These guys should be std::size_t. A fixed-size buffer? void Socket::receive(std::vector<char>& buffer) { std::size_t bytesReceived = 0; while (bytesReceived < buffer.size()) { int bytesExpected = buffer.size() - bytesReceived; int result = ::recv(sock, buffer.data() + bytesReceived, bytesExpected, 0); ... bytesReceived += result; } } Looping until we receive all the bytes in a fixed size buffer is very limiting and error-prone. I think this might be better enforced outside the Socket class. It's quite possible we'd want to receive a packet of unknown size in future. (And the same with sending).
{ "domain": "codereview.stackexchange", "id": 44688, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, game, socket, tcp", "url": null }
lua Title: Inverting a boolean in Lua Question: Is there a more elegant way to set this boolean value? SetScript() is a game API, while "OnClick" is its handler. What is important is the method that triggers when I click on the checkbutton. local foo = true checkbutton:SetScript("OnClick", function() if foo == true then foo = false else foo = true end end) Answer: a more elegant way ? Simply assign the negation, unconditionally: not foo This works in Lua, and in essentially every other language. checkbutton:SetScript("OnClick", function() foo = not foo end) If we're flipping {0, 1} integers instead of booleans, then the relevant idiom is to assign 1 - foo.
{ "domain": "codereview.stackexchange", "id": 44689, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "lua", "url": null }
rust Title: Rust: Looping over every file in a directory, collecting and modifying filenames and metadata Question: I'm building a simple blog with Axum and Rust, mainly to practice Rust. I find myself finding working solutions to the things I want to do, but I don't like the end result of my code, it doesn't feel right, too many unwraps and too many "if let Ok"s". I'm sure there are more idiomatic ways of achieving what I'm trying to do. Here I'm looping over a directory, getting the stem of every filename, replacing - with space, and also getting the created metadata and turning it from system time to UTC, then collecting it into a struct, and turning it to JSON to send it off to the client. I am also sending the actual name of the blog post to the client, to use as a link to the blog post later. use std::{fs, path::Path}; use axum::Json; use chrono::prelude::{DateTime, Utc}; use serde::{Deserialize, Serialize}; use serde_json::{json, Value}; use crate::error; use error::Result; #[derive(Debug, Serialize, Deserialize, PartialEq)] struct BlogPosts { title: String, date: String, link: String, } pub async fn get_blog_posts() -> Result<Json<Value>> { let results = blog_posts_title_date(); let body: Json<Value> = Json(json!(results)); Ok(body) }
{ "domain": "codereview.stackexchange", "id": 44690, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "rust", "url": null }
rust let body: Json<Value> = Json(json!(results)); Ok(body) } fn blog_posts_title_date() -> Vec<BlogPosts> { let path_to_dir = Path::new("./blog_posts"); let mut results = vec![]; if let Ok(entries) = fs::read_dir(path_to_dir) { for entry in entries { if let Ok(entry) = entry { let title = entry .path() .file_stem() .unwrap() .to_str() .unwrap() .to_string(); let create_time = entry.metadata().unwrap().created().unwrap(); let date: DateTime<Utc> = create_time.clone().into(); results.push(BlogPosts { title: title.replace("-", " "), date: format!("{}", date.format("%d-%m-%Y")), link: format!("{}", title), }) } } } results } #[cfg(test)] mod tests { use super::*; #[test] fn get_files_from_blog_folder() { let blog_posts = blog_posts_title_date(); assert_eq!( blog_posts, vec![BlogPosts { title: "This Is A Test".to_string(), date: "30-04-2023".to_string(), link: "This-Is-A-Test".to_string(), }] ) } } Edit: After spending the day learning, thinking, and trying. I did come up with a better and cleaner solution. I'm still not 100% happy, but this does handle errors better, now I will return a 404 if no files are found in the folder. I feel like it could be better, so any feedback would be much appreciated. Refactored code: use std::{fs, path::Path}; use axum::Json; use chrono::prelude::{DateTime, Utc}; use serde::{Deserialize, Serialize}; use serde_json::{json, Value}; use crate::error::{self, Error}; use error::Result;
{ "domain": "codereview.stackexchange", "id": 44690, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "rust", "url": null }
rust use crate::error::{self, Error}; use error::Result; #[derive(Debug, Serialize, Deserialize, PartialEq)] struct BlogPosts { title: String, date: String, link: String, } pub async fn get_blog_posts() -> Result<Json<Value>> { let results = blog_posts_title_date(); if let Some(body) = results { Ok(Json(json!(body))) } else { Err(Error::FileNotFound) } } fn blog_posts_title_date() -> Option<Vec<BlogPosts>> { let path_to_dir = Path::new("./blog_posts"); let mut results = Vec::new(); let entries = match fs::read_dir(path_to_dir) { Ok(entries) => entries, Err(e) => { eprintln!("Error: {}", e); return None; } }; for entry in entries { match entry { Ok(entry) => { let title = entry.path().file_stem()?.to_str()?.to_string(); let create_time = entry.metadata().ok()?.created().ok()?; let date: DateTime<Utc> = create_time.clone().into(); results.push(BlogPosts { title: title.replace("-", " "), date: format!("{}", date.format("%d-%m-%Y")), link: format!("{}", title), }) } Err(e) => { eprintln!("Error: {}", e); return None; } } } if results.is_empty() { None } else { Some(results) } } #[cfg(test)] mod tests { use super::*; #[test] fn get_files_from_blog_folder() { let blog_posts = blog_posts_title_date(); assert_eq!( blog_posts, Some(vec![BlogPosts { title: "This Is A Test".to_string(), date: "30-04-2023".to_string(), link: "This-Is-A-Test".to_string(), }]) ) } } ```
{ "domain": "codereview.stackexchange", "id": 44690, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "rust", "url": null }
rust Answer: You Want Railway-Oriented Programming Your instincts were completely correct: there is a better way than writing .unwrap() everywhere and panicking on any error. What you want to do is chain your results together in a way that short-circuits if there are any errors, or returns a result only if there are no errors. Scott Wlaschin coined the term “railway-oriented programming” in 2013, comparing it to parallel railway tracks, where a train starts on the main track but there are multiple bypasses that can send it to the other track instead. So, how do you do this in Rust? Functions that could fail normally use one of two types from the standard library, usually Result (Ok (x) or Err (e), but sometimes Option (Some(x) or None). You normally use map to apply a function that does no error checking to the chain, and and_then to apply a function that could return the same type of error. There are several other options. (For example, some built-in helpers to convert between Option and Result.) In two places, I apply a closure instead of a function, to deal with a type conversion. The downside of doing things this way is that the type inference isn’t there yet, so you have to get extremely verbose about your types. Rust won’t (as of 2023) accept .map(to_string) where self is a &str. You must specify .map(str::to_string). To pass an owned value to a function that borrows it, I ended up putting the borrow inside a closure. An Example Here is one of your functions, which contains both a chain of Option instances (title) and a chain of Result instances (date), rewritten in a railway-oriented style. This code is untested. use chrono::prelude::{DateTime, Utc}; use std::{ffi::OsStr, fs, fs::DirEntry, path::Path}; #[derive(Debug, /* Serialize, Deserialize, */ PartialEq)] struct BlogPosts { title: String, date: String, link: String, }
{ "domain": "codereview.stackexchange", "id": 44690, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "rust", "url": null }
rust fn blog_posts_title_date() -> Vec<BlogPosts> { fn per_entry(entry: DirEntry) -> BlogPosts { // The compiler doesn’t need to be told the types of title or date. let title: String = entry // : DirEntry .path() // : PathBuf .file_stem() // : Option<&OsStr> .and_then(OsStr::to_str) // : Option<&str> .map(str::to_string) // : Option<String> .unwrap_or_default(); // : String let date: DateTime<Utc> = entry // : DirEntry .metadata() // : Result<Metadata> .and_then(move |md| md.created()) // : Result<SystemTime> .map(DateTime::<Utc>::from) // : Result<DateTime<Utc>> .expect("Invalid file metadata."); BlogPosts { title: title.replace("-", " "), date: format!("{}", date.format("%d-%m-%Y")), link: format!("{}", title), } } let path_to_dir = Path::new("./blog_posts"); /* fs::read_dir returns a Result<ReadDir>, where the wrapped ReadDir is an * iterator yielding io::Result<DirEntry>. */ fs::read_dir(path_to_dir) .expect("Directory ./blog_posts not found.") .map(move |x| x.expect("I/O error reading directory entry.")) .map(per_entry) .collect() } This is a nice example because it requires every combination of Option/Result and map/and_then. So, for the snippet, .file_stem() // : Option<&OsStr> .and_then(OsStr::to_str) // : Option<&str> .map(str::to_string) // : Option<String>
{ "domain": "codereview.stackexchange", "id": 44690, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "rust", "url": null }
rust The OsStr::to_str function could return None, so it needs to be chained with and_then. On the other hand, str::to_string always succeeds, so chain it with map. There’s another use of map below that’s different, but not really. I changed the for loop over the ReadDir iterator to a map followed by collect, moving the loop body into a helper function. These are in fact the same: map applies a function to every element of a collection, and treats an Option or Result as a collection that could be empty or have a single element. This terminology comes from functional programming. Haskell is the language that goes furthest in generalizing it in the most abstract way it can. There are at least two changes in behavior: I had a failure to retrieve the file stem return an empty String instead of panicking, but checked the directory entries with expect rather than ignoring errors silently. If you want to go back to ignoring those, change the line .map(move|x| {x.expect("I/O error reading directory entry.")}) to .filter(Result::is_ok) .map(Result::unwrap)
{ "domain": "codereview.stackexchange", "id": 44690, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "rust", "url": null }
java, depth-first-search Title: Optimize Island Counter program Question: I am doing some assignments on my own and one of them is about a Island Counting program, I have come up with a working program but the problem is its very slow. When running test on for example maps that are 30x30 in size is its around 24 ms, which is not bad but pretty slow. because when I test on maps that are 10000x10000 in size if finishes after approximatly 9 seconds and it need to be much faster. Here is my code: import java.io.File; import java.io.FileNotFoundException; import java.util.*; public class oar { public static void main(String[] args) throws FileNotFoundException{ long startTime = System.nanoTime(); File inputfile = new File("islands.7.in"); Scanner sc = new Scanner(inputfile); //Scanner sc = new Scanner(System.in); int x = sc.nextInt(); int y = sc.nextInt(); char[][] map = new char[x][y]; for (int i = 0; i < x; i++) { String row = sc.next(); for (int j = 0; j < y; j++) { map[i][j] = row.charAt(j); } } int count = 0; boolean[][] visited = new boolean[x][y]; for (int i = 0; i < x; i++) { for (int j = 0; j < y; j++) { if (!visited[i][j] && map[i][j] == '@') { bfs(map, visited, i, j); count++; } } } System.out.println(count); long endTime = System.nanoTime(); long elapsedTime = endTime - startTime; long tiden = elapsedTime/1000000000; System.out.println("Elapsed time: " + tiden + " seconds"); }
{ "domain": "codereview.stackexchange", "id": 44691, "lm_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, depth-first-search", "url": null }
java, depth-first-search static void bfs(char[][] map, boolean[][] visited, int i, int j) { int x = map.length; int y = map[0].length; Queue<int[]> queue = new LinkedList<>(); queue.offer(new int[] { i, j }); visited[i][j] = true; while (!queue.isEmpty()) { int[] curr = queue.poll(); int row = curr[0]; int col = curr[1]; if (row > 0 && !visited[row - 1][col] && map[row - 1][col] == '@') { queue.offer(new int[] { row - 1, col }); visited[row - 1][col] = true; } if (row < x - 1 && !visited[row + 1][col] && map[row + 1][col] == '@') { queue.offer(new int[] { row + 1, col }); visited[row + 1][col] = true; } if (col > 0 && !visited[row][col - 1] && map[row][col - 1] == '@') { queue.offer(new int[] { row, col - 1 }); visited[row][col - 1] = true; } if (col < y - 1 && !visited[row][col + 1] && map[row][col + 1] == '@') { queue.offer(new int[] { row, col + 1 }); visited[row][col + 1] = true; } } } } I currently use a bfs algorithm, are there any better techniques i can use? Here are the input for example: Its in the format of x y and then under is the map, where '@' are land and '~' are water. 8 13 ~@@~~~@~~~~~~ ~@@~~@@~~~~~~ ~~~~~@~~~@~@~ ~~~@@~~~@@@@~ ~~~~~~~@@~~@~ ~~~~~~@@@@~~~ and the answer is 4 islands Now this is a very small map, I have a mapbuilder program that generates much bigger maps and on those the program is very slow. Answer: import java.util.*; ... Scanner sc = new Scanner(inputfile); It turns out the * wildcard refers to this class. Prefer to list {Scanner, LinkedList} classes explicitly, as an aid to grep and to eyeballs. Also, since you're getting ready to merge down to main, it's time to delete the System.in comment.
{ "domain": "codereview.stackexchange", "id": 44691, "lm_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, depth-first-search", "url": null }
java, depth-first-search You chose map dimensions of x, y, which is kind of OK. Consider renaming to w, h or width, height. You put the (0, 0) origin at top rather than bottom, which seems like it's worth a // comment. Or better, just assign to map[i][y - j]. The call to bfs omits the counter variable which the loop is very nicely maintaining. Consider changing the Public API of bfs to accept a color parameter, which would simply be the counter. This might simplify debugging and allow for more informative map analysis displays. The idea is that, instead of merely saying "yup, this is land that Hansel & Gretel placed a breadcrumb on", we can uniquely name each island with a distinct integer, and use that at display time. This can make a big difference when you're considering maps or algorithms that might use the 4- or 8- cell neighborhood, and you're trying to identify where flood fill leaked from one region into an unexpected region. The visited matrix would be promoted from boolean to integer. main() is clearly doing more than one thing. Break out a pair of read_map, color_map helpers. It is unclear why you include map reading as part of the elapsed time measurement, given that the bfs algorithm is the one of interest. queue.offer(new int[] { i, j }); I don't understand this line; please add a // comment. The common idiom would be queue.addLast(), which is obviously being evaluated for side effects since it is of type void. Why do we instead call a boolean valued function and then choose to discard its return value? Is this some java checked-exception craziness where there's a burden to coping with potential exceptions? Apparently the same thing is going on when we .poll() instead of .removeFirst(). Please declare a MANIFEST_CONSTANT for this magic character: '@'.
{ "domain": "codereview.stackexchange", "id": 44691, "lm_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, depth-first-search", "url": null }
java, depth-first-search Please declare a MANIFEST_CONSTANT for this magic character: '@'. I see that we define an Island w.r.t. the 4-cell neighborhood. Please document that. There's four lines of source to handle each of four directions. This is tedious. Minimally you should extract a trivial helper so we have one-line calls. Better would be to define a vector of (delta_x, delta_y) offsets, and iterate through that. You told me the bfs loop processes in excess of eleven million cells per second, and that is not enough. Sounds pretty quick to me, but OK. There's a lot of allocations going on, and you didn't provide any GC stats, so it's hard to know where to drill down. The (x, y) Point allocations are perhaps unavoidable? That is, we could have a pool of Points at the app level and recycle them, but I don't see any reason why that would be more efficient than what the JVM is doing. The LinkedList .offer() allocations, OTOH, seem ripe for improvement. When we .poll() we're doing random read against DRAM, hoping it plays nicely with the several levels of cache. I note that you have less than 4 billion cells on the map, so a point's location can fit within 32 data bits. You're probably messing with 64-bit object pointers. We have a queue of unknown size, which could be a valid motivation for LinkedList. I propose that we instead store the queue in an ArrayList having a small initial size, and at the app level we double its size each time it gets full (or factor of 1.3 instead of 2, whatever). It never shrinks. We maintain {front, back} integer indexes into this Circular Queue. Note that sequential raster scans of an ArrayList perform better on Intel hardware than scans of LinkedList, since fetch prediction is easy and we're asking DRAM for adjacent values so the {CAS, RAS} timing can stream them out at closer to the bus bandwidth. I imagine that max queue depth mostly scales with map width, and can be a bit more than map width while exploring oddly shaped islands.
{ "domain": "codereview.stackexchange", "id": 44691, "lm_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, depth-first-search", "url": null }
java, depth-first-search Here is a much crazier performance idea: read in the map lazily. That is, only read a line of input when forced to by an array de-reference. Upon noticing that "count of processed cells" in first raster is equal to map width, output that raster and delete it, recycle the memory. The idea is to have a narrow band of the map in play at any given moment, hopefully just a fraction of the ten-thousand rasters. Of course, island shapes can work against this, especially if they are designed by an adversary. Here's another idea, which again depends on the data pattern of typical input maps. Reduce the resolution. That is, turn a 6x2 map into a 3x1 map of cells colored according to the max() function. So if any cell in a 2x2 grid is land, the corresponding supergrid shall be land. Solve this smaller problem with BFS flood fill, identifying N islands. Now you have N sub-problems to solve at normal resolution, each needing just a reduced memory footprint. If the technique proves helpful on typical inputs, notice that you are free to reduce resolution more than once. Perhaps typical islands are uncooperative and they thwart those attempts to use less RAM. Deterministically insert lines of water into your map, both horizontal and vertical. Again you have some simpler sub-problems to solve. Having done that, come back to stitch the islands back together, repairing damage done by your lines. You will want to switch from boolean to int color in order to correctly accomplish that.
{ "domain": "codereview.stackexchange", "id": 44691, "lm_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, depth-first-search", "url": null }
java, depth-first-search Come to think of it, there's no particular reason to introduce such lines. What I'm trying to do is get to a spot where we can conveniently use a standard pre-packaged spanning tree algorithm to find connected components of an undirected graph. Now strictly speaking the map we initially read in is such a graph, with each node having at most a degree of 4. It just wouldn't be attractive to run Prim over that; flood fill is a better match for bulk data reduction. But suppose we run bounded BFS flood fill, which terminates upon identifying the K-th island cell, where we have perhaps K = 1000. We're giving each pseudo-island a distinct integer identifier, and we understand that we'll have to come back to merge small pseudo-islands into giant proper islands. Shooting a spanning tree through those nodes would be a good way to merge together each connected component. What does this data-reduction buy us? Flexibility on problem size and memory footprint, even for extremely large input maps. We could run a JVM with low memory setting, or run on a tiny Raspberry Pi, and later come back to finish the job, stitching fragments into the larger islands required for the end product. The code achieves many of its design objectives. We have explored avenues for improvement. I would be willing to delegate or accept maintenance tasks on this code.
{ "domain": "codereview.stackexchange", "id": 44691, "lm_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, depth-first-search", "url": null }
php, object-oriented, classes, php7 Title: HTML form Class Question: After my previous question I revised the code to the code below. I am using PHP 7.0.33 and tried to accomplish PSR-12 as much as I could. In "condensed usage" in the docblock you can find a full copy-paste example. Here is the code: /** * This class aims to render a valid HTML form block * * @author julio * @date 1/5/2023 * * * -- Condensed usage -- * $form = new Form([ 'name'=>"my_form", 'action'=>"destination.php", 'method'=>"post" ]); $form->add_tag("fieldset"); $form->add_tag("legend"); $form->add_tag_attributes(['text'=>"My FLDST 1"]); $form->add_tag("label"); $form->add_tag_attributes([ 'for'=>"my_text", 'text'=>"My Text:" ]); $form->add_tag("input"); $form->add_tag_attributes([ 'id'=>"my_text", 'type'=>"text", 'name'=>"my_text", 'value'=>"", 'required'=>null ]); $form->add_tag("label"); $form->add_tag_attributes([ 'for'=>"my_textarea", 'text'=>"My Text Area:" ]); $form->add_tag("textarea"); $form->add_tag_attributes([ 'id'=>"my_textarea", 'name'=>"my_textarea", 'cols'=>80, 'rows'=>20, 'text'=>"My textarea text" ]); $form->add_tag("fieldset"); $form->add_tag("label"); $form->add_tag_attributes([ 'for'=>"my_check", 'text'=>"My Check:" ]); $form->add_tag("input"); $form->add_tag_attributes([ 'type'=>"checkbox", 'name'=>"my_check", 'value'=>"", 'id'=>"my_check", 'checked'=>true ]);
{ "domain": "codereview.stackexchange", "id": 44692, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "php, object-oriented, classes, php7", "url": null }
php, object-oriented, classes, php7 $form->add_tag("select"); $form->add_tag_attributes(['name'=>"my_select"]); $form->add_tag_options( [ "value11"=>"text11", "value12"=>"text12", "value13"=>"text13" ], ["value13"] ); $form->add_tag("select"); $form->add_tag_attributes([ 'name'=>"my_other_select", 'multiple'=>true ]); $form->add_tag_options( [ "value1"=> ["value11"=>"text11", "value12"=>"text12", "value13"=>"text13"], "value2"=> ["value21"=>"text21", "value22"=>"text22", "value23"=>"text23"], "value3"=> ["value31"=>"text31", "value32"=>"text32", "value33"=>"text33"],
{ "domain": "codereview.stackexchange", "id": 44692, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "php, object-oriented, classes, php7", "url": null }
php, object-oriented, classes, php7 ], ["value11", "value22", "value33"] ); $form->add_tag("fieldset"); $form->add_tag("label"); $form->add_tag_attributes([ 'for'=>"radio1", 'text'=>"radio1" ]); $form->add_tag("input"); $form->add_tag_attributes([ 'type'=>"radio", 'id'=>"radio1", 'name'=>"radio", 'value'=>"radio1" ]); $form->add_tag("label"); $form->add_tag_attributes([ 'for'=>"radio2", 'text'=>"radio2" ]); $form->add_tag("input"); $form->add_tag_attributes([ 'type'=>"radio", 'id'=>"radio2", 'name'=>"radio", 'value'=>"radio2" ]); $form->add_tag("label"); $form->add_tag_attributes([ 'for'=>"radio3", 'text'=>"radio3" ]); $form->add_tag("input"); $form->add_tag_attributes([ 'type'=>"radio", 'id'=>"radio3", 'name'=>"radio", 'value'=>"radio3" ]); $form->add_tag("fieldset"); $form->add_tag("input"); $form->add_tag_attributes([ 'type'=>"submit", 'value'=>"enviar", 'name'=>"enviar" ]); echo $form->render(); // or $html = $form->render(); * * -- Important -- * * This code is written for PHP 7.0.33 so visibility, return types and some * other improvements are not available to me. However I tried to accomplish * PSR 12 as much as a I could. * * You will notice there are no escaping functions in use. This is intended * for a developer so any kind of validation is left for it. * * Thorough tests still need to be run but so long this class is working. * * -- Notes about my coding style -- * * As much as I try to accomplish standards there are certain things I don't * like such as camel case for method names (and will ignore anything related * to this), using sprintf() for replacements or swith to `[]` instead of * `array()` (I use `array()` to declare multidimensional arrays and will * continue this way), just to name some of them. * They are not much and IMO they can be allowed. * * -- About this class -- * * This class aims to render a valid code for HTML forms.
{ "domain": "codereview.stackexchange", "id": 44692, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "php, object-oriented, classes, php7", "url": null }
php, object-oriented, classes, php7 * * -- About this class -- * * This class aims to render a valid code for HTML forms. * When this class is instantiated constructor takes an associative array * to set <form> attributes. Like this: * * $form = new Form([ * "name" => "my_form", * "action" => "destination.php", * "method" => "post" * ]); * * Those three attributes are mandatory. The others are optional. * * In general: * * parameters, when its type is array, are associative arrays, and * * mandatory attributes must be present and have a valid value, and * * if any optional attribute is set it must contain a non empty * string excepting boolean attributes such as `required`, `autofocus`, * `multiple` and `checked` (which can hold anything you want) or when the * attribute is `value`. When dealing with labels, textareas, fieldsets and * legends attribute `value` is named `text`, and * * custom or non standard attributes are not allowed and will be dismissed * with a user level warning (not implemented yet) * * To add a tag: * * $form->add_tag("tag_name"); * $form->add_tag_attributes(["attr1"=>"value1", ...]); * * If intended tag is a select, options must be set: * * $form->add_tag_options(["opt1"=>"value1", ...]); * * If select tag has any pre-selected value: * * $form->add_tag_options(["opt1"=>"value1", ...], ["selected1", "selected2", ...]); * * This documentation is still in progress. */ class Form { /** in here each valid tag is stored. * it is looped in render() * @var array */ private $output = array();
{ "domain": "codereview.stackexchange", "id": 44692, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "php, object-oriented, classes, php7", "url": null }