body
stringlengths
25
86.7k
comments
list
answers
list
meta_data
dict
question_id
stringlengths
1
6
<p>This takes a user password, hashes password to SHA1 and does a check against the Pwnedpasswords database.</p> <p>I know I need to use unwrap less and do more real checking to improve the clarity of errors. In what other places is my code lacking and what should I learn or look at to improve in the future.</p> <p>The current resources I am using are the Rust by Example. The documentation for the crates I used and in general looking at rust code on GitHub.</p> <pre><code>$ cargo run --bin checker -- check Password: ********* Password is (not) compromised </code></pre> <p></p> <pre><code>#[macro_use] extern crate clap; extern crate crypto; extern crate reqwest; extern crate regex; extern crate rpassword; use crypto::digest::Digest; use crypto::sha1::Sha1; use clap::App; use regex::Regex; /* loads clap cli config * if the check subcommand is used, run check */ fn main () { let yaml = load_yaml!("config/clap_cli.yml"); let matches = App::from_yaml(yaml).get_matches(); if let Some(_m_check) = matches.subcommand_matches("check") { check(); } } /* get password from user * hash the password * check against pwned database * tell user if the password is bad */ fn check () { let value = &amp;rpassword::prompt_password_stdout("Password: ") .unwrap(); let mut hasher = Sha1::new(); hasher.input_str(value); let pass_hash = hasher.result_str().to_uppercase(); let pass_hash_slice = pass_hash.get(0..5).unwrap(); let pass_hash_end = pass_hash.get(5..).unwrap(); let body = reqwest::get( &amp;format!("https://api.pwnedpasswords.com/range/{}", pass_hash_slice) ).unwrap().text().unwrap(); let re_pass = Regex::new(&amp;pass_hash_end).unwrap(); if re_pass.is_match(&amp;body) { println!("Password is compromised."); } else { println!("Password is not compromised."); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-17T07:35:00.210", "Id": "417093", "Score": "1", "body": "You should erase the clear password from memory as soon as possible." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-17T19:15:07.043", "Id": "417143", "Score": "0", "body": "Thank you Stargateur for the input, I will learn how to do that and implement it in future iterations. And also keep it in mind as well for future projects that handle sensitive data." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-17T00:58:28.873", "Id": "215584", "Score": "1", "Tags": [ "api", "rust" ], "Title": "Password Checker using Pwnedpasswords API in Rust" }
215584
<p>I wrote a script using Python that gets data from several sources (news sites, Twitter, Yahoo), puts it into a dict and then formats it as a string to be sent through email.</p> <p>I wonder if there is possibility to write the code more neatly in a shorter way. Maybe I'm doing some steps that are a bit unnecessary and maybe faster and I could do it differently, but not sure how.</p> <pre><code>import json import urllib.request from twitter import Twitter, OAuth, TwitterHTTPError, TwitterStream from bs4 import BeautifulSoup import requests import datetime from pymongo import MongoClient from email.mime.text import MIMEText import smtplib import os #from config import * now = datetime.datetime.now() api_news= os.environ["api_news"] #twitter setup ACCESS_TOKEN = os.environ["ACCESS_TOKEN"] ACCESS_SECRET = os.environ["ACCESS_SECRET"] CONSUMER_KEY = os.environ["CONSUMER_KEY"] CONSUMER_SECRET = os.environ["CONSUMER_SECRET"] oauth = OAuth(ACCESS_TOKEN, ACCESS_SECRET, CONSUMER_KEY, CONSUMER_SECRET) twitter = Twitter(auth=oauth) #polish pol_trends = twitter.trends.place(_id = 23424923) twittrendlistPL=[] for i in pol_trends[0]['trends']: twittrendlistPL.append(i['name']) strPLT="&lt;br&gt;".join(str(x) for x in twittrendlistPL[0:15]) #global trends globaltrends=twitter.trends.place(_id = 1) twittrendlist=[] for i in globaltrends[0]['trends']: twittrendlist.append(i['name']) def isEnglish(s): try: s.encode(encoding='utf-8').decode('ascii') except UnicodeDecodeError: return False else: return True G=[i for i in twittrendlist if isEnglish(i)] strGT="&lt;br&gt;".join(str(x) for x in G[0:15]) #us headlines url = ('https://newsapi.org/v2/top-headlines?' 'country=us&amp;'+api_news) response = requests.get(url) listus=[] for i in range(len(response.json()['articles'])): listus.append(response.json()['articles'][i]['title']) listus.append(response.json()['articles'][i]['url']) strNUS="&lt;br&gt;".join(str(x) for x in listus[0:10]) #uk headlines url = ('https://newsapi.org/v2/top-headlines?country=gb&amp;'+api_news) response = requests.get(url) listGB=[] for i in range(len(response.json()['articles'])): listGB.append(response.json()['articles'][i]['title']) listGB.append(response.json()['articles'][i]['url']) strGB="&lt;br&gt;".join(str(x) for x in listGB[0:10]) #google news(global) headlines url = ("https://newsapi.org/v2/top-headlines?sources=google-news&amp;"+api_news) response = requests.get(url) listg=[] for i in range(len(response.json()['articles'])): listg.append(response.json()['articles'][i]['title']) listg.append(response.json()['articles'][i]['url']) strg="&lt;br&gt;".join(str(x) for x in listg[0:10]) #most popular from technology url = ("https://newsapi.org/v2/top-headlines?category=technology&amp;country=us&amp;sortBy=popularity&amp;"+api_news) response = requests.get(url) listt=[] for i in range(len(response.json()['articles'])): listt.append(response.json()['articles'][i]['title']) listt.append(response.json()['articles'][i]['url']) strt="&lt;br&gt;".join(str(x) for x in listt[0:10]) #yahoo trending charts page = requests.get("https://finance.yahoo.com/trending-tickers/") soup = BeautifulSoup(page.content, 'html.parser') base=soup.findAll('td', {'class':'data-col1 Ta(start) Pstart(10px) Miw(180px)'}) yhoo=[] for i in base: yhoo.append(i.get_text()) strYHOO='&lt;br&gt;'.join(str(x) for x in yhoo[0:15]) #crypto trends to find with urllib.request.urlopen("https://api.coinmarketcap.com/v2/ticker/") as url: cmc = json.loads(url.read().decode()) names=[] change=[] for i in cmc['data']: names.append(cmc['data'][i]['symbol']) change.append(cmc['data'][i]['quotes']['USD']['percent_change_24h']) change, names = zip(*sorted(zip(change, names))) cmcstr='&lt;br&gt;'.join([str(a) + ': '+ str(b) + '%' for a,b in zip(names[-5:],change[-5:])]) #create a dict to upload for db maind={ "Global Twitter trends": strGT, "Polish Twitter trends" : strPLT, "Top US headlines": strNUS, "Top UK headlines": strGB, "Top Google News headlines": strg, "Top tech headlines": strt, "Trending yahoo stocks": strYHOO, "CMC trending": cmcstr, "Date": str(datetime.date.today()) } #create and connect to mongo database mongo=os.environ["mongodb"] try: #local test #conn = MongoClient() #production conn = MongoClient(mongo) print("Connected successfully!!!") except: print("Could not connect to MongoDB") #Create/conn database db = conn.database # Created or Switched to collection names: trends collection = db.trends # Insert Data rec_id1 = collection.insert_one(maind) print("Data inserted with record ids",rec_id1) mpass=os.environ["mpass"] record = collection.find_one({'Date': str(datetime.date.today())}) #create record that is from today #convert all from database so that its easier to put into mail gtt=record["Global Twitter trends"] ptt=record["Polish Twitter trends"] tus=record["Top US headlines"] tuk=record["Top UK headlines"] tgn=record["Top Google News headlines"] tech=record["Top tech headlines"] cmc=record["CMC trending"] yahoo=record["Trending yahoo stocks"] date=record["Date"] #crate function to send mail def send_email(date, *args): #login data from_email="" #sending mail from_password=mpass to_email="" #recipient subject="Daily trends {0}".format(date) message="Today's dose of news and trends starting with global twitter trends:&lt;br&gt; &lt;strong&gt;{0}&lt;/strong&gt;. &lt;br&gt; &lt;br&gt; Polish twitter:&lt;br&gt; &lt;strong&gt;{1}&lt;/strong&gt; &lt;br&gt; &lt;br&gt; Top us headlines:&lt;br&gt; &lt;strong&gt;{2}&lt;/strong&gt; &lt;br&gt; &lt;br&gt; Top uk headlines:&lt;br&gt; &lt;strong&gt;{3}&lt;/strong&gt; &lt;br&gt; &lt;br&gt; Top news headlines:&lt;br&gt; &lt;strong&gt;{4}&lt;/strong&gt; &lt;br&gt; &lt;br&gt; Tech news:&lt;br&gt; &lt;strong&gt;{5}&lt;/strong&gt; &lt;br&gt; &lt;br&gt; CMC trending:&lt;br&gt; &lt;strong&gt;{6}&lt;/strong&gt; &lt;br&gt; &lt;br&gt; Yahoo trending:&lt;br&gt; &lt;strong&gt;{7}&lt;/strong&gt; &lt;br&gt;".format(*args) msg=MIMEText(message, 'html') #msg setup msg['Subject']=subject msg['To']=to_email msg['From']=from_email gmail=smtplib.SMTP('smtp.gmail.com', 587) #mail setup gmail.ehlo() gmail.starttls() gmail.login(from_email, from_password) gmail.send_message(msg) send_email(date, gtt, ptt, tus, tuk, tgn, tech, cmc, yahoo) </code></pre>
[]
[ { "body": "<h1>Now isn't now</h1>\n\n<p>You call <code>now</code> at the top of the program. First of all, it's never used, so it should be deleted. Even if it were used, this call should be moved next to the usage so that any delay between program start and the usage of this variable won't introduce error.</p>\n\n<h1>Use what Python gives you</h1>\n\n<p>In this case, <code>os.environ[\"api_news\"]</code> is more easily expressed as:</p>\n\n<pre><code>from os import getenv\n# ...\napi_news = getenv('api_news')\n</code></pre>\n\n<h1>Configuration</h1>\n\n<p>This isn't Python-specific, but for the kind of configuration you're pulling from the environment (access token, secret, etc.), the environment isn't really an appropriate place to keep it. Keep it in a permissions-protected file, perhaps JSON for ease of use.</p>\n\n<h1>Make some functions</h1>\n\n<p>Resist the urge to dump all of your code into global scope. Make a <code>main</code> method and a handful of subroutines. This makes the stack trace meaningful if something goes wrong, and helps with maintainability.</p>\n\n<h1>Use snake case</h1>\n\n<p>Python promotes <code>is_english</code> instead of <code>isEnglish</code>, in general.</p>\n\n<h1>Use requests features</h1>\n\n<p>You're using requests, which buys you a lot of power. Strip the query params off of your url and pass them into <code>get</code> as a dictionary on the <code>params</code> kwarg.</p>\n\n<h1>Only call json() once</h1>\n\n<p>You call <code>json()</code> a bunch of times on the response. Instead, you should probably save a temporary variable:</p>\n\n<pre><code>articles = response.json()['articles']\n</code></pre>\n\n<p>and work with that.</p>\n\n<h1>Check for failure</h1>\n\n<p>Call <code>response.raise_for_status()</code>.</p>\n\n<h1>Form strg as a text stream</h1>\n\n<p>Rather than populating <code>listg</code> in a loop and then <code>join</code>ing it to <code>strg</code>, you should make <code>strg</code> a <code>StringIO</code> and write it out that way, so that you don't need to hold onto a list object at all.</p>\n\n<h1>Early-bail out of your loops</h1>\n\n<p>You're iterating over all of your content in several places but then only using the first ten items. Instead, slice the content before iterating. Also, don't use an index; iterate through the list itself. In other words:</p>\n\n<pre><code>for article in articles[:10]:\n</code></pre>\n\n<h1>Use f-strings</h1>\n\n<p>This:</p>\n\n<pre><code>str(a) + ': '+ str(b) + '%'\n</code></pre>\n\n<p>can be expressed as</p>\n\n<pre><code>f'{a}: {b}%'\n</code></pre>\n\n<h1>Don't except</h1>\n\n<p>There are a few problems with your bare <code>except:</code>. First of all, it's catching things you won't expect to catch, like a user's Ctrl+C. At the least, you should be doing <code>except Exception:</code>. Also, when you fail, you don't do anything useful. You should probably print the exception along with your failure message and re-raise rather than continuing on with your database code.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-17T18:00:51.493", "Id": "215619", "ParentId": "215586", "Score": "5" } } ]
{ "AcceptedAnswerId": "215619", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-17T01:29:24.583", "Id": "215586", "Score": "4", "Tags": [ "python", "performance", "mongodb" ], "Title": "Get data and send mail script" }
215586
<p>I am a hobbyist computer programmer trying to learn modern C++ (in this case C++17). I thought it might be an interesting challenge to write a Binary Search Tree similar to <code>std::map</code> while using heap-like array structure to store the elements of the tree such that the index of the parent node is always half that of the child nodes and the root node index is one. As expected this leads to a poor performing implementation (unlike moving pointers around, elements needed to be moved around the array (<code>std::vector</code>) one at a time).</p> <p>During the course of this work I did learn of the <a href="http://supertech.csail.mit.edu/papers/debruijn.pdf" rel="nofollow noreferrer">DeBruijn algorithm</a> for determining the most significant bit. I did make some naming design choices that may be unconventional: variables (including <code>constexpr</code> variables) are all snake_case as are all of the public facing <code>std::map</code>-like functions. Internal private functions are camelCase as are non-STL functions (<code>isBST</code>, <code>viewTree</code>, etc.) that are used for debugging. Enum classes are CamelCase. I hope folks aren’t too offended by these choices, but they helped me keep things straight. This BST uses the AVL self-balancing method (yes, I know <code>std::map</code> uses red-black), and I must confess some of the weights did get away from me. In the end I resorted to some on-the-fly reweighting schemes that probably make the program even slower than it would have been without resorting to this method (see <code>rebalance</code> – <code>reweight</code> (pivot) – should be totally unnecessary, but I never found its cause. Extra thanks to the person who finds the missing weight term).</p> <p>During the course of this project I needed to come up with methods to compute how to shift nodes around to simulate moving sub-trees. Suggestions, better methods within these constraints, etc. will be appreciated.</p> <p>BSTree.hpp:</p> <pre><code>#pragma once #ifndef BSTREE #define BSTREE #include &lt;cstdint&gt; #include &lt;functional&gt; #include &lt;iomanip&gt; #include &lt;iostream&gt; #include &lt;queue&gt; #include &lt;sstream&gt; #include &lt;stack&gt; #include &lt;utility&gt; #include &lt;vector&gt; #include &lt;gsl.h&gt; #include &lt;stdexcept&gt; constexpr std::size_t min_size = 2; constexpr std::size_t root_node = 1; constexpr std::size_t default_depth = 4; constexpr std::size_t out_of_range = 0; constexpr void printSpaces(std::size_t num) { for (std::size_t i = 0; i &lt; num; ++i) std::cout &lt;&lt; ' '; } constexpr std::size_t leftChild(size_t index) { return index &lt;&lt; 1; } constexpr std::size_t rightChild(size_t index) { return (index &lt;&lt; 1) + 1; } constexpr std::size_t myParent(size_t index) { return index &gt;&gt; 1; } constexpr bool isLeftEdge(std::size_t index) { std::size_t temp = index &gt;&gt; 1; temp |= temp &gt;&gt; 1; // temp + 1 = 2^(floor(log2(index))) temp |= temp &gt;&gt; 2; // which is on the left edge temp |= temp &gt;&gt; 4; temp |= temp &gt;&gt; 8; temp |= temp &gt;&gt; 16; return temp + 1 == index; } constexpr bool isRightEdge(std::size_t index) { std::size_t temp = index; temp |= temp &gt;&gt; 1; // temp = 2^(floor(log2(index))+1)-1 temp |= temp &gt;&gt; 2; // which is on the right edge temp |= temp &gt;&gt; 4; temp |= temp &gt;&gt; 8; temp |= temp &gt;&gt; 16; return temp == index; } enum class Justify { Left, Right, Center }; enum class ChildType :bool { Left, Right }; constexpr ChildType whatType(std::size_t index) { if(index &amp; 1) return ChildType::Right; return ChildType::Left; } template &lt;class K, class M = char&gt; class BSTree { public: struct Node; using key_type = K; using key_compare = std::function&lt;bool(const key_type&amp;, const key_type&amp;)&gt;; using value_type = std::pair&lt;K, M&gt;; using mapped_type = M; using reference = value_type&amp; ; using const_reference = const value_type&amp;; using size_type = std::size_t; using container_type = std::vector&lt;Node&gt;; template &lt;bool isconst&gt; struct bstIterator; class value_compare; using iterator = bstIterator&lt;false&gt;; using const_iterator = bstIterator&lt;true&gt;; BSTree(std::size_t size = min_size); BSTree(std::size_t size, const key_compare fn); mapped_type&amp; at(const key_type&amp; key); const mapped_type&amp; at(const key_type&amp; key) const; iterator begin(); const_iterator begin() const; const_iterator cbegin() const; void clear(); std::size_t count(const key_type&amp; key) const; const_iterator cend() const noexcept; const_iterator crbegin() const; const_iterator crend() const noexcept; iterator end() noexcept; const_iterator end() const noexcept; std::pair&lt;iterator, iterator&gt; equal_range(const key_type&amp; key); std::pair&lt;const_iterator, const_iterator&gt; equal_range(const key_type&amp; key) const; iterator erase(const_iterator position); iterator erase(const_iterator first, const_iterator last); std::size_t erase(const key_type&amp; key); iterator find(const key_type key); const_iterator find(const key_type key) const; std::size_t height(); std::pair&lt;typename BSTree&lt;K, M&gt;::iterator, bool&gt; insert(const key_type&amp; key, const mapped_type&amp; mapped = mapped_type()); std::pair&lt;typename BSTree&lt;K, M&gt;::iterator, bool&gt; insert(const value_type &amp; value); iterator insert(iterator, const value_type &amp; value); template &lt;class InputIterator&gt; void insert(InputIterator first, InputIterator last); void insert(std::initializer_list&lt;value_type&gt; il); bool isBalanced(); bool isBST(); key_compare key_comp() const; iterator lower_bound(const key_type&amp; key); const_iterator lower_bound(const key_type&amp; key) const; mapped_type&amp; operator[](const key_type&amp; key); void reserve(std::size_t size); std::size_t size() const noexcept; void swap(BSTree&amp;) noexcept; iterator rbegin(); const_iterator rbegin() const; iterator rend() noexcept; const_iterator rend() const noexcept; iterator upper_bound(const key_type &amp; key); const_iterator upper_bound(const key_type &amp; key) const; value_compare value_comp; void viewKeys(); void viewTree(std::size_t root = root_node, std::size_t depth = default_depth); class value_compare { friend class BSTree; protected: key_compare comp; value_compare(key_compare c):comp(c) {} public: using result_type = bool; using first_argument_type = value_type; using second_argument_type = value_type; bool operator()(const value_type&amp; a, const value_type&amp; b) const { return comp(a.first, b.first); } }; template &lt;bool isconst = false&gt; struct bstIterator { public: using value_type = std::pair&lt;K, M&gt;; using reference = typename std::conditional_t &lt; isconst, value_type const &amp;, value_type &amp; &gt;; using pointer = typename std::conditional_t &lt; isconst, value_type const *, value_type * &gt;; using vec_pointer = typename std::conditional_t &lt;isconst, std::vector&lt;Node&gt; const *, std::vector&lt;Node&gt; *&gt;; using key_compare_pointer = typename std::conditional_t &lt;isconst, std::function&lt;bool(const K&amp;, const K&amp;)&gt; const *, std::function&lt;bool(const K&amp;, const K&amp;)&gt; *&gt;; using iterator_category = std::bidirectional_iterator_tag; bstIterator() noexcept : ptrToBuffer(nullptr), index_(0), reverse_(false), ptrToComp(nullptr) {} /* * copy/conversion constructor */ bstIterator(const BSTree&lt;K, M&gt;::bstIterator&lt;false&gt;&amp; i) noexcept : ptrToBuffer(i.ptrToBuffer), index_(i.index_), reverse_(i.reverse_), ptrToComp(i.ptrToComp) {} /* * dereferencing and other operators */ reference operator*() { if (index_ == out_of_range) { std::stringstream ss; ss &lt;&lt; "\nPointer Out Of Range!\n"; throw std::out_of_range(ss.str()); } return (*ptrToBuffer).at(index_).value_; } pointer operator-&gt;() { return &amp;(operator *()); } bstIterator&amp; operator++ () { if (!reverse_) { if (index_ == out_of_range) { std::stringstream ss; ss &lt;&lt; "\nOut Of Range: operator++\n"; throw std::out_of_range(ss.str()); } nextIndex(); return *this; } if (index_ != out_of_range) previousIndex(); else index_ = highest(root_node); return *this; } bstIterator operator ++(int) { const bstIterator iter = *this; if (!reverse_) { if (index_ == out_of_range) { std::stringstream ss; ss &lt;&lt; "\nOut Of Range: operator ++(int)\n"; throw std::out_of_range(ss.str()); } nextIndex(); return iter; } if(index_ != out_of_range) previousIndex(); else index_ = highest(root_node); return iter; } bstIterator&amp; operator --() { if (reverse_) { if (index_ == out_of_range) { std::stringstream ss; ss &lt;&lt; "\nOut Of Range: operator--\n"; throw std::out_of_range(ss.str()); } nextIndex(); return *this; } if (index_ != out_of_range) previousIndex(); else index_ = highest(root_node); return *this; } bstIterator operator --(int) { const bstIterator iter = *this; if (reverse_) { if (index_ == out_of_range) { std::stringstream ss; ss &lt;&lt; "\nOut Of Range: operator --(int)\n"; throw std::out_of_range(ss.str()); } nextIndex(); return iter; } if (index_ != out_of_range) previousIndex(); else index_ = highest(root_node); return iter; } bool operator==(const bstIterator &amp;other) noexcept { if (comparable(other)) return (index_ == other.index_); return false; } bool operator!=(const bstIterator &amp;other) noexcept { if (comparable(other)) return !this-&gt;operator==(other); return true; } friend class BSTree&lt;K, M&gt;; private: inline bool comparable(const bstIterator &amp; other) noexcept { return (reverse_ == other.reverse_); } std::size_t highest(std::size_t root) { while ((*ptrToBuffer).at(root).rnode) root = rightChild(root); return root; } std::size_t lowest(std::size_t root) { while ((*ptrToBuffer).at(root).lnode) root = leftChild(root); return root; } void nextIndex() { if ((*ptrToBuffer).at(index_).rnode) { index_ = lowest(rightChild(index_)); return; } if (!isRightEdge(index_)) { const key_type key = (*ptrToBuffer).at(index_).key(); index_ = myParent(index_); while ((*ptrToComp)((*ptrToBuffer).at(index_).key(), key)) index_ = myParent(index_); } else index_ = out_of_range; } void previousIndex() { if ((*ptrToBuffer).at(index_).lnode) { index_ = highest(leftChild(index_)); return; } if (!isLeftEdge(index_)) { const key_type key = (*ptrToBuffer).at(index_).key(); index_ = myParent(index_); while ((*ptrToComp)(key, (*ptrToBuffer).at(index_).key())) index_ = myParent(index_); } else index_ = out_of_range; } vec_pointer ptrToBuffer; size_type index_; bool reverse_; key_compare_pointer ptrToComp; }; private: struct Node { Node(key_type key = key_type(), mapped_type mapped = mapped_type()) noexcept : value_(std::make_pair(key, mapped)), lnode(false), rnode(false) {} Node(value_type value) : value_(value), lnode(false), rnode(false) {} Node(const Node &amp;node) : value_(node.value_), lnode(node.lnode), rnode(node.rnode) {} virtual ~Node() = default; Node&amp; operator=(const Node&amp;) = default; Node(Node&amp;&amp;) = default; Node&amp; operator=(Node&amp;&amp;) = default; key_type&amp; key() noexcept { return value_.first; } const key_type&amp; key() const noexcept { return value_.first; } mapped_type&amp; mapped() noexcept { return value_.second; } const mapped_type&amp; mapped() const { return value_.second; } void printKey(std::size_t size, Justify just); value_type value_; bool lnode; bool rnode; }; uint8_t msbDeBruijn32(uint32_t v) noexcept; void moveDown(std::size_t root, ChildType type); void shift(std::size_t root, int diff); void moveUp(std::size_t); void shiftLeft(std::size_t); void shiftRight(std::size_t); void rotateRight(std::size_t index); void rotateLeft(std::size_t index); void rotateLR(std::size_t index); void rotateRL(std::size_t index); void reweight(std::size_t index); bool rebalanceRoot(); bool rebalance(std::size_t index, bool increase); void simpleRemove(std::size_t parent, ChildType type); std::size_t bottomNode(std::size_t current, ChildType type); void complexRemove(std::size_t child, ChildType type); void wipeout(std::size_t child, ChildType type); std::size_t locate(key_type key, std::size_t start = root_node); std::size_t erase(const key_type&amp; key, std::size_t start); std::size_t height(std::size_t node); void inject(std::size_t index, iterator&amp; iter, key_type key, mapped_type mapped, ChildType type); std::pair&lt;typename BSTree&lt;K, M&gt;::iterator, bool&gt; insert(std::size_t, const key_type &amp; , const mapped_type &amp; ); iterator bound(const key_type &amp; key, bool upper); bool isBalanced(std::size_t index); bool isBST(std::size_t current); void inorder(std::size_t index, std::function&lt;void(key_type&amp;, mapped_type&amp;)&gt; fn); void traverseByLevel(std::size_t root, std::size_t max_level, std::function&lt;void(std::size_t, std::size_t)&gt; fn); std::size_t node_count; std::vector&lt;Node&gt; nodes; std::vector&lt;int8_t&gt; weights; key_compare comp; }; template&lt;class K, class M&gt; inline BSTree&lt;K, M&gt;::BSTree(std::size_t size) : comp(std::less&lt;K&gt;()), value_comp(std::less&lt;K&gt;()) { try { nodes.reserve(size); weights.reserve(size); } catch (const std::exception&amp; e) { throw; } node_count = 0; } template&lt;class K, class M&gt; inline BSTree&lt;K, M&gt;::BSTree(std::size_t size, const key_compare fn) : comp(fn), value_comp(fn) { try { nodes.reserve(size); weights.reserve(size); } catch (const std::exception&amp; e) { throw; } node_count = 0; } template&lt;class K, class M&gt; inline typename BSTree&lt;K, M&gt;::mapped_type &amp; BSTree&lt;K, M&gt;::at(const key_type &amp; key) { const std::size_t index = locate(key); if (index == out_of_range) { std::stringstream ss; ss &lt;&lt; "\nOut Of Range for key: \"" &lt;&lt; key &lt;&lt; "\"\n"; throw std::out_of_range(ss.str()); } return nodes.at(index).mapped(); } template&lt;class K, class M&gt; inline const typename BSTree&lt;K, M&gt;::mapped_type &amp; BSTree&lt;K, M&gt;::at(const key_type &amp; key) const { std::size_t index = locate(key); if (index == out_of_range) { std::stringstream ss; ss &lt;&lt; "\nOut Of Range for key: \"" &lt;&lt; key &lt;&lt; "\"\n"; throw std::out_of_range(ss.str()); } return nodes.at(index).mapped(); } template&lt;class K, class M&gt; inline typename BSTree&lt;K, M&gt;::iterator BSTree&lt;K, M&gt;::begin() { iterator iter; iter.ptrToBuffer = &amp;nodes; iter.index_ = iter.lowest(root_node); iter.reverse_ = false; iter.ptrToComp = &amp;comp; return iter; } template&lt;class K, class M&gt; inline typename BSTree&lt;K, M&gt;::const_iterator BSTree&lt;K, M&gt;::begin() const { return cbegin(); } template&lt;class K, class M&gt; inline typename BSTree&lt;K, M&gt;::const_iterator BSTree&lt;K, M&gt;::cbegin() const { const_iterator iter; iter.ptrToBuffer = &amp;nodes; iter.index_ = iter.lowest(root_node); iter.reverse_ = false; iter.ptrToComp = &amp;comp; return iter; } template&lt;class K, class M&gt; inline void BSTree&lt;K, M&gt;::clear() { nodes.resize(min_size); weights.resize(min_size); node_count = 0; weights.at(root_node) = 0; nodes.at(root_node).lnode = false; nodes.at(root_node).rnode = false; } template&lt;class K, class M&gt; inline std::size_t BSTree&lt;K, M&gt;::count(const key_type&amp; key) const { if (locate(key) != out_of_range) return 1; return 0; } template&lt;class K, class M&gt; inline typename BSTree&lt;K, M&gt;::const_iterator BSTree&lt;K, M&gt;::cend() const noexcept { const_iterator iter; iter.ptrToBuffer = &amp;nodes; iter.index_ = out_of_range; iter.reverse_ = false; iter.ptrToComp = &amp;comp; return iter; } template&lt;class K, class M&gt; inline typename BSTree&lt;K, M&gt;::const_iterator BSTree&lt;K, M&gt;::crbegin() const { const_iterator iter; iter.ptrToBuffer = &amp;nodes; iter.index_ = iter.highest(root_node); iter.reverse_ = true; iter.ptrToComp = &amp;comp; return iter; } template&lt;class K, class M&gt; inline typename BSTree&lt;K, M&gt;::const_iterator BSTree&lt;K, M&gt;::crend() const noexcept { const_iterator iter; iter.ptrToBuffer = &amp;nodes; iter.index_ = out_of_range; iter.reverse_ = true; iter.ptrToComp = &amp;comp; return iter; } template&lt;class K, class M&gt; inline typename BSTree&lt;K, M&gt;::iterator BSTree&lt;K, M&gt;::end() noexcept { iterator iter; iter.ptrToBuffer = &amp;nodes; iter.index_ = out_of_range; iter.reverse_ = false; iter.ptrToComp = &amp;comp; return iter; } template&lt;class K, class M&gt; inline typename BSTree&lt;K, M&gt;::const_iterator BSTree&lt;K, M&gt;::end() const noexcept { return cend(); } template&lt;class K, class M&gt; inline std::pair&lt;typename BSTree&lt;K, M&gt;::iterator, typename BSTree&lt;K, M&gt;::iterator&gt; BSTree&lt;K, M&gt;::equal_range(const key_type &amp; key) { iterator lower = bound(key, false); iterator upper = bound(key, true); return std::make_pair(lower, upper); } template&lt;class K, class M&gt; inline std::pair&lt;typename BSTree&lt;K, M&gt;::const_iterator, typename BSTree&lt;K, M&gt;::const_iterator&gt; BSTree&lt;K, M&gt;::equal_range(const key_type &amp; key) const { std::pair&lt;const_iterator, const_iterator&gt; range; const_iterator&amp; lower = range.first; const_iterator&amp; upper = range.second; lower = upper = lower_bound(); upper.nextIndex(); return range; } template&lt;class K, class M&gt; inline uint8_t BSTree&lt;K, M&gt;::msbDeBruijn32(uint32_t v) noexcept { /* The use of a deBruijn sequence in order to find the most significant bit (MSB) in a 32-bit value. This cool idea is from a 1998 paper out of MIT (http://supertech.csail.mit.edu/papers/debruijn.pdf). */ static const std::array&lt;uint8_t, 32&gt; BitPosition { 0, 9, 1, 10, 13, 21, 2, 29, 11, 14, 16, 18, 22, 25, 3, 30, 8, 12, 20, 28, 15, 17, 24, 7, 19, 27, 23, 6, 26, 5, 4, 31 }; v |= v &gt;&gt; 1; // first round down to one less than a power of 2 v |= v &gt;&gt; 2; v |= v &gt;&gt; 4; v |= v &gt;&gt; 8; v |= v &gt;&gt; 16; return BitPosition.at(gsl::narrow_cast&lt;uint32_t&gt;(v * 0x07C4ACDDU) &gt;&gt; 27); } template&lt;class K, class M&gt; inline void BSTree&lt;K, M&gt;::moveDown(std::size_t root, ChildType type) { std::stack&lt;std::size_t&gt; inv_tree; std::queue&lt;std::size_t&gt; sub_tree; sub_tree.push(root); while (!sub_tree.empty()) { const std::size_t current = sub_tree.front(); sub_tree.pop(); inv_tree.push(current); if (nodes.at(current).lnode) sub_tree.push(leftChild(current)); if (nodes.at(current).rnode) sub_tree.push(rightChild(current)); } const std::size_t diff = (type == ChildType::Left) ? root : root + 1; const int root_msb = msbDeBruijn32(root); while (!inv_tree.empty()) { const std::size_t current = inv_tree.top(); inv_tree.pop(); const int n = msbDeBruijn32(current); const std::size_t forward = current + diff * (1 &lt;&lt; (n - root_msb)); nodes.at(forward) = nodes.at(current); weights.at(forward) = weights.at(current); nodes.at(current).lnode = false; nodes.at(current).rnode = false; weights.at(current) = 0; } if (type == ChildType::Left) nodes.at(root).lnode = true; else nodes.at(root).rnode = true; } template&lt;class K, class M&gt; inline void BSTree&lt;K, M&gt;::shift(std::size_t root, int diff) { if (root &lt;= 1) return; std::queue&lt;size_t&gt; sub_tree; const int root_msb = msbDeBruijn32(root); sub_tree.push(root); while (true) { int levelCount = sub_tree.size(); if (levelCount == 0) return; while (levelCount &gt; 0) { const std::size_t current = sub_tree.front(); sub_tree.pop(); if (nodes.at(current).lnode) sub_tree.push(current &lt;&lt; 1); if (nodes.at(current).rnode) sub_tree.push((current &lt;&lt; 1) + 1); const int n = msbDeBruijn32(current); const std::size_t forward = current + diff * (1 &lt;&lt; (n - root_msb)); nodes.at(forward) = nodes.at(current); weights.at(forward) = weights.at(current); nodes.at(current).lnode = false; nodes.at(current).rnode = false; weights.at(current) = 0; --levelCount; } } } template&lt;class K, class M&gt; inline void BSTree&lt;K, M&gt;::moveUp(std::size_t root) { const int diff = (root &gt;&gt; 1) - root; shift(root, diff); } template&lt;class K, class M&gt; inline void BSTree&lt;K, M&gt;::shiftLeft(std::size_t root) { const int diff = -1; shift(root, diff); } template&lt;class K, class M&gt; inline void BSTree&lt;K, M&gt;::shiftRight(std::size_t root) { const int diff = 1; shift(root, diff); } template&lt;class K, class M&gt; inline void BSTree&lt;K, M&gt;::rotateRight(std::size_t index) { const std::size_t parent = myParent(index); nodes.at(parent).lnode = false; moveDown(parent, ChildType::Right); const std::size_t rchild = rightChild(index); const std::size_t sibling = index + 1; if (nodes.at(index).rnode) { shiftRight(rchild); nodes.at(index).rnode = false; nodes.at(sibling).lnode = true; } else { nodes.at(sibling).lnode = false; } moveUp(index); nodes.at(parent).rnode = true; reweight(parent); reweight(index); reweight(sibling); } template&lt;class K, class M&gt; inline void BSTree&lt;K, M&gt;::rotateLeft(std::size_t index) { const std::size_t parent = myParent(index); nodes.at(parent).rnode = false; moveDown(parent, ChildType::Left); const std::size_t lchild = leftChild(index); const std::size_t sibling = index - 1; if (nodes.at(index).lnode) { shiftLeft(lchild); nodes.at(index).lnode = false; nodes.at(sibling).rnode = true; } else { nodes.at(sibling).rnode = false; } moveUp(index); nodes.at(parent).lnode = true; reweight(parent); reweight(index); reweight(sibling); } template&lt;class K, class M&gt; inline void BSTree&lt;K, M&gt;::rotateLR(std::size_t index) { const std::size_t parent = myParent(index); const std::size_t rchild = rightChild(index); std::size_t rlgrand(out_of_range), rrgrand(out_of_range); if (nodes.at(rchild).lnode) rlgrand = leftChild(rchild); if (nodes.at(rchild).rnode) rrgrand = rightChild(rchild); nodes.at(parent).lnode = false; moveDown(parent, ChildType::Right); nodes.at(parent) = nodes.at(rchild); nodes.at(rchild).lnode = false; nodes.at(rchild).rnode = false; nodes.at(index).rnode = false; const std::size_t sibling = index + 1; if (rrgrand != out_of_range) { const int diff = ((rrgrand + 1) &gt;&gt; 1) - rrgrand; shift(rrgrand, diff); nodes.at(sibling).lnode = true; } if (rlgrand != out_of_range) { moveUp(rlgrand); nodes.at(index).rnode = true; } nodes.at(parent).rnode = true; nodes.at(parent).lnode = true; reweight(rchild); reweight(parent); reweight(index); reweight(sibling); } template&lt;class K, class M&gt; inline void BSTree&lt;K, M&gt;::rotateRL(std::size_t index) { const std::size_t parent = myParent(index); const std::size_t lchild = leftChild(index); std::size_t llgrand(out_of_range), lrgrand(out_of_range); if (nodes.at(lchild).lnode) llgrand = leftChild(lchild); if (nodes.at(lchild).rnode) lrgrand = rightChild(lchild); nodes.at(parent).rnode = false; moveDown(parent, ChildType::Left); nodes.at(parent) = nodes.at(lchild); nodes.at(lchild).lnode = false; nodes.at(lchild).rnode = false; nodes.at(index).lnode = false; const std::size_t sibling = index - 1; if (llgrand != out_of_range) { const int diff = ((llgrand - 1) &gt;&gt; 1) - llgrand; shift(llgrand, diff); nodes.at(sibling).rnode = true; } if (lrgrand != out_of_range) { moveUp(lrgrand); nodes.at(index).lnode = true; } nodes.at(parent).lnode = true; nodes.at(parent).rnode = true; reweight(lchild); reweight(parent); reweight(index); reweight(sibling); } template&lt;class K, class M&gt; inline void BSTree&lt;K, M&gt;::reweight(std::size_t index) { int left(0), right(0); if (nodes.at(index).lnode) left = gsl::narrow_cast&lt;int&gt;(height(leftChild(index))); if (nodes.at(index).rnode) right = gsl::narrow_cast&lt;int&gt;(height(rightChild(index))); weights.at(index) = gsl::narrow_cast&lt;int8_t&gt;(right - left); } template&lt;class K, class M&gt; inline bool BSTree&lt;K, M&gt;::rebalanceRoot() { reweight(root_node); if (weights.at(root_node) &gt;= -1 &amp;&amp; weights.at(root_node) &lt;= 1) return false; if (weights.at(root_node) &gt; 0) rotateLeft(rightChild(root_node)); else rotateRight(leftChild(root_node)); reweight(root_node); return true; } template&lt;class K, class M&gt; inline bool BSTree&lt;K, M&gt;::rebalance(std::size_t index, bool increase) { if (index == 1) { return rebalanceRoot(); } const bool changed = true; while (index &gt; 1) { const std::size_t parent = myParent(index); const int8_t old_weight = weights.at(parent); reweight(parent); if (weights.at(parent) == old_weight) return !changed; if ((whatType(index) == ChildType::Left &amp;&amp; increase) || (whatType(index) == ChildType::Right &amp;&amp; !increase)) { if (weights.at(parent) &lt; -1) { const std::size_t pivot = leftChild(parent); reweight(pivot); // Added since weights can be inacurate (eek!) if (weights.at(pivot) &lt; 0) rotateRight(pivot); else rotateLR(pivot); return changed; } index = parent; if (weights.at(index) == 0) return !changed; continue; } if (weights.at(parent) &gt; 1) { const std::size_t pivot = rightChild(parent); reweight(pivot); // Added since weights can be inacurate (eek!) if (weights.at(pivot) &gt; 0) rotateLeft(pivot); else rotateRL(pivot); return changed; } index = parent; if (weights.at(index) == 0) return !changed; } return changed; } template&lt;class K, class M&gt; void BSTree&lt;K, M&gt;::simpleRemove(std::size_t index, ChildType type) { const std::size_t parent = myParent(index); /* nodes.at(index).lnode = false; nodes.at(index).rnode = false; */ weights.at(index) = 0; if (type == ChildType::Right) { nodes.at(parent).rnode = false; if (weights.at(parent) - 1 &lt; -1) { const std::size_t sibling = index - 1; rebalance(sibling, true); return; } if (--weights.at(parent) == 0) rebalance(parent, false); } else { nodes.at(parent).lnode = false; if (weights.at(parent) + 1 &gt; 1) { const std::size_t sibling = index + 1; rebalance(sibling, true); return; } if (++weights.at(parent) == 0) rebalance(parent, false); } } template&lt;class K, class M&gt; std::size_t BSTree&lt;K, M&gt;::bottomNode(std::size_t current, ChildType type) { while (true) { if (type == ChildType::Right) { if (nodes.at(current).lnode) { current = leftChild(current); continue; } break; } if (nodes.at(current).rnode) { current = rightChild(current); continue; } break; } return current; } template&lt;class K, class M&gt; void BSTree&lt;K, M&gt;::complexRemove(std::size_t child, ChildType type) { const std::size_t index = myParent(child); if (type == ChildType::Left) { // move left child if (!nodes.at(child).rnode) { moveUp(child); nodes.at(index).rnode = true; if (++weights.at(index) == 0) rebalance(index, false); return; } wipeout(child, type); return; } if (!nodes.at(child).lnode) { // move right child moveUp(child); nodes.at(index).lnode = true; if (--weights.at(index) == 0) rebalance(index, false); return; } wipeout(child, type); return; } template&lt;class K, class M&gt; inline void BSTree&lt;K, M&gt;::wipeout(std::size_t child, ChildType type) { const std::size_t current = (type == ChildType::Left) ? bottomNode(rightChild(child), type) : bottomNode(leftChild(child), type); nodes.at(myParent(child)).value_ = nodes.at(current).value_; if (type==ChildType::Left) { if (nodes.at(current).lnode) moveUp(leftChild(current)); else nodes.at(myParent(current)).rnode = false; } else { if (nodes.at(current).rnode) moveUp(rightChild(current)); else nodes.at(myParent(current)).lnode = false; } rebalance(current, false); } template&lt;class K, class M&gt; std::size_t BSTree&lt;K, M&gt;::locate(key_type key, std::size_t start) { std::size_t current = start; while (true) { if (nodes.at(current).key() == key) return current; if (comp(key, nodes.at(current).key())) { if (!nodes.at(current).lnode) return out_of_range; current = current &lt;&lt; 1; continue; } if (!nodes.at(current).rnode) return out_of_range; current = (current &lt;&lt; 1) + 1; } return out_of_range; } template&lt;class K, class M&gt; typename BSTree&lt;K, M&gt;::iterator BSTree&lt;K, M&gt;::erase(const_iterator position) { constexpr std::size_t count_zero = 0; iterator iter; if (position == cend()) return end(); key_type next_key{}; std::size_t next_index(0); if (++position != cend()) { next_key = position-&gt;first; next_index = position.index_; } --position; if (erase(position-&gt;first, position.index_) == count_zero) return end(); if (next_index == out_of_range) return end(); iter = find(next_key); return iter; } template&lt;class K, class M&gt; typename BSTree&lt;K, M&gt;::iterator BSTree&lt;K, M&gt;::erase(const_iterator first, const_iterator last) { iterator iter; for (auto it = first; it != last; ++it) iter = erase(it); return iter; } template&lt;class K, class M&gt; std::size_t BSTree&lt;K, M&gt;::erase(const key_type&amp; key) { return erase(key, 1); } template&lt;class K, class M&gt; std::size_t BSTree&lt;K, M&gt;::erase(const key_type&amp; key, std::size_t start) { constexpr std::size_t count_zero = 0; constexpr std::size_t count_one = 1; const auto index = locate(key, start); if (index == out_of_range) return count_zero; const bool left = nodes.at(index).lnode; const bool right = nodes.at(index).rnode; --node_count; if (!left &amp;&amp; !right) { simpleRemove(index, whatType(index)); return count_one; } const std::size_t lchild = leftChild(index); const std::size_t rchild = rightChild(index); if (left &amp;&amp; !right) { moveUp(lchild); rebalance(index, false); return count_one; } if (!left &amp;&amp; right) { moveUp(rchild); rebalance(index, false); return count_one; } if (left&amp;&amp;right) { if (height(rchild) &lt;= height(lchild)) complexRemove(lchild, ChildType::Left); else complexRemove(rchild, ChildType::Right); return count_one; } throw std::exception(); return count_zero; } template&lt;class K, class M&gt; inline typename BSTree&lt;K, M&gt;::iterator BSTree&lt;K, M&gt;::find(const key_type key) { iterator iter; iter.ptrToBuffer = &amp;nodes; iter.reverse_ = false; iter.ptrToComp = &amp;comp; iter.index_ = locate(key); return iter; } template&lt;class K, class M&gt; inline typename BSTree&lt;K, M&gt;::const_iterator BSTree&lt;K, M&gt;::find(const key_type key) const { const_iterator iter; iter.ptrToBuffer = &amp;nodes; iter.reverse_ = false; iter.ptrToComp = &amp;comp; iter.index_ = locate(key); return iter; } template&lt;class K, class M&gt; std::size_t BSTree&lt;K, M&gt;::height(std::size_t index) { int height = 0; if (index == out_of_range) return height; std::queue&lt;size_t&gt; sub_tree; sub_tree.push(index); while (true) { int nodeCount = sub_tree.size(); if (nodeCount == 0) return height; height++; while (nodeCount &gt; 0) { const std::size_t current = sub_tree.front(); sub_tree.pop(); if (nodes.at(current).lnode) sub_tree.push(leftChild(current)); if (nodes.at(current).rnode) sub_tree.push(rightChild(current)); --nodeCount; } } } template&lt;class K, class M&gt; inline std::size_t BSTree&lt;K, M&gt;::height() { if (node_count == 0) return 0; return height(root_node); } template&lt;class K, class M&gt; inline void BSTree&lt;K, M&gt;::inject(std::size_t index, iterator &amp; iter, key_type key, mapped_type mapped, ChildType type) { ++node_count; std::size_t child{ 0 }; bool tilted = false; if (type == ChildType::Left) { child = leftChild(index); nodes.at(index).lnode = true; if (--weights.at(index) != 0) tilted = true; } else { child = rightChild(index); nodes.at(index).rnode = true; if (++weights.at(index) != 0) tilted = true; } nodes.at(child).key() = key; nodes.at(child).mapped() = mapped; weights.at(child) = 0; iter.index_ = child; if (tilted) { if (rebalance(index, true)) iter.index_ = locate(key); } } template&lt;class K, class M&gt; std::pair&lt;typename BSTree&lt;K, M&gt;::iterator, bool&gt; BSTree&lt;K, M&gt;::insert(std::size_t root, const key_type&amp; key, const mapped_type&amp; mapped) { iterator iter; iter.reverse_ = false; iter.ptrToComp = &amp;comp; iter.ptrToBuffer = &amp;nodes; if (node_count == 0) { ++node_count; nodes.resize(min_size); weights.resize(min_size); nodes.at(root_node).key() = key; nodes.at(root_node).mapped() = mapped; weights.at(root_node) = 0; iter.index_ = 1; return std::pair(iter, true); } std::size_t index = root; while (true) { if (key == nodes.at(index).key()) { nodes.at(index).mapped() = mapped; iter.index_ = index; return std::pair(iter, false); break; } if (2 * index &gt;= nodes.size()) { const int n = msbDeBruijn32(index); nodes.resize(1 &lt;&lt; (n + 2)); weights.resize(nodes.size()); } if (comp(key, nodes.at(index).key())) { if (!nodes.at(index).lnode) { inject(index, iter, key, mapped, ChildType::Left); return std::pair(iter, true); } index = leftChild(index); continue; } if (!nodes.at(index).rnode) { inject(index, iter, key, mapped, ChildType::Right); return std::pair(iter, true); } index = rightChild(index); } } template&lt;class K, class M&gt; std::pair&lt;typename BSTree&lt;K, M&gt;::iterator, bool&gt; BSTree&lt;K, M&gt;::insert(const key_type&amp; key, const mapped_type&amp; mapped) { return insert(1, key, mapped); } template&lt;class K, class M&gt; inline std::pair&lt;typename BSTree&lt;K, M&gt;::iterator, bool&gt; BSTree&lt;K, M&gt;::insert(const value_type&amp; value) { return insert(value.first, value.second); } template&lt;class K, class M&gt; inline typename BSTree&lt;K, M&gt;::iterator BSTree&lt;K, M&gt;::insert(iterator hint, const value_type &amp; value) { const std::size_t index = hint.index_; if (index == out_of_range) { if (!comp(value.first, (--hint)-&gt;first)) return insert(hint.index_, value.first, value.second).first; return insert(root_node, value.first, value.second).first; } if (comp(value.first, hint-&gt;first)) { --hint; if (hint.index_ == out_of_range || !comp(value.first, hint-&gt;first)) return insert(index, value.first, value.second).first; return insert(root_node, value.first, value.second).first; } ++hint; if (hint.index_ == out_of_range || comp(value.first, hint-&gt;first)) return insert(index, value.first, value.second).first; return insert(root_node, value.first, value.second).first; } template&lt;class K, class M&gt; template&lt;class InputIterator&gt; inline void BSTree&lt;K, M&gt;::insert(InputIterator first, InputIterator last) { for (auto it = first; it != last; ++it) const auto reply = insert(root_node, it-&gt;first, it-&gt;second); } template&lt;class K, class M&gt; inline void BSTree&lt;K, M&gt;::insert(std::initializer_list&lt;value_type&gt; il) { for (auto it = il.begin(); it != il.end(); ++it) const auto reply = insert(root_node, it-&gt;first, it-&gt;second); } template&lt;class K, class M&gt; bool BSTree&lt;K, M&gt;::isBalanced(std::size_t index) { std::size_t old_level = gsl::narrow_cast&lt;std::size_t&gt;(-1); bool ret = true; if (index == out_of_range) return true; traverseByLevel(index, height(index), [&amp;](std::size_t level, std::size_t current) -&gt; void { if (level != old_level) { old_level = level; } if (current == 0) return; if (nodes.at(current).lnode || nodes.at(current).rnode) { const std::size_t lheight = height(leftChild(current)); const std::size_t rheight = height(rightChild(current)); if ((lheight &gt; rheight) &amp;&amp; (lheight - rheight &gt; 1) || (rheight &gt; lheight) &amp;&amp; (rheight - lheight &gt; 1)) { ret = false; return; } } }); return ret; } template&lt;class K, class M&gt; inline bool BSTree&lt;K, M&gt;::isBalanced() { return isBalanced(root_node); } template&lt;class K, class M&gt; bool BSTree&lt;K, M&gt;::isBST(std::size_t index) { std::size_t old_level = gsl::narrow_cast&lt;std::size_t&gt;(-1); bool ret = true; if (index == out_of_range) return true; traverseByLevel(index, height(index), [&amp;](std::size_t level, std::size_t current) -&gt; void { if (level != old_level) { old_level = level; } if (current == 0) return; if (nodes.at(current).lnode) { const std::size_t lchild = leftChild(current); if (comp(nodes.at(current).key(), nodes.at(lchild).key())) { ret = false; return; } } if (nodes.at(current).rnode) { const std::size_t rchild = rightChild(current); if (comp(nodes.at(rchild).key(), nodes.at(current).key())) { ret = false; return; } } }); return ret; } template&lt;class K, class M&gt; inline bool BSTree&lt;K, M&gt;::isBST() { return isBST(root_node); } template&lt;class K, class M&gt; inline typename BSTree&lt;K, M&gt;::key_compare BSTree&lt;K, M&gt;::key_comp() const { return comp; } template&lt;class K, class M&gt; inline typename BSTree&lt;K, M&gt;::iterator BSTree&lt;K, M&gt;::bound(const key_type &amp; key, bool upper) { iterator iter; std::size_t index = root_node; iter.ptrToBuffer = &amp;nodes; iter.reverse_ = false; iter.ptrToComp = &amp;comp; while (true) { if (key == nodes.at(index).key()) { iter.index_ = index; if (upper) return ++iter; return iter; } if (comp(key, nodes.at(index).key())) { // key &lt; root-&gt;key if (nodes.at(index).lnode) { index = leftChild(index); continue; } else { iter.index_ = index; return iter; } } if (nodes.at(index).rnode) { index = rightChild(index); continue; } iter.index_ = index; return ++iter; } } template&lt;class K, class M&gt; inline typename BSTree&lt;K, M&gt;::iterator BSTree&lt;K, M&gt;::lower_bound(const key_type &amp; key) { return bound(key, false); } template&lt;class K, class M&gt; inline typename BSTree&lt;K, M&gt;::const_iterator BSTree&lt;K, M&gt;::lower_bound(const key_type &amp; key) const { const_iterator iter; iter = bound(key, false); return iter; } template&lt;class K, class M&gt; inline typename BSTree&lt;K, M&gt;::mapped_type &amp; BSTree&lt;K, M&gt;::operator[](const key_type &amp; key) { std::size_t index = locate(key); if (index == out_of_range) { mapped_type mapped{}; const auto[iter, reply] = insert(root_node, key, mapped); index = iter.index_; } return nodes.at(index).mapped(); } template&lt;class K, class M&gt; inline void BSTree&lt;K, M&gt;::reserve(std::size_t size) { nodes.reserve(size); weights.reserve(size); } template&lt;class K, class M&gt; inline std::size_t BSTree&lt;K, M&gt;::size() const noexcept { return node_count; } template&lt;class K, class M&gt; inline void BSTree&lt;K, M&gt;::swap(BSTree &amp; other) noexcept { std::swap(nodes, other.nodes); std::swap(weights, other.weights); std::swap(node_count, other.node_count); } template&lt;class K, class M&gt; inline typename BSTree&lt;K, M&gt;::iterator BSTree&lt;K, M&gt;::rbegin() { iterator iter; iter.ptrToBuffer = &amp;nodes; iter.index_ = iter.highest(root_node); iter.reverse_ = true; iter.ptrToComp = &amp;comp; return iter; } template&lt;class K, class M&gt; inline typename BSTree&lt;K, M&gt;::const_iterator BSTree&lt;K, M&gt;::rbegin() const { return crbegin(); } template&lt;class K, class M&gt; inline typename BSTree&lt;K, M&gt;::iterator BSTree&lt;K, M&gt;::rend() noexcept { iterator iter; iter.ptrToBuffer = &amp;nodes; iter.index_ = out_of_range; iter.reverse_ = true; iter.ptrToComp = &amp;comp; return iter; } template&lt;class K, class M&gt; inline typename BSTree&lt;K, M&gt;::const_iterator BSTree&lt;K, M&gt;::rend() const noexcept { return crend(); } template&lt;class K, class M&gt; inline typename BSTree&lt;K, M&gt;::iterator BSTree&lt;K, M&gt;::upper_bound(const key_type &amp; key) { return bound(key, true); } template&lt;class K, class M&gt; inline typename BSTree&lt;K, M&gt;::const_iterator BSTree&lt;K, M&gt;::upper_bound(const key_type &amp; key) const { const_iterator iter; iter = bound(key, true); return iter; } template&lt;class K, class M&gt; void BSTree&lt;K, M&gt;::inorder(std::size_t index, std::function&lt;void(key_type&amp;, mapped_type&amp;)&gt; fn) { if (index == out_of_range) return; size_t current = index; std::stack&lt;size_t&gt; s; while (!s.empty() || current != out_of_range) { if (current != out_of_range) { s.push(current); if (!nodes.at(current).lnode) current = out_of_range; else current = leftChild(current); } else { current = s.top(); s.pop(); fn(nodes.at(current).key(), nodes.at(current).mapped()); if (!nodes.at(current).rnode) current = out_of_range; else current = rightChild(current); } } } template&lt;class K, class M&gt; inline void BSTree&lt;K, M&gt;::viewKeys() { inorder(1, [](key_type&amp; key, mapped_type&amp; mapped) -&gt; void { std::cout &lt;&lt; key &lt;&lt; '\n'; }); } template&lt;class K, class M&gt; inline void BSTree&lt;K, M&gt;::traverseByLevel(std::size_t root, std::size_t max_level, std::function&lt;void(std::size_t, std::size_t)&gt; fn) { if (root &lt; 1) return; std::queue&lt;size_t&gt; sub_tree; sub_tree.push(root); std::size_t level = 0; while (level &lt; max_level) { int levelCount = sub_tree.size(); if (levelCount == 0) return; while (levelCount &gt; 0) { const std::size_t current = sub_tree.front(); sub_tree.pop(); if (nodes.at(current).lnode) sub_tree.push(leftChild(current)); else sub_tree.push(0); if (nodes.at(current).rnode) sub_tree.push(rightChild(current)); else sub_tree.push(0); fn(level, current); --levelCount; } ++level; } } template&lt;class K, class M&gt; inline void BSTree&lt;K, M&gt;::Node::printKey(std::size_t size, Justify just) { std::stringstream ss; char buf[255]; ss &lt;&lt; key(); ss.getline(buf,255); std::string s{buf}; const std::size_t length = s.length(); switch (just) { case Justify::Left: std::cout &lt;&lt; s; printSpaces(size - length); break; case Justify::Right: printSpaces(size - length); std::cout &lt;&lt; s; break; case Justify::Center: const std::size_t pad = (size - length) &gt;&gt; 1; printSpaces(pad); std::cout &lt;&lt; s; printSpaces(size - length - pad); break; } } template&lt;class K, class M&gt; inline void BSTree&lt;K, M&gt;::viewTree(std::size_t root, std::size_t depth) { std::string s; std::size_t key_size = 0; traverseByLevel(root, depth, [&amp;](std::size_t level, std::size_t index) -&gt; void { std::stringstream ss; char buf[255]; if (index != 0) { ss &lt;&lt; nodes.at(index).key(); ss.getline(buf, 255); s = buf; if (s.length() &gt; key_size) key_size = s.length(); s.clear(); } }); std::size_t oldLevel = gsl::narrow_cast&lt;std::size_t&gt;(-1); traverseByLevel(root, depth, [&amp;] (std::size_t level, std::size_t index) -&gt; void { const std::size_t space_size = (key_size &amp; 1) ? 1 : 2; if (level != oldLevel) { const std::size_t lead_space = ((1 &lt;&lt; (depth - level - 1)) - 1) * ((key_size + space_size) &gt;&gt; 1); oldLevel = level; std::cout &lt;&lt; "\n"; printSpaces(lead_space); } else { const std::size_t internal_space = ((1 &lt;&lt; (depth - level - 1)) - 1)*(key_size + space_size) + space_size; printSpaces(internal_space); } if (index != 0) nodes.at(index).printKey(key_size, Justify::Center); else printSpaces(key_size); }); std::cout &lt;&lt; "\n"; } #endif // !BSTREE </code></pre> <p>Test.cpp (It's a mess, but I have yet to learn how to write an organized test suite. Maybe that will be my next project.)</p> <pre><code>// test.cpp : This file contains the 'main' function. Program execution // begins and ends there. #include "pch.h" #include "BSTree.hpp" #include &lt;iostream&gt; #include &lt;vector&gt; #include &lt;fstream&gt; #include &lt;string&gt; #include &lt;sstream&gt; #include &lt;cassert&gt; #include &lt;chrono&gt; #include &lt;cctype&gt; #include &lt;map&gt; #include &lt;tuple&gt; #include &lt;random&gt; using std::cout; using std::endl; using namespace std::chrono; bool myfunc(const int&amp; a, const int&amp; b) noexcept { return a &gt; b; } template&lt;class K&gt; bool myfunc2(const K&amp; a, const K&amp; b) noexcept { const bool ret = std::less&lt;K&gt;::less()(a, b); return ret; } int main() { BSTree&lt;int&gt; bs_tree(20000); auto [it, good] = bs_tree.insert(5,'a'); assert (good &amp;&amp; "inserted 5,a\n"); std::tie(it, good) = bs_tree.insert(2,'b'); assert (good &amp;&amp; "inserted 2,b\n"); std::tie(it, good) = bs_tree.insert(21,'c'); assert(good &amp;&amp; "inserted 21,c\n"); bs_tree.viewTree(); auto count = bs_tree.erase(5); assert(count == 1 &amp;&amp; "erased 5\n"); count = bs_tree.erase(5); assert(count == 0 &amp;&amp; "erased 5\n"); bs_tree.viewTree(); cout &lt;&lt; std::boolalpha &lt;&lt; bs_tree.isBalanced(); cout &lt;&lt; " " &lt;&lt; std::boolalpha &lt;&lt; bs_tree.isBST() &lt;&lt; std::noboolalpha; cout &lt;&lt; " " &lt;&lt; bs_tree.height() &lt;&lt; "\n"; std::tie(it, good) = bs_tree.insert(25, 'd'); assert(good &amp;&amp; "inserted 25,d\n"); std::tie(it, good) = bs_tree.insert(25, 'd'); assert(!good &amp;&amp; "inserted 25,d\n"); bs_tree.viewTree(); count = bs_tree.erase(25); assert(count == 1 &amp;&amp; "erased 25\n"); std::tie(it, good) = bs_tree.insert(5, 'd'); assert(good &amp;&amp; "inserted 5,d\n"); bs_tree.viewTree(); std::tie(it, good) = bs_tree.insert(19,'e'); assert(good &amp;&amp; "inserted 19,e\n"); std::tie(it, good) = bs_tree.insert(25,'f'); assert(good &amp;&amp; "inserted 25,f\n"); std::tie(it, good) = bs_tree.insert(55,'g'); assert(good &amp;&amp; "inserted 55,g\n"); std::tie(it, good) = bs_tree.insert(60,'h'); assert(good &amp;&amp; "inserted 60,h\n"); std::tie(it, good) = bs_tree.insert(15,'i'); assert(good &amp;&amp; "inserted 15,i\n"); std::tie(it, good) = bs_tree.insert(0,'j'); assert(good &amp;&amp; "inserted 0,j\n"); cout &lt;&lt; "Before erase:\n"; bs_tree.viewTree(); bs_tree.erase(21); cout &lt;&lt; "After:\n"; bs_tree.viewTree(); bs_tree.erase(15); bs_tree.viewTree(); auto [it2, result] = bs_tree.insert(63,'l'); assert(result &amp;&amp; "inserted 63,l\n"); auto it3 = bs_tree.insert(it2, std::make_pair(67,'k')); it3 = bs_tree.erase(it3); it2 = bs_tree.find(63); it3 = bs_tree.insert(it2, std::make_pair(67, 'k')); it2 = bs_tree.find(63); for (; it2 != bs_tree.end(); --it2) cout &lt;&lt; it2-&gt;first &lt;&lt; ": "; cout &lt;&lt; "\n"; bs_tree.viewTree(); bs_tree.erase(1); bs_tree[1] = '.'; assert(bs_tree.at(1) == '.' &amp;&amp; "operator[1]='.'\n"); bs_tree.viewTree(); std::vector&lt;std::pair&lt;int, char&gt;&gt; pairs; for (int i = 0; i &lt; 70; ++i) { auto iter = bs_tree.find(i); if (iter != bs_tree.end()) { cout &lt;&lt; "found: " &lt;&lt; iter-&gt;first &lt;&lt; "-&gt; " &lt;&lt; iter-&gt;second &lt;&lt; "\n"; pairs.push_back(std::make_pair(iter-&gt;first, iter-&gt;second)); } } assert(pairs.size() == 10 &amp;&amp; "pairs found\n"); count = bs_tree.erase(5); assert(count == 1 &amp;&amp; "erased 5\n"); bs_tree.viewTree(); count = bs_tree.erase(0); assert(count == 1 &amp;&amp; "erased 0\n"); count = bs_tree.erase(0); assert(count == 0 &amp;&amp; "!erased 0\n"); bs_tree.viewTree(); cout &lt;&lt; "\n"; bs_tree.viewKeys(); for (const auto p : bs_tree) cout &lt;&lt; p.first &lt;&lt; ": "; cout &lt;&lt; "\n"; for (auto i = bs_tree.crbegin(); i != bs_tree.crend(); ++i) cout &lt;&lt; i-&gt;first &lt;&lt; ": "; cout &lt;&lt; "\n"; it = bs_tree.begin(); it = bs_tree.erase(it); cout &lt;&lt; it-&gt;first &lt;&lt; ": " &lt;&lt; (*++it).first &lt;&lt; ": "; cout &lt;&lt; (*++it).first &lt;&lt; ": " &lt;&lt; (*++it).first &lt;&lt; ": " &lt;&lt; (*++it).first &lt;&lt; "\n"; cout &lt;&lt; (*it--).first &lt;&lt; ": " &lt;&lt; it-&gt;first &lt;&lt; "\n"; bs_tree.viewTree(); auto it5 = bs_tree.lower_bound(3); assert(it5-&gt;first == 19 &amp;&amp; "lower bound of 3 is 19"); auto it6 = bs_tree.upper_bound(60); assert(it6-&gt;first == 63 &amp;&amp; "upper bound of 60 is 63"); for (auto it = it5; it != it6; ++it) cout &lt;&lt; it-&gt;first &lt;&lt; "|"; cout &lt;&lt; "\nnow\n"; try { cout &lt;&lt; (it6)-&gt;first &lt;&lt; "-" &lt;&lt; (++it6)-&gt;first &lt;&lt; "-" &lt;&lt; (++it6)-&gt;first &lt;&lt; "\n"; } catch (const std::out_of_range&amp; e) { cout &lt;&lt; e.what() &lt;&lt; "\n"; } --it6; --it6; cout &lt;&lt; it6-&gt;first &lt;&lt; "\n"; it5 = bs_tree.lower_bound(25); cout &lt;&lt; it5-&gt;first &lt;&lt; "\n"; it = bs_tree.erase(it5, it6); cout &lt;&lt; it-&gt;first &lt;&lt; "\n"; bs_tree.viewTree(); cout &lt;&lt; "\n"; cout &lt;&lt; std::boolalpha &lt;&lt; bs_tree.isBalanced(); cout &lt;&lt; " " &lt;&lt; std::boolalpha &lt;&lt; bs_tree.isBST() &lt;&lt; std::noboolalpha; cout &lt;&lt; " " &lt;&lt; bs_tree.height() &lt;&lt; "\n"; cout &lt;&lt; "Hello World!\n"; cout &lt;&lt; "pairs: \n"; bs_tree.clear(); bs_tree.insert(pairs.begin(), pairs.end()); bs_tree.viewTree(); cout &lt;&lt; "\n"; bs_tree.insert(6, 'F'); bs_tree.viewTree(); bs_tree.insert({ std::make_pair(6,'f'), std::make_pair(13,'m'), std::make_pair(56,'x') }); bs_tree.viewTree(); bs_tree.erase(0); bs_tree.erase(5); bs_tree.erase(57); bs_tree.viewTree(); cout &lt;&lt; "\n"; BSTree&lt;int&gt; temp; temp.swap(bs_tree); // = std::move(bs_tree); BSTree&lt;std::string, std::string&gt; state_capitals(64,myfunc2&lt;std::string&gt;); std::ifstream infile("capitals.txt"); std::string state, capital; std::string line; while (std::getline(infile, line)) { capital = line.substr(0, line.find(',')); state = line.substr(line.find(',') + 2); state_capitals.insert(state, capital); } infile.close(); state_capitals.viewTree(1); cout &lt;&lt; "\n"; cout &lt;&lt; state_capitals.size() &lt;&lt; "\n"; cout &lt;&lt; state_capitals.find("Massachusetts")-&gt;second &lt;&lt; "\n"; cout &lt;&lt; state_capitals.lower_bound("Mass")-&gt;second &lt;&lt; "\n"; try { cout &lt;&lt; state_capitals.at("Mass") &lt;&lt; "\n"; } catch (const std::out_of_range&amp; oor) { cout &lt;&lt; oor.what() &lt;&lt; "\n"; } state_capitals["Alabama"] = "Mobile is not the capital"; cout &lt;&lt; state_capitals["Alabama"] &lt;&lt; "\n"; auto mycomp = state_capitals.key_comp(); cout &lt;&lt; "'chicken' is less than 'turkey': " &lt;&lt; std::boolalpha &lt;&lt; mycomp("chicken", "turkey") &lt;&lt; "\n"; cout &lt;&lt; "'fox' is less than 'dog': " &lt;&lt; std::boolalpha &lt;&lt; mycomp("fox", "dog") &lt;&lt; "\n"; /* Lets do some timing Possible seeds of high prime value: 134998043, 1951818181, 2146999991 */ bs_tree.clear(); const std::size_t num_to_test = 1'000'000; const std::size_t seed_to_test = 134998043; std::mt19937 rng(seed_to_test); pairs.clear(); pairs.reserve(num_to_test); const std::uniform_int_distribution&lt;std::mt19937::result_type&gt; dist(1, num_to_test); // distribution in range [0, num_to_test] time_point start = high_resolution_clock::now(); for (int i = 0; i &lt; num_to_test; ++i) { const int num = dist(rng); bs_tree.insert(num); } time_point end = high_resolution_clock::now(); int cnt = 0; for (const auto p : bs_tree) ++cnt; cout &lt;&lt; "count: " &lt;&lt; cnt &lt;&lt; " size: " &lt;&lt; bs_tree.size() &lt;&lt; "\n"; duration&lt;int, std::ratio&lt;1, 1'000&gt;&gt; time_span = duration_cast&lt;duration&lt;int, std::ratio&lt;1, 1'000&gt;&gt;&gt;(end - start); cout &lt;&lt; "BSTree Insert took " &lt;&lt; time_span.count() &lt;&lt; "ms\n"; cout &lt;&lt; "It's Balanced: " &lt;&lt; std::boolalpha &lt;&lt; bs_tree.isBalanced() &lt;&lt; "\n"; cout &lt;&lt; "It's a BST: " &lt;&lt; std::boolalpha &lt;&lt; bs_tree.isBST() &lt;&lt; "\n"; std::map&lt;int, char&gt; my_map; rng.seed(seed_to_test); start = high_resolution_clock::now(); for (int i = 0; i &lt; num_to_test; ++i) { my_map.insert(std::make_pair(dist(rng), '\0')); } end = high_resolution_clock::now(); duration&lt;int, std::ratio&lt;1, 1'000'000&gt;&gt; time_span2 = duration_cast&lt;duration&lt;int, std::ratio&lt;1, 1'000'000&gt;&gt;&gt;(end - start); cout &lt;&lt; "Map Insert took " &lt;&lt; time_span2.count() &lt;&lt; "us\n"; auto my_it = my_map.lower_bound(-4); auto my_it2 = my_map.upper_bound(-4); auto my_it3 = bs_tree.lower_bound(-4); auto my_it4 = bs_tree.upper_bound(-4); assert(my_it-&gt;first == my_it3-&gt;first &amp;&amp; "different lower_bound"); assert(my_it2-&gt;first == my_it4-&gt;first &amp;&amp; "different upper_bound"); my_it = my_map.lower_bound(25); my_it2 = my_map.upper_bound(25); my_it3 = bs_tree.lower_bound(25); my_it4 = bs_tree.upper_bound(25); assert(my_it-&gt;first == my_it3-&gt;first &amp;&amp; "different lower_bound"); assert(my_it2-&gt;first == my_it4-&gt;first &amp;&amp; "different upper_bound"); auto range = my_map.equal_range(27); auto range2 = bs_tree.equal_range(27); assert(range.first-&gt;first == range2.first-&gt;first &amp;&amp; "different lower_bound"); assert(range.second-&gt;first == range.second-&gt;first &amp;&amp; "different upper_bound"); cout &lt;&lt; "map lower: " &lt;&lt; my_it-&gt;first &lt;&lt; " upper: " &lt;&lt; my_it2-&gt;first &lt;&lt; "\n"; cout &lt;&lt; "BST lower: " &lt;&lt; my_it3-&gt;first &lt;&lt; " upper: " &lt;&lt; my_it4-&gt;first &lt;&lt; "\n"; int counted = bs_tree.size(); cout &lt;&lt; "bs_tree size = " &lt;&lt; counted &lt;&lt; "\n"; rng.seed(seed_to_test); const auto end_type = bs_tree.end(); std::size_t counted2 = 0; start = high_resolution_clock::now(); for (int i = 0; i &lt; num_to_test; ++i) { const int num = dist(rng); if (bs_tree.find(num) != end_type) ++counted2; } end = high_resolution_clock::now(); time_span = duration_cast&lt;duration&lt;int, std::ratio&lt;1, 1'000&gt;&gt;&gt;(end - start); cout &lt;&lt; "BSTree find took " &lt;&lt; time_span.count() &lt;&lt; "ms\n"; cout &lt;&lt; "bs_tree size = " &lt;&lt; counted2 &lt;&lt; "\n"; rng.seed(seed_to_test); start = high_resolution_clock::now(); for (int i = 0; i &lt; num_to_test; ++i) { my_map.find(dist(rng)); } end = high_resolution_clock::now(); time_span2 = duration_cast&lt;duration&lt;int, std::ratio&lt;1, 1'000'000&gt;&gt;&gt;(end - start); cout &lt;&lt; "Map find took " &lt;&lt; time_span2.count() &lt;&lt; "us\n"; rng.seed(seed_to_test); start = high_resolution_clock::now(); for (int i = 0; i &lt; num_to_test; ++i) { const int num = dist(rng); counted -= bs_tree.erase(num); } end = high_resolution_clock::now(); time_span = duration_cast&lt;duration&lt;int, std::ratio&lt;1, 1'000&gt;&gt;&gt;(end - start); cout &lt;&lt; "BSTree erase took " &lt;&lt; time_span.count() &lt;&lt; "ms\n"; cout &lt;&lt; "bs_tree size = " &lt;&lt; counted &lt;&lt; "\n"; rng.seed(seed_to_test); start = high_resolution_clock::now(); for (int i = 0; i &lt; num_to_test; ++i) { my_map.erase(dist(rng)); } end = high_resolution_clock::now(); time_span2 = duration_cast&lt;duration&lt;int, std::ratio&lt;1, 1'000'000&gt;&gt;&gt;(end - start); cout &lt;&lt; "Map erase took " &lt;&lt; time_span2.count() &lt;&lt; "us\n"; if (bs_tree.size() != 0) { bs_tree.viewTree(1, 6); cout &lt;&lt; "size: " &lt;&lt; gsl::narrow_cast&lt;int&gt;(bs_tree.size()) &lt;&lt; "\n"; } else cout &lt;&lt; "good bye!\n"; } </code></pre> <p>Output verifying that it all works:</p> <pre class="lang-none prettyprint-override"><code> 5 2 21 2 21 true true 2 21 2 25 5 2 21 Before erase: 21 5 55 2 19 25 60 0 15 After: 19 5 55 2 15 25 60 0 19 2 55 0 5 25 60 63: 60: 55: 25: 19: 5: 2: 0: 19 2 55 0 5 25 63 60 67 19 2 55 0 5 25 63 1 60 67 found: 0-&gt; j found: 1-&gt; . found: 2-&gt; b found: 5-&gt; d found: 19-&gt; e found: 25-&gt; f found: 55-&gt; g found: 60-&gt; h found: 63-&gt; l found: 67-&gt; k 19 1 55 0 2 25 63 60 67 19 1 55 2 25 63 60 67 1 2 19 25 55 60 63 67 1: 2: 19: 25: 55: 60: 63: 67: 67: 63: 60: 55: 25: 19: 2: 1: 2: 19: 25: 55: 60 60: 55 55 19 63 2 25 60 67 19|25|55|60| now 63-67- Pointer Out Of Range! 63 25 63 19 2 63 67 true true 3 Hello World! pairs: 5 1 60 0 2 25 63 19 55 67 25 5 60 1 19 55 63 0 2 6 67 25 5 60 1 13 55 63 0 2 6 19 56 67 25 2 60 1 13 55 63 6 19 56 67 New York Kansas South Carolina Delaware Mississippi Oklahoma Utah Arkansas Idaho Maryland Nevada North Dakota Pennsylvania Tennessee West Virginia 50 Boston Boston Out Of Range for key: "Mass" Mobile is not the capital 'chicken' is less than 'turkey': true 'fox' is less than 'dog': false count: 631638 size: 631638 BSTree Insert took 2810ms It's Balanced: true It's a BST: true Map Insert took 473343us map lower: 26 upper: 26 BST lower: 26 upper: 26 bs_tree size = 631638 BSTree find took 256ms bs_tree size = 1000000 Map find took 16210us BSTree erase took 1483ms bs_tree size = 0 Map erase took 534368us good bye! </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-20T16:22:22.600", "Id": "450300", "Score": "0", "body": "I like the `reinventing the wheel` tag. I'll need to use that more often myself." } ]
[ { "body": "<p>First of all, your code produces a <em>lot</em> of warnings and errors on Clang. I recommend trying to compile your code with at least two compilers, especially in cases like this where it's small enough to just cut-and-paste into <a href=\"https://godbolt.org/z/3_Cr6X\" rel=\"nofollow noreferrer\">Godbolt Compiler Explorer</a>.</p>\n\n<p>The only immediately fatal error in your <code>.h</code> file is that you declared <code>struct Node</code> public, and then re-declared it as private later. You can't do that. Just make the forward-declaration also private; or even better, make the first declaration the <em>only</em> declaration.</p>\n\n<p>In your test file, you write</p>\n\n<pre><code>const std::uniform_int_distribution&lt;std::mt19937::result_type&gt; dist // ...\n</code></pre>\n\n<p>A <code>const</code> distribution won't do you any good! The <code>operator()</code> of all standard distributions is non-const-qualified (because they have internal state that the <code>operator()</code> needs to modify). Remove the <code>const</code>. Besides, <a href=\"https://quuxplusone.github.io/blog/2019/01/03/const-is-a-contract/\" rel=\"nofollow noreferrer\"><code>const</code> is a contract</a>, and in this case you're making a contract between yourself and... yourself! (And making an contract between yourself and <code>operator()</code> which <code>operator()</code> then tries to violate, which is why you get a compiler error in the first place.)</p>\n\n<pre><code>template&lt;class K, class M&gt;\ninline BSTree&lt;K, M&gt;::BSTree(std::size_t size,\n const key_compare fn) : comp(fn), value_comp(fn)\n</code></pre>\n\n<p>All compilers will warn about this mistake: you've said \"initialize <code>comp</code> to this and <code>value_comp</code> to that,\" but in fact what will happen at runtime is \"initialize <code>value_comp</code> to this and <code>comp</code> to that,\" because the data members are declared in the latter order.</p>\n\n<pre><code>template&lt;class K&gt;\nbool myfunc2(const K&amp; a, const K&amp; b) noexcept {\n const bool ret = std::less&lt;K&gt;::less()(a, b);\n return ret;\n}\n</code></pre>\n\n<p>The compiler won't be able to compile this, because it has no way of knowing (at parse time) that <code>std::less&lt;K&gt;::less</code> is a type name and not a variable name. It'll assume it's a variable name, so that <code>std::less&lt;K&gt;::less()</code> is a function call... and then at template-instantiation time, it'll discover that it's a constructor call instead, and it'll fail. You need the keyword <code>typename</code> in there to tell the parser what to expect.</p>\n\n<p>Separately, don't write two lines when one will do.</p>\n\n<pre><code> return typename std::less&lt;K&gt;::less()(a, b);\n</code></pre>\n\n<p>(Flabbergastingly, Clang trunk will <em>also</em> issue a warning on the above line <s><em>even though it is the only correct way to write the code.</em></s> (Clang will issue an error if you omit the <code>typename</code> keyword.) I'll raise this bug on the bug tracker.)</p>\n\n<blockquote>\n <p>EDIT: Aha! Clang's diagnostic failed to enlighten me, but the actual problem here was simply that you meant <code>return std::less&lt;K&gt;()(a, b);</code>. That extra <code>::less</code> shouldn't have been there at all. Yeesh. Filed <a href=\"https://bugs.llvm.org/show_bug.cgi?id=43733\" rel=\"nofollow noreferrer\">https://bugs.llvm.org/show_bug.cgi?id=43733</a> for the unhelpful diagnostic.</p>\n</blockquote>\n\n<hr>\n\n<p>For your tests, you can use a testing framework such as GTest (the old standby, easy to install from any package manager) or newer things like Catch2. In GTest, your first couple of test cases would look like this:</p>\n\n<pre><code>cat &gt;tests.cc &lt;&lt;EOF\n#include \"bst.h\"\n#include &lt;algorithm&gt;\n#include &lt;gtest/gtest.h&gt;\n\nTEST(BSTree, FirstTest)\n{\n BSTree&lt;int&gt; bt(20000);\n auto [it, good] = bt.insert(5,'a');\n EXPECT_TRUE(good);\n\n std::tie(it, good) = bt.insert(2,'b');\n EXPECT_TRUE(good);\n\n std::tie(it, good) = bt.insert(21,'c');\n EXPECT_TRUE(good);\n\n std::pair&lt;int, char&gt; expected[] = {{2,'b'}, {5,'a'}, {21,'c'}};\n EXPECT_TRUE(std::equal(bt.begin(), bt.end(), expected, expected+3));\n}\n\nTEST(BSTree, SecondTest)\n{\n BSTree&lt;int&gt; bt = {{2,'b'}, {5,'a'}, {21,'c'}};\n EXPECT_EQ(bt.erase(5), 1);\n EXPECT_EQ(bt.erase(5), 0);\n}\nEOF\n$ g++ tests.cc -std=c++17 -lgtest_main -lgtest\n$ ./a.out\nRunning main from googletest/src/gtest_main.cc\n[==========] Running 2 tests from 1 test suite.\n[----------] Global test environment set-up.\n[----------] 2 tests from BSTree\n[ RUN ] BSTree.FirstTest\n[ OK ] BSTree.FirstTest (0 ms)\n[ RUN ] BSTree.SecondTest\n[ OK ] BSTree.SecondTest (1 ms)\n[----------] 2 tests from BSTree (1 ms total)\n\n[----------] Global test environment tear-down\n[==========] 2 tests from 1 test suite ran. (1 ms total)\n[ PASSED ] 2 tests.\n</code></pre>\n\n<hr>\n\n<p>Actually, I lied. This line</p>\n\n<pre><code>BSTree&lt;int&gt; bt = {{2,'b'}, {5,'a'}, {21,'c'}};\n</code></pre>\n\n<p>ought to work, but you didn't write an <code>initializer_list</code> constructor, so instead, I have to write something like</p>\n\n<pre><code>BSTree&lt;int&gt; bt;\nbt.insert({{2,'b'}, {5,'a'}, {21,'c'}});\n</code></pre>\n\n<hr>\n\n<p>It's weird that you have a constructor taking <code>size_t size</code>, like <code>vector</code>, but that constructor doesn't initialize the container with <code>size</code> elements. And that constructor needs to be <code>explicit</code>, btw! Otherwise</p>\n\n<pre><code>BSTree&lt;int&gt; bt = 42;\n</code></pre>\n\n<p>works, and you don't want that.</p>\n\n<hr>\n\n<p>It's very weird to me that the <code>value_type</code> of <code>BSTree&lt;int&gt;</code> is <code>std::pair&lt;int, char&gt;</code> — where on earth did that <code>char</code> come from?? Imagine if the standard <code>std::map</code> had a defaulted <code>mapped_type</code> parameter. That would be crazy, right? So why is it a good idea for <code>BSTree</code>? (And why can't I just make a binary search tree of <code>int</code>s in the first place — why <em>must</em> I attach a <code>char</code> payload to every node?)</p>\n\n<hr>\n\n<p>Your <code>iterator</code> type is broken (and thus won't work with any of the standard algorithms) because it fails to provide <code>using difference_type = std::ptrdiff_t;</code>. This is one of the five member typedefs that every iterator type <em>must</em> provide. If you'd tested your iterators you'd have seen that they didn't work with the STL.</p>\n\n<hr>\n\n<p>It's also weird that you provide different types for <code>iterator</code> and <code>const_iterator</code> but <em>not</em> different types for <code>iterator</code> and <code>reverse_iterator</code>. Each of your iterators is paying for an extra bool of storage, just so that you can use the same static type for forward and backward iteration? Do you have some special motivation why you used this technique?</p>\n\n<p>The usual technique would be something like this:</p>\n\n<pre><code>using reverse_iterator = std::reverse_iterator&lt;iterator&gt;;\nusing const_reverse_iterator = std::reverse_iterator&lt;const_iterator&gt;;\nreverse_iterator rbegin() { return reverse_iterator(end()); }\nconst_reverse_iterator rbegin() const { return const_reverse_iterator(end()); }\nconst_reverse_iterator crbegin() const { return rbegin(); }\n</code></pre>\n\n<hr>\n\n<pre><code>if (index_ == out_of_range) {\n std::stringstream ss;\n ss &lt;&lt; \"\\nOut Of Range: operator++\\n\";\n throw std::out_of_range(ss.str());\n}\n</code></pre>\n\n<p>First, please don't use global variables. (You have four of these global <code>constexpr</code> variables. They have four distinct values, almost like an enumeration... but it's unclear if that's actually important to the code.) If you must use globals, at least don't name them the same thing as standard exception <em>types</em>. And finally, don't write three lines when one would do.</p>\n\n<pre><code>if (index_ == 0) { // what's special about this index??\n throw std::out_of_range(\"Out Of Range: operator++\");\n}\n</code></pre>\n\n<p>Notice that I've removed the excess newlines in your <code>e.what()</code> string. What-strings traditionally don't have any \"formatting\"; they're just simple strings that the client programmer can wrap in formatting if he wants to.</p>\n\n<pre><code>std::cout &lt;&lt; \"error: \" &lt;&lt; e.what() &lt;&lt; \"\\n\";\n // this would look weird if e.what() also had embedded newlines\n</code></pre>\n\n<hr>\n\n<p>That's all for now... but if you fix all the compiler warnings and errors, and write some good tests and run them (You don't even have to upload the tests! But write them and run them and fix the bugs they find!), and re-upload the code as a new question, I'll probably be back to look at the actual data structure.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-20T15:26:30.077", "Id": "231042", "ParentId": "215587", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-17T01:35:52.830", "Id": "215587", "Score": "9", "Tags": [ "c++", "reinventing-the-wheel", "collections", "c++17" ], "Title": "Binary Search Tree Implementation in C++17" }
215587
<p>I decided to write a function <code>divisorSum</code> that <a href="https://en.wikipedia.org/wiki/Divisor_function" rel="nofollow noreferrer">sums the divisors of number</a>. For instance 1, 2, 3 and 6 divide 6 evenly so:</p> <p><span class="math-container">$$ \sigma(6) = 1 + 2 + 3 + 6= 12 $$</span></p> <p>I decided to use Euler's recurrence relation to calculate the sum of divisors:</p> <p><span class="math-container">$$\sigma(n) = \sigma(n-1) + \sigma(n-2) - \sigma(n-5) - \sigma(n-7) + \sigma(n-12) +\sigma(n-15) + \ldots$$</span></p> <p>i.e. </p> <p><span class="math-container">$$\sigma(n) = \sum_{i\in \mathbb Z_0} (-1)^{i+1}\left( \sigma\left(n - \tfrac{3i^2-i}{2}\right) + \delta\left(n,\tfrac{3i^2-i}{2}\right)n \right)$$</span></p> <p>(See here <a href="https://math.stackexchange.com/a/22744/15140">for the details</a>). As such, I decided to export some other useful functions like <code>nthPentagonal</code> which returns the nth (generalized) pentagonal number. I created a new project with <code>stack new</code> and modified these two files:</p> <h1><code>src/Lib.hs</code></h1> <pre><code>module Lib ( nthPentagonal, pentagonals, divisorSum, ) where -- | Creates a [generalized pentagonal integer] -- | (https://en.wikipedia.org/wiki/Pentagonal_number_theorem) integer. nthPentagonal :: Integer -&gt; Integer nthPentagonal n = n * (3 * n - 1) `div` 2 -- | Creates a lazy list of all the pentagonal numbers. pentagonals :: [Integer] pentagonals = map nthPentagonal integerStream -- | Provides a stream for representing a bijection from naturals to integers -- | i.e. [1, -1, 2, -2, ... ]. integerStream :: [Integer] integerStream = map integerOrdering [1 .. ] where integerOrdering :: Integer -&gt; Integer integerOrdering n | n `rem` 2 == 0 = (n `div` 2) * (-1) | otherwise = (n `div` 2) + 1 -- | Using Euler's formula for the divisor function, we see that each summand -- | alternates between two positive and two negative. This provides a stream -- | of 1 1 -1 -1 1 1 ... to utilze in assiting this property. additiveStream :: [Integer] additiveStream = map summandSign [0 .. ] where summandSign :: Integer -&gt; Integer summandSign n | n `rem` 4 &gt;= 2 = -1 | otherwise = 1 -- | Kronkecker delta, return 0 if the integers are not the same, otherwise, -- | return the value of the integer. delta :: Integer -&gt; Integer -&gt; Integer delta n i | n == i = n | otherwise = 0 -- | Calculate the sum of the divisors. -- | Utilizes Euler's recurrence formula: -- | $\sigma(n) = \sigma(n - 1) + \sigma(n - 2) - \sigma(n - 5) \ldots $ -- | See [here](https://math.stackexchange.com/a/22744/15140) for more informa- -- | tion. divisorSum :: Integer -&gt; Integer divisorSum n | n &lt;= 0 = 0 | otherwise = sum $ takeWhile (/= 0) (zipWith (+) (divisorStream n) (markPentagonal n)) where pentDual :: Integer -&gt; [Integer] pentDual n = [ n - x | x &lt;- pentagonals] divisorStream :: Integer -&gt; [Integer] divisorStream n = zipWith (*) (map divisorSum (pentDual n)) additiveStream markPentagonal :: Integer -&gt; [Integer] markPentagonal n = zipWith (*) (zipWith (delta) pentagonals (repeat n)) additiveStream </code></pre> <h1><code>app/Main.hs</code> (mostly just to "test" it.)</h1> <pre><code>module Main where import Lib main :: IO () main = putStrLn $ show $ divisorSum 8 </code></pre>
[]
[ { "body": "<p><strong>TL;DR:</strong></p>\n\n<ul>\n<li>use memoization to speed up calculations</li>\n<li>if you drive for performance use <code>quot</code> instead of <code>div</code></li>\n<li>if possible, try to define your sequences without complicated functions</li>\n<li>use <code>even n</code> instead of <code>n `rem` 2 == 0</code> or <code>odd n</code> instead of <code>n `rem` 2 == 1</code></li>\n</ul>\n\n<h1>Type annotations and documentation</h1>\n\n<p>You use both type annotations as well as documentation. Great. There are only two small drawbacks:</p>\n\n<ol>\n<li>The documentation strings sometimes miss highlighting, e.g. <code>[1, -1, 2, -2,...]</code> in <code>pentagonals</code>. Cross-references would also be great, e.g. <code>pentagonals</code> could point to <code>nthPentagonal</code> in its documentation.</li>\n<li>Type annotations for <em>workers</em> (the local bindings) only contribute noise, as their type will be inferred by its surrounding function's types.</li>\n</ol>\n\n<p>For example</p>\n\n<pre><code>integerStream :: [Integer]\nintegerStream = map integerOrdering [1 .. ]\n where\n integerOrdering :: Integer -&gt; Integer\n integerOrdering n\n | n `rem` 2 == 0 = (n `div` 2) * (-1)\n | otherwise = (n `div` 2) + 1\n</code></pre>\n\n<p>doesn't need the second type annotation:</p>\n\n<pre><code>integerStream :: [Integer]\nintegerStream = map integerOrdering [1 .. ]\n where\n integerOrdering n\n | n `rem` 2 == 0 = (n `div` 2) * (-1)\n | otherwise = (n `div` 2) + 1\n</code></pre>\n\n<h1>Convey ideas in code as direct as possible</h1>\n\n<p>Above, we use <code>n `rem` 2 == 0</code> to check whether a number is even. However, there is already a function for that: <code>even</code>. It immediately tells us the purpose of the expression, so let's use that:</p>\n\n<pre><code>integerStream :: [Integer]\nintegerStream = map integerOrdering [1 .. ]\n where\n integerOrdering n\n | even n = (n `div` 2) * (-1)\n | otherwise = (n `div` 2) + 1\n</code></pre>\n\n<h1>Use <code>quotRem</code> if you need both the result of <code>rem</code> and <code>quot</code></h1>\n\n<p><code>integerStream</code> is a special case, though: as we need both the reminder as well as <code>div</code>'s result, we can use <code>divMod</code> or <code>quotRem</code>, e.g.</p>\n\n<pre><code>integerStream :: [Integer]\nintegerStream = map integerOrdering [1 .. ]\n where\n integerOrdering n\n | r = -q\n | otherwise = q + 1\n where\n (q, r) = n `quotRem` 2\n</code></pre>\n\n<h1>Use simpler code where applicable</h1>\n\n<p>We stay at <code>integerStream</code>. As the documentation tells us, we want to have a bijection from the sequence of natural numbers to a sequence of all integers.</p>\n\n<p>While the canonical mapping is indeed</p>\n\n<p><span class=\"math-container\">$$\nf(n) = \n\\begin{cases}\n\\frac{n-1}{2}+1&amp; \\text{if } n \\text{ is odd}\\\\\n-\\frac{n}{2}&amp; \\text{otherwise}\n\\end{cases}\n$$</span>\nwe don't need to use that definition in our code. Instead, we can use</p>\n\n<p><span class=\"math-container\">$$\nn_1,-n_1,n_2,-n_2,\\ldots.\n$$</span></p>\n\n<pre><code>integerStream :: [Integer]\nintegerStream = go 1\n where\n go n = n : -n : go (n + 1)\n</code></pre>\n\n<p>Or, if you don't want to write it explicitly</p>\n\n<pre><code>integerStream :: [Integer]\nintegerStream = concatMap mirror [1..]\n where\n mirror n = [n, -n]\n</code></pre>\n\n<p>Both variants have the charm that no division is necessary in the computation of your list.</p>\n\n<h2>Use <code>cycle</code> for repeating lists</h2>\n\n<p>While the methods above arguably break down to personal preference, <code>additiveStream</code> can benefit from <code>cycle</code>:</p>\n\n<pre><code>additiveStream :: [Integer]\nadditiveStream = cycle [1, 1, -1, -1]\n</code></pre>\n\n<h1>Generalize functions where applicable</h1>\n\n<p><code>delta</code> can be written for <em>any</em> type that is an instance of <code>Num</code> an <code>Eq</code>, so lets generalize:</p>\n\n<pre><code>delta :: (Eq n, Num n) =&gt; n -&gt; n -&gt; n\ndelta n i\n | n == i = n\n | otherwise = 0\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-17T08:10:26.337", "Id": "417097", "Score": "0", "body": "I still need a section on memoization but I don't have any time at the moment." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-17T20:44:05.817", "Id": "417159", "Score": "0", "body": "It's all good. I'm looking into how memoization is typically done in Haskell and can probably implement it as an exercise. :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-17T20:56:14.303", "Id": "417165", "Score": "0", "body": "@Dair [This Q&A on SO](https://stackoverflow.com/questions/3208258/memoization-in-haskell) provides a great introduction IMHO." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-17T08:10:04.467", "Id": "215600", "ParentId": "215589", "Score": "4" } }, { "body": "<p>I tried writing <code>divisorSum</code> in terms of <code>ZipList</code>, but it kept shrinking until that wasn't needed anymore. Which is half the point of such rewrites!</p>\n\n<pre><code>divisorSum :: Integer -&gt; Integer\ndivisorSum n\n | n &lt;= 0 = 0\n | otherwise = sum $ takeWhile (/= 0) $ zipWith (*) additiveStream $\n map (\\x -&gt; divisorSum (n - x) + if x == n then 1 else 0) pentagonals\n</code></pre>\n\n<p>The call tree of with what arguments <code>divisorSum</code> calls itself is going to overlap with itself. In such situations, you can trade off space for time by keeping around a data structure that remembers the result for each possible argument after it's been calculated once. The <code>memoize</code> library captures this pattern:</p>\n\n<pre><code>divisorSum :: Integer -&gt; Integer\ndivisorSum = memoFix $ \\recurse n -&gt; if n &lt;= 0 then 0 else\n sum $ takeWhile (/= 0) $ zipWith (*) (cycle [1, 1, -1, -1]) $\n map (\\x -&gt; recurse (n - x) + if x == n then 1 else 0) pentagonals\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-17T15:52:35.770", "Id": "417126", "Score": "1", "body": "it's nigh-impossible to understand this code without expending a significant amount of mental resources. As such this refactoring is not an improvement IMO, but a step back. There may be a point regarding performance, but clarity is the deciding factor here. The compiler can do the inlining for us..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-17T18:37:58.610", "Id": "417141", "Score": "0", "body": "The inlining allowed fusing the `zipWith`s. I think that's an improvement. Do the additional names aid your understanding? They are mere arcane symbols to me. If you find it easier to parse short definitions, simply read the code up to one `$` at a time, and pretend for the time being that the remainder is an argument - that's why it's structured that way." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-17T11:54:52.877", "Id": "215606", "ParentId": "215589", "Score": "-1" } } ]
{ "AcceptedAnswerId": "215600", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-17T02:00:38.010", "Id": "215589", "Score": "5", "Tags": [ "haskell" ], "Title": "Sum of divisors in Haskell" }
215589
<h1>Background</h1> <p>I decided to write build script as a gentle introduction to PowerShell. It builds and packages <a href="https://github.com/michaelsanford/bittray" rel="nofollow noreferrer">this</a> Go application, which is an internal tool I decided to open source, and not the focus of this review.</p> <p>This script is used primarily for <em>packaging artifacts for release</em>.</p> <h1>My approach</h1> <p>The script below gets, vets and builds a small Go application and then invokes a <a href="https://github.com/electron/rcedit" rel="nofollow noreferrer">separate command-line tool</a> to add Windows rsrc metadata such as version strings and icons.</p> <p>Since the version number is mandatory for the packaging process, I validated it using <code>param()</code> rules rather than <code>if</code> statements. It validates against a regex for <a href="https://semver.org/" rel="nofollow noreferrer">semver</a>.</p> <p>I then execute every packing step, check for its return status, and present a graceful message in addition to the error output by the build step.</p> <p>The packager relies on having <code>rcedit-x64.exe</code> available in the PATH. I originally allowed specifying a path to the executable as a command-line flag, but it seemed to make the code messier for nothing, so I just removed it. The tool is primarily for myself.</p> <h1>Example</h1> <h2>Invocation</h2> <pre><code>powershell.exe -ExecutionPolicy Unrestricted .\build.ps1 -version 1.1.0 </code></pre> <h2>Output</h2> <pre><code>Packing bittray version 1.1.0 Cleaning old build products. go get... go vet... go build... Validating artifact... Applying rsrc metadata... Compressing archive (bittray-1.1.0.zip)... SHA1 hash of bittray-1.1.0.zip: cd283afd10f613919bb4dc694bce3c1f9bd23483 CertUtil: -hashfile command completed successfully. Done! </code></pre> <h1>Concerns</h1> <ol> <li>Does the code follow PS idioms?</li> <li>Is there a more elegant way to check for the success of commands and bail than repeating <code>if (!$?)</code> all the time?</li> <li>To wit, is the single <code>trap</code> appropriate?</li> <li>Is the code adequately defensive? Overly defensive?</li> <li>I cannot sign my script as I don't have a code signing certificate. Is my invocation <em>correct</em> and <em>safe</em>?</li> <li>Is there a shorter invocation available without altering the system-side Execution Policy?</li> <li>Because of the validator on <code>-version</code>, you need to provide a valid version to be able to run just <code>-clean</code>. Any way around that (like providing some order of precedence of <code>param()</code>s, or short-cutting)? I really like those top-level validators, and would prefer to keep them in favor of if statements, if possible.</li> </ol> <h1>Code</h1> <pre><code>param( [string] [Parameter(Mandatory = $True)] [ValidateNotNullorEmpty()] [ValidatePattern('^([0-9]|[1-9][0-9]*)\.([0-9]|[1-9][0-9]*)\.([0-9]|[1-9][0-9]*)(?:-([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?(?:\+[0-9A-Za-z-]+)?$')] $version, [switch] $clean ) function Clean-Artifacts { Write-Host "Cleaning old build products." Remove-Item * -Include bittray.exe, bittray-*.zip if (!$?) { Write-Host -BackgroundColor red -ForegroundColor white "Failed to remove existing artifacts; see above." exit 1 } } if ($clean -eq $True) { Clean-Artifacts exit 0 } if ((Get-Command "rcedit-x64.exe" -ErrorAction SilentlyContinue) -eq $null) { Write-Host -ForegroundColor red "Unable to find rcedit-x64.exe in your PATH." exit 1 } Write-Host "Packing bittray version $version" -ForegroundColor green Clean-Artifacts Write-Host "go get..." go get Write-Host "go vet..." go vet ./... if (!$?) { Write-Host -BackgroundColor red -ForegroundColor white "'go vet' failed; see above." exit 1 } Write-Host "go build..." go build -ldflags -H=windowsgui bittray.go if (!$?) { Write-Host -BackgroundColor red -ForegroundColor white "'go build' failed; see above." exit 1 } Write-Host "Validating artifact..." if ( [System.IO.File]::Exists("bittray.exe")) { Write-Host "Applying rsrc metadata..." trap { "Error adding resource metadata: $_" } rcedit-x64.exe --set-icon .\bitbucket.ico "bittray.exe" rcedit-x64.exe "bittray.exe" --set-version-string "ProductName" "Bittray" rcedit-x64.exe "bittray.exe" --set-version-string "ProductVersion" "$version" } else { Write-Host -BackgroundColor red -ForegroundColor white "'go build' claims to have succeeded, but there is no artifact?" exit 1 } $package = "bittray-$version.zip" Write-Host "Compressing archive ($package)..." Compress-Archive -Path .\bittray.exe -CompressionLevel Optimal -DestinationPath $package if (!$?) { Write-Host -BackgroundColor red -ForegroundColor white "Failed to create zip package." exit 1 } certUtil -hashfile "$package" sha1 if (!$?) { Write-Host -BackgroundColor red -ForegroundColor white "Failed to generate SHA1 integrity checksum." exit 1 } else { Write-Host -BackgroundColor green -ForegroundColor white "Done!" } </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-17T03:37:07.983", "Id": "215590", "Score": "1", "Tags": [ "windows", "powershell" ], "Title": "PowerShell script to build and pacakge Go application for release" }
215590
<p>I wrote this program to check the number of times that each letter appears in a string input by the user. It works fine, but is there a more efficient or alternative solution of going about this task than reiterating through a twenty-six-element-long array for every single character?</p> <pre><code>import java.util.Scanner; public class Letters { public static void main(String[] args) { @SuppressWarnings("resource") Scanner sc = new Scanner(System.in); char[] c = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'}; int[] f = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; System.out.println("Enter a string."); String k = sc.nextLine(); String s = k.toUpperCase(); s = s.trim(); int l = s.length(); System.out.println("Checking string = " + s); char ch; for (int i = 0; i &lt; l; i++) { ch = s.charAt(i); for (int j = 0; j &lt; c.length; j++) { if (ch == c[j]) { f[j]++; } } } System.out.println("Char\tFreq"); for (int i = 0; i &lt; c.length; i++) { if (f[i] != 0) { System.out.println(c[i] + "\t" + f[i]); } } } } </code></pre>
[]
[ { "body": "<h3>Separate logical elements</h3>\n\n<p>It's good to separate different logical parts of a program, for example:</p>\n\n<ul>\n<li>Parse input: a function that takes an <code>InputStream</code> and returns a <code>String</code></li>\n<li>Compute frequencies: a function that takes a <code>String</code> and returns frequencies in some form. In your current program you used an <code>int[]</code>, it could have been a <code>Map&lt;Character, Integer&gt;</code>.</li>\n<li>Print the frequencies: a function that takes the frequencies in some form, returns nothing, and prints to screen the frequencies nicely formatted.</li>\n</ul>\n\n<h3>Computing indexes of letters</h3>\n\n<p>If the input string contains only uppercase letters, then you can translate those letters to array indexes in the range of 0 to 25 (inclusive) like this:</p>\n\n<pre><code>int index = ch - 'A';\n</code></pre>\n\n<p>This eliminates the nested loop you had.\nIt also eliminates the need for the <code>c</code> array.</p>\n\n<h3>Initializing arrays</h3>\n\n<p>Instead of this:</p>\n\n<blockquote>\n<pre><code>int[] f = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};\n</code></pre>\n</blockquote>\n\n<p>You could write simply <code>int[] f = new int[26];</code></p>\n\n<p>Instead of this:</p>\n\n<blockquote>\n<pre><code>char[] c = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'};\n</code></pre>\n</blockquote>\n\n<p>I would take a lazy approach and write <code>char[] c = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\".toCharArray();</code></p>\n\n<h3>Use better variable names</h3>\n\n<p>Single-letter variable names should only be used for trivial, highly transient things.\nThe names <code>f</code> and <code>c</code> in the program are inappropriate, and make the program more difficult to read.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-17T08:43:55.853", "Id": "417099", "Score": "0", "body": "I've been sticking to arrays because I haven't yet started learning about Maps and HashMaps. I'll be sure to check them out now... Thanks for pointing out the toCharArray() function. I was unaware that it existed." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-17T08:47:58.637", "Id": "417101", "Score": "0", "body": "I didn't mean that you *should* use a `Map`. I mentioned as an option. Both ways have advantages and disadvantages, the best solution depends on the use case. Here it doesn't matter much." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-17T08:51:50.997", "Id": "417102", "Score": "0", "body": "Understood. BTW, thought I'd point out about the variable names, I actually find it pretty convenient to go with single-letter names: c for character, f for frequency, i for iterator and so on." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-17T09:35:30.467", "Id": "417103", "Score": "0", "body": "I somewhat disagree with @janos's statement regarding single-letter variables for \"trivial, highly transient things\". I think the only appropriate use for these are, as I also state in my answer, as loop indices, where ```i```, ```j```, and maybe even ```k``` for a third level, are accepted. A very likely consumer of your code is a human being, maybe you, maybe a fellow coder. That person will appreciate decent naming." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-17T10:14:56.653", "Id": "417105", "Score": "1", "body": "@TomG But your consumer usually wouldn't have access to your code, would they? The consumer is meant to receive the application which the code runs. In case of another coder, you might be right, but even a simple remark next to the variable's declaration might suffice, would it not?\nActually, I only use single letters in my basic programs, like the one above. Usually my programs have clear names." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-17T11:34:31.763", "Id": "417113", "Score": "7", "body": "@ArtemisHunter There are aspects of style that are subjective. In this example, good objective arguments exist, against comments. 1. The consumers of your *binaries* indeed don't care about variable names. But the consumers of your *source code* do: the human reviewers and maintainers. Without descriptive names, it's hard to keep in mind what `f` meant, you may have to scan back in the program to understand, which is a mental burden. 2. Comments can go out of sync with the code they describe. If instead of comments you write in a way that's self-descriptive, that's a better long-term solution." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-18T10:33:03.303", "Id": "417255", "Score": "0", "body": "Mod note: if you want to have extended discussions around an answer (or a question), I'd like to suggest you use the [chat]. Comments are not intended for discussion. Thanks!" } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-17T08:40:49.817", "Id": "215601", "ParentId": "215592", "Score": "12" } }, { "body": "<h1>Warnings</h1>\n\n<p>Don't use the <code>suppresswarnings</code> annotation for things that can be fixed easily. I don't recognize the \"resource\" warning, I guess it's specific to the compiler you're using (Eclipse?). Probably comes from using the <code>Scanner</code> without closing it properly. By using the <a href=\"https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html\" rel=\"noreferrer\">try-with-resources</a> -statement for anything that supports <code>java.lang.AutoCloseable</code>, this will be handled for you automatically.</p>\n\n<h1>Variables and naming</h1>\n\n<p>There's no point in trying to save a few keystrokes by using short variable names. The compiler doesn't care what the names are, so you can just as well use human-readable names. The exception here being de-facto standardized loop indices like <code>i</code> and <code>j</code>.</p>\n\n<p>Any decent code editor or IDE will autocomplete the names for you, so it's not that much more to type. A modified section of your original code, notice how I also chained the call to <code>toUpperCase()</code> directly after the <code>nextLine()</code> call. No need to create a new variable for the case-corrected string:</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>Scanner inputScanner = new Scanner(System.in);\nString input = inputScanner.nextLine().toUpperCase();\n</code></pre>\n\n<h1>Object methods</h1>\n\n<p>Familiarize yourself with the <a href=\"https://docs.oracle.com/javase/10/docs/api/overview-summary.html\" rel=\"noreferrer\">Java standard library and API</a>. The <a href=\"https://docs.oracle.com/javase/10/docs/api/java/lang/String.html\" rel=\"noreferrer\">String</a> class has a method for returning its contents as a char array: <code>toCharArray()</code>. You could use that, combined with the <a href=\"https://docs.oracle.com/javase/tutorial/java/nutsandbolts/for.html\" rel=\"noreferrer\">enhanced for loop</a> to simplify your loop:</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>String input = // fetch string somehow\nfor (char inputChar : input.toCharArray()) {\n // Loop processing here\n}\n</code></pre>\n\n<p>Printing an array is similarly a one-line operation: <code>System.out.println(Arrays.toString(your array here))</code></p>\n\n<h1>Tips and tricks</h1>\n\n<p>There's a neat(?) trick for calculations using chars in Java. As you are upper-casing all the chars, you can use 'A' as the base for the array index. So instead of having two arrays, one with the frequencies, one for the char-to-index mapping, use subtraction from 'A' to get the index:</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>for (char inputChar : input.toCharArray()) {\n frequencies[inputChar - 'A']++;\n}\n</code></pre>\n\n<h1>Alternative implementation</h1>\n\n<p>Here's my alternative implementation using only the same data structures as in your original post. I do agree with <a href=\"https://codereview.stackexchange.com/users/195397/vishal-dhanotiya\">Vishal Dhanotiya</a> about the use of a map for this.</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>import java.util.Arrays;\nimport java.util.Scanner;\n\npublic class Letters {\n public static void main(String[] args) {\n\n int[] frequencies = new int[26];\n\n try (Scanner scanner = new Scanner(System.in)) {\n System.out.print(\"Enter a string: \");\n String input = scanner.nextLine().toUpperCase().replaceAll(\"[^A-Z]\", \"\");\n\n for (char inputChar : input.toCharArray()) {\n frequencies[inputChar - 'A']++;\n }\n\n for (int i = 0; i &lt; frequencies.length; i++) {\n System.out.printf(\"%s: %d, \", (char)('A' + i), frequencies[i]);\n }\n }\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-17T10:16:32.953", "Id": "417106", "Score": "0", "body": "Yes, the \"resource\" is from eclipse. I usually ignore it, but this time I just felt like adding it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-17T14:32:20.520", "Id": "417119", "Score": "0", "body": "It would probably be a good idea to check that inputChar is an uppercase letter. The code fails with `ArrayIndexOutOfBoundsException` otherwise." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-17T15:37:56.413", "Id": "417124", "Score": "0", "body": "@EricDuminil. I convert the whole string to uppercase, so that should be taken care of: ```String input = scanner.nextLine().toUpperCase();```. Should it still be checked with```Character.isUpperCase()```? Of course, this code fails in many ways if there are non-ASCII characters in the input. But ASCII was an implicit requirement also for the original code. I could have mentioned it, though." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-17T16:34:59.040", "Id": "417132", "Score": "0", "body": "@TomG: It fails with a space for example." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-17T17:09:37.450", "Id": "417137", "Score": "0", "body": "@EricDuminil, true, thanks for pointing that out! Never trust the user: if they can enter bad input, they will ;). Fixed it with a regex replacing everything except upper case A-Z before the loop. Any more code on there, and I really should break it out into it's own method..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-18T09:53:48.163", "Id": "417241", "Score": "1", "body": "If I was reviewing this, I think I'd want a comment for the `inputChar - 'A'` trick. Could also init the frequencies to `'Z' - 'A'` just to make clear what the length means?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-18T10:01:23.480", "Id": "417245", "Score": "0", "body": "Damn, can't edit anymore. The frequencies length should be `'Z' - 'A' + 1` but a `// A to Z` comment would be clearer." } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-17T09:30:00.587", "Id": "215602", "ParentId": "215592", "Score": "10" } } ]
{ "AcceptedAnswerId": "215601", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-17T04:37:54.237", "Id": "215592", "Score": "12", "Tags": [ "java", "strings" ], "Title": "Calculate the frequency of characters in a string" }
215592
<p>This is a practice problem on <a href="https://open.kattis.com/problems/greetingcard" rel="nofollow noreferrer">Kattis</a></p> <p>I have exceeded the time limit for the 5th out of 11 test case. Can anyone inspire me what could be done to optimize the code?</p> <p><strong>Problem Description</strong></p> <blockquote> <p>Quido plans to send a New Year greeting to his friend Hugo. He has recently acquired access to an advanced high-precision plotter and he is planning to print the greeting card on the plotter.</p> <p>Here’s how the plotter operates. In step one, the plotter plots an intricate pattern of <strong>n</strong> dots on the paper. In step two, the picture in the greeting emerges when the plotter connects by a straight segment each pair of dots that are exactly <strong>2018</strong> length units apart.</p> <p>The plotter uses a special holographic ink, which has a limited supply. Quido wants to know the number of all plotted segments in the picture to be sure that there is enough ink to complete the job.</p> <p><strong>Input</strong></p> <p>The first line of input contains a positive integer n specifying the number of plotted points. The following n lines each contain a pair of space-separated integer coordinates indicating one plotted point. Each coordinate is non-negative and less than <strong>2^31</strong>. There are at most <strong>10^5</strong> points, all of them are distinct.</p> <p>In this problem, all coordinates and distances are expressed in plotter length units, the length of the unit in the x-direction and in the y-direction is the same.</p> <p><strong>Output</strong></p> <p>The output contains a single integer equal to the number of pairs of points which are exactly <strong>2018</strong> length units apart.</p> </blockquote> <p><strong>Sample input</strong></p> <pre><code>4 20180000 20180000 20180000 20182018 20182018 20180000 20182018 20182018 </code></pre> <p><strong>Output</strong></p> <pre><code>4 </code></pre> <p>Here is my code</p> <pre><code>import java.util.*; class Coordinates { int x; int y; public Coordinates(int x,int y) { this.x=x; this.y=y; } public double distanceWith(Coordinates z) { return Math.hypot((x-z.x),(y-z.y)); } } class GreetingCard { public static void main(String [] args) { Scanner sc = new Scanner(System.in); HashSet&lt;Coordinates&gt; set = new HashSet&lt;&gt;(); int count = sc.nextInt(); int total = 0; for (int i=0;i&lt;count;i++) { int x = sc.nextInt(); int y = sc.nextInt(); Coordinates curr = new Coordinates(x,y); if (i!=0) { total+=findDistances(curr, set); } set.add(curr); } System.out.println(total); } public static int findDistances(Coordinates curr, HashSet&lt;Coordinates&gt; set) { int total = 0; for (Coordinates inside : set) { if (inside.distanceWith(curr)==2018) { total+=1; } } return total; } } </code></pre>
[]
[ { "body": "<p>Calculating the distance between each pair of points is expensive. Since the coordinates are all integers, you can first calculate which delta-x and delta-y can lead to the distance 2018 at all. Define a function <code>candidates(point, set)</code> that filters the possible candidates. To do this efficiently, group the points by their x coordinate. Then, for a given x, you only have to look at a few of these groups.</p>\n\n<p>Grouping the points improves performance because grouping has complexity around <span class=\"math-container\">\\$\\mathcal O(n)\\$</span>, where <span class=\"math-container\">\\$n\\$</span> is the number of points.</p>\n\n<p>Afterwards, finding the candidate points is a simple lookup: for each delta in (-2018, -1680, -1118, 0, 1118, 1860, 2018) you need one lookup, which again sums up to <span class=\"math-container\">\\$\\mathcal O(n)\\$</span>.</p>\n\n<p>In summary, the number of comparisons will be much less than the <span class=\"math-container\">\\$n\\cdot n\\$</span> from your current code.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-17T06:27:54.957", "Id": "417088", "Score": "0", "body": "Strictly speaking, how would you know if a particular arithmetic operation is expensive, after all a comparison is still made even in the filtering process that you suggested, why would it make such a big difference?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-17T06:47:04.263", "Id": "417089", "Score": "0", "body": "I expanded my answer a bit." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-17T06:25:05.980", "Id": "215595", "ParentId": "215594", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-17T05:58:10.673", "Id": "215594", "Score": "3", "Tags": [ "java", "programming-challenge", "time-limit-exceeded" ], "Title": "GreetingCard problem with Coordinates" }
215594
<p>I would like to define some constant sequences (of bytes, specifically) in my C# library/API. Both length and content should not vary, preferably by any means (barring reflection). To this end, a <code>byte[]</code> array would not be sufficient, and a <code>ReadOnlyCollection&lt;T&gt;</code> can still be mutated. I have not done a full comparison yet, but this effort may be re-inventing <code>ImmutableList&lt;T&gt;</code>, in which case I would still appreciate feedback on the successes and weaknesses of this implementation. To be precise, this class is meant to be inherited by multiple derived classes, which actually define the constants.</p> <h3>Design &amp; Style</h3> <ul> <li><p>I have chosen to build this class on the most primitive interface (<code>IEnumerable&lt;T&gt;</code>) that I could; partially to preserve maximal compatibility, and partially to avoid having to hide or throw <code>NotSupportedException</code> for certain <code>ICollection&lt;T&gt;</code> methods and such. Does this have any drawbacks?</p></li> <li><p>The actual collection that contains the items is a <code>private List&lt;byte&gt;</code>.</p></li> <li><p>I have implemented a couple convenience fields, <code>AsString</code>, <code>Count</code>, and <code>Length</code> (<code>Length</code> feels more appropriate for the type, but the existence of the <code>Count&lt;&gt;</code> LINQ extension made me feel both should be included for consistency). I considered <code>get</code>-only properties, however, <a href="https://stackoverflow.com/a/37496888/2868156">this Q&amp;A on SO</a> points out that <code>readonly</code> is a more explicit modifier. Are there other pros/cons that I am missing in this specific case?</p></li> <li><p>Given that I only intend to derive this class, I could mark it <code>abstract</code>, but could I also build it as an <code>interface</code>? (This would affect the <code>readonly</code>/<code>get</code>-only decision.) However, stylistically, it feels like derived classes should have an "is-a" relationship with <code>Bytes</code> rather than a "can-do".</p></li> <li><p>I have omitted all namespace qualifiers here, as seems to be the standard in C#. However, I come mostly from Python, and global imports and polluting the global namespace are almost unbearable to me. I also don't want to see <code>System.Collections.Generic.[...]</code> everywhere; is it an acceptable compromise to use, for example, <code>using CollectionsGen = System.Collections.Generic</code>, or would this horrify C# programmers reading my code?</p></li> </ul> <h3>Code</h3> <pre><code>/// &lt;summary&gt; /// Implementation of an immutable collection of bytes, with some extras. /// &lt;/summary&gt; public class Bytes : IEnumerable&lt;byte&gt; { private List&lt;byte&gt; bytesList; public readonly string AsString; public readonly int Count; public readonly int Length; // just a synonym for Count // accepts values from -Length to Length-1 (similar to Python indexing). public byte this[int i] { get { return this.bytesList[ i&gt;=0 ? i : i+this.Length ]; } } public Bytes(IEnumerable&lt;byte&gt; bytes) { this.bytesList = new List&lt;byte&gt;(bytes); this.AsString = string.Join(" ", this.Select(b =&gt; $"0x{b:X2}")); this.Count = this.bytesList.Count; this.Length = this.Count; } public IEnumerator&lt;byte&gt; GetEnumerator() { return this.bytesList.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return this.GetEnumerator(); } </code></pre> <p>I think could generalize this to any type by defining <code>public class MyImmutableCollection&lt;T&gt; : IEnumerable&lt;T&gt;</code> with roughly the same body, but I have no need for that now.</p> <h3>Usage</h3> <pre><code>var byteArray = new byte[] { 0x01, 0x02, 0x03 }; var bytesInst = new Bytes(byteArray); byteArray[1] = 0xFF; // observe that byteArray has changed, where bytesInst has not. bytesInst[1] = 0xFF; // correctly generates a read-only compiler error </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-17T07:29:11.810", "Id": "417090", "Score": "0", "body": "Mhmm... I would just use the `ReadOnlyList` or any of the other type from the `System.Collections.Immutable` package. The negative indexing could then just be an extension method. Maybe if you showed us how this is supposed to be used it would make more sense." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-17T07:34:31.237", "Id": "417092", "Score": "0", "body": "oh, and could you show me a way how to mutate a `ReadOnlyCollection`? I couldn't find any." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-17T07:44:40.457", "Id": "417095", "Score": "0", "body": "@t3chb0t Sure, and the negative indexing is just a nice-to-have. Only issue right now is that I don't have access to the NuGet packages right now on this machine, so it will be some time before I can even try it out. Still it was an interesting exercise to try to make something really read-only. Did I do okay? `:)`.\nFrom what I've seen `ReadOnlyCollection` can be changed if you still have access to the wrapped collection. I think it can also be obtained from the `Items` property. The msdn site's example shows mutation in the first case." } ]
[ { "body": "<h2>Abstractness</h2>\n\n<blockquote>\n <p>To be precise, this class is meant to be inherited by multiple derived classes, which actually define the constants.</p>\n</blockquote>\n\n<p>Do you mean there will be many <em>classes</em> each of which contain a constant set of <code>bytes</code>, but are otherwise the same? If so, then there is no need to create a new class for each one. You could instead just provide <code>static readonly</code> instances for each constant, e.g.</p>\n\n<pre><code>public static class MagicNumbers\n{\n public static readonly Bytes Example1 = new Bytes(new byte[] { 0xFF, 0xFF });\n public static readonly Bytes Example2 = new Bytes(new byte[] { 0xFE, 0xFF });\n}\n</code></pre>\n\n<h2>Readonlyness</h2>\n\n<p>This certainly provides a read-only interface, which is good. The only way to violate the read-onlyness would be with reflection (which it is essentially always fine to ignore).</p>\n\n<p>You are right that the backing collection of a <code>ReadOnlyCollection&lt;T&gt;</code> can change; this is all part of the 'interface is gospel' approach of languages like C# (which personally I subscribe to whole-heartedly). Note that if you pass a <code>ReadOnlyCollection&lt;T&gt;</code> to someone else, however, that <em>they</em> can't modify it. This means it is up to whoever creates the backing collections for the <code>ReadOnlyCollection&lt;T&gt;</code> as to what can or cannot be done with it. <code>ReadOnlyCollection&lt;T&gt;</code>, however, is not a type I would use for anything, pretty much, because it unhelpfully implements <code>IList&lt;T&gt;</code> (among other things). It's also annoyingly named (in my opinion), because <code>IReadOnlyCollection&lt;T&gt;</code> doesn't expose indexed retrieval (that's <code>IReadOnlyList&lt;T&gt;</code> job).</p>\n\n<p>It's good that your constructor takes an <code>IEnumerable&lt;T&gt;</code>. You might consider implementing <code>IReadOnlyList&lt;T&gt;</code> (which 'includes' <code>IEnumerable&lt;T&gt;</code>) if you think it appropriate; this would expose an efficient implementation of <code>Count</code> and <code>T this[int]</code> (more discussion about this below).</p>\n\n<p>Inside your class you could also use a read-only collection instead of <code>List&lt;byte&gt;</code>, to enforce the contract internally, e.g. <code>IReadOnlyList&lt;T&gt;</code>.</p>\n\n<h2>Properties</h2>\n\n<p>Your <code>Count</code> and <code>Length</code> properties are, as you comment, redundant. Don't do this: it will only create confusion. <code>Length</code> is (in my experiance) pretty much exclusive to arrays: go with <code>Count</code> instead (it's the property exposed by <code>IReadOnlyList&lt;T&gt;</code>), and instead of storing the value, I'd suggest retrieving it from the actual list, which means the construtor has less to do (which means there is less to go wrong).</p>\n\n<pre><code> public int Count =&gt; bytesList.Count;\n</code></pre>\n\n<p>It's good that your external properties were <code>readonly</code> (this is preserved with the 'expression-bodied property' syntax above). You might also want to make <code>bytesList</code> <code>readonly</code> (the class is fine as it is, because it's public API is sound, but this again will enforce the contract inside the class, making it easier to maintain and understand).</p>\n\n<p>Concerning <code>readonly</code> vs getter-only, unless I have good reason (which basically never happens), I go with getter-only. While what <code>Rob</code> says in the linked thread is true, I personlly don't care what a class does so long as the API makes sense, and a public <code>readonly</code> field has two important disadvantages over getter-only properties: it can't implement an interface property (e.g. <code>int IReadOnlyList.Count</code>), and you can't quietly change it to be a property in future. For example, changing your <code>public int read-only Count</code> to <code>public int Count =&gt; byteList.Count</code> is a binary breaking change: any code that depends on the old field needs to be recompiled to work with the new property. If, however, you had made it <code>public int Count { get; }</code>, then you could make this change to the <em>implementation</em> without breaking any consuming code. One case where you might want this would be <code>AsString</code>: if you found that this was hardly ever being used, you might consider deferring the creation until it is needed: you <em>can't</em> do this with a <code>readonly</code> field, but you can easily replace a getter-only property with one which implements caching.</p>\n\n<p>In practical terms, as Henk Holterman points out in the linked thread, <code>readonly</code> fields are a nightmare when it comes to serialisation. A getter-only field, however, can become a <code>{ get; private set; }</code> field without issue if your serialisation scheme demands it. This is by no means ideal, but it doesn't change the external API, so the unpleasantness is contained within the class.</p>\n\n<h2>Indexer <code>this[int]</code></h2>\n\n<p>You might consider the <code>expression-bodied member</code> syntax again:</p>\n\n<pre><code>public byte this[int i] =&gt; this.bytesList[ i &gt;= 0 ? i : i + this.Count ];\n</code></pre>\n\n<p>Though it's just syntatic sugar we could live without, it is arguably a bit easier to read, and makes it immediately apprent that there is no <code>set</code> block.</p>\n\n<p>If you did decide to implement <code>IReadOnlyList</code>, you would need 2 versions of this methods; one with the negative-index support, and one without.</p>\n\n<pre><code>byte IReadOnlyList&lt;T&gt;.this[int i] =&gt; this.bytesList[i];\npublic byte this[int i] =&gt; this.bytesList[ i &gt;= 0 ? i : i + this.Count ];\n</code></pre>\n\n<p>This means that code which misuses the <code>IReadOnlyList&lt;T&gt;</code> interface will still get an out-of-bounds error, but anyone who has an instance of your class by name of the class can use the negative-indexing.</p>\n\n<h2>Namespace qualifiers</h2>\n\n<p>It's been a while since I used Python for anything substancial, but my understanding is that *-imports pull methods as well as classes, so the issue is lesser in C# (only pulls types and other namespaces). As you say, it's pretty standard for C#ers to use *-imports, and because it is expected, APIs are designed in a manner which assumes it: e.g. there are many more namespaces in C# than C++. Most importantly, however, is that C# fails at compile-time if there are <em>observed</em> name-collisions (e.g. even if <code>Horse</code> could be interpreted as two things, the code is fine so long as you don't try to use <code>Horse</code> unqualified). This means two things have to change for library authors to break your code - the introduction of a 'duplicate' method or type in a dependency in Python will quietly create problems - and you can't break your own (because it won't compile). The only leak in all this, is that classes in their own namespace are preferred over classes in an imported namespace (but only the author of that namespace can change the behaviour of their code, not someone else).</p>\n\n<p><code>using CollectionsGen = System.Collections.Generic</code> would mostly horrifying me because <code>Gen</code> is truncated. Anothing think you'll find in C# is that we prefer long easy-to-remember-and-understand names over short quicker-to-type (if you can remember them) names. The time-to-type is minimised by auto-complete in the IDE/editor.</p>\n\n<h2>Documentation</h2>\n\n<p>It's good that your class has an inline-summary, but inline-documentation (<code>///</code>) on all public non-inherited members significantly improved usabily. The <code>Count == Length</code> thing, for example, would be confusing no end, which is why you have a comment in your code to remind you that it is correct: this same comment should be available to the people using your code. The negative-indexing support is another thing that should be documented externally. The constructor should also state that it takes a copy of the <code>IEnumerable</code>; while this is implied (by virtue of taking an <code>IEnumerable&lt;T&gt;</code> rather than, say, an <code>IReadOnlyList&lt;T&gt;</code>), as a consumer of your code I would appreciate knowing that this is the intended long-term behaviour and not just an implementation detail.</p>\n\n<p>Remember: code is <em>consumed</em> far more often than it is read or written (which people all too often seem to forget).</p>\n\n<h2>Misc</h2>\n\n<ul>\n<li><p>I wouldn't bother with the lining stuff up; it's just effort to maintain.</p></li>\n<li><p>I'd also avoid things like \"x>=2\", and some IDEs will 'correct' it to <code>x &gt;= 2</code>, so you'll just end up fighting them. If expressions need grouping, then use parenthesis, which are unambiguous.</p></li>\n<li><p>If you are worried about space, consider using a <code>byte[]</code> rather than a list (you can use LINQ's <code>IEnumerable&lt;T&gt;.ToArray()</code> (guarantees copy) to keep the code short. (Note that <code>byte[]</code> implements <code>IReadOnlyList&lt;T&gt;</code>).</p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-18T22:23:09.450", "Id": "417378", "Score": "0", "body": "Thanks for this review. To briefly clarify the usage, I have a few dozen constants that conform to different rules, and so really should be different types. So their classes will inherit `Bytes`, and those classes will clearly define the different kinds of constants. At least, I hope this is a reasonable design." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-18T22:23:13.370", "Id": "417379", "Score": "0", "body": "I will take your advice and implement properties instead of fields. I was leaning towards fields because the values are also constant and can be evaluated at creating the instance. This should have some performance gain over calling a function every time, but I hear that properties are usually inlined anyway, so it may not be an issue." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-17T14:41:42.260", "Id": "215611", "ParentId": "215599", "Score": "5" } }, { "body": "<p>There is no need to define a class <em>at all</em>. Everything you want to do, you can do with extension methods:</p>\n\n<ul>\n<li><p>The <code>Length</code> field is completely unnecessary. There is not a need to make <code>Length</code> a synonym for <code>Count</code>. Yes, it is unfortunate that in .NET some collections have <code>Count</code> and some have <code>Length</code>. It's a dumb inconsistency. Live with it.</p></li>\n<li><p>The indexer with the fancy wraparound behavior can be replaced by an extension method:</p></li>\n</ul>\n\n<hr>\n\n<pre><code>public static T Index&lt;T&gt;(this IImmutableList&lt;T&gt; items, int i) =&gt; \n items[i &gt;= 0 ? i : items.Count + i]\n</code></pre>\n\n<hr>\n\n<ul>\n<li>The <code>AsString</code> can also be replaced with an extension method, or even better, two:</li>\n</ul>\n\n<hr>\n\n<pre><code>public static string WithSpaces&lt;T&gt;(this IEnumerable&lt;T&gt; items) =&gt;\n string.Join(\" \", items);\n\npublic static string AsHex(this IEnumerable&lt;byte&gt; bytes) =&gt; \n bytes.Select(b =&gt; $\"0x{b:X2}\").WithSpaces();\n</code></pre>\n\n<hr>\n\n<p>And now you can delete <code>class Bytes</code> and just use an <code>ImmutableList&lt;byte&gt;</code> in all places where you used <code>Bytes</code> before. Want to index it with your fancy indexer? <code>myBytes.Index(-1)</code>, done. Want a hex string? <code>myBytes.ToHex()</code>, done. No class required.</p>\n\n<blockquote>\n <p>global imports and polluting the global namespace are almost unbearable to me</p>\n</blockquote>\n\n<p>Well, you be you, but C# programmers do not consider <code>using System.Collections.Generic;</code> to be \"polluting the global namespace\". The notion that bringing useful types into scope is \"pollution\" is a strange one.</p>\n\n<blockquote>\n <p>this class is meant to be inherited by multiple derived classes, which actually define the constants.</p>\n</blockquote>\n\n<p>Please do not. There is no reason you've given to build an inheritance hierarchy for <em>constant byte sequences</em>. Just make an <code>ImmutableList&lt;byte&gt;</code> when you need one!</p>\n\n<p>You may be suffering from a condition I call \"object oriented happiness syndrome\", which is a condition common to OO programmers who think they have to use OO techniques in order to solve problems that they don't actually have. You want an immutable sequence of bytes, then <em>make an immutable sequence of bytes</em>. Don't make a class and then have to figure out an inheritance mechanism that you don't need. OO techniques are for organizing large bodies of code written by teams that have to communicate across organizational boundaries; you don't have to use all that ceremony to represent what is essentially a string!</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-20T07:47:58.363", "Id": "417593", "Score": "0", "body": "Thank you for this thoughtful review, @Eric." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-20T06:35:08.653", "Id": "215814", "ParentId": "215599", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-17T07:23:52.950", "Id": "215599", "Score": "3", "Tags": [ "c#", ".net", "reinventing-the-wheel", "immutability" ], "Title": "Implement Immutable Collection in C#" }
215599
<p><em>Application Logic</em></p> <p>I wrote a web scraper that store some football data inside my database. Those data need to be update if 7 days are passed since the last update. I have three types of record:</p> <ul> <li>Team</li> <li>Season</li> <li>Player</li> </ul> <p>The table structure of those records is essentially this:</p> <pre><code>id | season_id | update_at </code></pre> <p>only the second column name change for the specific type, eg for <code>Team</code>:</p> <pre><code>id | team_id | | update_at </code></pre> <p><em>Structure</em></p> <p>The web scraper run 24h on a server, and check steadily if the records need to be updated. For doing that I wrote this method:</p> <pre><code>public List&lt;Season&gt; GetSeasonsToAddUpdate(List&lt;Season&gt; seasons) { //Store the seasons that need to update List&lt;Season&gt; newSeasons = new List&lt;Season&gt;(); using (MySqlConnection connection = new DBConnection().Connect) { using (MySqlCommand command = new MySqlCommand()) { connection.Open(); command.Connection = connection; //Get all the ids of the seasons to add or update command.CommandText = "SELECT cs.season_id " + "FROM (SELECT {textToReplace}) cs " + "LEFT JOIN competition_seasons s on s.id = cs.season_id " + "WHERE s.id IS NULL OR " + "s.update_at &lt; DATE_SUB(CURRENT_DATE, INTERVAL 7 DAY) OR s.update_at IS NULL"; //Join all the available parameters. StringBuilder unions = new StringBuilder(); //List of available parameters. List&lt;MySqlParameter&gt; prms = new List&lt;MySqlParameter&gt;(); //Add the first parameter. MySqlParameter pr = new MySqlParameter("@first", MySqlDbType.UInt32) { Value = seasons.First().Id }; prms.Add(pr); unions.Append($" @first as season_id "); //Start from one 'cause first param already defined in query. int prmCounter = 1; //Create the parameter for the derived table based on the available seasons foreach (Season t in seasons.Skip(1)) { string placeholder = "@p" + prmCounter; unions.Append($" UNION ALL SELECT {placeholder}"); pr = new MySqlParameter(placeholder, MySqlDbType.Int32) { Value = t.Id }; prms.Add(pr); prmCounter++; } command.Parameters.AddRange(prms.ToArray()); command.CommandText = command.CommandText.Replace("{textToReplace}", unions.ToString()); using (MySqlDataReader reader = command.ExecuteReader()) { //Remove all the seasons that doesn't need update. while (reader.Read()) { newSeasons.Add(seasons.FirstOrDefault(x =&gt; x.Id == Convert.ToInt32(reader["season_id"]))); } } return newSeasons; } } } </code></pre> <p>Basically, the method above only works for the <code>Season</code> object, and perform the following query:</p> <pre><code>SELECT cs.season_id FROM (SELECT 67 as season_id UNION ALL SELECT 68 UNION ALL SELECT 69 UNION ALL SELECT 70 ) cs LEFT JOIN competition_season s on s.id = cs.season_id AND update_at &gt;= DATE_SUB(CURRENT_DATE, INTERVAL 7 DAY) WHERE s.id IS NULL; </code></pre> <p>The query structure is essentially the same for the other two type: <code>Team</code> and <code>Players</code> (only the table name change).</p> <p><em>The goal</em></p> <p>My goal is remove the code redundancy, 'cause I have three method of the code above which are essentially the same but change only for the table name and the type of object, eg:</p> <pre><code>public List&lt;Team&gt; GetTeamsToAddUpdate(List&lt;Team&gt; teams) { //Store the teams that need to update List&lt;Team&gt; newTeams = new List&lt;Team&gt;(); using (MySqlConnection connection = new DBConnection().Connect) { using (MySqlCommand command = new MySqlCommand()) { connection.Open(); command.Connection = connection; //Get all the ids of the teams to add or update command.CommandText = "SELECT tt.team_id " + "FROM (SELECT {textToReplace}) tt " + "LEFT JOIN team t on t.id = tt.team_id " + "WHERE t.id IS NULL OR " + "t.update_at &lt; DATE_SUB(CURRENT_DATE, INTERVAL 7 DAY) OR t.update_at IS NULL"; </code></pre> <p>I though to implement something like a switch statement for create 1 method that handle multiple types, but I don't know if there are better ways to handle this.</p> <p>Could someone tell me if is possible optimize that and remove this redundancy?</p> <hr> <p>The other two methods:</p> <p><em>Team:</em></p> <pre><code>public List&lt;Team&gt; GetTeamsToAddUpdate(List&lt;Team&gt; teams) { List&lt;Team&gt; newTeams = new List&lt;Team&gt;(); using (MySqlConnection connection = new DBConnection().Connect) { using (MySqlCommand command = new MySqlCommand()) { connection.Open(); command.Connection = connection; command.CommandText = "SELECT tt.team_id " + "FROM (SELECT {textToReplace}) tt " + "LEFT JOIN team t on t.id = tt.team_id " + "WHERE t.id IS NULL OR " + "t.update_at &lt; DATE_SUB(CURRENT_DATE, INTERVAL 7 DAY) OR t.update_at IS NULL"; StringBuilder unions = new StringBuilder(); List&lt;MySqlParameter&gt; prms = new List&lt;MySqlParameter&gt;(); MySqlParameter pr = new MySqlParameter("@first", MySqlDbType.UInt32) { Value = teams.First().Id }; prms.Add(pr); unions.Append($" @first as team_id "); int prmCounter = 1; foreach (Team t in teams.Skip(1)) { string placeholder = "@p" + prmCounter; unions.Append($" UNION ALL SELECT {placeholder}"); pr = new MySqlParameter(placeholder, MySqlDbType.Int32) { Value = t.Id }; prms.Add(pr); prmCounter++; } command.Parameters.AddRange(prms.ToArray()); command.CommandText = command.CommandText.Replace("{textToReplace}", unions.ToString()); using (MySqlDataReader reader = command.ExecuteReader()) { while (reader.Read()) { newTeams.Add(teams.FirstOrDefault(x =&gt; x.Id == Convert.ToInt32(reader["team_id"]))); } } return newTeams; } } } </code></pre> <p><em>Player</em>:</p> <pre><code>public List&lt;Player&gt; GetPlayersToAddUpdate(List&lt;Player&gt; players) { List&lt;Player&gt; newPlayers = new List&lt;Player&gt;(); using (MySqlConnection connection = new DBConnection().Connect) { using (MySqlCommand command = new MySqlCommand()) { connection.Open(); command.Connection = connection; command.CommandText = "SELECT pp.player_id " + "FROM (SELECT {textToReplace}) pp " + "LEFT JOIN player p on p.id = pp.player_id " + "WHERE p.id IS NULL OR " + "p.update_at &lt; DATE_SUB(CURRENT_DATE, INTERVAL 7 DAY) OR p.update_at IS NULL"; StringBuilder unions = new StringBuilder(); List&lt;MySqlParameter&gt; prms = new List&lt;MySqlParameter&gt;(); MySqlParameter pr = new MySqlParameter("@first", MySqlDbType.UInt32) { Value = players.First().Id }; prms.Add(pr); unions.Append($" @first as player_id "); int prmCounter = 1; foreach(Player p in players.Skip(1)) { string placeholder = "@p" + prmCounter; unions.Append($" UNION ALL SELECT {placeholder}"); pr = new MySqlParameter(placeholder, MySqlDbType.Int32) { Value = p.Id }; prms.Add(pr); prmCounter++; } command.Parameters.AddRange(prms.ToArray()); command.CommandText = command.CommandText.Replace("{textToReplace}", unions.ToString()); using (MySqlDataReader reader = command.ExecuteReader()) { while (reader.Read()) { newPlayers.Add(players.FirstOrDefault(x =&gt; x.Id == Convert.ToInt32(reader["player_id"]))); } } return newPlayers; } } } </code></pre>
[]
[ { "body": "<blockquote>\n <p><code>new DBConnection().Connect</code></p>\n</blockquote>\n\n<p>Just curious: from where have you this construct?</p>\n\n<hr>\n\n<p>You should check the input:</p>\n\n<pre><code>if (seasons == null || seasons.Count == 0) return seasons; // or throw?\n</code></pre>\n\n<hr>\n\n<blockquote>\n<pre><code> using (MySqlConnection connection = new MySqlConnection())\n {\n using (MySqlCommand command = new MySqlCommand())\n {\n connection.Open();\n command.Connection = connection;\n //Get all the ids of the seasons to add or update\n command.CommandText = \"SELECT cs.season_id \" +\n \"FROM (SELECT {textToReplace}) cs \" +\n \"LEFT JOIN competition_seasons s on s.id = cs.season_id \" +\n \"WHERE s.id IS NULL OR \" +\n \"s.update_at &lt; DATE_SUB(CURRENT_DATE, INTERVAL 7 DAY) OR s.update_at IS NULL\";\n</code></pre>\n</blockquote>\n\n<p>You should open the connection for a short a period as possible and build the command text using a <code>StringBuilder</code> instead.</p>\n\n<pre><code>StringBuilder commandBuilder = new StringBuilder();\ncommandBuilder.AppendFormat(...);\n...\n// and the other initialization stuff\n...\nusing (MySqlConnection connection = new MySqlConnection())\n{\n using (MySqlCommand command = new MySqlCommand())\n {\n connection.Open();\n command.Connection = connection; \n command.CommandText = commandBuilder.ToString();\n using (MySqlDataReader reader = command.ExecuteReader())\n {\n ...\n</code></pre>\n\n<p>And besides that, concatenating strings in the above manner is considered bad practice and is expensive, because you instantiate a lot more strings than you may think (9 in the example above, I think).</p>\n\n<hr>\n\n<p>In order to generalize the method, you have to consider only three variables: the items in the list, the table name and the name of the id column. The table name and the name of the id column are just strings, so it is easy.</p>\n\n<p>For the items in the list, you can let them derive from the same base class that holds the Id as property, or you could let them implement an interface like:</p>\n\n<pre><code> public interface IdHolder // Maybe a descriptive name, but some kind of ugly?\n {\n int Id { get; }\n }\n\n public class Team : IdHolder\n {\n public int Id { get; internal set; }\n }\n\n public class Season : IdHolder\n {\n public int Id { get; internal set; }\n }\n\n public class Player : IdHolder\n {\n public int Id { get; internal set; }\n }\n</code></pre>\n\n<p>Doing so you can make a generic method with a signature like:</p>\n\n<pre><code>public IEnumerable&lt;TItem&gt; GetItemsToAddUpdate&lt;TItem&gt;(IEnumerable&lt;TItem&gt; items, string tableName, string idColumn) where TItem : IdHolder\n</code></pre>\n\n<p>and then the rest is just a question of readjusting the existing string creation in one of the methods, so it all in all could end up like something like this:</p>\n\n<pre><code>public IEnumerable&lt;TItem&gt; GetItemsToAddUpdate&lt;TItem&gt;(IEnumerable&lt;TItem&gt; items, string tableName, string idColumn) where TItem : IdHolder\n{\n if (items == null || !items.Any())\n {\n yield break;\n }\n\n StringBuilder commandBuilder = new StringBuilder();\n commandBuilder.AppendFormat(\"SELECT idLst.{0} \", idColumn);\n commandBuilder.Append(\"FROM (SELECT {textToReplace}) idLst \");\n commandBuilder.AppendFormat(\"LEFT JOIN {0} x on x.id = idLst.{1} \", tableName, idColumn);\n commandBuilder.Append(\"WHERE x.id IS NULL OR \");\n commandBuilder.Append(\"x.update_at &lt; DATE_SUB(CURRENT_DATE, INTERVAL 7 DAY) OR x.update_at IS NULL\");\n\n //Join all the available parameters.\n StringBuilder unions = new StringBuilder();\n\n //List of available parameters.\n List&lt;MySqlParameter&gt; parameters = new List&lt;MySqlParameter&gt;();\n\n //Add the first parameter.\n MySqlParameter pr = new MySqlParameter(\"@first\", MySqlDbType.UInt32) { Value = items.First().Id };\n parameters.Add(pr);\n unions.AppendFormat(\" @first as {0} \", idColumn);\n\n //Start from one 'cause first param already defined in query.\n int parameterIndex = 1;\n\n //Create the parameter for the derived table based on the available seasons\n foreach (TItem item in items.Skip(1))\n {\n string placeholder = \"@p\" + parameterIndex;\n unions.Append($\" UNION ALL SELECT {placeholder}\");\n pr = new MySqlParameter(placeholder, MySqlDbType.Int32) { Value = item.Id };\n parameters.Add(pr);\n parameterIndex++;\n }\n\n using (MySqlConnection connection = new MySqlConnection(\"&lt;ConnectionString?&gt;\"))\n {\n using (MySqlCommand command = new MySqlCommand())\n {\n connection.Open();\n command.Connection = connection;\n command.Parameters.AddRange(parameters.ToArray());\n command.CommandText = commandBuilder.ToString().Replace(\"{textToReplace}\", unions.ToString());\n\n using (MySqlDataReader reader = command.ExecuteReader())\n {\n //Remove all the seasons that doesn't need update.\n while (reader.Read())\n {\n TItem item = items.FirstOrDefault(x =&gt; x.Id == Convert.ToInt32(reader[idColumn]));\n if (item != null)\n yield return item;\n }\n }\n }\n }\n}\n</code></pre>\n\n<p>You can then make dedicated methods for each object type as:</p>\n\n<pre><code>public IEnumerable&lt;Team&gt; GetTeamsToAddUpdate(IEnumerable&lt;Team&gt; teams)\n{\n return GetItemsToAddUpdate(teams, \"team\", \"team_id\");\n}\n</code></pre>\n\n<hr>\n\n<p>If making the types implement a common interface or derive from the same base class is not an option, then you can provide a function as argument for extracting the id from each item:</p>\n\n<pre><code>public IEnumerable&lt;TItem&gt; GetItemsToAddUpdate&lt;TItem&gt;(IEnumerable&lt;TItem&gt; items, Func&lt;TItem, int&gt; idFetcher, string tableName, string idColumn)\n</code></pre>\n\n<p>where <code>idFetcher</code> is called like:</p>\n\n<pre><code> MySqlParameter pr = new MySqlParameter(\"@first\", MySqlDbType.UInt32) { Value = idFetcher(items.First()) };\n</code></pre>\n\n<p>and the method can be called as:</p>\n\n<pre><code>public IEnumerable&lt;Team&gt; GetTeamsToAddUpdate(IEnumerable&lt;Team&gt; teams)\n{\n return GetItemsToAddUpdate(teams, (team) =&gt; team.Id, \"team\", \"team_id\");\n}\n</code></pre>\n\n<hr>\n\n<p>Disclaimer: I may have overlooked some minor details in the sql strings, that differs from one type to the other.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-20T18:58:26.520", "Id": "417697", "Score": "0", "body": "First of all, thanks for the help, just a question: I did: `teams = GetItemsToAddUpdate(teams, \"team\", \"team_id\");` where `teams` is: `List<Team> teams = new List<Teams>();`. I got this error: `You can't use the type 'SWP.Models.Team' as a parameter of type 'TItem' in the method or in the generic type 'GetItemsToAddUpdate <TItem> (IEnumerable <TItem>, string, string)'.`, I did something wrong?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-20T19:45:21.927", "Id": "417699", "Score": "1", "body": "@sfarzoso: The `Team` class you use, does it implement `IdHolder`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-20T20:14:39.480", "Id": "417706", "Score": "0", "body": "Oh sorry I overlooked it, another thing: why do you set `internal set`? I need to use `set`, is there a specific reason?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-20T20:26:03.163", "Id": "417708", "Score": "1", "body": "@sfarzoso: Sorry, not at all, you can freely change the access specifier to support your needs (for instance `public`)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-20T20:43:02.387", "Id": "417709", "Score": "0", "body": "I'm not practice of `yield` operator, if I understood well, `yield` should add the item to a collection? Could you please explain the line `yield return item`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-20T20:51:06.750", "Id": "417711", "Score": "1", "body": "@sfarzoso: There is a quite good explanation with examples in the reference [here...](https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/yield)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-20T20:53:35.330", "Id": "417712", "Score": "1", "body": "Thanks for the help, I really appreciate that, have a good day :)" } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-19T15:47:46.397", "Id": "215760", "ParentId": "215603", "Score": "2" } }, { "body": "<p>My first recommendation would be to refactor this query so that it's friendlier to dynamic construction. Perhaps something like</p>\n\n<pre class=\"lang-sql prettyprint-override\"><code>CREATE TEMPORARY TABLE RequestedIds (id INT);\nINSERT INTO RequestedIds (id)\nVALUES (@p0), (@p1), (@p2);\n\nSELECT requested.id\nFROM RequestedIds AS requested\nLEFT JOIN player AS item ON item.id = requested.id\nWHERE item.id IS NULL\n OR item.update_at IS NULL\n OR item.update_at &lt; DATE_SUB(CURRENT_DATE, INTERVAL 7 DAY);\n</code></pre>\n\n<p>Now the <em>only</em> indicator here that we're looking at players (and not seasons or teams) is the table name. Also, the use of a temp table means the generated list of parameters is isolated. <code>(@p0), (@p1), (@p2)</code> is more straightforward to build than <code>SELECT @first as id UNION ALL SELECT @p1 UNION ALL SELECT @p2</code>.</p>\n\n<p>Now the command text is buildable with something like this:</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>private string BuildCommandText(IEnumerable&lt;MySqlParameter&gt; parameters, string tableName)\n{\n var paramNames = parameters.Select(param =&gt; $\"({param.ParameterName})\");\n\n return string.Join(Environment.NewLine,\n \"CREATE TEMPORARY TABLE RequestedIds (id INT);\",\n \"INSERT INTO RequestedIds (id)\",\n $\"VALUES {string.Join(\", \", paramNames)};\",\n \"\",\n \"SELECT requested.id\",\n \"FROM RequestedIds AS requested\",\n $\"LEFT JOIN {tableName} AS item ON item.id = requested.id\",\n \"WHERE item.id IS NULL\",\n \"OR item.update_at IS NULL\",\n \"OR item.update_at &lt; DATE_SUB(CURRENT_DATE, INTERVAL 7 DAY);\");\n}\n</code></pre>\n\n<p>As a side note, I usually prefer <code>string.Join</code> over <code>StringBuilder</code>. The performance is comparable, and it feels more declarative: \"Join these string with newlines\" vs \"Start with this string. Now add this string. Now add this string...\"</p>\n\n<hr/>\n\n<p>As for the parameters themselves, you can map a collection of IDs to a collection of parameters with a helper function like this:</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>var parameters = players.Select(player =&gt; player.Id).Select(BuildIdParameter);\n\n// ...\n\nprivate MySqlParameter BuildIdParameter(int value, int index)\n{\n return new MySqlParameter($\"p{index}\", MySqlDbType.Int32) { Value = value };\n}\n</code></pre>\n\n<p>This technique takes advantage of the handy automatic index parameter provided by <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.linq.enumerable.select?view=netframework-4.7.2#System_Linq_Enumerable_Select__2_System_Collections_Generic_IEnumerable___0__System_Func___0_System_Int32___1__\" rel=\"nofollow noreferrer\">this overload of Select</a>. I recommend doing this in conjunction with the generalization advice from Henrik's answer.</p>\n\n<hr/>\n\n<p>My last piece of advice is for after you've done the query. If you hide the actual execution of the query in a function, like this (braces ommitted for brevity)</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>private IEnumerable&lt;int&gt; GetIdsToAddOrUpdate(...)\n{\n using (var connection...)\n using (var command...)\n using (var reader...)\n while (reader.read())\n yield return Convert.ToInt32(reader[\"id\"]);\n}\n</code></pre>\n\n<p>Then you can skip the <code>.FirstOrDefault</code> and the null check, and write</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>public List&lt;TItem&gt; GetItemsToAddOrUpdate&lt;TItem&gt;(List&lt;TItem&gt; items) where TItem : IDHolder\n{\n var ids = GetIdsToAddOrUpdate(...).ToHashSet();\n\n return items.Where(item =&gt; ids.Contains(item.Id)).ToList();\n}\n</code></pre>\n\n<p>Now, this <em>is</em> more efficient for large numbers of players/teams/seasons: it is O(n), while calling <code>.FirstOrDefault</code> in a loop gives you O(n^2). However, you're unlikely to notice the difference unless <code>n</code> is large indeed.</p>\n\n<p>The real reason I like it isn't the efficiency, but because it's more declarative: \"The players that need to be updated are all the players with IDs that need to be updated\".</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-22T17:53:07.513", "Id": "417968", "Score": "0", "body": "Isn't a temp table creation slower than a direct query execution?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-22T17:57:45.080", "Id": "417969", "Score": "1", "body": "It may be. Honestly, I have no idea. You could try it out and see if you notice performance issues. You could adapt this command-building approach to work with an inline UNION query. Or you could ignore that advice entirely - this is just my opinion on how to make the code prettier :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-22T18:18:01.290", "Id": "417970", "Score": "0", "body": "I appreciate your help, thanks, maybe you could look at that question: https://stackoverflow.com/questions/55247116/how-to-execute-different-query-based-on-returned-value I started a bounty" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-22T17:41:01.910", "Id": "216009", "ParentId": "215603", "Score": "1" } } ]
{ "AcceptedAnswerId": "215760", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-17T10:52:01.317", "Id": "215603", "Score": "5", "Tags": [ "c#", "mysql", "web-scraping" ], "Title": "Web scraper for football data with three very similar methods" }
215603
<p>This is my implementation of lowest common ancestor problem,I tried to solve it using square root decomposition </p> <blockquote> <p>pre processing time : O(n)</p> <p>query time:O(sqrt(h))<br> h -> height of tree</p> </blockquote> <p>This was <a href="https://www.spoj.com/problems/LCA/" rel="nofollow noreferrer">LCA on spoj</a></p> <p>Well i added comments in my code and My approach very well explained here with every line of code <a href="https://www.geeksforgeeks.org/sqrt-square-root-decomposition-set-2-lca-tree-osqrth-time/" rel="nofollow noreferrer">https://www.geeksforgeeks.org/sqrt-square-root-decomposition-set-2-lca-tree-osqrth-time/</a></p> <p>You can see in the comments of spoj that many people O(n) query is getting accepted. But mine is O(sqrt(n)) and is not accepted getting TLE.</p> <p>Please help me where i am doing wrong ?</p> <pre><code>#include&lt;bits/stdc++.h&gt; using namespace std; #define MAXN 2000 int block_sz; int depth[MAXN]; int parent[MAXN]; int jump_parent[MAXN]; int hmax; ///jump_parent is first ancestor ///of current node vector &lt;int&gt; adj[MAXN]; void addEdge(int u,int v){ adj[u].push_back(v); adj[v].push_back(u); } int lca_naive(int u,int v){ if(u==v){ return u; } if(depth[u]&gt;depth[v]) swap(u,v); v=parent[v]; return lca_naive(u,v); } // precalculating the required parameters // associated with every node void dfs(int cur,int prev){ depth[cur]=depth[prev]+1; parent[cur]=prev; //hmax=max(height,hmax); ///suppose if h=9,then sqrt(h)=3 ///in that case total blocks will be ///0 to 3-1 /// so rem will be zero for only first element in the current block if(depth[cur] % block_sz == 0){ jump_parent[cur]=parent[cur]; } else{ jump_parent[cur]=jump_parent[prev]; } for(int i=0;i&lt;adj[cur].size();i++){ if(adj[cur][i]!=prev){ dfs(adj[cur][i],cur); } } } int lcasqrt(int u,int v){ while(jump_parent[u]!=jump_parent[v]){ if(depth[u]&gt;depth[v]) swap(u,v); v=jump_parent[v]; } return lca_naive(u,v); } void preprocess(int height){ block_sz=sqrt(height); depth[0]=-1; dfs(1,0); } ///seperate dfs to calculate height void dfs_height(int cur,int prev,int height){ hmax=max(height,hmax); for(int i=0;i&lt;adj[cur].size();i++){ if(adj[cur][i]!=prev) dfs_height(adj[cur][i],cur,height+1); } } int main(int argc, char const *argv[]) { // adding edges to the tree int t; cin&gt;&gt;t; while(t--){ int n; cin&gt;&gt;n; for(int i=1;i&lt;=n;i++){ int m; cin&gt;&gt;m; for(int j=1;j&lt;=m;j++){ int v; cin&gt;&gt;v; adj[i].push_back(v); } } dfs_height(1,0,0); preprocess(hmax); dfs(1,0); int q; cin&gt;&gt;q; for(int i=0;i&lt;q;i++){ int u,v; cin&gt;&gt;u&gt;&gt;v; cout&lt;&lt;lcasqrt(u,v)&lt;&lt;endl; } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-17T11:27:33.980", "Id": "417112", "Score": "4", "body": "Welcome to Code Review! This question is incomplete. To help reviewers give you better answers, please add sufficient context to your question. The more you tell us about what your code does and what the purpose of doing that is, the easier it will be for reviewers to help you. [Questions should include a description of what the code does](//codereview.meta.stackexchange.com/q/1226)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-17T12:17:55.843", "Id": "417114", "Score": "0", "body": "For each test case print Q + 1 lines, The first line will have “Case C:” without quotes where C is the case number starting with 1" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-17T18:46:21.860", "Id": "417142", "Score": "0", "body": "`#include<bits/stdc++.h>` is bad habit." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-17T11:14:27.953", "Id": "215604", "Score": "2", "Tags": [ "c++", "algorithm", "time-limit-exceeded" ], "Title": "lowest common ancestor with square root decompostion" }
215604
<p>I just started learning programming a few months ago, and I'm intrigued by Haskell. To learn a bit I tried to adapt some code I have in Java so I can see what are equivalent solutions in Haskell.</p> <p>The problem I had was to see how many different numbers can be “represented” by a string of roman numbers (0, .., 9, where <code>X</code> is equivalent to zero).</p> <p>For example <code>"I"</code> means just one possible number (1), but <code>"II"</code> could be two possibilities: 11 (two <code>"I"</code>) or 2 (one <code>"II"</code>). This is from some competitive programming website. Similar <code>"XX"</code> should give 1, since it represents 00 only. A bit bigger example: <code>"IVII"</code> should give 6, because there are 6 possibilities:</p> <ul> <li><code>"I" + "V" + "I" + "I" = 1511</code></li> <li><code>"I" + "V" + "II" = 152</code></li> <li><code>"I" + "VI" + "I" = 161</code></li> <li><code>"IV" + "I" + "I" = 411</code></li> <li><code>"I" + "VII" = 17</code></li> <li><code>"IV" + "II" = 42</code></li> </ul> <p>Ok, that said, this is my Haskell code (first thing I write so far).</p> <pre><code>romanCombinations :: String -&gt; Int romanCombinations [] = 1 romanCombinations str = if length str == 1 then 1 else foldr (+) 0 [ romanCombinations xs | (x, xs) &lt;- sep , elem x possibles ] where sep = map (divide str) $ take (length str) [1..4] divide str n = (take n str, drop n str) possibles = ["X", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"] </code></pre> <p>What would you change in this Haskell code? I've never written anything before. Anything is welcome since I will probably learn from every comment. (I'm not asking about algorithms, but anything is welcome too)</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-17T19:15:20.053", "Id": "417144", "Score": "0", "body": "Welcome to Code Review. If you never written anything in Haskell before, you might want to add the [tag:beginner] tag to your question." } ]
[ { "body": "<h1>Use pattern matching to check for single-element lists</h1>\n\n<p>Let's start with <code>romamCombination</code>'s second pattern:</p>\n\n<pre><code>romanCombinations str = if length str == 1 then 1\n</code></pre>\n\n<p>Compared to Java, <code>length</code> isn't a constant time operation in Haskell. It will traverse the whole list. If we only want to know if a list consists of a single element, we should pattern match to get a constant time behaviour:</p>\n\n<pre><code>romanCombinations [_] = 1\n</code></pre>\n\n<h1>Use named variants of folds where applicable</h1>\n\n<p>Next, we will sum all elements in some list:</p>\n\n<pre><code> -- we have to change the else due to the new pattern, but more on that later\n else foldr (+) 0 [ romanCombinations xs | (x, xs) &lt;- sep , elem x possibles ]\n</code></pre>\n\n<p>However, <code>foldr (+) 0</code> is a common operation and therefore has a name in the <code>Prelude</code>: <code>sum</code>. We should use the named variant to convey our intend:</p>\n\n<pre><code> else sum [ romanCombinations xs | (x, xs) &lt;- sep , elem x possibles ]\n</code></pre>\n\n<p>Similarly, <code>divide</code> is already in the <code>Prelude</code>, it's called <code>splitAt</code>, although the arguments are flipped:</p>\n\n<pre><code> where\n divide str n = splitAt n str\n</code></pre>\n\n<h1>Use Hoogle to find functions</h1>\n\n<p>But how would we find those functions? With Hoogle. If we search for <a href=\"https://hoogle.haskell.org/?hoogle=Num%20a%20%3D%3E%20%5Ba%5D%20-%3E%20a&amp;scope=set%3Astackage\" rel=\"nofollow noreferrer\"><code>Num a =&gt; \\[a\\] -&gt; a</code></a>, we will come across <code>sum</code> very soon, and if we search for <a href=\"https://hoogle.haskell.org/?hoogle=[a]%20-%3E%20Int%20-%3E%20([a]%20%2C%20[a])\" rel=\"nofollow noreferrer\"><code>[a] -&gt; Int -&gt; ([a], [a])</code></a>, Hoogle will also find <code>splitAt</code>, even though the arguments are flipped.</p>\n\n<p>Note that you sometimes need to use more general type signatures to find something with Hoogle.</p>\n\n<h1>All together so far</h1>\n\n<p>If we apply all those recommendations, we end up with</p>\n\n<pre><code>romanCombinations :: String -&gt; Int\nromanCombinations [] = 1\nromanCombinations [_] = 1\nromanCombinations str = sum [ romanCombinations xs | (x, xs) &lt;- sep , elem x possibles ]\n where\n sep = map (`splitAt` str) $ take (length str) [1..4]\n possibles = [\"X\", \"I\", \"II\", \"III\", \"IV\", \"V\", \"VI\", \"VII\", \"VIII\", \"IX\"]\n</code></pre>\n\n<h1>Adjusting the length of a list by another list</h1>\n\n<p>We're already at the end. However, there is one last step we should take: get rid of the other <code>length</code>. That can be done with <code>zip</code> and <code>map</code>:</p>\n\n<pre><code>limit :: [a] -&gt; [b] -&gt; [b]\nlimit xs = map snd . zip xs\n</code></pre>\n\n<p>In case you're not familiar with pointfree-code, it's the same as</p>\n\n<pre><code>limit :: [a] -&gt; [b] -&gt; [b]\nlimit xs ys = map snd (zip xs ys)\n</code></pre>\n\n<p>As <code>zip</code> will end whenever the shorter list is exhausted, this will limit <code>str</code> to at most <code>4</code> elements in <code>[1..4]</code> and of course limit <code>[1..4]</code> to at most <code>length str</code>.</p>\n\n<p>We end up with</p>\n\n<pre><code>romanCombinations :: String -&gt; Int\nromanCombinations [] = 1\nromanCombinations [_] = 1\nromanCombinations str = sum [ romanCombinations xs | (x, xs) &lt;- sep , elem x possibles ]\n where\n sep = map (`splitAt` str) $ limit str [1..4]\n possibles = [\"X\", \"I\", \"II\", \"III\", \"IV\", \"V\", \"VI\", \"VII\", \"VIII\", \"IX\"]\n\nlimit :: [a] -&gt; [b] -&gt; [b]\nlimit xs = map snd . zip xs\n</code></pre>\n\n<h1>Bottom line</h1>\n\n<p>All in all, your original code was already easy to read, had type signatures and uses simple splitting algorithm one can easily infer from your code. That being said, I haven't checked your algorithm or thought about improvements but only checked the code.</p>\n\n<p>I recommend you to check the <a href=\"https://hackage.haskell.org/package/base-4.12.0.0/docs/Prelude.html\" rel=\"nofollow noreferrer\"><code>Prelude</code></a>, as <code>splitAt</code> and <code>sum</code> are already available for your use without any import. Also, try to avoid <code>length</code>. Either work with the list immediately (e.g. <code>map</code>, <code>fold</code>, <code>sum</code>, ...) or pattern match.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-18T08:36:41.983", "Id": "417226", "Score": "0", "body": "Thank you, very detailed, and lots of info." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-17T19:14:44.877", "Id": "215622", "ParentId": "215609", "Score": "3" } }, { "body": "<p><code>Data.List</code> saves us the number manipulation. The length-1 case reduces to the length-0 case.</p>\n\n<pre><code>romanCombinations :: String -&gt; Int\nromanCombinations [] = 1\nromanCombinations str =\n sum $ map romanCombinations $ mapMaybe (`splitPrefix` str) \n [\"X\", \"I\", \"II\", \"III\", \"IV\", \"V\", \"VI\", \"VII\", \"VIII\", \"IX\"]\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-19T02:03:56.930", "Id": "215715", "ParentId": "215609", "Score": "1" } } ]
{ "AcceptedAnswerId": "215622", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-17T12:40:57.767", "Id": "215609", "Score": "3", "Tags": [ "programming-challenge", "haskell", "combinatorics", "roman-numerals" ], "Title": "Number of possible numbers in roman number string" }
215609
<p>I found a couple of similar questions, but they were mostly outdated. Here's the problem: create a flat array from the values in several arrays contained in several nested objects. </p> <pre><code>const data = [ { id: 1, items: ['one', 'two', 'three'] }, { id: 2, items: ['two', 'one', 'four'] }, ] </code></pre> <p>Expected result <code>const result = ['one', 'two', 'three', 'four']</code></p> <p>My current solution:</p> <pre><code>function() { const result = [] data.forEach(item =&gt; data.items.forEach(item =&gt; result.push(item))) return _.uniq(result) } </code></pre> <p>lodash is allowed</p> <p>Any suggestion is more than welcome</p>
[]
[ { "body": "<p>Although at the time of writing, <code>flatMap</code> is not in every browser (according to MDN not in Edge and Samsung Internet);</p>\n\n<pre><code>data.flatMap(obj =&gt; obj.items).filter((e, i, ary) =&gt; ary.indexOf(e) == i)\n</code></pre>\n\n<p>Although, you could check the uniqueness from the result array in your code, and push only if not in there, to save one loop over the array.</p>\n\n<p>Another option would be a reducer like</p>\n\n<pre><code>uniqItems = (acc, {items}) =&gt; acc.concat(items.filter(item =&gt; acc.indexOf(item) &lt; 0))\n</code></pre>\n\n<p>to <code>data.reduce(uniqItems, [])</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-17T17:48:44.817", "Id": "215617", "ParentId": "215615", "Score": "1" } }, { "body": "<p>Use a <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set\" rel=\"nofollow noreferrer\">Set</a>, it will store unique items for you.</p>\n\n<p>You can convert the set to an array with <code>[...set.values()];</code></p>\n\n<p>Or as a set is iterateable there is no need to convert it to an array until needed if at all.</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const data = [{items: ['one', 'two', 'three'] },{items: ['two', 'one', 'four'] }];\n\n// Quickest solution\nfunction getUniqueA(arr) {\n const unique = new Set();\n for (const {items} of arr) {\n for (const item of items) { unique.add(item) }\n }\n return [...unique.values()];\n}\n\n// Smallest solution\nconst getUniqueB = arr =&gt; [...(new Set(arr.map(i =&gt; i.items).flat())).values()];\n \n// Returns the set\nconst getUniqueC = arr =&gt; new Set(arr.map(i =&gt; i.items).flat());\n \nconst resA = getUniqueA(data);\nconst resB = getUniqueB(data);\nconst resC = getUniqueC(data);\n\nlogArray(\"Result A: \", resA);\nlogArray(\"Result B: \", resB);\nlogArray(\"Result C: \", ...resC);\n\nfunction logArray(t, ...a) { console.log(t + `[${a}]`) }</code></pre>\r\n</div>\r\n</div>\r\n</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-18T00:13:23.377", "Id": "215639", "ParentId": "215615", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-17T16:44:32.377", "Id": "215615", "Score": "2", "Tags": [ "javascript", "ecmascript-6" ], "Title": "Optimized pulling items out of arrays in nested objects" }
215615
<p>I am trying to implement a bank account with Java in a thread safe way. My code looks like:</p> <pre><code>import java.math.BigDecimal; import java.math.RoundingMode; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; /** * Class to represent an account, it also provides with methods to add and withdraw amount from the account. * * @author Karan Khanna * @version 1.0 * @since 3/17/2019 */ public class Account { private ReadWriteLock accountLock; private BigDecimal balance; private String accountNumber; private String accountHolder; public Account(String accountNumber, String accountHolder) { this.balance = new BigDecimal(0); this.accountNumber = accountNumber; this.accountHolder = accountHolder; this.accountLock = new ReentrantReadWriteLock(); } public double getBalance() { this.accountLock.readLock().lock(); double balance = this.balance.setScale(2, RoundingMode.HALF_DOWN).doubleValue(); this.accountLock.readLock().unlock(); return balance; } public String getAccountNumber() { return accountNumber; } public String getAccountHolder() { return accountHolder; } public ReadWriteLock getAccountLock() { return accountLock; } public void addAmount(double amount) { this.accountLock.writeLock().lock(); this.balance.add(new BigDecimal(amount)); this.accountLock.writeLock().unlock(); } public void withdrawAmount(double amount) { this.accountLock.writeLock().lock(); this.balance.subtract(new BigDecimal(amount)); this.accountLock.writeLock().unlock(); } } </code></pre> <p>I am looking for feedback for the implementation.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-18T11:42:34.263", "Id": "417276", "Score": "0", "body": "FWIW, you can always implement `AutoCloseable` in your lock and do try-with-resources on your operations - IMVHO, that would make both the intention more obvious, the code would be shorter, and the risk of omitting the unlock (either as a typo or after throwing in method) would be mitigated. I dunno why Java doesn't provide this functionality as default..." } ]
[ { "body": "<p>In terms of the basic thread locking, it looks like it is doing the right thing, but there are a number of issues in how you are calculating the account balance, and also some escaped locking as well.</p>\n\n<p>Note, your post is titled \"Synchronized implementation\", but it is not, it is a locked implementation. Synchronization is different, and, in this case, it may be a simpler mechanism.</p>\n\n<h3>Locking</h3>\n\n<p>Even if you don't catch exceptions, you should always use the try/finally mechanism for locking. Here, for example, it's possible that the addition may throw an exception (even though you don't catch it):</p>\n\n<pre><code>public void addAmount(double amount) {\n this.accountLock.writeLock().lock();\n try {\n this.balance.add(new BigDecimal(amount));\n } finally {\n this.accountLock.writeLock().unlock();\n }\n}\n</code></pre>\n\n<p>In case you think that's extreme, well, the amount could be <code>NaN</code> or <code>infinity</code>, and that would throw a <code>NumberFormatException</code>, etc. Even if it were impossible for the logic to throw an error, you should still use the try/finally mechanism because it makes the logic obvious.</p>\n\n<p>The balance method has the most to gain:</p>\n\n<pre><code>public double getBalance() {\n this.accountLock.readLock().lock();\n try {\n return this.balance.setScale(2, RoundingMode.HALF_DOWN).doubleValue();\n } finally {\n this.accountLock.readLock().unlock();\n }\n}\n</code></pre>\n\n<p>You are also leaking the lock through the public method to get it. You really should not allow other people to manipulate the lock strategy you have in your class. It is intended to be internal for a reason.</p>\n\n<p>Speaking of that lock, you should also make it final... </p>\n\n<pre><code>private final ReadWriteLock accountLock;\n</code></pre>\n\n<h3>Bugs</h3>\n\n<p>The most glaring issue is not with your locking, but with the balance management itself. BigDecimals are immutable. They cannot be changed. This does nothing: <code>this.balance.add(new BigDecimal(amount));</code> .... that should be <code>this.balance = this.balance.add(new BigDecimal(amount));</code>.</p>\n\n<p>The <code>accountNumber</code> and <code>accountHolder</code> should be final as well.</p>\n\n<p>Finally, the getBalance method will not always return a 2-decimal double value. Not all values in binary floating-point are representable in decimal.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-17T17:52:10.223", "Id": "215618", "ParentId": "215616", "Score": "12" } }, { "body": "<p><code>double</code> is not a good choice to use for currency in Java. The better option is <code>BigDecimal</code> (which you are using for the internal balance, but not for the parameters passed to the <code>addAmount</code> and <code>withdrawAmount</code> methods). A better approach would be to make those methods take a <code>BigDecimal</code> parameter instead (and to use <code>BigDecimal</code> everywhere in your code that deals with currency amounts).</p>\n\n<p>If for some reason those methods <strong>need</strong> to take a <code>double</code> parameter then you should not convert it to a <code>BigDecimal</code> with the <code>new BigDecimal(double)</code> constructor - this will give an inaccurate conversion and an unexpected (and incorrect) value for the balance after the add/withdraw operation. For example, the following test fails:</p>\n\n<pre><code> @Test\n public void demonstrateBigDecimalRoundingErrorsFromDouble() {\n BigDecimal balance = BigDecimal.ZERO;\n balance = balance.add(new BigDecimal(0.1));\n assertThat(balance, is(new BigDecimal(\"0.1\")));\n }\n</code></pre>\n\n<p>with the error</p>\n\n<pre><code>java.lang.AssertionError: \nExpected: is &lt;0.1&gt;\n but: was &lt;0.1000000000000000055511151231257827021181583404541015625&gt;\n</code></pre>\n\n<p>The correct way to convert from a <code>double</code> to a <code>BigDecimal</code> is to use <code>BigDecimal.valueOf(double)</code>. For example, changing the middle line in the above test will make it pass:</p>\n\n<pre><code> @Test\n public void demonstrateBigDecimalRoundingErrorsFromDouble() {\n BigDecimal balance = BigDecimal.ZERO;\n balance = balance.add(BigDecimal.valueOf(0.1));\n assertThat(balance, is(new BigDecimal(\"0.1\")));\n }\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-18T02:56:56.910", "Id": "215642", "ParentId": "215616", "Score": "3" } } ]
{ "AcceptedAnswerId": "215618", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-17T17:34:13.283", "Id": "215616", "Score": "7", "Tags": [ "java", "multithreading", "thread-safety" ], "Title": "Synchronized implementation of a bank account in Java" }
215616
<p>I am aware that my VBA code can be improved.I would like to standardize and reduce repeating same procedures. Can I have some guide lines for this? Where to start? I would be glad to have some examples from you! I would like to learn to write code more efficiently. Also does this will improve efficiency too?</p> <pre><code>' Color_code ' Dim white, red, green, orange, peach, yellow, pink, blue, maroon, violet, black As Long white = RGB(255, 255, 255) 'White red = RGB(255, 0, 0) 'Red green = RGB(215, 228, 188) 'Green orange = RGB(228, 109, 10) 'Orange peach = RGB(242, 174, 92) 'Peach yellow = RGB(255, 255, 113) 'Yellow pink = RGB(255, 182, 193) 'Pink blue = RGB(147, 205, 221) 'Blue maroon = RGB(149, 55, 53) 'Maroon violet = RGB(204, 192, 218) 'Violet black = RGB(0, 0, 0) 'Black ws_kanban.Select Set shelf_card = ActiveSheet.Range("A1:E10") Set trav_card = ActiveSheet.Range("A12:G21") Set int_supp = ActiveSheet.Range("C17:E17") Set int_supp_loc = ActiveSheet.Range("C20:E20") Set section = ws_kanban_data.Range("G2") Set section2 = ActiveSheet.Range("G2:H2") Set warning = ActiveSheet.Range("G6") Set warning2 = ActiveSheet.Range("G7") Set issue_type = ActiveSheet.Range("F1:F10") Set issue_type_trav = ActiveSheet.Range("H12:H21") Set types = ws_kanban_data.Range("F2") section2.Select If section = "MECH" Then shelf_card.Interior.Color = green trav_card.Interior.Color = green ElseIf section = "LAB" Then shelf_card.Interior.Color = orange trav_card.Interior.Color = orange ElseIf section = "HOCC" Then shelf_card.Interior.Color = peach trav_card.Interior.Color = peach ElseIf section = "SASW" Then shelf_card.Interior.Color = yellow trav_card.Interior.Color = yellow ElseIf section = "SAMO" Then shelf_card.Interior.Color = pink trav_card.Interior.Color = pink ElseIf section = "RRC" Then shelf_card.Interior.Color = blue trav_card.Interior.Color = blue ElseIf section = "CUST" Then shelf_card.Interior.Color = maroon trav_card.Interior.Color = maroon ElseIf section = "PE" Then shelf_card.Interior.Color = red trav_card.Interior.Color = red ElseIf section = "PACK" Then shelf_card.Interior.Color = violet trav_card.Interior.Color = violet ElseIf section = "LC" Then shelf_card.Interior.Color = white trav_card.Interior.Color = white Else section2.Font.Color = white warning.Value = "Check Section!!" For i = 1 To 2 shelf_card.Interior.Color = red trav_card.Interior.Color = red warning.Interior.Color = red warning.Font.Color = white Application.Wait (Now + TimeValue("0:00:01")) shelf_card.Interior.Color = white trav_card.Interior.Color = white warning.Interior.Color = white warning.Font.Color = red Application.Wait (Now + TimeValue("0:00:01")) Next i warning.Font.Color = white warning.Interior.Color = red End If If types = "M" Then issue_type.Value = "Manual Issue " issue_type_trav.Value = "Manual Issue " issue_type.Interior.Color = black issue_type_trav.Interior.Color = black issue_type.Font.Color = white issue_type_trav.Font.Color = white ElseIf types = "B" Then issue_type.Interior.ColorIndex = 0 issue_type_trav.Interior.ColorIndex = 0 issue_type.Font.Color = white issue_type_trav.Interior.ColorIndex = 0 Else issue_type.Interior.ColorIndex = 0 issue_type_trav.Interior.ColorIndex = 0 issue_type.Font.Color = white issue_type_trav.Interior.ColorIndex = 0 warning2.Value = "Check Type!!" For i = 1 To 2 shelf_card.Interior.Color = red trav_card.Interior.Color = red warning2.Interior.Color = red warning2.Font.Color = white Application.Wait (Now + TimeValue("0:00:01")) shelf_card.Interior.Color = white trav_card.Interior.Color = white warning2.Interior.Color = white warning2.Font.Color = red Application.Wait (Now + TimeValue("0:00:01")) Next i warning2.Font.Color = white warning2.Interior.Color = red End If </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-18T09:44:23.413", "Id": "417237", "Score": "1", "body": "This question lacks any indication of what the code is intended to achieve. To help reviewers give you better answers, please add sufficient context to your question, including a title that summarises the *purpose* of the code. We want to know **why** much more than **how**. The more you tell us about [what your code is for](//meta.codereview.stackexchange.com/q/1226), the easier it will be for reviewers to help you. The title needs an [edit] to simply [**state the task**](//meta.codereview.stackexchange.com/q/2436)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-18T11:42:05.657", "Id": "417275", "Score": "0", "body": "It also doesn't appear to be a complete, functional subroutine of any sort - just a snippet or two from random places in code." } ]
[ { "body": "<p>If you're going to do any developing in VBA then you need to check out <a href=\"http://rubberduckvba.com/\" rel=\"nofollow noreferrer\">Rubberduck</a> . Open disclosure, I'm a contributor. I've used it for long enough now that the IDE doesn't feel complete without it. Rubberduck will help you write better code and teach you along the way with code inspections and other goodies.</p>\n\n<p><code>Dim white, red, ... , black as Long</code> is only having the last variable <code>black</code> actually declared <code>as Long</code>. The rest are implicitly <code>as Variant</code>. Something that Rubberduck will spot for you as part of its Code Inspections. If you declare several variables I advocate doing them each on their own line. You can avoid doing this by using enumeration values from <code>VBA.ColorConstants.vbWhite</code>, I mention this since this is available through the VBA. However, since you are using Excel you have access to <a href=\"https://docs.microsoft.com/en-us/office/vba/api/excel.xlrgbcolor\" rel=\"nofollow noreferrer\">XlRgbColor enumeration</a> and you can access as an unqualified <code>rgbWhite</code> , enumeration qualified <code>XlRgbColor.rgbWhite</code>, or fully qualified <code>Excel.XlRgbColor.rgbWhite</code> member. You'll have to map out what's closest to the colors you want. If that doesn't suffice you can create your own enumeration as I included in the example.</p>\n\n<pre><code>Private Enum MyEnumeration\n peach = 6074098 'rgb(242,174,92)\n '...\n violet = 14336204 'RGB(204, 192, 218)\nEnd Enum\n</code></pre>\n\n<p>I don't know if you have turned on <code>Option Explicit</code> as it wasn't included. In the VBA IDE menu at the top Tools>Options>Editor tab>Code Settings group>Require Variable Declaration should be turned on. This mandates you declare all your variables, <code>Dim foo as Bar</code>, before you can use them. It'll save you hours of hair pulling and needless typographical errors since implicit variables won't be created for you.</p>\n\n<p>To take those variable declarations a step further convert them to named ranges. This will eliminate static cell references that break when, not if, a cell is moved. You can enter a name by navigating through the Ribbon under the Formulas tab>Defined Names group>Name Manager or using either of the Hotkeys <kbd>Ctrl+F3</kbd>, <kbd>Alt, M, N</kbd>, or <kbd>Alt, I, N, D</kbd>. This will display the Name Manager dialog and from there you can add the named range. As a best practice don't forget when adding a named range in the New Name dialog to change the Scope dropdown to the specific sheet the range is on. Scoping a named range like this lets you add a getter property for the worksheet thy are one. These properties will look like</p>\n\n<pre><code>Public Property Get ShelfCard() As Range\n Set ShelfCard = Me.Range(\"ShelfCard\")\nEnd Property\n</code></pre>\n\n<p>So you can go from what you currently have</p>\n\n<pre><code>Set shelf_card = ActiveSheet.Range(\"A1:E10\")\n...\n shelf_card.Interior.Color = green\n...\n</code></pre>\n\n<p>to</p>\n\n<pre><code>KanBan.ShelfCard.Interior.Color = MyEnumeration.green\n</code></pre>\n\n<p>Avoid <code>Worksheet.Select</code> and <code>Activesheet.FooBar = ...</code> or the implicit <code>Range(\"A1\").FooBar = ...</code>. You rarely have to select worksheet to achieve something programatically. </p>\n\n<p>Next. Take all the <code>If ... ElseIf ... End If</code> and create a specific sub procedure for them. Something like <code>Private Sub UpdateBasedOnSection(ByVal sectionValue As String)</code> that encapsulates all the logic. This way when you call the sub it'll look something like <code>UpdateBasedOnSection KanBanData.Section2</code>. Hidden in this logic was a redundant <code>issue_type_trav.Interior.ColorIndex = 0</code>. When setting properties, group them so all the <code>KanBan.IssueType</code> properties are set, then move onto the next. Mixing them together makes it easy to miss these redundancies. There's also duplicated logic in the <code>For ... Next</code> block that should be refactored into its own sub.</p>\n\n<p>Once you've done this you'll have cleaned up the code. Below is what I ended up achieving. The entirety of your module ended up being contained in <code>CodeReview</code>. More can be done but this should is a good start for now.</p>\n\n<pre><code>'Module1 standard module\nOption Explicit\n\nPublic Enum MyEnumeration\n green = 12379351 'RGB(215,228,188)\n orange = 683492 'RGB(228,109,10)\n peach = 6074098 'rgb(242,174,92)\n yellow = 7471103 'RGB(255, 255, 113)\n pink = 12695295 'RGB(255, 182, 193)\n blue = 14536083 'RGB(147, 205, 221)\n maroon = 3487637 'RGB(149, 55, 53)\n violet = 14336204 'RGB(204, 192, 218)\nEnd Enum\n\nPublic Sub CodeReview()\n UpdateBasedOnSection KanBan.Section2\n UpdateBasedOnTypes KanBanData.Types\nEnd Sub\n\nPrivate Sub UpdateBasedOnSection(ByVal sectionValue As String)\n Dim updateColor As Long\n If ShouldSectionColorBeUpdated(sectionValue, updateColor) Then\n KanBan.ShelfCard.Interior.Color = updateColor\n KanBan.TravelCard.Interior.Color = updateColor\n Else\n KanBan.Section2.Font.Color = XlRgbColor.rgbWhite\n KanBan.Warning.Value2 = \"Check Section!!\"\n WarningFlash KanBan.Warning\n End If\nEnd Sub\n\nPrivate Function ShouldSectionColorBeUpdated(ByVal sectionValue As String, ByRef outSectionColor As Long) As Boolean\n ShouldSectionColorBeUpdated = True\n Select Case sectionValue\n Case \"MECH\"\n outSectionColor = MyEnumeration.green\n Case \"LAB\"\n outSectionColor = MyEnumeration.orange\n Case \"HOCC\"\n outSectionColor = MyEnumeration.peach\n Case \"SASW\"\n outSectionColor = MyEnumeration.yellow\n Case \"SAMO\"\n outSectionColor = MyEnumeration.pink\n Case \"RRC\"\n outSectionColor = MyEnumeration.blue\n Case \"CUST\"\n outSectionColor = MyEnumeration.maroon\n Case \"PE\"\n outSectionColor = XlRgbColor.rgbRed\n Case \"PACK\"\n outSectionColor = MyEnumeration.violet\n Case \"LC\"\n outSectionColor = XlRgbColor.rgbWhite\n Case Else\n outSectionColor = -1\n ShouldSectionColorBeUpdated = False\n End Select\nEnd Function\n\nPrivate Sub UpdateBasedOnTypes(ByVal Types As String)\n If Types = \"M\" Then\n With KanBan.IssueType\n .Value2 = \"Manual Issue \"\n .IssueType.Interior.Color = XlRgbColor.rgbBlack\n .IssueType.Font.Color = XlRgbColor.rgbWhite\n End With\n\n With KanBan.IssueTypeTravel\n .Value2 = \"Manual Issue \"\n .Interior.Color = XlRgbColor.rgbBlack\n .Font.Color = XlRgbColor.rgbWhite\n End With\n Else\n KanBan.IssueType.Interior.ColorIndex = 0\n KanBan.IssueType.Font.Color = XlRgbColor.rgbWhite\n KanBan.IssueTypeTravel.Interior.ColorIndex = 0\n\n If Types &lt;&gt; \"B\" Then\n KanBan.Warning2.Value2 = \"Check Type!!\"\n WarningFlash KanBan.Warning2\n End If\n End If\nEnd Sub\n\nPrivate Sub WarningFlash(ByVal warningCell As Range)\n Const OneSecond As Double = #12:00:01 AM#\n Dim i As Long\n For i = 1 To 2\n KanBan.ShelfCard.Interior.Color = XlRgbColor.rgbRed\n KanBan.TravelCard.Interior.Color = XlRgbColor.rgbRed\n warningCell.Interior.Color = XlRgbColor.rgbRed\n warningCell.Font.Color = XlRgbColor.rgbWhite\n Application.Wait Now + OneSecond\n KanBan.ShelfCard.Interior.Color = XlRgbColor.rgbWhite\n KanBan.TravelCard.Interior.Color = XlRgbColor.rgbWhite\n warningCell.Interior.Color = XlRgbColor.rgbWhite\n warningCell.Font.Color = XlRgbColor.rgbRed\n Application.Wait Now + OneSecond\n Next i\n warningCell.Font.Color = XlRgbColor.rgbWhite\n warningCell.Interior.Color = XlRgbColor.rgbRed\nEnd Sub\n</code></pre>\n\n<pre><code>'KanBan worksheet\nOption Explicit\n\nPublic Property Get ShelfCard() As Range\n Set ShelfCard = Me.Range(\"ShelfCard\")\nEnd Property\n\nPublic Property Get TravelCard() As Range\n Set TravelCard = Me.Range(\"TravelCard\")\nEnd Property\n\nPublic Property Get InternalSupport() As Range\n Set InternalSupport = Me.Range(\"InternalSupport\")\nEnd Property\n\nPublic Property Get InternalSupportLocation() As Range\n Set InternalSupportLocation = Me.Range(\"InternalSupportLocation\")\nEnd Property\n\nPublic Property Get Section2() As Range 'Use a better more descriptive name\n Set Section2 = Me.Range(\"Section2\")\nEnd Property\n\nPublic Property Get Warning() As Range 'Advocate changing to what the warning actually is about\n Set Warning = Me.Range(\"Warning\")\nEnd Property\n\nPublic Property Get Warning2() As Range\n Set Warning2 = Me.Range(\"Warning2\")\nEnd Property\n\nPublic Property Get IssueType() As Range\n Set IssueType = Me.Range(\"IssueType\")\nEnd Property\n\nPublic Property Get IssueTypeTravel() As Range\n Set IssueTypeTravel = Me.Range(\"IssueTypeTravel\")\nEnd Property\n</code></pre>\n\n<pre><code>'KanBanData worksheet\nOption Explicit\n\nPublic Property Get Types() As String\n Types = Me.Range(\"Types\").Value2\nEnd Property\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-18T05:24:45.037", "Id": "417211", "Score": "0", "body": "Thanks for your help. Its a great start for me! I will go trough your reviews and fix while learning!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-17T23:19:16.847", "Id": "215635", "ParentId": "215623", "Score": "4" } } ]
{ "AcceptedAnswerId": "215635", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-17T19:16:20.283", "Id": "215623", "Score": "-1", "Tags": [ "vba", "excel" ], "Title": "Standardize and reduce repeating same procedures in my coding Excel VBA" }
215623
<p>I've created the following code to try and find the optimum "diet" from a game called Eco. The maximum amount of calories you can have is 3000, as shown with MAXCALORIES. </p> <p>Is there any way to make this code faster, since the time predicted for this code to compute 3000 calories is well over a few hundred years.</p> <p>Note: I am trying to find the highest SP (skill points) you get from a diet, the optimum diet. To find this, I must go through every combination of diets and check how many skill points you receive through using it. The <strong>order of food does not matter</strong>, and I feel this is something that is slowing this program down.</p> <pre><code>import itertools import sys import time sys.setrecursionlimit(10000000) #["Name/Carbs/Protein/Fat/Vitamins/Calories"] available = ['Fiddleheads/3/1/0/3/80', 'Fireweed Shoots/3/0/0/4/150', 'Prickly Pear Fruit/2/1/1/3/190', 'Huckleberries/2/0/0/6/80', 'Rice/7/1/0/0/90', 'Camas Bulb/1/2/5/0/120', 'Beans/1/4/3/0/120', 'Wheat/6/2/0/0/130', 'Crimini Mushrooms/3/3/1/1/200', 'Corn/5/2/0/1/230', 'Beet/3/1/1/3/230', 'Tomato/4/1/0/3/240', 'Raw Fish/0/3/7/0/200', 'Raw Meat/0/7/3/0/250', 'Tallow/0/0/8/0/200', 'Scrap Meat/0/5/5/0/50', 'Prepared Meat/0/4/6/0/600', 'Raw Roast/0/6/5/0/800', 'Raw Sausage/0/4/8/0/500', 'Raw Bacon/0/3/9/0/600', 'Prime Cut/0/9/4/0/600', 'Cereal Germ/5/0/7/3/20', 'Bean Paste/3/5/7/0/40', 'Flour/15/0/0/0/50', 'Sugar/15/0/0/0/50', 'Camas Paste/3/2/10/0/60', 'Cornmeal/9/3/3/0/60', 'Huckleberry Extract/0/0/0/15/60', 'Yeast/0/8/0/7/60', 'Oil/0/0/15/0/120', 'Infused Oil/0/0/12/3/120', 'Simple Syrup/12/0/3/0/400', 'Rice Sludge/10/1/0/2/450', 'Charred Beet/3/0/3/7/470', 'Camas Mash/1/2/9/1/500', 'Campfire Beans/1/9/3/0/500', 'Wilted Fiddleheads/4/1/0/8/500', 'Boiled Shoots/3/0/1/9/510', 'Charred Camas Bulb/2/3/7/1/510', 'Charred Tomato/8/1/0/4/510', 'Charred Corn/8/1/0/4/530', 'Charred Fish/0/9/4/0/550', 'Charred Meat/0/10/10/0/550', 'Wheat Porridge/10/4/0/10/510', 'Charred Sausage/0/11/15/0/500', 'Fried Tomatoes/12/3/9/2/560', 'Bannock/15/3/8/0/600', 'Fiddlehead Salad/6/6/0/14/970', 'Campfire Roast/0/16/12/0/1000', 'Campfire Stew/5/12/9/4/1200', 'Wild Stew/8/5/5/12/1200', 'Fruit Salad/8/2/2/10/900', 'Meat Stock/5/8/9/3/700', 'Vegetable Stock/11/1/2/11/700', 'Camas Bulb Bake/12/7/5/4/400', 'Flatbread/17/8/3/0/500', 'Huckleberry Muffin/10/5/4/11/450', 'Baked Meat/0/13/17/0/600', 'Baked Roast/4/13/8/7/900', 'Huckleberry Pie/9/5/4/16/1300', 'Meat Pie/7/11/11/5/1300', 'Basic Salad/13/6/6/13/800', 'Simmered Meat/6/18/13/5/900', 'Vegetable Medley/9/5/8/20/900', 'Vegetable Soup/12/4/7/19/1200', 'Crispy Bacon/0/18/26/0/600', 'Stuffed Turkey/9/16/12/7/1500'] global AllSP, AllNames AllSP = [] AllNames = [] def findcombs(totalNames, totalCarbs, totalProtein, totalFat, totalVitamins, totalNutrients, totalCalories, MAXCALORIES): doneit = False for each in available: each = each.split("/") name = each[0] carbs = float(each[1]) protein = float(each[2]) fat = float(each[3]) vitamins = float(each[4]) nutrients = carbs+protein+fat+vitamins calories = float(each[5]) # print(totalNames, totalCalories, calories, each) if sum(totalCalories)+calories &lt;= MAXCALORIES: doneit = True totalNames2 = totalNames[::] totalCarbs2 = totalCarbs[::] totalProtein2 = totalProtein[::] totalFat2 = totalFat[::] totalVitamins2 = totalVitamins[::] totalCalories2 = totalCalories[::] totalNutrients2 = totalNutrients[::] totalNames2.append(name) totalCarbs2.append(carbs) totalProtein2.append(protein) totalFat2.append(fat) totalVitamins2.append(vitamins) totalCalories2.append(calories) totalNutrients2.append(nutrients) # print(" ", totalNames2, totalCarbs2, totalProtein2, totalFat2, totalVitamins2, totalNutrients2, totalCalories2) findcombs(totalNames2, totalCarbs2, totalProtein2, totalFat2, totalVitamins2, totalNutrients2, totalCalories2, MAXCALORIES) else: #find SP try: carbs = sum([x * y for x, y in zip(totalCalories, totalCarbs)]) / sum(totalCalories) protein = sum([x * y for x, y in zip(totalCalories, totalProtein)]) / sum(totalCalories) fat = sum([x * y for x, y in zip(totalCalories, totalFat)]) / sum(totalCalories) vitamins = sum([x * y for x, y in zip(totalCalories, totalVitamins)]) / sum(totalCalories) balance = (carbs+protein+fat+vitamins)/(2*max([carbs,protein,fat,vitamins])) thisSP = sum([x * y for x, y in zip(totalCalories, totalNutrients)]) / sum(totalCalories) * balance + 12 except: thisSP = 0 #add SP and names to two lists AllSP.append(thisSP) AllNames.append(totalNames) def main(MAXCALORIES): findcombs([], [], [], [], [], [], [], MAXCALORIES) index = AllSP.index(max(AllSP)) print() print(AllSP[index], " ", AllNames[index]) for i in range(100, 3000, 10): start = time.time() main(i) print("Calories:", i, "&gt;&gt;&gt; Time:", time.time()-start) </code></pre> <hr> <p><strong>Edit:</strong> On request, here is the formula for calculating the <span class="math-container">\$\text{SP} :\$</span></p> <p><span class="math-container">$$ \begin{align} \text{Carbs} &amp; {~=~} \frac{\text{amount}_1 \times \text{calories}_1 \times \text{carbs}_1 + \cdots}{\text{amount}_1 \times \text{calories}_1 + \cdots} \\[5px] \text{SP} &amp; {~=~} \frac{N_1 C_1 + N_2 C_2}{C_1 + C_2} \times \text{Balance} + \text{Base Gain} \end{align} $$</span> where:</p> <ul> <li><p><span class="math-container">\$N\$</span> is the nutrients of the food (carbs+protein+fat+vitamins);</p></li> <li><p><span class="math-container">\$C\$</span> is the calories of the food;</p></li> <li><p><span class="math-container">\$\text{Base Gain} = 12\$</span> (in all cases);</p></li> <li><p><span class="math-container">\$\text{Balance} = \frac{\text{Sum Nutrients}}{2 \times \text{highest nutrition}} .\$</span></p></li> </ul>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-17T20:11:32.527", "Id": "417153", "Score": "1", "body": "I didn't even know you could set the recursion limit to be so huge... :O Yeah keeping it at 1000 forces you to write safer code btw :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-17T20:12:34.400", "Id": "417154", "Score": "0", "body": "Good point, when you set it that high it usually means the code is very inefficient! :P @Peilonrayz" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-17T20:52:39.730", "Id": "417161", "Score": "0", "body": "Let's try to be more specific about your constraints. You need to select between 1 and *n* foods so long as the calorie count is smaller than or equal to 3000? This doesn't need recursion if you use Python's built-in `itertools.combinations`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-17T20:54:12.367", "Id": "417164", "Score": "0", "body": "Can you edit your question to describe the exact mathematical relationship between a set of foods and their computed `thisSP` value?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-17T20:57:54.373", "Id": "417166", "Score": "0", "body": "(3000 calories is about 12.5 kJ. The FAO puts the energy needed per day by a young 55 kg woman at about 10 MJ, a 68 kg man about 13 MJ.)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-17T20:58:20.050", "Id": "417167", "Score": "0", "body": "@Reinderien I have added the formulas for SP" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-17T20:58:39.470", "Id": "417168", "Score": "2", "body": "@greybeard These values are all for a game called \"Eco\", not for real life!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-17T23:14:36.093", "Id": "417178", "Score": "0", "body": "Can you provide the source for finding 'balance'? [I found the rest of the equation however](https://eco.gamepedia.com/Skill_Points#Nutrition_SP_Bonus)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-17T23:16:34.417", "Id": "417179", "Score": "0", "body": "@Peilonrayz It's on a Reddit post, not sure if I'll be able to find it. I've tested everything myself and it all works, if that's your concern." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-17T23:19:39.157", "Id": "417180", "Score": "0", "body": "@RulerOfTheWorld I find your description to not be well-defined and so having another source for an explanation should clear up the ambiguity." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-17T23:31:53.353", "Id": "417181", "Score": "0", "body": "@Peilonrayz What would you like me to clear up? Let me know and I can explain" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-17T23:33:55.797", "Id": "417182", "Score": "0", "body": "What is \"Sum Nutrients\" is it `sum(f.nutrients for f in foods)` as the name describes, or is it something else?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-17T23:36:44.660", "Id": "417183", "Score": "0", "body": "It means the amount of carbs calculated (carbs = ...) + The protein calculated + fat calculated + vitamins calculated. I'm note sure if this is clear from how I have written the balance to be in my original code" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-17T23:40:24.733", "Id": "417185", "Score": "0", "body": "@RulerOfTheWorld am I correct in assuming that you are assuming you have an unlimited amount of every food? That is, if the best outcome is eating 37 Fiddleheads, that's okay so long as the result maximizes the SP equation?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-17T23:40:53.433", "Id": "417186", "Score": "0", "body": "@AustinHastings That's correct" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-18T11:46:09.253", "Id": "417277", "Score": "1", "body": "OOh, it's the knapsac problem! You're probably better off trying for a \"good enough\" solution." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-18T17:03:33.193", "Id": "417333", "Score": "0", "body": "Given the already-extensive comments on this question, let's please continue to discuss it at https://chat.stackexchange.com/rooms/91219/optimising-a-list-searching-algorithm - I have more questions." } ]
[ { "body": "<h2>Data representation</h2>\n\n<p>Your choice of data representation is curious. It's a middle ground between a fully-serialized text format and a fully-deserialized in-memory format (such as nested tuples or dictionaries). I'd offer that it's not as good as either of the above. If you're going for micro-optimization, you need to do \"pre-deserialized\" literal variable initialization that doesn't require parsing at all. The best option would probably be named tuples or even plain tuples, i.e.</p>\n\n<pre><code>available = (\n ('Fiddleheads', 3, 1, 0, 3, 80),\n # ...\n)\n</code></pre>\n\n<p>But this won't yield any noticeable benefit, and it's not as maintainable as the alternative: just write a CSV file.</p>\n\n<h2>main isn't main</h2>\n\n<p>You've written a <code>main</code> function that isn't actually top-level code. This is not advisable. Rename it to something else, and put your top-level code in an <em>actual</em> main function, called from global scope with a standard <code>if __name__ == '__main__'</code> check.</p>\n\n<h2>list duplication</h2>\n\n<p>This:</p>\n\n<pre><code>totalNames[::]\n</code></pre>\n\n<p>should simply be</p>\n\n<pre><code>list(totalNames)\n</code></pre>\n\n<h2>snake_case</h2>\n\n<p>Your names should follow the format <code>total_names</code>, rather than <code>totalNames</code>.</p>\n\n<p>Also, variables in global scope (i.e. <code>AllSP</code>) should be all-caps; and you shouldn't need to declare them <code>global</code>.</p>\n\n<h2>Suggested</h2>\n\n<p>This doesn't at all tackle the main issue of algorithmic complexity, only Python usage. It isn't a good implementation, it's just to illustrate some stylistic improvements.</p>\n\n<p>Note a few things:</p>\n\n<ul>\n<li>Having a shebang at the top is very important to indicate to the shell and other programmers what's being executed</li>\n<li>Use csv</li>\n<li>Use tuple unpacking in your loops where possible</li>\n<li>Abbreviate the formation of new lists by doing appends inline</li>\n<li>Never <code>except:</code>; at a minimum <code>except Exception:</code> although even this should be more specific</li>\n<li>Use f-strings where appropriate</li>\n<li>Drop inner lists in list comprehensions when you don't need them</li>\n</ul>\n\n<p><em>foods.csv</em></p>\n\n<pre><code>name,carbs,protein,fat,vitamins,calories\nFiddleheads,3,1,0,3,80\nFireweed Shoots,3,0,0,4,150\nPrickly Pear Fruit,2,1,1,3,190\nHuckleberries,2,0,0,6,80\nRice,7,1,0,0,90\nCamas Bulb,1,2,5,0,120\nBeans,1,4,3,0,120\nWheat,6,2,0,0,130\nCrimini Mushrooms,3,3,1,1,200\nCorn,5,2,0,1,230\nBeet,3,1,1,3,230\nTomato,4,1,0,3,240\nRaw Fish,0,3,7,0,200\nRaw Meat,0,7,3,0,250\nTallow,0,0,8,0,200\nScrap Meat,0,5,5,0,50\nPrepared Meat,0,4,6,0,600\nRaw Roast,0,6,5,0,800\nRaw Sausage,0,4,8,0,500\nRaw Bacon,0,3,9,0,600\nPrime Cut,0,9,4,0,600\nCereal Germ,5,0,7,3,20\nBean Paste,3,5,7,0,40\nFlour,15,0,0,0,50\nSugar,15,0,0,0,50\nCamas Paste,3,2,10,0,60\nCornmeal,9,3,3,0,60\nHuckleberry Extract,0,0,0,15,60\nYeast,0,8,0,7,60\nOil,0,0,15,0,120\nInfused Oil,0,0,12,3,120\nSimple Syrup,12,0,3,0,400\nRice Sludge,10,1,0,2,450\nCharred Beet,3,0,3,7,470\nCamas Mash,1,2,9,1,500\nCampfire Beans,1,9,3,0,500\nWilted Fiddleheads,4,1,0,8,500\nBoiled Shoots,3,0,1,9,510\nCharred Camas Bulb,2,3,7,1,510\nCharred Tomato,8,1,0,4,510\nCharred Corn,8,1,0,4,530\nCharred Fish,0,9,4,0,550\nCharred Meat,0,10,10,0,550\nWheat Porridge,10,4,0,10,510\nCharred Sausage,0,11,15,0,500\nFried Tomatoes,12,3,9,2,560\nBannock,15,3,8,0,600\nFiddlehead Salad,6,6,0,14,970\nCampfire Roast,0,16,12,0,1000\nCampfire Stew,5,12,9,4,1200\nWild Stew,8,5,5,12,1200\nFruit Salad,8,2,2,10,900\nMeat Stock,5,8,9,3,700\nVegetable Stock,11,1,2,11,700\nCamas Bulb Bake,12,7,5,4,400\nFlatbread,17,8,3,0,500\nHuckleberry Muffin,10,5,4,11,450\nBaked Meat,0,13,17,0,600\nBaked Roast,4,13,8,7,900\nHuckleberry Pie,9,5,4,16,1300\nMeat Pie,7,11,11,5,1300\nBasic Salad,13,6,6,13,800\nSimmered Meat,6,18,13,5,900\nVegetable Medley,9,5,8,20,900\nVegetable Soup,12,4,7,19,1200\nCrispy Bacon,0,18,26,0,600\nStuffed Turkey,9,16,12,7,1500\n</code></pre>\n\n<p><em>Python</em></p>\n\n<pre><code>#!/usr/bin/env python3\n\nimport csv\nfrom time import time\n\nALL_SP = []\nALL_NAMES = []\n\n\ndef read(fn):\n with open('foods.csv') as f:\n reader = csv.reader(f, newline='')\n next(reader) # ignore title\n return tuple(\n (name, float(carbs), float(protein), float(fat), float(vitamins), float(calories))\n for name, carbs, protein, fat, vitamins, calories in reader\n )\n\n\nAVAILABLE = read('foods.csv')\n\n\ndef find_combs(total_names, total_carbs, total_protein, total_fat, total_vitamins, total_nutrients,\n total_calories, max_calories):\n for name, carbs, protein, fat, vitamins, calories in AVAILABLE:\n nutrients = carbs+protein+fat+vitamins\n\n if sum(total_calories) + calories &lt;= max_calories:\n find_combs(total_names + [name],\n total_carbs + [carbs],\n total_protein + [protein],\n total_fat + [fat],\n total_vitamins + [vitamins],\n total_nutrients + [nutrients],\n total_calories + [calories],\n max_calories)\n else:\n # find SP\n try:\n carbs = sum(x * y for x, y in zip(total_calories, total_carbs)) / sum(total_calories)\n protein = sum(x * y for x, y in zip(total_calories, total_protein)) / sum(total_calories)\n fat = sum(x * y for x, y in zip(total_calories, total_fat)) / sum(total_calories)\n vitamins = sum(x * y for x, y in zip(total_calories, total_vitamins)) / sum(total_calories)\n balance = (carbs+protein+fat+vitamins)/(2*max(carbs,protein,fat,vitamins))\n thisSP = sum(x * y for x, y in zip(total_calories, total_nutrients)) / sum(total_calories) * balance + 12\n except Exception:\n thisSP = 0\n\n # add SP and names to two lists\n ALL_SP.append(thisSP)\n ALL_NAMES.append(total_names)\n\n\ndef calc(max_calories):\n find_combs([], [], [], [], [], [], [], max_calories)\n index = ALL_SP.index(max(ALL_SP))\n print()\n print(f'{ALL_SP[index]:.2f} {ALL_NAMES[index]}')\n\n\ndef main():\n for i in range(100, 3000, 10):\n start = time()\n calc(i)\n print(f'Calories: {i} &gt;&gt;&gt; Time: {time()-start:.3f}')\n\n\nif __name__ == '__main__':\n main()\n</code></pre>\n\n<p>I'm going to do some reading and see what you're doing in terms of algorithm and submit a second answer to suggest a saner one.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-17T20:10:56.270", "Id": "417152", "Score": "0", "body": "Wow, thanks a lot! I'll edit my code following your advice now. Let me know if you find a way to optimise the algorithm!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-17T21:03:42.447", "Id": "417171", "Score": "3", "body": "@RulerOfTheWorld Please [do not edit the code in your question once reviewing started](https://codereview.stackexchange.com/help/someone-answers)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-17T21:11:20.683", "Id": "417173", "Score": "0", "body": "@greybeard Of course, my apologies. I was not editing the code, but explaining the functions behind it in a section marked as an edit at the end of my post, so it wouldn't affect the previous code." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-17T20:08:56.267", "Id": "215628", "ParentId": "215626", "Score": "10" } }, { "body": "<h1>Readability is #1</h1>\n\n<ol>\n<li><p>Global variables are bad. Don’t use them. I have to spend a long while looking at your code to tell what uses them and when. When your code becomes hundreds of lines long this is tedious and unmaintainable.</p>\n\n<p>If you need to use recursion and add to something not in the recursive function use a closure.</p></li>\n<li><p>You should load <code>available</code> into an object, rather than extract the information from it each and every time you use it.</p></li>\n<li><p>Using the above you can simplify all your <code>totalNames</code>, <code>totalCarbs</code> into one list.</p></li>\n<li><p>Rather than using <code>AllSP</code> and <code>AllNames</code> you can add a tuple to one list.</p></li>\n<li><p>You should put all your code into a <code>main</code> so that you reduce the amount of variables in the global scope. This goes hand in hand with (1).</p></li>\n<li><p>Rather than copying and pasting the same line multiple times you can create a function.</p></li>\n</ol>\n\n<p>All this gets the following. Which should be easier for you to increase the performance from:</p>\n\n<pre><code>import collections\nimport sys\nimport time\n\nsys.setrecursionlimit(10000000)\n\n_Food = collections.namedtuple('Food', 'name carbs protein fat vitamins calories')\n\n\nclass Food(_Food):\n @property\n def nutrients(self):\n return sum(self[1:5])\n\n\ndef read_foods(foods):\n for food in foods:\n name, *other = food.split('/')\n yield Food(name, *[float(v) for v in other])\n\n\ndef tot_avg(food, attr):\n return (\n sum(f.calories * getattr(f, attr) for f in food)\n / sum(f.calories for f in food)\n )\n\n\ndef find_sp(total):\n try:\n nutrients = [\n tot_avg(total, 'carbs'),\n tot_avg(total, 'protein'),\n tot_avg(total, 'fat'),\n tot_avg(total, 'vitamins')\n ]\n balance = sum(nutrients) / 2 / max(nutrients)\n except ZeroDivisionError:\n return None\n return tot_avg(total, 'nutrients') * balance + 12\n\n\ndef find_combs(available, MAXCALORIES):\n all_combinations = []\n\n def inner(total):\n for food in available:\n total_calories = [f.calories for f in total]\n if sum(total_calories) + food.calories &lt;= MAXCALORIES:\n inner(total[:] + [food])\n else:\n sp = find_sp(total)\n if sp is not None:\n all_combinations.append((sp, total))\n\n inner([])\n return max(all_combinations, key=lambda i: i[0])\n\n\ndef main(available):\n for MAXCALORIES in range(100, 3000, 10):\n start = time.time()\n all_ = find_combs(available, MAXCALORIES)\n amount, foods = max(all_, key=lambda i: i[0])\n print(amount, ' ', [f.name for f in foods])\n print('Calories:', amount, '&gt;&gt;&gt; Time:', time.time()-start)\n\n\nif __name__ == '__main__':\n available = ['Fiddleheads/3/1/0/3/80', 'Fireweed Shoots/3/0/0/4/150', 'Prickly Pear Fruit/2/1/1/3/190', 'Huckleberries/2/0/0/6/80', 'Rice/7/1/0/0/90', 'Camas Bulb/1/2/5/0/120', 'Beans/1/4/3/0/120', 'Wheat/6/2/0/0/130', 'Crimini Mushrooms/3/3/1/1/200', 'Corn/5/2/0/1/230', 'Beet/3/1/1/3/230', 'Tomato/4/1/0/3/240', 'Raw Fish/0/3/7/0/200', 'Raw Meat/0/7/3/0/250', 'Tallow/0/0/8/0/200', 'Scrap Meat/0/5/5/0/50', 'Prepared Meat/0/4/6/0/600', 'Raw Roast/0/6/5/0/800', 'Raw Sausage/0/4/8/0/500', 'Raw Bacon/0/3/9/0/600', 'Prime Cut/0/9/4/0/600', 'Cereal Germ/5/0/7/3/20', 'Bean Paste/3/5/7/0/40', 'Flour/15/0/0/0/50', 'Sugar/15/0/0/0/50', 'Camas Paste/3/2/10/0/60', 'Cornmeal/9/3/3/0/60', 'Huckleberry Extract/0/0/0/15/60', 'Yeast/0/8/0/7/60', 'Oil/0/0/15/0/120', 'Infused Oil/0/0/12/3/120', 'Simple Syrup/12/0/3/0/400', 'Rice Sludge/10/1/0/2/450', 'Charred Beet/3/0/3/7/470', 'Camas Mash/1/2/9/1/500', 'Campfire Beans/1/9/3/0/500', 'Wilted Fiddleheads/4/1/0/8/500', 'Boiled Shoots/3/0/1/9/510', 'Charred Camas Bulb/2/3/7/1/510', 'Charred Tomato/8/1/0/4/510', 'Charred Corn/8/1/0/4/530', 'Charred Fish/0/9/4/0/550', 'Charred Meat/0/10/10/0/550', 'Wheat Porridge/10/4/0/10/510', 'Charred Sausage/0/11/15/0/500', 'Fried Tomatoes/12/3/9/2/560', 'Bannock/15/3/8/0/600', 'Fiddlehead Salad/6/6/0/14/970', 'Campfire Roast/0/16/12/0/1000', 'Campfire Stew/5/12/9/4/1200', 'Wild Stew/8/5/5/12/1200', 'Fruit Salad/8/2/2/10/900', 'Meat Stock/5/8/9/3/700', 'Vegetable Stock/11/1/2/11/700', 'Camas Bulb Bake/12/7/5/4/400', 'Flatbread/17/8/3/0/500', 'Huckleberry Muffin/10/5/4/11/450', 'Baked Meat/0/13/17/0/600', 'Baked Roast/4/13/8/7/900', 'Huckleberry Pie/9/5/4/16/1300', 'Meat Pie/7/11/11/5/1300', 'Basic Salad/13/6/6/13/800', 'Simmered Meat/6/18/13/5/900', 'Vegetable Medley/9/5/8/20/900', 'Vegetable Soup/12/4/7/19/1200', 'Crispy Bacon/0/18/26/0/600', 'Stuffed Turkey/9/16/12/7/1500']\n main(list(read_foods(available)))\n</code></pre>\n\n<h1>I want speed and I want it now!</h1>\n\n<p>To speed up your program you can return early. Knowing <code>if sum(total_calories) + food.calories &lt;= MAXCALORIES:</code> then you should return if the inverse is true when <code>food</code> is the food with the lowest amount of calories.</p>\n\n<pre><code>def find_combs(available, MAXCALORIES):\n all_combinations = []\n min_calories = min(a.calories for a in available)\n\n def inner(total):\n if sum(f.calories for f in total) + min_calories &gt; MAXCALORIES:\n sp = find_sp(total)\n if sp is not None:\n all_combinations.append((sp, total))\n else:\n for food in available:\n total_calories = [f.calories for f in total]\n if sum(total_calories) + food.calories &lt;= MAXCALORIES:\n inner(total[:] + [food])\n\n inner([])\n return max(all_combinations, key=lambda i: i[0])\n</code></pre>\n\n<p>I added another function that performs naive memoization via an LRU cache with an unbound size. However it seemed to slow the process.<br>\nThe function that runs in roughly linear time is described below.</p>\n\n<p><img src=\"https://raw.githubusercontent.com/Peilonrayz/Stack-Exchange-contributions/master/code-review/215626/static/figs/all_plots.svg?sanitize=true\" alt=\"image\"></p>\n\n<p>Lets extrapolate these results. Your solution looks fairly linear, and so given the start and the end we should be able to get the estimated time. Now we just need to get it in the form <span class=\"math-container\">\\$y = mx + c\\$</span>.</p>\n\n<p>The lower bound is <span class=\"math-container\">\\$\\log_{10}(0.2)\\$</span> at 100 and <span class=\"math-container\">\\$\\log_{10}(60)\\$</span> at 200. And so we can determine:</p>\n\n<p><span class=\"math-container\">$$\nm = \\frac{\\log(60) - \\log(0.2)}{200 - 100}\n$$</span>\n<span class=\"math-container\">$$\nc = \\log(0.2) - 100m\n$$</span></p>\n\n<p>This shows that it would take <span class=\"math-container\">\\$1.785 \\times 10^{71}\\$</span> seconds or 178 Duovigintillion seconds.</p>\n\n<h1>How to optimizing the algorithm</h1>\n\n<p>Firstly the equations are:</p>\n\n<p><span class=\"math-container\">$$\ng(f, a) = \\frac{\\Sigma(f_{a_i} \\times f_{\\text{calories}_i})}{\\Sigma(f_{\\text{calories}_i})}\n$$</span></p>\n\n<p><span class=\"math-container\">$$\nn = \\{g(f, \\text{carbs}), g(f, \\text{protein}), g(f, \\text{fat}), g(f, \\text{vitimins})\\}\n$$</span></p>\n\n<p><span class=\"math-container\">$$\n\\text{SP} = g(f, \\text{nutrients}) \\times \\frac{\\Sigma n}{2\\max(n)} + \\text{Base gain}\n$$</span></p>\n\n<p>From here we have to find the maximums.</p>\n\n<ol>\n<li><p>What’s the maximum and minimum that <span class=\"math-container\">\\$\\frac{\\Sigma n}{2\\max(n)}\\$</span> can be?</p>\n\n<p><span class=\"math-container\">$$\n \\frac{n + n + n + n}{2 \\times n} = \\frac{4n}{2n} = 2\n $$</span></p>\n\n<p><span class=\"math-container\">$$\n \\frac{n + 0 + 0 + 0}{2 \\times n} = \\frac{n}{2n} = 0.5\n $$</span></p>\n\n<p>This means all we need to do is ensure the calorie average of all the different nutrients are the same. It doesn’t matter what value this average is, only that all have the same.</p></li>\n<li><p>What’s the maximum that <span class=\"math-container\">\\$g(f, \\text{nutrients})\\$</span> can be?</p>\n\n<p>Firstly taking into account:</p>\n\n<p><span class=\"math-container\">$$\n \\frac{\\Sigma(a_i \\times b_i)}{\\Sigma(b_i)} = \\Sigma(a_i \\times \\frac{b_i}{\\Sigma(b_i)})\n $$</span></p>\n\n<p>We know that these are the calorie average of the foods nutritional value. To maximize this you just want the foods with the highest nutritional value.</p></li>\n</ol>\n\n<p>Lets work through an example lets say we have the following five foods:</p>\n\n<ul>\n<li><p>a/10/0/0/0/1</p></li>\n<li><p>b/0/10/0/0/1</p></li>\n<li><p>c/0/0/10/0/1</p></li>\n<li><p>d/0/0/0/10/1</p></li>\n<li><p>e/1/1/1/1/4</p></li>\n</ul>\n\n<p>What’s the way to maximize SP?</p>\n\n<p>Eating 1 e would give you <span class=\"math-container\">\\$4 \\times 2 = 8\\$</span>.<br>\nEating 4 a would give you <span class=\"math-container\">\\$10 \\times 0.5 = 5\\$</span>.<br>\nEating 1 a, b, c and d would give you <span class=\"math-container\">\\$10 \\times 2 = 20\\$</span>.<br>\nAnd so from here we have deduced eating a, b, c and d in ratios of 1:1:1:1 give the most SP.</p>\n\n<p>This means the rough solution is to find the foods that have the same calorie average for their individual nutrients where you select foods with a bias for ones with high total nutrients.</p>\n\n<pre><code>import sys\nimport collections\n\n\nsys.setrecursionlimit(10000000)\n\n_Food = collections.namedtuple('Food', 'name carbs protein fat vitamins calories')\n\n__all__ = [\n 'available',\n 'find_combs',\n]\n\n\nclass Food(_Food):\n @property\n def nutrients(self):\n return sum(self[1:5])\n\n\ndef tot_avg(food, attr):\n return (\n sum(f.calories * getattr(f, attr) for f in food)\n / sum(f.calories for f in food)\n )\n\n\ndef ratio_transform(attrs):\n largest = max(attrs[1:5])\n if largest == 0:\n return 0, 0, 0, 0\n return tuple(100 * a / largest for a in attrs[1:5])\n\n\ndef bulid_ratios(food_ratios, delta_step):\n def _ratios(attrs, delta):\n wanted = []\n for *ratio, food in food_ratios:\n if all((a - delta) &lt;= r &lt;= (a + delta) for r, a in zip(ratio, attrs)):\n wanted.append(food)\n return wanted\n\n def ratios(attrs, calories):\n ratios = ratio_transform(attrs)\n ratios = tuple(100 - int(round(r)) for r in ratios)\n delta = delta_step\n while delta &lt;= 100:\n rets = _ratios(ratios, delta)\n rets = [f for f in rets if f.calories &lt;= calories]\n if rets:\n return rets\n delta += delta_step\n return ratios\n\n\ndef find_sp(total):\n try:\n nutrients = [\n tot_avg(total, 'carbs'),\n tot_avg(total, 'protein'),\n tot_avg(total, 'fat'),\n tot_avg(total, 'vitamins')\n ]\n balance = sum(nutrients) / 2 / max(nutrients)\n except ZeroDivisionError:\n return None\n return tot_avg(total, 'nutrients') * balance + 12\n\n\ndef find_combs(available, max_calories, delta_step=10):\n available = list(sorted(available, key=lambda f: f.nutrients, reverse=True))\n\n food_ratios = [\n ratio_transform(food[1:5]) + (food,)\n for food in available\n ]\n\n ratios = bulid_ratios(food_ratios, delta_step)\n largest = (0, ())\n for food in available:\n if food.calories &gt; max_calories:\n continue\n if food.nutrients * 2 &lt;= largest[0] - 12:\n break\n foods = [food]\n calories = food.calories\n attrs = [a * food.calories for a in food[1:5]]\n while True:\n new_foods = ratios(attrs, max_calories - calories)\n if not new_foods:\n break\n new_food = new_foods[0]\n foods.append(new_food)\n calories += new_food.calories\n attrs = [a + b * new_food.calories for a, b in zip(attrs, new_food[1:5])]\n sp = find_sp(foods)\n if sp &gt; largest[0]:\n largest = sp, tuple(foods)\n return largest\n\n\ndef read_foods(foods):\n for food in foods:\n name, *other = food.split('/')\n yield Food(name, *[float(v) for v in other])\n\n\navailable = [\n \"Fiddleheads/3/1/0/3/80\",\n \"Fireweed Shoots/3/0/0/4/150\",\n \"Prickly Pear Fruit/2/1/1/3/190\",\n \"Huckleberries/2/0/0/6/80\",\n \"Rice/7/1/0/0/90\",\n \"Camas Bulb/1/2/5/0/120\",\n \"Beans/1/4/3/0/120\",\n \"Wheat/6/2/0/0/130\",\n \"Crimini Mushrooms/3/3/1/1/200\",\n \"Corn/5/2/0/1/230\",\n \"Beet/3/1/1/3/230\",\n \"Tomato/4/1/0/3/240\",\n \"Raw Fish/0/3/7/0/200\",\n \"Raw Meat/0/7/3/0/250\",\n \"Tallow/0/0/8/0/200\",\n \"Scrap Meat/0/5/5/0/50\",\n \"Prepared Meat/0/4/6/0/600\",\n \"Raw Roast/0/6/5/0/800\",\n \"Raw Sausage/0/4/8/0/500\",\n \"Raw Bacon/0/3/9/0/600\",\n \"Prime Cut/0/9/4/0/600\",\n \"Cereal Germ/5/0/7/3/20\", # test\n \"Bean Paste/3/5/7/0/40\",\n \"Flour/15/0/0/0/50\",\n \"Sugar/15/0/0/0/50\",\n \"Camas Paste/3/2/10/0/60\",\n \"Cornmeal/9/3/3/0/60\",\n \"Huckleberry Extract/0/0/0/15/60\",\n \"Yeast/0/8/0/7/60\", # test\n \"Oil/0/0/15/0/120\",\n \"Infused Oil/0/0/12/3/120\",\n \"Simple Syrup/12/0/3/0/400\",\n \"Rice Sludge/10/1/0/2/450\",\n \"Charred Beet/3/0/3/7/470\",\n \"Camas Mash/1/2/9/1/500\",\n \"Campfire Beans/1/9/3/0/500\",\n \"Wilted Fiddleheads/4/1/0/8/500\",\n \"Boiled Shoots/3/0/1/9/510\",\n \"Charred Camas Bulb/2/3/7/1/510\",\n \"Charred Tomato/8/1/0/4/510\",\n \"Charred Corn/8/1/0/4/530\",\n \"Charred Fish/0/9/4/0/550\",\n \"Charred Meat/0/10/10/0/550\",\n \"Wheat Porridge/10/4/0/10/510\",\n \"Charred Sausage/0/11/15/0/500\",\n \"Fried Tomatoes/12/3/9/2/560\",\n \"Bannock/15/3/8/0/600\",\n \"Fiddlehead Salad/6/6/0/14/970\",\n \"Campfire Roast/0/16/12/0/1000\",\n \"Campfire Stew/5/12/9/4/1200\",\n \"Wild Stew/8/5/5/12/1200\",\n \"Fruit Salad/8/2/2/10/900\",\n \"Meat Stock/5/8/9/3/700\",\n \"Vegetable Stock/11/1/2/11/700\",\n \"Camas Bulb Bake/12/7/5/4/400\",\n \"Flatbread/17/8/3/0/500\",\n \"Huckleberry Muffin/10/5/4/11/450\",\n \"Baked Meat/0/13/17/0/600\",\n \"Baked Roast/4/13/8/7/900\",\n \"Huckleberry Pie/9/5/4/16/1300\",\n \"Meat Pie/7/11/11/5/1300\",\n \"Basic Salad/13/6/6/13/800\",\n \"Simmered Meat/6/18/13/5/900\",\n # \"Vegetable Medley/9/5/8/20/900\", outdated values\n \"Vegetable Medley/8/4/7/17/900\",\n \"Vegetable Soup/12/4/7/19/1200\",\n \"Crispy Bacon/0/18/26/0/600\",\n \"Stuffed Turkey/9/16/12/7/1500\",\n]\navailable = list(read_foods(available))\n</code></pre>\n\n<p>Which runs fairly quickly across the board:</p>\n\n<p><img src=\"https://raw.githubusercontent.com/Peilonrayz/Stack-Exchange-contributions/master/code-review/215626/static/figs/final.svg?sanitize=true\" alt=\"image\"></p>\n\n<p>Output is also what you’d expect:</p>\n\n\n\n<pre><code>&gt;&gt;&gt; find_combs(available, 2000)\n(79.65454545454546, (Food(name='Simmered Meat', carbs=6.0, protein=18.0, fat=13.0, vitamins=5.0, calories=900.0), Food(name='Vegetable Medley', carbs=8.0, protein=4.0, fat=7.0, vitamins=17.0, calories=900.0), Food(name='Flour', carbs=15.0, protein=0.0, fat=0.0, vitamins=0.0, calories=50.0), Food(name='Flour', carbs=15.0, protein=0.0, fat=0.0, vitamins=0.0, calories=50.0), Food(name='Flour', carbs=15.0, protein=0.0, fat=0.0, vitamins=0.0, calories=50.0), Food(name='Flour', carbs=15.0, protein=0.0, fat=0.0, vitamins=0.0, calories=50.0)))\n</code></pre>\n\n<p><strong>NOTE</strong>: Code to <a href=\"https://github.com/Peilonrayz/Stack-Exchange-contributions/blob/master/code-review/215626/tests/test_plot.py\" rel=\"nofollow noreferrer\">plot the graphs</a>, <a href=\"https://github.com/Peilonrayz/Stack-Exchange-contributions/tree/master/code-review/215626\" rel=\"nofollow noreferrer\">complete changes</a>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-17T23:43:29.450", "Id": "417187", "Score": "0", "body": "I'm going to leave it a little while until I accept this amazing answer, just in case there are any massive developments. Thanks for your help!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-17T23:46:00.137", "Id": "417189", "Score": "0", "body": "@RulerOfTheWorld It's always good to wait a while before accepting. :) If someone comes along and posts something better than the above I'd encourage you to give them the tick rather than me. I posted my answer halfway through so others can have easier to read code to work from." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-18T11:53:45.033", "Id": "417278", "Score": "0", "body": "If someone posts a better answer later, you can change your accept vote. I think it makes sense to accept once you've read *and understood* an answer to make sure it's actually good, and think it's comprehensive enough. Having an accepted answer doesn't close a question." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-17T23:04:14.057", "Id": "215634", "ParentId": "215626", "Score": "21" } }, { "body": "<p>I see some replies with general tips for optimization, but I don't see anyone recommending a specific approach called memoization. It works wonders just for this kind of problems (results in some finite range around the &lt;1M mark, 3000 is far below the upper limit).</p>\n\n<p>Basically you would do something like this:</p>\n\n<p>Create a sort of array (this one will be struxtured differently depending on whether you just need the value of the result, only one combination of food items or all combinations). Since no food has negative calories, you can only make it 0-3000</p>\n\n<p>Then you do something like this (pseudocode):</p>\n\n<pre><code>for foodItem in foodItems:\n for value in caloriesArray:\n if caloriesArray[value] != 0: #has been reached before, so I can expand on it\n caloriesArray[value]+foodItems[foodItem] = ... #whatever you need, can be just True\n</code></pre>\n\n<p>There are plenty of sites explaining memoization and I'm not very good at explanations, but if this doesn't help you then I can include a simple example.</p>\n\n<p>Then just find the highest reached value of the array.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-23T04:03:06.933", "Id": "418002", "Score": "1", "body": "I tested your theory, and found it to not really improve performance. (See the graph in my answer)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-25T07:11:04.700", "Id": "418201", "Score": "0", "body": "I will add an update with the code to my answer, but for exclusion/inclusion kind of problems like this, memoization should be vastly superior to anything else when used in the right way. Cannot promise I'll do it today though." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-18T12:51:18.067", "Id": "215674", "ParentId": "215626", "Score": "3" } }, { "body": "<p><em>I guess that my code needs a review too, because I am by far no good python programmer, but I wanted to share some of my ideas to solve your probelm that do not fit in a comment. So I hope at least the approach is some optimization to your code, if it is not the code itself.</em></p>\n\n<hr>\n\n<p>I looked a bit on the function and thought that there must be an easier way to calculate it. So what I do here is:</p>\n\n<p><span class=\"math-container\">$$\\textrm{weighted_nutrients} = \\frac{(m \\odot c)^\\top \\cdot n}{m^\\top \\cdot c}=\\frac{\\{\\sum_j^M(m_j \\times c_j) \\times n_{jk}\\}_{k=1 \\ldots M}}{\\sum_j^M(m_j \\times c_j)}$$</span></p>\n\n<p>with <span class=\"math-container\">\\$m\\$</span> being the amount of each foods (1 apple, 2 peaches, ... <span class=\"math-container\">\\$\\rightarrow\\$</span> <code>[1,2,...]</code>), <span class=\"math-container\">\\$M\\$</span> being the amount of foods (67 foods available), <span class=\"math-container\">\\$c\\$</span> the kcals, <span class=\"math-container\">\\$n\\$</span> the nutrients and <span class=\"math-container\">\\$\\odot\\$</span> is element-wise multiplication. The result is a vector that needs to be summed up for the base value. It gets squared as the balance's numerator is the same. For the maximum in the balance, we can simply plug it in, as it is a vector from which a maximum can be chosen. The result looks in principle like this:\n<span class=\"math-container\">$$\\textrm{SP} = \\textrm{sum}(\\textrm{weighted_nutrients})^2 \\cdot \\frac{0.5}{\\max(\\textrm{weighted_nutrients})} + 12$$</span>\nNow as I write it, I think it looks even better like this:\n<span class=\"math-container\">$$\\textrm{SP} = \\frac{1}{2} \\cdot \\frac{\\textrm{sum}(\\textrm{weighted_nutrients})^2}{\\max(\\textrm{weighted_nutrients})} + 12$$</span></p>\n\n<p>What should be done with this function now?</p>\n\n<p>As you did, I wrote a function using itertools and a lot of possible combinations which luckily starts with the high calory foods, which give quite good results from the beginning. But as you found out yourself, you will be very old when/if the code ever finishes.\nTherefore, I chose a genetic algorithm to solve the problem as for my untrained eyes, this looked like a nice way. On the other hand I always wanted to use a GA to solve a problem ... :D</p>\n\n<pre><code>#!/usr/bin/env python3\nimport numpy as np\nimport itertools as it\nfrom deap import base, creator, tools, algorithms\nimport random\n\n\ndef generate_function(skill_gain_multiplier=1, base_skill_gain=12):\n # read in the foods\n names, nutrients, calories = give_food()\n\n # define skill_point function\n def skill_points(amounts):\n numerator = (amounts * calories).dot(nutrients)\n denominator = amounts.dot(calories)\n weighted_nutrients = np.divide(numerator, denominator)\n base_value = np.sum(weighted_nutrients) ** 2\n balance_modifier = (\n 0.5 * 1 / np.max(weighted_nutrients) * skill_gain_multiplier\n )\n result = base_value * balance_modifier + base_skill_gain\n return result\n\n # define calory check function\n def calory_check(amounts):\n calory_count = amounts.dot(calories)\n return calory_count\n\n return names, skill_points, calories, calory_check\n\n\ndef give_food():\n available = [\n \"Fiddleheads/3/1/0/3/80\",\n \"Fireweed Shoots/3/0/0/4/150\",\n \"Prickly Pear Fruit/2/1/1/3/190\",\n \"Huckleberries/2/0/0/6/80\",\n \"Rice/7/1/0/0/90\",\n \"Camas Bulb/1/2/5/0/120\",\n \"Beans/1/4/3/0/120\",\n \"Wheat/6/2/0/0/130\",\n \"Crimini Mushrooms/3/3/1/1/200\",\n \"Corn/5/2/0/1/230\",\n \"Beet/3/1/1/3/230\",\n \"Tomato/4/1/0/3/240\",\n \"Raw Fish/0/3/7/0/200\",\n \"Raw Meat/0/7/3/0/250\",\n \"Tallow/0/0/8/0/200\",\n \"Scrap Meat/0/5/5/0/50\",\n \"Prepared Meat/0/4/6/0/600\",\n \"Raw Roast/0/6/5/0/800\",\n \"Raw Sausage/0/4/8/0/500\",\n \"Raw Bacon/0/3/9/0/600\",\n \"Prime Cut/0/9/4/0/600\",\n \"Cereal Germ/5/0/7/3/20\", # test\n \"Bean Paste/3/5/7/0/40\",\n \"Flour/15/0/0/0/50\",\n \"Sugar/15/0/0/0/50\",\n \"Camas Paste/3/2/10/0/60\",\n \"Cornmeal/9/3/3/0/60\",\n \"Huckleberry Extract/0/0/0/15/60\",\n \"Yeast/0/8/0/7/60\", # test\n \"Oil/0/0/15/0/120\",\n \"Infused Oil/0/0/12/3/120\",\n \"Simple Syrup/12/0/3/0/400\",\n \"Rice Sludge/10/1/0/2/450\",\n \"Charred Beet/3/0/3/7/470\",\n \"Camas Mash/1/2/9/1/500\",\n \"Campfire Beans/1/9/3/0/500\",\n \"Wilted Fiddleheads/4/1/0/8/500\",\n \"Boiled Shoots/3/0/1/9/510\",\n \"Charred Camas Bulb/2/3/7/1/510\",\n \"Charred Tomato/8/1/0/4/510\",\n \"Charred Corn/8/1/0/4/530\",\n \"Charred Fish/0/9/4/0/550\",\n \"Charred Meat/0/10/10/0/550\",\n \"Wheat Porridge/10/4/0/10/510\",\n \"Charred Sausage/0/11/15/0/500\",\n \"Fried Tomatoes/12/3/9/2/560\",\n \"Bannock/15/3/8/0/600\",\n \"Fiddlehead Salad/6/6/0/14/970\",\n \"Campfire Roast/0/16/12/0/1000\",\n \"Campfire Stew/5/12/9/4/1200\",\n \"Wild Stew/8/5/5/12/1200\",\n \"Fruit Salad/8/2/2/10/900\",\n \"Meat Stock/5/8/9/3/700\",\n \"Vegetable Stock/11/1/2/11/700\",\n \"Camas Bulb Bake/12/7/5/4/400\",\n \"Flatbread/17/8/3/0/500\",\n \"Huckleberry Muffin/10/5/4/11/450\",\n \"Baked Meat/0/13/17/0/600\",\n \"Baked Roast/4/13/8/7/900\",\n \"Huckleberry Pie/9/5/4/16/1300\",\n \"Meat Pie/7/11/11/5/1300\",\n \"Basic Salad/13/6/6/13/800\",\n \"Simmered Meat/6/18/13/5/900\",\n # \"Vegetable Medley/9/5/8/20/900\", outdated values\n \"Vegetable Medley/8/4/7/17/900\",\n \"Vegetable Soup/12/4/7/19/1200\",\n \"Crispy Bacon/0/18/26/0/600\",\n \"Stuffed Turkey/9/16/12/7/1500\",\n ]\n\n all_names = []\n all_nutrients = []\n all_calories = []\n for item in available:\n name, *nutrients, calories = item.split(\"/\")\n all_names.append(name)\n nutrients = [float(x) for x in nutrients]\n all_nutrients.append(nutrients)\n all_calories.append(float(calories))\n return np.array(all_names), np.array(all_nutrients), np.array(all_calories)\n\n\ndef brute_force(names, f, calory_check, cals):\n # create every possible combination\n combinations = it.product(range(2), repeat=len(names))\n\n best = 0.0\n cnt = 0\n for comb in combinations:\n # calculate value\n comb = np.array(list(comb))\n new = f(comb)\n # if better, replace best\n if new &gt; best and calory_check(comb):\n best = new\n print(\n [x for x in zip(names, comb) if x[1] != 0], new, comb.dot(cals)\n )\n # show current iteration ... of quite a few\n else:\n sys.stdout.write(f\"\\r{cnt}\")\n sys.stdout.flush()\n cnt += 1\n\n\n# the genetic algorithm is very simply based on the tutorials here:\n# https://deap.readthedocs.io/en/master/examples/index.html\ndef genetic_algorithm(\n fitness_function,\n cal_chk,\n array_size,\n population_size=300,\n max_iterations=250,\n):\n creator.create(\"FitnessMax\", base.Fitness, weights=(1.0,))\n creator.create(\"Individual\", np.ndarray, fitness=creator.FitnessMax)\n\n toolbox = base.Toolbox()\n\n # Attribute generator\n toolbox.register(\"attr_bool\", random.randint, 0, 1)\n\n # Structure initializers\n toolbox.register(\n \"individual\",\n tools.initRepeat,\n creator.Individual,\n toolbox.attr_bool,\n array_size,\n )\n toolbox.register(\"population\", tools.initRepeat, list, toolbox.individual)\n\n def cxTwoPointCopy(ind1, ind2):\n \"\"\"Execute a two points crossover with copy on the input individuals. The\n copy is required because the slicing in numpy returns a view of the data,\n which leads to a self overwritting in the swap operation. It prevents\n ::\n\n &gt;&gt;&gt; import numpy\n &gt;&gt;&gt; a = numpy.array((1,2,3,4))\n &gt;&gt;&gt; b = numpy.array((5.6.7.8))\n &gt;&gt;&gt; a[1:3], b[1:3] = b[1:3], a[1:3]\n &gt;&gt;&gt; print(a)\n [1 6 7 4]\n &gt;&gt;&gt; print(b)\n [5 6 7 8]\n \"\"\"\n size = len(ind1)\n cxpoint1 = random.randint(1, size)\n cxpoint2 = random.randint(1, size - 1)\n if cxpoint2 &gt;= cxpoint1:\n cxpoint2 += 1\n else: # Swap the two cx points\n cxpoint1, cxpoint2 = cxpoint2, cxpoint1\n\n ind1[cxpoint1:cxpoint2], ind2[cxpoint1:cxpoint2] = (\n ind2[cxpoint1:cxpoint2].copy(),\n ind1[cxpoint1:cxpoint2].copy(),\n )\n\n return ind1, ind2\n\n # cutoff function was needed, as initial guesses were all above 3000 kcal\n # and no solution could be found. with the smooth cutoff function, the results\n # are pushed below 3000 kcal, which is where they belong.\n # not sure if this is smart or just overshot :D\n def cutoff(individual):\n return 0.5 - 0.5 * np.tanh((cal_chk(individual) - 3000) / 5000)\n\n # return the cutoff value if higher than 3000\n # and the true value if lower\n def evalFit(individual):\n if cal_chk(individual) &lt;= 3000:\n return (fitness_function(individual),)\n else:\n return (cutoff(individual),)\n\n # toolbox.register(\"evaluate\", evalOneMax)\n toolbox.register(\"evaluate\", evalFit)\n toolbox.register(\"mate\", tools.cxTwoPoint)\n toolbox.register(\"mutate\", tools.mutFlipBit, indpb=0.05)\n toolbox.register(\"select\", tools.selTournament, tournsize=3)\n\n # Creating the population\n def main():\n pop = toolbox.population(n=population_size)\n hof = tools.HallOfFame(5, similar=np.array_equal)\n stats = tools.Statistics(lambda ind: ind.fitness.values)\n stats.register(\"avg\", np.mean)\n stats.register(\"std\", np.std)\n stats.register(\"min\", np.min)\n stats.register(\"max\", np.max)\n\n pop, log = algorithms.eaSimple(\n pop,\n toolbox,\n cxpb=0.5,\n mutpb=0.5,\n ngen=max_iterations,\n stats=stats,\n halloffame=hof,\n verbose=True,\n )\n\n return pop, log, hof\n\n return main\n\n\nif __name__ == \"__main__\":\n # generating the functions\n names, f, cals, calory_check = generate_function()\n\n # not recommended\n # brute_force(names, f, calory_check, cals)\n\n # probably better\n ga = genetic_algorithm(\n f, calory_check, len(names), max_iterations=500, population_size=500\n )\n pop, log, hof = ga()\n\n # printing the result\n print(\"\\n########\\n# DONE #\\n########\")\n for star in hof[1:]:\n [print(i, s) for i, s in zip(star, names) if i &gt; 0]\n print(f\"which has {calory_check(star)} kcal\")\n print(f\"and gives a SP of {f(star)}\\n---\\n\")\n</code></pre>\n\n<p>and the result is something like this:</p>\n\n<pre><code>1 Vegetable Soup\n1 Stuffed Turkey\nwhich has 2700.0 kcal\nand gives a SP of 87.34734734734735\n---\n\n1 Cereal Germ\n1 Vegetable Soup\n1 Stuffed Turkey\nwhich has 2720.0 kcal\nand gives a SP of 87.04413748413035\n---\n\n1 Bean Paste\n1 Vegetable Soup\n1 Stuffed Turkey\nwhich has 2740.0 kcal\nand gives a SP of 87.01479581771551\n---\n\n1 Flour\n1 Vegetable Soup\n1 Stuffed Turkey\nwhich has 2750.0 kcal\nand gives a SP of 86.9337837837838\n---\n</code></pre>\n\n<p>87.347 is the highest I found so far. Sometime the algorithm gets stuck at a lower value, you may need to play around with the parameters of the GA to get a faster/better/more robust result. But as the code is very fast, maybe just run it multiple times and see which result is the highest.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-23T01:11:02.887", "Id": "417992", "Score": "0", "body": "I think I did, we should go to the chat https://chat.stackexchange.com/rooms/91219/optimising-a-list-searching-algorithm" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-23T01:12:11.593", "Id": "417993", "Score": "1", "body": "Ah! you used `\\`n\\``, rather than `\\$n\\$` my bad. Sorry :(" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-23T01:39:41.667", "Id": "417996", "Score": "0", "body": "Ah, this works different here. Thanks for highlighting." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-23T02:33:40.180", "Id": "417997", "Score": "0", "body": "Yeah it does :) What is \\$m\\$. Is that \\$n\\$ in my answer, but without calling the function?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-23T02:45:18.900", "Id": "417998", "Score": "0", "body": "I don't think so. If I understood it right, your \\$n\\$ is my *weighted_nutrients*. My \\$m\\$ holds the amount of every item." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-23T06:31:20.903", "Id": "418012", "Score": "1", "body": "[I had a go at optimizing the code tonight](https://gist.github.com/Peilonrayz/381c6c98b28b660f9ac0bfd3275a1a0a), I think it's a pretty naive implementation. It's just finds the inverse ratio and picks the highest within a range. And I get 90.761@2400 calories, with 1 Stuffed Turkey and 1 Vegetable Medley. I doubted that it was actually 90.761, but it seems legit from the math in my answer and the OPs code. Do you get the same?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-23T07:21:52.133", "Id": "418015", "Score": "0", "body": "The Vegetable Medley was updated (see my code and the chat). Without the update you are right with 90.761. I got the same. :)" } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-23T00:00:22.437", "Id": "216027", "ParentId": "215626", "Score": "4" } } ]
{ "AcceptedAnswerId": "215634", "CommentCount": "17", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-17T19:53:46.787", "Id": "215626", "Score": "19", "Tags": [ "python", "performance", "python-3.x" ], "Title": "Optimising a list searching algorithm" }
215626
<p>I was asked to code a TextPad with following functionality: </p> <blockquote> <p><code>display()</code> – to display the entire content<br> <code>display(n, m)</code> – to display from line n to m<br> <code>insert(n, text)</code> – to insert text at line n<br> <code>delete(n)</code> – delete line n<br> <code>delete(n, m)</code> – delete from line n to m<br> <code>copy(n, m)</code> – copy contents from line n to m to clipboard<br> <code>paste(n)</code> – paste contents from clipboard to line n<br> <code>undo()</code> – undo last command<br> <code>redo()</code> – redo last command</p> </blockquote> <p>They expected the textpad to be in memory (not as file). They also expected to handle error gracefully and the program to be menu driven.</p> <p>Can someone please review the class structure implemented. Can it be improved so that code can be easily modified and extended?</p> <pre><code>public interface Command { void execute(); void undo(); } </code></pre> <hr> <pre><code>package com.onedirect.oodesign.textpad; public class PasteCommand implements Command { private TextPad textPad; private Integer line; public PasteCommand(TextPad textPad, Integer line){ this.textPad = textPad; this.line = line; } @Override public void execute() { this.textPad.getLines().addAll(line, this.textPad.getClipBoard()); } @Override public void undo() { for (int i = line; i &lt; this.textPad.getClipBoard().size(); i++) { this.textPad.getLines().remove(i); } } } </code></pre> <hr> <pre><code>package com.onedirect.oodesign.textpad; public class CopyCommand implements Command { private TextPad textPad; private Integer from; private Integer to; public CopyCommand(TextPad textPad, Integer from, Integer to) { this.textPad = textPad; this.from = from; this.to = to; } @Override public void execute() { this.textPad.setClipBoard(this.textPad.getLines().subList(from, to)); } @Override public void undo() { } } </code></pre> <hr> <pre><code>package com.onedirect.oodesign.textpad; import java.util.List; public class DeleteCommand implements Command { private TextPad textPad; private Integer from; private Integer to; private List&lt;String&gt; lines; public DeleteCommand(TextPad textPad, Integer from, Integer to) { this.textPad = textPad; this.from = from; this.to =to; } @Override public void execute() { List&lt;String&gt; content = textPad.getLines(); this.lines = content.subList(from, to); for (int i = from; i &lt; to &amp;&amp; i&lt;content.size(); i++) { content.remove(i); } } @Override public void undo() { List&lt;String&gt; content = textPad.getLines(); content.addAll(from, this.lines); } } </code></pre> <hr> <pre><code>package com.onedirect.oodesign.textpad; import java.util.List; public class DisplayCommand implements Command { private TextPad textPad; private int m; private int n; public DisplayCommand(TextPad textPad, int m, int n) { this.textPad = textPad; this.m = m; this.n = n; } public DisplayCommand(TextPad textPad) { this.textPad = textPad; this.m = 0; this.n = this.textPad.getLines().size(); } @Override public void execute() { List&lt;String&gt; list = this.textPad.getLines(); list.subList(m, n).forEach(System.out::println); } @Override public void undo() { } } </code></pre> <hr> <pre><code>package com.onedirect.oodesign.textpad; public class InsertCommand implements Command{ private TextPad textPad; private Integer line; private String text; public InsertCommand(TextPad textPad, Integer line, String text) { this.line = line; this.textPad = textPad; this.text = text; } @Override public void execute() { this.textPad.getLines().add(line, text); } @Override public void undo() { this.textPad.getLines().remove((int)line); } } </code></pre> <hr> <pre><code>package com.onedirect.oodesign.textpad; import java.util.ArrayList; import java.util.List; import java.util.Stack; public class TextPad { private List&lt;String&gt; lines; private Stack&lt;Command&gt; undo; private Stack&lt;Command&gt; redo; private List&lt;String&gt; clipBoard; public TextPad() { this.lines = new ArrayList&lt;&gt;(); this.undo = new Stack&lt;&gt;(); this.redo = new Stack&lt;&gt;(); this.clipBoard = new ArrayList&lt;&gt;(); } public List&lt;String&gt; getClipBoard() { return this.clipBoard; } public void setClipBoard(List&lt;String&gt; clipBoard) { this.clipBoard = clipBoard; } public List&lt;String&gt; getLines() { return lines; } public void display() { DisplayCommand displayCommand = new DisplayCommand(this); displayCommand.execute(); } public void display(int m, int n) { DisplayCommand displayCommand = new DisplayCommand(this, m, n); displayCommand.execute(); } public void insert(int n, String text) { clearRedo(); InsertCommand insertCommand = new InsertCommand(this, n, text); insertCommand.execute(); undo.push(insertCommand); } public void delete(int n) { delete(n, n); } public void delete(int n, int m) { clearRedo(); DeleteCommand deleteCommand = new DeleteCommand(this, n, m); deleteCommand.execute(); undo.push(deleteCommand); } public void copy(int n, int m) { clearRedo(); CopyCommand copyCommand = new CopyCommand(this, n, m); copyCommand.execute(); } public void paste(int n) { clearRedo(); PasteCommand pasteCommand = new PasteCommand(this, n); pasteCommand.execute(); undo.push(pasteCommand); } public void undo(){ if(!undo.isEmpty()) { Command command = undo.pop(); command.undo(); redo.push(command); } } public void redo(){ if(!redo.isEmpty()) { Command command = redo.pop(); command.execute(); undo.push(command); } } private void clearRedo() { while (!redo.isEmpty()) { redo.pop(); } } } </code></pre> <hr> <pre><code>package com.onedirect.oodesign.textpad; import java.util.Scanner; public class TextPadDriver { public static void main(String[] args) { TextPad textPad = new TextPad(); Scanner in = new Scanner(System.in); while (true) { System.out.println("Please enter I to insert," + " D to delete, C to copy , P to paste, " + "U to undo, R to redo, S to show, another to end"); String c = in.next(); switch (c) { case "I" : System.out.println("Give Line Number"); Integer n = in.nextInt(); System.out.println("Give Text"); String text = in.next(); textPad.insert(n, text); break; case "D": System.out.println("Give Line Number"); Integer from = in.nextInt(); System.out.println("Give Line Number"); Integer to = in.nextInt(); textPad.delete(from, to); break; case "C": System.out.println("Give Line Number"); Integer fromCopy = in.nextInt(); System.out.println("Give Line Number"); Integer toCopy = in.nextInt(); textPad.copy(fromCopy, toCopy); break; case "P": System.out.println("Give Line Number"); Integer line = in.nextInt(); textPad.paste(line); break; case "U": textPad.undo(); break; case "R": textPad.redo(); break; case "S": textPad.display(); break; default: return; } } } } </code></pre> <p><a href="https://i.stack.imgur.com/TiVRo.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/TiVRo.png" alt="enter image description here"></a></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-18T09:48:09.510", "Id": "417238", "Score": "1", "body": "Since this has popped up in the close vote queue, does this code currently work as expected?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-19T08:53:36.997", "Id": "417421", "Score": "0", "body": "@Manu, is it possible for you to provide us the `TextPadDriver`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-19T11:01:23.873", "Id": "417441", "Score": "0", "body": "@Roman I have added textPadDriver. But it doesn't cover all use cases." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-19T11:02:26.537", "Id": "417442", "Score": "1", "body": "@Graipher It is working and might not cover all edge cases. But I am more concerened about the structure than correctness of the code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-19T11:11:47.963", "Id": "417444", "Score": "0", "body": "@Manu, thank you. I will edit my answer soon based on the `TextPadDriver`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-19T11:41:05.153", "Id": "417453", "Score": "0", "body": "Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*. Question threads get incredibly messy if multiple answers review different versions of the same question." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-19T15:04:30.590", "Id": "417483", "Score": "0", "body": "@Mast The `TextPadDriver` was not an update, but a completion of the code, because this class is included in the UML, but is not specified here. Could you please add it again.." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-20T06:02:58.617", "Id": "417584", "Score": "0", "body": "@Roman Since the only answer so far is yours, yes, in this particular instance I will." } ]
[ { "body": "<h1><a href=\"https://sourcemaking.com/design_patterns/command\" rel=\"nofollow noreferrer\">Command Pattern</a></h1>\n\n<blockquote>\n <p>[The] Command [Pattern] decouples the object that invokes the operation from the one that knows how to perform it.</p>\n</blockquote>\n\n<p>In our case this means, that a <code>Command</code> invokes a method of <code>TextPad</code>. Though it is the way around and <code>TextPad</code> invokes a <code>Command</code>.</p>\n\n<p>For example, when we look into the method <code>display</code> in <code>TextPad</code>:</p>\n\n<blockquote>\n <pre class=\"lang-java prettyprint-override\"><code>public void display() {\n DisplayCommand displayCommand = new DisplayCommand(this);\n displayCommand.execute();\n}\n</code></pre>\n</blockquote>\n\n<p>Actually the logic should not be in a <code>Command</code> instead it needs to be in the <code>TextPad</code> itself. In the following I extract the logic out of the <code>DisplayCommand</code> into <code>TextPad</code></p>\n\n<pre class=\"lang-java prettyprint-override\"><code>public void display() {\n List&lt;String&gt; list = this.textPad.getLines();\n list.subList(m, n).forEach(System.out::println);\n}\n</code></pre>\n\n<p>After that we can invoke the method in <code>DisplayCommand</code>.</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>@Override\npublic void execute() {\n textPad.display();\n}\n</code></pre>\n\n<hr>\n\n<p>The <code>TextPad</code> should work totally independent of <code>Command</code>. Additionally the fields <code>Stack&lt;Command&gt; undo</code> and <code>Stack&lt;Command&gt; redo</code> do not belong into <code>TextPad</code> but inside <code>TextPadDriver</code>.</p>\n\n<hr>\n\n<h2>Why this Way?</h2>\n\n<p>Currently the code base violates against some opp-principles.</p>\n\n<h3><a href=\"https://refactoring.guru/smells/feature-envy\" rel=\"nofollow noreferrer\">Feature Envy</a></h3>\n\n<blockquote>\n <p>A method accesses the data of another object more than its own data.</p>\n</blockquote>\n\n<p>All implementations of <code>Command</code> operates on <code>TextPad</code>. For that the <code>TextPad</code> needs to offer its fields like <code>lines</code> and <code>clipBoard</code>. But actual the a <code>Command</code> should <a href=\"https://martinfowler.com/bliki/TellDontAsk.html\" rel=\"nofollow noreferrer\">Tell, Don't Ask</a> a <code>TextPad</code>.</p>\n\n<p>So the preferred way is </p>\n\n<pre class=\"lang-java prettyprint-override\"><code>@Override\npublic void execute() {\n textPad.display();\n}\n</code></pre>\n\n<h2><a href=\"https://en.wikipedia.org/wiki/Law_of_Demeter\" rel=\"nofollow noreferrer\">Law of Demeter</a></h2>\n\n<blockquote>\n <p>Only talk to your immediate friends.</p>\n</blockquote>\n\n<p>This \"problem\" coheres with the Feature Envy, because every <code>Command</code> gets an instance of <code>TextPad</code> but only needs a sub information of it like <code>lines</code> or <code>clipBoard</code>.</p>\n\n<blockquote>\n <pre class=\"lang-java prettyprint-override\"><code>this.textPad.getLines().remove(i)\n</code></pre>\n</blockquote>\n\n<p>The Law of Demeter do not allow the above statements, because you talk via <code>remove</code> to a \"frind\" (<code>lines</code>) of your \"frind\" (<code>textPad</code>), but you are only allow to talk to your \"immediat friend\" (<code>textPad</code>). </p>\n\n<p>A valid statement under the Law of Demeter is </p>\n\n<pre class=\"lang-java prettyprint-override\"><code>this.textPad.removeLine(i)\n</code></pre>\n\n<hr>\n\n<h1>Empty Methods</h1>\n\n<blockquote>\n <pre class=\"lang-java prettyprint-override\"><code>@Override\npublic void undo() {\n\n}\n</code></pre>\n</blockquote>\n\n<p>To have a empty method is totally valid, but it is better to leave it with a comment</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>@Override\npublic void undo() {\n // nothing to do here\n}\n</code></pre>\n\n<p>The benefits are that as a reader, I know that you are aware that you are not implementing it, and that you will know in the future that you have not forgotten the implementation.</p>\n\n<hr>\n\n<h1>Constructor Chaining</h1>\n\n<blockquote>\n <pre class=\"lang-java prettyprint-override\"><code>public DisplayCommand(TextPad textPad, int m, int n) {\n this.textPad = textPad;\n this.m = m;\n this.n = n;\n}\n\npublic DisplayCommand(TextPad textPad) {\n this.textPad = textPad;\n this.m = 0;\n this.n = this.textPad.getLines().size();\n}\n</code></pre>\n</blockquote>\n\n<p>It exists a constructor for all arguments <code>DisplayCommand(TextPad textPad, int m, int n)</code> and a constructor, which takes only one argument DisplayCommand(TextPad textPad) and sets <code>m</code> and <code>n</code> to some default values. </p>\n\n<p>It is possible to chain the one-argument constructor to the full-args constructor.</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>public DisplayCommand(TextPad textPad, int m, int n) {\n this.textPad = textPad;\n this.m = m;\n this.n = n;\n}\n\npublic DisplayCommand(TextPad textPad) {\n this(textPad, 0, textPad.getLines().size());\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-19T11:34:49.540", "Id": "417451", "Score": "0", "body": "I have added TextPad Driver Class. \n\npublic void display() {\n DisplayCommand displayCommand = new DisplayCommand(this);\n displayCommand.execute();\n}\n\n\npublic void display() {\n List<String> list = this.textPad.getLines();\n list.subList(m, n).forEach(System.out::println);\n}\n\n\n\nTo which classes the above two methods should belong to?" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-19T09:59:14.357", "Id": "215738", "ParentId": "215627", "Score": "3" } } ]
{ "AcceptedAnswerId": "215738", "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-17T19:57:30.033", "Id": "215627", "Score": "1", "Tags": [ "java", "object-oriented", "design-patterns", "text-editor" ], "Title": "Command pattern for simple text editor" }
215627
<p>This is my implementation of a hash function described below. The (compiled) program can be run as follows:</p> <pre><code>$ java Hash1 &lt; input.txt </code></pre> <p>The program reads a text file (of any size) with 8-digit student numbers on each line, splits each number into three numbers such that they have 3, 3 and 2 digits and then sums these numbers (e.g., for a student number 12345678, the hash is 123+456+78). Then, the hash is simply printed.</p> <p>If the hash has already been used, the student number is reversed and the hash function is calculated from the reversed number (12345678 is reversed to 87654321 and the hash is 876+543+21). If this value has also been taken, it just prints "-1" and continues to the next value.</p> <p>I use two external libraries for input and output:</p> <pre><code>edu.princeton.cs.algs4.stdin edu.princeton.cs.algs4.stdout </code></pre> <p>The implementation:</p> <pre><code>public class Hash1 { // the main method reads student number and // gets the hash value. it outputs the hash // if it hasn't been used, reverse hash // or -1 if both hash values are taken public static void main(String[] args) { // the size is 2098 because the highest // hash (index) can be 999+999+99=2097 String[] indexarray = new String[2098]; while (!StdIn.isEmpty()) { String key = StdIn.readLine(); char[] charray = key.toCharArray(); int hash = hash(charray); if (indexarray[hash] != null) { int newhash = reverse_hash(charray); if (indexarray[newhash] != null) { int errorFlag = -1; StdOut.println(errorFlag); } else { indexarray[newhash] = key; StdOut.println(newhash); } } else { indexarray[hash] = key; StdOut.println(hash); } } } // this method performs the hash as specified // and returns the value of the hash private static int hash(char[] charray) { String[] numbers = {"", "", ""}; for (int i = 0; i &lt; charray.length; i++) if (i &lt; 3) numbers[0] = numbers[0] + charray[i]; else if (i &gt;= 3 &amp;&amp; i &lt; 6) numbers[1] = numbers[1] + charray[i]; else if (i &gt;= 6 &amp;&amp; i &lt; 8) numbers[2] = numbers[2] + charray[i]; int firstNumb = Integer.parseInt(numbers[0]); int secondNumb = Integer.parseInt(numbers[1]); int thirdNumb = Integer.parseInt(numbers[2]); int result = firstNumb + secondNumb + thirdNumb; return result; } // this method reverses the student number, // calls hash() method to hash the reversed // student number and returns the hash private static int reverse_hash(char[] charray) { char [] reverse = new char[charray.length]; for (int i = 0; i &lt; reverse.length; i++) { int index = reverse.length - i -1; reverse[i] = charray[index]; } int hash = hash(reverse); return hash; } } </code></pre> <p>I am new to Java and would like to know how could I improve or optimize this program, if there are any issues with the code or I am using any bad (discouraged) practises etc.</p>
[]
[ { "body": "<p>If this is a class assignment, you might ask your professor why you spend time reading test data from keyboard instead of writing unit tests. Or if you really have to, at least use a Scanner to learn how the standard libraries work. That's what everyone else does in their classes. Nobody reads input from keyboard outside of the classroom in the extent the classroom examples would imply.</p>\n\n<p>Operating on the input character-by-character makes the code a bit hard to read. Instead split the string using regexps: <a href=\"https://stackoverflow.com/questions/3760152/split-string-to-equal-length-substrings-in-java\">https://stackoverflow.com/questions/3760152/split-string-to-equal-length-substrings-in-java</a></p>\n\n<p>Java also comes with a built in reverse function in the StringBuilder class.</p>\n\n<p>You have made reversing the hash a responsibility of the caller (e.g. you do it in the main method). The assignment says it should be part of the hash function, so your implementation is incomplete. Also, the hash function is private so it can not be used unless the data is read from System in. Make the hash function a separate class and the input handling another.</p>\n\n<p>Underscores don't belong in Java method naming convention. Use <code>reverseHash</code> instead of <code>reverse_hash</code>.</p>\n\n<p>Make all fields and arguments <code>final</code>, unless you mean to change their value.</p>\n\n<p>Don't worry about optimization until you have enough data to know for sure what part of your code is a bottleneck.</p>\n\n<p>Some people say RuntimeExceptions shouldn't be declared in the method signature. I say that is a stupid ass opinion, since NumberFormatException is used as a return value for malformed input here. So, in my opinion, you should declare <code>throws NumberFormatException</code> that so that whoever uses your code can prepare for it. Or if you don't want to declare it, catch it and handle errors in other manner.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-18T07:29:40.170", "Id": "417219", "Score": "1", "body": "The structure of the code exactly follows the instructions, therefore handling the collisions outside of the basic `hash` function makes sense to me. It also makes sense to make the `hash` method private since it is not intended to be used by outsiders. (They might forget to handle the collisions.) It would make sense to remember the already taken hashes in a separate class, and that might be the topic for the class 3 weeks later." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-18T22:10:30.353", "Id": "417377", "Score": "0", "body": "Thank you, that's a great review! One question though. When you say \"reading test data from keyboard\", what do you mean? In my head, that means actually typing the student numbers in the terminal. This program takes a text file as input. I believe (I might be wrong) that's how you often do it in the \"real world\", too." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-21T06:30:54.610", "Id": "417755", "Score": "0", "body": "Reading from StdIn implies the data comes from keyboard (or piped from another command). The StdIn wrapper gives me the vibe that your professor is a C/UNIX programmer who tries to work against Java idiomacies. I had one of those in 1997. :) Anyway, Java is not very handy for making tools to be invoked from command line. You'd always need a shell script to hide the JVM, then portability is lost and the whole thing becomes a bit of a mess (IMO). Looking back... learning to write unit tests at school would have been quite beneficial." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-18T06:35:04.927", "Id": "215649", "ParentId": "215630", "Score": "4" } }, { "body": "<p>The very idea of \"if that hash is already taken, use another one\" leads to bugs that are really hard to find later.</p>\n\n<p>It's because your hash function (oh, it is called a function, hopefully in the mathematical sense) no longer has the signature <code>hash(studentNumber)</code> but instead becomes <code>hash(studentNumber, allPreviousStudentNumbers)</code>. This means you get different hashes based on how the students are sorted.</p>\n\n<p>A hash function may by definition produce collisions, and that is fine. Choosing an appropriate hash function that minimizes these collisions is often crucial. In cryptography the commonly used hashes have 256 bits, which makes a collision very unlikely. I hope your teacher plans to discuss these topics in class, as these are important.</p>\n\n<p>Regarding your implementation of the basic <code>hash</code> function. It looks a little more complicated than necessary. An experienced Java programmer will know that there is a predefined <code>String</code> constructor that forms a String from part of a character array. It is <code>new String(charray, start, count)</code>. Using this, the code becomes simple:</p>\n\n<pre><code>private static int hash(char[] studentNo) {\n int first = Integer.parseInt(new String(studentNo, 0, 3));\n int second = Integer.parseInt(new String(studentNo, 3, 3));\n int third = Integer.parseInt(new String(studentNo, 6, 2));\n return first + second + third;\n}\n</code></pre>\n\n<p>This code is almost as simple as you would describe the algorithm to a human, and that's how it should be.</p>\n\n<p>One tricky thing that bites me every time I use the String class: in general there are two ways of referring to a substring, a subarray or a subsequence: either (start, end) or (start, count). Unfortunately Java uses both of them. In the String constructor I used above, it's (start, count), while in the <code>substring</code> method it's (start, end). Even after 20 years of programming in Java, I still have to look at the documentation to know when each of these applies.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-18T07:11:43.233", "Id": "215652", "ParentId": "215630", "Score": "6" } } ]
{ "AcceptedAnswerId": "215649", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-17T20:44:46.557", "Id": "215630", "Score": "6", "Tags": [ "java", "beginner", "algorithm", "hash-map" ], "Title": "Implementation of a simple hash function" }
215630
<p>Recently, I became very interested in a probability practice problem in my textbook for my class. I decided to implement it in code and I think I got most of it implemented. Right now, I'm hoping to see if there is any possible way that I can improve upon it. </p> <p>The question reads as follows:</p> <blockquote> <p>A particle starts at <code>(0, 0)</code> and moves in one unit independent steps with equal probabilities of <span class="math-container">\$\frac{1}{4}\$</span> in each of the four directions: north, south, east, and west. Let S equal the east-west position and T the north-south position after n steps.</p> </blockquote> <p>The code (and more information) can be found <a href="https://github.com/Duke02/WalkingChances" rel="noreferrer">here</a> in the GitHub repository. </p> <p>The code is right here: simulation.py</p> <pre class="lang-py prettyprint-override"><code>""" A particle starts at (0, 0) and moves in one unit independent steps with equal probabilities of 1/4 in each of the four directions: north, south, east, and west. Let S equal the east-west position and T the north-south position after n steps. """ from random import choice import numpy as np from options import Options # Directions (K -&gt; V is initial of direction -&gt; (dx, dy) directions = { 'S': (0, -1), 'N': (0, 1), 'E': (1, 0), 'W': (-1, 0) } def get_direction(): """ Get a random direction. Each direction has a 25% chance of occurring. :returns: the chosen directions changes in x and y """ dirs = "NSEW" return directions[choice(dirs)] def change_position(curr_pos, change_in_pos): """ Updates the current location based on the change in position. :returns: the update position (x, y) """ return curr_pos[0] + change_in_pos[0], curr_pos[1] + change_in_pos[1] def increment_counter(counter, end_pos): """ Increments the provided counter at the given location. :param counter: an numpy ndarray with the number of all ending locations in the simulation. :param end_pos: the ending position of the last round of the simulation. :returns: the updated counter. """ counter[end_pos[1], end_pos[0]] += 1 return counter def get_chance_of_positions(n): """ Gets the approximated chance the particle ends at a given location. Starting location is in the center of the output. :param n: The number of steps the simulation is to take. :returns: the number of iterations and an ndarray with the approximated chance the particle would be at each location. """ # The starting position starts at n, n so that we can pass in the location # into the counter without worrying about negative numbers. starting_pos = (n, n) options = Options.get_options() total_num_of_sims = options.num_of_rounds counter = np.zeros(shape=(2 * n + 1, 2 * n + 1)) for j in range(total_num_of_sims): curr_pos = starting_pos for i in range(n): change_in_pos = get_direction() curr_pos = change_position(curr_pos, change_in_pos) counter = increment_counter(counter, curr_pos) chances = np.round(counter / total_num_of_sims, decimals=n + 1) return total_num_of_sims, chances </code></pre> <p>plot.py</p> <pre class="lang-py prettyprint-override"><code>import matplotlib.pyplot as plt from mpl_toolkits.axes_grid1 import make_axes_locatable from simulation import get_chance_of_positions as get_chance from options import Options def plot(n): """ Saves the plots of the chance of positions from simulation.py :param n: the number of steps the simulation will take. """ num_of_iterations, counter = get_chance(n) fig = plt.figure() ax = fig.add_subplot(111) ax.set_title("Position Color Map (n = {})".format(n)) ax.set_xlabel("Number of iterations: {}".format(int(num_of_iterations))) plt.imshow(counter, cmap=plt.get_cmap('Blues_r')) ax.set_aspect('equal') divider = make_axes_locatable(ax) cax = divider.append_axes("right", size="5%", pad=0.05) plt.colorbar(orientation='vertical', cax=cax) fig.savefig('plots/plot-{:03}.png'.format(n), dpi=fig.dpi) def main(): """ The main function for this file. Makes max_n plots of the simulation. """ options = Options.get_options() for n in range(1, options.num_of_sims + 1): plot(n) if __name__ == "__main__": main() </code></pre> <p>options.py</p> <pre class="lang-py prettyprint-override"><code>import argparse class Options: options = None @staticmethod def generate_options(): arg_parser = argparse.ArgumentParser() arg_parser.add_argument('-N', '--num-of-rounds', type = int, required = False, default = 10**5, help = "The number of rounds to run in each simulation. Should be a big number. Default is 1E5") arg_parser.add_argument('-n', '--num-of-sims', type = int, required = False, default = 10, help = "The number of simulations (and plots) to run. Default is 10.") return arg_parser.parse_args() @staticmethod def get_options(): if Options.options is None: Options.options = Options.generate_options() return Options.options </code></pre> <p>I would love for some recommendations on PEP 8, design, and "Pythonic" code (code that Python expects and will thus be better optimized, such as list comprehension and numpy optimizations, wherever they may be.)</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-20T04:22:26.250", "Id": "417580", "Score": "0", "body": "The `Options` class could be replaced with a function (or 2), since all it has are static methods. My guess is it works ok as written, but it's more complicated than it needs to be. And a minor point, you can leave off the `required=False` parameter; that's the default ." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-20T04:41:31.653", "Id": "417582", "Score": "0", "body": "Oh it's default? Learn something new everyday. Thank you for your help!" } ]
[ { "body": "<ul>\n<li><p>Your <code>directions</code> dictionary is only used by <code>get_direction</code>; why not put it inside the function rather than have it as a global? I'd maybe even put the dict inside <code>get_chance_of_positions()</code> and drop the <code>get_direction()</code> function entirely; it's short, only used once and doesn't require a docstring (its obvious how it works). Put dirs straight into the line as well, rather than creating the <code>dirs</code> variable.</p></li>\n<li><p>I think you've created more functions than you need in the first file. Both <code>change_position()</code> and <code>increment_counter()</code> should probably be merged into your worker function (<code>get_chance_of_positions()</code>). At the moment, the reader has to jump around functions and their docstrings when a commented line in the worker function would be better.</p></li>\n<li><p>When looping, you often use names like <code>n</code>, <code>i</code> or <code>j</code>. Try to be more explicit, e.g. <code>for sim in range(total_num_of_sims)</code>. Sometimes you actually define what the variable does in the docstring; a good name would do this job better.</p></li>\n<li><p>You could use fstrings in your plotting rather than <code>.format()</code>. You shouldn't need to cast to int either.</p></li>\n<li><p>I like ternary operators so I would change <code>get_options</code> to:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>return Options.options if Options.options is not None else Options.generate_options()\n</code></pre></li>\n<li><p>Try to be consistent with how you indent when splitting a line across multiple lines as you have in <code>options.Options.generate_options()</code>. By which I mean:</p>\n\n<p>Instead of: </p>\n\n<pre class=\"lang-py prettyprint-override\"><code>arg_parser.add_argument('-N', '--num-of-rounds',\n type = int,\n required = False,\n default = 10**5 ...)\n</code></pre>\n\n<p>Use:</p>\n\n<pre><code>arg_parser.add_argument('-N', '--num-of-rounds',\n type = int,\n required = False,\n default = 10**5 ...)\n</code></pre>\n\n<p>Or:</p>\n\n<pre><code>arg_parser.add_argument(\n '-N', '--num-of-rounds',\n type = int,\n required = False,\n default = 10**5 ...\n)\n</code></pre></li>\n</ul>\n\n<p>Overall very readable code. Not many comments but the code generally speaks for itself. Try to avoid compartmentalising your code so much, it doesn't always make sense to split things up.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-18T12:46:55.987", "Id": "417283", "Score": "0", "body": "On the ternary operator, wouldn't that require the program to get a new set of arguments each time it's called? Because I want it to keep the same state throughout the program, but it can't do that if it needs new arguments. Thank you for the suggestions nonetheless!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-18T13:21:01.660", "Id": "417293", "Score": "0", "body": "I'm not entirely sure what you mean. the ternary operator I've written is equivalent to the 3 lines in your ```get_options()``` method; It won't change any other logic in your code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-18T13:32:08.063", "Id": "417296", "Score": "0", "body": "Sorry for not being clear. Wouldn't parse_args() in the generate_options() require there to be another set of arguments each time you called generate_options()? Maybe instead of your suggested code (but still with a ternary operator) I could do `Options.options = Options.options if Options.options is not None else generate_options()` then return Options.options?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-18T13:34:46.960", "Id": "417297", "Score": "0", "body": "Oh I understand. Yes you're right, you need to set Options.options first before returning it; I hadn't caught that, sorry." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-18T14:35:04.840", "Id": "417313", "Score": "0", "body": "Don't worry. Thank you for your help!" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-18T12:27:21.040", "Id": "215670", "ParentId": "215632", "Score": "5" } } ]
{ "AcceptedAnswerId": "215670", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-17T22:18:47.347", "Id": "215632", "Score": "8", "Tags": [ "python", "numpy", "statistics", "simulation", "matplotlib" ], "Title": "Python implementation of approximating the chance a particle is at a location after n steps in the cardinal directions" }
215632
<p>I have forked a previous version of my script, critiqued here: <a href="https://codereview.stackexchange.com/questions/214375/generate-public-private-keys-encrypt-decrypt-sign-verify">Generate public/private keys, encrypt, decrypt, sign, verify</a></p> <p>This program allows you to encrypt and decrypt raw files using RSA keys generated by the program. When generating the key pairs, the private key gets protected with aes 256.</p> <p>I'm fond of the prime number theorem so I added my python code back for that instead of soley relying upon gmpy2.</p> <p>The file becomes larger and it takes a long time to decrypt. For 8192 you're looking at 7 minutes a MB to decrypt. 3ish min/MB with 4096, and much faster smaller than that. File size is not ideal with asymmetric.</p> <p>I'm aware that keys aren't purposefully used for data; a key is only typically 256 bits. That's why I wrote the first one. For symmetric speed like in real world application.</p> <p>I wrote this so I can say or feel in my head that my file is TRULY being encrypted with N-bit encryption. For example using a 16000 bit key would provide 1000 bit security. You could cryptolock the borg with that. I know there's absolutely no reason guys. I know 256 is enough. And I know its not ideal for data encryption and is truly ideal for signing and key exchange. I love the math, I wanted to pump up the numbers and send files to the Crypto-Abyss and bring them back again.</p> <p>This was an experiment; my other tool remains my instructional aid as that represents more of a real world implementation.</p> <pre><code>#!/usr/bin/env python3 import os import sys import math import re import hashlib import random import base64 import string import getpass import multiprocessing as mp from Crypto.Cipher import AES from Crypto import Random from Crypto.Protocol.KDF import PBKDF2 #Non builtins from gmpy2 import mpz as mpz from gmpy2 import is_extra_strong_lucas_prp as is_eslprp #Primality testing, extended greatest common divisor and least common multiple def get1prime(keysize): while True: p = random.randrange(1&lt;&lt;(keysize-(keysize//256)), 1&lt;&lt;(keysize+(keysize//256))) if isprime(p): return p def isprime(n): n = mpz(n) if not n &amp; 1: #check if first bit is 1 return False for i in (3,5,7,11): if divmod(n, i)[1] == 0: return False #Fermat if (pow(2, n-1, n)) != 1: return False #MilRab, x**2 = 1 mod P - ERH s = 0 d = n-1 while not d &amp; 1: d&gt;&gt;=1 #shifts binary rep of number right one place, same as dividing by 2^d s+=1 assert(2**s * d == n-1) #Process to find s and d def trial_composite(a): if pow(a, d, n) == 1: return False for i in range(s): if pow(a, 2**i * d, n) == n-1: return False return True for i in range(23): a = random.randrange(2, n-1) if trial_composite(a): return False if is_eslprp(n,1): return True else: return False def modInverse(a, m) : #Euclid's Extended Algorithm m0 = m y = 0 x = 1 while (a &gt; 1) : q = a // m t = m m = divmod(a,m)[1] a = t t = y y = x - q * y x = t if (x &lt; 0) : x = x + m0 return x def lcm(x, y): return (x*y)//math.gcd(x,y) ##AES256CHUNK def get_private_key(password): salt = b"We will know, we must know" kdf = PBKDF2(password, salt, 64, 1000) key = kdf[:32] return key def encryptaes(raw, password): private_key = password raw = pad(raw) iv = Random.new().read(AES.block_size) cipher = AES.new(private_key, AES.MODE_CBC, iv) return base64.b64encode(iv + cipher.encrypt(raw)) def decryptaes(enc, password): private_key = password enc = base64.b64decode(enc) iv = enc[:16] cipher = AES.new(private_key, AES.MODE_CBC, iv) return unpad(cipher.decrypt(enc[16:])) BLOCK_SIZE = 64 #Block is 128 no matter what,this is multiple of 16 pad = lambda s: s + (BLOCK_SIZE - len(s) % BLOCK_SIZE) * chr(BLOCK_SIZE - len(s) % BLOCK_SIZE) unpad = lambda s: s[:-ord(s[len(s) - 1:])] #RSA #Unique and Arbitrary Pub E, a prime. e = 66047 # because I can #e = 65537 def encryptit(e, n, thestring):#for sigining pass d as e thestring = pad(str(thestring)).encode() rbinlist = ['{0:08b}'.format(x) for x in thestring] catstring = '' catstring += rbinlist[0].lstrip('0') del rbinlist[0] for i in rbinlist: catstring += str(i) puttynumber = int(catstring,2) cypherstring = str(pow(mpz(puttynumber), mpz(e), mpz(n))) return cypherstring def decryptit(d, n, cynum):#for signing pass e as d decryptmsg = '' n = int(n) d = int(d) puttynum = pow(mpz(int(cynum)), mpz(d), mpz(n)) puttynum = '{0:08b}'.format(puttynum) while True: if len(puttynum)%8 == 0: break puttynum = '0{0}'.format(puttynum) locs = re.findall('[01]{8}', puttynum) for x in locs: letter = chr(int(x,2)) decryptmsg += letter return unpad(decryptmsg) def chunkitE(exp, N, phatstr): line = phatstr n = len(bin(N))//16 # speed tune newlist = [line[i:i+n] for i in range(0, len(line), n)] #print(newlist) cypherlist = [] for i in newlist: cypherlist.append(encryptit(exp, N, i)) return cypherlist def chunkitD(d, N, phatlistnum): declist = [] for i in phatlistnum: declist.append(decryptit(d, N, i)) return declist def primegenerator(keysize): while True: primes = [] plist = [] for i in range(mp.cpu_count()): plist.append(keysize) workpool = mp.Pool(processes=mp.cpu_count()) reslist = workpool.imap_unordered(get1prime, plist) workpool.close() for res in reslist: if res: primes.append(res) workpool.terminate() break workpool.join() # workpool1 = mp.Pool(processes=mp.cpu_count()) reslist = workpool1.imap_unordered(get1prime, plist) workpool1.close() for res in reslist: if res: primes.append(res) workpool1.terminate() break workpool1.join() return primes #Begin User Flow choice = input(""" ██ ▄█▀▓█████ ▓██ ██▓ ██▀███ ▓██ ██▓ ██▓███ ▄▄▄█████▓ ██▄█▒ ▓█ ▀ ▒██ ██▒▓██ ▒ ██▒ ▒██ ██▒▓██░ ██▒▓ ██▒ ▓▒ ▓███▄░ ▒███ ▒██ ██░▓██ ░▄█ ▒ ▒██ ██░▓██░ ██▓▒▒ ▓██░ ▒░ ▓██ █▄ ▒▓█ ▄ ░ ▐██▓░▒██▀▀█▄ ░ ▐██▓░▒██▄█▓▒ ▒░ ▓██▓ ░ ▒██▒ █▄░▒████▒ ░ ██▒▓░░██▓ ▒██▒ ░ ██▒▓░▒██▒ ░ ░ ▒██▒ ░ ▒ ▒▒ ▓▒░░ ▒░ ░ ██▒▒▒ ░ ▒▓ ░▒▓░ ██▒▒▒ ▒▓▒░ ░ ░ ▒ ░░ ░ ░▒ ▒░ ░ ░ ░ ▓██ ░▒░ ░▒ ░ ▒░ ▓██ ░▒░ ░▒ ░ ░ ░ ░░ ░ ░ ▒ ▒ ░░ ░░ ░ ▒ ▒ ░░ ░░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ Welcome to Dan's Cryptography Concept Program. Generate/Encrypt/Decrypt/Sign RSA++/DSA++/AES/OTP/Double DH key method w SHA256 Choose: A: Generate New Public/Private Key Pair B: Encrypt a File RSA/DSA C: Decrypt a File RSA/DSA =&gt; """) if choice == 'A' or choice == 'a': try: keysize = (int(input("Enter a keysize: "))&gt;&gt;1) except ValueError as a: print('Enter a number\n\n') sys.exit() pubkeyname = input('Input desired public key name: ') pkey = input('Input desired private key name: ') pwkey = get_private_key(getpass.getpass(prompt='Password to protect your private key: ', stream=None)) print('Generating Keys...') primes = primegenerator(keysize) if primes[0] != primes[1]: p, q = primes[0], primes[1] else: print('God hates you') exit() n = p*q cm = lcm(p-1, q-1) print('Computing Private key ...') d = modInverse(e, cm) print('Private Key Size: {} bits'.format(keysize*2)) print('Functional Length of: {}'.format(len(bin((d))))) keystring = encryptaes(str(d).encode('ascii', errors='ignore').decode('utf-8'),pwkey) b64key = bytes.decode(base64.encodestring(bytes(str(hex(n)).encode()))) with open(pkey, 'w') as f1: f1.write(str(n)+'\n') f1.write(bytes.decode(keystring)) with open(pubkeyname, 'w') as f2: f2.write(b64key) print('Complete - {} and {} generated'.format(pubkeyname,pkey)) print('e exponent: {}'.format(str(e))) print(""" -----BEGIN PUBLIC KEY----- {}-----END PUBLIC KEY----- """.format(b64key)) b64privkey = b64key = bytes.decode(base64.encodestring(bytes(str(hex(d)).encode()))) print(""" -----BEGIN PRIVATE KEY----- {}-----END PRIVATE KEY----- """.format(b64privkey)) if choice == 'B' or choice == 'b': lineoutholder = [] pubkeyname = input('Enter the PUBLIC key of the RECIPIENT: ') privkey = input('Enter YOUR Private KEY for signing: ') pwkey = get_private_key(getpass.getpass(prompt='Password for your private key: ', stream=None)) try: with open(pubkeyname, 'r') as f1: pubkey = f1.read() except: print('bad keyname') exit() n = int(bytes.decode(base64.decodestring(bytes(pubkey.encode()))), 16) workfile = input('Enter the file to ENCRYPT: ') outfile = input('Enter filename to WRITE out: ') sha256_hash = hashlib.sha256() try: os.system('pigz -9 {0};mv {0}.gz {0}'.format(workfile)) with open(workfile, 'rb') as f2: wholefile = f2.read() with open(workfile, 'rb') as f2:#open again to clear memory for byte_block in iter(lambda: f2.read(4096),b""): sha256_hash.update(byte_block) HASH = sha256_hash.hexdigest() with open(privkey) as f3: priv = f3.readlines() except Exception as x: print(x) exit() try: d = int(bytes.decode(decryptaes(priv[1], pwkey))) except: print('Bad PW') exit() HASH = [str(ord(i)) for i in HASH] numhash = ''.join(HASH) signature = pow(int(numhash), d, int(priv[0])) plaintext = base64.encodestring(wholefile) cypherlist = chunkitE(e, n, plaintext.decode('ascii')) cyphertext = "X".join(cypherlist) concat = str(str(signature)+'CUTcutCUTcutCUT'+str(cyphertext)) with open(outfile, 'w') as f3: f3.write(concat) os.system('pigz -9 {0};mv {0}.gz {0};rm {1}'.format(outfile, workfile)) print('Wrote to {} ...'.format(outfile)) if choice == 'C' or choice == 'c': dspubkeyname = input('Enter the PUBLIC key of the SENDER: ') try: with open(dspubkeyname, 'r') as f1: pubkey = f1.read() except: print('bad keyname') exit() nsig = int(bytes.decode(base64.decodestring(bytes(pubkey.encode()))), 16) privkey = input('YOUR Private KEY filename to access the data: ') pwkey = get_private_key(getpass.getpass(prompt='Password for your private keyfile: ', stream=None)) workfile = input('Enter the file to DECRYPT: ') outfile = input('Enter the filename to WRITE out: ') print('DECRYPTING') os.system('mv {0} {0}.gz;pigz -d {0}.gz'.format(workfile)) sha256_hash = hashlib.sha256() try: with open(workfile) as f1: lineholder = f1.read().split('CUTcutCUTcutCUT') signature, cyphertext = lineholder[0], lineholder[1] except: print('Bad file name or path') exit() try: with open(privkey) as f2: priv = f2.readlines() except: print('Bad private key location') n = priv[0] try: d = int(bytes.decode(decryptaes(priv[1], pwkey))) except: print('Bad PW') exit() sigdec = pow(int(signature), e, nsig) cypherlist = cyphertext.split("X") plainlist = chunkitD(d, n, cypherlist) decstr = ''.join(plainlist) cleartext = base64.decodestring(bytes(decstr, 'ascii')) with open(outfile, 'wb') as f1: f1.write(cleartext) with open(outfile, 'rb') as f2: for byte_block in iter(lambda: f2.read(4096),b""): sha256_hash.update(byte_block) HASH = sha256_hash.hexdigest() HASH = [str(ord(i)) for i in HASH] numhash = ''.join(HASH) if int(numhash) == int(sigdec): print('Signature Verified') else: print('FAILURE, bad hash. TRANSPORTER ACCIDENT') os.system('mv {0} {0}.gz;pigz -d {0}.gz;rm {1}'.format(outfile, workfile)) print('Wrote out to {} '.format(outfile)) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-18T10:49:00.543", "Id": "417266", "Score": "0", "body": "for the record: 256 is really only enough for transient communication. For less time-critical applications, 2048 bits or even 4096 are not unheard of." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-25T02:21:25.243", "Id": "423109", "Score": "1", "body": "Bad padding (especially for RSA), bad key encryption, magic values, CBC enabling (more) padding oracles, lots of unexplained code, DSA for encryption (?) and many more mistakes (did I see a raw signature in there?). This is good practice crypto code, but there are too many things for me to even look at, and the result is *definitely* not as secure as it should be. KEYRYPT is nice and all, but some kind of documentation of the functions would be nice." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-25T10:15:05.120", "Id": "423161", "Score": "0", "body": "@MaartenBodewes To be fair, CBC padding oracles are unlikely to be relevant in this use case." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-17T23:34:52.910", "Id": "215636", "Score": "2", "Tags": [ "python", "security", "mathematics", "cryptography" ], "Title": "Python RSA/DSA File Cryptography, Key Generation, Key Protection" }
215636
<p>I want to write my snake game procedurally, using as much windows call as I can so as to practice. Looking into GetAsyncKeyState to capture keyboard inputs and play sound functions. Also making a sweet user interface. Fun!</p> <p>Also shout to bytecomb for providing example as to how to traverse the array structure, used his code function to find ptr to element in array!! </p> <p><a href="https://github.com/Evanml2030/Excel-ArrayFunctions" rel="nofollow noreferrer">https://github.com/Evanml2030/Excel-ArrayFunctions</a></p> <p><strong>API CALLS</strong></p> <pre><code>Option Explicit Private Declare PtrSafe Function VarPtrArray Lib "VBE7" Alias "VarPtr" _ (ByRef Var() As Any) As LongPtr Private Declare PtrSafe Sub CopyMemoryI Lib "kernel32.dll" Alias "RtlMoveMemory" _ (ByVal dst As LongPtr, ByVal src As LongPtr, ByVal Length As Long) Private Declare PtrSafe Sub CopyMemoryII Lib "kernel32.dll" Alias "RtlMoveMemory" _ (ByRef dst As SAFEARRAY, ByVal src As LongPtr, ByVal Length As Long) Private Declare PtrSafe Function GetAsyncKeyState Lib "user32" _ (ByVal vKey As Long) As Boolean </code></pre> <p><strong>DATA STRUCTS</strong></p> <pre><code>Private Type SAFEARRAY_BOUND cElements As Long lLbound As Long End Type Private Type SAFEARRAY cDims As Integer fFeatures As Integer cbElements As Long cLocks As Long pvData As LongPtr rgsabound(0) As SAFEARRAY_BOUND End Type Public Type TestStruct Column As Long Row As Long End Type Private Const TESTSTRUCT_BYTELENGTH = 8 </code></pre> <p><strong>FUNCTIONS</strong></p> <pre><code>Public Function ArrayPush(ByRef ArrayOriginal() As TestStruct, ByRef ElementToAdd As TestStruct) As TestStruct() Dim NewLength As Long Dim CopiedBytes As Long Dim NewBytes As Long NewLength = UBound(ArrayOriginal) + 1 ReDim ArrayPush(NewLength) CopiedBytes = NewLength * TESTSTRUCT_BYTELENGTH NewBytes = TESTSTRUCT_BYTELENGTH CopyMemoryI ArrayElementGetPointer(ArrayPush, 0, TESTSTRUCT_BYTELENGTH), ArrayElementGetPointer(ArrayOriginal, 0, TESTSTRUCT_BYTELENGTH), CopiedBytes CopyMemoryI ArrayElementGetPointer(ArrayPush, NewLength, TESTSTRUCT_BYTELENGTH), VarPtr(ElementToAdd), NewBytes End Function Public Function ArrayPop(ByRef ArrayOriginal() As TestStruct) As TestStruct() Dim NewLength As Long Dim CopiedBytes As Long NewLength = UBound(ArrayOriginal) - 1 ReDim ArrayPop(NewLength) CopiedBytes = UBound(ArrayOriginal) * TESTSTRUCT_BYTELENGTH CopyMemoryI ArrayElementGetPointer(ArrayPop, 0, TESTSTRUCT_BYTELENGTH), ArrayElementGetPointer(ArrayOriginal(), 0, TESTSTRUCT_BYTELENGTH), CopiedBytes End Function Public Function ArrayShift(ByRef ArrayOriginal() As TestStruct, ByRef ElementToAdd As TestStruct) As TestStruct() Dim NewLength As Long Dim CopiedBytes As Long Dim NewBytes As Long NewLength = UBound(ArrayOriginal) + 1 ReDim ArrayShift(NewLength) CopiedBytes = NewLength * TESTSTRUCT_BYTELENGTH NewBytes = TESTSTRUCT_BYTELENGTH CopyMemoryI ArrayElementGetPointer(ArrayShift, 1, TESTSTRUCT_BYTELENGTH), ArrayElementGetPointer(ArrayOriginal, 0, TESTSTRUCT_BYTELENGTH), CopiedBytes CopyMemoryI ArrayElementGetPointer(ArrayShift, 0, TESTSTRUCT_BYTELENGTH), VarPtr(ElementToAdd), NewBytes End Function Public Function ArrayUnshift(ByRef ArrayOriginal() As TestStruct) As TestStruct() Dim NewLength As Long Dim CopiedBytes As Long NewLength = UBound(ArrayOriginal) - 1 ReDim ArrayUnshift(NewLength) CopiedBytes = UBound(ArrayOriginal) * TESTSTRUCT_BYTELENGTH CopyMemoryI ArrayElementGetPointer(ArrayUnshift, 0, TESTSTRUCT_BYTELENGTH), ArrayElementGetPointer(ArrayOriginal, 1, TESTSTRUCT_BYTELENGTH), CopiedBytes End Function Public Function ArrayElementGetPointer(ByRef Arr() As TestStruct, ByVal ElementIndex As Long, ByVal ElementByteLength As Long) As LongPtr Dim ptrToArrayVar As LongPtr Dim ptrToSafeArray As LongPtr Dim ptrToArrayData As LongPtr Dim ptrCursor As LongPtr Dim uSAFEARRAY As SAFEARRAY ptrToArrayVar = VarPtrArray(Arr) CopyMemoryI VarPtr(ptrToSafeArray), ptrToArrayVar, 8 CopyMemoryII uSAFEARRAY, ptrToSafeArray, LenB(uSAFEARRAY) ptrToArrayData = uSAFEARRAY.pvData ptrCursor = ptrToArrayData + (ElementIndex * ElementByteLength) ArrayElementGetPointer = ptrCursor End Function </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-19T10:50:22.493", "Id": "417440", "Score": "2", "body": "Quick thing, I've got to ask why you use `Debug.Print` rather than `Debug.Assert` for your tests, the latter will actually let you know when something has gone wrong - rather than relying on your eyes to tell you. Or indeed switch to [Rubberduck](http://rubberduckvba.com/UnitTesting) for some proper *unit tests*" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-19T13:54:09.773", "Id": "417471", "Score": "0", "body": "had never seen .assert used, will explore. thanks. i have rubber duck but have barely gotten the indentation features working, will look into the unit testing. just time!!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-20T13:47:10.340", "Id": "417662", "Score": "0", "body": "by got working i mean understand how to use!" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-18T05:06:30.930", "Id": "215646", "Score": "2", "Tags": [ "array", "vba", "excel", "vectors", "winapi" ], "Title": "VBA array functions: push, pop, shift, unshift" }
215646
<p>This Python script does following activities:</p> <ul> <li><p>clone repo, as provided from the list</p></li> <li><p>creating a new branch "jenkinsMigrate"</p></li> <li><p>rename Jenkinsfile to Jenkinsfile.migrate </p></li> <li><p>push code to GitHub in a new branch.</p></li> </ul> <p>NOTE: credentials were configured already.</p> <pre><code>import git import os import subprocess gitUrl = "https://*****" cwd = "*****" with open("migrateList.txt", "r") as file: for line in file: #configure gitUri for each repository gitUri = gitUrl + line.strip() + ".git" try: global repo repo = git.Repo.clone_from(gitUri, cwd + line.strip()) except: print(" directory already available") os.chdir(cwd + line.strip()) #checkout new branch for migration repo.git.checkout('-b', "jenkinsMigrate") subprocess.call(["git", "mv", "Jenkinsfile", "Jenkinsfile.migrate"]) repo.git.add(update=True) repo.index.commit("jenkins migration") origin = repo.remote(name='origin') #push new branch to github subprocess.call(["git","push", "--set-upstream", "origin", "jenkinsMigrate"]) subprocess.call(["cd", ".."]) </code></pre> <p>Sample text file:</p> <pre><code>$ cat migrateList.txt repo1 repo2 repo3 repo4 </code></pre> <p>This is a working code, but all I am looking for is to maintain consistency in the commands that I use. eg: For some of the git commands that I have used are from gitpython module where as others are invoked with shell commands. Apart from these any other suggestions are welcome.</p> <p>Thanks!</p> <p><strong>UPDATE 1:</strong> python - 2.7.10</p> <p>gitPython module</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-18T09:55:13.790", "Id": "417242", "Score": "1", "body": "What version of Python are you using?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-18T14:49:40.360", "Id": "417314", "Score": "0", "body": "Which `git` pacakage are you using? Probably not [git](https://pypi.org/project/git/), but maybe [GitPython](https://pypi.org/project/GitPython/)?" } ]
[ { "body": "<h1>Review</h1>\n\n<ul>\n<li><p>Stick to the PEP8 style guide</p>\n\n<ol>\n<li>Functions and variables should be <code>snake_case</code></li>\n<li>Constants like <code>gitUrl</code> should be <code>UPPER_SNAKE_CASE</code></li>\n</ol></li>\n<li><p>There is a function for getting the current working directory</p>\n\n<p><code>os.getcwd()</code> Depending on your use case this might be useful</p></li>\n<li><p>If you are using Python3.5+ you should change the <a href=\"https://docs.python.org/3/library/subprocess.html#replacing-older-functions-with-the-subprocess-module\" rel=\"nofollow noreferrer\">older <code>subprocces.call</code> with the newer <code>subprocess.run</code></a></p></li>\n<li><p>Don't catch bare <code>Exceptions</code></p>\n\n<p>If you now what exceptions are going to be caught it is better to define them</p></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-18T10:03:24.577", "Id": "215660", "ParentId": "215647", "Score": "4" } }, { "body": "<h3>Use Python 3.x</h3>\n<p>Python 2.7 will retire in 2020 (end of support) so I'd sugest you migrate your project to a newer version.</p>\n<h3>Other aspects apart from what <a href=\"https://codereview.stackexchange.com/a/215660/61966\">@Ludisposed</a> already mentioned:</h3>\n<ul>\n<li>you're using <code>line.strip()</code> in several places so you might want to assign it to a new variable and use that instead.</li>\n<li>declare the <code>migrateList</code> as a constant at the top of the file (under your imports). That way it will be easier to be modified.</li>\n<li>use <code>f-strings</code> (Python &gt; 3.6). E.g: <code>f&quot;{gitUrl}{line.strip()}.git&quot;</code></li>\n<li>don't use <code>global</code>s. The reason they are bad is that they allow functions/variables to have hidden (as in <em>non-obvious</em> and <em>undeclared</em>) and thus hard to understand side effects. Also, this can lead to Spaghetti code.</li>\n<li><a href=\"https://www.python.org/dev/peps/pep-0008/#comments\" rel=\"nofollow noreferrer\">PEP8</a>: leave an empty space after <code>#</code> in your comments. E.g: <code># configure gitUri for each repository</code></li>\n<li><a href=\"https://www.python.org/dev/peps/pep-0008/#imports\" rel=\"nofollow noreferrer\">PEP8</a>:</li>\n</ul>\n<blockquote>\n<p>Imports should be grouped in the following order:</p>\n<ul>\n<li>Standard library imports.</li>\n<li>Related third party imports.</li>\n<li>Local application/library specific imports.</li>\n<li><strong>You should put a blank line between each group of imports.</strong></li>\n</ul>\n</blockquote>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-19T08:17:23.050", "Id": "215730", "ParentId": "215647", "Score": "2" } } ]
{ "AcceptedAnswerId": "215660", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-18T05:47:12.117", "Id": "215647", "Score": "4", "Tags": [ "python", "python-2.x", "git" ], "Title": "automating to push changes to github for multiple repos using python" }
215647
<p>I have a Vue.js computed property as follows.</p> <pre><code>odds() { if(this.course &amp;&amp; this.time &amp;&amp; this.runner) { let race = this.data.events.runners.filter(item =&gt; item.course === this.course &amp;&amp; item.time === this.time) let runner = race[0].data.filter(item =&gt; item.name === this.runner) return runner[0].odds } else { return false } } </code></pre> <p>Although it returns the expected value I think it looks dirty. Can any one suggest best way to write this code.</p> <p>Sample JSON is as follows.</p> <pre><code>{ "courses": [{ "type": "horses", "course": "Exeter" }], "runners": [{ "course": "Exeter", "time": "14:10", "data": [{ "number": "1", "name": "White Lilac", "odds": "6\/1" }, { "number": "2", "name": "Sauvignon", "odds": "5\/1" }, { "number": "3", "name": "Foxy Lass", "odds": "33\/1" }, { "number": "4", "name": "Hot Ryan", "odds": "8\/1" }, { "number": "5", "name": "Arqalina", "odds": "11\/8" }, { "number": "6", "name": "Presenting Lucina", "odds": "14\/1" }, { "number": "7", "name": "Persistantprincess", "odds": "12\/1" }, { "number": "8", "name": "Windy Bottom", "odds": "20\/1" }, { "number": "9", "name": "Shotgun Sally", "odds": "33\/1" }, { "number": "10", "name": "Rule The Ocean", "odds": "9\/1" }, { "number": "11", "name": "Avithos", "odds": "12\/1" }, { "number": "12", "name": "Monet Moor", "odds": "16\/1" }] }]} </code></pre> <p>I would like to know if there is a much better way to do this. Thanks in advance.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-18T10:10:31.563", "Id": "417249", "Score": "2", "body": "Welcome to Code Review. Can you provide some more context about what this code is supposed to be doing? Also what is `this.course`, `this.time` and `this.runner` ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-18T14:32:01.190", "Id": "417312", "Score": "0", "body": "@SimonForsberg this property returns the odds of the horse when 3 select boxes Course, Race time and Runner are selected. Basically i want to return the odds of the selected runner in the Runner select box." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-18T07:03:31.737", "Id": "215651", "Score": "2", "Tags": [ "javascript", "promise", "vue.js" ], "Title": "Vue.js Computed Property Filtering" }
215651
<p>I want to convert an integer to a perfect square by multiplying it by some number. That number is the product of all the prime factors of the number which not appear an even number of times. Example 12 = 2 x 2 x 3; 2 appears twice (even number of times) but 3 just once (odd number of times), so the number I need to multiply 12 by to get a perfect square is 3. And in fact 12 x 3 = 36 = 6 * 6.</p> <p>I converted my code to Haskell and would like to know what suggestions you have.</p> <pre><code>import Data.List (group) toPerfectSquare :: Int -&gt; Int toPerfectSquare n = product . map (\(x:_) -&gt; x) . filter (not . even . length) . group $ primefactors n primefactors :: Int -&gt; [Int] primefactors n = prmfctrs' n 2 [3,5..] where prmfctrs' m d ds | m &lt; 2 = [1] | m &lt; d^2 = [m] | r == 0 = d : prmfctrs' q d ds | otherwise = prmfctrs' m (head ds) (tail ds) where (q, r) = quotRem m d </code></pre> <p>Sorry about the naming, I'm bad at giving names.</p> <p>One particular doubt I have is in the use of <code>$</code> in <code>toPerfectSquare</code>, that I first used <code>.</code> but it didn't work and I needed to use parenthesis. Why? And is it usual to have that many compositions in one line?</p>
[]
[ { "body": "<p>We can replace some custom functions or constructs by standard library ones:</p>\n\n<ul>\n<li><code>\\(x:_) -&gt; x</code> is called <code>head</code></li>\n<li><code>not . even</code> is called <code>odd</code></li>\n</ul>\n\n<p>Next, <code>1</code> is not a prime, and <code>1</code> does not have a prime factorization. Since <code>product []</code> yields <code>1</code>, we can use <code>[]</code> instead in <code>prmfctrs'</code>.</p>\n\n<p>The worker <code>prmfctrs'</code> is a mouthful. Workers are usually called the same as their context (but with an apostrophe, so <code>primefactors'</code>) or short names like <code>go</code>.</p>\n\n<p>And last but not least, we can use <code>@</code> bindings to pattern match on the <code>head</code>, <code>tail</code> and the whole list at once.</p>\n\n<p>If we apply those suggestions, we get</p>\n\n<pre><code>import Data.List (group)\n\ntoPerfectSquare :: Int -&gt; Int\ntoPerfectSquare n = product . map head . filter (odd . length) . group $ primefactors n\n\nprimefactors :: Int -&gt; [Int]\nprimefactors n = go n 2 [3,5..]\n where\n go m d ds@(p:ps) | m &lt; 2 = []\n | m &lt; d^2 = [m]\n | r == 0 = d : go q d ds\n | otherwise = go m p ps\n where (q, r) = quotRem m d\n</code></pre>\n\n<p>In theory, we can even get rid of a parameter in <code>go</code>, namely the <code>d</code>, so that we always just look at the list of the divisors:</p>\n\n<pre><code>import Data.List (group)\n\ntoPerfectSquare :: Int -&gt; Int\ntoPerfectSquare n = product . map head . filter (odd . length) . group $ primefactors n\n\nprimefactors :: Int -&gt; [Int]\nprimefactors n = go n $ 2 : [3,5..]\n where\n go m dss@(d:ds) | m &lt; 2 = []\n | m &lt; d^2 = [m]\n | r == 0 = d : go q dss\n | otherwise = go m ds\n where (q, r) = m `quotRem` d\n</code></pre>\n\n<p>We could also introduce another function <span class=\"math-container\">\\$f\\$</span>, so that for any <span class=\"math-container\">\\$a,b \\in \\mathbb N\\$</span> we get a pair <span class=\"math-container\">\\$(n,y) \\in \\mathbb N^2\\$</span> such that</p>\n\n<p><span class=\"math-container\">$$\na^n y = b\n$$</span>\nIf we had that function, we could write use it to check easily whether the power of a given factor is even or odd. However, that function and its use in <code>toPerfectSquare</code> are left as an exercise.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-18T12:32:16.050", "Id": "417282", "Score": "0", "body": "You mean that function `f` as an optimization to the algorithm or to clean a bit the code? My problem is that I cannot “think in Haskell”, so I'm converting code I already have in other language to learn more about how to program in Haskell. By the way, I think you removed `map` and you wanted to keep `map head` (almost everytime a function exists, but it's difficult to know it exists, so many functions to learn, but I will keep learning to use Hoogle). And nice to know `product []` gives 1 (I didn't kno, which is precisely why I used `[1]` instead of `[]`)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-18T14:04:54.887", "Id": "417306", "Score": "0", "body": "@Manuel Yeah, wanted to use `map head`, sorry. The function `f` is both a clean-up, as well as an optimization, as you can get rid of the list of primefactors. However, it's not necessary to solve this and is therefore just an optional exercise." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-18T21:06:58.510", "Id": "417369", "Score": "0", "body": "I thought a bit and I think it does solve the problem more concisely, but I couldn't figure how to do it in Haskell directly (I would need to write in other language and then try to translate), so I will leave it for now. Thanks again for the answer! By the way at first i used `sqrt m < d` but changed to `m < d^2` because I thought it would be more efficient, is that the case?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-18T21:11:20.737", "Id": "417370", "Score": "0", "body": "Usually yes. `sqrt` is a very expensive operation in most programming languages, whereas multiplication is a single assembly instruction as long as we're using native CPU integers. However, Haskell being Haskell, `sqrt` doesn't even work on `Int`, as `sqrt` only works on floating point numbers. So `m < d*d` was not only more efficient, but more idiomatic Haskell in that regard :)" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-18T10:52:28.903", "Id": "215664", "ParentId": "215654", "Score": "7" } } ]
{ "AcceptedAnswerId": "215664", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-18T08:54:28.153", "Id": "215654", "Score": "8", "Tags": [ "haskell", "primes", "integer" ], "Title": "Prime factors and perfect square" }
215654
<p>An exam requires me to create a program for an interactive board for an auction:</p> <blockquote> <p>An auction company has an interactive auction board at their sale rooms, which allows buyers to place bids at any time during the auction. Before the auction starts, the sellers place their items in the sale room with a unique number attached to each item (item number). The following details about each item need to be set up on the interactive auction board system: item number, number of bids, description and reserve price. The number of bids is initially set to zero. During the auction, buyers can look at the items in the sale room and then place a bid on the interactive auction board at the sale room. Each buyer is given a unique number for identification (buyer number). All the buyer needs to do is enter their buyer number, the item number and their bid. Their bid must be greater than any existing bids. At the end of the auction, the company checks all the items and marks those that have bids greater than the reserve as sold. Any items sold will incur a fee of 10% of the final bid to be paid to the auction company. Write and test a program or programs for the auction company.</p> <ul> <li>Your program or programs must include appropriate prompts for the entry of data, data must be validated on entry.</li> <li>Error messages and other output need to be set out clearly and understandably.</li> <li>All variables, constants and other identifiers must have meaningful names.</li> </ul> <p>You will need to complete these three tasks. Each task must be fully tested.</p> <h3>Task 1 – Auction set up.</h3> <p>For every item in the auction the item number, description and the reserve price should be recorded. The number of bids is set to zero. There must be at least 10 items in the auction.</p> <h3>Task 2 – Buyer bids.</h3> <p>A buyer should be able to find an item and view the item number, description and the current highest bid. A buyer can then enter their buyer number and bid, which must be higher than any previously recorded bids. Every time a new bid is recorded the number of bids for that item is increased by one. Buyers can bid for an item many times and they can bid for many items.</p> <h3>Task 3 – At the end of the auction.</h3> <p>Using the results from TASK 2, identify items that have reached their reserve price, mark them as sold, calculate 10% of the final bid as the auction company fee and add this to the total fee for all sold items. Display this total fee. Display the item number and final bid for all the items with bids that have not reached their reserve price. Display the item number of any items that have received no bids. Display the number of items sold, the number of items that did not meet the reserve price and the number of items with no bids.</p> </blockquote> <p>Here's my solution in VB.net console. How could I have done it better?</p> <pre><code>'Task 1' Dim enteries, d As Integer d = 1 Console.WriteLine(&quot;How many total entries?&quot;) enteries = Console.ReadLine While enteries &lt; 10 Console.WriteLine(&quot;Number of enteries should be greater than 10, please try again&quot;) enteries = Console.ReadLine End While Dim item_num(enteries), num_bids(enteries) As Integer Dim reserve_price(enteries) As Single Dim description(enteries) As String For c = 1 To enteries Console.WriteLine(&quot;Enter item description&quot;) description(c) = Console.ReadLine Console.WriteLine(&quot;Enter the item number&quot;) item_num(c) = Console.ReadLine Console.WriteLine(&quot;Enter reserve price&quot;) 'The reserve price is the minimum amount the seller is willing to accept' reserve_price(c) = Console.ReadLine num_bids(c) = 0 Next For c = 1 To enteries For d = 1 To enteries - 1 If item_num(d) = item_num(d + 1) Then While item_num(d) = item_num(d + 1) Console.Write(&quot;Value &quot; &amp; d + 1) Console.WriteLine(&quot; Is duplicate, enter a new value&quot;) item_num(d + 1) = Console.ReadLine End While End If Next Next 'Task 2' Dim buyer_num(enteries) As Integer Dim bid(enteries), highest(enteries) As Single Dim extra_bids As String For c = 1 To enteries Console.WriteLine(&quot;Enter number of the item from 1-&quot; &amp; enteries) d = Console.ReadLine Console.WriteLine(&quot;Product is: &quot; &amp; description(d)) Console.WriteLine(&quot;Item number is: &quot; &amp; item_num(d)) Console.WriteLine(&quot;Current highest bid: &quot; &amp; bid(d)) Console.WriteLine(&quot;Enter buyer number&quot;) buyer_num(d) = Console.ReadLine Console.WriteLine(&quot;Enter your bid&quot;) bid(d) = Console.ReadLine If bid(d) &gt; highest(d) Then highest(d) = bid(d) End If num_bids(d) = num_bids(d) + 1 Console.WriteLine(&quot;Make more bids? Enter Yes/No&quot;) extra_bids = Console.ReadLine While extra_bids = &quot;Yes&quot; Console.WriteLine(&quot;Current highest bid is &quot; &amp; highest(c)) Console.WriteLine(&quot;Enter bid&quot;) bid(d) = Console.ReadLine If bid(d) &gt; highest(d) Then highest(d) = bid(d) Else While bid(d) &lt; highest(d) Console.WriteLine(&quot;Bid cannot be less than the previous bid, please enter a higher value&quot;) bid(d) = Console.ReadLine End While highest(d) = bid(d) End If Console.WriteLine(&quot;Make more bids? Enter Yes/No&quot;) extra_bids = Console.ReadLine End While Next 'Task 3' Dim final_price(enteries), comp_fee(enteries), total_fee As Single Dim items_sold, not_sold, no_bids As Integer Dim sold_status(enteries) As String For c = 1 To enteries If highest(c) &gt;= reserve_price(c) Then sold_status(enteries) = &quot;Sold&quot; comp_fee(c) = 10 / 100 * highest(c) final_price(c) = highest(c) + comp_fee(c) total_fee = total_fee + final_price(c) items_sold = items_sold + 1 Else not_sold = not_sold + 1 Console.WriteLine(item_num(c) &amp; &quot; Did not reach reserve price&quot;) Console.WriteLine(&quot;Their final bid was &quot; &amp; highest(c)) End If If num_bids(c) = 0 Then Console.WriteLine(item_num(c) &amp; &quot;recieved no bids&quot;) no_bids = no_bids + 1 End If Next Console.WriteLine(&quot;Total fee for all sold items is &quot; &amp; total_fee) Console.WriteLine(&quot;Number of items sold = &quot; &amp; items_sold) Console.WriteLine(&quot;Number of items not sold = &quot; &amp; not_sold) Console.WriteLine(&quot;Number of items with no bids = &quot; &amp; no_bids) Console.ReadKey() </code></pre>
[]
[ { "body": "<p>Okay, so I'll admit I am a little bit rusty right now on some best practices, but I'm doing this anyway.</p>\n\n<p>First, this whole thing needs to be wrapped in a <code>sub</code> I assume. </p>\n\n<p>Second, when I read the description of what you need to create, it screams at me \"<strong>objects!</strong>\" - what I mean is that you have an interactive app that needs to keep track of auction items. Each item has several attributes. Sounds like the basis for some <em>object-oriented design</em> doesn't it? e.g.</p>\n\n<pre><code>Public Class AuctionItem\n Public Property description As String\n Public Property reservePrice As Integer\n Public Property numberOfBids As Integer\n Public Property currentBid As Integer\n Public Property currentBidder As Integer\nEnd Class\n</code></pre>\n\n<p>So right out of the gate, now you have a structure for the items at the auction, before doing anything else. And each item has properties. And now you just handle a list of the room you're talking about</p>\n\n<pre><code>Dim firstRoom As New List(Of AuctionItem)\n</code></pre>\n\n<p>Ignoring the minimum entry requirement, you could simply create your auction on the fly -</p>\n\n<pre><code> Dim firstRoom As New List(Of AuctionItem)\n Dim numberOfEntries As Integer\n Console.WriteLine(\"How many total entries?\")\n numberOfEntries = Console.ReadLine\n For i As Integer = 1 To numberOfEntries\n firstRoom.Add(New AuctionItem)\n Console.WriteLine(\"Enter item description\")\n firstRoom(i).description = Console.ReadLine\n Console.WriteLine(\"Enter reserve price\") 'The reserve price is the minimum amount the seller is willing to accept' \n firstRoom(i).reservePrice = Console.ReadLine\n Next\n</code></pre>\n\n<p>See what I mean? Now <strong>you</strong> assign the item number and when a bidder wants to bid on it, you just access that object and get what you need.</p>\n\n<p>Another small thing I noted is that you aren't type checking entries - say I want to say my item number is \"two\" - the program throws an unhandled error and crashes. You expect an integer, so you need to check you receive an integer.</p>\n\n<p>Sorry, that's all I got right now.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-23T06:03:01.480", "Id": "216032", "ParentId": "215657", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-18T09:19:35.327", "Id": "215657", "Score": "2", "Tags": [ "vb.net" ], "Title": "Interactive auction board" }
215657
<p>Link: <a href="https://www.hackerrank.com/contests/hackerrank-all-womens-codesprint-2019/challenges/name-the-product/" rel="nofollow noreferrer">https://www.hackerrank.com/contests/hackerrank-all-womens-codesprint-2019/challenges/name-the-product/</a> </p> <h2>Problem</h2> <blockquote> <p>You are contesting to name a new product in your company given the following conditions:</p> <p>You are given an array of <span class="math-container">\$n\$</span> different names, <span class="math-container">\$names\$</span>, where <span class="math-container">\$names_i\$</span> denotes the <span class="math-container">\$i^{th}\$</span> name and all the names are of length <span class="math-container">\$5\$</span>. The distance between any two names is the number of positions in which the characters in these names differ. For example, "bubby" and "bunny" differ in two positions.</p> <p>You have to choose a name such that the sum of differences of all names in <span class="math-container">\$names\$</span> with the chosen name is maximal. In order to win the contest, give the new product this chosen name.</p> <p>Note: If there are many such names chose the lexicographically largest one.</p> <p>Take for example, names = ["bubby", "bunny", "berry"], with length <span class="math-container">\$n = 3\$</span>. Then, the name that you should choose is "zzzzz" as this name has no common character with any name in the names list and is also lexicographically the largest.</p> <h3>Function Description</h3> <p>Complete the productName function in the editor below. It should return the lexigraphically largest string of length whose sum of differences with all the names is maximal.</p> <p><em>productName</em> has the following parameter(s):</p> <p>names: array of <span class="math-container">\$n\$</span> names</p> <h3>Input Format</h3> <ul> <li>The first line contains an integer, <span class="math-container">\$n\$</span>, denoting the number of elements in <span class="math-container">\$names\$</span>.</li> <li>Each line <span class="math-container">\$i\$</span> of the <span class="math-container">\$n\$</span> subsequent lines (where <span class="math-container">\$0 \le i \le n\$</span>) contains a string describing <span class="math-container">\$names_i\$</span>.</li> </ul> <h3>Constraints</h3> <ul> <li><span class="math-container">\$1 \le n \le 10^5\$</span></li> <li>All characters in the names are lowercase English alphabets.</li> <li>Each name is of length <span class="math-container">\$5\$</span>.</li> </ul> <h3>Output Format</h3> <ul> <li>The output should contain the lexigraphically largest string of length whose sum of differences with all the names is maximal.</li> </ul> <h3>Sample Input 0</h3> <pre><code>3 bubby bunny berry </code></pre> <h3>Sample Output 0</h3> <pre><code>zzzzz </code></pre> <h3>Explanation 0</h3> <ul> <li>Difference between <span class="math-container">\$names_0\$</span>, bubby, and zzzzz is <span class="math-container">\$5\$</span>.</li> <li>Difference between <span class="math-container">\$names_1\$</span>, bunny, and zzzzz is <span class="math-container">\$5\$</span>.</li> <li>Difference between <span class="math-container">\$names_2\$</span>, berry, and zzzzz is <span class="math-container">\$5\$</span>. So, total difference is 15, which is maximal.</li> </ul> <h3>Sample Input 1</h3> <pre><code>3 ready stedy zebra </code></pre> <h3>Sample Output 1</h3> <pre><code>yzzzz </code></pre> <h3>Explanation 1</h3> <ul> <li>Difference between <span class="math-container">\$names_0\$</span>, ready, and yzzzz is <span class="math-container">\$5\$</span>.</li> <li>Difference between <span class="math-container">\$names_1\$</span>, stedy, and yzzzz is <span class="math-container">\$5\$</span>.</li> <li>Difference between <span class="math-container">\$names_2\$</span>, zebra, and yzzzz is <span class="math-container">\$5\$</span>. So, total differce is 15, which is maximal. <hr></li> </ul> </blockquote> <p>I would strip the extraneous parts from my solution: </p> <pre class="lang-py prettyprint-override"><code>import math, os, random, re, sys from collections import defaultdict as dd, Counter as count alphabet = "abcdefghijklmnopqrstuvwxyz" def productName(names): charmap = [dd(lambda: 0, count(name[i] for name in names)) for i in range(5)] return "".join(max(alphabet, key=lambda x: (-charmap[i][x], x)) for i in range(5)) </code></pre> <p>I'm concerned with adhering to best practices and maximising performance. </p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-18T10:38:36.523", "Id": "417258", "Score": "0", "body": "Meta comment, writing up the question took me much more time than actually solving the question due to the copious amounts of formatting involved. I would likely submit more questions from this particular codesprint, would leaving out the problem description and merely dropping the link be acceptable?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-18T10:41:04.030", "Id": "417261", "Score": "12", "body": "Absolutely not." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-18T10:43:57.323", "Id": "417262", "Score": "3", "body": "See [Can I include problem statements when posting exercise solutions to Code Review?](//codereview.meta.stackexchange.com/q/8827). In short, a link alone is not sufficient (the question must be complete in itself), but you may need to write the requirements *in your own words* - unless you have specific permission to copy and republish." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-18T10:46:10.930", "Id": "417265", "Score": "0", "body": "I think online programming challenges are by default public domain?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-18T10:49:56.413", "Id": "417267", "Score": "0", "body": "I'd have thought that unlikely - you'll need to check with the specific site whether its license allows re-use of the challenge text here. Remember that Stack Exchange requires you to license your post using CC By-SA 3.0 with Attribution Required - if that contradicts your other obligations, then your question is at risk of being deleted." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-18T12:52:41.680", "Id": "417284", "Score": "3", "body": "@TobySpeight Although it's unlikely to be deleted by the community, since the community is explicitly not tasked with legal enforcement. That's SE-employees territory, it goes even beyond the moderators." } ]
[ { "body": "<h2>Imports</h2>\n<pre><code>import math, os, random, re, sys\nfrom collections import defaultdict as dd, Counter as count\n</code></pre>\n<p>Seriously, don't do this. It may be useful to read <a href=\"https://www.python.org/dev/peps/pep-0008/#imports\" rel=\"noreferrer\">PEP8 regarding imports</a> again.</p>\n<ul>\n<li><p>Imports should be on separate lines.</p>\n</li>\n<li><p>Why do <code>Counter as count</code>? It impairs readability.</p>\n<p>Especially in larger scripts, every Python dev knows <code>Counter</code>, but <code>count</code> could be a random variable and is easy to be overshadowed.</p>\n</li>\n<li><p>You don't use all of the imported modules; just remove them if you don't need them.</p>\n</li>\n<li>\n<pre><code> alphabet = &quot;abcdefghijklmnopqrstuvwxyz&quot;\n</code></pre>\n<p>Here you missed something that is in the standard lib: <a href=\"https://docs.python.org/2/library/string.html#string.ascii_lowercase\" rel=\"noreferrer\"><code>from string import ascii_lowercase</code></a></p>\n</li>\n</ul>\n<h2>Misc</h2>\n<ul>\n<li><p>This <code>dd(lambda: 0, ...</code> adds no value</p>\n<p>Counter is already a dictionary with <code>default value 0</code> just remove that part</p>\n</li>\n<li><p>Magic numbers</p>\n<p><code>5</code> is a Magic number, you should define it as a CONSTANT:</p>\n<pre><code> NAME_LENGTH = 5\n</code></pre>\n</li>\n</ul>\n<p>The rest looks good!</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-18T18:28:24.973", "Id": "417348", "Score": "6", "body": "May as well avoid aliasing `defaultdict`, too. Who the heck is going to know what `dd` is if they skip past the imports?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-18T18:59:56.000", "Id": "417354", "Score": "0", "body": "They're fault for skipping past the imports IMO. *shrugs*" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-18T19:03:36.493", "Id": "417355", "Score": "5", "body": "Respectfully no, the same advice goes for aliasing `defaultdict`. In this small example it doesn't matter, and it's easy to read, but when you are working on larger projects this can be a true pain in the ***" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-18T19:51:08.350", "Id": "417359", "Score": "1", "body": "@jpmc26 Yeah I thought it meant [Disk Destroyer](https://en.wikipedia.org/wiki/Dd_%28Unix%29) at first." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-18T20:25:55.593", "Id": "417363", "Score": "6", "body": "@TobiAlafin You need to learn the [Principle of Least Astonishment](https://www.reddit.com/r/ProgrammerHumor/comments/7ym547/the_only_valid_measurement_of_code_quality_is/). The biggest thing you should do to make your code readable and maintainable is to avoid doing things that are surprising. Aliasing something that's referenced exactly *once* is the code is weird. It's surprising. So is abbreviating names from the standard library. Don't do things that will surprise other developers. Do normal things. Great code is so obvious, it makes you think you could have easily thought of it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-18T20:36:50.407", "Id": "417365", "Score": "3", "body": "@jpmc26 That's a solid principle,.. I will use this in future code reviews :)" } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-18T11:15:09.913", "Id": "215665", "ParentId": "215662", "Score": "15" } } ]
{ "AcceptedAnswerId": "215665", "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-18T10:37:18.507", "Id": "215662", "Score": "4", "Tags": [ "python", "performance", "beginner", "programming-challenge" ], "Title": "Hackerrank All Women's Codesprint 2019: Name the Product" }
215662
<p>I have a method that works perfectly well and does what it's supposed to, albeit a little slow (30 - 40 seconds). I would like to be able to speed it up or at least make it more efficient, any ideas please?</p> <p>The purpose is to generate a list of which customers are buying the top requested (topN) lines from a supplier. The first part gets a list of products from the requested supplier, the second part works out which products are the best selling by distribution and then sales and then adds those products to an array and they form the column names for the datatable. The last part loops all of the customer accounts and puts yes or no in the column if they have bought it in the last 3 months. I hope that makes sense. </p> <pre><code>private void CustomersBuyingRange(string supplier, int topN) { // Get a list of products from a supplier. string[] products = productDetails .Where(x =&gt; x.SupplierID == supplier.ToUpper()) .Select(x =&gt; x.ProductCode).ToArray(); // Rank the products by distribution and then by sales, // then add the required amount to an array. string[] topSellers = detailedOrderLines .Where(x =&gt; products.Contains(x.ProductCode)) .GroupBy(x =&gt; x.ProductCode) .Select(x =&gt; new { x.FirstOrDefault().ProductCode, DeliveredQty = x.Sum(p =&gt; p.DeliveredQty), Distribution = x.Select(c =&gt; c.CustomerID).Distinct().Count() }) .OrderByDescending(x =&gt; x.Distribution) .ThenByDescending(x =&gt; x.DeliveredQty) .Take(topN) .Select(a =&gt; a.ProductCode).ToArray(); DataTable table = new DataTable("Customers"); table.Columns.Add("CustomerID", typeof(string)); table.Columns.Add("Customer", typeof(string)); table.Columns.Add("AccountManager", typeof(string)); // Add the columns with the products. foreach (string product in topSellers) { table.Columns.Add(product, typeof(string)); } // We only want customers that have had an order in the last 3 months. var customers = customerDetails .Where(x =&gt; x.LastInvoiceDate &gt; DateTime.Now.AddMonths(-3).Date) .OrderBy(x =&gt; x.CustomerName) .ToList(); foreach (var customer in customers) { DataRow row = table.NewRow(); row["CustomerID"] = customer.CustomerID; row["Customer"] = customer.CustomerName; row["AccountManager"] = customer.AccountManager; for (int i = 0; i &lt; topN; i++) { row[topSellers[i]] = detailedOrderLines .Any(x =&gt; x.CustomerID == customer.CustomerID &amp;&amp; x.ProductCode == topSellers[i] &amp;&amp; x.InvoiceDate &gt; DateTime.Now.AddMonths(-3).Date ) ? "Yes" : "No"; } table.Rows.Add(row); } Export.ExportToExcel(table, true); } </code></pre> <p>There are roughly 3000 customers.<br> Any advise would be greatly appreciated.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-18T13:15:26.020", "Id": "417292", "Score": "1", "body": "The \"easy\" fix here is to not do this in your client, but in the database... Unfortunately that doesn't make for a great answer, so I'll just leave it as a comment :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-18T13:25:44.690", "Id": "417294", "Score": "4", "body": "Welcome to Code Review! The current question title, which states your concerns about the code, is too general to be useful here. Please [edit] to the site standard, which is for the title to simply state **the task accomplished by the code**. Please see [How to get the best value out of Code Review: Asking Questions](//codereview.meta.stackexchange.com/q/2436) for guidance on writing good question titles." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-19T11:52:58.963", "Id": "417455", "Score": "0", "body": "What data types are `productDetails`, `detailedOrderLines` and `customerDetails` and what type of objects do they contain and how do you instantiate them?" } ]
[ { "body": "<p>As said in a comment this may be done better and faster with an SQL script depending on how the involved data sets are created, but below are some optimization suggestions.</p>\n\n<hr>\n\n<p>You should maybe consider some input check:</p>\n\n<pre><code>private void CustomersBuyingRange(string supplier, int topN)\n{\n if (string.IsNullOrWhiteSpace(supplier)) return;\n if (topN &lt;= 0) throw new ArgumentOutOfRangeException(nameof(topN));\n</code></pre>\n\n<hr>\n\n<p><strong>Optimizations:</strong></p>\n\n<p>1)</p>\n\n<blockquote>\n<pre><code> // Get a list of products from a supplier.\n string[] products = productDetails\n .Where(x =&gt; x.SupplierID == supplier.ToUpper())\n .Select(x =&gt; x.ProductCode).ToArray();\n</code></pre>\n</blockquote>\n\n<p><code>supplier.ToUpper()</code> is called repeatedly for every element in the vector. Consider to do it once:</p>\n\n<pre><code> supplier = supplier.ToUpper();\n\n // Get a list of products from a supplier.\n var products = productDetails\n .Where(x =&gt; x.SupplierID == supplier)\n .Select(x =&gt; x.ProductCode);\n</code></pre>\n\n<p>As shown, there is also no need to populate an array with the result here.</p>\n\n<hr>\n\n<p>2)</p>\n\n<blockquote>\n<pre><code> var customers = customerDetails\n .Where(x =&gt; x.LastInvoiceDate &gt; DateTime.Now.AddMonths(-3).Date)\n .OrderBy(x =&gt; x.CustomerName)\n .ToList();\n</code></pre>\n</blockquote>\n\n<p>Again you create a new <code>DateTime</code> object for each customer you evaluate in the <code>Where()</code> call. Consider to create that date once:</p>\n\n<pre><code> DateTime minDate = DateTime.Now.AddMonths(-3).Date;\n // We only want customers that have had an order in the last 3 months.\n var customers = customerDetails\n .Where(x =&gt; x.LastInvoiceDate &gt; minDate)\n .OrderBy(x =&gt; x.CustomerName);\n</code></pre>\n\n<p>You can then reuse it in the last loop too.</p>\n\n<hr>\n\n<p>3)</p>\n\n<blockquote>\n<pre><code> for (int i = 0; i &lt; topN; i++)\n {\n row[topSellers[i]] = detailedOrderLines\n .Any(x =&gt; x.CustomerID == customer.CustomerID &amp;&amp;\n x.ProductCode == topSellers[i] &amp;&amp;\n x.InvoiceDate &gt; DateTime.Now.AddMonths(-3).Date\n ) ? \"Yes\" : \"No\";\n }\n</code></pre>\n</blockquote>\n\n<p>Here you should be able to run a <code>foreach</code> loop instead:</p>\n\n<pre><code> foreach (var topSeller in topSellers)\n {\n row[topSeller] = detailedOrderLines\n .Any(x =&gt; x.CustomerID == customer.CustomerID &amp;&amp;\n x.ProductCode == topSeller &amp;&amp;\n x.InvoiceDate &gt; minDate) ? \"Yes\" : \"No\";\n }\n</code></pre>\n\n<hr>\n\n<p>4)</p>\n\n<blockquote>\n<pre><code>foreach (var customer in customers)\n {\n DataRow row = table.NewRow();\n row[\"CustomerID\"] = customer.CustomerID;\n row[\"Customer\"] = customer.CustomerName;\n row[\"AccountManager\"] = customer.AccountManager;\n for (int i = 0; i &lt; topN; i++)\n {\n row[topSellers[i]] = detailedOrderLines\n .Any(x =&gt; x.CustomerID == customer.CustomerID &amp;&amp;\n x.ProductCode == topSellers[i] &amp;&amp;\n x.InvoiceDate &gt; DateTime.Now.AddMonths(-3).Date\n ) ? \"Yes\" : \"No\";\n }\n table.Rows.Add(row);\n }\n</code></pre>\n</blockquote>\n\n<p>Here you keep require the entire <code>detailedOrderLines</code> although you previously when creating the <code>topSellers</code> actually grouped those by <code>ProductCode</code>. So if you instead of selecting <code>topSellers</code> as <code>strings</code> select them as anonymous objects like:</p>\n\n<pre><code> // Rank the products by distribution and then by sales,\n // then add the required amount to an array.\n var topProducts = detailedOrderLines\n .Where(x =&gt; products.Contains(x.ProductCode))\n .GroupBy(x =&gt; x.ProductCode)\n .Select(x =&gt; new\n {\n ProductCode = x.FirstOrDefault().ProductCode,\n DeliveredQty = x.Sum(p =&gt; p.DeliveredQty),\n Distribution = x.Select(c =&gt; c.CustomerID).Distinct().Count(),\n OrderLines = x.ToList()\n })\n .OrderByDescending(x =&gt; x.Distribution)\n .ThenByDescending(x =&gt; x.DeliveredQty)\n .Take(topN).ToList();\n</code></pre>\n\n<p>you only have to query the subset of <code>orderLines</code> that belongs to the current <code>ProductCode</code>:</p>\n\n<pre><code> foreach (var customer in customers)\n {\n DataRow row = table.NewRow();\n row[\"CustomerID\"] = customer.CustomerID;\n row[\"Customer\"] = customer.CustomerName;\n row[\"AccountManager\"] = customer.AccountManager;\n\n foreach (var topProduct in topProducts)\n {\n row[topProduct.ProductCode] = topProduct.OrderLines.Any(x =&gt; x.CustomerID == customer.CustomerID &amp;&amp; x.InvoiceDate &lt; minDate) ? \"Yes\" : \"No\";\n }\n\n table.Rows.Add(row);\n }\n</code></pre>\n\n<hr>\n\n<p>All in all the method could then be something like:</p>\n\n<pre><code>private void CustomersBuyingRange(string supplier, int topN)\n{\n if (string.IsNullOrWhiteSpace(supplier)) return;\n if (topN &lt;= 0) throw new ArgumentOutOfRangeException(nameof(topN));\n\n supplier = supplier.ToUpper();\n\n // Get a list of products from a supplier.\n var products = productDetails\n .Where(x =&gt; x.SupplierID == supplier)\n .Select(x =&gt; x.ProductCode);\n\n // Rank the products by distribution and then by sales,\n // then add the required amount to an array.\n var topProducts = detailedOrderLines\n .Where(x =&gt; products.Contains(x.ProductCode))\n .GroupBy(x =&gt; x.ProductCode)\n .Select(x =&gt; new\n {\n ProductCode = x.FirstOrDefault().ProductCode,\n DeliveredQty = x.Sum(p =&gt; p.DeliveredQty),\n Distribution = x.Select(c =&gt; c.CustomerID).Distinct().Count(),\n OrderLines = x.ToList()\n })\n .OrderByDescending(x =&gt; x.Distribution)\n .ThenByDescending(x =&gt; x.DeliveredQty)\n .Take(topN).ToList();\n\n using (DataTable table = new DataTable(\"Customers\"))\n {\n table.Columns.Add(\"CustomerID\", typeof(string));\n table.Columns.Add(\"Customer\", typeof(string));\n table.Columns.Add(\"AccountManager\", typeof(string));\n // Add the columns with the products.\n foreach (var topProduct in topProducts)\n {\n table.Columns.Add(topProduct.ProductCode, typeof(string));\n }\n\n DateTime minDate = DateTime.Now.AddMonths(-3).Date;\n // We only want customers that have had an order in the last 3 months.\n var customers = customerDetails\n .Where(x =&gt; x.LastInvoiceDate &gt; minDate)\n .OrderBy(x =&gt; x.CustomerName);\n\n\n foreach (var customer in customers)\n {\n DataRow row = table.NewRow();\n row[\"CustomerID\"] = customer.CustomerID;\n row[\"Customer\"] = customer.CustomerName;\n row[\"AccountManager\"] = customer.AccountManager;\n\n foreach (var topProduct in topProducts)\n {\n row[topProduct.ProductCode] = topProduct.OrderLines.Any(x =&gt; x.CustomerID == customer.CustomerID &amp;&amp; x.InvoiceDate &lt; minDate) ? \"Yes\" : \"No\";\n }\n\n table.Rows.Add(row);\n }\n\n Export.ExportToExcel(table, true);\n }\n}\n</code></pre>\n\n<hr>\n\n<p>Disclaimer: I haven't had the opportunity to test the above, so don't hang me if it doesn't improve anything or if I have misunderstood something. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-19T14:52:30.810", "Id": "417481", "Score": "1", "body": "Hi Henrik, thanks for all of the tips it's greatly appreciated. I will test it all later and let you know." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-19T13:38:17.407", "Id": "215751", "ParentId": "215675", "Score": "3" } }, { "body": "<ul>\n<li>My eye started twitching uncontrollably when I saw <code>.Where(x =&gt; x.SupplierID == supplier.ToUpper())</code>. To me, this indicates a major design flaw: something that's called an ID should not be compared to a string that needs to be uppercased.</li>\n</ul>\n\n<hr>\n\n<ul>\n<li>Names are important. <code>string[] products = [...] .Select(x =&gt; x.ProductCode).ToArray();</code> suggests to me that this should be named <code>productCodes</code>, not <code>products</code>. See also <code>DataTable table</code>: \"table\" is about as undescriptive as you can get.</li>\n</ul>\n\n<hr>\n\n<ul>\n<li>The best solution would be to investigate if you couldn't replace all this code with a single query.</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-19T13:40:55.000", "Id": "215752", "ParentId": "215675", "Score": "2" } } ]
{ "AcceptedAnswerId": "215751", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-18T13:04:04.527", "Id": "215675", "Score": "4", "Tags": [ "c#", "linq", ".net-datatable" ], "Title": "Making a list of customers who buy the top N items from a supplier" }
215675
<p>I wrote the following code to deal with possible network problems.</p> <pre><code>def getPage(browser: Browser, page: String): Document = { var attempts = 5 while (attempts &gt; 0) { try { return browser.get(page) } catch { case ste: java.net.SocketTimeoutException if attempts == 1 =&gt; throw ste case ste: java.net.SocketTimeoutException =&gt; attempts -= 1 } } return null } </code></pre> <p>I am new to scala and would appreciate if there is a better, "scala-way" of implementing similar</p> <p>Document and Browser are classes from Scalascraper lib which is a wrapper around JSoup lib.</p>
[]
[ { "body": "<p>Your code uses a number of things seldom if ever seen in idiomatic Scala:</p>\n\n<ol>\n<li><code>return</code></li>\n<li><code>null</code></li>\n<li><code>throw</code></li>\n<li><code>var</code></li>\n</ol>\n\n<p><strong>the land of no return</strong></p>\n\n<p>The final statement in a code block is the return value of that block, so the keyword <code>return</code> isn't needed. If you structure your code so that each block/method/function has only one exit point, at the end, then your code is easier to read and understand, and less prone to unexpected results.</p>\n\n<p>Also, under some circumstances (I won't detail here) using <code>return</code> will do unexpected things. Easier to just avoid it altogether.</p>\n\n<p><strong>failure is an option</strong></p>\n\n<p>Code that might fail to complete correctly usually does one of two things: return a nonsense value, like <code>null</code>, which the calling code will test for (hopefully), or <code>throw</code> an exception, indicating the source of the problem, which some routine somewhere will catch (hopefully) and process.</p>\n\n<p>Scala offers a third and better option: put the failure in the type system. If a routine might fail, put that in its return <em>type</em>, not its return <em>value</em>. That way the calling code can't ignore the possibility of failure.</p>\n\n<p>In this case, instead of returning a <code>Document</code>, return a <code>Try[Document]</code>. Much like an <code>Option</code>, which is <code>Some(value)</code> or <code>None</code>, a <code>Try</code> is expressed as <code>Success(value)</code> or <code>Failure(exception)</code>.</p>\n\n<p><strong>iteration without mutation</strong></p>\n\n<p>Functional Programming avoids data structures with mutable state. Scala has <code>var</code>s but they are discouraged. There are a number of different ways to iterate without using a <code>var</code>. In this case here's what I'd do.</p>\n\n<pre><code>Seq.iterate(Try(browser get page), 5)(_ orElse Try(browser get page))\n</code></pre>\n\n<p>This is a sequence of 5 results from the page requests, but a new attempt is made only if the previous one failed. The first <code>Success</code> is passed down the line to all subsequent positions in the sequence.</p>\n\n<p><strong>putting it all together</strong></p>\n\n<pre><code>import util.Try\n\ndef getPage(browser :Browser, page :String) :Try[Document] =\n Seq.iterate(Try(browser get page), 5)(_ orElse Try(browser get page))\n .last\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-20T04:54:45.840", "Id": "215811", "ParentId": "215677", "Score": "1" } } ]
{ "AcceptedAnswerId": "215811", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-18T13:35:14.617", "Id": "215677", "Score": "1", "Tags": [ "error-handling", "scala", "networking" ], "Title": "Page download with reattempts in Scala" }
215677
<p>I have created this login script for a website I'm making; basically I want to make it as secure as possible, but also I want it to keep users logged in for 30 minutes. For example if I've logged in but accidentally go back to the login page for some reason I want it to recognise I've already logged in and take me to the home page. I also want to make sure my script is as secure as possible with no possibility of being SQL injected.</p> <p>Please could someone have a look at my script and let me know how I can improve it? Also how can I make it so each page checks for a login first and cannot be viewed if the user isn't logged in?</p> <h3>authenticate.php</h3> <pre><code>&lt;?php ini_set('display_errors', 1); ini_set('display_startup_errors', 1); error_reporting(E_ALL); //Session session_start(); require 'connection.php'; //If the POST var "login" exists (our submit button), then we can //assume that the user has submitted the login form. if(isset($_POST['login'])) { //Retrieve the field values from our login form. $username = !empty($_POST['username']) ? trim($_POST['username']) : null; $passwordAttempt = !empty($_POST['password']) ? trim($_POST['password']) : null; //Retrieve the user account information for the given username. $sql = "SELECT * FROM userAccounts WHERE user_email = :username"; $stmt = $usersConn-&gt;prepare($sql); //Bind value. $stmt-&gt;bindValue(':username', $username); //Execute. $stmt-&gt;execute(); //Fetch row. $user = $stmt-&gt;fetch(PDO::FETCH_ASSOC); $activationStat = $user['user_activationStatus']; //If $row is FALSE. if($user === false){ //Could not find a user with that username! //PS: You might want to handle this error in a more user-friendly manner! die('Incorrect username / password combination!'); } else { //User account found. Check to see if the given password matches the //password hash that we stored in our users table. //Compare the passwords. $validPassword = password_verify($passwordAttempt, $user['user_password']); //If $validPassword is TRUE, the login has been successful. if($validPassword){ if ($activationStat == 1) { //Provide the user with a login session. $_SESSION["user_id"] = $user['user_id']; $_SESSION['user_name'] = $user['user_firstName']." ".$user['user_lastName']; $_SESSION['user_security'] = $user['user_securityID']; $_SESSION["logged_in"] = time(); //Error Reporting //ini_set('display_errors', 1); ini_set('display_startup_errors', 1); error_reporting(E_ALL); //Redirect to our protected page, which we called home.php ?&gt; &lt;script type="text/javascript"&gt; //alert("Login successful!"); alert("Login Successful!"); &lt;/script&gt; &lt;?php } else { ?&gt; &lt;script type="text/javascript"&gt; alert("Sorry! Your account has not yet been verified!"); window.location.href = "../index.php"; &lt;/script&gt; &lt;?php } } else{ //$validPassword was FALSE. Passwords do not match. die('Incorrect username / password combination!'); } } } ?&gt; </code></pre> <h3>login.html</h3> <pre><code>&lt;div class="login"&gt; &lt;h1&gt;Login&lt;/h1&gt; &lt;form action="scripts/authenticate.php" method="post"&gt; &lt;label for="username"&gt; &lt;i class="fas fa-user"&gt;&lt;/i&gt; &lt;/label&gt; &lt;input type="text" name="username" placeholder="Username" id="username" required&gt; &lt;label for="password"&gt; &lt;i class="fas fa-lock"&gt;&lt;/i&gt; &lt;/label&gt; &lt;input type="password" name="password" placeholder="Password" id="password" required&gt; &lt;input type="submit" name="login" value="Login"&gt; &lt;/form&gt; </code></pre> <p></p> <h3>connection.php</h3> <pre><code> try { $usersConn = new PDO('mysql:host=HOSTNAME HERE;dbname=DB NAME HERE;charset=utf8', 'USERNAME HERE', 'PASSWORD HERE'); // echo 'client version: ', $conn-&gt;getAttribute(PDO::ATTR_CLIENT_VERSION), "\n"; // echo 'server version: ', $conn-&gt;getAttribute(PDO::ATTR_SERVER_VERSION), "\n"; $usersConn-&gt;setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $usersConn-&gt;setAttribute(PDO::ATTR_EMULATE_PREPARES, false); } catch(PDOException $err) { var_dump($err-&gt;getMessage()); die('...'); } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-18T14:07:33.660", "Id": "417307", "Score": "0", "body": "You can just do `$stmt->execute(['username'=>$username]);` - I mean that's what I do. Other then cleaning it up some, it looks fine to me." } ]
[ { "body": "<p>The only thing I see that I would like to see changed is this</p>\n\n<pre><code>if($user === false){\n die('Incorrect username / password combination!');\n} else {\n ...\n}\n</code></pre>\n\n<p>Here you are relying on \"very\" strict conditions to fail the login, if that's not met for any reason they may get logged in.... </p>\n\n<p>It's not terrible because the other things that you should be doing your doing, it's just better if the login condition is strict and the failure is easy. If that makes sense.</p>\n\n<p>Just sort of a best practice thing to keep in mind.</p>\n\n<p>Here is an example of what can happen:</p>\n\n<pre><code>&lt;?php\n //$user is undefined\nif($user === false){\n die('Incorrect username / password combination!');\n} else {\n echo \"pass\";\n}\n</code></pre>\n\n<p>Output</p>\n\n<pre><code> pass\n</code></pre>\n\n<p><a href=\"http://sandbox.onlinephpfunctions.com/code/c5003f3b98d0fb3a93d947064fb3f09233e834bd\" rel=\"nofollow noreferrer\">Sandbox</a></p>\n\n<p>As I said it's not terrible because your doing everything else right. But it's something I would change, just because.</p>\n\n<p>The only other thing is you could get rid of some of these local variables that are one time use like this:</p>\n\n<pre><code>//Compare the passwords.\n$validPassword = password_verify($passwordAttempt, $user['user_password']);\n\n//If $validPassword is TRUE, the login has been successful.\nif($validPassword){\n</code></pre>\n\n<p>Could just be</p>\n\n<pre><code> if(password_verify($passwordAttempt, $user['user_password'])){\n</code></pre>\n\n<p>But, I get that it's easier to debug and all that when it's more verbose, so that is just my preference.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-18T14:13:24.967", "Id": "215679", "ParentId": "215678", "Score": "2" } }, { "body": "<p>The code is technically safe. </p>\n\n<p>There are some side effects that could help a hacker to penetrate elsewhere, namely a flawed error reporting. The error reporting must be flexible, allowing the same code base behave differently based on the server's role:</p>\n\n<ul>\n<li>on a dev server all errors are better to be shown on-screen (which your code does)</li>\n<li>but on a live server not a single word from the system error message should be shown outside. </li>\n</ul>\n\n<p>To serve these rather contradicting demands your code should never output errors by itself but let PHP to do it instead. And then PHP could be told what to do with error messages by means of couple configuration settings, one of which, <code>display_errors</code> you are already using.</p>\n\n<p>So, long story short, all this fuss is about this small part, <code>var_dump($err-&gt;getMessage());</code>. but you must remember that hackers are cunning. They could overload your database server to make PHP throw an error on connection, and then get a lot of useful information from the error message. To prevent that, just never have a code like this. Most of time an exception thrown must be left alone. But the connection is a special case, as it reveal the database credentials in the stack trace. To prevent this, you can just re-throw the exception, as it shown in my article on <a href=\"https://phpdelusions.net/pdo_examples/connect_to_mysql#error_handling\" rel=\"nofollow noreferrer\">connecting to MySQL using PDO</a>. So connection.php could be rewritten this way:</p>\n\n<pre><code>try {\n $usersConn = new PDO('mysql:host=HOSTNAME HERE;dbname=DB NAME HERE;charset=utf8', 'USERNAME HERE', 'PASSWORD HERE'); \n $usersConn-&gt;setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);\n $usersConn-&gt;setAttribute(PDO::ATTR_EMULATE_PREPARES, false);\n}\ncatch(PDOException $err) {\n throw new \\PDOException($e-&gt;getMessage(), (int)$e-&gt;getCode());\n}\n</code></pre>\n\n<p>so it will never leak anything sensitive, neither in the browser on a properly configured live server, nor even leak the database password into the logs.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-18T16:10:44.723", "Id": "215688", "ParentId": "215678", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-18T13:57:07.013", "Id": "215678", "Score": "3", "Tags": [ "php", "mysql", "security" ], "Title": "PHP Secure Login Scripts" }
215678
<p>Looking for hints on style and clarity re. below. While I'm not saying speed is irrelevant, it's less of a priority than style &amp; avoiding bad habits at this point. Focus is on clean use of fundamentals of the language.</p> <p>Summary of task:</p> <blockquote> <p>Take a list and return a list indicating the number of times each (eql) element appears, sorted from most common element to least common."</p> </blockquote> <p>Example run with required output:</p> <p><code>&gt; (occurrences '(a b a d a c d c a)) ((A . 4) (C . 2) (D . 2) (B . 1))</code></p> <p>My solution:</p> <pre class="lang-lisp prettyprint-override"><code>(defun occurrences (lst) "Takes a list and returns a list indicating the number of times each (eql) element appears, sorted from most common element to least common." (occurrences2 lst (mapcar #'(lambda (x) (cons x 0)) (remove-dups lst)))) (defun occurrences2 (lst res) "Update res, an alist which already contains all needed entries with all values set to zero, with frequencies of occurrence as found in lst" (if (null lst) res ; todo: add a sort here on cdr of each element (occurrences2 (cdr lst) (mapcar #'(lambda (x) (if (eql (car x) (car lst)) (cons (car x) (+ (cdr x) 1)) x)) res)))) (defun remove-dups (lst) (if (null lst) nil (adjoin (car lst) (remove-dups (cdr lst))))) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-18T09:50:07.093", "Id": "417315", "Score": "3", "body": "I think this should be on codereview.se rather than stack overflow." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-18T12:19:32.947", "Id": "417316", "Score": "0", "body": "ok - should i delete it from here then?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-18T14:49:15.173", "Id": "417317", "Score": "0", "body": "If you are going to post it on another stack exchange site, then you do need to delete it here first. Always check the help centre to see what's on topic" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-18T14:57:52.137", "Id": "417318", "Score": "0", "body": "Welcome, to get the best out of CodeReview, please add an summery of the task you are trying to solve, and don't omit anything `\"(works, omitting the sort)\"`." } ]
[ { "body": "<p><strong>Use primitive functions and operators as much as possible</strong></p>\n\n<p>You are defining <code>remove-dups</code>, and in this function you use the primitive <code>adjoin</code>, which adds an element to a list if not already present. But in Common Lisp the primitive function <code>remove-duplicates</code> is also <a href=\"http://www.lispworks.com/documentation/HyperSpec/Body/f_rm_dup.htm#remove-duplicates\" rel=\"nofollow noreferrer\">available</a>, that returns a list without duplicates.</p>\n\n<p>Instead of <code>(+ expression 1)</code> use the primitive <code>1+</code> function: <code>(1+ expression)</code>.</p>\n\n<p>To iterate over a list there are convenient primitives iterative constructs, like <code>dolist</code> and <code>loop</code> (see below).</p>\n\n<p><strong>Alists</strong></p>\n\n<p>If you want to use alists, it can be more clean to use the primitive operators already defined on them, like <code>acons</code>, <code>pairlis</code>, <code>assoc</code>. For instance, the program could be simplified in this way:</p>\n\n<pre><code>(defun occurrences (lst)\n (let* ((elements (remove-duplicates lst))\n (alist (pairlis elements (make-list (length elements) :initial-element 0))))\n (loop for x in lst\n do (incf (cdr (assoc x alist))))\n alist))\n</code></pre>\n\n<p>Note that the counters inside the alist are incremented with <code>incf</code>; in fact another suggestion of mine is “don’t by shy to use modifying primitives”, when you are modifying things locally to some function and are sure no undesirable side-effects arise.</p>\n\n<p><strong>Hash tables</strong></p>\n\n<p>Another suggestion is: use the data structures for the task at hand. In Common Lisp there are hash tables, which are <em>ideal</em> for problems like yours. For instance:</p>\n\n<pre><code>(defun occurrences (lst)\n (let ((table (make-hash-table)))\n (loop for x in lst\n do (incf (gethash x table 0)))\n (loop for k being the hash-key of table\n using (hash-value v)\n collect (cons k v))))\n</code></pre>\n\n<p>This is of course the most efficient solution of all, since it is of O(<em>n</em>), and it scans only once the input list. At the end you could sort the elements returned by their <code>car</code>, and remember always that all the primitive functions that need to do comparisons use by default <code>eql</code> but can be called with an extra keyword parameter <code>:test</code> to chose another comparison predicate, as for instance <code>equal</code> to compare complex values as lists. This applies to <code>remove-duplicates</code>, <code>assoc</code> and <code>make-hash-table</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-25T18:06:14.223", "Id": "418306", "Score": "0", "body": "Nice comparison of alist & hashing approaches. Also of note: 1) Although the original problem only requires `eql` elements, alists automatically allow any lisp object as key, whereas hashing requires a priori specification of the key test (worst case `equalp`); 2) In line with not being shy about modifying primitives, the alist approach might be simplified and speeded up by incrementally constructing and destructively modifying the resulting alist by using something like `(let ((pair (assoc x alist))) (if pair (rplacd pair (incf (cdr pair))) (push (cons x 1) alist))`;" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-25T18:06:41.763", "Id": "418308", "Score": "0", "body": "3) You can generalize the alist solution to accept any sequence of objects as input by using the :iterate library, which allows a driver like `(for x in-sequence lst)`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-25T18:10:14.567", "Id": "418310", "Score": "0", "body": "Thanks, @davypough, very interesting comments!" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-18T16:45:25.937", "Id": "215691", "ParentId": "215682", "Score": "8" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-18T09:23:06.827", "Id": "215682", "Score": "6", "Tags": [ "common-lisp" ], "Title": "Occurrences (frequency count) - exercise 3 ch. 3 in \"ansi common lisp\"" }
215682
<p>In my WordPress theme I have built a function that uses Isotope Layout by Metafizzy to accomplish filtering and sorting.</p> <p>I have used a mix of AJAX and JQuery to accomplish this, however I feel the code is very repetitive and potentially overly long.</p> <pre><code>/** * Get posts using AJAX */ jQuery(document).ready(function ($) { /** * All filter inputs */ let $filters = $(".filters input"); /** * The selectable categories */ let $categories = $(".filter-box__categories input"); /** * The selectable tags */ let $tags = $(".filter-box__categories input"); /** * Initialize the load more */ let load_more = $("button.load-more-posts"); /** * The area to show result counts */ let $resultCount = $(".filter-box__result-count"); /** * An array to store selected filters */ let $selectedFilters = []; let $selectedCategories = []; let $selectedTags = []; /** * Declare that the load more button has not been pressed */ let has_run = false; /** * Specify that the initial next page is always the second */ let next_page = 2; /** * Initialize the Isotope grid */ const $grid = $("#grid").isotope({ itemSelector: ".grid-item", percentagePosition: true, animationEngine: "best-available", animationOptions: { duration: 800 }, filter: "*", masonry: { columnWidth: ".grid-item", gutter: 30 } }); /** * Get the Isotope instance */ const $items = $grid.data("isotope"); /** * Each time an image is loaded, re-layout the grid. * This prevents any weird overlapping. */ $grid.imagesLoaded().progress(function () { $grid.isotope("layout"); }); /** * Apply filters to Isotope when any filters are updated. * This will also update the result count and add some block elements. */ $filters.change(function () { has_run = false; $selectedCategories = []; $selectedTags = []; $selectedFilters = []; // Loop through filters and add values if checked $(".filters input").each(function (counter, element) { if (element.checked) { $selectedFilters.push(element.value); } }); // If there are filters in the filters array, join them if ($selectedFilters.length &gt; 0) { $(".filter-box__applied-filters-area").show(); $filters = $selectedFilters.join(", "); } else { $filters = "*"; } // Add categories to their own array $(".filter-box__categories input").each(function (counter, element) { if (element.checked) { $selectedCategories.push(element.value); } }); if ($selectedCategories.length &gt; 0) { $categories = $selectedCategories.join(", "); $('.toggler--category .toggle').text("Category " + "(" + $selectedCategories.length + ")"); } else { $('.toggler--category .toggle').text("Category"); } // Add tags to their own array $(".filter-box__tags input").each(function (counter, element) { if (element.checked) { $selectedTags.push(element.value); } }); if ($selectedTags.length &gt; 0) { $tags = $selectedTags.join(", "); $('.toggler--tag .toggle').text("Tag " + "(" + $selectedTags.length + ")"); } else { $('.toggler--tag .toggle').text("Tag"); } // Send AJAX request to get posts relating to filter selections $.ajax({ type: "POST", dataType: "json", url: ajax_get_posts_object.ajax_url, data: { action: "ajax_get_posts", security: ajax_get_posts_object.ajax_nonce, categories: $selectedCategories, tags: $selectedTags, }, beforeSend: function (xhr) { // }, success: function (response) { if (response) { console.log(response); // An array to store new items added via AJAX let new_items = []; // Run through JSON $.each(response.posts, function (key, value) { let $new_item = $(`&lt;div class="grid-item article-post-card ${value.category[0]["slug"]} ${value.tags ? value.tags[0]["slug"] : ''}"&gt; &lt;a class="article-post-card__anchor" href=" ${value.permalink}" alt="${value.title}"&gt; &lt;div class="article-post-card__featured-image-container"&gt; &lt;div class="article-post-card__overlay"&gt;&lt;/div&gt; &lt;div class="article-post-card__featured-image"&gt; ${value.thumbnail} &lt;/div&gt; &lt;div class="article-post-card__category-label"&gt; ${value.category[0]["name"]} &lt;/div&gt; &lt;/div&gt; &lt;div class="article-post-card__content-wrapper"&gt; &lt;div class="article-post-card__publish-date"&gt; &lt;time class="updated" datetime="${value.post_time}"&gt;${value.date}&lt;/time&gt; &lt;/div&gt; &lt;div class="article-post-card__title"&gt; ${value.title} &lt;/div&gt; &lt;div class="article-post-card__excerpt"&gt; ${value.introduction} &lt;/div&gt; &lt;/div&gt; &lt;/a&gt; &lt;/div&gt;`); new_items.push($new_item[0]); }); if (response.pages &lt; 2) { load_more.prop("disabled", true); load_more.text("No more posts"); } else { load_more.prop("disabled", false); load_more.text("Load more"); } $grid.isotope("remove", $grid.isotope("getItemElements")); $grid .isotope({ filter: $filters }) .isotope("insert", new_items) .imagesLoaded() .progress(function () { $grid.isotope("layout"); }); updateFilterCount(response.post_count); // Return false as we're at the end return false; // If the AJAX function returned no data } else {} }, error: function (xhr, status, error) { console.log("There was an error", error); } }); }); /** * Reset all filtering */ $(".filter-box__reset-filter").click(function () { has_run = false; $.ajax({ type: "POST", dataType: "json", url: ajax_get_posts_object.ajax_url, data: { security: ajax_get_posts_object.ajax_nonce, action: "ajax_get_posts", current_page: 1 }, beforeSend: function (xhr) { console.log("Resetting"); }, success: function (response) { if (response) { console.log(response); // An array to store new items added via AJAX var new_items = []; // Run through JSON $.each(response.posts, function (key, value) { var $new_item = $(`&lt;div class="grid-item article-post-card ${value.category[0]["slug"]} ${value.tags ? value.tags[0]["slug"] : ''}"&gt; &lt;a class="article-post-card__anchor" href=" ${value.permalink}" alt="${value.title}"&gt; &lt;div class="article-post-card__featured-image-container"&gt; &lt;div class="article-post-card__overlay"&gt;&lt;/div&gt; &lt;div class="article-post-card__featured-image"&gt; ${value.thumbnail} &lt;/div&gt; &lt;div class="article-post-card__category-label"&gt; ${value.category[0]["name"]} &lt;/div&gt; &lt;/div&gt; &lt;div class="article-post-card__content-wrapper"&gt; &lt;div class="article-post-card__publish-date"&gt; &lt;time class="updated" datetime="${value.post_time}"&gt;${value.date}&lt;/time&gt; &lt;/div&gt; &lt;div class="article-post-card__title"&gt; ${value.title} &lt;/div&gt; &lt;div class="article-post-card__excerpt"&gt; ${value.introduction} &lt;/div&gt; &lt;/div&gt; &lt;/a&gt; &lt;/div&gt;`); new_items.push($new_item[0]); }); $grid.isotope("remove", $grid.isotope("getItemElements")); $grid .isotope({ filter: "*" }) .isotope("insert", new_items) .imagesLoaded() .progress(function () { $grid.isotope("layout"); }); updateFilterCount(response.post_count); if (response.pages &lt; 2) { load_more.prop("disabled", true); load_more.text("No more posts"); } else { load_more.prop("disabled", false); load_more.text("Load more"); } // Return false as we're at the end return false; // If the AJAX function returned no data } else {} }, error: function (xhr, status, error) { console.log("There was an error", error); } }); // Hide added divs $(".filters").hide(); $(".filter-box__applied-filters-area").hide(); // Uncheck all checkboxes $(".filter-box__toggler").removeClass("filter-box__toggler--disabled"); $(".filter-box__toggler input").prop("checked", false); $(".filters input").prop("checked", false); // Reset text on buttons $('.toggler--category .toggle').text("Category"); $('.toggler--tag .toggle').text("Tag"); }); /** * Load more posts function: on click of load more, makes an AJAX request to get more posts. * Takes into consideration categories and tags */ $("button.load-more-posts").click(function (e) { e.preventDefault(); load_more.prop("disabled", true); if (has_run == false) { next_page = 2; }; // Perform AJAX request $.ajax({ type: "POST", dataType: "json", url: ajax_get_posts_object.ajax_url, data: { action: "ajax_get_posts", security: ajax_get_posts_object.ajax_nonce, current_page: next_page, categories: $selectedCategories, tags: $selectedTags, }, beforeSend: function (xhr) { load_more.text("Fetching..."); }, success: function (response) { if (response) { console.log(response); // An array to store new items added via AJAX var new_items = []; // Run through JSON $.each(response.posts, function (key, value) { var $new_item = $(`&lt;div class="grid-item article-post-card ${value.category[0]["slug"]} ${value.tags ? value.tags[0]["slug"] : ''}"&gt; &lt;a class="article-post-card__anchor" href=" ${value.permalink}" alt="${value.title}"&gt; &lt;div class="article-post-card__featured-image-container"&gt; &lt;div class="article-post-card__overlay"&gt;&lt;/div&gt; &lt;div class="article-post-card__featured-image"&gt; ${value.thumbnail} &lt;/div&gt; &lt;div class="article-post-card__category-label"&gt; ${value.category[0]["name"]} &lt;/div&gt; &lt;/div&gt; &lt;div class="article-post-card__content-wrapper"&gt; &lt;div class="article-post-card__publish-date"&gt; &lt;time class="updated" datetime="${value.post_time}"&gt;${value.date}&lt;/time&gt; &lt;/div&gt; &lt;div class="article-post-card__title"&gt; ${value.title} &lt;/div&gt; &lt;div class="article-post-card__excerpt"&gt; ${value.introduction} &lt;/div&gt; &lt;/div&gt; &lt;/a&gt; &lt;/div&gt;`); new_items.push($new_item[0]); }); // Add the new items to the grid $grid .isotope("insert", new_items) .imagesLoaded() .progress(function () { $grid.isotope("layout"); }); updateFilterCount(response.post_count); if (next_page &gt;= response.pages) { load_more.text("No more posts to load"); } else { // Undo Button Disable load_more.text("Load more"); load_more.prop("disabled", false); } // Update boolean so that page count is not reset has_run = true; next_page++; // Return false as we're at the end return false; // If the AJAX function returned no data } else { load_more.remove(); } }, error: function (xhr, status, error) { console.log("There was an error", error); } }); }); /** * A change event for the category toggler so we can tell the script to add the div containing categories */ $(".toggler--category input").change(function () { if ($(this).is(":checked")) { $(".toggler--tag").addClass("filter-box__toggler--disabled"); $(".filter-box__categories").show(); } else { $(".toggler--tag").removeClass("filter-box__toggler--disabled"); $(".filter-box__categories").hide(); } }); /** * A change event for the tag toggler so we can tell the script to add the div containing tags */ $(".toggler--tag input").change(function () { if ($(this).is(":checked")) { $(".toggler--category").addClass("filter-box__toggler--disabled"); $(".filter-box__tags").show(); } else { $(".toggler--category").removeClass("filter-box__toggler--disabled"); $(".filter-box__tags").hide(); } }); /** * Update the count of returned items from Isotope */ function updateFilterCount(post_count) { $resultCount.text("Showing " + $items.filteredItems.length + " of " + post_count + " results"); } }); </code></pre> <p>Is there a way I can avoid repetition, however I do have to perform an AJAX request each time to correctly get data based on filtering.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-18T16:24:01.197", "Id": "215689", "Score": "1", "Tags": [ "javascript", "jquery", "ajax", "wordpress" ], "Title": "Load more and filtering - WordPress AJAX" }
215689
<p>I'm trying to implement a free list by using a <code>std::vector</code> as its growable buffer. The reason I made this instead of just adding/removing elements directly into a vector, is because I'd like the indices to remain valid after an item is removed. Please take a look at the code below. I think it works pretty well with my use cases and tests. However it requires the data type, which is stored in the buffer, to always have a default constructor. I'd appreciate any improvements/fixes to this code as well as any alternative ideas to do this.</p> <pre><code>#pragma once #include &lt;vector&gt; #include &lt;stdint.h&gt; #include &lt;assert.h&gt; using u32 = uint32_t; constexpr u32 u32_invalid_id{ 0xffffffff }; template &lt;typename T&gt; class free_list_vector { static_assert(sizeof(T) &gt;= sizeof(u32)); public: explicit free_list_vector() = default; explicit free_list_vector(size_t n) { _array.reserve(n); _next_free_index = u32_invalid_id; } ~free_list_vector() { clear(); } template&lt;class... params&gt; u32 add(params&amp;&amp;... p) { u32 id{ u32_invalid_id }; if (_next_free_index == u32_invalid_id) { id = (u32)_array.size(); _array.emplace_back(std::forward&lt;params&gt;(p)...); } else { id = _next_free_index; assert(id &lt; _array.size() &amp;&amp; already_removed(id)); _next_free_index = read_index(id); new (&amp;_array[id]) T(std::forward&lt;params&gt;(p)...); } return id; } constexpr void remove(u32 id) { assert(id &lt; _array.size() &amp;&amp; !already_removed(id)); T&amp; item{ _array[id] }; item.~T(); write_index(id, _next_free_index); _next_free_index = id; } constexpr void clear() { clear_removed_items(); _array.clear(); } constexpr decltype(auto) size() const { return _array.size(); } [[nodiscard]] T&amp; operator[](u32 id) { assert(id &lt; _array.size()); return _array[id]; } [[nodiscard]] const T&amp; operator[](u32 id) const { assert(id &lt; _array.size()); return _array[id]; } constexpr operator const std::vector&lt;T&gt;&amp;() const { return _array; } private: constexpr void write_index(u32 id, u32 next_free_id) { debug_op(memset(&amp;_array[id], 0xcc, sizeof(T))); u32 *const p{ reinterpret_cast&lt;u32 *const&gt;(&amp;_array[id]) }; *p = next_free_id; } constexpr u32 read_index(u32 id) const { return *reinterpret_cast&lt;const u32 *const&gt;(&amp;_array[id]); } constexpr void clear_removed_items() { while (_next_free_index != u32_invalid_id) { const u32 id{ _next_free_index }; _next_free_index = read_index(id); new (&amp;_array[id]) T{}; } } #ifdef _DEBUG constexpr bool already_removed(u32 id) const { u32 i{ sizeof(u32) }; // skip the first 4 bytes const u8 *const p{ reinterpret_cast&lt;const u8 *const&gt;(&amp;_array[id]) }; while ((p[i] == 0xcc) &amp;&amp; (i &lt; sizeof(T))) ++i; return i == sizeof(T); } #endif std::vector&lt;T&gt; _array; u32 _next_free_index{ u32_invalid_id }; }; </code></pre> <p>Here is a little test:</p> <pre><code>struct _1 { explicit _1() = default; explicit _1(ID3DBlob* b, u32 size) :res1{ b }, blah{ size } { } DISABLE_COPY(_1); // deletes copy constructor and copy assignment operator explicit _1(_1&amp;&amp; o) { *this = std::move(o); } ~_1() { reset(); } _1&amp; operator=(_1&amp;&amp; o) { reset(); res1 = o.res1; blah = o.blah; new (&amp;o) _1{}; // we don't want to release the COM-object after a move return *this; } ID3DBlob *const blob() { return res1; } private: void reset() { if (res1) { res1-&gt;Release(); res1 = nullptr; } } ID3DBlob* res1{ nullptr }; u32 blah{ u32_invalid_id }; }; void free_list_test() { free_list_vector&lt;_1&gt; list; for (u32 i = 0; i &lt; 10; ++i) { ID3DBlob* b; D3DCreateBlob(4096, &amp;b); list.add(b, 4096); } { u32 indices[]{ 3, 5, 8, 1, 6 }; for (u32 i = 0; i &lt; _countof(indices); ++i) { list.remove(indices[i]); } } for (u32 i = 0; i &lt; 40; ++i) { ID3DBlob* b; D3DCreateBlob(4096, &amp;b); list.add(b, 4096); } size_t sizes{ 0 }; for (u32 i = 0; i &lt; 45; ++i) { sizes += list[i].blob()-&gt;GetBufferSize(); } assert(sizes == 45 * 4096); { u32 indices[]{ 23, 35, 18, 11, 26 }; for (u32 i = 0; i &lt; _countof(indices); ++i) { list.remove(indices[i]); } } } int main(){ free_list_test(); return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-18T18:00:40.543", "Id": "417343", "Score": "2", "body": "I just threw up in my mouth a little: `struct _1 {`. That's bad on so many levels. 1: It makes the code unreadable. 2: There are already libraries out there (for special use cases that use _1). 2: Its a reserved identifier so illegal to use in user code. 3: I am just gob smacked." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-18T18:33:03.717", "Id": "417351", "Score": "4", "body": "@MartinYork Please put all critiques in answers, not comments." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-18T23:51:01.573", "Id": "417383", "Score": "1", "body": "@Deduplicator The standard does reserve names that begin with an underscore and is followed by either another underscore or an uppercase character. That applies to all scopes. The standard also reserves names beginning with an underscore specifically in the global scope. ([11](https://timsong-cpp.github.io/cppwp/n3337/global.names#1.2), [14](https://timsong-cpp.github.io/cppwp/n4140/global.names#1.2), [17](https://timsong-cpp.github.io/cppwp/n4659/lex.name#3.2), [Latest Revision](http://eel.is/c++draft/lex.name#3.2))" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-19T00:14:47.033", "Id": "417386", "Score": "1", "body": "@Martin York That's in the test code though, not the actual class." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-19T09:09:53.610", "Id": "417424", "Score": "0", "body": "@MartinYork: I am frasmotic, anispeptic, even compunctuous for having caused you such pericombobulation!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-19T09:50:55.813", "Id": "417430", "Score": "0", "body": "I've rolled your edit back, since it invalidates an existing answer. Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*." } ]
[ { "body": "<p>With the proviso that it will fail unpredictably if mis-used (ex: deleting an index and then accessing it), the implementation seems reasonable for the most part.</p>\n\n<p><strong>size</strong> however, is misleading since it doesn't take removals into account: list size 5 -> add 10 items -> remove 10 items -> list size 15. You could easily track the correct value in add / remove, so I'd suggest doing that.</p>\n\n<p>Related to that, there's no way to traverse the list, or to see whether a particular index is valid. For the purposes you're using it, that might not matter, but it does limit the usage.</p>\n\n<p>Adding a method to convert the contents to a gap-less vector, or to a map (key = index) would give a way to do that. Adding a method to check the validity of a given index is also an option, but at O(n) for each one it's not an efficient way to traverse the contents.</p>\n\n<p>I would definitely suggest removing the implicit (incorrect) conversion to vector though! Treating a free_list_vector with any elements deleted as a normal vector will blow up as soon as you try to traverse it.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-19T08:55:54.210", "Id": "417422", "Score": "0", "body": "Thank you. Please see my edit to my original post addressing your points." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-19T10:00:34.437", "Id": "417435", "Score": "0", "body": "I agree. This class should only be used with valid ids, and throwing away invalid ids being the user's responsibility is why I'm uncomfortable using this container in production code.\n\nRemoving size() as well as the implicit conversion operator would prevent users from traversing the array linearly (they don't know how many elements are in there to traverse). This way it behaves more like a templated memory allocator which gives you 32-bit opaque handles instead of pointers. I believe this would make the free list a lot safer to use. Any other suggestions are very welcome!" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-19T00:31:10.327", "Id": "215713", "ParentId": "215690", "Score": "2" } } ]
{ "AcceptedAnswerId": "215713", "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-18T16:42:42.563", "Id": "215690", "Score": "4", "Tags": [ "c++", "c++11", "vectors" ], "Title": "std::vector free list" }
215690
<p>I have a loop which insert rows on specific cases. The loop goes through ~2000 rows and insert about 500.</p> <p>Due to the inserted rows it doesn't loop the full range I want. I have solved that problem by counting the number of row I will insert with a first loop and then looping up to LastRow + Counter.</p> <p>I feel as if there must have been a better way to do it.</p> <pre><code>Sub AddRows() Dim i As Integer: i = 8 Dim LastRow As Integer: LastRow = Cells(8, 2).End(xlDown).Row Dim counter As Integer: counter = 0 For i = 8 To LastRow If Cells(i, 1) &lt;&gt; "" Then counter = counter + 1 End If Next i NewLastRowAfterAddingRows = LastRow + counter For i = 8 To NewLastRowAfterAddingRows If Cells(i, 1) &lt;&gt; "" Then Range(i + 1 &amp; ":" &amp; i + 1).Insert CopyOrigin:=xlFormatFromRightOrBelow i = i + 1 End If Next i End Sub </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-19T08:12:50.667", "Id": "417412", "Score": "1", "body": "It's not clear the code is intended to achieve. To help reviewers give you better answers, please add sufficient context to your question, including a title that summarises the *purpose* of the code. We want to know **why** much more than **how** (\"loop\" is the latter, rather than the former). The more you tell us about [what your code is for](//meta.codereview.stackexchange.com/q/1226), the easier it will be for reviewers to help you. The title needs an [edit] to simply [**state the task**](//meta.codereview.stackexchange.com/q/2436)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-19T09:28:48.270", "Id": "417425", "Score": "0", "body": "I'm not sure I get you. The purpose of this function is to insert rows in order to do then other retreatement to the file.\nMy problem was : Reduce from two loop to one loop or better. \nMy title is vague as I don't know the proper terms." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-19T09:37:15.210", "Id": "417426", "Score": "1", "body": "What do the rows *mean*? \"Rows of data\" is very much a *solution space* description, but a good code review question needs a *problem space* explanation. I'd expect to see terms like \"house prices\" or \"particle velocities\" or whatever matches the problem you're solving." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-19T09:57:43.070", "Id": "417434", "Score": "0", "body": "rows as in excel sheet rows." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-19T10:05:52.270", "Id": "417437", "Score": "0", "body": "Now i'm intrigued Solution space ? Problem Space ? What does it mean ? I'm not a proffesional of developpement. Merely a hobbyist having fun coding his accountancy retreatement." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-19T12:33:57.510", "Id": "417461", "Score": "0", "body": "What made you write this? What specific problem does it solve? Inserting rows is part of the solution, not the problem." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-19T13:26:44.973", "Id": "417467", "Score": "0", "body": "Now Im confused. I have posted whole problems here before. I was met with \"Please ask for specific questions on specific blocs of code\". \n\nIf you want the context. \nThe aim here is generating all the accountancy writings from an extract of a bank statement. Which I have managed to do. Now I can spend my day on reddit making it seems I work hard and fast :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-21T02:03:08.493", "Id": "417737", "Score": "0", "body": "Why not loop backwards?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-21T13:06:19.467", "Id": "417804", "Score": "0", "body": "Did not think of that. But indeed it would have been the better choice. Now i'm fine with the Bill Hileman version. \nIf anyone manage to even further reduce the complexity of the loop, I take." } ]
[ { "body": "<p>It's generally not a good idea to alter the iterator variable in a for/next loop. While your code works, it's just not a good practice. Also, your initializing i to 8 is redundant since your loop starts at 8 as well. Here's how I would handle it:</p>\n\n<pre><code>Sub AddRows()\n\n Dim i As Integer\n Dim LastRow As Integer\n Dim counter As Integer\n\n LastRow = Cells(8, 2).End(xlDown).Row\n counter = 8\n\n For i = counter To LastRow\n If Cells(counter, 1) &lt;&gt; \"\" Then\n counter = counter + 1\n Range(counter &amp; \":\" &amp; counter).Insert CopyOrigin:=xlFormatFromRightOrBelow\n End If\n counter = counter + 1\n Next i\n\nEnd Sub\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-18T20:18:16.720", "Id": "417362", "Score": "0", "body": "Thank you. I like yours better." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-18T18:53:12.913", "Id": "215698", "ParentId": "215693", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "9", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-18T17:08:06.783", "Id": "215693", "Score": "1", "Tags": [ "vba", "excel" ], "Title": "Loop whose endpoint (?) change during the loop" }
215693
<p>I am searching for an optimization solution, which is a 8d vector representing 4 complex elements, where each element is within the complex circle with maximal radius 1.2.</p> <p>The objective function is:</p> <p><span class="math-container">$$f: \left\|\mathbf{c}_{ref}-\mathbf{c}\right\|_{2}+\left|2-\|\mathbf{c}\|_{2}\right|$$</span></p> <p>I am using the <code>scipy.optimize.basinhopping</code> module.</p> <pre><code>import numpy as np from scipy import optimize class MyBounds(object): def __init__(self, xmax=[360, 360, 360, 360, 1.2, 1.2, 1.2, 1.2], xmin=[0, 0, 0, 0, 0, 0, 0, 0] ): self.xmax = np.array(xmax) self.xmin = np.array(xmin) def __call__(self, **kwargs): x = kwargs["x_new"] tmax = bool(np.all(x &lt;= self.xmax)) tmin = bool(np.all(x &gt;= self.xmin)) return tmax and tmin class MyTakeStep(object): def __init__(self, stepsize=45): self.stepsize = stepsize def __call__(self, x): s = self.stepsize x[0] += np.random.uniform(0, 1*s) x[1] += np.random.uniform(0, 2*s) x[2] += np.random.uniform(0, 3*s) x[3] += np.random.uniform(0, 4*s) s = 1 x[4] += np.random.uniform(0, 1*s) x[5] += np.random.uniform(0, 1*s) x[6] += np.random.uniform(0, 1*s) x[7] += np.random.uniform(0, 1*s) return x def f(input_list): polar_form = [rphi for rphi in zip(input_list[4:], input_list[:4])] x = np.array([z(e[0], e[1]) for e in polar_form]) # objective function componenets result = abs(2 - np.linalg.norm(x, 2)) + np.linalg.norm(cref-x, 2) return result def hopping_solver(min_f, min_x): minimizer_kwargs = {"method":'Nelder-Mead'} comb = np.array([0, 0, 0, 0, 0, 0, 0, 0]) # define bounds mybounds = MyBounds() mytakestep = MyTakeStep() optimal_c = optimize.basinhopping(f, x0 = comb, niter=50000, T=45, stepsize=1, minimizer_kwargs=minimizer_kwargs, take_step=None, accept_test=mybounds, callback=None, interval=5000, disp=False, niter_success=None) min_x, min_f = optimal_c['x'], optimal_c['fun'] print(optimal_c) return min_x, min_f min_f = 10**10 min_x = [] min_x, min_f = hopping_solver(min_f, min_x) </code></pre> <p>My questions relate to the step essentially: My first elements are angles in [0,360] and the others are in [0,1.2]. What is a suitable way to define a good step here to balance between precision and fast processing? </p> <p>I am aware that this code does not return the global minimum.</p> <p>Also here I chose the center of my solutions space as x0, is there on recommendations on how to choose the starting point?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-18T18:25:23.630", "Id": "417345", "Score": "0", "body": "Asking how to fix the code so that it finds the global minimum is outside the scope of Code Review, because our rules require that the code be already working correctly as intended. However, if you relax your expectations so that a non-optimal solution is acceptable, then we can review the code as is." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-18T18:28:24.637", "Id": "417347", "Score": "0", "body": "Well the code is functional. The issue of not finding the global minimum is related mostly to not using the proper parameters." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-18T18:30:09.143", "Id": "417349", "Score": "0", "body": "If you are primarily interested in the computational technique and choosing initial points, rather than open-ended suggestions to improve your code, then try the [scicomp.se] site instead." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-18T18:10:01.480", "Id": "215697", "Score": "2", "Tags": [ "python", "performance", "scipy" ], "Title": "Solve multi-dimentional optimization problem using basinhopping" }
215697
<p>Link: <a href="https://www.hackerrank.com/contests/hackerrank-all-womens-codesprint-2019/challenges/visually-balanced-sections/problem" rel="nofollow noreferrer">https://www.hackerrank.com/contests/hackerrank-all-womens-codesprint-2019/challenges/visually-balanced-sections/problem</a> </p> <h1>Problem Description</h1> <blockquote> <p>A rack has <span class="math-container">\$n\$</span> horizontal compartments. The leftmost compartment is the <span class="math-container">\$1^{st}\$</span> compartment and the rightmost compartment is the <span class="math-container">\$n^{th}\$</span> compartment. Each of the compartments of a rack has a colorful item. A section of a rack consists of one or more consecutive compartments.<br> <a href="https://s3.amazonaws.com/hr-assets/0/1550775726-0e6f0a58ee-visially_balanced_2.jpg" rel="nofollow noreferrer"><img src="https://s3.amazonaws.com/hr-assets/0/1550775726-0e6f0a58ee-visially_balanced_2.jpg" alt="enter image description here"></a> </p> <p>A section (<span class="math-container">\$i^{th}\$</span> compartment to <span class="math-container">\$j^{th}\$</span> compartment where, <span class="math-container">\$i \le j\$</span>) of a rack is visually balanced if the items within the section can be re-arranged in such a way that the color sequence of the items from the <span class="math-container">\$i^{th}\$</span> compartment to the <span class="math-container">\$j^{th}\$</span> compartment is same as the color sequence of the items from the <span class="math-container">\$j^{th}\$</span> compartment to the <span class="math-container">\$i^{th}\$</span> compartment.</p> <p>Few examples of visually balanced sections are:<br> <a href="https://s3.amazonaws.com/hr-assets/0/1550776423-9cc611940c-visually_balanced_3.jpg" rel="nofollow noreferrer"><img src="https://s3.amazonaws.com/hr-assets/0/1550776423-9cc611940c-visually_balanced_3.jpg" alt="enter image description here"></a><br> <a href="https://s3.amazonaws.com/hr-assets/0/1550780752-8ab908e6ff-visually_balanced_4.jpg" rel="nofollow noreferrer"><img src="https://s3.amazonaws.com/hr-assets/0/1550780752-8ab908e6ff-visually_balanced_4.jpg" alt="enter image description here"></a><br> <a href="https://s3.amazonaws.com/hr-assets/0/1550776992-5655b08291-visually_balanced_5.jpg" rel="nofollow noreferrer"><img src="https://s3.amazonaws.com/hr-assets/0/1550776992-5655b08291-visually_balanced_5.jpg" alt="enter image description here"></a> </p> <p>Note that, in the third example, the items in this section can be re-arranged in such a way that the color sequence of the items from the <span class="math-container">\$1^{st}\$</span> compartment of this section to the compartment of this section will be same as the color sequence of the items from the compartment of this section to the <span class="math-container">\$1^{st}\$</span> compartment of this section.</p> <p>Given the colors of each of the <span class="math-container">\$n\$</span> items of a rack, your task is to determine the number of visually balanced sections of a rack.</p> <h3>Function Description</h3> <p>Complete the <em>visuallyBalancedSections</em> function in the editor below. It should return an integer denoting the number of visually balanced sections of a rack..</p> <p><em>visuallyBalancedSections</em> has the following parameter(s):</p> <p>colors: an integer array representing the colors of item in each compartment</p> <h3>Input Format</h3> <ul> <li>The first line contains a single integer <span class="math-container">\$t\$</span> denoting the number of scenarios. </li> <li>The first line of each scenario contains a single integer <span class="math-container">\$n\$</span> denoting the number of compartments of a rack. </li> <li>Each of the next line <span class="math-container">\$i\$</span> of the <span class="math-container">\$n\$</span> subsequent lines (where <span class="math-container">\$1 \le i \le n\$</span>) of a scenario contains an integer <span class="math-container">\$color\$</span> denoting the color of the item in the <span class="math-container">\$i^{th}\$</span> compartment. </li> </ul> <h3>Constraints</h3> <ul> <li><span class="math-container">\$1 \le t \le 100\$</span> </li> <li><span class="math-container">\$1 \le n \le 1000\$</span> </li> <li><span class="math-container">\$1 \le color \le 50\$</span> </li> </ul> <h3>Output Format</h3> <ul> <li>For each scenario, print an integer denoting the number of visually balanced sections of a rack. </li> </ul> <h3>Sample Input 0</h3> <pre><code>1 4 1 2 1 2 </code></pre> <h3>Sample Output 0</h3> <pre><code>7 </code></pre> <h3>Explanation 0</h3> <p>There is only one scenario where the rack has four compartments.</p> <ul> <li>The <span class="math-container">\$1^{st}\$</span> compartment has an item of <span class="math-container">\$= 1\$</span>. </li> <li>The <span class="math-container">\$2^{nd}\$</span> compartment has an item of <span class="math-container">\$= 2\$</span>. </li> <li>The <span class="math-container">\$3^{rd}\$</span> compartment has an item of <span class="math-container">\$= 1\$</span>. </li> <li>The <span class="math-container">\$4^{th}\$</span> compartment has an item of <span class="math-container">\$= 2\$</span>. </li> </ul> <p>The visually balanced sections are: </p> <ol> <li>{<span class="math-container">\$\{1\}\$</span>} - compartment 1 </li> <li>{<span class="math-container">\$\{2\}\$</span>} - compartment 2 </li> <li>{<span class="math-container">\$\{1\}\$</span>} - compartment 3 </li> <li>{<span class="math-container">\$\{2\}\$</span>} - compartment 4 </li> <li>{<span class="math-container">\$\{1, 2, 1\}\$</span>} - compartments 1, 2 and 3 </li> <li>{<span class="math-container">\$\{2, 1, 2\}\$</span>} - compartments 2, 3 and 4 </li> <li>{<span class="math-container">\$\{1, 2, 1, 2\}\$</span>} - compartments 1, 2, 3 and 4 </li> </ol> </blockquote> <hr> <p>This current solution times out. I have an idea for a faster solution with memoisation, but I'm still working on it so I decided to submit this for review in the interim. </p> <h2>Current Solution</h2> <pre class="lang-py prettyprint-override"><code>from collections import defaultdict from copy import copy def is_palindrome(counter): return len(list(filter(lambda x: x%2, counter.values()))) == (1 if sum(counter.values()) % 2 else 0) def visuallyBalancedSections(colours): counter = defaultdict(lambda: 0) total = 0 for i, val in enumerate(colours): counter[val] += 1 temp_counter = copy(counter) for j in range(i+1): total += int(is_palindrome(temp_counter)) temp_counter[colours[j]] -= 1 return total </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-19T05:30:37.827", "Id": "417395", "Score": "0", "body": "In future code, I would probably not alias it, but I had already written the code in this answer by the time you guys made your comment (uploading came much later because formatting the question is stressful)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-19T08:27:04.573", "Id": "417416", "Score": "0", "body": "All that explanation really boils down to \"*compute the number of (possibly overlapping) substrings that are permutations of palindromes*\", doesn't it? I think that reproducing the problem statement word-for-word really isn't a good use of your time and effort." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-20T07:52:50.623", "Id": "417595", "Score": "0", "body": "I thought it would be better to produce the original rather than my interpretation of it, as it is possible I may misunderstand something, and reading the original may give prospective reviewers access to some key insight. But I'll consider your suggestion going forward." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-18T19:47:27.210", "Id": "215700", "Score": "1", "Tags": [ "python", "beginner", "algorithm", "programming-challenge", "time-limit-exceeded" ], "Title": "Hackerrank All Women's Codesprint 2019: Visually Balanced Sections" }
215700
<p>This is in continuation with my <a href="https://codereview.stackexchange.com/questions/215616/synchronized-implementation-of-a-bank-account-in-java">synchronized implementation of a bank account in Java</a>. I am trying to implement bank accounts repository and method to transfer money from one account to another. My implementation for the account and the repository looks like:</p> <p>Account:</p> <pre><code>import java.math.BigDecimal; import java.math.RoundingMode; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; /** * Class to represent an account, it also provides with methods to add and withdraw amount from the * account. * * @author Karan Khanna * @version 1.0 * @since 3/17/2019 */ public class Account { private final ReadWriteLock accountLock; private BigDecimal balance; private final String accountNumber; private final String accountHolder; public Account(String accountNumber, String accountHolder) { this.balance = new BigDecimal(0); this.accountNumber = accountNumber; this.accountHolder = accountHolder; this.accountLock = new ReentrantReadWriteLock(); } public String getAccountNumber() { return accountNumber; } public String getAccountHolder() { return accountHolder; } public ReadWriteLock getAccountLock() { return accountLock; } public double getBalance() { this.accountLock.readLock().lock(); try { return this.balance.setScale(2, RoundingMode.HALF_DOWN).doubleValue(); } finally { this.accountLock.readLock().unlock(); } } public void addAmount(double amount) { this.accountLock.writeLock().lock(); try { this.balance = this.balance.add(BigDecimal.valueOf(amount)); } finally { this.accountLock.writeLock().unlock(); } } public void withdrawAmount(double amount) { this.accountLock.writeLock().lock(); try { this.balance = this.balance.subtract(BigDecimal.valueOf(amount)); } finally { this.accountLock.writeLock().unlock(); } } } </code></pre> <p>AccountsRepository:</p> <pre><code>import static java.lang.String.format; import java.util.HashMap; import java.util.Map; import org.spituk.banking.app.repositories.AccountsRepository; import org.spituk.banking.app.vo.Account; /** * Map based account repository. * * @author Karan Khanna * @version 1.0 * @since 3/17/2019 */ public class AccountsRepositoryImpl implements AccountsRepository { private final static String SOURCE_ACCOUNT_DONOT_EXIST = "Source account number %s don't exist."; private final static String DESTINATION_ACCOUNT_DONOT_EXIST = "Destination account number %s don't exist."; private final static String NOT_ENOUGH_BALANCE = "Account number %s don't have enough balance."; private final Map&lt;String, Account&gt; accountMap; public AccountsRepositoryImpl() { this.accountMap = new HashMap&lt;&gt;(); } @Override public void transferAmount(String accountNumberFrom, String accountNumberTo, double amountToTransfer) throws IllegalArgumentException { if (accountMap.containsKey(accountNumberFrom)) { if(accountMap.get(accountNumberFrom).getBalance() &lt; amountToTransfer) { if(accountMap.containsKey(accountNumberTo)) { Account accountFrom = accountMap.get(accountNumberFrom); Account accountTo = accountMap.get(accountNumberTo); accountFrom.getAccountLock().writeLock().lock(); accountTo.getAccountLock().writeLock().lock(); try { accountFrom.withdrawAmount(amountToTransfer); accountTo.addAmount(amountToTransfer); } finally { accountFrom.getAccountLock().writeLock().unlock(); accountTo.getAccountLock().writeLock().unlock(); } } else { throw new IllegalArgumentException(format(DESTINATION_ACCOUNT_DONOT_EXIST, accountNumberTo)); } } else { throw new IllegalArgumentException(format(NOT_ENOUGH_BALANCE, accountNumberFrom)); } } else { throw new IllegalArgumentException(format(SOURCE_ACCOUNT_DONOT_EXIST, accountNumberFrom)); } } } </code></pre> <p>I am looking for feedback for the implementation.</p>
[]
[ { "body": "<p>Some is personal taste, some is improving performance, some is avoiding deadlocks:</p>\n\n<pre><code>@Override\npublic void transferAmount(String accountNumberFrom, String accountNumberTo, double amountToTransfer) throws IllegalArgumentException {\n synchronized(accountMap) {\n Account accountFrom = getAccount(accountNumberFrom, SOURCE_ACCOUNT_DONOT_EXIST);\n if (accountFrom.getBalance() &gt;= amountToTransfer) {\n // BTW: I think that should be only &gt; because balance==amount should be possible\n throw new IllegalArgumentException(format(NOT_ENOUGH_BALANCE, accountNumberFrom));\n }\n Account accountFrom = getAccount(accountNumberTo, DESTINATION_ACCOUNT_DONOT_EXIST);\n accountFrom.withdrawAmount(amountToTransfer);\n accountTo.addAmount(amountToTransfer);\n }\n}\n\nprivate Account getAccount(String accountNumber, String errorReason) {\n Account ret = accountMap.get(accountNumber);\n if (ret == null) {\n throw new IllegalArgumentException(format(errorReason, accountNumberFrom));\n }\n return ret;\n}\n</code></pre>\n\n<p>In lack of knowledge about the details of this program, I changed everything to be synchronized. The reason is that otherwise it will lead to a deadlock, if there are two accounts each sending money to each other. Each thread might be able to aquire the first lock but then both will wait to get the second lock. In other words: You need to redesign your locking mechanism but without knowing more about the whole thing it's hard to come up with usable proposals.</p>\n\n<p>What else have I changed:</p>\n\n<ul>\n<li>I created a method <code>getAccount</code> that returns the account or throws the <code>IllegalArgumentException</code> with the error message passed by the caller. This avoid code duplication and makes the code more readable by itself</li>\n<li>I personally prefer early returns and throwing exceptions. So instead of a big if-cascade that all need to pass before you do something, I prefer to check the inverted condition and return or throw immediately instead. I found that to be more understandable when looking at it after some time has passed.</li>\n<li>Instead of checking the existence of a key and the retrieval of the value in case it exists, it's simpler (and faster) to try to get the value and check for <code>null</code> unless <code>null</code> is a valid value (which is possible with <code>HashMap</code> but I doubt is the case in your application).</li>\n</ul>\n\n<p>Some more thoughts:</p>\n\n<ul>\n<li>If <code>accountMap</code> can change (accounts added or deleted), you need to make sure that access to it is synchronized as well (with my change it already is but when you put it back to locks you need to take care of that). Otherwise you might transfer money to an account that stopped existing at that very moment and money \"vanishes\".</li>\n<li>Your account works with <code>BigDecimal</code> internally but you pass a <code>double</code> to <code>transferAmount</code>. That should be <code>BigDecimal</code> as well, otherwise you still end up with rounding problems. Your implementation of <code>getBalance</code> looks like you've ran into this problem already and your rounding is your workaround to fix the effect.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-19T09:52:15.220", "Id": "417431", "Score": "0", "body": "I didn't get the point for having a lock on the complete map. It will not allow multiple transactions to be processed in parallel even if they are related to different accounts." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-19T11:53:06.640", "Id": "417456", "Score": "0", "body": "@KaranKhanna Then why are you read- and write-locking said accounts if there is no parallel operation taking place?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-19T13:34:28.420", "Id": "417468", "Score": "0", "body": "I want to allow parallel operations on the accounts but if I take a lock on the whole map as you suggested, it will not allow parallel operations. Every thread will wait for the lock on the map to be released." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-19T13:34:54.180", "Id": "417469", "Score": "0", "body": "I have the locks on the accounts and not on the whole map." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-19T16:50:38.253", "Id": "417508", "Score": "0", "body": "@KaranKhanna I know, what you have done and why and I explained why that will lead to deadlocks if you keep it the way you implemented it, so I changed it to a more robust (but definetely slower) way. You need to rethink your locking mechanism." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-18T21:18:31.330", "Id": "215706", "ParentId": "215701", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-18T20:12:15.600", "Id": "215701", "Score": "1", "Tags": [ "java", "multithreading", "thread-safety" ], "Title": "Java concurrency exercise, implementing transfer of amount from one account to another" }
215701
<p>So I am trying to implement a menu in a program I am writing. My goal is to have zero errors when collecting user input. So I thought the best way to validate was to capture the input as a string and then test against it and prompt for input again until it is valid.</p> <p>As far as I can tell, my code works as I want it to. BUT, is this the best way to go about this? Almost every example online uses char or int for the input, are there benefits to this?. I feel like I made it more complex than it needed to be. As a beginner, any suggestions would be appreciated.</p> <pre><code>#include &lt;iostream&gt; #include &lt;string&gt; using namespace std; string GetInput() { string s = ""; cout &lt;&lt; "&gt;&gt; "; getline(cin, s); return s; } void mainMenu() { cout &lt;&lt; "Select an option" &lt;&lt; endl; cout &lt;&lt; "1. Add Entry" &lt;&lt; endl; cout &lt;&lt; "2. Edit Entry" &lt;&lt; endl; cout &lt;&lt; "Q. Quit" &lt;&lt; endl; string input = GetInput(); while (!(input.find_first_not_of("12qQ") == string::npos) || input.empty()) { input = GetInput(); } if (input == "1") { cout &lt;&lt; "Add Entry" &lt;&lt; endl; //AddEntry(); } else if (input == "2") { cout &lt;&lt; "Edit Entry" &lt;&lt; endl; } else { cout &lt;&lt; "Quit" &lt;&lt; endl; } } int main() { cout &lt;&lt; "===================================================" &lt;&lt; endl; cout &lt;&lt; "| Secure Database |" &lt;&lt; endl; cout &lt;&lt; "===================================================" &lt;&lt; endl &lt;&lt; endl; mainMenu(); return 0; } </code></pre>
[]
[ { "body": "<p>Let me collect a couple of thoughts here.</p>\n\n<ul>\n<li><p>When the input validation is not successful, users immediately get the <code>\"&gt;&gt;\"</code> prompt without any notification that their input wasn't accepted. Maybe add a hint that no action was performed?</p></li>\n<li><blockquote>\n <p>Almost every example online uses <code>char</code> or <code>int</code> for the input, are there benefits to this?</p>\n</blockquote>\n\n<p>The input that you ask for so far is one out of <code>1</code>, <code>2</code>, <code>q</code> or <code>Q</code>, i.e., 4 entries from the ASCII table. Using a single <code>char</code> for this is a reasonable choice, but might be limiting when the program grows. Maybe you want to ask users for paths, tokens, anything with more than one character? Having setup everything with <code>std::string</code> in the first place might be the more pragmatic approach, as it simplifies things (e.g. one function for both the one-<code>char</code>-only and multi-<code>char</code>-input).</p></li>\n<li><p>In <code>GetInput()</code>, you are doing more work than necessary:</p>\n\n<pre><code>string s = \"\";\n</code></pre>\n\n<p>You want an empty string instance to be passed to <code>std::getline</code>, then default-construct it with <code>std::string s;</code> instead of initializing it with an empty string literal (remember that the type of <code>\"\"</code> is <code>const char[1]</code>, <code>std::string s = \"\";</code> is not a no-op), see also Item 4 in Scott Meyer's Effective C++.</p></li>\n<li><p>You flush the standard output a lot of time, when you actually just want a newline <code>\\n</code> to be printed out. See <a href=\"https://stackoverflow.com/questions/213907/c-stdendl-vs-n\">this thread</a> for more details.</p></li>\n<li><p>This is in my opinion the most severe point: the menu logic doesn't scale well. What do you have to change when you need to add a third option? You need to adjust the initial check <em>and</em> you need another <code>else if</code> branch:</p>\n\n<pre><code>input.find_first_not_of(\"123qQ\") // ...\n\n/* ... */ \n\nelse if (input == \"3\") { /* ... */ }\n</code></pre>\n\n<p>The number of options to make this approach unreadable and hard to maintain is quite low, so think about an alternative here. To give you an idea of how this \ncould be improved:</p>\n\n<pre><code>struct MenuAction {\n std::string description;\n std::function&lt;void()&gt; action;\n};\n\nstatic const std::map&lt;std::string, MenuAction&gt; actionTable {\n {\"1\", { \"Add entry\", [](){ std::cout &lt;&lt; \"Add entry\" &lt;&lt; \"\\n\"; }}},\n {\"2\", { \"Edit entry\", [](){ std::cout &lt;&lt; \"Edit entry\" &lt;&lt; \"\\n\"; }}},\n {\"q\", { \"Quit\", [](){ std::cout &lt;&lt; \"Quit\" &lt;&lt; \"\\n\"; }}}\n};\n</code></pre>\n\n<p>Then, you can display available options (assuming C++17 is available) via</p>\n\n<pre><code>for (const auto&amp; [key, value] : actionTable)\n std::cout &lt;&lt; key &lt;&lt; \". \" &lt;&lt; value.description &lt;&lt; \"\\n\";\n</code></pre>\n\n<p>and the original <code>if</code>-<code>else if</code>-<code>else</code> logic boils down to</p>\n\n<pre><code>while (actionTable.count(input) == 0)\n input = GetInput();\n\nactionTable.at(input).action();\n</code></pre>\n\n<p>Maintaining user options is now identical to maintaining the <code>std::map</code> instance.</p></li>\n<li><p>Minor detail; you naming scheme doesn't seem to be consistent. <code>GetInput()</code> starts with an upper case letter, while <code>mainMenu()</code> with a lower case letter.</p></li>\n<li><p>This is very rare, but you <em>could</em> use a <code>do</code>-<code>while</code> construct here to reduce the number of calls to <code>GetInput()</code>:</p>\n\n<pre><code> std::string input;\n\n do\n input = GetInput();\n while (actionTable.count(input) == 0);\n</code></pre>\n\n<p>It seems at least debatable to me whether this is worth it, but as it crossed my mind, I couldn't resist suggesting it :)</p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-20T04:45:21.670", "Id": "417583", "Score": "0", "body": "Thanks for taking the time to review my code. Your suggestions really helped me look at this a different way. I had to research structs and map, I have never used them. I'm just not sure what you were trying to explain about my GetInput() function, could you clarify?" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-19T07:26:54.413", "Id": "215729", "ParentId": "215704", "Score": "5" } } ]
{ "AcceptedAnswerId": "215729", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-18T20:45:38.347", "Id": "215704", "Score": "3", "Tags": [ "c++", "beginner", "strings" ], "Title": "C++ Console Menu User Validation" }
215704
<p>After a bit of a break away from any coding, I decided to return with something simple. As I haven't done much of GUI programming with python, and I would like to do more, I decided to make a simple calculator. If anyone is so kind, I'd like some feedback on anything that might be improved. If it makes a difference in how you'd give feedback, I consider myself an intermediate python coder (whether that's actually true remains to be seen). Some things I'm curious about in particular:</p> <ul> <li>Logic - Am I using any convoluted chains of logic that can be simplified?</li> <li>General Style - I've attempted to adhere to PEP8</li> <li>Key bindings - Is there a more effective way to bind so many keys?</li> <li>Bugs - Did I add in some unnoticed "features"? How can I avoid them in the future?</li> <li>(Opinion based) Tkinter: Even a good choice/something to pursue?</li> </ul> <p></p> <pre><code>import tkinter as tk from decimal import Decimal from tkinter import ttk class Calculator(ttk.Frame): def __init__(self, master=tk.Tk()): super().__init__(master) self.master = master self.master.title("tKalculator") self.operator = None self.prev_num = 0 self.completed_calculation = False self.grid() self.create_widgets() self.bind_keys() self.arrange_widgets() self.mainloop() def create_widgets(self): """ Create all calculator buttons and widgets """ self.number_buttons = [] # Number display self.top_display_space = ttk.Label(self, text=" ") self.display = tk.Text(self, height=1, width=30, pady=4) self.display.insert(1.0, "0") self.display["state"] = "disabled" self.bottom_display_space = ttk.Label(self, text=" ") # Number buttons for num in range(0, 10): num = str(num) self.number_buttons.append( # note to self: The num=num is necessary here ttk.Button(self, text=num, command=lambda num=num: self.update(num)) ) self.decimal_button = ttk.Button(self, text=".", command=lambda: self.update(".")) # Special Buttons self.clearall_button = ttk.Button(self, text="A/C", command=self.all_clear) self.clear_button = ttk.Button(self, text="C", command=self.clear) # Math operators self.add_button = ttk.Button(self, text="+", command=lambda: self.math("+")) self.sub_button = ttk.Button(self, text="-", command=lambda: self.math("-")) self.mult_button = ttk.Button(self, text="X", command=lambda: self.math("x")) self.div_button = ttk.Button(self, text="/", command=lambda: self.math("/")) self.eql_button = ttk.Button(self, text="=", command=lambda: self.math("=")) def arrange_widgets(self): """ Arrange all calculator widgets. """ # Display self.top_display_space.grid(row=0, column=1) self.display.grid(row=1, column=0, columnspan=5) self.bottom_display_space.grid(row=2, column=2) # Number buttons row = 3 column = 1 for i in range(1, 10): self.number_buttons[i].grid(row=row, column=column) column += 1 if column &gt; 3: column = 1 row += 1 self.number_buttons[0].grid(row=6, column=2) self.decimal_button.grid(row=6, column=1) # Special Buttons self.clearall_button.grid(row=7, column=1) self.clear_button.grid(row=6, column=3) # Math operator buttons self.add_button.grid(row=7, column=2) self.sub_button.grid(row=7, column=3) self.mult_button.grid(row=8, column=2) self.div_button.grid(row=8, column=3) self.eql_button.grid(row=8, column=1) def bind_keys(self): """ Binds events to keyboard button presses. """ # Numbers self.master.bind("1", self.keypress_handler) self.master.bind("&lt;KP_1&gt;", self.keypress_handler) self.master.bind("2", self.keypress_handler) self.master.bind("&lt;KP_2&gt;", self.keypress_handler) self.master.bind("3", self.keypress_handler) self.master.bind("&lt;KP_3&gt;", self.keypress_handler) self.master.bind("4", self.keypress_handler) self.master.bind("&lt;KP_4&gt;", self.keypress_handler) self.master.bind("5", self.keypress_handler) self.master.bind("&lt;KP_5&gt;", self.keypress_handler) self.master.bind("6", self.keypress_handler) self.master.bind("&lt;KP_6&gt;", self.keypress_handler) self.master.bind("7", self.keypress_handler) self.master.bind("&lt;KP_7&gt;", self.keypress_handler) self.master.bind("8", self.keypress_handler) self.master.bind("&lt;KP_8&gt;", self.keypress_handler) self.master.bind("9", self.keypress_handler) self.master.bind("&lt;KP_9&gt;", self.keypress_handler) self.master.bind("0", self.keypress_handler) self.master.bind("&lt;KP_0&gt;", self.keypress_handler) self.master.bind(".", self.keypress_handler) self.master.bind("&lt;KP_Decimal&gt;", self.keypress_handler) # Special buttons self.master.bind("c", self.keypress_handler) self.master.bind("a", self.keypress_handler) self.master.bind("C", self.keypress_handler) self.master.bind("A", self.keypress_handler) self.master.bind("&lt;BackSpace&gt;", self.backspace) # Math operator buttons self.master.bind("+", self.keypress_handler) self.master.bind("-", self.keypress_handler) self.master.bind("*", self.keypress_handler) self.master.bind("x", self.keypress_handler) self.master.bind("/", self.keypress_handler) self.master.bind("&lt;KP_Add&gt;", self.keypress_handler) self.master.bind("&lt;KP_Subtract&gt;", self.keypress_handler) self.master.bind("KP_Multiply&gt;", self.keypress_handler) self.master.bind("&lt;KP_Divide&gt;", self.keypress_handler) # Attempt to math self.master.bind("&lt;KP_Enter&gt;", self.keypress_handler) self.master.bind("&lt;Return&gt;", self.keypress_handler) self.master.bind("=", self.keypress_handler) # Escape to close the calculator self.master.bind("&lt;Escape&gt;", self.keypress_handler) def backspace(self, event): """ Remove one character from the display. """ self.display["state"] = "normal" current = self.display.get(1.0, tk.END) self.display.delete(1.0, tk.END) current = current[:-2] # Make sure that the display is never empty if current == "": current = "0" self.display.insert(1.0, current) self.display["state"] = "disabled" def keypress_handler(self, event): """ Handles any bound keyboard presses. """ char_keycode = '01234567890.' char_operator = "+-x*/" if (event.char in char_keycode): self.update(event.char) elif event.char in char_operator: self.math(event.char) elif event.char == "\r" or event.char == "=": self.math("=") elif event.char == "\x1b": self.master.destroy() elif event.char == "c" or event.char == "C": self.clear() elif event.char == "a" or event.char == "A": self.all_clear() def update(self, character): """ Handles all updating of the number display. """ # Allow editing of the display self.display["state"] = "normal" # Get the current number num = self.display.get(1.0, tk.END) # clear the display self.display.delete(1.0, tk.END) # Remove "\n" num = num.strip() # Clear num provided we're not putting a # decimal after a zero if num == "0" and not character == ".": num = "" num = f"{num}{character}" self.display.insert(1.0, f"{num}") self.display["state"] = "disabled" def all_clear(self): """ Resets everything for starting a new calculation. """ self.clear() self.prev_num = 0 self.operator = None def clear(self): """ Clears the display by removing any current text and setting the display to 0 """ self.display["state"] = "normal" self.display.delete(1.0, tk.END) self.display.insert(1.0, "0") self.display["state"] = "disabled" def math(self, operator): """ Handle any actual math. """ if not self.operator: # If an operator doesn't exist, the # calculator is waiting for a new # input. self.operator = operator self.prev_num = self.display.get(1.0, tk.END) self.clear() else: # The calculator is ready to do some math. self.prev_num = Decimal(self.prev_num) curr_num = self.display.get(1.0, tk.END) curr_num = Decimal(curr_num) if self.operator == "+": self.prev_num += curr_num elif self.operator == "-": self.prev_num -= curr_num elif self.operator == "x": self.prev_num *= curr_num elif self.operator == "/": self.prev_num /= curr_num self.operator = operator if self.operator == "=": # It's now time to show the current result # of all calculations. self.display["state"] = "normal" self.display.delete(1.0, tk.END) self.display.insert(1.0, str(self.prev_num)) self.display["state"] = "disabled" self.completed_calculation = True else: # We're ready for another number to # perform calculations on self.clear() if __name__ == "__main__": calc = Calculator() </code></pre> <p>I realized a while after posting that there is a better way to bind the keys: A <code>for</code> loop (duh). While I've implemented that in my updated code, I've kept the original here.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-18T20:58:36.087", "Id": "215705", "Score": "3", "Tags": [ "python", "python-3.x", "tkinter" ], "Title": "Python 3 tkinter calculator" }
215705
<p>I am in the process of learning Rust and am still having some issues with borrowing and ownership. I find myself trying to borrow mutable references that are already borrowed as immutable references etc...</p> <p>I noticed that when I try to iterate over the primes without owning them, I encounter issues trying to modify the <code>composites</code> hash map. I was able to get around this by calling <code>to_owned</code> on the vector. Is this the right way to handle this?</p> <p>This uses the <a href="https://doc.rust-lang.org/nightly/std/ops/trait.Generator.html" rel="nofollow noreferrer">unstable generator feature</a>.</p> <pre class="lang-none prettyprint-override"><code>cargo -V cargo 1.35.0-nightly (0e35bd8af 2019-03-13) </code></pre> <pre class="lang-rust prettyprint-override"><code>#![feature(generators, generator_trait)] use std::collections::HashMap; use std::ops::{Generator, GeneratorState}; let mut sieve = || { let mut x: u32 = 2; let mut composites: HashMap&lt;u32, Vec&lt;u32&gt;&gt; = HashMap::new(); loop { match composites.get(&amp;x) { Some(primes) =&gt; { for _prime in primes.to_owned() { composites .entry(x + _prime) .and_modify(|v| v.push(_prime)) .or_insert(vec![_prime]); composites.remove(&amp;x); } } None =&gt; { yield x; composites.insert(x * x, vec![x]); } } x = x + 1; } }; </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-19T09:57:19.117", "Id": "417433", "Score": "0", "body": "Your code is incomplete and I doubt that doing a review of a code based on an highly unstable feature is useful. Your code does not reflect anymore the last state of this feature BTW." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-19T14:43:31.363", "Id": "417479", "Score": "0", "body": "@FrenchBoiethios how is the code incomplete? And the documentation is actually incorrect, but I realize that this helps to prove the point you're trying to make. I will refactor this with iterators or a class and post that for review instead." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-19T16:34:17.790", "Id": "417502", "Score": "0", "body": "Incomplete because we cannot run it. This is difficult to test" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-19T16:55:10.737", "Id": "417510", "Score": "0", "body": "Okay thank you for the feedback, I have refactored this to use stable features and posted it at https://codereview.stackexchange.com/questions/215768/incremental-sieve-of-eratosthenes-refactored" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-19T17:08:52.637", "Id": "417513", "Score": "0", "body": "This code *can* work if you provide a `main` function around the code. You should do so." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-21T19:30:56.590", "Id": "417854", "Score": "1", "body": "@Vogel612 — I don't believe this to be a duplicate. This version of the code and the linked duplicate do the same thing but in two greatly different implementation styles." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-21T21:50:20.257", "Id": "417873", "Score": "1", "body": "@Shepmaster I assumed the comment by kyle earlier indicated that they were no longer interested in any answers to this question. To make that clear I elected to close this as a duplicate of the newer question to redirect possibly interested reviewers to that new question. This is not a duplicate-closure because I think the questions are duplicates. It's a duplicate-closure because that redirects people to the updated version of the code avoiding stale or unhelpful reviews :)" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-18T21:45:08.333", "Id": "215708", "Score": "1", "Tags": [ "rust", "sieve-of-eratosthenes" ], "Title": "Incremental Sieve of Eratosthenes using unstable generators" }
215708
<p>I am making a code with basic RSA encryption/decryption. My professor wants me to speed up this function but it is already so simple and I am lost. Any ideas?</p> <pre><code>def decrypt(kenc,d,n): kdec=(kenc**d)%n return kdec </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-19T09:55:56.047", "Id": "417432", "Score": "1", "body": "You can trivially make the code simpler/shorter and also (minimally) more efficient by removing the unnecessary variable assignment. But of course this isn’t what your professor meant." } ]
[ { "body": "<p>Simple does not mean fast, so you cannot judge performance based on how simple the implementation looks. Usually the most efficient way to perform a non-trivial task is not also the simplest way to do it. In this case though, there is a much more efficient solution that is about equally simple, and is probably sufficient.</p>\n\n<p>There is a serious problem with this implementation: it computes <code>kenc**d</code>.</p>\n\n<p><code>kenc**d</code> is in general a very big number that takes a long time to compute, and then it takes a long time again to reduce it modulo <code>n</code>. For example, trying it out with 1024bit RSA (the lowest setting!):</p>\n\n<pre><code>import Crypto\nfrom Crypto.PublicKey import RSA\nfrom Crypto import Random\n\nrandom_generator = Random.new().read\nkey = RSA.generate(1024, random_generator)\n\ndef decrypt(kenc,d,n):\n kdec=(kenc**d)%n\n return kdec\n\n(ciphertext,) = key.encrypt(42, 0)\nprint(decrypt(ciphertext, key.d, key.n))\n</code></pre>\n\n<p>This does not finish in a reasonable time.</p>\n\n<p>There is a simple remedy: use modular exponentiation, which keeps the size of the numbers that it is working with low throughout the whole calculation by reducing modulo <code>n</code> as it goes along. You could implement it yourself, but Python handily provides a built-in function for this: <code>pow(x, e, n)</code></p>\n\n<p>So <code>decrypt</code> can be written as:</p>\n\n<pre><code>def decrypt(kenc, d, n):\n return pow(kenc, d, n)\n</code></pre>\n\n<p>With that change, the code above decodes the message quickly.</p>\n\n<p>Further improvements are possible, but more complicated, and won't be drop-in replacements.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-19T10:41:32.043", "Id": "417439", "Score": "1", "body": "And of course, it's even faster not to have `decrypt` at all when all it does is call `pow`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-19T16:50:48.733", "Id": "417509", "Score": "0", "body": "Keeping decrypt would be a good idea. If you were actually implementing RSA, you would also want PKCS or something there, and the performance penalty of a func call will be small compared to the time to call `pow`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-19T20:16:11.947", "Id": "417543", "Score": "1", "body": "Also note that `pow` probably doesn't exhibit timing independent of base and exponent (\"constant-time\") allowing for timing side-channel attacks which one may want / need to defend against." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-19T02:13:45.350", "Id": "215716", "ParentId": "215712", "Score": "16" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-18T23:55:24.760", "Id": "215712", "Score": "4", "Tags": [ "python", "performance", "homework", "cryptography" ], "Title": "Naïve RSA decryption in Python" }
215712
<p>I tried to learn Python during the weekend and after getting some knowledge decided to make a small rock-paper-scissors game. I would be grateful for your input on how I could improve my code. All feedback is highly appreciated.</p> <pre><code>import random def round_winner(choice): ai_chosen = str(random.randint(1, 3)) print(f'AI chose {ai_chosen}') if choice == '1' and ai_chosen == '2': return 'ai' elif choice == '2' and ai_chosen == '3': return 'ai' elif choice == '3' and ai_chosen == '1': return 'ai' elif choice == ai_chosen: return 'tie' else: return 'player' def display_round_winner(winner): if winner == 'tie': print('This round is tied!') else: print(f'The winner this round is the {winner.upper()}') print(f''' Current points as follows: Player: {counter['player']} AI: {counter['ai']} Rounds Tied: {counter['tie']} ''') def score_checker(): global game_ongoing for key, value in counter.items(): if value == 2: print(f'{key.upper()} wins the game!') game_ongoing = False def initializer(): global counter message = ''' Please choose one of the following: 1: Rock 2: Paper 3: Scissors ''' print(message) choice_of_obj = input('What will it be: ') if choice_of_obj in ['1', '2', '3']: winner = round_winner(choice_of_obj) counter[winner] += 1 display_round_winner(winner) score_checker() else: print('Out of bounds') counter = { 'player': 0, 'ai': 0, 'tie': 0 } game_ongoing = True while game_ongoing: initializer() </code></pre>
[]
[ { "body": "<p>You ask the player to enter 1, 2 or 3 for Rock, Paper or Scissors. When you tell the player what the AI choose, you say it was a 1, 2 or a 3. It would be friendlier if you said what they choose. You could do this with a dictionary that translates the abbreviated choice into the actual item.</p>\n\n<pre><code>choices = { '1': 'Rock', '2': 'Paper', '3': 'Scissors' }\n\ndef round_winner(choice):\n ai_chosen = ...\n print(f'AI chose {choice[ai_chosen]}')\n ...\n</code></pre>\n\n<p>Also, you could use that dictionary to print out the menu for the player, instead of hard-coding it:</p>\n\n<pre><code> print('Please choose one of the following:')\n for choice, item in choices:\n print(f'{choice}: {item}')\n</code></pre>\n\n<hr>\n\n<p>You are using “ai”, “player”, and “tie” as keys for your counter dictionary, and always printing out <code>winner.upper()</code> when you print out a winner. You could just use “AI”, “PLAYER” and “TIE” as the dictionary keys, avoiding the need for the <code>.upper()</code> calls.</p>\n\n<hr>\n\n<p><code>score_checker</code> is an odd name. Perhaps one of the hardest things about programming is coming up with good names. <code>check_for_game_winner</code> might be better.</p>\n\n<p>Using <code>global</code> is almost always bad. You just need to pass a <code>true</code>/<code>false</code> value back to the caller to indicate if the game is over. Use a return statement. Ie, inside <code>if value == 2:</code>, add a <code>return True</code> statement.</p>\n\n<hr>\n\n<p><code>initializer</code> is another terrible name. <code>play_round</code> would be better.</p>\n\n<p>Checking for the overall winner inside <code>play_round</code> is confusing responsibilities. The <code>play_round</code> function doesn’t know it is being called in a loop, if at all. It should be removed from here.</p>\n\n<p><code>global counter</code> is again a bad idea. You could simply pass the <code>counter</code> in as an argument.</p>\n\n<hr>\n\n<p>Instead of having the game code run directly, you should add a <code>play_games</code> function, and move the counter initialization code and loop inside that. With other changes, above, it might look like:</p>\n\n<pre><code>def play_games():\n counter = { 'PLAYER': 0, 'AI':0, 'TIE': 0}\n while True:\n play_round(counter)\n if check_for_game_winner(counter):\n break\n</code></pre>\n\n<hr>\n\n<p>The file should only execute code if the file is the main program. If the file is imported into another file, you wouldn’t want the code to automatically run. The following guard is usually used for this:</p>\n\n<pre><code>if __name__ == '__main__':\n play_game()\n</code></pre>\n\n<hr>\n\n<p>Your model of storing the player’s &amp; AI’s moves as strings is perhaps not the best. If you used integers, you could perform the rock beats scissors beats paper beats rock test with modulo arithmetic:</p>\n\n<pre><code>if ai_choice % 3 == (choice + 1) % 3:\n # the AI won\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-19T04:36:16.527", "Id": "417392", "Score": "0", "body": "Thanks for the input! c:" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-19T03:54:58.680", "Id": "215720", "ParentId": "215714", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-19T00:42:21.647", "Id": "215714", "Score": "3", "Tags": [ "python", "beginner", "rock-paper-scissors" ], "Title": "Simple Rock, Paper, Scissors Python Game" }
215714
<p>I am developing another bigger project, I want to try a simple DatingApp and currently I try to develop a Login and Registration Form. There is no special register / login button, the code will later decide wether email is registered (-> login) or not (-> register). But even though it's working I am not sure if I make things to complex:</p> <p>First I want so show a very simple overview of the logic I try to develop:</p> <p><a href="https://i.stack.imgur.com/CsD7j.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/CsD7j.png" alt="enter image description here"></a></p> <p>The App launches with the LogoActivity as a simple SplashScreen. In here the Activity decides which Activity and Fragment is about to be displayed next. It has a sharedElementTransition connected to the <strong>AuthOptionActivity</strong>.</p> <p>The AuthOptionActivity only contains the Logo and a fragment Container.<br/> Depending on the AuthStatus it will show the AuthOptionFragment, containing a Layout with two Buttons. Here you can decide which way you want to use for your registration.</p> <p>In case there is for example an email-registered user but he is not verified yet the AuthOptionActivity will show the MailAuthFragment instead of the AuthOptionFragment.</p> <p>The MailAuthOptionFragment itself contains another two ChildFragments.<br/> The EnterMailSubFragment contains two EditText-Views and the ConfirmMailSubFragment is just a Text containing the Email Adress and a clickable resend textview (not implemented yet).</p> <p>The code so far implemented is working but it is not as clear as I want it to be.</p> <p><strong>Logo Activity</strong></p> <pre><code>public class LogoActivity extends AppCompatActivity { private ImageView mLogo; private Handler mHandler; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_logo); this.init(); } private void init(){ mLogo = findViewById(R.id.activity_logo_logo); AuthHandler.performStartUpCheck(new AuthHandler.StartupAuthStatus() { @Override public void noUser() { Toast.makeText(LogoActivity.this, "No User", Toast.LENGTH_SHORT).show(); performSharedElementTransactionToAuthOption(); } @Override public void onError(String e) { Toast.makeText(LogoActivity.this, e, Toast.LENGTH_SHORT).show(); performSharedElementTransactionToAuthOption(); } @Override public void onPhone() { Toast.makeText(LogoActivity.this, "Phone", Toast.LENGTH_SHORT).show(); //direct to loadingActivity } @Override public void onEmail(boolean isVerified) { Toast.makeText(LogoActivity.this, "Email" + String.valueOf(isVerified), Toast.LENGTH_SHORT).show(); if(isVerified){ //direct to LoadingActivity }else{ performSharedElementTransactionToAuthOption(); } } }); //this.performSharedElementTransaction(); } private void performSharedElementTransactionToAuthOption(){ //check for auth and proceed to Loading Intent pIntent = new Intent(LogoActivity.this, AuthOptionActivity.class); ActivityOptions mOptions = ActivityOptions.makeSceneTransitionAnimation(LogoActivity.this, mLogo, mLogo.getTransitionName()); startActivity(pIntent, mOptions.toBundle()); } private void performTransactionToLoadingScreen(){ /**dummy**/ } @Override protected void onStop() { //Call finish here to avoid flickering this.finish(); super.onStop(); } } </code></pre> <p>Nothing so special here, I am quite happy with that class. Disregard some comments, they are just for me as a reminder.</p> <p><strong>AuthHandler</strong></p> <pre><code>public class AuthHandler { public interface StartupAuthStatus{ void noUser(); void onError(String e); void onPhone(); void onEmail(boolean isVerified); } public interface SignInStatus{ void onEmail(boolean isVerified); } private FirebaseAuth mAuth; private FirebaseFirestore mFirestore; /**STARTUP PROCEDURE**/ public static void performStartUpCheck(final StartupAuthStatus mCallback){ final FirebaseAuth mAuth = FirebaseAuth.getInstance(); checkStartupAuthStatus(mAuth, mCallback); } private static void checkStartupAuthStatus(FirebaseAuth mAuth, StartupAuthStatus mCallback){ mAuth = FirebaseAuth.getInstance(); checkForCurrentUser(mAuth,mCallback); } private static void checkForCurrentUser(FirebaseAuth mAuth, StartupAuthStatus mCallback){ if(mAuth.getCurrentUser()!=null){ checkRegistrationMethod(mAuth, mCallback); }else{ mCallback.noUser(); } } private static void checkRegistrationMethod(final FirebaseAuth mAuth, final StartupAuthStatus mCallback){ if(mAuth.getUid() == null){ mCallback.onError("NullPointerInUID"); return; } FirebaseFirestore.getInstance().collection("Registration").document(mAuth.getUid()).get().addOnCompleteListener(new OnCompleteListener&lt;DocumentSnapshot&gt;() { @Override public void onComplete(@NonNull Task&lt;DocumentSnapshot&gt; task) { if(task.getResult() != null &amp;&amp; task.getResult().exists()){ Map&lt;String, Object&gt; mData = task.getResult().getData(); String mRegistrationForm = (String) mData.get("reg"); if(mRegistrationForm.equals("mail")){ checkMailVerificationStatus(mAuth, mCallback); }else if(mRegistrationForm.equals("phone")){ mCallback.onPhone(); } } } }).addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { mCallback.onError(e.getMessage()); mAuth.signOut(); } }); } private static void checkMailVerificationStatus(FirebaseAuth mAuth, StartupAuthStatus mCallback){ if(mAuth.getCurrentUser().isEmailVerified()){ mCallback.onEmail(true); }else{ mCallback.onEmail(false); } } /**LOGIN PROCEDURE**/ public static void enterUserWithEmailAndPassword(String mEmail, String mPassword){ FirebaseAuth mAuth = FirebaseAuth.getInstance(); createUserWithEmailAndPassword(mAuth, mEmail, mPassword); } private static void createUserWithEmailAndPassword(FirebaseAuth mAuth, String mEmail, String mPassword){ } private static void signUserWithEmailAndPassword(FirebaseAuth mAuth, String mEmail, String mPassword){ } private static void sendVerificationEmail(FirebaseAuth mAuth){ } private static void setupRegistrationModel(String mModelType){ } /**DELETE PROCEDURE**/ } </code></pre> <p>This class is made to "outsource" the code mess. Here I am not sure if it's a common or even usefull way to handle this. The Database contains Users (with a lot of Data later) and a Pool of Registrations, here I only store the choosen registration form (field reg(String): "phone" or "mail").</p> <p>I need to seperate it somehow as the email-registrated-user needs to verify the email.</p> <p><strong>AuthOptionActivity</strong></p> <pre><code>public class AuthOptionActivity extends AppCompatActivity { @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_authoption); if(Build.VERSION.SDK_INT &gt;= Build.VERSION_CODES.LOLLIPOP){ getWindow().setSharedElementEnterTransition(TransitionInflater.from(this).inflateTransition(android.R.transition.move)); } this.checkAuthStatus(); } @Override public void onBackPressed() { findViewById(R.id.activity_authoption_logo).setTransitionName(null); super.onBackPressed(); /** Problem occured: SharedViewElement will be visible after App was closed. * Reason: The View will try to perform the ExitTransition * Solution 1: Delete super.onBackPressed(); and override with finish(); * Solution 2: Set Transitionname to Null**/ } /**The SlideEnter Transition is variable, on First Startup we want a smooth slide in, * for phoneauth we want a Left-Side Slide and for Email a Right-Side Slide. * The Exit Animation is always slide-out-bottom-smooth. * The Reenter Animation is always slide-in-bottom-smooth and due to overlapping * the ExitTransition of the View before BackPress will be hidden and is always 0**/ private void performFragmentTransaction(Fragment mFragment, String mTag, Boolean mAddToBackStack, int mEnterTransition){ FragmentTransaction mFragmentTransaction = getSupportFragmentManager().beginTransaction(); mFragmentTransaction.setCustomAnimations(mEnterTransition, 0, R.anim.slide_in_bottom_smooth, 0); if(mAddToBackStack){ mFragmentTransaction.addToBackStack(mTag); } mFragmentTransaction.replace(R.id.activity_authoption_container, mFragment, mTag); mFragmentTransaction.commit(); } /**Check Auth Status: if CurrentUser != null but not Email verified -&gt; Show MailAuth**/ private void checkAuthStatus(){ if(FirebaseAuth.getInstance().getCurrentUser()!=null &amp;&amp; !FirebaseAuth.getInstance().getCurrentUser().isEmailVerified()){ //very bad way to force a backstack, still looking for a solution this.showAuthOptionFragment(); this.showMailAuth(); }else{ this.showAuthOptionFragment(); } } /**Handle Fragment Transaction including Listener**/ private void showAuthOptionFragment(){ this.performFragmentTransaction(AuthOptionFragment.newInstance(new AuthOptionFragment.ClickListener() { @Override public void onMail() { showMailAuth(); } @Override public void onPhone() { showPhoneAuth(); } }), "AuthOption", false, R.anim.slide_in_bottom); } private void showPhoneAuth(){ this.performFragmentTransaction(_PhoneAuthFragment.newInstance(new _PhoneAuthFragment.AuthStatusListener() { @Override public void onCancel() { //PhoneAuthFragment contains a "back" Button it will fire "onCancel()" onBackPressed(); } @Override public void onSuccess() { //show LoadingScreen } }), "PhoneAuth", true, R.anim.slide_in_left_smooth); } private void showMailAuth(){ this.performFragmentTransaction(_MailAuthFragment.newInstance(new _MailAuthFragment.AuthStatusListener() { @Override public void onCancel() { //MailAuthFragment contains a "back" Button it will fire "onCancel()" onBackPressed(); } @Override public void onSuccess() { //show LoadingScreen } }), "MailAuth", true, R.anim.slide_in_right_smooth); } } </code></pre> <p>For this activity I have some questions:</p> <ol> <li>I am checking the Auth Status &amp; email again to decide which fragment to show. It's easy and simple, but repetitive (it will occur again in MailAuthFragment). Is it a common way to repetitive use FirebaseAuth instances?</li> <li>I have seen a couple of fragment -> activity communication solutions using onAttach etc. Is my solution to pass a CustomListener(interface) in the newInstance method okay? Is there any bug that could occur using it that way?<br/> I pretty much like it as it makes the handling easier.</li> </ol> <p><strong>MailAuthOptionFragment</strong><br/></p> <pre><code>public class _MailAuthFragment extends Fragment { public interface AuthStatusListener{ void onCancel(); void onSuccess(); } private AuthStatusListener mCallback; private String mActiveWindow; private CheckCancelButton mCheckCancelButton; private String mEmail; private String mPassword; @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View mView = inflater.inflate(R.layout.fragment_mailauth, container, false); this.checkAuthStatus(); this.initButton(mView); return mView; } /**PUBLIC METHODS**/ /**Set the Fragment Listener for AuthOptionActivity**/ public void setListener(AuthStatusListener mCallback){ this.mCallback = mCallback; } /**Replaces hard coded Instances as Listener will be passed directly**/ public static _MailAuthFragment newInstance(AuthStatusListener mCallback){ _MailAuthFragment mFragment = new _MailAuthFragment(); mFragment.setListener(mCallback); return mFragment; } /**PRIVATE METHODS**/ /**Check AuthStatus, if CurrentUser!=null but not verified -&gt; Show VerificationScreen**/ private void checkAuthStatus(){ if(FirebaseAuth.getInstance().getCurrentUser() != null &amp;&amp; !FirebaseAuth.getInstance().getCurrentUser().isEmailVerified()){ this.showConfirmEmailSubFragment(R.anim.slide_in_right_smooth); }else{ this.showEnterEmailSubFragment(R.anim.slide_in_right_smooth); } } /**Handle Registration Process Fragments**/ private void performFragmentTransaction(Fragment mFragment, String mTag, int mEnterAnim){ mActiveWindow = mTag; FragmentTransaction mFragmentTransaction = getChildFragmentManager().beginTransaction(); mFragmentTransaction.setCustomAnimations(mEnterAnim, 0); mFragmentTransaction.replace(R.id.fragment_mailauth_container, mFragment, mTag); mFragmentTransaction.commit(); } /**MailAuth receives any valid TextChange from SubFragment**/ private void showEnterEmailSubFragment(int mEnterAnim){ this.performFragmentTransaction(EnterMailSubFragment.newInstance(new EnterMailSubFragment.EnterMailListener() { @Override public void onEmailChanged(String mEmail) { _MailAuthFragment.this.mEmail = mEmail; } @Override public void onPasswordChanged(String mPassword) { _MailAuthFragment.this.mPassword = mPassword; } }), "EnterMail", mEnterAnim); } /**MailAuth receives resend VerificationEmailRequest from SubFragment**/ private void showConfirmEmailSubFragment(int mEnterAnim){ this.performFragmentTransaction(new ConfirmMailSubFragment(), "ConfirmMail", R.anim.slide_in_right_smooth); } private void initButton(final View mView){ /**Custom Button using AfterEffects, Bodymovin and LottieView, contains some commands like "transform to tick"**/ mCheckCancelButton = new CheckCancelButton((LottieAnimationView)mView.findViewById(R.id.fragment_mailauth_nextBtn)); mCheckCancelButton.setCustomClickListener(new CheckCancelButton.CheckCancelButtonClickListener() { @Override public void onClick() { switch(mActiveWindow){ case "EnterMail": // the received Email and Password will be passed to AuthHandlerClass - not implemented yet break; case "ConfirmMail": // the AuthHandler will reloard the currentUser and check for email verification Status - not implemented yet break; } } }); } } </code></pre> <p>Checking AuthStatus again and choosing whether to show the EnterEmailSubFragment or the ConfirmEmailSubFragment. This class contains a button handling both SubFragment pages. This leads to that switch-case method. Not sure if that is a proper way.</p> <p><strong>EnterMailSubFragment</strong></p> <pre><code>public class EnterMailSubFragment extends Fragment { public interface EnterMailListener{ void onEmailChanged(String mEmail); void onPasswordChanged(String mPassword); } private EnterMailListener mCallback; private EditText mEmail, mPassword; private ImageView mEmailWarning, mPasswordWarning; @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View mView = inflater.inflate(R.layout.subfragment_mailauth, container, false); this.initUiWidgets(mView); this.initEditText(mView); return mView; } public void setEnterMailListener(EnterMailListener mMailListener){ this.mCallback = mMailListener; } public static EnterMailSubFragment newInstance(EnterMailListener mMailListener){ EnterMailSubFragment mFragment = new EnterMailSubFragment(); mFragment.setEnterMailListener(mMailListener); return mFragment; } private void initUiWidgets(View mView){ mEmail = mView.findViewById(R.id.subfragment_mailauth_email_ET); mPassword = mView.findViewById(R.id.subfragment_mailauth_password_et); mEmailWarning = mView.findViewById(R.id.subfragment_mailauth_email_warning); mPasswordWarning = mView.findViewById(R.id.subfragment_mailauth_password_warning); } /**Any Valid Entry will be passed to MailFragment**/ private void initEditText(final View mView){ mEmail.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } @Override public void afterTextChanged(Editable s) { if(mEmail.getText() != null &amp;&amp; Patterns.EMAIL_ADDRESS.matcher(mEmail.getText().toString()).matches()){ mEmailWarning.setVisibility(View.GONE); mCallback.onEmailChanged(mEmail.getText().toString()); }else{ mEmailWarning.setVisibility(View.VISIBLE); } } }); mPassword.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } @Override public void afterTextChanged(Editable s) { if(mPassword.getText() != null &amp;&amp; mPassword.getText().length() &gt;= 6){ mPasswordWarning.setVisibility(View.GONE); mCallback.onPasswordChanged(mPassword.getText().toString()); }else{ mPasswordWarning.setVisibility(View.VISIBLE); } } }); } } </code></pre> <p>The Textwatcher checks every entry and transfers it to the MailAuthFragment as MailAuthFragment handels the button event (this is for design puposes, I want the content to move and the button is meant to stay in its position).</p> <p><strong>ConfirmMailAuthSubFragment</strong></p> <pre><code>public class ConfirmMailSubFragment extends Fragment { public interface ConfirmMailListener{ void onResendEmail(); } private ConfirmMailListener mCallback; @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View mView = inflater.inflate(R.layout.subfragment_confirmmail, container, false); return mView; } public void setConfirmMailListener(ConfirmMailListener mCallback){ this.mCallback = mCallback; } public static ConfirmMailSubFragment newInstance(ConfirmMailListener mCallback){ ConfirmMailSubFragment mFragment = new ConfirmMailSubFragment(); mFragment.setConfirmMailListener(mCallback); return mFragment; } } </code></pre> <p>Nothing special here yet. It will handle the Button Event "Resend Verification Mail" and transfer it to MailAuthFragment.</p> <p>I know it's a very early stage of my code but as beautiful as it looks with that slide in animations I am not sure if I am running in the wrong direction or making stuff unnecessary complex.<br/><br/> <strong>Update</strong><br/> I decided to handle the onBackPress manually (no more backstack) as the ChildFragmentManager does not allow to get a step back using the backpress button. Every fragment and childfragment now has a public method "onBackPress" called from AuthOptionActivity.<br/></p> <p><em>AuthOptionActivity - onBackPressed()</em><br/></p> <pre><code> @Override public void onBackPressed() { /**Checking for Fragments and then checking of which instance so you can acess methods**/ if(getSupportFragmentManager().findFragmentById(R.id.activity_authoption_container) != null) { Fragment mCurrent = getSupportFragmentManager().findFragmentById(R.id.activity_authoption_container); if(mCurrent instanceof AuthOptionFragment){ this.finish(); } if(mCurrent instanceof _MailAuthFragment){ ((_MailAuthFragment) mCurrent).onBackPress(); } if(mCurrent instanceof _PhoneAuthFragment){ ((_PhoneAuthFragment) mCurrent).onBackPress(); } } findViewById(R.id.activity_authoption_logo).setTransitionName(null); //super.onBackPressed(); } </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-19T02:39:25.717", "Id": "215717", "Score": "2", "Tags": [ "java", "android", "authentication", "firebase" ], "Title": "Firebase login/registration process for a dating app" }
215717
<p>A Java program that writes each digit on a new line, from 1 to max integer. We should end up with 2.4 Billion lines. After looping to near the maximum integer, the text file becomes really huge. Like 55gb after running for 16 minutes. How can I optimize it to be faster, and also reduce the file size? </p> <p>Below is the code</p> <pre><code>import java.io.BufferedWriter; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.UnsupportedEncodingException; import java.io.Writer; /** * * @author kingamada */ public class reElegant { /** * @param args the command line arguments * @throws java.io.UnsupportedEncodingException */ public static void main(String[] args) throws UnsupportedEncodingException, IOException { // TODO code application logic here try (Writer writer = new BufferedWriter(new OutputStreamWriter( new FileOutputStream("filename.txt"), "utf-8"))) { for (int i = 0; i &lt; Integer.MAX_VALUE - 1; i++) { writer.write(i + " | " + i*2 + "\n"); } } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-19T04:13:51.383", "Id": "417390", "Score": "4", "body": "We can't change the file size without changing what the code does. But you haven't specified what the code must achieve. So, how can we possibly help you?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-19T04:36:52.320", "Id": "417393", "Score": "0", "body": "@200_success I'm just writing a program that writes new digit on each line, max line of the max integer. I hope that clarifies the question." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-19T08:29:07.537", "Id": "417418", "Score": "1", "body": "@kingamada A) Your code doesn't go up to `Integer.MAX_VALUE`, but \"only\" `Integer.MAX_VALUE - 2`. B) You are multiplying by 2, so half way through you are [overflowing the integer](https://en.wikipedia.org/wiki/Integer_overflow). C) Finally why do you think a 55 GB file is too big? I roughly estimate that size is to be expected." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-19T12:08:45.657", "Id": "417458", "Score": "1", "body": "You can't expect a certain output *and* want the output to be smaller. That's not how it works." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-19T12:23:21.147", "Id": "417460", "Score": "0", "body": "What is your newline `\\n` setting? Replacing CRLF with LF will save one byte per line." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-19T20:55:30.363", "Id": "417547", "Score": "0", "body": "If speed is your concern, use a profiler to find out where your program comsumes its time." } ]
[ { "body": "<p>I have no idea why you need this text file. Making it faster should be possible though.</p>\n\n<p>Your current code allocates a StringBuilder and a String for every line. You can avoid this by allocating a single StringBuilder and modifying it using append and setSize. This will reduce the time spent in the garbage collector.</p>\n\n<p>Printing an integer involves splitting it into digits, and that involves integer division, one of the slowest opcodes a processor provides. In your case you can avoid integer division by defining a class called StrInt that stores the integer as a character array and as the number itself. You would need to define methods like <code>add(n)</code> and <code>appendTo(StringBuilder)</code> and take care of the wraparound into the negative numbers.</p>\n\n<p>Using these two techniques will make your code much longer (especially the unit test for the StrInt class should be large) and probably also quite fast.</p>\n\n<p>Writing 55 GB in 1000 seconds means the write rate is already 55 MB/s, which is not the worst.</p>\n\n<p>You should also write to a byte stream instead of a character stream to avoid the unnecessary conversion. Simply changing the encoding from UTF-8 to US-ASCII may already speed it up measurably.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-19T06:54:23.857", "Id": "417407", "Score": "1", "body": "On my system, using a `StringBuilder` in the manner described in your first paragraph only slows the program down. I am a little surprised how efficient plain old string addition is in this context. Your second idea is interesting, though I have not implemented it." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-19T06:39:33.730", "Id": "215727", "ParentId": "215718", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-19T03:17:54.207", "Id": "215718", "Score": "-3", "Tags": [ "java", "performance", "file", "integer" ], "Title": "Code creates huge Text File" }
215718
<p>So I decided to make a more efficient solution to a Google interview question where they ask you to either find the lowest or second lowest value in an array without using the max or min methods. I believe it is more efficient because you can use my method to find any nth lowest value in the array so it solves for all cases. </p> <p>Please let me know if there is anything I can do to improve this solution or if there is anything I am missing:</p> <pre><code>/*Algorithm: -first sort the array from ascending order -Then iterate over the array with a loop -if(array[i + nth lowest input you want]) -return the output function nThOrderStatistic(array, number): -if you want to find the lowest number sub in 0 for number -for every nth lowest number you would sub in n - 1 for the number */ function nThOrderStatistic(array, number) { array.sort(function(a,b){return a -b}); for(i = 0; i &lt; array.length; i++) { if(array[i + number] &lt; array[i + (number + 1)]) { return array[i + number]; } } } nThOrderStatistic([6,7,43,2,95], 2); //sample output for 3rd lowest value is: 7 // </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-19T08:39:11.860", "Id": "417419", "Score": "1", "body": "I don't know JS, but if you are sorting the array and you have to find the nth minimum number, why not just return array[n-1]?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-19T11:28:35.963", "Id": "417450", "Score": "0", "body": "Your code does not work. I dont know why your question has not been closed. You should fix it and ask for another review." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-19T14:16:56.103", "Id": "417478", "Score": "0", "body": "@Blindman67 Broken code isn't off-topic here, only code that the author *knew* was broken (at the time of posting), is off-topic. There is nothing in the post, that suggests that the author knew his code was wrong." } ]
[ { "body": "<p>Good code primary doesn't need to be the most efficient, it needs to be readable, so you should make sure it is correctly formated and indented.</p>\n\n<hr>\n\n<p>More importantly it needs to be correct. Here are some examples of wrong results:</p>\n\n<pre><code>nThOrderStatistic([6,7,43,2,95], 4); // Expected result: 95, returns undefined\n\nnThOrderStatistic([1], 0); // Expected result: 1, returns undefined\n\nnThOrderStatistic([1, 1, 2], 1); // Expected result: 2, returns 1.\n</code></pre>\n\n<hr>\n\n<p>It's not really \"more\" efficient either. Sorting the array is much more inefficient, than directly looking for the nth lowest element in it (or than just looking for the two lowest elements). </p>\n\n<hr>\n\n<p>And finally, it's bad form of a function like this one to unexpectedly modify its input (in this case sort the given array).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-19T11:26:40.433", "Id": "417449", "Score": "0", "body": "I disagree with your opening statement. Good code MUST FIRST be efficient. Ask the end users, the many who pay for the code to be written, which is better, code that takes 10seconds or code that takes 1second to run. -1" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-19T14:05:01.197", "Id": "417477", "Score": "2", "body": "I didn't phrase that well. Code doesn't need to be *most* efficient. One should prefer readable code over perfectly optimized code. I'm speaking of cases where inefficient, but readable code takes 1.1 seconds instead of 1 second to run. If it were not for the bugs, the original idea of sorting the complete array would be IMHO an acceptable solution. It may not the most efficient solution, but in 99% of all use cases a more efficient solution would be overkill. However the OP did imply that this would be a more efficient solution than to \"just\" look for the top 2 lowest values, which it isn't." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-19T21:46:49.517", "Id": "417555", "Score": "1", "body": "-1 *from that*?! Gosh this place is hostile. +1 from me for that very same statement; the whole \"computation time over developer time\" was a thing of the 80s to my understanding, but these days we don't reuse variables for different things, nor use GOTO's, etc." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-19T08:59:27.280", "Id": "215733", "ParentId": "215722", "Score": "3" } }, { "body": "<blockquote>\n <p>efficient solution to a Google interview question where they ask you to either find the lowest or second lowest value in an array without using the max or min methods.</p>\n</blockquote>\n\n<p>If the question is to find the lowest or second lowest value, then sorting (log-linear) will be <em>very</em> inefficient compared to making one or two passes (linear) to find the two numbers.</p>\n\n<p>The generalized version of the task to find the <code>k</code>-th lowest number,\nis not a small detail and not to be underestimated.\nSorting the entire array is still going to be quite inefficient.\nConsider an alternative approach, using a max-heap:</p>\n\n<ul>\n<li>If <code>k</code> is larger than the number of elements, then raise an exception or return <code>undefined</code>.</li>\n<li>Add the first <code>k</code> elements to a max-heap.</li>\n<li>For each remaining element:\n\n<ul>\n<li>If the value is equal or greater than the top of the heap, ignore it</li>\n<li>Otherwise add the value to the heap, and remove the top</li>\n</ul></li>\n</ul>\n\n<p>In the end, the top of the heap is the <code>k</code>-the lowest value.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-20T23:14:52.790", "Id": "417734", "Score": "0", "body": "Yea perhaps I didn't realize the inherent difficulty of finding a generalized solution for this problem, which is why I struggled for a bit. I'm going to definitely need to learn algorithms and data structures soon" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-20T21:56:22.477", "Id": "215880", "ParentId": "215722", "Score": "3" } }, { "body": "<blockquote>\n <p>I decided to make a more efficient solution to a Google interview question</p>\n</blockquote>\n\n<p>The purpose of such interview questions is to get signal as to whether you understand asymptotic efficiency or not; your answer indicates you do not. It will also be looking for signal as to whether you understand the asymptotic performance characteristics of various data structures.</p>\n\n<p><code>sort</code> is O(n lg n) time complexity in the typical case, but <code>max</code> and <code>min</code> can be implemented in O(n) time complexity; whether you can recognize that or not, and write the code accordingly, is the test.</p>\n\n<blockquote>\n <p>I believe it is more efficient because you can use my method to find any nth lowest value in the array so it solves for all cases.</p>\n</blockquote>\n\n<p>That's not the sort of \"efficiency\" they're looking for. The question they're asking is not \"<em>can you solve a more general problem, and therefore be more efficient in terms of lines of code written per problem solved?</em>\" The question they are asking is \"<em>can you find the algorithm that makes more efficient use of machine resources?</em>\".</p>\n\n<p>If you wanted to use this solution in a Google-style interview and impress the interviewers, what you need to do is to make the argument that your sorting solution is more efficient in terms of <em>amortized</em> costs.</p>\n\n<p><strong>Exercise</strong>: under what circumstances is the amortized cost of the \"least n\" query on an arbitrary unsorted array lower if you spend the time sorting the array once?</p>\n\n<blockquote>\n <p>Please let me know if there is anything I can do to improve this solution</p>\n</blockquote>\n\n<p>Google-style interviewers will be looking <em>primarily</em> for signal as to whether you can write <em>correct</em> code, and provide <em>test cases</em> and <em>logical arguments</em> that demonstrate its correctness. Summing up:</p>\n\n<ul>\n<li>You haven't found a correct solution.</li>\n<li>You haven't made any argument for correctness.</li>\n<li>You have provided a single test case.</li>\n<li>You haven't found the asymptotically efficient solution.</li>\n</ul>\n\n<p>This would be an easy \"no hire\" for a Google interviewer.</p>\n\n<p>So, this gives you some things to concentrate on:</p>\n\n<ul>\n<li>Solve the problem that was posed; if you feel the need to solve a more general problem, say why.</li>\n<li>Have a good working understanding of asymptotic performance; I do not expect candidates to be able to rattle off the Master Theorem (I have had a grand total of one candidate in 20 years do so, and they did it wrong) but I do expect candidates to be able to tell me if an algorithm is sublinear, linear, superlinear, quadratic, exponential, and so on.</li>\n<li>Follow good coding practices: don't mutate your inputs, for example.</li>\n<li>Create a correct solution.</li>\n<li>Make a cogent, clear, correct argument that explains why your solution is correct.</li>\n<li>Provide test cases that convince the interviewer that you've thought about ways your algorithm could go wrong.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-20T23:09:42.263", "Id": "417733", "Score": "0", "body": "You shared a really helpful advice on just solving the problem at hand. For the initial problem I was easily able to solve it without using sort functions or mutating my array. But I thought for some reason that they would appreciate it if I can find a more general solution. All in all, the advice you gave was pretty great and I'll study further. (I haven't touched on algorithms and complexity yet, so I will give it a try after I brush up on my programming a bit more)." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-20T22:14:49.040", "Id": "215882", "ParentId": "215722", "Score": "4" } } ]
{ "AcceptedAnswerId": "215733", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-19T04:58:49.477", "Id": "215722", "Score": "0", "Tags": [ "javascript", "algorithm", "programming-challenge", "array", "functional-programming" ], "Title": "Finding nth lowest value without any Math max or min methods" }
215722
<p>Regarding the use of the file system as a database to simply hold <code>JSON</code> files.</p> <p>Any input on this matter from people who know will be appreciated...</p> <pre><code>class JDB{ public $path; function JDB( $path = __DIR__.'/jdb/' ){ $this-&gt;path = $path; if( !file_exists($this-&gt;path) ) mkdir($this-&gt;path); } function p($t){ return $this-&gt;path.$t.'.json'; } function get($t){ return json_decode(file_get_contents( $this-&gt;p($t) )); } function set($t,$c){ return file_put_contents( $this-&gt;p($t), json_encode($c,JSON_PRETTY_PRINT) ); } function create( $t, $d = [] ){ $s = file_put_contents( $this-&gt;p($t), json_encode($d) ); return $s; } function destroy(){ $files = glob($this-&gt;path.'*'); // get all file names present in folder foreach($files as $file){ // iterate files if(is_file($file)) unlink($file); // delete the file } } function delete( $t ){ $s = unlink( $this-&gt;p($t) ); return $s; } function insert( $t, $d = null ){ if($d) $d['__uid'] = $t.'_'.$this-&gt;uid(); $c = $this-&gt;get($t); array_push($c,$d); $s = $this-&gt;set($t,$c); if($s) return $d['__uid']; } function update($t,$conditions,$u){ $c = $this-&gt;get($t); $this-&gt;search($c,$conditions,function($object) use (&amp;$c,$u){ foreach ($u as $key =&gt; $value) { $object-&gt;$key = $value; } }); $this-&gt;set($t,$c); } function remove($t,$conditions){ $c = $this-&gt;get($t); $this-&gt;search($c,$conditions,function($object,$key) use (&amp;$c){ unset($c[$key]); }); $this-&gt;set($t,$c); } function search( $c, $conditions = [], $fn ){ $l = count($conditions); foreach ($c as $key =&gt; $object) { $f = 0; foreach ($conditions as $k =&gt; $v) { if( property_exists($object,$k) &amp;&amp; ($object-&gt;$k == $v) ){ $f++; if( $f==$l ) $fn($object,$key); }else break; } } } function select( $t, $conditions = [] ){ $c = $this-&gt;get($t); $r = []; $this-&gt;search($c,$conditions,function($object) use (&amp;$r){ array_push($r,$object); }); if (count($r) == 0) return false; if (count($r) == 1) return $r[0]; return $r; } function count($t){ $c = $this-&gt;get($t); return count($c); } function uid($length = 20) { $c = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; $cl = strlen($c); $uid = ''; for ($i = 0; $i &lt; $length; $i++) { $uid .= $c[rand(0, $cl - 1)]; } return $uid; } } /* $db = new JDB(); $db-&gt;create('users'); $db-&gt;create('pages'); $user_uid = $db-&gt;insert('users',[ 'name' =&gt; 'a', 'password' =&gt; 'hello world', 'pages' =&gt; [] ]); $user_uid = $db-&gt;insert('users',[ 'name' =&gt; 'b', 'password' =&gt; 'hello world', 'pages' =&gt; [] ]); _log($user_uid,'1'); $page_uid = $db-&gt;insert('pages',[ 'name' =&gt; 'page 1', 'content' =&gt; 'hello world', 'users' =&gt; [$user_uid] ]); _log($page_uid); $user = $db-&gt;select('users',['name' =&gt; 'a']); $page = $db-&gt;select('pages',['users' =&gt; [$user_uid]]); $db-&gt;update('users',['name' =&gt; 'b'],['pages' =&gt; [$page-&gt;__uid]]); $db-&gt;remove('users',['name' =&gt; 'a']); _log($user); _log($page); */ </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-19T08:13:54.880", "Id": "417413", "Score": "0", "body": "Welcome to Code Review! The current question title, which states your concerns about the code, is too general to be useful here. Please [edit] to the site standard, which is for the title to simply state **the task accomplished by the code**. Please see [How to get the best value out of Code Review: Asking Questions](//codereview.meta.stackexchange.com/q/2436) for guidance on writing good question titles." } ]
[ { "body": "<p>The only good thing about this code is your desire to invent. It is a very good desire, only ones possessing it make good programmers. You just made the very first step towards inventing your own database, just like every aspiring newbie programmer does. And that's a very good sign <em>per se</em>.</p>\n\n<p>Everything else about this code - let me be frank - is bad. From the main idea to the minute syntax issues. To outline some misconceptions:</p>\n\n<ul>\n<li>The premise. I know, I know, you have a million reasons not to use a relational database. All of them are wrong though. Beside an aspiration, a good programmer possesses a thing called common sense. Which is bound to tell them that generations of programmers created and polished a thing called a relational database for a reason.</li>\n<li>the above leads to the number of consequences:\n\n<ul>\n<li>scalability. By no means it is good for any project you would call \"large\". All these manual loops in the memory will become unbearably slow. A good database never loads the entire file in the memory, it reads a file by chunks. And uses indexes to speed up all the operations dramatically.</li>\n<li>race condition. With your database you will learn the hard way such things like file locking and a race condition. In concurrent environments a file must be locked when operated with, in order to prevent other files from accessing it. Or it will lead to data corruption and other unwanted consequences.</li>\n<li>features. SQL is one of the greatest inventions of the last century. In a relatively short sentence that is close to natural English it lets us to do the data filtering, ordering, aggregation. How many lines of code you will have to write to get the overall salary for all employees? Grouped by departments? For the certain period? It's just a single line in SQL mind you. </li>\n</ul></li>\n<li>naming. What do remove(), delete() and destroy() functions do? Can you tell from looking at them used in the code? </li>\n<li>OOP. Not to mention the <em>ancient</em> constructor definition (it was discouraged from using for decades!), the overall class structure is flat. It's just a collection of functions. There is no delegation, no abstraction, no separation of concerns. At least there should be two classes, one operating at the filesystem level and one operating at the single json file level.</li>\n<li>syntax in general. Again, it seems to be inevitable for many people to pass such a stage, trying to make a code easier to <em>write</em>, making names gibberish as a result. It takes time to realize that reading is much more important than writing, and such names as <code>p()</code>, <code>$d</code> and such is a blasphemy. Every variable and method should have a meaningful name.</li>\n<li><code>if (count($r) == 1) return $r[0];</code> is my favorite. I learned the hard way that such a magic will lead to a situation when your code expects a 2-dimensional array of rows but gets just a single row. It's funny to see the result when you are trying to loop over it and then access distinct fields inside each element. there must be explicit methods to get you certain result types, you want to look at <a href=\"http://php.net/manual/en/class.pdostatement.php\" rel=\"noreferrer\">PDOStatement</a> for inspiration</li>\n<li><p>error reporting. at least for json_encode() you have to implement a wrapper that will produce a meaningful error message</p>\n\n<pre><code>function jsonDecode($json, $assoc = false)\n{\n $ret = json_decode($json, $assoc);\n if ($error = json_last_error())\n {\n throw new Exception(json_last_error_msg(), $error);\n }\n return $ret;\n}\n</code></pre></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-19T16:57:30.337", "Id": "417511", "Score": "0", "body": "I would only contend that \"All of them are wrong\" is... well... wrong :)\nThere are some valid resons not to use a relational database for certain purposes:\n1) overhead : the \"relational\" part is sometimes just not needed\n2) rigidity : you sometimes just want to dump data without worrying about schema\n3) Lack of in-process alternatives: options are scarce in PHP for in-process RDBs, except SQLite, which doesn't provide hash indexes so it's inefficient for KV stores\nSo there are valid reasons not to use a relational database. But there are luckily KV store alternatives (like DB4)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-19T17:08:00.470", "Id": "417512", "Score": "0", "body": "... so the point is valid that one should use a mature tried-and-tested solution for any persisted data. But it doesn't have to be a RDB. It can be KV, noSQL, etc." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-19T07:21:11.247", "Id": "215728", "ParentId": "215724", "Score": "5" } }, { "body": "<p>To add a constructive suggestion to this, it is apparent to me you are implementing a glorified KV (key-value) store; value being JSON is of no consequence. So why not use something that is already designed for this?</p>\n\n<ol>\n<li><a href=\"http://php.net/manual/en/book.dba.php\" rel=\"nofollow noreferrer\">http://php.net/manual/en/book.dba.php</a></li>\n<li>Any flavor of DB with hash-type storage</li>\n</ol>\n\n<p>This would or at least should rid you of concurrency concerns (well, not entirely, you will still quite possibly get deadlocks but at least integrity is preserved by any of the above suggestions).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-19T12:25:38.623", "Id": "215745", "ParentId": "215724", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-19T05:46:51.193", "Id": "215724", "Score": "2", "Tags": [ "php", "database" ], "Title": "PHP Filesystem JSON Files DB" }
215724
<p>There is no intended end use for this. It is for learning and development only.</p> <p>I got carried away following an example and ended up with a miniaturised vehicle registration system. You can bulk generate records, each of which is given a unique registration number in keeping with British registration format. I've written a script that compares and lists all registration numbers that fall afoul of the criteria. </p> <p><strong>It does work</strong>, but it is incredibly slow. (over an hour to check 1 mil records). I am looking for critique on the logic and any optimisation I may have missed.</p> <p>Example string: AA99AAA</p> <p>Example criteria: A?9?AAA </p> <pre><code> def full_search(offensive_list) p 'Full check:' p "Comparing #{$all_vehicles.count} records against #{offensive_list.count} banned combinations" p 'This will take a few minutes' vrm_array, example_array = [], [] vrm_list = $all_vehicles.keys.sort vrm_list.each do |vrm| vrm_array &lt;&lt; vrm.split("") #We split each reg into an array of characters end offensive_list.each do |example| example.strip! example_array &lt;&lt; example.split("") #and the same with our banned combinations end vrm_array.each do |vrm| example_array.each do |example| #itterate through vrms x examples @formatted_vrm = vrm.dup if example.length == vrm.length example.each_index do |index| if example[index] == "?" #for each wildcard we add a wildcard to the vrm for comparison @formatted_vrm[index] = "?" end end if @formatted_vrm == example then offensive_found(vrm, example) end end end end end def offensive_found(vrm, example) built_vrm = "" built_example = "" if vrm.class == Array #clean up formatting so we can store it vrm.each do |character| built_vrm &lt;&lt; character end example.each do |character| built_example &lt;&lt; character end else built_example = example #clearly redundant, but it works so... built_vrm = vrm end if $bad_vrms[built_example] # if we already have a record prev_matched = $bad_vrms[built_example] #just add to the array prev_matched &lt;&lt; built_vrm $bad_vrms.store(built_example, prev_matched) else new_match = [built_vrm] # or create a new hash key $bad_vrms.store(built_example, new_match) end #p "#{built_vrm} - matched with #{built_example}" end </code></pre> <p>If you'd prefer you can clone the full thing on github. <a href="https://github.com/Niall47/RubySomDemo" rel="nofollow noreferrer">https://github.com/Niall47/RubySomDemo</a></p>
[]
[ { "body": "<p>You could consider using Regex to speed up the search. The cleanest way to do so would be to change your <code>full_search.txt</code> to be Regex expressions. For example <code>A?9?AAA</code> would need to be changed to <code>A.9.AAA</code> (<a href=\"https://rubular.com/\" rel=\"nofollow noreferrer\">in Regex the <code>.</code> means <em>any single character</em></a>).</p>\n\n<p>Then you could change your <code>full_search</code> method to look like this:</p>\n\n<pre><code>def full_search(offensive_list)\n vrm_list = $all_vehicles.keys.sort\n offensive_examples = offensive_list.map(&amp;:strip)\n\n offensive_examples.each do |offensive_example|\n vrm_list.grep(/^#{offensive_example}$/).each do |offensive_vrm|\n offensive_found(offensive_vrm, offensive_example)\n end\n end\nend\n</code></pre>\n\n<p>In the Regex the <code>^</code> means start of string and the <code>$</code> means end of string; this basically ensures that substrings are not matched e.g.) <code>abcd</code> matches with the regex <code>.c</code> but not with <code>^.c$</code></p>\n\n<p>If you don't want to modify your list, you could so something that dynamically creates the regex in Ruby. For example: <code>offensive_example.gsub(\"?\", \".\")</code> this would replace all <code>?</code> with <code>.</code>.</p>\n\n<hr>\n\n<p>A couple unrelated pointers...</p>\n\n<ul>\n<li>Ruby has a <a href=\"https://ruby-doc.org/core-2.6.2/String.html#method-i-chars\" rel=\"nofollow noreferrer\"><code>String#chars</code></a> method that is (arguably) more readable and might have some minor performance improvements over <code>string.split(\"\")</code>.</li>\n<li>Instead of assigning an initial empty value and building it in an <code>each</code>, consider using <code>Array#map</code> to reduce the amount of variable reassignments.</li>\n</ul>\n\n<pre class=\"lang-rb prettyprint-override\"><code># before\nvrm_array = []\nvrm_list.each do |vrm|\n vrm_array &lt;&lt; vrm.split(\"\")\nend\nvrm_array.each do |vrm|\n # do stuff\nend\n\n# after\nvrm_array = vrm_list.map { |vrm| vrm.split(\"\") } # this calls `split` on each element in `vrm_list`\nvrm_array.each do |vrm|\n # do stuff\nend\n</code></pre>\n\n<ul>\n<li>If you need to take an array of characters and <em>join</em> them together into a single string, consider using <code>Array#join</code>.</li>\n</ul>\n\n<pre><code>irb(main):001:0&gt; ['a', 'b', 'c'].join\n=&gt; \"abc\"\n</code></pre>\n\n<ul>\n<li>If you have a Hash and you want an empty array if a key doesn't exist, consider using a default value (but be careful with <a href=\"https://stackoverflow.com/questions/2698460/strange-unexpected-behavior-disappearing-changing-values-when-using-hash-defa\">some gotchas related to mutable defaults</a>)</li>\n</ul>\n\n<pre class=\"lang-rb prettyprint-override\"><code>$bad_vrms = Hash.new { |h, k| h[k] = [] } # the argument is the default value which in this case is a block that initializes the key's value to a new instance of an empty array\n\n# now we don't need to check if a key exists and can simply push to it\n$bad_vrms[example] &lt;&lt; vrm\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-21T10:37:08.367", "Id": "215921", "ParentId": "215734", "Score": "3" } } ]
{ "AcceptedAnswerId": "215921", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-19T09:00:18.007", "Id": "215734", "Score": "2", "Tags": [ "beginner", "strings", "ruby" ], "Title": "Ruby Beginner - Fuzzy matching / string manipulation" }
215734
<p>I have a matrix of fewer than 1021 rows. I'd like to take its transpose, but it is too big for GNU <code>datamash</code> and <code>awk</code> solutions to fit into memory.</p> <p>To keep memory overhead low, my thought is that I keep a list of read-only file pointers to the start of each row. I then read out bytes from each pointer until I hit a delimiter (tab or newline). </p> <p>Because I have fewer than 1021 rows, I won't hit the usual 1024 OS-based file pointer limit.</p> <p>Once I have read out a field from all file pointers, I write a newline character and start over, reading a field from all file pointers, and again, until no more bytes are available:</p> <pre><code>#!/usr/bin/env python import sys import os try: in_fn = sys.argv[1] except ValueError as ve: sys.exit(-1) def get_size(fn): st = os.stat(fn) return st.st_size # # 1) Read in file offsets to start of new line # 2) Open up a file pointer to that offset # 3) Process each file pointer to get a value until a delimiter is hit, then write it as a row of output # size = get_size(in_fn) fps = [] new_fp = open(in_fn, 'r') new_fp.seek(0, 0) fps.append(new_fp) with open(in_fn, 'r') as f: byte = f.read(1) while byte: if byte == '\n': new_offset = f.tell() if new_offset &lt; size: new_fp = open(in_fn, 'r') new_fp.seek(new_offset, 0) fps.append(new_fp) else: break byte = f.read(1) while size &gt; 0: for fi, f in enumerate(fps): byte = f.read(1) size -= 1 while byte: if byte == '\t' or byte == '\n': if fi != len(fps) - 1: sys.stdout.write('\t') break sys.stdout.write('%s' % (byte)) byte = f.read(1) size -= 1 sys.stdout.write('\n') for f in fps: f.close() </code></pre> <p>Is there anything I can do to improve the performance of this? Reading and processing a set of file pointers one byte at a time seems quite expensive. However, I need to find newline characters to build offsets and file pointers. Is there a cleverer/faster way (in Python) to find the byte offsets of newlines?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-19T11:39:07.827", "Id": "417452", "Score": "2", "body": "While you did say how many rows your matrix has, you did not specify the number of columns. If that is less than a million or so, reading it all into memory and transposing it there will be faster." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-19T11:44:57.700", "Id": "417454", "Score": "1", "body": "Have you considered `mmap` and offsets as an alternative to file descriptors? That might be easier to work with. It certainly scales to more rows." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-19T16:04:40.437", "Id": "417494", "Score": "0", "body": "Unfortunately, I can't read the file into memory, otherwise I'd use `datamash` or `awk` if I could. The `mmap` approach looks interesting, thanks!" } ]
[ { "body": "<p>The golden rule of I/O performance is <strong>never read a block twice</strong>. You're reading each block thousands of times.</p>\n\n<p>I made a thousand-row test file with records of about 2MB each:</p>\n\n<pre><code>tr -dc '[:alnum:]' &lt; /dev/urandom | fold -w2000000 | head -1000 &gt; test.txt\n</code></pre>\n\n<p>And modified the <code>fps</code>-building portion of your code thusly:</p>\n\n<pre><code>#!/usr/bin/env python\nfrom prettyprinter import pprint\nimport sys\nimport os\nimport re\n\ntry:\n in_fn = sys.argv[1]\nexcept ValueError as ve:\n sys.exit(-1)\n\nsz = os.path.getsize(in_fn)\nfps = [ open(in_fn, 'r') ]\nbufsz = 100 * 2**20 # MB\n\nwith open(in_fn, 'r') as f:\n offset = 0\n buf = f.read(bufsz)\n while len(buf)&gt;0:\n for p in [m.start() for m in re.finditer(r'\\n', buf)]:\n new_pos = offset+p+1\n if new_pos &lt; sz:\n new_fp = open(in_fn, 'r')\n new_fp.seek(new_pos, 0)\n fps.append(new_fp)\n\n offset = f.tell()\n buf = f.read(bufsz)\n\npprint( list( map( lambda f: f.tell(), fps ) ) )\n</code></pre>\n\n<p>This runs 65 times faster than the bytewise version on my machine.</p>\n\n<p>The actual transposition will benefit similarly from this treatment. Keep a buffer for each row and append to it with a <code>read</code> when it's empty. </p>\n\n<p>If you want to keep the logic simpler, you can compromise (with a performance penalty) by reading a few kilobytes at a time and rewind-<code>seek</code>ing the filehandle back to the first tab character. This would remove the need to keep an array of buffers.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-19T17:33:03.703", "Id": "417517", "Score": "1", "body": "This appears to be ridiculously faster, in comparison." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-19T11:30:50.507", "Id": "215741", "ParentId": "215736", "Score": "5" } } ]
{ "AcceptedAnswerId": "215741", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-19T09:32:29.153", "Id": "215736", "Score": "4", "Tags": [ "python", "matrix" ], "Title": "Transpose of a very large matrix with fewer than 1021 rows with Python" }
215736
<p>I wrote a script to fetch the location for the ISS using two simple APIs.</p> <p>This is my first time writing a python script. Any advice or modifications would be highly appreciated. How is the code, and where are the areas I can improve upon?</p> <p>This code is also <a href="https://github.com/dsaharia/iss_location" rel="nofollow noreferrer">on GitHub</a>.</p> <pre><code>import urllib.request # to make requests to the api import json # to parse the json response import reverse_geocoder as rg # to get address from location url = "http://api.open-notify.org/astros.json" response = urllib.request.urlopen(url) # request the api, returns a JSON object json_result = json.loads(response.read()) # read the JSON object # Separate different values based on keys. people = json_result['people'] # people currently in space number_in_space = json_result['number'] # total people in space print("People in space : ", number_in_space) print("----NAMES----") for p in people: print(p['name']) # ISS data iss_url = "http://api.open-notify.org/iss-now.json" iss_response = urllib.request.urlopen(iss_url) iss_json_result = json.loads(iss_response.read()) # Store the positions latitude = iss_json_result['iss_position']['latitude'] # store the latitude longitude = iss_json_result['iss_position']['longitude'] print("Latitude: ", latitude," -- ", "Longitude: ", longitude) address = rg.search((latitude, longitude)) # Get the address from location tuple returns a list address_name = address[0]['name'] address_admin1 = address[0]['admin1'] address_admin2 = address[0]['admin2'] address_cc = address[0]['cc'] print("----Address----") print(address_name, ", ", address_admin1, address_admin2, address_cc) </code></pre>
[]
[ { "body": "<p>Not bad for a first Python script!</p>\n\n<p>In general, you can greatly benefit from giving parts of your code names, by encapsulating them in functions. This makes it also re-usable and let's you add a <a href=\"https://www.python.org/dev/peps/pep-0257/\" rel=\"nofollow noreferrer\"><code>docstring</code></a> giving more detail on what this function does.</p>\n\n<p>If you add a <code>main</code> function which you call under a <code>if __name__ == \"__main__\":</code> guard you can also import these functions from another script without all of your code running.</p>\n\n<p>Instead of <code>urllib.request</code>, you can use the <a href=\"http://docs.python-requests.org/en/master/\" rel=\"nofollow noreferrer\"><code>requests</code></a> module, it even has a method to directly return a JSON object.</p>\n\n<p>While it is nice that the astronauts response contains the number of astronauts in space, you could get the same information from calling <code>len(people)</code>, which is <span class=\"math-container\">\\$\\mathcal{O}(1)\\$</span> for Python lists.</p>\n\n<p>Familiarize yourself with <a href=\"https://www.python.org/dev/peps/pep-0498/\" rel=\"nofollow noreferrer\"><code>f-string</code></a>s (Python 3.6+). They are a nice and compact way to write formatted strings, since they can contain arbitrary Python expressions (I used it for the address here).</p>\n\n<pre><code>import requests\nimport reverse_geocoder\n\ndef get_json(url):\n \"\"\"Retrieve JSON object from url.\n\n Raises an exception if connection fails.\n \"\"\"\n response = requests.get(url)\n response.raise_for_status() # make sure an exception is raised if something goes wrong\n return response.json()\n\ndef get_astronauts():\n \"\"\"Returns a list of all people currently in space\"\"\"\n url = \"http://api.open-notify.org/astros.json\"\n return get_json(url)['people']\n\ndef get_iss_location():\n \"\"\"Returns the current latitude and longitude of the ISS\"\"\"\n url = \"http://api.open-notify.org/iss-now.json\"\n position = get_json(url)['iss_position']\n return position['latitude'], position['longitude']\n\ndef get_address(position):\n \"\"\"Do a reverse lookup getting the closest address to a given position\"\"\"\n return reverse_geocoder.search(position)[0]\n\ndef main():\n astronauts_in_space = get_astronauts()\n print(\"People in space : \", len(astronauts_in_space))\n print(\"----NAMES----\")\n for astronaut in astronauts_in_space:\n print(astronaut['name'])\n\n iss_position = get_iss_location()\n print(\"Latitude: {}, Longitude: {}\".format(*position))\n\n address = get_address(iss_position)\n print(\"----Address----\")\n print(f\"{address['name']}, {address['admin1']} {address['admin2']} {address['cc']}\")\n\nif __name__ == \"__main__\":\n main()\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-19T13:54:13.830", "Id": "417472", "Score": "2", "body": "I would add a function \"get_data(url)\" where you can pass the url and it returns a response" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-19T13:55:03.187", "Id": "417473", "Score": "1", "body": "@Margon True, I was on edge whether or not I would add it, since it is only repeated once..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-19T14:00:22.020", "Id": "417475", "Score": "1", "body": "@Margon This even fixed some bugs (typos and the fact that the dictionary returned by `.json()` does not have a `raise_for_status` method)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-19T14:00:37.617", "Id": "417476", "Score": "3", "body": "Yeah, I quite agree with you, but it's better to give the \"best practices\", so he can re-use the code if he wants to add more api" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-25T07:42:21.977", "Id": "431683", "Score": "0", "body": "Thank You very much :)" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-19T11:54:30.763", "Id": "215742", "ParentId": "215737", "Score": "12" } } ]
{ "AcceptedAnswerId": "215742", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-19T09:45:38.027", "Id": "215737", "Score": "14", "Tags": [ "python", "beginner", "python-3.x" ], "Title": "Script to load the ISS location and data" }
215737
<p>The problem is to take a list of integers and map them to another list containing those integers added to their respective position in the list.</p> <p>Example runs with required outputs:</p> <pre class="lang-lisp prettyprint-override"><code>&gt; (pos+ '(1 1 1 1)) (1 2 3 4) &gt; (pos+ '(7 5 1 4)) (7 6 3 7) </code></pre> <p>We are required to develop three alternate solutions. One using recursion, one using iteration, and one using mapcar.</p> <p>I present my solutions below and seek comments on style, best coding conventions &amp; habits to adopt. Also the question of which solution is preferred for this particular case arises, including justification for the choice.</p> <p>Observations (on which I seek discussion) are included as comments in the code.</p> <pre class="lang-lisp prettyprint-override"><code>;;; (1) Using recursion (defun pos+ (lst) (pos-helper lst 0)) (defun pos-helper (lst n) (if (null lst) nil (cons (+ (first lst) n) (pos-helper (rest lst) (+ n 1))))) ;; Elegant, as recursion often is, but not a tail call (cant abandon stack frame), ;; hence less efficient at scale (which may not matter). ;;; (2) With iteration (defun pos+2 (lst) (do ((i 0 (+ i 1))) ((&gt;= i (length lst)) lst) (setf (nth i lst) (+ (nth i lst) i)))) ;; Fewer lines, but i have a feeling of disappointment to be learning lisp ;; and not be using a functional style. Q. Is that intuition well-placed? ;;; (3) With mapcar (defun pos+3 (lst) (mapcar #'(lambda (x y) (+ x y)) lst (range (length lst)))) ;; This would be my 'most beautiful' solution except for one problem. ;; Could not find any built in range function. I found range [footnote 1] ;; and pasted it here. The syntax doesn't look anything like CL to me! (defun range (max &amp;key (min 0) (step 1)) (loop for n from min below max by step ;; did the lisp alien write this?! :) collect n)) </code></pre> <p><a href="https://stackoverflow.com/questions/13937520/pythons-range-analog-in-common-lisp">link to range function used above</a> </p>
[]
[ { "body": "<p>For <a href=\"http://www.lispworks.com/documentation/HyperSpec/Body/m_loop.htm#loop\" rel=\"nofollow noreferrer\"><code>loop</code></a> you can see the excellent book by P. Seibel “Practical Common Lisp”, <a href=\"http://www.gigamonkeys.com/book/\" rel=\"nofollow noreferrer\">available on-line</a>, in particular <a href=\"http://www.gigamonkeys.com/book/macros-standard-control-constructs.html\" rel=\"nofollow noreferrer\">chapter 7</a> and <a href=\"http://www.gigamonkeys.com/book/loop-for-black-belts.html\" rel=\"nofollow noreferrer\">chapter 22</a>.</p>\n\n<p>Let’s start from the last function: the idea is ok, we can just simplify the function noting that <code>(lambda (x y) (+ x y))</code> is nothing more than the original <code>+</code>:</p>\n\n<pre><code>(defun pos+3 (lst)\n (mapcar #'+ lst (range (length lst))))\n</code></pre>\n\n<p>For the first function, since an helper function is introduced, it could as well be used for tail-recursion, instead of normal recursion:</p>\n\n<pre><code>(defun pos-helper (lis n acc)\n (if (null lis)\n (reverse acc)\n (pos-helper (rest lis) (1+ n) (cons (+ (first lis) n) acc))))\n\n(defun pos+ (lis)\n (pos-helper lis 0 nil))\n</code></pre>\n\n<p>where <code>acc</code> accumulates the result, which at the end must be reversed. Note that certain Common Lisp compilers transform the function in an iterative loop, so I do not know if this would be considered recursive. In that case, your version is ok (but note the idiomatic use of <code>(1+ expression)</code> instead of <code>(+ expression 1)</code>).</p>\n\n<p>Then, for the second function, of course a <code>loop</code> version is much more readable (even if it is not so lispy :) :</p>\n\n<pre><code>(defun pos+2 (lis)\n (loop for i from 0 \n for x in lis\n collect (+ x i)))\n</code></pre>\n\n<p>If you prefer more parentheses, here is a variant (without modifying the original list):</p>\n\n<pre><code>(defun pos+2 (lis)\n (let ((result nil))\n (do ((i 0 (1+ i))\n (y lis (cdr y)))\n ((null y) (reverse result))\n (push (+ (car y) i) result))))\n</code></pre>\n\n<p>A final note about efficiency: the function <code>pos3</code> is the less efficient one since it must generate a new list with the same length as the original one (and so the list must be scanned twice, in addition to doubling the memory footprint of the program). With a simple trick we could use <code>mapcar</code> and avoid creating a new list:</p>\n\n<pre><code>(defun pos+3 (lis)\n (let ((index -1))\n (mapcar (lambda (x) (+ x (incf index))) lis)))\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-19T13:13:20.790", "Id": "417465", "Score": "0", "body": "Thank you @Renzo! May I ask a stylistic question on the 1+ function: I *do want to use it* and probably will, but first impression is it seems syntactically egregious, appearing to imply infix notation. Does one just get used to the functions `1+` & `1-`, or is there some mitigating reason for them to be named that way which does make them aesthetically 'ok'? e.g. obviously 'inc' & 'dec' are just one more character, and don't _'look like a typo'_, which to me those do in a way, at least right now!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-19T13:55:53.863", "Id": "417474", "Score": "1", "body": "I confess at first using `1+` and `1-` was not always immediate for me, but after some time I was quite used to them. Maybe `inc` and `dec` were not used since they look too similar to `incf` and `decf`, that have a very different meaning, or maybe it was considered funny to prove that in CommonLisp symbols can have very peculiar names! Modern compiler optimization techniques of course make useless such specific operators, however, and I think they are still used just because of habit." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-19T16:01:06.747", "Id": "417492", "Score": "0", "body": "Your final example is something I now realise I'd wanted to express but didn't know how get an incrementing value into the function passed to the map function. Mutable state 'to the rescue' (?). (is this barski's \"lisp alien\" rearing its hand-trunk for us? :)) In sum, maybe that final three liner wins hands down for compactness, of all the versions we've considered. What do you think? So to conclude: Q. Are there *any* drawbacks of coding in this way? (i do yearn for more recursion on aesthetic grounds, but the mapcar with state version looks like it could be the winner :))" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-20T09:21:30.660", "Id": "417616", "Score": "1", "body": "@mwal, yes, I love the barki's cartoon too. For the best version: for readability I am oriented towards the loop solution, but the last one is surely a good second for me. After so many years of programming, I tend to see recursion as just another tool to use when needed: the elegance for me is mostly a mix of readability, conciseness and efficiency." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-19T12:14:19.363", "Id": "215744", "ParentId": "215739", "Score": "5" } }, { "body": "<h3>General style remarks</h3>\n\n<ul>\n<li><code>lst</code> is more of a Scheme idiom, in Common Lisp you don't eat vowels but write directly <code>list</code> if your variable is a list (to be honest, some CL standard functions have weird names too).</li>\n<li><em>\"Functional = Elegant\"</em> is somewhat true, but don't let purity blind you into ignoring perfectly good alternative approaches; it is often reasonable to have a purely functional interface implemented with local mutable state, for example. Building a fresh list and reversing it is a pure functional way to implement map, but that's not how you implement an efficient map function.</li>\n</ul>\n\n<h3>Tail-call elimination</h3>\n\n<p>For solution 1, you define a helper function; you can use a tail-recursive call if you add an accumulator parameter to hold the reversed result list. For example:</p>\n\n<pre><code>(defun pos+helper (list result position)\n (if list\n (pos+helper (rest list)\n (cons (+ (first list) position) result)\n (1+ position))\n result))\n</code></pre>\n\n<p>Note however that Lisp being dynamic, it is possible that you can at a later point redefine <code>pos+helper</code> to be another function, which prevents the compiler to automatically transform it as a loop. Consider for example the case where you want to <code>trace</code> an existing function: the original function is likely to be instrumented by wrapping it into another function, and then the recursive call is calling the resulting wrapper. </p>\n\n<p>Whether I compile the above function with <code>(optimize speed)</code> declaration or not, I obtain different outputs with <code>disassemble</code>. When speed is not optimized, the recursive call is effectively a CALL, which grows the stack but allows for a redefinition of <code>pos+helper</code>. A simpler example:</p>\n\n<pre><code>(defun tester ()\n (sleep 2)\n (tester))\n\n(ql:quickload :bordeaux-threads)\n(bt:make-thread #'tester :name \"tester\")\n</code></pre>\n\n<p>I created a thread which calls <code>tester</code>, which contains a call to <code>sleep</code> to slow down the infinite recursion, to avoid stack overflows.</p>\n\n<pre><code>USER&gt; (find \"tester\" (bt:all-threads) :test #'string= :key #'bt:thread-name)\n#&lt;SB-THREAD:THREAD \"tester\" RUNNING {100CC049F3}&gt;\n</code></pre>\n\n<p>The thread is found in the list of all threads, which means it is alive and the function is effectively recursing infinitely. Now, if I redefine <code>tester</code>:</p>\n\n<pre><code>(defun tester () :done)\n</code></pre>\n\n<p>Then the thread is stopped:</p>\n\n<pre><code>USER&gt; (find \"tester\" (bt:all-threads) :test #'string= :key #'bt:thread-name)\nNIL\n</code></pre>\n\n<p>This is obviously implementation dependant, but if I declare the function to be optimized for speed, no amount of redefinition changes the behaviour of the function under test.</p>\n\n<p>You have better control of this if you define your helper function locally:</p>\n\n<pre><code>(defun pos+ (list)\n (labels ((recurse (list result position)\n (if list\n (recurse (rest list)\n (cons (+ (first list) position) result)\n (1+ position))\n result)))\n (nreverse (recurse list nil 0))))\n</code></pre>\n\n<p>First, it hides the auxiliary function, which is after all an implementation detail; but most importantly, since the body of a function is <em>static</em> in the sense that you do not redefine parts of it at runtime, the compiler is able to infer that <code>recurse</code> is never going to change, and can do the tail-call elimination without additional hints (most compilers can do that easily, except on platforms like Java (ABCL) where this is not possible).</p>\n\n<p>(opinion: tail-call elimination breaks the elegance of the purely functional approach by making you rearrange parameters to satisfy an implicit, particular case where calls can be converted as jumps; in other words, this is a hack. In languages that mandates tail-call elimination, this is less of a hack, but not necessarily elegant either.)</p>\n\n<p>The portable way to implement a loop is to write a loop or higher-level functions.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-20T10:02:31.577", "Id": "215829", "ParentId": "215739", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-19T10:02:42.843", "Id": "215739", "Score": "3", "Tags": [ "common-lisp" ], "Title": "pos+ (value added to position) - ex 3.5 in “ANSI Common Lisp” (p57)" }
215739
<p>i am currently learning to do things with vanilla Javascript. No plugins, libraries or code snippets. I want to do things on my own, so that I understand 100% of what is happening.</p> <p>I wrote a little script which checks, if a section of the page is in view.</p> <p>Now, the script works as expected, but I was wondering, if I had accomplished the task in a good way. I am especially unsure about looping over the sections in a scroll event. I would love to get some feedback on this. <a href="http://dennisfink.de/projects/scrollOn/scrollOnBeispiel.html?fbclid=IwAR0vTfDImiujqW-yZdt5ovb-ii3EhCo3jxNXnM65SfbGOAENXTUrGYpJIrg" rel="nofollow noreferrer">Example page</a></p> <p>Here is the code</p> <pre><code>(function () { // Store all panels in variable const panels = document.querySelectorAll(".panel"); // Window on load event window.addEventListener("load", () =&gt; { let scrollTop = window.scrollY; let windowHeight = window.innerHeight; let documentHeight = document.body.offsetHeight; panels.forEach( panel =&gt; { if(scrollTop == panel.offsetTop ){ panel.classList.add("is-visible"); } }); }); // end of load event // Window on scroll event window.addEventListener("scroll", () =&gt; { let scrollTop = window.scrollY; let windowHeight = window.innerHeight; let documentHeight = document.body.offsetHeight; panels.forEach( panel =&gt; { if(scrollTop &gt;= panel.offsetTop - ( windowHeight / 2)){ panel.classList.add("is-visible"); } else { panel.classList.remove("is-visible"); } if(scrollTop &gt;= (panel.offsetTop + panel.clientHeight) - ( windowHeight / 2) ) { panel.classList.remove("is-visible"); } }); }); // end of scroll event })(); </code></pre> <p><strong>APPENDIX</strong></p> <p>So I refactored the code as follows. I am still not sure about things like the IIFs.</p> <pre><code>(function(){ const panels = document.querySelectorAll(".panel"); let scrolling = false; (function windowOnLoad () { // Window on load event window.addEventListener("load", () =&gt; { let scrollTop = window.scrollY; let windowHeight = window.innerHeight; let documentHeight = document.body.offsetHeight; panels.forEach( panel =&gt; { if(scrollTop == panel.offsetTop ){ panel.classList.add("is-visible"); } }); }); // end of load event })(); (function windowOnSCroll(){ window.addEventListener("scroll", () =&gt; { scrolling = true; }); })(); setInterval( function() { if (scrolling) { scrolling = false; let scrollTop = window.scrollY; let windowHeight = window.innerHeight; let documentHeight = document.body.offsetHeight; panels.forEach( panel =&gt; { if(scrollTop &gt;= panel.offsetTop - ( windowHeight / 2)){ panel.classList.add("is-visible"); } else { panel.classList.remove("is-visible"); } if(scrollTop &gt;= (panel.offsetTop + panel.clientHeight) - ( windowHeight / 2) ) { panel.classList.remove("is-visible"); } }); } }, 250 ); })(); </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-19T13:54:09.320", "Id": "417470", "Score": "1", "body": "Hey, just a small tip. The scroll event fires a lot, and this may cause performance issues, you can resolve this by debouncing the event." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-19T16:07:04.283", "Id": "417495", "Score": "0", "body": "Thanks for your comment. Actually I have never heart about debouncing events. I just did a quick research. So, what would be a good way to debounce? Depending on pixels or on time?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-19T16:17:03.480", "Id": "417499", "Score": "1", "body": "I suggest something like this: https://www.google.com/amp/s/benmarshall.me/attaching-javascript-handlers-to-scroll-events/amp/" } ]
[ { "body": "<blockquote>\n <p><em>I am especially unsure about looping over the sections in a scroll event.</em></p>\n</blockquote>\n\n<p>There doesn't seem to be much of an alternative. One could select all elements with class name <code>is-visible</code>:</p>\n\n<pre><code>const visible = document.getElementsByClassName('is-visible');\n</code></pre>\n\n<p>Note that that collection is live, meaning it will be updated dynamically as the DOM changes, so there isn't any reason to re-query the DOM for those.</p>\n\n<p>In the version that attempts to debounce the DOM updates, the IIFEs seem a bit excessive. Is the goal to limit scope of variables?</p>\n\n<hr>\n\n<p>The function passed to <code>panels.forEach()</code> could be simplified:</p>\n\n<blockquote>\n<pre><code>panel =&gt; {\n if(scrollTop &gt;= panel.offsetTop - ( windowHeight / 2)){\n panel.classList.add(\"is-visible\");\n } else {\n panel.classList.remove(\"is-visible\");\n }\n if(scrollTop &gt;= (panel.offsetTop + panel.clientHeight) - ( windowHeight / 2) ) {\n panel.classList.remove(\"is-visible\");\n }\n}\n</code></pre>\n</blockquote>\n\n<p>This can be simplified by calling <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Element/classList#Methods\" rel=\"nofollow noreferrer\"><code>Element.classList.toggle()</code></a> with two arguments.</p>\n\n<pre><code>panel =&gt; {\n let addClass = scrollTop &gt;= panel.offsetTop - ( windowHeight / 2);\n\n if(scrollTop &gt;= (panel.offsetTop + panel.clientHeight) - ( windowHeight / 2) ) {\n addClass = false;\n }\n panel.classList.toggle(\"is-visible\", addClass);\n}\n</code></pre>\n\n<hr>\n\n<blockquote>\n<pre><code>const panels = document.querySelectorAll(\".panel\");\n</code></pre>\n</blockquote>\n\n<p>In most browsers it would generally be quicker to fetch the game squares using <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Element/getElementsByClassName\" rel=\"nofollow noreferrer\"><code>document.getElementsByClassName()</code></a>, but that would return a live collection (refer to <a href=\"https://stackoverflow.com/a/39213298/1575353\">this SO answer</a> for an explanation). </p>\n\n<pre><code> const panels = [...document.getElementsByClassName(\"panel\")];\n</code></pre>\n\n<hr>\n\n<p>The debounced version looks a little bit un-efficient because it uses an interval so that function gets executed more than it needs to. </p>\n\n<p>There are also many arguments not to use <code>setInterval</code> and <code>setTimeout</code> - e.g. <a href=\"https://stackoverflow.com/q/38709923/1575353\">blindman67's SO Post <em>Why is requestAnimationFrame better than setInterval or setTimeout</em></a></p>\n\n<p>The functionality from the <code>setInterval</code> callback could be put into a function called <code>checkVisibility</code>. Then the scroll handler could be simplified to use <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame\" rel=\"nofollow noreferrer\"><code>requestAnimationFrame()</code></a></p>\n\n<pre><code>let timeout;\nwindow.addEventListener(\"scroll\", _ =&gt; {\n if (timeout) {\n window.cancelAnimationFrame(timeout);\n }\n timeout = window.requestAnimationFrame(checkVisibility);\n}); \n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-05T00:29:43.653", "Id": "231860", "ParentId": "215743", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-19T12:02:45.933", "Id": "215743", "Score": "6", "Tags": [ "javascript", "ecmascript-6", "event-handling", "dom" ], "Title": "Determine if a section is in view" }
215743
<p>I have question about my code. It should swap words from an array into an HTML Element and it does so like expected. However, I was wondering about the style of my code. I would like to get some feedback on how to improve the code.</p> <p><strong>Javascript</strong></p> <pre><code>const words = [ "Webdesigner", "Frontend Entwickler", "Webentwickler", "eine Flitzpiepe" ]; const interval = 2000; function swapWords(words, interval){ const swappingWord = document.getElementById("swappingWord"); let i = 0; setInterval(function(){ swappingWord.textContent = words[i].toUpperCase(); i++; if(i == words.length){ i = 0; } }, interval) } swapWords(words, interval) </code></pre> <p><strong>HTML</strong></p> <pre><code>&lt;span id="swappingWord"&gt;WEBDESIGNER&lt;/span&gt; </code></pre>
[]
[ { "body": "<ol>\n<li>There is no way to remove the behavior. This is usually bad design.</li>\n<li>Since there is no way to remove behavior, <code>swapWords()</code> as a function is unneeded: you will never call it twice. It would only make sense defining it as a function if it could be called on different elements.</li>\n<li>The initial state of the cycle is undefined and/or inconsistent: since the first swap only occurs after 2s, until then the initial content of the span will be displayed (WEBDESIGNER). Then it will be swapped with... WEBDESIGNER. Either leave the span empty and explicitly call a swap round on initialisation, or push the initial contents of the span on top of the stack of words. Otherwise it's not a cycle, it's a \"weird start, then a cycle\".</li>\n<li><code>if(i == words.length){</code> - ok, you defined words as <code>const</code> so this is safe. But it's a bad habit to develop to write code like this: if <code>words</code> was variable between rounds, as it got trimmed from, say, 6 items to 4, and <code>i</code> would be 5, the condition would not be triggered anymore, and also not checked before access. So it would just go on to infinity. The responsible way to write code is always update and bound-check any state vars in a synchronous matter, which means BEFORE using them (i.e. before <code>swappingWord.textContent = words[i].toUpperCase();</code>), not at the end of the round for the next async round. Also always use <code>&gt;=words.length</code> not <code>==words.length</code>, as a coding habit. Always test for valid/invalid condition, not edge condition. In case you decide later to make <code>words</code> list variable, the <code>==</code> condition will automatically introduce a bug. <code>&gt;=</code> won't. The remarks of this point don't qualify as bad code (it works as long as you don't change initial assumptions), it's just bad style. Get rid of it before you get used to it :)</li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-19T16:02:10.920", "Id": "417493", "Score": "0", "body": "Thanks for your answer! I think i will need some time to fully understand it. Maybe I can post a refactored version of the code at a later point." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-19T16:24:30.760", "Id": "417501", "Score": "0", "body": "You're welcome, I hope it's useful! Maybe it's not very clear, I'm new around here." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-19T13:06:33.573", "Id": "215748", "ParentId": "215747", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-19T12:51:06.993", "Id": "215747", "Score": "1", "Tags": [ "javascript" ], "Title": "Swap a word in the DOM from an array of words" }
215747
<p>I am working on a program that checks for the browser support of a CSS file. Below you can find my working code, so far it supports CSS At-Rules &amp; Properties. In the next few weeks, I will need to expand this code so that I can slowly support the entire language.</p> <p>I am trying to come up with a readable and efficient system, keep in mind that some CSS files can get huge (10.000 + Lines), so I want to keep the iteration count as low as possible.</p> <p>There are a couple of things bothering me at the moment, for once, I don't like that I have different functions to check the browser support ('getAtruleSupportData' &amp; 'getPropertySupportData'). I am quite sure I can write this in a single function but I have had no success so far. The other thing that really bothers me is the 'checkBrowserSupport' function itself. I am not sure, what to think about it, but the more I expand it, the more 'reduces' and 'filters' I will need to use. I am not sure this is going to scale at all.</p> <p>In general, I want to improve the scalability of my code, it's readability and general performance. Any help is more than welcome.</p> <p><strong>Example Input:</strong></p> <pre><code>{ atrules: [ { type: 'Atrule', loc: [Object], name: 'media', prelude: [Object], block: [Object] } ], declarations: [ { type: 'Declaration', loc: [Object], important: false, property: 'margin', value: [Object] }, { type: 'Declaration', loc: [Object], important: false, property: 'margin', value: [Object] } ], mediaFeatures: [ { type: 'MediaFeature', loc: [Object], name: 'min-width', value: [Object] } ] } </code></pre> <p><strong>Example Browserscope:</strong></p> <pre><code>const browserscope = { chrome: 60, edge: 15, firefox: 60, ie: 10, safari: 10, }; </code></pre> <p><strong>Working Code:</strong></p> <pre><code>const bcd = require('mdn-browser-compat-data'); const checkBrowserSupport = ({atrules, declarations}, browserscope) =&gt; { return { atrules: atrules .reduce((acc, {name, loc}) =&gt; { const supportData = getAtruleSupportData(name); supportData &amp;&amp; acc.push(formatData(browserscope, name, loc, supportData)); return acc; }, []) .filter((atrule) =&gt; atrule.notSupported.length), declarations: declarations .reduce((acc, {property, loc}) =&gt; { const supportData = getPropertySupportData(property); supportData &amp;&amp; acc.push(formatData(browserscope, property, loc, supportData)); return acc; }, []) .filter((property) =&gt; property.notSupported.length), }; }; const formatData = (browserscope, name, loc, supportData) =&gt; { const {line, column} = loc.start; return Object.entries(browserscope).reduce((acc, [browser, version]) =&gt; { acc.name = name; acc.location = {line, column}; acc.supported = acc.supported || []; acc.notSupported = acc.notSupported || []; const browserSupportData = Array.isArray(supportData[browser]) ? supportData[browser][0].version_added : supportData[browser].version_added; browserSupportData &amp;&amp; browserSupportData &lt;= version ? acc.supported.push(browser) : acc.notSupported.push(browser); return acc; }, {}); }; const getAtruleSupportData = (atrule) =&gt; { try { return bcd.css['at-rules'][atrule].__compat.support; } catch (error) { return false; } }; const getPropertySupportData = (property) =&gt; { try { return bcd.css.properties[property].__compat.support; } catch (error) { return false; } }; module.exports = { checkBrowserSupport, }; </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-19T13:12:35.613", "Id": "215749", "Score": "2", "Tags": [ "javascript", "performance", "node.js" ], "Title": "A CSS Browser Compatibility Checker" }
215749
<p>I'm putting together a basic web app in .NET core 2.1 MVC to try and better understand how it works. Currently I'm working on returning validation to the UI. Once I have this working I then want to use the same service class for a Web API front end too.</p> <p>Currently the Create Action in the Controller calls the service layer, which returns my ValidationResultModel. This is then checked and errors are displayed or redirected to the index if all was ok.</p> <pre><code>[HttpPost] [ValidateAntiForgeryToken] public async Task&lt;IActionResult&gt; Create(CreateSupplierViewModel createSupplierViewModel) { if (ModelState.IsValid) { Suppliers suppliers = _mapper.Map&lt;Suppliers&gt;(createSupplierViewModel); SuppliersService suppliersService = new SuppliersService(_context); ValidationResultModel returnData = suppliersService.Add(suppliers); if(returnData.Message== "Success") { return RedirectToAction(nameof(Index)); } foreach (ValidationError ve in returnData.Errors) { ModelState.AddModelError(ve.Field, ve.Message); } } return View(createSupplierViewModel); } </code></pre> <p>In the supplierService Add Method I check if the accounts ID has been used, and run some other fluentvalidaion in the SupplierValidator class</p> <pre><code>public ValidationResultModel Add(Suppliers newSupplier) { ValidationResultModel vrm = new ValidationResultModel(); var suppliers = _stockContext.Suppliers.Where(supplier =&gt; supplier.AccountsId == newSupplier.AccountsId).FirstOrDefault(); if (suppliers != null) { vrm.Message = "Failure"; ValidationError re = new ValidationError("AccountsId", "This Accounts ID already exists"); vrm.Errors.Add(re); } SupplierValidator supplierValidator = new SupplierValidator(); var results = supplierValidator.Validate(newSupplier); if (!results.IsValid) { foreach (var validationError in results.Errors) { vrm.Message = "Failure"; vrm.Errors.Add(new ValidationError(validationError.PropertyName, validationError.ErrorMessage)); } } if (vrm.Message != "Failure") { _stockContext.Add(newSupplier); _stockContext.SaveChanges(); } return vrm; } </code></pre> <p>Validation Classes:</p> <pre><code>public class ValidationError { public string Field { get; } public string Message { get; } public ValidationError(string field, string message) { Field = field != string.Empty ? field : null; Message = message; } } public class ValidationResultModel { public string Message { get; set; } public List&lt;ValidationError&gt; Errors { get; set; } public ValidationResultModel() { Message = "Success"; Errors = new List&lt;ValidationError&gt;(); } } </code></pre> <p>Everything is functioning, but it feels very clunky. One of my main worries is what happens when I want to send back something in addition to the ValidationResultModel. Is there a better way of doing this. Or indeed a set of Core classes that do exactly this, that I need to read up on?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-19T19:12:31.537", "Id": "417530", "Score": "0", "body": "What .Net Core version do you use?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-20T09:35:39.950", "Id": "417619", "Score": "0", "body": "Using .Net Core 2.1. The Code is working fine, but I'm not sure about the best way to deal with the possible exceptions that could be generated." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-19T13:37:14.763", "Id": "215750", "Score": "4", "Tags": [ "c#", "mvc", "asp.net-core" ], "Title": "MVC Controller Error & Exception Handling .NET Core" }
215750
<p>I've recently vectorized most of the code for an optimization problem but this one still eludes me. As the procedure and not the actual values are important here, I have replaced the original matrices with random dummies.</p> <p><strong>Problem:</strong><br> Given a matrix <code>A</code> of shape <code>(m x n)</code> and a three dimensional matrix <code>B</code> of shape <code>(n x (n-1)*r x m)</code> multiply the i-th row of <code>A</code> with the i-th slice/page of <code>B</code> for i=1,...,m . This yields a matrix of shape <code>m x (n-1)*r</code>.<br> <strong>Note</strong> that I have arranged the m two dimensional matrices in a three dimensional matrix <code>B</code>, which is not necessarily a given. <code>B</code> can as well be modeled as a block matrix or other applicable shapes.</p> <p><strong>Criterion:</strong><br> As this code is evaluated very often as part of the optimization, it is crucial that it is as fast as possible. Memorywise it does not need to be optimal, but it should remain within feasible limits, as <code>m=6000</code>, <code>n=6</code> and <code>r=2</code> are rather the lower end of the expected dimension of the problem.</p> <p><strong>What I have tried:</strong> </p> <p>The code below is the first solution that came to my mind and the one that so far has proven the fastest. I have tried replacing the for-loop by using <code>cellfun</code>, but this has not proven to be faster.<br> Trying to approach this in a vectorized fashion, I also tried structuring B instead of a 3D matrix as a 2D, horizontal block matrix B* with the 'slices' of B simply appended as columns. Then matrix multiplication can then be used to obtain a <code>(m x (n-1)*r*m)</code> matrix where the solution is found on the diagonal + some offset. However, this is of course horribly inefficient, as most of the result matrix isn't required and such a matrix becomes intractable from a memory perspective pretty quickly.</p> <pre><code>rng(1) m = 6000; n = 6; r = 2; A = rand(m,n); B = rand(n,(n-1)*r,m); result = zeros(m,(n-1)*r); for i=1:m result(i,:) = A(i,:) * B(:,:,i); end </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-24T00:36:54.013", "Id": "418113", "Score": "0", "body": "`cellfun` is implemented as an M-file with a loop, so it’s unsurprising that it’s not any faster. I have no comments on your code, it’s correct and likely optimal. Loops are no longer slow in MATLAB, vectorization is only beneficial if it doesn’t involve large intermediate matrices or complex indexing." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-26T12:43:44.357", "Id": "423364", "Score": "0", "body": "Could it be you meant: `result = zeros(m,(n-1)*r, m);` and `result(:, :, i) = A(i,:) * B(:,:,i);`?" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-19T14:05:32.170", "Id": "215754", "Score": "3", "Tags": [ "performance", "mathematics", "matlab", "vectorization" ], "Title": "Optimising multiplication of matrix rows with matrix slice/page" }
215754
<p>I want to create a RESTful API with Apache/PHP and the Slim Framework (3.x). The API should support URI-based versioning like <code>&lt;host&gt;/rest/api/v1/&lt;resource&gt;</code> and <code>&lt;host&gt;/rest/api/latest/&lt;resource&gt;</code>.</p> <p>Overall I found a solution which works, but I not really happy with my solution and I'm want to known what can I make better. I'm a rookie/newbie about Slim. I'm looking for new ideas and how I can improve my knowledge about Slim.</p> <p>Every new version should be a new project, which a own independent code base. The version dispatching should be done by the Apache server and no in the PHP/Slim code. I found some example which implements different versions of the API in on project by using the group-method. But I'm not very happy with this solution. I feel better to have independent projects for independent versions.</p> <ul> <li>General improvements or comments?</li> <li>Do you have a better/simpler solution?</li> <li>Do you see problems in my solution?</li> <li>Improvements for .htaccess / rewrite rules</li> <li>Links to real implementations of a RESTful API with Slim</li> <li>....</li> </ul> <p>I'm looking forward for your answers and I'll be curious to see what's new.</p> <hr> <p>The implementation of all version of the API are in the Apache <code>htdoc</code> folder with following structure</p> <pre><code>rest +--api +-v1 +-.htaccess +-index.php +-v2 +-.htaccess +-index.php +-.htaccess +-index.html </code></pre> <p>The implementation of the API are in the file <code>index.php</code>. Map calls like <code>/rest/api/v1/books</code> to my implementation I create in every version folder a <code>.htaccess</code> file which includes rules for the rewrite Apache module:</p> <pre><code>RewriteEngine On RewriteRule ^ index.php [QSA,L] </code></pre> <p>In <code>index.php</code> I create some routes</p> <pre><code>$app-&gt;get('/books', function ... $app-&gt;get('/books/{id}', function ... </code></pre> <p>Everything works fine if I use a explicit version in the URI (<code>&lt;host&gt;/rest/api/v2/books</code>). For convenience if I create an alias <em>latest</em> (<code>/rest/api/latest/books</code>), which redirect the alias-call to the latest version of the API version. </p> <p>Therefore I create the file <code>rest/api/.htaccess</code> which rewrites the URI to an implementation: </p> <pre><code>RewriteEngine On RewriteRule ^latest.*$ ./v2/index.php [QSA,L] </code></pre> <p>The rewrite rule works fine and the v2 implementation are called. But the routes don't match anymore. I found out that the original path is now part of the path.</p> <pre><code>/rest/api/v2/books -&gt; /books /rest/api/latest/books -&gt; /rest/api/latest/books </code></pre> <p>If I modified the rules like this, it works - but I don't like to implement every rule twice.</p> <pre><code>$app-&gt;get('/rest/api/latest/books', function ... $app-&gt;get('/rest/api/latest/books/{id}', function ... </code></pre> <p>Therefore I wrote a middleware function which trims <code>/rest/api/latest</code> from the path before the routes are matched.</p> <pre><code>$app-&gt;add(function (Request $request, Response $response, callable $next) { $uri = $request-&gt;getUri(); $path = $uri-&gt;getPath(); if (substr($path,0,16) == "/rest/api/latest") { $uri = $uri-&gt;withPath(substr($path,16)); return $next($request-&gt;withUri($uri), $response); } return $next($request, $response); }); </code></pre> <p>Now I can use the same rules for both cases, explicit version call and implicit version call. </p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-20T02:47:17.593", "Id": "417573", "Score": "0", "body": "...not really worth posting as a proper review, but I recommend using `strpos($path, $needle) === 0` instead of `substr($path, 0, 16) == $needle`. https://gist.github.com/vicb/1596588 (It is more of a habit rather than a micro-optimization for me because there is no need to extract the substring, just check if it is at position `0`. Plus, if you ever need to adjust the needle, you don't have to recount the substring length with your finger on the monitor.)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-20T09:43:51.617", "Id": "417620", "Score": "0", "body": "@mickmackusa Thank you for your answer. Yes you are absolutely right `strpos` is much better/nicer than `substr`. I cannot use my fingers, because I have only ten :-D" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-19T14:46:37.463", "Id": "215755", "Score": "1", "Tags": [ "php", "api", "rest", ".htaccess", "slim" ], "Title": "Implement versioning of a RESTful API with PHP/Slim and Apache" }
215755
<p>I´m currently working on a small microservice application, which will in it´s simplest form just receive a Request from a Formular and and based on containing information perform several other Server-request to different API´s using the <code>Fetch API</code>.</p> <p>For now I´m just about to create a prototype that contains the Application structure and the promise-chain structure which I´d prefer to use. </p> <p>I`ve created a prototype which is showing what I´m doing here. My Question is now if this is the right use of promises in which errors i would probably run in a production mode. </p> <p>I´m currently feeling like I would do it wrong, therefore I´m asking for an advice here.</p> <p>This is my Controller class which receives the Request:</p> <pre><code>'use strict'; var indexService = require('../services/index'); class IndexController { constructor(router) { this.router = router; this.registerRoutes(); } registerRoutes() { this.router.get('/', this.index.bind(this)); } index(req, res){ indexService.test() .then(data =&gt; res.json(data)) .then(test =&gt; console.log("Maybe have to do other things after repsonding to client")) .catch(err =&gt; console.log(err)); } } module.exports = IndexController; </code></pre> <p>And this is my Service Class for the business logic:</p> <pre><code>'use strict'; const fetch = require("node-fetch"); const HttpsProxyAgent = require('https-proxy-agent'); class IndexService { constructor() { } test(){ var _this = this; return new Promise(function(resolve, reject) { console.log("INSIDE PROMIES"); _this.getOne() .then(function(data){ resolve(data); }) .catch(function(error){ console.log("Not connection to endpoint possible 1"); reject(error); }); }) .then(function(data){ //based on data I call two or three console.log("ALSO REACHED THIS ONE"); if("a"){ _this.getTwo() .then(function(data){ return data; }) .catch(function(error){ console.log("Not connection to endpoint possible 2"); return error; }); }else{ _this.getThree() .then(function(data){ return data; }) .catch(function(error){ console.log("Not connection to endpoint possible 2"); return error; }); } return data; }).then(function(data){ console.log(data); return data; }) .catch(function(err){ console.log("ERROR REACHED"); console.log(err); throw "error"; }); } async getOne(){ let response = await fetch('https://jsonplaceholder.typicode.com/todos/1', { agent: new HttpsProxyAgent("http://xxx:80"), }); if(response.ok){ console.log("Response OK"); // console.log(response); let data = await response.json(); return data; }else{ console.log("Response NOT OK"); //console.log(response); return null; } } async getTwo(){ let response = await fetch('https://jsonplaceholder.typicode.com/todos/1', { agent: new HttpsProxyAgent("http:/xxxx:80"), }); if(response.ok){ console.log("Response OK"); // console.log(response); let data = await response.json(); return data; }else{ console.log("Response NOT OK"); // console.log(response); return null; } } async getThree(){ let response = await fetch('https://jsonplaceholder.typicode.com/todos/1', { agent: new HttpsProxyAgent("http://xxx:80"), }); if(response.ok){ console.log("Response OK"); // console.log(response); let data = await response.json(); return data; }else{ console.log("Response NOT OK"); // console.log(response); return null; } } } module.exports = new IndexService(); </code></pre> <p>To make my question more clear:</p> <ol> <li><p>Am I using the promises correct here? Should I better do everything in the first then and just chain the async class to use <code>resolve or reject</code> on finish?</p></li> <li><p>What could be a problem with the current design when it gets more complex, because i feel like it is not really readable currently? </p></li> <li><p>Should I use <code>new Promise(function(resolve, reject)</code> instead of <code>async function</code>?</p></li> </ol> <p>I´m pretty new to this topic and would love to learn from your knowledge!</p> <p>Thanks.</p>
[]
[ { "body": "<h1>Promise chain callback hell</h1>\n\n<p>The <code>Promise API</code> and now <code>async functions</code> are designed to reduce the number of callbacks (Colloquially known as \"callback hell\"). You have a total of 16 defined callbacks and by all the console logs I see you are struggling to follow the flow (callback hell)</p>\n\n<h2>Your questions</h2>\n\n<blockquote>\n <p>Am I using the promises correct here? \n Should I better do everything in the first then and just chain the async class to use resolve or reject on finish?</p>\n</blockquote>\n\n<p>As the chain of data (dependency, content, immediacy, life...) is not clear it is hard to say. At face value. \"No\" you are not handling the promises correctly, and \"Yes\" in this case handle the rest in the first resolve in the callback. Let the errors fall through to the calling function.</p>\n\n<blockquote>\n <p>What could be a problem with the current design when it gets more complex, because i feel like it is not really readable currently?</p>\n</blockquote>\n\n<p>See the notes below regarding style and readability. </p>\n\n<h2>Parallel systems</h2>\n\n<p>As for increased complexity using the same approach will quickly become a nightmare. You are creating a node in a parallel data processing system. Parallel processing hates dependencies as they increase the latency of the system and increase the chance of dependency lock.</p>\n\n<p>As it stands you have already set up a high latency system. B Depends on A and will not start until A has responded, thus the best response time is 2 times the response time of the service you are using. Add another dependence and the response is 3 times the service response time. This is an unmanageable condition in the real world.</p>\n\n<p>You may ask what should I do? I can not answer as...</p>\n\n<ul>\n<li>I do not know the nature of the data you are fetching, </li>\n<li>I do not know the nature of the service you are calling, especialy its dependencies on other services (lord forbid if it depended on a response from the server you are running the request on).</li>\n</ul>\n\n<p>The only suggestions is likely impractical, \"Keep a local store updated via poling to remove the need for external data dependency chains when responding to requests\" and would likely need a redesign of the whole system.</p>\n\n<h2>Async functions rule.</h2>\n\n<blockquote>\n <p>Should I use new Promise(function(resolve, reject) instead of async function?</p>\n</blockquote>\n\n<p>Use <code>async</code>. The rule of thumb is \"async means not having to type <code>new Promise</code>\" \nSee rewrite</p>\n\n<h2>Notes on style and design</h2>\n\n<ul>\n<li><p><strong>DON'T!!! throw strings</strong> They require special handling and will cause most standard catch handlers to throw an error in the handlers block (the very last place a throw should ever happen). Throw a new instance of an error eg <code>new Error(\"message\")</code> or one of the standard error types eg <code>new RangeError(\"Value to big\")</code></p></li>\n<li><p>Class syntax is bad. It has forced you to expose what should be private functions <code>getOne</code>, <code>getTwo</code>, <code>getThree</code>. In this case you are creating a single instance object for which the class syntax is completely inappropriate.</p></li>\n<li><p>Use arrow functions to avoid the need for hacks like <code>var _this = this;</code></p></li>\n<li><p>Use <code>const</code> for variables that do not change.</p></li>\n<li><p>Use <code>var</code> for variables that do change and are function scoped.</p></li>\n<li><p>Use <code>let</code> for variables that are block scoped.</p></li>\n<li><p>Don't create one use variables unless it improves readability. Eg <code>let data = await response.json(); return data;</code> the variable data is just noise. In this case you can return the promise <code>return response.json();</code></p></li>\n<li><p>Names add abstract meaning. Bad naming results in bugs due to confusion regarding the data being handled. eg you call a promise <code>data</code> in <code>let data = await response.json()</code> The name <code>data</code> is already very generic, but in this case its totally misleading.</p></li>\n<li><p>Avoid the use of <code>null</code> as it is often use as an alias to <code>undefined</code> however it does not have the same semantic meaning, nor does it follow JS convention for undefined return type.</p></li>\n<li><p>If a statement block returns it should not be followed by an <code>else</code> or <code>else if</code> statement block.</p></li>\n<li><p>The two callbacks a promise callback function is passed as arguments should be named appropriately, <code>new Promise((resolve, reject) =&gt;</code> would be better as <code>new Promise((fetchOk, fetchFailed) =&gt;</code></p></li>\n<li><p>Don't create intermediate functions when not required. eg <code>.then(function(data) {resolve(data)})</code> can be <code>.then(resolve)</code></p></li>\n<li><p>Exceptions float to the top. You are returning a promise when you call <code>test</code>, It looks like you intend the calling function to include a <code>.catch</code> callback. That means you do not have to handle the catches inside the function test. just let the exceptions fall though to the calling function.</p></li>\n<li><p>Console logging is for debugging only and has no place in release code. You are using console.log to follow flow. Avoid console logging and use dev tools debugger to follow flow. </p>\n\n<p>One issues with using console is that it forces you to write the code in such a way as to allow for the console expression to exist, often to the detriment of optimal execution and readability. </p></li>\n</ul>\n\n<h2>Rewrite</h2>\n\n<p>It is unclear how you intend to handle this code. Nor is the argument <code>router</code> defined. I assume that the function <code>IndexController.index</code> is only for private use. The returned object <code>IndexController</code> is only a husk object to hold the closure. It has no interface.</p>\n\n<p>Note <code>indexService</code> returns a parsed result not the JSON text</p>\n\n<p>I have created only the one module as they are so tightly integrated.</p>\n\n<pre><code>\"use strict\";\nconst fetch = require(\"node-fetch\");\nconst HttpsProxyAgent = require(\"https-proxy-agent\");\n\nconst service = {\n URL: \"https://jsonplaceholder.typicode.com/todos/\",\n get agent() { return new HttpsProxyAgent(\"http://xxx:80\") },\n};\nasync function todos(name){\n const response = await fetch(service.url + name, {agent : service.agent});\n if (response.ok) { return response.json() }\n throw new Error(\"Fetch of `\" + name + \"` failed. \");\n} \nconst index = async () =&gt; todos(\"1\").then(todo =&gt; todos(todo.foo === \"a\" ? \"2\" : \"3\"));\nfunction IndexController(router) =&gt; {\n router.get(\"/\", (req, res) =&gt; index()\n .then(todos =&gt; /*respond with todos data*/)\n .catch(err =&gt; /*respond with service error*/);\n );\n}\nmodule.exports = IndexController;\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-19T19:58:39.737", "Id": "417539", "Score": "0", "body": "First of all thank you very much for this high quality answer! To make this not too long here in the answer box just one or two things left about the part \"On which data the system dependeds\". The app is build on top of a cloud platform, The Server instance will get a request from an formular hosted somewhere else. Internally a cloud service will get called and afterwards 3 requests will be made to an API Server outside cloud." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-19T19:59:04.603", "Id": "417540", "Score": "0", "body": "second question about the code. In the case as describe could i just call the other requests after and like `const index = async () => todos(\"1\").then(todo => todos(todo.foo === \"a\" ? \"2\" : \"3\"));` of course with other functions than todo." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-19T21:14:05.960", "Id": "417549", "Score": "0", "body": "@elsololobo I am not sure if I understand the question. You can call `index` I did not expose it in the example as I was unsure on its use. If you want to call it from outside the module have `IndexController` return the function directly `return index` or if you use `new IndexController` add it to a new object `return {indexService: index};` . Renaming it back to the original `indexService`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-20T06:29:10.173", "Id": "417586", "Score": "0", "body": "Okay my Question was a bit unclear. What I mean is that if it would be the correct way to fulfill my requirement of performing several Request in a row. E.g. `const index = async () => todos(\"1\").then(todo => todos(todo.foo === \"a\" ? \"2\" : \"3\"));` and then afterwards `const index2 = async () => todos(\"3\").then(todo => todos(todo.foo === \"a\" ? \"2\" : \"3\"));` ." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-20T21:48:25.950", "Id": "417721", "Score": "0", "body": "@elsololobo Without knowing exact nature of the service my advice is tentative and may not be the best solution. If req B is dependent on the results of req A then that is the only way. If the reqs are independent but part of the same res use `Promise.all([fetchA(), fetchB()...and so on]).then(.`. If the res requires any one of the several reqs use `Promise.race` See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises for more details and links. As you are creating a service be aware the cost is very dependent on all traffic, always do what you can to reduce traffic." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-19T19:20:34.897", "Id": "215789", "ParentId": "215758", "Score": "3" } } ]
{ "AcceptedAnswerId": "215789", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-19T15:17:08.527", "Id": "215758", "Score": "3", "Tags": [ "javascript", "node.js", "async-await", "promise" ], "Title": "Separating Fetch Calls and using in Promise Chain" }
215758
<p>I've been working on a library that includes a list-like structure, which I use internally multiple times to store different types of structs. However, I'm not entirely confident with my ability to safely manage memory in C yet, so I'd appreciate if someone could let me know if there's anything wrong with my code (it seems to work just fine.)</p> <p>This is the code for the list structure (with some bits from the associated header put at the top for simplicity.)</p> <pre><code>// Put this at the top of structs to make it possible to use them in a cg_mem_list #define CG_ITEMIZABLE int cg_index; // Free extra spaces after this many exist #define CG_MEM_EXTRAS 10 typedef struct cg_mem_item { CG_ITEMIZABLE } cg_mem_item; typedef struct cg_mem_list { cg_mem_item** items; int num, capacity, itemsize; } cg_mem_list; void cg_new_mem_list (cg_mem_list* list, int itemsize) { list-&gt;items = 0; list-&gt;num = 0; list-&gt;capacity = 0; list-&gt;itemsize = itemsize; } cg_mem_item* cg_mem_list_add (cg_mem_list* list) { cg_mem_item* mitem = malloc (list-&gt;itemsize); if (list-&gt;capacity - list-&gt;num &lt; 1) { list-&gt;capacity++; list-&gt;items = realloc (list-&gt;items, list-&gt;capacity * sizeof (cg_mem_item*)); } mitem-&gt;cg_index = list-&gt;num; list-&gt;items[list-&gt;num++] = mitem; return mitem; } void cg_mem_list_remove (cg_mem_list *list, cg_mem_item *item) { list-&gt;num--; int index = item-&gt;cg_index; if (index &lt; list-&gt;num) { list-&gt;items[index] = list-&gt;items[list-&gt;num]; list-&gt;items[index]-&gt;cg_index = index; } if (list-&gt;capacity - list-&gt;num &gt; CG_MEM_EXTRAS) { list-&gt;capacity = list-&gt;num; list-&gt;items = realloc (list-&gt;items, list-&gt;capacity * sizeof (cg_mem_item*)); } free (item); } void cg_destroy_mem_list (cg_mem_list* list) { free (list-&gt;items); } </code></pre> <p>This is how I use it:</p> <pre><code>// The struct being stored in the list typedef struct some_data_type { CG_ITEMIZABLE int random_data; } some_data_type; int main (void) { // Declare and define the list cg_mem_list data_list; cg_new_mem_list (&amp;data_list, sizeof(some_data_type)); // Allocates a new item and sets it up some_data_type* first_item = (some_data_type*)cg_mem_list_add(&amp;data_list); first_item-&gt;random_data = 12; // &lt;More additions and operations&gt; // This frees the item cg_mem_list_remove(&amp;data_list, (cg_mem_item*)&amp;first_item); } </code></pre> <p>I'd also like to note that I didn't implement any checks <code>malloc</code> or <code>realloc</code> because this is in a game-dev-related library, and I figure if it can't allocate any new memory it's probably gonna crash and burn either way. If you have any suggestions for how to gracefully handle this (other than just straight-up throwing an error and aborting, which is pretty much the same as crashing anyways for this sort of application honestly) I'd appreciate it.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-19T15:48:20.463", "Id": "417489", "Score": "0", "body": "BTW, if you're not confident of memory-management, it's wise to exercise your functions under Valgrind or some other checker - have you done that?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-19T15:49:20.733", "Id": "417490", "Score": "0", "body": "Welcome to Code Review! I changed the title so that it describes what the code does per [site goals](/questions/how-to-ask): \"*State what your code does in your title, not your main concerns about it.*\". Please check that I haven't misrepresented your code, and correct it if I have." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-19T15:49:36.080", "Id": "417491", "Score": "0", "body": "@TobySpeight I've never looked into it, honestly. I've only relatively recently started getting serious about working with compiled languages. Will do." } ]
[ { "body": "<h1>Use a memory checker</h1>\n<p>There's a clear bug, identified by running the test program under Valgrind:</p>\n<pre class=\"lang-none prettyprint-override\"><code>==21190== Invalid free()\n==21190== at 0x48369AB: free (in /usr/lib/x86_64-linux-gnu/valgrind/vgpreload_memcheck-amd64-linux.so)\n==21190== by 0x109320: cg_mem_list_remove (215759.c:64)\n==21190== by 0x109388: main (215759.c:94)\n==21190== Address 0x1fff0006a8 is on thread 1's stack\n==21190== in frame #2, created by main (215759.c:82)\n</code></pre>\n<p>This is where a local variable, not allocated with <code>malloc()</code> has been passed to <code>free()</code>.</p>\n<p>There's also a leak:</p>\n<pre class=\"lang-none prettyprint-override\"><code>==21190== 16 (8 direct, 8 indirect) bytes in 1 blocks are definitely lost in loss record 2 of 2\n==21190== at 0x48356AF: malloc (in /usr/lib/x86_64-linux-gnu/valgrind/vgpreload_memcheck-amd64-linux.so)\n==21190== by 0x4837DE7: realloc (in /usr/lib/x86_64-linux-gnu/valgrind/vgpreload_memcheck-amd64-linux.so)\n==21190== by 0x1091F8: cg_mem_list_add (215759.c:36)\n==21190== by 0x109366: main (215759.c:88)\n</code></pre>\n<p>This is only partially mitigated if we add a call to <code>cg_destroy_mem_list</code>, because the individual items still don't get reclaimed (that's what the &quot;8 indirect&quot; refers to).</p>\n<h1>Other issues</h1>\n<p>We need to include <code>&lt;stdlib.h&gt;</code>, to use <code>malloc()</code> and family.</p>\n<p>We're completely missing the (necessary) error checking when we call <code>malloc()</code> and <code>realloc()</code>, both of which can return null pointers. Remember to check the result of <code>realloc()</code> <em>before</em> overwriting the old pointer (which is still valid if <code>realloc()</code> failed).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-19T16:12:45.673", "Id": "417496", "Score": "0", "body": "Oh, that first invalid `free()` is just a typo in my example usage, I should be passing `first_item` instead of `&first_item`. Thank you, though! I've fixed the leak. What should I do about my realloc checks? I figure if it fails the program'll have to terminate either way at some point so it may as well do it just by tripping up on an unexpected NULL value - is there a way to recover from a failed realloc and still obtain some memory?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-19T16:15:00.933", "Id": "417497", "Score": "0", "body": "No, don't do that - for two reasons. Firstly, if you're implementing a library, you don't know the calling program's recovery strategy; you want to return an error indication and do nothing else. Secondly, dereferencing a null pointer is Undefined Behaviour; there's no guarantee that your program will be terminated. It will just be wrong." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-19T16:18:11.210", "Id": "417500", "Score": "0", "body": "BTW, this is just a very quick review, as I'm departing for a few days; you might want to hang on for some more considered reviews before accepting (unless you plan to post a follow-up question with improved/fixed code)." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-19T15:55:40.097", "Id": "215762", "ParentId": "215759", "Score": "3" } } ]
{ "AcceptedAnswerId": "215762", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-19T15:18:40.240", "Id": "215759", "Score": "1", "Tags": [ "c", "array", "memory-management" ], "Title": "Dynamically-resizable array implementation, for use in a game-dev-related library" }
215759
<p>Here is my TCP socket that sends eight images per second to a connected Client.<br> The images are taken from a thermal camera. </p> <pre><code>static void HandleServer() { Console.WriteLine("Server is starting..."); byte[] data = new byte[1024]; IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 9050); Socket newsock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); newsock.Bind(ipep); newsock.Listen(10); Console.WriteLine("Waiting for a client..."); Socket client = newsock.Accept(); IPEndPoint newclient = (IPEndPoint)client.RemoteEndPoint; Console.WriteLine("Connected with {0} at port {1}", newclient.Address, newclient.Port); HandleImage(client, newsock); } private static void HandleImage(Socket client, Socket s) { int sent; int imageCount = 0; double totalSize = 0; try { while (true) { Image bmp = getImage(); MemoryStream ms = new MemoryStream(); // Save to memory using the bmp format bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg); byte[] bmpBytes = ms.ToArray(); bmp.Dispose(); ms.Close(); sent = SendVarData(client, bmpBytes); imageCount++; totalSize += sent; Console.WriteLine("Sent " + sent + " bytes"); Thread.Sleep(125); } } catch (Exception e) { Console.WriteLine("Exception catched, probably an interrupted connection. Restarting server..."); s.Close(); Console.WriteLine("Transferred {0} images with a total size of {1}", imageCount, totalSize); Console.WriteLine("Average JPEG size: " + totalSize / imageCount + " byte"); HandleServer(); } } private static int SendVarData(Socket s, byte[] data) { int total = 0; int size = data.Length; int dataleft = size; int sent; byte[] datasize = new byte[4]; datasize = BitConverter.GetBytes(size); sent = s.Send(datasize); while (total &lt; size) { sent = s.Send(data, total, dataleft, SocketFlags.None); total += sent; dataleft -= sent; } return total; } } } </code></pre> <p>Any feedback is appreciated:) </p> <p>Update: getImage simply calls the driver DLL of the thermal camera and returns the actual Image. I do this every 125ms because the camera is specified with 8fps and does NOT provide a method or property to check whether there is a new image available.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-19T16:34:21.597", "Id": "417503", "Score": "0", "body": "I highly recommend reading up on the relationship between `IDisposable`-implementing objects (such as `Image`, `MemoryStream`, and `Socket`) and the `using` statement." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-19T16:39:15.430", "Id": "417505", "Score": "0", "body": "@Jesse thanks a lot for your feedback. So this is a Kind of try with ressources like in Java?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-19T17:18:05.780", "Id": "417515", "Score": "0", "body": "I'm not terribly familiar with Java, but based on the way you phrased it, I would suspect so." } ]
[ { "body": "<p>This isn't quite true:</p>\n\n<blockquote>\n <p>sends eight images per second </p>\n</blockquote>\n\n<p>The 125ms sleep means that your code will sit around blocking a thread for about ~1/8th of a second (<code>Thread.Sleep</code> shouldn't be use for accurate timing ever) after it sends every image. This means that the time between images is ~125ms plus the time to actually send an image (i.e. no more than ~8 images per second, could be much fewer). This pretty much guarantees that you will drop a frame now and then.</p>\n\n<p>You say that <code>getImage()</code> may or may not be providing a new image, and there is no nice way to check if a new image is available; however, you might consider interrogating the image received and checking if it is the same the one you last sent (and then don't send it); you can do this cheaply enough by taking a hash of the data stream. If <code>getImage()</code> itself isn't too expensive, then this would enable a quicker response rate, and ensure 8fps, rather than the 7-or-8 fps that a method like this will give you (assuming sending the image data is reasonably fast). If this makes sense will depend on the resource available, and how much you care about receiving every frame.</p>\n\n<p>It would also be nice if you could avoid locking up a whole thread, as that sort of methodology does not scale (you run out of threads). An asynchronous <code>HandleServer</code>/<code>HandleImage</code> combination which makes use of <code>Task.Delay()</code> to schedule work might be a good solution, and would not significantly increase the complexity of the implementation.</p>\n\n<hr />\n\n<p>Don't leave comments to rot:</p>\n\n\n\n<pre class=\"lang-cs prettyprint-override\"><code>// Save to memory using the bmp format\nbmp.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);\n</code></pre>\n\n<p>Such a comment is probably not worth the space it consumes, and it's unhelpful when it is out of date like this.</p>\n\n<hr />\n\n<p>Calling <code>HandleServer()</code> within <code>HandleImage()</code> means that every exception will consume a little more of the stack frame, until eventually the program crashes. You might consider putting the logic for handling exceptions outside of both of these methods, and putting it in a loop; for example, something like:</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>while (keepRunning)\n{\n try\n {\n HandleServer();\n }\n catch (Exception ex)\n {\n // do whatever\n } \n}\n</code></pre>\n\n<p>Not only will this save slowly filling the stack, but it means that <code>HandleImage</code> can focus on <em>handling images</em> and not restarting the server when it goes wrong.</p>\n\n<p>The difficulty with this is that you currently print some information when catching an exception, to which this alternative does not lend itself. (you could catch the expcetion, print everything out, and then throw it again: this way <code>HandleImage</code> is still only concerned with sending lots of images, and the code above it takes the role of deciding how to deal with other failures (e.g. network errors)).</p>\n\n<p>You include the exception in your <code>catch</code> clause, but you don't report anything about it. It would be much better to print out the exception rather than the assumption that it is a network error: that way, when something goes wrong in production there is some hope of debugging it.</p>\n\n<hr />\n\n<p>This code needlessly allocates an extra <code>byte[]</code>.</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>byte[] datasize = new byte[4];\ndatasize = BitConverter.GetBytes(size);\n</code></pre>\n\n<p>It can be simplified to this:</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>byte[] dataSize = BitConverter.GetBytes(size);\n</code></pre>\n\n<hr />\n\n<p>Your code to send the data to the server is suspect: when sending the size-data, you don't check the return value, but you have a corresponding loop to send the image data. I'm not sure how socket and TCP get along, but if you don't trust <code>data</code> to send in one go, you should be giving <code>sizeData</code> the same treatment (you can put the loop in it's own method to keep it simple).</p>\n\n<hr />\n\n<p>Consider using the <a href=\"https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/using-statement\" rel=\"noreferrer\"><code>using</code> statement</a> (as suggested by Jesse C. Slicer in the comments) to ensure proper disposal of disposables. For example, in <code>HandleImage</code>:</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>byte[] bmpBytes;\n\nusing (Image bmp = getImage())\nusing (MemoryStream ms = new MemoryStream())\n{\n bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);\n bmpBytes = ms.ToArray();\n}\n</code></pre>\n\n<p>This will dispose the resources in the event that an exception if thrown in there somehow, and moves the released resources into a different scope, which means they can't be misused as easily (you can't forget to dispose them, and you can't use once when are disposed).</p>\n\n<hr />\n\n<p>It's generally a good idea to define variables as close to their usage as possible. <code>sent</code> in <code>HandleImage</code>, for example, is declared on the first line of the method, but only used inside the <code>while</code> loop; it's purpose would be clearer if it was defined and assigned on the same line, and it would be impossible to use outside of its meaningful scope. <code>total</code> in <code>SendVarData</code> is also initialised first thing, but has no role in first piece of logic in the method.</p>\n\n<hr />\n\n<p>These methods would really benefit from some <a href=\"https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/documentation-comments\" rel=\"noreferrer\">inline-documentation</a> (<code>///</code>) explaining what their role and behaviour is: I would not assume a method called <code>HandleImage()</code> could ever start a TCP server, so this needs to be written down somewhere (though ideally that would be changed, either as suggested above or through some other refactoring).</p>\n\n<hr />\n\n<p>Small things:</p>\n\n<ul>\n<li><p>Your 'bytes sent' reporting doesn't include the 4 bytes sent for the length-prefix.</p></li>\n<li><p>The past-participle of 'catch' is 'caught', rather than 'catched'.</p></li>\n<li><p>The variable <code>data</code> in <code>HandleServer</code> is never used.</p></li>\n<li><p>Be consistent with your use of white-space (e.g. the gaps between methods, and indentation in <code>HandleServer</code>, etc.)</p></li>\n<li><p>You might consider reusing the memory stream; we don't know how large the files are, but taking a new memory stream for each image may ruin your program's memory characteristics, and will necessarily degrade performance to some extent.</p></li>\n<li><p><code>static void HandleServer()</code> is missing an accessibility modifier (which are otherwise present)</p></li>\n<li><p><code>double totalSize = 0;</code> should not be a <code>double</code> (64bit float-point); did you mean <code>long</code> (64-bit integer)?</p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-19T20:15:02.060", "Id": "417542", "Score": "0", "body": "Thanks a lot! Nice points which I will take care of. The Code ist just for a Mini PC running on a multicopter to send the images, so you know a bot about the background. But thank you for your very helpful answer!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-19T17:17:25.100", "Id": "215772", "ParentId": "215761", "Score": "7" } } ]
{ "AcceptedAnswerId": "215772", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-19T15:52:45.577", "Id": "215761", "Score": "2", "Tags": [ "c#" ], "Title": "C# TCP Socket for sending images" }
215761
<p>I am looking for a undo redo system that allows me to log changes of properties.<br> After searching a bit I found the memento pattern. I took the idea and wrote it in my classes:</p> <p>Basic Structure:</p> <pre><code>public class Face { List&lt;Vertex&gt; vertices; } public class Vertex : ValueLog&lt;Vertex&gt; { Vector3 _position; public Vector3 Position { set { Log(); _position = value; } get { return _position; } } public Vertex(Vector3 position) { _position = position; } protected override void Restore(Vertex value) { _position = value._position; } protected override Vertex GetLogValue() { return new Vertex(_position); } } </code></pre> <p>ValueLog class to keep track of the modification history:</p> <pre><code>public abstract class ValueLog&lt;T&gt; : ICmd { Stack&lt;T&gt; undoStack; Stack&lt;T&gt; redoStack; bool logged = false; public ValueLog() { undoStack = new Stack&lt;T&gt;(); redoStack = new Stack&lt;T&gt;(); } protected abstract void Restore(T value); protected abstract T GetLogValue(); protected void Log() { if (!logged &amp;&amp; !Logger.Instance.logPaused) { logged = true; redoStack.Clear(); undoStack.Push(GetLogValue()); // add log operation to a list of operations that happen at once Logger.Instance.AddCmd(this); Logger.Instance.OnCollect += OnCollect; } } public override void Undo() { if (undoStack.Count &gt; 0) { T current = GetLogValue(); redoStack.Push(current); T restore = undoStack.Pop(); Restore(restore); } } public override void Redo() { if (redoStack.Count &gt; 0) { T current = GetLogValue(); undoStack.Push(current); T restore = redoStack.Pop(); Restore(restore); } } void OnCollect() { // called when operation finished (On Mouse Up) logged = false; Logger.Instance.OnCollect -= OnCollect; } } </code></pre> <p>So far it works fine. However I plan to have about a million of vertices. If I set the position of 100.000 of them at the same time I expect some performance problems. Also storage will be critical if each Vertex stores two Stacks. </p> <ul> <li>Is there something I can optimize? </li> <li>Is there a better pattern to solve this? </li> <li>Is it possible to move this on a gpu to run faster?</li> </ul> <p>Thank you for reading and answers! Sorry for this code heavy question. This is only the important part of the code. I don't want to explode the question with the whole code.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-20T10:27:27.657", "Id": "417626", "Score": "3", "body": "Can you also show us the implementation of `Logger` and the definition of `ICmd`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-20T12:46:31.903", "Id": "417651", "Score": "2", "body": "This is not a code-heave question, in fact, there is a lot of code missing. Could you add all parts please?" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-19T16:14:34.980", "Id": "215763", "Score": "2", "Tags": [ "c#", "performance" ], "Title": "Undo Redo pattern for high performance? C#" }
215763
<p>I found an <a href="https://www.ohjelmointiputka.net/postit/tehtava.php?tunnus=muslam" rel="nofollow noreferrer">optimization problem</a> written in Finnish but I will translate it into English. The following is an example case.</p> <blockquote> <p>I have <span class="math-container">\$n=120\$</span> lamps in a circle, and enumerated by <span class="math-container">\$L_1,…,L_{120}\$</span>. Some of them are switched on and some of them are switched off. I also have been given a positive integer <span class="math-container">\$m=7\$</span>. One every turn I choose one lamp <span class="math-container">\$L_i\$</span> and then the lamps <span class="math-container">\$L_{i−m},…,L_{i+m}\$</span> will change their state. I mean if lamp <span class="math-container">\$L_j\$</span> was turned off then now it is turned on and vice versa. Indexes are are modulo <span class="math-container">\$n\$</span> so the lamps <span class="math-container">\$L_{118},L_{119},L_1,L_2\$</span> are consecutive.</p> <p>What is the minimum number of turns to shut off all lamps and which switches one must press, if the initial states of the lamps are (from <span class="math-container">\$L_1\$</span> to <span class="math-container">\$L_{120}\$</span>)</p> <pre><code>1010110110000100000101011001011111010111 1010011101001100000010001010011010110000 0000100110010100010010110111000000010110 </code></pre> <p>The list of cases is as follows:</p> <pre><code>B 6 1 101101 -------------------------------------------------------------------------------- C 10 2 1011010110 -------------------------------------------------------------------------------- D 20 1 11111011101010111111 -------------------------------------------------------------------------------- E 30 7 011100001010011011100001010011 -------------------------------------------------------------------------------- F 39 6 110100111111101000011000100110111100010 -------------------------------------------------------------------------------- G 53 9 0101100101111100100011100111101001001010 0010000010110 -------------------------------------------------------------------------------- H 120 7 1010110110000100000101011001011111010111 1010011101001100000010001010011010110000 0000100110010100010010110111000000010110 -------------------------------------------------------------------------------- I 220 27 1110111111101000100110011001100110100000 0010100011000111101100111111000001010000 1010110110011100100010011011010111100011 0101101000010000100110111101001001011010 1101001001110110001100011010111101001100 11010111110101010100 -------------------------------------------------------------------------------- J 500 87 1010001101101001110001101001000101010100 0001111111001101011000000011001111111011 1001110011010111111011010100010011011001 1001101110011011100001000111110101011111 1100111100001100110011101110101100001111 1100010010011010001111000000101110101101 1010100001100011111000111001000101101000 1011111111101111000000011111010001000000 1110011110111101010010011000000100010100 0011101011010011010110011110111000010010 0111100100011010010110001000011100101001 1110111010001001011001111011111011010110 10101101111011101110 -------------------------------------------------------------------------------- K 1002 83 0010100100100101000000110101111111101011 1101000101111110001110000110110110010101 1110110011011101100110111001110110010011 1101111010110011110101100001101010100011 1110001100011111110100011110100111111100 0011001011100110101100001101000001110010 0110100000100100100000011010000010111100 1110001110011110101001100111101101010000 0101010000011010011110101001001001000000 0011000100011011011001111010001101111000 0100001011010011001010111001111100110001 0011111110101101001100111101110000000000 1101100100000011000010010100010101001000 1100001000101001100110010100001000001101 1101000100001010011000101001101000100010 0011010001011101010100011101001101101100 0111110100110011001111000000001001001001 1001111001011111000010110000110010101000 1011001100111101000101000110000111010100 0010011011010111001101011001111000001011 1110101010101101111011111110100001100110 1000101100110011010000110000011011110011 0010000010000000111101101000001111101111 0100111110010101100011101001111101010000 1111100010011001110111111000101000000101 01 -------------------------------------------------------------------------------- L 2107 108 0111110100011000011111101110010101100011 1001111011101001001110111110001100011001 1001010100101011101101001000010111111111 1001101010111011110100100101000101100011 1110100010010010101110100000111100101000 0111101011111100010010110000100110100100 0100110101110010110011110010101101100111 1110010011000110110111010110010100101110 0111111101110000111001111100100010010001 1010110011000101100111111001011110101110 0111010110111110110101000101100100011000 1011000011011110001111100110100010100101 1101111100110011001110010010001010101111 1000001001000110011110010011011101110100 1011111100110010011000010110010110101010 0110101000011011110001010000010001000110 1001110101001001110110111111010011010111 1111011001000110111001000011101101110001 0000011111101000010101011111011011000011 1111000000011100010011011001011000110101 1101011111100001100010110010110011000000 0001001111100101110100100011011010011100 0000001111010101000111011000110110100001 1010110011100110111010111110110000010000 1000101001111001000110000101010000010111 1011100001000110001100010000001011101110 1001111110100010010000011000100101010101 1001001001110110101000001001001100001011 0011011100011111100111001110101101110001 0111010000010011110110011011000011101001 1111011010010000101111000010000001100110 1001011101001000010101001001011111111011 1000111000100001101100101110100011111100 1011001111101111110110101111101111011111 1001111100110101110101111110010010101101 1111111111000100100111100011101110110100 0100011011001010110100101101000000110010 0010010001001110110100011111100011111101 0100110111101101010101010100110110011011 0001111111000100000111011010101011000010 0011011110110110110100011001101111001000 1000000011110011100111100000001010010011 1000011101111100000101010101010010100101 1010001011010100011011001110110010100000 1000111101111000010111111101010110110111 0110001111100011001110000100100101001111 0000111111100010011001010000010110111000 1000110110001000001100110000001011000010 1000101101110000101100100010101111100011 1000010010111101000010000110011010000001 0010001100001000001100110111110100100111 1001100110001000100101011111001011001111 110001011111001101010101001 ================================================================================ </code></pre> </blockquote> <p>I was wondering how to solve the case I. I tried to solve it by Sage but my algorithm seems to be too slow. How can I make the program such that it finds the optimal solution and stops the computing as it find it?</p> <p>Current code:</p> <pre><code>room = [] input = [] m = [] F = GF(2) room.append('B') input.append('101101') m.append(1) room.append('C') input.append('1011010110') m.append(2) room.append('D') input.append('11111011101010111111') m.append(1) room.append('E') input.append('011100001010011011100001010011') m.append(7) room.append('F') input.append('110100111111101000011000100110111100010') m.append(6) room.append('G') input.append('01011001011111001000111001111010010010100010000010110') m.append(9) room.append('H') input.append(''.join([ s for s in """1010110110000100000101011001011111010111 1010011101001100000010001010011010110000 0000100110010100010010110111000000010110""".split('\n') if s]) m.append(7) for case in range(len(room)): L_init = vector(F,input[case]) d = len(L_init) print(d) M = matrix(F,d,d) print(d) for i in range(d): for j in range(-m[case],m[case]+1 ): M[i,(i+j) % d] = 1 I = M.solve_right(L_init) K = M.right_kernel() best = None for k in K: A = (I+k).nonzero_positions() B = [] if len((I+k).nonzero_positions()) &lt; best or best == None: S = room[case] + ' ' best = len((I+k).nonzero_positions()) for i in range(len(A)): S +=str(int(A[i])+1) + ' ' print( str(S)) </code></pre> <p>This outputs: File "lampsB.sage.py", line 32 m.append(_sage_const_7 ) ^ SyntaxError: invalid syntax</p> <p>I also found discussion in <a href="https://math.stackexchange.com/questions/2569003/how-to-find-an-algorithm-to-shut-down-all-lamps-with-minimum-number-of-moves?noredirect=1&amp;lq=1">https://math.stackexchange.com/questions/2569003/how-to-find-an-algorithm-to-shut-down-all-lamps-with-minimum-number-of-moves?noredirect=1&amp;lq=1</a> but the algorithm described there seems too hard for me to be implemented.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-24T21:58:57.510", "Id": "418185", "Score": "0", "body": "Welcome on Code Review! Code Review is supposed to be a platform where users review *working* code. Try adding a `)` at the end of `input.append(''.join(...)`. The syntax error should vanish now. If this fixes your problem reconsider if you still want your code to be reviewed, otherwise move your question so Stack Overflow until you arrive at a working solution." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-19T16:15:56.303", "Id": "215764", "Score": "2", "Tags": [ "python", "mathematics" ], "Title": "Shutting down all lamps with minimum number of switch presses" }
215764
<p>There is some language where the following are considered comments:</p> <ol> <li><code>[str] // comment</code></li> <li><code>[str] /* comment */ [str]</code></li> <li><code>[str] # comment</code></li> <li><code>[str] /* comment1 comment2 */ [str]</code></li> </ol> <p>where <code>[str]</code> is 0 or more occurrences of some string.</p> <p>I'm reading a file line by line, and need to remove the comments from the whole file (the file is large so I cannot keep the whole content in memory).</p> <p>I have written a method that receives each line, removes the comments from it, and returns the remaining string.</p> <p>(Here <code>s_bInComment</code> is a static variable in <code>Parser</code> class with initial value of <code>false</code>)</p> <pre><code>void Parser::removeComments(std::string &amp;str) { // see if we're still in comment lines, i.e. not reached */ auto commentEnd = str.find("*/"); if (s_bInComment &amp;&amp; commentEnd == std::string::npos) { str.clear(); return; } std::string result; const auto iStrLen = str.length(); for (std::size_t idx = 0; idx &lt; iStrLen; ++idx) { if (str[idx] == '/') { if (idx + 1 &lt; iStrLen) { if (str[idx + 1] == '/') { // we found // // take the part of the string before the comment, if any str = str.substr(0, idx); break; } if (str[idx + 1] == '*') { // see if */ is in the same line commentEnd = str.find("*/"); if (commentEnd == std::string::npos) { // multiline comment s_bInComment = true; str = str.substr(0, idx); } else { // remove the comment str = result + str.substr(commentEnd + 2); // recurse on the remaining string removeComments(str); } break; } } } else if (str[idx] == '*') { if (idx + 1 &lt; iStrLen) { if (str[idx + 1] == '/') { // we have found */, comment ended s_bInComment = false; // take the part of the string after the comment, if any str = str.substr(idx + 2); // recurse on the remaining string removeComments(str); break; } } } else if (str[idx] == '#') { // if there's a text before #, it should be accumulated in result str = result.size() ? result : std::string(); break; } else if (!s_bInComment) result += str[idx]; } } </code></pre> <p>I have tested my code with the following input lines:</p> <ol> <li><code>a /* b */ c</code></li> <li><code>a /* b */</code></li> <li><code>a // b</code></li> <li><code>a /* b c */</code></li> <li><code>// a</code></li> <li><code>a /* b */ c</code></li> <li><code># a</code></li> <li><code>a # b</code></li> <li><code>a /* a */ b /* b */ c</code></li> </ol> <p>Please let me know if there's room for improvement in one or other part.</p>
[]
[ { "body": "<p>That's an interesting case. First, I thought that the function should be a function template for a pair of input iterators and an output iterator, as that's an idiomatic approach taken by many STL algorithms and what the function matches this pattern. But given that <code>\\n</code> plays a crucial role here, passing iterators to an underlying <code>std::ifstream</code> doesn't make much sense (it consumes words, not lines).</p>\n\n<p>Nevertheless, let me share my thoughts besides.</p>\n\n<ul>\n<li><p>Why does it have to be a static data member <code>s_bInComment</code>? I assume <code>removeComment</code> is static, too? This sounds like it's somewhat decoupled from the rest of the <code>Parser</code> class, which might have some instance-specific state. Maybe it makes things cleaner and more testable if you create a small class only for the removal of comments, which improves encapsulation and circumvents the <code>static</code> variable - non-<code>const</code>, <code>static</code> variables are too global for my taste, and they are generally thread-unsafe.</p></li>\n<li><p>The function is very long, and it contains many nested branches. I think it's common sense that this is not very readable and should be split into smaller functions. If you give them meaningful names, you can even remove some of your comments (e.g. <code>hasPartialEndToken(str)</code> or <code>startsWithGlobalToken(str)</code>).</p></li>\n<li><p>If you care about allocations and C++17 is available, you could change the way this functions passes its result back to the caller, i.e., via a <code>std::vector&lt;std::string_view&gt;</code>. The lifetime of the input argument is controlled by the caller, so it is probably sufficient to not copy the non-comment parts of the string into a result, but instead create a collection of views on the input. As <code>std::string::substr</code> and concatenating strings with <code>operator +</code> are possibly expensive operations, you might keep this option in mind (and of course, only go with it after you made sure that performance/memory footprint is important, you profiled your code and so on...)</p></li>\n<li><p>Minor point, as this is not in your list of tested string: what should happen with something like <code>\"a /* b \\n c */ d # e\"</code>, i.e., a multiline comment followed by a until-the-end-of-line comment?</p></li>\n</ul>\n\n<p>Last, a more general question - why aren't you using <code>&lt;regex&gt;</code>? The API is not famous for its ease of use, but you do a lot of manual work that could be outsourced to the standard library, and developers maintaining such a piece of code wouldn't be surprised to find some regular expressions in it. Here's a small class has the same functionality as the snippet you posted:</p>\n\n<pre><code>class CommentRemover {\n public:\n std::string strip(const std::string&amp; input);\n\n private:\n bool isInComment = false;\n static const std::regex restOfLine;\n static const std::regex partialInline;\n static const std::regex multiLineBegin;\n static const std::regex multiLineEnd;\n};\n</code></pre>\n\n<p>with the actual <code>std::regex</code> objects being defined as</p>\n\n<pre><code>const std::regex CommentRemover::restOfLine{\"(//|#)\"};\nconst std::regex CommentRemover::partialInline{\"(/\\\\*.*?\\\\*/)\"};\nconst std::regex CommentRemover::multiLineBegin{\"(/\\\\*.*(?!\\\\*/))\"};\nconst std::regex CommentRemover::multiLineEnd{\"(/\\\\*.*(?!\\\\*/))\"};\n</code></pre>\n\n<p>and the implementation of the member function looks like</p>\n\n<pre><code>std::string CommentRemover::strip(const std::string&amp; input)\n{\n std::smatch match;\n // Save some typing below:\n const auto search = [&amp;match, &amp;input](const std::regex&amp; re){\n return std::regex_search(input, match, re); };\n\n if (isInComment &amp;&amp; search(multiLineEnd)) {\n isInComment = false;\n return strip(match.suffix().str());\n } else if (search(partialInline))\n return match.prefix().str() + strip(match.suffix().str());\n else if (search(restOfLine))\n return match.prefix().str();\n else if (search(multiLineBegin)) {\n isInComment = true;\n return match.prefix().str();\n }\n\n return input;\n}\n</code></pre>\n\n<p>This is not a prime example for readability, and the regex specifications are admittedly cryptic. But I think it reduces the likelihood of bugs due to less code and no manual looping/indexing. Plus, it allows for concentrating the complexity of the operation into the regex definitions and the <code>if</code>-<code>else if</code> ordering.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-20T17:41:17.527", "Id": "417688", "Score": "0", "body": "the reason i'm not using regex is that, after removing the comments i run a regex on the string, so if i remove the comments using regex, that'll be 2 regex passes for each string, and i know c++ regex is infamous for its slowness.\ni know about string_view, but don't have c++17 available.\nthe input `\"a /* b \\n c */ d # e\"` is supposed to return `a \\n d` (i had a bug and fixed it to return the correct string).\nand i like the idea to have a comment remover class. i'll update my code respectively and post it again, thanks." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-20T18:25:27.070", "Id": "417692", "Score": "0", "body": "Well, the regex approach I posted will definitely be slow... Besides, make sure to read e.g. [this thread](https://codereview.meta.stackexchange.com/questions/1763/for-an-iterative-review-is-it-okay-to-edit-my-own-question-to-include-revised-c) before editing your question." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-20T16:47:35.270", "Id": "215853", "ParentId": "215767", "Score": "1" } }, { "body": "<p>You must not use static variables for this task. Doing that makes it impossible to have two of these parsers at the same time.</p>\n\n<p>Test cases 1 and 6 are the same.</p>\n\n<p>You are missing some interesting test cases:</p>\n\n<ul>\n<li><code>/* /* 2*/ 1 */</code></li>\n<li><code>/**/</code></li>\n<li><code>/* // */</code></li>\n<li><code>// /* \\n word */</code></li>\n<li><code>/// comment</code></li>\n<li><code>// \\\\u000A next line?</code></li>\n</ul>\n\n<p>There's no reason to read the input line by line. That only wastes some memory. And for the <code>/* */</code> it doesn't matter if there are line breaks nearby or not. Therefore having a character reader instead of a line reader is more appropriate.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-20T22:44:14.360", "Id": "215884", "ParentId": "215767", "Score": "0" } }, { "body": "<p>I believe it's a good example of a problem that you can represent with a state-machine. What you do with the next character depends on the state you're in: </p>\n\n<ul>\n<li>if you're outside of a comment, then you copy the character unless it's a <code>/</code> or a <code>#</code></li>\n<li>if the last character was a <code>/</code> outside a comment, then test if the new character is a <code>*</code> or a <code>/</code></li>\n<li>if you're inside a single line comment, you ignore it unless it's a newline</li>\n<li>if you're inside a multi-line comment, you ignore it unless it's a star</li>\n<li>if you've just read a <code>*</code> inside a multi-line comment then you need to check if the new char isn't a <code>/</code></li>\n</ul>\n\n<p>State-machines aren't always the most elegant way of coding, but they're robust, easy to read and blazingly fast. So how would you implement it in this case?</p>\n\n<p>First, don't read the input line by line. It is probably a mistake since crucial information resides in the previous line, if there's one: you can't know, looking at a line, if a multi-line comment was opened in the previous one. Also, it will force you to perform memory management each time you read a line (you need to check if the output string is big enough and allocate more memory if it isn't), which will slow down your program, whereas looking character by character will allow you greater flexibility (any object exposing iterators on characters is acceptable) and prevent allocations if they aren't needed.</p>\n\n<p>That brings us to the signature:</p>\n\n<pre><code>template &lt;typename InputIt, typename OutputIt&gt;\nOutputIt copy_without_comments(InputIt first, InputIt last, OutputIt out)\n</code></pre>\n\n<p>The <code>OutputIt</code> can be many things: an iterator on an allocated buffer, an iterator constructing a <code>string</code>, an iterator on a stream...</p>\n\n<p>The state machine itself is generally implemented with an <code>enum</code> specifying the possible states:</p>\n\n<pre><code>enum class State : char { SlashOutsideComment, StarInsideComment, SingleLineComment, MultiLineComment, NotAComment };\n</code></pre>\n\n<p>Then it's only a big <code>switch</code> to know how to handle the next character:</p>\n\n<pre><code> switch (state) {\n case State::SlashOutsideComment:\n if (*first == '/') state = State::SingleLineComment;\n else if (*first == '*') state = State::MultiLineComment;\n else {\n state = State::NotAComment;\n *out++ = '/';\n *out++ = *first;\n }\n break;\n case State::StarInsideComment:\n if (*first == '/') state = State::NotAComment;\n else state = State::MultiLineComment;\n break;\n case State::NotAComment:\n if (*first == '#') state = State::SingleLineComment;\n else if (*first == '/') state = State::SlashOutsidedComment;\n else *out++ = *first;\n break;\n case State::SingleLineComment:\n if (*first == '\\n') {\n state = State::NotAComment;\n *out++ = '\\n';\n }\n break;\n case State::MultiLineComment:\n if (*first == '*') state = State::StarInsideComment;\n }\n</code></pre>\n\n<p>Link to test and play with: <a href=\"https://wandbox.org/permlink/iXC7DWaU8Tk8jrf3\" rel=\"nofollow noreferrer\">https://wandbox.org/permlink/iXC7DWaU8Tk8jrf3</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-21T13:29:07.243", "Id": "417807", "Score": "0", "body": "if i'm reading the file character by character, then i'm gonna construct a string, so the allocations will still be done, right?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-21T18:20:49.017", "Id": "417844", "Score": "0", "body": "@user3132457 Well, of course you'll pay for the string if you use it, but not if you don't (for example if you redirect the result to a stream or copy it to a statically allocated buffer)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-21T18:23:33.707", "Id": "417845", "Score": "0", "body": "i'm gonna use it. i suppose by statically allocated buffer you mean a `char[]` of some size allocated beforehand. i don't know the size of each line, so i can't allocate enough i guess.\nalso, after removing the comments i'm removing spaces from beginning and end of the string (with a function) (actually i don't need any spaces, but removing them just from beginning and end is easier and cheaper). where should i do that if i use this state machine comment remover (i made it into a class): https://wandbox.org/permlink/ZtDvwYoEASE3rnIm.\nin this class? or a standalone function?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-21T18:36:53.180", "Id": "417847", "Score": "0", "body": "also one question, why do you need the `else` branch for `case CharacterState::SlashOC:`? it's never hit i guess?\np.s. i was wrong when i said i don't need any spaces. okay, i just don't need them at the beginning and end" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-21T18:43:30.013", "Id": "417848", "Score": "0", "body": "updated the code: https://wandbox.org/permlink/lwphb2NrwmpNlIDp" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-21T08:13:43.190", "Id": "215913", "ParentId": "215767", "Score": "2" } } ]
{ "AcceptedAnswerId": "215913", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-19T16:51:44.160", "Id": "215767", "Score": "6", "Tags": [ "c++", "parsing" ], "Title": "Method to remove comments from a string line" }
215767
<p>I am in the process of learning Rust and am still having some issues with borrowing and ownership. I find myself trying to borrow mutable references that are already borrowed as immutable references etc...</p> <p>I noticed that when I try to iterate over the primes without owning them, I encounter issues trying to modify the <code>composites</code> hash map. I was able to get around this by calling <code>to_owned</code> on the vector. Is this the right way to handle this?</p> <p>I also see that when I build the code, I get warnings about unused code for <code>warning: struct is never constructed: 'Sieve'</code> and <code>warning: method is never used: 'new'</code>, am I constructing them incorrectly?</p> <pre class="lang-rust prettyprint-override"><code>use std::collections::HashMap; struct Sieve { composites: HashMap&lt;u64, Vec&lt;u64&gt;&gt;, x: u64, } impl Sieve { fn new() -&gt; Sieve { Sieve { composites: HashMap::new(), x: 2, } } } impl Iterator for Sieve { type Item = u64; fn next(&amp;mut self) -&gt; Option&lt;u64&gt; { let x = self.x; self.x = self.x + 1; match self.composites.get(&amp;x) { Some(numbers) =&gt; { for _num in numbers.to_owned() { self.composites .entry(x + _num) .and_modify(|v| v.push(_num)) .or_insert(vec![_num]); } self.composites.remove(&amp;x); self.next() } None =&gt; { self.composites.insert(x * x, vec![x]); Some(x) } } } } fn main() { let mut sieve = Sieve::new(); println!("{:?}", sieve.next()); // 2 println!("{:?}", sieve.next()); // 3 println!("{:?}", sieve.next()); // 5 println!("{:?}", sieve.next()); // 7 } </code></pre> <p><a href="https://play.rust-lang.org/?version=stable&amp;mode=debug&amp;edition=2018&amp;gist=f949aec9b4fb1891bd860f9edffd5c88" rel="nofollow noreferrer">Here is the code on the Rust playground</a>.</p> <p><em>I <a href="https://codereview.stackexchange.com/q/215708/32521">previously posted a version of the Sieve of Eratosthenes using experimental Rust features</a>, this made it difficult to get feedback on. I have refactored the code to use iterators</em></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-19T17:13:00.300", "Id": "417514", "Score": "0", "body": "*when I build the code, I get warnings about unused code* — in what context? If it's the playground, choosing **build** compiles your code as a library, so your `main` method would not be called and thus your code would be unused." } ]
[ { "body": "<p>Your code is totally fine and idiomatic, but I would change some minor points:</p>\n\n<pre><code>use std::collections::HashMap;\n\nstruct Sieve {\n composites: HashMap&lt;u64, Vec&lt;u64&gt;&gt;,\n current: u64,\n}\n\nimpl Default for Sieve {\n fn default() -&gt; Self {\n Sieve {\n composites: HashMap::new(),\n current: 2,\n }\n }\n}\n\nimpl Sieve {\n pub fn new() -&gt; Sieve {\n Default::default()\n }\n}\n\nimpl Iterator for Sieve {\n type Item = u64;\n\n fn next(&amp;mut self) -&gt; Option&lt;u64&gt; {\n fn next_prime(composites: &amp;mut HashMap&lt;u64, Vec&lt;u64&gt;&gt;, x: u64) -&gt; u64 {\n match composites.get(&amp;x) {\n Some(numbers) =&gt; {\n for num in numbers.to_owned() {\n composites\n .entry(x + num)\n .and_modify(|v| v.push(num))\n .or_insert_with(|| vec![num]);\n }\n composites.remove(&amp;x);\n next_prime(composites, x + 1)\n }\n None =&gt; {\n composites.insert(x * x, vec![x]);\n x\n }\n }\n }\n\n let prime = next_prime(&amp;mut self.composites, self.current);\n self.current = prime + 1; // This number will be the next to be tested\n\n Some(prime)\n }\n}\n\nfn main() {\n let mut sieve = Sieve::new();\n\n assert_eq!(sieve.next(), Some(2));\n assert_eq!(sieve.next(), Some(3));\n assert_eq!(sieve.next(), Some(5));\n assert_eq!(sieve.next(), Some(7));\n}\n</code></pre>\n\n<ul>\n<li>It is good to implement <code>Default</code> when you can build your data structure without parameters (<a href=\"https://stackoverflow.com/a/41510505/4498831\">related answer</a>).</li>\n<li>This is a good practice to put assertions instead of prints. That's easier to change to code and verify that it is still ok.</li>\n<li>The naming of the variables is important; but I do not pretend that mine is perfect, though. By the way, <code>_num</code> should not be prefixed with an underscore because it is used.</li>\n<li>You can run <code>clippy</code> to catch some common error. Clippy warns you that you create a <code>vec![_num]</code> at each iteration. You should give to <code>or_insert_with</code> a closure that will build the correct vector.</li>\n<li>The more important refactoring that I did is to make the algorithm more \"functional\". I think that yours is difficult to reason about because it calls recursively the <code>Iterator::next</code> method and rely on internal state.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-20T13:11:48.610", "Id": "417655", "Score": "0", "body": "Thank you for the feedback, I really appreciate it. Clippy looks great btw. I like your idea of not actually calling the next method recursively and offloading it to another function. Is there any performance benefit to moving the next_prime def outside of the next method?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-20T13:43:32.740", "Id": "417661", "Score": "2", "body": "That's mainly a readability difference (separate the pure calculation from the iterator implementation). I think that the performance would be the same, but if you want to be sure, you must benchmark this." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-20T10:31:00.693", "Id": "215832", "ParentId": "215768", "Score": "3" } }, { "body": "<p>I have some more suggestions that can improve your code.</p>\n\n<ul>\n<li>You can avoid cloning <code>numbers</code> by just removing it from <code>composites</code> to begin with, since you already remove it later. <code>HashMap::remove</code> will give you an <code>Option&lt;Vec&lt;u64&gt;&gt;</code>, so you can now modify the hashmap while you iterate over the vec because it is no longer owned by the hashmap.</li>\n<li>You can make your function iterative by using a <code>while let</code> loop.</li>\n<li>You can simplify your usage of entry by just using <code>or_default</code> which will give a mutable reference to either the vec that was already there, or an empty one. Then you can just push into that vec.</li>\n<li>Another option for clarity is to make a <code>next_prime</code> method on <code>Sieve</code>.</li>\n</ul>\n\n<pre><code>impl Sieve {\n pub fn next_prime(&amp;mut self) -&gt; u64 {\n while let Some(numbers) = self.composites.remove(&amp;self.current) {\n for num in numbers {\n self.composites\n .entry(self.current + num)\n .or_default()\n .push(num)\n }\n self.current += 1;\n }\n let prime = self.current;\n self.composites.insert(prime * prime, vec![prime]);\n self.current += 1;\n prime\n }\n}\n\nimpl Iterator for Sieve {\n type Item = u64;\n\n fn next(&amp;mut self) -&gt; Option&lt;u64&gt; {\n Some(self.next_prime())\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-20T17:58:32.237", "Id": "215859", "ParentId": "215768", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-19T16:53:37.070", "Id": "215768", "Score": "4", "Tags": [ "rust", "sieve-of-eratosthenes" ], "Title": "Incremental Sieve of Eratosthenes using iterators" }
215768
<p>I am using the following pattern in my code. It works. But, it feels as though it is on the edge of what should work!</p> <p>Should I consider an alternative?</p> <p>I have an array in my class that maps an underlying data array. This is the sort of thing for which I could use a lazy sequence. However, I don't want to re-evaluate every time an element is accessed. So, I lazily load my array, then track the data array with KVO. I also want my top-level array to be observable. I mutate that with a <code>mutableArrayValue</code>.</p> <p>I have mocked up a simple working example of the pattern below.</p> <p><code>mutableArrayValue</code> would usually cause a lazy var to initialise, but it seems OK to call it during an initialisation.</p> <p>Setting up an observation on a lazy var does not cause it to initialise. I don't get a call here even though the effective setting of the array comes after the observation is created.</p> <pre><code>import Cocoa class LazyData: NSObject { @objc dynamic lazy var units: [Int] = { print("Loading units") return [1,2,3,4,5,6] }() } class Lazy: NSObject { let data: LazyData init(with data: LazyData) { self.data = data } var unitsObservation: NSKeyValueObservation? func tenTimes(_ input: Int) -&gt; Int { return 10 * input } @objc dynamic lazy var tens: [Int] = { print("Loading tens") let tenProxy = mutableArrayValue(forKeyPath: #keyPath(Lazy.tens)) unitsObservation = data.observe(\.units) { object, change in if change.kind == .insertion { for insertionIndex in change.indexes! { let ten = self.tenTimes(object.units[insertionIndex]) tenProxy.insert(ten, at: insertionIndex) } } } return data.units.map { tenTimes($0) } }() } var lazyData = LazyData() var lazy = Lazy(with: lazyData) print(lazy.tens) let lazyDataProxy = lazyData.mutableArrayValue(forKeyPath: #keyPath(LazyData.units)) lazyDataProxy.insert(9, at: 0) print(lazy.tens) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-13T08:28:02.520", "Id": "429954", "Score": "0", "body": "Actually, as written this doesn't work if you want to subsequently observe the `tens` property. `mutableArrayValue(forKey...` must be called after any observations are added to a key for those observations to be fired. So, that call should be within the the observation closure." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-19T16:55:09.617", "Id": "215769", "Score": "1", "Tags": [ "swift", "cocoa" ], "Title": "Swift lazy observe and mutate pattern for arrays" }
215769
<p>I have completed my website and I'm super happy with its design, but I feel that how I reached this point can be made more efficient and genuinely improved.</p> <p><strong>Note: I'm only looking for assistance on how I can get the same output, but with fewer media queries for responsive design</strong></p> <p>I feel that there is a flaw in the about pages design that has required me to make so many media queries to ensure the output is quality (in my opinion).</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>#about { height: 725px; position: relative; } .about-container { display: flex; position: absolute; height: inherit; } #about-div-one { height: 500px; width: 450px; left:9%; top: 16%; padding: 25px 0; } #about-div-one p { font-size: 20px; font-family: Montserrat; } #about-div-two { height: 500px; width: 350px; left: 61%; top: 15%; background-color: #314455; } #about-div-three { height: 500px; width: 350px; left: 57%; top: 20%; background-image: url("https://i.ibb.co/VCCd5zV/6dbfe498-c284-4e0a-a35f-5f38df3d3d74.jpg"); background-position: 70% 50%; } @media only screen and (max-width: 1225px) { #about-div-two { height: 500px; width: 350px; left: 61%; top: 15%; } #about-div-three { height: 500px; width: 350px; left: 57%; top: 20%; } } @media only screen and (max-width: 1114px) { #about-div-one { height: 500px; width: 450px; left:5%; top: 16%; padding: 25px 0; } #about-div-two { width: 350px; left: 61%; top: 15%; } #about-div-three { height: 500px; width: 350px; left: 57%; top: 20%; } } @media only screen and (max-width: 992px) { .about-container { position: static; } #about { height: 1200px; position: static; } #about-div-one { height: 300px; width: 80%; margin-left: 10%; text-align: center; padding-top: 50px; } #about-div-one p { font-size: 20px; font-family: Montserrat; } #about-div-two { display: none; } #about-div-three { display: none; } #about-sub-container { height: 600px; position: relative; padding-bottom: 50px; } .about-container2 { display: flex; position: absolute; height: inherit; } #about-div-four { height: 100%; width: 45%; left: 37%; background-color: #314455; } #about-div-five { height: 100%; width: 45%; left: 22%; top: 10%; background-image: url("https://i.ibb.co/VCCd5zV/6dbfe498-c284-4e0a-a35f-5f38df3d3d74.jpg"); background-position: 70% 50%; } } @media only screen and (max-width: 975px) { #about { height: 1225px; position: static; } #about-div-one { height: 375px; } #about-div-one p { font-size: 20px; font-family: Montserrat; } #about-sub-container { height: 600px; position: relative; padding-bottom: 50px; } .about-container2 { display: flex; position: absolute; height: inherit; } #about-div-four { height: 100%; width: 45%; left: 37%; background-color: #314455; } #about-div-five { height: 100%; width: 45%; left: 22%; top: 10%; background-image: url("https://i.ibb.co/VCCd5zV/6dbfe498-c284-4e0a-a35f-5f38df3d3d74.jpg"); background-position: 70% 50%; } } @media only screen and (max-width: 875px) { #about { height: 1250px; position: static; } #about-div-one { height: 375px; } } @media only screen and (max-width: 820px) { #about-div-one { height: 375px; } } @media only screen and (max-width: 750px) { #about { height: 1150px; position: static; } #about-div-one { height: 400px; } #about-div-four { height: 80%; width: 45%; left: 37%; background-color: #314455; } #about-div-five { height: 80%; width: 45%; left: 22%; top: 10%; background-image: url("https://i.ibb.co/VCCd5zV/6dbfe498-c284-4e0a-a35f-5f38df3d3d74.jpg"); background-position: 70% 50%; } } @media only screen and (max-width: 700px) { #about { height: 1175px; position: static; } #about-div-one { height: 425px; } } @media only screen and (max-width: 654px) { #about { height: 1100px; position: static; } #about-div-one { height: 450px; } #about-div-four { height: 65%; width: 50%; left: 30%; background-color: #314455; } #about-div-five { height: 65%; width: 50%; left: 15%; top: 10%; background-image: url("https://i.ibb.co/VCCd5zV/6dbfe498-c284-4e0a-a35f-5f38df3d3d74.jpg"); background-position: 70% 50%; } } @media only screen and (max-width: 614px) { #about { height: 1125px; position: static; } #about-div-one { height: 475px; } } @media only screen and (max-width: 600px) { #about { height: 1125px; position: static; } #about-sub-container { height: 600px; position: relative; padding-bottom: 50px; } #about-div-four { height: 63%; width: 65%; left: 24%; background-color: #314455; } #about-div-five { height: 63%; width: 65%; left: 12%; top: 13%; background-image: url("https://i.ibb.co/VCCd5zV/6dbfe498-c284-4e0a-a35f-5f38df3d3d74.jpg"); background-position: 70% 50%; } } @media only screen and (max-width: 549px) { #about { height: 1150px; position: static; } #about-div-one { height: 500px; } #about-sub-container { height: 600px; position: relative; padding-bottom: 50px; } } @media only screen and (max-width: 525px) { #about { height: 1185px; position: static; } #about-div-one { height: 545px; } } @media only screen and (max-width: 471px) { #about { height: 1215px; position: static; } #about-div-one { height: 575px; } } @media only screen and (max-width: 453px) { #about { height: 1245px; position: static; } #about-div-one { height: 600px; } } @media only screen and (max-width: 445px) { #about { height: 1270px; position: static; } #about-div-one { height: 625px; } } @media only screen and (max-width: 435px) { #about { height: 1295px; position: static; } #about-div-one { height: 650px; } } @media only screen and (max-width: 410px) { #about { height: 1300px; position: static; } #about-div-one { height: 675px; } #about-div-four { height: 63%; width: 65%; left: 23%; background-color: #314455; } #about-div-five { height: 63%; width: 65%; left: 12%; top: 10%; background-image: url("https://i.ibb.co/VCCd5zV/6dbfe498-c284-4e0a-a35f-5f38df3d3d74.jpg"); background-position: 70% 50%; } }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div id="about"&gt; &lt;div id="about-div-one" class="about-container"&gt; &lt;p&gt;Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur sagittis nibh ac lobortis dictum. Proin at venenatis augue. Sed vehicula felis in erat scelerisque, vitae luctus tortor tristique. Praesent pharetra felis quam, eget tincidunt massa tristique sit amet. Phasellus viverra, lorem nec sagittis consequat, dui arcu faucibus tortor, ac dictum nisl ex vitae diam. Donec sed tortor sit amet nunc tristique pulvinar in ullamcorper quam. Suspendisse eu sapien convallis, rutrum odio non, efficitur est. Nam quis finibus nunc. Etiam eget lectus scelerisque lacus faucibus pharetra. Donec sit amet tincidunt ipsum. Sed quam ipsum, fermentum sed nisl et, faucibus scelerisque nulla. Duis ac eleifend ex. Nullam a ligula in dui aliquet ultrices a ut arcu.&lt;/p&gt; &lt;/div&gt; &lt;div id="about-div-two" class="about-container"&gt; &lt;/div&gt; &lt;div id="about-div-three" class="about-container"&gt; &lt;/div&gt; &lt;div id="about-sub-container"&gt; &lt;div id="about-div-four" class="about-container2"&gt; &lt;/div&gt; &lt;div id="about-div-five" class="about-container2"&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <p><strong>Note: I attempted to have between 50px and 25px between <code>#about</code> and it's content</strong></p>
[]
[ { "body": "<p>At first, do you have a link do a working demo? It would be easier to examine the page. But I'll try to give some advice anyway.</p>\n\n<ol>\n<li><p>If you want your page to be fully responsive you should not use <code>px</code> as a unit for the properties <code>width</code> and <code>height</code>. <code>px</code> is an absolute unit. It would be better to use a relative unit such as <code>%</code>, <code>vh</code>, <code>vw</code>, <code>vmin</code>, <code>vmax</code>, <code>em</code> or <code>rem</code>. If you do that, your layout will be more fluid. I would recommend <code>%</code> on the <code>width</code> property and <code>vh</code> on the <code>height</code> property.</p></li>\n<li><p>I am not sure why your layout depends so heavily on a height set on the divs. I rarely use <code>height</code> (and if I do it is almost always <code>vh</code>) because a container will expand to the height of its children e.g. text content. So if you maximize the screen and a container has a larger width (use % on width) it will take up less space because the text can spread over the width. I hope it's clear what I mean :D</p></li>\n</ol>\n\n<p>Hopefully this is helpful. If you could post a link to a demo version I'd like do have a second look on it.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-19T22:46:36.570", "Id": "417559", "Score": "0", "body": "Yeah sure, I can try and get one on here soon. But I took your suggestions and put them and use, and whilst it may have reduced my CSS code by 200 lines, `vh` has kind of messed up a lot things. When resizing the browser, it looks fine. But when inspecting in Google Chrome or other browser testing sites, there are huge gaps between the content. Any idea why?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-20T00:46:33.617", "Id": "417565", "Score": "0", "body": "That's really difficult to answer without a working demo version. Apart from this it is not always reliable what browser testing sites show you. They just try to emulate the behavior of certain browser/device. It's always best to test it on real devices. Maybe this video on CSS units is helpful: https://www.youtube.com/watch?v=qrduUUdxBSY\n\nBTW this used to be my favorite YT channel about web design. There are lots of video series about HMTL, CSS and programming a website from scratch. I definitely recommend it, especially the older videos by the channel founder Travis." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-20T08:39:57.547", "Id": "417611", "Score": "0", "body": "Hi, here is a working demo. https://aqueous-lowlands-38591.herokuapp.com/" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-20T08:40:20.957", "Id": "417612", "Score": "0", "body": "Please know that this is no where near the finished version, I have a lot to polish still" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-19T17:32:44.417", "Id": "215775", "ParentId": "215771", "Score": "1" } }, { "body": "<p>I would get rid of the heights. Like I explained in my answer before: there is this natural flow in a web document. The content takes the space it needs. I think what you want to do is add a padding at the top and the bottom of each section. So I would suggest you create a CSS class like this <code>.panel{padding: 8% 0}</code> or something similar. If the padding will be too much on smaller screens you can use media queries.</p>\n\n<p>Now, your #about section is another story. Since all the childs of #about are set to <code>position:absolute</code> you cannot just remove the <code>height</code> otherwise the section would collapse. What you could do is something like this:</p>\n\n<p><strong>HTML</strong></p>\n\n<pre><code>&lt;div id=\"about\" class=\"panel\"&gt;\n &lt;div class=\"left-side\"&gt;\n &lt;div id=\"about-div-one\" class=\"about-container\"&gt;\n &lt;p&gt;Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur sagittis nibh ac lobortis dictum. Proin at venenatis augue. Sed vehicula felis in erat scelerisque, vitae luctus tortor tristique. Praesent pharetra felis quam, eget tincidunt massa tristique sit amet. Phasellus viverra, lorem nec sagittis consequat, dui arcu faucibus tortor, ac dictum nisl ex vitae diam. Donec sed tortor sit amet nunc tristique pulvinar in ullamcorper quam. Suspendisse eu sapien convallis, rutrum odio non, efficitur est. Nam quis finibus nunc. Etiam eget lectus scelerisque lacus faucibus pharetra. Donec sit amet tincidunt ipsum. Sed quam ipsum, fermentum sed nisl et, faucibus scelerisque nulla. Duis ac eleifend ex. Nullam a ligula in dui aliquet ultrices a ut arcu.&lt;/p&gt;\n &lt;/div&gt;\n &lt;/div&gt;\n &lt;div class=\"right-side\"&gt;\n &lt;div id=\"about-div-two\" class=\"about-container\"&gt;\n &lt;/div&gt;\n &lt;div id=\"about-div-three\" class=\"about-container\"&gt;\n &lt;/div&gt;\n &lt;div id=\"about-sub-container\"&gt;\n &lt;div id=\"about-div-four\" class=\"about-container2\"&gt;\n &lt;/div&gt;\n &lt;div id=\"about-div-five\" class=\"about-container2\"&gt;\n &lt;/div&gt;\n &lt;/div&gt;\n &lt;/div&gt;\n&lt;/div&gt;\n</code></pre>\n\n<p><strong>CSS</strong></p>\n\n<pre><code>#about{\n display: flex;\n}\n\n.left-side,\n.right-side{\n width: 50%;\n position: relative;\n}\n\n.div-inside-right-side{\n position: absolute;\n}\n</code></pre>\n\n<p>Maybe you need to use a <code>min-height</code>. I hope this helps.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-20T10:03:37.307", "Id": "215830", "ParentId": "215771", "Score": "1" } } ]
{ "AcceptedAnswerId": "215830", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-19T17:06:57.240", "Id": "215771", "Score": "0", "Tags": [ "html", "css" ], "Title": "Improving the code of my About Page" }
215771
<p>I'm working through Paul Graham's ANSI Common Lisp and in Exercise 2.5, I'm stumped. My specific question (I wasn't sure whether this type of question is suitable for stack overflow, code review, or neither) is:</p> <p><em>How to even begin</em> working on an answer to this question.</p> <p>What's interesting is that I simply don't know how to proceed, analytically. Hopefully, it isn't a question which involves simply knowing the answer due to existing familiarity. So, my question is subtle, and it's not simply to ask 'what is the answer', but 'how could you go about finding the answer', if you were really stumped. So I'm asking about <strong><em>method</em></strong>.</p> <p>The Question: What do these functions do?</p> <pre class="lang-lisp prettyprint-override"><code>(defun enigma (x) (and (not (null x)) (or (null (car x)) (enigma (cdr x))))) (defun mystery (x y) (if (null y) nil (if (eql (car y) x) 0 (let ((z (mystery x (cdr y)))) (and z (+ z 1)))))) </code></pre> <p>I've realised in typing this in that one approach would be simply to run the functions. Perhaps we could call that the "what does this button do?" approach. :)</p> <p>Update: before posting this, I've found I just solved the first one. The method I used (I won't reveal the answer completely here, but the following will certainly make it much easier to guess): just run the function with various inputs. First I discovered it errors unless the argument is not a list (we see it calls <code>car</code> on the arg). So, the first arg to <code>and</code> looks like a base case. While it's clear to me now what it does (easy to say), the only way I was able to discover it was by playing with various inputs. It seemed always to return nil on any input I gave it. That seemed strange. Then I just looked at the line <code>(or (null (car x))</code>, and it's easy to see how to make that evaluate to true: put a nil as an element of the list. And then the secret was revealed... This seems an interesting function, worth plenty of attention. I do love recursion :)</p> <p>The second remains mystery for now. Please remember, I'd appreciate discussion to be around <strong><em>method</em></strong> and/or techniques, if anyone would care to chip in. Obviously there's much less value in just revealing the answer.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-20T07:23:49.763", "Id": "417588", "Score": "0", "body": "Welcome to Code Review! Unfortunately this question doesn't reflect what the site is about. We review code that you have written for improvements. It's not on topic to ask for explanations of code that has been written by someone else than you. For more information, see the [help/on-topic]. Thanks." } ]
[ { "body": "<p>I'm also huge fan of recursion, and the best book on recursion I know is \"Little Schemer\". I highly recommend it! It looks \"slow\" and repetitive, but that's how you learn (at least this approach was great for me).</p>\n\n<p>In my opinion it's hard to read code when you find pattern you didn't knew before. It takes a lot of time and is highly frustrating to figure out what's happening inside, and often you still don't fully get why it was written this way (and if it's even correct). So the best advise I can give is - learn how to write code, reading will come naturally. You know what you are looking for.</p>\n\n<p>In recursion, most important part is - when to stop and what to do (return) in that case.</p>\n\n<p>Your <code>mystery</code> function stops when:</p>\n\n<ul>\n<li><code>y</code> is nil (it returns nil) - first <code>if</code>\nor</li>\n<li>first element of <code>y</code> is <code>eql</code> to <code>x</code> (it returns <code>0</code>) - second <code>if</code></li>\n</ul>\n\n<p>It will also return logical \"something <code>and</code> something\" - the last line - but we will talk about it later.</p>\n\n<p>From the above, we know that:</p>\n\n<ul>\n<li><code>y</code> should be some list, since it's user with <code>car</code> and <code>cdr</code> functions, and tested for empty list (<code>null y</code>)</li>\n<li><code>x</code> should be some atom, simple one, since it's compared to every element of <code>y</code> list with <code>eql</code>, which works fine with things like symbols and numbers, but not more complicated things like strings or lists</li>\n</ul>\n\n<p>OK, we know what to pass to <code>mystery</code> functions (roughly). Now - what this last part with <code>let</code> and <code>and</code> do? Apparently <code>let</code> is used here to store result of recursive call only to speed thing up. It could also be written as:</p>\n\n<pre><code>(and (mystery x (cdr y))\n (1+ (mystery x (cdr y))))\n</code></pre>\n\n<p>We know what <code>mystery</code> function can return: <code>nil</code> or <code>0</code>. Last thing to do is to analyse what <code>and</code> can return:</p>\n\n<ul>\n<li>first argument if it evaluates to <code>false</code></li>\n<li>second argument otherwise.</li>\n</ul>\n\n<p>As you can see there is no magical trick to help reading code. When you use some pattern (recursion in this case) long enough, you learn what are the important things to look for, and what are just common construction parts.</p>\n\n<p>When you have some idea how function works, you can call it with some parameters just to verify your understanding, but I don't think you should begin with that. Pan and paper method can be a lot better, especially when you start with simple cases, like what will happen if I pass an empty list and empty list? Or zero and one element list? Calling function you don't know and observing results is called \"black box testing\" and is more hackerish activity. You have all the information you need - code of the function - so it's easier to read and reason about its behaviour.</p>\n\n<p>When you stuck and don't know how to proceed, try to reformat the code. Rewrite the parts you understand. It might look silly and like wasting your time, but I find it helpfull.</p>\n\n<p>If something is not clear, I'm happy to expand my answer, just post a comment :)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-20T09:29:35.907", "Id": "417617", "Score": "0", "body": "Thanks @rsm, very useful :) i got `mystery` after some thought, followed by, i confess, a little black box testing :) - a key realisation for me was that there are actually _two_ base cases in this example: the `nil` case may never be reached. The second point I had to acclimatise to was exact behaviour of `and` in this _procedural_ context. So to round this out, how might we describe or think about this particular type of recursion? My feeling is that `mystery` is somehow exploiting the fact that we recur exactly once per position; as one of its symmetries. Does that make sense?" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-19T19:13:28.627", "Id": "215786", "ParentId": "215773", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-19T17:27:35.197", "Id": "215773", "Score": "1", "Tags": [ "common-lisp" ], "Title": "Enigma questions from \"ANSI Common Lisp\"" }
215773
<p>The task:</p> <blockquote> <p>Given an array of numbers and an index i, return the index of the nearest larger number of the number at index i, where distance is measured in array indices.</p> <p>For example, given [4, 1, 3, 5, 6] and index 0, you should return 3.</p> <p>If two distances to larger numbers are the equal, then return any one of them. If the array at i doesn't have a nearest larger integer, then return null.</p> <p>Follow-up: If you can preprocess the array, can you do this in constant time?</p> </blockquote> <p>My solution:</p> <pre><code>const nearestLargestNumber = (arr, idx1) =&gt; { const num = arr[idx1]; let nearestLargest; const findIdxOfNearestLargest = (idxOfNearestLargest, item, idx2) =&gt; { if (item &gt; num &amp;&amp; (idxOfNearestLargest === null || nearestLargest &gt; item )) { nearestLargest = item; idxOfNearestLargest = idx2; } return idxOfNearestLargest; }; return arr.reduce(findIdxOfNearestLargest, null); }; console.log(nearestLargestNumber([4, 1, 3, 5, 6], 0)); </code></pre>
[]
[ { "body": "<p><em>EDIT: I mistook \"nearest\" to mean \"numerically closest\" but the problem asks for minimum distance from the index. As the other answer points out, there are faster methods than visiting every element.</em></p>\n\n<p>The answer to the followup question is \"yes.\"</p>\n\n<p>\"Larger\" is <a href=\"https://english.stackexchange.com/questions/102351/what-is-an-adjective-for-a-very-large-negative-number\">ambiguous</a>: if you ask someone for a \"large negative number\" they probably don't answer \"negative one.\" Attribute this to sloppiness on the author's part, unless you've reason to suspect trickery.</p>\n\n<p>I'm not a fan of these variable names: <code>idx1</code> should be <code>idx0</code>, or <code>i0</code> or <code>initialIndex</code>. <code>nearestLargest</code> isn't the largest anything and <code>nearestLarger</code> would be more accurate. <code>num</code> <em>is</em> a number, but so is everything else—maybe <code>minimum</code> or <code>baseline</code> or <code>mustBeGreaterThan</code>. <code>nearestLargestNumber</code> contains an index, not a number, while the number is held in <code>nearestLargest</code>.</p>\n\n<p>I suggest one common prefix for your index variables and another prefix for value variables (though you don't really need more than one).</p>\n\n<pre><code>const nearestGreater = (arr, i0) =&gt; arr.reduce( \n (iNearestGreater, val, i) =&gt; \n ( val &gt; arr[i0] &amp;&amp; ( iNearestGreater===null || val &lt; arr[ iNearestGreater ] ) ) ? \n i : iNearestGreater,\n null\n );\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-20T01:53:25.417", "Id": "215804", "ParentId": "215778", "Score": "4" } }, { "body": "<p>You are iterating every item in the array a solution that is <span class=\"math-container\">\\$O(n)\\$</span>. The task is to find the <em>\"nearest larger\"</em>. If the values are random and evenly distributed then the solution is <span class=\"math-container\">\\$O(log(n))\\$</span> which is much better than <span class=\"math-container\">\\$O(n)\\$</span> </p>\n\n<p>To get the best result start the search at the index and search outwards away from index. The first item larger than the starting item is at the index to return.</p>\n\n<pre><code>function findNearestLarger(arr, idx) {\n const minVal = arr[idx], len = arr.length;\n var down = idx;\n while (++idx &lt; len || --down &gt;= 0) {\n if (idx &lt; len &amp;&amp; arr[idx] &gt; minVal) { return idx }\n if (down &gt;= 0 &amp;&amp; arr[down] &gt; minVal) { return down }\n }\n return null;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-22T11:22:42.713", "Id": "417922", "Score": "0", "body": "I think your runtime estimate is too pessimistic. If the numbers are random, then half of them are larger than `idx` and each element inspected is a coinflip opportunity to return an answer. Amortized runtime will be \\$\\sum_{i=1}^n \\frac{i}{2^i}\\$ which converges to \\$2 - \\frac{1}{2^n}\\$, giving \\$O(1)\\$." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-20T02:23:44.227", "Id": "215808", "ParentId": "215778", "Score": "5" } }, { "body": "<blockquote>\n <p>Given an array of numbers and an index i, return the index of the nearest larger number of the number at index i, where distance is measured in array indices.</p>\n</blockquote>\n\n<p>I'm a bit confused to be honest. Reading this description, for input <code>[1, 5, 4], 0</code> I would expect 1 as output instead of 2 returned by the program. Because <code>arr[1] = 5</code> is larger than <code>arr[0] = 1</code>, and it's closer in distance than <code>arr[2] = 4</code>. Similarly, for input <code>[4, 5, 1], 2</code> I would expect 1 instead of 0.</p>\n\n<p>In other words, the program seems to be implementing a more precisely worded problem statement:</p>\n\n<blockquote>\n <p>Given an array of numbers and an index i, return the index of the nearest <strong><em>smallest</em></strong> larger number of the number at index i, where distance is measured in array indices.</p>\n</blockquote>\n\n<hr>\n\n<blockquote>\n <p>Follow-up: If you can preprocess the array, can you do this in constant time?</p>\n</blockquote>\n\n<p>The posted code doesn't address the follow-up question.</p>\n\n<p>I think this follow-up question is not specified well enough,\nbecause it doesn't impose any limits on the preprocessing time and space.\nYou could certainly \"preprocess\" the array, using <code>nearestLargestNumber</code> to compute the answer for all valid indexes, store in another array. With the current implementation, computing a single answer takes linear time, therefore computing all answers up-front would take quadratic time. Since no limits were imposed, that may be fine and well.</p>\n\n<p>This follow-up question would become a lot more interesting if preprocessing was limited to linear time and space.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-20T07:08:46.797", "Id": "215816", "ParentId": "215778", "Score": "1" } }, { "body": "<p>I ran your code and got the following results:</p>\n\n<pre><code>console.log(nearestLargestNumber([4, 1, 3, 5, 6], 0));\n&gt; 3\nconsole.log(nearestLargestNumber([4, 1, 3, 5, 6], 1));\n&gt; 2\nconsole.log(nearestLargestNumber([4, 1, 3, 5, 6], 2));\n&gt; 0\nconsole.log(nearestLargestNumber([4, 1, 3, 5, 6], 3));\n&gt; 4\nconsole.log(nearestLargestNumber([4, 1, 3, 5, 6], 4));\n&gt; null\n</code></pre>\n\n<p>I believe the result for index 2 is incorrect. At index 2 the number is 3 so the closest larger number is 5 at index 3. Why it returns index 0 I do not know.</p>\n\n<p>My solution is:</p>\n\n<pre><code>let nearestLargerNumber = (array, index) =&gt; {\n\n let indexNum = array[index];\n\n // Get position of index.\n let distToEnd = (array.length - 1) - index;\n\n if(distToEnd &gt; index){\n // If index is in the left half.\n\n for(let i = index + 1; i &lt; (index + 1) * 2; i ++){\n if(array[i] &gt; indexNum){\n return i;\n }else if(array[index - (i - index)] &gt; indexNum){\n return index - (i - index);\n }\n }\n\n // Check remaining elements at the end of the array.\n for(; i &lt; array.length; i ++){\n if(array[i] &gt; indexNum){\n return i;\n }\n }\n\n }else if(distToEnd &lt; index){\n // If index is in the right half.\n\n for(let i = index + 1; i &lt; array.length; i ++){\n if(array[i] &gt; indexNum){\n return i;\n }else if(array[index - (i - index)] &gt; indexNum){\n return index - (i - index);\n }\n }\n\n // Check remaining elements at the beginning of the array\n for(let i = index - ((array.length - 1) - index); i &gt;= 0; i --){\n if(array[i] &gt; indexNum){\n return i;\n } \n }\n\n }else{\n // If index is the exact middle (only if array has an odd length).\n\n for(let i = index + 1; i &lt; array.length; i ++){\n if(array[i] &gt; indexNum){\n return i;\n }else if(array[index - (i - index)] &gt; indexNum){\n return index - (i - index);\n }\n }\n }\n\n return null;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-20T07:40:02.193", "Id": "215820", "ParentId": "215778", "Score": "2" } }, { "body": "<p>Complexity: <span class=\"math-container\">\\$O(\\log n)\\$</span><br />\nIt worked. It gave me correct answers for many testcases:</p>\n<pre class=\"lang-none prettyprint-override\"><code>i/p:[1, 5, 4] ,0 \n o/p:1\n\ni/p:[4, 1, 3, 5, 6] ,0 \n o/p:3\n</code></pre>\n<pre><code>l=list(map(int,input().split()))\nn=int(input())\np=n-1\nq=n+1\nwhile(p&gt;=0 or q&lt;len(l)):\n if(p&gt;=0 and l[p]&gt;l[n]):\n print(p)\n break\n elif(q&lt;len(l) and l[q]&gt;l[n]):\n print(q)\n break\n p=p-1\n q=q+1\nif(p&lt;0 and q&gt;=len(l)):\n print(&quot;null&quot;)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-29T18:50:23.447", "Id": "513516", "Score": "1", "body": "Welcome to Code Review! Please Check out our [Help] pages specifically the [How to write a good answer](https://codereview.stackexchange.com/help/how-to-answer) page. we look for explanations of why you would use a specific technique or code structure." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-29T18:02:22.180", "Id": "260161", "ParentId": "215778", "Score": "-3" } } ]
{ "AcceptedAnswerId": "215808", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-19T17:42:36.780", "Id": "215778", "Score": "4", "Tags": [ "javascript", "algorithm", "programming-challenge", "functional-programming" ], "Title": "Find index of the nearest larger number of a number" }
215778
<p>I'm using Ionic 4 and Angular animations to animate modals. I created the following two functions that control the animations but they share a lot of repeated code. Is there a way I can clean these up into a single function that just takes an array of parameters for the animations?</p> <pre><code>import { Injectable } from '@angular/core'; import { Animation } from '@ionic/core'; @Injectable({ providedIn: 'root' }) export class AnimationsService { modalLeave(AnimationC: Animation, baseEl: HTMLElement): Promise&lt;Animation&gt; { const baseAnimation = new AnimationC(); const backdropAnimation = new AnimationC(); backdropAnimation.addElement(baseEl.querySelector('ion-backdrop')); const wrapperAnimation = new AnimationC(); const wrapperEl = baseEl.querySelector('.modal-wrapper'); wrapperAnimation.addElement(wrapperEl); const wrapperElRect = wrapperEl!.getBoundingClientRect(); wrapperAnimation .beforeStyles({ opacity: 1 }) .fromTo('transform', 'translateX(0%)', 'translateX(100%)') .fromTo('opacity', 1, 0) .fromTo('-webkit-backdrop-filter', 'blur(7px)', 'blur(0px)'); return Promise.resolve( baseAnimation .addElement(baseEl) .easing('ease-in') .duration(150) .add(backdropAnimation) .add(wrapperAnimation) ); } modalEnter(AnimationC: Animation, baseEl: HTMLElement): Promise&lt;Animation&gt; { const baseAnimation = new AnimationC(); const backdropAnimation = new AnimationC(); backdropAnimation.addElement(baseEl.querySelector('ion-backdrop')); const wrapperAnimation = new AnimationC(); const wrapperEl = baseEl.querySelector('.modal-wrapper'); wrapperAnimation.addElement(wrapperEl); wrapperAnimation .beforeStyles({ opacity: 1 }) .fromTo('transform', 'translateX(100%)', 'translateX(0%)') .fromTo('opacity', 0, 1) .fromTo('-webkit-backdrop-filter', 'blur(0px)', 'blur(7px)'); return Promise.resolve( baseAnimation .addElement(baseEl) .easing('ease-in') .duration(150) .add(wrapperAnimation) ); } } </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-19T17:44:39.900", "Id": "215779", "Score": "2", "Tags": [ "animation", "typescript", "angular-2+", "easing" ], "Title": "Two Angular animations for modal dialogs" }
215779
<p>The overall idea is: I have an Android phone and I would like to copy the files in a folder from the phone (which is running an SSH server, that's how I connect to it) to a harddrive connected to my Raspberry Pi. </p> <p><sub>(I want to know, for sure, what files on my Android were copied to the Harddrive, which is why I have the filenames get a <code>_c</code> amended to them. (So <code>20190321.jpg</code> becomes <code>20190321_c.jpg</code> on my phone.) That should show me, without doubt, that I can delete the file on my Android since it was successfully copied to the Harddrive.)</sub></p> <p>I am decently familiar with Python, but this is the most "advanced" program I've made. The SSH stuff was put together via trial/error and lots of SE/Google searching. </p> <p>Any suggestions, from PEP8 conventions, to better workflow, are very much appreciated! I tried to handle errors correctly, but am curious if the <code>quit()</code> in the exceptions is what I want to do, or if that's not how it should be handled. (Note the <code>ssh.close() // quit()</code> are repeated in both exceptions.)</p> <p>I know some of my docstrings are rather obvious, but I keep reading it's best practice to include them, but any tips are appreciated there too.</p> <p>The SublimeText linter doesn't show any PEP8 suggestions, so I think I'm doing good so far on that point, but of course defer to your wise judgement :) Also, is there a "best practice" to the order my functions should be in? </p> <p>A final note - this should copy the files, and <strong>all</strong> metadata/EXIF data, etc. so that I don't leave any parts out. AFAIK it does, just thought to mention here in case <code>sftp.get()</code> strips something out that I won't notice until later.</p> <p>Edit: Ah, forgot to mention: you'll note that sometimes I do <code>directory + filename</code> and another I do <code>os.path.join(directory, filename)</code>...any big difference I those or would it just be user preference?</p> <pre><code>import paramiko as pmko import os from PIL import Image import re def get_date_taken(path): """ This will be implemented later and is currently just to test how to get EXIF data from photos. """ return Image.open(path)._getexif()[36867] def list_files(directory, filetype, ssh): """ This will scan a directory for the filetype, which is passed as `.jpg`, or `.mp3`, etc. and return a list of those files. """ print("Collecting filenames of all photos in", directory) distantFiles = list() filePath = '/storage/emulated/0/' + directory filePattern = '"*' + filetype + '"' rawcommand = 'find {path} -name {pattern}' command = rawcommand.format(path=filePath, pattern=filePattern) stdin, stdout, stderr = ssh.exec_command(command) filelist = stdout.read().splitlines() for afile in filelist: (head, filename) = os.path.split(afile) distantFiles.append(filename) return distantFiles def connect_to_ssh_server(host_ip, port, username, password): """ This will connect to an SSH Server and return the sftp and ssh objects """ print("Starting connection to", host_ip) ssh = pmko.SSHClient() ssh.set_missing_host_key_policy(pmko.AutoAddPolicy()) try: ssh.connect(host_ip, port=port, username=username, password=password) sftp = ssh.open_sftp() print("Connected!") return sftp, ssh except pmko.ssh_exception.NoValidConnectionsError: print("No valid connections for", host_ip) ssh.close() quit() except TimeoutError: print("Connection attempt timed out when trying to connect to", host_ip) ssh.close() quit() def fix_filenames(files, directory, rgx, replacement, sftp): for file in files: if type(file) != str: file = file.decode('utf-8') if file.endswith(".jpg_c"): print("Fixing", file) new_end = re.sub(rgx, replacement, file) print(directory + file, " will be in ", directory + new_end) sftp.rename(directory + file, directory + new_end) def download_file(sftp, filename, origin, destination): sftp.get(origin + filename, destination + filename, callback=None) def rename_file(sftp, filename, directory, suffix): """ This will rename a file in a directory with the passed in suffix. """ extention = filename.rsplit(".")[1] new_name = re.sub(r"\..*", suffix + extention, filename) print(filename, "will become", new_name) sftp.rename(directory + filename, os.path.join(directory, new_name)) def copy_all_files(lst, origin_directory, destination, ssh, sftp): """ This copies files from a list, from an origin directory to the destination. """ for _file in lst: if type(_file) != str: _file = _file.decode('utf-8') if not bool(re.search(r'\_c\.', _file)): try: download_file(sftp, _file, origin_directory, destination) rename_file(sftp, _file, origin_directory, "_c.") except FileNotFoundError: print("Could not find", origin_directory + _file) continue except OSError: print("OSError on", str(os.path.join( origin_directory, _file)), "--------------&lt;&lt;") continue else: print(_file, "already copied") def main(): sftp, ssh = connect_to_ssh_server( "192.168.0.100", 2222, "testUsr", "supersecretpassword") android_path = "DCIM/camera/" # use `.*` to copy all filetypes files = list_files(android_path, ".*", ssh) origin_directory = '/storage/emulated/0/' + android_path copy_all_files(files, origin_directory, '/media/pi/My Passport/Galaxy S8/', ssh, sftp) ssh.close() if __name__ == "__main__": main() </code></pre>
[]
[ { "body": "<p>This is decent code, job well done!</p>\n\n<p>I have a few nitpicks,</p>\n\n<ul>\n<li><p>PEP8 violations</p>\n\n<ol>\n<li>Functions and variables should be <code>snake_case</code></li>\n<li><a href=\"https://www.python.org/dev/peps/pep-0008/#imports\" rel=\"nofollow noreferrer\">Group your imports</a></li>\n</ol>\n\n<p>There are multiple tools out there that checks your code PEP8 violations</p></li>\n<li><p>When joining paths => us <a href=\"https://docs.python.org/3/library/pathlib.html\" rel=\"nofollow noreferrer\"><code>pathlib</code></a> or <code>os.path.join</code></p>\n\n<p>Adding paths via string concatenations can be error prone, it is best to use <code>os.path.join(path1, path2)</code> </p>\n\n<p>For instance it will handle cases when you try to add <code>/a/b/</code> with <code>/c/d</code></p>\n\n<p>You do this in a few places, but not all the time. Stay consistent!</p></li>\n<li><p><code>extention = filename.rsplit(\".\")[1]</code></p>\n\n<p>You can use <code>root, extentsion = os.path.splittext(filename)</code></p></li>\n<li><p>You can catch multiple exceptions at once</p>\n\n<pre><code>except (pmko.ssh_exception.NoValidConnectionsError, TimeoutError):\n</code></pre></li>\n<li><p>Instead of printing what went wrong, try <a href=\"https://docs.python.org/3/howto/logging.html\" rel=\"nofollow noreferrer\">logging</a></p>\n\n<p>Print statements are there for a short time, logs are forever</p></li>\n<li><p><code>if not bool(re.search(r'\\_c\\.', _file)):</code></p>\n\n<p>Here <code>bool</code> is superfluous when no match is found it will return <code>None</code>, which is Falsey</p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-20T14:05:27.827", "Id": "417664", "Score": "0", "body": "Thanks so much for your time and comments! 1) Looks like I mostly grouped imports, just need to move the `from x import y` to the end? 2) Yes! That's exactly what I was trying to figure out, because it's going to happen where I forget to add a trailing `/`, so the concat won't work. 3) Most excellent, because this also avoids any issue where I have a `.` in the filename (however rare, it's awesome I can truly split on the extension like that, great tip!), 4) Noted! 5) Thanks for that, I haven't come across logging, will check out!, 6) Noted! ...thanks again, these are excellent points :D" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-20T22:32:47.320", "Id": "417730", "Score": "0", "body": "Also, just for the record, it's `os.path.splitext()`, not `...splittext()`, as I found after getting an `AttributeError`. ...which is odd. Perhaps a typo in Python library? Who knows!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-21T06:34:27.360", "Id": "417757", "Score": "1", "body": "That is easy to misspell ;). About the imports both PIL and paramiko are 3th party tools, and should be at the end. The PEP8 link has all the rules regarding imports" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-22T03:20:28.317", "Id": "417889", "Score": "0", "body": "Sorry to ask another question - can you clarify the last point? Do I simply need to remove the `bool`? (I'm studying up on Falsey/True-y/bool, but maybe a quick explanation here would help quicker. No worries if not, your answer (especially the `logging` part) have already taught me tons and sent me down a few fun rabbit holes.. :D" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-22T08:15:26.077", "Id": "417900", "Score": "1", "body": "@BruceWayne No problem! You can either simply remove the `bool` since `None` is Falsey or be explicit with `if re.search(...) is None`" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-20T13:46:29.797", "Id": "215841", "ParentId": "215780", "Score": "1" } } ]
{ "AcceptedAnswerId": "215841", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-19T18:02:39.417", "Id": "215780", "Score": "4", "Tags": [ "python", "python-3.x", "file-system", "ssh" ], "Title": "Copy files from directory to SSH Server" }
215780
<p>I have a Numpy function that takes the values of an existing array <code>X</code> and a size (int) <code>k</code> equivalent to the columns of the array. This function does some calculations in a new array, to finally output the new array after the calculations are done.</p> <pre><code>def ff(x, k): newarr = np.zeros((x.shape[0], 1), dtype=np.uint32) newarr[:, 0] = x[:, 0] * 4 for i in range(1, k - 1): newarr[:, 0] += x[:, i] newarr[:, 0] = newarr[:, 0] * 4 newarr[:, 0] += x[:, -1] return newarr </code></pre> <p><code>newarr</code> it's the array where the calculated data is stored, it's initialized with <code>np.zeros</code> and a <code>dtype</code>, and it has a shape of <code>(y,1)</code> where <code>y</code> is the length of the <code>x</code> array.</p> <p>The first step is to store in the (only) column of the <code>newarr</code> the multiplication of the first column of the <code>x</code> by 4.</p> <p>The iteration occurs over the columns <code>1 to k-1</code> of the original array (<code>x</code>). Inside the iteration, the next step is to sum the values of the first column of <code>x</code> to the column of <code>newarr</code>. Next, to multiply the column of <code>newarr</code> by 4 To finally, after the iteration is complete, sum the last column of the original array <code>x</code> to the column of <code>newarr</code>.</p> <p>I'm looking for a way (if there's any) to avoid the creation of the <code>newarr</code>, and do the calculations in the original array. This', to reduce the memory usage of this function, mainly because the <code>x</code> tends to be very big in execution.</p> <p>The <code>x</code> array looks like this.</p> <pre><code>array([[3, 3, 0, 1], [3, 0, 1, 0], [0, 1, 0, 2], [1, 0, 2, 2], [0, 2, 2, 3], [2, 2, 3, 1], [2, 3, 1, 3], . . . [2, 2, 0, 1]], dtype=uint8) </code></pre> <p>In this case, the <code>k</code> value would be 4.</p> <p><strong>Edit</strong></p> <p>For the sake of completeness, I've attached the memory profile of my solution and the proposed dot product, for a big <code>x</code> array: (248956413, 10).</p> <p>My solution</p> <pre><code>Line # Mem usage Increment Line Contents ================================================ 18 322.0 MiB 322.0 MiB @profile 19 def ff(x, k): 20 322.0 MiB 0.0 MiB newarr = np.zeros((x.shape[0], 1), dtype=np.uint32) 21 1271.7 MiB 949.8 MiB newarr[:, 0] = x[:, 0] * 4 22 1274.2 MiB 0.0 MiB for i in range(1, k - 1): 23 1274.2 MiB 0.0 MiB newarr[:, 0] += x[:, i] 24 1274.2 MiB 2.5 MiB newarr[:, 0] = newarr[:, 0] * 4 25 1274.2 MiB 0.0 MiB newarr[:, 0] += x[:, -1] 26 1274.2 MiB 0.0 MiB return newarr </code></pre> <p>Dot product.</p> <pre><code>Line # Mem usage Increment Line Contents ================================================ 18 321.7 MiB 321.7 MiB @profile 19 def ff2(x,k): 20 2221.2 MiB 1899.5 MiB return x.dot(4 ** np.arange(k - 1, -1, -1)) </code></pre> <p>I was expecting a reduction in memory usage. Clearly, I was wrong.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-20T03:20:56.697", "Id": "417577", "Score": "1", "body": "This looks like a simple matrix product, with a power series: `x.dot(4**np.arange(k-1,-1,-1)) `. `newarr` is only one column, or 1d, a fraction of the size of `x` (with `k` columns). I wouldn't worry about memory savings." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-20T11:39:55.023", "Id": "417632", "Score": "0", "body": "@hpaulj Indeed was a dot product, thanks for that!. But for the sake of completeness, I've attached the memory profile of both functions. Weird at least!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-29T22:57:49.903", "Id": "418857", "Score": "0", "body": "@hpaulj: Would you mind making your comment up into a short answer (maybe explain your thought process as well, or add some memory profiling as OP did) so that this question gets out of the large pool of unanswered questions?" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-19T18:30:56.610", "Id": "215783", "Score": "1", "Tags": [ "python", "python-3.x", "numpy" ], "Title": "Reduce memory consumption of numpy function" }
215783
<pre><code>#include &lt;iostream&gt; #include &lt;iomanip&gt; #ifdef USE_OLD_RAND #include &lt;stdlib.h&gt; inline double getRandDart() {return rand() * 1.0 / RAND_MAX;} #else #include &lt;random&gt; std::default_random_engine generator; std::uniform_real_distribution&lt;double&gt; distribution(0,1); inline double getRandDart() {return distribution(generator);} #endif // Monte Carlo Simulator to estimate the value of PI. // // If we have a circle with a radius of 1. // Then the smallest square that encloses the circle as sides of length 2. // // Area of circle pi r^2 = pi // Area of square 2.r.2.r = 4 // // Ratio of overlapping area: pi/4 // // If we throw darts randomly at a dart board (with an even distribution) and always hit the square. // Then the ratio of darts falling into the circle should be pi/4 of the total number of darts thrown. // // pi/4 * countInSquare = countInCircle // // pi = 4 . countInCircle / countInSquare // // To simplify the maths. // We will set the center point as 0,0 and only use the top right quadrant of the circle. // We have 1/4 the size of the square and circle but the same maths still apply. // // A dart thrown has a random x/y value in the range 0-&gt;1 (top right quadrant). // A dart is outside the circle if x^2 + y^2 &gt; 1 (note 1^2 is 1) // int main() { long countInSquare = 0; long countInCircle = 0; for(long iteration = 0; iteration &lt;= 10'000'000'000; ++iteration) { double x = getRandDart(); double y = getRandDart(); double d = (x * x) + (y * y); countInSquare += 1; countInCircle += (d &gt;= 1.0) ? 0 : 1; if (iteration % 10'000'000 == 0) { std::cout &lt;&lt; iteration &lt;&lt; " " &lt;&lt; (4.0 * countInCircle / countInSquare) &lt;&lt; "\n"; } } std::cout &lt;&lt; "\n\n" &lt;&lt; std::setprecision(9) &lt;&lt; (4.0 * countInCircle / countInSquare) &lt;&lt; "\n"; } </code></pre> <p>Output:</p> <pre><code>&gt; ./a.out 9990000000 3.14158 10000000000 3.14158 3.14158355 </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-19T19:29:29.833", "Id": "417532", "Score": "0", "body": "Your comment says that x*x+y*y==1 is not outside the circle (hence it is inside), but your code considers it outside. Which way is the correct interpretation?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-19T19:31:17.687", "Id": "417533", "Score": "0", "body": "@1201ProgramAlarm: Good catch. Stupid comments; why don't they compile so we can check the code matches the comments." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-19T20:03:26.213", "Id": "417541", "Score": "0", "body": "There are languages where that's kind of true (but also means that you can get syntax errors with your comments)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-19T21:16:30.977", "Id": "417551", "Score": "0", "body": "@Foon Interesting! Do you have any examples?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-19T21:22:02.863", "Id": "417553", "Score": "0", "body": "Spark is the first one that comes to mind (https://en.wikipedia.org/wiki/SPARK_(programming_language)) ... I was thinking Eiffel also did it, but actually, Eiffel's contracts are probably natively supported (Spark is basically a subset of Ada with additional things embedded in Ada compilers for the Spark checker to work with)" } ]
[ { "body": "<p>One could consider at least the following points:</p>\n\n<ul>\n<li><p>Instead of including <code>&lt;stdlib.h&gt;</code>, I'd include <code>&lt;cstdlib&gt;</code>.</p></li>\n<li><p>In <code>getRandDart()</code>, it <em>might</em> in this case be more readable to do <code>static_cast&lt;double&gt;(rand()) / RAND_MAX;</code> instead of multiplying by <code>1.0</code>.</p></li>\n<li><p>In the for loop, all of <code>x</code>, <code>y</code> and <code>d</code> can be const, so I'd make them const. This has the potential to protect the programmer from unintended mistakes, and can sometimes allow the compiler to optimize better.</p></li>\n<li><p>When you increment by one (in <code>countInSquare += 1;</code>), it makes more sense to use the <code>++</code> operator, i.e., to just write <code>++countInSquare</code>. This is more idiomatic and protects us from unintended mistakes: ++ conveys the meaning of increment (by one), whereas with <code>+=</code> we might accidentally write <code>+= 2;</code> and that would be perfectly valid (but not what we wanted).</p></li>\n<li><p>Regardless of the above point, notice that during the for-loop, it holds that <code>iteration == countInSquare</code>. So strictly speaking, the variable <code>countInSquare</code> is unnecessary and could be replaced by just <code>iteration</code> when needed.</p></li>\n<li><p>You could consider making the number of iterations and the second operand of the <code>%</code> operand constants to allow for easier modification and perhaps to slightly improve readability.</p></li>\n<li><p>Instead of typing <code>(4.0 * countInCircle / countInSquare)</code> twice, we could make a function that takes the two variables as parameters. This would allow us to save some typing, and again to protect us from unintended mistakes. </p></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-19T19:16:25.740", "Id": "215788", "ParentId": "215784", "Score": "11" } }, { "body": "<pre><code>#include &lt;random&gt;\nstd::default_random_engine generator;\n</code></pre>\n\n<p>If you require portable and reproducible results from your random engine, consider specifying the exact random engine you want instead of relying on an implementation-defined alias.</p>\n\n<pre><code>// GCC &amp; Clang\nusing minstd_rand0 = linear_congruential_engine&lt;uint_fast32_t, 16807, 0, 2147483647&gt;;\nusing default_random_engine = minstd_rand0;\n\n// MSVC\nusing default_random_engine = mt19937;\n</code></pre>\n\n<hr>\n\n<pre><code>std::uniform_real_distribution&lt;double&gt; distribution(0,1);\n</code></pre>\n\n<p>For distributions, the standard doesn't require the result to be reproducible and identical across all implementations. If you care for portability, you'll need to write/copy the specific distribution behavior you want.</p>\n\n<hr>\n\n<pre><code>inline double getRandDart() {return distribution(generator);}\n\n// A dart thrown has a random x/y value in the range 0-&gt;1 (top right quadrant).\n// A dart is outside the circle if x^2 + y^2 &gt; 1 (note 1^2 is 1)\n</code></pre>\n\n<p>This is an example of where the comment doesn't match the function. The function <code>getRandDart()</code> doesn't return a dart. It returns a single magnitude instead of a Dart/Vec2d.</p>\n\n<hr>\n\n<pre><code> for(long iteration = 0; iteration &lt;= 10'000'000'000; ++iteration) {\n</code></pre>\n\n<p>Did you intend for ten billion and one iterations (<code>&lt;=</code>)?</p>\n\n<hr>\n\n<pre><code> long countInSquare = 0;\n for(long iteration = 0; iteration &lt;= 10'000'000'000; ++iteration) {\n countInSquare += 1;\n if (iteration % 10'000'000 == 0) {\n std::cout &lt;&lt; iteration &lt;&lt; \" \" &lt;&lt; (4.0 * countInCircle / countInSquare) &lt;&lt; \"\\n\";\n</code></pre>\n\n<p>Do you need <code>countInSquare</code>? Both <code>iteration</code> and <code>countInSquare</code> are maintaining the same count.</p>\n\n<p>When you don't care for the size in which an integer can represent because the value is countable, simply use <code>int</code>. In this case, you went with <code>long</code> as you needed a larger integral type to hold a value that couldn't be represented by an <code>int</code>. Compiling in an environment where <code>long</code> is 32-bit (windows) would obviously be bad. In these cases, use a specific fixed width integer type from <code>&lt;cstdint&gt;</code>. <code>auto</code> also works in determining the correct type (64-bit <code>long</code> on gcc/clang, 64-bit <code>long long</code> on msvc).</p>\n\n<hr>\n\n<pre><code> countInCircle += (d &gt;= 1.0) ? 0 : 1;\n</code></pre>\n\n<p>Compilers are nice nowadays and optimized your ternary add.</p>\n\n<pre><code> countInCircle += (d &lt; 1.0);\n</code></pre>\n\n<hr>\n\n<p>You can tighten the inner loop by reorganizing the operations. Rather than checking every iteration to report, tile the iterations into groups that calculate between reports.</p>\n\n<pre><code> constexpr auto totalIterations = 10'000'000'001;\n constexpr auto reportInterval = 10'000'000;\n constexpr auto reports = std::div(totalIterations, reportInterval);\n\n while (reports.quot--) {\n for (auto iteration = 0; iteration &lt; reportInterval; ++iteration) {\n const auto x = getRandDart();\n const auto y = getRandDart();\n const auto d = x * x + y * y;\n countInCircle += (d &lt; 1.0);\n }\n countInSquare += reportInterval;\n std::cout &lt;&lt; countInSquare &lt;&lt; \" \" &lt;&lt; (4.0 * countInCircle / countInSquare) &lt;&lt; \"\\n\";\n }\n\n while (reports.rem--) {\n const auto x = getRandDart();\n const auto y = getRandDart();\n const auto d = x * x + y * y;\n countInCircle += (d &lt; 1.0);\n }\n\n std::cout &lt;&lt; \"\\n\\n\" &lt;&lt; std::setprecision(9) &lt;&lt; (4.0 * countInCircle / totalIterations) &lt;&lt; \"\\n\";\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-20T09:05:45.547", "Id": "215824", "ParentId": "215784", "Score": "4" } } ]
{ "AcceptedAnswerId": "215788", "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-19T19:04:31.970", "Id": "215784", "Score": "11", "Tags": [ "c++", "numerical-methods" ], "Title": "Calculate Pi using Monte Carlo" }
215784
<p>I have a Winforms MVP application where I need to use the ErrorProvider on the view. I have added the following methods to my presenter to allow me to show the ErrorProvider but it just doesn't feel right. Please review my code and tell me if you think there is a more efficient way of carrying out the validation.</p> <pre><code>private bool IsValid(string sender) { bool isValid = true; ResetValidation(); //FilePath Validation if(!ValidationService.StringHasValue(_view.FilePath)) { _view.SetFilePathErrorMessage(Messages.FieldRequired); isValid = false; } if (sender == "OnImportClicked") return isValid; //BatchRef Validation if (!ValidationService.StringHasValue(_view.BatchRef.ToString())) { _view.SetBatchRefErrorMessage(Messages.FieldRequired); isValid = false; } //Transfer Validaion if(!_transferredToHoldingTable) { _view.SetTransferErrorMessage(Messages.NoRawData); isValid = false; } return isValid; } private void ResetValidation() { _view.SetFilePathErrorMessage(string.Empty); _view.SetBatchRefErrorMessage(string.Empty); _view.SetTransferErrorMessage(string.Empty); } </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-19T19:08:24.130", "Id": "215785", "Score": "5", "Tags": [ "c#", "validation", "winforms", "mvp" ], "Title": "Winforms MVP Validation" }
215785
<p>I've recently decided to get into functional programming with F#, and decided to learn the language through <a href="https://projecteuler.net/" rel="nofollow noreferrer">Project Euler</a>. The following is my implementation of <a href="https://projecteuler.net/problem=102" rel="nofollow noreferrer">problem 102</a>:</p> <p>Problem:</p> <blockquote> <p>Three distinct points are plotted at random on a Cartesian plane, for which -1000 ≤ x, y ≤ 1000, such that a triangle is formed.</p> <p>Consider the following two triangles:</p> <p>A(-340,495), B(-153,-910), C(835,-947)</p> <p>X(-175,41), Y(-421,-714), Z(574,-645)</p> <p>It can be verified that triangle ABC contains the origin, whereas triangle XYZ does not.</p> <p>Using triangles.txt (right click and 'Save Link/Target As...'), a 27K text file containing the co-ordinates of one thousand "random" triangles, find the number of triangles for which the interior contains the origin.</p> <p>NOTE: The first two examples in the file represent the triangles in the example given above.</p> </blockquote> <p>Implementation:</p> <pre><code>type Coord = { x: int; y: int } let origin = { x = 0; y = 0 } let intToCoord [x; y] = { x = x; y = y } let twiceTriangleArea a b c = abs (a.x * (b.y - c.y) + b.x * (c.y - a.y) + c.x * (a.y - b.y)) let containsOrigin [a; b; c] = twiceTriangleArea a b c = twiceTriangleArea origin a b + twiceTriangleArea origin b c + twiceTriangleArea origin a c let solution = System.IO.File.ReadLines "triangles.txt" |&gt; Seq.map (fun line -&gt; line.Split ',' |&gt; Array.map int |&gt; List.ofArray |&gt; List.chunkBySize 2 |&gt; List.map intToCoord ) |&gt; Seq.filter containsOrigin |&gt; Seq.length printfn "%i" solution </code></pre> <p>Explanation:</p> <ol> <li>This code iterates through each line of <code>triangles.txt</code>.</li> <li>It then splits each line (by comma), takes elements in groups of 2, and converts them to coordinates.</li> <li>For each of these three coordinates, it checks if they make a triangle containing the origin by checking if the sum of the areas of all triangles made from two of the passed points and the origin is equal to the total triangle area (with all three points). Note that the area isn't divided by 2 in order to prevent floating point errors. All triangles that do not meet this criteria are filtered out.</li> <li>The number of remaining triangles are summed and printed to the user.</li> </ol> <p>While making this, I tried to maintain a functional style as much as possible.</p> <p>Here is what mainly I want to get from a review:</p> <ol> <li>Is my code idiomatic and functional? Where can it be improved in this regard?</li> <li>Are there any areas where I am unnecessarily doing extra computation and the code can be simplified?</li> </ol>
[]
[ { "body": "<p>It looks OK to me. You can avoid the <code>List.ofArray</code> call, if you change the arguments to <code>intToCoord</code> and <code>containsOrigin</code> to arrays instead of lists:</p>\n\n<pre><code>let intToCoord [|x; y|] = { x = x; y = y }\n\nlet containsOrigin [|a; b; c|] =\n twiceTriangleArea a b c = twiceTriangleArea origin a b +\n twiceTriangleArea origin b c +\n twiceTriangleArea origin a c\n\n\n\nlet solution =\n System.IO.File.ReadLines \"p102_triangles.txt\"\n |&gt; Seq.map (fun line -&gt; \n line.Split ',' |&gt; Array.map int |&gt; Array.chunkBySize 2 |&gt; Array.map intToCoord\n )\n |&gt; Seq.filter containsOrigin\n |&gt; Seq.length\n</code></pre>\n\n<hr>\n\n<p><strong>Update</strong>:</p>\n\n<p>You could though \"rearrange\" the mapping from <code>string</code> to a \"triangle\" in this way:</p>\n\n<pre><code>let toCoord [|x; y|] = { x = int x; y = int y}\n\nlet toTriangle line = (string line).Split ',' |&gt; Array.chunkBySize 2 |&gt; Array.map toCoord\n</code></pre>\n\n<p>And then change the main function to:</p>\n\n<pre><code>let solution =\n System.IO.File.ReadLines \"p102_triangles.txt\"\n |&gt; Seq.map toTriangle\n |&gt; Seq.filter containsOrigin\n |&gt; Seq.length\n</code></pre>\n\n<p>In this way you gain more even abstraction levels in the pipe chain in the main function.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-19T22:05:29.150", "Id": "215797", "ParentId": "215790", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-19T19:44:22.527", "Id": "215790", "Score": "2", "Tags": [ "programming-challenge", "f#", "computational-geometry" ], "Title": "Project Euler Problem #102 in F#: counting triangles that contain the origin" }
215790
<p>I am trying to solve this HackerRank challenge which asks to write a function that prints the indexes of all sentences which contain the query words. For example, if the inputs to the function are:</p> <pre class="lang-py prettyprint-override"><code>textQueries(sentences, queries) textQueries(['jim likes mary','kate likes tom', 'tom does not like jim'],['jim tom', 'likes']) </code></pre> <p>Then the function will print</p> <pre><code>2 0 1 </code></pre> <p>If there is no sentence contains the query words, <code>-1</code> will be printed</p> <p>The constraints for the inputs are:</p> <ul> <li>The length of the <code>sentences</code> and <code>queries</code> lists will not exceed 10000.</li> <li>The number of words in any sentence or query is from 1 to 10 words.</li> <li>Each word has at most 11 characters.</li> <li>No word appears in more than 10 sentences.</li> <li>Each word consists of uppercase and lowercase English letters only.</li> </ul> <p>My attempt so far is to create a hashmap which maps each single query word with a set that contains the indexes to the sentences which contain that word, then I intersect those sets with each other to get the final set. My code runs fine, but it is slow for large test cases. Is there any way I can have it optimized?</p> <pre class="lang-py prettyprint-override"><code>def textQueries(sentences, queries): word_map = {} for query in queries: query_words = query.split() final_set = set([]) set_modified = False for query_word in query_words: if query_word in word_map: if len(final_set) == 0 and not set_modified: final_set = word_map[query_word] set_modified = True continue elif len(final_set) == 0 and set_modified: break else: final_set = final_set.intersection(word_map[query_word]) continue else: sentences_contain_word = [] for index, sentence in enumerate(sentences): words = sentence.split() if query_word in words: sentences_contain_word.append(index) if len(sentences_contain_word) &gt;= 10: break word_map[query_word] = set(sentences_contain_word) if len(final_set) == 0 and not set_modified: final_set = word_map[query_word] set_modified = True elif len(final_set) == 0 and set_modified: break else: final_set = final_set.intersection(word_map[query_word]) if len(final_set) == 0: print(-1) else: for index in sorted(final_set): print(str(index), end=' ') print() </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-19T23:11:57.927", "Id": "417560", "Score": "0", "body": "Welcome to Code Review! Your example prints `2` followed by `0 1`if I execute the code. Could you verify that your code and the example output are correct?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-19T23:15:29.357", "Id": "417561", "Score": "0", "body": "yea it should be `2` and `0 1` sorry for the confusion" } ]
[ { "body": "<p>Your code is fairly readable, but I find it quite dense. Here are some general things you could do to improve it:</p>\n\n<ol>\n<li><p>Use vertical white space to separate different areas of the code.</p></li>\n<li><p>Provide a docblock at the top outlining the algorithm you are using.</p></li>\n<li><p>Use more than one function to break your code into smaller chunks.</p></li>\n</ol>\n\n<p>With that advice out of the way, let's look at your performance with an eye to the worst possible case:</p>\n\n<pre><code>def textQueries(sentences, queries):\n for query in queries: # Worst case: 10,000 times\n ...\n for query_word in query_words: # Worst case: 10 times\n if query_word in word_map:\n final_set.intersection # Worst case: O(10,000) in C\n else:\n for ... in enumerate(sentences): # Worst case: 10,000 times\n if ... else:\n final_set.intersection # Worst case: O(10,000) in C\n</code></pre>\n\n<p>According to me, your code runs worst case in <span class=\"math-container\">\\$O(Q \\times W \\times S)\\$</span> where <span class=\"math-container\">\\$Q\\$</span> is the number of queries, <span class=\"math-container\">\\$W\\$</span> is the number of words in the query, and <span class=\"math-container\">\\$S\\$</span> is the number of sentences. (The number of words in the sentences is hidden behind a split, but it's in C so we'll let it go by.)</p>\n\n<p>There's no question you need to split the sentences and split the queries into separate words, somehow. But you are <em>nesting</em> your loops when the \"best\" way to loop is to do them one after the other. If you can convert from this:</p>\n\n<pre><code>for q in Q:\n for s in Q:\n pass\n</code></pre>\n\n<p>to something like this:</p>\n\n<pre><code>for s in S:\n pass\n\nfor q in Q:\n pass\n</code></pre>\n\n<p>You will have converted from <span class=\"math-container\">\\$O(S \\times Q)\\$</span> to <span class=\"math-container\">\\$O(S + Q)\\$</span> which is considerably faster.</p>\n\n<p>Your current approach is to define a set of sentences that contain a particular word. You cache these sets, in case the same words appear again. You intersect the sets for each word in the query, producing a final set of all the sentences that contain all the query words.</p>\n\n<p>This is pretty much <strong>guaranteed to fail</strong> based on the instructions you quoted:</p>\n\n<blockquote>\n <p>No word appears in more than 10 sentences.</p>\n</blockquote>\n\n<p>In other words, the probability of a \"cache hit\" is 10/10,000, or 0.1%. Any time you spend maintaining the cache is wasted time.</p>\n\n<p>Suppose you just go through the sentences one time, and build the big dictionary of sets:</p>\n\n<pre><code>sentence_words = collections.defaultdict(set)\nfor i, s in enumerate(sentences):\n for w in s.split():\n sentence_words[s].add(i)\n</code></pre>\n\n<p>Then you can go through the query words and do what you were doing before, without any caching:</p>\n\n<pre><code>for q in queries:\n matches = functools.reduce(operator.and_, (sentence_words[w] for w in q.split()))\n matches = [-1] if not matches else sorted(matches)\n</code></pre>\n\n<p>This will seem very similar to what you were doing, but the difference is that these two loops are run one after the other, providing something like <span class=\"math-container\">\\$O(100,000 + 100,000)\\$</span> performance instead of <span class=\"math-container\">\\$O(100,000 \\times 10,000)\\$</span>. It's that last operator that makes all the difference.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-20T01:34:57.767", "Id": "215802", "ParentId": "215792", "Score": "3" } }, { "body": "<p>I'm not sure how much there can be gained performance-wise, since the problem has an inherent theoretical complexity limit (quite nicely elaborated in <a href=\"https://codereview.stackexchange.com/a/215802/92478\">this</a> answer) not even the most well crafted code can overcome. Additionally, Python usually is not terribly fast when you have a lot of (nested) loops.</p>\n\n<p>Python IDEs like Spyder come with a built-in profiler tool (<a href=\"https://docs.spyder-ide.org/profiler.html\" rel=\"nofollow noreferrer\">see the docs</a>), which allows you to identify performance bottlenecks. Having a quick run with your small example code showed me that on my machine most of the time is actually spent in printing the values.<br/>\nFeel free to give it a go with more realistic inputs on your machine.</p>\n\n<hr>\n\n<p>Nevertheless, I think your code could easily gain quite a bit on the style and clarity side.</p>\n\n<p>What do I mean by this? Well, let me elaborate:</p>\n\n<p>What (I think) your code wants to do:</p>\n\n<ol>\n<li>Build a dictionary/hash map where each query word is a key that maps to a collection of indices of all sentences where the query word occurs.</li>\n<li>Use this dictionary to determine the indices of all sentences containing all the query's words</li>\n<li>Print those indices to the command line</li>\n</ol>\n\n<h2>Printing</h2>\n\n<p>Let's start with an easy one, #3. Your code was</p>\n\n<pre><code>if len(final_set) == 0:\n print(-1)\nelse:\n for index in sorted(final_set):\n print(str(index), end=' ')\n print()\n</code></pre>\n\n<p>which does what you want to do. But can we do better?\nI would like to propose as slight improvement.</p>\n\n<pre><code>if final_set:\n print(' '.join(str(i) for i in sorted(final_set)))\nelse:\n print(-1)\n</code></pre>\n\n<p>So what is going on here?<br/>\nFirst, <code>if final_set:</code> quite obviously replaces <code>if len(final_set) == 0:</code>. <br/>\nHow? In Python empty \"iterables\" like lists, tuples, strings or in your case sets evaluate to <code>False</code> which would then print <code>-1</code> in the console, just as before.<br/>\nNext, <code>\" \".join(str(i) for i in sorted(final_set))</code> uses list comprehension together with the built-in <a href=\"https://docs.python.org/3/library/stdtypes.html#str.join\" rel=\"nofollow noreferrer\">join</a>-function to generate the final indices output.\nThis does basically the same as your original code and is just a little shorter, as a bonus you get the newline for free.</p>\n\n<h2>Building the hash map</h2>\n\n<p>To get to point #1, most of the heavy lifting is done in the <code>else</code> branch of the major <code>if</code> statement in your code.<br/>\nSo far so straightforward, not much to gain here. In my oppinion, <code>words = sentence.split()</code> should not be necessary. Python's <code>in</code> is capable of finding the word in the full string, too.<br/>\nOne could argue that it would be increase clarity and maintainability to place move this functionality to the beginning of the function (or in a seperate function altogether) to better seperate subtasks #1 and #2.</p>\n\n<h1>Using the hash map</h1>\n\n<p>Last but not least #2.<br/>\nYour code in the <code>if</code> branch gets a little bit involved here.<br/>\nIf you build your word_map before processing the sentences and I'm not mistaken this can be simplified quite a bit to</p>\n\n<pre><code>final_set = set()\nfor word in query.split():\n if not final_set:\n final_set = word_map.get(word, set())\n else:\n final_set = final_set.intersection(word_map.get(word, set()))\n if not final_set:\n break\n</code></pre>\n\n<p>I have talked about using the \"trueness/falseness\" of iterables before so the use here should not suprise you. <code>word_map.get(word, set())</code> is just a way of saying \"get me the value of key <code>word</code>, and if there's nothing, return <code>set()</code>\".<br/></p>\n\n<h1>Final code</h1>\n\n<p>My final code was</p>\n\n<pre><code>def textQueriesRevised(sentences, queries):\n # 1. build the hash map\n word_map = {}\n for query in queries:\n for query_word in query.split(): \n for i, sentence in enumerate(sentences):\n if query_word in sentence:\n word_map.setdefault(query_word, []).append(i)\n for query in queries:\n # 2. look up in the hash map\n final_set = set()\n for word in query.split():\n if not final_set:\n final_set = set(word_map.get(word, []))\n else:\n final_set = final_set.intersection(word_map.get(word, []))\n if not final_set:\n break\n # 3. print the indices\n if final_set:\n print(' '.join(str(i) for i in sorted(final_set)))\n # or\n #print(*sorted(final_set), sep=' ')\n else:\n print(-1)\n</code></pre>\n\n<p>You will find subtle differeces to some of the snippets posted above, but these mainly stem from me not wanting to work with sets while populating <code>word_map</code> (no particular reason for this - apart from that it's getting late here).\nPerformance-wise this should be comparable to your original solution, at least in the cases where I tested it.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-20T01:39:19.097", "Id": "215803", "ParentId": "215792", "Score": "1" } } ]
{ "AcceptedAnswerId": "215802", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-19T20:19:58.123", "Id": "215792", "Score": "2", "Tags": [ "python", "performance", "programming-challenge" ], "Title": "Determine which sentences contain the set of phrases" }
215792
<p>I'm extracting variables from user entered mathematical expressions, so that I can enter them into the expression evaluator exprtk. For now, the condition is given that variable names will be composed of consecutive capital letters. Any mathematical constants or function names will be lowercase. Some hypothetical inputs and expected outputs:</p> <p>Input: "(A + B) - 2"<br> Expected Output: { A, B }</p> <p>Input: "pow(AC,E) * ( E * F )"<br> Expected Output: { AC, E, F }</p> <p>The code I have right now seems to work, but I would love a critique. I add a space to the end of the string to make my algorithm catch cases at the end of the string, which seems a bit hacky(?).</p> <pre><code>template&lt;class T&gt; std::vector&lt;std::string&gt; MapEvaluator&lt;T&gt;::extractVariables(std::string expression) { expression = expression + " "; std::vector&lt;std::string&gt; variables = {}; std::string substring; size_t consecutiveCharsCaps = 0; bool previousCharCaps = false; for (size_t i = 0; i &lt; expression.length(); i++) { if (isCapital(expression[i])) { consecutiveCharsCaps++; previousCharCaps = true; } else { if(previousCharCaps) { substring = expression.substr(i - consecutiveCharsCaps, consecutiveCharsCaps); variables.push_back(substring); consecutiveCharsCaps = 0; previousCharCaps = false; } } } unique(variables); return variables; } template &lt;class T&gt; void MapEvaluator&lt;T&gt;::unique(std::vector&lt;std::string&gt; &amp;vec) { auto end = vec.end(); for (auto it = vec.begin(); it != end; ++it) { end = std::remove(it + 1, end, *it); } vec.erase(end, vec.end()); } template&lt;class T&gt; bool MapEvaluator&lt;T&gt;::isCapital(char c) { return (c &gt;='A' &amp;&amp; c &lt;= 'Z'); } </code></pre>
[]
[ { "body": "<p>Some observations:</p>\n\n<ul>\n<li><p>It seems that <a href=\"https://en.cppreference.com/w/cpp/algorithm/adjacent_find\" rel=\"nofollow noreferrer\"><code>std::adjacent_find</code></a> essentially already does what you want, which is extracting all continuous sub-strings consisting of uppercase letters.</p></li>\n<li><p>Removing duplicates from a vector might be fine, but you can also avoid this completely by inserting the found elements into a <code>std::set</code>. I suspect that the number of unique variables is always small, so this is a cleaner approach.</p></li>\n<li><p>There is no reason for <code>isCapital</code> to be a member function. Instead, it should be a free function. Remember that interfaces should be complete but minimal. But in fact, there's no reason for the function in the first place: the standard already has <code>std::isupper</code> that we should rather use.</p></li>\n</ul>\n\n<p>So with these in mind, we can re-write your function to e.g.,:</p>\n\n<pre><code>std::vector&lt;std::string&gt; get_variables(const std::string&amp; str)\n{\n std::set&lt;std::string&gt; vars;\n\n for (auto first = str.cbegin(); first != str.cend(); )\n {\n auto var_end = std::adjacent_find(first, str.cend(),\n [](char a, char b) \n { \n return std::isupper(static_cast&lt;unsighed char&gt;(a)) !=\n std::isupper(static_cast&lt;unsigned char&gt;(b)); \n });\n\n if (var_end != str.cend())\n {\n ++var_end;\n }\n\n if (std::isupper(static_cast&lt;unsigned char&gt;(*first)))\n {\n vars.insert(std::string(first, var_end));\n }\n\n first = var_end;\n }\n\n return std::vector&lt;std::string&gt;(vars.cbegin(), vars.cend());\n}\n</code></pre>\n\n<p>Notice that we've cast <code>char</code> to <code>unsigned char</code> before the call to <code>std::isupper</code> (thanks to <a href=\"https://codereview.stackexchange.com/users/42409/deduplicator\">Deduplicator</a> for explaining this to me). The reason is that <code>std::isupper</code> takes an argument of type <code>int</code> which must be in the range of unsigned char (or special value EOF, -1). Unfortunately, a plain <code>char</code> has either the range of signed char or unsigned char, so we perform a cast to confer to this common convention of character classification functions.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-20T03:44:16.040", "Id": "417578", "Score": "0", "body": "Very nice. Right away I tested it and got the right output. After, I stepped through your code with pencil and paper until I got the same answers, to make sure I understood how it worked. Much appreciated." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-19T20:44:52.777", "Id": "215794", "ParentId": "215793", "Score": "5" } }, { "body": "<ol>\n<li><p>Take advantage of views, specifically C++17 <a href=\"https://en.cppreference.com/w/cpp/string/basic_string_view\" rel=\"nofollow noreferrer\"><code>std::string_view</code></a>, to avoid needless allocations.</p></li>\n<li><p>Take advantage of the standard algorithms. They help writing clear, concise and fast code.</p></li>\n<li><p>Text is hard. So, do you really want uppercase ASCII letters, all single-byte (thus non-unicode) uppercase letters the current locale supports, or full unicode support? I will ignore the last option.</p></li>\n<li><p>Minimize the accessible context, and decouple as you can. <code>extractVariables()</code> can be a free function. Actually, extract a function for listing runs of any kind.</p></li>\n<li><p><code>auto</code> is very useful to avoid error-prone repetition.</p></li>\n</ol>\n\n<p>Applying that:</p>\n\n<pre><code>template &lt;class T, class F&gt;\nauto listRuns(T s, F f) {\n std::vector&lt;T&gt; r;\n auto first = begin(s);\n while ((first = std::find_if(first, end(s), f) != end(s)) {\n auto last = std::find_if_not(first, end(s), f);\n r.emplace(first, last - first);\n first = last;\n }\n std::sort(begin(r), end(r));\n r.resize(end(r) - std::unique(begin(r), end(r)));\n return r;\n}\n\nauto extractVariables(std::string_view s) {\n return listRuns(s, [](unsigned char c){ return std::is_upper(c); });\n // Keep in mind the defined domain of std::is_upper()\n\n return listRuns(s, [](char c){ return c &gt;= 'A' &amp;&amp; c &lt;= 'Z';});\n // Assumes ASCII and asks for uppercase letters\n}\n</code></pre>\n\n<p>Something to ponder:</p>\n\n<p>It might seem (or rarely actually be) advantageous to first insert into a <code>std::set</code> or <code>std::unordered_set</code> to filter out duplicates.<br>\nUnfortunately the added complexity and reduced locality of reference will almost always destroy any potential advantage, unless it leads to a very significant saving of memory. Every single dynamic allocation has (sometimes significant) overhead though.<br>\nSo if you want to try it, measure.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-20T13:17:18.527", "Id": "215839", "ParentId": "215793", "Score": "2" } }, { "body": "<p>In the ExprTk readme.txt there is a section called: <strong>Helpers &amp; Utils</strong></p>\n\n<p>In the sub-section called <strong>collect_variables</strong> there is a description of a helper free function named <code>exprtk::collect_variables</code>, which can be used to extract a list of variables used in a given expression.</p>\n\n<p>The following is an example usage of the <code>exprtk::collect_variables</code> function:</p>\n\n<pre><code>std::string expression = \"X + abs(y / Z)\";\n\nstd::vector&lt;std::string&gt; variable_list;\n\nif (exprtk::collect_variables(expression, variable_list))\n{\n for (const auto&amp; var : variable_list)\n {\n ...\n }\n}\nelse\n printf(\"An error occurred.\");\n</code></pre>\n\n<p>If successful the variable_list should contain the variables names \"X\", \"y\" and \"Z\".</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-09T17:28:43.357", "Id": "242013", "ParentId": "215793", "Score": "-1" } } ]
{ "AcceptedAnswerId": "215794", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-19T20:24:52.640", "Id": "215793", "Score": "3", "Tags": [ "c++", "algorithm", "strings" ], "Title": "Extracting all-caps variables from string expressions" }
215793
<p>Yesterday I saw a CodeTrain <a href="https://www.youtube.com/watch?v=uH4trBNn540" rel="nofollow noreferrer">video</a> in where Daniel Shiffman tried to approximate Pi using the <a href="https://en.wikipedia.org/wiki/Leibniz_formula_for_%CF%80" rel="nofollow noreferrer">Leibniz series</a>. It was interesting so I decided to try it too.</p> <p>I wrote this console application with a simple goal: Approximate as fast as possible as many digits of Pi the program can until it reaches the maximum number the cycle counter can achieve(without starting to commit calculation errors with the series formula) OR the program is stopped.</p> <p>It starts by first running two background threads which execute two functions that do all the job: <code>piLoop()</code>, for calculating the series; and <code>displayLoop()</code>, for refreshing the screen and displaying the actual calculated Pi. To prevent concurrency problems, mutexes are used to prevent the threads from accessing Pi and other program shared variables at the same time. The program runs until piCycles reaches the maximum value a <code>long long int</code> can get OR the End key is pressed.</p> <p>The final program runs, by glancing at it (that means a very unreliable measurement), at an approximated rate of 30 million cycles per second in my computer. That means it can calculate the 10th digit of PI (around 87 billion cycles) in about an hour.</p> <p>I want to know if there are some optimizations that can be made so the program can run at all his power.</p> <p><strong><em>main.cpp</em></strong></p> <pre><code>#include &lt;iostream&gt; #include &lt;thread&gt; #include &lt;mutex&gt; #include &lt;chrono&gt; #include &lt;windows.h&gt; #include &lt;limits&gt; void piLoop(); void displayLoop(); void getShouldStop(); namespace { typedef std::numeric_limits&lt;long double&gt; ldbl; typedef std::numeric_limits&lt;long long int&gt; ullint; const char displayDigits = ldbl::max_digits10; const short int updateDelay_ms = 50; // You can modify this value to change the speed of console refreshing. const long long int maxCicles = ullint::max(); bool shouldStop = false; long double PI = 0; unsigned long long int piCicles = 0; std::mutex piLock; } int main() { std::thread piCalculatorThread( piLoop ); std::thread displayUpdaterThread( displayLoop ); piCalculatorThread.join(); displayUpdaterThread.join(); std::cin.get(); return 0; } void getShouldStop() { shouldStop = GetAsyncKeyState( VK_END ) || shouldStop; } // If PI mutex is not locked, proceed to calculate the next PI, else wait void piLoop() { while ( true ) { piLock.lock(); if ( shouldStop ) { piLock.unlock(); return; } // Here the series is calculated PI += ((long double)((piCicles&amp;1)&gt;0 ? -1 : 1)) / (piCicles*2 + 1); if ( piCicles == maxCicles ) { shouldStop = true; piLock.unlock(); return; } piCicles++; piLock.unlock(); } } // Wait until PI mutex is unlocked, then refresh the screen. void displayLoop() { std::cout.precision( displayDigits ); while ( true ) { piLock.lock(); system("cls"); std::cout &lt;&lt; "\n\n ----- PI Calculator ----- \n\n - \"Seeing how PI is calculated is more enjoyable while eating some snacks.\""; std::cout &lt;&lt; "\n\n\n PI: " &lt;&lt; PI * 4; std::cout &lt;&lt; "\n Cicles: " &lt;&lt; piCicles &lt;&lt; std::endl; if ( maxCicles == piCicles ) // Just in case someone has the time to run this program for long enough std::cout &lt;&lt; "\n Max precise 64-bit computable value reached!" &lt;&lt; std::endl; if ( !shouldStop ) getShouldStop(); piLock.unlock(); if ( shouldStop ) return; std::this_thread::sleep_for( std::chrono::milliseconds( updateDelay_ms ) ); } } </code></pre> <p>I think this code can also be run on other operating systems by removing the <em>windows.h</em> header and the <code>getShouldStop()</code> function as well, so Linux users may also give it a try.</p> <p>Here is a <strong><a href="http://www.mediafire.com/file/b992gzgb6de9b02/PiCalculator.zip/file" rel="nofollow noreferrer">link</a></strong> to download the Windows executable if you want to test it.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-20T00:17:28.217", "Id": "417564", "Score": "0", "body": "Just a side note, that's a excellent YouTube channel. Daniel is a great teacher despite being very scatter brained. I highly recommend it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-20T04:18:05.013", "Id": "417579", "Score": "0", "body": "@Carcigenicate Indeed it is :) Just for the sake of this comment not being uninformative, I discovered that the Leibniz series can be accelerated using some techniques known as [\"Series acceleration\"](https://en.wikipedia.org/wiki/Series_acceleration), maybe in a future post I will improve this program with the review I could get from here and the accelerated Leibniz series if I manage to work it out, and maybe making a nice UI too :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-01T09:05:31.290", "Id": "419045", "Score": "0", "body": "You get a better acceleration using the Euler-Machin or Machin-like formulas. These are still obtained from relative simple geometry in the complex plane and the same arcus tangent series that gives the Leibniz-Georgy formula." } ]
[ { "body": "<h1>Threading structure</h1>\n<p>I rather dislike the overall structure of the code. Rather than having two threads contending over a single location where the current estimate of <span class=\"math-container\">\\$\\pi\\$</span> is stored, I'd rather have the calculator thread compute successive approximations, and write them to a queue. The display thread would then wait on value to show up in the queue, display it, and repeat. The locking and such should be in the queue itself.</p>\n<p>You've also created not just one, but two secondary threads. There's no real point in this. You started with the process' primary thread, then all it does is create two other threads, then wait for them to finish. It might as well do something useful, and only create one other thread.</p>\n<h1>Formula</h1>\n<p>It seems to me that if you're going to try to make it faster, you could at least do a minor improvement to the formula. One that's quite a bit faster, and still utterly trivial (in fact, arguably simpler than the plain Leibniz formula) is:</p>\n<p><span class=\"math-container\">\\$ {\\pi \\over 4} = {\\sum_{n=0}^{\\infty} {2 \\over (4n+1)(4n+3)}}\\$</span></p>\n<h1>Summation</h1>\n<p>This does have one interesting twist: if you just use a naive summation over this formula, you'll find that it &quot;gets stuck&quot;--with a typical double, no matter how many iterations you do, it will only ever get about 8 digits correct.</p>\n<p>The problem is that you have a number of relatively large magnitude, and you're trying to add numbers of relatively small magnitude to it. Each of them individually is too small to affect the larger number, so it remains constant.</p>\n<p>In this case, there's a pretty simple cure: start from the <em>smallest</em> numbers, and work your way toward larger numbers. That way, the sum you have and the amount you're adding to it each time have closer to the same magnitude, so more terms continue to improve the overall result.</p>\n<p>For this particular program, that has a bit of a problem though: since we're trying to display the approximation as it gets better over time, we want approximations that actually do get better over time--and if we start from the smallest, and sum toward the largest, our approximation is truly terrible for almost the entire time, then at the very end, the last few iterations suddenly make it a <em>lot</em> better in a hurry.</p>\n<p>As a compromise, we can take a middle ground: work from beginning to end, but work in &quot;chunks&quot; of (say) 10'000'000 terms, so we have an overall estimate, and we have a temporary sum of only the most recent terms. At the beginning of each iteration of the inner loop, we start over from a value of 0.0, so we don't have a drastically larger term dominating when we do the addition. Then when we've added those terms together, we add the result to the overall estimate.</p>\n<p>This also works nicely with updating the display--each time we add an intermediate value to our overall estimate, we can send the result out to be displayed.</p>\n<h1>Portability</h1>\n<p>I've left out the asynchronous keyboard reading, so the code can be portable. I'd rather use an even better formula than just let one that converges extremely slowly run for weeks on end (and then add non-portable code to let them quit more easily when they get bored).</p>\n<h1>Code</h1>\n<p>So, doing things this way, we could end up with code on this general order:</p>\n<pre><code>#include &lt;iostream&gt;\n#include &lt;iomanip&gt;\n#include &lt;deque&gt;\n#include &lt;mutex&gt;\n#include &lt;thread&gt;\n#include &lt;condition_variable&gt;\n\nnamespace concurrent {\n template&lt;class T&gt;\n class queue {\n std::deque&lt;T&gt; storage;\n std::mutex m;\n std::condition_variable cv;\n public:\n void push(T const &amp;t) {\n std::unique_lock&lt;std::mutex&gt; L(m);\n storage.push_back(t);\n cv.notify_one();\n }\n\n // This is not exception safe--if copying T may throw,\n // this can/will lose data.\n T pop() {\n std::unique_lock&lt;std::mutex&gt; L(m);\n cv.wait(L, [&amp;] { return !storage.empty(); });\n auto t = storage.front();\n storage.pop_front();\n return t;\n }\n };\n}\n\nint main() { \n concurrent::queue&lt;double&gt; values;\n\n auto t = std::thread([&amp;] {\n double pi4 = 0.0;\n for (double n = 0.0; n &lt; 8'000'000'000.0; n += 10'000'000) {\n double temp = 0.0;\n for (double i = 0; i &lt; 10'000'000; i++)\n temp += 2.0 / ((4.0 * (n + i) + 1.0) * (4.0 * (n + i) + 3.0));\n pi4 += temp;\n values.push(4.0 * pi4);\n }\n values.push(-1.0);\n });\n\n double pi;\n while ((pi=values.pop())&gt; 0.0) \n std::cout &lt;&lt; &quot;\\r&quot; &lt;&lt; std::setw(11) &lt;&lt; std::setprecision(11) &lt;&lt; std::fixed &lt;&lt; pi;\n t.join();\n}\n</code></pre>\n<p>On my machine, this calculates Pi to 10 places in about 45 seconds. Unless your computer is quite old/slow (like mine is) it'll probably run faster than that for you.</p>\n<p>On the other hand, for watching the value converge, this does have kind of the opposite problem: it finds around six or seven digits nearly instantly, then grinds for a long time to a few more. Visually, some might find the Leibniz formula more appealing for the fact that it goes first above, then below, then back above, below again, and so on as it approaches the true value of Pi (though that's more apparent if you draw a graph rather than just printing out the values).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-21T06:15:54.240", "Id": "417751", "Score": "1", "body": "The idea of taking multiple partial sums is related to Kahan summation (see Wikipedia), which may be useful in this case. In this case it might be worth having more than one correction term. On the other hand, as soon as you feed a single inexact value to the sum, all bets are off for any digits to the right." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-21T06:32:01.913", "Id": "417756", "Score": "0", "body": "Thank you very much :) I'm not very familiar with C++ so I'll try to learn something from the code you wrote, also thanks for the info @RolandIllig . I'll make some reverse engineering tests tomorrow(its late now) to your code and accept your answer if it satisfies my program needs :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-21T06:35:28.893", "Id": "417758", "Score": "1", "body": "@RolandIllig: It's true that you *could* use Kahan Summation in this case, but it's also true that Kahan summation imposes a fair amount of overhead. I should probably do a quick test to see how much (if any) real difference it makes, but I haven't yet." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-21T07:22:01.687", "Id": "417765", "Score": "0", "body": "Any reason you use a double as loop counter instead of casting afterwards?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-21T07:23:08.133", "Id": "417766", "Score": "0", "body": "I think your pop method is thread safe, however, if copying throws, you most likely are in an infinite loop if you would try again" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-21T14:14:15.733", "Id": "417811", "Score": "0", "body": "@JVApen: I simply prefer to avoid mixing types and casting unless I get at least a little bit of benefit from doing so (which I don't see in this case)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-21T22:09:59.350", "Id": "417874", "Score": "0", "body": "Your loop count ain't stable any more and you can get some bigger errors on the numbers. If I'm correct, the cert-rules suggest to never use floating point numbers as loop counter" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-21T22:16:59.700", "Id": "417875", "Score": "0", "body": "@JVApen: If somebody tries to use this software in a situation calling for high reliability, I'll be the first to ding it as a bad idea. But changing the type of the loop counter isn't going to change that." } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-21T05:52:47.683", "Id": "215903", "ParentId": "215796", "Score": "5" } } ]
{ "AcceptedAnswerId": "215903", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-19T21:35:17.223", "Id": "215796", "Score": "7", "Tags": [ "c++", "performance", "multithreading", "windows", "numerical-methods" ], "Title": "C++ Pi Calculator - Leibniz Formula" }
215796
<p>I read <a href="https://softwareengineering.stackexchange.com/questions/291141/how-to-handle-design-changes-for-auto-ptr-deprecation-in-c11">an interesting old question</a> on the Software Engineering SE about how to transition away from <code>std::auto_ptr</code>. So I wrote a wrapper around the common subset of <code>std::auto_ptr</code> and <code>std::unique_ptr</code>.</p> <p>The wrapper's mission in life at runtime is to clean up pointers created with <code>new</code> when the scope ends regardless of how the scope is exited. Its job at compile time is to make compilation fail as informatively as possible when <code>fake_autoptr</code> is used in a non-lowest-common-denominator way.</p> <p><code>fake_autoptr</code> is supposed to make it easier to transition away from <code>std::auto_ptr</code> and support both C++11 and C++03 until support for C++03 is dropped. It should behave the same way whether it is backed by an <code>auto_ptr</code> or a <code>unique_ptr</code>.</p> <p>The example given in the old question is this. This example is not leveraging many of the things that an <code>autoptr</code> can do. I think, but am not 100% certain that the <code>autoptr</code>'s job here is just to run <code>delete</code> when its destructor is called and not to steal resources from other <code>autoptr</code>s. </p> <pre><code>// NOT MINE DO NOT REVIEW Foo* GetFoo() { autoptr&lt;Foo&gt; ptr(new Foo); // Initialize Foo ptr-&gt;Initialize(...); // Now configure remaining attributes ptr-&gt;SomeSetting(...); return ptr.release(); } </code></pre> <p>Here is the wrapper I came up with.</p> <pre><code>#ifndef FAKE_AUTOPTR_FAKE_AUTOPTR_INCLUDED #define FAKE_AUTOPTR_FAKE_AUTOPTR_INCLUDED 1 #include &lt;memory&gt; #if __cplusplus &gt;= 201103L #include &lt;type_traits&gt; #endif namespace fake_autoptr_ns { namespace detail { template &lt;class T&gt; void destroy(T* goner) { delete goner; } } template &lt;class T&gt; class fake_autoptr { public: #if __cplusplus &gt;= 201103L std::unique_ptr&lt;T, decltype(&amp;detail::destroy&lt;T&gt;)&gt; smartptr_; typedef decltype(smartptr_) smartptr_type; #else std::auto_ptr&lt;T&gt; smartptr_; typedef std::auto_ptr&lt;T&gt; smartptr_type; #endif #if __cplusplus &gt;= 201103L fake_autoptr() = delete; ~fake_autoptr() = default; #else private: fake_autoptr(); public: #endif #if __cplusplus &gt;= 201103L template &lt;class CtorArg&gt; explicit fake_autoptr(CtorArg something) : smartptr_(something, detail::destroy&lt;T&gt;) { static_assert(std::is_same&lt;T*, CtorArg&gt;::value, "constructor argument must be T*"); } #else template &lt;class CtorArg&gt; explicit fake_autoptr(CtorArg something) : smartptr_(something) {} #endif // delete special member functions #if __cplusplus &gt;= 201103L explicit fake_autoptr(const fake_autoptr&lt;T&gt;&amp;) = delete; explicit fake_autoptr(fake_autoptr&lt;T&gt;&amp;&amp;) = delete; fake_autoptr&amp; operator=(const fake_autoptr&lt;T&gt;&amp;) = delete; fake_autoptr&amp; operator=(fake_autoptr&lt;T&gt; &amp;&amp;) = delete; #else private: explicit fake_autoptr(const fake_autoptr&lt;T&gt;&amp;); fake_autoptr&amp; operator=(const fake_autoptr&lt;T&gt;&amp;); public: #endif #if __cplusplus &gt;= 201103L T&amp; operator*() = delete; T* get() = delete; #endif const smartptr_type&amp; operator-&gt;() const { return smartptr_; } smartptr_type&amp; operator-&gt;() { return smartptr_; } T* release() { return smartptr_.release(); } #if __cplusplus &gt;= 201103L const T* release() const = delete; void reset() = delete; void reset() const = delete; #endif }; } #endif // FAKE_AUTOPTR_FAKE_AUTOPTR_INCLUDED </code></pre> <p>This is less interesting, but here's a smoke test to make sure it works</p> <pre><code>#include "fake_autoptr.hpp" #include &lt;cstdio&gt; struct TwoInts { int int1; int int2; void print_first_int() { printf("1st %d\n", int1); } void print_second_int() { printf("2nd %d\n", int2); } }; TwoInts* GetInt() { using namespace fake_autoptr_ns; TwoInts *t = new TwoInts(); t-&gt;int1 = 3; t-&gt;int2 = 7; fake_autoptr&lt;TwoInts&gt; ptr(t); ptr-&gt;print_first_int(); ptr-&gt;print_second_int(); return ptr.release(); } int main() { TwoInts *t = GetInt(); delete t; return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-20T01:30:31.627", "Id": "417566", "Score": "0", "body": "Can you explain your use-case better? When would I want to use `fake_autoptr<T>` in preference to `std::unique_ptr<T>`? The only advantage to `std::auto_ptr` is that it compiles as C++03... but your `fake_autoptr` is C++11-only, so *that's* not why you're using it. Why not just use `std::unique_ptr`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-20T02:30:36.273", "Id": "417570", "Score": "0", "body": "@Quuxplusone, I've edited the code so it compiles as either C++11 or C++03 ..." } ]
[ { "body": "<p>I'm not a 100% convinced that you should put effort in supporting C++98/03. Especially since you can upgrade your code with <a href=\"https://clang.llvm.org/extra/clang-tidy/checks/modernize-replace-auto-ptr.html\" rel=\"nofollow noreferrer\">Clang tidy modernize</a> However, I see the arguments on moving slowly.</p>\n\n<p>That said, your code looks good. However, I do have some remarks.</p>\n\n<p>#ifdef is used a lot. So often, that one can wonder whether it makes sense to use a single ifdef with separate class definitions. It might improve the readability.</p>\n\n<p>I really like the deleted methods and the shadow private variants. It can help a lot in ensuring the compatibility.</p>\n\n<p>Looking at the stored unique_ptr, you use a helper function to delete the stored instance. WHY? This is what the default already does with a better implementation. (No extra memory needed) I don't see a compatibility argument as you don't use it with the auto_ptr.</p>\n\n<p>I see the templated constructor, however, I don't see the point of having it as a template. Instead you could just use <code>T*</code> directly in the wrapper?</p>\n\n<p>The thing I find the strangest is your <code>operator-&gt;</code> which doesn't return a raw pointer. Instead you expose the underlying storage in that signature.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-20T21:26:02.647", "Id": "215878", "ParentId": "215798", "Score": "1" } } ]
{ "AcceptedAnswerId": "215878", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-19T22:47:58.727", "Id": "215798", "Score": "5", "Tags": [ "c++", "c++11", "pointers", "c++03" ], "Title": "wrapper for common subset of auto_ptr and unique_ptr API" }
215798
<p>This function is a wrapper for <code>arc4random(3)</code>, a cryptographic pseudo-random number generator on macOS and BSDs, but you can also get it by installing <code>libbsd-devel</code> on most Linux distros.</p> <p>It serves the same purpose as <code>arc4random_uniform(3)</code>, the official wrapper for <code>arc4random(3)</code>, i.e. to generate a nonnegative random integer less than <code>range</code>.</p> <pre><code>static inline unsigned random_uniform(unsigned range) { static uint32_t random_32b; static uint32_t full_32b; if (full_32b &lt; range) { random_32b = arc4random(); full_32b = UINT32_MAX; } unsigned result = random_32b % range; random_32b /= range; full_32b /= range; return result; } </code></pre> <p>You can find the implementation of <code>arc4random_uniform(3)</code> on macOS at the bottom of <a href="https://opensource.apple.com/source/Libc/Libc-1272.200.26/gen/FreeBSD/arc4random.c.auto.html" rel="noreferrer">this page</a>. Basically, it makes use of the rejection method to produce uniform deviates and eliminate the modulo bias. On the other hand, my implementation tries to eliminate the modulo bias by keeping track of the maximum possible range of the remaining random bytes in <code>full_32b</code>. What's more, it saves the unused random bytes in a static variable for future use, as a call to <code>arc4random(3)</code> can be costly. It appears to be faster according to my benchmark, but I'm not sure if it's correct.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-20T04:40:36.973", "Id": "417581", "Score": "2", "body": "I recommend viewing [OpenBSD's `arc4random_uniform(3)`](https://github.com/openbsd/src/blob/7e5f239444a6c4227bcf791551e257a58e0e9c4a/lib/libc/crypt/arc4random_uniform.c#L22), which is _far_ cleaner than the macOS one you link. I'd be interested in it's performance according to your benchmarking." } ]
[ { "body": "<pre><code>result = random % range\n</code></pre>\n\n<p>You can only do this if <code>range</code> is constrained to be much smaller than the maximum value of <code>random</code>. Imagine a 2-bit PRNG that returns a value from 0 to 3. When your function is invoked with range 3, return value 0 will be twice as common as 1 or 2.</p>\n\n<pre><code>random_32b /= range;\nfull_32b /= range;\n</code></pre>\n\n<p>This is going to exhibit obvious bias when the result has a small number of bits. Imagine a range of 3 and a 4-bit random pool. On exit, <code>full_32b</code> will equal 5 but <code>random_32b</code> will only equal 5 one time in 15. </p>\n\n<hr>\n\n<p>There are three good ways to go about this: </p>\n\n<ol>\n<li><ul>\n<li>choose an acceptable margin of bias (expressed as a fraction); </li>\n<li>divide <code>range</code> by that fraction; </li>\n<li>select enough bits to make <code>max(random)</code> larger than the result of the division;</li>\n<li>return a simple modulus.</li>\n</ul></li>\n</ol>\n\n<p>For example, 1% bias is 0.01. If the range is 10, the random number needs a maximum larger than <span class=\"math-container\">\\$10/0.01 = 1000\\$</span>.\nThat's ten bits.</p>\n\n<ol start=\"2\">\n<li><ul>\n<li>select enough bits to represent <code>range</code></li>\n<li>repeat until the result is smaller than <code>range</code>.</li>\n</ul></li>\n</ol>\n\n<p>Example: for a range of 10, consume four bits and discard results larger than 9.</p>\n\n<ol start=\"3\">\n<li><ul>\n<li>select enough bits to represent <code>range</code>, plus a couple more, to represent a multiple of <code>range</code>. Call the multiplier <span class=\"math-container\">\\$i\\$</span>.</li>\n<li>repeat until the result is smaller than <span class=\"math-container\">\\$i * \\$</span><code>range</code> </li>\n<li>divide result by <span class=\"math-container\">\\$i\\$</span></li>\n</ul></li>\n</ol>\n\n<p>This last approach combines the advanatages of first two: you get bias-free numbers and mostly predictable runtime. </p>\n\n<p>Example: approach #2 with a range of 9 consumes four bits per attempt, and discards almost half of the results. With 5 bits, instead of 4, you keep results from 0-26 (i.e., <code>range</code><span class=\"math-container\">\\$*3\\$</span>) and divide them by 3. Discard 27 or larger—that's only 5/32 attempts wasted. With 6 bits and range of 9, values 0-62 are usable (<code>range</code><span class=\"math-container\">\\$*7\\$</span>), and only one possible value (63) will be discarded.</p>\n\n<p>In all cases, consume bits by bit-shifting (or dividing by powers of two). Integer division with arbitrary denominators won't work.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-20T07:45:25.920", "Id": "215821", "ParentId": "215810", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-20T03:58:51.850", "Id": "215810", "Score": "5", "Tags": [ "performance", "beginner", "c", "random", "cryptography" ], "Title": "High performance wrapper for CSPRNG arc4random(3)" }
215810
<p>I am trying to make a simple expression evaluator in Java using Jacc (a parser generator). I am done with the AST creation and now need to create an evaluator. For this I made a simple test to try to understand how visitors work. Here is my code</p> <pre><code>interface Visitor { public void visitB(B b); public void visitC(C c); public void visitD(D d); } class PrintVisitor implements Visitor { public void visitB(B b) { b.child1.accept(this); b.child2.accept(this); System.out.println("a B visited: " + b.name); } public void visitC(C c) { c.child.accept(this); System.out.println("a C visited: " + c.name); } public void visitD(D d) { System.out.println("a D visited: " + d.name); } } abstract class A { public String name; abstract void accept(Visitor v); } class B extends A { public A child1; public A child2; public B(String name) { this.name = name; } @Override void accept(Visitor v) { v.visitB(this); } } class C extends A { public A child; public C(String name) { this.name = name; } @Override void accept(Visitor v) { v.visitC(this); } } class D extends A { public D(String name) { this.name = name; } @Override void accept(Visitor v) { v.visitD(this); } } class Main { public static void main(String[] args) { B b1 = new B("b1"); B b2 = new B("b2"); C c1 = new C("c1"); C c2 = new C("c2"); D d1 = new D("d1"); D d2 = new D("d2"); D d3 = new D("d3"); D d4 = new D("d4"); /* b1 / \ c1 c2 / \ b2 d2 / \ d3 d4 */ b1.child1 = c1; b1.child2 = c2; c1.child = b2; c2.child = d2; b2.child1 = d3; b2.child2 = d4; PrintVisitor v = new PrintVisitor(); b1.accept(v); } } </code></pre> <p>I would appreciate if you guys commented on my understanding of visitors.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-20T05:06:29.333", "Id": "215812", "Score": "1", "Tags": [ "java", "parsing", "visitor-pattern" ], "Title": "AST Visitor Pattern in Java" }
215812
<blockquote> <p>Implement an autocomplete system. That is, given a query string s and a set of all possible query strings, return all strings in the set that have s as a prefix.</p> <p>For example, given the query string de and the set of strings [dog, deer, deal], return [deer, deal].</p> </blockquote> <pre><code> class DailyCodingProble11 { public static void main(String args[]) { String[] words = { "dog", "deer", "deal" }; Trie trie = new Trie(); for (String word : words) { trie.insert(word); } trie.search("de", trie.root, 0).stream().forEach(word -&gt; System.out.println(word)); trie.search("do", trie.root, 0).stream().forEach(word -&gt; System.out.println(word)); } } class TrieNode { public Character content; public TrieNode[] children = new TrieNode[26]; public boolean isWord; TrieNode(Character ch) { this.content = ch; } } class Trie { TrieNode root; Trie() { root = new TrieNode('*'); } public void insert(String word) { TrieNode currentNode = root; for (int i = 0; i &lt; word.length(); i++) { Character ch = word.charAt(i); if (currentNode.children[ch - 'a'] == null) { currentNode.children[ch - 'a'] = new TrieNode(ch); } currentNode = currentNode.children[ch - 'a']; } currentNode.isWord = true; } public List&lt;String&gt; search(String searchTxt, TrieNode currentNode, int index) { List&lt;String&gt; results = new ArrayList&lt;&gt;(); Character ch = searchTxt.charAt(index); if (currentNode.children[ch - 'a'] == null) { return results; } currentNode = currentNode.children[ch - 'a']; if (index == searchTxt.length() - 1) { findWords(currentNode, new StringBuilder(searchTxt), results); return results; } return search(searchTxt, currentNode, ++index); } public void findWords(TrieNode currentNode, StringBuilder sb, List&lt;String&gt; results) { for (TrieNode child : currentNode.children) { if (child != null) { if (child.isWord == true) { results.add(sb.append(child.content).toString()); } findWords(child, new StringBuilder(sb).append(child.content), results); } } } } </code></pre> <p>How can I improve my solution? Are there any code improvements?</p>
[]
[ { "body": "<h2>Hide implementation details of <code>Trie</code></h2>\n\n<ul>\n<li><code>root</code> should be private</li>\n<li>current <code>search</code> and <code>findWords</code> methods should be private</li>\n<li>write public version of <code>search</code>: should take only a <code>String</code> and call the private one</li>\n<li>make <code>TrieNode</code> a <code>private static</code> inner class of <code>Trie</code></li>\n</ul>\n\n<h2>Change storage of <code>children</code></h2>\n\n<p>Storing 26 pointers, most of which will be <code>null</code> in regular usage, is wasteful. You should use a more compact data structure; perhaps a <code>TreeMap&lt;Character, TrieNode&gt;</code>. You could even extend <code>TreeMap</code> for a cleaner interface.</p>\n\n<h2>Only store characters once</h2>\n\n<p>You effectively store each character in two places: explicitly in <code>TrieNode.content</code>, and implicitly by the node's position in its parent's <code>children</code> array (or in the key of the children map if you take my recommendation above). If you grab the character in the previous round of recursion, you should not need the <code>TrieNode.content</code> field at all.</p>\n\n<h2>Fix bug using <code>StringBuilder</code></h2>\n\n<p>In <code>findWords</code> if a node is a word and has children, the character will be appended twice.</p>\n\n<h2>Minor tweaks</h2>\n\n<ul>\n<li>write a <code>Trie(Iterable&lt;String&gt; content)</code> constructor</li>\n<li>no need to store <code>'*'</code> in root</li>\n<li>use <code>List.forEach()</code> instead of <code>List.stream().forEach()</code></li>\n<li>separate <code>search</code> functionality into <code>findNode</code> and <code>findWords</code></li>\n<li>change <code>if (blah == true)</code> to <code>if (blah)</code></li>\n<li>pass functions instead of using lambdas when possible</li>\n<li>fix indentation -- your IDE should do this for you</li>\n</ul>\n\n<p>Finally, variables names can often be shorter if their purpose is clear in context. For example: <code>currentNode</code> vs <code>current</code>. A lot of people say to \"use descriptive variables names\"; however, brevity can also help with readability as well.</p>\n\n<h2>My stab at the changes</h2>\n\n<pre><code>class Trie {\n private static class TrieNode extends TreeMap&lt;Character, TrieNode&gt; {\n public boolean isWord;\n }\n\n private TrieNode root;\n\n public Trie(Iterable&lt;String&gt; content) {\n this();\n content.forEach(this::insert);\n }\n\n public Trie() {\n root = new TrieNode();\n }\n\n public void insert(String word) {\n TrieNode current = root;\n for (int i = 0; i &lt; word.length(); i++) {\n current = current.computeIfAbsent(word.charAt(i),\n k -&gt; new TrieNode());\n }\n current.isWord = true;\n }\n\n public List&lt;String&gt; search(String word) {\n List&lt;String&gt; results = new ArrayList&lt;&gt;();\n\n TrieNode node = findNode(word, root, 0);\n if (node == null) {\n return results;\n }\n\n findWords(node, new StringBuilder(word), results);\n return results;\n }\n\n private TrieNode findNode(String word, TrieNode current, int index) {\n if (index == word.length()) {\n return current;\n }\n\n Character ch = word.charAt(index);\n if (!current.containsKey(ch)) {\n return null;\n }\n\n return findNode(word, current.get(ch), ++index);\n }\n\n private void findWords(TrieNode current, StringBuilder sb, List&lt;String&gt; results) {\n current.forEach((Character ch, TrieNode child) -&gt; {\n StringBuilder word = new StringBuilder(sb).append(ch);\n if (child.isWord) {\n results.add(word.toString());\n }\n findWords(child, word, results);\n });\n }\n}\n</code></pre>\n\n<pre><code>class TrieTest {\n public static void main(String args[]) {\n Trie trie = new Trie(Arrays.asList(new String[] { \"dog\", \"dee\", \"deer\", \"deal\" }));\n\n trie.search(\"de\").forEach(System.out::println);\n System.out.println();\n\n trie.search(\"do\").forEach(System.out::println);\n System.out.println();\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-20T06:38:47.177", "Id": "215815", "ParentId": "215813", "Score": "6" } }, { "body": "<p>Your code does not consider the case when your query string is among the set. You can add that in the search method:</p>\n<pre><code>public List&lt;String&gt; search(String word) {\n List&lt;String&gt; results = new ArrayList&lt;&gt;();\n\n TrieNode node = findNode(word, root, 0);\n if (node == null) {\n return results;\n }\n if(node.isWord) {\n results.add(s);\n }\n findWords(node, new StringBuilder(word), results);\n return results;\n} \n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-06T13:42:15.613", "Id": "260415", "ParentId": "215813", "Score": "3" } } ]
{ "AcceptedAnswerId": "215815", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-20T05:29:14.263", "Id": "215813", "Score": "4", "Tags": [ "java", "programming-challenge" ], "Title": "Given a query string s and a set of all possible query strings, return all strings in the set that have s as a prefix" }
215813
<p>The problem is regarding probability. The problem is given in detail <a href="https://www.hackerrank.com/challenges/matchstick-experiment/problem" rel="nofollow noreferrer">here</a>.</p> <blockquote> <p>In an <span class="math-container">\$m \times n\$</span> grid, <span class="math-container">\$2mn -m -n\$</span> matchsticks are placed at the boundaries between cells.</p> <p><a href="https://i.stack.imgur.com/Tf2Kr.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Tf2Kr.png" alt="enter image description here"></a></p> <p>We can play a chance experiment where each matchstick can be removed with a certain probability <span class="math-container">\$p\$</span>. We can define the ratio between number of cells with area less than or equal to 3 and the total number of cells pre-experiment (<span class="math-container">\$m \times n\$</span>) as <em>score</em>. We need to find the expectation of this score for a given grid specified by <span class="math-container">\$m\$</span>, <span class="math-container">\$n\$</span> and a given probability <span class="math-container">\$p\$</span>.</p> <p><a href="https://i.stack.imgur.com/3wQVd.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/3wQVd.png" alt="enter image description here"></a></p> <p>The score of the instance in fig.2 is: <span class="math-container">$$ \text{score} = \frac{16}{9 \times &gt; 5} = 0.3555 $$</span></p> <p>It is sufficient if we calculate the expected value of the score within an absolute error of 1e-9.</p> </blockquote> <p>The code I have produced till now is:</p> <pre><code>import math class Cell: def __init__(self, Row, Coloumn): self.Row = Row self.Coloumn = Coloumn self.Name = 'CellR'+str(Row)+'C'+str(Coloumn) self.UNeighbor = None self.DNeighbor = None self.LNeighbor = None self.RNeighbor = None self.UConnection = False self.DConnection = False self.LConnection = False self.RConnection = False class Grid: def __init__(self, m, n): self.Rows = m self.Coloumns = n self.Cells = [[Cell(i,j) for j in range(n)] for i in range(m)] for i in range(m): for j in range(n): if(i != 0): self.Cells[i][j].UNeighbor = self.Cells[i - 1][j] if(i != m-1): self.Cells[i][j].DNeighbor = self.Cells[i + 1][j] if(j != 0): self.Cells[i][j].LNeighbor = self.Cells[i][j - 1] if(j != n-1): self.Cells[i][j].RNeighbor = self.Cells[i][j + 1] def Remove(self, BoundaryStatuses): m = self.Rows n = self.Coloumns for i in range(m): for j in range(2*n-1): ThisCell = self.Cells[i][math.floor(j/2)] if(i != m-1): if(j %2 == 0): if(BoundaryStatuses[i][j] == 1): ThisCell.DConnection = True ThisCell.DNeighbor.UConnection = True else: if(BoundaryStatuses[i][j] == 1): ThisCell.RConnection = True ThisCell.RNeighbor.LConnection = True else: if(j%2 != 0): if(BoundaryStatuses[i][j] == 1): ThisCell.RConnection = True ThisCell.RNeighbor.LConnection = True def Connections(Grid, x, y, Partial): ThisCell = Grid.Cells[x][y] Partial.add(ThisCell.Name) if(ThisCell.LConnection &amp; (ThisCell.LNeighbor != None)): if(ThisCell.LNeighbor.Name not in Partial): Partial.union(Connections(Grid, x, y-1, Partial)) if(ThisCell.RConnection &amp; (ThisCell.RNeighbor != None)): if(ThisCell.RNeighbor.Name not in Partial): Partial.union(Connections(Grid, x, y+1, Partial)) if(ThisCell.UConnection &amp; (ThisCell.UNeighbor != None)): if(ThisCell.UNeighbor.Name not in Partial): Partial.union(Connections(Grid, x-1, y, Partial)) if(ThisCell.DConnection &amp; (ThisCell.DNeighbor != None)): if(ThisCell.DNeighbor.Name not in Partial): Partial.union(Connections(Grid, x+1, y, Partial)) return Partial def ConnectedRegions(Grid): ListOfRegions = [] for i in range(Grid.Rows): for j in range(Grid.Coloumns): ThisCell = Grid.Cells[i][j] Accounted = False for Region in ListOfRegions: if(ThisCell.Name in Region): Accounted = True if(not(Accounted)): NewRegion = Connections(Grid, i, j, set()) ListOfRegions.append(NewRegion) return ListOfRegions def CalcScore(ListOfRegions, m, n): score = 0 for Region in ListOfRegions: if(len(Region) &lt;= 3): score = score + 1 return score/(m*n) def CalcExp(m, n, p): NoS = 2*m*n -m -n NoP = 2**(NoS) ListOfScores = [] ProbsOfScores = [] for i in range(NoP): BoundaryStatuses = [[0 for iy in range(2*n-1)] for ix in range(m)] quo = i NoSR = 0 for ix in range(m): for iy in range(2*n-1): if(ix != m-1): BoundaryStatuses[ix][iy] = (quo%2) if(quo %2 == 1): NoSR = NoSR + 1 quo = int(quo/2) else: if(iy %2 != 0): BoundaryStatuses[ix][iy] = (quo%2) if(quo %2 == 1): NoSR = NoSR + 1 quo = int(quo/2) MatchGrid = Grid(m, n) MatchGrid.Remove(BoundaryStatuses) ListOfRegions = ConnectedRegions(MatchGrid) score = CalcScore(ListOfRegions, m, n) ProbOfInstance = (p**(NoSR))*((1-p)**(NoS - NoSR)) if(score not in ListOfScores): ListOfScores.append(score) ProbsOfScores.append(ProbOfInstance) else: idx = ListOfScores.index(score) ProbsOfScores[idx] = ProbsOfScores[idx] + ProbOfInstance print(ListOfScores) print(ProbsOfScores) Exp = 0 for idx,score in enumerate(ListOfScores): Exp = Exp + ProbsOfScores[idx]*score return Exp q = 1 for q_itr in range(q): m = 4 n = 3 p = 0.9 Exp = CalcExp(m, n, p) print(Exp) </code></pre> <p>My reasoning behind it is:</p> <ol> <li><p>For an <span class="math-container">\$m\$</span> by <span class="math-container">\$n\$</span> grid, there are <span class="math-container">\$n_{ms} = 2mn -m -n\$</span> matchsticks (provided in the problem &amp; represented in the code as <code>NoS</code>). For each stick, there are two possibilities - it can either be removed or can be retained (with a probability of <span class="math-container">\$p\$</span> or <span class="math-container">\$1-p\$</span>). Therefore, there are <span class="math-container">\$2^{n_{ms}}\$</span> possible states of the Grid post experiment.</p></li> <li><p>The expectation of the score is (from definition): <span class="math-container">$$E[score] = \sum x.Pr(score = x)$$</span> As I am unable to come up with an estimate of the probability of landing on a particular score. I have decided to go the other way around by searching through all the possibilities as: <span class="math-container">$$E[score] = \sum_{i=0}^{2^{n_{ms}}-1} score_i \times Pr(case_i)$$</span> Here every case is one of the possibilities listed in Step 1.</p></li> <li><p>To do this, I can generate numbers from <span class="math-container">\$0\$</span> till <span class="math-container">\$2^{n_{ms}}\$</span> in binary. If each digit in the binary number represents the presence/absence of a particular matchstick, then if I remove/retain matchsticks according to the binary string (<code>Remove</code> method of the <code>Grid</code> class) I will have simulated the entire space of possibilities. For every case I can compute the score (<span class="math-container">\$score_i\$</span>) with <code>ConnectedRegions</code> and <code>CalcScore</code> functions if I have the corresponding Grid.</p></li> <li><p>For a particular case in step 3 (say, case <span class="math-container">\$i\$</span>, <span class="math-container">\$i \in Z\$</span> &amp; <span class="math-container">\$i \in [0, 2^{n_{ms}})\$</span>), there will be <span class="math-container">\$n_r\$</span> sticks that are removed (represented in code as <code>NoSR</code>) and <span class="math-container">\$n_{ms}-n_r\$</span> sticks that are retained (basically the number of 1s and 0s in the binary representation of <span class="math-container">\$i\$</span>). The probability of this particular case to occur is <span class="math-container">\$p^{n_r}(1-p)^{n_{ms} - n_r}\$</span> (which is nothing but <span class="math-container">\$Pr(case_i)\$</span>). Now finally to compute the expected score, we just need to list the different scores and their corresponding probabilities to plug into the expression in Step 2. </p></li> </ol> <p>It works as expected. However, in the question we are required to find this value correct to 9 decimal places. My code doesn't exploit this. Also, it is incredibly slow.</p> <p>Can you help me with math ideas or alternate algorithms that can help me leverage the accuracy requirement into speed? Is my code style consistent enough? Or does it cause much confusion?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-20T13:31:19.163", "Id": "417658", "Score": "1", "body": "Hi, I just want to point out I think this is a great first question, welcome to Code Review :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-20T14:08:32.110", "Id": "417665", "Score": "0", "body": "Thank you very much. Question credit goes to Hackerrank :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-20T14:09:36.110", "Id": "417666", "Score": "1", "body": "The question may come from HackerRank, but you've written your post in a great way, that's what I wanted to congratulate you about. There are explanations, code is there, everything's sharp" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-20T18:19:03.700", "Id": "417691", "Score": "1", "body": "As long as there are no answers to your post I believe it is fine to add things, just try not to add too much as it may break an answer someone might be writting at the moment for example" } ]
[ { "body": "<h1>math</h1>\n<blockquote>\n<ol start=\"2\">\n<li>... unable to come up with an estimate of the probability of landing on a particular score</li>\n</ol>\n</blockquote>\n<p>This is the max-3-cell problem in a two-dimensional setting.\nI wonder if we could make analytic progress against this by considering\nthe max-2-cell problem in a one-dimensional setting.\nThere must be some sort of symmetry we can appeal to.\nConsidering the density on an infinite line\nor an infinite plane\nwould let us ignore the complexities of boundary conditions,\nat least for a little while.</p>\n<h1>code</h1>\n<pre><code> def __init__(self, Row, Coloumn):\n</code></pre>\n<p><a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP-8</a> asks that you not use caps for such variables.\nPrefer <a href=\"https://en.wikipedia.org/wiki/Snake_case\" rel=\"nofollow noreferrer\">snake_case</a> names like <code>u_neighbor</code> or <code>u_connection</code>.\nRun <a href=\"http://flake8.pycqa.org/en/latest/\" rel=\"nofollow noreferrer\"><code>$ flake8</code></a>, and heed its advice, before sharing your code.\nAlso, typo: <code>column</code>.</p>\n<p>You made a modeling choice here, that the <a href=\"https://en.wikipedia.org/wiki/Von_Neumann_neighborhood\" rel=\"nofollow noreferrer\">Von Neumann neighborhood</a>\nshould be represented as union of four distinct unrelated things.\nI don't agree with that perspective.\nI would prefer to see a vector of four similar things,\nwhere you iterate through this list:</p>\n<pre><code>[(0, -1),\n (0, 1),\n (-1, 0),\n (1, 0)]\n</code></pre>\n<p>You wrote:</p>\n<pre><code> self.Name = 'CellR'+str(Row)+'C'+str(Coloumn)\n</code></pre>\n<p>If a <a href=\"https://cito.github.io/blog/f-strings/\" rel=\"nofollow noreferrer\">modern</a> python is available to you, it would be more natural to use an <a href=\"https://www.python.org/dev/peps/pep-0498/#abstract\" rel=\"nofollow noreferrer\">f-string</a>:</p>\n<pre><code> self.name = f'CellR{row}C{column}'\n</code></pre>\n<p>Here is some tediously repetitive code to express the notion of adjacency:</p>\n<pre><code> if(i != 0):\n self.Cells[i][j].UNeighbor = self.Cells[i - 1][j]\n if(i != m-1):\n self.Cells[i][j].DNeighbor = self.Cells[i + 1][j]\n if(j != 0):\n self.Cells[i][j].LNeighbor = self.Cells[i][j - 1]\n if(j != n-1):\n self.Cells[i][j].RNeighbor = self.Cells[i][j + 1]\n</code></pre>\n<p>Recommend using a single assignment that loops through the <code>von_neumann</code> list of delta x's &amp; y's above.</p>\n<p>This is obscure:</p>\n<pre><code> for i in range(m):\n for j in range(2 * n - 1):\n ThisCell = self.Cells[i][math.floor(j / 2)]\n</code></pre>\n<p>It's not clear why there's no symmetry between horizontal and vertical.\nAt a minimum it warrants a comment.</p>\n<pre><code> if (i != m - 1):\n</code></pre>\n<p>This is lovely C bounds checking, and you can certainly keep it.\nBut consider following the pythonic &quot;ask forgiveness, not permission&quot;,\nby using <code>try</code> / <code>catch IndexError</code> to deal with the borders.\nSame remark for <code>CalcExp</code>.</p>\n<p>Also, no need for <code>(</code> extra parens <code>)</code> in a python <code>if</code> statement.</p>\n<p>Couple of issues with this one:</p>\n<pre><code>if (ThisCell.LConnection &amp; (ThisCell.LNeighbor != None)):\n</code></pre>\n<ol>\n<li>No <code>(</code> extra parens <code>)</code>, please.</li>\n<li>Do <em>not</em> use bitwise <code>&amp;</code> and on booleans. Use boolean <code>and</code> instead.</li>\n<li><code>flake8</code> would have told you to use <code>is</code> to test identity of the <code>None</code> singleton, rather than an equality operator.</li>\n</ol>\n<p>So that would leave us with:</p>\n<pre><code>if this_cell.l_connection and this_cell.l_neighbor is not None:\n</code></pre>\n<p>or even more simply:</p>\n<pre><code>if this_cell.l_connection and this_cell.l_neighbor:\n</code></pre>\n<p>Similarly a subsequent line would be <code>if not accounted:</code></p>\n<p>More tedious statements follow, that could be a loop through <code>von_neumann</code>.</p>\n<p>In <code>def connected_regions</code>, this takes too long:</p>\n<pre><code> Accounted = False\n for Region in ListOfRegions:\n if(ThisCell.Name in Region):\n Accounted = True\n</code></pre>\n<p>Please use a generator expression:</p>\n<pre><code> accounted = any(this_cell.name in region\n for region in list_of_regions)\n</code></pre>\n<p>Why? Because <code>any()</code> will bail out early, upon encountering 1st <code>True</code>.</p>\n<p>Kudos for using <code>set()</code>, so the <code>in</code> test will be fast.</p>\n<pre><code> score = score + 1\n</code></pre>\n<p>In python we prefer to phrase that as <code>score += 1</code>.</p>\n<p>The name <code>calc_exp</code> surprisingly turns out to relate to expectations,\nrather than <code>math.exp</code> or exponentials.</p>\n<p>This is a bit cumbersome:</p>\n<pre><code>ListOfScores = []\nProbsOfScores = []\n</code></pre>\n<p>Better to store a single list of (score, prob) tuples.\nIt would simplify some manipulations farther down in the function,\nincluding allowing you to finish with <code>return sum( ... )</code>.</p>\n<h1>visualization</h1>\n<p>Consider writing code that depicts how a given configuration of matchsticks turned out, with\nmarkings of the 1-, 2-, &amp; 3-cell regions.\nThis would facilitate manual checking of your results for a couple of particular configurations.</p>\n<p>In a similar vein, unit tests using very small number of matchsticks wouldn't hurt.</p>\n<h1>high level advice</h1>\n<p>Run <a href=\"http://flake8.pycqa.org/en/latest/\" rel=\"nofollow noreferrer\"><code>flake8</code></a>.\nFollow its instructions.\nThis will make your code more easily understood by people who interact with it.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-31T19:32:02.613", "Id": "216599", "ParentId": "215817", "Score": "3" } } ]
{ "AcceptedAnswerId": "216599", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-20T07:09:24.867", "Id": "215817", "Score": "10", "Tags": [ "python", "python-3.x", "programming-challenge" ], "Title": "Hackerrank Matchstick experiment" }
215817
<p>This is what I am doing and it's working:</p> <pre><code>var isEmpty = true; for(let i = 0; i&lt; members.length; i++) { var member = members[i]; if(member &amp;&amp; member[3]){ isEmpty = false; break; } } if(isEmpty) { var somePrefix = "123 -" for(let i = 0; i&lt; members.length; i++) { var member = members[i]; if(member &amp;&amp; member[2]){ member[3] = somePrefix + i; } } } </code></pre> <p>Can this be improved? I'm simply checking if a specific property is empty for all of the collection of multi dimensional array.</p> <p>Here is what's happening:</p> <ol> <li>Checking X property is empty for all members</li> <li>If it is, then auto populate it <ul> <li>If any of the property is filled in then leave it as is</li> </ul></li> </ol>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-20T13:09:39.260", "Id": "417654", "Score": "0", "body": "Can I just point out that your \"style\" is very hard to read/uncommon." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-20T15:07:10.900", "Id": "417671", "Score": "1", "body": "@VeraPerrone show me how you would improve it, without that your comment isn't of much help" } ]
[ { "body": "<h2>Style</h2>\n\n<p>Some points on your style</p>\n\n<ul>\n<li>Don't forget to close the line with semicolons where appropriate. </li>\n<li>Use <code>const</code> for variables that do not change.</li>\n<li>Use <code>let</code> for variables that are scoped to the block.</li>\n<li>Use <code>for of</code> loops when you do not need the index.</li>\n<li>In JS the opening block delimiter <code>{</code> is on the same line as the associated statement. eg <code>for(...) { // &lt;&lt; { on same line</code></li>\n<li><p>Even if its an example, always write code as functions, not as flat bits of code as in your example. The function name adds additional contextual semantic meaning and forces you to write in a style more akin to real world needs.</p></li>\n<li><p>Use a space between </p>\n\n<ul>\n<li>tokens and <code>(</code>, eg <code>for (</code>, <code>if (foo) {</code>. </li>\n<li>operators and operands, eg <code>1 + 2</code>, <code>i ++</code></li>\n<li>commas and expressions, eg <code>a, b</code> (not that it applies in your example) </li>\n</ul></li>\n</ul>\n\n<h2>Typescript?</h2>\n\n<p>You have the question tagged typescript, yet the code is pure JS. If you wanted a typescript version you have not indicated, and personally apart from better IDE integration the additional complexity of typescript does not offer any benefit over well written JS.</p>\n\n<h2>Rewrites</h2>\n\n<p>With all things equal the best quality source code has the shortest line count.</p>\n\n<h2>Cleaning up of your code</h2>\n\n<p><strong>Note</strong> that because the code is written as a function I have not needed to use an intermediate to hold the abstract \"empty\" state of members, removing 4 lines of code.</p>\n\n<pre><code>function populateIfMembersEmpty(members, prefix = \"123 -\") {\n for (const member of members) { \n if (member &amp;&amp; member[3]) { return } \n }\n for (let i = 0; i&lt; members.length; i++) { \n if (members[i] &amp;&amp; members[i][2]) { members[i][3] = prefix + i } \n }\n}\n</code></pre>\n\n<h2>Alternatives</h2>\n\n<pre><code>function populateIfMembersEmpty(members, prefix = \"123 -\") {\n if (! members.some(member =&gt; member &amp;&amp; member[3])) {\n members.forEach((member, i) =&gt; {\n if (member &amp;&amp; member[2]) { member[3] = prefix + i } \n });\n }\n}\n</code></pre>\n\n<p>or</p>\n\n<p>Does a member of members on the same line need to be named, or is a symbolic representation any less meaningful?</p>\n\n<pre><code>function populateIfMembersEmpty(members, prefix = \"123 -\") {\n if (! members.some(m =&gt; m &amp;&amp; m[3])) {\n members.forEach((m, i) =&gt; m &amp;&amp; m[2] &amp;&amp; (m[3] = prefix + i)); \n }\n}\n</code></pre>\n\n<p>or</p>\n\n<pre><code>function populateIfMembersEmpty(members, prefix = \"123 -\") {\n if (members.some(m =&gt; m &amp;&amp; m[3])) { return }\n members.forEach((m, i) =&gt; m &amp;&amp; m[2] &amp;&amp; (m[3] = prefix + i)); \n}\n</code></pre>\n\n<p>19 lines down to 4 may sound pedantic, but apply the same to a large code base and a monster source file of 10,000 lines can be a far more manageable 2,000 reducing the odds of a bug by 80%</p>\n\n<hr>\n\n<p>As the only response you have so far got that has unnecessarily emphasized a confusing point, I will say your style is neither <em>\"very\"</em> hard (or hard) to read, nor is it uncommon. (Let alone <em>\"very\"</em> uncommon, meaning... unique? no! ).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-21T23:32:01.420", "Id": "215962", "ParentId": "215823", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-20T08:55:21.483", "Id": "215823", "Score": "0", "Tags": [ "javascript", "typescript" ], "Title": "Checking if a multi dimensional array's given property is empty or not for the whole collection" }
215823
<p>I have no problem, but I would like some advice:</p> <p>I've read some help to do some jQuery plugin, and I just did my first one. This plugin helps to generate dynamic datatable:</p> <ul> <li>Autofill the table with some JSON data using the plugin datatable</li> <li>Create a form to add new lines</li> <li>Create some trigger click on the line => display a form to modify</li> <li>Create a trigger for sending form => add or modify a line</li> </ul> <p>All works fine! But because of my first jQuery plugin, I would like some advice to optimize it, and make it as clean as possible. Is there a better way to do it?</p> <p>Here is my plugin:</p> <pre><code>(function($) { var PLUGIN_NS = 'dataTableAuto'; var Plugin = function ( target, options ) { this.$T = $(target); this._init( target, options ); return this; /** #### OPTIONS #### */ this.options= $.extend( true, { DEBUG: false }, options ); } /* Init */ Plugin.prototype._init = function ( target, options ) { this.field = $(target).attr("id").split("_")[1]; /* some default values are generated with the table id, but can be changed if needed */ defaultAutoOptions = { tableName: "table_" + this.field, formClassName: "form_" + this.field, jsonFile: "/json/json_" + this.field + ".json", submitEvtFct: this._submitEvtFct, clickEvtFct: this._clickEvtFct, dispFormAjax: false, /* click on the line will change it by a form or make any ajax call to get form if needed */ formAdd: true, /* add some lines allowed */ titreFormNew: "" } this.options = $.extend(defaultAutoOptions, Plugin.defaults, options); if (this.options.formAdd &amp;&amp; $("#formNew_" + this.field).length == 0) this._createFormAdd(target); this.dataTableAuto = this._dataTableAuto(target); this.options.clickEvtFct(this); this.options.submitEvtFct(this); return this; }; /* Default val */ Plugin.defaults = { events: function(_, callback){ callback([]) } }; /* Auto create the form to add some lines */ Plugin.prototype._createFormAdd = function ( target ) { var _form = "&lt;form id='formNew_" + this.field + "' class='" + this.options.formClassName + " preventDblClick' method='post'&gt;"; _form += "&lt;h2&gt;" + this.options.titreFormNew + "&lt;/h2&gt;"; $(" &gt; thead &gt; tr th", $(this.$T)).each(function(index) { var attr = $(this).attr("id"); if (typeof attr !== typeof undefined &amp;&amp; attr !== false &amp;&amp; attr != "col_actions") _form += "&lt;label&gt;" + $(this).html() + "&lt;br /&gt;&lt;input type='text' name='" + attr.split("_")[1] + "' maxlength='" + $(this).data("maxlength") + "' /&gt;&lt;/label&gt;"; }) _form += "&lt;input type='submit' value='Enregistrer' /&gt;"; _form += "&lt;/form&gt;"; $(this.$T).before(_form); } /* Init the datatable */ Plugin.prototype._dataTableAuto = function ( target, options ) { var _this = this; var infosTable = this._getInfosColumn(target); return tableDT = $(this.$T).DataTable({ "ajax": { 'type': 'GET', 'url': this.options.jsonFile, 'data': function ( d ) { } }, destroy: true, info: false, rowId: "lineID", 'columnDefs': infosTable.listColumnDef, "columns": infosTable.listColumn, 'paging' : false, "searching": false, "initComplete": function( settings, json ) { if (typeof json['eval']!='undefined'){ eval(json['eval']); } }, createdRow: function( row, data, dataIndex ) { _this._setClickableRow(target, row); } }); } /* get column data used for datatable */ Plugin.prototype._getInfosColumn = function ( target) { listColumn = []; listColumnDef = []; attr = $(" &gt; thead &gt; tr th:first-child", $(target[0])).attr("id"); if (typeof attr === typeof undefined || attr === false) { listColumn.push({ "data": "control" }); listColumnDef.push({ className: 'control', targets: 0 }); } $(" &gt; thead &gt; tr th", $(target[0])).each(function(index) { if ($(this).attr("id") != undefined) { listColumnDef.push({ responsivePriority: $(this).attr("id") == "col_buttons" ? 1 : index, targets: index}); if ($(this).hasClass("isDate")) listColumn.push( { "data": $(this).attr("id").split("_")[1], render: function ( data, type, row ) { return (data.split("-").length == 3 ? moment(data).format("DD/MM/YYYY") : data); } } ) else listColumn.push({ "data": $(this).attr("id").split("_")[1] }) } }) return {listColumnDef: listColumnDef, listColumn: listColumn}; } /* On which row add a trigger onclick */ Plugin.prototype._setClickableRow = function (target, row) { $(" &gt; thead &gt; tr th", $(target[0])).each(function(index) { if ($(this).hasClass("clickable")) { $("td:eq(" + index + ")", row).addClass('clickable'); } if ($(this).attr("id") != undefined) $("td:eq(" + index + ")", row).addClass($(this).attr("id").split("_")[1]); }) } /* trigger onclick */ Plugin.prototype._clickEvtFct = function ( target, options) { $(target.$T).on("click", "tr td.clickable, .btDelete", function() { /* Click on a cell =&gt; aff a form to modify */ if ($(this).hasClass("clickable")) { var theRowObject = target.dataTableAuto.row($(this).closest('tr')); /* Get the form with ajax request */ if (target.options.dispFormAjax) { $.getJSON( target.options.jsonFile, { command: "modLigne", lineID: lineID }) .done(function( data ) { data = data.data[0]; target.dataTableAuto.row(theRowObject).data(data).draw(); /* Not update again the line if the form is displayed */ $("tr#" + data.lineID + " td.clickable").addClass("pausedClick").removeClass("clickable"); }); } /* auto create the form */ else { temp = theRowObject.data(); var affForm = true; var tr = $(this).closest("tr"); var lineID = tr.attr("id").split("_")[1]; $.each(temp, function(item, value) { var maxLength = $(" &gt; thead &gt; tr th#col_" + item, $(target.$T)).data("maxlength"); if (item != "lineID" &amp;&amp; item != "control") if (item == "actions") temp[item] = "&lt;button form='mod" + target.field + "_" + lineID + "'&gt;OK&lt;/button&gt;"; else if (affForm) { temp[item] = "&lt;form name='formMod' id='mod" + target.field + "_" + lineID + "' class='form_" + target.field + "'&gt;&lt;input type='text' name='" + item + "' value='" + value + "' maxlength='" + maxLength + "' /&gt;&lt;/form&gt;"; affForm = false; } else temp[item] = "&lt;input type='text' name='" + item + "' value='" + value + "' form='mod" + target.field + "_" + lineID + "' maxlength='" + maxLength + "' /&gt;"; }) target.dataTableAuto.row(theRowObject).data(temp).draw(); $("td.clickable", tr).addClass("pausedClick").removeClass("clickable"); } } /* bouton to delete the line */ else if ($(this).hasClass("btDelete")) { var goAction = true; var tr = $(this).closest("tr"); var lineID = tr.attr("id").split("_")[1]; if(typeof $(this).data("message")!='undefined' &amp;&amp; !confirm($(this).data("message"))) return false; $.getJSON( target.options.jsonFile, {command: 'suppLine', lineID: lineID}) .done(function( datas ) { /* Actions to do when succeed */ if (datas.success) target.dataTableAuto.row('#' + tr.attr("id")).remove().draw(); }); } }) } /* trigger submit form to add or update line */ Plugin.prototype._submitEvtFct = function ( target) { $("body").on("submit", "form." + target.options.formClassName, function(e) { e.preventDefault(); $.getJSON( target.options.jsonFile, $(this).serialize() + "&amp;command=saveData&amp;lineID=" + ($(this).closest("tr").length &gt; 0 ? $(this).closest("tr").attr("id").split("_")[1] : 0)) .done(function( datas ) { data = datas.data[0]; var _tr = $("tr#" + data.lineID); if (_tr.length &gt; 0) { target.dataTableAuto.row($("tr#" + data.lineID).index()).data(data).draw(); /* Autorize the click for display one more time the update form */ $("tr#" + data.lineID + " td.pausedClick").addClass("clickable").removeClass("pausedClick"); } else { target.dataTableAuto.row.add( data ).node().id = data.lineID; target.dataTableAuto.draw(); } if(typeof datas['eval']!='undefined')eval(datas['eval']); }); }) } Plugin.prototype.DWARN = function () { this.DEBUG &amp;&amp; console.warn( arguments ); } $.fn[ PLUGIN_NS ] = function( methodOrOptions ) { if (!$(this).length) { return $(this); } var instance = $(this).data(PLUGIN_NS); if ( instance &amp;&amp; methodOrOptions.indexOf('_') != 0 &amp;&amp; instance[ methodOrOptions ] &amp;&amp; typeof( instance[ methodOrOptions ] ) == 'function' ) { return instance[ methodOrOptions ](this, Array.prototype.slice.call( arguments, 1 ) ); } else if ( typeof methodOrOptions === 'object' || ! methodOrOptions ) { return this.each(function() { instance = new Plugin( $(this), methodOrOptions ); $(this).data( PLUGIN_NS, instance ); }) // CASE: method called before init } else if ( !instance ) { $.error( 'Plugin must be initialised before using method: ' + methodOrOptions ); // CASE: invalid method } else if ( methodOrOptions.indexOf('_') == 0 ) { $.error( 'Method ' + methodOrOptions + ' is private!' ); } else { $.error( 'Method ' + methodOrOptions + ' does not exist.' ); } }; })(jQuery); </code></pre> <p>The HTML code can be:</p> <pre><code> &lt;table id="table_categorie"&gt; &lt;thead&gt; &lt;th&gt;&lt;/th&gt; &lt;th id="col_categorieCode" class="clickable" data-maxlength="10"&gt;Code&lt;/th&gt; &lt;th id="col_categorieLib" class="clickable" data-maxlength="100"&gt;libellé&lt;/th&gt; &lt;th id="col_actions"&gt;&lt;/th&gt; &lt;/thead&gt; &lt;tbody&gt; &lt;/tbody&gt; &lt;/table&gt; </code></pre> <p>I call my plugin by the line:</p> <pre><code>var tableCategorie = $("table#table_categorie").dataTableAuto({titreFormNew: "New category"}); </code></pre> <p>And the JSON will return this data, for example:</p> <pre><code>"data": [ { "control": "", "lineID": "categorie_1", "categorieClientCode": "123", "categorieClientLib": "categorie 1", "codeCompta": "", "actions": "&lt;button class="btSupp" data-message="Are you sure to delete this categorie ?"&gt;&lt;/button&gt;" } , { "control": "", "lineID": "categorie_2", "categorieClientCode": "124", "categorieClientLib": "categorie 2", "codeCompta": "", "actions": "&lt;button class="btSupp" data-toggle="tootltip" data-placement="top" data-message="Are you sure to delete this categorie ?"&gt;&lt;/button&gt;" } ] </code></pre> <p>And when I delete a line, it return after delete the line in the database:</p> <pre><code>{"success":"true","msg":"the line was deleted"} </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-20T09:10:31.320", "Id": "215825", "Score": "1", "Tags": [ "javascript", "jquery" ], "Title": "jQuery plugin linked with dataTable" }
215825
<p>I am writing function <code>numericValues(text: String): List[Int]</code> to extract patterns <code>"""([a-z]+)\s*:\s*(\d+)"""</code> and return the list of the numeric values :</p> <pre><code>numericValues("a123 : 0 abc:123 123:abc xyz:1") // List(123, 1) </code></pre> <p>I would write <code>numericValues</code> like this:</p> <pre><code>def numericValues(text: String): List[Int] = { val regex = """([a-z]+)\s*:\s*(\d+)""".r regex.findAllIn(text).toList.flatMap {s =&gt; PartialFunction.condOpt(s) { case regex(_, num) =&gt; num.toInt } } } </code></pre> <p>I guess the <code>condOpt</code> invocation is redundant and I wonder how to simplify this implementation. Also, I'd appreciate comments on improvements to style and best practice.</p>
[]
[ { "body": "<p>You usually want a zero-width word boundary <code>\\b</code> on either end of the regex, to avoid matching things like <code>1a:1a</code>.</p>\n\n<p>There's no need to capture <code>[a-z]+</code> since you are throwing it away. </p>\n\n<p>You can use lookbehind <code>(?&lt;=…)</code> assertions to require a match to be preceded by whatever, without including the whatever in the match result. This means no need for capturing parenthesis, only the integer is included in the match, and the final map is simply <code>_.toInt</code>. Variable-width lookbehind was introduced in Java 9; older versions have only fixed-width lookbehind.</p>\n\n<p>Finally, removing the variable makes braces unnecessary.</p>\n\n<pre><code>def numericValues(text: String): List[Int] = \"\"\"(?&lt;=\\b[a-z]+\\s*:\\s*)\\d+\\b\"\"\".r.findAllIn(text).toList.map(_.toInt)\n</code></pre>\n\n<p>With only fixed-width lookbehind, you could postprocess the matches to remove non-numerics:</p>\n\n<pre><code>….map(_.replaceAll(\"[^0-9]\", \"\").toInt)\n</code></pre>\n\n<p>Or, more idiomatically and less hacky, just capture the digits and extract the capture groups:</p>\n\n<pre><code>\"\"\"\\b[a-z]+\\s*:\\s*(\\d+)\\b\"\"\".r.findAllIn(text).matchData.toList.map(_.group(1).toInt)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-20T13:00:44.460", "Id": "417653", "Score": "0", "body": "Thanks a lot. What if I have only fixed-width lookbehind ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-20T13:56:01.553", "Id": "417663", "Score": "1", "body": "then you can't use variable-width lookbehind :) See edit." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-20T12:35:09.393", "Id": "215836", "ParentId": "215831", "Score": "7" } } ]
{ "AcceptedAnswerId": "215836", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-20T10:20:56.427", "Id": "215831", "Score": "5", "Tags": [ "regex", "scala" ], "Title": "Extracting numeric values from a string containing key:value pairs" }
215831
<p>(We are on SQL Server 2008).</p> <p>The following constellation:</p> <p>Our applications passes date&amp;time around (in the most horrible way possible).</p> <p>We want to simplify this. Instead of a culture-specific string like '31.12.2019', we're now passing an ecma-timestamp (the number of milliseconds between the point in time <strong>in UTC</strong> and <code>1970-01-01 00:00:00 UTC</code> that is).</p> <p>Now an additional complication:</p> <p>Our pitiful application historically has saved all datetime values in the database as local time <strong>WITH DAYLIGHT-SAVING</strong> (central European summer or winter time, depending on the date) instead of UTC. </p> <p>Now, central European summer time (CEST) is UTC+2, while central European winter time (CET) is UTC+1.</p> <p>For the adjustment between summer and winter time, the following rules are applied:</p> <ul> <li><p>The change from winter time to summer time is on the last Sunday of March</p> <ul> <li>On the last Sunday morning of March, the clocks will be put forward from 02:00 to 03:00. (one 'loses' an hour)</li> </ul></li> <li><p>The change from summer time to winter time is on the last Sunday of October:</p> <ul> <li>On the last Sunday morning of October, the clocks will be put backward from 03:00 to 02:00 (one wins an hour)</li> </ul></li> </ul> <p>As you might realize from looking at the definition, the change from summer to winter time presents a discontinuity range, in which a given local-time value can be both summer or winter time... (but not the change from winter to summer time)</p> <p>Now, I have written the below functions to convert local/UTC-time into an ECMA-timestamp, and you can specify if the input datetime is UTC or localtime. </p> <p>I haven't had the time to test it all too extensively, but I'd like to collect a second opinion on how to handle the times between 02 and 03 o'clock at the last Sunday of October...</p> <ul> <li>Would you handle the conversion the same? (apart from the fact that ideally, the conversion would be avoided / data changed to UTC)</li> <li>Do you spot any errors?</li> <li>Thoughts on what best to do between 02 and 03</li> </ul> <p></p> <pre><code>PRINT 'Begin Executing "01_fn_dtLastSundayInMonth.sql"' GO IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[fn_dtLastSundayInMonth]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT')) BEGIN EXECUTE(N'CREATE FUNCTION [dbo].[fn_dtLastSundayInMonth]() RETURNS int BEGIN RETURN 0 END ') END GO /* -- This is for testing SET DATEFIRST 3; -- Monday WITH CTE AS ( SELECT 1 AS i, CAST('20190101' AS datetime) AS mydate UNION ALL SELECT i+1 AS i, DATEADD(month, 1, CTE.mydate) AS mydate FROM CTE WHERE i &lt; 100 ) SELECT -666 AS i, dbo.fn_dtLastSundayInMonth('17530101') AS lastSundayInMonth, dbo.fn_dtLastSundayInMonth('17530101') AS Control UNION ALL SELECT -666 AS i, dbo.fn_dtLastSundayInMonth('99991231') AS lastSundayInMonth, dbo.fn_dtLastSundayInMonth('99991231') AS Control UNION ALL SELECT mydate ,dbo.fn_dtLastSundayInMonth(mydate) AS lastSundayInMonth ,dbo.fn_dtLastSundayInMonth(mydate) AS lastSundayInMonth ,DATEADD(day,DATEDIFF(day,'19000107', DATEADD(MONTH, DATEDIFF(MONTH, 0, mydate, 30))/7*7,'19000107') AS Control FROM CTE */ -- ===================================================================== -- Author: Stefan Steiger -- Create date: 01.03.2019 -- Last modified: 01.03.2019 -- Description: Return Datum von letztem Sonntag im Monat -- mit gleichem Jahr und Monat wie @in_DateTime -- ===================================================================== ALTER FUNCTION [dbo].[fn_dtLastSundayInMonth](@in_DateTime datetime ) RETURNS DateTime AS BEGIN -- Abrunden des Eingabedatums auf 00:00:00 Uhr DECLARE @dtReturnValue AS DateTime -- 26.12.9999 SO IF @in_DateTime &gt;= CAST('99991201' AS datetime) RETURN CAST('99991226' AS datetime); -- @dtReturnValue is now last day of month SET @dtReturnValue = DATEADD ( DAY ,-1 ,DATEADD ( MONTH ,1 ,CAST(CAST(YEAR(@in_DateTime) AS varchar(4)) + RIGHT('00' + CAST(MONTH(@in_DateTime) AS varchar(2)), 2) + '01' AS datetime) ) ) ; -- SET DATEFIRST 1 -- Monday - Super easy ! -- SET DATEFIRST != 1 - PHUK THIS ! SET @dtReturnValue = DATEADD ( day , - ( ( -- DATEPART(WEEKDAY, @lastDayofMonth) -- with SET DATEFIRST 1 DATEPART(WEEKDAY, @dtReturnValue) + @@DATEFIRST - 2 % 7 + 1 ) %7 ) , @dtReturnValue ); RETURN @dtReturnValue; END GO GO PRINT 'Done Executing "01_fn_dtLastSundayInMonth.sql"' GO PRINT 'Begin Executing "02_fn_dtIsCEST.sql"' GO IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[fn_dtIsCEST]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT')) BEGIN EXECUTE(N'CREATE FUNCTION [dbo].[fn_dtIsCEST]() RETURNS int BEGIN RETURN 0 END ') END GO -- ===================================================================== -- Author: Stefan Steiger -- Create date: 01.03.2019 -- Last modified: 01.03.2019 -- Description: Ist @in_DateTime Mitteleuropäische Sommerzeit ? -- ===================================================================== -- SELECT dbo.fn_dtIsCEST('2019-03-31T01:00:00'), dbo.fn_dtIsCEST('2019-03-31T04:00:00') ALTER FUNCTION [dbo].[fn_dtIsCEST](@in_DateTime datetime ) RETURNS bit AS BEGIN DECLARE @dtReturnValue AS bit -- https://www.linker.ch/eigenlink/sommerzeit_winterzeit.htm -- the change from winter time to summer time is on the last sunday of March -- the clocks will be put forward from 02:00 to 03:00. (one 'loses' an hour) -- the change from summer time to winter time is on the last sunday of October: -- the clocks will be put backward from 03:00 to 02:00 (one wins an hour). DECLARE @beginSummerTime datetime SET @beginSummerTime = dbo.fn_dtLastSundayInMonth(DATEADD(MONTH, 2, DATEADD(YEAR, YEAR(@in_DateTime)-1900, 0)) ) SET @beginSummerTime = DATEADD(HOUR, 2, @beginSummerTime) DECLARE @beginWinterTime datetime SET @beginWinterTime = dbo.fn_dtLastSundayInMonth(DATEADD(MONTH, 9, DATEADD(YEAR, YEAR(@in_DateTime)-1900, 0)) ) SET @beginWinterTime = DATEADD(HOUR, 2, @beginWinterTime) SET @dtReturnValue = 0; IF @in_DateTime &gt;= @beginSummerTime AND @in_DateTime &lt; @beginWinterTime BEGIN SET @dtReturnValue = 1; END RETURN @dtReturnValue; END GO GO PRINT 'Done Executing "02_fn_dtIsCEST.sql"' GO PRINT 'Begin Executing "03_fn_dtToEcmaTimeStamp.sql"' GO IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[fn_dtToEcmaTimeStamp]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT')) BEGIN EXECUTE(N'CREATE FUNCTION [dbo].[fn_dtToEcmaTimeStamp]() RETURNS int BEGIN RETURN 0 END ') END GO -- ===================================================================== -- Author: Stefan Steiger -- Create date: 01.03.2019 -- Last modified: 01.03.2019 -- Description: Ist @in_DateTime Mitteleuropäische Sommerzeit ? -- ===================================================================== -- SELECT dbo.fn_dtToEcmaTimeStamp('2019-03-31T01:00:00', 1), dbo.fn_dtToEcmaTimeStamp('2019-03-31T04:00:00', 1) ALTER FUNCTION [dbo].[fn_dtToEcmaTimeStamp](@in_DateTime datetime, @in_convert_to_utc bit) RETURNS bigint AS BEGIN DECLARE @dtReturnValue AS bigint IF @in_convert_to_utc = 1 BEGIN SET @in_DateTime = CASE WHEN dbo.fn_dtIsCEST(@in_DateTime) = 1 THEN DATEADD(HOUR, -2, @in_DateTime) ELSE DATEADD(HOUR, -1, @in_DateTime) END; END SET @dtReturnValue = CAST ( DATEDIFF ( HOUR ,CAST('19700101' AS datetime) ,@in_DateTime ) AS bigint ) *60*60*1000 + DATEDIFF ( MILLISECOND ,CAST(FLOOR(CAST(@in_DateTime AS float)) AS datetime) ,@in_DateTime ) % (60*60*1000) ; RETURN @dtReturnValue; END GO GO PRINT 'Done Executing "03_fn_dtToEcmaTimeStamp.sql"' GO PRINT 'Begin Executing "04_fn_dtFromEcmaTimeStamp.sql"' GO IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[fn_dtFromEcmaTimeStamp]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT')) BEGIN EXECUTE(N'CREATE FUNCTION [dbo].[fn_dtFromEcmaTimeStamp]() RETURNS int BEGIN RETURN 0 END ') END GO -- ===================================================================== -- Author: Stefan Steiger -- Create date: 01.03.2019 -- Last modified: 01.03.2019 -- Description: Ist @in_DateTime Mitteleuropäische Sommerzeit ? -- ===================================================================== -- SELECT dbo.fn_dtFromEcmaTimeStamp('1551437088122', 1), dbo.fn_dtFromEcmaTimeStamp('1554069600000', 1) ALTER FUNCTION [dbo].[fn_dtFromEcmaTimeStamp](@in_timestamp bigint, @in_convert_to_localtime bit) RETURNS datetime AS BEGIN DECLARE @dtReturnValue AS datetime DECLARE @hours int SET @hours = @in_timestamp /(1000*60*60); DECLARE @milliseconds int SET @milliseconds = @in_timestamp - (@in_timestamp /(1000*60*60))*(1000*60*60); SET @dtReturnValue = DATEADD ( MILLISECOND, @milliseconds, DATEADD(hour, @hours, CAST('19700101' AS datetime)) ) IF @in_convert_to_localtime = 1 BEGIN SET @dtReturnValue = DATEADD(HOUR, 1, @dtReturnValue) SET @dtReturnValue = CASE WHEN dbo.fn_dtIsCEST(@dtReturnValue) = 1 THEN DATEADD(HOUR, 1, @dtReturnValue) ELSE @dtReturnValue END; END RETURN @dtReturnValue; END GO GO PRINT 'Done Executing "04_fn_dtFromEcmaTimeStamp.sql"' GO </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-20T11:55:05.253", "Id": "417634", "Score": "0", "body": "\"and you can specify if the input datetime is UTC or localtime\" Why not store all dates/times in the exact same timezone and let the client handle the conversion to whatever time the viewer wants?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-20T11:55:50.697", "Id": "417635", "Score": "0", "body": "Is this all supposed to be one query or multiple queries that accidentally got stacked together in one codeblock?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-20T12:00:38.360", "Id": "417637", "Score": "1", "body": "@Mast: Because several very large application(s) that handles time that wrong internally just works with local time. You can't just change the data on the database, you first need to change the application as well. By specifying it as parameter, you can use UTC where changed, and localtime where the change still needs to be done." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-20T12:03:31.213", "Id": "417638", "Score": "1", "body": "@Mast: These are 4 functions that were merged into one script. Function 1 to get the last sunday of month x in year y, function 2 to determine if a local datetime is summer or winter-time, function 3 to to convert datetime to ecma-timestamp, function 4 to convert from ecma-timestamp to datetime." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-20T12:52:53.810", "Id": "417652", "Score": "2", "body": "I don't envy you for your problem. A thought I had that may or may not apply: If you have an autoincrement primary key or another way to determine ordering between records aside from the date, you can use that to find out when the DST rollover happened for one given period. That's unfortunately rather nontrivial and depends on a column existing that is monotonous as a function of time..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-20T16:53:42.310", "Id": "417681", "Score": "0", "body": "@Vogel612: Nice idea, but they're non-sequential uids :(" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-21T15:36:44.547", "Id": "417819", "Score": "0", "body": "Handle ambiguous times the same way you'd handle a date without time, or any other timestamp that's less precise than the data type. Choose a value and apply it consistently. Examples: round them all to 03:00:00 Summer time, or 02:59:59 if you think that will be more distinctive. Or adjust to the average of the two possible times (i.e., add 30 minutes). If the nature of the application makes \"too early\" more of a problem than \"too late\" (or vice versa), pin the values to the earlier or later of the two possible times." } ]
[ { "body": "<p>Since I wasn't previously aware of the SQL Server 2008 requirement, I've added a segment about SQL Server 2008 here. I still endorse everything in my original review, and strongly prefer that method.</p>\n\n<p>Overall, I think the premise of the original review is still the best approach:</p>\n\n<ol>\n<li>Convert to <code>datetimeoffset</code> with the appropriate time zone</li>\n<li>Use that everywhere instead of a raw <code>datetime</code></li>\n</ol>\n\n<p>We still have functionality available to us in SQL Server 2008, but not as convenient as <code>AT TIME ZONE</code></p>\n\n<ol>\n<li><a href=\"https://docs.microsoft.com/en-us/sql/t-sql/functions/switchoffset-transact-sql?redirectedfrom=MSDN&amp;view=sql-server-ver15\" rel=\"nofollow noreferrer\"><code>SWITCHOFFSET</code></a></li>\n<li><a href=\"https://docs.microsoft.com/en-us/sql/t-sql/functions/todatetimeoffset-transact-sql?view=sql-server-ver15\" rel=\"nofollow noreferrer\"><code>TODATETIMEOFFSET</code></a></li>\n</ol>\n\n<p>To use this, I would reformulate the problem into a few steps:</p>\n\n<ol>\n<li>Determine the appropriate time zone of the data</li>\n<li>Convert the data to be time-zone aware using <code>TODATETIMEOFFSET</code></li>\n<li>Swap to UTC using <code>SWITCHOFFSET</code></li>\n<li>Get your timestamp</li>\n</ol>\n\n<p>When getting a datetime from the timestamp, it'll largely be the same in reverse.</p>\n\n<p>In terms of where you should change things, I think it would look like this:</p>\n\n<ol>\n<li>Update <code>dbo.fn_dtLastSundayInMonth</code> to return a <code>date</code> instead of a <code>datetime</code> (b/c we don't have any meaningful time information). </li>\n<li>Update <code>dbo.fn_dtIsCEST</code> to return the offset instead of just a bit flag.</li>\n<li>Add a new function, <code>dbo.fn_dtToOffset</code> that takes a date, derives the offset, and converts it using <code>TODATETIMEOFFSET</code></li>\n<li>Update <code>dbo.fn_dtToEcmaTimestamp</code> and inverse to either consume an offset or convert it inside, and use <code>SWITCHOFFSET</code> as needed if UTC is desired.</li>\n</ol>\n\n<p>Otherwise my same general comments apply from the previous review.</p>\n\n<p>I do think that, given the additional complexity vs <code>AT TIME ZONE</code>, you should consider converting your data to include the values as a <code>datetimeoffset</code>. This could either be a computed column (absolutely don't put a UDF in there, as all queries touching the table will tank), or creating a new column entirely, and then gradually transition your applications to use the new column insead of the old one.</p>\n\n<hr>\n\n<p><strong>Note</strong> - the rest of this answer assumes that you can use SQL Server 2016+ features.</p>\n\n<p>You are overcomplicating this problem. There are only two pieces of functionality you need to solve this problem:</p>\n\n<ol>\n<li><a href=\"https://docs.microsoft.com/en-us/sql/t-sql/data-types/datetimeoffset-transact-sql?view=sql-server-ver15\" rel=\"nofollow noreferrer\"><code>datetimeoffset</code></a></li>\n<li><a href=\"https://docs.microsoft.com/en-us/sql/t-sql/queries/at-time-zone-transact-sql?view=sql-server-ver15\" rel=\"nofollow noreferrer\"><code>AT TIME ZONE</code></a></li>\n</ol>\n\n<p>Using <code>datetimeoffset</code> lets you encode the timezone as part of the data. Then you can ignore the complexities of time zone math, and use standard APIs.</p>\n\n<p><code>AT TIME ZONE</code> lets you take an arbitrary <code>datetime</code> or <code>datetimeoffset</code>, and returns a <code>datetimeoffset</code> of the targetted time zone. Two main points here:</p>\n\n<ol>\n<li>If the input does not have time zone information, then it will assume the target time zone. <strong>It will handle DST</strong> if necessary (see <a href=\"https://docs.microsoft.com/en-us/sql/t-sql/queries/at-time-zone-transact-sql?view=sql-server-ver15#remarks\" rel=\"nofollow noreferrer\">the docs</a> for your example specifically)</li>\n<li>If the input does have time zone information, then it will do whatever time zone math necessary to convert.</li>\n</ol>\n\n<p>This turns your operations into:</p>\n\n<pre><code>DECLARE @dtDateTimeInLocal datetimeoffset = @in_DateTime AT TIME ZONE 'CENTRAL EUROPEAN STANDARD TIME';\nDECLARE @dtDateTimeUtc datetimeoffset = @dtDateTimeInLocal AT TIME ZONE 'UTC';\nDECLARE @timestamp bigint = dbo.fn_dtToEcmaTimestamp( @dtDateTimeUtc );\nRETURN @timestamp;\n</code></pre>\n\n<p>If manually converting things to UTC is too much to ask of your users, then <code>dbo.fn_dtToEcmaTimestamp</code> can do the <code>AT TIME ZONE 'UTC'</code> and assume that the caller has a time-zone aware value.</p>\n\n<p>If all of your data is already in CEST, you could also update the tables to be <code>datetimeoffset</code> using a similar method. Then moving forward you can always add data to be timezone aware, and this problem goes away.</p>\n\n<p>A few final notes:</p>\n\n<ol>\n<li>You should consider not using scalar UDFs, as they are the root of all evil. Use inline table-valued functions instead.</li>\n<li>If they are necessary for &lt;&lt;reasons&gt;&gt;, then you should create them <code>WITH SCHEMABINDING</code> for performance reasons</li>\n<li>I strongly prefer <code>CREATE OR ALTER</code> instead of this dynamic stuff you have going on with an <code>ALTER</code> later</li>\n<li>Instead of leaving test cases as comments, investigate a framework like <a href=\"https://tsqlt.org/\" rel=\"nofollow noreferrer\">tSQLt</a> to write unit tests in. This will make it much easier to do things like verify that my proposed solution doesn't change the behavior.</li>\n<li>In <code>dbo.fn_dtLastSundayInMonth</code>, you can just use <a href=\"https://docs.microsoft.com/en-us/sql/t-sql/functions/eomonth-transact-sql?view=sql-server-ver15\" rel=\"nofollow noreferrer\"><code>EOMONTH</code></a> to simplify it a lot</li>\n<li>In <code>dbo.fn_dtLastSundayInMonth</code>, you are <a href=\"https://stackoverflow.com/a/5925176/3076272\">overcomplicating</a> your modular arithmatic.</li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-24T15:09:25.750", "Id": "450952", "Score": "0", "body": "To point 5: True, assuming you wouldn't have to support SQL-Server 2008 anymore (which will become true at the end of the year 2019 for us). Point 3: create or alter is 2016+ only. Unfortunately, AT TIME ZONE is only supported in SQL-Server 2016+, so just saying, overcomplicated - yes - but not if you need to support SQL-Server 2008 R2+, Thanks for the tip with schemabinding though, didn't know that yet." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-24T15:12:28.493", "Id": "450953", "Score": "0", "body": "@Quandary good point, thanks. I didn't see a version called out in the question, so I tend to assume latest and greatest. I might get around to posting more information that is more helpful on your version" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-28T22:07:43.733", "Id": "451408", "Score": "0", "body": "@Quandary I added details for SQL Server 2008. Please give it a look when you get a chance" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-24T14:06:03.497", "Id": "231263", "ParentId": "215834", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-20T10:48:25.173", "Id": "215834", "Score": "2", "Tags": [ "sql", "datetime", "sql-server", "t-sql" ], "Title": "Determining daylight-saving time in Central European Time" }
215834
<p>I have often found myself using a <code>try {semaphore.Wait()} finally {semaphore.Release()}</code> pattern when using a semaphore, so decided I wanted to try and write an extension method to do this instead.</p> <p>This stems from the problem where I wanted to dispose of my class containing the <code>SemaphoreSlim</code> instance, and was unsure how to safely and elegantly deal with the <code>SemaphoreSlim</code> instance as well. I'm still not sure if this is the right approach:</p> <pre><code>public static class SemaphoreSlimExtension { public static async Task RunAsync(this System.Threading.SemaphoreSlim semaphore, Func&lt;Task&gt; action, System.Threading.CancellationToken cancellationToken) { try { cancellationToken.ThrowIfCancellationRequested(); try { await semaphore.WaitAsync(cancellationToken); await action(); } finally { semaphore.Release(); } } catch (OperationCanceledException ex) { if (cancellationToken != ex.CancellationToken || !cancellationToken.IsCancellationRequested) { throw; } } catch (ObjectDisposedException ex) { if (!cancellationToken.IsCancellationRequested) { throw; } } } } </code></pre> <p>Example usage:</p> <pre><code>public class ClassA : IDisposable { private CancellationTokenSource WorkSemaphoreCancellationTokenSource { get; } = new CancellationTokenSource(); private SemaphoreSlim WorkSemaphore { get; } = new SemaphoreSlim(1, 1); public async Task DoWork() { await WorkSemaphore.RunAsync(() =&gt; Task.Delay(5000), WorkSemaphoreCancellationTokenSource.Token); } public void Dispose() { WorkSemaphoreCancellationTokenSource.Cancel(); WorkSemaphore.Dispose(); WorkSemaphoreCancellationTokenSource.Dispose(); } } </code></pre> <p>Does this seem like a good approach? Is there a better way to safely manage the cancellation and disposal of <code>SemaphoreSlim</code> instances?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-20T14:56:41.440", "Id": "417669", "Score": "3", "body": "You should never `await` the `SemaphoreSlim` inside the `try` block. If it throws an exception, you'll end up releasing even though you never acquired a lock. Generally this only matters if the `SemaphoreSlim` has multiple *requests* (I see you've limited it at 1)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-04T15:06:07.853", "Id": "495386", "Score": "1", "body": "@BradM this is a problem even if the semaphore has only one request because the call to Release will throw if it's already full. If you really wanted to leave it inside the try-finally for some reason, you could set a flag immediately after that you check before releasing in the finally block." } ]
[ { "body": "<h3>Review</h3>\n<ul>\n<li>\n<blockquote>\n<p><em>Is there a better way to safely manage the cancellation and disposal of SemaphoreSlim instances?</em></p>\n</blockquote>\n<p>You've made a pattern to safely manage completing / aborting a task that is acquiring or has acquired a lock on a semaphore, not to safely manage the cancellation and disposal of <code>SemaphoreSlim</code> instances.</p>\n</li>\n<li><p>You should only release the semaphore if you are sure you have acquired a lock. So take <code>await semaphore.WaitAsync(cancellationToken);</code> out the <code>try</code> block (as suggested in the comments).</p>\n</li>\n<li><p>You should also provide overloads or equivalent checks that return <code>Task&lt;T&gt;</code> and/or accept a <code>CancellationToken</code> as argument for the task.</p>\n</li>\n<li><p>In your exception handlers you might get <code>false negatives</code>, in that it's possible an <code>OperationCanceledException</code> or <code>ObjectDisposedException</code> was raised while condition <code>cancellationToken.IsCancellationRequested</code> was met, but coming from a different source than the cancellationToken. I don't know whether this is a big issue, since cancellation was requested anyway. But you should definately document in which scenarios exceptions could be propagated to the consumer.</p>\n</li>\n<li><p>Rather than the <code>catch - if - throw</code> blocks, you could use <code>catch when (condition)</code> blocks. For instance, <code>catch (OperationCanceledException ex) when (cancellationToken == ex.CancellationToken)</code>. This is more compact, doesn't require you rethrow yourself and allows you to focus on silently capturing these exceptions on certain conditions. You might want to log something on such errors.</p>\n</li>\n<li><p>I'm not convinced this extension method should take the semaphore as source object. To me, the semaphore is more of a utility used to execute these tasks. Maybe a static <code>Helper</code> class would have been the better choice.</p>\n</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-11T11:26:09.560", "Id": "514399", "Score": "0", "body": "I think that this link can be helpful too: https://gist.github.com/brendankowitz/5949970076952746a083054559377e56" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-09-26T14:46:20.067", "Id": "229705", "ParentId": "215837", "Score": "5" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-20T12:52:46.057", "Id": "215837", "Score": "5", "Tags": [ "c#", ".net", "error-handling", "async-await", "task-parallel-library" ], "Title": "SemaphoreSlim extension method for safely handling cancellation and disposal" }
215837
<p>This emulates behavior of <kbd>tab</kbd> and <kbd>shift</kbd><kbd>tab</kbd> with <kbd>→</kbd> and <kbd>←</kbd>.</p> <p>I.e., switch focus to the next/previous <code>select</code> field with parent class <code>.tab</code> (which are not siblings in the DOM.)</p> <p>It works, but is there any way to make it more elegant? Especially the <code>if</code>/<code>then</code> and the limit to range. I'm fairly new to JavaScript.</p> <pre><code>$(document).on('keydown', '.tab select', function (e) { let tabs = $(".tab select"); //get all tabs let tab = tabs.index($($(document.activeElement))); //focused tab if (e.which == 37) { //left arrow tab -= 1; } else { if (e.which == 39) { //right arrow tab += 1; } }; tab = Math.min(tabs.length, Math.max(tab, 0)); //stay in range tabs.eq(tab).focus() }); </code></pre>
[]
[ { "body": "<p>One thing you could consider is making this a little more generic and thus reusable. Currently you seem to assume, that there is only one <code>.tab</code> element in your document. If you had multiple (independent) <code>.tab</code> elements, each with their own set of <code>select</code> elements and you did't want to allow \"tabbing\" between then, then <code>$(\".tab select\")</code> will select all selects and not only the ones in the \"current\" <code>.tab</code>. So instead of </p>\n\n<pre><code>let tabs = $(\".tab select\");\n</code></pre>\n\n<p>I'd use </p>\n\n<pre><code>let tabs = $(this).closest(\".tab\").find(\"select\");\n</code></pre>\n\n<p>Furthermore instead of hardcoding the selectors, consider making them variable, so that the script could be used with other class names and form elements:</p>\n\n<pre><code>function initArrowKeyTabbing(parentSelector, formElementSelector) {\n $(document).on('keydown', parentSelector + \" \" + formElementSelector, function (e) {\n $(this).closest(parentSelector).find(formElementSelector);\n // ...\n }\n}\n\ninitArrowKeyTabbing(\".tab\", \"select\");\n</code></pre>\n\n<hr>\n\n<p>In the line</p>\n\n<pre><code>let tab = tabs.index($($(document.activeElement)));\n</code></pre>\n\n<p>you are calling <code>jQuery</code> twice. <code>tabs.index($(document.activeElement))</code> would suffice. For the matter of the fact, <code>.index()</code> alternatively takes a DOM element as its parameter, so you even only need <code>tabs.index(document.activeElement)</code>.</p>\n\n<hr>\n\n<p>With an <code>if ... else if ...</code> construct you don't need the brackets around the second if:</p>\n\n<pre><code>if (e.which == 37) {\n tab -= 1;\n} else if (e.which == 39) {\n tab += 1;\n}\n</code></pre>\n\n<p>In this case instead of using <code>if</code>, a <code>switch</code> statement would be more flexible:</p>\n\n<pre><code>switch (e.which) {\n case 37:\n tab--; // Short form of tab -= 1;\n break;\n case 39:\n tab++;\n break;\n}\n</code></pre>\n\n<hr>\n\n<p>The <code>which</code> event property is deprecated. The \"proper\" replacement is the <code>key</code> property, which however requires concessions towards IE and Edge, which use non-standard key names:</p>\n\n<pre><code>switch (e.key) {\n case \"Left\": // IE/Edge specific value\n case \"ArrowLeft\":\n tab--;\n break;\n case \"Right\": // IE/Edge specific value\n case \"ArrowRight\":\n tab++;\n break;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-21T14:11:27.740", "Id": "417810", "Score": "0", "body": "I understood from the `(which are not siblings in the DOM)` that the OP wants tabbing between all `.tab select`’s." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-21T15:35:40.837", "Id": "417818", "Score": "0", "body": "@morbusg Yes, but as i understand it, all `select`s all inside the same `tab`. That `tab` element isn't really necessary, if the script should apply to all `select`s on the page, however if there are multiple `tab` elements, the \"tabbing\" could be \"isolated\" to each `tab`." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-21T14:00:23.463", "Id": "215932", "ParentId": "215840", "Score": "2" } } ]
{ "AcceptedAnswerId": "215932", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-20T13:30:56.700", "Id": "215840", "Score": "1", "Tags": [ "javascript", "jquery" ], "Title": "Switching to next select field by class of parent" }
215840
<p><a href="https://github.com/Peilonrayz/graphtimer" rel="noreferrer">GitHub repo</a> (MIT)<br> Clone the repo and replace the contents of <code>example.py</code> with the one at the bottom and you'll have everything setup.</p> <h1>Explanation of the code</h1> <p>A long while ago I posted the question "<a href="https://codereview.stackexchange.com/q/146434">Abstract graphing-and-timing functions</a>". It was a god class, wasn't extendable/configurable, you also had to use strings to interact with <code>timeit</code>. And it just wasn't clear what was what.</p> <p>A little while ago I posted an answer where I used a couple ikky <code>timeit.timeit</code> calls rather than build a graph. And Graipher showed me a nice looking graph. I've continued to see these nice graphs, with no easy way to make them myself. And so I decided I needed to way-too-early-spring clean my code.</p> <ol> <li><p>(<code>timer.py</code>) A <code>Timer</code> object should be in charge of building and calling <code>timeit</code>.<br> This object was based of <code>timeit.Timer</code>, however I thought it needed some additional functionality:</p> <ol> <li>It should be able to time multiple functions.</li> <li>It should be able to test against multiple values.</li> <li>It should only perform timings.</li> </ol></li> <li><p>(<code>graph.py</code>) A graph class should be introduced that plots the data in the correct way. If you want to plot in something that isn't <code>matplotlib</code> then you just need to change the class.</p></li> <li>(<code>plotter.py</code>) Statistical analysis should not be in either the <code>Timer</code> or the graph class. I also kept the analysis to be pretty basic as per the <a href="https://docs.python.org/3.7/library/timeit.html#timeit.Timer.repeat" rel="noreferrer">Python docs suggestion</a>.</li> <li>(<code>plotter.py</code>) Performing all the above should be simple with good defaults. And so <code>Plotter</code> handles interacting with everything. Whilst it's a small wrapper it means that I, and other, don't have to write that many lines to get the wanted graph.</li> </ol> <h1>What I'd like out of a review.</h1> <ol> <li><p>The thing I find most important right now is, <a href="https://codereview.meta.stackexchange.com/a/1926">is the design good</a>?</p> <p>Is <code>Plotter</code> a poor design pattern? Is splitting the code out like I have done a bad idea?</p></li> <li><p>Is the usage for a user clean and readable?</p></li> <li>Is there a way to make my code more readable? I find <code>MatPlotLib</code> to be a bit on the not so clean side.</li> <li>Any and all critiques are welcome.</li> </ol> <h1>Code</h1> <p>(I have left out some code, and the .pyi files. These are available <a href="https://github.com/Peilonrayz/graphtimer" rel="noreferrer">on GitHub</a>.)</p> <p><code>graph.py</code></p> <pre><code>from .graphtimer import CATEGORY10 class MatPlotLib: def _graph_times(self, graph, data, domain, colors, error, fmt): for results, color in zip(data, colors): values = [v.value for v in results] if error: errors = zip(*[v.errors or [] for v in results]) for error in errors: lower, upper = zip(*error) graph.fill_between(domain, upper, lower, facecolor=color, edgecolor=None, alpha=0.1) yield graph.plot(domain, values, fmt, color=color)[0] def graph(self, graph, data, domain, *, functions=None, colors=CATEGORY10, title=None, legend=True, error=True, x_label='Input', y_label='Time [s]', fmt='-'): lines = list(self._graph_times(graph, data, domain, colors, error, fmt)) if x_label is not None: graph.set_xlabel(x_label) if y_label is not None: graph.set_ylabel(y_label) if title is not None and hasattr(graph, 'set_title'): graph.set_title(title) if legend and functions is not None and hasattr(graph, 'legend'): graph.legend(lines, [fn.__name__ for fn in functions], loc=0) return lines </code></pre> <p><code>timers.py</code></p> <pre><code>import timeit SENTINAL = object() class MultiTimer: """Interface to timeit.Timer to ease timing over multiple functions.""" def __init__(self, functions, timer=timeit.Timer): self.timer = timer self.functions = functions def build_timer(self, fn, domain, stmt='fn(*args)', setup='pass', timer=SENTINAL, globals=SENTINAL, args_conv=SENTINAL): """Build a timeit.Timer""" if not isinstance(domain, tuple): domain = domain, if args_conv is not SENTINAL: domain = args_conv(*domain) if not isinstance(domain, tuple): domain = domain, if globals is SENTINAL: globals = {} else: globals = globals.copy() globals.update({'fn': fn, 'args': domain}) # print(f'{self.timer}({stmt!r}, {setup!r}, {timer!r}, {globals!r})') if timer is SENTINAL: timer = timeit.default_timer return self.timer(stmt, setup, timer, globals=globals) def build_timers(self, domain, *args, **kwargs): """Build multiple timers from various inputs and functions""" return [ [ self.build_timer(fn, dom, *args, **kwargs) for fn in self.functions ] for dom in domain ] def _call(self, domain, repeat, call, *args, **kwargs): """Helper function to generate timing data.""" if len(domain) == 0: raise ValueError('domain must have at least one argument.') functions = self.build_timers(domain, *args, **kwargs) output = [[[] for _ in domain] for _ in functions[0]] for _ in range(repeat): for j, fns in enumerate(functions): for i, fn in enumerate(fns): output[i][j].append(call(fn)) return output def repeat(self, domain, repeat, number, *args, **kwargs): """Interface to timeit.Timer.repeat. `domain` is the values to pass to the functions.""" return self._call(domain, repeat, lambda f: f.timeit(number), *args, **kwargs) def timeit(self, domain, number, *args, **kwargs): """Interface to timeit.Timer.timeit. `domain` is the values to pass to the functions.""" return [ [value[0] for value in values] for values in self.repeat(domain, 1, number, *args, **kwargs) ] def autorange(self, domain, *args, **kwargs): """Interface to timeit.Timer.autorange. `domain` is the values to pass to the functions.""" return [ [value[0] for value in values] for values in self._call(domain, 1, lambda f: f.autorange(), *args, **kwargs) ] class TimerNamespaceMeta(type): """Convenience class to ease creation of a MultiTimer.""" def __new__(mcs, name, bases, attrs): if 'functions' in attrs: raise TypeError('FunctionTimers cannot define `functions`') if 'multi_timer' in attrs: raise TypeError('FunctionTimers cannot define `multi_timer`') ret: TimerNamespace = super().__new__(mcs, name, bases, attrs) functions = [v for k, v in attrs.items() if k.startswith('test')] ret.functions = functions ret.multi_timer = ret.MULTI_TIMER(functions, ret.TIMER) return ret class TimerNamespace(metaclass=TimerNamespaceMeta): """Convenience class to ease creation of a MultiTimer.""" TIMER = timeit.Timer MULTI_TIMER = MultiTimer </code></pre> <p><code>plotter.py</code></p> <pre><code>from .graph import MatPlotLib class Plotter: """Interface to the timer object. Returns objects made to ease usage.""" def __init__(self, timer): self.timer = getattr(timer, 'multi_timer', timer) def timeit(self, number, domain, *args, **kwargs): """Interface to self.timer.timeit. Returns a PlotValues.""" return self.repeat(1, number, domain, *args, **kwargs).min(errors=None) def repeat(self, repeat, number, domain, *args, **kwargs): """Interface to self.timer.repeat. Returns a PlotTimings.""" return PlotTimings( self.timer.repeat(domain, repeat, number, *args, **kwargs), { 'functions': self.timer.functions, 'domain': domain } ) class _DataSet: """Holds timeit values and defines statistical methods around them.""" def __init__(self, values): self.values = sorted(values) def quartile_indexes(self, outlier): """Generates the quartile indexes. Uses tukey's fences to remove outliers.""" delta = (len(self.values) - 1) / 4 quartiles = [int(round(delta * i)) for i in range(5)] if outlier is not None: if outlier &lt; 0: raise ValueError("outlier should be non-negative.") iqr = outlier * (self.values[quartiles[3]] - self.values[quartiles[1]]) low = self.values[quartiles[1]] - iqr high = self.values[quartiles[3]] + iqr for i, v in enumerate(self.values): if v &gt;= low: quartiles[0] = i break for i, v in reversed(list(enumerate(self.values))): if v &lt;= high: quartiles[4] = i break return tuple(quartiles) def errors(self, errors, outlier): """Returns tuples containing the quartiles wanted.""" if errors is None: return None quartiles = self.quartile_indexes(outlier) # Allow out of quartile error bars using -1 and 5. quartiles += (-1, 0) return [ ( self.values[quartiles[start]], self.values[quartiles[stop]] ) for start, stop in errors ] def quartile(self, quartile, outlier): """Return the value of the quartile provided.""" quartiles = self.quartile_indexes(outlier) return self.values[quartiles[quartile]] def mean(self, start, end, outlier): """Return the mean of the values over the quartiles specified.""" quartiles = self.quartile_indexes(outlier) start = quartiles[start] end = quartiles[end] return sum(self.values[start:end + 1]) / (1 + end - start) class PlotTimings: """Thin interface over _DataSet""" def __init__(self, data, kwargs): self.data = [ [_DataSet(results) for results in function_values] for function_values in data ] self.kwargs = kwargs def quartile(self, quartile, *, errors=None, outlier=1.5): """Interface to _DataSet.quartile and errors. Returns a PlotValues.""" return PlotValues( [ [ _DataValues( ds.quartile(quartile, outlier), ds.errors(errors, outlier) ) for ds in function_values ] for function_values in self.data ], self.kwargs ) def min(self, *, errors=((-1, 3),), outlier=1.5): """Return the Q1 value and show the error from Q-1 Q3.""" return self.quartile(0, errors=errors, outlier=outlier) def max(self, *, errors=((1, 5),), outlier=1.5): """Return the Q4 value and show the error from Q1 Q5.""" return self.quartile(4, errors=errors, outlier=outlier) def mean(self, start=0, end=4, *, errors=((1, 3),), outlier=1.5): """Interface to _DataSet.mean and errors. Returns a PlotValues.""" return PlotValues( [ [ _DataValues( ds.mean(start, end, outlier), ds.errors(errors, outlier) ) for ds in function_values ] for function_values in self.data ], self.kwargs ) class _DataValues: """Holds the wanted statistical data from the timings.""" def __init__(self, value, errors): self.value = value self.errors = errors class PlotValues: """Thin interface to Graph.graph.""" def __init__(self, data, kwargs): self.data = data self.kwargs = kwargs def plot(self, graph, graph_lib=MatPlotLib, **kwargs): g = graph_lib() return g.graph( graph, self.data, self.kwargs.pop('domain'), functions=self.kwargs.pop('functions'), **kwargs ) </code></pre> <h1>Example usage</h1> <p>I've included the same graph as I did on my old code. And two of Graipher's graphs.</p> <ol> <li><p><a href="https://codereview.stackexchange.com/q/146434">Abstract graphing-and-timing functions</a> - This is to ensure usage is simple in abnormal usage.<br> It also shows that you can plot multiple error areas, highlighted in the unoptimised graph.</p></li> <li><p><a href="https://codereview.stackexchange.com/q/165245">Plot timings for a range of inputs</a> - This is to make sure standard usage is simple.</p></li> <li><p><a href="https://codereview.stackexchange.com/a/215181">String reversal in Python</a> - This is so I know logerithmic graphs display correctly.</p> <p>I'm running on Windows and don't have a C compiler, and so I can't include the additional two functions. However I think it nicely shows why the Python docs say to use <code>min</code>.</p></li> </ol> <pre><code>import time import math import matplotlib.pyplot as plt import numpy as np from graphtimer import flat, Plotter, TimerNamespace class UnoptimisedRange(object): def __init__(self, size): self.size = size def __getitem__(self, i): if i &gt;= self.size: raise IndexError() return i class Peilonrayz(TimerNamespace): def test_comprehension(iterable): return [i for i in iterable] def test_append(iterable): a = [] append = a.append for i in iterable: append(i) return a SCALE = 10. class Graipher(TimerNamespace): def test_o_n(n): time.sleep(n / SCALE) def test_o_n2(n): time.sleep(n ** 2 / SCALE) def test_o_log(n): time.sleep(math.log(n + 1) / SCALE) def test_o_exp(n): time.sleep((math.exp(n) - 1) / SCALE) def test_o_nlog(n): time.sleep(n * math.log(n + 1) / SCALE) class Reverse(TimerNamespace): def test_orig(stri): output = '' length = len(stri) while length &gt; 0: output += stri[-1] stri, length = (stri[0:length - 1], length - 1) return output def test_g(s): return s[::-1] def test_s(s): return ''.join(reversed(s)) def main(): # Reverse fig, axs = plt.subplots() axs.set_yscale('log') axs.set_xscale('log') ( Plotter(Reverse) .repeat(10, 10, np.logspace(0, 5), args_conv=lambda i: ' '*int(i)) .min() .plot(axs, title='Reverse', fmt='-o') ) fig.show() # Graipher fig, axs = plt.subplots() ( Plotter(Graipher) .repeat(2, 1, [i / 10 for i in range(10)]) .min() .plot(axs, title='Graipher', fmt='-o') ) fig.show() # Peilonrayz fig, axs = plt.subplots(nrows=2, ncols=2, sharex=True, sharey=True) p = Plotter(Peilonrayz) axis = [ ('Range', {'args_conv': range}), ('List', {'args_conv': lambda i: list(range(i))}), ('Unoptimised', {'args_conv': UnoptimisedRange}), ] for graph, (title, kwargs) in zip(iter(flat(axs)), axis): ( p.repeat(100, 5, list(range(0, 10001, 1000)), **kwargs) .min(errors=((-1, 3), (-1, 4))) .plot(graph, title=title) ) fig.show() if __name__ == '__main__': main() </code></pre> <p><a href="https://i.stack.imgur.com/Nx6Ia.png" rel="noreferrer"><img src="https://i.stack.imgur.com/Nx6Ia.png" alt="My graphs"></a> <a href="https://i.stack.imgur.com/Csvbr.png" rel="noreferrer"><img src="https://i.stack.imgur.com/Csvbr.png" alt="Graipher&#39;s graphs"></a> <a href="https://i.stack.imgur.com/RHIhE.png" rel="noreferrer"><img src="https://i.stack.imgur.com/RHIhE.png" alt="Reverse graphs"></a></p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-20T14:47:58.707", "Id": "215846", "Score": "5", "Tags": [ "python", "python-3.x", "graph", "matplotlib" ], "Title": "graphtimer v2 - Utility to plot timings" }
215846
<p>I have a stream of ZMQ messages, I need to filter the right ones and save them in MongoDB. The trick is to have an option to set the filter conditions <strong>dynamically</strong>. </p> <p>I have come up with this solution using <code>multiprocessing</code> and <code>Flask</code>. Basicaly I use Flask HTTP API to change the global <code>filter_parameters</code> dictionary given by <code>Manager</code> and shared with another Process that is running the zmq filter itself. So my question is - <strong>is it a good solution and what is the best practice in this regard</strong>? </p> <pre><code>from multiprocessing import Process, Manager from flask import Flask, jsonify, request from pymongo import MongoClient app = Flask(__name__) manager = Manager() filter_parameters = manager.dict() filter_parameters['addresses'] = [''] def scan(q, filter_parameters): import zmq context = zmq.Context() socket = context.socket(zmq.SUB) socket.connect("tcp://localhost:5556") socket.setsockopt_unicode(zmq.SUBSCRIBE, 'tx') client = MongoClient() # localhost db = client.transactions_db tx_collection = db.tx_collection while True: recv_str = socket.recv_string() recv_str = recv_str.split() filter(recv_str, filter_parameters, tx_collection) def filter(recv_str, filter_parameters, tx_collection): if recv_str[0] == 'tx': if recv_str[7] == '0': if recv_str[2] in filter_parameters['addresses']: tx_collection.insert_one({'tx':recv_str}).inserted_id p = Process(target=scan, args=(filter_parameters)) p.daemon = True p.start() @app.route('/zmq_buffer/set_filter_addresses', methods=["POST"]) def set_filter_addresses(): data_jsn = request.json filter_parameters['addresses'] = data_jsn['addresses'] return jsonify({'addresses':filter_parameters['addresses']}), 200 @app.route('/zmq_buffer/get_filter_addresses', methods=["GET"]) def get_filter_addresses(): if filter_parameters['addresses']: resp = jsonify(filter_parameters['addresses']) else: resp = 'None' return resp, 200 if __name__ == '__main__': app.run(port=7050) p.terminate() </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-20T15:06:56.887", "Id": "417670", "Score": "0", "body": "Why are you using `multiprocessing`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-20T15:29:07.257", "Id": "417672", "Score": "0", "body": "@Peilonrayz Because how else you would separate HTTP requests and ZMQ stream handling?" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-20T14:54:42.347", "Id": "215847", "Score": "0", "Tags": [ "python", "flask", "etl" ], "Title": "Dynamically configurable ZMQ filter with Flask API" }
215847
<p>The task:</p> <blockquote> <p>Given a pivot x, and a list lst, partition the list into three parts.</p> <p>The first part contains all elements in lst that are less than x The second part contains all elements in lst that are equal to x The third part contains all elements in lst that are larger than x Ordering within a part can be arbitrary.</p> <p>For example, given x = 10 and lst = [9, 12, 3, 5, 14, 10, 10], one partition may be `[9, 3, 5, 10, 10, 12, 14].</p> </blockquote> <p>My solution:</p> <pre><code>const createPartitionOf = (lst, pivot) =&gt; { const lessLst = lst.filter(x =&gt; x &lt; pivot); const equalLst = lst.filter(x =&gt; x === pivot); const largerLst = lst.filter(x =&gt; x &gt; pivot); return [...lessLst, ...equalLst, ...largerLst]; }; console.log(createPartitionOf([9, 12, 3, 5, 14, 10, 10], 10)); </code></pre> <p>My solution2:</p> <pre><code>const createPartitionOf2 = (lst, pivot) =&gt; { const lessLst = []; const equalLst = []; const largerLst = []; for (let i = 0; i &lt; lst.length; i++) { if (lst[i] &lt; pivot) { lessLst.push(lst[i]); } else if (lst[i] &gt; pivot) { largerLst.push(lst[i]); } else { equalLst.push(lst[i]); } } return [...lessLst, ...equalLst, ...largerLst]; }; console.log(createPartitionOf2([9, 12, 3, 5, 14, 10, 10], 10)); </code></pre>
[]
[ { "body": "<p>In your first solution you are traversing the list 3 times, whereas in the second solution only once. Given the functional-tag, I’d say you’re after the <code>reduce</code> function:</p>\n\n<pre><code>const flatten = (acc, x) =&gt; acc.concat(x)\n\nconst pivotPartition = (pivot, ary) =&gt; {\n const toOrdered = (triplet, n) =&gt; {\n let [less, equal, greater] = triplet\n\n switch(true) {\n case n &lt; pivot: less.push(n); break\n case n &gt; pivot: greater.push(n); break\n default: equal.push(n)\n }\n\n return triplet\n }\n\n return ary.reduce(toOrdered, [[], [], []]).reduce(flatten)\n}\n</code></pre>\n\n<p>If you want to sort the subarrays as well, then the whole thing is just a <code>ary.sort((a, b) =&gt; a - b)</code>, although as it is mutating the list, it isn’t a functional solution.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-21T02:05:48.593", "Id": "215895", "ParentId": "215848", "Score": "5" } }, { "body": "<p>These problems are always looking to test. It seamed way to straight forward until I realized the clue.</p>\n<p>To be fair in JS a there is no such thing as a list which helps understand the problem.</p>\n<h2>This is a storage problem</h2>\n<p>The Question I think is implying that the array be partitioned in place <em>&quot;partition <strong>the</strong> list&quot;</em>. The aim is to keep storage complexity down. With a side benefit of reduced complexity?</p>\n<p>The clue that gives the solution away is the part <em>&quot;Ordering within a part can be arbitrary&quot;</em></p>\n<h2>Strategy</h2>\n<p>If we think of the problem as separating high and low values (above and below the pivot) you can step the array and swap high values with the current value using an index that moves down.</p>\n<p>To deal with the middle values (which you do not know the position of until you know how many there are) you use a consuming index. That is an index made of two parts, the first part is the current index that will hold the current value, the second part is an offset (ahead on the index) that is the location that we get the current value from.</p>\n<p>When the consuming index meets the top index we fill the remaining items with the pivot value.</p>\n<h2>Solution <span class=\"math-container\">\\$O(1)\\$</span> storage</h2>\n<p>Well that is the gist of it. The solution turned out a little more complicated (it was a hard one) But it maintains a storage complexity of <span class=\"math-container\">\\$O(1)\\$</span> and a complexity of <span class=\"math-container\">\\$O(n)\\$</span> (was hoped it could be log(n) but edge cases made it impossible for my mind)</p>\n<p>This is not the best possible solution, I am sure there are some shortcuts and unnecessary code in this.</p>\n<pre><code>function partition(arr, pivot) {\n var i, temp, top = arr.length - 1, mid = 0, step = true;\n for (i = 0; i &lt;= top - mid; i++) {\n if (mid &amp;&amp; step) { arr[i] = arr[i + mid] } \n step = true;\n if (arr[i] &gt; pivot) { \n if (arr[top] === pivot) { \n arr[top--] = arr[i];\n arr[i] = arr[i + (++mid)];\n } else { \n temp = arr[i]; \n arr[i] = arr[top];\n arr[top--] = temp;\n step = false;\n }\n i--;\n } else if(arr[i] === pivot) { \n mid++;\n i--;\n }\n }\n while (mid--) { arr[i++] = pivot }\n return arr;\n}\n\n \n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-21T05:38:00.513", "Id": "417743", "Score": "0", "body": "How long did it take you to solve it (from reading the first word to typing the last code)?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-21T05:50:35.893", "Id": "417746", "Score": "0", "body": "@thadeuszlay Not long for the basics 10-15 min, worked for your example, but tested some other arguments and it did not work, All up about an hour. I needed to add visualization so I could see the bugs in action. Had to add `step`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-21T06:18:26.623", "Id": "417753", "Score": "0", "body": "What do you mean by you had to „add visualization“? You mean had to add the step variable or are you speaking of a visualization tool?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-21T06:29:56.933", "Id": "417754", "Score": "0", "body": "@thadeuszlay I have my own custom editor (ace,js at the core) that lets me debug and edit while extracting info to a canvas but needs extra code to direct what is being visualized.. `step` was the fix that it helped me find." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-21T03:52:52.060", "Id": "215898", "ParentId": "215848", "Score": "5" } }, { "body": "<p>Consider 2 Pointers low and high are keep moving towards center direction ultimately x == value will be centered</p>\n<pre><code> int x = 10;\n Integer[] intList = new Integer[] {9, 12, 3, 5, 14, 17, 10, 10};\n int pointlow=0, pointhigh = intList.length-1;\n Integer arr[] = new Integer[intList.length];\n \n for(int i=0; i&lt;= intList.length-1; i++) {\n if(intList[i] &lt; x) {\n arr[pointlow] = intList[i];\n pointlow++;\n }\n else {\n arr[pointhigh] = intList[i];\n pointhigh--;\n }\n } \n System.out.println(Arrays.asList(arr));\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-08T20:45:58.610", "Id": "514211", "Score": "2", "body": "Welcome to Code Review Akshay Zade. Please can you add more to your description as I'm currently struggling to understand your answer. Thank you." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-08T19:54:32.007", "Id": "260508", "ParentId": "215848", "Score": "-1" } } ]
{ "AcceptedAnswerId": "215898", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-20T15:22:41.937", "Id": "215848", "Score": "3", "Tags": [ "javascript", "algorithm", "programming-challenge", "functional-programming" ], "Title": "Given a pivot x, and a list lst, partition the list into three parts" }
215848
<p>This working script reads a list of URLs from one or more text files, <br/> and for each, retrieves the page title from the Internet <br/> and appends the results in the format<br/></p> <pre><code>&lt;url/&gt;\t&lt;title/&gt;\n </code></pre> <p>to the output file (for each input file it creates a corresponding output file).</p> <p>I am a Python newbie and would appreciate any feedback.</p> <h2>How to run</h2> <ol> <li>Save the below script as "retrieveWebTitles.py" (or whatever name you like)</li> <li>In the same folder create a folder called "url". </li> <li>In the folder create 3 text files named "links1.txt", "links2.txt", "links3.txt" with the corresponding contents listed below.</li> <li>Make sure you're connected to the Internet or the script won't work.</li> <li>Load the script into Idle and press F5. It should run a couple minutes and print "Done" when finished.</li> <li>Look in the "url" folder for files "links1.out.txt", "links2.out.txt", "links3.out.txt" which should have been created. These will contain the page titles alongside the URLs.</li> </ol> <h2>Contents of "retrieveWebTitles.py"</h2> <pre><code># **************************************************************************************************************************************************************** # Batch Retrieve Web Titles From URLs # # DESCRIPTION: this is a batch version of # Extract the title from a web page using # the standard lib. # ^^^ # I would prefer to just use standard Python # while I am learning, so we do not use # any special libraries like beautiful soup. # **************************************************************************************************************************************************************** # BACKGROUND: I keep my bookmarks in a spreadsheet # which stores the URL, date visited, title, and # a bunch of other columns such as tags, notes, etc. # Somehow it got corrupted and the titles are wrong # for all 120,000+ URLs. I found a couple of free online # tools to batch retrieve Web titles but they choke on # this huge list, so I wrote this script to do the job. # You can just leave it running on a spare computer overnight # or for a couple of days. It takes a list of URLs # (actually several lists, each one corresponding to # a different spreadsheet tab) and goes online and # retrieves the titles. # **************************************************************************************************************************************************************** # Input : One or more text files named like "myfile.txt", # each containing a list of URLs, # with one URL per line. # File names are hardcoded in "main" function with "arrList.append". # Files are expected to be in folder "url" in the same folder as this script. # **************************************************************************************************************************************************************** # Output: One or more text files, named like "myfile.out.txt", # with one URL and Web page title per line delimited by tab, # in the format "&lt;url/&gt;\t&lt;title/&gt;\n" # **************************************************************************************************************************************************************** # Current issues + questions: # 1. Speed: need to make it run faster # # 2. Exceptions not sure if I am handling exceptions right, # sometimes the code in except blows up # so I put that inside a try/except # # 3. File encoding: script was blowing up with some error that # upon googling seemed to be because it was reading text # file where it expected ascii but was utf8. # I want script to work with both so I wrote a hack function # "getFileEncoding" that checks. There is probably a better # way to handle this and probably other types of encoding. # # 4. GUI: Eventually it would be cool to have this run in a GUI Window # with a file dialog to select input folder/files, # and display a progress bar while running. # I have not done any GUI in Python, any suggestions? # Maybe Kivy or PyQT or Windows Forms in IronPython # http://www.voidspace.org.uk/ironpython/winforms/index.shtml # (since I am in Windows)? # # 5. Unknown: I don't really know Python so any advice on # what could be done better? # I am looking to keep the code easy to understand # and maintain, rather than advanced or complicated, # mainly I want to fix anything that is # breaking any basic rules or doing something totally wrong, # # **************************************************************************************************************************************************************** # ---------------------------------------------------------------------------------------------------------------------------------------------------------------- # The code that gets the Web page titles is based on code from: # # Extract the title from a webpage using the python 3 standard lib - Code Review Stack Exchange # https://codereview.stackexchange.com/questions/183160/extract-the-title-from-a-webpage-using-the-python-3-standard-lib # Here is a fault tolerant HTMLParser implementation. # You can throw pretty much anything at get_title() without it breaking, # If anything unexpected happens get_title() will return None. # When Parser() downloads the page it encodes it to ASCII # regardless of the charset used in the page ignoring any errors. # It would be trivial to change to_ascii() to convert the data into UTF-8 # or any other encoding. # Just add an encoding argument and rename the function to something like to_encoding(). # By default HTMLParser() will break on broken html, # it will even break on trivial things like mismatched tags. # To prevent this behavior I replaced HTMLParser()'s error method # with a function that will ignore the errors. #!/usr/bin/python3 #-*-coding:utf8;-*- #qpy:3 #qpy:console # ^^^ NO IDEA WHAT THESE 3 LINES ARE?? import os import re import urllib from urllib.request import urlopen # is this needed if we already imported all of urllib? from html.parser import HTMLParser from pathlib import Path from urllib.request import Request # is this needed if we already imported all of urllib? from urllib.error import URLError, HTTPError # ---------------------------------------------------------------------------------------------------------------------------------------------------------------- # Time out process code from: # Python 101: How to timeout a subprocess | The Mouse Vs. The Python # https://www.blog.pythonlibrary.org/2016/05/17/python-101-how-to-timeout-a-subprocess/ import subprocess # ---------------------------------------------------------------------------------------------------------------------------------------------------------------- # Continuation of code from # Extract the title from a webpage using the python 3 standard lib - Code Review Stack Exchange # https://codereview.stackexchange.com/questions/183160/extract-the-title-from-a-webpage-using-the-python-3-standard-lib def error_callback(*_, **__): pass def is_string(data): return isinstance(data, str) def is_bytes(data): return isinstance(data, bytes) def to_ascii(data): if is_string(data): try: data = data.encode('ascii', errors='ignore') except: try: data = str(data).encode('ascii', errors='ignore') except: try: data = str(data) except: data = "(could not encode data string)" elif is_bytes(data): try: data = data.decode('ascii', errors='ignore') except: try: data = str(data).encode('ascii', errors='ignore') except: try: data = str(data) except: data = "(could not encode data bytes)" else: try: data = str(data).encode('ascii', errors='ignore') except: data = "(could not encode data)" return data class Parser(HTMLParser): def __init__(self, url): self.title = None self.rec = False HTMLParser.__init__(self) try: # Added urlopen Timeout parameter so script doesn't freeze up: #self.feed(to_ascii(urlopen(url).read())) self.feed(to_ascii(urlopen(url, None, 5).read())) except Exception as err: # Not sure if I am handling exception right, script sometimes dies here: try: self.feed(str(err)) except: self.feed("(unknown error in urlopen)") self.rec = False self.error = error_callback def handle_starttag(self, tag, attrs): if tag == 'title': self.rec = True def handle_data(self, data): if self.rec: self.title = data def handle_endtag(self, tag): if tag == 'title': self.rec = False def get_title(url): try: return Parser(url).title except: return "(unknown error in Parser)" # //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// # Some other (untested) method of getting web title, from # # html - How can I retrieve the page title of a webpage using Python? - Stack Overflow # https://stackoverflow.com/questions/51233/how-can-i-retrieve-the-page-title-of-a-webpage-using-python) # # Rahul Chawla answered Jan 31 '17 at 12:46 # No need to import other libraries. # Request has this functionality in-built. # &gt;&gt; hearders = {'headers':'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:51.0) Gecko/20100101 Firefox/51.0'} # &gt;&gt;&gt; n = requests.get('http://www.imdb.com/title/tt0108778/', headers=hearders) # &gt;&gt;&gt; al = n.text # &gt;&gt;&gt; al[al.find('&lt;title&gt;') + 7 : al.find('&lt;/title&gt;')] # u'Friends (TV Series 1994\u20132004) - IMDb' # //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// # Function that gets # of lines in a text file, based on code found at: # text files - How to get line count cheaply in Python? - Stack Overflow # https://stackoverflow.com/questions/845058/how-to-get-line-count-cheaply-in-python # Kyle answered Jun 19 '09 at 19:07 # One line, probably pretty fast: # **************************************************************************************************************************************************************** # NOTE: I added an try/catch to try utf8 encoding if it failed. # There is probably a better way, not sure # what other encoding I might want to look for, # right now I just have utf8 and ascii files, # so script just needs to handle those. # **************************************************************************************************************************************************************** def fileLen(sFilePath): try: num_lines = sum(1 for line in open(sFilePath)) except UnicodeDecodeError as ude: try: num_lines = sum(1 for line in open(sFilePath, encoding="utf8")) except: num_lines = -1 return num_lines # //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// # Some dumb way I came up with to check to see if file is ascii # or unicode or something else, based on the try/catch # I added to fileLen when it was blowing up. def getFileEncoding(sFilePath): sType = "" try: sType = "ascii" num_lines = sum(1 for line in open(sFilePath)) except UnicodeDecodeError as ude: try: sType = "utf8" num_lines = sum(1 for line in open(sFilePath, encoding="utf8")) except: sType = "other" num_lines = -1 return sType # //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// # Function that reads URLs from a text file sInputFile # named like "myfile.txt" # and gets the page title for each, # and writes the URL + tab + title # to an output file named "myfile.out.txt". # # Based on code from: # Extract the title from a webpage using the python 3 standard lib - Code Review Stack Exchange # https://codereview.stackexchange.com/questions/183160/extract-the-title-from-a-webpage-using-the-python-3-standard-lib # # and whatever I could find on how to read/write text files in Python. # # TODO: figure out some other method to get titles for ftp:// and other non-http URL protocols. # TODO: just use the file name for images, PDFs (URLs ending in .jpg, .jpeg, .pdf, etc.) def getTitles(sInputFile, sStatus): sResult = "" iLineNum = 0 iCount = 0 iTitle = 0 iNull = 0 iTimeouts = 0 if Path(sInputFile).is_file(): sInputFile = str(sInputFile) sOutputFile = sInputFile.replace(".txt", ".out.txt") iLineCount = fileLen(sInputFile) print("File \"" + sInputFile + "\" has " + str(iLineCount) + " lines.") #print("File \"" + sInputFile + "\":") sEncoding = getFileEncoding(sInputFile) if (sEncoding == "ascii"): print("File encoding = ASCII") #fIn = open("url.txt", "r") fIn = open(sInputFile, "r") elif (sEncoding == "utf8"): print("File encoding = UTF8") fIn = open(sInputFile, "r", encoding="utf8") else: print("*** File encoding unknown ***") #TODO: open output file in ascii or utf8 mode depending on sEncoding #fOut = open("title.txt","w+") #fOut = open(sOutputFile,"w+") fOut = open(sOutputFile,"w+", encoding="utf-8") fLines = fIn.readlines() for sLine in fLines: iLineNum += 1 sLine = str(sLine) sLine = repr(sLine) #print(get_title('http://www.google.com')) #fOut.write("This is line %d\r\n" % (i+1)) #fOut.write(get_title('http://www.google.com') + "\r\n") sLine = sLine.lstrip('\'') sLine = sLine.rstrip('\'') sLine = sLine.strip('\\n') sLine = sLine.strip('\\r') sLine = sLine.strip('\\n') if sLine != "": iCount += 1 sTitle = get_title(sLine) if sTitle is None: iNull += 1 sTitle = '' else: iTitle += 1 # If title is blank then just use the URL as the description for now. if str(sTitle)=="": sTitle = sLine sTitle = sTitle.replace('\n', ' ').replace('\r', ' ') sTitle = re.sub('\s+', ' ', sTitle).strip() print(sStatus + "Line " + str(iLineNum) + " of " + str(iLineCount)) #print(str(iLineNum) + " of " + str(iLineCount) + ": " + sLine + '\t' + sTitle) #print(sLine + '\t' + sTitle) ##print(sLine) ##print(sTitle) #print("") ##fOut.write(get_title(sLine) + "\r\n") #fOut.write(sLine + '\t' + sTitle + '\r\n') fOut.write(sLine + '\t' + sTitle + '\n') else: print (str(iLineNum) + " of " + str(iLineCount) + ": (Skipping blank line.)") #print("(Skipping blank line.)") fIn.close() fOut.close() sResult = "Retrieved " + str(iTitle) + " titles, " + str(iNull) + " empty, " + str(iTimeouts) + " timeouts, " + "from \"" + sInputFile + "\", output to \"" + sOutputFile + "\"." else: sResult = "File \"" + sInputFile + "\" not found." return sResult # END getTitles # //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// def main(): # TODO: save start time # Get full path to this current script, based on code from: # Open file in a relative location in Python - Stack Overflow # https://stackoverflow.com/questions/7165749/open-file-in-a-relative-location-in-python/51671107 # Russ answered Aug 23 '11 at 18:59 script_dir = os.path.dirname(__file__) # &lt;-- absolute dir the script is in #print ("script_dir=" + script_dir) # Specifies subfolder (should be in same folder as this script) # that holds the input text files (and where output files are saved): # TODO: maybe accept a command line parameter for a different folder name or path sSubfolder = "url" # For now just add file names here hardcoded: # TODO: automatically process all *.txt files in "url" folder that don't end in ".out.txt" arrList = [] arrList.append("links1.txt") arrList.append("links2.txt") arrList.append("links3.txt") # Test code method #1 to traverse array (can't remember if it worked): #for iLoop in range(len(arrList)): # print(arrList(iLoop)) # Traverse array and process each file: iCount = 0 sTotal = str(len(arrList)) for sInputFile in arrList: iCount += 1 sStatus = "File " + str(iCount) + " of " + sTotal + ", " # Get filename with full path, and fix forward/back slashes in path # (I am on Windows so some parts have backslashes and not others): sInputFile = str(Path(os.path.join(script_dir, sSubfolder, sInputFile))) #print(str(iCount) + ". " + sInputFile) # Get the web titles for all the urls in the file: sResult = getTitles(sInputFile, sStatus) # Ouptut summary of results for the current file: print(str(iCount) + ". " + sResult) # Test output fileLen: #print(" fileLen: " + str(fileLen(sInputFile)) ) # ALL FINISHED: # TODO: save end time and display run duration as days/hours/minutes/seconds print("Done.") # //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// # RUNS FIRST, STARTS main SUBROUTINE: if __name__== "__main__": main() </code></pre> <h2>Contents of "links1.txt"</h2> <pre><code>https://codereview.stackexchange.com/questions/215849/batch-retrieve-web-titles-from-urls https://www.blog.pythonlibrary.org/2017/06/15/python-101-working-with-dates-and-time/ https://stackoverflow.com/questions/311627/how-to-print-a-date-in-a-regular-format https://www.w3resource.com/python-exercises/python-basic-exercise-3.php https://www.tutorialspoint.com/python3/python_date_time.htm </code></pre> <h2>Contents of "links2.txt"</h2> <pre><code>https://stackoverflow.com/questions/21618351/format-time-string-in-python-3-3 https://stackoverflow.com/questions/415511/how-to-get-the-current-time-in-python https://docs.python.org/3/library/time.html#time.strftime https://elearning.wsldp.com/python3/python-get-current-date/ </code></pre> <h2>Contents of "links3.txt"</h2> <pre><code>https://docs.python.org/3/download.html https://docs.python.org/3/archives/python-3.7.3rc1-docs-pdf-letter.zip https://media.readthedocs.org/pdf/python-guide/latest/python-guide.pdf https://www.datacamp.com/community/tutorials/python-data-science-cheat-sheet-basics https://s3.amazonaws.com/assets.datacamp.com/blog_assets/PythonForDataScience.pdf https://www.python.org/community/logos/ https://www.python.org/static/community_logos/python-logo.png </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-20T16:19:46.007", "Id": "417679", "Score": "1", "body": "Welcome to Code Review. You probably want to add an example call of your script, just to give reviewers a nice entry point to test your script on their PC before they post their review. I hope you get good reviews." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-20T18:45:06.107", "Id": "417696", "Score": "0", "body": "Sure - I added instructions and some test data." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-20T19:55:33.413", "Id": "417701", "Score": "0", "body": "Not realy worth an answer, but I would like to drop a note regarding `# ^^^ NO IDEA WHAT THESE 3 LINES ARE??`. Those are special comments to declare the source file encoding ([see here](https://www.python.org/dev/peps/pep-0263/)) as well as IDE specific commands, in your case for QPython ([see here](http://wiki.qpython.org/doc/program_guide/#user-mode))." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-21T13:11:02.983", "Id": "417806", "Score": "0", "body": "Alex, thanks. Hey, I'm a total newbie, so it IS worth an answer TO ME. So thank you, I will read those links." } ]
[ { "body": "<p>Since there is a lot going on here I will not be able to address all of your questions, but I hope my feedback will help you nevertheless.</p>\n\n<h1>General Remarks</h1>\n\n<h2>In-source Documentation</h2>\n\n<p>When I first had a look at your code I was stunned by the sheer amount of stuff that was happing. On the second look a lot of the content presented itself as extensive documentation on the sources of the code, its intention, and similar things.<br/>\nDon't get me wrong here, <strong>well documented code</strong> is a joy to read and review.\nContrary to what you will usually see in the wild, I'm inclined to say yours is a little bit to much for a source file.\nFrom my point of view a lot of the \"introduction\" section might actually better be suited to go into a seperate README file. This will help to reduce the amount of \"noise\" that presents itself to a reviewer or future you who wants to have a look at the code (only).</p>\n\n<h2>Seperation of Concerns / Structure</h2>\n\n<p>I would like remind you that keeping your code organized in digestible chunks is not something that is reserved to libraries. You can easily do this with your code as well. For example you could have a file where you collect all your functions which are used to determine the encoding, another file containing the parsers can than import this file to prepare website content. You could then import the parser in your main script file and use it without ever seeing the whole encoding detection again. Looking further, this would also give you the ability to easier test those seperate files.</p>\n\n<h1>The Python Code</h1>\n\n<p>After the general remarks I want to focus more on the code itself. The following points are in no particular order and I make them up as I go.</p>\n\n<h2>Header</h2>\n\n<p>Most Python script files will start with the following or similar lines</p>\n\n<pre><code>#!/usr/bin/python3\n#-*-coding:utf8;-*-\n</code></pre>\n\n<p>The first line is the so called <a href=\"https://en.wikipedia.org/wiki/Shebang_(Unix)\" rel=\"nofollow noreferrer\">shebang</a> used primarily on Unix systems which tells the system which interpreter to use when someone asks the system to treat the file as executable. Here it's the <code>python3</code> executable.<br/>\nThe next line tells the interpreter how the source file is encoded. As with most of the time one can read more about this in the corresponding <a href=\"https://www.python.org/dev/peps/pep-0263/\" rel=\"nofollow noreferrer\">PEP</a>.</p>\n\n<p>In addition to these two, there is a sheer endless collection of IDE specific \"magic comments\" that help your IDE or their integrated tools to work better with your source files. Since this is not Python-specific, I will not go into details here.</p>\n\n<h2>imports</h2>\n\n<p>Here, I would like to address your comments on <code>is this needed if we already imported all of urllib?</code>. The short answer is usually <strong>no</strong>. It just saves you from writing <code>urllib.request.urlopen</code> whenever you want to use <code>urlopen</code>. The same goes for <code>Request</code>.</p>\n\n<p>Another note on imports would be to keep your inputs grouped together, e.g. all imports from <code>urllib</code> should be in one block, like so:</p>\n\n<pre><code>import os\nimport re\nimport subprocess\n\nimport urllib\nfrom urllib.request import urlopen, Request\nfrom urllib.error import URLError, HTTPError\n\nfrom html.parser import HTMLParser\nfrom pathlib import Path\n</code></pre>\n\n<p>This will help you to easier find an import statement later, even without IDE support. See also the infamous <a href=\"https://www.python.org/dev/peps/pep-0008/#imports\" rel=\"nofollow noreferrer\">PEP8 Style Guide</a> for more details on this topic.</p>\n\n<h2>Style</h2>\n\n<p>Since we have opened the discussion on PEP8, I would like to give some hints to general style as well. Most Python code tends to use <code>snake_case</code> in function and variable names, following the PEP8 style guide. Also, those \"type prefixes\" like <code>i</code> or <code>s</code> sometimes found in C code are extremely uncommon in Python code. These aspects are no strict requirement for the code to work, just a recommendation. But however you choose to name your variables and functions <strong>be consistent</strong>, so either use <code>snake_case</code> or <code>camelCase</code>, not both. I know that, strictly speaking, not all of it is not \"your\" code, but you are the one who will have to work it ad it's a painfull experience not only to have to remember what function to use best, but also having to think about to how write the name.<br/>\nMost IDEs have tools that can check PEP8 or other style guidelines automatically and remind you with sadistic thoroughness on were you have violated the \"rules\". <a href=\"http://flake8.pycqa.org/en/latest/\" rel=\"nofollow noreferrer\">Flake8</a> and <a href=\"https://www.pylint.org/\" rel=\"nofollow noreferrer\">Pylint</a> are just some of the examples.</p>\n\n<h2>Documentation</h2>\n\n<p>Since we've already had a look at this topic I just want to give some further hints on this topic which are specific for Python source code.<br/>\nPython has built-in support for docstrings of functions and classes, e.g. by using the <a href=\"https://docs.python.org/3/library/functions.html#help\" rel=\"nofollow noreferrer\">help</a> function. For this to work you have to provide your documentation in a way Python expects.</p>\n\n<p>For example, you have a nice description on what <code>getTitles</code> is supposed to do. However, Python does not know about it, since it's freely floating in the source file. Enter <strong>docstrings</strong>, which is basically just the Python name for function and class documentation in the source file. Usually these docstrings are enclosed in <code>\"\"\"&lt;doc here&gt;\"\"\"</code> and can span multiple lines. A version of <code>getTitles</code> which works with the built-in help system can be found below:</p>\n\n<pre><code>def getTitles(sInputFile, sStatus):\n \"\"\"Function that reads URLs from a text file sInputFile\n\n Read URLs from a file named like \"myfile.txt\" and gets the page title for each, \n and writes the URL + tab + title to an output file named \"myfile.out.txt\".\n\n Based on code from:\n Extract the title from a webpage using the python 3 standard lib - Code Review Stack Exchange\n https://codereview.stackexchange.com/questions/183160/extract-the-title-from-a-webpage-using-the-python-3-standard-lib\n and whatever I could find on how to read/write text files in Python.\n\n TODO: figure out some other method to get titles for ftp:// and other non-http URL protocols.\n TODO: just use the file name for images, PDFs (URLs ending in .jpg, .jpeg, .pdf, etc.)\n \"\"\"\n ...\n</code></pre>\n\n<p>If you were to call <code>help(getTitles)</code> on this version of the function, Python would be able to find your documentation. Sweet, isn't it?</p>\n\n<h2>String Formatting</h2>\n\n<p>I'm one of the persons who tends to think not everything got better with Python 3. However, one of the most convenient things to work with (and badly miss in Python 2) are the so called <code>f-strings</code>.\nAn f-string is convenient way to express things like <code>sStatus = \"File \" + str(iCount) + \" of \" + sTotal + \", \"</code> simple as <code>sStatus = f\"File {iCount} of {sTotal}, \"</code>. Wonderful.<br/>\nSee <a href=\"https://realpython.com/python-f-strings/\" rel=\"nofollow noreferrer\">this blog post</a> for a nice comparison between the different ways to format string in Python.</p>\n\n<h2>Opening and Closing Files</h2>\n\n<p>It is common knowledge that you have to close file if you open it. So far so good. But what happens if there is an exception between opening and closing the file? Not so nice. But wait, there is help! Conceptually similar to C++ <a href=\"https://en.wikipedia.org/wiki/Resource_acquisition_is_initialization\" rel=\"nofollow noreferrer\">RAII idiom</a>, python offers something called <em>context managers</em>. A context manager in Python is a construct that aquires a resource when it is instantiated and also releases the resource no matter how the context is left.<br/>\nSo for example instead of </p>\n\n<pre><code>infile = open(\"test.txt\", \"r\")\n... # do something with infile, better not break somethig\ninfile.close()\n</code></pre>\n\n<p>one could simple write</p>\n\n<pre><code>with open(\"test.txt\", \"r\") as infile:\n ... # do something with infile, now can even throw!\n</code></pre>\n\n<p>See also <a href=\"https://stackoverflow.com/a/9283052\">this SO post</a> on how to open multiple files in a single <code>with</code> statement.</p>\n\n<h1>(Not so) Final Notes</h1>\n\n<p>There are a few topics that I have not touched, e.g. the chained handling of exceptions in the encoding detection. Maybe someone else or tomorrow me will have a go at them. Till then, happy coding and welcome to the world of Python!</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-21T15:37:02.347", "Id": "417820", "Score": "0", "body": "Holy cow, that's a lot of information. Thank you for taking the time to go through it all, and give all that feedback. I will read through everything and post an updated version of the script as time allows. (BTW the script finished running, it took about 20 hours to grab the titles to 120,000 URLs. I will review the results later.)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-21T21:50:11.327", "Id": "417872", "Score": "0", "body": "Looking at the results, the script worked for the majority of the links, but pulled the wrong title for maybe 15%, which of 120,000 is a lot. Some of the titles are messages like \"Are you a robot?\" which means I'll have to figure out how to make the script appear like a human browser, but others are things like \"Close\" or \"Close Navigation Menu\" or \"Chevron Icon\". Before the Python, I wrote a macro in Excel VBA to retrieve titles by automating Internet Explorer - it gets the correct titles but is prohibitively slow. So I know it can be done, just need to figure out how to get Python to do it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-22T09:49:42.360", "Id": "417905", "Score": "0", "body": "This is a good example for \"Use the right tool for the right job.\" Part of the Python learning experience is to realize that there are lots of useful libraries and that it's easy to use them. Library like beautifulsoup and requests make it a lot more comfortable to create HTTP requests that look more like ones that come from a browser." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-24T15:29:09.777", "Id": "418162", "Score": "0", "body": "That makes sense, I will read up on those and give them a try, and post the update in the next couple of days. Thank you!" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-20T23:27:30.437", "Id": "215887", "ParentId": "215849", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-20T16:04:12.920", "Id": "215849", "Score": "4", "Tags": [ "python", "python-3.x", "web-scraping" ], "Title": "Batch retrieve web titles from URLs" }
215849
<p>I'm new to python, and I wrote the following code. Please review, critique and enhance.</p> <blockquote> <p>This project compares quicksort, mergesort and bubblesort</p> <ol> <li><p>write/test the partition routine for quicksort. (20 points) The rest of the code is given.</p> </li> <li><p>write/test the merging part of the mergesort. (20 points) The rest of the code is given.</p> </li> <li><p>write/test bubblesort. (10 points) No code is given.</p> </li> <li><p>compare the sorts using lists of 10 and 50 items (in-order, reverse order and random (hard coded).</p> </li> </ol> <p>Be sure to print out the initial and sorted arrays so I can see that your module sorted properly.</p> </blockquote> <pre><code>#1) write/test the partition routine for quicksort. def qS(items): quickSortHelper(items,0,len(items)-1) def quickSortHelper(items,first,last): if first&lt;last: splitpoint = partition(items,first,last) quickSortHelper(items,first,splitpoint-1) quickSortHelper(items,splitpoint+1,last) def partition(items,first,last): pivotvalue = items[first] leftside = first+1 rightside = last done = False while not done: while leftside &lt;= rightside and items[leftside] &lt;= pivotvalue: leftside = leftside + 1 while items[rightside] &gt;= pivotvalue and rightside &gt;= leftside: rightside = rightside -1 if rightside &lt; leftside: done = True else: temp = items[leftside] items[leftside] = items[rightside] items[rightside] = temp temp = items[first] items[first] = items[rightside] items[rightside] = temp return rightside # 2) write/test the merging part of the mergesort. def mS(items): #print(&quot;Splitting &quot;,items) if len(items)&gt;1: mid = len(items)//2 lefthalf = items[:mid] righthalf = items[mid:] mS(lefthalf) mS(righthalf) i=0 j=0 k=0 while i &lt; len(lefthalf) and j &lt; len(righthalf): if lefthalf[i] &lt; righthalf[j]: items[k]=lefthalf[i] i=i+1 else: items[k]=righthalf[j] j=j+1 k=k+1 while i &lt; len(lefthalf): items[k]=lefthalf[i] i=i+1 k=k+1 while j &lt; len(righthalf): items[k]=righthalf[j] j=j+1 k=k+1 # 3) write/test bubblesort. (10 points) No code is given. def bS(items): exchanges = True passnum = len(items)-1 while passnum &gt; 0 and exchanges: exchanges = False for i in range(passnum): if items[i]&gt;items[i+1]: exchanges = True temp = items[i] items[i] = items[i+1] items[i+1] = temp passnum = passnum-1 # 4) compare the sorts using lists of 10 and 50 items (in-order, reverse #order # and random (hard coded). Be sure # to print out the initial and sorted arrays so I can see that #your module # sorted properly. (10 points) def mergeSort(L, ascending = True): result = [] if len(L) == 1: return L mid = len(L) // 2 firsthalf = mergeSort(L[:mid]) secondhalf = mergeSort(L[mid:]) x, y = 0, 0 while x &lt; len(firsthalf) and y &lt; len(secondhalf): if firsthalf[x] &gt; secondhalf[y]: # &lt; for descending result.append(secondhalf[y]) y = y + 1 else: result.append(firsthalf[x]) x = x + 1 result = result + firsthalf[x:] result = result + secondhalf[y:] if ascending == True : return result else: result.reverse() return result def _quickSort(list): if len(list) &lt;= 1: return list smaller, equal, larger = [], [], [] pivot = random.choice(list) for x in list: if x &lt; pivot: smaller.append(x) elif x == pivot: equal.append(x) else: larger.append(x) return _quickSort(smaller) + equal + _quickSort(larger) def quickSort(list, ascending=True): if ascending: return _quickSort(list) else: return _quickSort(list)[::-1] def BubbleSortAsc(list): swapped = True sortedvalue=0 while swapped: swapped = False sortedvalue+=1 for i in range(0,len(list)-sortedvalue): if list[i]&gt;list[i+1]: list[i], list[i+1], swapped = list[i+1], list[i], True def BubbleSortDsc(list): swapped = True sortedvalue=0 while swapped: swapped = False sortedvalue+=1 for i in range (0,len(list)-sortedvalue): if list[i]&lt;list[i+1]: list[i], list[i+1], swapped = list[i+1], list[i], True list=[3,2,4,1,5,9,7,6] # 6) write/test a variation on quicksort (vqS) that makes the following # improvements: # chooses pivot by taking a small sample size (3 items) and using # median for pivot. (10 points) def quicksort(array, l=0, r=-1): if r == -1: r = len(array) # base case if r-l &lt;= 1: return # pick the median of 3 possible pivots mid = int((l+r)*0.5) pivot = 0 #pivots = [ l, mid, r-1] if array[l] &gt; array[mid]: if array[r-1]&gt; array[l]: pivot = l elif array[mid] &gt; array[r-1]: pivot = mid else: if array[r-1] &gt; array[mid]: pivot = mid else: pivot = r-1 i = l+1 array[l], array[pivot] = array[pivot], array[l] for j in range(l+1,r): if array[j] &lt; array[l]: array[i], array[j] = array[j], array[i] i = i+1 array[l], array[i-1] = array[i-1], array[l] quicksort(array, l, i-1) quicksort(array, i, r) return array ls =[random.randrange(50) for _ in range(10)] #7) write/test a variation on mergesort (vmS) that makes the following # improvement: # Use insertion sort for small arrays (10 items or less). RUN = 10 def insertionSort(arr, left, right): for i in range(left + 1, right+1): temp = arr[i] j = i - 1 while arr[j] &gt; temp and j &gt;= left: arr[j+1] = arr[j] j -= 1 arr[j+1] = temp def hybridSort(arr, n): # Sort individual subarrays of size RUN for i in range(0, n, RUN): insertionSort(arr, i, min((i+31), (n-1))) # start merging from size RUN (or 10). It will merge size = RUN while size &lt; n: for left in range(0, n, 2*size): mid = left + size - 1 right = min((left + 2*size - 1), (n-1)) merge(arr, left, mid, right) size = 2*size # utility function to print the Array def printArray(arr, n): for i in range(0, n): print(arr[i], end = &quot; &quot;) print() # Driver program to test above function if __name__ == &quot;__main__&quot;: arr = [5, 21, 7, 23, 19,25,2] n = len(arr) items = [55,27,90,18,78,30,44,56,21,67] </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-20T16:28:31.240", "Id": "215852", "Score": "1", "Tags": [ "python", "beginner", "sorting", "mergesort", "quick-sort" ], "Title": "Sorts (merge, quick, bubble) in Python" }
215852
<p>The User story is as follows: </p> <p>Users are allowed to get "verified", so other users know they have passed a background check.</p> <p>After tapping "get verified" button, or the "verification badge" displayed on another users profile, they will be redirected to a view that will either prompt the <code>current user to get verified</code>, indicate that current user has <code>already been verified</code>, or indicate the <code>user they selected is already verified</code>. In code, this logic is initiated by calling the method <code>checkStatus</code>. </p> <p>The process to get verified requires the user to first upload their ID (2 attempts to successfully upload), and agree to a background check. These steps are carried with the use of a <code>UIPageViewController</code>. </p> <p>This is my code to determine what stage the current user is in the verification process, what page to segue to, and what view to display. I think the way my logic is set up is pretty messy, and am looking for advice to make it more clean and concise. Any advice is appreciated. I left some comments that could help reading the code as well. Its nothing complex, but think the code could be improved, I wrote this pretty quickly. </p> <pre><code>- (void)checkStatus { if (![self isCurrentUserEqualToBriefUser]) { // Current user tapped on verification badge of another user. // Still check progress of current user to enable/disable button to get verified. // If current user is verified that display type will overried dispaly indicating other person is verified. [self setupViewWithAppearance:AppearanceTypeTheyreVerified]; } if (![self isUserVerified]) { [self checkProgress]; } } - (BOOL)isUserVerified { // When user completes verification, Core Data is updated with date of verification. If `isVerificationDateValid` is nil, or invalid, they are not verified. if ([CoreDataUser currentUser].isVerificationDateValid) { dispatch_async(dispatch_get_main_queue(), ^{ if ([self isCurrentUserEqualToBriefUser]) { [self setupViewWithAppearance:AppearanceTypeYoureVerified]; } [self setPermissionToContinue:NO]; [self removeLoadingAnimation]; }); return YES; } return NO; } - (void)checkProgress { dispatch_async(dispatch_get_main_queue(), ^{ [self.view setUserInteractionEnabled:NO]; }); RequestTask *task = [[VerificationDataManager sharedInstance] getVerificationStatus:^(NSDictionary *results, NSError *error) { if (results) { // Check if user failed background check if ([results valueForKey:kVerificationIsBackgroundCheckSuccessful] != nil) { if ([results[kVerificationIsBackgroundCheckSuccessful] boolValue] == NO) { dispatch_async(dispatch_get_main_queue(), ^{ if ([self isCurrentUserEqualToBriefUser]) { [self setupViewWithAppearance:AppearanceTypeGetVerified]; } [self setPermissionToContinue:NO]; [self removeLoadingAnimation]; }); return; } } // get status of ID and backround check if (![self isIdUploadInProgress:results]) { [self isBackgroundCheckInProgress:results]; } } else if (error) { if (error.code == 204) { // 204 error means no object exist. so user isnt verified yet. dispatch_async(dispatch_get_main_queue(), ^{ if ([self isCurrentUserEqualToBriefUser]) { [self setupViewWithAppearance:AppearanceTypeGetVerified]; } [self setPermissionToContinue:YES]; [self removeLoadingAnimation]; }); } else { // Actual error. VerifyPageViewController *parent = (VerifyPageViewController *)[self parentViewController]; [parent dismissViewControllerAnimated:YES completion:nil]; [self setPermissionToContinue:NO]; [self removeLoadingAnimation]; } } dispatch_async(dispatch_get_main_queue(), ^{ [self.view setUserInteractionEnabled:YES]; }); }]; [RequestsDispatcher performSingleRequest:task]; } - (BOOL)isIdUploadInProgress:(NSDictionary *)results { VerifyPageViewController *parent = (VerifyPageViewController *)[self parentViewController]; if ([results valueForKey:kVerificationIsIdVerified] == nil) { // key does not exist so has not attempted to submit ID yet. [parent nextPageAtIndex:2]; return YES; } else { // key does exist, but ID not verified so check how many attempts were performed. if ([results[kVerificationIsIdVerified] boolValue] == NO) { // 2 attempts max int idAttemptCount = [[results objectForKey:kIdUploadAttempts] intValue]; if (idAttemptCount &gt; 1) { // reached max ID upload attempts. // set isIDSubmitting to YES, so page 7 shows proper related error. // Maybe use state machine with enums in data manager instead. [VerificationDataManager sharedInstance].isIdSumitting = YES; [parent nextPageAtIndex:7]; } else { // segue to ID upload page. [parent nextPageAtIndex:2]; } return YES; } } return NO; } - (BOOL)isBackgroundCheckInProgress:(NSDictionary *)results { if ([results valueForKey:kVerificationIsBackgroundCheckSuccessful] == nil) { // key doesnt exist, so havnt perfomred backgorund check yet. VerifyPageViewController *parent = (VerifyPageViewController *)[self parentViewController]; [parent nextPageAtIndex:4]; return YES; } else { // already check for backgroundcheck failure and dispatch_async(dispatch_get_main_queue(), ^{ if ([self isCurrentUserEqualToBriefUser]) { [self setupViewWithAppearance:AppearanceTypeGetVerified]; } [self setPermissionToContinue:NO]; [self removeLoadingAnimation]; }); return NO; } } </code></pre>
[]
[ { "body": "<p>It's good that you are getting that feeling that something isn't right. You are violating the single responsibility principle. Your view controller should only be responsible for it's view hierarchy, not the data that drives the view hierarchy.</p>\n\n<p>You should create a data model/context to encapsulate the logic around the user verification status. You can observe changes in that model to update your UI.</p>\n\n<ol>\n<li>Create a data model and optionally a context around that data.</li>\n</ol>\n\n<pre><code> @interface User\n\n @property (nonatomic, readonly) BOOL idUploading;\n @property (nonatomic, readonly) BOOL idUploaded;\n @property (nonatomic, readonly) BOOL verified;\n\n @end\n</code></pre>\n\n<p>The implementation of the data model/context updates the properties based on the verification status.</p>\n\n<ol start=\"2\">\n<li>Now you can observe the data model to update page view controller using <a href=\"https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/KeyValueObserving/KeyValueObserving.html\" rel=\"nofollow noreferrer\">Key Value Observing</a>.</li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-15T19:07:52.030", "Id": "217509", "ParentId": "215856", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-20T17:19:38.703", "Id": "215856", "Score": "2", "Tags": [ "objective-c", "ios", "state" ], "Title": "Checking user verification status" }
215856
<p>Say that I have running id from 1 to <em>n</em>, and a value column:</p> <pre><code>set.seed(1) x &lt;- data.frame(c(1:10),rnorm(10,10, sd = 2.5)) colnames(x) &lt;- c("id", "value") id value 1 1 8.433865 2 2 10.459108 3 3 7.910928 4 4 13.988202 5 5 10.823769 6 6 7.948829 7 7 11.218573 8 8 11.845812 9 9 11.439453 10 10 9.236529 </code></pre> <p>Now let's imagine that I have for some reason lost some of that data, but I nevertheless need to fill it with some value</p> <pre><code># Let's lose data (x &lt;- x[-5,]) </code></pre> <p>Now I am missing observation #5, but I still need to replace it with a value (e.g. 0 or NA). Note that in reality I don't necessary know what observation ID is missing. </p> <p>This is what I wrote, and it works. However, I am wondering whether there is a vectorized way of doing this (or a more efficient way in general)?</p> <pre><code>f &lt;- function(x, fill_value){ # Get number of rows n &lt;- nrow(x) max_id &lt;- max(x$id) # Get missing data position no_data_position &lt;- which(!(1:max_id %in% x$id)) # Fill missing data out &lt;- data.frame() start &lt;- 0 counter &lt;- 1 for(i in 1:max_id){ if(!i %in% no_data_position){ out[start + i, "id"] &lt;- start + i out[start + i, "value"] &lt;- x$value[counter] counter &lt;- counter + 1 } else { out[start + i, "id"] &lt;- start + i out[start + i, "value"] &lt;- fill_value } } return(out) } f(x, NA) id value 1 1 8.433865 2 2 10.459108 3 3 7.910928 4 4 13.988202 5 5 NA 6 6 7.948829 7 7 11.218573 8 8 11.845812 9 9 11.439453 10 10 9.236529 </code></pre>
[]
[ { "body": "<p>First, you can find the missing values using set operations:</p>\n\n<pre><code>no_data_position &lt;- setdiff(c(1:max(x$id)), x$id)\n</code></pre>\n\n<p>And then just build a dataframe with the missing values and <code>merge</code> it:</p>\n\n<pre><code>out &lt;- merge(x, data.frame(id=no_data_position, value=fill_value), all=TRUE)\n</code></pre>\n\n<p>And that is literally the full function:</p>\n\n<pre><code>f &lt;- function(x, fill_value) {\n no_data_position &lt;- setdiff(c(1:max(x$id)), x$id)\n merge(x, data.frame(id=no_data_position, value=fill_value), all=TRUE)\n}\n</code></pre>\n\n<p>Note that you don't need the explicit <code>return</code>, a function implicitly returns the last return value (not sure if that is best practice in R, though). You probably also want to give that function a more descriptive name as well.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-20T20:13:57.797", "Id": "215871", "ParentId": "215860", "Score": "3" } }, { "body": "<p>Your code does work but there are indeed better ways of doing this.</p>\n\n<p>Some details could be improved in your current function:</p>\n\n<ul>\n<li>You could replace <code>which(!(1:max_id %in% x$id))</code> with <code>setdiff(seq(min_id, max_id), x$id)</code>. It's more legible, and, more importantly, it does not rely on the fact that your IDs are the <em>n</em> first integers. (Consider for instance <code>which(!(2:5 %in% c(2, 3, 5)))</code>: it does not return 4.)</li>\n<li><code>start</code> is assigned to 0 but is never modified, so you could get rid of this local variable.</li>\n</ul>\n\n<p>But the main point is that growing a dataframe in a loop is generally not a good idea, as most of the time you can find better options. Here are two possible solutions:</p>\n\n<p><strong>1) With base R</strong></p>\n\n<pre><code>y &lt;- data.frame(id = seq(min(x$id), max(x$id)))\nx &lt;- merge(y, x, all.x = TRUE)\nx$value[is.na(x$value)] &lt;- fill_value\n</code></pre>\n\n<p><strong>2) With <code>tidyr</code></strong></p>\n\n<pre><code>library(tidyr)\n\ncomplete(x, id = seq(min(id), max(id)), fill = list(value = fill_value))\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-21T07:31:18.243", "Id": "417767", "Score": "0", "body": "Thanks, I was indeed almost certain that there is a way to do it within the tidyverse, but just didn't find it. :)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-20T20:21:45.583", "Id": "215872", "ParentId": "215860", "Score": "4" } }, { "body": "<p>An alternative: as long as the <code>id</code> column is an integer, I have found the <code>padr</code> package's <code>pad_id</code> function helpful for this:</p>\n\n<pre><code>padr::pad_int(x, \"id\")\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-26T20:52:35.797", "Id": "223019", "ParentId": "215860", "Score": "2" } } ]
{ "AcceptedAnswerId": "215872", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-20T18:31:28.337", "Id": "215860", "Score": "5", "Tags": [ "performance", "r" ], "Title": "Fill missing value based on ID" }
215860
<p>The HTML page shows list of a friend network of a person (each Name has anchor <code>&lt;a&gt;</code> tag w. link to list of friend network). Since the page has a timer, I've written a py code to scrap the mth position (friend) of the nth count (page) by traversing through the cycle: (m->n->m->n....). And it works!</p> <pre><code>import urllib.request, urllib.parse, urllib.error from bs4 import BeautifulSoup import ssl # Ignore SSL certificate errors ctx = ssl.create_default_context() ctx.check_hostname = False ctx.verify_mode = ssl.CERT_NONE url = input('Enter URL: ') position = int(input('Enter position: ')) #Name/link Traverse count = int(input('Enter count: ')) #Page Traverse print("Retrieving:", url) for c in range(count): #returns range of indices html = urllib.request.urlopen(url, context=ctx).read() #opening URL soup = BeautifulSoup(html, 'html.parser') a_tags=soup('a') link=a_tags[position-1].get('href', None) #url = href(key) value pair content=a_tags[position-1].contents #name=a_tag.contents url=link print("Retrieving:", url) </code></pre> <p><strong>Input:</strong></p> <pre><code>Enter URL: http://py4e-data.dr-chuck.net/known_by_Kory.html Enter position: 1 Enter count: 10 </code></pre> <p><strong>Output:</strong></p> <pre><code>Retrieving: http://py4e-data.dr-chuck.net/known_by_Kory.html Retrieving: http://py4e-data.dr-chuck.net/known_by_Shaurya.html Retrieving: http://py4e-data.dr-chuck.net/known_by_Raigen.html Retrieving: http://py4e-data.dr-chuck.net/known_by_Dougal.html Retrieving: http://py4e-data.dr-chuck.net/known_by_Aonghus.html Retrieving: http://py4e-data.dr-chuck.net/known_by_Daryn.html Retrieving: http://py4e-data.dr-chuck.net/known_by_Pauline.html Retrieving: http://py4e-data.dr-chuck.net/known_by_Laia.html Retrieving: http://py4e-data.dr-chuck.net/known_by_Iagan.html Retrieving: http://py4e-data.dr-chuck.net/known_by_Leanna.html Retrieving: http://py4e-data.dr-chuck.net/known_by_Malakhy.html </code></pre> <p><strong>Questions:</strong></p> <ol> <li><p>Is there a better way to approach this? (libraries, workarounds to delay the timer)</p></li> <li><p>My goals is to make an exhaustive 'list' of friends of all unique Names here; I don't want any code, just suggestions and approaches will do.</p></li> </ol>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-21T08:00:15.970", "Id": "417779", "Score": "2", "body": "What do you mean with \"the page has a timer\"? Once you have retrieved the page content, the website cannot magically change the string in memory (unlike when visiting the page with a browser, where dynamic elements can exist)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-21T08:37:40.153", "Id": "417782", "Score": "1", "body": "I mean that the page has a timer when opened in a browser; is there a better way to approach this problem, or should I just proceed like how I've done so far. Just looking for a specific library that can open each link and scrap content from the 'n' pages for me, without me looping through." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-21T16:16:56.813", "Id": "417834", "Score": "0", "body": "Welcome to Code Review! Please don't comment comments asking for clarification or additional information: edit your post." } ]
[ { "body": "<p>Currently you only get one new name per page request. However, the page contains all people known by that person. So I would implement a queue of yet to be visited people and a set of people already visited. If there are no more people left to visit, you have found all people (assuming there are no disjoint sets of people and that this is your actual goal).</p>\n\n<p>In addition, using <a href=\"http://docs.python-requests.org/en/master/\" rel=\"nofollow noreferrer\"><code>requests</code></a> is usually a bit more user-friendly than using <code>urllib</code> directly.</p>\n\n<pre><code>import requests\nfrom bs4 import BeautifulSoup, SoupStrainer\nimport re\n\nSTRAINER = SoupStrainer(\"a\")\n\ndef get_name(url):\n match = re.match(r\"http://py4e-data.dr-chuck.net/known_by_(.*).html\", url)\n if match is not None:\n return match.groups()[0]\n\ndef find_all_people(start_url):\n with requests.Session() as session:\n queue = set([start_url])\n visited = set()\n while queue:\n url = queue.pop()\n visited.add(url)\n print(len(visited), \"/\", len(visited) + len(queue), url)\n response = session.get(url)\n soup = BeautifulSoup(response.text, \"lxml\", parse_only=STRAINER)\n queue.update(a[\"href\"]\n for a in soup.select(\"a\")\n if a[\"href\"] not in visited)\n return list(map(get_name, visited))\n\nif __name__ == \"__main__\":\n url = \"http://py4e-data.dr-chuck.net/known_by_Kory.html\"\n people = find_all_people(url)\n print(len(people))\n</code></pre>\n\n<p>This uses a <a href=\"http://docs.python-requests.org/en/master/user/advanced/#session-objects\" rel=\"nofollow noreferrer\"><code>request.Session</code></a> to keep the connection alive, speeding it up a tiny bit. It also has a <a href=\"http://stackoverflow.com/questions/419163/what-does-if-name-main-do\"><code>if __name__ == \"__main__\":</code></a> guard to allow importing from this script from another script without the code running, a <a href=\"https://www.crummy.com/software/BeautifulSoup/bs4/doc/#soupstrainer\" rel=\"nofollow noreferrer\"><code>bs4.SoupStrainer</code></a> to only parse the parts of the page needed and it uses the faster <a href=\"https://www.crummy.com/software/BeautifulSoup/bs4/doc/#specifying-the-parser-to-use\" rel=\"nofollow noreferrer\"><code>lxml</code></a> parser.</p>\n\n<p>It still takes quite some time to find all people. Finding that there are <em>probably</em> 5754 people takes only a few seconds.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-23T17:20:03.147", "Id": "216063", "ParentId": "215862", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-20T18:34:13.620", "Id": "215862", "Score": "3", "Tags": [ "python", "web-scraping", "beautifulsoup" ], "Title": "Data retrieval from Dynamic HTML page with time-out (Web scraping w. Python)" }
215862
<p>I have inherited this nightmare Python, Selenium, and Pandas project. I am learning Python as I go; and have been cleaning up and refactoring the code where I see necessary - It was worst if you can imagine; <strong>anyway</strong>, if anyone is a Python/Pandas/Selenium enthusiast and has ideas to optimize it further beyond this point; I'd love to hear.</p> <p>The goal of this project, was to grab excel files in a directory or 'hot folder'; iterate through the files, sequentially; take the excel data to pandas, then to fill out a 1-page 'data entry' style web form via selenium on a website and save.</p> <ul> <li>It would loop and fill out this 1-web form as many times as there are data in the 'hot folder'/excel files to do so.</li> <li>Currently, I have it working with a .zip folder; and saving the form after 1 entry.</li> <li><em>Lastly, eventually; I will just shoot out a "stat" log file with the date appended with the data success rate from each file..</em></li> </ul> <hr> <p>Here is my /<code>config.py</code>.</p> <pre><code>FILE_LOCATION = r"C:\Zip\2019.02.12 VCCS Docs.zip" #altering this to directory produces Permission Denied UNZIP_LOCATION = r"C:\Zip\Pending" VITAL_URL = 'http://boringDBwebsite:8080/ContactForm' HEADLESS = False PROCESSORS = 4 MAPPING_DOC = ".//map/mappingDoc.xlsx" </code></pre> <p>here is my <code>/main.py</code></p> <pre><code>"""Start Point""" from data.find_pending_records import FindPendingRecords from vital.vital_entry import VitalEntry import sys from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.common.keys import Keys from selenium.webdriver.common.action_chains import ActionChains import pandas as pd if __name__ == "__main__": try: # for PENDING_RECORDS in FindPendingRecords().get_excel_data(): begin to loop through entire directory PENDING_RECORDS = FindPendingRecords().get_excel_data() # Do operations on PENDING_RECORDS # Reads excel to map data from excel to vital MAP_DATA = FindPendingRecords().get_mapping_data() # Configures Driver VITAL_ENTRY = VitalEntry() # Start chrome and navigate to vital website # driver = VITAL_ENTRY.instantiate_chrome() VITAL_ENTRY.instantiate_chrome() # Begin processing Records VITAL_ENTRY.process_records(PENDING_RECORDS, MAP_DATA) # Save Record # VITAL_ENTRY.save_contact(driver) print (PENDING_RECORDS) print("All done") except Exception as exc: # print(exc) raise #Start Stat Log old_stdout = sys.stdout log_file = open("./logs/message.log","w") sys.stdout = log_file # print ("Write to File") sys.stdout = old_stdout log_file.close() # df = pd.read_excel(UNZIP_LOCATION, sheetname="Care Coordinaton Contact Log 2.12.2019") # print len(df) </code></pre> <p>here is my <code>/vital_entry.py</code></p> <pre><code>"""Module for completing VITAL contact logs from Advance Health""" import re import sys import os from time import sleep from itertools import repeat from traceback import format_exception from datetime import datetime, timedelta from multiprocessing import cpu_count from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.common.keys import Keys from selenium.webdriver.common.action_chains import ActionChains from selenium.common.exceptions import NoSuchElementException from joblib import Parallel, delayed from vital.vital_common import (RadioWhileException, DidNotProcessAll, wait_until, page_change_until, wait_ready_state) import config class VitalEntry: """Vital Entry""" def __init__(self): self.assessment_type = "Care Coordination Contact Log (Custom) - VHP" self.processors = config.PROCESSORS assert self.processors &gt; 0, 'Need number of processes to be greater than zero.' assert self.processors &lt;= cpu_count(),\ ('Need number of processes to be at most the max number of cores/threads ' f'available. For this computer, it\'s {cpu_count()}.') self.user = os.environ['USERNAME'] self.options = webdriver.ChromeOptions() def instantiate_chrome(self): """Create Chrome webdriver instance.""" self.options.headless = config.HEADLESS if not self.options.headless: self.options.add_argument("--start-maximized") self.options.add_argument('--disable-infobars') self.options.add_argument('--disable-gpu') self.driver = webdriver.Chrome(options=self.options) self.driver.set_page_load_timeout(30) self.driver.implicitly_wait(15) self.driver.get(config.VITAL_URL) # return driver def close_chrome(self): """Used to close out of chrome""" self.driver.quit() print("Closing chrome") def process_records(self, records, map_data, completed=None, errors=None): """Code to execute after webdriver initialization.""" series_not_null = False try: num_attempt = 0 for record in records.itertuples(): print(record) series_not_null = True mrn = record.MRN self.navigate_to_search(num_attempt) self.navigate_to_member(mrn) self.navigate_to_assessment() self.add_assessment(record, map_data) # self.save_contact(self.driver) self.driver.switch_to.parent_frame() sleep(.5) error_flag = self.close_member_tab(self.driver, mrn, error_flag) except Exception as exc: if series_not_null: errors = self.process_series_error(exc) return completed, errors def navigate_to_search(self, num_attempt): """Uses webdriver to navigate to Search tab and select Member Status=All""" if num_attempt == 0: page_change_until(self.driver, By.XPATH, './/*[text()="Search"]') wait_ready_state(self.driver) else: self.driver.switch_to.parent_frame() elem = wait_until(self.driver, By.XPATH, './/*[text()="Search"]') is_disp_n = 0 while True: if elem.is_displayed(): break else: self.driver.switch_to.parent_frame() is_disp_n += 1 sleep(1) if is_disp_n == 30: raise Exception('Could not find Search tab after 30 tries.') num_attempt += 1 radio_locator = (By.XPATH, './/*[@type="RADIO"][@value="All"]') while True: break_while_timer = datetime.now() if datetime.now() - break_while_timer &gt; timedelta(seconds=20): break_while = True break try: if wait_until(self.driver, *radio_locator).is_selected(): pass else: wait_until(self.driver, *radio_locator).click() break except Exception: sleep(1) def navigate_to_member(self, mrn): """Finds member""" wait_until(self.driver, By.XPATH, './/*[@name="MemberIdItem_1"]').clear() wait_until(self.driver, By.XPATH, './/*[@name="MemberIdItem_1"]').send_keys(f'{mrn}'+Keys.ENTER) page_change_until(self.driver, By.XPATH, f'.//*[text()="{mrn}"]') wait_ready_state(self.driver) def navigate_to_assessment(self): """Navigates to the appropriate contact log""" self.driver.find_element_by_css_selector("div[eventproxy^='memberAssessment']").click() #clicks assessment icon element = self.driver.find_element_by_xpath(f"//div[contains(text(), '{self.assessment_type}')]") actions = ActionChains(self.driver) actions.move_to_element(element).perform() self.driver.find_element_by_xpath(f"//div[contains(text(), '{self.assessment_type}')]").click() self.driver.find_element_by_css_selector("div[eventproxy^='createSelectedAssessmentsButton']").click() def add_assessment(self, record, map_data): """Create contact log""" qna_frame = self.driver.find_element_by_css_selector("iframe[id^='iccc']") self.driver.switch_to.frame(qna_frame) pages = self.driver.find_element_by_css_selector("ul[class='nav nav-pills nav-stacked qna-tabs']") pages = pages.find_elements_by_css_selector("a") for page in pages: page.click() questions = self.driver.find_elements_by_css_selector("fieldset") questions = [question for question in questions if question.text not in ("", " ", "NaT", "NaN", None)] for question in questions[1:]: self.q_text = question.find_element_by_css_selector("span[class='question-text ng-binding']").text questionType = map_data.loc[map_data['question_text'] == self.q_text, 'question_type'].item() answer = map_data.loc[map_data['question_text'] == self.q_text, 'map'].item() answer = getattr(record, answer) if answer not in ("", " ", "NaT", "NaN", None): # while answer != "" and answer != " " and answer != "NaT": if questionType == 'checks': self.choose_checks(question, answer) else: try: if questionType == 'text': self.driver.implicitly_wait(0) (question.find_element_by_css_selector("textarea").send_keys(str(answer)) if question.find_elements_by_css_selector("textarea") else question.find_element_by_css_selector("input").send_keys(answer)) self.driver.implicitly_wait(15) elif questionType == 'date': try: answer = answer.strftime('%m/%d/%Y') question.find_element_by_css_selector("input").send_keys(answer) page.click() except Exception as e: raise Errors.RequiredDataError('Issues with Assessment Date -- {}'.format(e)) elif questionType == 'radio': question.find_element_by_css_selector("input[value='{}']".format(answer)).click() except: continue else: # driver.find_element_by_css_selector("#publishButton").click() pass def choose_checks(self, question, answer): checkboxes = question.find_elements_by_css_selector('label') for check in checkboxes: if check.text == answer: check.click() def close_member_tab(self, driver, mrn, error_flag): """Close member tab""" tab = driver.find_element_by_xpath(f'.//*[contains(@aria-label,"{mrn}")]') while True: try: tab = driver.find_element_by_xpath( f'.//*[contains(@aria-label,"{mrn}")]') except NoSuchElementException: break except Exception: sleep(1) continue else: try: tab.find_element_by_xpath('./div/table/tbody/tr/td/table/tbody/tr/td[2]').click() except Exception: pass break if error_flag: error_flag = False num_tries = 1 while num_tries &lt;= 5: try: xpath = ('.//*[starts-with(@eventproxy, "YesNoCan celDialog")]//*[text()="No"]') driver.find_element_by_xpath(xpath).click() break except Exception: sleep(1) num_tries += 1 continue return error_flag # def find_hidden_fields (self, driver, answer): # driver.implicitly_wait(10) # # driver.find_element_by_css_selector("").click() # driver.find_element_by_xpath("//*[@id='qna_0']/fieldset[1]/fieldset[21]/div[2]/div/textarea").click() # driver.find_element_by_xpath("//*[@id='qna_0']/fieldset[1]/fieldset[21]/div[2]/div/textarea").send_keys("test") # def save_contact (self, driver): # driver.implicitly_wait(15) # driver.find_element_by_css_selector("#publishButton").click() def process_series_error(self, errors): #stub print(errors) return errors </code></pre> <p>here is my <code>/find_pending_records.py</code></p> <pre><code> """Module used to find records that need to be inserted into Vital""" from zipfile import ZipFile import math import pandas import config class FindPendingRecords: """Class used to find records that need to be inserted into Vital""" @classmethod def find_file(cls): """"Finds the excel file to process""" archive = ZipFile(config.FILE_LOCATION) for file in archive.filelist: if file.filename.__contains__('Care Coordinaton Contact Log '): return archive.extract(file.filename, config.UNZIP_LOCATION) return FileNotFoundError # class FindPendingRecords: Begin solution for loop through entire directory # @classmethod # def find_file(cls): # return ["file1", "file2", "file3"] # def __init__(self): # self.files = self.find_file() # def get_excel_data(self): # for excel_data in self.files: # # process your excel_data # yield excel_data # @classmethod # def find_file(cls): # all_files = list() # """"Finds the excel file to process""" # archive = ZipFile(config.FILE_LOCATION) # for file in archive.filelist: # if file.filename.__contains__('Care Coordinaton Contact Log '): # all_files.append(archive.extract(file.filename, config.UNZIP_LOCATION)) # return all_files def get_excel_data(self): """Places excel data into pandas dataframe""" excel_data = pandas.read_excel(self.find_file()) columns = pandas.DataFrame(columns=excel_data.columns.tolist()) excel_data = pandas.concat([excel_data, columns]) excel_data.columns = excel_data.columns.str.strip() excel_data.columns = excel_data.columns.str.replace("/", "_") excel_data.columns = excel_data.columns.str.replace(" ", "_") num_valid_records = 0 for row in excel_data.itertuples(): mrn = row.MRN if mrn in ("", " ", None) or math.isnan(mrn): print(f"Invalid record: {row}") excel_data = excel_data.drop(excel_data.index[row.Index]) # continue else: num_valid_records += 1 print(f"Processing #{num_valid_records} records") return self.clean_data_frame(excel_data) def clean_data_frame(self, data_frame): """Cleans up dataframes""" for col in data_frame.columns: if "date" in col.lower(): data_frame[col] = pandas.to_datetime(data_frame[col], errors='coerce', infer_datetime_format=True) data_frame[col] = data_frame[col].dt.date data_frame['MRN'] = data_frame['MRN'].astype(int).astype(str) return data_frame def get_mapping_data(self): map_data = pandas.read_excel(config.MAPPING_DOC, sheet_name='main') columns = pandas.DataFrame(columns=map_data.columns.tolist()) return pandas.concat([map_data, columns]) </code></pre> <p>Lastly, and less important; <code>/vital_common.py</code></p> <pre><code>""" Base functions and classes for contact log completion """ from datetime import datetime, date, timedelta from inspect import getmembers, isclass, getclasstree import re from time import sleep from contextlib import contextmanager import pandas as pd import numpy as np from selenium import webdriver, common from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.keys import Keys def recurse_tree(class_tree, recurse=0): """Parse through subclass tree and rank by layer level.""" out_list = [] for sub_tree in class_tree: if isinstance(sub_tree, list): out_list.extend(recurse_tree(sub_tree, recurse=recurse+1)) elif isinstance(sub_tree, tuple): out_list.append((sub_tree[1][0], recurse)) return out_list class RadioWhileException(Exception): """Exception for missing radio button in while loop.""" def __str__(self): return 'Never found radio button for "all" on Search tab.' class DidNotProcessAll(Exception): """Exception for not processing all records.""" def __str__(self): return "Didn't process all records" class NoCloseButton(Exception): """Exception when close button doesn't exist for tab""" def __str__(self): return "Close button doesn't exist on tab" class ContactLogError(Exception): """Error in processing the contact log.""" def __init__(self, add_msg): self.add_msg = add_msg def __str__(self): return 'Error in contact log completion: {}.'.format(self.add_msg) def full_unravel(lol): """Take list-like objects with list-like entries and create a single list""" items = [] for lobj in lol: if isinstance(lobj, tuple(list.__subclasses__() + [list])): items.extend(full_unravel(lobj)) else: items.append(lobj) return items def subsubclasses(cls): """Find subclasses and subclasses of subclasses.""" subc = cls.__subclasses__() ssc = [x.__subclasses__() if hasattr(x, '__subclasses__') else x for x in datetime.__subclasses__()] return full_unravel(ssc) + subc #+ [cls] def send_enter(self): """WebElement method shortcut for send_keys(Keys.ENTER).""" self.send_keys(Keys.ENTER) webdriver.remote.webelement.WebElement.send_enter = send_enter def wait_until(driver, by_strat, value, tries=None): """Wrapper for WebDriverWait.until method using the presence_of_element_located expected condition. defaults to 6 tries at 5 seconds per try.""" if isinstance(tries, type(None)): tries = 6 count = 0 while count &lt; tries: try: return WebDriverWait(driver, 5).until(EC.presence_of_element_located((by_strat, value))) except common.exceptions.TimeoutException: sleep(1) count += 1 raise common.exceptions.TimeoutException def wait_until_not(driver, by_strat, value): """Similar to above, excpet for until_not method""" return WebDriverWait(driver, 20).until_not(EC.presence_of_element_located((by_strat, value))) @contextmanager def page_change(driver): """Function to find innerHTML from 'html' tag prior to performing a click that causes a page load.""" old_html = driver.find_element_by_tag_name('html').get_attribute('innerHTML') yield def new_html(): """Grab new HTML code""" return driver.find_element_by_tag_name('html').get_attribute('innerHTML') while True: if old_html != new_html(): break else: sleep(1) def page_change_until(driver, by_strat, value, tries=None): """Uses page_change wrapper in context and performs actual click""" with page_change(driver): wait_until(driver, by_strat, value, tries).click() def wait_ready_state(driver): """Pauses code execution until page has loaded.""" script = 'return document.readyState == "complete";' def func(): """Execute script""" return driver.execute_script(script) while True: if func(): break else: sleep(1) def space_replace(text): """Replace spaces""" text = re.sub(r'\s', ' ', text) return re.sub(r' {2,}', ' ', text) class NullType(type): """Make a Null type""" def __repr__(cls): return 'Null' def __str__(cls): return 'Null' class Null(object, metaclass=NullType): """Make a null object of NullType""" def __repr__(self): return 'Null' def __str__(self): return 'Null' def convert_to_string(obj): """Converts various data types to proper string format which will then be passed as SQL strings.""" if pd.isnull(obj): return Null if hasattr(obj, 'tolist'): obj = obj.tolist() if isinstance(obj, float): if obj.is_integer(): return str(int(obj)) return str(obj) elif isinstance(obj, int): return str(obj) wrap = "'{}'" obj = str(obj).replace("'", "''") return wrap.format(obj) def convert_to_cte(frame): """Converts dataframe rows to SELECT UNION SELECT format to then be used in a common table expression""" frame = frame.copy() frame.columns = list(map(lambda x: re.sub(r'[^\w]', '', str(x)),frame.columns)) frame = frame.applymap(convert_to_string) selects = [] for idx, series in frame.iterrows(): select = "SELECT " series_items = list(series.to_dict().items()) series_items = list(map(lambda x: '{1} as {0}'.format(*x),series_items)) selects.append(select + ', '.join(series_items)) return '\nUNION\n'.join(selects) def excel_float_to_date(flt): """Convert Excel float values to datetime format""" if isinstance(flt, (datetime, date, np.datetime64)): return flt assert isinstance(flt, (float, int)), 'Value must by float or int object' if pd.isnull(flt): return pd.NaT days = int(np.trunc(flt)) flt -= days flt *= 24*60*60 seconds = int(np.round(flt, 0)) base = datetime(1899, 12, 31, 0, 0) return base + timedelta(days, seconds) def assess_type_map(key): """Dummy for type_map's use remaining_logs.""" atm = {'CA': 'Comprehensive Assessment', 'HRA': 'HRA', 'IBS': 'IBS (MLTSS)', 'TA': 'Triggering Assessment', 'PA': 'Comprehensive Assessment'} return atm[key] def category_icp(key): """Dummy for type_map's use remaining_logs.""" cat = {'init': 'Initial', 'reass': 'Reassessment', 'upd': 'Update'} key = re.sub(r'\s', '', key.lower()) key_match = re.compile(r'init|reass|upd', re.IGNORECASE) matched = key_match.search(key) if matched: return cat[matched[0]] return None def category_ict(key): """Dummy for type_map's use remaining_logs.""" cat = {'ICT Summary': 'ICT Summary'} return cat[key] def type_map(log, key): """Used for column setup in remaining_logs""" types = {'Assess': assess_type_map, 'ICP': category_icp, 'ICT': category_ict} return types[log](key) def split_on_col_values(frame, col): """Splits DataFrame object on a columns unique values.""" values = frame[col].unique() return {str(val): frame[frame[col] == val] for val in values} def col_count(frame, col, **kwargs): """Get counts for unique items in DataFrame.""" return frame[col].reset_index().groupby(col, **kwargs).count() </code></pre> <p>Any thoughts at all, or help; much appreciated. You may see some of my comments in the code above which were some recent/thoughts attempts of mine; such as for the 'iterating through multiple files' functionality.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-20T19:40:27.370", "Id": "215866", "Score": "2", "Tags": [ "python", "pandas", "selenium" ], "Title": "Python, Selenium, Pandas project; for populating web form page on loop" }
215866
<p>This is also on github: <a href="https://github.com/theypsilon/getters-by-type-rs" rel="nofollow noreferrer">https://github.com/theypsilon/getters-by-type-rs</a></p> <pre><code>#[proc_macro_derive(GettersByType)] pub fn getters_by_type(input: TokenStream) -&gt; TokenStream { ImplContext::new(input, "GettersByType", false).transform_ast() } #[proc_macro_derive(GettersMutByType)] pub fn getters_mut_by_type(input: TokenStream) -&gt; TokenStream { ImplContext::new(input, "GettersByMutType", true).transform_ast() } struct ImplContext { ast: syn::DeriveInput, derive_name: &amp;'static str, with_mutability: bool, } impl ImplContext { fn new(input: TokenStream, derive_name: &amp;'static str, with_mutability: bool) -&gt; ImplContext { ImplContext { ast: syn::parse(input).expect("Could not parse AST."), derive_name, with_mutability, } } fn transform_ast(&amp;self) -&gt; TokenStream { let fields_by_type = match self.ast.data { syn::Data::Struct(ref class) =&gt; self.read_fields(&amp;class.fields), _ =&gt; panic!( "The type '{}' is not a struct but tries to derive '{}' which can only be used on structs.", self.ast.ident, self.derive_name ), }; let mut methods = Vec::&lt;TokenTree&gt;::new(); for (type_pieces, fields_sharing_type) in fields_by_type.into_iter() { let return_type = MethodReturnType { ty: fields_sharing_type.ty, name: make_type_name_from_type_pieces(type_pieces), }; methods.extend(self.make_method_tokens("get_fields", &amp;return_type, false, fields_sharing_type.immutable_fields)); if self.with_mutability { methods.extend(self.make_method_tokens("get_mut_fields", &amp;return_type, true, fields_sharing_type.mutable_fields)); } } let (ty, generics) = (&amp;self.ast.ident, &amp;self.ast.generics); let (impl_generics, ty_generics, where_clause) = generics.split_for_impl(); let tokens = quote! { impl #impl_generics #ty #ty_generics #where_clause { #(#methods) * } }; tokens.into() } fn read_fields&lt;'a&gt;(&amp;self, fields: &amp;'a syn::Fields) -&gt; HashMap&lt;Vec&lt;TypePart&lt;'a&gt;&gt;, FieldsSharingType&lt;'a&gt;&gt; { let mut fields_by_type = HashMap::&lt;Vec&lt;TypePart&gt;, FieldsSharingType&gt;::new(); for field in fields.iter() { if let Some(ref ident) = field.ident { let info = get_info_from_type(&amp;field.ty); match make_idents_from_type(&amp;field.ty) { Ok(type_pieces) =&gt; { let fields_by_type = fields_by_type.entry(type_pieces).or_insert_with(|| FieldsSharingType::new(info.ty)); if info.is_mutable &amp;&amp; self.with_mutability { fields_by_type.mutable_fields.push(ident); } fields_by_type.immutable_fields.push(ident); } Err(err) =&gt; { eprintln!("[WARNING::{}] Field '{}' of struct '{}' not covered because: {}", self.derive_name, ident, self.ast.ident, err); } } } } fields_by_type } fn make_method_tokens(&amp;self, method_prefix: &amp;str, return_type: &amp;MethodReturnType, mutability: bool, field_idents: Vec&lt;&amp;syn::Ident&gt;) -&gt; proc_macro2::TokenStream { let count = field_idents.len(); let method_name = syn::Ident::new(&amp;format!("{}_{}", method_prefix, return_type.name), Span::call_site()); let (vis, return_type) = (&amp;self.ast.vis, &amp;return_type.ty); if mutability { quote! { #vis fn #method_name(&amp;mut self) -&gt; [&amp;mut #return_type; #count] { [#(&amp;mut self.#field_idents),*] } } } else { quote! { #vis fn #method_name(&amp;self) -&gt; [&amp;#return_type; #count] { [#(&amp;self.#field_idents),*] } } } } } struct MethodReturnType&lt;'a&gt; { ty: &amp;'a syn::Type, name: String, } struct FieldsSharingType&lt;'a&gt; { immutable_fields: Vec&lt;&amp;'a syn::Ident&gt;, mutable_fields: Vec&lt;&amp;'a syn::Ident&gt;, ty: &amp;'a syn::Type, } impl&lt;'a&gt; FieldsSharingType&lt;'a&gt; { fn new(ty: &amp;'a syn::Type) -&gt; FieldsSharingType { FieldsSharingType { immutable_fields: vec![], mutable_fields: vec![], ty, } } } struct TypeInfo&lt;'a&gt; { is_mutable: bool, ty: &amp;'a syn::Type, } #[derive(Hash, PartialEq, Eq)] enum TypePart&lt;'a&gt; { Ident(&amp;'a syn::Ident), Integer(u64), Separator(&amp;'static str), } impl&lt;'a&gt; TypePart&lt;'a&gt; { fn to_string(&amp;self) -&gt; String { match self { TypePart::Ident(i) =&gt; i.to_string(), TypePart::Separator(s) =&gt; s.to_string(), TypePart::Integer(i) =&gt; i.to_string(), } } } fn get_info_from_type(ty: &amp;syn::Type) -&gt; TypeInfo { let (ty, is_mutable) = match ty { syn::Type::Reference(ref reference) =&gt; (&amp;*reference.elem, reference.mutability.is_some()), _ =&gt; (ty, true), }; TypeInfo { is_mutable, ty } } fn make_idents_from_type&lt;'a&gt;(ty: &amp;'a syn::Type) -&gt; Result&lt;Vec&lt;TypePart&lt;'a&gt;&gt;, &amp;'static str&gt; { let mut type_pieces = Vec::&lt;TypePart&lt;'a&gt;&gt;::with_capacity(8); fill_type_pieces_from_type(&amp;mut type_pieces, ty)?; Ok(type_pieces) } fn fill_type_pieces_from_type&lt;'a&gt;(type_pieces: &amp;mut Vec&lt;TypePart&lt;'a&gt;&gt;, ty: &amp;'a syn::Type) -&gt; Result&lt;(), &amp;'static str&gt; { match ty { syn::Type::Path(ref path) =&gt; fill_type_pieces_from_type_path(type_pieces, &amp;path.path), syn::Type::Reference(ref reference) =&gt; fill_type_pieces_from_type(type_pieces, &amp;reference.elem), syn::Type::BareFn(ref function) =&gt; { type_pieces.push(TypePart::Separator("fn(")); fill_type_pieces_from_array_of_inputs(type_pieces, &amp;function.inputs, ",", |type_pieces, arg| fill_type_pieces_from_type(type_pieces, &amp;arg.ty))?; type_pieces.push(TypePart::Separator(")")); fill_type_pieces_from_return_type(type_pieces, &amp;function.output)?; Ok(()) } syn::Type::Slice(slice) =&gt; { type_pieces.push(TypePart::Separator("[")); fill_type_pieces_from_type(type_pieces, &amp;slice.elem)?; type_pieces.push(TypePart::Separator("]")); Ok(()) } syn::Type::Array(array) =&gt; { type_pieces.push(TypePart::Separator("[")); fill_type_pieces_from_type(type_pieces, &amp;array.elem)?; type_pieces.push(TypePart::Separator(";")); match &amp;array.len { syn::Expr::Lit(lit) =&gt; match &amp;lit.lit { syn::Lit::Int(int) =&gt; type_pieces.push(TypePart::Integer(int.value())), _ =&gt; return Err("syn::Lit::* are not implemented yet."), }, _ =&gt; return Err("syn::Expr::* are not implemented yet."), } type_pieces.push(TypePart::Separator("]")); Ok(()) } syn::Type::Tuple(tuple) =&gt; { type_pieces.push(TypePart::Separator("(")); fill_type_pieces_from_array_of_inputs(type_pieces, &amp;tuple.elems, ",", fill_type_pieces_from_type)?; type_pieces.push(TypePart::Separator(")")); Ok(()) } syn::Type::Paren(paren) =&gt; { type_pieces.push(TypePart::Separator("(")); fill_type_pieces_from_type(type_pieces, &amp;paren.elem)?; type_pieces.push(TypePart::Separator(")")); Ok(()) } syn::Type::Ptr(ptr) =&gt; { type_pieces.push(TypePart::Separator("ptr_")); if ptr.const_token.is_some() { type_pieces.push(TypePart::Separator("const_")); } if ptr.mutability.is_some() { type_pieces.push(TypePart::Separator("mut_")); } fill_type_pieces_from_type(type_pieces, &amp;ptr.elem)?; Ok(()) } syn::Type::ImplTrait(_) =&gt; Err("syn::Type::ImplTrait can not be implemented."), // ImplTrait is not valid outside of functions and inherent return types, so can't be implemented. syn::Type::TraitObject(trait_object) =&gt; { if trait_object.dyn_token.is_some() { type_pieces.push(TypePart::Separator("dyn_")); } fill_type_pieces_from_array_of_inputs(type_pieces, &amp;trait_object.bounds, "+", |type_pieces, bound| match bound { syn::TypeParamBound::Trait(trait_bound) =&gt; fill_type_pieces_from_type_path(type_pieces, &amp;trait_bound.path), syn::TypeParamBound::Lifetime(_) =&gt; Ok(()), }) } syn::Type::Never(_) =&gt; Err("syn::Type::Never is not implemented yet."), syn::Type::Group(_) =&gt; Err("syn::Type::Group is not implemented yet."), syn::Type::Infer(_) =&gt; Err("syn::Type::Infer is not implemented yet."), syn::Type::Macro(_) =&gt; Err("syn::Type::Macro is not implemented yet."), syn::Type::Verbatim(_) =&gt; Err("syn::Type::Verbatim is not implemented yet."), } } fn fill_type_pieces_from_type_path&lt;'a&gt;(type_pieces: &amp;mut Vec&lt;TypePart&lt;'a&gt;&gt;, path: &amp;'a syn::Path) -&gt; Result&lt;(), &amp;'static str&gt; { for segment in path.segments.iter() { type_pieces.push(TypePart::Ident(&amp;segment.ident)); fill_type_pieces_from_path_arguments(type_pieces, &amp;segment.arguments)?; } Ok(()) } fn fill_type_pieces_from_path_arguments&lt;'a&gt;(type_pieces: &amp;mut Vec&lt;TypePart&lt;'a&gt;&gt;, arguments: &amp;'a syn::PathArguments) -&gt; Result&lt;(), &amp;'static str&gt; { match arguments { syn::PathArguments::AngleBracketed(ref angle) =&gt; { type_pieces.push(TypePart::Separator("&lt;")); fill_type_pieces_from_array_of_inputs(type_pieces, &amp;angle.args, ",", |type_pieces, arg| match arg { syn::GenericArgument::Type(ref ty) =&gt; fill_type_pieces_from_type(type_pieces, ty), syn::GenericArgument::Lifetime(_) =&gt; Ok(()), syn::GenericArgument::Binding(_) =&gt; Ok(()), syn::GenericArgument::Constraint(_) =&gt; Ok(()), syn::GenericArgument::Const(_) =&gt; Ok(()), })?; type_pieces.push(TypePart::Separator("&gt;")); } syn::PathArguments::None =&gt; {} syn::PathArguments::Parenthesized(ref paren) =&gt; { type_pieces.push(TypePart::Separator("(")); fill_type_pieces_from_array_of_inputs(type_pieces, &amp;paren.inputs, ",", fill_type_pieces_from_type)?; type_pieces.push(TypePart::Separator(")")); fill_type_pieces_from_return_type(type_pieces, &amp;paren.output)?; } } Ok(()) } fn fill_type_pieces_from_return_type&lt;'a&gt;(type_pieces: &amp;mut Vec&lt;TypePart&lt;'a&gt;&gt;, output: &amp;'a syn::ReturnType) -&gt; Result&lt;(), &amp;'static str&gt; { match output { syn::ReturnType::Default =&gt; Ok(()), syn::ReturnType::Type(_, ref arg) =&gt; fill_type_pieces_from_type(type_pieces, &amp;**arg), } } fn fill_type_pieces_from_array_of_inputs&lt;'a, T, U&gt;( type_pieces: &amp;mut Vec&lt;TypePart&lt;'a&gt;&gt;, inputs: &amp;'a syn::punctuated::Punctuated&lt;T, U&gt;, separator: &amp;'static str, action: impl Fn(&amp;mut Vec&lt;TypePart&lt;'a&gt;&gt;, &amp;'a T) -&gt; Result&lt;(), &amp;'static str&gt;, ) -&gt; Result&lt;(), &amp;'static str&gt; { if !inputs.is_empty() { for arg in inputs { action(type_pieces, arg)?; match type_pieces[type_pieces.len() - 1] { TypePart::Separator(_s) if _s == separator =&gt; {} _ =&gt; type_pieces.push(TypePart::Separator(separator)), } } match type_pieces[type_pieces.len() - 1] { TypePart::Separator(_s) if _s == separator =&gt; type_pieces.truncate(type_pieces.len() - 1), _ =&gt; {} } } Ok(()) } fn make_type_name_from_type_pieces(type_pieces: Vec&lt;TypePart&gt;) -&gt; String { type_pieces .into_iter() .map(|piece| piece.to_string()) .collect::&lt;String&gt;() .to_lowercase() .chars() .map(|c| match c { '&lt;' | '&gt;' | '(' | ')' | '[' | ']' | '-' | ',' | ';' =&gt; '_', _ =&gt; c, }) .collect() } </code></pre> <p>Can you see any way to improve it? It's my first code using the new proc_macro feature, and I don't find much examples out there.</p> <p>Thanks!</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-13T13:29:02.510", "Id": "492760", "Score": "0", "body": "Did you ever update this to use proc_macro2 ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-06T14:08:24.760", "Id": "507069", "Score": "0", "body": "Kind of @gerhardd. I made this other version: https://github.com/theypsilon/arraygen" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-20T19:55:37.383", "Id": "215869", "Score": "1", "Tags": [ "rust" ], "Title": "proc_macro derive for generatting getters in a struct for each type it contains" }
215869
<p>I wrote a function to convert an unsigned integer number given by a string from one base to another. Can you please give me any tips to improve it?</p> <pre><code>#include &lt;assert.h&gt; #include &lt;stdio.h&gt; #include &lt;string.h&gt; #include &lt;stdlib.h&gt; #include &lt;errno.h&gt; #include &lt;limits.h&gt; #define MAX_BASE() strlen(alphabet) static char const *alphabet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; static unsigned int ullong2str(char [], unsigned long long, unsigned int); static unsigned long long str2ullong(char const [], unsigned int); static char *convertToNewBase(char const [], unsigned int, unsigned int); static long indexOf(char const [], char); static unsigned long long power(unsigned int, unsigned int); static void reverse(char []); int main(void) { char *decimal = "28697"; char *binary = convertToNewBase(decimal, 10, 2); printf("%s (base 10) = %s (base 2)\n", decimal, binary); perror(NULL); free(binary); } /* =============== char *convertToNewBase(char [], unsigned int, unsigned int); The function converts an unsigned integer number from the source base to destination base. The function allocates a buffer of length large enough to store the result and returns it. If an error occurs the function returns NULL. =============== */ char *convertToNewBase(char const s[], unsigned int src, unsigned int dest) { assert(s); assert(src &gt;= 2 &amp;&amp; src &lt;= MAX_BASE()); assert(dest &gt;= 2 &amp;&amp; dest &lt;= MAX_BASE()); errno = 0; unsigned long long const n = str2ullong(s, src); if (errno != 0) return NULL; unsigned int const resultLength = ullong2str(NULL, n, dest); char *result = calloc(resultLength + 1, 1); if (result == NULL) return NULL; ullong2str(result, n, dest); return result; } /* =============== unsigned long long ullong2str(char [], unsigned long long, unsigned int); The function converts an unsigned integer value to a null-terminated string using the specified base and stores the result in the array given by the first parameter. It assumes that size of the array is large enough to store the result. The function returns length of the result string. If the first parameter is NULL nothing is written, however the return value is still calculated and returned. =============== */ unsigned int ullong2str(char out[], unsigned long long n, unsigned int base) { assert(base &gt;= 2 &amp;&amp; base &lt;= MAX_BASE()); unsigned int i = 0; do { if (out != NULL) out[i] = alphabet[n % base]; n /= base; i++; } while (n); if (out != NULL) { out[i] = '\0'; reverse(out); } return i; } /* =============== unsigned long long str2ullong(char const [], base_t base); If no errors occurs the function returns an unsigned integer value corresponding to the contents of the input string. If the result is too large the function returns 0 and sets errno to ERANGE [1]. If the arguments is invalid the function return 0 and sets errno to EINVAL [2]. 1. str2llong("18446744073709551616", 10) in most cases returns 0 and sets errno to ERANGE, since 18446744073709551616 is greater than ULLONG_MAX (in most cases). 2. str2llong("10191", 2) returns 0 and sets errno to EINVAL, since '9' is not allowed in a binary number. =============== */ unsigned long long str2ullong(char const s[], unsigned int base) { assert(s != NULL); assert(base &gt;= 2 &amp;&amp; base &lt;= MAX_BASE()); unsigned long long r = 0; for (unsigned int i = strlen(s), j = 0; i-- &gt; 0; j++) { long const index = indexOf(alphabet, s[i]); if (index == -1 || index &gt;= (int) base) { errno = EINVAL; return 0; } unsigned long long const t = (unsigned long long) index * power(base, j); if (r &gt; ULLONG_MAX - t) { errno = ERANGE; return 0; } r += t; } return r; } /* =============== unsigned long long power(unsigned int, unsigned int); If no errors occurs the function returns aⁿ. If the result is too large the function returns 0 and sets errno to ERANGE. =============== */ unsigned long long power(unsigned int a, unsigned int n) { unsigned long long r = 1; while (n--) { /* If a * r would overflow… */ if (a &gt; ULLONG_MAX / r) { errno = ERANGE; return 0; } r *= a; } return r; } /* =============== long indexOf(char const [], char); The function return index of the first occurence of the character in the string. If the character is not found returns -1. =============== */ long indexOf(char const s[], char c) { assert(s); for (size_t i = 0; s[i]; i++) if (s[i] == c) return (long) i; return -1; } /* =============== void reverse(char []); The function reverses the input string. =============== */ void reverse(char s[]) { assert(s); assert(strlen(s)); for (unsigned int i = 0, j = strlen(s) - 1; i &lt; j; i++, j--) { char const tmp = s[i]; s[i] = s[j]; s[j] = tmp; } } </code></pre>
[]
[ { "body": "<ul>\n<li><p><code>power</code> is suboptimal. Check out <a href=\"https://en.wikipedia.org/wiki/Exponentiation_by_squaring\" rel=\"nofollow noreferrer\">exponentiation by squaring</a>. That said, I would rather avoid <code>power</code> completely. Consider instead</p>\n\n<pre><code> unsigned long long power_factor = 1;\n\n for (unsigned int i = strlen(s), j = 0; i-- &gt; 0; j++) {\n ....\n unsigned long long const t = index * power_factor;\n power_factor *= base;\n }\n</code></pre></li>\n<li><p><code>indexOf</code> may signal the failure via <code>errno</code>, just like your other functions. That would allow it to return an unsigned value, thus getting rid of the unpleasant <code>(unsigned long long) index</code> cast.</p></li>\n<li><p>Dynamic allocation of the resulting string (and the dry run to determine the required length) seem unnecessary. The longest possible result is obtained with base 2, and the resulting length is limited by <code>sizeof(unsigned long long) * CHAR_BITS</code> (realistically 64).</p></li>\n<li><p>Consider filling <code>out</code> buffer from right to left, to avoid the reversal.</p>\n\n<p>EDIT: (sketchy) filling <code>out</code> from right to left:</p>\n\n<pre><code>int main()\n{\n ....\n char out[sizeof(unsigned long long) * CHAR_BITS + 1];\n char * result = ullong2str(out + sizeof(out), n, dest);\n ....\n}\n\nchar * ullong2str(char * end, unsigned long long n, unsigned int base)\n{\n *--end = 0;\n do {\n *--end = alphabet[n % base];\n n /= base;\n }\n return end;\n}\n</code></pre></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-20T21:56:03.510", "Id": "417722", "Score": "0", "body": "Thanks you very much for your answer! It is very helpful. But about the second point... it is not an error, when `indexOf` returns -1, is it?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-20T21:58:52.533", "Id": "417723", "Score": "0", "body": "And if I will fill `out` buffer from right to left, how I can get index of the most right position?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-20T22:00:44.357", "Id": "417724", "Score": "0", "body": "@eanmos Return it! If the buffer is statically allocated, you may return a pointer into the midst of it. Let me know if I am not clear, and I'll add an example." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-20T22:03:30.630", "Id": "417725", "Score": "0", "body": "Oh, I'll glad if you add an example, please)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-20T22:11:01.063", "Id": "417726", "Score": "0", "body": "I mean that I need get length of the number in any case. For example, length of 1294 is 4, so I will fill `out` buffer from 3 to 0 inclusive." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-20T21:13:01.750", "Id": "215875", "ParentId": "215874", "Score": "2" } }, { "body": "<p>When you make your alphabet <code>static</code> there is no need to declare the variable as a pointer and then assigning it an actual pointer to a string in an anonymous array (which is also static).</p>\n\n<pre><code>#define MAX_BASE() strlen(alphabet)\nstatic char const *alphabet = \"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ\";\n</code></pre>\n\n<p>You can as well declare the alphabet explicitly as an array:</p>\n\n<pre><code>static char const alphabet[] = \"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ\";\n</code></pre>\n\n<p>and then you don't need to scan it with <code>strlen</code> each time you invoke the conversion, because the size of the array is constant and known at compile time:</p>\n\n<pre><code>#define MAX_BASE() (sizeof alphabet - 1)\n</code></pre>\n\n<p>However, if you need a variable-length alphabet, then you need to keep two variables, one <code>const char*</code> for the alphabet itself, and one <code>int</code> to store its length. Then you can re-assign the alphabet at run-time, but scan it with <code>strlen()</code> just once on each assignment instead of on each use.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-21T00:28:54.390", "Id": "215889", "ParentId": "215874", "Score": "2" } } ]
{ "AcceptedAnswerId": "215875", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-20T20:31:30.183", "Id": "215874", "Score": "1", "Tags": [ "c", "number-systems" ], "Title": "Convert a number from one base to another" }
215874
<p>I have a script for zipping up old files. I know using Windows Compression isn't ideal, so I will make the script run using 7-Zip later on. For now though, I just want see how I can make my current script better. By better I mean, how could I make this code cleaner or neater? How could I make the script more effective? Here is the code:</p> <pre><code>Write-Output("Beginning script....") #File path of file to be cleaned $File_Path = "C:\Users\Administrator\Downloads\Testing\*" #Location of ZIP file $Send_To = "C:\Users\Administrator\Documents\ARCHIVE2" #Location of old files before being zipped $Old_Files = "C:\Users\Administrator\Documents\OLD_FILES" #Time frame for files $Days = "-65" $now = Get-Date $last_Write = $now.AddDays($Days) #Filtering files according to time parameters $Filter = Get-ChildItem -Path $File_Path | Where-Object { $_.LastWriteTime -lt $last_Write } #Moving old files to destination folder if (!$Filter){ Write-Host "Variable is null" } else{ Move-Item $Filter -Destination $Old_Files Write-Output("Moving files....") } #Compressing destination folder if there is folders in $Old_Files folder if (!(Test-Path $Old_Files)) { Write-Output("No old files found") } else{ Compress-Archive -Path $Old_Files -DestinationPath $Send_To -Update Write-Output("Old files zipped!") Remove-Item -Path $Old_Files -Force } Write-Output("Script is finished") </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-21T15:22:42.520", "Id": "417815", "Score": "1", "body": "Omit the `#Moving old files to destination folder` part. `Compress-Archive` accepts pipeline input (_ByPropertyName_) instead of `-Path`/`-LiteralPath`. Use `$Filter | Compress-Archive -DestinationPath $Send_To -Update -CompressionLevel Optimal`. For planned `7-Zip`, use its `@{listfile}` facility; create an auxiliary list file from `$Filter.FullName` using `UTF8` encoding (`7-Zip`'s default)." } ]
[ { "body": "<p>I spent several weeks writing and tuning <a href=\"https://github.com/mossrich/PowershellRecipes/blob/master/ArchiveOldLogs.ps1\" rel=\"nofollow noreferrer\">a script</a> that moves old files to a timestamped Zip file. Here are a few guidelines I learned that may help: </p>\n\n<p>1) Move variables into script parameters so they can be changed at runtime without editing the file: </p>\n\n<pre><code>Param($File_Path = \"C:\\Users\\Administrator\\Downloads\\Testing\\*\", #File path of file to be cleaned \n $Send_To = \"C:\\Users\\Administrator\\Documents\\ARCHIVE2\", #Location of ZIP file\n $Old_Files = \"C:\\Users\\Administrator\\Documents\\OLD_FILES\", #Location of old files before being zipped\n $Days = \"-65\"\n)\n</code></pre>\n\n<p>2) Filter usually means 'criteria for filtering a list'. Calling the list of files <code>$Filter</code> is misleading. <code>$FilesToZip</code> might be a better variable name. </p>\n\n<p>3) There are lots of reasons a file can't be moved or zipped (in use, doesn't exist, no read/write permission, etc.) You should have a try-catch block around Compress-Archive to account for this, and fail or proceed gracefully. Using ZipFileExtensions, an error created an unusable file until it was finalized. Compress-Archive may be more robust, but there are still chances for failure (try pulling your network cable while creating a large archive of files on your LAN). </p>\n\n<p>4) There's no need for an intermediate folder, and it creates more opportunities for failure. You can just compress the file into the zip and delete on success. </p>\n\n<p>5) The message 'No old files found' is misleading. Reading it, I would think that there were no files found matching the age criteria, when it really means the intermediate folder doesn't exist. </p>\n\n<p>6) Don't you need a .Zip file name for the -DestinationPath? </p>\n\n<p>7) <code>Write-Output</code> is usually used for return values rather than messages. Write-verbose, or Write-Host are more appropriate for status messages. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-03T21:54:38.250", "Id": "219677", "ParentId": "215876", "Score": "2" } } ]
{ "AcceptedAnswerId": "219677", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-20T21:14:31.507", "Id": "215876", "Score": "4", "Tags": [ "file-system", "powershell" ], "Title": "Powershell script for zipping up old files" }
215876
<p>I have written the following function to be a general "error logging" solution for my Windows API projects. Basically, given a Windows system error code (a la <a href="https://msdn.microsoft.com/en-us/library/windows/desktop/ms679360(v=vs.85).aspx" rel="noreferrer"><code>GetLastError()</code></a>), it will log the error message into a file:</p> <pre><code>#include &lt;Windows.h&gt; #include &lt;strsafe.h&gt; // MAX_PATH for file name, 12 for max signed int in base 10 (-2147483648), 20 for datetime string, 5 for brackets/colon/spaces #define MAX_DFL_LENGTH (MAX_PATH + 37) // So that it can be used as a callback if desired typedef VOID(CALLBACK *ERRORPROC)(DWORD, WCHAR *, INT, HANDLE, BOOL); /** * Logs an error message that occurred elsewhere in the program. * PARAMETERS: * dwError - The system error code to process. * wszFileName - The name of the file in which the error occurred (pass __FILEW__) * nLine - The line at which the error was detected (pass __LINE__) * hOutFile - A handle to an already open file for writing the error message to. * fRecoverable - If true, this error is recoverable; return to the calling code. If false, exit after logging the error. */ VOID CALLBACK ErrorProc( DWORD dwError, WCHAR *wszFileName, INT nLine, HANDLE hOutFile, BOOL fRecoverable ) { LPWSTR lpMsgBuf; DWORD dwWritten; HRESULT hr; UINT uLen; SYSTEMTIME st; WCHAR wszDateFileLine[MAX_DFL_LENGTH]; CONST WCHAR *wRecovMsg[2] = { L" Not recoverable, exiting program.\r\n", L" Recoverable; continuing execution...\r\n" }; (VOID)FormatMessageW( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, dwError, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPVOID)&amp;lpMsgBuf, 0, NULL ); GetLocalTime(&amp;st); StringCchPrintfW( wszDateFileLine, MAX_DFL_LENGTH, L"[%.4hu-%.2hu-%.2huT%.2hu:%.2hu:%.2hu %s:%d] ", st.wYear, st.wMonth, st.wDay, st.wHour, st.wMinute, st.wSecond, wszFileName, nLine ); SetFilePointer(hOutFile, 0, NULL, FILE_END); hr = StringCbLengthW(wszDateFileLine, (MAX_DFL_LENGTH) * sizeof(WCHAR), &amp;uLen); if (SUCCEEDED(hr)) { WriteFile(hOutFile, wszDateFileLine, uLen, &amp;dwWritten, NULL); } hr = StringCbLengthW(lpMsgBuf, STRSAFE_MAX_CCH * sizeof(WCHAR), &amp;uLen); if (SUCCEEDED(hr)) { // Length - 2 WCHARs to not write out the \r\n at the end of the error message. WriteFile(hOutFile, lpMsgBuf, uLen - (2 * sizeof(WCHAR)), &amp;dwWritten, NULL); } WriteFile(hOutFile, wRecovMsg[!!fRecoverable], (36 + (!!fRecoverable * 3)) * sizeof(WCHAR), &amp;dwWritten, NULL); LocalFree((HLOCAL)lpMsgBuf); if (FALSE == fRecoverable) { ExitProcess(dwError); } } </code></pre> <p>While this historically worked well enough for my personal projects, I am wondering if there are any modifications I should make to the presentation or operation of this function before suggesting its addition to a larger Windows project with an entire team of developers.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-25T21:21:50.070", "Id": "418325", "Score": "1", "body": "instead several calls to `WriteFile` - first format buffer and once call `WriteFile`. the `SetFilePointer` never need at all. in case log file - open file with `FILE_APPEND_DATA` access. the win32 errors sometime ambiguous, frequently it (not injective) derived from *NTSTATUS*. you can query last status via `RtlGetLastNtStatus()` and then check are it converted to the same `dwError` via `RtlNtStatusToDosError[NoTeb]` if yes - more informative save status and it related error message" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-20T21:36:08.557", "Id": "215879", "Score": "7", "Tags": [ "c", "error-handling", "winapi" ], "Title": "Error handling function (Win32/C)" }
215879
<p>The following code works fine, however, I'm trying to simplify it. I wrote it but I'm a beginner PHP coder. I can see that most probably the use of a function or class would be better... or anything to make it more concise in terms of PHP.</p> <p>This is WordPress PHP code. I can't do it in a loop. You see how repetitive it is. The first three elements just have different variables to be fed via PHP. The last two have slightly different HTML markup.</p> <pre><code>&lt;div class="row mb-3"&gt; &lt;!-- beginning of TOP row --&gt; &lt;div class="col-xs-12 col-sm-6 col-md-4 tile pr-0 mb-3"&gt; &lt;?php $post_object = get_field('top_left_tile'); if( $post_object ): // override $post $post = $post_object; setup_postdata( $post ); $img = get_the_post_thumbnail_url($post_id, 'frontTile'); ?&gt; &lt;a class="tile-text" href="&lt;?php the_field('tile_url'); ?&gt;"&gt; &lt;div class="img-overlay h-100"&gt; &lt;?php if ( $img ) { ?&gt; &lt;img src="&lt;?php echo $img; ?&gt;" /&gt; &lt;?php } else { ?&gt; &lt;img src="https://via.placeholder.com/500x500" /&gt; &lt;?php } ?&gt; &lt;/div&gt; &lt;div class="d-flex align-items-start flex-column tile-overlay"&gt; &lt;div class="mb-auto p-2"&gt; &lt;h5&gt;&lt;span class="tag pr-2 pl-2"&gt; &lt;?php the_field('tile_category'); ?&gt; &lt;/span&gt;&lt;/h5&gt; &lt;/div&gt; &lt;div class="p-2 bg-secondary"&gt; &lt;h3 class="p-2"&gt; &lt;?php the_title(); ?&gt; &lt;/h3&gt; &lt;p class="p-2"&gt; &lt;?php echo $post-&gt;post_content; ?&gt; &lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;/a&gt; &lt;?php wp_reset_postdata(); // IMPORTANT - reset the $post™™£ object so the rest of the page works correctly ?&gt; &lt;?php endif; ?&gt; &lt;/div&gt; &lt;!-- end of top left --&gt; &lt;div class="col-xs-12 col-sm-6 col-md-4 tile pr-0 mb-3"&gt; &lt;!-- beginning of top centre --&gt; &lt;?php $post_object = get_field('top_centre_tile'); if( $post_object ): // override $post $post = $post_object; setup_postdata( $post ); $img = get_the_post_thumbnail_url($post_id, 'frontTile'); ?&gt; &lt;a class="tile-text" href="&lt;?php the_field('tile_link'); ?&gt;"&gt; &lt;div class="img-overlay h-100"&gt; &lt;?php if ( $img ) { ?&gt; &lt;img src="&lt;?php echo $img; ?&gt;" /&gt; &lt;?php } else { ?&gt; &lt;img src="https://via.placeholder.com/500x500" /&gt; &lt;?php } ?&gt; &lt;/div&gt; &lt;div class="d-flex align-items-start flex-column tile-overlay"&gt; &lt;div class="mb-auto p-2"&gt; &lt;h5&gt;&lt;span class="tag pr-2 pl-2"&gt; &lt;?php the_field('tile_category'); ?&gt; &lt;/span&gt;&lt;/h5&gt; &lt;/div&gt; &lt;div class="p-2 bg-secondary"&gt; &lt;h3 class="p-2"&gt; &lt;?php the_title(); ?&gt; &lt;/h3&gt; &lt;p class="p-2"&gt; &lt;?php echo $post-&gt;post_content; ?&gt; &lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;/a&gt; &lt;?php wp_reset_postdata(); // IMPORTANT - reset the $post™™£ object so the rest of the page works correctly ?&gt; &lt;?php endif; ?&gt; &lt;/div&gt; &lt;!-- end of top centre --&gt; &lt;div class="col-xs-12 col-sm-6 col-md-4 tile pr-0 mb-3"&gt; &lt;!-- beginning of top right --&gt; &lt;?php $post_object = get_field('top_right_tile'); if( $post_object ): // override $post $post = $post_object; setup_postdata( $post ); $img = get_the_post_thumbnail_url($post_id, 'frontTile'); ?&gt; &lt;a class="tile-text" href="&lt;?php the_field('tile_link'); ?&gt;"&gt; &lt;div class="img-overlay h-100"&gt; &lt;?php if ( $img ) { ?&gt; &lt;img src="&lt;?php echo $img; ?&gt;" /&gt; &lt;?php } else { ?&gt; &lt;img src="https://via.placeholder.com/500x500" /&gt; &lt;?php } ?&gt; &lt;/div&gt; &lt;div class="d-flex align-items-start flex-column tile-overlay"&gt; &lt;div class="mb-auto p-2"&gt; &lt;h5&gt;&lt;span class="tag pr-2 pl-2"&gt; &lt;?php the_field('tile_category'); ?&gt; &lt;/span&gt;&lt;/h5&gt; &lt;/div&gt; &lt;div class="p-2 bg-secondary"&gt; &lt;h3 class="p-2"&gt; &lt;?php the_title(); ?&gt; &lt;/h3&gt; &lt;p class="p-2"&gt; &lt;?php echo $post-&gt;post_content; ?&gt; &lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;/a&gt; &lt;?php wp_reset_postdata(); // IMPORTANT - reset the $post™™£ object so the rest of the page works correctly ?&gt; &lt;?php endif; ?&gt; &lt;/div&gt; &lt;!-- end of top right --&gt; &lt;/div&gt; &lt;!-- end of TOP row --&gt; &lt;div class="row mb-3"&gt; &lt;!-- beginning of middle row --&gt; &lt;div class="col-xs-12 col-sm-6 col-md-6 mb-3"&gt; &lt;!-- beginning of middle left --&gt; &lt;?php $post_object = get_field('middle_left_tile'); if( $post_object ): // override $post $post = $post_object; setup_postdata( $post ); $img = get_the_post_thumbnail_url($post_id, 'frontTilePort'); ?&gt; &lt;a class="tile-text" href="&lt;?php the_field('tile_link'); ?&gt;"&gt; &lt;div class="row text-white"&gt; &lt;div class="col-5 mr-0 pr-0 d-none d-md-block"&gt; &lt;img class="" src="&lt;?php echo $img; ?&gt;" /&gt; &lt;/div&gt; &lt;div class="col ml-0 bg-secondary"&gt; &lt;h5 class="py-2"&gt;&lt;span class="tag px-2"&gt; &lt;?php the_field('tile_category'); ?&gt; &lt;/span&gt;&lt;/h5&gt; &lt;div class="p-1"&gt; &lt;h5&gt; &lt;?php the_title(); ?&gt; &lt;/h5&gt; &lt;p&gt; &lt;?php echo $post-&gt;post_content; ?&gt; &lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/a&gt; &lt;?php wp_reset_postdata(); // IMPORTANT - reset the $post™™£ object so the rest of the page works correctly ?&gt; &lt;?php endif; ?&gt; &lt;/div&gt; &lt;!-- end of middle left --&gt; &lt;div class="col-xs-12 col-sm-6 col-md-6 mb-3"&gt; &lt;!-- beginning of middle right --&gt; &lt;?php $post_object = get_field('middle_right_tile'); if( $post_object ): // override $post $post = $post_object; setup_postdata( $post ); $img = get_the_post_thumbnail_url($post_id, 'frontTilePort'); ?&gt; &lt;a class="tile-text" href="&lt;?php the_field('tile_link'); ?&gt;"&gt; &lt;div class="row text-white"&gt; &lt;div class="col-5 mr-0 pr-0 d-none d-md-block"&gt; &lt;img class="" src="&lt;?php echo $img; ?&gt;" /&gt; &lt;/div&gt; &lt;div class="col ml-0 bg-secondary"&gt; &lt;h5 class="py-2"&gt;&lt;span class="tag px-2"&gt; &lt;?php the_field('tile_category'); ?&gt; &lt;/span&gt;&lt;/h5&gt; &lt;div class="p-1"&gt; &lt;h5&gt; &lt;?php the_title(); ?&gt; &lt;/h5&gt; &lt;p&gt; &lt;?php echo $post-&gt;post_content; ?&gt; &lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/a&gt; &lt;?php wp_reset_postdata(); // IMPORTANT - reset the $post™™£ object so the rest of the page works correctly ?&gt; &lt;?php endif; ?&gt; &lt;/div&gt; &lt;!-- end of middle right --&gt; &lt;/div&gt; &lt;!-- end of middle row --&gt; </code></pre>
[]
[ { "body": "<p>There are a few ways you could handle this. One of the simpler ways would be to split it up into 2 loops - the first one handles the first 3 HTML structures and the 2nd loop handles the final 2 HTML structures.</p>\n\n<pre><code>&gt; $post_object = get_field('top_centre_tile');\n&gt; if( $post_object ): \n&gt; // override $post\n&gt; $post = $post_object;\n</code></pre>\n\n<p>Why are you clobbering the <code>$post_object</code>? You can simply name the variable <code>$post</code> and then continue using it. </p>\n\n<p>I omitted the HTML structure here for clarity. </p>\n\n<pre><code>&lt;!-- Handles the first 3 common HTML structures. --&gt;\n&lt;div class=\"row mb-3\"&gt;\n &lt;?php\n $posts = [\n 'top_left_tile',\n 'top_centre_tile',\n 'top_right_tile'\n ];\n\n foreach ($posts as $title): ?&gt;\n &lt;div class=\"col-xs-12 col-sm-6 col-md-4 tile pr-0 mb-3\"&gt;\n &lt;?php\n $post = get_field($title);\n\n if ($post): ?&gt;\n &lt;!-- common HTML structure --&gt;\n &lt;?php endif; ?&gt;\n &lt;/div&gt;\n &lt;?php endforeach; ?&gt;\n&lt;/div&gt;\n\n&lt;!-- Handles the final 2 common HTML structures. --&gt;\n&lt;div class=\"row mb-3\"&gt;\n &lt;?php\n $posts = [\n 'middle_left_tile',\n 'middle_right_tile'\n ];\n\n foreach ($posts as $title): ?&gt;\n &lt;div class=\"col-xs-12 col-sm-6 col-md-6 mb-3\"&gt;\n &lt;?php\n $post = get_field($title);\n\n if ($post): ?&gt;\n &lt;!-- common HTML structure --&gt;\n &lt;?php endif; ?&gt;\n &lt;/div&gt;\n &lt;?php endforeach; ?&gt;\n&lt;/div&gt;\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-22T15:53:54.590", "Id": "216002", "ParentId": "215881", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-20T22:11:02.250", "Id": "215881", "Score": "1", "Tags": [ "php", "wordpress" ], "Title": "Feeding PHP variables to a number of HTML elements" }
215881
<p>I'm beginning to learn about Golang and I would like to have some advice about the following program.</p> <pre><code>package main import ( "fmt" "net/http" "time" ) const BenchmarkTry = 1000 type PageBenchmark struct { url string time int64 // microseconds } func execBenchmark(url string, channel chan PageBenchmark) { totalExecTimeChan := make(chan int64, BenchmarkTry) // set size to prevent blocked goroutine totalExecTime := int64(0) // start all the goroutines for i := 0; i &lt; BenchmarkTry; i++ { go execHttpRequest(url, totalExecTimeChan) } // catch new values from totalExecTimeChan values come from execHttpRequest()) and add it to the total for i := 0; i &lt; BenchmarkTry; i++ { totalExecTime += &lt;-totalExecTimeChan // waiting to get a value from one of the goroutines started in the previous for loop } channel &lt;- PageBenchmark{url, totalExecTime / BenchmarkTry} } // exec http request and attach exec time to channel func execHttpRequest(url string, channel chan int64) { begin := time.Now() _, _ = http.Get(url) channel &lt;- time.Since(begin).Nanoseconds() / 1000000 // convert to milliseconds } func main() { sites := [...]string{ } pages := [...]string{ } benchmarkChan := make(chan PageBenchmark, len(sites)*len(pages)) // set size to prevent blocked goroutine begin := time.Now() fmt.Println("Beginning !") // start all the goroutines for site := range sites { for page := range pages { go execBenchmark(sites[site]+pages[page], benchmarkChan) } } // catch new values from benchmarkChan and "print" the PageBenchmark for i := 0; i &lt; len(sites)*len(pages); i++ { benchmark := &lt;-benchmarkChan fmt.Printf("Url : %v\nResponse Time : %d ms\n\n", benchmark.url, benchmark.time) } // print execution time fmt.Println("End.") fmt.Println(fmt.Sprintf("%d ms", time.Since(begin).Nanoseconds()/1000000)) } </code></pre> <p>Basically, I'm making HTTP requests (GET method) to multiple URLs on multiple web sites. 1000 requests by URL in this example.</p> <p>For now, I just want to start some goroutines in this order:</p> <ol> <li><p>Main: start a benchmark (goroutine) for each web site pages, get the average execution time and print it.</p></li> <li><p>Page routine: start 1000 goroutines (benchmark tries), get the execution times from a channel and store the average execution time in an other channel.</p></li> <li><p>Execute an HTTP request on the page and store the execution time in a channel.</p></li> </ol> <p>This piece of code works but there may be things I'm missing.</p> <ul> <li>Is the execution scheduling valid?</li> <li>Is it appropriate to use defined size channels here?</li> <li>Is there a better/more effective way to achieve this task?</li> </ul>
[]
[ { "body": "<p>When running your program with the <a href=\"https://blog.golang.org/race-detector\" rel=\"nofollow noreferrer\">Go race detector</a>, it found no race conditions. That's good!</p>\n\n<p>Given this, I would consider your \"execution scheduling\" valid.</p>\n\n<blockquote>\n <p>Is it appropriate to use defined-size channels here?</p>\n</blockquote>\n\n<p>Sure. In this case you make the buffer large enough such that it will not be blocked. You can read more about the difference between buffered and unbuffered channels <a href=\"https://golang.org/doc/effective_go.html#channels\" rel=\"nofollow noreferrer\">here</a>.</p>\n\n<h2>Benchmark through <a href=\"https://golang.org/pkg/testing/#hdr-Benchmarks\" rel=\"nofollow noreferrer\"><code>testing</code></a></h2>\n\n<blockquote>\n <p>Is there a better/more effective way to achieve this task?</p>\n</blockquote>\n\n<p>For benchmarking, it is recommended to use the utilities provided by the <code>testing</code> package.</p>\n\n<p>A lot of this code is boilerplate benchmarking code. With the <code>testing</code> package you can be more confident in the accuracy of your benchmarks, especially since you're using goroutines.</p>\n\n<p>(I will leave switching to the <code>testing</code> package for you.)</p>\n\n<h2>Performance bias</h2>\n\n<pre><code>sites[site]+pages[page]\n</code></pre>\n\n<p>Adding strings through the <code>+</code> operator <a href=\"https://stackoverflow.com/q/1760757/6789498\">is slow</a>. This could bias your results (ie if you have lots of very long strings), but that also depends on how many sites and pages you test with.</p>\n\n<p>Without knowledge of your full usage, it's hard to tell.</p>\n\n<h2>Accuracy</h2>\n\n<pre><code>time.Since(begin).Nanoseconds() / 1000000 // convert to milliseconds\n</code></pre>\n\n<p>I would instead use <code>.Seconds()</code>. Any variation on the scale of milliseconds would be meaningless. From testing with one site and two pages, I received response times of 10288 (10s) and 8128 ms (8s) and an end time of 30073 ms (30s).</p>\n\n<p>Rather than converting to <code>int64</code> I would keep the type as <code>float64</code>.</p>\n\n<h2>String formatting</h2>\n\n<p>With the details above:</p>\n\n<pre><code>fmt.Println(\"End.\")\nfmt.Println(fmt.Sprintf(\"%d ms\", time.Since(begin).Nanoseconds()/1000000))\n</code></pre>\n\n<p>Should instead be converted to:</p>\n\n<pre><code>fmt.Printf(\"End.\\nTotal time: %.0fs\\n\", time.Since(begin).Seconds())\n</code></pre>\n\n<p>And</p>\n\n<pre><code>fmt.Printf(\"Url : %v\\nResponse Time : %d ms\\n\\n\", benchmark.url, benchmark.time)\n</code></pre>\n\n<p>Should instead be:</p>\n\n<pre><code>fmt.Printf(\"Url: %s\\nResponse Time: %.0fs\\n\\n\", benchmark.url,\n benchmark.time)\n</code></pre>\n\n<p>(Notice I use <code>%s</code> rather than <code>%v</code>.)</p>\n\n<h2>Variable naming</h2>\n\n<p>Variables can have shorter names, especially in shorter functions where their purpose is clear.</p>\n\n<ul>\n<li><code>totalExecTimeChan</code> becomes <code>timeChan</code></li>\n<li><code>totalExecTime</code> becomes <code>time</code></li>\n<li><code>BenchmarkTry</code> becomes <code>tries</code></li>\n</ul>\n\n<p>I would argue that the names <code>tc</code> and <code>t</code> would be equally fine for the first two.</p>\n\n<p>Capitalization matters in Go. The variable <code>BenchmarkTry</code> and the type <code>PageBenchmark</code> would be exported. In this case it does not make a difference, but for larger programs and packages it would be important.</p>\n\n<h2>Miscellaneous</h2>\n\n<ol>\n<li><p>This cast is not needed.</p>\n\n<pre><code>totalExecTime := int64(0)\n</code></pre>\n\n<p>With the switch to <code>float64</code>, it can instead be:</p>\n\n<pre><code>totalExecTime := 0.0\n</code></pre></li>\n<li><p>Some of your comments extend beyond the 80-character column. It is useful to stay within 80 characters when viewing things split across your screen. Instead, move comments to the line before the code. (Some of these comments are superfluous, but you're learning so that's okay.)</p></li>\n<li><p>Store <code>len(sites)*len(pages)</code> in a constant, rather than recomputing it each time.</p></li>\n</ol>\n\n<h2>Conclusion</h2>\n\n<p>Here is the code I ended up with:</p>\n\n<pre><code>package main\n\nimport (\n \"fmt\"\n \"net/http\"\n \"time\"\n)\n\nconst tries = 1000\n\ntype pageBenchmark struct {\n url string\n time float64\n}\n\nfunc execBenchmark(url string, benchmarks chan pageBenchmark) {\n // prevent blocking goroutine\n timeChan := make(chan float64, tries)\n time := 0.0\n\n // start all requests\n for i := 0; i &lt; tries; i++ {\n go execHTTPRequest(url, timeChan)\n }\n\n // catch new values from execHTTPRequest()\n for i := 0; i &lt; tries; i++ {\n // wait to get value from goroutine\n time += &lt;-timeChan\n }\n\n benchmarks &lt;- pageBenchmark{url, time / tries}\n}\n\n// exec HTTP request and attach exec time to channel\nfunc execHTTPRequest(url string, timeChan chan float64) {\n begin := time.Now()\n _, _ = http.Get(url)\n timeChan &lt;- time.Since(begin).Seconds()\n}\n\nfunc main() {\n sites := [...]string{\n // sites\n }\n\n pages := [...]string{\n // pages\n }\n\n const length = len(sites) * len(pages)\n\n // set size to prevent blocked goroutine\n benchmarks := make(chan pageBenchmark, length)\n\n begin := time.Now()\n\n fmt.Println(\"Beginning!\\n\")\n\n // start all the goroutines\n for site := range sites {\n for page := range pages {\n go execBenchmark(sites[site]+pages[page], benchmarks)\n }\n }\n\n // catch and print benchmarks\n for i := 0; i &lt; length; i++ {\n b := &lt;-benchmarks\n fmt.Printf(\"Url: %s\\nResponse Time: %.0fs\\n\\n\", b.url, b.time)\n }\n\n // print total execution time\n fmt.Printf(\"End.\\nTotal time: %.0fs\\n\", time.Since(begin).Seconds())\n}\n</code></pre>\n\n<p>Hope this helps!</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-21T08:35:23.523", "Id": "417781", "Score": "0", "body": "Thank you very much for your time and all the advices :D\nI've tried the race detector with 2 sites and 12 urls and it's giving me this error : \"race: limit on 8128 simultaneously alive goroutines is exceeded, dying\". Is that normal?\nI'll try the `testing` package too thank you ^^" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-21T09:41:22.600", "Id": "417785", "Score": "0", "body": "I tried to use `strings.Builder{}` to concatenate `site` and `url` instead of `+=`.\nFirst try, my computer just crashed...\nSecond try (same code) was very long\nDon't know why :/" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-21T17:05:49.137", "Id": "417839", "Score": "0", "body": "@hunomina I think on this scale, `+` may not be worth optimizing -- just something to consider. For the race detector error, you receive this because you start 1000 goroutines per `execBenchmark` call, and you then have 24 calls to `execBenchmark` -- meaning it tries to spawn 24,000 goroutines. Switch to doing `tries` non-concurrently -- and only keep calls to `execBenchmark` concurrent." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-21T18:14:12.930", "Id": "417843", "Score": "1", "body": "Ok ^^ I may have misunderstood the purpose of the race detector. Let me read it again ;)\nFinally I'm using the `strings.Builder{}`, starting the program in a Docker container and it does not crash so happy ending ^^\nThank you for everything @esote ;)" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-21T00:55:03.013", "Id": "215892", "ParentId": "215883", "Score": "3" } } ]
{ "AcceptedAnswerId": "215892", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-20T22:20:59.563", "Id": "215883", "Score": "3", "Tags": [ "multithreading", "go", "http", "benchmarking" ], "Title": "Golang HTTP requests" }
215883