text
stringlengths
1
2.12k
source
dict
c#, performance, asp.net-core, entity-framework-core [StringLength(15)] public string Sofulfillmentbin { get; set; } [Column("MULTIPLEBINS")] public byte Multiplebins { get; set; } [Column("Print_Phone_NumberGB")] public short PrintPhoneNumberGb { get; set; } [Column("DEX_ROW_TS", TypeName = "datetime")] public DateTime DexRowTs { get; set; } [Column("DEX_ROW_ID")] public int DexRowId { get; set; }
{ "domain": "codereview.stackexchange", "id": 43345, "lm_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, asp.net-core, entity-framework-core", "url": null }
c#, performance, asp.net-core, entity-framework-core public Order Order { get; set; } public event PropertyChangedEventHandler PropertyChanged; [NotifyPropertyChangedInvocator] protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } } Answer: Sorry for the late post. I did find a solution. The Foreach loop in my original question was making a database call for each item. It worked but it was painfully slow. My biggest improvement was getting that done in one database call with a group by. var ecItems = await _context.BmaEcItems .Where(e => e.DisplayOnEcommerce == true) .Select(e => e.Itemnmbr) .ToListAsync(); var test = await _context.OrderDetails .Where(e => ecItems.Contains(e.Itemnmbr)) .GroupBy(e => e.Itemnmbr) .Select(e => new { ItemNumber = e.Key, QuantitySold = Convert.ToInt32(e.Sum(x => x.Quantity)) }) .OrderByDescending(e => e.QuantitySold) .Take(25) .ToListAsync(); var itemList = test.Select(e => e.ItemNumber) .ToList();
{ "domain": "codereview.stackexchange", "id": 43345, "lm_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, asp.net-core, entity-framework-core", "url": null }
c++, linked-list Title: Linked list implementation in cpp Question: I need some review for this CPP Linked list implementation. This is my first time implementing such a data structure in CPP. Thanks in advance. /* ** ** author: Omar_Hafez ** created: 12/05/2022 05:15:38 PM ** */ #include <bits/stdc++.h> using namespace std; template<class T> struct Node { Node<T> *next; T data; }; template<class T> class Linked_List { private: Node<T> *head = NULL; int count = 0; public: bool is_empty() { return (head == NULL); } void push_front(T value) { Node<T> *new_node = new Node<T>; new_node -> data = value; new_node -> next = head; head = new_node; count++; } void push_back(T value) { Node<T> *new_node = new Node<T>; new_node -> data = value; new_node -> next = NULL; if(is_empty()) head = new_node; else { Node<T> *tmp = head; while(tmp -> next != NULL) { tmp = tmp -> next; } tmp -> next = new_node; } count++; } int push_after(T value, T after) { if(is_empty()) return 0; Node<T> *tmp = head; while(tmp != NULL && (tmp -> data) != after) { tmp = tmp -> next; } if(tmp == NULL) return -1; Node<T> *new_node = new Node<T>; new_node -> data = value; new_node -> next = tmp -> next; tmp -> next = new_node; count++; return 1; } int delete_front() { if(is_empty()) return 0; if(count == 1) { count--; head = NULL; return 1; } head = head -> next; count--; return 1; } int delete_back() { if(is_empty()) return 0; if(count == 1) { count--; head = NULL; return 1; } Node<T> *tmp = head; while(tmp -> next -> next != NULL) tmp = tmp -> next; tmp -> next = NULL; count--; return 1; }
{ "domain": "codereview.stackexchange", "id": 43346, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, linked-list", "url": null }
c++, linked-list int erase(int value) { if(is_empty()) return 0; int cnt = 0; while(!is_empty() && head -> data == value) { cnt++; delete_front(); } Node<T> *tmp = head; while(tmp -> next != NULL) { if(tmp -> next -> data == value) { tmp -> next = tmp -> next -> next; cnt++; count--; } else tmp = tmp -> next; } if(tmp -> data == value) { delete_back(); cnt++; } return cnt; } void print_values() { Node<T> *tmp = head; while(tmp != NULL) { cout << (tmp -> data) << " "; tmp = tmp -> next; } cout << endl; } int search(T value) { Node<T> *tmp = head; while(tmp != NULL) { if(tmp -> data == value) return value; tmp = tmp -> next; } return -1; } int size() { return count; } }; Answer: Overview This is a singly linked list. Which is fine. But it is relatively trivial to implement a doubly linked list (next/prev link in each node). Also by using a doubly linked list and a sentinel (look up the sentinel pattern) you can remove the need to check for nullptr (which makes the code easier to read). You don't release the memory you allocate with new. For every call to new there should be an matching call to delete. This means your object should have a destructor. You don't obey the rule of three or five. If your object owns (owns ⇒ creates and destroys) a resource (in this case head) then the compiler-implemented copy constructor and assignment operator will not work (as you expect) and you need to implement your own. Code-Review Always good. /* ** ** author: Omar_Hafez ** created: 12/05/2022 05:15:38 PM ** */ Not sure if you need a time :-) but you may want to add (C) 2022 if this is auto generated. Note: By posting on this site you are licensing under CC (see bottom of page for details).
{ "domain": "codereview.stackexchange", "id": 43346, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, linked-list", "url": null }
c++, linked-list Never do: This: #include <bits/stdc++.h> That include is non-standard and your code is going to break and not compile at some point. Or this: using namespace std; This is going to get you in trouble in the long run. You should read the article Why is "using namespace std;" considered bad practice? second answer is the best in my opinion. Rather than doing this, prefix standard library types objects with std::. It's only 5 characters and the name std was designed to be short for that reason. This is good. But nobody should use this information (it is an internal detail to the class Linked_List) so make it a private member of the class so only it can use it. template<class T> struct Node { Node<T> *next; T data; }; It's not wrong. Node<T> *head = NULL; But in C++ (unlike C) the * is usually placed as part of the type. Node<T>* head = nullptr; In C++ the type information is very important so keeping it all together is useful in reading. Also NULL is C code. In C++ we use nullptr - it is type safe (unlike NULL). We can simplify this a bit and make it more readable in one go: void push_front(T value) { Node<T> *new_node = new Node<T>; new_node -> data = value; // Normally we don't add space new_node -> next = head; // around the -> operator. head = new_node; count++; } // How about this? void push_front(T value) { head = new Node<T>{head, value}; ++count; } This is a OK when T is a simple type like int. But what happens when T is LargeObjectWithState or std::vector<std::vector<int>>? void push_front(T value) ^^^^^^^ You are passing the parameter by value. That means there is a copy made before the call is even made (to copy it to the location where parameters are stored). Then inside the function you are copying into a Node object. new_node -> data = value; // Makes another copy of the object.
{ "domain": "codereview.stackexchange", "id": 43346, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, linked-list", "url": null }
c++, linked-list To get around this we normally pass parameters by reference to avoid the first copy. void push_front(T const& value) ^^^^^^ // a reference to the original value. // but we can't change the value. So that gets around one copy. But C++11 added a concept called move semantics that allows us to move objects (rather than copy them). Parameters that are movable are marked with && to indicate that we want to bind to an R-Value reference and that we may steal the content of the object as a result of calling the function. void push_front(T&& value) There is some magic you have to do. When you assign these values you need to make sure you do so in a way that tells the destination that you are moving the object to the destination: // Your function would look like this: void push_front(T&& value) { Node<T> *new_node = new Node<T>; new_node->data = std::move(value); new_node->next = head; head = new_node; count++; } // or how about this? void push_front(T&& value) { head = new Node<T>{head, std::move(value)}; ++count; } Node. You should have both versions of the function: void push_front(T&& value); void push_front(T const& value); There is a third variant called emplacing (but we can get to that in a subsequent review). Basically the same comments for push_back() as push_front(). void push_back(T value) { Here is returning magic numbers? int push_after(T value, T after) { 0: Empty List -1: Value does not exist 1: Value was inserted.
{ "domain": "codereview.stackexchange", "id": 43346, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, linked-list", "url": null }
c++, linked-list 0: Empty List -1: Value does not exist 1: Value was inserted. Not sure why 0 and -1 are different (in both cases after does not exist in the list). So it you combine these two you could return a boolean value to indicate whether the value was inserted. If you must stick with three then I would create an enum that makes this relationship readable. enum InsertStatus {FailedEmptyList, FailedValueDoesNotExist, OK}; InsertStatus push_after(T value, T after) { This looks very similar to some of the code above. Node<T> *new_node = new Node<T>; new_node -> data = value; new_node -> next = tmp -> next; tmp -> next = new_node; count++; We now have three places where you are calling new Node and then setting up the values and incrementing count. When you have repeated code you may want to put that in a named function, so that if there is a bug you only have to fix it in one place - and it makes reading the code easier. If you removed this if code. if(count == 1) { count--; head = NULL; return 1; } head = head -> next; count--; Would it change the behaviour? If there is only one item, then head->next should be nullptr. So head = head->next; would set head to nullptr. My main issue with this function is that you are leaking the Node. You allocated that node with new, so you should release the memory with delete. Node* old = head; head = head -> next; delete old; // every call to new should be matched with a call to delete. Don't think this will ever be true. if(tmp -> data == value) { delete_back(); cnt++; } You covered this situation in your main loop above. You don't want to use std::endl. It prints \n then flushes the stream. cout << endl; The stream is flushed automatically. You flushing it manually is only going to make it very inefficient.
{ "domain": "codereview.stackexchange", "id": 43346, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, linked-list", "url": null }
c++, linked-list If a function does not change the state of the object, mark it constant. int size() const { // ^^^^^^ return count; }
{ "domain": "codereview.stackexchange", "id": 43346, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, linked-list", "url": null }
python, python-3.x, python-requests Title: Printing a JSON/HTTP response from a Cisco endpoint Question: Please check over my Python code for a HTTP GET operation using the requests library, and provide any potential pointers for improvement. import requests token = input() payload={} headers = { "Accept": "application/yang-data+json", "Content-Type": "application/yang-data+json", "Authorization": "Bearer {}".format(token), } url = "https://sandbox-xxxx.cisco.com/restconf/data/native/router/bgp" try: response = requests.get(url, headers=headers, data=payload, verify=False, timeout=10) except requests.exceptions.HTTPError as errh: print(f"An HTTP Error occured: {errh}") except requests.exceptions.ConnectionError as errc: print(f"An Error Connecting to the API occured: {errc}") except requests.exceptions.Timeout as errt: print(f"A Timeout Error occured: {errt}") except requests.exceptions.RequestException as err: print(f"An Unknown Error occured: {err}") else: print(response.status_code) print(response.json()) Answer: Since this is the entire script, it doesn't need to exist and you can just invoke curl directly; and we can be a little more forgiving on exception-handling best practices.
{ "domain": "codereview.stackexchange", "id": 43347, "lm_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, python-requests", "url": null }
python, python-3.x, python-requests There isn't a whole lot of value in separating your excepts for different exception types. This is one of the few use cases where a catch-all except Exception is not a bad idea. If you print the repr() of the exception object using the !r format specifier, it will show you the exception type and content while omitting the traceback. If you do want to see the traceback, just delete your try/except entirely and let the default printing take effect. occured is spelled occurred. Don't call input() prompt-less. verify=False is risky. If the certificate does not have a valid trust chain, then you should pull the certificate and trust it explicitly either in your OS or within requests. Consider using pprint to print your JSON document. When you print the status code you should also print the reason string. Suggested from pprint import pprint import requests token = input('Please enter your bearer authentication token: ') sandbox = input('Please enter your sandbox ID: ') headers = { "Accept": "application/yang-data+json", "Content-Type": "application/yang-data+json", "Authorization": "Bearer " + token, } try: with requests.get( url=f"https://sandbox-{sandbox}.cisco.com/restconf/data/native/router/bgp", headers=headers, data={}, verify=False, timeout=10, ) as response: doc = response.json() except Exception as e: print(f'An error occurred: {e!r}') else: print(response.status_code, response.reason) pprint(doc)
{ "domain": "codereview.stackexchange", "id": 43347, "lm_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, python-requests", "url": null }
performance, swift, wordle Title: Simplify wordle logic Swift Question: I wrote logic for "Wordle" game but I think it's too heavy and not very readable. Is there any way to improve it? Simple wordle game with conditions: 1) Green colour - "G" if string1 and string2 indices values are equal. 2) Yellow colour - "Y" if string2 indices value appears in string1. 3) else statement Grey colour - "." 4) Every letter from string1 used for colour only once. My code: let mstr1 = readLine()! let mstr2 = readLine()! var string1 = mstr1.compactMap { $0.asciiValue } var string2 = mstr2.compactMap { $0.asciiValue } var dict: Dictionary<UInt8, Int> = [:] for element in Set(string1) { dict[element] = string1.filter { $0 == element }.count } var answer = Array(repeatElement(".", count: string1.count)) for i in 0 ..< string1.count { if string1[i] == string2[i] { answer[i] = "G" dict[string1[i]]! -= 1 } } for i in 0 ..< string1.count { if dict[string2[i]] != nil && answer[i] != "G"{ if dict[string2[i]]! > 0 { dict[string2[i]]! -= 1 answer[i] = "Y" } } if dict.values.filter { $0 > 0 }.count <= 0 { break } } print(answer.joined()) Input: ABBEY ALGAE Output: G...Y Answer: The logic itself looks good to me, but the readability of the program can be improved: Put the logic to compute the response for some guess into a function and separate it from the I/O. That increases the clarity of the program and allows to add test cases more easily. Use better variable names: What is string1 and string2? Which one is the correct answer and which one is the guessed word? What you call “answer” is (IMO) better called “response”. The dictionary dict plays a crucial role in the algorithm, therefore some comment explaining what it exactly contains would be helpful. Also the code can be simplified and improved, using Swift features like enumeration, dictionary subscripting with default values, optional binding, etc:
{ "domain": "codereview.stackexchange", "id": 43348, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "performance, swift, wordle", "url": null }
performance, swift, wordle There is no need to convert the strings to ASCII. One reason to do that might be that you get an array which allows easy access by subscript. But often that is not needed, and one can enumerate the strings instead. Dictionary<UInt8, Int> is more Swiftly written as [UInt8: Int] Creating the dictionary with the character frequencies can be done simpler and more efficiently by enumerating the string once: var dict: Dictionary<UInt8, Int> = [:] for element in string1 { dict[element, default: 0] += 1 } or even more concisely: var dict = string1.reduce(into: [:]) { (dict, char) in dict[char, default: 0] += 1 } However: if the frequencies are counted inside the first loop (which tests for exact matches) then one can get rid of the forced unwrapping in dict[string1[i]]! -= 1. This is fine var answer = Array(repeatElement(".", count: string1.count)) but an alternative is var answer = string1.map { _ in "." } Checking for existence of a value for a key in a dictionary is often better done with optional binding instead of if dict[...] != nil, in particular if the value is also needed, i.e. if dict[string2[i]] != nil && answer[i] != "G"{ if dict[string2[i]]! > 0 { dict[string2[i]]! -= 1 answer[i] = "Y" } } can be replaced by if let count = dict[string2[i]], count > 0, answer[i] != "G" { dict[string2[i]] = count - 1 answer[i] = "Y" } Putting it all together, the function could look like this: func wordleResponse(guess: String, solution: String) -> String { var response = guess.map { _ in "." } // For each character `c` in the solution word, `frequencies[c]` is // the number of occurrences not yet matched by a character in the // guessed word. var frequencies = [Character: Int]()
{ "domain": "codereview.stackexchange", "id": 43348, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "performance, swift, wordle", "url": null }
performance, swift, wordle for (position, (guessedChar, solutionChar)) in zip(guess, solution).enumerated() { if guessedChar == solutionChar { response[position] = "G" } else { frequencies[solutionChar, default: 0] += 1 } } for (position, guessedChar) in guess.enumerated() { if let count = frequencies[guessedChar], count > 0, response[position] != "G" { response[position] = "Y" frequencies[guessedChar] = count - 1 } } return response.joined() }
{ "domain": "codereview.stackexchange", "id": 43348, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "performance, swift, wordle", "url": null }
c++ Title: Map: Group Tuple keys Together with Empty Elements Question: Introduction We have std::map<key,std::vector<std::string>> m; where the key is represented by std::tuple<std::string, std::string,std::string>. But there is a constraint, the last field of the tuple can be an empty string. If the last element of the tuple is an empty string then we should merge it with the with elements of the map having same first and second elements. Input: o1("1","1","1") o2("1","1","1") o3("1","1","1") o4("2","2","2") o5("2","2","2") o6("2","2","") o7("2","2","") Output: Key: 1 1 1 ==> size: 3 Key: 2 2 2 ==> size: 4 Indeed, (1,1,1) are grouped together and (2,2,2), (2,2,"") are grouped together. I have to do the merge in 2 steps and I have to use 2 maps to do that. Is there a way to improve how I merge the keys together?
{ "domain": "codereview.stackexchange", "id": 43349, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++", "url": null }
c++ #include <iostream> #include <tuple> #include <map> #include <vector> #include <algorithm> using key = std::tuple<std::string, std::string,std::string>; /* Object we want to merge */ struct Object { Object(const std::string& x, const std::string& y, const std::string& z ):_x(x),_y(y),_z(z){} std::string _x; std::string _y; std::string _z; /* This object has more data members */ }; std::map<key,std::vector<Object>> mergeObjects(const std::vector<Object> &v) { /* Holds the objects without empty elements */ std::map<key,std::vector<Object>> m; /* Holds the objects with last empty element */ std::map<key,std::vector<Object>> m1; /* Step 1: Fill maps m and m1 based on whether z is empty or not*/ for(const auto &o:v) { /* if "z" is empty then put "o" in m1 else in m */ if(o._z.empty()) { m1[std::make_tuple(o._x, o._y, o._z)].push_back(o); } else { m[std::make_tuple(o._x, o._y, o._z)].push_back(o); } } /* Step 2: Merge elements. Find elements of m1 in m that have the same first and second elements */ for(const auto& [k,v]: m1){ auto[x, y, z] = k; /* Find first occurrence of k in m */ auto it = std::find_if(m.begin(), m.end(),[&](const std::pair<key, std::vector<Object>>& k1){ auto[x1, y1, z1] = k1.first; return (x == x1 and y == y1); }); /* If key found then merge and concatenate vectors*/ if(it != m.end()) { it->second.insert(it->second.end(),v.begin(), v.end()); } } return m; } int main() { /* What we receice as input */ Object o1("1","1","1"), o2("1","1","1"), o3("1","1","1"), o4("2","2","2"), o5("2","2","2"), o6("2","2",""),o7("2","2",""); std::vector<Object> v = {o1, o2, o3, o4, o5, o6, o7}; /* Merge Objects together if applicable */ std::map<key,std::vector<Object>> m = mergeObjects(v);
{ "domain": "codereview.stackexchange", "id": 43349, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++", "url": null }
c++ std::map<key,std::vector<Object>> m = mergeObjects(v); /* Print Merged Objects */ for(const auto&[k,v]: m){ std::cout << "Key: " << std::get<0>(k) <<" " << std::get<1>(k) <<" "<<std::get<2>(k) <<" ===> Size: "<< v.size() << std::endl; } return 0; }
{ "domain": "codereview.stackexchange", "id": 43349, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++", "url": null }
c++ Answer: The problem is not well-defined Your explaination and the code make it look like this is a well-defined problem, but it actually raises some questions. Consider this input: o1("1", "1", ""); o2("2", "2", "2"); o3("2", "2", "3"); o4("2", "2", ""); o5("2", "2", ""); o6("2", "", ""); o7("2", "", "2");
{ "domain": "codereview.stackexchange", "id": 43349, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++", "url": null }
c++ What should happen with o1? Should it appear in the merged objects or not? What of o4 and o5, should they both be merged with o2, both with o3, or should they be distributed over o2 and o3? And is only the last tuple element special when it is empty, or is the middle one being empty also something to consider? The answers to these questions will influence the algorithm you should use to merge the items. Merging using a single pass It is possible to merge the elements using a single pass. While looping over the vector of Objects, consider the order in which we see items with the last tuple item being empty or non-empty. If we see elements with the last item non-empty, then you can just add it to m. If an element follows with the last item non-empty, but we already have an element in m which matches the first two items of the tuple, then we can just append it there. The problem of course is when you start with an element with the last tuple element empty. A possible solution is to add it to m anyway. The moment we encounter an element with the same first two elements and the third one non-empty, we can merge them (which involves deleting the item with an empty last tuple element from m). However, a single-pass algorithm is not necessarily more efficient or more elegant than a two-pass algorithm, so I wouldn't automatically consider your approach bad. Improving efficiency I would rather focus on making the algorithm more efficient. The first pass is rather straight-forward. The only thing to improve here is that you don't need m1 to be an ordered map, instead you can in principle use a std::unordered_map, however since std::hash is not overloaded for std::tuple, that will not compile unless you add your own hash function.
{ "domain": "codereview.stackexchange", "id": 43349, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++", "url": null }
c++ The second pass can be greatly improved. The problem is that std::find_if() is doing a linear search, and since you have to do that for every element in m1, this has complexity \$\mathcal{O}(N^2)\$. But we can be smarter than that, since a std::map is ordered, and supports lookups in \$\mathcal{O}(\log N)\$ time. You can do that with lower_bound(): for (const auto& [k,v]: m1) { if (auto it = m.lower_bound(k); it != m.end()) { auto [x, y, z] = k; auto [x1, y1, z1] = it->first; if (x == x1 and y == y1) { it->second.insert(it->second.end(), v.begin(), v.end()); } } }
{ "domain": "codereview.stackexchange", "id": 43349, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++", "url": null }
c++ While that improves the time complexity of your algorithm, another issue is that you are copying objects, instead you can move them using move iterators. Unnecessary use of tuples Using tuples is sometimes handy, but you already have a nice type holding three strings: Object. Why not declare your maps like so? std::map<Object, std::vector<Object>> m; Now you can get rid of std::make_tuple, structured bindings still work, and instead of std::get<0>(k) you can just write k._x. The only issue is that your Object doesn't have a comparison operator. You will have to add one yourself so that std::map knows how to order your Objects. In C++20 this is very easy, just add: friend auto operator<=>(const Object& lhs, const Object& rhs) = default; Consider changing the data structure Some of the issues you have merging the elements come from the decision to store things in a std::map<key, std::vector<Object>>. If it is possible to change this data structure, you have some opportunities to make the merging even faster, and at the same time use less memory. The idea is that instead of a single map, you have an outer map of tuples of two strings, and inside you have a map of a string to an integer: std::map<std::tuple<std::string, std::string>, std::map<std::string, std::size_t>> m; Then adding the input into that data structure becomes: for (const auto &o: v) { m[{o._x, o._y}][o._z]++; } Maybe this is already good enough; for a given key k with three non-zero elements you can write: auto size = m[{k._x, k._y}][k._z] + m[{k._x, k._y}][{}]; std::cout << "Key: " << k._x << " " << k._y << " " << k._z << " size: " << size << '\n';
{ "domain": "codereview.stackexchange", "id": 43349, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++", "url": null }
c++ But if you want to merge them, you can simply loop over the elements of the outer map and check if the inner map has an element with an empty string, and then move its count to that of (one of the other) element(s) with a non-empty string: for (auto& [k, v]: m) { if (auto it1 = k.find({}); it1 != k.end()) { if (auto it2 = k.upper_bound({}); it2 != k.end()) { *it2 += *it1; k.erase(it1); } } }
{ "domain": "codereview.stackexchange", "id": 43349, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++", "url": null }
c++, chess, sfml Title: Chess game setup: Initial board state Question: This app only creates a chess board set to the start-of-game state. It does nothing else. I'd appreciate feedback on the files that are relevant to this board setup (all shown below: board.cpp, pieces.cpp, board_view.cpp). Although the project uses SFML, I'm hoping for C++ feedback, not SFML best practices per se. Below the files I will give a link just in case you want the two .cpp files I didn't include (main.cpp and game_loop.cpp), which don't control how the board is actually built at all. (The link also has all the header files, the pieces fonts, and the CMakeLists file... for whatever it's worth, everything will "just work" only if you have SFML installed). board.h #pragma once #include <SFML/Graphics.hpp> class board { public: explicit board(sf::Vector2u windowSize); explicit board(sf::Event &event); void render_board(); void draw_board(sf::RenderWindow &render_window) const; private: std::unordered_map<std::string, std::string> board_state{}; std::unordered_map<int, std::string> row_index_to_alg_notation_num{}; std::unordered_map<int, std::string> column_index_to_alg_notation_letter{}; sf::Vector2u windowSize; sf::RenderTexture render_texture; sf::Color white_square_color = sf::Color(238, 238, 211); sf::Color black_square_color = sf::Color(118, 150, 86); sf::Color window_background_color = sf::Color(169, 169, 169); sf::Font open_sans_font; std::unordered_map<int, std::string> alg_notation_letter_map; std::unordered_map<int, int> alg_notation_number_map; float x_offset = 0.0; float y_offset = 0.0; float square_size{}; void render_square(int i, int j); void render_piece(int i, int j); void render_algebraic_notation(int i, int j);
{ "domain": "codereview.stackexchange", "id": 43350, "lm_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++, chess, sfml", "url": null }
c++, chess, sfml void set_open_sans_font(); void set_alg_notation_letter_map(); void set_alg_notation_number_map(); void set_initial_board_state(); void set_indices_to_alg_notation(); std::string get_algebraic_notation(int i, int j); std::string get_piece_for_square(const std::string &); void init_(); }; board.cpp #include <SFML/Graphics.hpp> #include <cmath> #include "board.h" #include "pieces.h" board::board(sf::Vector2u windowSize) : windowSize(windowSize) { init_(); } board::board(sf::Event &event) { windowSize = {event.size.width, event.size.height}; init_(); } void board::render_board() { for (int i = 0; i < 8; i++) { for (int j = 0; j < 8; j++) { render_square(i, j); render_algebraic_notation(i, j); render_piece(i, j); } } } void board::render_square(int i, int j) { sf::RectangleShape currSquare({square_size, square_size}); currSquare.setFillColor((i + j) % 2 == 0 ? white_square_color : black_square_color); currSquare.setPosition(x_offset + static_cast<float>(j) * square_size, y_offset + static_cast<float>(i) * square_size); render_texture.draw(currSquare); render_texture.display(); } void board::render_piece(int i, int j) { std::string square_alg_notation = get_algebraic_notation(i, j); std::string piece_for_square = get_piece_for_square(square_alg_notation); if (!piece_for_square.empty()) { pieces p; sf::Text sfml_text_for_piece = p.get_positioned_sfml_text_graphic_for_piece(piece_for_square, square_size, x_offset, y_offset, i, j); render_texture.draw(sfml_text_for_piece); render_texture.display(); } } void board::render_algebraic_notation(int i, int j) {
{ "domain": "codereview.stackexchange", "id": 43350, "lm_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++, chess, sfml", "url": null }
c++, chess, sfml } void board::render_algebraic_notation(int i, int j) { if (i == 7) { sf::Text text(alg_notation_letter_map.at(j), open_sans_font, std::floor(square_size / 5.8f)); auto letter_color = j % 2 == 0 ? white_square_color : black_square_color; text.setFillColor(letter_color); text.setPosition(square_size / 1.2f + x_offset + static_cast<float>(j) * square_size, square_size / 1.3f + y_offset + static_cast<float>(i) * square_size); render_texture.draw(text); render_texture.display(); } if (j == 0) { sf::Text text(std::to_string(alg_notation_number_map.at(i)), open_sans_font, std::floor(square_size / 5.8f)); auto letter_color = i % 2 == 1 ? sf::Color(254, 232, 209) : sf::Color(83, 120, 99); text.setFillColor(letter_color); text.setPosition(square_size / 18.f + x_offset + static_cast<float>(j) * square_size, square_size / 25.f + y_offset + static_cast<float>(i) * square_size); render_texture.draw(text); render_texture.display(); } } void board::draw_board(sf::RenderWindow &render_window) const { render_window.draw(sf::Sprite(render_texture.getTexture())); } std::string board::get_algebraic_notation(int i, int j) { return column_index_to_alg_notation_letter.at(j) + row_index_to_alg_notation_num.at(i); } /** * get_piece_for_square Takes the algebraic notation for a square and returns the piece belonging on that square. * @param sqr_alg_notation Algebraic notation for the square of interest. * @return Piece belonging on the square provided as input. */ std::string board::get_piece_for_square(const std::string &sqr_alg_notation) { return board_state.at(sqr_alg_notation); }; void board::init_() { x_offset = 0; square_size = static_cast<float>(windowSize.y) / 8.f; render_texture.create(windowSize.x, windowSize.y);
{ "domain": "codereview.stackexchange", "id": 43350, "lm_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++, chess, sfml", "url": null }
c++, chess, sfml set_open_sans_font(); set_alg_notation_letter_map(); set_alg_notation_number_map(); set_initial_board_state(); set_indices_to_alg_notation(); } /** * Methods called by `init_()` appear below */ void board::set_open_sans_font() { if (!open_sans_font.loadFromFile("font/OpenSans-ExtraBold.ttf")) { // error... } } void board::set_alg_notation_letter_map() { alg_notation_letter_map = {{0, "a"}, {1, "b"}, {2, "c"}, {3, "d"}, {4, "e"}, {5, "f"}, {6, "g"}, {7, "h"}}; } void board::set_alg_notation_number_map() { alg_notation_number_map = {{0, 8}, {1, 7}, {2, 6}, {3, 5}, {4, 4}, {5, 3}, {6, 2}, {7, 1}}; } void board::set_initial_board_state() { board_state = { {"a1", "white_rook"}, {"b1", "white_knight"}, {"c1", "white_bishop"}, {"d1", "white_queen"}, {"e1", "white_king"}, {"f1", "white_bishop"}, {"g1", "white_knight"}, {"h1", "white_rook"}, {"a2", "white_pawn"}, {"b2", "white_pawn"}, {"c2", "white_pawn"}, {"d2", "white_pawn"}, {"e2", "white_pawn"}, {"f2", "white_pawn"}, {"g2", "white_pawn"}, {"h2", "white_pawn"}, {"a3", ""}, {"b3", ""}, {"c3", ""}, {"d3", ""}, {"e3", ""}, {"f3", ""}, {"g3", ""}, {"h3", ""}, {"a4", ""}, {"b4", ""}, {"c4", ""}, {"d4", ""}, {"e4", ""}, {"f4", ""}, {"g4", ""}, {"h4", ""}, {"a5", ""}, {"b5", ""}, {"c5", ""}, {"d5", ""}, {"e5", ""}, {"f5", ""}, {"g5", ""}, {"h5", ""}, {"a6", ""}, {"b6", ""}, {"c6", ""}, {"d6", ""}, {"e6", ""}, {"f6", ""}, {"g6", ""}, {"h6", ""}, {"a7", "black_pawn"}, {"b7", "black_pawn"}, {"c7", "black_pawn"}, {"d7", "black_pawn"}, {"e7", "black_pawn"}, {"f7", "black_pawn"}, {"g7", "black_pawn"}, {"h7", "black_pawn"},
{ "domain": "codereview.stackexchange", "id": 43350, "lm_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++, chess, sfml", "url": null }
c++, chess, sfml {"a8", "black_rook"}, {"b8", "black_knight"}, {"c8", "black_bishop"}, {"d8", "black_queen"}, {"e8", "black_king"}, {"f8", "black_bishop"}, {"g8", "black_knight"}, {"h8", "black_rook"} }; } void board::set_indices_to_alg_notation() { row_index_to_alg_notation_num = { {0, "8"}, {1, "7"}, {2, "6"}, {3, "5"}, {4, "4"}, {5, "3"}, {6, "2"}, {7, "1"} }; column_index_to_alg_notation_letter = { {0, "a"}, {1, "b"}, {2, "c"}, {3, "d"}, {4, "e"}, {5, "f"}, {6, "g"}, {7, "h"} }; } pieces.h #pragma once #include "../include/game_loop.h" #include <iostream> #include <codecvt> class pieces { public: pieces(); sf::Color white_piece_color = sf::Color(248, 248, 248); sf::Color black_piece_color = sf::Color(86, 83, 82); char32_t king{}; char32_t queen{}; char32_t rook{}; char32_t bishop{}; char32_t knight{}; char32_t pawn{}; sf::Text get_positioned_sfml_text_graphic_for_piece(const std::string &piece_for_square, float square_size, float x_offset, float y_offset, int i, int j); private: sf::Font free_sarif_font; char32_t get_char32_piece_code(const std::string &piece_name) const; void set_free_sarif_font(); void init_(); sf::Color get_piece_color(const std::string &piece_for_square) const; static std::string get_piece_name(const std::string &piece_for_square); }; pieces.cpp #include <SFML/Graphics.hpp> #include <cmath> #include "pieces.h" pieces::pieces() { init_(); }
{ "domain": "codereview.stackexchange", "id": 43350, "lm_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++, chess, sfml", "url": null }
c++, chess, sfml #include "pieces.h" pieces::pieces() { init_(); } sf::Text pieces::get_positioned_sfml_text_graphic_for_piece(const std::string &piece_for_square, float square_size, float x_offset, float y_offset, int i, int j) { sf::Text text(get_char32_piece_code(get_piece_name(piece_for_square)), free_sarif_font, std::floor(square_size)); text.setFillColor(get_piece_color(piece_for_square)); text.setOutlineColor(sf::Color(0, 0, 0)); text.setOutlineThickness(1); text.setPosition(square_size / 8.f + x_offset + static_cast<float>(j) * square_size, -square_size / 8.f + y_offset + static_cast<float>(i) * square_size); return text; } std::string pieces::get_piece_name(const std::string &piece_for_square) { size_t index_of_first_piece_letter = piece_for_square.find('_') + 1; std::string piece_name = piece_for_square.substr(index_of_first_piece_letter, piece_for_square.size()); return piece_name; } sf::Color pieces::get_piece_color(const std::string &piece_for_square) const { sf::Color piece_color; if (piece_for_square.find("white") != std::string::npos) { piece_color = white_piece_color; } else { piece_color = black_piece_color; }; return piece_color; } char32_t pieces::get_char32_piece_code(const std::string &piece_name) const { if (piece_name == "king") return king; if (piece_name == "queen") return queen; if (piece_name == "rook") return rook; if (piece_name == "bishop") return bishop; if (piece_name == "knight") return knight; if (piece_name == "pawn") return pawn; } void pieces::init_() { set_free_sarif_font();
{ "domain": "codereview.stackexchange", "id": 43350, "lm_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++, chess, sfml", "url": null }
c++, chess, sfml void pieces::init_() { set_free_sarif_font(); king = std::stoul("265A", nullptr, 16); queen = std::stoul("265B", nullptr, 16); rook = std::stoul("265C", nullptr, 16); bishop = std::stoul("265D", nullptr, 16); knight = std::stoul("265E", nullptr, 16); pawn = std::stoul("265F", nullptr, 16); } /** * Methods called by `init_()` appear below */ void pieces::set_free_sarif_font() { if (!free_sarif_font.loadFromFile("font/FreeSerif-4aeK.ttf")) { // error... }; } board_view.h #pragma once #include <SFML/Graphics.hpp> class board_view { public: board_view(const sf::Event &event, sf::RenderWindow &render_window); void configure_and_set_view(); private: const sf::Event &event; sf::RenderWindow &render_window; sf::View view; }; board_view.cpp #include "board_view.h" board_view::board_view(const sf::Event &event, sf::RenderWindow &render_window) : event(event), render_window(render_window) {} void board_view::configure_and_set_view() { auto w = static_cast<float>(event.size.width); auto h = static_cast<float>(event.size.height); view.setSize({w, h}); view.setCenter({ w / 2.f, h / 2.f}); render_window.setView(view); } https://github.com/tarstevs/chess
{ "domain": "codereview.stackexchange", "id": 43350, "lm_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++, chess, sfml", "url": null }
c++, chess, sfml https://github.com/tarstevs/chess Answer: General Observations Right now there is a serious Object Oriented Design flaw, the model of the game and the display are too closely coupled. There are many reasons to separate the game itself from the visual representation. The visual representation only needs to display the board and the pieces, the model needs to know what the pieces are, how those pieces move, any strategy that needs to be known such as basic openings, is this a tournament game so clocks should be shown, etc. One of the reasons for this separation is that it allows you to use the same game engine with different display engines. A second reason for this is to keep each of software piece of the program simpler and reusable. Use the SOLID design principles. SOLID is 5 object oriented design principles. SOLID is a mnemonic acronym for five design principles intended to make software designs more understandable, flexible and maintainable. This will help you design your objects and classes better.
{ "domain": "codereview.stackexchange", "id": 43350, "lm_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++, chess, sfml", "url": null }
c++, chess, sfml The Single Responsibility Principle - A class should only have a single responsibility, that is, only changes to one part of the software's specification should be able to affect the specification of the class. The Open–closed Principle - states software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification. The Liskov Substitution Principle - Objects in a program should be replaceable with instances of their subtypes without altering the correctness of that program. The Interface segregation principle - states that no client should be forced to depend on methods it does not use. The Dependency Inversion Principle - is a specific form of decoupling software modules. When following this principle, the conventional dependency relationships established from high-level, policy-setting modules to low-level, dependency modules are reversed, thus rendering high-level modules independent of the low-level module implementation details. There are multiple design patterns to help prevent tight coupling of the model and the presentation: MVC - Model View Controller MVVM - Model View ViewModel
{ "domain": "codereview.stackexchange", "id": 43350, "lm_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++, chess, sfml", "url": null }
c++, chess, sfml MVC - Model View Controller MVVM - Model View ViewModel The board_view class should contain all presentation code for the board, the board class should only contain the model for the board. The board_state, row_index_to_alg_notation_num and column_index_to_alg_notation_letter members should remain in the board class, most of the other members belong in the board_view class. There should be a piece_view class for presenting the pieces. The current piece class should probably be an abstract base class that all piece classes can inherit from, some of the possible abstractions are the name of the piece, and how the piece moves. The current presentation can't handle tournament play, since there isn't any way to display time clocks. Code Observations Include What is Necessary Right now board.h is missing an include for unordered_map, this is hidden by the fact that SMFL/Graphics.hpp is including it. Don't depend on all inclusive files, make it clear in the code what is necessary. SMFL/Graphics.hpp also seems to include the string header in pieces.cpp. While the game_loop class is not presented it became necessary to look at it, the default constructor for game_loop should be in the header file rather than the game_loop.cpp file. Don't Include What Isn't Necessary It isn't clear why game_loop.h is included in pieces.h, there really shouldn't be any dependency on the game loop for any of the pieces. Complexity The board_state variable is too complex, rather than store all 64 squares, just store the piece with X, and Y positions. The current complexity is required due to the coupling between the display and the model, it isn't necessary for the game.
{ "domain": "codereview.stackexchange", "id": 43350, "lm_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++, chess, sfml", "url": null }
javascript, performance, array Title: Sum up nested array of objects based on keys Question: I have this function that should take some array of objects and sum up the values of the inner objects based on some keys, and conditionally add to it some values from another object. Is there a way to optimize this code? function sumUpKeys(objects, totals = undefined) { const totalsSum = totals?.reduce((totalsAcc, currentTotalsItem) => { return { key1: (totalsAcc.key1 || 0) + (this.computeVal( currentTotalsItem.num || 0, currentTotalsItem.gross ) || 0), key2: (totalsAcc.key2 || 0) + (this.computeVal( currentTotalsItem.num || 0, currentTotalsItem.net ) || 0), }; }, {}); const objectsSum = objects.reduce((objectsAcc, currentObject) => { const itemsSum = currentObject.items.reduce((itemsAcc, currentItem) => { return { key1: (this.computeVal(currentObject.num, currentItem.key1) || 0) + (itemsAcc.key1 || 0), key2: (this.computeVal(currentObject.num, currentItem.key2) || 0) + ( itemsAcc.key2 || 0), }; }, {}); objectsAcc = { key1: (objectsAcc.key1 || 0) + (itemsSum.key1 || 0), key2: (objectsAcc.key2 || 0) + (itemsSum.key2 || 0), }; return objectsAcc; }, {}); // add additional services sum to the monthly charges sum return { key1: (objectsSum.key1 || 0) + (totalsSum?.key1 || 0), key2: (objectsSum.key2 || 0) + (totalsSum?.key2 || 0), }; }
{ "domain": "codereview.stackexchange", "id": 43351, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript, performance, array", "url": null }
javascript, performance, array function computeVal(num, val) { return val ? val * num : undefined; } const objects1 = [ { num: 3, items: [ { key1: 4, key2: 2, }, { key1: 10, key2: 20, }, ], key3: 'aa', }, { num: 4, items: [ { key1: 4, key2: 2, }, ], key3: 'aa', }, ]; const totals1 = [ { num: 2, gross: 10, net: 5, }, { num: 3, gross: 6, net: 12, }, ]; // result with totals const result1 = sumUpKeys(objects1, totals1); // result without totals const result2 = sumUpKeys(objects1); console.log(result1); console.log(result2); Answer: You are returning a new object in each iteration inside the reducers, when you could use just one object for the tallies (see below). The handling of undefined values suggest to me that the underlying data might be invalid, in which case it makes more sense to fix the data and establish validation before insert. Unless of course the values are spec'd to be optional. const sumKeys = (xs, ys = []) => { const sum = {key1: 0, key2: 0} for (const obj of xs) { for (const item of obj.items) { sum.key1 += item.key1 * obj.num sum.key2 += item.key2 * obj.num } } for (const obj of ys) { sum.key1 += obj.gross * obj.num sum.key2 += obj.net * obj.num } return sum }
{ "domain": "codereview.stackexchange", "id": 43351, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript, performance, array", "url": null }
c++, algorithm, graph Title: Number of paths in a randomly labeled complete graph Question: I have a complete graph with n vertices, set W (let's say W = {1,2,3}) and a path path (let's also say path = {1,2,3}). Every edge of my graph is randomly labeled with one of the elements of the set W. For better understanding, that's one of the examples for n = 5. What I need is to find the number of paths path in this graph. All paths for the graph above (11 paths in total). I've developed some kind of algorithm for finding this paths but I want to know are there any chance to improve it? Or maybe I can find this paths in a complete different, more efficient way? #include <iostream> #include <vector> #include <tuple> std::vector<int> path{1,2,3}; // paths we are looking for void finderRec(std::vector<std::tuple<int,int,int>>& edges, int& p, int k, int& TotalNumber){ for (int i = 0; i < edges.size(); ++i){ if (std::get<2>(edges[i]) == path[k] && (p == std::get<0>(edges[i]) || p == std::get<1>(edges[i]))){ if (p == std::get<0>(edges[i]) && k + 1 < path.size()) finderRec(edges, std::get<1>(edges[i]), k + 1, TotalNumber); else if (p == std::get<1>(edges[i]) && k + 1 < path.size()) finderRec(edges, std::get<0>(edges[i]), k + 1, TotalNumber); else TotalNumber++; } } } int pathFinder(std::vector<int>& path, std::vector<std::tuple<int,int,int>>& edges){ int TotalNumber = 0; for (auto& x: edges) if (std::get<2>(x) == path[0]){ finderRec(edges, std::get<0>(x), 1, TotalNumber); finderRec(edges, std::get<1>(x), 1, TotalNumber); } return TotalNumber; }
{ "domain": "codereview.stackexchange", "id": 43352, "lm_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++, algorithm, graph", "url": null }
c++, algorithm, graph std::vector<std::tuple<int,int,int>> generateGraph(int& n, std::vector<int>& W){ std::vector<std::tuple<int,int,int>> edges; int m = (n * (n - 1)) / 2; // number of edges in a complete graph int j = 0; // number of the vertex next to the vertex i int random; int len = W.size(); // length of vector W int sel_elem; for (int i = 1; i <= n; ++i){ j = i + 1; while (j <= n){ random = rand() % len; sel_elem = W[random]; edges.push_back({i,j,sel_elem}); j++; } } return edges; } int main(){ std::cout << "Hello, World!" << "\n"; int n; // number of vertices std::cout << "Input the number of vertices n: "; std::cin >> n; std::vector<int> W{1,2,3}; // set of labels std::vector<std::tuple<int,int,int>> edges = generateGraph(n, W); std::cout << "\n"; std::cout << "Total number of paths = " << pathFinder(path, edges) << "\n"; return 0; } Answer: Prefer struct over std::tuple where possible std::tuple has several drawbacks over declaring your own struct, the most notable one is that you can't name the tuple elements, instead you have to use std::get<> and remember which order you put the elements in. It's a little effort up front to declare a struct, but it will be much easier to work with, and since both the tuple as a whole and its members have names, it's almost self-documenting. Consider: struct Edge { int from; int to; int label; }; Consider using type aliases There are a lot of ints and vectors of things. It would be nice to give things distinct names; this helps document their purpose and can reduce the length of some type names, making the code easier to read. It also makes it easier later on to change the type of things by just changing the alias. Consider: using Node = int; using Label = int; struct Edge { Node from; Node to; Label label; };
{ "domain": "codereview.stackexchange", "id": 43352, "lm_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++, algorithm, graph", "url": null }
c++, algorithm, graph struct Edge { Node from; Node to; Label label; }; using LabelSet = std::vector<Label>; using Path = std::vector<Node>; using Graph = std::vector<Edge>; This way your code will start to look like this: void finderRec(Graph& graph, Node p, Node k, int& TotalNumber) { for (auto& edge: graph) { if (edge.label == path[k] && (p == edge.from || p == edge.to)) { ... Use C++'s random number generators Avoid rand(); it's a C function, it's not a very good random number generator, and you didn't even seed it so it produces the same sequence of "random" numbers every time you start your program. Using the modulo operator to limit the random numbers to a certain range is also not great, since it can introduce a bias in the numbers produced. Since C++11 the C++ standard library comes with some very good random number generator facilities, so prefer to use those instead: std::random_device random_device; std::default_random_engine random_engine(random_device()); std::uniform_int_distribution<int> random_label(0, W.size() - 1); ... sel_elem = W[random_label(random_engine)];
{ "domain": "codereview.stackexchange", "id": 43352, "lm_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++, algorithm, graph", "url": null }
c++, algorithm, graph Improving efficiency Your algorithm is very slow for larger graphs, since each time it finds a suitable edge, it will recurse and scan through all the edges again until it completes a path. That's \$\mathcal{O}(E^3)\$ time complexity, where \$E\$ is the number of edges, which in itself is in the order of the number of nodes squared. What would greatly help is if we didn't have to scan all the edges. If you would store the graph as an adjecency list, then in finderRec() you would only have to check the edges directly connected to the node p. It might also be possible to gain some performance improvement by sorting the adjacency list on the label, such that you can easily find those edges your are really interested in. Whether that pays off probably depends on the size of the graph and the number of distinct labels. Avoid global variables It's a bit weird that you have only path as a global variable. I would make this a parameter of pathFinder() and finderRec(). I recommend avoiding global variables where possible, as they can become problematic in larger projects, where they pollute the global namespace, and if they are not const they are unsafe if you have reentrant functions and multiple threads using them. Make variables and references const where appropriate When you pass parameters by reference and they should not be changed, make them const references. This allows the compiler to optimize the code more, and will also catch programming errors if you accidentily do change some parameter that should have been kept unchanged. Make functions static where appropriate Functions that are only used within the same source file should be made static. This avoids polluting the global namespace, and might allow the compiler to make more optimizations. main() itself should not be static though. Naming things
{ "domain": "codereview.stackexchange", "id": 43352, "lm_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++, algorithm, graph", "url": null }
c++, algorithm, graph Naming things Try to avoid one-character names for variables, unless it's something very commonly used, like i and j for loop indices, or x/y/z for coordinates. I would suggest the following changes:
{ "domain": "codereview.stackexchange", "id": 43352, "lm_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++, algorithm, graph", "url": null }
c++, algorithm, graph pathFinder() -> countPaths(), as it only returns the number of paths found. TotalNumber -> count n -> size edges -> graph, especially if you change it from a list of edges to a list of nodes with adjacency lists W -> labels
{ "domain": "codereview.stackexchange", "id": 43352, "lm_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++, algorithm, graph", "url": null }
python, algorithm Title: Solution to arithmetic arranger from freecodecamp Question: I tried my hand at the freecodecamp python algorithm and I came up with a solution for the first question but need help refactoring it. Here is the arithmetic arranger question click here to access the question and the detailed question can be found below: Students in primary school often arrange arithmetic problems vertically to make them easier to solve. For example, "235 + 52" becomes: 235 + 52 ----- Create a function that receives a list of strings that are arithmetic problems and returns the problems arranged vertically and side-by-side. The function should optionally take a second argument. When the second argument is set to True, the answers should be displayed. Example Function Call: arithmetic_arranger(["32 + 698", "3801 - 2", "45 + 43", "123 + 49"]) Output: 32 3801 45 123 + 698 - 2 + 43 + 49 ----- ------ ---- ----- Function Call: arithmetic_arranger(["32 + 8", "1 - 3801", "9999 + 9999", "523 - 49"], True) Output: 32 1 9999 523 + 8 - 3801 + 9999 - 49 ---- ------ ------ ----- 40 -3800 19998 474 Rules The function will return the correct conversion if the supplied problems are properly formatted, otherwise, it will return a string that describes an error that is meaningful to the user. Situations that will return an error:
{ "domain": "codereview.stackexchange", "id": 43353, "lm_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, algorithm", "url": null }
python, algorithm Situations that will return an error: If there are too many problems supplied to the function. The limit is five, anything more will return: Error: Too many problems. The appropriate operators the function will accept are addition and subtraction. Multiplication and division will return an error. Other operators not mentioned in this bullet point will not need to be tested. The error returned will be: Error: Operator must be '+' or '-'. Each number (operand) should only contain digits. Otherwise, the function will return: Error: Numbers must only contain digits. Each operand (aka number on each side of the operator) has a max of four digits in width. Otherwise, the error string returned will be: Error: Numbers cannot be more than four digits. If the user supplied the correct format of problems, the conversion you return will follow these rules: There should be a single space between the operator and the longest of the two operands, the operator will be on the same line as the second operand, both operands will be in the same order as provided (the first will be the top one and the second will be the bottom. Numbers should be right-aligned. There should be four spaces between each problem. There should be dashes at the bottom of each problem. The dashes should run along the entire length of each problem individually. (The example above shows what this should look like.) The solution can be found below: import operator ops = {"+": operator.add, "-": operator.sub, "*": operator.mul} def arithmetic_arranger(problems, solver=False): # Check problems does not exceed the given max(5) if len(problems) > 5: return "Error: Too many problems." toptier = "" bottomtier = "" lines = "" totals = "" for n in problems: fnumber = n.split()[0] operator = n.split()[1] snumber = n.split()[2]
{ "domain": "codereview.stackexchange", "id": 43353, "lm_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, algorithm", "url": null }
python, algorithm # Handle errors for input: if operator != "+" and operator != "-": return "Error: Operator must be '+' or '-'." if not fnumber.isdigit() or not snumber.isdigit(): return "Error: Numbers must only contain digits." if len(fnumber) > 4 or len(snumber) > 4: return "Error: Numbers cannot be more than four digits" # Get total of correct function total = ops[operator](int(fnumber), int(snumber)) # Get distance for longest operator operatorDistance = max(len(fnumber), len(snumber)) + 2 snumber = operator + snumber.rjust(operatorDistance - 1) toptier = toptier + fnumber.rjust(operatorDistance) + (4 * " ") bottomtier = bottomtier + snumber + (4 * " ") lines = lines + len(snumber) * "_" + (4 * " ") totals = totals + str(total).rjust(operatorDistance) + (4 * " ") if solver: print(toptier) print(bottomtier) print(lines) print(totals) if __name__ == "__main__": arithmetic_arranger(["32 + 698", "3801 - 2", "45 + 43", "123 + 49"])
{ "domain": "codereview.stackexchange", "id": 43353, "lm_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, algorithm", "url": null }
python, algorithm if __name__ == "__main__": arithmetic_arranger(["32 + 698", "3801 - 2", "45 + 43", "123 + 49"]) Answer: Use PEP484 type hints. The too-many-problems and too-many-digits constraints are not good ones, but whatever: we'll keep them because the problem asks so. You call split() three times when you should only call it once and tuple-unpack to three substrings. You should not make literal comparisons of the operator to potential strings, nor should you include + and - verbatim in the error message. Instead, derive these from your ops dictionary (you adding it was a good idea!) Where possible, pass validation problems from subroutines to your main routine using exceptions. Your len(fnumber) is technically not correct if they expand the problem to allow negative numbers. The minus sign constitutes another character. They want you to limit digit count, not character count. I think a safer check would be comparing to abs() >= 1e4. fnumber and snumber (short for "first" and "second") are non-obvious, and should use something else: number_1, or more easily just x and y since it's pretty obvious what's going on. One potential refactor could look like: Create a simple class representing a problem On the class, have a parse that loads a class instance from a string If parse fails with a ValueError, the string isn't parseable: bail. If parse succeeds but validate() fails, the string is parseable but invalid: bail. Write a formatting method that returns a tuple of lines for one problem. In your upper method, zip the lines of all of the problems together, join the lines with \n and the groups among each line with however many spaces you want (looks like 4). Suggested import operator from typing import Sequence, NamedTuple, Literal ops = {"+": operator.add, "-": operator.sub} class Problem(NamedTuple): x: int y: int op: Literal['+', '-'] @classmethod def parse(cls, s: str) -> 'Problem': x, op, y = s.split()
{ "domain": "codereview.stackexchange", "id": 43353, "lm_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, algorithm", "url": null }
python, algorithm @classmethod def parse(cls, s: str) -> 'Problem': x, op, y = s.split() for n in (x, y): if not n.isdigit(): raise ValueError('Error: Numbers must only contain digits.') return cls(x=int(x), y=int(y), op=op) def validate(self) -> None: for n in (self.x, self.y): if abs(n) >= 1e4: raise ValueError('Error: Number cannot be more than four digits.') if self.op not in ops: raise ValueError( 'Error: Operator must be ' + ' or '.join(f"'{o}'" for o in ops.keys()) ) def format_lines(self, solve: bool = False) -> tuple[str, ...]: longest = max(self.x, self.y) width = len(str(longest)) lines = ( f'{self.x:>{width + 2}}', f'{self.op} {self.y:>{width}}', f'{"":->{width+2}}', ) if solve: lines += ( f'{self.answer:>{width+2}}', ) return lines @property def answer(self) -> int: return ops[self.op](self.x, self.y) def arithmetic_arranger(problem_strings: Sequence[str], solve: bool = False) -> None: if len(problem_strings) > 5: print('Error: Too many problems.') return try: problems = [Problem.parse(s) for s in problem_strings] for problem in problems: problem.validate() except ValueError as e: print(e) return lines = zip(*(p.format_lines(solve) for p in problems)) print( '\n'.join( ' '.join(groups) for groups in lines ) ) if __name__ == "__main__": arithmetic_arranger(( "32 + 698", "3801 - 2", "4 + 4553", "123 + 49", "1234 - 9876" ), solve=True)
{ "domain": "codereview.stackexchange", "id": 43353, "lm_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, algorithm", "url": null }
python, beginner, python-3.x, console, quiz Title: Python CLI math game Question: I'm a self-taught programmer starting out with Python and my latest project is this game: It runs in the console, displays an equation, takes the user's answer, and increases your score if it's correct. Every level has 5 questions, and the operands get bigger each level. At the end of each level. It asks if you want to continue or quit. I managed to get it down to 41 SLOC but I want to know if there are ways I don't know about to make it even shorter. # ---- IMPORTS ---- from random import randint, choice from re import search from subprocess import run # ---- VARIABLES ---- multis = [ -1, 1 ] # "Multipliers" ops = [ "+", "-", "*", "/" ] # "Operators" score = 0 level = 1 # ---- FUNCTIONS ---- def setQuestion(): global answer global userInput # Set the two operands and operator. oper1 = randint( (level * 5), (level * 10) ) * choice( multis ) # "Operand 1" oper2 = randint( 1, abs(oper1) ) * choice( multis ) # "Operand 2" opsCheck = randint( 0, 3 ) # If the operator is division, subtract the modulus from {oper1} so that # the quotient is an integer. if( opsCheck == 3 ): if( oper1 < 0 ): oper1 -= ( abs(oper1) % oper2 ) * -1 else: oper1 -= oper1 % oper2 # Display the question and get the answer. userInput = input( (" {} {} {} = ?\n A: ").format(oper1, ops[opsCheck], oper2) ) # Set global {answer} to the solution. answer = eval( ("{}{}{}").format(oper1, ops[opsCheck], oper2) ) def runLevel(): global score # Each level has 5 questions for i in range( 5 ): # Clear the screen each level (Unix-Like). run( "clear", shell = True ) # Print the header and run the question. print( ("\t---- LEVEL {}: ----\n").format(level) ) setQuestion()
{ "domain": "codereview.stackexchange", "id": 43354, "lm_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, python-3.x, console, quiz", "url": null }
python, beginner, python-3.x, console, quiz # If correct, increase score. If not, display correct answer. if( int(userInput) == answer ): print( "\n Correct!" ) score += 1 else: print( ("\n Incorrect. Sorry.\n The answer was {}.").format(answer) ) # Wait for user input to move on to the next question. input( "\n (Press any key to advance)" ) # ---- MAIN ---- # Program will run continuously while( True ): # Go through one level runLevel() # Clear and display "Level Complete" Screen and player score. run( "clear", shell = True ) print( ("\t--- LEVEL {} COMPLETE! ---").format(level) ) userInput = input( ("\n Your score is {}\n Continue? (y/n) ").format(score) ) # If user enters "y" or "Y", increase global {level} by one and restart. if( search("y|Y", userInput) ): level += 1 continue # If user does not enter "y" or "Y", clear screen and terminate. run( "clear", shell = True ) exit() ``` Answer: I want to know if there are ways I don't know about to make it even shorter.
{ "domain": "codereview.stackexchange", "id": 43354, "lm_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, python-3.x, console, quiz", "url": null }
python, beginner, python-3.x, console, quiz Shorter isn't always better, and this is not code golf. Strive for good code, and the short code will come naturally as a side-effect. Your IMPORTS and VARIABLES comments should be deleted. Your multis are really just signs. But you don't need to random.choice on these; you can get a sign directly from randrange. setQuestion should first of all be set_question by PEP8, and also doesn't "set the question"; it "asks the question" so should be renamed. score and level should not be global. opsCheck is not a "check", it's an operator index. But you don't need to choose an index; all you need to do is choose a key of a dictionary where the keys are your existing ops values and the values are functions from operators. The modulus magic is nasty. I would sooner choose two operands, find their quotient, and then multiply back the quotient to get a perfect multiple. Get into the habit of using f-strings instead of format() calls when they're suitable (which is frequent). Never use eval. There's basically never a use case that calls for it, particularly in beginner code. Your clear and your bonus newlines sprinkled through the output are harming, not helping. Good console UI design shows output in well-organised paragraphs, and those paragraphs don't vanish between levels or the end of the program. Related: the question prompt should not be split across two different lines. Pressing a key to continue is really only helpful if there's a flood of text risking exceeding the buffer height, and that isn't the case here; so don't do it. Consider making [y] the default answer for whether the user wants to continue; convention is to show the default in brackets and assume that default if the user just presses enter. Regexes are not appropriate here. You can just check the first letter of the response. Avoid exit(); write a main() function and return from it when you're done. Suggested from itertools import count from random import choice, randint, randrange import operator
{ "domain": "codereview.stackexchange", "id": 43354, "lm_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, python-3.x, console, quiz", "url": null }
python, beginner, python-3.x, console, quiz ops = { "+": operator.add, "-": operator.sub, "*": operator.mul, "/": operator.floordiv, } def rand_sign() -> int: return randrange(-1, 2, 2) def ask_question(level: int) -> tuple[ int, # user answer int, # actual answer ]: x = randint(a=level*5, b=level*10) * rand_sign() y = randint(a=1, b=abs(x)) * rand_sign() op = choice(tuple(ops.keys())) if op == '/': answer = x//y x = answer*y else: answer = ops[op](x, y) user_input = int(input(f"{x} {op} {y} = ")) return user_input, answer def run_level(level: int, n_questions: int = 5) -> int: print(f"---- LEVEL {level}: ----") score_change = 0 for _ in range(n_questions): user_answer, actual_answer = ask_question(level) if user_answer == actual_answer: print("Correct!") score_change += 1 else: print(f"Incorrect. Sorry. The answer was {actual_answer}.") return score_change def main() -> None: score = 0 for level in count(1): score += run_level(level) print( f"--- LEVEL {level} COMPLETE! ---" f"\n Your score is {score}" ) user_input = input('Continue [y]/n? ').lower() if user_input.startswith('n'): break print() if __name__ == '__main__': main() Output ---- LEVEL 1: ---- 8 / 8 = 1 Correct! 7 * -6 = 99 Incorrect. Sorry. The answer was -42. 7 * 4 = 28 Correct! 9 / -3 = -3 Correct! -8 / -2 = 4 Correct! --- LEVEL 1 COMPLETE! --- Your score is 4 Continue [y]/n? y ---- LEVEL 2: ---- -12 + 4 = -8 Correct! -11 - 9 = ... ^ This demonstrates what I mean when I say "paragraphs". All of level 1 is grouped together, and the only time there is a blank line is between levels.
{ "domain": "codereview.stackexchange", "id": 43354, "lm_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, python-3.x, console, quiz", "url": null }
javascript, beginner, node.js, numerical-methods Title: Three efficient JavaScript functions that converge to pi extremely fast Question: I am learning JavaScript and decided to translate my Python scripts into JavaScript. Approximations of π are extremely popular programming challenges and I am sure they must be a staple of the challenges one must overcome to learn a programming language. I am sure you must be bored of this kind of questions but I have tested many algorithms and selected the algorithms that converge the fastest: > console.log(pi(50)) 3.1415926535897922 undefined > console.log(BBP(11)) 3.141592653589793 undefined > console.log(Ramanujan(3)) 3.141592653589793 undefined > The first function takes 50 iterations to generate the closest value before precision loss, the second function takes only 11 iterations to get the closest approximation of π possible within the IEEE-754 Binary64 (double) format, whereas the last function only takes THREE iterations! Code function pi (t) { function db (x) { if (x <= 0) { return 1 } return x * db(x - 2) } let term = (x) => db(2 * x) / db(2 * x + 1) * 0.5 ** x const stack = [] for (let i=0; i<t; i++) { stack.push(term(i)) } return 2 * stack.reduce((s, n) => s + n, 0) } function BBP (t) { const stack = [] for (let k=0; k<t; k++) { let a = 1/16**k let b = 4/(8*k+1) let c = 2/(8*k+4) let d = 1/(8*k+5) let e = 1/(8*k+6) let item = a * (b - c - d - e) stack.push(item) } return stack.reduce((s, n) => s + n, 0) } function Ramanujan (t) { function factorial (n) { var f = 1 for (let i=1; i<=n; i++) { f *= i } return f } let term = (k) => (factorial(4*k) * (1103 + 26390*k)) / (factorial(k)**4 * 396**(4*k)) const stack = [] for (let i=0; i<t; i++) { stack.push(term(i)) } var sum = stack.reduce((a, b) => a + b, 0) return 1 / (2 * 2**.5 * sum/9801) }
{ "domain": "codereview.stackexchange", "id": 43355, "lm_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, beginner, node.js, numerical-methods", "url": null }
javascript, beginner, node.js, numerical-methods console.log(pi(50)) console.log(BBP(11)) console.log(Ramanujan(3)) How can they be improved? (I wrote them all within half an hour.)
{ "domain": "codereview.stackexchange", "id": 43355, "lm_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, beginner, node.js, numerical-methods", "url": null }
javascript, beginner, node.js, numerical-methods Answer: In terms of more precision, I can't really help there... But, in terms of general code styling and performance, I'd be happy to give some pointers. This is good code, but slightly inconsistent (which is understandable, since you're new to JS!). I'm going to mainly focus on the Ramanujan function, but the advice can be applied in other areas too. Styling You seem to keep switching between var, let and const and using them in inappropriate contexts. var is the older syntax, and let and const are both newer. There are some differences to let and var under the hood, mainly surrounding scoping: let is block scoped, var is function scoped. const is used to annotate immutable variables, but they're not truly immutable all the time... Another weird remnant of poor language design choices. You can use Object.freeze() to get (more)true immutability. I'd stick to using let as it's the way that variables should have been designed in the first place. A good article explaining the pitfalls of var: https://hackernoon.com/why-you-shouldnt-use-var-anymore-f109a58b9b70 Next, const. You originally assigned an empty array as a const, then pushed values to it. Whilst this is technically allowed in JS, it's not great practice. A constant should remain immutable. Alongside that, you also used the arrow function syntax and stored it's name using the let keyword... Which implies that it may be mutable in the future, which of course is not the case :) Performance The runtime of this algorithm is fast, but there's 3 things that I picked up on that will improve it's performance. Firstly, when you calculate the terms, you push each of them into an array. Once the loop finishes, you iterate over that array and then add each of them together (in the reduce function). Whilst this works, it's sub-optimal, as you have to run 2 loops, when you can do it all in the first loop by simply adding each result to a running total.
{ "domain": "codereview.stackexchange", "id": 43355, "lm_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, beginner, node.js, numerical-methods", "url": null }
javascript, beginner, node.js, numerical-methods Secondly, the return function calculates: 2 * 2 ** 0.5 before returning... This is a bit of a waste, as the values are not dynamic- and so the result of that calculation could be inserted as a constant, so that those operations are not wasted at run time. Finally, and this one's extremely pedantic (and slightly mystical), when raising k to the power n, I've found that k ** n is slightly slower than Math.pow(k, n). This one might not even count as advice to be honest, as the speed gain is absolutely minimal. Refactored function Ramanujan2(t) { function factorial(n) { let f = 1; for (let i=1; i<=n; i++) { f *= i; } return f; }
{ "domain": "codereview.stackexchange", "id": 43355, "lm_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, beginner, node.js, numerical-methods", "url": null }
javascript, beginner, node.js, numerical-methods // In my experience, Math.pow seems to be faster than ** const term = k => (factorial(4*k) * (1103 + 26390*k)) / (Math.pow(factorial(k), 4) * Math.pow(396, 4*k)); // Rather than allocate each term to an array, then iterate that array and // add each number; simply add the numbers to a total as they're calculated. // More efficient on memory, and slightly faster as only one iteration of the // set is required. let sum = 0; for (let i=0; i<t; i++) { sum += term(i); } // Factored out two operations ( * and a ** ) into a constant representing // the actual value calculated... so it's a fixed value every time. return 1 / ( 2.8284271247461903 * sum/9801 ); } Finally, if you ever need to get the value of Pi outside of this learning exercise, you can use the Math.PI constant provided by default.
{ "domain": "codereview.stackexchange", "id": 43355, "lm_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, beginner, node.js, numerical-methods", "url": null }
c#, strings Title: Split string by last occurence of character within a range Question: So I would like to split a string in two by the last space within the first 40 characters, the best solution I could think of: public static void Main(string[] sargs) { var address = "...Are included in two of the " + "substrings. If you want to exclude the " + "period characters, you can add the period..."; var splitIndex = address.LastIndexOf(' ', 40); var address1 = address.Substring(0, splitIndex); var address2 = address.Substring(splitIndex + 1, address.Length - splitIndex - 1); Console.WriteLine(address1); Console.WriteLine(address2); } Is there a better, faster or more elegant way of doing it? Answer: You can use the index and range operators instead of SubString calls var address = "...Are included in two of the " + "substrings. If you want to exclude the " + "period characters, you can add the period..."; var splitIndex = address.LastIndexOf(' ', 40); Console.WriteLine(address[..splitIndex]); Console.WriteLine(address[(splitIndex+1)..]);
{ "domain": "codereview.stackexchange", "id": 43356, "lm_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#, strings", "url": null }
c++, object-oriented, homework, c++17, binary-tree Title: Create and view a family tree Question: I have an assignment due Friday to make a family tree. Started to code in January. My reviews from the teacher for this code was that the use of pointers was horrendous and it wasn't OOP enough. This code compiles and works. What can I do better to make the code more object oriented? The best commentary was "It's horrendous to see pointers in the wild like this". At the same time, he taught us, so my assignment partner and I don't know what else to do. It seems like every time we ask for help, the code gets more complicated than necessary and we go further away from C++. I know that I have to create a node that takes in a person, but is there anything else? This code is made to let a user put in him/herself and to add parents, grandparents etc. You can edit, delete and search. class person { private: public: std::string firstName; // variable to hold the firstname of the person std::string lastName; // variable to hold the lastname of the person int yearOfBirth; // variable to hold the year of birth int age; // variable to hold the age of person int alive; // variable to hold data int sex; // variable to hold the gender of the person person *left; person *right; person(); ~person(); void getData(); }; person::person() // constructor outside the class { left = right = nullptr; firstName = ""; lastName = ""; yearOfBirth = 0; age = 0; alive = 0; sex = 0; } person::~person() = default; //destructor of person::person (check if this code runs and are okey!!) void ignoreLine() { std::cin.clear(); std::cin.ignore(INT_MAX, '\n'); } void person::getData() // get information about a person { char gender;
{ "domain": "codereview.stackexchange", "id": 43357, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, object-oriented, homework, c++17, binary-tree", "url": null }
c++, object-oriented, homework, c++17, binary-tree void person::getData() // get information about a person { char gender; std::cout << "\nFirstname of the person: " << std::endl; std::cin >> firstName; std::cout << "Lastname of the person: " << std::endl; std::cin >> lastName; std::cout << "Age of " << firstName << ": " << std::endl; while (!(std::cin >> age) or (age < 0) or std::cin.fail()) // check if the inputs only contains positives int. { std::cin >> age; std::cout << "Only positives number allowed: " << std::endl; ignoreLine(); } std::cout << "What is the sex of " << firstName << " (m/f): " << std::endl; std::cin >> gender; switch (gender) // all other int, char etc, than m/M is considered as female. Maybe change later, but good for now. { case 'm': case 'M': sex = 1; break; } ignoreLine(); // "pause" the program until the user press "Enter" } class familyTree { private: public: person *root; person *search(const std::string&); person *traverseLeft(person *, const std::string&); person *traverseRight(person *, const std::string&); familyTree(); void addNewPerson(); void addMother(person *, person *); void addFather(person *, person *); static void show(person *); void printInOrder(person *, int); }; familyTree::familyTree() { root = nullptr; } void familyTree::addMother(person *a, person *b) // to add b as the mother of a { if (a->left == nullptr) { a->left = b; } else { addMother(a->left, b); } } void familyTree::addFather(person *a, person *b)// to add b as the father of a { while (a->right != nullptr) a = a->right; a->right = b; } person *familyTree::traverseLeft(person *ptr, const std::string& person) { ptr = ptr->left; while (ptr != nullptr) { if ((ptr->firstName) == person) { return ptr; }
{ "domain": "codereview.stackexchange", "id": 43357, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, object-oriented, homework, c++17, binary-tree", "url": null }
c++, object-oriented, homework, c++17, binary-tree else if (traverseRight(ptr, person) != nullptr) { return traverseRight(ptr, person); } else { ptr = ptr->left; } } return nullptr; } person *familyTree::traverseRight(person *ptr, const std::string& person) { ptr = ptr->right; while (ptr != nullptr) { if ((ptr->firstName) == person) { return ptr; } else if (traverseLeft(ptr, person) != nullptr) { return traverseLeft(ptr, person); } else ptr = ptr->right; } return nullptr; } void familyTree::addNewPerson() { auto *temp = new struct person; temp->getData(); std::string personChild; if (root == nullptr) { std::cout << "\nFirst person added to the family!" << std::endl; root = temp; } else // if there exists a person in the tree, add the new person as a relative to a previous { std::cout << "Enter the name of the person " << temp->firstName << " is the parent to: " << std::endl; std::cin >> personChild; if (familyTree::search(personChild)) //tests if the person entered is found int the tree, if yes it continues. { int opt; std::cout << "\nWhat is the family relation? " << std::endl; std::cout << "(1) if " << temp->firstName << " is the Mother to " << personChild << std::endl; std::cout << "(2) if " << temp->firstName << " is the Father to " << personChild << std::endl; std::cout << "Enter: " << std::endl; std::cin >> opt; ignoreLine(); // "pause" the program until the user press "Enter"
{ "domain": "codereview.stackexchange", "id": 43357, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, object-oriented, homework, c++17, binary-tree", "url": null }
c++, object-oriented, homework, c++17, binary-tree while (std::cin.fail() or opt < 1 or opt > 2) { std::cout << "\nOnly a number of 1 or 2 is accepted!" << std::endl; std::cout << "Enter: " << std::endl; std::cin >> opt; ignoreLine(); // "pause" the program until the user press "Enter" } switch (opt) { case 1: addMother(search(personChild), temp); std::cout << temp->firstName << " is now added as the mother!" << std::endl; break; case 2: addFather(search(personChild), temp); std::cout << temp->firstName << " is now added as the father!" << std::endl; break; } } // else // { // maybe make a code that loops the "enter name" until it's correct? Or just go straight back to main menu? // } } } void familyTree::printInOrder (person *person, int space) //print its persons using in order traversal { auto count = 7; //using count for how much space between generations (horizontal) space += count; if (person != nullptr) { if(person->left != nullptr) { printInOrder(person->left, space); } std::cout << std::endl; for (int i = count; i < space; i++) std::cout << " "; std::cout << person->firstName << "\n"; if(person->right != nullptr) { printInOrder(person->right, space); } } else { std::cout << "No tree exist!" << std::endl; ignoreLine(); // "pause" the program until the user press "Enter" return; } } person *familyTree::search(const std::string& per) // to search for a person { person *ptr = root; if ((ptr->firstName) == per) { return ptr; }
{ "domain": "codereview.stackexchange", "id": 43357, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, object-oriented, homework, c++17, binary-tree", "url": null }
c++, object-oriented, homework, c++17, binary-tree if ((ptr->firstName) == per) { return ptr; } else if (traverseRight(root, per) != nullptr) { return traverseRight(root, per); } else if (traverseLeft(root, per) != nullptr) { return traverseLeft(root, per); } else { std::cout << "\nNo person found with the given name" << std::endl; ignoreLine(); // "pause" the program until the user press "Enter" return nullptr; } } void familyTree::show(person *ptr) // to show the information of a particular person { std::string sex = "Female"; if (ptr->sex) { sex = "Male"; } std::cout << "\nName: " << ptr->firstName << " " << ptr->lastName << std::endl; std::cout << "Age: " << ptr->age << std::endl; std::cout << "Sex: " << sex << std::endl; std::cin.ignore(); } void showMainMenu() // hold the output for the main menu { std::cout << "Welcome" << std::endl; std::cout << "Please enter a number for your choice below:\n" << std::endl; std::cout << "(1) Add new person to tree" << std::endl; std::cout << "(2) Show information for a person" << std::endl; std::cout << "(3) Print complete family-tree" << std::endl; std::cout << "(4) Used for testing new choices" << std::endl; std::cout << "(0) Quit" << std::endl; std::cout << "\nYour choice: " << std::endl; } int main() { familyTree fT; // used to access/init. familytree class. int option, exit = 0; std::string temp, str; while (exit == 0) { showMainMenu(); std::cin >> option; while (std::cin.fail()) { ignoreLine(); std::cout << "\nOnly a number between 0 and 10 is allowed: "; std::cin >> option; }
{ "domain": "codereview.stackexchange", "id": 43357, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, object-oriented, homework, c++17, binary-tree", "url": null }
c++, object-oriented, homework, c++17, binary-tree switch (option) { case 1: fT.addNewPerson(); break; case 2: std::cout << "Enter name of person to show information: "; std::cin >> temp; fT.show(fT.search(temp)); break; case 3: fT.printInOrder(fT.root, 0); break; case 4: /* n/a */ break; case 0: exit = 1; break; } std::cout << "\nPress enter to continue.." << std::endl; ignoreLine(); } return 0; } Answer: This is by no means exhaustive, more a list of general highlights on what to focus on rather that deep analysis of the implementation. Some general pieces of advice first:
{ "domain": "codereview.stackexchange", "id": 43357, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, object-oriented, homework, c++17, binary-tree", "url": null }
c++, object-oriented, homework, c++17, binary-tree Use some coding conventions that easily allows identification of types, variables etc. What is person here: person *familyTree::traverseRight(person *ptr, const std::string& person)? Well, it ambiguous, or at least context-dependent. Writing like this is huge disservice to future maintainers of the code. Raw pointers are generally evil especially when taking modern C++ into account. However, using smart ones for trees, lists etc. can lead to stack overflow upon destruction of the data structure if that one is too big, due to destructors being called recursively. So it's either manual resource management with all its drawbacks, or correctness by default at the expense of limited size. This is for the author to decided. I can't tell that for you. Incorporate some testing framework, be it Catch2, Google Test, BoostTest; write unit tests to protect the existing functionalities. Even superficially tested code becomes tremendously easier to review and maintain. (not entirely review related) Familiarize yourself with version control and develop a habit of committing often, it saves a lot of time especially when testing new features as reverting to previous revision gets easier. That sentence: the code gets more complicated than necessary and we go further away from C++. suggests you have troubles tracking what has been changed. Any VCS should make that way easier.
{ "domain": "codereview.stackexchange", "id": 43357, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, object-oriented, homework, c++17, binary-tree", "url": null }
c++, object-oriented, homework, c++17, binary-tree As for the code itself: First, I'd try to define responsibilities of classes and split them accordingly. Class person has mixed responsibilities: it's both the person as well as a tree node. Let's extract the person first: If it's stripped of its node responsibilities it becomes way easier to maintain; all its special operations (move, copy, its respectable assignments etc.) become more automatic. If (de)serialization should be part of the class's member function or a freestanding one is an open question. I tend to prefer the freestanding ones (by overloading stream operators << and >>), but that's a matter of style, convention, taste and needs... you name it. I skipped that for brevity. Also, consider using more suitable datatypes, e.g. boolean for alive, enumeration for sex, maybe unsigned instead of int for year (unless you're reaching BC; or maybe even choose a completely distinct type? I don't know, depends on your exact case). Personally I'd go +- this way. struct Person { enum struct Sex{male, female}; std::string firstName{}; // variable to hold the firstname of the person std::string lastName{}; // variable to hold the lastname of the person unsigned yearOfBirth{}; // variable to hold the year of birth unsigned age{}; // variable to hold the age of person bool alive{}; // variable to hold data Sex sex{}; // variable to hold the gender of the person };
{ "domain": "codereview.stackexchange", "id": 43357, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, object-oriented, homework, c++17, binary-tree", "url": null }
c++, object-oriented, homework, c++17, binary-tree If person should be default-constructible - hard to say out of the blue. Yes, should you plan to read it from streams. Otherwise - I'd say no. The next step would be fitting that into the tree. BTW, as far as I understand family trees, they don't have to be binary ones, but let's assume the whole assignment is about binary trees so it's been designed like that wittingly ;) Also, I'm not sure if you're supposed to use templates or not. Assuming a non-templated version: struct FamilyTreeNode { Person person{}; FamilyTreeNode* left; FamilyTreeNode* right; }; Note I'm using raw pointers here. No problem with using the smart ones, at the price of potential stack-related problems. And that can be enclosed inside a family tree: struct FamilyTree { private: FamilyTreeNode* root; //I wouldn't make it public, but your call //also, maybe root doesn't necessarily has to be heap-allocated, but let's stick to that to keep it consistent... ////the rest Now, as for family tree's interface: I would need to dig through that thoroughly and it is also highly dependent on ones needs. Hard for me to say if your preference is to operate directly on people (Person class) or maybe tree's nodes. I'd probably go the node way, making it somewhat C++- iterator-ish. Also, keep const-correcntess in mind. E.g. method: person *search(const std::string&); should probably have its const overload, i.e. const person *search(const std::string&); const (or FamilyTreeNode instead of person in this case) should need to look for a person only for printing.
{ "domain": "codereview.stackexchange", "id": 43357, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, object-oriented, homework, c++17, binary-tree", "url": null }
c#, beginner Title: Calculate sum and count of even and odd numbers Question: Started learning C# second time. I have written a console program to calculate sum and count of even and odd numbers. Provided code : using System; namespace Studying_ { class Program { static void Main(string[] args) { uint evenNumbersCount = 0; uint oddNumbersCount = 0; int sum = 0; Console.WriteLine("Enter the first number in the range to find out it odd or even. The program won't count numbers you entered in the sum"); int numberOne = int.Parse(Console.ReadLine()); Console.WriteLine("Enter the second number"); int numberTwo = int.Parse(Console.ReadLine()); if (numberTwo < numberOne) { int a = numberTwo; numberTwo = numberOne; numberOne = a; } while(numberOne < numberTwo - 1) { numberOne++; int result = numberOne % 2; sum += numberOne; switch (result) { case 0: evenNumbersCount++; break; case 1: oddNumbersCount++; break; } } Console.WriteLine("Sum - " + sum + " | Even - " + evenNumbersCount + " | Odd - " + oddNumbersCount); Console.ReadKey(); } } } Input : 2, 5 Output : "Sum - 7 | Even - 1 | Odd - 1 2 and 5 aren't counted Is this code good? Can I improve it or optimize? P.S. Sorry for my english and if I did something off-topic. Let me know if something is wrong.
{ "domain": "codereview.stackexchange", "id": 43358, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c#, beginner", "url": null }
c#, beginner Answer: The naming could be better. numberOne, numberTwo and result does not tell anything about what these numbers represent. Better rangeStartExclusive and rangeEndExclusive. The ...Exclusive makes it clear that the bounds will not be counted. I also would use a for-loop. This is the standard way of looping a number range. It also allows us to easily define a loop variable. The problem of incrementing numberOne is that it makes it a range bound and a running variable at the same time. This double role decreases readability. Instead of an int result, I would use a Boolean telling its meaning. for (int n = rangeStartExclusive + 1; n < rangeEndExclusive; n++) { bool isEven = n % 2 == 0; if (isEven) { evenNumbersCount++; } else { oddNumbersCount++; } sum += n; } Alternatively, you could keep your original implementation and instead rename result to remainder. It is okay to give our number a non-descriptive name like i or n, often used in math to denote a whole number. i is often used for indexes. To keep the declaration and use of isEven close together, I have moved sum += n to the end of the loop. It looks strange if you first calculate result, then calculate an unrelated sum and only then use result. Why use uint for the count of even and odd numbers? This count will always be smaller than the range bounds given as int. The maximum uint is about the double of the maximum int. However, the sum could exceed the maximum int. The sum of all whole numbers starting at 1 and up to n is n * (n + 1) / 2. When starting counting at 1, this limits the maximum number at 65,535. Therefore, it would make sense to use long for the sum.
{ "domain": "codereview.stackexchange", "id": 43358, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c#, beginner", "url": null }
c++ Title: "Fast Pimpl": aligned storage instead of the pointer, special member functions Question: I have attempted to implement a "fast Pimpl" idiom based on the talk slides and further sources, which is essentially an aligned storage of some size that can be used as a drop-in replacement for std::unique_ptr when implementing the Pimpl idiom: // ... private: // std::unique_ptr<Impl> pimpl_; // allocation and pointer redirection is required // versus: FastPimpl<Impl, implSize, implAlignment> pimpl_; // no allocation, no redirection // BUT: size and alignment of Impl must be provided (manually or via build system) The implementation: template <typename T, std::size_t Size, std::size_t Alignment> class FastPimpl { public: template <typename... Args, typename = std::enable_if<not(sizeof...(Args) == 1 and std::conjunction_v<std::is_same<T, Args>...>)>> explicit FastPimpl(Args&&... args) noexcept(std::is_nothrow_constructible_v<T, Args&&...>) { validate<sizeof(T), alignof(T)>(); std::cerr << "ctor\n"; new (pimpl()) T(std::forward<Args>(args)...); } FastPimpl(FastPimpl const& other) noexcept(std::is_nothrow_copy_constructible_v<T>) { std::cerr << "copy ctor\n"; new (pimpl()) T(*other.pimpl()); } FastPimpl& operator=(FastPimpl const& rhs) noexcept(std::is_nothrow_copy_assignable_v<T>) { std::cerr << "copy assign\n"; if (&rhs != this) { std::destroy_at(pimpl()); new (pimpl()) T(*rhs.pimpl()); } return *this; } FastPimpl(FastPimpl&& other) noexcept(std::is_nothrow_move_constructible_v<T>) { std::cerr << "move ctor\n"; new (pimpl()) T(std::move(*other.pimpl())); }
{ "domain": "codereview.stackexchange", "id": 43359, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++", "url": null }
c++ FastPimpl& operator=(FastPimpl&& rhs) noexcept(std::is_nothrow_move_assignable_v<T>) { std::cerr << "move assign\n"; if (&rhs != this) { std::destroy_at(pimpl()); new (pimpl()) T(std::move(*rhs.pimpl())); } return *this; } ~FastPimpl() noexcept { std::destroy_at(pimpl()); } T* operator->() noexcept { return pimpl(); } T const* operator->() const noexcept { return pimpl(); } T& operator*() noexcept { return *pimpl(); } T const& operator*() const noexcept { return *pimpl(); } private: T* pimpl() noexcept { return std::launder(reinterpret_cast<T*>(&data_)); } T const* pimpl() const noexcept { return std::launder(reinterpret_cast<T const*>(&data_)); } template <std::size_t ActualSize, std::size_t ActualAlignment> static void validate() noexcept { // Compiler suggests correct values. static_assert(Size == ActualSize, "Size and sizeof(T) mismatch"); static_assert(Alignment == ActualAlignment, "Alignment and alignof(T) mismatch"); } alignas(Alignment) std::byte data_[Size]; };
{ "domain": "codereview.stackexchange", "id": 43359, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++", "url": null }
c++ alignas(Alignment) std::byte data_[Size]; }; An simple (but wordy) runnable example of pimpl'ing Boost.Graph can be found on godbolt. Perhaps copy/move assign operators can be implemented better. The problem I see is that they do not give even the basic exception guarantee. If T's copy/move constructor throws, then data_ is in undefined state, because the T object representation was deallocated, and no new valid representation emplaced. On the other hand, as I read in the article, the contents of data_ can only be accessed in terms of T, which makes it UB to copy between std::byte objects, unless T is trivially_copyable, in which case one can use memcpy without invoking UB. So, based on my understanding, I am not allowed to allocate a temporary std::byte object and place-new a copy/move-constructed T object into it, and if it succeeds (doesn't throw), move object from temporary storage to data_. Again, unless T is trivially_copyable, in which case I am allowed to memcpy contents of temporary object into data_. I imagine something like: // Basic exception safety: if copy ctor throws, data_ still has valid state. alignas(Alignment) std::byte tmp[Size]; new (std::launder(reinterpret_cast<T*>(&tmp))) T(*rhs.pimpl()); std::destroy_at(pimpl()); if constexpr (std::is_trivially_copyable_v<T>) { std::memcpy(pimpl(), std::launder(reinterpret_cast<T*>(&tmp)), Size); } else { // ??? // move from &tmp into pimpl() } I understand the topic of placement new, memory laundering and strict aliasing rather superficially to use with confidence. If you happen to know any comprehensive guide besides many SO Q&A's, please share. Answer: It has certain limitations I have attempted to implement a "fast Pimpl" idiom [...], which is essentially an aligned storage of some size that can be used as a drop-in replacement for std::unique_ptr
{ "domain": "codereview.stackexchange", "id": 43359, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++", "url": null }
c++ Be careful saying something is a drop-in replacement. Apart from needing the size and alignment up front of course, there are other differences between FastPimpl and std::unique_ptr. Some members are missing, like get() and swap(), FastPimpl always creates a new Impl in its constructor, while a std::unique_ptr can be empty. However, for the purpose of a PImpl it is fine, and the name doesn't suggest it's a replacement for std::unique_ptr. But if you would write documentation for this class, I would carefully describe the intended use cases and restrictions. Invalid use of std::launder() I am not a language lawyer, however it seems that many of the calls to std::launder() in your code might not be valid. The reason is that std::launder() requires that at the address you give it, there is already an object that is within the lifetime of that object. Therefore, new(pimpl()) would be incorrect since there should not be a live object yet, it's new that is going to make one. So instead write: new (data_) T(...); There is no need to reinterpret_cast<>() the pointer. Only use pimpl() when you want to get a pointer to a live object, like in operator->(), operator*() and in calls to std::destroy_at(). Assignment operators If T's copy/move constructor throws, then data_ is in undefined state, because the T object representation was deallocated, and no new valid representation emplaced. For a well-defined class T, its copy/move assignment operators should already ensure that the object assigned to is either valid or in its original state. Consider that otherwise, by the time the destructor is called on that object, bad things would happen. So you should be able to make use of that fact: FastPimpl& operator=(FastPimpl const& rhs) noexcept(std::is_nothrow_copy_assignable_v<T>) { *pimpl() = *rhs.pimpl(); return *this; }
{ "domain": "codereview.stackexchange", "id": 43359, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++", "url": null }
c++ FastPimpl& operator=(FastPimpl&& rhs) noexcept(std::is_nothrow_move_assignable_v<T>) { *pimpl() = std::move(*rhs.pimpl()); return *this; } Note that you also don't need to check whether the objects are the same, since the assignment operators of T should already do that themselves.
{ "domain": "codereview.stackexchange", "id": 43359, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++", "url": null }
python, python-3.x, python-requests Title: Python script to POST requests to a networking device Question: Request to review my code please and see if I am following the best practices. This is sending a POST operation via a Python script using the requests library to a networking cloud orchestration endpoint import requests import sys requests.packages.urllib3.disable_warnings() token = input("Please enter your token: ") dev_ip = "1.1.1.1" service_id_c = input("Please enter the service ID: ") out_vlan_c = int(input("Please enter the uplink outer vlan ID: ")) in_vlan_c = int(input("Please enter the uplink inner vlan ID: ")) content_provider_c = input("Please enter the Content Provider name: ") interface_name_c = input("Please enter the Downlink Interface name: ") remote_id_c = input("Please enter the Remote ID: ") agent_id_c = input("Please enter the Agent Circuit ID: ") profile_name_c = input("Please enter the Profile name: ") payload = f"{{\r\n \"input\": {{\r\n \"service-context\": {{\r\n \"service-id\": \"{service_id_c}\",\r\n \"uplink-endpoint\": {{\r\n \"interface-endpoint\": {{\r\n \"outer-tag-vlan-id\": {out_vlan_c},\r\n \"inner-tag-vlan-id\": {in_vlan_c},\r\n \"content-provider-name\": \"{content_provider_c}\"\r\n }}\r\n }},\r\n \"downlink-endpoint\": {{\r\n \"interface-endpoint\": {{\r\n \"outer-tag-vlan-id\": \"untagged\",\r\n \"inner-tag-vlan-id\": \"none\",\r\n \"interface-name\": \"{interface_name_c}\"\r\n }}\r\n }},\r\n \"remote-id\": \"{remote_id_c}\",\r\n \"agent-circuit-id\": \"{agent_id_c}\",\r\n \"profile-name\": \"{profile_name_c}\"\r\n }}\r\n }}\r\n}}" headers = { 'Authorization': "Bearer " + token, }
{ "domain": "codereview.stackexchange", "id": 43360, "lm_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, python-requests", "url": null }
python, python-3.x, python-requests headers = { 'Authorization': "Bearer " + token, } def main(): try: with requests.post( url=f"https://{dev_ip}/api/restconf/operations/cloud-platform-orchestration:create", headers=headers, data=payload, verify=False, timeout=10, ) as response: represt_c = response.json() except Exception as e: print(f'An error occurred, please investigate further: {e!r}') else: print(response.status_code, response.reason, response.url) print(represt_c) if __name__ == '__main__': sys.exit(main()) Credit to @Reinderien who helped me formulate best practices for GET requests which I have adopted into my POST script (with a few minor tweaks) above. Successful response shown below Please enter your token: ****************************** Please enter the service ID: ABCD-ABC2525 Please enter the uplink outer vlan ID: 3060 Please enter the uplink inner vlan ID: 1060 Please enter the Content Provider name: COMPANY-SERVICE-B50 Please enter the Downlink Interface name: ABC123456_ETH_20 Please enter the Remote ID: test897 Please enter the Agent Circuit ID: test897 Please enter the Profile name: Data Service 200 OK https://192.168.1.1/api/restconf/operations/abc-cloud-platform-orchestration:create {'output': {'completion-status': 'in-progress', 'service-id': 'ADTN-ADTN2525', 'status': 'creating', 'timestamp': '2022-05-16T2:41:11.371020', 'trans-id': 'ed2667f3-629384-22734-t334-07d345551b93'}}
{ "domain": "codereview.stackexchange", "id": 43360, "lm_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, python-requests", "url": null }
python, python-3.x, python-requests Answer: Disable hard certificate failures, fine (temporarily). But do not disable_warnings. They're there to remind you that you're doing a bad thing. You're a network engineer, so you appreciate more than I do the hazards of handicapping TLS. Remove your _c suffixes. If I understood correctly, these are used as a rudimentary form of source control to show that this is the third incarnation of the script, but this is really not a good idea. Given the context of this question, which is that the script is intended for eventual automated reuse, I'm going to recommend that you convert your inputs to argparse parameters. If you're lucky, this script might eventually be drop-in reused with no modification needed. Your payload is prematurely serialised. I realise that the documentation told you to do this, but the documentation is wrong. You shouldn't be manually writing out a JSON representation in a string constant and then passing that to data=; start with a dictionary and pass that to json=. In other words, tell Requests to do the hard work for you. You have a main method (good), but it's failed to capture half of your imperative instructions, particularly your inputs. Constants can remain in the global namespace, but thing-doers should be in functions. You have a sys.exit(main()) which is a typical pattern to expose a numeric return code to the shell, but you've only half-implemented it. main needs to return an integer for this to work. You should return 0 on success, and different non-zero values based on various failures you see. One of these failures should be a non-200-series HTTP response code. Beside your post(), you should include a link to the API documentation. For automation compatibility, the only output going to stdout should be JSON. The rest - HTTP statuses and error codes - should go to stderr.
{ "domain": "codereview.stackexchange", "id": 43360, "lm_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, python-requests", "url": null }
python, python-3.x, python-requests This use case has already exceeded the forgiving circumstances in the previous question that allowed for simplified exception handling. You should only catch the exceptions you anticipate. Everything else should be left exceptional. As a refactor, consider writing:
{ "domain": "codereview.stackexchange", "id": 43360, "lm_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, python-requests", "url": null }
python, python-3.x, python-requests more subroutines an Enum to self-document your process status codes argparse support Suggested from argparse import ArgumentParser, Namespace from enum import Enum from json import JSONDecodeError from typing import Any import json import requests import sys class ProcessStatus(Enum): OK = 0 PYTHON_DEFAULT_ERROR = 1 IO_ERROR = 2 JSON_ERROR = 3 HTTP_ERROR = 4 def get_args() -> Namespace: parser = ArgumentParser( description='Fill out circuit parameters and send an orchestration create command to the cloud.', ) parser.add_argument('--host', '-s', default='1.1.1.1', help='Orchestration server host') parser.add_argument('--token', '-t', required=True, help='Bearer token for authorisation to the cloud service') parser.add_argument('--service-id', '-v', required=True, help='Service ID of the circuit') parser.add_argument('--out-vlan', '-o', required=True, type=int, help='ID of the outgoing VLAN') parser.add_argument('--in-vlan', '-i', required=True, type=int, help='ID of the incoming VLAN') parser.add_argument('--content-provider', '-c', required=True, help='Content provider name') parser.add_argument('--downlink-interface', '-d', required=True, help='Downlink interface name') parser.add_argument('--remote-id', '-r', required=True, help='Remote ID') parser.add_argument('--agent-circuit', '-a', required=True, help='Agent circuit ID') parser.add_argument('--profile', '-p', required=True, help='Profile name') return parser.parse_args()
{ "domain": "codereview.stackexchange", "id": 43360, "lm_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, python-requests", "url": null }
python, python-3.x, python-requests return parser.parse_args() def fill_payload(args: Namespace) -> dict[str, Any]: payload = { 'input': { 'service-context': { 'service-id': args.service_id, 'uplink-endpoint': { 'interface-endpoint': { 'outer-tag-vlan-id': args.out_vlan, 'inner-tag-vlan-id': args.in_vlan, 'content-provider-name': args.content_provider, } }, 'downlink-endpoint': { 'interface-endpoint': { 'outer-tag-vlan-id': 'untagged', 'inner-tag-vlan-id': 'none', 'interface-name': args.downlink_interface, } }, 'remote-id': args.remote_id, 'agent-circuit-id': args.agent_circuit, 'profile-name': args.profile, } } } return payload def post(host: str, token: str, payload: dict[str, Any]) -> requests.Response: headers = { 'Authorization': 'Bearer ' + token, 'Content-Type': 'application/yang-data+json', 'Accept': 'application/yang-data+json', } # See "Create Bundle": # https://documenter.getpostman.com/view/2389999/TVsrGVaa#071c1413-852b-467d-9049-8f19fb757d9b return requests.post( url=f'https://{host}/api/restconf/operations/cloud-platform-orchestration:create', headers=headers, json=payload, verify=False, timeout=10, ) def main() -> ProcessStatus: args = get_args() payload = fill_payload(args) try: response = post(host=args.host, token=args.token, payload=payload) except IOError as e: print(f'An I/O error occurred: {e!r}', file=sys.stderr) return ProcessStatus.IO_ERROR print(response.status_code, response.reason, response.url, file=sys.stderr)
{ "domain": "codereview.stackexchange", "id": 43360, "lm_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, python-requests", "url": null }
python, python-3.x, python-requests print(response.status_code, response.reason, response.url, file=sys.stderr) try: print(json.dumps(response.json(), indent=4)) except JSONDecodeError: print('The response could not be decoded:\n', response.text, file=sys.stderr) return ProcessStatus.JSON_ERROR if response.ok: return ProcessStatus.OK return ProcessStatus.HTTP_ERROR if __name__ == '__main__': sys.exit(main().value)
{ "domain": "codereview.stackexchange", "id": 43360, "lm_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, python-requests", "url": null }
c++, hash-map, memory-optimization Title: How do I increase the memory efficiency of this longest substring implementation? (C++) Question: I'm practicing my coding on leetcode. I implemented the following algorithm to solve the longest substring problem: class Solution { public: int lengthOfLongestSubstring(string s) { int max = 0; int start = 0; int rec = 0; int curs = 0; char p; char q; //p = string[0]; if(s.size() == 1){ return 1; } if(s.size() == 0){ return 0; } while(start < s.size()-1){ // Fresh map for every "starting" key we try unordered_map<char, int> umap; while(curs < s.size()){ if(umap.find(s[curs])==umap.end()){ //String does not exist umap[s[curs]] = 0; rec++; }else{ //The string does exist. We found a double. if(umap.size() > max){ max = umap.size(); } break; } if(curs == (s.size()-1)){ //we made it to the end without a double. if (umap.size() > max) { max = umap.size(); } return max; } curs++; } start++; curs = start; } return max; } };
{ "domain": "codereview.stackexchange", "id": 43361, "lm_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, memory-optimization", "url": null }
c++, hash-map, memory-optimization I noticed I did not rank high in memory efficiency. Can you all suggest some ways to improve memory usage in my solution? Would it help for me to clear out the hashmap in place in order to avoid allocating it each time? Is there somewhere where I am inadvertently copying data by not using references? I am aware there is a similar question at Leetcode longest substring without repeating characters but my code / algorithm is pretty different from that author's question. I am also open to other critiques of my code unrelated to the question I specifically asked. Thank you so much. Answer: Use a std::bitset A std::unordered_map is inappropriate here. First of all, it stores keys and values, but you are not interested in the value, only if the key is in the map. Therefore, a std::unordered_set would have been better. But these containers can handle arbitrary keys and values, while for your problem you know exactly how many possible keys there are: 256 (assuming CHAR_BIT == 8). So you can make a std::bitset instead to track which characters you have already seen. As the name implies, it only uses a single bit per element, so for 256 possible characters, it only needs 32 bytes, which is likely even less than an empty std::unordered_map takes.
{ "domain": "codereview.stackexchange", "id": 43361, "lm_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, memory-optimization", "url": null }
c, homework, embedded Title: Toggle 2 LEDs using a timer XMEGA-A3BU Xplained Question: I’m currently taking an online embedded programming course. This was our 4th programming assignment. The device is Microchip(Atmel) XMEGA-A3BU Xplained Development Kit, Mfr. Part Number: ATXMEGAA3BU-XPLD, the short name is Atxmega256A3BU. The device has an 8 bit data bus and a 16 bit address bus. I'm doing the development on Windows 10 in Microchip Studio 7 (a very poor clone of Visual Studio). I'm building the code without optimization. The optimizer has a habit of optimizing out my timing loops. The assignment is to alternate between 2 LEDs and if one of the buttons is pushed change the behavior so that the LED associated with that button is pushed is lit. Current LED 0 is associated with button SW1 and LED 1 is associated with button SW2. We are to use the TCC0 timer to alternate between the 2 LEDs. My question in addition to asking for a general review is the code for reading from and writing to a hardware address most often similar to the code in ReadReg() and WriteReg() in the code below? I'm asking about the pointer and not the volatile keyword. I've known the volatile keyword a long time. Just FYI, the instructor really likes comments. If you are wondering about the change history, I am not using GIT for this class. This assignment has been handed in. reg_io_wrappers.h /* * reg_io_wrappers.h * * Functions to read and write the hardware registers on the device. * Required for assignments from my class. * * Created: 4/27/2022 4:20:26 PM * Author: pacmaninbw * * Change History: * 5/11/2022 Changed added include for stdint-gcc.h to reg_io_wrappers.h, * changed input and output types to uint8_t. Easier to find and change * than unsigned char, better representation. */ #ifndef REG_IO_WRAPPERS_H_ #define REG_IO_WRAPPERS_H_ #include <stdint-gcc.h> extern void WriteReg(uint16_t RegAddress, uint8_t Value); extern uint8_t ReadReg(uint16_t RegAddress);
{ "domain": "codereview.stackexchange", "id": 43362, "lm_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, homework, embedded", "url": null }
c, homework, embedded #endif /* REG_IO_WRAPPERS_H_ */ reg_io_wrappers.c /* * reg_io_wrappers.c * * Functions to read and write the hardware registers on the device. * Required for assignments from my class. * * Created: 4/27/2022 4:08:13 PM * Author: pacmaninbw * * Change History: * 5/11/2022 Changed added include for stdint-gcc.h to reg_io_wrappers.h, * changed input and output types to uint8_t. Easier to find and change * than unsigned char, better representation. */ #include "reg_io_wrappers.h" /* Write data to a hardware register */ void WriteReg(uint16_t RegAddress, uint8_t Value) { *((volatile unsigned char *)RegAddress) = Value; } /* Read data from a hardware register */ uint8_t ReadReg(uint16_t RegAddress) { // disable interrupts uint8_t return_val = *((volatile uint8_t *)RegAddress); // enable interrupts return return_val; }
{ "domain": "codereview.stackexchange", "id": 43362, "lm_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, homework, embedded", "url": null }
c, homework, embedded return return_val; } main.c /** * Programming Assignment 4: Add timing using Clock to LED On/Off using switches * * 1. Create a code using Round Robin architecture to blink both LED’s when no * switch is pressed like in previous assignment. * * 2. When any switch is pressed, then only blink the LED(s) associated to the * switch number. Use the SW1 switch to control LED 0 and SW2 switch to * control LED 1. * * 3. Create a function that controls the blink operation. * * 4. The main task loop should check the switch setting and make decisions * whether to blink both LED's on at a time OR only blink the LEDS associated * with the switches that are pressed. * * Change History * 05/11/2022 - Moved call to delay function from main round robin to service_leds(). * This will allow buttons to interrupt the delay loop and force an early * from the service_leds() function. * Added service_buttons() function. * Added include for stdint-gcc.h so that uint8_t is defined, better than * putting unsigned char everywhere. Easier to modify if necessary. * * 05/14/2022 - 05/15/2022 - Converted the delay subroutine to use the * TCC0 timer/counter from a timing loop. * * 05/16/2022 - Fixed bug in delay function, was not complementing the read back * of the overflow flag. Moved the declaration of toggle into main(), there * was no need for it to be global to the file. */ #include <stdint-gcc.h> /* Include the hardware address macros. */ #include "devreg.h" /* * The I/O read and write wrapper functions are in a separate file, they will rarely * need to be recompiled. */ #include "reg_io_wrappers.h" /* * Not including stdbool.h, using K & R solution instead. */ #define TRUE 1 #define FALSE 0
{ "domain": "codereview.stackexchange", "id": 43362, "lm_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, homework, embedded", "url": null }
c, homework, embedded /* * Not including stdbool.h, using K & R solution instead. */ #define TRUE 1 #define FALSE 0 #if 0 /* * Used for debugging purposes. */ static void lightRedLED(void) { uint8_t pin4 = 0x01 << 4; WriteReg(PORTD_DIR_REG, pin4); WriteReg(PORTD_OUTTGL_REG, ~pin4); } #endif /* * Non-interrupt service function. * First determine if a button has been pushed, then determine which button * it is. Set the global button pushed flag. * * The button read back is in bits 1 and 2 (pins 1 and 2). Since the toggle * is an index into an array this needs to change to bits 0 and 1 so right * shift 1 bit. Since the pins are low when the button is pushed we need to * get the complement to find the proper value. */ static uint8_t service_buttons(uint8_t toggle) { /* Set PORTF direction to input */ WriteReg(BUTTON_ENABLE_REG, ENABLE_BUTTON_INPUT); uint8_t current_pin_read = ReadReg(BUTTON_VALUE_REG); /* Read back if any buttons are pushed. */ current_pin_read = current_pin_read >> 1; current_pin_read = ~current_pin_read & (uint8_t)0x03; /* * If no buttons are currently pushed return the current toggle value. */ current_pin_read = (current_pin_read)? current_pin_read : toggle; return current_pin_read; }
{ "domain": "codereview.stackexchange", "id": 43362, "lm_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, homework, embedded", "url": null }
c, homework, embedded /* * Keep each display state to approximately 1 to 2 seconds. Hopefully 1000 * loop executions equals 1 second. The delay function will be terminated * if the button status has changed. Use the TCC0 timer for the delay. */ static void DelayUsingTCC0(uint8_t requestedDelay) { /* * As per the instructions for this weeks lab, * 1) Set CTRLA for prescaling divide by 1024 * 2) Since we want the counter to overflow based on only the 8 bits in * the low counter register, set the high count register to all high. * 3) Set the desired delay value in the lower 8 bits of the counter. * 4) Make sure the overflow interrupt bit is cleared. * 5) Poll the clock interrupt flags to check for overflow conditions. */ WriteReg(TCC0_INTFLAGS, CLEAR_OVFIF); WriteReg(TCC0_CTRLA, CLK_CTRL_OPTS_DIV1024); WriteReg(TCC0_COUNT_HI, 0xFF); /* * Subtract the desired delay from the overflow value for the lower * 8 bits of the timer/counter. The overflow should occur when the * lower 8 bits reaches 0xFF. */ WriteReg(TCC0_COUNT_LOW, 0xFF - requestedDelay); /* * When overflow occurs the overflow bit in the interrupt register goes low. * Poll the interrupt flags for overflow. */ volatile uint8_t noOverflow = TRUE; while(noOverflow) { volatile uint8_t overFlowCheck = ReadReg(TCC0_INTFLAGS); noOverflow = ~overFlowCheck & OVFIF_MASK; } /* Make sure there are not interrupts for the rest of the program. */ WriteReg(TCC0_INTFLAGS, CLEAR_OVFIF); } /* * Non-interrupt service function. * * Toggle the LEDs. First LED 0 then LED 1. */ #define PIN0 (uint8_t) 0x01 #define PIN1 (uint8_t) 0x02 #define PINS_0_AND_1 (uint8_t) 0x03 static void service_leds(uint8_t pin_index) { uint8_t pins[] = {PIN0, PIN1, PINS_0_AND_1}; uint8_t pin = pins[pin_index];
{ "domain": "codereview.stackexchange", "id": 43362, "lm_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, homework, embedded", "url": null }
c, homework, embedded WriteReg(LED_ENABLE_REG, pin); /* Enable output on the specific pin(s) */ WriteReg(LED_TOGGLE_REG, ~pin); /* Drive the pin low. */ DelayUsingTCC0(250); WriteReg(LED_ENABLE_REG, 0); /* Disable output on the pin */ } int main (void) { uint8_t toggle = 0; while (TRUE) { /* * Simple Round Robin Architecture without interrupts. * Buttons are a higher priority than the LEDs because the buttons provide * user input and require a better response time. The buttons also change * the status of which LEDs to display. */ toggle = service_buttons(toggle); service_leds(toggle); toggle = (toggle)? 0 : 1; } } devreg.h /* * devreg.h * Portable Register Addressing to allow the code using this file to port to * other devices. * Required for assignments from my class. * * Created: 4/27/2022 3:33:12 PM * Author: pacmaninbw * * Change History * Created 4/27/2022.Currently only contains macros to program the PORTR * functionality, to enable and disable the LEDs. To make the LED * programming more portable LED macros were added to hide the PORTR * implementation on the device. * * 5/1/2022. Changed the PORT Address macros implementation, Ports can be added * by copy and paste, select region, find and replace base port register * name. * * 5/8/2022 Added PORTF Macros. * * 5/10/2022 Converted LED constants to use the complement of decimal numbers * rather than Hex values. * * 5/14/2022 Added clock address offsets, CLOCK_TCC0 and the clock prescaler values * for clock TCC0. * * 5/16/2022 Added Port D addresses, corrected copy paste errors in Ports B & C. * Attempting to use red LED for debugging. */ #ifndef DEVREG_H_ #define DEVREG_H_
{ "domain": "codereview.stackexchange", "id": 43362, "lm_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, homework, embedded", "url": null }
c, homework, embedded #ifndef DEVREG_H_ #define DEVREG_H_ /* * Clock Control Registers for TCC0 */ #define CLOCK_TCC0 0x0800 #define CLOCK_CTRLA_OFFSET 0x00 #define CLOCK_CTRLB_OFFSET 0x01 #define CLOCK_CTRLC_OFFSET 0x02 #define CLOCK_CTRLD_OFFSET 0x03 #define CLOCK_CTRLE_OFFSET 0x04 #define CLOCK_INTERRUPT_CTRLA_OFFSET 0x06 #define CLOCK_INTERRUPT_CTRLB_OFFSET 0x07 #define CLOCK_CTRLF_CLEAR_OFFSET 0X08 #define CLOCK_CTRLF_SET_OFFSET 0X09 #define CLOCK_CTRLG_CLEAR_OFFSET 0X0A #define CLOCK_CTRLG_SET_OFFSET 0X0B #define CLOCK_INTERRUPT_FLAGS_OFFSET 0X0C #define CLOCK_COUNTER_LOW_OFFSET 0X20 #define CLOCK_COUNTER_HI_OFFSET 0X21
{ "domain": "codereview.stackexchange", "id": 43362, "lm_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, homework, embedded", "url": null }
c, homework, embedded /* * Adding Clock Offsets */ #define ADD_CLOCK_CTRLA_OFFSET(baseAddress) \ (baseAddress + CLOCK_CTRLA_OFFSET) #define ADD_CLOCK_CTRLB_OFFSET(baseAddress) \ (baseAddress + CLOCK_CTRLB_OFFSET) #define ADD_CLOCK_CTRLC_OFFSET(baseAddress) \ (baseAddress + CLOCK_CTRLC_OFFSET) #define ADD_CLOCK_CTRLD_OFFSET(baseAddress) \ (baseAddress + CLOCK_CTRLD_OFFSET) #define ADD_CLOCK_CTRLE_OFFSET(baseAddress) \ (baseAddress + CLOCK_CTRLE_OFFSET) #define ADD_CLOCK_INTERRUPT_CTRLA_OFFSET(baseAddress) \ (baseAddress + CLOCK_INTERRUPT_CTRLA_OFFSET) #define ADD_CLOCK_INTERRUPT_CTRLB_OFFSET(baseAddress) \ (baseAddress + CLOCK_INTERRUPT_CTRLB_OFFSET) #define ADD_CLOCK_CTRLF_CLEAR_OFFSET(baseAddress) \ (baseAddress + CLOCK_CTRLF_CLEAR_OFFSET) #define ADD_CLOCK_CTRLF_SET_OFFSET(baseAddress) \ (baseAddress + CLOCK_CTRLF_SET_OFFSET) #define ADD_CLOCK_CTRLG_CLEAR_OFFSET(baseAddress) \ (baseAddress + CLOCK_CTRLG_CLEAR_OFFSET) #define ADD_CLOCK_CTRLG_SET_OFFSET(baseAddress) \ (baseAddress + CLOCK_CTRLG_SET_OFFSET) #define ADD_CLOCK_INTERRUPT_FLAGS_OFFSET(baseAddress) \ (baseAddress + CLOCK_INTERRUPT_FLAGS_OFFSET) #define ADDCLOCK_COUNTER_LOW_OFFSET(baseAddress) \ (baseAddress + CLOCK_COUNTER_LOW_OFFSET) #define ADD_CLOCK_COUNTER_HI_OFFSET(baseAddress) \ (baseAddress + CLOCK_COUNTER_HI_OFFSET) /* * Clock Register Addresses */
{ "domain": "codereview.stackexchange", "id": 43362, "lm_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, homework, embedded", "url": null }
c, homework, embedded /* * Clock Register Addresses */ /* * TCC0 Clock Control Register Addresses */ #define TCC0_CTRLA ADD_CLOCK_CTRLA_OFFSET(CLOCK_TCC0) #define TCC0_CTRLB ADD_CLOCK_CTRLB_OFFSET(CLOCK_TCC0) #define TCC0_CTRLC ADD_CLOCK_CTRLC_OFFSET(CLOCK_TCC0) #define TCC0_CTRLD ADD_CLOCK_CTRLD_OFFSET(CLOCK_TCC0) #define TCC0_CTRLE ADD_CLOCK_CTRLE_OFFSET(CLOCK_TCC0) #define TCC0_CTRLA_INT ADD_CLOCK_INTERRUPT_CTRLA_OFFSET(CLOCK_TCC0) #define TCC0_CTRLB_INT ADD_CLOCK_INTERRUPT_CTRLB_OFFSET(CLOCK_TCC0) #define TCCO_CTRLF_CLR ADD_CLOCK_CTRLF_CLEAR_OFFSET(CLOCK_TCC0) #define TCC0_CTRLF_SET ADD_CLOCK_CTRLF_SET_OFFSET(CLOCK_TCC0) #define TCCO_CTRLG_CLR ADD_CLOCK_CTRLG_CLEAR_OFFSET(CLOCK_TCC0) #define TCC0_CTRLG_SET ADD_CLOCK_CTRLG_SET_OFFSET(CLOCK_TCC0) #define TCC0_INTFLAGS ADD_CLOCK_INTERRUPT_FLAGS_OFFSET(CLOCK_TCC0) #define TCC0_COUNT_LOW ADDCLOCK_COUNTER_LOW_OFFSET(CLOCK_TCC0) #define TCC0_COUNT_HI ADD_CLOCK_COUNTER_HI_OFFSET(CLOCK_TCC0) /* * Clock Control Options and Prescaler Settings */ #define CLK_CTRL_OPTS_OFF (uint8_t) 0X00 #define CLK_CTRL_OPTS_DIV1 (uint8_t) 0X01 #define CLK_CTRL_OPTS_DIV2 (uint8_t) 0X02 #define CLK_CTRL_OPTS_DIV4 (uint8_t) 0X03 #define CLK_CTRL_OPTS_DIV8 (uint8_t) 0X04 #define CLK_CTRL_OPTS_DIV64 (uint8_t) 0X05 #define CLK_CTRL_OPTS_DIV256 (uint8_t) 0X06 #define CLK_CTRL_OPTS_DIV1024 (uint8_t) 0X07 /* * Other Clock Control settings */ #define CLEAR_OVFIF (uint8_t) 0x01 #define OVFIF_MASK (uint8_t) 0x01
{ "domain": "codereview.stackexchange", "id": 43362, "lm_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, homework, embedded", "url": null }
c, homework, embedded // LED control values // For this device there are 2 LEDs, so there are 4 LED states, all LEDs off, // all LEDs on, LED 0 on, LED 1 on. // The yellow LEDs are controlled by pins 0 and 1 in PORTR. The LED controlled // by pin 0 will be called LED 0 and the LED controlled by pin 1 will be called // LED 1. When driving low on either pin 0 or pin 1 the associated LED will // light up. #define ALL_LEDS_OFF (uint8_t) ~0x00 #define ALL_LEDS_ON (uint8_t) ~0x03 #define LED_0_ON (uint8_t) ~0x01 #define LED_1_ON (uint8_t) ~0x02 #define LED_MAX_STATES 4 #define LED_STATE_MASK 0x03 /* The 2 LSBs in the PORT R register */ #define ENABLE_ALL_LEDS (uint8_t) 0x03 #define TURN_OFF_ALL_LEDS (uint8_t) 0x03 #define PORT_DIR_OUTPUT 0xFF /* Page 148 of the Manual Bits 0 and 1 output */ #define PORT_DIR_INPUT 0xFC /* Bits 0 and 1 input */ // Device Port Address Offsets // These offsets are documented on page 160 of the manual // Atmel-8331-8-and-16-bit-AVR-Microcontroller-XMEGA-AU_Manual.pdf #define PORT_DIR_OFFSET 0x00 #define PORT_DIRSET_OFFSET 0x01 #define PORT_DIRCLR_OFFSET 0X02 #define PORT_DIRTGL_OFFSET 0X03 #define PORT_OUT_OFFSET 0x04 #define PORT_OUTSET_OFFSET 0x05 #define PORT_OUTCLR_OFFSET 0x06 #define PORT_OUTTGL_OFFSET 0x07 #define PORT_IN_OFFSET 0x08
{ "domain": "codereview.stackexchange", "id": 43362, "lm_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, homework, embedded", "url": null }
c, homework, embedded // Adding Device Port Offsets #define ADD_PORT_DIR_OFFSET(baseAddress) \ (baseAddress + PORT_DIR_OFFSET) #define ADD_PORT_DIRSET_OFFSET(baseAddress) \ (baseAddress + PORT_DIRSET_OFFSET) #define ADD_PORT_DIRCLR_OFFSET(baseAddress) \ (baseAddress + PORT_DIRCLR_OFFSET) #define ADD_PORT_DIRTGL_OFFSET(baseAddress) \ (baseAddress + PORT_DIRTGL_OFFSET) #define ADD_PORT_OUT_OFFSET(baseAddress) \ (baseAddress + PORT_OUT_OFFSET) #define ADD_PORT_OUTSET_OFFSET(baseAddress) \ (baseAddress + PORT_OUTSET_OFFSET) #define ADD_PORT_OUTCLR_OFFSET(baseAddress) \ (baseAddress + PORT_OUTCLR_OFFSET) #define ADD_PORT_OUTTGL_OFFSET(baseAddress) \ (baseAddress + PORT_OUTTGL_OFFSET) #define ADD_PORT_IN_OFFSET(baseAddress) \ (baseAddress + PORT_IN_OFFSET) /* PORT R Device Addresses */ #define PORTR_BASE_ADDRESS 0x07E0 #define PORTR_DIR_REG ADD_PORT_DIR_OFFSET(PORTR_BASE_ADDRESS) #define PORTR_DIRSET_REG ADD_PORT_DIRSET_OFFSET(PORTR_BASE_ADDRESS) #define PORTR_DIRCLR_REG ADD_PORT_DIRCLR_OFFSET(PORTR_BASE_ADDRESS) #define PORTR_DIRTGL_REG ADD_PORT_DIRTGL_OFFSET(PORTR_BASE_ADDRESS) #define PORTR_OUT_REG ADD_PORT_OUT_OFFSET(PORTR_BASE_ADDRESS) #define PORTR_OUTSET_REG ADD_PORT_OUTSET_OFFSET(PORTR_BASE_ADDRESS) #define PORTR_OUTCLR_REG ADD_PORT_OUTCLR_OFFSET(PORTR_BASE_ADDRESS) #define PORTR_OUTTGL_REG ADD_PORT_OUTTGL_OFFSET(PORTR_BASE_ADDRESS) #define PORTR_IN_REG ADD_PORT_IN_OFFSET(PORTR_BASE_ADDRESS)
{ "domain": "codereview.stackexchange", "id": 43362, "lm_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, homework, embedded", "url": null }
c, homework, embedded /* PORT F Device Addresses */ #define PORTF_BASE_ADDRESS 0x06A0 #define PORTF_DIR_REG ADD_PORT_DIR_OFFSET(PORTF_BASE_ADDRESS) #define PORTF_DIRSET_REG ADD_PORT_DIRSET_OFFSET(PORTF_BASE_ADDRESS) #define PORTF_DIRCLR_REG ADD_PORT_DIRCLR_OFFSET(PORTF_BASE_ADDRESS) #define PORTF_DIRTGL_REG ADD_PORT_DIRTGL_OFFSET(PORTF_BASE_ADDRESS) #define PORTF_OUT_REG ADD_PORT_OUT_OFFSET(PORTF_BASE_ADDRESS) #define PORTF_OUTSET_REG ADD_PORT_OUTSET_OFFSET(PORTF_BASE_ADDRESS) #define PORTF_OUTCLR_REG ADD_PORT_OUTCLR_OFFSET(PORTF_BASE_ADDRESS) #define PORTF_OUTTGL_REG ADD_PORT_OUTTGL_OFFSET(PORTF_BASE_ADDRESS) #define PORTF_IN_REG ADD_PORT_IN_OFFSET(PORTF_BASE_ADDRESS) /* PORT A Device Addresses */ #define PORTA_BASE_ADDRESS 0x0600 #define PORTA_DIR_REG ADD_PORT_DIR_OFFSET(PORTA_BASE_ADDRESS) #define PORTA_DIRSET_REG ADD_PORT_DIRSET_OFFSET(PORTA_BASE_ADDRESS) #define PORTA_DIRCLR_REG ADD_PORT_DIRCLR_OFFSET(PORTA_BASE_ADDRESS) #define PORTA_DIRTGL_REG ADD_PORT_DIRTGL_OFFSET(PORTA_BASE_ADDRESS) #define PORTA_OUT_REG ADD_PORT_OUT_OFFSET(PORTA_BASE_ADDRESS) #define PORTA_OUTSET_REG ADD_PORT_OUTSET_OFFSET(PORTA_BASE_ADDRESS) #define PORTA_OUTCLR_REG ADD_PORT_OUTCLR_OFFSET(PORTA_BASE_ADDRESS) #define PORTA_OUTTGL_REG ADD_PORT_OUTTGL_OFFSET(PORTA_BASE_ADDRESS) #define PORTA_IN_REG ADD_PORT_IN_OFFSET(PORTA_BASE_ADDRESS)
{ "domain": "codereview.stackexchange", "id": 43362, "lm_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, homework, embedded", "url": null }
c, homework, embedded /* PORT B Device Addresses */ #define PORTB_BASE_ADDRESS 0x0620 #define PORTB_DIR_REG ADD_PORT_DIR_OFFSET(PORTB_BASE_ADDRESS) #define PORTB_DIRSET_REG ADD_PORT_DIRSET_OFFSET(PORTB_BASE_ADDRESS) #define PORTB_DIRCLR_REG ADD_PORT_DIRCLR_OFFSET(PORTB_BASE_ADDRESS) #define PORTB_DIRTGL_REG ADD_PORT_DIRTGL_OFFSET(PORTB_BASE_ADDRESS) #define PORTB_OUT_REG ADD_PORT_OUT_OFFSET(PORTB_BASE_ADDRESS) #define PORTB_OUTSET_REG ADD_PORT_OUTSET_OFFSET(PORTB_BASE_ADDRESS) #define PORTB_OUTCLR_REG ADD_PORT_OUTCLR_OFFSET(PORTB_BASE_ADDRESS) #define PORTB_OUTTGL_REG ADD_PORT_OUTTGL_OFFSET(PORTB_BASE_ADDRESS) #define PORTB_IN_REG ADD_PORT_IN_OFFSET(PORTB_BASE_ADDRESS) /* PORT C Device Addresses */ #define PORTC_BASE_ADDRESS 0x0640 #define PORTC_DIR_REG ADD_PORT_DIR_OFFSET(PORTC_BASE_ADDRESS) #define PORTC_DIRSET_REG ADD_PORT_DIRSET_OFFSET(PORTC_BASE_ADDRESS) #define PORTC_DIRCLR_REG ADD_PORT_DIRCLR_OFFSET(PORTC_BASE_ADDRESS) #define PORTC_DIRTGL_REG ADD_PORT_DIRTGL_OFFSET(PORTC_BASE_ADDRESS) #define PORTC_OUT_REG ADD_PORT_OUT_OFFSET(PORTC_BASE_ADDRESS) #define PORTC_OUTSET_REG ADD_PORT_OUTSET_OFFSET(PORTC_BASE_ADDRESS) #define PORTC_OUTCLR_REG ADD_PORT_OUTCLR_OFFSET(PORTC_BASE_ADDRESS) #define PORTC_OUTTGL_REG ADD_PORT_OUTTGL_OFFSET(PORTC_BASE_ADDRESS) #define PORTC_IN_REG ADD_PORT_IN_OFFSET(PORTC_BASE_ADDRESS)
{ "domain": "codereview.stackexchange", "id": 43362, "lm_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, homework, embedded", "url": null }
c, homework, embedded /* PORT D Device Addresses */ #define PORTD_BASE_ADDRESS 0x0660 #define PORTD_DIR_REG ADD_PORT_DIR_OFFSET(PORTD_BASE_ADDRESS) #define PORTD_DIRSET_REG ADD_PORT_DIRSET_OFFSET(PORTD_BASE_ADDRESS) #define PORTD_DIRCLR_REG ADD_PORT_DIRCLR_OFFSET(PORTD_BASE_ADDRESS) #define PORTD_DIRTGL_REG ADD_PORT_DIRTGL_OFFSET(PORTD_BASE_ADDRESS) #define PORTD_OUT_REG ADD_PORT_OUT_OFFSET(PORTD_BASE_ADDRESS) #define PORTD_OUTSET_REG ADD_PORT_OUTSET_OFFSET(PORTD_BASE_ADDRESS) #define PORTD_OUTCLR_REG ADD_PORT_OUTCLR_OFFSET(PORTD_BASE_ADDRESS) #define PORTD_OUTTGL_REG ADD_PORT_OUTTGL_OFFSET(PORTD_BASE_ADDRESS) #define PORTD_IN_REG ADD_PORT_IN_OFFSET(PORTD_BASE_ADDRESS) /* * Portable names for device registers does not require knowledge of device */ #define LED_ENABLE_REG PORTR_DIR_REG #define LED_TOGGLE_REG PORTR_OUTTGL_REG #define ENABLE_LEDS PORT_DIR_OUTPUT #define DISABLE_LEDS PORT_DIR_INPUT #define LEDS_OFF_REG PORTR_OUT_REG /* * Buttons * The SW1 and SW2 button input is available on PORTF PIN1 and PIN2 respectively * as documented on page 10 of doc8394.pdf. */ #define SW1_AND_SW2_ARE_PRESSED (uint8_t) ~0x06 // Pins 1 and 2 are low #define SW1_IS_PRESSED (uint8_t) ~0x02 // Pin 1 is low #define SW2_IS_PRESSED (uint8_t) ~0x04 // Pin 2 is low #define BUTTON_ENABLE_REG PORTF_DIR_REG #define BUTTON_VALUE_REG PORTF_IN_REG #define ENABLE_BUTTON_INPUT (uint8_t) ~0x06 #endif /* DEVREG_H_ */ [1]: https://i.stack.imgur.com/g0zPK.jpg Answer: The optimizer has a habit of optimizing out my timing loops.
{ "domain": "codereview.stackexchange", "id": 43362, "lm_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, homework, embedded", "url": null }
c, homework, embedded Answer: The optimizer has a habit of optimizing out my timing loops. This is (a) a non-surprise, and (b) somewhat of a red flag when it comes to coding practice. If you're writing timing loops that attempt to take advantage of instruction durations to time events, expect difficulty unless you drop down to assembly (bypassing the compiler and optimiser), or do the saner thing and use hardware timers when possible. Regarding ReadReg and WriteReg. Don't treat addresses as uint16_t. You'll need to read your compiler manual to rule out weird behaviour like near/far modifiers etc., but if humanly possible, those RegAddress should be actual * pointers. You cast to a volatile unsigned char *: check if that's the size you're looking for, and if so, just use that as your argument type. More on the above: as is quite typical with microcontrollers, they have an address space that's more complicated in some ways to use than modern desktop architectures. Read chapter 3 AVR CPU, particularly Direct addressing of up to 16MB of program memory and 16MB of data memory The memory spaces are linear. The data memory space and the program memory space are two different memory spaces. All I/O status and control registers reside in the lowest 4KB addresses of the data memory. This is referred to as the I/O memory space. The lowest 64 addresses can be accessed directly, or as the data space locations from 0x00 to 0x3F. The rest is the extended I/O memory space, ranging from 0x0040 to 0x0FFF. I/O registers here must be accessed as data space locations using load (LD/LDS/LDD) and store (ST/STS/STD) instructions. and Chapter 4 Memories Data memory One linear address space Single-cycle access from CPU SRAM EEPROM Byte and page accessible Optional memory mapping for direct load and store I/O memory Configuration and status registers for all peripherals and modules 16 bit-accessible general purpose registers for global variables or flags
{ "domain": "codereview.stackexchange", "id": 43362, "lm_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, homework, embedded", "url": null }
c, homework, embedded [...] All memory spaces are linear and require no memory bank switching. Not all addresses are created equal. Addresses in the lower 64B use a different access mechanism from those above. Read this section in GCC for evidence that gcc treats AVR specially. Generically speaking, gcc may (though doesn't appear to) have chosen to add a near prefix for pointers to this lower segment, and far for pointers to this upper segment - this is done in other compilers for other architectures. Since I don't think it does, I encourage you to Rewrite your macros e.g. #define PORTD_DIR_REG ((volatile unsigned char*)0x0660) Get rid of your ReadReg/WriteReg Just *PORTD_DIR_REG = 0x...; Manually verify the compiled assembly to ensure that it makes sense based on the destination address I don't understand the comment // disable interrupts. Because.. you don't do that? Or is this some magic the compiler does for you to wrap volatile dereferences? You should specify. Set PORTF direction to input seems like something that should be done once on initialisation and then left alone. current_pin_read = (current_pin_read)? current_pin_read : toggle; return current_pin_read; is a pretty surprising way of writing return current_pin_read || toggle; The delay function will be terminated if the button status has changed. Polling loops are a method of last resort. Hopefully your dev board has wired the button to a pin supporting hardware interrupt. Based on the documentation, your button pins are PE5, PF1 and PF2. In your microcontroller manual chapter 13.6, it shows Two port interrupts with pin masking per I/O port
{ "domain": "codereview.stackexchange", "id": 43362, "lm_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, homework, embedded", "url": null }
c, homework, embedded Two port interrupts with pin masking per I/O port Enable that hardware interrupt. As a matter of some urgency, you need to know what your clock rate is (ask your prof?). Then, there will be no manual iterations, and a single setting of the timer with a single expiry. You claim that the current delay is somewhere between 250-500 ms for your timer value of 250. This suggests a system clock between $$ 1024 * 250 / 0.250 = 1.024 \text{MHz} $$ and $$ 1024 * 250 / 0.500 = 512 \text{kHz} $$ Visual inspection only reveals an RTC-style 32 kHz crystal and no other hardware oscillator. Between this and the fact that the 2 MHz internal oscillator is the default clock source used on startup, chances are that your base oscillator is 2 MHz, depicted in the bottom right: It's less likely that XOSCSEL and PLLSRC are set such that your system clock is some multiple of the 32,768 Hz crystal. A PLL factor of 15-31 would be consistent with the delay you're seeing, but again, if you haven't chosen this explicitly, you're just on 2 MHz. TC0 in figure 14-1 only shows an input of clkPER, so it's unlikely that the system prescaler has any effect, which in turn increases the likelihood that you're on 2 MHz or below. You should attempt to nail this down before your next assignment. For an expiry of one second, you cannot use your timer's lower half only. You need to use all 16 bits. If you add a macro that - rather than pointing to a uint8_t, points to a uint16_t - and you get your endianness right, a simple dereference-and-assign should compile to the right thing. Assuming for now that your system clock of 2 MHz is accurate, with a 16-bit-wide counter and your available prescaler settings, your prescaler feasibility region looks like:
{ "domain": "codereview.stackexchange", "id": 43362, "lm_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, homework, embedded", "url": null }
c, homework, embedded The timer should be "set-and-forget". Refer to chapter 14.8.1 Waveform Generation - the output should be automatic, and you should only enact a port override if you get a button interrupt. Then put the CPU into an idle or sleep state with no loops required. By chapter 8.2: When the device enters sleep mode, program execution is stopped and interrupts or a reset is used to wake the device again.
{ "domain": "codereview.stackexchange", "id": 43362, "lm_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, homework, embedded", "url": null }
python Title: Command dispatcher in Python Question: I have this function in python: def executecommand(call): if call.data == "/getpair": return getpaircmd(call.message) elif call.data == "/menu": return menucmd(call.message) elif call.data == "/setalarm": return setalarmcmd(call.message) And I was hoping to replace it with object and .get(call.data) message, like this: def executecommand(call): return { "/getpair": getpaircmd(call.message), "/menu": menucmd(call.message), "/setalarm": setalarmcmd(call.message) }.get(call.data) But it seems like it calls every function on the list. So, is there a way to simplify it? Answer: The parentheses act as a function-calling operator in Python. Therefore, your attempt to build the dispatch table would end up calling all the functions. What you can do instead is this: def executecommand(call): return { "/getpair": getpaircmd, "/menu": menucmd, "/setalarm": setalarmcmd, }[call.data](call.message) Note that the behavior with the lookup table is different from the original in the case where call.data is not one of the expected choices. In your code unknown messages will be ignored, in the example code above it would raise a TypeError because the dictionary would return None, which is not callable. I also recommend putting a comma consistently, so that if you later add or remove a command, you'll get cleaner diffs in your source code version control. The fact that you see all the functions being called highlights a potential performance issue: the dispatch table is rebuilt every time executecommand() runs. The table should be built just once: _DISPATCH = { "/getpair": getpaircmd, "/menu": menucmd, "/setalarm": setalarmcmd, } def executecommand(call): return _DISPATCH[call.data](call.message)
{ "domain": "codereview.stackexchange", "id": 43363, "lm_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", "url": null }
c++, c++17, template-meta-programming Title: C++17 view over the Ith elements of tuples in containers of tuples Question: For mainly didactic reasons, I have designed my ElementsView<I, T> class template, which provides a view over the I th elements of each tuple contained by a given container T, provided that container supports operator[]. The entry point is the factory function template animal::util::elements<I>(...sequence-container-of-tuples...). This is similar (though way less powerful) to C++20's std::ranges::elements_view, and is designed to interop with a custom "zip" view (not shown, maybe in some other review). I'm looking for any kind of insight/criticism, but my main doubt is about this lref_iff_lref_t helper I "invented" to the elements functions accept rvalues. That is, so I can write things like: elements<1>(elements<2>(container_of_tuples_of_tuples)); I'm also looking for simplification, hidden performance problems and UB. So here is the code, follow by "Catch2" tests // eview.hpp #include <tuple> #ifdef EVIEW_MP_TESTS #include <type_traits> #include <vector> #endif namespace animal::util::eview { using std::size_t, std::remove_reference_t, std::decay_t, std::tuple_element_t, std::is_same_v; /** * fwd_tup_elem_t<I, TUP> * * Get Ith type of tuple TUP, cvref'ed as TUP */ template <size_t I, typename Tup> struct fwd_tup_elem; template <size_t I, typename Tup> using fwd_tup_elem_t = typename fwd_tup_elem<I, Tup>::type; template <size_t I, typename T> struct fwd_tup_elem<I, const T> {using type = const fwd_tup_elem_t<I, T>;}; template <size_t I, typename T> struct fwd_tup_elem<I, T&> { using type = tuple_element_t<I, remove_reference_t<T>> &; }; template <size_t I, typename T> struct fwd_tup_elem<I, T&&> { using type = tuple_element_t<I, remove_reference_t<T>> &; }; /** * fwd_cont_val<TC> * * Get value_type of tuple container TC, cvref'ed as TC */ template <size_t I, typename TC> struct fwd_cont_val;
{ "domain": "codereview.stackexchange", "id": 43364, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, c++17, template-meta-programming", "url": null }
c++, c++17, template-meta-programming template <size_t I, typename TC> using fwd_cont_val_t = typename fwd_cont_val<I, TC>::type; template <size_t I, typename TC> struct fwd_cont_val<I, const TC&> { using type = const fwd_tup_elem_t<I, const typename TC::value_type&>; }; template <size_t I, typename TC> struct fwd_cont_val<I, TC&> { using type = fwd_tup_elem_t<I, typename TC::value_type&>; }; template <size_t I, typename TC> struct fwd_cont_val<I, TC&&> { using type = fwd_tup_elem_t<I, typename TC::value_type&>; }; #ifdef EVIEW_MP_TESTS // ERROR, GOOD: non-supported tuple type // static_assert(is_same_v<tup_fwd_t<0, std::tuple<int>>, int>); static_assert(is_same_v<tup_fwd_t<0, std::tuple<int>&>, int&>); static_assert(is_same_v<tup_fwd_t<0, const std::tuple<int>&>, const int&>); static_assert(is_same_v<tup_fwd_t<0, const std::tuple<int>&&>, const int&>); // ERROR, GOOD: non-supported vector type // static_assert(is_same_v<val_fwd_t<0, std::vector<std::tuple<int>>>, int>); static_assert(is_same_v<val_fwd_t<0, std::vector<std::tuple<int>>&>, int&>); static_assert(is_same_v<val_fwd_t<0, std::vector<std::tuple<int>>&&>, int&>); static_assert(is_same_v<val_fwd_t<0, const std::vector<std::tuple<int>>&>, const int&>); #endif /** * lref_iff_lref_t<TC> * * TC& if TC is T&. TC if TC is T&&. Error otherwise */ template <typename T> struct lref_iff_lref; template <typename T> using lref_iff_lref_t = typename lref_iff_lref<T>::type; template <typename T> struct lref_iff_lref<T&> {using type = T&;}; template <typename T> struct lref_iff_lref<T&&> {using type = remove_reference_t<T>;};
{ "domain": "codereview.stackexchange", "id": 43364, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, c++17, template-meta-programming", "url": null }