text
stringlengths
1
2.12k
source
dict
c, linked-list, macros /** * Defines a Singly Linked List storing data type TData which can be retrieved * later on with TKey. Requires a 3-way comparison function FComparer_TData_TKey * comparing data against a key to be provided to enable retrieval and deletion * of the data. */ #define DEFINE_SINGLY_LINKED_LIST_T(TKey, TData, FComparer_TData_TKey) \ typedef struct SinglyLinkedList_##TData##_##TKey SinglyLinkedList_##TData##_##TKey; \ typedef struct SinglyLinkedListNode_##TData##_##TKey SinglyLinkedListNode_##TData##_##TKey; \ \ struct SinglyLinkedList_##TData##_##TKey { \ SinglyLinkedList_##TData##_##TKey *this; \ \ SinglyLinkedListNode_##TData##_##TKey *head; \ \ void (*add)(SinglyLinkedList_##TData##_##TKey * this, TData *data); \ void (*remove)(SinglyLinkedList_##TData##_##TKey * this, TKey *key); \ TData *(*find)(SinglyLinkedList_##TData##_##TKey * this, TKey *key); \ void (*clear)(SinglyLinkedList_##TData##_##TKey * this); \ }; \ \
{ "domain": "codereview.stackexchange", "id": 44178, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c, linked-list, macros", "url": null }
c, linked-list, macros struct SinglyLinkedListNode_##TData##_##TKey { \ TData *data; \ SinglyLinkedListNode_##TData##_##TKey *next; \ }; \ \ void sll_add_##TData##_##TKey(SinglyLinkedList_##TData##_##TKey *this, TData *data); \ void sll_remove_##TData##_##TKey(SinglyLinkedList_##TData##_##TKey *this, TKey *key); \ TData *sll_find_##TData##_##TKey(SinglyLinkedList_##TData##_##TKey *this, TKey *key); \ void sll_clear_##TData##_##TKey(SinglyLinkedList_##TData##_##TKey *this); \ \ SinglyLinkedList_##TData##_##TKey *newSinglyLinkedList_##TData##_##TKey(void) { \ SinglyLinkedList_##TData##_##TKey *list = malloc(sizeof(SinglyLinkedList_##TData##_##TKey)); \ if (list == NULL) return NULL; \ list->this = list; \ list->head = NULL; \ \ list->add = sll_add_##TData##_##TKey; \ list->remove = sll_remove_##TData##_##TKey; \
{ "domain": "codereview.stackexchange", "id": 44178, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c, linked-list, macros", "url": null }
c, linked-list, macros list->find = sll_find_##TData##_##TKey; \ list->clear = sll_clear_##TData##_##TKey; \ \ return list; \ } \ \ SinglyLinkedListNode_##TData##_##TKey *newSinglyLinkedListNode_##TData##_##TKey(void) { \ SinglyLinkedListNode_##TData##_##TKey *node = malloc(sizeof(SinglyLinkedListNode_##TData##_##TKey)); \ if (node == NULL) return NULL; \ node->data = NULL; \ node->next = NULL; \ \ return node; \ } \ \ void sll_add_##TData##_##TKey(SinglyLinkedList_##TData##_##TKey *this, TData *data) { \ SinglyLinkedListNode_##TData##_##TKey *newNode = newSinglyLinkedListNode_##TData##_##TKey(); \ newNode->data = data; \
{ "domain": "codereview.stackexchange", "id": 44178, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c, linked-list, macros", "url": null }
c, linked-list, macros \ SinglyLinkedListNode_##TData##_##TKey *node = this->head; \ \ if (node == NULL) { \ this->head = newNode; \ return; \ } \ \ while (node->next != NULL) node = node->next; \ node->next = newNode; \ } \ \ void sll_remove_##TData##_##TKey(SinglyLinkedList_##TData##_##TKey *this, TKey *key) { \ SinglyLinkedListNode_##TData##_##TKey *previous = NULL; \ SinglyLinkedListNode_##TData##_##TKey *node = this->head; \ \ while (node != NULL) { \ if (FComparer_TData_TKey(node->data, key) == 0) { \
{ "domain": "codereview.stackexchange", "id": 44178, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c, linked-list, macros", "url": null }
c, linked-list, macros if (previous != NULL) previous->next = node->next; \ free(node); \ return; \ } \ \ previous = node; \ node = node->next; \ } \ } \ \ TData *sll_find_##TData##_##TKey(SinglyLinkedList_##TData##_##TKey *this, TKey *key) { \ SinglyLinkedListNode_##TData##_##TKey *node = this->head; \ \ while (node != NULL) { \ if (FComparer_TData_TKey(node->data, key) == 0) return node->data; \ node = node->next; \ } \ \
{ "domain": "codereview.stackexchange", "id": 44178, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c, linked-list, macros", "url": null }
c, linked-list, macros return NULL; \ } \ \ void sll_clear_##TData##_##TKey(SinglyLinkedList_##TData##_##TKey *this) { \ SinglyLinkedListNode_##TData##_##TKey *node = this->head; \ while (node != NULL) { \ SinglyLinkedListNode_##TData##_##TKey *next = node->next; \ free(node); \ node = next; \ } \ }
{ "domain": "codereview.stackexchange", "id": 44178, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c, linked-list, macros", "url": null }
c, linked-list, macros #endif The following shows the various things you might expect a linked list to be able to do: #include <stdio.h> #include <string.h> #include "linkedlist.h" // Data to store inside the linked list typedef struct Cake { char name[255]; size_t size; } Cake; // Function to find out if we have the correct data int compare(Cake *data, size_t *key) { return data->size - *key; } // Actually define the linked list storing the data we chose DEFINE_SINGLY_LINKED_LIST_T(size_t, Cake, compare) int main() { // Create an instance of the linked list we just defined SinglyLinkedList_Cake_size_t *list = newSinglyLinkedList_Cake_size_t(); // Push some data into it Cake *c1 = malloc(sizeof(Cake)); strcpy(c1->name, "Cakeus Biggus"); c1->size = 420; Cake *c2 = malloc(sizeof(Cake)); strcpy(c2->name, "Cakeus Smallus"); c2->size = 69; list->add(list->this, c1); list->add(list->this, c2); // Find data we pushed earlier size_t *key = malloc(sizeof(size_t)); // this is rather unfortunate *key = 69; Cake *cake = list->find(list->this, key); // Data is still intact if (cake != NULL) { printf("Name: %s\nSize: %zu\n", cake->name, cake->size); } // Remove data list->remove(list->this, key); // we can recycle the key we made earlier // Sanity check to check the data really is gone Cake *nocake = list->find(list->this, key); if (nocake == NULL) { printf("The cake is a lie\n"); } // The OS would free our sanity cakes for us here, but otherwise we have to free it ourselves free(cake); free(nocake); return 0; } ```
{ "domain": "codereview.stackexchange", "id": 44178, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c, linked-list, macros", "url": null }
c, linked-list, macros return 0; } ``` Answer: General Observations Very interesting code and question. This looks like an attempt to write object oriented code in C. I've tried to do this myself, it has inherent problems. The use of list->this everywhere is an example of these problems. Another problem is that every time a bug is fixed in this code all the code that includes it must be recompiled and retested since all of the code is in the header file, the definitions of the functions should be in a C source file and only the function prototypes should be in the header file. As a general observation macro code is very hard to debug and maintain, the fact that you got it working is impressive, but maintaining the code over years could be a problem. Remember that you might not be the one that needs to maintain the code. Putting malloc() and free() into macros can definitely lead to debug and maintenance problems. Warning Messages I compiled this in Visual Studio 2022 using the C11 standard, with the warnings set to W3 and using the -wall switch. I got the following warning messages: 1>main.c 1>C:\CodeReview\macrolinkedlist\macrolinkedlist\linkedlist.h(1,1): warning C4067: unexpected tokens following preprocessor directive - expected a newline 1>C:CodeReview\macrolinkedlist\macrolinkedlist\main.c(14,23): warning C4267: 'return': conversion from 'size_t' to 'int', possible loss of data The type mismatch in the second warning is definitely a problem, the int value may switch from positive to negative. For the first warning message, rather than using DEFINE_SINGLY_LINKED_LIST_T(TKey, TData, FComparer) as the include guard I would have a second macro just as an include guard: #ifndef SINGLY_LINKED_LIST_H #define SINGLY_LINKED_LIST_H ... #endif // SINGLY_LINKED_LIST_H
{ "domain": "codereview.stackexchange", "id": 44178, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c, linked-list, macros", "url": null }
c, linked-list, macros Specific Observations Test for Possible Memory Allocation Errors The code is inconsistent for testing for memory allocation errors, there is a test in the macro in the header file, but the malloc() calls in main() are not tested. In modern high-level languages such as C++, memory allocation errors throw an exception that the programmer can catch. This is not the case in the C programming language. While it is rare in modern computers because there is so much memory, memory allocation can fail, especially if the code is working in a limited memory application such as embedded control systems. In the C programming language when memory allocation fails, the functions malloc(), calloc() and realloc() return NULL. Referencing any memory address through a NULL pointer results in undefined behavior (UB). Possible unknown behavior in this case can be a memory page error (in Unix this would be call Segmentation Violation), corrupted data in the program and in very old computers it could even cause the computer to reboot (corruption of the stack pointer). To prevent this undefined behavior a best practice is to always follow the memory allocation statement with a test that the pointer that was returned is not NULL. Convention When Using Memory Allocation in C When using malloc(), calloc() or realloc() in C a common convention is to sizeof(*PTR) rather sizeof(PTR_TYPE), this make the code easier to maintain and less error prone, since less editing is required if the type of the pointer changes. // Push some data into it Cake* c1 = malloc(sizeof(*c1)); if (c1) { strcpy(c1->name, "Cakeus Biggus"); c1->size = 420; } Cake* c2 = malloc(sizeof(*c2)); if (c2) { strcpy(c2->name, "Cakeus Smallus"); c2->size = 69; } list->add(list->this, c1); list->add(list->this, c2);
{ "domain": "codereview.stackexchange", "id": 44178, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c, linked-list, macros", "url": null }
c, linked-list, macros list->add(list->this, c1); list->add(list->this, c2); Odd Sized Char Array The declaration of Cake contains the declarations for a character array, but it is using 255 rather than 256, since 256 is an even binary number that is what I would expect to be used. // Data to store inside the linked list typedef struct Cake { char name[255]; size_t size; } Cake; To not waste memory it might be better to make name a character pointer and use strdup() if it available or write your own strdup(). Magic Numbers There are Magic Numbers in the main() function (255 above), it might be better to create symbolic constants for them to make the code more readable and easier to maintain. These numbers may be used in many places and being able to change them by editing only one line makes maintenance easier. Numeric constants in code are sometimes referred to as Magic Numbers, because there is no obvious meaning for them. There is a discussion of this on stackoverflow.
{ "domain": "codereview.stackexchange", "id": 44178, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c, linked-list, macros", "url": null }
javascript Title: Filtering array of nested objects Question: The following code is producing the desired output but I'm wondering if there's a way to accomplish the same result by applying .filter() to data. Any other more concise approaches than shown below are also welcomed. Data description: scenarios consist of a scenario object plus an array of profile objects Filtering goal: keep scenarios that have flag = 1 and probability > 0.9
{ "domain": "codereview.stackexchange", "id": 44179, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript", "url": null }
javascript const data = [ { "scenario": { "scenarioId": 41511, "flag": 1, "probability": 0.92 }, "profile": [ { "profileId": 1, "scenarioId": 41511, "capacity": 0.77 }, { "profileId": 2, "scenarioId": 41511, "capacity": 0.74 } ] }, { "scenario": { "scenarioId": 41521, "flag": 1, "probability": 0.8 }, "profile": [ { "profileId": 3, "scenarioId": 41521, "capacity": 0.96 } ] }, { "scenario": { "scenarioId": 41530, "flag": 0, "probability": 0.95 }, "profile": [ { "profileId": 4, "scenarioId": 41530, "capacity": 0.73 }, { "profileId": 5, "scenarioId": 41530, "capacity": 0.92 } ] }, { "scenario": { "scenarioId": 41540, "flag": 0, "probability": 0.85 }, "profile": [ { "profileId": 6, "scenarioId": 41540, "capacity": 0.88 } ] }, { "scenario": { "scenarioId": 41551, "flag": 1, "probability": 1 }, "profile": [ { "profileId": 7, "scenarioId": 41551,
{ "domain": "codereview.stackexchange", "id": 44179, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript", "url": null }
javascript { "profileId": 7, "scenarioId": 41551, "capacity": 0.88 }, { "profileId": 8, "scenarioId": 41551, "capacity": 0.99 } ] }, ];
{ "domain": "codereview.stackexchange", "id": 44179, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript", "url": null }
javascript const keepers = {}; for (i of data) { if (i.scenario.flag == 1 && i.scenario.probability > 0.9) { keepers[i.scenario.scenarioId] = { ...i.scenario, profile: i.profile }; } } console.log(keepers); Answer: Use filter to select a subset of elements. Use map to map all the elements from one type to another. Your program is a case for combination of both. For efficiency reasons, filter first so that you don't map elements you are not interested in. Don't use semicolons in js. They are not needed and it gets inconsistent if you forget them somewhere but the program still works. You can also use destructuring of the arguments to get rid of the dummy i. Also prefer strict comparison. In this case for the flag scenario.flag === 1 const data = [{"scenario":{"scenarioId":41511,"flag":1,"probability":0.92},"profile":[{"profileId":1,"scenarioId":41511,"capacity":0.77},{"profileId":2,"scenarioId":41511,"capacity":0.74}]},{"scenario":{"scenarioId":41521,"flag":1,"probability":0.8},"profile":[{"profileId":3,"scenarioId":41521,"capacity":0.96}]},{"scenario":{"scenarioId":41530,"flag":0,"probability":0.95},"profile":[{"profileId":4,"scenarioId":41530,"capacity":0.73},{"profileId":5,"scenarioId":41530,"capacity":0.92}]},{"scenario":{"scenarioId":41540,"flag":0,"probability":0.85},"profile":[{"profileId":6,"scenarioId":41540,"capacity":0.88}]},{"scenario":{"scenarioId":41551,"flag":1,"probability":1},"profile":[{"profileId":7,"scenarioId":41551,"capacity":0.88},{"profileId":8,"scenarioId":41551,"capacity":0.99}]}]; const keepers = data .filter(({ scenario }) => scenario.flag === 1 && scenario.probability > 0.9) .map(({ scenario, profile }) => { return { ...scenario, profile } }) console.log(keepers)
{ "domain": "codereview.stackexchange", "id": 44179, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript", "url": null }
python, performance Title: lemmatize very long texts in python Question: i really need to optimize this piece of code for my master thesis. it take up to 20 seconds to lemmatize documents with >6000 words. the problem is that i have to lemmatize more than 200.000 documents with an avarage of 10.000 words each. import pandas as pd import nltk import gensim from nltk.stem.wordnet import WordNetLemmatizer from nltk.corpus import wordnet from collections import defaultdict lemmatizer = WordNetLemmatizer() def get_wordnet_pos(treebank_tag): options = defaultdict(lambda: "", {'J': wordnet.ADJ, 'V': wordnet.VERB, 'N': wordnet.NOUN, "R": wordnet.ADV}) return options[treebank_tag[0]] def preprocess(text): result=[] tokens = gensim.utils.simple_preprocess(text) text_pos = list(zip(tokens,[get_wordnet_pos(nltk.pos_tag(tokens)[i][1]) for i in range(len(nltk.pos_tag(tokens)))])) text_pos_cleaned = [text_pos[i] for i,n in enumerate(text_pos) if text_pos[i][1] != ''] lemmatized = [lemmatizer.lemmatize(text_pos_cleaned[i][0], text_pos_cleaned[i][1]) for i in range(0,len(text_pos_cleaned))] [result.append(token) for token in lemmatized if token not in gensim.parsing.preprocessing.STOPWORDS and len(token) > 3] return result dummy_text= "strangeWordWithNoMeaning and i am a good guys with very important values he is a good student, i am reading books and making cake rectangles to be better than any other students, he has very interesting abilities, oqf and i am so proud" preprocess(dummy_text) thank you in advance all. Answer: I've been playing with your code a bit, and I have two key recommendations for you. Bring the code back from quadratic time to linear time The most important gain requires fixing this line: text_pos = list(zip(tokens,[get_wordnet_pos(nltk.pos_tag(tokens)[i][1]) for i in range(len(nltk.pos_tag(tokens)))]))
{ "domain": "codereview.stackexchange", "id": 44180, "lm_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", "url": null }
python, performance Notice how you're calling nltk.pos_tag(tokens) on the whole set of tokens again for each token you're processing. This way, you've made the computational cost quadratic in the number of tokens in a document instead of just linear. You can bring computational time back to linear by calculating it just once for the document: pos_tags = nltk.pos_tag(tokens) text_pos = list(zip(tokens, [get_wordnet_pos(tag[1]) for tag in pos_tags])) The nltk initializations are expensive I also noticed that a lot of time is just spent in the initialization of the data structures. The imports alone take 3-4 seconds on my machine, and the line options = defaultdict(lambda: "", {'J': wordnet.ADJ, 'V': wordnet.VERB, 'N': wordnet.NOUN, "R": wordnet.ADV}) takes 2 seconds by itself! After that, the rest of the script is quite fast (with my fix above), taking just a fraction of a second on my machine. While the rest of your code could certainly be optimized further, you will get a worthwhile additional gain by looping over all your files inside your Python program rather than by calling your program in the shell loop for each document. Minor thing: iterate over items, not indices In Python, we don't usually iterate over indices, but rather directly over the elements of any iterable structure. For example: text_pos_cleaned = [text_pos[i] for i,n in enumerate(text_pos) if text_pos[i][1] != ''] can be written more efficiently as: text_pos_cleaned = [item for item in text_pos if item[1]] The code is shorter and easier to read (imho) but also faster, because iteration already yields one item at a time for you, you don't have to find the item at each position while you loop.
{ "domain": "codereview.stackexchange", "id": 44180, "lm_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", "url": null }
c++, performance, object-oriented, c++17, collections Title: Yet another sparse set implementation Question: I got inspired by this blog post and implemented a fixed-size sparse set, removing the need for vectors, because the sparse set's size equals at least sizeof(value_type * Size), it should be allocated on the heap when using a large set. The idea is to be enable for the creation of contiguous sets inside a container that's allocated on the heap to try and increase cache hits. I did not add iterators because I am not sure how it would work on such container... #pragma once //////////////////////////////////////////////////////////////////////////////// // Includes //////////////////////////////////////////////////////////////////////////////// #include <cstring> #include <cstdint> #include <array> #include <memory> #include <type_traits> //////////////////////////////////////////////////////////////////////////////// // Class declarations //////////////////////////////////////////////////////////////////////////////// template<typename Type, uint32_t Size> class sparse_set { public: using value_type = Type; using size_type = decltype(Size); constexpr inline sparse_set() noexcept; inline ~sparse_set() noexcept(std::is_nothrow_invocable_v<decltype(&sparse_set::clear), sparse_set>); /** @return The maximum number of elements that can be inserted in the set*/ constexpr inline size_type max_size() const noexcept; /** @return The number of elements contained in the set */ constexpr inline size_type size() const noexcept; /** @return true if the set contains no element */ constexpr inline bool empty() const noexcept; /** @return true if the number of elements in the set equals max_size() */ constexpr inline bool full() const noexcept; /** @brief empties the set */ constexpr inline void clear() noexcept(std::is_nothrow_invocable_v<decltype(&sparse_set::erase), sparse_set, size_type > );
{ "domain": "codereview.stackexchange", "id": 44181, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, performance, object-oriented, c++17, collections", "url": null }
c++, performance, object-oriented, c++17, collections /** @return the element contained at this index */ constexpr inline value_type& at(size_type a_Index); /** @return the element contained at this index */ constexpr inline const value_type& at(size_type a_Index) const; /** * @brief Inserts a new element at the specified index, * replaces the current element if it already exists * @return the newly created element */ template<typename ...Args> constexpr inline value_type& insert(size_type a_Index, Args&&... a_Args) noexcept(std::is_nothrow_constructible_v<value_type, Args...> && std::is_nothrow_destructible_v<value_type>); /** @brief Removes the element at the specified index */ constexpr inline void erase(size_type a_Index) noexcept(std::is_nothrow_destructible_v<value_type>); /** @return true if a value is attached to this index */ constexpr inline bool contains(size_type a_Index) const; private: #pragma warning(push) #pragma warning(disable : 26495) //variables are left uninitialized on purpose struct storage { size_type sparseIndex; alignas(value_type) std::byte data[sizeof(value_type)]; operator value_type& () { return *(value_type*)data; } }; #pragma warning(pop) size_type _size{ 0 }; std::array<size_type, Size> _sparse; std::array<storage, Size> _dense; }; template<typename Type, uint32_t Size> inline constexpr sparse_set<Type, Size>::sparse_set() noexcept { _sparse.fill(max_size()); } template<typename Type, uint32_t Size> inline sparse_set<Type, Size>::~sparse_set() noexcept(std::is_nothrow_invocable_v<decltype(&sparse_set::clear), sparse_set>) { clear(); } template<typename Type, uint32_t Size> inline constexpr auto sparse_set<Type, Size>::max_size() const noexcept -> size_type { return Size; } template<typename Type, uint32_t Size> inline constexpr auto sparse_set<Type, Size>::size() const noexcept -> size_type { return _size; }
{ "domain": "codereview.stackexchange", "id": 44181, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, performance, object-oriented, c++17, collections", "url": null }
c++, performance, object-oriented, c++17, collections template<typename Type, uint32_t Size> inline constexpr bool sparse_set<Type, Size>::empty() const noexcept { return _size == 0; } template<typename Type, uint32_t Size> inline constexpr bool sparse_set<Type, Size>::full() const noexcept { return _size == max_size(); } template<typename Type, uint32_t Size> inline constexpr void sparse_set<Type, Size>::clear() noexcept(std::is_nothrow_invocable_v<decltype(&sparse_set::erase), sparse_set, size_type >) { for (size_type index = 0; !empty(); ++index) { erase(index); } } template<typename Type, uint32_t Size> inline constexpr auto sparse_set<Type, Size>::at(size_type a_Index) -> value_type& { return _dense.at(_sparse.at(a_Index)); } template<typename Type, uint32_t Size> inline constexpr auto sparse_set<Type, Size>::at(size_type a_Index) const -> const value_type& { return _dense.at(_sparse.at(a_Index)); } template<typename Type, uint32_t Size> template<typename ...Args> inline constexpr auto sparse_set<Type, Size>::insert(size_type a_Index, Args && ...a_Args) noexcept(std::is_nothrow_constructible_v<value_type, Args...> && std::is_nothrow_destructible_v<value_type>) -> value_type& { if (contains(a_Index)) //just replace the element { auto& dense = _dense.at(_sparse.at(a_Index)); std::destroy_at((value_type*)dense.data); new(&dense.data) value_type(std::forward<Args>(a_Args)...); return (value_type&)dense; } //Push new element back auto& dense = _dense.at(_size); new(&dense.data) value_type(std::forward<Args>(a_Args)...); dense.sparseIndex = a_Index; _size++; _sparse.at(a_Index) = _size - 1; return (value_type&)dense; }
{ "domain": "codereview.stackexchange", "id": 44181, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, performance, object-oriented, c++17, collections", "url": null }
c++, performance, object-oriented, c++17, collections template<typename Type, uint32_t Size> inline constexpr void sparse_set<Type, Size>::erase(size_type a_Index) noexcept(std::is_nothrow_destructible_v<value_type>) { if (empty() || !contains(a_Index)) return; auto& currDense = _dense.at(_sparse.at(a_Index)); auto& lastDense = _dense.at(_size - 1); size_type lastIndex = lastDense.sparseIndex; std::destroy_at((value_type*)currDense.data); //call current data's destructor std::memmove(currDense.data, lastDense.data, sizeof(value_type)); //crush current data with last data std::swap(lastDense.sparseIndex, currDense.sparseIndex); std::swap(_sparse.at(lastIndex), _sparse.at(a_Index)); _sparse.at(a_Index) = max_size(); _size--; } template<typename Type, uint32_t Size> inline constexpr bool sparse_set<Type, Size>::contains(size_type a_Index) const { return _sparse.at(a_Index) != max_size(); } Here is the gist
{ "domain": "codereview.stackexchange", "id": 44181, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, performance, object-oriented, c++17, collections", "url": null }
c++, performance, object-oriented, c++17, collections Here is the gist Answer: At a high level this looks quite well thought out. I like that you took care to make inline, constexpr and nothrow. I like the fact that you took care of defining conditional noexcept for the destructor, erase and clear. Although your approach to using the function you are using as the determinant for the noexcept is generally a good idea. It is debatable if it might be cleared to understand to make all three functions noexcept dependent on the destructor of Type. To me using inline and constexpr together is a smell. Either some function is clearly constexpr, then inline is meaningless or it is not and then it is questionable if inline may help. In this vein, especially erase and insert pop out as functions that probably should not be inlined. For a first implementation, unless I need constepr I would leave it be and see if it is needed. As we are on decorators, you could add the [[nodiscard]] on the functions where discarding the result makes no sense, like max_size, size and at. Since you provided an at function; for symmetry purposes I would add an operator []. It could either call at or just use _dense[_sparse[a_Index]]. In this regard, you are using at a lot. As a general rule of thumb, if you know for certain that you have a valid index into an array or vector, you probably should use the subscript operator. Considering this line in insert: new(&dense.data) value_type(std::forward<Args>(a_Args)...); Althoug I don't 100% understand when it really is needed and when not, but I think this line needs to pass though std::launder. See What is the purpose of std::launder? for a discussion on the issue. Considering this line in erase: if (empty() || !contains(a_Index)) return;
{ "domain": "codereview.stackexchange", "id": 44181, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, performance, object-oriented, c++17, collections", "url": null }
c++, performance, object-oriented, c++17, collections I would replace this check with an assert. Following the STL understanding, of don't call erase with invalid iterators semantic. This code probably just masks bugs in the calling code. Considering erase in general: Why are you enforcing compacting of the set? Now, I get this makes inserting quicker, but it also invalidates any references outside of the set. This feels like unnecessary burden on the client code. It certainly needs to be documented and communicated that erase will invalidate any of your references.
{ "domain": "codereview.stackexchange", "id": 44181, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, performance, object-oriented, c++17, collections", "url": null }
c, console Title: C safe getline() Question: For a recent project of mine I had to do read input from the console in pure C with no external libraries (in other words, code I've written by myself). I don't like the standard formatted input such as scanf or std::cin in C++, I feel like having to do a dummy read to get rid of the leftover newline is not great. In C++ I can do std::string in; std::getline(std::cin, in); to read an entire line, but C doesn't have that (at least not on my system). Reading input from the console is often needed, so after several times of writing it I decided I wanted something I can write once and for all. This code is simple enough that I don't think I've left too many holes, but I'd still love to hear feedback about it so please do let me know what I can do to improve it. #ifndef UUTIL_H #define UUTIL_H #include <stdbool.h> #include <stddef.h> #include <stdio.h> bool getLine(FILE *src, char **dest, size_t *size); #endif #include <stdbool.h> #include <stddef.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include "uutil.h" bool getLine(FILE *src, char **dest, size_t *size) { if (src == NULL) { if (size != NULL) *size = 0; return false; } if (dest == NULL) { if (size != NULL) *size = 0; return false; } char *data; size_t cap = 32; size_t readCount = 0; data = malloc(cap * sizeof(char)); if (data == NULL) { *size = 0; return false; } while (true) { int readVal = fgetc(src); if (readVal == EOF || readVal == '\n') { if (readCount == cap) { // The buffer is full, but we still need to shove in the final NUL byte size_t newCap = cap + 1; char *newData = realloc(data, newCap * sizeof(char)); if (newData == NULL) { // Failed to resize, shove it in anyway data[readCount - 1] = '\0';
{ "domain": "codereview.stackexchange", "id": 44182, "lm_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, console", "url": null }
c, console data[readCount - 1] = '\0'; if (size != NULL) *size = readCount; return false; } cap = newCap; data = newData; } data[readCount] = '\0'; // Do not count the final NUL byte if (size != NULL) *size = readCount; *dest = data; return true; } if (readCount == cap) { // The buffer is full, but we still have more data to shovw in size_t newCap = cap * 2; char *newData = realloc(data, newCap * sizeof(char)); if (newData == NULL) { // Failed to resize, clean up stdin and return data[readCount - 1] = '\0'; if (src == stdin) while (fgetc(src) != EOF); if (size != NULL) *size = readCount; return false; } cap = newCap; data = newData; } data[readCount++] = readVal; } } Answer: let me know what I can do to improve it. Design flaw Somehow, the caller needs to distinguish between a call that immediately ended due to '\n' vs. EOF. Just like fgets(). Perhaps a 3-way return: EOF, 0 (failure) or 1 (success)? Design flaw 2 (subtle) EOF occurs due to end-of-file and input error. Some input, then end-of-file should return true No input and end-of-file should return EOF. (See above). Any amount of input, then input error should return EOF. (See above). Review feof() and ferror(). Something like: if (readVal == EOF) { ... // Note: `!feof()` subtlely different than `ferror()` here. if (readCount == 0 || !feof(src)) return EOF; return 1; }
{ "domain": "codereview.stackexchange", "id": 44182, "lm_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, console", "url": null }
c, console Lack of documentation bool getLine(FILE *src, char **dest, size_t *size) deserves a few comments, especially how to call and what the return value means. Allocate to the reference object size, not type Easier to code right, review and maintain. //data = malloc(cap * sizeof(char)); data = malloc(sizeof data[0] * cap); Declare and initialize Avoid leaving newly declare objects unassigned. //char *data; //.... some time later //data = malloc(cap * sizeof(char)); char *data = malloc(cap * sizeof(char)); Assign a dummy As apparently size == NULL is OK, when NULL, reassign to a dummy so later code does not need multiple if (size != NULL) ... tests size_t dummy; if (size == NULL) { size = &dummy; } Remove special code for reallocate on end-of-line Simply use if (readCount + 1 == cap) { in the general loop. Final allocation When leaving the function, perform a final "right-size" re-allocation. Allocation growth newCap = cap * 2 is reasonable, yet 1) does not detect overflow for a really long input. 2) Limited to SIZE_MAX/2. Instead, start at 31 and then newCap = cap * 2 + 1, code can then handle up to SIZE_MAX.
{ "domain": "codereview.stackexchange", "id": 44182, "lm_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, console", "url": null }
c#, multithreading, .net, httpclient Title: Use a static field for cache an authentication token in .NET API Question: I have a .NET 6 web API that does some requests to another third party API, this API has a token that expires after a few hours, so I want to cache this token and reuse in the requests. Here how I implemented it: public class TokenInformation { public string Token { get; set; } public DateTime ExpiresIn { get; set; } } public static class TokenManagement { private static object _lock = new object(); private static TokenInformation _token; // HttpClient already have credentials and other default headers public static async Task<string> GetToken(HttpClient httpClient) { if (_token is null || _token.ExpiresIn <= DateTime.Now) { var response = await httpClient.GetAsync("/token"); if (!response.IsSuccessStatusCode) throw new Exception($"Authentication Failure: {response.StatusCode}"); var token = await response.Content.ReadAsAsync<TokenInformation>(); lock (_lock) { _token = token; } } return _token.Token; } } public class EmployeeServiceClient { private HttpClient _httpClient; public EmployeeServiceClient(HttpClient httpClient) { _httpClient = httpClient; } public async Task<string> GetEmployeeDetails(int employeeId) { using var message = new HttpRequestMessage(HttpMethod.Get, $"/employee/{employeeId}/details"); message.Headers.Authorization = new AuthenticationHeaderValue("Bearer", await TokenManagement.GetToken(_httpClient)); var result = await _httpClient.SendAsync(message); return await result.Content.ReadAsStringAsync(); } }
{ "domain": "codereview.stackexchange", "id": 44183, "lm_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#, multithreading, .net, httpclient", "url": null }
c#, multithreading, .net, httpclient My biggest doubt is if I really need the lock since this is an API with multiple threads and requests. I think so, what you guys think, any tips? Also, should yje lock be wider? If so, since contains async calls should I use .Result ? Obs. Each class is in a separate file, some class names were changed to hide vendor name, everything else is real code. Answer: Generally speaking there are two ways to solve the auto-refresh token problem: Proactive / Preventive / Pessimistic: Try to prevent to use an expired token by asking a new one before calling the secured endpoint Reactive / Mitigative / Optimistic: Calling the secured endpoint with the token and whenever the server indicates token expiry then ask for a new one Proactive approach Your solution falls under this category. The token server issues a token and indicates the expiry of it. And your application proactively checks this expiry before making any http calls. The problem with this preventive approach is that the token server time and your application server time might not be synced. Your application server's system clock might be earlier or later in time compared to the token server's system clock. Let's see what could happen around the token expiry. Let's suppose that the token expires at 10:05. Then depending on the time skew the result is different: The application server thinks it is 10:04, but the secured endpoint's server's time is 10:06 Your code will not ask for a new token but the secured endpoint will reject your call since the token is expired The application server thinks it is 10:06, but the secured endpoint's server's time is 10:04 Your code will ask a new token even though it was not expired yet
{ "domain": "codereview.stackexchange", "id": 44183, "lm_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#, multithreading, .net, httpclient", "url": null }
c#, multithreading, .net, httpclient Your code will ask a new token even though it was not expired yet The former case is problematic. This problem can be solved by adding some error-margin to the expiry check (like token.Expiry < Now - 5m). The actual value of the margin depends on the validity length of a token. (P.S. Please try to prefer UTC kind over local in case of DateTime) Reactive approach In this case the application always assumes that the token is valid. It does not do any expiry check. Rather the secured endpoint call is wrapped into a retry handler. If the endpoint call fails because the token was expired (for example the response's status code is 401) then you ask for a new token and issue a new retry attempt with the new token. If the token is shared and the concurrency is high then it might happen that multiple requests will fail with 401 at the same time and try to get a new token. Either you write a code which ensures that only a single thread is asking for a new token. Or your code uses the last one wins strategy in your cache. In the later case there is an intermittent period when multiple tokens are used concurrently by your application but eventually it will consolidate into a single one. So, it is wasting resources but still a good approach. Here I have proposed two solutions for this mitigative technique.
{ "domain": "codereview.stackexchange", "id": 44183, "lm_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#, multithreading, .net, httpclient", "url": null }
c++, concurrency, c++20 Title: Thread Safe Queue Question: I have a thread safe queue in my library c9y. It is generally used as a task queue in the task_pool class, but in can be used for any producer / consumer problem. queue.h #ifndef _C9Y_QUEUE_H_ #define _C9Y_QUEUE_H_ #include <mutex> #include <condition_variable> #include <deque> #include <chrono> namespace c9y { using namespace std::chrono_literals; //! Thread Safe Queue //! //! This is a thread safe implementation of a queue. //! //! @note There is no really safe way to copy a queue, so this //! queue is not copyable or asingable. template <typename T, class Container = std::deque<T>> class queue { public: typedef Container container_type; typedef typename Container::value_type value_type; typedef typename Container::size_type size_type; typedef typename Container::reference reference; typedef typename Container::const_reference const_reference; //! Create an empty queue. queue() {} //! Initialize the queue with values. //! //! @param c the container to initialize the queue with explicit queue(const Container& c) : container(c) {} //! Initialize the queue with a reange of values. //! //! @param begin an iterator to the beginning of the range //! @param end an iterator to the one beond the end of the range template <class Iterator> queue(const Iterator& begin, const Iterator& end) : container(begin, end) {} //! Destructor ~queue() { wake(); }
{ "domain": "codereview.stackexchange", "id": 44184, "lm_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++, concurrency, c++20", "url": null }
c++, concurrency, c++20 //! Destructor ~queue() { wake(); } //! Push a value onto the queue. //! //! This method will push the value onto the queue and //! wake up a thread that is wating in pop_wait. //! //! @param value the value to push onto the queue void push(const value_type& value) { auto lock = std::unique_lock<std::mutex>{mutex}; container.push_back(value); cond.notify_one(); } //! Pop a value of the queue. //! //! This method will try to pop a value off the queue. If no value is //! in the queue, it will return false. //! //! @param value the value of the pop //! @return true if a value was poped of the queue bool pop(value_type& value) { auto lock = std::unique_lock<std::mutex>{mutex}; if (!container.empty()) { value = container.front(); container.pop_front(); return true; } else { return false; } } //! Pop a value of the queue, wait if nessesary. //! //! This method will try to pop a value off the queue. If no value is //! in the queue, it will wait until either a value is pushed onto the //! queue or wake is called. //! //! @param value the value of the pop //! @return true if a value was poped of the queue //! //! @warning It is quite simple to build a race condition with pop_wait //! and wake. If you intend to reliably wake all waiting threads, use //! pop_wait_for with a reasonable timeout. bool pop_wait(value_type& value) { auto lock = std::unique_lock<std::mutex>{mutex}; if (container.empty()) { cond.wait(lock); }
{ "domain": "codereview.stackexchange", "id": 44184, "lm_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++, concurrency, c++20", "url": null }
c++, concurrency, c++20 if (container.empty()) { cond.wait(lock); } if (!container.empty()) { value = container.front(); container.pop_front(); return true; } else { return false; } } //! Pop a value of the queue, wait for a defined duration if nessesary. //! //! This method will try to pop a value off the queue. If no value is //! in the queue, it will wait until either a value is pushed onto the //! queue or wake is called. //! //! @param value the value of the pop //! @param duration the duration to wait for //! @return true if a value was poped of the queue bool pop_wait_for(value_type& value, std::chrono::milliseconds duration) { auto lock = std::unique_lock<std::mutex>{mutex}; if (container.empty()) { cond.wait_for(lock, duration); } if (!container.empty()) { value = container.front(); container.pop_front(); return true; } else { return false; } } //! Wake up any threads that are wating in pop_wait. void wake() { cond.notify_all(); } private: std::mutex mutex; std::condition_variable cond; Container container; queue(const queue& other) = delete; queue& operator = (const queue& other) = delete; }; } #endif Of course there are matching unit tests: queue_test.cpp #include <c9y/queue.h> #include <atomic> #include <thread> #include <gtest/gtest.h> #include <c9y/thread_pool.h> using namespace std::chrono_literals; TEST(queue, create) { auto q = c9y::queue<int>{}; }
{ "domain": "codereview.stackexchange", "id": 44184, "lm_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++, concurrency, c++20", "url": null }
c++, concurrency, c++20 using namespace std::chrono_literals; TEST(queue, create) { auto q = c9y::queue<int>{}; } TEST(queue, consumer_producer) { auto q = c9y::queue<int>{}; auto count = std::atomic<unsigned int>{0}; auto prod = c9y::thread_pool{[&] () { for (int i = 1; i < 101; i++) { q.push(i); } }, 3}; auto cons = c9y::thread_pool{[&] () { int value = 0; while (q.pop(value)) { count++; std::this_thread::sleep_for(1ms); } }, 3}; prod.join(); cons.join(); EXPECT_EQ(300, static_cast<unsigned int>(count)); } TEST(queue, consumer_producer_wait) { auto q = c9y::queue<int>{}; auto count = std::atomic<unsigned int>{0}; auto prod = c9y::thread_pool{[&] () { for (int i = 1; i < 101; i++) { q.push(i); std::this_thread::sleep_for(5ms); } }, 3}; auto cons = c9y::thread_pool{[&] () { int value = 0; while (q.pop_wait_for(value, 100ms)) { count++; std::this_thread::sleep_for(3ms); } }, 3}; prod.join(); std::this_thread::sleep_for(100ms); q.wake(); cons.join(); EXPECT_EQ(300, static_cast<unsigned int>(count)); } Just by posting it here, I already found some issues I need to look into. This code is C++11 code but the library was recently updated to C++20; so these standards should be applied. I am interested what you think. Answer: Consider using perfect forwarding to initialize the container You have three constructors, a default one and two that initialize the container based on existing data. But the constructor of std::deque has many more forms. Picking only a few of them is inconsistent, and having to copy all of them is a lot of work. Instead, consider using perfect forwarding: template<typename... Args> explicit queue(Args&&... args) : container(std::forward<Args>(args)...) {}
{ "domain": "codereview.stackexchange", "id": 44184, "lm_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++, concurrency, c++20", "url": null }
c++, concurrency, c++20 The destructor should not call wake() I see you have a destructor that calls wake(), but that is very unsafe. No thread should be in pop_wait() when the destructor is called. Consider what happens after the destructor returns and those other threads have woken up: they assume they still have a live queue object! So the only time it is safe to call the destructor is if no threads are using the queue object any more, and thus there is no need to call wake() in the destructor. For a task pool it is important that you can signal the worker threads that they should stop doing any work. That has to be done in some other way; for example by setting a flag that signals that work has to stop. The destructor of the thread pool should look like: class thead_pool { queue q; std::vector<std::thread> threads; … ~thread_pool() { q.stop(); // signal queue that no more items will be pushed for (auto& thread: threads) threads.join(); // not necessary if you use std::jthread // after the destructor exits, q will be destroyed } }; So queue should have something like: template<…> class queue { public: … void stop() { auto lock = std::unique_lock<std::mutex>{mutex}; stopped = true; wake(); } private: std::mutex mutex; … bool stopped = false; }; Always wait using a predicate std::condition_variable::wait() can wake up spuriously (i.e., without notify_one() or notify_all() having been called), and in more complex programs it's hard to see when a condition variable can be notified. So it's almost always better to use wait() with a predicate: bool pop_wait(value_type& value) { auto lock = std::unique_lock<std::mutex>{mutex}; cond.wait(lock, [&]{return !container.empty() || stopped;}); if (container.empty()) // can only happen if stopped == true return false; value = container.front(); container.pop_front(); return true; }
{ "domain": "codereview.stackexchange", "id": 44184, "lm_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++, concurrency, c++20", "url": null }
c++, concurrency, c++20 value = container.front(); container.pop_front(); return true; } Consider returning std::optional<T> Instead of passing a reference and returning a bool, consider returning a std::optional<T>. This is much nicer and safer to use. Don't pass a duration in a specific unit Instead of passing the time to wait as std::chrono::milliseconds, make it a generic type, just like the duration argument of std::condition_variable::wait_for() itself. No need to delete the copy constructor/assignment operator Because std::mutex and std::condition_variable are not copyable, your class will automatically be non-copyable, and you don't have to delete the copy constructor and copy assignment operator. Allow moving data into and out of the queue You are copying data when you push to and pop from the queue. That can be inefficient for large types, and it also prevents you from storing non-copyable types in the queue. Consider using r-value references and/or perfect forwarding to push things into the queue, i.e. by having a push() with the same overloads as std::deque::push_back(), and an emplace() with the same parameters as std::deque::emplace_back(). Use std::move() when popping an item from the queue into a temporary variable (you don't need to move it when returning the temporary). Notify without holding the lock It's slightly more efficient to call notify_one() and notify_all() without having the mutex locked, otherwise there is a possibility the other thread(s) will wake, see that the mutex is still locked, then they have to do a system call to wait again until the mutex is unlocked.
{ "domain": "codereview.stackexchange", "id": 44184, "lm_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++, concurrency, c++20", "url": null }
c++, sorting, vectors Title: Sorting multiple vectors based on a reference vector Question: I am trying to sort vectors based on a reference vector. First I am getting the indexes for the reference vector and then using that I am doing inplace sorting for the rest of the vectors. #include <vector> #include <cassert> #include <iostream> #include <algorithm> using iter = std::vector<int>::iterator; using order_type = std::vector<std::pair<size_t, iter>>; void create_permutation(order_type &order) { struct ordering { bool operator ()(std::pair<size_t, iter> const& a, std::pair<size_t, iter> const& b) { return *(a.second) < *(b.second); } }; std::sort(order.begin(), order.end(), ordering()); } void reorder(std::vector<int> &vect, order_type index) { for (int i=0; i< vect.size(); i++) { while (index[i].first != i) { int old_target_idx = index[index[i].first].first; int old_target_v = vect[index[i].first]; vect[index[i].first] = vect[i]; index[index[i].first].first = index[i].first; index[i].first = old_target_idx; vect[i] = old_target_v; } } } template<typename... argtype> void sort_from_ref(argtype... args); template<typename T, typename A, typename... argtype> void sort_from_ref(order_type order, std::vector<T,A> &vect, argtype &&...args) { reorder(vect, order); sort_from_ref(order, std::forward<argtype>(args)...); } template<> void sort_from_ref(order_type order, std::vector<int> &vect) { reorder(vect, order); }
{ "domain": "codereview.stackexchange", "id": 44185, "lm_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++, sorting, vectors", "url": null }
c++, sorting, vectors int main() { size_t n = 0; std::vector<int> vect_1{ 1, 0, 2, 3 }; std::vector<int> vect_2{ 100, 200, 300, 400 }; std::vector<int> vect_3{ 100, 200, 300, 400 }; std::vector<int> vect_4{ 400, 200, 3000, 4000 }; std::vector<int> vect_5{ 500, 200, 360, 400 }; order_type order(vect_1.size()); for (iter it = vect_1.begin(); it != vect_1.end(); ++it) { order[n] = std::make_pair(n, it); n++; } create_permutation(order); sort_from_ref(order, vect_2, vect_3, vect_4, vect_5); { std::vector<int> test{200, 100, 300, 400}; assert(vect_2 == test); } { std::vector<int> test{200, 100, 300, 400}; assert(vect_3 == test); } { std::vector<int> test{200, 400, 3000, 4000}; assert(vect_4 == test); } { std::vector<int> test{200, 500, 360, 400}; assert(vect_5 == test); } return 0; } Answer: For another take on the same problem (sorting parallel arrays), see Quicksort template (for sorting corresponding arrays). Your code is strangely organized. I would expect it to have a single entry point, something like this: template<class Vector, class... Vectors> void parallel_sort(Vector& keyvector, Vectors&... vectors) { std::vector<size_t> order(keyvector.size()); std::iota(order.begin(), order.end(), 0); std::sort(order.begin(), order.end(), [&](size_t a, size_t b) { return keyvector[a] < keyvector[b]; }); (reorder(keyvector, order) , ... , reorder(vectors, order)); }
{ "domain": "codereview.stackexchange", "id": 44185, "lm_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++, sorting, vectors", "url": null }
c++, sorting, vectors (Hey, look at that! It's a complete implementation, except for the reorder function you already wrote!) But instead you require the calling code to set up their own order vector manually, then call create_permutation, then sort_from_ref, in that order. That's a lot of steps. At the very least, you could provide a function create_order_vector to simplify that first step. The one advantage I can see to requiring the caller to provide the order vector is that it allows your library code to do no heap allocations. Vice versa, a problem with my code above is that it requires O(n) memory to sort n elements. If I have a million-element vector, I need to heap-allocate another eight million bytes to sort it! That could be annoying or prohibitive for some callers — they might not expect a sorting function to throw std::bad_alloc. At least by making the caller allocate the eight million bytes themselves, you're putting the issue front and center where they can't miss it. I think it's strange that you define the alias order_type to be std::vector<std::pair<size_t, iter>>. I would rather see using order_type = std::pair<size_t, iter>; [...] std::vector<order_type> order; Again, I guess it comes down to my wanting to see std::vector-ness explicitly in the code. I have the same complaint about typedefs such as using Foo = foo*; that hide a type's pointer-ness. template<typename T, typename A, typename... argtype> void sort_from_ref(order_type order, std::vector<T,A> &vect, argtype &&...args) { reorder(vect, order); sort_from_ref(order, std::forward<argtype>(args)...); }
{ "domain": "codereview.stackexchange", "id": 44185, "lm_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++, sorting, vectors", "url": null }
c++, sorting, vectors In C++17, you can use a comma-operator fold-expression to do this, as I did above. But even in C++11, you can use a pack expansion to do this without all the "recursive template" stuff. (See "Iteration is better than recursion.") You'd just do something like this: template<class... Args> void sort_from_ref(order_type order, Args&... args) { int dummy[] = { [&]() { reorder(args, order); return 0; } ... }; } Notice that I also changed argtype to Args. It's a pack of multiple argtypes, not just one; and the C++ convention for template parameters is to CamelCase them. I also eliminated your perfect forwarding. We know that all our args are going to be non-const lvalue references; so we should just say so. We also know that all our args are going to be std::vector<T> for some T, because that's the only kind of argument that will be accepted by our reorder template. Therefore, it is incorrect (but largely harmless) that you wrote template<typename T, typename A, [...]> void sort_from_ref([...] std::vector<T,A> &vect, [...] because there is only one possible A that can go there and have the code still compile. You should just have said template<typename T, typename... argtype> void sort_from_ref(order_type order, std::vector<T>& vect, argtype&&... args) (except that, as we've seen, you don't need this "recursive" template at all). No comment on your reorder function; that part is all math. (Does it work? Did you test it exhaustively?) Okay, two comments... index[i].first = old_target_idx; vect[i] = old_target_v; Your whitespace here (and other places) is wonky. It looks like maybe you were trying to align the = signs, but failed? I strongly recommend not trying to align anything, ever. It's not robust against refactoring. (For example, if you change the name of a variable, now you have to realign everything it touched.) for (int i=0; i< vect.size(); i++)
{ "domain": "codereview.stackexchange", "id": 44185, "lm_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++, sorting, vectors", "url": null }
c++, sorting, vectors You should be getting a stupid warning from your compiler about "comparing signed and unsigned" here. If you're not, then turn up your warning levels — you should be using -W -Wall (and maybe -Wextra) on non-MSVC compilers, and I'd say -W4 on MSVC. The traditional workaround would be to make i a size_t instead of an int.
{ "domain": "codereview.stackexchange", "id": 44185, "lm_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++, sorting, vectors", "url": null }
javascript, datetime Title: How to handle optional date parameters? Question: When creating a function to be reusable throughout the project I came across something strange. After looking at this function it looks very much like it could be refactored. The function should only return the short month and day, in that order. If it receives a parameter, it will be a Firestore Timestamp with the following format: { "seconds":1667420699, "nanoseconds":394000000 } If it does not receive a parameter, it must return today's month and day. So I did this: function shortMonthDay(timestamp = undefined) { let date if (timestamp) { date = new Date(timestamp.seconds * 1000 + timestamp.nanoseconds / 1000000) } else { date = new Date() } return date.toLocaleDateString('en-US', { month: 'short', day: 'numeric' }) // Nov 2 } The function works as it should, it doesn't return any errors. But I wonder if it could be improved and how. Answer: Minor points Default parameters eg shortMonthDay(timestamp = undefined) are only assigned to arguments that are undefined or contain undefined. To assign the default undefined will do nothing and is just code noise. The timestamp object is not vetted. If it contains seconds, it may not have nanoseconds (and visa versa), or either or both may not hold a number. You need to ensure that you do not pass NaN to the Date constructor when parsing the timestamp Function roles shortMonthDay would be better as two functions. timestampToDate to convert a timestamp if given to a date. formatDate to format the date object, which you can curry with the locale format. Thus you don't need to touch the timestampToDate to change the output format Rewrite We can rewrite the function as follows
{ "domain": "codereview.stackexchange", "id": 44186, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript, datetime", "url": null }
javascript, datetime Rewrite We can rewrite the function as follows const formatDate = (loc = "en-US", format = {month: "short", day: "numeric"}) => date => date.toLocaleDateString(loc, format); const timestampToDate = (timestamp = {}) => new Date( (isNaN(timestamp.seconds) ? Date.now() : Number(timestamp.seconds) * 1000) + (isNaN(timestamp.nanoseconds) ? 0 : timestamp.nanoseconds * 1e-6) ); const toMonthDay = formatDate(); // basic tests const timestamps = [undefined, // current local date {seconds: 1670263910, nanoseconds: 394000000}, // ~ Dec 6 GMT+0800 for rest {seconds: 1670263910, nanoseconds: "blah"}, {seconds: 1670263910}, {seconds: "foo", nanoseconds: 1667420699000 + 394} ].forEach(timestamp => console.log(toMonthDay(timestampToDate(timestamp)))); Note As a habit I avoid divides as generally divides are slower than multiplies. Its just a habit, in this case the difference between * 1e-6 and / 1e6 is inconsequential. Note In timestampToDate the names are a little noisy and because the variable timestamp is being used so often one could also write it as const timestampToDate = (stamp = {}) => new Date( (isNaN(stamp.seconds) ? Date.now() : Number(stamp.seconds) * 1000) + (isNaN(stamp.nanoseconds) ? 0 : stamp.nanoseconds * 1e-6) );
{ "domain": "codereview.stackexchange", "id": 44186, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript, datetime", "url": null }
python, beginner, algorithm, comparative-review Title: Getting three numbers input interactively and process them Question: I'm new to Python and programming in general. Let's imagine I have a simple task: Given 3 numbers from user input, I need to count negative ones and print the result. Considering what I know about Python at this moment, I can solve it like this: class ListTooShort(Exception): pass def input_check(): temp_list = [] while True: try: temp_list = [float(x) for x in input('Input 3 numbers, separated by space: ').split()] if (len(temp_list) < 3): raise ListTooShort if (len(temp_list) > 3): temp_list = temp_list[:3] except ValueError: print('One of given values is not a number, try again.') except ListTooShort: print('Not enough values, try again.') else: return temp_list def count_negative_numbers(value_list): counter = 0 for i in value_list: if (i < 0): counter += 1 return counter print('If theres more than 3 numbers,\nlist will be trimmed to 3 first values.') numbers = input_check() result = count_negative_numbers(numbers) print(f'Theres {result} negative numbers in this 3 value list') or like this: counter = 0 numbers = [float(x) for x in input('Input 3 numbers, seperated by space: ').split()] if (len(numbers) >= 3): numbers = numbers[:3] for i in numbers: if (i < 0): counter += 1 print(f'Theres {counter} negative numbers in this value(s) list') Both do the trick, but the main questions I have is: Would it be better to not complicate the code too much when there's a simple task at hand? Is it even worth to make functions for simple things like that or should I just go straight to solving an issue? Should I even pay attention to things like that or its better to just "freeroam" without caring that much?
{ "domain": "codereview.stackexchange", "id": 44187, "lm_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, beginner, algorithm, comparative-review", "url": null }
python, beginner, algorithm, comparative-review Answer: Getting exactly 3 values I think that since you are requesting exactly 3 values, I'd abandon inputting an arbitrary number of values separated by a space. Instead, in your while loop, just enforce the constraint that your list has no more than 3 values: temp_list = [] while len(temp_list) < 3: try: temp_list.append( float(input(f"Input number {len(temp_list) + 1}: ")) ) except ValueError: print("Error processing your number, try again!") Defining custom exceptions While we're at it, rarely do you need to create your own exceptions. A ValueError, if needed, would suffice: def some_function(mylist: List[int]): if len(mylist) != 3: raise ValueError("Expected 'mylist' to have exactly 3 values") print(len(mylist)) bool and int can be used the same way When you are checking for a condition and counting True values, this behaves just like 1: int(True) 1 int(False) 0 So you can add the boolean expression if you felt so inclined: def count_negative_numbers(value_list): counter = 0 for i in value_list: counter += (i < 0) return counter Your for loop here is perfectly readable and doesn't really need refactoring, but a more advanced technique would be to feed a generator expression to sum: def count_negative_numbers(value_list): return sum(i < 0 for i in value_list) Other Questions Would it be better to not complicate the code too much when theres a simple task at hand? To borrow a quote: Simple is better than complex, complex is better than complicated.
{ "domain": "codereview.stackexchange", "id": 44187, "lm_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, beginner, algorithm, comparative-review", "url": null }
python, beginner, algorithm, comparative-review Simple is better than complex, complex is better than complicated. Make it as simple as reasonably possible to solve the problem at hand. As a note, less code (one-liners) does not always mean simpler. Is it even worth to make functions for simple things like that or should i just go straight to solving an issue? It's good practice (both in terms of standards and practice in general) to keep up good code organization. Personally, I have found myself sometimes going back to small scripts I wrote where I know I solved a certain problem before. Writing good functions with helpful names and docstrings makes finding them much faster. I'd keep writing functions where you find it helps readability and organization of your scripts. It will pay dividends when it comes time to write much larger applications. Should i even pay attention to things like that or its better to just "freeroam" without caring that much? Freeroaming is great for just getting ideas out there, but there's a balance to be struck. Writing nothing but "freeroam" code will enforce habits that will need to be broken when writing code for larger problems/applications. It's an iterative process: Solve Refactor Repeat
{ "domain": "codereview.stackexchange", "id": 44187, "lm_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, beginner, algorithm, comparative-review", "url": null }
r Title: Calculate number of max and min outliers from data.frame Question: I am working on a problem where I need to get specific information for min and max outliers. This is in relation to the ggplot library. I will be getting all my information from ggplot_build object. The data that is used will look something like this: cleandata <- data.frame(middle=c(1, 4, 7), xmiddle=c(2, 9, 1)) cleandata$outliers <- list(c(-3, 1.5, 6), 5, 8) flipped <- TRUE Or to have actual example data yourself this code would work: boxplot = ggplot(mpg, aes(class, hwy)) + geom_boxplot(varwidth = TRUE) boxplot_b = ggplot_build(boxplot ) flipped <- boxplot_b [["data"]][[1]][["flipped_aes"]] == length(boxplot_b [["data"]][[1]][["flipped_aes"]]) cleandata = boxplot_b [["data"]][[1]] Although any boxplot will work with a little change of code listed. I have this bit of code that will get the min and max outliers in two vectors. maxoutliers = c() minoutliers = c() for (box in seq_along(cleandata$outliers)) { outliers = cleandata$outliers[[box]] if (flipped) { middle = cleandata$xmiddle[box] } else { middle = cleandata$middle[box] } maxoutliers[length(maxoutliers)+1] = outliers[outliers > middle] |> length() minoutliers[length(minoutliers)+1] = outliers[outliers < middle] |> length() } flipped is whether the boxplot is horizontal or not. And cleandata is the data frame you can see above. I just feel like there is a cleaner way to do this but I can’t seem to think of a way. Answer: R is a vectorized language, and code is often nicer when we keep things as vectors instead of looping through their elements. For instance, we could replace your code selecting the "middle" element for each row of your data with: middle <- if (flipped) cleandata$xmiddle else cleandata$middle
{ "domain": "codereview.stackexchange", "id": 44188, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "r", "url": null }
r Now, middle is a vector containing the correct "middle" value for each row of your data. At this point, you want to compute the number of elements in each of your outliers vectors that are above or below the corresponding middle value for that row. You do this by computing outliers[outliers > middle] |> length() and outliers[outliers < middle] |> length() and then concatenating those results one element at a time into vectors you are building. Building a vector this way is actually a big no-no in R -- it needs to reallocate the whole output vector each iteration of your loop and can be painfully slow for large loops (for more discussion of this topic, see Circle 2 of The R Inferno). At the end of the day, you want to loop through each pair of middle/outliers and do your calculations, storing the result into a properly-sized vector. Looping through multiple lists at once (akin to zip in python) and outputting to a properly sized output can be accomplished with mapply in R: minoutliers <- mapply(function(x, y) sum(x < y), cleandata$outliers, middle) maxoutliers <- mapply(function(x, y) sum(x > y), cleandata$outliers, middle) Notice that keeping things vectors as long as possible has given us one final advantage -- our code is much shorter (just 3 lines).
{ "domain": "codereview.stackexchange", "id": 44188, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "r", "url": null }
javascript, jquery, google-chrome, bookmarklet Title: Chrome bookmarklet to expand examples elements on a dictionary webpage Question: I created the following Chrome bookmarklet to open all elements with text Extra Examples boxes on this page. For example - the element labeled with text Extra Examples below can be clicked: When it is clicked then a list of examples will be displayed: The element can then be clicked again to hide the list of examples. The bookmarklet code javascript:$('.box_title').click(); It works with no problem. However, I'd prefer to use vanilla JavaScript. This is what I have for now: javascript:document.querySelectorAll('.box_title').forEach(e => e.click()); Do you see any problem, or can it be improved? Demonstration Below is a runnable snippet that shows a sample of the page without the bookmarklet:
{ "domain": "codereview.stackexchange", "id": 44189, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript, jquery, google-chrome, bookmarklet", "url": null }
javascript, jquery, google-chrome, bookmarklet <link href="https://www.oxfordlearnersdictionaries.com/external/styles/oald10.css" rel="stylesheet" /> <link href="https://www.oxfordlearnersdictionaries.com/external/styles/interface.css" rel="stylesheet" /> <span class="shcut-g" id="get_sngs_2"> <h2 class="shcut" htag="h2" id="get_shcut_2" hclass="shcut">bring</h2><li class="sense" cefr="a1" id="get_sng_4" hclass="sense" htag="li" sensenum="5" ox3000="y"><a class="open oup_icons" title="Add to My Word Lists"><span class="star-btn" aria-hidden="true">​</span></a> <span class="sensetop" hclass="sensetop" htag="span"> <div class="symbols" htag="div" hclass="symbols"><a href="https://www.oxfordlearnersdictionaries.com/wordlists/oxford3000-5000?dataset=english&amp;list=ox3000&amp;level=a1"><span class="ox3ksym_a1">&nbsp;</span></a></div> </span> <span class="grammar" hclass="grammar" htag="span">[transitive]</span> <span class="def" htag="span" hclass="def">to go to a place and bring somebody/something back</span> <span class="xrefs" htag="span" xt="nsyn" hclass="xrefs"><span class="prefix">synonym</span> <a class="Ref" href="https://www.oxfordlearnersdictionaries.com/definition/english/fetch" title="fetch definition"><span class="xr-g" href="fetch_e" bord="n"><span class="xh">fetch</span></span></a></span> <ul class="examples" hclass="examples" htag="ul"> <li class="" htag="li"> <span class="cf" htag="span" hclass="cf">get somebody/something</span> <span class="x">Quick—<span class="cl">go and get</span> a cloth!</span> </li> <li class="" htag="li"><span class="x">Somebody get a doctor!</span></li> <li class="" htag="li"><span class="x">She went to <span class="cl">get help</span>.</span> </li> <li class="" htag="li"><span class="x">I have to go and get my mother from the airport <span class="gloss" htag="span" hclass="gloss">(= collect her)</span>.</span> </li>
{ "domain": "codereview.stackexchange", "id": 44189, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript, jquery, google-chrome, bookmarklet", "url": null }
javascript, jquery, google-chrome, bookmarklet </li> <li class="" htag="li"> <span class="cf" hclass="cf" htag="span">get something for somebody</span> <span class="x">Get a drink for John.</span></li> <li class="" htag="li"> <span class="cf" htag="span" hclass="cf">get somebody/yourself something</span> <span class="x">Get John a drink.</span></li> </ul> <div class="collapse" htag="div" hclass="collapse"><span class="unbox" id="get_unbox_2" unbox="extra_examples"><span class="box_title">Extra Examples</span> <ul class="examples" hclass="examples" htag="ul"> <li class="" htag="li"><span class="unx">She's gone to get a few more chairs.</span></li> <li class="" htag="li"><span class="unx">Could you go upstairs and get my wallet for me, please?</span></li> <li class="" htag="li"><span class="unx">Can I get you anything to eat or drink?</span></li> </ul> </span> </div> </li> </span> <div id="flex-menu"></div> <div id="panel-smartphone"></div> <div id="dictionarySelector"></div> <script src="https://www.oxfordlearnersdictionaries.com/common.js"></script> <script src="https://www.oxfordlearnersdictionaries.com/external/scripts/jquery.lightbox-0.5.min.js"></script> <script src="https://www.oxfordlearnersdictionaries.com/external/scripts/oxford.js"></script> <script src="https://www.oxfordlearnersdictionaries.com/external/scripts/entry.js"></script> <script language="javascript" type="text/javascript"> var contextId= (location.hash != "" ? location.hash : null); // global variable that contains the path to external files // and used by the lightbox script var lightboxImageLoading = "https://www.oxfordlearnersdictionaries.com/external/images/lightbox-ico-loading.gif?version=2.3.41"; var lightboxImageBtnPrev = "https://www.oxfordlearnersdictionaries.com/external/images/lightbox-btn-prev.gif?version=2.3.41"; var lightboxImageBtnNext = "https://www.oxfordlearnersdictionaries.com/external/images/lightbox-btn-next.gif?version=2.3.41";
{ "domain": "codereview.stackexchange", "id": 44189, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript, jquery, google-chrome, bookmarklet", "url": null }
javascript, jquery, google-chrome, bookmarklet var lightboxImageBtnClose = "https://www.oxfordlearnersdictionaries.com/external/images/lightbox-btn-close.gif?version=2.3.41"; var lightboxImageBlank = "https://www.oxfordlearnersdictionaries.com/external/images/lightbox-blank.gif?version=2.3.41"; if (document.readyState != 'loading'){ initEntry('See more', 'See less'); } else if (document.addEventListener) { document.addEventListener('DOMContentLoaded', function(){initEntry('See more', 'See less');}); } else { document.attachEvent('onreadystatechange', function() { if (document.readyState != 'loading') initEntry('See more', 'See less'); }); } </script>
{ "domain": "codereview.stackexchange", "id": 44189, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript, jquery, google-chrome, bookmarklet", "url": null }
javascript, jquery, google-chrome, bookmarklet And here is the code with the effect of the bookmarklet added:
{ "domain": "codereview.stackexchange", "id": 44189, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript, jquery, google-chrome, bookmarklet", "url": null }
javascript, jquery, google-chrome, bookmarklet document.addEventListener('DOMContentLoaded', function() { document.querySelectorAll('.box_title').forEach(e => e.click()); }); <link href="https://www.oxfordlearnersdictionaries.com/external/styles/oald10.css" rel="stylesheet" /> <link href="https://www.oxfordlearnersdictionaries.com/external/styles/interface.css" rel="stylesheet" /> <span class="shcut-g" id="get_sngs_2"> <h2 class="shcut" htag="h2" id="get_shcut_2" hclass="shcut">bring</h2><li class="sense" cefr="a1" id="get_sng_4" hclass="sense" htag="li" sensenum="5" ox3000="y"><a class="open oup_icons" title="Add to My Word Lists"><span class="star-btn" aria-hidden="true">​</span></a> <span class="sensetop" hclass="sensetop" htag="span"> <div class="symbols" htag="div" hclass="symbols"><a href="https://www.oxfordlearnersdictionaries.com/wordlists/oxford3000-5000?dataset=english&amp;list=ox3000&amp;level=a1"><span class="ox3ksym_a1">&nbsp;</span></a></div> </span> <span class="grammar" hclass="grammar" htag="span">[transitive]</span> <span class="def" htag="span" hclass="def">to go to a place and bring somebody/something back</span> <span class="xrefs" htag="span" xt="nsyn" hclass="xrefs"><span class="prefix">synonym</span> <a class="Ref" href="https://www.oxfordlearnersdictionaries.com/definition/english/fetch" title="fetch definition"><span class="xr-g" href="fetch_e" bord="n"><span class="xh">fetch</span></span></a></span> <ul class="examples" hclass="examples" htag="ul"> <li class="" htag="li"> <span class="cf" htag="span" hclass="cf">get somebody/something</span> <span class="x">Quick—<span class="cl">go and get</span> a cloth!</span> </li> <li class="" htag="li"><span class="x">Somebody get a doctor!</span></li> <li class="" htag="li"><span class="x">She went to <span class="cl">get help</span>.</span> </li> <li class="" htag="li"><span class="x">I have to go and get my mother from the airport <span class="gloss" htag="span" hclass="gloss">(= collect her)</span>.</span>
{ "domain": "codereview.stackexchange", "id": 44189, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript, jquery, google-chrome, bookmarklet", "url": null }
javascript, jquery, google-chrome, bookmarklet </li> <li class="" htag="li"> <span class="cf" hclass="cf" htag="span">get something for somebody</span> <span class="x">Get a drink for John.</span></li> <li class="" htag="li"> <span class="cf" htag="span" hclass="cf">get somebody/yourself something</span> <span class="x">Get John a drink.</span></li> </ul> <div class="collapse" htag="div" hclass="collapse"><span class="unbox" id="get_unbox_2" unbox="extra_examples"><span class="box_title">Extra Examples</span> <ul class="examples" hclass="examples" htag="ul"> <li class="" htag="li"><span class="unx">She's gone to get a few more chairs.</span></li> <li class="" htag="li"><span class="unx">Could you go upstairs and get my wallet for me, please?</span></li> <li class="" htag="li"><span class="unx">Can I get you anything to eat or drink?</span></li> </ul> </span> </div> </li> </span> <div id="flex-menu"></div> <div id="panel-smartphone"></div> <div id="dictionarySelector"></div> <script src="https://www.oxfordlearnersdictionaries.com/common.js"></script> <script src="https://www.oxfordlearnersdictionaries.com/external/scripts/jquery.lightbox-0.5.min.js"></script> <script src="https://www.oxfordlearnersdictionaries.com/external/scripts/oxford.js"></script> <script src="https://www.oxfordlearnersdictionaries.com/external/scripts/entry.js"></script> <script language="javascript" type="text/javascript"> var contextId= (location.hash != "" ? location.hash : null); // global variable that contains the path to external files // and used by the lightbox script var lightboxImageLoading = "https://www.oxfordlearnersdictionaries.com/external/images/lightbox-ico-loading.gif?version=2.3.41"; var lightboxImageBtnPrev = "https://www.oxfordlearnersdictionaries.com/external/images/lightbox-btn-prev.gif?version=2.3.41"; var lightboxImageBtnNext = "https://www.oxfordlearnersdictionaries.com/external/images/lightbox-btn-next.gif?version=2.3.41";
{ "domain": "codereview.stackexchange", "id": 44189, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript, jquery, google-chrome, bookmarklet", "url": null }
javascript, jquery, google-chrome, bookmarklet var lightboxImageBtnClose = "https://www.oxfordlearnersdictionaries.com/external/images/lightbox-btn-close.gif?version=2.3.41"; var lightboxImageBlank = "https://www.oxfordlearnersdictionaries.com/external/images/lightbox-blank.gif?version=2.3.41"; if (document.readyState != 'loading'){ initEntry('See more', 'See less'); } else if (document.addEventListener) { document.addEventListener('DOMContentLoaded', function(){initEntry('See more', 'See less');}); } else { document.attachEvent('onreadystatechange', function() { if (document.readyState != 'loading') initEntry('See more', 'See less'); }); } </script>
{ "domain": "codereview.stackexchange", "id": 44189, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript, jquery, google-chrome, bookmarklet", "url": null }
javascript, jquery, google-chrome, bookmarklet P.S. This is where everything started: "Expand all comments" button. A jQuery snippet is already suggested, but I prefer a plain JavaScript solution as jQuery isn't always available, e.g., on this dictionary. Answer: Be aware of all elements selected by the selector In the first revision it was stated: I created the following Chrome bookmarklet to open all Extra Examples boxes on this page And the code selects elements with the class name box_title: document.querySelectorAll('.box_title') Running that in the console on that URL I see 8 elements in the node list, though when I do a find on that page for "Extra Examples" there are only 4 elements. The other elements with that class name are for similar elements - e.g. labeled Verb Forms, Synonyms Understand, More Like This Verbs with two objects, and Word Origin - so the bookmarklet is toggling all of those elements. While this may not have any negative side-effects, it is doing more than the original intention. If the goal was to only click on the elements containing that text, then the jQuery :contains() selector could be used, though the goal here is to use vanilla JavaScript. While inspecting the HTML of those elements it appears that there is an attribute on the parent <span> with an unbox attribute set to extra_examples: <span class="unbox" id="get_unbox_5" unbox="extra_examples"> <span class="box_title">Extra Examples</span> <ul class="examples" htag="ul" hclass="examples"> <li class="" htag="li"><span class="unx">I finally got Michael to talk to them and he explained everything.</span></li> <li class="" htag="li"><span class="unx">We had trouble getting enough people to sign up.</span></li> </ul> </span> An attribute selector utilizing that unbox attribute could be used to find all elements with class box_title that are a direct child of an element with that attribute - e.g. document.querySelectorAll('[unbox="extra_examples"] > .box_title')
{ "domain": "codereview.stackexchange", "id": 44189, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript, jquery, google-chrome, bookmarklet", "url": null }
javascript, jquery, google-chrome, bookmarklet Modifying classes directly I did explore other options besides calling the click method. The best I could come up with was toggling the class name directly on the elements using the toggle() method of the classList property, but it gets more complex because the class name is-active needs to be added to both the parent <span> and the <span> with the text Extra Examples. Any event handlers that detect clicks would not be triggered - this could be a drawback, though it is possible that the page owner is attempting to detect clicks and maybe that leads to something like targeted advertising. document.querySelectorAll('[unbox="extra_examples"], [unbox="extra_examples"] > .box_title').forEach(e => e.classList.toggle('is-active'))
{ "domain": "codereview.stackexchange", "id": 44189, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript, jquery, google-chrome, bookmarklet", "url": null }
python, python-3.x Title: Translating excel spreadsheets Question: Context: This is a program that translates spreadsheets to English from Dutch using another custom library (transl). Question: Would like to hear criticism or advice on how to make the code better - not noob-like (Though I am one). Also, want to know what I do good. Thank you. Backstory: I Never got feedback on my code because I do it to facilitate my work. (I am not a programmer, but a business student) from openpyxl import load_workbook import transl import logging level = logging.INFO fmt = '[%(levelname)s] %(asctime)s - %(message)s' logging.basicConfig(level=level, format=fmt) class Spreadsheet: def __init__(self, filename_): self.workbook = None self.filename = filename_ @staticmethod def translate_cell(text): try: float(text) except ValueError: if text[0] != "=": return transl.translate(text) else: return text except TypeError: return '' else: return round(float(text), 2) def transl_sheet(self, sheet): for col_n, column in enumerate(sheet.iter_cols(values_only=True), start=1): for row_n, cell in enumerate(column, start=1): try: sheet.cell(row=row_n, column=col_n).value = self.translate_cell(cell) except AttributeError: pass logging.info(f'Worksheet "{sheet.title}" - Translation complete. Moving on...') return sheet def translate(self): logging.info(f'Loading the workbook.') try: self.workbook = load_workbook(filename=self.filename) except Exception as e: logging.error(f"Error occurred. Couldn't load the workbook. Possibly wrong filename.\n{e}") else: logging.info(f'Successfully loaded the workbook.') return [self.transl_sheet(sheet) for sheet in self.workbook]
{ "domain": "codereview.stackexchange", "id": 44190, "lm_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 def save(self): name = f'Translated - {self.filename}' logging.info(f'Saving the workbook into "{name}"') self.workbook.save(filename=name) logging.info('Done.') if __name__ == "__main__": spreadsheet = Spreadsheet("UvA-Budget_2023-2026.xlsx") spreadsheet.translate() spreadsheet.save() ``` Answer: For the most part this is good stuff! I only have a few pointers to give: Strings: Only use an f-string where necessary. Bits like logging.info(f'Loading the workbook.') should just be replaced with normal strings if you don't plan on interpolating any variables. Comments: Adding docstrings to functions will make the code much more useful to anyone who may want to touch your script in the future, because they'll be able to take one glance at things and understand exactly what each code segment is responsible for. Extensibility: Instead of hard-coding your file name into your code, you could use argparse like the following to make it a CLI that you can use on the fly: import argparse ... parser = argparse.ArgumentParser() parser.add_argument("-n", "--name", type=str, required=True, help="The name of the file") args = parser.parse_args() ... if __name__ == "__main__": spreadsheet = Spreadsheet(args.name) spreadsheet.translate() spreadsheet.save() This will allow for you to invoke the file like ./filename.py -n UvA-Budget_2023-2026.xlsx instead of having to go into a text editor to make the change. That's all I have for you, happy coding!
{ "domain": "codereview.stackexchange", "id": 44190, "lm_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++, file, formatting, logging, c++20 Title: Logger that writes to text file with std::vformat Question: This class has a Log function that appends text to a log text file. It takes a format string and a variable amount of arguments, much like a printf sort of function. It then writes the formatted string with the interpolated arguments to the file. I wanted to know if there are any edge cases I might've missed, or if anything can be done to improve this code? class Logger { private: Logger() = delete; Logger(const Logger&) = delete; public: template <class... FormatArgs> static void Log(const std::string_view format, FormatArgs&&... args) { std::ofstream logfile("log.txt", std::ios::app); logfile << std::vformat(format, std::make_format_args(args...)) << std::endl; } }; Edit Here are some usage examples*. Logger::Log("This is an example log message"); Logger::Log("This is a log message with {}", "one argument"); Logger::Log("This is a log message with {} {}", 2, "arguments"); Should produce a log.txt text file in the process's working directory with the following contents. This is an example log message This is a log message with one argument This is a log message with 2 arguments
{ "domain": "codereview.stackexchange", "id": 44191, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, file, formatting, logging, c++20", "url": null }
c++, file, formatting, logging, c++20 Answer: The class seems pointless, since it can't even be instantiated. Why not a free function (in a suitable namespace, perhaps)? The function itself opens and closes log.txt each time it's called. That's pretty inefficient, and will cause that file to be appended or created uncontrollably wherever the process's working directory happens to be. I'm not sure I'd want any program doing that to my files (and it will be many files if the process frequently changes directory). It's impossible to test in isolation, as it can't be decoupled from the file-system. We'd want to be able to write to a std::ostringstream in our tests, and we might want to write to the syslog service or equivalent in a daemon program, to take advantage of OS services such as log forwarding. The template with forwarding reference arguments (FormatArgs&&) fails to std::forward() them when they are used. There's really no need to flush output using std::endl when we immediately close the file, since that also flushes. Just use plain \n instead. Flushing output would be sensible if we kept the file open, rather than opening for each call. We probably want to catch std::format_error, and perhaps also std::ios_base::failure and std::bad_alloc, as it's better for logging to fail than to bring down the whole program (unless it's an audit log, I guess). Perhaps the most flexible option is to return a status value that the caller can choose to ignore or to act on. Perhaps we should be accepting a std::format_string as first argument (which would enable compile-time checking of its validity) rather than relying on run-time exceptions? Modified code #include <filesystem> #include <format> #include <fstream> #include <string_view> class Logger { std::ofstream file = {}; std::ostream& stream; public: explicit Logger(std::ostream& os) : stream{os} {} explicit Logger(std::filesystem::path& filename) : file{filename, std::ios::app}, stream{file} {}
{ "domain": "codereview.stackexchange", "id": 44191, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, file, formatting, logging, c++20", "url": null }
c++, file, formatting, logging, c++20 // This one has compile-time checking template<typename... Args> bool log(std::format_string<Args...> format, Args&&... args) { try { stream << std::format(format, std::forward<Args>(args)...) << std::endl; return true; } catch (...) { return false; } } // Run-time checking only template<typename... Args> bool log_unchecked(std::string_view format, Args&&... args) { try { stream << std::vformat(format, std::make_format_args(args...)) << std::endl; return true; } catch (...) { return false; } } }; #include <gtest/gtest.h> #include <sstream> TEST(Logger, Log) { auto s = std::ostringstream{}; auto logger = Logger{s}; EXPECT_TRUE(logger.log("{} {}!", "Hello", "world", "junk")); EXPECT_EQ(s.str(), std::string{"Hello world!\n"}); // logger.log("{} {}!", "Hello"); // doesn't compile EXPECT_FALSE(logger.log_unchecked("{} {}!", "Hello")); } For an alternative form of error checking, we could pass a flag to choose whether failures during logging should throw or not. This allows us to preserve the exception's type and content, which may be useful. We can use an extra argument to select the run-time-checked version instead of compile-time-checked (or mix and match parts of each change). That looks like: enum log_tag{ unchecked }; enum log_flags{ throw_on_error = 1 };
{ "domain": "codereview.stackexchange", "id": 44191, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, file, formatting, logging, c++20", "url": null }
c++, file, formatting, logging, c++20 // This one has compile-time checking template<typename... Args> void log(log_flags flags, std::format_string<Args...> format, Args&&... args) { try { stream << std::format(format, std::forward<Args>(args)...) << std::endl; } catch (...) { if (flags & throw_on_error) { throw; } } } template<typename... Args> void log(std::format_string<Args...> format, Args&&... args) { log(log_flags{}, format, std::forward<Args>(args)...); } // Run-time checking only template<typename... Args> void log(log_tag, log_flags flags, std::string_view format, Args&&... args) { try { stream << std::vformat(format, std::make_format_args(args...)) << std::endl; } catch (...) { if (flags & throw_on_error) { throw; } } } template<typename... Args> void log(log_tag tag, std::string_view format, Args&&... args) { log(tag, log_flags{}, format, std::forward<Args>(args)...); } Corresponding changes to tests: auto s = std::ostringstream{}; auto logger = Logger{s}; logger.log("{} {}!", "Hello", "world", "junk"); EXPECT_EQ(s.str(), std::string{"Hello world!\n"}); // logger.log("{} {}!", "Hello"); // doesn't compile // std::string fmt{"{}!"}; logger.log(fmt, "Hello"); // doesn't compile s.str({}); logger.log(Logger::unchecked, "{} {}!", "Hello"); EXPECT_EQ(s.str(), ""); EXPECT_THROW(logger.log(Logger::unchecked, Logger::throw_on_error, "{} {}!", "Hello"), std::exception);
{ "domain": "codereview.stackexchange", "id": 44191, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, file, formatting, logging, c++20", "url": null }
c++, regex Title: Replace Multiple Matches with different Values Question: I want to replace multiple matches of a Regex with different values from a map. I have for example the following string #id#_#date#_#value#_additional_text. I now want to replace the parts #xxx# with the corresponding values from a map. (The string could change so that I don't exactly know what kind of patterns are in there. What I'm currently doing are the following steps: Use std::sregex_token_iterator to go through the string and store all patterns I found in a std::vector. Go through all the patterns in the vector and use std::regex_replace to replace them with the values from the map. This is the code for the steps above: int main() { std::map<std::string, std::string> metadata{ {"value", "9"}, {"id", "1234"}, {"date", "1234"}, {"more", "abc"}}; std::vector<std::string> patterns{}; std::string input_data = "#id#_#date#_#value#_additional_text"; std::regex reg{R"(#([a-zA-Z]+)#)"}; const std::sregex_token_iterator end; for (std::sregex_token_iterator iter{std::cbegin(input_data), std::cend(input_data), reg, 1}; iter != end; ++iter) { std::cout << iter->str() << '\n'; patterns.push_back(iter->str()); } for (const auto pattern : patterns) { std::cout << pattern << '\n'; std::regex regex_pattern{"#" + pattern + "#"}; input_data = std::regex_replace(input_data, regex_pattern, metadata[pattern]); std::cout << input_data << '\n'; } std::cout << input_data << '\n'; } My question now is, is there a better way to achieve this? Answer: Library includes The code doesn't compile as presented. I needed to add a few headers: #include <iostream> #include <map> #include <regex> #include <string> #include <vector> Unnecessary output The problem statement just refers to replacing parts of the string, but we seem to be writing lots of other things to std::cout:
{ "domain": "codereview.stackexchange", "id": 44192, "lm_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++, regex", "url": null }
c++, regex std::cout << iter->str() << '\n'; std::cout << pattern << '\n'; std::cout << input_data << '\n'; These look like leftover debugging prints (that would normally go to std::clog rather than std::cout, and be removed before the program is ready for review). I'm assuming this output is not required. Unnecessary copying We don't need to copy each pattern here: for (const auto pattern : patterns) { Instead, we can just bind a reference: for (const auto& pattern : patterns) { Consider a single-pass algorithm without regular expressions Since # acts as a delimiter, we can implement these substitutions much more simply - just search for # and then look to see if it's followed by one of our translation keys and another #. That would look something like this: #include <iostream> #include <map> #include <string> #include <string_view> std::string replace_in_string(std::string_view s, const std::map<std::string, std::string>& replacements) { std::string result; for (;;) { auto pos = s.find('#'); auto end = s.find('#', pos+1); if (end == std::string_view::npos) { return result.append(s); } auto const key = s.substr(pos+1, end - pos - 1); auto const it = replacements.find(std::string{key}); if (it != replacements.end()) { result.append(s.substr(0, pos)).append(it->second); s = s.substr(end+1); } else { result.append(s.substr(0, end)); s = s.substr(end); } } } int main() { const std::map<std::string, std::string> metadata{ {"value", "9"}, {"id", "1234"}, {"date", "1234"}, {"more", "abc"}}; const std::string input_data = "#id#_#date#_#value#_additional_text"; std::cout << replace_in_string(input_data, metadata) << '\n'; }
{ "domain": "codereview.stackexchange", "id": 44192, "lm_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++, regex", "url": null }
c#, hash-map, enum Title: Switch case on an enum to return a specific mapped object from IMapper Question: I have an ever growing switch case statement I plan on adding 3 more case statements to. Given an int, compare it to an enum, and call IMapper.Map<TDestination>(sourceObject); public WebhookActivity MakeMessage(WebhookActivityRequest request) { WebhookActivity command = _mapper.Map<ConsecutiveCaseCreated>(request); var mappingId = 0; for(int i = 0; i < mappings.Length; i++) { if(request.WorkflowCode == mappings[i].WorkflowCode) { mappingId = mappings[i].EventHandlerId; } } switch(mappingId) { case (int)WorkflowEventHandler.CONSECUTIVE_CASE_CREATED: { command = _mapper.Map<ConsecutiveCaseCreated>(request); break; } case (int)WorkflowEventHandler.CONSECUTIVE_CASE_MODIFIED: { command = _mapper.Map<ConsecutiveCaseModified>(request); break; } case (int)WorkflowEventHandler.CONSECUTIVE_CASE_CANCELLED: { command = _mapper.Map<ConsecutiveCaseCancelled>(request); break; } case (int)WorkflowEventHandler.INTERMITTENT_CASE_CREATED: { command = _mapper.Map<IntermittentCaseCreated>(request); break; } case (int)WorkflowEventHandler.INTERMITTENT_CASE_TIME_ADJUSTED: { command = _mapper.Map<IntermittentCaseTimeAdjusted>(request); break; } case (int)WorkflowEventHandler.INTERMITTENT_CASE_TIME_DELETED: { command = _mapper.Map<IntermittentCaseTimeDeleted>(request); break; } case (int)WorkflowEventHandler.CASE_CHANGED_TYPE: { command = _mapper.Map<CaseChangedType>(request); break; } }
{ "domain": "codereview.stackexchange", "id": 44193, "lm_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#, hash-map, enum", "url": null }
c#, hash-map, enum return command; } I looked at other enum related questions and saw a common solution of using a dictionary. I tried that and couldn't quite figure out how to make the call to IMapper.Map() work out. Made the code a lot smaller though! Here's what the dictionary based solution I came up with looks like and what the method code became. private static readonly Dictionary<int, Type> workflowEventHandlers = new Dictionary<int, Type> { { (int)WorkflowEventHandler.CONSECUTIVE_CASE_CREATED, typeof(ConsecutiveCaseCreated)}, { (int)WorkflowEventHandler.CONSECUTIVE_CASE_CANCELLED, typeof(ConsecutiveCaseCancelled) }, { (int)WorkflowEventHandler.CONSECUTIVE_CASE_MODIFIED, typeof(ConsecutiveCaseModified) }, { (int)WorkflowEventHandler.INTERMITTENT_CASE_CREATED, typeof(IntermittentCaseCreated) }, { (int)WorkflowEventHandler.INTERMITTENT_CASE_TIME_ADJUSTED, typeof(IntermittentCaseTimeAdjusted) }, { (int)WorkflowEventHandler.INTERMITTENT_CASE_TIME_DELETED, typeof(IntermittentCaseTimeDeleted) }, { (int)WorkflowEventHandler.CASE_CHANGED_TYPE, typeof(CaseChangedType) } }; public WebhookActivity MakeMessage(WebhookActivityRequest request) { WebhookActivity command = _mapper.Map<ConsecutiveCaseCreated>(request); var mappingId = 0; for(int i = 0; i < mappings.Length; i++) { if(request.WorkflowCode == mappings[i].WorkflowCode) { mappingId = mappings[i].EventHandlerId; } } if(workflowEventHandlers.TryGetValue(mappingId, out Type mapDestinationType)) { //command = _mapper.Map(request, typeof(WebhookActivityRequest), mapDestinationType); //command = Map(request, mapDestinationType); } } // doesn't really work private WebhookActivityMessage Map<TSource, TDestination>(TSource source, TDestination destination) where TDestination: WebhookActivityMessage { return _mapper.Map<TSource, TDestination>(source); }
{ "domain": "codereview.stackexchange", "id": 44193, "lm_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#, hash-map, enum", "url": null }
c#, hash-map, enum The destination types all inherit from a base class called WebhookActivityMessage which inherits from WebhookActivity so I figured if I could say the return type of my Map() method was WebhookActivityMessage then it could be happy. Answer: You can use a switch expression (C# 8) instead of a switch statement to make the code a lot smaller: public WebhookActivity MakeMessage(WebhookActivityRequest request) { int mappingId = 0; for (int i = 0; i < mappings.Length; i++) { if (request.WorkflowCode == mappings[i].WorkflowCode) { mappingId = mappings[i].EventHandlerId; } } return (WorkflowEventHandler)mappingId switch { WorkflowEventHandler.CONSECUTIVE_CASE_CREATED => _mapper.Map<ConsecutiveCaseCreated>(request), WorkflowEventHandler.CONSECUTIVE_CASE_MODIFIED => _mapper.Map<ConsecutiveCaseModified>(request), WorkflowEventHandler.CONSECUTIVE_CASE_CANCELLED => _mapper.Map<ConsecutiveCaseCancelled>(request), WorkflowEventHandler.INTERMITTENT_CASE_CREATED => _mapper.Map<IntermittentCaseCreated>(request), WorkflowEventHandler.INTERMITTENT_CASE_TIME_ADJUSTED => _mapper.Map<IntermittentCaseTimeAdjusted>(request), WorkflowEventHandler.INTERMITTENT_CASE_TIME_DELETED => _mapper.Map<IntermittentCaseTimeDeleted>(request), WorkflowEventHandler.CASE_CHANGED_TYPE => _mapper.Map<CaseChangedType>(request), _ => _mapper.Map<ConsecutiveCaseCreated>(request) }; } But note that only the last mappingId in your for-loop will be used. Did you want to search for the first occurrence instead? int mappingId = mappings .FirstOrDefault(m => request.WorkflowCode == m.WorkflowCode)?.EventHandlerId ?? 0; As for your solution with the dictionary, you could declare a Dictionary<WorkflowEventHandler, Func<IMapper, WebhookActivityRequest, WebhookActivity>>
{ "domain": "codereview.stackexchange", "id": 44193, "lm_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#, hash-map, enum", "url": null }
c#, hash-map, enum instead. I.e., you would add it lambda expressions doing the work. private static readonly Dictionary<WorkflowEventHandler, Func<IMapper, WebhookActivityRequest, WebhookActivity>> workflowEventHandlers = new(){ { WorkflowEventHandler.CONSECUTIVE_CASE_CREATED, (m, r) => m.Map<ConsecutiveCaseCreated>(r) }, { WorkflowEventHandler.CONSECUTIVE_CASE_CANCELLED, (m, r) => m.Map<ConsecutiveCaseCancelled>(r) }, { WorkflowEventHandler.CONSECUTIVE_CASE_MODIFIED, (m, r) => m.Map<ConsecutiveCaseModified>(r) }, { WorkflowEventHandler.INTERMITTENT_CASE_CREATED, (m, r) => m.Map<IntermittentCaseCreated>(r) }, { WorkflowEventHandler.INTERMITTENT_CASE_TIME_ADJUSTED,(m, r) => m.Map<IntermittentCaseTimeAdjusted>(r) }, { WorkflowEventHandler.INTERMITTENT_CASE_TIME_DELETED, (m, r) => m.Map<IntermittentCaseTimeDeleted>(r) }, { WorkflowEventHandler.CASE_CHANGED_TYPE, (m, r) => m.Map<CaseChangedType>(r) } }; Then you can use it like this if (workflowEventHandlers.TryGetValue((WorkflowEventHandler)mappingId, out var mapCreator)) { command = mapCreator(_mapper, request); } else { command = _mapper.Map<ConsecutiveCaseCreated>(request); }
{ "domain": "codereview.stackexchange", "id": 44193, "lm_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#, hash-map, enum", "url": null }
javascript, html, ajax, cross-browser Title: Ajax to load data for company products without refreshing the page Question: I am using AJAX script to fetch data from a database. For example, it has Motorola Samsung Apple as company and I use AJAX to fetch models of it, so that when Apple is selected then it shows Apple iPhone 12, iPhone 13, iPhone 14, 14 pro max. This is an improved version of my AJAX script to load data for mobile phones from table. Here's the Ajax code - is it near perfect yet, or are there still improvements I can make? function createRequestObject(){var e,t=navigator.userAgent;return e="Microsoft Internet Explorer"==t?new ("Microsoft.XMLHTTP"):new XMLHttpRequest}function getRequest(e,t,n,a){elementId=t,loading_layer_in=a,http.open("get",e),http.onreadystatechange=ManipulateRequest,http.send(null)}function getRequestalert(e){http.open("get",e),http.onreadystatechange=function(){if(4==http.readyState){var e=http.responseText;res=e}},http.send(null)} function ManipulateRequest(){if(""==e)var e="<FONT><B>Loading please wait.........</B></FONT>";else msg=e;if(document.getElementById(loading_layer_in)&&(document.getElementById(loading_layer_in).style.display="block"),1==http.readyState);else if(4==http.readyState){var t=http.responseText;document.getElementById(elementId)&&(document.getElementById(elementId).innerHTML=t)}} function hideLoadingLayer(e){var t=e;document.getElementById(t)&&(document.getElementById(t).style.display="none")}var elementId="",loadingMessage="",loading_layer_in="",http=createRequestObject(); Answer: Checking for Internet Explorer requires other means The answer by QAnew stated: It is generally not recommended to use the navigator.appName property to determine the user's web browser, because this property can be easily changed by the user or by third-party software. Instead, you can use the navigator.userAgent property, which returns a string that contains information about the user's web browser and operating system. It appears that
{ "domain": "codereview.stackexchange", "id": 44194, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript, html, ajax, cross-browser", "url": null }
javascript, html, ajax, cross-browser It appears that t=navigator.appName; was changed to t=navigator.userAgent And that is used in a comparison: "Microsoft Internet Explorer"==t It is highly unlikely that the userAgent property will be exactly equal to the string "Microsoft Internet Explorer". There are many sites that list possible user agent strings - e.g. this list on useragentstring.com for Internet Explorer. Notice that string is not listed. Use feature detection instead of attempting to detect the browser As this StackOverflow answer suggests: use feature detection instead of browser detection to determine which object to use. This MDN page about IE 6 also matches this advice: Using XMLHttpRequest in IE6 XMLHttpRequest was first introduced by Microsoft in Internet Explorer 5.0 as an ActiveX control. However, in IE7 and other browsers XMLHttpRequest is a native JavaScript object. In all modern browsers, you can create a new XMLHttpRequest object using the following code: const request = new XMLHttpRequest() However, if you need to also support Internet Explorer 6 and older, you need to extend your code like this: let request; if (window.XMLHttpRequest) { //Firefox, Opera, IE7, and other browsers will use the native object request = new XMLHttpRequest(); } else { //IE 5 and 6 will use the ActiveX control request = new ActiveXObject("Microsoft.XMLHTTP"); } 1 Usage of Internet Explorer is down dramatically in recent years As I mentioned in this answer IE8 isn’t supported by Microsoft anymore. Even the last version of IE - i.e. 11 had support end on June 15th 2022. While users may still be using it, usage is low. For example, the caniuse.com usage table (based on data from StatCounter GlobalStats2) currently shows usage numbers less than 0.5% for the seven latest versions: IE 5.5: 0.01% 6: 0.01% 7: 0.01% 8: 0.04% 9: 0.09% 10: 0.01% 11: 0.42%
{ "domain": "codereview.stackexchange", "id": 44194, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript, html, ajax, cross-browser", "url": null }
javascript, html, ajax, cross-browser IE 5.5: 0.01% 6: 0.01% 7: 0.01% 8: 0.04% 9: 0.09% 10: 0.01% 11: 0.42% 2 Some HTML tags used are deprecated or can be replaced by other styling tools In function ManipulateRequest() the following assignment statement exists: e="<FONT><B>Loading please wait.........</B></FONT>" Note that some of those HTML elements are deprecated - e.g. per the MDN documentation for <font>: Deprecated: This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time. 3 And while the <b> tag is not deprecated it is recommended to use other tools for styling instead: <b>: The Bring Attention To element The <b> HTML element is used to draw the reader's attention to the element's contents, which are not otherwise granted special importance. This was formerly known as the Boldface element, and most browsers still draw the text in boldface. However, you should not use for styling text; instead, you should use the CSS font-weight property to create boldface text, or the <strong> element to indicate that text is of special importance. 4
{ "domain": "codereview.stackexchange", "id": 44194, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript, html, ajax, cross-browser", "url": null }
c++, linked-list, iterator, binary-search-tree Title: Max Stack implementation in C++ involving iterators Question: The tricky thing was keeping copies of list iterators in a tree map and managing both together. I'm not handling invalid input cases (like popping an empty stack) in this code. I am following Google C++ style guide. Any advice and feedback would be appreciated! // A Max Stack data structure which supports the push/pop LIFO operations // of a stack and allows removal of the largest number class MaxStack { // Doubly linked list serving as a stack list<int> dll_; // Tree map mapping user added values to iterator references in the // doubly linked list map<int, vector<list<int>::iterator>, std::greater<int>> bst_;
{ "domain": "codereview.stackexchange", "id": 44195, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, linked-list, iterator, binary-search-tree", "url": null }
c++, linked-list, iterator, binary-search-tree public: // Push element into the data structures // - Push to the end of doubly linked list // - Push the iterator from the doubly linked list to the vector // corresponding to the key of the input number void Push(int x) { dll_.push_back(x); if (bst_.find(x) == bst_.end()) { bst_[x] = vector<list<int>::iterator>(); } bst_[x].push_back(std::prev(dll_.end())); } // Pop from the top of the stack and remove the corresponding iterator // from the map int Pop() { int val = *(dll_.rbegin()); auto to_delete = *(bst_[val].rbegin()); dll_.erase(to_delete); bst_[val].pop_back(); // Remove the key from the map if nothing is left if (bst_[val].empty()) { bst_.erase(val); } return val; } int Top() { return *(dll_.rbegin()); } int PeekMax() { return bst_.begin()->first; } // Remove one instance of the largest element in the tree map // and the corresponding node in the doubly linked list. // If there are multiple largest elements, remove the most recently // added one. int PopMax() { int val = bst_.begin()->first; auto to_delete = *(bst_[val].rbegin()); dll_.erase(to_delete); bst_[val].pop_back(); // Remove the key from the map if nothing is left if (bst_[val].empty()) { bst_.erase(val); } return val; } }; ``` Answer: Don't use the using namespace std; directive. It should be std::list, not just list. Don't tend to name your variables for their types because types denote how we store data, not what data we store. We can simplify Push method. void Push(int x) { dll_.push_back(x); bst_[x].push_back(std::prev(dll_.end())); }
{ "domain": "codereview.stackexchange", "id": 44195, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, linked-list, iterator, binary-search-tree", "url": null }
c++, linked-list, iterator, binary-search-tree Method map::operator[] inserts empty vector for us if x does not exist. And to make the intent clearer, void Push(int x) { auto it = dll_.insert(std::end(dll_), x); bst_[x].push_back(it); } To get the last vector element, use vector::back(). auto to_delete = bst_[val].back(); bst_[val] used frequently in Pop. I would replace it with an alias to make things look more concise int Pop() { int val = *(dll_.rbegin()); auto& entries = bst_[val]; dll_.erase(entries.back()); entries.pop_back(); if (entries.empty()) bst_.erase(val); return val; } We can optimize Pop* methods a bit. int Pop() { int val = *(dll_.rbegin()); dll_.pop_back(); // to_delete always points to the last element if (auto& entries = bst_[val]; entries.size() == 1) // shortcut for unique elements bst_.erase(val); else entries.pop_back(); return val; } int PopMax() { auto it = std::begin(bst_); int val = it->first; auto& entries = it->second; dll_.erase(entries.back()); if (entries.size() == 1) bst_.erase(it); // reuse iterator else entries.pop_back(); return val; } We can optimize memory usage by replacing the vector of iterators with corresponding std::stack. Stack is an adapter for std::deque which acquires memory sparingly in compare to vector.
{ "domain": "codereview.stackexchange", "id": 44195, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, linked-list, iterator, binary-search-tree", "url": null }
bash Title: Short bash script to join arguments with dashoption, escaping quotes and $ dollar sign Question: So I got this short awk invocation wrapped in a bash script. unfortunately the bash script is kinda unreadable. Do you have any pointers? #!/bin/bash action="printf \"$1 \" \$1 \" \"" awk {"$action"} $2 Invoking it like this joinargs -s tmp if the tmp file looks like: a bb ccc would create this output -s a -s bb -s ccc and it's useful when assembling commands Answer: It's not clear why we're using Bash here - we're not using any features that aren't available in plain sh. You forgot to quote the expansion of $2 - we don't want that subject to word-splitting. Composing AWK commands like this is fragile - what if $1 contains ;, } or anything else with significance to the interpreter? The usual remedy is to pass an AWK variable on the command line with -v: #!/bin/sh set -eu prefix=$1 shift awk -v p="$prefix" \ '{printf "%s %s ", p, $1}' \ "$@" See that this makes the command more readable, too!
{ "domain": "codereview.stackexchange", "id": 44196, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "bash", "url": null }
beginner, bash, shell, sed Title: Changing file encoding, removing mid-line LF, and converting DOS CR-LF to Unix LF Question: We have several thousand large (10M<lines) text files produced by a windows machine. We need to change the file encoding of these files from cp1252 to utf-8, replace any bare Unix LF sequences (i.e. \n) with spaces, then replace the DOS line end sequences ("CR-LF", i.e \r\n) with Unix line end sequences (i.e. \n). The dos2unix utility is not available for this task. We've written a bash function to package these operations together using iconv and sed, with iconv doing the encoding and sed dealing with the LF/CRLF sequences. It first changes the encoding, then replaces \r\n sequences with a placeholder. It then replaces remaining \n with , and finally replaces the placeholders with \n: post_extract() { iconv --from-code=CP1252 --to-code=UTF-8 $1 | \ sed 's/\\r\\n/@PLACEHOLDER@/g' | \ sed 's/\\n/ /g' | \ sed 's/@PLACEHOLDER@/\\n/g' > $2 } I'm not used to writing shell functions. There may be many edge cases and other considerations not handled here but this first pass works. To be specific with how this function is used in practice, it is sent to the --to-command= argument of a call to tar, such that the above process is performed for every file extracted from the tar archive. Use case is preprocessing tabular data for upload to a database. I'm not sure if we can do the operation in place or not. Open to using tools other than sed, e.g. tr, awk or perl (though I don't think the latter is necessary). (Highly simplified) example input: apple|orange|\n|lemon\r\nrasperry|strawberry|mango|\n\r\n Example output: apple|orange| |lemon\nrasperry|strawberry|mango| \n
{ "domain": "codereview.stackexchange", "id": 44197, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "beginner, bash, shell, sed", "url": null }
beginner, bash, shell, sed Example output: apple|orange| |lemon\nrasperry|strawberry|mango| \n Answer: There's nothing Bash-specific here, so consider using plain sh for lower overheads. The unquoted expansions of $1 and $2 are subject to word-splitting, and you probably don't want that - use "$1" and "$2" respectively. It looks like you're over-escaping \r\n, unless you actually meant to handle those four characters (backslash, r, backslash, n). If we're handling ASCII CR and NL, then we need single backslashes for sed (the single quotes prevent shell expanding them). There's a small risk that the input might contain the magic @PLACEHOLDER@ sequence, and no matter how unlikely you make it, there's always a finite probability that it will turn up. It's worth cultivating a habit that such things aren't needed - that's the sort of "unlikely" input that gets exploited for security breaches. We're never going to match a newline in our sed commands, because sed is line-oriented. We would need an entirely different sed program, that removes \r$ (i.e. CR at end of line), and for lines that don't end in CR, read in the following line using the N command and replace the resulting newline with space). In any case, sed always writes complete lines of output - if input finishes with an incomplete line (no newline) then there's no way to prevent sed from corrupting that. An alternative would be to use Perl (I know you said that might be overkill). It can simply replace all newlines not preceded by CR by using a negative lookbehind assertion: s/(?<!\r)\n/ /g. And can slurp the entire file rather than operating on individual lines: perl -g -pe 's/(?<!\r)\n/ /g; s/\r\n/\n/g;'
{ "domain": "codereview.stackexchange", "id": 44197, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "beginner, bash, shell, sed", "url": null }
beginner, bash, shell, sed We might be able to get Perl to do the character-code conversion too. perl -C6 ensures that standard output and error are UTF-8, so if we can put its input stream into windows-1252, we'll have a short single program rather than needing a pipeline with iconv. I'm not sure we can do that with -p - we might need to provide the read-execute-write loop ourselves in that case.
{ "domain": "codereview.stackexchange", "id": 44197, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "beginner, bash, shell, sed", "url": null }
python, pandas Title: Create new columns in a DataFrame using functions and reposition the new columns Question: I would like a review regarding the method I use to create the new columns and then reposition them in the correct place where they should be. The new column called total_matched_vls should always be on the right side of the column called total_matched, which in the original CSV is at position 10 The new column called market_matched_vls should always be on the right side of the column called market_matched, which in the original CSV is at position 12 import pandas as pd def calc_back(df): if (df['result'] == 'WINNER'): return (df['odds']-1)*0.935 elif (df['result'] == 'LOSER'): return -1 else: return '' def calc_lay(df): if (df['result'] == 'LOSER'): return (1/(df['odds']-1))*0.935 elif (df['result'] == 'WINNER'): return -1 else: return '' def total_matched(df): if (df['total_matched'] < 1000): return 'centenas' elif (df['total_matched'] >= 1000) and (df['total_matched'] < 100000): return 'milhares' elif (df['total_matched'] >= 100000) and (df['total_matched'] < 1000000): return 'centenas de milhares' elif (df['total_matched'] >= 1000000): return 'milhões' else: return '' def market_matched(df): if (df['market_matched'] < 1000): return 'centenas' elif (df['market_matched'] >= 1000) and (df['market_matched'] < 100000): return 'milhares' elif (df['market_matched'] >= 100000) and (df['market_matched'] < 1000000): return 'centenas de milhares' elif (df['market_matched'] >= 1000000): return 'milhões' else: return '' filials = [ [ r'C:\Users\Computador\Desktop\csv\history.csv', 'history_p&l.csv' ], [ r'C:\Users\Computador\Desktop\csv\results.csv', 'results_p&l.csv' ] ]
{ "domain": "codereview.stackexchange", "id": 44198, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, pandas", "url": null }
python, pandas for a,b in filials: df = pd.read_csv(a, dtype={'market_id': str}) df['back'] = df.apply(calc_back, axis=1) df['lay'] = df.apply(calc_lay, axis=1) df['total_matched_vls'] = df.apply(total_matched, axis=1) df['market_matched_vls'] = df.apply(market_matched, axis=1) col = df.pop("total_matched_vls") df.insert(11, col.name, col) col_2 = df.pop("market_matched_vls") df.insert(14, col_2.name, col_2) df.to_csv(b, index=False) A brief example of the original CSV for ease of testing: open_local_data,country,competition,match_id,match_name,market_id,market_name,runner_id,runner_name,status,total_matched,odds,market_matched,percentage,above_odds,result 2022-08-24 15:00:00,UY,Uruguayan Segunda Division,31684262,Uruguay Montevideo FC v Progreso,1.202440748,Match Odds,11076801,Uruguay Montevideo FC,OPEN,197.2,2.88,448.52,43.96682422188531,9.24460199966309,WINNER 2022-08-24 15:00:00,AT,Austrian Matches,31685733,SV Gerasdorf Stammersdorf v Dinamo Helfort,1.202453470,Match Odds,10299781,SV Gerasdorf Stammersdorf,OPEN,15.99,3.05,27.12,58.96017699115043,26.17329174524879,LOSER 2022-08-24 15:00:00,UY,Uruguayan Segunda Division,31684267,Villa Espanola v Sud America,1.202440560,Match Odds,58805,The Draw,OPEN,458.35,3.5,651.11,70.39517132281796,41.82374275138939,LOSER 2022-08-24 15:00:00,UY,Uruguayan Segunda Division,31684266,Miramar Misiones v Central Espanol,1.202440654,Match Odds,5300627,Miramar Misiones,OPEN,642.05,2.1,1075.66,59.68893516538684,12.069887546339224,LOSER
{ "domain": "codereview.stackexchange", "id": 44198, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, pandas", "url": null }
python, pandas Answer: A typical antipattern is using apply when better alternatives exist (see e.g., this question on StackOverflow). Vectorized operations can be several hundred folds faster than using apply, which processes the dataframe in a row-based fashion. Looking at your functions, especially total_matched and market_matched, they seem to be the same function but applied on a different column. This is bad practice in general as you would have to maintain the same code in two places. Intuitively, a better idea is to write a function that accepts a column name to perform the same computation on different columns. You don't say why it is important that columns appear in a specific order. Perhaps this for a human reader only, but it's probably not a good idea to trust on the order of columns. However, if we insist on it and especially if your dataset is large, it feels wasteful to pop a column and then reinsert it. Instead, you can just insert the columns directly into the place where you want them. I'm omitting a few things and making a few assumptions: The result column will only either contain WINNER or LOSER. It's easy to handle a DRAW too, but I will let you do that. It's good practice to explicitly set the type of each column of your dataframe. I don't know or understand your data, so I will not do this. You are already saying that market_id is a string, but keep going and note that categoricals are very useful in this and typically result in smaller dataframes (in terms of memory) and faster processing. To summarize, we could write your snippet as follows: # -*- coding: utf-8 -*- from io import StringIO import pandas as pd import numpy as np
{ "domain": "codereview.stackexchange", "id": 44198, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, pandas", "url": null }
python, pandas import pandas as pd import numpy as np def describe_matched(df: pd.DataFrame, inspected: str) -> np.ndarray: return np.select( [ df["total_matched"] < 100, df[inspected].between(1_000, 100_000, inclusive="left"), df[inspected].between(100_000, 1_000_000, inclusive="left"), ], ["centenas", "milhares", "centenas de milhares"], default="milhões", ) example_data = StringIO( """open_local_data,country,competition,match_id,match_name,market_id,market_name,runner_id,runner_name,status,total_matched,odds,market_matched,percentage,above_odds,result 2022-08-24 15:00:00,UY,Uruguayan Segunda Division,31684262,Uruguay Montevideo FC v Progreso,1.202440748,Match Odds,11076801,Uruguay Montevideo FC,OPEN,197.2,2.88,448.52,43.96682422188531,9.24460199966309,WINNER 2022-08-24 15:00:00,AT,Austrian Matches,31685733,SV Gerasdorf Stammersdorf v Dinamo Helfort,1.202453470,Match Odds,10299781,SV Gerasdorf Stammersdorf,OPEN,15.99,3.05,27.12,58.96017699115043,26.17329174524879,LOSER 2022-08-24 15:00:00,UY,Uruguayan Segunda Division,31684267,Villa Espanola v Sud America,1.202440560,Match Odds,58805,The Draw,OPEN,458.35,3.5,651.11,70.39517132281796,41.82374275138939,LOSER 2022-08-24 15:00:00,UY,Uruguayan Segunda Division,31684266,Miramar Misiones v Central Espanol,1.202440654,Match Odds,5300627,Miramar Misiones,OPEN,642.05,2.1,1075.66,59.68893516538684,12.069887546339224,LOSER """ ) df = pd.read_csv(example_data, dtype={"market_id": str}) df = df.assign( back=np.where(df["result"] == "WINNER", (df["odds"] - 1) * 0.935, -1), lay=np.where(df["result"] == "LOSER", (1 / (df["odds"] - 1)) * 0.935, -1), ) df.insert( loc=11, column="total_matched_vls", value=describe_matched(df, "total_matched") ) df.insert( loc=14, column="market_matched_vls", value=describe_matched(df, "market_matched") )
{ "domain": "codereview.stackexchange", "id": 44198, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, pandas", "url": null }
c++, thread-safety, concurrency, c++20 Title: Thread Pool Class Question: I have a thread_pool class, that mimics std::thread. (I would have liked std to have a pool, but alas that is not the case.) thread_pool.h #ifndef _C9Y_THREAD_POOL_H_ #define _C9Y_THREAD_POOL_H_ #include <functional> #include <thread> #include <vector> #include "defines.h" namespace c9y { //! Thread Pool class C9Y_EXPORT thread_pool { public: //! Contruct empty thread pool. //! //! The default constructor will create a thread pool, but with no threads. //! It can be used to create an instance on the stack that can later accept //! a running thread pool with move assignment. thread_pool() noexcept; //! Create a thread pool. //! //! @param thread_func The thread function each thread in the pool executes. //! @param concurency The number of threads to run concurently. //! //! This constructor will create @arg concurency threads that execute @arg thread_func. thread_pool(std::function<void ()> thread_func, size_t concurency); //! Move Constructor thread_pool(thread_pool&& other) noexcept; //! Destructor //! //! @warning If the thread pool is not joined, the underlying std::thread //! objects will invoke std::terminate. ~thread_pool(); //! Move Asignment thread_pool& operator = (thread_pool&& other) noexcept; //! Get the concurency of the thread pool. size_t get_concurency() const; //! Join each thread in the pool. //! //! Calling join ensures that each thread function terminates and //! the coresponsing memory is freed. void join(); //! //! Swap thread pool. void swap(thread_pool& other) noexcept; private: std::vector<std::thread> threads;
{ "domain": "codereview.stackexchange", "id": 44199, "lm_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++, thread-safety, concurrency, c++20", "url": null }
c++, thread-safety, concurrency, c++20 private: std::vector<std::thread> threads; thread_pool(const thread_pool&) = delete; thread_pool& operator = (const thread_pool&) = delete; }; } #endif thread_pool.cpp: #include "thread_pool.h" namespace c9y { thread_pool::thread_pool() noexcept {} thread_pool::thread_pool(std::function<void()> thread_func, size_t concurency) { for (size_t i = 0; i < concurency; i++) { threads.emplace_back(std::thread(thread_func)); } } thread_pool::thread_pool(thread_pool&& other) noexcept { swap(other); } thread_pool::~thread_pool() {} thread_pool& thread_pool::operator = (thread_pool&& other) noexcept { swap(other); return *this; } size_t thread_pool::get_concurency() const { return threads.size(); } void thread_pool::join() { for (auto& thread : threads) { thread.join(); } threads.clear(); } void thread_pool::swap(thread_pool& other) noexcept { threads.swap(other.threads); } } thread_pool_test.cpp #include <c9y/thread_pool.h> #include <atomic> #include <gtest/gtest.h> TEST(thread_pool, create) { auto count = std::atomic<unsigned int>{0}; auto pool = c9y::thread_pool{[&]() { count++; }, 2}; pool.join(); EXPECT_EQ(2, static_cast<unsigned int>(count)); } TEST(thread_pool, default_contructor) { auto pool = c9y::thread_pool{}; } TEST(thread_pool, move) { auto count = std::atomic<unsigned int>{0}; auto pool = c9y::thread_pool{}; pool = c9y::thread_pool{[&]() { count++; }, 2}; pool.join(); EXPECT_EQ(2, static_cast<unsigned int>(count)); } This code was originally written against C++11 but the library recently was updated to C++20 and I am in the process up "updating" the code; so please consider it in the light of C++20.
{ "domain": "codereview.stackexchange", "id": 44199, "lm_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++, thread-safety, concurrency, c++20", "url": null }
c++, thread-safety, concurrency, c++20 Answer: Use std::jthread Since you target C++20, use std::jthread instead of std::thread. Its destructor will automatically call join() so you don't have to, and more importantly so you cannot forget to do so like you did in your destructor. Furthermore, it provides a framework for notifying the thread that it should stop. If you do use this, it would be nice to manage a stop token in your class thread_pool, and provide a request_stop() member function that will in turn request all threads to stop. No need to write your own move constructor Since the vector threads can be move constructed, the compiler can generate an implicit move constructor for your class that does what you want. So you can omit your explicit move constructor. In fact, you can then omit swap() as well, as std::swap() will then work on your class because it will have a move constructor. No need to delete the copy constructor You don't need to delete the copy constructor since threads is already non-copyable. Provide a default value for concurrency Often you want your thread pool to have as many threads as your CPU has hardware threads. You can get that number by calling std::thread::hardware_concurrency(). Consider making the parameter concurrency default to that so the user doesn't have to specify it themselves. Incomplete test suite You only have a few tests, and they don't capture some of the problems your class has. For example, you don't have a test that creates a thread pool with a given number of threads that ends without calling join(), you never call get_concurrency() or swap(), and you do move-assign but you don't move-construct. What if you construct a thread pool with a thread function but a concurrency of zero? Move assignment issues
{ "domain": "codereview.stackexchange", "id": 44199, "lm_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++, thread-safety, concurrency, c++20", "url": null }
c++, thread-safety, concurrency, c++20 Move assignment issues Move assignment looks very safe if the thread_pool moved into did not have any threads, but what if it does? The swap() will exchange them with the thread_pool object being assigned from, but then what? Should join() be called on that object? What if join() was already called? Using std::jthread makes this a lot safer, but even then you might wonder if moving is ever the right thing to do here if the object moved into has one or more (unjoined) threads. Maybe only allow this if there are no threads or if they have all been joined already? More optimal use of emplace_back() The great thing about emplace_back() is that it forwards its arguments to the constructor of the value_type of the container. So you can just write: threads.emplace_back(thread_func);
{ "domain": "codereview.stackexchange", "id": 44199, "lm_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++, thread-safety, concurrency, c++20", "url": null }
c++, thread-safety, concurrency, c++20 This avoids creating a temporary std::thread which then is moved into the container. Incomplete Doxygen documentation It's great to see the API being documented using Doxygen. However, you did not document all parameters and return values. For example, @return is missing for get_concurency() (which is misspelled: consider using codespell), and @param other is missing for swap(). You can enable warnings in Doxygen that will alert you to these issues. Make sure you run Doxygen now and then on your code, or even better run it automatically as part of your build system.
{ "domain": "codereview.stackexchange", "id": 44199, "lm_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++, thread-safety, concurrency, c++20", "url": null }
javascript, array, sorting, node.js Title: How can I condense my code in node.js for sorting unique values within an array? Question: Kattis problem - ("I've been everywhere") I would highly recommend looking at the problem through the link, however I will summarize it a bit here and explain the functionality of each part of my horrendous code. Example input: 2 7 saskatoon toronto winnipeg toronto vancouver saskatoon toronto 3 edmonton edmonton edmonton (line 1: number of test cases 2, lines 2 and 10: number of working trips 7 3) Example output: 4 1 The goal is to ouput how many unique locations has been traveled to per test case. (correction, it does not matter if a location was visited already in a previous test case) So, basically I want some help condensing my code as much as possible, and make it simpler also because I believe my code is a little bit much for such a basic coding question. Also, I want to extend my knowledge beyond spamming for loops XD My Code var readline = require('readline'); var input = []; var rl = readline.createInterface({ input: process.stdin, output: process.stdout }); rl.on('line', function (cmd) { input.push(cmd); }); rl.on('close', function () { input.shift(); let counter = 50; for (let i = 0; i < input.length; i++) { value = parseInt(input[i]); if (value / value == 1) { input[i] = counter; counter++; } } let index = []; let unique = [...new Set(input)]; //console.log(unique) for (let i = 0; i < unique.length; i++) { value = parseInt(unique[i]); if (value / value == 1) { unique[i] = unique.indexOf(unique[i]); index.push(unique.indexOf(unique[i])); } } index.push(unique.length); unique.push(unique.length); //console.log(unique); //console.log(index);
{ "domain": "codereview.stackexchange", "id": 44200, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript, array, sorting, node.js", "url": null }
javascript, array, sorting, node.js let cityList = []; for (let i = 0; i < index.length; i++) { let start = index[i]; let end = (index[i+1]); //console.log(start); //console.log(end); if (end == undefined) { break; } array = []; for (let j = start + 1; j < end; j++) { if (unique[j] == undefined) { array.push(""); } else { array.push(unique[j]); } } cityList.push(array); } //console.log(cityList); for (let i = 0; i < cityList.length; i++) { console.log(cityList[i].length); } process.exit(0); }); //i know it's bad The code below removes the first element from the input array, changes the integers into distinct numbers to avoid removing them during the filtering later one: input.shift(); let counter = 50; for (let i = 0; i < input.length; i++) { value = parseInt(input[i]); if (value / value == 1) { input[i] = counter; counter++; } } Next, create an array of the indexes of each integer in the input array so we can used them as lower and upper bound limits. Filter out an duplicates. Change the input arrays integer values to their positional value or index for future use as well. Push the length of the input array into the index array and input array so that we have an index for the last upper bound. let index = []; let unique = [...new Set(input)]; //console.log(unique) for (let i = 0; i < unique.length; i++) { value = parseInt(unique[i]); if (value / value == 1) { unique[i] = unique.indexOf(unique[i]); index.push(unique.indexOf(unique[i])); } } index.push(unique.length); unique.push(unique.length); //console.log(unique); //console.log(index);
{ "domain": "codereview.stackexchange", "id": 44200, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript, array, sorting, node.js", "url": null }
javascript, array, sorting, node.js Establish an array that will include the unique locations per test case. Loop through the index array, using the value of index[i] for (start) and index[i+1] for (end). Create a nested array where it loops through the new input array known as the unique array, where we push every element between the start and end. let cityList = []; for (let i = 0; i < index.length; i++) { let start = index[i]; let end = (index[i+1]); //console.log(start); //console.log(end); if (end == undefined) { break; } array = []; for (let j = start + 1; j < end; j++) { if (unique[j] == undefined) { array.push(""); } else { array.push(unique[j]); } } cityList.push(array); } Finally, output the length of each nested array within cityList for (let i = 0; i < cityList.length; i++) { console.log(cityList[i].length); } : ) Answer: Here's a general heuristic: for "easy" Kattis problems, the solution should typically only be a dozen or so lines of code. If you're writing on the order of 70 lines, a red flag should go off. If you can get that 70-liner to be accepted, no problem. You can minimize the logic afterwards. But often, the 70-liner will have some sort of bug, in which case you shouldn't be afraid to toss it out or strip it down and start again based on what you learned from your attempt. Back to the problem at hand: for each test case, the input is a list of simple strings representing city names, and the output should be the count of distinct items in this list. You used a Set in your solution. This is the correct data structure! Given an array of items, putting it into a Set and taking its .size will return the number of distinct elements: const dishes = ["cranberries", "mashed potatoes", "cranberries"]; console.log(new Set(dishes).size); // => 2
{ "domain": "codereview.stackexchange", "id": 44200, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript, array, sorting, node.js", "url": null }
javascript, array, sorting, node.js Based on this, the task becomes a matter of locating each test case subarray of the input, putting it into the set and taking its size: const readline = require("readline"); const rl = readline.createInterface({ input: process.stdin, output: process.stdout, }); const lines = []; rl.once("line", () => { rl.on("line", line => lines.push(line)); }); rl.on("close", () => { lines.forEach((line, i) => { if (!isNaN(line)) { console.log(new Set(lines.slice(i + 1, i + +line + 1)).size); } }); }); Note that +lines parses a number from a string. Another thing to note: Kattis problems are generally pretty verbose in Node because of the awkwardness of the callback-based readline API. My solution in Ruby was: require "set" gets.to_i.times do places = Set.new gets.to_i.times {places.add gets.chomp} p places.size end That said, for this particular problem, it's reasonable to slurp the lines into an array, then process it at the end and use O(n) .shift() and indexOf() calls. I also used .slice() which is similarly inefficient. But this resource-intensive strategy may not work well on future problems. When the input is large, O(n) operations and a large memory footprint will cause tests to fail. Here's a more memory- and time-efficient setup to solve this problem. It's a bit more verbose and the solution needs to be triggered from a couple of places, but in some ways it's clearer than my above JS code since indexing is simplified. const readline = require("readline"); const rl = readline.createInterface({ input: process.stdin, output: process.stdout, }); const solve = () => console.log(places.size); const places = new Set(); rl.once("line", () => { rl.on("line", line => { if (!isNaN(line)) { if (places.size) { solve(); places.clear(); } } else { places.add(line); } }); }); rl.on("close", solve);
{ "domain": "codereview.stackexchange", "id": 44200, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript, array, sorting, node.js", "url": null }
javascript, array, sorting, node.js When solving Kattis problems in Node, avoiding memory and time issues often comes down to successful readline management. For more readline tips and tricks for Kattis problems with Node, check out the links in this SO answer. A few other pointers: Use const rather than let to avoid reassigning things. Using let often is a code smell. var can be totally dropped at this point. Watch out for accidental global variables like array = [];. A linter can find these errors for you. Avoid counter loops when possible. Prefer semantically-meaningful, higher-order looping functions like forEach, map, filter, every, some, find and so forth. Remove commented-out code you used to debug when finalizing it. Code shown for review should reflect the code you'd normally provide in a pull request or production commit.
{ "domain": "codereview.stackexchange", "id": 44200, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript, array, sorting, node.js", "url": null }
rust Title: Tree implementation in Rust Question: I am a beginner to Rust, started learning because of Advent of Code 2022. I solved Day 7's problem by implementing a tree data structure and traversing it. TLDR, the problem provides a log of terminal inputs and outputs, consisting of either ls or cd <dir> commands, such as $ cd / $ ls dir a 1 b $ cd a $ ls a 2 a 3 b And here is my solution: use std::cell::RefCell; use std::default::Default; use std::fmt::Debug; use std::ops::Add; use std::rc::Rc; const ITER_ERR: &str = "err: iterator is empty"; const PARSE_ERR: &str = "err: can't parse int"; const SPLIT_ERR: &str = "err: can't split string"; struct Solver { content: String, } trait Solvable { fn solve(self) -> (usize, usize); } // Blanket implementation trait NodeValTrait<T>: Add<Output = T> + Default + Copy + Debug {} impl<T> NodeValTrait<T> for T where T: Add<Output = T> + Default + Copy + Debug {} #[derive(Debug)] struct TreeNode<T: NodeValTrait<T>> { val: Option<T>, name: String, children: Vec<Rc<RefCell<TreeNode<T>>>>, } impl<T: NodeValTrait<T>> TreeNode<T> { fn new(s: impl ToString) -> TreeNode<T> { TreeNode { val: None, name: s.to_string(), children: Vec::new(), } } fn val(&mut self, val: T) { self.val = Some(val); } fn push(&mut self, node: TreeNode<T>) { self.children.push(Rc::new(RefCell::new(node))); } fn insert_and_find(&mut self, name: impl ToString) -> Rc<RefCell<TreeNode<T>>> { let name = name.to_string(); for child in &self.children { if child.borrow().name == name { return Rc::clone(child); } } let child = TreeNode::new(name); self.push(child); Rc::clone(&self.children[&self.children.len() - 1]) }
{ "domain": "codereview.stackexchange", "id": 44201, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "rust", "url": null }
rust fn sum(&self) -> T { let mut res: T = Default::default(); if let Some(val) = &self.val { res = res + *val; } for child in &self.children { res = res + child.borrow().sum(); } res } fn dfs<F, T2>(&self, f: F) -> Vec<T2> where F: Fn(&TreeNode<T>) -> T2, { let mut res = Vec::new(); res.push(f(self)); for child in &self.children { // workaround for infinite recursion let f = &f as &dyn Fn(&TreeNode<T>) -> T2; res.extend(child.borrow_mut().dfs(f)); } res } } impl Solvable for Solver { fn solve(self) -> (usize, usize) { let root: Rc<RefCell<TreeNode<usize>>> = Rc::new(RefCell::new(TreeNode::new(""))); let mut cur_path = Vec::new(); cur_path.push(Rc::clone(&root)); // each $ represents new command input / output group for cmds in self.content.split("$ ") { let cur = &cur_path[cur_path.len() - 1]; let lines: Vec<&str> = cmds.trim().lines().collect(); if lines.is_empty() { continue; }
{ "domain": "codereview.stackexchange", "id": 44201, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "rust", "url": null }
rust let cmd: Vec<&str> = lines[0].split(" ").collect(); if cmd[0] == "ls" { // handles `ls` commands for &line in &lines[1..] { let (prefix, dir) = line.split_once(" ").expect(SPLIT_ERR); let child = cur.borrow_mut().insert_and_find(dir); match prefix { "dir" => { cur.borrow_mut().insert_and_find(dir); } _ => { let prefix = prefix.parse().expect(PARSE_ERR); child.borrow_mut().val(prefix); } } } } else { // handles `cd` commands match cmd[1] { ".." => { cur_path.pop(); } dir => { let child = cur.borrow_mut().insert_and_find(dir); cur_path.push(child); } } } } let func = |node: &TreeNode<usize>| (node.val.is_some(), node.sum()); let binding = root.borrow_mut().dfs(func); let vals = binding .iter() .filter(|(is_file, _)| !is_file) .map(|(_, sum)| sum); // part 1 let part1 = vals.clone().filter(|&sum| *sum <= 100000).sum(); // part 2 let freeup = root.borrow_mut().sum() - 40000000; let part2 = vals .clone() .filter(|&sum| *sum >= freeup) .min() .expect(ITER_ERR); (part1, *part2) } } fn main() { let solver = Solver { content: include_str!("../input").to_string(), }; let (part1, part2) = solver.solve(); println!("Part 1: {part1:?}"); println!("Part 2: {part2:?}"); }
{ "domain": "codereview.stackexchange", "id": 44201, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "rust", "url": null }
rust If there are any suggestions on how to simplify this code, or how to make it more Rust-like, then it would be great. In particular, the implementation for dfs just seems... weird, especially the "hack" with &f as &dyn ... to avoid infinite recursion at compile time. Also, is it possible to modify dfs such that it returns say Vec<(&TreeNode<T>, T2)> or similar? I tried doing it naively by replace res.push(f(self)) with res.push((self, f(self))), but it fails horribly with tons of lifetime problems. Another question - is it encouraged to use match and iter.method().method().method() chains over other options like if let? It seems that especially when using match, the indentation level goes quite deep. Finally, are there other options to Rc<RefCell<...>>? It is working great but keeping track of the types are annoying. Answer: In particular, the implementation for dfs just seems... weird, especially the "hack" with &f as &dyn ... to avoid infinite recursion at compile time. Let's take a look: fn dfs<F, T2>(&self, f: F) -> Vec<T2> where F: Fn(&TreeNode<T>) -> T2, { let mut res = Vec::new(); res.push(f(self)); for child in &self.children { // workaround for infinite recursion let f = &f as &dyn Fn(&TreeNode<T>) -> T2; res.extend(child.borrow_mut().dfs(f)); } res } The fundamental problem here is that dfs takes ownership of f, but you don't want to pass ownership of f when calling it recursively. The easiest solution is to never take ownership. Specifically, take a borrow of f: fn dfs<F, T2>(&self, f: &F) -> Vec<T2> where F: Fn(&TreeNode<T>) -> T2, { let mut res = Vec::new(); res.push(f(self)); for child in &self.children { res.extend(child.borrow_mut().dfs(f)); } res }
{ "domain": "codereview.stackexchange", "id": 44201, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "rust", "url": null }
rust This will require updating calling sites to pass a borrow. However, there is another problem with this implementation. It will create and destroy a lot of Vecs. It'd be more efficient to put everything directly into a single target vec. I'd split it into two functions: fn dfs_impl<F, T2>(&self, res: &mut Vec<T2>, f: &F) where F: Fn(&TreeNode<T>) -> T2, { res.push(f(self)); for child in &self.children { child.borrow_mut().dfs_impl(res, f); } } fn dfs<F, T2>(&self, f: F) -> Vec<T2> where F: Fn(&TreeNode<T>) -> T2, { let mut res = Vec::new(); self.dfs_impl(&mut res, &f); res } Another question - is it encouraged to use match and iter.method().method().method() chains over other options like if let? It seems that especially when using match, the indentation level goes quite deep. In cases where there is a binary decisions (if this else that) then I recommend using if let over a match. Matches makes sense if you have several different paths to choose from. I also usually prefer if let over methods but that's more situations specific. Also, is it possible to modify dfs such that it returns say Vec<(&TreeNode, T2)> or similar? I tried doing it naively by replace res.push(f(self)) with res.push((self, f(self))), but it fails horribly with tons of lifetime problems. As it stands, you shouldn't. Your code works with Rc<RefCell< and so you should return that and not simple borrows. You can do this by defining static methods that operate on Rc<RefCell<. fn dfs_impl<F, T2>(me: &Rc<RefCell<Self>>, res: &mut Vec<(Rc<RefCell<Self>>, T2)>, f: &F) where F: Fn(&TreeNode<T>) -> T2, { res.push((Rc::clone(me), f(&me.borrow()))); for child in &me.borrow().children { TreeNode::dfs_impl(&child, res, f); } } fn dfs<F, T2>(me: &Rc<RefCell<Self>>, f: F) -> Vec<(Rc<RefCell<Self>>, T2)> where F: Fn(&TreeNode<T>) -> T2, { let mut res = Vec::new(); TreeNode::dfs_impl(me, &mut res, &f); res }
{ "domain": "codereview.stackexchange", "id": 44201, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "rust", "url": null }
rust But this leads us to your last question. Finally, are there other options to Rc<RefCell<...>>? It is working great but keeping track of the types are annoying. The alternative is to use the types directly. Instead of Vec<Rc<RefCell<TreeNode>> just use Vec<TreeNode>. If you just do that with your current code you'll end up in a morass of lifetime errors. The particular problem that you'll find is cur_path in Solver::solve. Right now it is a vector of Rcs which is fine, but a Vec of mutable borrows to different parts of the same tree structure and that won't work very well since Rust's borrow checker can't ensure that you use that safely. One approach would be reimplement the solution recursively. In particular, anytime you need to move down a layer in the tree, you should call a method on that tree node to take care of it. It should return when it leaves tree (i.e. sees a cd ..) so that the directory above can continue processing. Another approach would be to use indexes instead of references. The idea here is that your tree structure has methods to manipulate the tree and takes indexes to determine which node is being manipulated instead of operating on references or Rcs. This avoids issues with the borrow checker and avoids the annoyance of dealing with Rc<RefCell. The drawback is that Rust borrow checker can't ensure that you use the indexes correctly.
{ "domain": "codereview.stackexchange", "id": 44201, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "rust", "url": null }
php, html, file-system, bootstrap Title: PHP Bootstrap Autoloader Question: I wrote an PHP Autoloader to include it "easyer" to my projects. Here the folder structure: www ├───index.php ├───init.php └───Libarys └───bootstrap ├───index.php ├───bootstrap_loader.php └───bootstrap_core_files (Files and Directories (Abbreviated so it doesn't get too much)) www/index.php: It's just like the main method in Java, which starts on execution. This integrates the init.php file. <?php include_once("./init.php"); $init = new Initialisation(); $init->loadBS(); ?> www/init.php: It's just like the init method in Java, which initialized integrate following things: Directory Locations (initialized) BootStrapLoader (integrate (www/Libarys/bootstrap/index.php) <?php class Initialisation { private $direct; function getFileLocation() { $value = ""; $value = $_SERVER["REQUEST_URI"]; return($value); } function getCurrentDirectory() { $dir = ""; $getFileLocation = $this->getFileLocation(); $countetSlashes = substr_count($getFileLocation,"/")-1; if ($getFileLocation !== "") { for ($i = 0; $i < $countetSlashes; $i++) { $dir = $dir."../"; } } $dir = $dir."./Libarys/bootstrap"; return $dir; } function setDirect($dir) { $this->direct = $dir; } function getDirect() { return $this->direct; } function loadBS() { $this->setDirect($this->getCurrentDirectory()); include_once($this->getDirect()."/index.php"); $loadBS = new LoadBootStrap(); $loadBS->loadBootStrap(); } } ?>
{ "domain": "codereview.stackexchange", "id": 44202, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "php, html, file-system, bootstrap", "url": null }
php, html, file-system, bootstrap www/Libarys/bootstrap/index.php: This index.php file just starts the true loader (www/Libarys/bootstrap/bootstrap_loader.php). <?php class LoadBootStrap { function loadBootStrap() { $init = new Initialisation(); $init->setDirect($init->getCurrentDirectory()); include_once($init->getDirect()."/bootstrap_loader.php"); $bootstrap = new BootStrap(); $bootstrap->loadFileGeter("JS", $init->getDirect()); $bootstrap->loadFileGeter("CSS", $init->getDirect()); } } ?>
{ "domain": "codereview.stackexchange", "id": 44202, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "php, html, file-system, bootstrap", "url": null }