text
stringlengths
1
2.12k
source
dict
c#, asp.net-core Title: C# decomposition and refactoring of a very long Web Data Scraping Function with multiple different tasks using a Clean Architecture Pattern Question: I inherited a very long and messy C# function with a task to make it more readable and Clean Architecture Pattern friendly. The primary goal of a function is to send an API request to an endpoint and stream a collection of sport events which took place on a specific date. Response need to be saved to local File Storage. For this approach I abstracted two services within Core (Application) Layer and implemented them in an Infrastructue Layer: webScraperService (for api calls) fileStorageService (for saving scraped data) I think that this should be good enough. Regarding the function itself, I have identified key regions (I marked them and put a description) and for now the code itself is working, but it is still far away from being readable and clean (note that I am junior and this is my first "official" task). I excluded validations and exceptions to make the pasted code shorter. My first thoughts are that this is a typical ETL process so I am thinking in a direction similar to SQL Server Integration Services (SSIS) with Control and Data flow (pipeline pattern) implementation, but it would take to much time and it might be an overkill for this scenario. From the point of view of a more experienced programmer, do you have some suggestions to share about a good approach to better organize this code? Thank you in advance. public async Task ExecuteAsync() { #region #1 // Generating a List of Dates for which we need to send an API Request. var dates = GetDates(); #endregion #1 #region #2 // Loop through a previously generated List of Dates for which we need to send an API Request. foreach (var date in dates) { Console.WriteLine("Sending API Request for date: " + date); #region #3
{ "domain": "codereview.stackexchange", "id": 44543, "lm_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#, asp.net-core", "url": null }
c#, asp.net-core #region #3 // Sending an API Request to initial Endpoint which will return which contains a specific JSON string which further contains data // about sports which, additionally, contains a collection of events which took place on defined date. // HTML string will serve as an input for next step. var html = string.Empty; var initialUri = "matches/soccer/" + date.ToString("yyyyMMdd"); await webScraperService.GetAsync(initialUri, async stream => { using (GZipStream gZipStream = new(stream, CompressionMode.Decompress)) { using (StreamReader streamReader = new(gZipStream)) { html = await streamReader.ReadToEndAsync(); } } }); #endregion #3 #region #4 // From HTML string from previous step, we need to extract a specific JSON string which contains data // about sports which contains a collection of events which took place on defined date. // Defined JSON string will serve as an input in next step. var pattern = ":data-next=\"" + "({.*?})" + "\""; var match = Regex.Match(html, pattern); var json = match.Groups[1].Value.Replace(""", "\""); #endregion #4 #region #5 // FROM JSON string We need to extract data based on which we will generate (and loop) list of sport urls // to which we need to send an API request in order to get Events which took place on defined date. using (JsonDocument jsonDocument = JsonDocument.Parse(json)) { var dateSegment = jsonDocument.RootElement .GetProperty("dataSegment") .GetString();
{ "domain": "codereview.stackexchange", "id": 44543, "lm_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#, asp.net-core", "url": null }
c#, asp.net-core var dateCodeSegment = jsonDocument.RootElement .GetProperty("encodedXhash") .GetString(); var sports = jsonDocument.RootElement .GetProperty("tabs") .GetProperty("sports") .EnumerateArray(); foreach (var sport in sports) { var id = sport .GetProperty("sid") .GetInt32(); var slug = sport .GetProperty("sportUrl") .GetString(); if (id > 0) // value 0 is not relevant in this context (sportId is always greated than 0) { var sportUri = "ajax-nextgames/" + id + "/1/2/" + dateSegment + "/" + dateCodeSegment + ".dat"; #region #6 // We are sending new API request for each sport URL and saving the responce to a File Storage. Console.WriteLine("Sending API Request for sport: " + slug); await webScraperService.GetAsync(sportUri, async stream => { var path = "Events\\" + date.ToString("yyyy-MM-dd") + "-" + slug + ".gz"; await fileStorageService.CreateAsync(path, stream); }); #endregion #6 } } } #endregion #5 } #endregion #1 } Answer: After refactoring the initial code (based on your valuable feedback and my further research) I ended up with the below solution. I moved the logic to 3 additional classes:
{ "domain": "codereview.stackexchange", "id": 44543, "lm_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#, asp.net-core", "url": null }
c#, asp.net-core FileDownloader (responsible for downloading content from WebApi to local FileStorage) DateCollection (responsible for generating a list of dates based on specified date range) SportCollection (responsible for generating a list of sports) It could be improved even more, but I am quite happy at the moment with how it looks now (in comparison to the original). public async Task ExecuteAsync() { DateCollection dates = new('2022-03-01', '2022-03-02'); foreach (var date in dates) { string url = "matches/soccer/" + date.ToString("yyyyMMdd"); string input = await webScraperService.GetStringAsync(url); SportCollection sports = new(input); foreach (var sport in sports) { await FileDownloader.DownloadAsync(sport.RequestUri, sport.Path); } } }
{ "domain": "codereview.stackexchange", "id": 44543, "lm_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#, asp.net-core", "url": null }
array, node.js, inheritance Title: Extend native `Array` instances Question: I need/want to extend created array instance, to add extra methods that i see as useful. class.labels.js const { find, filter, value, key } = require("./labels.js"); module.exports = class Labels extends Array { constructor(...args) { super(...args); } find(...args) { return find(this, ...args); } filter(...args) { return filter(this, ...args); } value(...args) { return value(this, ...args); } key(...args) { return key(this, ...args); } }; labels.js function match(label, filter) { let [fk, fv] = filter.split("="); let [lk, lv] = label.split("="); if (fv === "*") { return fk === lk; } if (fk === "*") { return fv === lv; } return label === filter; } function find(arr, filter) { return Array.prototype.find.call(arr, (label) => { return match(label, filter); }); } function filter(arr, filter) { return Array.prototype.find.call(arr, (label) => { return match(label, filter); }); } function value(arr, key) { return find(arr, `${key}=*`)?.split("=")[1]; } function key(arr, val) { return find(arr, `*=${val}`)?.split("=")[0]; } module.exports = { match, find, filter, value, key }; example.js const Labels = require("./class.labels.js"); const labels = new Labels(); labels.push("key=value"); labels.push("foo=bar"); labels.push("bar=baz"); labels.push("key1=value") console.log(labels); console.log(labels.find("foo=*")); console.log(labels.map((s) => { return String.prototype.toUpperCase.call(s); })); console.log(labels.key("value")); console.log(labels.value("key1")); Is this praxis considered ok? Answer: function find(arr, filter) { ... function filter(arr, filter) {
{ "domain": "codereview.stackexchange", "id": 44544, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "array, node.js, inheritance", "url": null }
array, node.js, inheritance Answer: function find(arr, filter) { ... function filter(arr, filter) { DRY. I can't say I'm pleased with this pair of functions. They are literally the same thing, byte for byte. Pick one and go with it. Don't pollute the IDE autocomplete menu with multiple spellings for same concept. Don't clutter the documentation of your public API. Maybe find is culturally appropriate, since we're calling into Array's find which callers are already familiar with. Maybe filter is better, as it suggests zero or more results. You are the API designer. Choose a winner and run with it. (Imagine there was some backward compatibility reason why the V2 filter needs to be just like the V1 find. That's unfortunate, but still no reason for copy-n-paste code. Choose one to be canonical, and have the other call it.) Apparently it would be Bad to have a data value that includes the = equal sign. (Similarly for keys, but I'm willing to believe that comes up less often.) We really need to have a comment or other documentation which explains that. More generally, there seems to be some business concept of a Label which would benefit from documentation that introduces the notion. Maybe there's a specification for what valid labels look like. In example.js we find some demo calls, which is helpful documentation, it shows what's expected. But it's a far cry from using Jest or similar unit test framework. Automated tests should be self-evaluating, they should "know" the right answer, so they can report Green / Red bar results. The console logging we see here assumes that the human eyeballing the results will know the right answer, and will usefully respond when the wrong answer is displayed.
{ "domain": "codereview.stackexchange", "id": 44544, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "array, node.js, inheritance", "url": null }
array, node.js, inheritance Overall? This module seems to have a "find vs filter?" issue that still needs to be resolved. With one of them deleted (or at least deprecated), it should be ready to ship. We still need to decide whether we're commited to automated testing of this codebase. As it stands, I would be reluctant to delegate or accept maintenance tasks for it.
{ "domain": "codereview.stackexchange", "id": 44544, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "array, node.js, inheritance", "url": null }
python, performance, interview-questions Title: Detecting timeouts in a stream of events Question: I'm trying to come up with a solution to this interview question: You have a stream of RPC requests coming into a server which is being logged. Each log entry is of the form [id, timestamp, type ('Start' or 'End')]. Given a sequence of log entries and a timeout value, you need to figure out at the earliest possible time if an RPC call has timed out (e.g. print a message as soon as you detect such situation). Example: Timeout = 3 id - time - type 0 - 0 - Start 1 - 1 - Start 0 - 2 - End 2 - 6 - Start # figured out id 1 had timed out at time 6 1 - 7 - End I believe that my solution is O(NlogN), is there any way to improve it? from sortedcontainers import SortedList def process_log(log: list[list], timeout=3): rpc_ids = {} rpcs = SortedList() for rpc_id, timestamp, action in log: if action == 'Start': rpcs.add([timestamp, rpc_id]) rpc_ids[rpc_id] = timestamp else: if rpc_id in rpc_ids: entry = [rpc_ids[rpc_id], rpc_id] if timestamp - rpc_ids[rpc_id] > timeout: report_rpc(rpc_id, rpc_ids[rpc_id], timestamp) del rpc_ids[rpc_id] rpcs.remove(entry) idx = rpcs.bisect_left([timestamp-timeout, float('inf')]) if idx > 0: for i in range(idx): start_time, rpc_id = rpcs[i] report_rpc(rpc_id, start_time, timestamp) del rpc_ids[rpc_id] del rpcs[:idx] def report_rpc(rpc_id, start_time, timestamp): print(f'RPC #{rpc_id} started at {start_time} has timed out (@{timestamp})') process_log([ # RPC #1 times out at timestamp 6 [0, 0, 'Start'], [1, 1, 'Start'], [0, 2, 'End'], [2, 6, 'Start'], [1, 7, 'End'], ]) Answer: Here's a O(n) solution using just a dictionary: from dataclasses import dataclass
{ "domain": "codereview.stackexchange", "id": 44545, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, performance, interview-questions", "url": null }
python, performance, interview-questions Answer: Here's a O(n) solution using just a dictionary: from dataclasses import dataclass @dataclass(frozen=True, slots=True) class LogEntry: rpc_id: int timestamp: int action: str class LogProcessor: def __init__(self, timeout: int): self.entries: dict[int, LogEntry] = {} self.timeout = timeout def process_log_entry(self, entry: LogEntry) -> list[LogEntry]: if entry.action == 'Start': self.entries[entry.rpc_id] = entry elif entry.rpc_id in self.entries and entry.timestamp - self.entries[entry.rpc_id].timestamp <= self.timeout: del self.entries[entry.rpc_id] timed_out = [] for e in self.entries.values(): if entry.timestamp - e.timestamp <= self.timeout: break timed_out.append(e) for e in timed_out: del self.entries[e.rpc_id] return timed_out log_processor = LogProcessor(timeout=3) assert log_processor.process_log_entry(LogEntry(1, 0, 'Start')) == [] assert log_processor.process_log_entry(LogEntry(2, 1, 'Start')) == [] assert log_processor.process_log_entry(LogEntry(1, 2, 'End')) == [] assert log_processor.process_log_entry(LogEntry(3, 6, 'Start')) == [LogEntry(2, 1, 'Start')] As Python dictionaries are insertion ordered, we can check for timed out entries on each call to process_log_entry() by iterating once from the beginning of the dictionary. Since we remove timed out entries immediately after the iteration, the total time complexity will still be O(n). P.S. The code has also been refactored to use a dataclass for log entry and a class for log processor, which should be more readable/maintainable.
{ "domain": "codereview.stackexchange", "id": 44545, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, performance, interview-questions", "url": null }
performance, beginner, c, hash-map Title: quadratic probing hashmap and its time efficiency Question: I am writing small a hashmap library (not full featured yet) but I have some questions about the algorithm I wrote, the formula I hope I got right from wikipedia and general things. Measured ~14.3 million inserts in ~5.3 seconds with a load factor of 0.75, 2.1 s at 0.5. From the sparsehash readme: RESOURCE USAGE sparse_hash_map has memory overhead of about 4 to 10 bits per hash-map entry, assuming a typical average occupancy of 50%. dense_hash_map has a factor of 2-3 memory overhead: if your hashtable data takes X bytes, dense_hash_map will use 3X-4X memory total. Why are they talking about bits here? Don't we work with bytes? First of all I tested against rockyou.txt as it's known to me and has a lot entries. And that's my output: Function Time hashdb_test_append_rockyou 5.309431 sec (Appending 14.344.392 keys to hashdb) hashdb_test_get_key 0.000005 sec (Get one key) hashdb_test_get_1000_keys 0.000221 sec (Get 1000 keys) hashdb_test_get_rockyou 3.330763 sec (Get all keys)
{ "domain": "codereview.stackexchange", "id": 44546, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "performance, beginner, c, hash-map", "url": null }
performance, beginner, c, hash-map hashdb_test_get_rockyou 3.330763 sec (Get all keys) My buckets only hold a const char *key pointer and a void *value pointer to store data. Is this common practice or do I need to allocate extra memory for the keys to keep a copy? EDIT: I added the source code below. The timebot is a header I've written because I wanted to compare functions that do the same operation to keep track of the time, compare them against each other and now I added some normal timing function to it for hashdb testing. Default capacity is 7 for testing reasons. Any call on hashdb_add calls hashdb_grow which tests if it should grow (also checking member hashdb::constant). Same for hashdb_del and hashdb_shrink. Default load factor of 0.75 used by hashdb_grow and hashdb_shrink to check if should grow or shrink. This is my first hash table implmentation. I now use double hashing + quadratic probing. I've tested if my formula hit every index and I think it does because I don't get any segmentation fault if I calculate the hash in range of the capacity. Hope this makes things more clear. misc.h (included by hashdb_internal) #ifndef _HASHDB_MISC_H #define _HASHDB_MISC_H #include <stdio.h> #include <stdbool.h> /*! @function @param n number to test if prime @return true if prime, false if not */ bool IsPrime(size_t n); /*! @function @param n number to get next bigger prime @return next bigger prime number */ size_t GetHigherPrime(size_t n); /*! @function @param n number to get next bigger prime @return next lower prime number */ size_t GetLowerPrime(size_t n); /*! @function @param str string to hash @return fnv hash */ size_t fnv_hash_string(const char *str); /*! @function @param data data to hash @param size size of data to hash @return fnv hash */ size_t fnv_hash(unsigned char *data, size_t size); /*! @function @param str string to hash @return elf hash */ size_t elfhash(const unsigned char *str); #endif
{ "domain": "codereview.stackexchange", "id": 44546, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "performance, beginner, c, hash-map", "url": null }
performance, beginner, c, hash-map #endif misc.c #include "misc.h" #include <stdbool.h> #include <limits.h> #define FNV_OFFSET 14695981039346656037UL #define FNV_PRIME 1099511628211UL /* Definition of prime number functions */ /*! @function @param n number to test @return ture if is prime, false if is not prime */ bool IsPrime(size_t n) { if((n & 1) != 0) { for(size_t divisor = 3; divisor <= n / divisor; divisor += 2) { if((n % divisor) == 0) { return 0; } } return 1; } return (n == 2); } /*! @function @param n number to get next higher prime from @return next higher prime from n */ size_t GetHigherPrime(size_t n) { for(size_t i = (n | 1); i < LONG_MAX; i += 2) { if(IsPrime(i)) { return i; } } return n; } /*! @function @param n number to get next lower prime from @return next lower prime from n */ size_t GetLowerPrime(size_t n) { for(size_t i = (n | 1); i < LONG_MAX; i -= 2) { if(IsPrime(i)) { return i; } } return n; } /* hashing functions */ /*! @function @param str null terminated character string to hash @return hash in form of size_t */ size_t fnv_hash_string(const char *str) { size_t hash; int i; for(i = 0, hash = FNV_OFFSET; *str != '\0'; str++, i++) { hash = hash ^ *str; hash = hash * FNV_PRIME; } return hash; } /*! @function @param data unsigned byte array @param size size of byte array @return hash in form of size_t */ size_t fnv_hash(unsigned char *data, size_t size) { size_t hash; int i; for(i = 0, hash = FNV_OFFSET; size != 0; size--, i++) { hash = hash ^ *data; hash = hash * FNV_PRIME; } return hash; }
{ "domain": "codereview.stackexchange", "id": 44546, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "performance, beginner, c, hash-map", "url": null }
performance, beginner, c, hash-map /*! @function @param str null terminated character string to hash @return hash in form of size_t */ unsigned long elfhash(const unsigned char *str) { unsigned long h = 0, high; while (*str) { h = (h << 4) + *str++; if ((high = h & 0xF0000000)) h ^= high >> 24; h &= ~high; } return h; } hashdb_internal.h (included by hashdb) #ifndef _HASHDB_INTERNAL_H #define _HASHBD_INTERNAL_H #include "misc.h" /* definitions */ #define HASHDB_DEFAULT_CAPACITY 7 /* prime number */ #define HASHDB_DEFAULT_LOADFACTOR 0.90 /* */ /* get index by this ... formular */ #define hash_probe(hash, i, cap) ((hash + (-1) * (i * i + 1) * (i / 2) * (i / 2)) % cap) /* simple bucket that holds an pointer key as string and pointer to value */ typedef struct bucket { const char *key; void *value; } bucket; /* hashdb holding capacity (number of elements), n (number of elements inside), map (memory location of entries) */ typedef struct hashdb { size_t cap; size_t n; bucket *map; bool constant; } hashdb; /*! @function @param list pointer to bucket list @param capacity capacity of bucket list @param key key to store @param value value to store by key @return 0 if succes, -1 if failure */ int hashdb_insert(bucket *list, size_t capacity, const char *key, void *value); /*! @function @param list pointer to list to return from @param capacity capacity of list @param key key to get data from @return location of bucket */ bucket* hashdb_return(bucket *list, size_t capacity, const char *key); /*! @function @param old_list old list with data @param old_cap old_list's capacity @param new_list new_list to insert to @param new_cap new_list's capacity */ void hashdb_rehash(bucket *old_list, size_t old_cap, bucket *new_list, size_t new_cap);
{ "domain": "codereview.stackexchange", "id": 44546, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "performance, beginner, c, hash-map", "url": null }
performance, beginner, c, hash-map /*! @function @param db hashdb pointer @param new_cap new capacity @return 0 on succes, ENOMEM on failure */ int hashdb_realloc(hashdb *db, size_t new_cap); /*! @function @param db hashdb pointer @return 0 if nothing to allocate or reallocated successfully, ENOMEM on failure */ int hashdb_grow(hashdb *db); /*! @function @param db hashdb pointer @return 0 if nothing to allocate or reallocated successfully, ENOMEM on failure */ int hashdb_shrink(hashdb *db); /*! @function @param str null terminated string to hash */ size_t double_hash(const char *str); #endif hashdb_internal.c #include "hashdb_internal.h" #include <stdlib.h> #include <string.h> #include <stdbool.h> #include <errno.h> /*! @function @param list pointer to bucket list @param capacity capacity of bucket list @param key key to store @param value value to store by key @return 0 if succes, -1 if failure */ int hashdb_insert(bucket *list, size_t capacity, const char *key, void *value) { size_t i = 0; size_t hash = double_hash(key); size_t probe = 0; /* starting at 1 because 1 and 0 would get the same probe so we can safe that step */ for(i = 1; i <= capacity; i++) { probe = hash_probe(hash, i, capacity); if(list[probe].key == NULL) { list[probe].key = key; list[probe].value = value; return 0; } } return -1; } /*! @function @param list pointer to list to return from @param capacity capacity of list @param key key to get data from @return location of bucket */ bucket* hashdb_return(bucket *list, size_t capacity, const char *key) { size_t i = 0; size_t probe = 0; size_t hash = double_hash(key); for(i = 1; i <= capacity; i++) { probe = hash_probe(hash, i, capacity);
{ "domain": "codereview.stackexchange", "id": 44546, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "performance, beginner, c, hash-map", "url": null }
performance, beginner, c, hash-map for(i = 1; i <= capacity; i++) { probe = hash_probe(hash, i, capacity); if(list[probe].key != NULL) { if(strcmp(key, list[probe].key) == 0) { return &list[probe]; } } } return NULL; } /*! @function @param old_list old list with data @param old_cap old_list's capacity @param new_list new_list to insert to @param new_cap new_list's capacity */ void hashdb_rehash(bucket *old_list, size_t old_cap, bucket *new_list, size_t new_cap) { for(size_t i = 0; i < old_cap; i++) { if(old_list[i].key != NULL) { hashdb_insert(new_list, new_cap, old_list[i].key, old_list[i].value); } } } /*! @function @param db hashdb pointer @param new_cap new capacity @return 0 on succes, ENOMEM on failure */ int hashdb_realloc(hashdb *db, size_t new_cap) { bucket *new_list = calloc(new_cap, sizeof *db->map); if(new_list == NULL) { return ENOMEM; } hashdb_rehash(db->map, db->cap, new_list, new_cap); free(db->map); db->map = new_list; db->cap = new_cap; return 0; } void hashdb_enable_constant(hashdb *db, bool newval) { db->constant = newval; } /*! @function @param db hashdb pointer @return 0 if nothing to allocate or reallocated successfully, ENOMEM on failure */ int hashdb_grow(hashdb *db) { if((db->n != (size_t) (db->cap * HASHDB_DEFAULT_LOADFACTOR)) || db->constant == true) { return 0; } size_t new_cap = GetHigherPrime(db->cap * 2); if(hashdb_realloc(db, new_cap) != 0) { return ENOMEM; } return 0; } /*! @function @param db hashdb pointer @return 0 if nothing to allocate or reallocated successfully, ENOMEM on failure */ int hashdb_shrink(hashdb *db) { if(db->cap <= HASHDB_DEFAULT_CAPACITY){ db->cap = HASHDB_DEFAULT_CAPACITY; return 0; }
{ "domain": "codereview.stackexchange", "id": 44546, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "performance, beginner, c, hash-map", "url": null }
performance, beginner, c, hash-map if((db->n != (size_t) (db->cap * (1 - HASHDB_DEFAULT_LOADFACTOR))) || db->constant == true) { return 0; } size_t new_cap = GetLowerPrime(db->cap / 2); if(hashdb_realloc(db, new_cap) != 0) { return ENOMEM; } return 0; } size_t double_hash(const char *str) { return elfhash((const unsigned char*) str) + fnv_hash_string(str); } hashdb.h #ifndef _HMAP_H #define _HMAP_H #include <stdio.h> #include <stdbool.h> typedef void hashdb; hashdb* hashdb_create(void); void hashdb_destroy(hashdb *db); void hashdb_enable_constant(hashdb *db, bool newval); size_t hashdb_cap(hashdb *db); size_t hashdb_len(hashdb *db); double hashdb_filled_percent(hashdb *db); int hashdb_add(hashdb *db, const char *key, const void *data); void* hashdb_get(hashdb *db, const char *key); void* hashdb_del(hashdb *db, const char *key); int hashdb_ensure_capacity(hashdb *db, size_t new_capacity); /* int hashdb_clear(hashdb *db); int hashdb_reset(hashdb *db); int hashdb_hardreset(hashdb *db); int hashdb_to_json(hashdb *db, const char *path); int hashdb_from_json(hashdb *db, const char *path); int hashdb_to_http(hashdb *db, char *buffer, size_t bufsiz); int hashdb_from_http(hashdb *db, char *buffer, size_t bufsiz); */ void hashdb_printall(hashdb *db); #endif hashdb.c #include <stdio.h> #include <stdlib.h> #include <string.h> #include <errno.h> #include <limits.h> #include <ctype.h> #include <time.h> #include "hashdb_internal.h" #define HASHDB_DEFAULT_CAP 7 /*! @function @return hashdb pointer */ hashdb* hashdb_create() { hashdb *db = calloc(1, sizeof *db); if(db == NULL) { return NULL; } db->cap = HASHDB_DEFAULT_CAP; db->map = calloc(db->cap, sizeof *db->map); if(db->map == NULL) { free(db); return NULL; } return db; } /*! @function @param db hashdb pointer to destroy */ void hashdb_destroy(hashdb *db) { free(db->map); free(db); }
{ "domain": "codereview.stackexchange", "id": 44546, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "performance, beginner, c, hash-map", "url": null }
performance, beginner, c, hash-map /*! @function @param db hashdb pointer @param key key @param value value associated with key @return 0 on success, ENOMEM on failure */ int hashdb_add(hashdb *db, const char *key, void *value) { if(db->n == db->cap) { return -1; /* full, should not happen */ } /* check if it should grow */ if(hashdb_grow(db) != 0) { return ENOMEM; } if(hashdb_insert(db->map, db->cap, key, value)) { return -1; /* internal error */ } db->n++; return 0; } /*! @function @param db hashdb pointer @param key key to retrieve date from @return data associated with key */ void* hashdb_get(hashdb *db, const char *key) { bucket *item = hashdb_return(db->map, db->cap, key); if(item == NULL) { return item; /* not found */ } return item->value; } /*! @function @param db hashdb pointer @param key key to retrieve date from @return data associated with key */ void* hashdb_del(hashdb *db, const char *key) { bucket *item = hashdb_return(db->map, db->cap, key); if(item == NULL) { return item; } void *value = item->value; item->key = NULL; item->value = NULL; db->n--; if(hashdb_shrink(db) != 0) { return NULL; } return value; } /*! @function @param db hashdb pointer @param new_capacity new number of elements @return 0 on succes, ENOMEM on failure */ int hashdb_ensure_capacity(hashdb *db, size_t new_capacity) { size_t new_cap = GetHigherPrime(new_capacity); if(hashdb_realloc(db, new_cap) != 0) { return ENOMEM; } return 0; } size_t hashdb_cap(hashdb *db) { return db->cap; } size_t hashdb_len(hashdb *db) { return db->n; } double hashdb_filled_percent(hashdb *db) { return (double) db->n / db->cap * 100; } void hashdb_printall(hashdb *db) { for(size_t i = 0; i < db->cap; i++) { printf("%s\n", db->map[i].key); } }
{ "domain": "codereview.stackexchange", "id": 44546, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "performance, beginner, c, hash-map", "url": null }
performance, beginner, c, hash-map hashdb_test.c #include "../../include/hashdb.h" #include "timebot.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #define ROCKYOU_PATH "../src/test/data/rockyou.txt" #define ROCKYOU_LINES 14344392 /* number of lines in rockyou.txt */ #define HASHDB_START_GET_FROM 121512 /* start point for hashdb_test_get_1000_keys and hashdb_test_get_key*/ char **test_keys = NULL; /* initialize keys from rockyou.txt */ int init_test_keys(const char *path) { FILE *fp = fopen(path, "r"); if(fp == NULL) { perror("open file"); return -1; } test_keys = calloc(ROCKYOU_LINES, sizeof *test_keys); if(test_keys == NULL) { perror("init_test_keys"); return -1; } char key_buf[128]; for(size_t i = 0; i < ROCKYOU_LINES; i++) { fgets(key_buf, sizeof(key_buf), fp); key_buf[strlen(key_buf)-1] = '\0'; test_keys[i] = strdup(key_buf); } fclose(fp); return 0; } void destroy_keys() { for(size_t i = 0; i < ROCKYOU_LINES; i++) { free(test_keys[i]); } free(test_keys); } void hashdb_test_fullfill(hashdb *db) { for(size_t i = 0; i < hashdb_cap(db); i++) { if(hashdb_add(db, test_keys[i], test_keys[i]) != 0) { fprintf(stderr, "error: hashdb_add failed\n"); abort(); } //printf("adding Key: %s - %s\n", test_keys[i], test_keys[i]); } char *res = NULL; for(size_t i = 0; i < hashdb_cap(db); i++) { res = hashdb_get(db, test_keys[i]); if(res == NULL) { fprintf(stderr, "error: hashdb_get failed\n"); abort(); } //printf("getting Key: %s - %s\n", test_keys[i], res); } }
{ "domain": "codereview.stackexchange", "id": 44546, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "performance, beginner, c, hash-map", "url": null }
performance, beginner, c, hash-map } void test_not_found_cap_rockyou(hashdb *db) { char *res = hashdb_get(db, "definitely not inside"); if(res != NULL) { fprintf(stderr, "definitely not inside - found (failure/must not happen)\n"); abort(); } //printf("definitely not inside - not found (success) rockyou\n"); } void test_not_found_default_cap(hashdb *db) { char *res = hashdb_get(db, "definitely not inside"); if(res != NULL) { fprintf(stderr, "definitely not inside - found (failure/must not happen)\n"); abort(); } //printf("definitely not inside - not found (success) default\n"); } /* test append 14344392 keys */ void hashdb_test_append_rockyou(hashdb *db) { size_t x = ROCKYOU_LINES-1; size_t i; for(i = 0; i < ROCKYOU_LINES; i++, x--) { if(hashdb_add(db, test_keys[i], test_keys[x]) != 0) { fprintf(stderr, "error: hashdb_test_append_rockyou\n"); abort(); } } } /* test get 1000 keys */ void hashdb_test_get_1000_keys(hashdb *db) { for(size_t i = HASHDB_START_GET_FROM; i < HASHDB_START_GET_FROM + 1000; i++) { const char *res = hashdb_get(db, test_keys[i]); if(res == NULL) { fprintf(stderr, "error: hashdb_test_get_1000_keys"); abort(); } } } /* test get single keys */ void hashdb_test_get_key(hashdb *db) { const char *res = hashdb_get(db, test_keys[HASHDB_START_GET_FROM]); if(res == NULL) { fprintf(stderr, "error: hashdb_test_get_key"); abort(); } } /* test get all keys */ void hashdb_test_get_rockyou(hashdb *db) { for(size_t i = 0; i < ROCKYOU_LINES; i++) { const char *res = hashdb_get(db, test_keys[i]); if(res == NULL) { fprintf(stderr, "error: hashdb_test_get_rockyou"); abort(); } } }
{ "domain": "codereview.stackexchange", "id": 44546, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "performance, beginner, c, hash-map", "url": null }
performance, beginner, c, hash-map void hashdb_test_del_rockyou(hashdb *db) { for(size_t i = 0; i < ROCKYOU_LINES; i++) { const char *res = hashdb_del(db, test_keys[i]); if(res == NULL) { fprintf(stderr, "error: hashdb_test_del_rockyou"); abort(); } } } void hashdb_test_del_default(hashdb *db) { for(size_t i = 0; i < hashdb_cap(db); i++) { const char *res = hashdb_del(db, test_keys[i]); if(res == NULL) { fprintf(stderr, "error: hashdb_test_del_rockyou"); abort(); } } } int main(void) { timebot *bot = timebot_create(20); if(init_test_keys(ROCKYOU_PATH) != 0) { return EXIT_SUCCESS; } hashdb *db = hashdb_create(); /* enable constant so it don't execute the grow function */ hashdb_enable_constant(db, true); timebot_standalone(bot, hashdb_test_fullfill, db, "test if hashdb is filled completely if growing is disabled"); timebot_standalone(bot, test_not_found_default_cap, db, "test if not found works with default capacity"); timebot_standalone(bot, hashdb_test_del_default, db, "delete HASHDB_DEFAULT_CAP entries"); hashdb_enable_constant(db, false); /* disable constant so it executes the grow function */ printf("after creation and adding 7 (HASHDB_DEFAULT_CAPACITY)\n"); printf("\ncap: %1lu (should be 7)\n", hashdb_cap(db)); printf("len: %1lu (should be 0)\n", hashdb_len(db)); printf("filled: %2.1f (should be 0.0)\n", hashdb_filled_percent(db)); // ensure capacity fits with lines in rockyou.txt hashdb_ensure_capacity(db, ROCKYOU_LINES * 2);
{ "domain": "codereview.stackexchange", "id": 44546, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "performance, beginner, c, hash-map", "url": null }
performance, beginner, c, hash-map timebot_append(bot, hashdb_test_append_rockyou, db, "adding 14.344.392 keys to hashdb"); timebot_append(bot, hashdb_test_get_key, db, "get one key"); timebot_append(bot, hashdb_test_get_1000_keys, db, "get 1000 keys"); timebot_append(bot, hashdb_test_get_rockyou, db, "get all keys"); timebot_append(bot, test_not_found_cap_rockyou, db, "key is not found with cap of 14.3 million entries"); timebot_run(bot); printf("\nafter appending rockyou.txt\n"); printf("cap: %lu\n", hashdb_cap(db)); printf("len: %lu\n", hashdb_len(db)); printf("filled: %f\n", hashdb_filled_percent(db)); timebot_standalone(bot, hashdb_test_del_rockyou, db, "deleting all rockyou keys"); hashdb_add(db, "testkey", "testdata"); printf("\nafter deleting all and adding one\n"); printf("cap: %lu\n", hashdb_cap(db)); printf("len: %lu\n", hashdb_len(db)); printf("filled: %f\n", hashdb_filled_percent(db)); timebot_print_summery(bot); hashdb_destroy(db); destroy_keys(); timebot_destroy(bot); } timebot.h (used by hashdb_test.c) #ifndef _TIMEBOT_H #define _TIMEBOT_H #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> #include <errno.h> typedef struct excecute_bundle { const char *description; const char *function_name; void (*run)(void*); void *arg; double runtime; } excecute_bundle; typedef struct timebot { excecute_bundle *exec_pool; int n; double capacity; double total_time; double longest_rtime; const char *longest_rtime_fname; int longest_function_name_length; } timebot; /*! @function @param n number of preallocated executions @return timebot pointer */ static timebot *timebot_create(size_t n) { timebot *bot = (timebot *) calloc(1, sizeof *bot); if(bot == NULL) { perror("timebot_create"); /* this must not happen */ abort(); }
{ "domain": "codereview.stackexchange", "id": 44546, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "performance, beginner, c, hash-map", "url": null }
performance, beginner, c, hash-map bot->exec_pool = (excecute_bundle *) calloc(n, sizeof *bot->exec_pool); if(bot->exec_pool == NULL) { perror("timebot_create execution pool"); abort(); } return bot; } static void timebot_destroy(timebot *tb) { free(tb->exec_pool); free(tb); } /* runs function with a argument and logs its runtime */ static void _get_runtime(excecute_bundle *bundle) { clock_t start = clock(); bundle->run(bundle->arg); bundle->runtime = (double) (clock() - start) / CLOCKS_PER_SEC; } static void _tb_append(timebot *tb, void (*func)(void *), void *arg, const char *name, const char *description) { excecute_bundle *current = &tb->exec_pool[tb->n]; size_t fname_len = strlen(name); if(fname_len > tb->longest_function_name_length) { tb->longest_function_name_length = fname_len; } current->function_name = name; current->run = func; current->arg = arg; current->description = description; tb->n++; } static void _tb_standalone(timebot *tb, void (*func)(void *), void *arg, const char *name, const char *description) { _tb_append(tb, func, arg, name, description); excecute_bundle *current = &tb->exec_pool[tb->n-1]; _get_runtime(current); current->run = NULL; current->arg = NULL; } /* append to timebot's execution list */ #define timebot_append(tb, func, arg, desc) _tb_append(tb, func, arg, #func, desc) #define timebot_standalone(tb, func, arg, desc) _tb_standalone(tb, func, arg, #func, desc) /* runs all appended functions */ static void timebot_run(timebot *tb) { excecute_bundle *current; for(size_t i = 0; i < tb->n; i++) { current = &tb->exec_pool[i]; if(current->run != NULL) { _get_runtime(current); if(current->runtime > tb->longest_rtime) { tb->longest_rtime = current->runtime; tb->longest_rtime_fname = current->function_name; } } } }
{ "domain": "codereview.stackexchange", "id": 44546, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "performance, beginner, c, hash-map", "url": null }
performance, beginner, c, hash-map /* compare functions execution time */ static void timebot_compare(timebot *tb) { excecute_bundle *current; printf("\nTimebot Summery:\n%*s\tTime\n", -tb->longest_function_name_length, "Function"); for(size_t i = 0; i < tb->n; i++) { current = &tb->exec_pool[i]; printf("%*s\t%f sec (faster than %s by %f%%)\n", -tb->longest_function_name_length, current->function_name, current->runtime, tb->longest_rtime_fname, 100 - (current->runtime / tb->longest_rtime * 100)); } } /* prints a summery of all executions */ static void timebot_print_summery(timebot *tb) { excecute_bundle *current; printf("\nTimebot Summery:\n %*s | Time\n", -tb->longest_function_name_length, "Function"); printf(" --------------------------------------------------------------------\n"); for(size_t i = 0; i < tb->n; i++) { current = &tb->exec_pool[i]; if(current->run == NULL) { printf(" %*s | %f sec STANDALONE (%s)\n", -tb->longest_function_name_length, current->function_name, current->runtime, current->description); } else { printf(" %*s | %f sec (%s)\n", -tb->longest_function_name_length, current->function_name, current->runtime, current->description); } } } #endif
{ "domain": "codereview.stackexchange", "id": 44546, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "performance, beginner, c, hash-map", "url": null }
performance, beginner, c, hash-map #endif Answer: General Observations Interesting question! As the comments show, a lot of room for learning! Consistency! Some header files are using Doxygen Comments, other headers are not, some header files don't even have comments. Pick a style and stay with it. When you use Doxygen for one function in a file use it for all functions in the file. Header files with commented out function prototypes (hashdb.h) are not ready for code review. I recommend using a configuration management system such as Git. You can store your files on GitHub. This allows you to delete code and be able to restore it if you want to. When I was starting out as a software engineer it was common to run lint on the code after it compiled, this found a lot of errors in the code. This isn't really necessary now if you use the proper compiler flags (for gcc -pedantic, -Wall, -Wextra, and -Wconversion for Visual Studio Warning Level3 or Level4). This allowed me to find some problems in the code such as a type mismatch between the prototype declarations of elfhash(const unsigned char *str) and the implementation of elfhash(const unsigned char *str). misc.h: size_t elfhash(const unsigned char *str); misc.c unsigned long elfhash(const unsigned char *str) This particular mismatch problem is important because size_t is implementation dependent and may not use a unsigned long on all systems. Other type mismatches:
{ "domain": "codereview.stackexchange", "id": 44546, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "performance, beginner, c, hash-map", "url": null }
performance, beginner, c, hash-map timebot.h(71,44): warning C4267: '=': conversion from 'size_t' to 'int', possible loss of data hashdb_test.c.c(187,12): warning C4477: 'printf' : format string '%1lu' requires an argument of type 'unsigned long', but variadic argument 1 has type 'size_t' hashdb_test.c(187,12): message : consider using '%zu' in the format string hashdb_test.c(188,12): warning C4477: 'printf' : format string '%1lu' requires an argument of type 'unsigned long', but variadic argument 1 has type 'size_t' hashdb_test.c(188,12): message : consider using '%zu' in the format string hashdb_test.c(204,12): warning C4477: 'printf' : format string '%lu' requires an argument of type 'unsigned long', but variadic argument 1 has type 'size_t' hashdb_test.c(204,12): message : consider using '%zu' in the format string hashdb_test.c(205,12): warning C4477: 'printf' : format string '%lu' requires an argument of type 'unsigned long', but variadic argument 1 has type 'size_t' hashdb_test.c(205,12): message : consider using '%zu' in the format string hashdb_test.c(214,12): warning C4477: 'printf' : format string '%lu' requires an argument of type 'unsigned long', but variadic argument 1 has type 'size_t' hashdb_test.c(214,12): message : consider using '%zu' in the format string hashdb_test.c(215,12): warning C4477: 'printf' : format string '%lu' requires an argument of type 'unsigned long', but variadic argument 1 has type 'size_t' hashdb_test.c(215,12): message : consider using '%zu' in the format string In the function main() should this really be the code? if(init_test_keys(ROCKYOU_PATH) != 0) { return EXIT_SUCCESS; } or should it be if(init_test_keys(ROCKYOU_PATH) != 0) { return EXIT_FAILURE; }
{ "domain": "codereview.stackexchange", "id": 44546, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "performance, beginner, c, hash-map", "url": null }
performance, beginner, c, hash-map or should it be if(init_test_keys(ROCKYOU_PATH) != 0) { return EXIT_FAILURE; } Doxygen Comments This is a great system for documenting the code, I reccomend that you either use it in the header files or the source files but not both. It is very hard to maintain 2 different sets of comments and keep them in sync. timebot.h I recommend putting the actual C source code in timebot.c and only putting the data structure declarations and prototype functions in in timebot.h. While the code does a good job of protecting the functions with static declarations C source code generally isn't put into header files. Magic Numbers The code already has a lot of symbolic constants and this is really good, but there is code where there are still raw numbers that need explanation: misc.c bool IsPrime(size_t n) { if((n & 1) != 0) { for(size_t divisor = 3; divisor <= n / divisor; divisor += 2) { if((n % divisor) == 0) { return 0; } } return 1; } return (n == 2); } size_t GetHigherPrime(size_t n) { for(size_t i = (n | 1); i < LONG_MAX; i += 2) { if(IsPrime(i)) { return i; } } return n; } size_t GetLowerPrime(size_t n) { for(size_t i = (n | 1); i < LONG_MAX; i -= 2) { if(IsPrime(i)) { return i; } } return n; } size_t elfhash(const unsigned char *str) { size_t h = 0, high; while (*str) { h = (h << 4) + *str++; if ((high = h & 0xF0000000)) h ^= high >> 24; h &= ~high; } return h; }
{ "domain": "codereview.stackexchange", "id": 44546, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "performance, beginner, c, hash-map", "url": null }
performance, beginner, c, hash-map Variable Declarations A best practice in most programming languages is to declare a single variable per line. In the C and C++ programming languages this best practice also suggests that each variable be initiated on that line as well since neither language provides default values for variables. It turns out that the lack of initialization is a source of many bugs (I have had to trace this error through someone else's code when I was merging libraries into an executable). In the elfhash function above the code: size_t h = 0, high; would be better written if it was: size_t h = 0; size_t high = 0; One of the reasons for putting each variable on its own line is that it improves readability and maintainability. While Loops Versus For Loops The for loops in fnv_hash_string(const char *str) and fnv_hash(unsigned char *data, size_t size) should be while loops, at no point is the loop counter variable i used. Loop invariants should be moved out of the loop, and i is a loop invariant. An optimizing compiler might fix the performance in this code and it might not, there are also times that you can't use the optimization of the compiler such as when you are working on embedded systems. size_t fnv_hash_string(const char *str) { size_t hash; int i; for(i = 0, hash = FNV_OFFSET; *str != '\0'; str++, i++) { hash = hash ^ *str; hash = hash * FNV_PRIME; } return hash; } size_t fnv_hash_string(const char *str) { size_t hash = FNV_OFFSET; while (*str) { hash = hash ^ *str; hash = hash * FNV_PRIME; str++; } return hash; }
{ "domain": "codereview.stackexchange", "id": 44546, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "performance, beginner, c, hash-map", "url": null }
performance, beginner, c, hash-map return hash; } DRY Code There is a programming principle called the Don't Repeat Yourself Principle sometimes referred to as DRY code. If you find yourself repeating the same code multiple times it is better to encapsulate it in a function. If it is possible to loop through the code that can reduce repetition as well. The 2 hash functions in misc.c, size_t fnv_hash_string(const char *str) and size_t fnv_hash(unsigned char *data, size_t size) appear to be a duplication of the code, this may be a problem in the future, however, fnv_hash() is never called and can probably be removed. There doesn't seem to be a reason to ever use fnv_hash() since a size shouldn't ever be needed. The functions size_t GetHigherPrime(size_t n) and GetLowerPrime(size_t n) could also be merged if a second parameter, direction is added. #define HIGHERPRIME 2 #define LOWERPRIME -2 size_t GetOtherPrime(size_t n, int direction) { for (size_t i = (n | 1); i < LONG_MAX; i += direction) { if (IsPrime(i)) { return i; } } return n; }
{ "domain": "codereview.stackexchange", "id": 44546, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "performance, beginner, c, hash-map", "url": null }
python, python-3.x, object-oriented, comparative-review Title: Wordlist formatter code Question: I am making a "wordlist cleaner" module that loads a words.txt file, and returns a list of cleaned/sorted words. Full code: import logging MIN_WORD_LENGTH = 3 MAX_WORD_LENGTH = 25 class WordlistCleaner: def _load_words_from_file(self, words_file: str): """Loads a list of words from a file""" words = [line.strip() for line in open(words_file, encoding="utf-8").read().lower().splitlines()] if len(words) == 0: logging.warning(f"No words were found in the {words_file} file.\nExiting script...") quit() return words def _remove_invalid_words(self, words: list[str]): """Cleans a list of words by removing words that do not adhere to requirements""" valid_words = [] for word in words: if len(word) > MAX_WORD_LENGTH or len(word) < MIN_WORD_LENGTH: logging.warning(f"{word} has been excluded - words MIN_word_LENGTH be between 3 and 25 characters.") continue try: word.encode("ascii") except UnicodeEncodeError: logging.warning(f"{word} has been excluded - words must not contain Unicode characters.") continue valid_words.append(word) return valid_words def _remove_duplicates(self, words: list[str]): """Removes duplicates from a list""" return list(set(words)) def clean_words(self, words_file: str): """Takes a filename / filepath as input and returns the cleaned words""" unsorted_words= self._load_words_from_file(words_file) valid_words = self._remove_invalid_words(unsorted_words) if len(unsorted_words) > len(valid_words): logging.warning( f"{len(unsorted_words)-len(valid_words)} words have been removed from the list as they were invalid" )
{ "domain": "codereview.stackexchange", "id": 44547, "lm_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, object-oriented, comparative-review", "url": null }
python, python-3.x, object-oriented, comparative-review sorted_words = self._remove_duplicates(valid_words) if len(valid_words) > len(sorted_words): logging.warning(f"{len(valid_words)-len(sorted_words)} duplicate words have been found and removed") with open(words_file, "w", encoding="ascii") as f: for word in sorted_words: f.write(word + "\n") logging.info(f"The {words_file} file has been updated.") return sorted_words cleaner = WordlistCleaner() cleaned_wordlist = cleaner.clean_words("words.txt") The goal is to just load a wordlist and make sure that every word adheres to requirements. This includes removing duplicates, words with Unicode characters, and words that don't meet character limits. I was wondering if anyone knew how I could clean up the code a bit, since it feels very messy now. I also have a habit of having this "top down" method execution approach when writing classes. That is, the method at the bottom of the class executes all of the top methods chronologically until it reaches the bottom. Not sure if there's anything wrong with that, but it is definitely a pattern I've noticed in a few of my programs. Moreover, I'm not sure if it's bad practice to call quit() if an empty file is provided, or if an exception would be more appropriate. Thank you in advance for any help/suggestions. Answer: There's nothing wrong with the "chronological" aspect of execution. I like the nice separation of public() vs _private() (helper) methods. Nice MANIFEST_CONSTANTS. Identifiers are spelled as PEP-8 recommends. bad practice to call quit() [?] Yes, definitely bad practice. Just raise an informative error and call it a day. If top-level caller drops out, fine, we drop out. (I assume that quit calls sys.exit(), but TBH it doesn't come up much outside an interactive context, and help(quit) proved rather less than informative.) words = [line.strip() for line in open(words_file, encoding="utf-8").read().lower().splitlines()]
{ "domain": "codereview.stackexchange", "id": 44547, "lm_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, object-oriented, comparative-review", "url": null }
python, python-3.x, object-oriented, comparative-review I know, I know, all the cool kids are doing "one liners". But rather than leaving an open file descriptor lying around, I would much rather see you use an explicit context handler that will close() when it's no longer needed. If you speak idiomatically it imposes less cognitive burden on the reader, so greater attention can be devoted to the novel pieces that matter. with open(words_file, encoding="utf-8") as f: words = [line.strip() for line in f.read().lower().splitlines()] This is just wrong: logging.warning(f"No words were found in the {words_file} file.\nExiting script...") quit() Please don't do that. It clearly is not a "warning". Rather, it is a fatal "error", and logging offers a method for that. The appropriate way to signal such trouble is with raise. Could be raise ValueError("No words..."), or with some new error you might choose to define. If caller exits, fine, that's similar to quit(). If caller catches the error and moves on, that's for the caller to decide and not for this low-level code. This is a lovely docstring: """Loads a list of words from a file""" Concise. Accurate. Consider augmenting the optional type hinting in the signature to reflect that we're returning List[str]. This is good: logging.warning(f"{word} has been excluded ... but I'm going to quibble with the "3 and 25" part of that string literal, on DRY grounds. You have some lovely constants defined already. So use them! ... between {MIN_WORD_LENGTH} and {MAX_WORD_LENGTH} characters.") In the words must not contain Unicode characters diagnostic, I get what you mean. But strictly speaking every 7-bit ASCII character is definitely a unicode codepoint. So let's rephrase it as words must be just ASCII characters. In _remove_duplicates we call both set and list, but just set would suffice. Then later we see sorted_words = self._remove_duplicates(valid_words)
{ "domain": "codereview.stackexchange", "id": 44547, "lm_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, object-oriented, comparative-review", "url": null }
python, python-3.x, object-oriented, comparative-review I do not understand that identifier at all. These words are in no way sorted. We could fix it in this way: return sorted(set(words)) Overall? Only minor issues, mostly related to reporting errors. This code achieves its objectives, and is maintainable. Is this "messy"? No, I'm not seeing that. There are some things we need to compute, and they are addressed in a straightforward way. No unit tests appeared in this submission.
{ "domain": "codereview.stackexchange", "id": 44547, "lm_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, object-oriented, comparative-review", "url": null }
c++, library, timer, template-meta-programming, c++23 Title: scoped timer class (3rd revision) Question: Again, here is the previous question. I have (re)revised my custom scoped timer using the valuable feedback I got from a helpful member of this community. However I feel the need to ask this question so that my new solution is reviewed. Here is the code (Compiler Explorer): #include <chrono> #include <type_traits> #include <functional> #include <exception> #include <utility> // these are only required by client code #include <thread> #include <cstdio> #include <fmt/core.h> #include <fmt/chrono.h> #define NODISCARD_WARNING_MSG "ignoring returned value of type 'ScopedTimer' might " \ "change the program's behavior since it has side effects" template < class Duration = std::chrono::microseconds, class Clock = std::chrono::steady_clock > requires ( std::chrono::is_clock_v<Clock> && requires { std::chrono::time_point<Clock, Duration>{ }; } ) class [[ nodiscard( NODISCARD_WARNING_MSG ) ]] ScopedTimer { public: using clock = Clock; using duration = Duration; using rep = Duration::rep; using period = Duration::period; using time_point = std::chrono::time_point<Clock, Duration>; using callback_type = std::conditional_t< noexcept( Clock::now( ) ), std::move_only_function<void ( Duration ) noexcept>, std::move_only_function<void ( Duration, std::exception_ptr ) noexcept> >; [[ nodiscard( "implicit destruction of temporary object" ) ]] explicit ScopedTimer( callback_type&& callback = nullptr ) noexcept( noexcept( now( ) ) ) : m_callback { std::move( callback ) } { } [[ nodiscard( "implicit destruction of temporary object" ) ]] ScopedTimer( ScopedTimer&& rhs ) noexcept = default;
{ "domain": "codereview.stackexchange", "id": 44548, "lm_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++, library, timer, template-meta-programming, c++23", "url": null }
c++, library, timer, template-meta-programming, c++23 ~ScopedTimer( ) { if ( m_callback == nullptr ) return; if constexpr ( noexcept( now( ) ) ) { const time_point end { now( ) }; m_callback( end - m_start ); } else { try { const time_point end { now( ) }; m_callback( end - m_start, nullptr ); } catch ( ... ) { const std::exception_ptr ex_ptr { std::current_exception( ) }; m_callback( duration { }, ex_ptr ); } } } [[ nodiscard ]] const time_point& get_start( ) const& noexcept { return m_start; } [[ nodiscard ]] const time_point& get_start( ) const&& noexcept = delete; [[ nodiscard ]] const callback_type& get_callback( ) const& noexcept { return m_callback; } [[ nodiscard ]] const callback_type& get_callback( ) const&& noexcept = delete; void set_callback( callback_type&& callback ) & noexcept { m_callback = std::move( callback ); } void set_callback( callback_type&& callback ) && noexcept = delete; [[ nodiscard ]] duration elapsed_time( ) const& noexcept( noexcept( now( ) ) ) { return now( ) - m_start; } [[ nodiscard ]] duration elapsed_time( ) const&& noexcept( noexcept( now( ) ) ) = delete; [[ nodiscard ]] time_point static now( ) noexcept( noexcept( clock::now( ) ) ) { return std::chrono::time_point_cast<duration>( clock::now( ) ); } private: time_point const m_start { now( ) }; callback_type m_callback; }; template <class Callback> ScopedTimer( Callback&& ) -> ScopedTimer<>; template <class Duration> ScopedTimer( std::move_only_function<void ( Duration ) noexcept> ) -> ScopedTimer<Duration>; // --------------------------- client code --------------------------- using std::chrono_literals::operator""ms;
{ "domain": "codereview.stackexchange", "id": 44548, "lm_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++, library, timer, template-meta-programming, c++23", "url": null }
c++, library, timer, template-meta-programming, c++23 using std::chrono_literals::operator""ms; template <class Duration, class Clock> ScopedTimer<Duration, Clock> func( ScopedTimer<Duration, Clock> timer ) { std::exception_ptr ex_ptr; timer.set_callback( [ &ex_ptr ]( const auto duration ) noexcept { try { fmt::print( stderr, "\nTimer in func took {}\n", duration ); } catch ( ... ) { ex_ptr = std::current_exception( ); } } ); if ( ex_ptr ) { try { std::rethrow_exception( ex_ptr ); } catch ( const std::exception& ex ) { fmt::print( stderr, "{}\n", ex.what( ) ); } } std::this_thread::sleep_for( 200ms ); return timer; } int main( ) { std::move_only_function<void ( std::chrono::milliseconds ) noexcept> f = [&]( const auto duration ) noexcept { try { fmt::print( stderr, "\nTimer took {}\n", duration ); } catch ( ... ) { } }; ScopedTimer timer { std::move( f ) }; std::this_thread::sleep_for( 100ms ); ScopedTimer t; auto t2 = func( std::move( timer ) ); t.set_callback( []( const auto d ) noexcept { fmt::print( stderr, "\nTimer t took {}\n", d ); } ); std::this_thread::sleep_for( 500ms ); } Chnages:
{ "domain": "codereview.stackexchange", "id": 44548, "lm_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++, library, timer, template-meta-programming, c++23", "url": null }
c++, library, timer, template-meta-programming, c++23 std::this_thread::sleep_for( 500ms ); } Chnages: I have added 3 [[nodiscard(message)]] attributes to the code. Although I'm not sure how the one for move constructor might be useful. No valid scenario comes to my mind. I also added setters and getters for members m_start and m_callback and also deleted their rvalue reference overloads. Used the class keyword instead of struct and thus made the two member variables private. Added a second template deduction guide so that the type parameter Duration can be deduced from the duration parameter type of the std::move_only_function object that is passed to the constructor of ScopedTimer. Any suggestions could be valuable. Answer: I think you reached all your goals with this class, and you implemented all the suggestions I made, so I don't have much to say about it anymore. You could consider adding some more utility functions. For example, a cancel() function that removes the callback and returns the (discardable) elapsed time. Or pause() and continue() functions. But the YAGNI principle applies here. The only issue I see with this code is that it looks overengineered, and it now relies on C++23, which means that not a lot of codebases will be able to use it yet.
{ "domain": "codereview.stackexchange", "id": 44548, "lm_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++, library, timer, template-meta-programming, c++23", "url": null }
python, python-3.x Title: Built a function to search a dictionary using key or value Question: I'm building an error handler which handles different kinds of errors arranged hierarchically. As part of that, I need a way to figure out what errors to send a recipient based on what their subscription level is. The below function gives me what I want, but it feels a bit crude to me. Please advise if there is a better, more pythonic way of doing this. alert_levels = { "all": { "import": ["file", "email"], "send": ["tableau", "delivery"] } } def get_children_if_parent(tag: str, parent_dict: dict) -> list: tag_list = [] for key in parent_dict.keys(): if type(parent_dict[key]) == dict: if key == tag: target = '' else: target = tag tag_list.extend(get_children_if_parent(target, parent_dict[key])) else: if tag == key or tag == '': tag_list.extend(parent_dict[key]) elif tag in parent_dict[key]: tag_list.append(tag) return tag_list print(get_children_if_parent('send', alert_levels)) # Output: ['tableau', 'delivery'] print(get_children_if_parent('file', alert_levels)) # Output: ['file'] print(get_children_if_parent('import', alert_levels)) # Output: ['file', 'email'] print(get_children_if_parent('delivery', alert_levels)) # Output: ['delivery'] print(get_children_if_parent('all', alert_levels)) # Output: ['file', 'email', 'tableau', 'delivery'] ````
{ "domain": "codereview.stackexchange", "id": 44549, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, python-3.x", "url": null }
python, python-3.x Answer: Just a few minor suggestions to simplify the code, lighten its visual weight, or otherwise enhance readability. Prefer normal language when feasible. If a regular word like tags is available and clear, don't complicate things by using something like tag_list. If you need a dict's keys and values, iterate via items(). You use parent_dict[key] multiple times. That's not necessary. Indeed, iterating over a dict via keys() is never useful, because directly iterating over the dict does the same thing. Use isinstance() when checking a type. There are special situations when type() is needed, but for garden-variety checks, isinstance() is the way to go. Give your special constant a name. Your are using empty string as a wildcard. Help your reader out by using a descriptive name to convey your intent. WILDCARD = '' def get_children_if_parent(tag, parent_dict): tags = [] for key, val in parent_dict.items(): if isinstance(val, dict): target = WILDCARD if key == tag else tag tags.extend(get_children_if_parent(target, val)) else: if tag == key or tag == WILDCARD: tags.extend(val) elif tag in val: tags.append(tag) return tags You could flatten the conditional structure, but I would lean against it. Initially, I was going to suggest an if-elif-elif structure to reduce the indentation. But after considering it, I opted to leave that alone: your current approach emphasizes the crucial distinction between the dict case (recurse) and the rest. Evaluate remaining awkward names. I find the function name and parent_dict to be a bit awkward and/or puzzling, but I don't have enough context about your project to suggest compelling alternatives.
{ "domain": "codereview.stackexchange", "id": 44549, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, python-3.x", "url": null }
c++, c++11, classes, constructor, overloading Title: A simple String class and its special member functions Question: I am learning the behavior of C++'s special member function, using a naive String class as example. (The code is modified from this tutorial) Here is the implementation so-question.cpp: #include <cstring> #include <iostream> #include <vector> using namespace std; class String { private: uint32_t size; char *buffer; public: String() { cout << "Default No-Parameter Constructor" << endl; this->size = 0; this->buffer = nullptr; } String(const char *name) { cout << "Parameterized Constructor" << endl; this->size = std::strlen(name); this->buffer = new char[this->size]; memcpy(this->buffer, name, this->size); } String(const String &other) { cout << "Copy Construtor" << endl; this->size = other.size; this->buffer = new char[this->size]; memcpy(this->buffer, other.buffer, this->size); } String &operator=(const String &other) { cout << "Copy Assignment Operator" << endl; if (this != &other) { // The buffer size of `this` is different from the `other`'s. So we need // to delete `this` and reallocate memory for `this` with the size of // `other`. delete[] this->buffer; this->size = other.size; this->buffer = new char[this->size]; memcpy(this->buffer, other.buffer, this->size); } return *this; } String(String &&other) { cout << "Move Constructor" << endl; this->size = other.size; /** * In the copy constructor, we have to allocate memory. * In the move constructor, we don't have to allocate any more memory. We * just have to change a couple of variables so it's very efficient. */ this->buffer = other.buffer;
{ "domain": "codereview.stackexchange", "id": 44550, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, c++11, classes, constructor, overloading", "url": null }
c++, c++11, classes, constructor, overloading /** * NOTE: Here, the destructor of "other" will deallocate "other.buffer" and * we've stolen the buffer so we don't want that to happen. So to deal * with this all we have to do is set "other.buffer" to point to * nullptr. And it is safe to delete a nullptr. */ other.size = 0; other.buffer = nullptr; } String &operator=(String &&other) { cout << "Move Assignment Operator" << endl; if (this != &other) { this->size = other.size; /** * Here, the object `buffer` to which `this` points, needs to be freed up, * because `this` is going to point to `other`'s memory. If it's not done, * then we have a memory leak. */ delete[] this->buffer; this->buffer = other.buffer; other.size = 0; other.buffer = nullptr; } return *this; } ~String() { cout << "Destructor: "; // NOTE: a potential bug is here. If `this` has pointed to a nullptr and // size is non-zero, then it causes error: // Segmentation fault (core dumped) for (uint32_t i = 0; i < this->size; ++i) { cout << this->buffer[i]; } cout << '\n'; delete[] this->buffer; } friend ostream &operator<<(ostream &out, const String &test); }; ostream &operator<<(ostream &out, const String &test) { out << "String: "; for (uint32_t i = 0; i < test.size; ++i) { out << test.buffer[i] << ' '; } return out; } String get_String() { return String(); } The String class can be tested with the following code: int main() { String test1; test1 = get_String(); String test2{"test2"}; String test3{test2}; cout << "test1: " << test1 << endl; test1 = test3; cout << "test2: " << test2 << endl; cout << "test3: " << test3 << endl; cout << "test1: " << test1 << endl; vector<String> vec; vec.push_back(String("rvalue")); vec.push_back(test1); cout << "vec[0] " << vec[0] << endl; cout << "vec[1] " << vec[1] << endl; cout << '\n';
{ "domain": "codereview.stackexchange", "id": 44550, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, c++11, classes, constructor, overloading", "url": null }
c++, c++11, classes, constructor, overloading cout << "Test move-from object:\n"; test2 = std::move(test1); cout << "test2: " << test2 << endl; cout << "test1: " << test1 << endl; return 0; } And the output message is: Default No-Parameter Constructor Default No-Parameter Constructor Move Assignment Operator Destructor: Parameterized Constructor Copy Construtor test1: String: Copy Assignment Operator test2: String: t e s t 2 test3: String: t e s t 2 test1: String: t e s t 2 Parameterized Constructor Move Constructor Destructor: Copy Construtor Copy Construtor Destructor: rvalue vec[0] String: r v a l u e vec[1] String: t e s t 2 Test move-from object: Move Assignment Operator test2: String: t e s t 2 test1: String: Destructor: rvalue Destructor: test2 Destructor: test2 Destructor: test2 And the code can be run with the command g++ -Wall -std=c++17 -std=gnu++17 so-question.cpp && ./a.out. The result looks good and makes sense to me. However, I have one question, is it true that in theory and in practice that when using move constructor and move assignment operator, the move-from object shall be invalid. I am asking this because I am just wondering what if I would like to have two objects points to the same memory location. For example, String test1{"apple"}; String test2; test2 = std::move(test1); test1 becomes invalid after it's moved. But what if I want both test1 and test2 both points to the same string in memory apple. (copy can't be used here because then it will not be the same memory) This can be done by changing the code in move assignment operator. But does it violate some software design pattern and should be avoided or there's a known method to address this behavior? Thank you. Update: Fix the code to make it as minimum reproducible. Answer: Answer to your question is it true that in theory and in practice that when using move constructor and move assignment operator, the move-from object shall be invalid.
{ "domain": "codereview.stackexchange", "id": 44550, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, c++11, classes, constructor, overloading", "url": null }
c++, c++11, classes, constructor, overloading No, the moved-from object must still be valid, however its contents are allowed to be undefined. So for your class: String test1{"apple"}; String test2{std::move(test1)}; std::cout << test1; The printing to std::cout should still work. However, it is allowed to print "a p p l e", "" or "w h a t e v e r". You chose to set size to zero and buffer to nullptr, which is valid. The reason why it must be valid is that the object test1 is still alive here, and at some point its destructor will be called. But what if I want both test1 and test2 both points to the same string in memory apple. (copy can't be used here because then it will not be the same memory) This can be done by changing the code in move assignment operator. But does it violate some software design pattern and should be avoided or there's a known method to address this behavior? Then test1 would not be valid anymore, as both its destructor and that of test2 would try to delete[] the same memory, which is not valid. A more elegant way to move The move constructor and move assignment operator become more elegant to write if you implement a swap() member function first, which in turn uses std::swap() on the member variables, and by using default member initializers: class String { std::size_t size = 0; char *buffer = nullptr; public: String() { std::cout << "Default No-Parameter Constructor\n"; // Nothing to do anymore! } String(String &&other) { std::cout << "Move Constructor\n"; swap(other); } String &operator=(String &&other) { std::cout << "Move Assignment Operator\n"; swap(other); return *this; } void swap(String& other) { std::swap(size, other.size); std::swap(buffer, other.buffer); } … };
{ "domain": "codereview.stackexchange", "id": 44550, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, c++11, classes, constructor, overloading", "url": null }
c++, c++11, classes, constructor, overloading You no longer have to check if this == &other, as std::swap() will do the right thing if it swaps the same member variables. The move constructor's body will run after it initialized size and buffer, so other will end up with 0 and nullptr. The move assignment operator will swap the two strings. As mentioned above, that's also valid. The destructor of other will then take care of deleting the old string. Unnecessary use of this-> You almost never have to write this-> in C++. I would just remove it everywhere, as it just adds noise. Prefer '\n' over std::endl Use '\n' instead of std::endl; the latter is equivalent to the former, but also forces the output to be flushed, which is usually not necessary and might impact performance. Use std::size_t for sizes, counts and indices The return value of std::strlen() is a std::size_t. Make sure you store your string's size in a variable of that type as well, otherwise you can run into problems if you ever try to store a string that is longer than a std::uint32_t can represent. It is good practice to always use std::size_t for anything that deals with the size of arrays or objects in memory, as well as counts and indices related to those.
{ "domain": "codereview.stackexchange", "id": 44550, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, c++11, classes, constructor, overloading", "url": null }
java, beginner Title: Select the type of triangle based on the input Question: I am trying to see if there is a way to improve my code this program ask for 3 number and calculate the what type of triangle it is import java.util.Scanner; public class Triangle{ public static void main (String[] args){ Scanner scan = new Scanner(System.in); System.out.println("Enter 3 numbers that represent side of triangle (one by one): "); int num1 = scan.nextInt(); int num2 = scan.nextInt(); int num3 = scan.nextInt(); boolean isoscelesTriangle = num1==num2 && num2!=num3 || num1!=num2 && num3==num1 || num3==num2 && num3!=num1; boolean equilateralTriangle = (num1 == num2 && num2 == num3) && num1 > 0 && num2 > 0 && num3 > 0; boolean rightAngleTriangle = num1 > 0 && num2 > 0 && num3 > 0 && ((num1 * num1) + (num2 * num2) == (num3 * num3) || (num1 * num1) + (num3 * num3) == (num2 * num2) || (num3 * num3) + (num2 *num2) == (num1 * num1)); boolean commonTriangle = num1 + num2 > num3 || num1 + num3 > num2 || num2 + num3 > num1; boolean notTriangle = num1 > 0 && num2 > 0 && num3 > 0 && num1 >= (num2+num3) || num3 >= (num2+num1) || num2 >= (num1+num3); // calculate to check what triangle it is if(equilateralTriangle) System.out.println("The Numbers: " +num1+", " + num2 + " and " +num3+ " represent an equilateral triangle"); else if (isoscelesTriangle) System.out.println("The Numbers: " +num1+", " + num2 +" and " +num3+ " represent an Isosceles Triangle"); else if (rightAngleTriangle) System.out.println("The Numbers: " +num1+", " + num2 + " and " +num3+ " represent an right-angle Triangle"); else if(commonTriangle) System.out.println("The Numbers: " + num1 + ", " + num2 + " and " + num3 + " represent an Common Triangle");
{ "domain": "codereview.stackexchange", "id": 44551, "lm_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, beginner", "url": null }
java, beginner else if (notTriangle) System.out.println("The Numbers: " +num1+", " + num2 + " and " +num3+ " cannot represent an triangle"); } } this is the code that I did. I can't change the order of the calculation but I wonder if there is way to make it shorter and better. or maybe improve the calculation. *I am new to programing in general so if you have any tips to help me in general its will be good Answer: DRY applies to this both in small and larger ways. We several times see the expression "The Numbers: " + num1 + ", " + num2 + " and " + num3 + " represent" ... That's the trivial aspect. Assign to a prefix string and you're done. The five booleans are the more interesting aspect, which we will come to. int num1 = scan.nextInt(); int num2 = scan.nextInt(); int num3 = scan.nextInt(); There's nothing wrong with that. Certainly they are all numbers. But think about what you'll be using them for. In some ways they're not as convenient as they could be. Every text since Euclid has used alpha, beta, ... ok some have used a, b, c. Let's go with that when defining three ints. In many languages, including java, it is conventional for booleans and predicates to start with is. (Or "has" / "have" for plural.) I will follow that here. Also, we should report fatal error immediately upon noticing any negative numbers. It is reasonable for the rest of the code to be able to safely assume it is working with non-negative lengths. Finally, to simplify matters, I am going to enforce monotonicity. The user is free to enter figures in any order, but by the time we've validated them we will have a <= b && b <= c. In some languages we might rely on sorted(); here we can ask ArrayList to .sort().
{ "domain": "codereview.stackexchange", "id": 44551, "lm_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, beginner", "url": null }
java, beginner Ok, time for some math. It seems like you'd want to establish this one first, as absent the triangle inequality the others just don't make sense. I choose to define these in the positive, as humans do a better job reasoning in that way. It avoids the infamous double negative. boolean isValid = a >= 0 && b >= 0 && c >= 0; boolean isTriangle = c <= a + b; We should bail immediately if ! isValid or ! isTriangle. Note that isTriangle still admits of degenerate triangles, such as 2, 3, 5. Feel free to define isDegenerate if you like. Now isEquilateralTriangle = a == b && b == c, just as you defined. We can quibble about whether the first term is needed, but following your code we have isIsoscelesTriangle = !isEquilateralTriangle && (b == a || b == c). Notice how sorting makes the middle entry, b, the one of interest. Here's the original motivation for sorting: isRightAngleTriangle = a*a + b*b == c*c. We're dealing with Pythagorean triples here, given the int declaration. I caution you that, if floats and round-off were involved, you'd want to compare abs() difference to a small epsilon, or use a fancier measure like relative error. Having dispatched some specific types, we could define isCommonTriangle = !isIsoscelesTriangle && !isEquilateralTriangle && !isRightTriangle. But for this code it's probably better to just leave it as the default case when reporting an outcome. That is, simply use an else. There is an opportunity to pass sorted a, b, c to a helper function here. But "extract helper" might be a topic for your next coding assignment. Summary: There are many ways to code up the several details of an assignment. Look for what is common across them, find their hierarchy, and tackle them in sequence. It simplifies both your code, and reasoning about your code, if you discard the pathological cases early on.
{ "domain": "codereview.stackexchange", "id": 44551, "lm_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, beginner", "url": null }
c, programming-challenge, c99 Title: Solution to Codejam 2021 1C (Closest Pick) in C Question: The following code is my solution to the Closest Pick problem from Codejam 2021. You are entering a raffle for a lifetime supply of pancakes. N tickets have already been sold. Each ticket contains a single integer between 1 and K, inclusive. Different tickets are allowed to contain the same integer. You know exactly which numbers are on all of the tickets already sold and would like to maximize your odds of winning by purchasing two tickets (possibly with the same integer on them). You are allowed to choose which integers between 1 and K, inclusive, are on the two tickets. You know you are the last customer, so after you purchase your tickets, no more tickets will be purchased. Then, an integer c between 1 and K, inclusive, is chosen uniformly at random. If one of your tickets is strictly closer to c than all other tickets or if both of your tickets are the same distance to c and strictly closer than all other tickets, then you win the raffle. Otherwise, you do not win the raffle. Given the integers on the N tickets purchased so far, what is the maximum probability of winning the raffle you can achieve by choosing the integers on your two tickets optimally? This is an easy problem, and we can solve it by sorting all ticket numbers and finding all number gaps between them. Then we can buy two tickets either to cover the largest gap or half of the two largest gaps. The code below is correct, i.e. it gets two green checkmarks. I'd appreciate any feedback! #include <stdio.h> #include <stdlib.h> #define MIN_TICKET 1 static int cmp_long(const void *num1, const void *num2) { return *(const long *)num1 - *(const long *)num2; }
{ "domain": "codereview.stackexchange", "id": 44552, "lm_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, programming-challenge, c99", "url": null }
c, programming-challenge, c99 static double solve(long *tickets, size_t n_tickets, long max_ticket) { qsort(tickets, n_tickets, sizeof(tickets[0]), cmp_long); // Sizes of ticket gaps that we can "cover" by being closer than others long gaps[n_tickets + 1]; // Max total number of tickets that we can cover long max_gap_size = 0; // Size of the leftmost ticket gap gaps[0] = tickets[0] - MIN_TICKET; // Size of the rightmost ticket gap gaps[n_tickets] = max_ticket - tickets[n_tickets-1]; for (int i = 1; i < n_tickets; i++) { long gap_size = tickets[i] - tickets[i-1] - 1; // Number of tickets that we can cover by buying a ticket at one of the // gap boundaries (divide the size by 2 and round up). gaps[i] = (gap_size + 1) / 2; // Alternatively, we can buy two tickets at each boundary of a large // gap. if (gap_size > max_gap_size) { max_gap_size = gap_size; } } qsort(gaps, n_tickets + 1, sizeof(gaps[0]), cmp_long); // Total size of our two largest options long top_two_gap_sizes = gaps[n_tickets - 1] + gaps[n_tickets]; // Choose between covering one large gap or two smaller gaps. if (top_two_gap_sizes > max_gap_size) { max_gap_size = top_two_gap_sizes; } return (double) max_gap_size / max_ticket; } int main(void) { size_t n_tests = 0; scanf("%lu", &n_tests); for (int case_num = 1; case_num <= n_tests; case_num++) { size_t n_tickets; long max_ticket; scanf("%lu %ld", &n_tickets, &max_ticket); long tickets[n_tickets]; for (int i = 0; i < n_tickets; i++) { scanf("%ld", &tickets[i]); } double prob = solve(tickets, n_tickets, max_ticket); printf("Case #%d: %.6f\n", case_num, prob); } } Example output $ cat tests.txt 4 3 10 1 3 7 4 10 4 1 7 3 4 3 1 2 3 2 4 4 1 2 4 2 $ ./solution < tests.txt Case #1: 0.500000 Case #2: 0.400000 Case #3: 0.000000 Case #4: 0.250000
{ "domain": "codereview.stackexchange", "id": 44552, "lm_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, programming-challenge, c99", "url": null }
c, programming-challenge, c99 Answer: Enable more compiler warnings GCC reports some warnings: gcc-10 -std=c17 -no-pie -g3 -ggdb -Wall -Wextra -Warray-bounds -Wconversion -Wmissing-braces -Wno-parentheses -Wpedantic -Wstrict-prototypes -Wwrite-strings -Winline -fanalyzer -fno-builtin -fno-common -fno-omit-frame-pointer -fsanitize=address -fsanitize=undefined -fsanitize=bounds-strict -fsanitize=leak -fsanitize=null -fsanitize=signed-integer-overflow -fsanitize=bool -fsanitize=pointer-overflow -fsanitize-address-use-after-scope -O2 ex.c -o ex
{ "domain": "codereview.stackexchange", "id": 44552, "lm_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, programming-challenge, c99", "url": null }
c, programming-challenge, c99 ex.c:7:32: warning: conversion from ‘long int’ to ‘int’ may change value [-Wconversion] 7 | return *(const long *)num1 - *(const long *)num2; | ~~~~~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~ ex.c: In function ‘solve’: ex.c:20:23: warning: comparison of integer expressions of different signedness: ‘int’ and ‘size_t’ {aka ‘long unsigned int’} [-Wsign-compare] 20 | for (int i = 1; i < n_tickets; i++) { | ^ ex.c:38:34: warning: conversion from ‘long int’ to ‘double’ may change value [-Wconversion] 38 | return (double) max_gap_size / max_ticket; | ^ ex.c: In function ‘main’: ex.c:44:37: warning: comparison of integer expressions of different signedness: ‘int’ and ‘size_t’ {aka ‘long unsigned int’} [-Wsign-compare] 44 | for (int case_num = 1; case_num <= n_tests; case_num++) { | ^~ ex.c:49:27: warning: comparison of integer expressions of different signedness: ‘int’ and ‘size_t’ {aka ‘long unsigned int’} [-Wsign-compare] 49 | for (int i = 0; i < n_tickets; i++) { | ^ ex.c:43:5: warning: ignoring return value of ‘scanf’ declared with attribute ‘warn_unused_result’ [-Wunused-result] 43 | scanf("%lu", &n_tests); | ^~~~~~~~~~~~~~~~~~~~~~ ex.c:47:9: warning: ignoring return value of ‘scanf’ declared with attribute ‘warn_unused_result’ [-Wunused-result] 47 | scanf("%lu %ld", &n_tickets, &max_ticket); | ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ex.c:50:13: warning: ignoring return value of ‘scanf’ declared with attribute ‘warn_unused_result’ [-Wunused-result] 50 | scanf("%ld", &tickets[i]); These are all avoidable. Check the return value of library functions
{ "domain": "codereview.stackexchange", "id": 44552, "lm_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, programming-challenge, c99", "url": null }
c, programming-challenge, c99 These are all avoidable. Check the return value of library functions If a function be advertised to return an error code in the event of difficulties, thou shalt check for that code, yea, even though the checks triple the size of thy code and produce aches in thy typing fingers, for if thou thinkest "it cannot happen to me", the gods shall surely punish thee for thy arrogance. — The Ten Commandments For C Programmers scanf() returns the number of input items successfully matched and assigned, it deserves to have its value checked: if (scanf("%zu", &n_tests) != 1) { complain (); } Note that the correct format specifier for size_t is zu, not lu. Use size_t for sizes, cardinalities, or ordinal numbers //for (int case_num = 1; case_num <= n_tests; case_num++) { // size_t n_tickets; // long max_ticket; for (size_t case_num = 1; case_num <= n_tests; case_num++) { size_t n_tickets; size_t max_ticket; qsort's comparison function risks invoking undefined behaviour return *(const long int*)num1 - *(const long int*)num2; This subtraction could result in integer overflow, which would invoke undefined behaviour. A common idiom is to subtract two integer comparisons: return (*(const long int*)num1 > *(const long int*)num2) - (*(const long int*)num1 < *(const long int*)num2); Or a more readable, but less compact, alternative: const long int *a = num1; const long int *b = num2; return (*a > *b) - (*a < *b); Or if you'd prefer an if/else ladder: if (*a > *b) { return 1; } else if (*a < *b) { return -1; } return 0; Or perhaps: return (*a < *b) : -1 : *a > *b;
{ "domain": "codereview.stackexchange", "id": 44552, "lm_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, programming-challenge, c99", "url": null }
python, performance, numpy, signal-processing, scipy Title: Fourier Series of a given function Question: This is a very simple code that expresses a function in terms of Trigonometric Fourier Series and generates a animation based on the harmonics. I would like to know some ways to improve the performance of the code and its readability. I believe that any question about the mathematical part can be answered here. Here's the whole code: import matplotlib.pyplot as plt from numpy import sin, cos, pi, linspace from scipy.integrate import quad as integral from celluloid import Camera def desired_function(t): return t**2 def a_zero(function, half_period, inferior_limit, superior_limit): return (1/(2*half_period)) * integral(function, inferior_limit, superior_limit)[0] def a_k(k, half_period, inferior_limit, superior_limit): return (1/half_period) * integral(lambda x: desired_function(x) * cos(x * k * (pi / half_period)), inferior_limit, superior_limit)[0] def b_k(k, half_period, inferior_limit, superior_limit): return (1/half_period) * integral(lambda x: desired_function(x) * sin(x * k * (pi / half_period)), inferior_limit, superior_limit)[0] def main(): fig = plt.figure() camera = Camera(fig) inferior_limit, superior_limit = -pi, pi half_period = (superior_limit - inferior_limit) / 2 x = linspace(inferior_limit, superior_limit, 1000) f = a_zero(desired_function, half_period, inferior_limit, superior_limit) # The sum ranging from 1 to total_k total_k = 30 for k in range(1, total_k+1): f += a_k(k, half_period, inferior_limit, superior_limit)*cos(k*x*(pi/half_period)) +\ b_k(k, half_period, inferior_limit, superior_limit)*sin(k*x*(pi/half_period)) plt.plot(x, desired_function(x), color='k') plt.plot(x, f, label=f'k = {k}') camera.snap() animation = camera.animate() plt.close() animation.save('animation.gif') if __name__ == '__main__': main()
{ "domain": "codereview.stackexchange", "id": 44553, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, performance, numpy, signal-processing, scipy", "url": null }
python, performance, numpy, signal-processing, scipy if __name__ == '__main__': main() And my biggest issue is this for loop being used as a Σ, is there a more elegant way to express this? # The sum ranging from 1 to total_k total_k = 30 for k in range(1, total_k+1): f += a_k(k, half_period, inferior_limit, superior_limit)*cos(k*x*(pi/half_period)) +\ b_k(k, half_period, inferior_limit, superior_limit)*sin(k*x*(pi/half_period)) Thanks in advance to anyone who takes the time to help me with this! Answer: I like it. This code hews closely to the underlying math, using lovely identifiers, and is very clear. For {a,b}_k, here's the only part I'm not super happy with: def a_k(k, half_period, inferior_limit, superior_limit): return (1/half_period) * integral(lambda x: desired_function(x) * cos(x * k * (pi / half_period)), inferior_limit, superior_limit)[0] We went with desired_function as a global. Ok, not the end of the world. Just sayin', consider adding it to the parameters. I probably would have gone with a concise lo, hi instead of inferior_limit, superior_limit. But hey, that's just me, it's a matter of taste. Don't change it on my account, looks good as it is. Maybe package them both as the 2-tuple limits, and then the call goes from ... * integral(... * (pi / half_period)), inferior_limit, superior_limit)[0] to ... * integral(... * (pi / half_period)), *limits)[0] def main(): ... x = linspace(inferior_limit, superior_limit, 1000) ... total_k = 30 We have two magic numbers, both quite reasonable. Consider burying one or both of them in the signature: def main(num_points=1000, total_k=30): One benefit of such practice is it makes it easy for unit tests to adjust numbers to more convenient values. It wouldn't hurt to sometimes add a """docstring""" to a function, explaining what it expects and what it offers. Not every function, mind you, just the big one(s).
{ "domain": "codereview.stackexchange", "id": 44553, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, performance, numpy, signal-processing, scipy", "url": null }
python, performance, numpy, signal-processing, scipy To follow PEP-8 conventions more closely, consider running black over this source. Whitespace within math expressions tends to improve readability. more elegant way to express [the summation?] No, I respectfully disagree with your assessment. It exactly corresponds to the math and it looks beautiful to me. You could change it, but then I fear it would be less clear. Now, if we wanted to worry about efficiency and execution speed, there are some constants that could be hoisted out of the loop, and the repeated calls to integral() seem like they might show up on cProfile's hit list. But if we cared about elapsed time we would use numba's @jit or another technique, and compilers are good at hoisting. This code achieves its design goals and is maintainable. ATM it looks good to me. Ship it!
{ "domain": "codereview.stackexchange", "id": 44553, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, performance, numpy, signal-processing, scipy", "url": null }
java, beginner, battleship Title: My First Java Battleship Simulator (single array, single ship) Question: I'm new to this community and also to Java programming! I recently picked up "Head First Java" and I did my Battleship project. If you could kindly, give me feedback on the code? import java.util.Scanner; public class Main { public static void main(String[] args) { int location; Battleship ship = new Battleship(); System.out.println("Ship is 3 blocks long, ocean is 10 blocks wide, choose a number: "); Scanner scanner = new Scanner(System.in); while (ship.end()) { location = scanner.nextInt(); ship.shoot(location); } System.out.println("Kill!\nYou win!"); } public static class Battleship { private int[] ocean; private int shipHead; private int counter; // check if game is over boolean end() { if (counter == 3) { return false; } return true; } // creates the battlefield Battleship() { ocean = new int[10]; shipHead = (int) (Math.random() * 7); for (int i = shipHead; i < shipHead + 3; i++) { ocean[i] = 1; } } // find the start of the ship void shipStart() { System.out.println("Ship head is at position " + (shipHead + 1)); } // cheat sheet void showOcean() { for (int i = 0; i < ocean.length; i++) { System.out.print(ocean[i] + " "); } System.out.println(); }
{ "domain": "codereview.stackexchange", "id": 44554, "lm_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, beginner, battleship", "url": null }
java, beginner, battleship void shoot(int a) { a -= 1; if (a >= 0 && a < 10) { switch (ocean[a]) { case 1: System.out.println("Hit!"); ocean[a] = -1; counter++; break; case 0: System.out.println("Miss!"); break; case -1: System.out.println("Was shot before!"); break; } } else { System.out.println("Number between 1 and 10!"); } } } } Answer: Your code is clear and clean, I would only suggest: Opposite name // check if game is over boolean end() { if (counter == 3) { return false; } return true; } I would expect this function to return true when the game ends but it does the opposite, I suggest is_ended as a name and inverting the check, (then use the function with a ! in front). Also the if is not necessary (return counter == 3 is enough). Separation of concerns The Battleship class should return Strings rather than printing, the main program should print. This allows easier testing and generalization to Web UI / GUI rather than console only. Removing magic numbers ocean = new int[10]; shipHead = (int) (Math.random() * 7); for (int i = shipHead; i < shipHead + 3; i++) { ocean[i] = 1; } What are the numbers 10, 7 and 3? They are respectively boardSize, boardSize - shipSize, shipSize, so boardSize and shipSize should be arguments to the initialization method of Battleship to allow customization of the game to different sizes. Use an Enum to associate numbers with states When you write: ocean[i] = 1;
{ "domain": "codereview.stackexchange", "id": 44554, "lm_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, beginner, battleship", "url": null }
java, beginner, battleship It does not mean that there is one thing there while there could be any number of things there, it means SHIP, just as 0 means NOTHING and -1 means DESTROYED. Enums are used when numbers represent concepts rather than quantities. Here is a basic example of enums. Using them will make the code more readable. Comment for off-by-one errors Off by one errors are really tricky, so I suggest adding a comment to: a -= 1; To: a -= 1; // User input is 1-index while Java is 0-index
{ "domain": "codereview.stackexchange", "id": 44554, "lm_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, beginner, battleship", "url": null }
python, web-scraping, https Title: HTTP scraper for Python Package Question: I'm trying to make my first Python package as a learning experience. There's a lot of things that I suspect I am doing poorly, but this post is specifically about my HttpRequest class. I made this class so that I can use retries and persistent session. class HttpRequest: __session = None @staticmethod def __init__session__(): if HttpRequest.__session is not None: return stderr.write("Initializing HTTPS Session\n") HttpRequest.__session = HttpSession() retries = Retry(total=3, backoff_factor=1, status_forcelist=[], # 429 allowed_methods=False) HttpRequest.__session.mount("https://", HTTPAdapter(max_retries=retries)) @staticmethod def get(url): print(f"Querying {url}") HttpRequest.__init__session__() return HttpRequest.__session.get(url) I use this class basically everywhere in the package, so I want to make sure I'm doing this well. Answer: I tend to be pretty happy with requests defaults, but I imagine you need specific retry behavior, so I won't comment on that. __session = None That's just weird. Please don't do that -- name mangling is seldom helpful. Prefer a single leading _ underscore to mark it private. Rather than naming it _init_session (a perfectly nice and helpful name), you might prefer _get_session. I'm just looking at how it's used, is all. Currently it is invoked for Singleton side effects, and caller must carefully remember to call it. When designing an API we strive for more than just clear names. We also want it to be easy to use, and hard to accidentally misuse. So a getter feels more natural, in this case. if HttpRequest.__session is not None: Feel free to abbreviate that to just: if HttpRequest.__session:
{ "domain": "codereview.stackexchange", "id": 44555, "lm_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, web-scraping, https", "url": null }
python, web-scraping, https Feel free to abbreviate that to just: if HttpRequest.__session: @staticmethod def get(url): print(f"Querying {url}") HttpRequest.__init__session__() return HttpRequest.__session.get(url) Both methods are declared static, yet they immediately dive into class attributes. Doesn't seem like a good match. Prefer: @classmethod def get(cls, url): ... cls._init_session() return cls._session.get(url) # # or maybe just: # return cls._get_session().get(url) Also, instead of print, consider using a logger. That way callers can dial verbosity up and down as they wish. Plus the logged timestamps can come in very handy when diagnosing why an overnight run suddenly slowed down.
{ "domain": "codereview.stackexchange", "id": 44555, "lm_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, web-scraping, https", "url": null }
c++, recursion, template, c++20, constrained-templates Title: The usages of make_view Template Function in C++ Question: This is a follow-up question for A recursive_transform_view Template Function which returns a view in C++. I am trying to revise the structure of recursive_transform template function implementation in C++. As the suggestion mentioned in Davislor's answer, For dealing with dangling reference issue, the updated recursive_transform template function implementation is posted here. The experimental implementation make_view template function implementation: template< std::ranges::input_range Container, std::copy_constructible F> requires (std::ranges::view<Container>&& std::is_object_v<F>) constexpr auto make_view(const Container& input, const F& f) noexcept { return std::ranges::transform_view( std::views::all(input), [&f](const auto&& element) constexpr { return recursive_transform(element, f ); } ); } /* Override make_view to catch dangling references. A borrowed range is * safe from dangling.. */ template < std::ranges::input_range T, std::copy_constructible F> requires (!std::ranges::borrowed_range<T>) constexpr std::ranges::dangling make_view(T&& input, const F& f) noexcept { return std::ranges::dangling(); } Full Testing Code The full testing code: // The usages of `make_view` Template Function in C++ #include <algorithm> #include <array> #include <cassert> #include <chrono> #include <complex> #include <concepts> #include <cstdlib> #include <deque> #include <execution> #include <exception> #include <functional> #include <iostream> #include <iterator> #include <list> #include <map> #include <mutex> #include <numeric> #include <optional> #include <queue> #include <ranges> #include <stack> #include <stdexcept> #include <string> #include <tuple> #include <type_traits> #include <utility> #include <variant> #include <vector>
{ "domain": "codereview.stackexchange", "id": 44556, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, recursion, template, c++20, constrained-templates", "url": null }
c++, recursion, template, c++20, constrained-templates // is_reservable concept template<class T> concept is_reservable = requires(T input) { input.reserve(1); }; // is_sized concept, https://codereview.stackexchange.com/a/283581/231235 template<class T> concept is_sized = requires(T x) { std::size(x); }; template<typename T> concept is_summable = requires(T x) { x + x; }; // recursive_depth function implementation template<typename T> constexpr std::size_t recursive_depth() { return 0; } template<std::ranges::input_range Range> constexpr std::size_t recursive_depth() { return recursive_depth<std::ranges::range_value_t<Range>>() + 1; } // recursive_invoke_result_t implementation template<typename, typename> struct recursive_invoke_result { }; template<typename T, std::regular_invocable<T> F> struct recursive_invoke_result<F, T> { using type = std::invoke_result_t<F, T>; }; template<typename F, template<typename...> typename Container, typename... Ts> requires ( !std::regular_invocable<F, Container<Ts...>>&& // F cannot be invoked to Container<Ts...> directly std::ranges::input_range<Container<Ts...>>&& requires { typename recursive_invoke_result<F, std::ranges::range_value_t<Container<Ts...>>>::type; }) struct recursive_invoke_result<F, Container<Ts...>> { using type = Container< typename recursive_invoke_result< F, std::ranges::range_value_t<Container<Ts...>> >::type >; }; template<template<typename, std::size_t> typename Container, typename T, std::size_t N, std::regular_invocable<Container<T, N>> F> struct recursive_invoke_result<F, Container<T, N>> { using type = std::invoke_result_t<F, Container<T, N>>; };
{ "domain": "codereview.stackexchange", "id": 44556, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, recursion, template, c++20, constrained-templates", "url": null }
c++, recursion, template, c++20, constrained-templates template<template<typename, std::size_t> typename Container, typename T, std::size_t N, typename F> requires ( !std::regular_invocable<F, Container<T, N>>&& // F cannot be invoked to Container<Ts...> directly requires { typename recursive_invoke_result<F, std::ranges::range_value_t<Container<T, N>>>::type; }) struct recursive_invoke_result<F, Container<T, N>> { using type = Container< typename recursive_invoke_result< F, std::ranges::range_value_t<Container<T, N>> >::type , N>; }; template<typename F, typename T> using recursive_invoke_result_t = typename recursive_invoke_result<F, T>::type; // https://codereview.stackexchange.com/a/253039/231235 template<template<class...> class Container = std::vector, std::size_t dim, class T> constexpr auto n_dim_container_generator(T input, std::size_t times) { if constexpr (dim == 0) { return input; } else { return Container(times, n_dim_container_generator<Container, dim - 1, T>(input, times)); } } namespace UL // unwrap_level { template< std::ranges::input_range Container, std::copy_constructible F> requires (std::ranges::view<Container>&& std::is_object_v<F>) constexpr auto make_view(const Container& input, const F& f) noexcept { return std::ranges::transform_view( std::views::all(input), [&f](const auto&& element) constexpr { return recursive_transform(element, f ); } ); }
{ "domain": "codereview.stackexchange", "id": 44556, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, recursion, template, c++20, constrained-templates", "url": null }
c++, recursion, template, c++20, constrained-templates /* Override make_view to catch dangling references. A borrowed range is * safe from dangling.. */ template < std::ranges::input_range T, std::copy_constructible F> requires (!std::ranges::borrowed_range<T>) constexpr std::ranges::dangling make_view(T&& input, const F& f) noexcept { return std::ranges::dangling(); }
{ "domain": "codereview.stackexchange", "id": 44556, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, recursion, template, c++20, constrained-templates", "url": null }
c++, recursion, template, c++20, constrained-templates // clone_empty_container template function implementation template< std::ranges::input_range Container, std::copy_constructible F> requires (std::ranges::view<Container>&& std::is_object_v<F>) constexpr auto clone_empty_container(const Container& input, const F& f) noexcept { const auto view = make_view(input, f); recursive_invoke_result_t<F, Container> output(std::span{input}); return output; } // recursive_transform template function implementation (the version with unwrap_level template parameter) template< std::size_t unwrap_level = 1, class T, std::copy_constructible F> requires (unwrap_level <= recursive_depth<T>()&& // handling incorrect unwrap levels more gracefully, https://codereview.stackexchange.com/a/283563/231235 std::ranges::view<T>&& std::is_object_v<F>) constexpr auto recursive_transform(const T& input, const F& f) { if constexpr (unwrap_level > 0) { auto output = clone_empty_container(input, f); if constexpr (is_reservable<decltype(output)>&& is_sized<decltype(input)>) { output.reserve(input.size()); std::ranges::transform( input, std::ranges::begin(output), [&f](auto&& element) { return recursive_transform<unwrap_level - 1>(element, f); } ); } else { std::ranges::transform( input, std::inserter(output, std::ranges::end(output)), [&f](auto&& element) { return recursive_transform<unwrap_level - 1>(element, f); } ); } return output; } else if constexpr(std::regular_invocable<F, T>) {
{ "domain": "codereview.stackexchange", "id": 44556, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, recursion, template, c++20, constrained-templates", "url": null }
c++, recursion, template, c++20, constrained-templates } else if constexpr(std::regular_invocable<F, T>) { return std::invoke(f, input); } else { static_assert(!std::regular_invocable<F, T>, "Uninvocable?"); } }
{ "domain": "codereview.stackexchange", "id": 44556, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, recursion, template, c++20, constrained-templates", "url": null }
c++, recursion, template, c++20, constrained-templates /* This overload of recursive_transform is to support std::array */ template< std::size_t unwrap_level = 1, template<class, std::size_t> class Container, typename T, std::size_t N, typename F > requires (std::ranges::input_range<Container<T, N>>) constexpr auto recursive_transform(const Container<T, N>& input, const F& f) { Container<recursive_invoke_result_t<F, T>, N> output; std::ranges::transform( input, std::ranges::begin(output), [&f](auto&& element){ return recursive_transform<unwrap_level - 1>(element, f); } ); return output; } // recursive_transform function implementation (the version with unwrap_level, without using view) template<std::size_t unwrap_level = 1, class T, class F> requires (!std::ranges::view<T>) constexpr auto recursive_transform(const T& input, const F& f) { if constexpr (unwrap_level > 0) { static_assert(unwrap_level <= recursive_depth<T>(), "unwrap level higher than recursion depth of input"); // trying to handle incorrect unwrap levels more gracefully recursive_invoke_result_t<F, T> output{}; std::ranges::transform( input, // passing a range to std::ranges::transform() std::inserter(output, std::ranges::end(output)), [&f](auto&& element) { return recursive_transform<unwrap_level - 1>(element, f); } ); return output; } else { return std::invoke(f, input); // use std::invoke() } } }
{ "domain": "codereview.stackexchange", "id": 44556, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, recursion, template, c++20, constrained-templates", "url": null }
c++, recursion, template, c++20, constrained-templates namespace NonUL { template< std::ranges::input_range Container, std::copy_constructible F> requires (std::ranges::view<Container>&& std::is_object_v<F>) constexpr auto make_view(const Container& input, const F& f) noexcept { return std::ranges::transform_view( std::views::all(input), [&f](const auto&& element) constexpr { return recursive_transform(element, f ); } ); } /* Override make_view to catch dangling references. A borrowed range is * safe from dangling.. */ template <std::ranges::input_range T, std::copy_constructible F> requires (!std::ranges::borrowed_range<T>, std::is_object_v<F>) constexpr std::ranges::dangling make_view(T&& input, const F& f) noexcept { return std::ranges::dangling(); } /* Base case of NonUL::recursive_transform template function https://codereview.stackexchange.com/a/283581/231235 */ template< typename T, std::regular_invocable<T> F> requires (std::copy_constructible<F>) constexpr auto recursive_transform( const T& input, const F& f ) { return std::invoke( f, input ); } /* The recursive case of NonUL::recursive_transform template function https://codereview.stackexchange.com/a/283581/231235 */ template< std::ranges::input_range Container, std::copy_constructible F> requires (std::ranges::input_range<Container>&& std::ranges::view<Container>&& std::is_object_v<F>) constexpr auto recursive_transform(const Container& input, const F& f) { const auto view = make_view(input, f); recursive_invoke_result_t<F, Container> output( std::span{view} );
{ "domain": "codereview.stackexchange", "id": 44556, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, recursion, template, c++20, constrained-templates", "url": null }
c++, recursion, template, c++20, constrained-templates // One last sanity check. if constexpr( is_sized<Container> && is_sized<recursive_invoke_result_t<F, Container>> ) { assert( output.size() == input.size() ); } return output; } /* The recursive case of NonUL::recursive_transform template function for std::array https://codereview.stackexchange.com/a/283581/231235 */ template< template<typename, std::size_t> typename Container, typename T, std::size_t N, std::copy_constructible F> requires std::ranges::input_range<Container<T, N>> constexpr auto recursive_transform(const Container<T, N>& input, const F& f) { Container<recursive_invoke_result_t<F, T>, N> output; std::ranges::transform( // Use std::ranges::transform() for std::arrays input, std::ranges::begin(output), [&f](auto&& element){ return recursive_transform(element, f); } ); // One last sanity check. if constexpr( is_sized<Container<T, N>> && is_sized<recursive_invoke_result_t<F, Container<T, N>>> ) { assert( output.size() == input.size() ); } return output; } } void tests() { // non-nested input test, lambda function applied on input directly std::cout << "non-nested input test, lambda function applied on input directly:\n"; int test_number = 3; auto nonul_recursive_transform_output1 = NonUL::recursive_transform(test_number, [](auto&& element) { return element + 1; }); std::cout << "NonUL::recursive_transform function output: \n" << nonul_recursive_transform_output1 << "\n\n";
{ "domain": "codereview.stackexchange", "id": 44556, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, recursion, template, c++20, constrained-templates", "url": null }
c++, recursion, template, c++20, constrained-templates // test with non-nested std::array container std::cout << "test with non-nested std::array container:\n"; static constexpr std::size_t D = 3; auto test_array = std::array< double, D >{1, 2, 3}; auto nonul_recursive_transform_output2 = NonUL::recursive_transform(test_array, [](int&& element) { return element + 1; }); std::cout << "NonUL::recursive_transform function output: \n"; for(int i = 0; i < nonul_recursive_transform_output2.size(); ++i) { std::cout << nonul_recursive_transform_output2[i] << " "; } std::cout << "\n\n"; // TODO: test with nested std::arrays auto test_nested_array = std::array< decltype(test_array), D >{test_array, test_array, test_array}; //std::cout << "test with nested std::arrays: \n" // << UL::recursive_transform<2>(test_nested_array, [](auto&& element) { return element + 1; })[0][0] << '\n'; std::cout << "std::vector input test, lambda function applied on input directly:\n"; std::vector<int> test_vector1 = { 1, 2, 3 }; auto ul_recursive_transform_output3 = UL::recursive_transform<0>(test_vector1, [](auto element) { element.push_back(4); element.push_back(5); return element; }); std::cout << "UL::recursive_transform function output: \n"; for(int i = 0; i < ul_recursive_transform_output3.size(); ++i) { std::cout << ul_recursive_transform_output3[i] << " "; } std::cout << '\n';
{ "domain": "codereview.stackexchange", "id": 44556, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, recursion, template, c++20, constrained-templates", "url": null }
c++, recursion, template, c++20, constrained-templates std::vector<int> test_vector2 = { 1, 2, 3 }; // [A Issue to Be Addressed] Error from Clang: // error: no matching function for call to '__begin' /* auto nonul_recursive_transform_output3 = NonUL::recursive_transform(test_vector2, [](int element) { return element; }); std::cout << "NonUL::recursive_transform function output: \n"; for(int i = 0; i < nonul_recursive_transform_output3.size(); ++i) { std::cout << nonul_recursive_transform_output3[i] << " "; } */ std::cout << "\n\n"; std::vector<int> test_vector = { 1, 2, 3 }; auto test_priority_queue = std::priority_queue<int>(std::ranges::begin(test_vector), std::ranges::end(test_vector)); std::cout << "test with std::priority_queue container: \n" << UL::recursive_transform<0>(test_priority_queue, [](auto element) { element.push(4); element.push(5); element.push(6); return element; }).top() << '\n'; } int main() { tests(); return 0; } The output of the test code above: non-nested input test, lambda function applied on input directly: NonUL::recursive_transform function output: 4 test with non-nested std::array container: NonUL::recursive_transform function output: 2 3 4 std::vector input test, lambda function applied on input directly: UL::recursive_transform function output: 1 2 3 4 5 test with std::priority_queue container: 6 Godbolt link All suggestions are welcome. The summary information: Which question it is a follow-up to? A recursive_transform_view Template Function which returns a view in C++ What changes has been made in the code since last question? For dealing with dangling reference issue, the updated recursive_transform template function implementation is posted here.
{ "domain": "codereview.stackexchange", "id": 44556, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, recursion, template, c++20, constrained-templates", "url": null }
c++, recursion, template, c++20, constrained-templates Why a new review is being asked for? I am not sure I understand the previous suggestions correctly and both implementation and the corresponding tests are posted here. If there is any misunderstanding, please let me know. Answer: This isn’t really very useful. What you want to do, in just about every case I can imagine, is create the transformed data structure. It meets the requirements of std::input_range, and can be passed by reference to nearly every function that expects a view. For the remaining cases where you really do want to pass around a small object representing a view, you can create the transformed structure and then take a view of it with std::ranges::views::all. This will not be able to outlive the transformed object. Where it might do you some good is when you only need one element of a large data structure under the transformation, and it would be wasteful to fill a copy of the entire data structure with transformed data you won’t need. But in that case, it’s more efficient to retrieve the element and apply the transformation function to it.
{ "domain": "codereview.stackexchange", "id": 44556, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, recursion, template, c++20, constrained-templates", "url": null }
c++, reinventing-the-wheel, memory-management, pointers Title: Implementation of a shared pointer constructors and destructor Question: I am writing my simple shared pointer. I am asking to review existing functions (understand that my implementations is not full, e.g now operator*) Review please correctness Copy/move constructors and operator= Destructors My code template<typename T> class my_shared_ptr { public: my_shared_ptr() {} my_shared_ptr(T* ptr) { ptr_ = ptr; counter_ = new size_t(1); } my_shared_ptr(const my_shared_ptr& other) { destroy_current(); ptr_ = other.ptr_; counter_ = other.counter_; if (other.ptr_ != nullptr) { *counter_ += 1; } } my_shared_ptr(my_shared_ptr&& other) { ptr_ = other.ptr_; counter_ = other.counter_; other.ptr_ = nullptr; other.counter_ = nullptr; } my_shared_ptr& operator=(const my_shared_ptr& other) { destroy_current(); ptr_ = other.ptr_; counter_ = other.counter_; if (other.ptr_ != nullptr) { *counter_ += 1; } } my_shared_ptr&& operator=(my_shared_ptr&& other) { ptr_ = other.ptr_; counter_ = other.counter_; other.ptr_ = nullptr; other.counter_ = nullptr; } ~my_shared_ptr() { destroy_current(); } private: void destroy_current() { if (counter_ and *counter_ > 1) { *counter_ -= 1; } else { delete ptr_; delete counter_; } } private: T* ptr_ = nullptr; size_t* counter_ = nullptr; }; template<typename T, typename... Args> my_shared_ptr<T> make_my_shared(Args&&... args) { auto ptr = new T(std::forward<Args>(args)...); return my_shared_ptr<T>(ptr); } struct A { int val_ = 0; A(int val) : val_(val) { std::cout << "A(" << val_ << ")" << std::endl ; } ~A() { std::cout << "~A(" << val_ << ")" << std::endl ; } };
{ "domain": "codereview.stackexchange", "id": 44557, "lm_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++, reinventing-the-wheel, memory-management, pointers", "url": null }
c++, reinventing-the-wheel, memory-management, pointers }; int main() { std::cout << "-----------\n"; { my_shared_ptr<A> a1; //my_shared_ptr<A> a2 = make_my_shared<A>(2); my_shared_ptr<A> a2(new A(2)); { my_shared_ptr<A> a3(new A(3)); std::cout << "log 1" << std::endl; a1 = a3; std::cout << "log 2" << std::endl; a2 = a3; std::cout << "log 3" << std::endl; } std::cout << "log 4" << std::endl; } std::cout << "Program finished!" << std::endl ; } Answer: Overview Self assignment is broken. Code Review First issue is here: my_shared_ptr(const my_shared_ptr& other) { // You are creating this object for the first time // So there is never going to be anything to destroy. destroy_current(); ptr_ = other.ptr_; counter_ = other.counter_; if (other.ptr_ != nullptr) { *counter_ += 1; } } You really want move semantics to be exception safe. I don't see any reason why it could not be exception safe. my_shared_ptr(my_shared_ptr&& other) { // So this function should be marked as noexcept. ptr_ = other.ptr_; counter_ = other.counter_; // There is already a command to set and move (see: std::exchange) other.ptr_ = nullptr; other.counter_ = nullptr; } This is actually broken. Self assignment is going to release the memory, then increment the pointer on the newly released counter. my_shared_ptr& operator=(const my_shared_ptr& other) { destroy_current(); ptr_ = other.ptr_; counter_ = other.counter_; if (other.ptr_ != nullptr) { *counter_ += 1; } } Try: my_shared_ptr<int> first(new int{4}); my_shared_ptr<int>& ref = first; first = ref; // bang.
{ "domain": "codereview.stackexchange", "id": 44557, "lm_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++, reinventing-the-wheel, memory-management, pointers", "url": null }
c++, reinventing-the-wheel, memory-management, pointers first = ref; // bang. Again. This should probably be exception safe. So mark it as such. Aslo you can use std::exchange() to do most of the work. my_shared_ptr&& operator=(my_shared_ptr&& other) { ptr_ = other.ptr_; counter_ = other.counter_; other.ptr_ = nullptr; other.counter_ = nullptr; } How I would write it: template<typename T> class my_shared_ptr { T ptr = nullptr; std::size_t* size = nullptr; bool decrementCountReachedZero() const { --(*size); return *size == 0; } public: ~my_shared_ptr() { if (size && decrementCountReachedZero()) { delete ptr; delete size; } } // Note: Default constructor // Uses the default initialization values. my_shared_ptr() {} // Take ownership of a pointer. explicit my_shared_ptr(T* take) : ptr(take) , size(new std::size_t{1}) {} // You may want a constructor that takes a `nullptr` // Because the above will not allow nullptr because of // the explicit my_shared_ptr(std::nullptr_t) : ptr(nullptr) , size(nullptr) {} // Standard Copy Constructor. my_shared_ptr(my_shared_ptr const& copy) : ptr(copy.ptr) , size(copy.size) { // OK we have constructed now. // So increment the size if it exists if (size) { ++(*size); } }
{ "domain": "codereview.stackexchange", "id": 44557, "lm_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++, reinventing-the-wheel, memory-management, pointers", "url": null }
c++, reinventing-the-wheel, memory-management, pointers // Standard Move Constructor my_shared_ptr(my_shared_ptr&& move) noexcept : ptr(std::exchange(move.ptr, nullptr)) , size(std::exchange(move.size, nullptr)) { // No action required // as original objects pointers have been set to null // Thus effectively transferring ownership of any // pointer. } // NOTE HERE // // I am writing both the copy and move assignment // operators out in full. This is NOT the best way // to do it. I am doing this to help illustrate the // correct way. (See below) // For normal copy assignment. // Use the copy and swap idiom. my_shared_ptr& operator=(my_shared_ptr const& copy) { my_shared_ptr tmp{copy}; // increment of any counters // happens in the copy. // decrement of any counters // happens when this object // is destroyed (which will not // be the same as the object created :-)
{ "domain": "codereview.stackexchange", "id": 44557, "lm_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++, reinventing-the-wheel, memory-management, pointers", "url": null }
c++, reinventing-the-wheel, memory-management, pointers // Do the work. // Swap the tmp and the current object. // everything should be in the correct place. tmp.swap(*this); return *this; } // For normal move assignment. // Make sure the current object owned by "this" is destroyed. // Overwrite "this" one and set "move" old version to nullptr. my_shared_ptr& operator=(my_shared_ptr&& move) noexcept { my_shared_ptr tmp{std::move(*this)};// This moves the current object // into a temp. This will be // destroyed at end of scope // and thus reduce the counter // if there is one. // Do the work. // The current object is now null // So we swap with the source("move") thus putting nulls // into "move" and setting this object with the new value. move.swap(*this); return *this; } // NOTE: You will notice that both versions of // the assignment operator are identical. // So there is a neat trick to simplify both these // into a single assignment operator that handles // both situations: // Simply pass by value. // If it is an lvalue it is copied. // If it is an rvalue it will be moved. // Which has the identical operation as the tmp variable my_shared_ptr& operator=(my_shared_ptr tmp) noexcept { tmp.swap(*this); return *this; } // At this point tmp goes out of scope. // destroying the tmp copy or the old value
{ "domain": "codereview.stackexchange", "id": 44557, "lm_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++, reinventing-the-wheel, memory-management, pointers", "url": null }
c++, reinventing-the-wheel, memory-management, pointers // Utility function. void swap(my_shared_ptr& other) noexcept { std::swap(ptr, other.ptr); std::swap(size, other.size); } friend void swap(my_shared_ptr& lhs, my_shared_ptr& rhs) { lhs.swap(rhs); } };
{ "domain": "codereview.stackexchange", "id": 44557, "lm_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++, reinventing-the-wheel, memory-management, pointers", "url": null }
python, performance, html, xpath, lxml Title: Counting Ads in webpage using XPath and EasyList in Python Question: I have the following the function the retrieves a given webpage and returns the number of adverts that are on the page using a shortened version of EasyList (17,000 rules). Using multiprocessing, this scraped 18,000 pages in just over 2 days (which was fine at the time). However, I now have a dataset that is 10x larger so this runtime isn't particularly ideal. I suspect that it's running in quadraticly due to this line result = len(document.xpath(rule)) in the for loop. I'm not very familiar with XPath/lxml at all so some advice on how to make this more efficient would be appreciated or at least some indication whether I can make it run much faster or not. import lxml.html import requests import cssselect import pandas as pd from multiprocessing import Pool def count_ads(url): rules_file = pd.read_csv("easylist_general_hide.csv", sep="\t",header=None) try: html = requests.get(url,timeout=5).text except: print(f"Page not found or timed out: {url}") return count = 0 translator = cssselect.HTMLTranslator() for rule in rules_file[0]: try: rule = translator.css_to_xpath(rule[2:]) document = lxml.html.document_fromstring(html) result = len(document.xpath(rule)) if result>0: count = count+result except: pass return count``` Answer: You are apparently using this library: https://pypi.org/project/cssselect Measured time to process a scraped page is ~ 10 seconds, and we wish to reduce that.
{ "domain": "codereview.stackexchange", "id": 44558, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, performance, html, xpath, lxml", "url": null }
python, performance, html, xpath, lxml There are so many essential details left out of the OP, including profiler observations of an actual run. I can see at least one thing that could be immediately improved. A constant could be hoisted out of a loop. html = requests.get(url,timeout=5).text ... for rule in rules_file[0]: ... rule = translator.css_to_xpath(rule[2:]) document = lxml.html.document_fromstring(html) result = len(document.xpath(rule)) It looks like constant document parsing could be hoisted, similar to how translator has already been hoisted. No need to recompute it 17 K times, once per rule. document = lxml.html.document_fromstring(html) for rule in rules_file[0]: ... Presumably a given worker process will handle multiple URLs. So for N pages we invoke .css_to_xpath() 1.7e4 × N times. Looks like there may be an opportunity for caching, here. A naïve approach would just tack on a cache decorator: @lru_cache(max_size=17_400) def get_xpath(...): But there can be some fiddly requirements, such as all arguments being hashable. If you encounter such trouble, don't give up. There must be some way to avoid boring repeated xpath extraction of same old rule data. Seventeen thousand rules sounds like a lot. I bet some of them trigger often, and some quite seldom, perhaps zero times in your corpus. You have time and resource constraints. Apparently fewer than twenty days are available. Rank order rules by how useful they are, and run just the top thousand of them against your freshly received pages. Publish preliminary results. Decide if you want to go back and try the next thousand rules, or ten thousand rules. Look for patterns. Perhaps the URL's hostname predicts which hundred rules are most likely to apply to the page. There's two parts to this program: I/O web download, and compute
{ "domain": "codereview.stackexchange", "id": 44558, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, performance, html, xpath, lxml", "url": null }
python, performance, html, xpath, lxml There's two parts to this program: I/O web download, and compute The former has a very small memory footprint, unlike the latter. This has implications for scheduling server resources. Consider breaking out a "fetch" phase that focuses solely on issuing .get()s (with timeout) and then persisting the result to disk. Then a subsequent "compute" phase can analyze the fetched pages, perhaps in much less than an average of ten seconds. Benchmark a short run. Then try it again with pypy. Sometimes that will win.
{ "domain": "codereview.stackexchange", "id": 44558, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, performance, html, xpath, lxml", "url": null }
c++, playing-cards Title: C++ Blackjack game Question: I made this small Blackjack game in the past as a way to practice C++ basics and have fun at the same time. I stopped working on the game during the last two years of my computer science degree program and now in my free time I want to improve it. I'm looking for suggestions on how I can improve the game. Not just adding new features, but how I can improve the organization, eliminate unnecessary code, and stick to common (industry standard) programming practice. Feel free to make as many comments as you like! (I'm aware that I could add more comments) Blackjack.cpp #include "stdafx.h" #include "Blackjack.h" Blackjack::Blackjack() { srand(time(0)); dhandSize = 0; phandSize = 0; dhandSum = 0; phandSum = 0; playerDone = false; dealerDone = false; } void Blackjack::playGame() { cout << "Welcome to Blackjack!\n"; // Start the player and dealer with two cards addPlayerCard(); addPlayerCard(); addDealerCard(); addDealerCard(); sumHands(); printHand(); if (dhandSum == 21) { cout << "Dealer has blackjack. Dealer wins.\n"; return; } else if (phandSum == 21) { cout << "Player has blackjack. Player wins.\n"; return; } while (dealerDone == false || playerDone == false) { if (playerDone == false) { cout << "Would you like to hit? (1 - Yes, 2 - No)\n"; cin >> phit; if (phit == 1) { addPlayerCard(); printHand(); sumHands(); if (phandSum > 21) { cout << "Player's hand exceeded 21. Player loses.\n"; return; } } } if (playerDone == false) { cout << "Would you like to stand? (1 - Yes, 2 - No)\n"; cin >> pstand; }
{ "domain": "codereview.stackexchange", "id": 44559, "lm_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++, playing-cards", "url": null }
c++, playing-cards if (pstand == 1) { playerDone = true; } if (dhandSum < 17 && dealerDone != true) { addDealerCard(); printHand(); sumHands(); if (dhandSum > 21) { cout << "Dealer hand exceeded 21. Dealer loses.\n"; return; } } else if (dhandSum >= 17) { dealerDone = true; } if (phandSum == 21 && dhandSum == 21) { cout << "Push, player and dealer reached 21.\n"; return; } else if (phandSum == 21) { cout << "Player reached 21. Player wins.\n"; return; } else if (dhandSum == 21) { cout << "Dealer reached 21. Dealer wins.\n"; return; } if ((playerDone == true && dealerDone == true) || (phandSize == 5 && phandSize == 5)) { if (dhandSum < phandSum) { cout << "Sum of your hand exceeds the dealer's sum of " << dhandSum << "! You win!"; return; } else if (phandSum == dhandSum) { cout << "Dealer sum of " << dhandSum << " is equal to the sum of your hand. Tie game."; return; } else if (dhandSum > phandSum) { cout << "Sum of your hand is lower than the dealer's sum of " << dhandSum << ". You lose!"; return; } } } } int dhand[5]; int phand[5]; int dhandSize; int phandSize; int dhandSum; int phandSum; int phit; int pstand; bool playerDone; bool dealerDone; void Blackjack::addPlayerCard() { if (phandSize <= 5) { phand[phandSize] = 1 + (rand() % 11); phandSize++; } else { cout << "Sorry. You have reached the maximum number of cards (5)." << endl; playerDone = true; } }
{ "domain": "codereview.stackexchange", "id": 44559, "lm_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++, playing-cards", "url": null }
c++, playing-cards void Blackjack::addDealerCard() { if (dhandSize <= 5) { dhand[dhandSize] = 1 + (rand() % 11); dhandSize++; } else { dealerDone = true; } } void Blackjack::printHand() { cout << "Your current hand is...\n"; for (int i = 0; i < phandSize; i++) { cout << " -" << phand[i] << "- \n\n"; } cout << "Dealer's current hand is...\n"; for (int j = 0; j < dhandSize; j++) { cout << " -" << dhand[j] << "- \n\n"; } } void Blackjack::sumHands() { dhandSum = 0; phandSum = 0; for (int i = 0; i < dhandSize; i++) { dhandSum += dhand[i]; } for (int j = 0; j < phandSize; j++) { phandSum += phand[j]; } cout << "Current player hand sum is: " << phandSum << endl; } main.cpp #include "stdafx.h" #include "Blackjack.h" int main() { int exitGame = 1; do { Blackjack casino_royale; casino_royale.playGame(); cout << "\nWould you like to play again? (1 - Yes, 2 - No)\n"; cin >> exitGame; }while (exitGame == 1); cout << "\nThanks for playing!\n"; system("pause"); return 0; } Blackjack.h #pragma once #include "stdafx.h" class Blackjack { public: Blackjack(); void playGame(); private: int dhand[5]; int phand[5]; int dhandSize; int phandSize; int dhandSum; int phandSum; int phit; int pstand; bool playerDone; bool dealerDone; void addPlayerCard(); void addDealerCard(); void printHand(); void sumHands(); }; Answer: Members Vs Globals It's odd that you have global variables defined in your Blackjack.cpp file. These: int dhand[5]; int phand[5]; int dhandSize; int phandSize; int dhandSum; int phandSum; int phit; int pstand; bool playerDone; bool dealerDone;
{ "domain": "codereview.stackexchange", "id": 44559, "lm_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++, playing-cards", "url": null }
c++, playing-cards Look like they should have been declared as class members (which now that you have added the header I can see that they are in there as well), rather than globals. The globals should be removed, they're just going to cause confusion. What's in a deck When you're dealing cards, you're deciding what card to add using a random generator. phand[phandSize] = 1 + (rand() % 11); This is ok as a start, however it's possible that the player could end up with 5 aces etc. Is that really what you want? With a pack of cards, there are many cards that have a value of ten (10,Jack,Queen,King) yet your current random approach thinks all card values are as likely. In reality, the chances of you getting each card decrease as cards of that value are removed from the deck. Consider adding a deck class that you initialise with 1 or more packs of shuffled cards when constructed then remove from the deck as each card is drawn. This would make your draws more realistic and allow you to reuse the deck class in any future card games you may construct (such as poker). Duplicated Code - Player Vs Dealer Dealers and players are almost the same. You're performing the same calculations in AddPlayerCard that you are performing in AddDealerCard. This could be generalised if you were for example to add the concept of a Player (dealers are players to, they're just automated) to your class. You could do something as simple as this: struct Player { int dhand[5]; int dhandSize; bool done; }; Then you have a addCardFunction that looked more like this: void Blackjack::addDealerCard(Player &player) { if (player.dhandSize <= 5) { player.dhand[dhandSize] = 1 + (rand() % 11); player.dhandSize++; } else { player.done = true; } }
{ "domain": "codereview.stackexchange", "id": 44559, "lm_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++, playing-cards", "url": null }
c++, playing-cards The next step being to look at the Player abstraction to see if some of the functionality could be pushed from your BlackJack class into it. For example it could have a method to CalculateScore, based on the cards it is holding. Adding this type of generalisation would also make it easier for you to extend your program so that it could for example support multiple players against the dealer. Dealer Bias After you deal your initial cards, you check if the dealer or player have Black Jack and declare them the winner if they do. If both players have 21, then the dealer is declared the winner. This is a good example of when extracting the functionality into a shared method would have helped you out. The checks you need to do are the same checks that are performed at the end of every round, except the end of round check supports a draw. If you extract the functionality into another method can call it from both places the game will become that little bit fairer for the players. Constants are your friends There are several places in your code that could benefit from the removal of 'magic' numbers. Replacing them with constants could help the readability of your code and reduce the chance of bugs. You might want to have a constant for 21 (possibly BlackJack), particularly since you have so many occurrences of it. A constant for MaxScoreForDealerToHit of 17 would help to make your code self-documenting, the <17 becomes much more readable as: if (dhandSum < MaxScoreForDealerToHit && dealerDone != true) However, the main constants I would introduce are for Yes(1) and No(2). You ask the user some yes no questions and have the same values for the answer, so using a constant would really aid translation. Consider this (from your main loop): int exitGame = Yes; do { Blackjack casino_royale; casino_royale.playGame(); cout << "\nWould you like to play again? (1 - Yes, 2 - No)\n"; cin >> exitGame; }while (exitGame == Yes);
{ "domain": "codereview.stackexchange", "id": 44559, "lm_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++, playing-cards", "url": null }
c++, playing-cards It becomes much more obvious that your exitGame variable should be called playAgain. Letters for variable names don't cost the Earth In context, you can figure out what dhand, dhandSize, dhandSum mean. However, they would be much more expressive if you pad them out with some missing letters: DealerHand, NumberOfCardsDealerHas, DealersCardTotal.
{ "domain": "codereview.stackexchange", "id": 44559, "lm_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++, playing-cards", "url": null }
java, strings, column Title: Print columns of text without hard coding the width Question: If you'd like to print this: One Two Three Four 1 2 3 4 using this: new Columns() .withColumnSeparator(" ") .withPad(" ") .alignCenter() .addLine("One", "Two", "Three", "Four") .addLine("1", "2", "3", "4") .print() ; all you need is this: import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.function.BiFunction; public class Columns { List<List<String>> lines = new ArrayList<>(); List<Integer> maxLengths = new ArrayList<>(); int numColumns; int oldLength; boolean firstCall = true; String columnSeparator = " "; String pad = " "; BiFunction<String, String, String> align = (word, pad) -> word += pad; public Columns addLine(String... line) { if (firstCall){ for(int column = 0; column < line.length; column++) { maxLengths.add(0); } oldLength = line.length; } if (oldLength != line.length) { throw new IllegalArgumentException(); } for(int column = 0; column < line.length; column++) { int length = Math .max( maxLengths.get(column), line[column].length() ) ; maxLengths.set( column, length ); } lines.add( Arrays.asList(line) ); firstCall = false; return this; } public void print(){ System.out.println( toString() ); }
{ "domain": "codereview.stackexchange", "id": 44560, "lm_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, strings, column", "url": null }
java, strings, column public void print(){ System.out.println( toString() ); } public String toString(){ String result = ""; for(List<String> line : lines) { for(int column = 0; column < line.size(); column++) { result += pad( line.get(column), maxLengths.get(column) ); if (column < line.size() - 1) { result += columnSeparator; } } result += System.lineSeparator(); } return result; } private String pad(String word, int newLength){ while (word.length() < newLength) { word = align.apply(word, pad); } return word; } public Columns withColumnSeparator(String columnSeparator){ this.columnSeparator = columnSeparator; return this; } public Columns withPad(String pad){ this.pad = pad; return this; } public Columns alignLeft(){ align = (word, pad) -> word = word + pad; return this; } public Columns alignRight(){ align = (word, pad) -> word = pad + word; return this; } public Columns alignCenter(){ align = (word, pad) -> { return (word.length() % 2 == 0) ? pad + word : word + pad ; }; return this; } } By waiting until all the lines have been added before printing it can figure out the width each column needs. Looking for a code review to reveal problems. Anything from better names to fewer bugs to better ideas. Answer: The idea is good, and on the first look I don't see any bugs, but the implementation is a bit strange. All fields are lacking a private modifier. Some of the lambdas have an unnessecary assignment: (word, pad) -> word = word + pad (word, pad) -> word += pad The assignment to the parameter word does nothing. Just (word, pad) -> word + pad
{ "domain": "codereview.stackexchange", "id": 44560, "lm_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, strings, column", "url": null }
java, strings, column The assignment to the parameter word does nothing. Just (word, pad) -> word + pad is needed. You do it correctly in the "center" lamdba. Also assigning "new" lambdas everywhere isn't very optimal. The lambdas should either be static constants or private methods: private static final BiFunction<String, String, String> ALIGN_RIGHT = (word, pad) -> word + pad; private BiFunction<String, String, String> align = ALIGN_RIGHT; public Columns alignRight() { align = ALIGN_RIGHT; return this; } or private BiFunction<String, String, String> = Columns::doAlignRight; // TODO `doAlignRight` isn't a good name. Find better. private static String doAlignRight(String word, String pad) { return word + pad; } public Columns alignRight() { align = Columns::doAlignRight; return this; } EDIT: In Java lambdas are just to short way to implement and instantiate an interface. For example: align = (word, pad) -> word + pad; in the method alignRight() is short for align = new BiFunction<String, String, String>() { public String apply(String word, String pad) { return word + pad; } }; In other words, everytime one one of the align... methods is called a new object is created. However this is unnessecary, because the objects are the same every time. Instead by, for example, keeping a single instance in a static variable and reusing them, much less memory management is needed. Method names could be a bit better. with... usually implies that a new instance (of a usually immutable class) is returned. set... would be better. The align...() methods should also start with set... to match the other configuration methods. It can be confusing that there is both a field and a method called pad. The field numColumns is not used. firstCall and oldLength isn't really needed. Instead of firstCall it could be checked if lines is empty, and when not use the length of one of its entries instead of oldLength.
{ "domain": "codereview.stackexchange", "id": 44560, "lm_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, strings, column", "url": null }
java, strings, column String concatenation shouldn't be used in loops. A StringBuilder would be a better choice.
{ "domain": "codereview.stackexchange", "id": 44560, "lm_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, strings, column", "url": null }
matlab Title: Simple validation and mathematical function in MATLAB Question: I've made a script (Triangle.m) to calculate the area of a triangle in MATLAB: function Triangle() % Main function clc; clear variables; close all; % Set function values base = force_positive_finite("Base"); height = force_positive_finite("Height"); area = tri_area(base,height); fprintf("Area: %2.3f m²\n",area); end function output = force_positive_finite(var_name) % Ask/force the user to enter a positive number output = -1; while true output = input("Enter in "+var_name+" (m): "); if input_error_response(output) % If no error, leave loop break end end end function response = input_error_response(in) % Warns user if input is invalid if isempty(in) || in < 0 || in==inf % Value must be a non-empty positive number disp("Enter a value: {0 <= VALUE < inf}"); response = false; % This signals the loop to continue else response = true; % This means we can exit the loop end end function area = tri_area(base,height) % Calculate the area of a triangle arguments base {mustBeNumeric, mustBeFinite}; height {mustBeNumeric, mustBeFinite}; end area = base*height*0.5; end It contains force_positive_finite to ensure the input is >= 0 and finite, then is fed into tri_area where it is checked to be numeric and finite, before calculating the area. I am new to MATLAB, so any pointers on convention, optimisation and general improvements are appreicated.
{ "domain": "codereview.stackexchange", "id": 44561, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "matlab", "url": null }
matlab Answer: The function Triangle() is clearly a script that you turned into a function. I personally don't like putting clc, clear and close at the top of my scripts, but I see this a lot, and it's not a terrible thing to do. In a function they are very much out of place. A function has its own workspace (it cannot see variables defined outside of it), so there really is no need for a clear. This is the point of using functions instead of scripts: each function has its own workspace ("scope" in other programming languages), which is cleared the moment the function ends. The base workspace doesn't get cluttered with variables if you use functions instead of scripts, and the code inside the function will not accidentally be using variables from a different scope (which makes finding bugs easier). Given that Triangle() asks for user input, a clc is not terrible, but you could accomplish the same effect (make the input prompt more visible) by first printing some empty lines. close all closes all figure windows. Your program doesn't deal with figure windows, why attack any existing ones? Just let them be! force_positive_finite() is fine. Of course there are other ways to implement it. Instead of break, for example, you could return. This makes it a bit easier (IMO) to read the function, because I don't need to look for additional code below the loop. I know this is where the function ends. But simpler would be: function output = force_positive_finite(var_name) % Ask/force the user to enter a positive number output = -1; while ~input_error_response(output) output = input("Enter in "+var_name+" (m): "); end end while tests a condition. Instead of invalidating that test by testing true, and adding an additional if statement, use that test to do what your if statement does.
{ "domain": "codereview.stackexchange", "id": 44561, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "matlab", "url": null }
matlab Similarly, input_error_response() can be simplified a bit. The construct if <test>, v = true, else, v = false is a typical anti-pattern, better written as v = <test>. You do a bit more inside your if statement, still you can avoid assigning true or false to your response variable: function response = input_error_response(in) % Warns user if input is invalid response = ~isempty(in) && in >= 0 && isfinite(in) if ~response disp("Enter a value: {0 <= VALUE < inf}"); end end Note that your comment "Value must be a non-empty positive number" comes next to a test for the number being non-negative, which is not the same as positive. Positive: in > 0. Non-negative: in >= 0. [Your original test, in < 0 is negated as in >= 0, as I put into my version of the function.] I changed the in == inf test to ~isfinite(in). This catches also the case where in == -inf (which you already tested for with the non-negativity test), and the case where in is NaN. Finally: What if the user inputs "foo"? What if the user inputs [4, 6]? You should probably also test that the input is a double array (isnumeric(in) or isfloat(in) or isa(in,'double')), and scalar (isscalar(in)).
{ "domain": "codereview.stackexchange", "id": 44561, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "matlab", "url": null }
python, web-scraping, selenium Title: Poetry Web Scraping in Python Question: I have a script that obtains urls that lead to a specific poem. This code current works and uses multiprocessing pools. I currently am getting restricted or blocked by some way from the website that I am attempting to scrape. How should I edit this code to scrape their site without slowing down their website (how slow should I go?) or is the speed not the problem. The code does work, but only when I go slowly and only run it a few times a day. The code goes a site "https://www.poetryfoundation.org/poems/browse#page=1&sort_by=recently_added" and then scrapes it for urls that go out to poems, like: "https://www.poetryfoundation.org/poems/159835/on-naming-yourself-a-cento" import bs4 as bs import re # For simulating the table on the webpage which is dynamically loaded. from selenium import webdriver from webdriver_manager.chrome import ChromeDriverManager from selenium.webdriver.chrome.service import Service from selenium.webdriver import Chrome from multiprocessing import cpu_count from multiprocessing import Pool import time global options global chrome_service chrome_path = ChromeDriverManager().install() #Path for my Chrome driver. options = webdriver.ChromeOptions() options.add_argument('--headless') # it's more scalable to work in headless mode # normally, selenium waits for all resources to download # we don't need it as the page also populated with the running javascript code. options.page_load_strategy = 'none' # this returns the path web driver downloaded chrome_path = ChromeDriverManager().install() chrome_service = Service(chrome_path) # pass the defined options and service objects to initialize the web driver def scrape_urls(pg_num: int): driver = Chrome(options=options, service=chrome_service) driver.implicitly_wait(5) link = f"https://www.poetryfoundation.org/poems/browse#page={pg_num}&sort_by=recently_added" driver.get(link) # load the page
{ "domain": "codereview.stackexchange", "id": 44562, "lm_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, web-scraping, selenium", "url": null }
python, web-scraping, selenium driver.get(link) # load the page # give it some time driver.implicitly_wait(45) time.sleep(10) html_source = driver.page_source soup = bs.BeautifulSoup(html_source, features="html.parser") out_urls = set() for aHref in soup.find_all("a",href=re.compile('.*/poems/[0-9]+/.*')): out_urls.add(aHref.get("href")) return out_urls def write(urls: set): # read past urls into set prev_urls = set() with open('urls.txt', mode='r', encoding='utf-8') as f: for line in f.readlines(): prev_urls.add(line.strip()) print(f'# of old urls: {len(prev_urls)}') # get urls not already in file out_urls = urls.difference(prev_urls) print(len(out_urls)) # append urls out to file with open('urls.txt', mode='a', encoding='utf-8') as f: for url in out_urls: f.write(url+'\n') return def main(): start = time.time() num_urls = 100 # number of urls to scrape from: max is 2341 num_processes = cpu_count() # number of processes out_urls = set() with Pool(num_processes) as p: for result in p.map(scrape_urls, range(1, num_urls+1)): out_urls |= result write(out_urls) end = time.time() print(f"Time spent: {end-start}") if __name__ == "__main__": main()
{ "domain": "codereview.stackexchange", "id": 44562, "lm_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, web-scraping, selenium", "url": null }
python, web-scraping, selenium if __name__ == "__main__": main() Answer: One thing that immediately jumps out at me is the fact you set num_processes = cpu_count() for the multi-processing pool. The absolute maximum I would recommend is cpu-count()-1 but even then I would consider that as high. I do similar web-scraping tasks using multi-processing and I have 16 logical processors and set the Pool at 10. CPU sits at roughly 80% utilisation when I do this and it prevents context switching which can make multi-processing slower than if you had used less processes. This point is more of an FYI for future reference though, I actually don't think you need to use multi-processing at all for this task... Instead, I strongly advise against using Selenium except for very specific use-cases. Inspecting the webpage and recording the network activity, we can see that there is a GET request which returns a JSON response of all the links you're looking for. See here: https://www.poetryfoundation.org/ajax/poems?page=1&sort_by=recently_added Fetching the JSON from this link and looping through the pages, you should be able to parse the links you want considerably faster.
{ "domain": "codereview.stackexchange", "id": 44562, "lm_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, web-scraping, selenium", "url": null }
python, object-oriented, classes Title: Making a game using python and pygame Question: I am making a game using python and pygame and as my game started to grow, in some of my classes the number of instance variables started to get big. Like in the settings class is like this: class Settings: """A class to store all settings for Alien Invasion.""" def __init__(self): """Initialize the game's static settings.""" # Screen Settings self.screen_size = (1260, 700) self.screen_width = 1260 self.screen_height = 700 # game background images self.bg_img = pygame.image.load('images/background/space.jpg') self.second_bg = pygame.image.load('images/background/space2.png') self.third_bg = pygame.image.load('images/background/space4.jpg') self.game_over = pygame.image.load('images/other/gameover.png') self.pause = pygame.image.load('images/other/pause.png') self.fire_sound = pygame.mixer.Sound('sounds/fire.wav') self.endless = False self.last_stand = False # Ships settings self.max_hp = 5 self.thunderbird_hp = 3 self.phoenix_hp = 3 # Thunderbolt settings self.thunderbird_bullet_count = 1 # Firebird settings self.phoenix_bullet_count = 50 # Alien settings self.alien_direction = 1 self.max_alien_speed = 4.0 self.max_aliens_num = 35 self.boss_hp = 50 self.boss_points = 2500 self.alien_points = 1 self.endless_num = 50 # PowerUps settings self.powerup_speed = 1.5 # How quickly the game speeds up self.speedup_scale = 0.3 self.score_scale = 4 self.initialize_dynamic_settings() # Player1 controls self.p1_controls = ("Player 1:\n" "Movement: Arrow Keys\n" "Shoot: Enter\n" "Ship skin: Numpad 1, 2, 3\n" "Pause: P")
{ "domain": "codereview.stackexchange", "id": 44563, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, object-oriented, classes", "url": null }
python, object-oriented, classes # Player2 controls self.p2_controls = ("Player 2:\n" "Movement: W, A, S, D\n" "Shoot: Space\n" "Ship skin: 1, 2, 3\n" "Pause: P") My question now is, i should create different classes for different groups of variables and call the classes inside the Settings, o I should just group the variables in different methods in the Settings class? Answer: It looks like you're actually mixing a few unrelated things here. Consider: how many of these are actually settings? That is, how many of these does it make sense for the end user to modify in some way? Fields like bg_img and game_over are clearly not settings, but rather constants which are built into the game. Fields like powerup_speed and boss_points could conceivably be dynamic (boss_points could be a function which depends on some points-increasing powerup, for example), but the user probably shouldn't be able to change them. Fields which are not user settings could be part of, for example, an admin settings class/instance (if that needs to exist), or just constants which can't be changed at runtime. As for solutions for handling lots of values (constant and dynamic) across lots of entities, you probably want to look into entity component systems. As a side note, screen_size duplicates the information in screen_width and screen_height, so it probably shouldn't exist at all.
{ "domain": "codereview.stackexchange", "id": 44563, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, object-oriented, classes", "url": null }
java, strings, lambda, column Title: Print columns of text without hard coding the width (attempt 2) Question: If you'd like to print this: One Two Three Four 1 2 3 4 using this: new Columns() .withColumnSeparator(" ") .withPad(" ") // .alignLeft() .alignCenter() // .alignRight() .addLine("One", "Two", "Three", "Four") .addLine("1", "2", "3", "4") .print() ; all you need is this: import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.function.Function; import java.util.function.UnaryOperator; public class Columns { private List<List<String>> lines = new ArrayList<>(); private List<Integer> maxLengths = new ArrayList<>(); private String columnSeparator = " "; private String pad = " "; private Function<String, Function<String, UnaryOperator<String>>> align; { alignLeft(); // set default alignment } public Columns addLine(String... line) { if (maxLengths.size() == 0){ for(int column = 0; column < line.length; column++) { maxLengths.add(0); } } if ( maxLengths.size() != line.length ) { throw new IllegalArgumentException(); } for(int column = 0; column < line.length; column++) { int length = Math .max( maxLengths.get(column), line[column].length() ) ; maxLengths.set( column, length ); } lines.add( Arrays.asList(line) ); return this; } public Columns print(){ System.out.println( toString() ); return this; }
{ "domain": "codereview.stackexchange", "id": 44564, "lm_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, strings, lambda, column", "url": null }
java, strings, lambda, column public Columns print(){ System.out.println( toString() ); return this; } public String toString(){ int totalLength = 0; for(List<String> line : lines) { for(int column = 0; column < line.size(); column++) { totalLength += maxLengths.get(column); if (column < line.size() - 1) { totalLength += columnSeparator.length(); } } totalLength += System.lineSeparator().length(); } StringBuilder result = new StringBuilder(totalLength); for(List<String> line : lines) { for(int column = 0; column < line.size(); column++) { result.append( padCell( line.get(column), maxLengths.get(column) ) ); if (column < line.size() - 1) { result.append(columnSeparator); } } result.append( System.lineSeparator() ); } return result.toString(); } private String padCell(String word, int newLength){ int padCount = newLength - word.length(); int leftCount = padCount / 2; int rightCount = padCount - leftCount; String left = new String(new char[leftCount]).replace("\0", pad); String right = new String(new char[rightCount]).replace("\0", pad); return align.apply(left).apply(word).apply(right); } public Columns separateColumnsWith(String columnSeparator){ this.columnSeparator = columnSeparator; return this; } public Columns padWith(String pad){ this.pad = pad; return this; } public Columns alignLeft(){ align = left -> word -> right -> word + left + right; return this; }
{ "domain": "codereview.stackexchange", "id": 44564, "lm_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, strings, lambda, column", "url": null }