body
stringlengths
25
86.7k
comments
list
answers
list
meta_data
dict
question_id
stringlengths
1
6
<p>We have code that reads in a DXF/DWG file (drawing file) and then our own geometry library that converts everything into point, line, arcs, circles, and etc. objects. Then we have a Shape object which will hold one or many entities. Shapes can also contain other shapes as children and those shapes can have children. </p> <p>We have basic checks that do the typical checks like if an entity touches another entity or intersects it and are generally perform well so we haven't included that code here. </p> <p>In the software when we load a drawing file we do the following:</p> <ol> <li>Read in the file, consume the entities into objects</li> <li>Up convert each entity into a shape object, circles are 1:1, lines and everything else get marked as 'Irregular' shape objects</li> <li>Build an array of shapes / merge shapes by checking which entities 'touch' each other, so anything touching gets grouped into a single shape <ul> <li>simple checks like are first/last points the same</li> <li>intersections</li> <li>standard checks pulled out of geometry text books and other geometry libraries</li> </ul></li> <li>Once we have a list of shapes we do parent/child analysis (right now it only goes one level deep) so instead of ending up with let's say a dozen shapes from a hundred entities we know some are shapes inside of a shape, so we may only have one true 'shape' in the drawing while other shapes are nested underneath it as children or we could have multiple shapes in a drawing that are not within each other</li> </ol> <p>Overall it performed pretty good but once we added more complex drawings into the mix we realized some authors don't do single polylines but may have dozens or hundreds of lines in a drawing and then you could also have dozens or hundreds of circles showing cuts/holes in it. Then on top of that the average number of drawings the code deals with could be 10-30 files. So now we are seeing an average use case and the code not scaling to handle it and the step #2 is more of a brute force algorithm and can take 4+ seconds to run when there's hundreds of entities in a file. The algorithm / code mainly just looks at all entities and tries to identify which ones are touching which ones. I'm looking for ideas to improve the algorithm. I am trying to write more geometry focused code vs cad code, the cad code that reads the file is separate and just builds geometry to work with, then we go into geometry and do generic geometry work that isn't cad based but universal like hull analysis, total distances, want to also integrate with other open source libraries and leverage stronger analysis techniques on the drawing data and eventually even do image recognition which translates into geometry then back into cad by keeping libraries de-coupled.</p> <p>It loops over all the entities checking if an entity touches (checking first/last points, intersection algorithms, standard geometry checks that are pretty quick), if so it adds it to the shape and keeps going then restarts all over again creating new shapes or adding to existing ones until it's passed over all the entities and all of the shapes made. And when creating shapes and looking at new entities, it loops all over the entities in the shape checking if they touch again so that's why it doesn't scale well and it's not the best piece of code.</p> <p>Ignoring the 'touching' checks and all Invalidate does is update internals like length calculations and things like that, the issue is below.</p> <p>Any suggestions on how to improve this algorithm for speed and efficiency when dealing with hundreds of entities?</p> <pre><code> //we can end up with disjointed shapes, this scan keeps passing until we have no //more merges to try and perform every time we find a match we restart int idx = 0; uint kickout = 0; bool no_more = false; bool restart = false; //nothing at all? if (shapes.Count() &lt;= 0) return shapes; do { int i = -1; Shape s1 = shapes[idx]; if (s1.Entities.Count() &gt; 0) { for (i = idx + 1; i &lt; shapes.Count(); i++) { Shape s2 = shapes[i]; if (s2.Entities.Count() &gt; 0) { foreach (Entity e in s2.Entities) { if (s1.Touches(e)) { //as a group, they all touch each other so they must //all connect. Invalidate later (for speed) s1.Add(s2); s2.Clear(); //empty shapes.Remove(s2); //empty from collection restart = true; break; } } } } } //check next shape if (i == shapes.Count() || i == -1) { idx++; //idx %= shapes.Count(); //b/c we are manipulating contents } if (idx == shapes.Count() &amp;&amp; !restart) { no_more = true; } if (idx == shapes.Count() &amp;&amp; restart) { //re-pass, we have to keep going in case we missed a //joining segment/point idx = 0; restart = false; } //something went wrong here, don't freeze but we need to capture this kickout++; if (kickout + 1 == uint.MaxValue) //pretty high limit for checking { Debug.WriteLine("CRITICAL ERROR, OVERFLOW DETECTED IN SHAPE ANALYSIS!"); throw new OverflowException("CRITICAL ERROR, OVERFLOW DETECTED IN SHAPE ANALYSIS!"); } } while (!no_more); </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-02T16:37:09.187", "Id": "477473", "Score": "0", "body": "is `Shape` a collection class ? we need to see the related code for it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-02T19:49:12.573", "Id": "477491", "Score": "0", "body": "Type information of all used variables would be nice. However, one quick performance win: avoid Count()! Use Length for arrays / Count for lists. When using IEnumerable - stop using IEnumerable (or at least use .Any() instead of .Count() > 0) ;)" } ]
[ { "body": "<p>First of all consider using <a href=\"https://github.com/dotnet/BenchmarkDotNet\" rel=\"nofollow noreferrer\">Benchmark.NET</a> for benchmarking your code. It could help you improve your performance and point out directly which parts are slow. It's very hard for us to point out one \"slowest\" place in your code, because we don't see all parts that could have influence. And even if you paste it here we can easily misjudge it. We're humans after all. That's why such library was created - to be sure.</p>\n\n<p>But I have few \"why\" for code you pasted:</p>\n\n<ol>\n<li><p>Why you keep checking if there is anything in 's2.Entities'? Loop is\ndoing it for you.</p></li>\n<li><p>Why Entities.Count() shapes.Count() are methods? It implies that those object implements IEnumerable, so when they're invoked IEnumerable actually iterates through all of elements and counts them, could be potential improvement. <a href=\"https://stackoverflow.com/questions/4098186/lists-count-vs-count\">[REFERENCE]</a></p></li>\n<li>What is the implementation of 'Touches' methods? It's one of the most crucial parts of the code because it's invoked many times. Even if you wrote that it's standard pulled out from the books and \"generally perform well\" doesn't mean that it performs well in this case.</li>\n<li>Why are you clearing s2? Does it clear collection of entities? It could cause huge GC pressure. Benchmark.NET will help you discover that.</li>\n<li>Why are you removing s2 from collection? Is it because it's merged into s1, so it's treated as one shape now, right? Remember that remove complexity could be O(n) (for List collection for example), because it has to 'find' correct shape to remove and while one shape can contain many other shapes it could case huge complexity during comparing one to another. You can easily return new List of shapes that are already merged. </li>\n<li><p>Basically this code looks like you're trying to minimize shapes count by merging those that are 'touching eachother'. By 'touching eachother' I mean shapes that has, at least, one entity that touches our shape. If I'm not mistaken we can write it like this:</p>\n\n<pre><code>public List&lt;Shape&gt; MergeShapes(Shape[] shapes)\n{\n var mergedShapes = new List&lt;Shape&gt;(shapes.Length); // my assumption also preallocating size of list to minimize resizing\n var alreadyMergedShapesIndices = new HashSet&lt;int&gt;();\n\n for (int i = 0; i &lt; shapes.Length; i++) // you applied indexing on shapes variable that's why I assumed it's an array\n {\n if (alreadyMergedShapesIndices.Contains(i)) // my assumption after seeing shapes.Remove(s2) we don't want to merge into shape that was already processed.\n {\n continue;\n }\n\n var shapeToMergeInto = shapes[i];\n\n for (int j = i + 1; j &lt; shapes.Length - 1; j++)\n {\n var shapeToVerify = shapes[j];\n\n if (shapeToVerify.Entities.Any(e =&gt; shapeToMergeInto.Touches(e)))\n {\n shapeToMergeInto.Add(shapeToVerify);\n alreadyMergedShapesIndices.Add(j);\n }\n\n j++;\n }\n\n mergedShapes.Add(shapeToMergeInto);\n }\n\n return mergedShapes;\n}\n</code></pre></li>\n</ol>\n\n<p>Please don't consider code in my answer as the fastest possible solution for your problem. It's just my attempt to make it more readable and to be sure that I understood algorithm correctly. The only way to make any performance improvements is to benchmark your code, because you and your team understood how domain is represented, what collections are used. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-02T20:23:35.657", "Id": "243282", "ParentId": "243240", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-02T00:42:54.713", "Id": "243240", "Score": "2", "Tags": [ "c#", "performance", "algorithm" ], "Title": "Slow C# algorithm needs enhancement when dealing with hundreds of objects (doesn't scale)" }
243240
<p>I have a directory with 'sets' of files that start with a state name followed by 4 or 5 digits (typically indicating year). Each 'file set' contains 3 files a <strong>.txt</strong>, a <strong>.png</strong>, and a <strong>.jpg</strong>. </p> <p>Example of files in directory:</p> <pre><code>California1998_reform_paper.txt California1998_reform_paper.pdf California1998_reform_paper.jpg California2002_waterdensity_paper.txt California2002_waterdensity_paper.pdf California2002_waterdensity_paper.jpg </code></pre> <p>Based on a users input I am trying to write some code that can put each of these file sets into a list of lists. Ultimately I would like to iterate over the list of lists. That said, I am not married to any one data type if a dictionary or something else may be more efficient. </p> <p>I would like the user to be able to enter either:</p> <ul> <li>The state name i.e. 'California' - to get all files from California <br> OR <br></li> <li>The state name + year i.e. 'California1998' to get all files from California 1998</li> </ul> <pre><code>import os import regex directory = #path to directory input = 'California1998' # Does input match proper format? If not error. mm = regex.match('^([a-z]+)([0-9]{4,5})|^([a-z]+)', input) dir = str(os.listdir(directory)) if mm.group(1): state = mm.group(1) number = mm.group(2) state_num = state + number fileset = regex.findall(state_num, dir) elif mm.group(3): state = mm.group(3) fileset = regex.findall(state + r'[0-9]{4,5}', dir) else: print('Put some error message here') # Does input exist? If not error. if len(fileset) &gt; 0: fileset = tuple(set(sorted(fileset))) else: print('Put some error message here') # Get list of lists state_num_files = [[file.path for file in os.scandir(directory) if file.name.startswith(state_num)] for state_num in fileset] return state_num_files </code></pre> <p>Above is the code I have thus far. It first uses <code>regex.match</code> to check the input, then <code>regex.findall</code> to find all matching state + years. I then create a <code>sorted()</code> <code>set()</code> from this list, which is converted into a <code>tuple()</code> called <code>fileset</code>. The last bit of code is a nested list comprehension that produces the list of lists by iterating through all files in the directory and iterating through all the state + years in <code>fileset</code>.</p> <p>It certainly works, but seems repetitive and slower than it needs to be. My goal is to increase efficiency and remove any unnecessary iteration. </p> <p>Thoughts on improvements:</p> <ul> <li>Possibly replace each <code>regex.findall</code> with a nested list comprehension? and thus remove the <code>state_num_files</code> nested comprehension at the end of script?</li> </ul> <p>Any thoughts are greatly appreciated! </p>
[]
[ { "body": "<h1>Review</h1>\n\n<ol>\n<li><p>Bug on Capitalization</p>\n\n<pre><code>mm = regex.match('^([a-z]+)([0-9]{4,5})|^([a-z]+)', input)\n</code></pre>\n\n<p>This does not work for the given use case of <em>California1998</em></p>\n\n<p>But it can be easily fixed by adjusting the regex to include <code>[A-Za-z]</code> capital letters</p></li>\n<li><p>Stop overshadowing!</p>\n\n<p>You use multiple built-in keywords as variable names ie, <code>input</code> <code>dir</code> this makes it that the overshadowed functions can no longer be used further in the program</p></li>\n<li><p><code>import regex</code>? </p>\n\n<p>I think this should be <code>import re</code>, since that's what the library is called</p></li>\n<li><p>Unnecesarry operations</p>\n\n<p>The <code>sort</code> and consecutive conversion do nothing at all</p>\n\n<p>Secondly you loop over the directory twice! This can be avoided by doing it one loop.</p></li>\n<li><p>Don't <code>print</code> errors <code>raise</code> them</p>\n\n<p>And make sure the user get's back useful information in the error message this generic message is not very helpful :)</p></li>\n</ol>\n\n<h1>Alternative</h1>\n\n<p>Look into the <a href=\"https://docs.python.org/3/library/glob.html\" rel=\"nofollow noreferrer\"><code>glob</code></a> module this does what you require, </p>\n\n<pre><code>&gt;&gt;&gt; import glob\n&gt;&gt;&gt; glob.glob(\"./California1998*\")\n['./California1998_reform_paper.jpg', './California1998_reform_paper.txt', './California1998_reform_paper.pdf']\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-04T14:23:57.260", "Id": "477704", "Score": "0", "body": "Note: `glob` is case-sensitive, unless run on Windows." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-02T12:10:57.893", "Id": "243262", "ParentId": "243241", "Score": "2" } }, { "body": "<p>Welcome to Stack Overflow! Based on your code and what your were trying to do (and one suggestion from Ludisposed) here's a attempt where you only scan once the directory where your files are situated:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>import re\nimport pathlib\nimport os\nimport collections\n\ndirectory_of_source_file = pathlib.Path(\"Input files\")\nfile_set_from_input = 'California1998'\n\nstate_name_matcher = re.compile(r'([a-z]+)(\\d{4,5})?', re.IGNORECASE)\nif state_name_found := state_name_matcher.match(file_set_from_input):\n state_wanted = state_name_found[1]\n set_number = state_name_found[2]\n set_number = '' if set_number is None else set_number\n\n files_found = directory_of_source_file.glob(f\"{state_wanted}{set_number}*\")\n files_found_strings = list(map(str, files_found))\n if set_number:\n files_found_formatted = [files_found_strings, ]\n else:\n strict_state_name_matcher = re.compile(rf'{os.sep}{state_wanted}(\\d{{4,5}})', re.IGNORECASE)\n documents_collector = collections.defaultdict(list)\n for current_file in files_found_strings:\n if matching_document_found := strict_state_name_matcher.search(current_file):\n current_set_number = matching_document_found[1]\n documents_collector[current_set_number].append(current_file)\n files_found_formatted = list(documents_collector.values())\n for current_file_set in files_found_formatted:\n current_file_set.sort()\n print(files_found_formatted)\nelse:\n print('Put some error message here')\n</code></pre>\n\n<p>I hope I understood correctly what you were trying to do</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-04T06:06:39.113", "Id": "243362", "ParentId": "243241", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-02T00:44:14.243", "Id": "243241", "Score": "2", "Tags": [ "python", "regex" ], "Title": "Creating nested list comprehension of files starting with specific string" }
243241
<p>I am working with cassandra using datastax c# driver. I need to pull data out from three different tables. Below is my code which does the job. </p> <pre><code> private const string itemMapStmt = "FROM product_data WHERE client_id = ? PER PARTITION LIMIT 1"; private const string itemSelectStatement = "FROM item WHERE item_id = ? PER PARTITION LIMIT 1"; private const string itemProStmt = "FROM process_holder WHERE item_id = ? AND process_id = ? PER PARTITION LIMIT 1"; private var semaphore = new SemaphoreSlim(100); private readonly IResponseMapper rpm; private readonly Cluster cluster; private readonly ISession session; private readonly IMapper mapper; /** * * Below method gets data from all 3 different tables. * */ public async Task&lt;IList&lt;Item&gt;&gt; GetAsync(IList&lt;int&gt; clientIds, int processId, int proc, Kyte kt) { var clientMaps = await ProcessCassQueries(clientIds, (ct, batch) =&gt; mapper.SingleOrDefaultAsync&lt;ItemMapPoco&gt;(itemMapStmt, batch), "GetPIMValue"); if (clientMaps == null || clientMaps.Count &lt;= 0) { return null; } var itemIds = clientMaps.SelectMany(x =&gt; x.ItemIds).Where(y =&gt; y != null).ToList(); // 1st table var itemsTask = ProcessCassQueries(itemIds, (ct, batch) =&gt; mapper.SingleOrDefaultAsync&lt;ItemPoco&gt;(itemSelectStmt, batch), "GetAsync"); // 2nd table var itemProTask = ProcessCassQueries(itemIds, (ct, batch) =&gt; mapper.SingleOrDefaultAsync&lt;ItemProPoco&gt;(itemProStmt, batch, processId), "GetIPValue"); var items = await itemsTask; if (items.Count &lt;= 0) { return null; } var itmDictionary = items.ToDictionary(dto =&gt; dto.ItemId, dto =&gt; rpm.MapToItem(dto, proc)); var itmProDict = itemIds.ToDictionary&lt;int, int, ItemProPoco&gt;(id =&gt; id, id =&gt; null); var holder = new List&lt;int&gt;(); var itemPrices = await itemProTask; itemPrices.ForEach(i =&gt; { if (i != null) itmProDict[i.ItemId] = i; }); foreach (var ip in itmProDict) if (ip.Value == null) holder.Add(ip.Key); if (holder.Count &gt; 0) { // 3rd table var ipHolder = await ProcessCassQueries(itemIds, (ct, batch) =&gt; mapper.SingleOrDefaultAsync&lt;ItemProPoco&gt;(itemProStmt, batch, kt.Pid), "GetIPValue"); ipHolder.ToList().ForEach(ipf =&gt; { if (ipf != null) itmProDict[ipf.ItemId] = ipf; }); } return itmDictionary.Select(kvp =&gt; { itmProDict.TryGetValue(kvp.Key, out var ip); if (kvp.Value != null) { rpm.convert(ip, kvp.Value); return kvp.Value; } return null; }).Where(s =&gt; s != null).ToList(); } /** * * Below method does multiple async calls on each table for their corresponding id's by limiting it down using Semaphore. * (does below method looks right in terms of performance?) * */ private async Task&lt;List&lt;T&gt;&gt; ProcessCassQueries&lt;T&gt;(IList&lt;int&gt; ids, Func&lt;CancellationToken, int, Task&lt;T&gt;&gt; mapperFunc, string msg) where T : class { var tasks = ids.Select(async id =&gt; { await semaphore.WaitAsync(); try { ProcessCassQuery(ct =&gt; mapperFunc(ct, id), msg); } finally { semaphore.Release(); } }); return (await Task.WhenAll(tasks)).Where(e =&gt; e != null).ToList(); } // this might not be good idea to do it. how can I improve below method? private Task&lt;T&gt; ProcessCassQuery&lt;T&gt;(Func&lt;CancellationToken, Task&lt;T&gt;&gt; requestExecuter, string msg) where T : class { return requestExecuter(CancellationToken.None); } } </code></pre> <p>In my <code>ProcessCassQueries</code> method, I get data out from cassandra for each <code>id</code> but I am limiting it down using <code>Semaphore</code> so that I don't put pressure on Scylla db under heavy load. I wanted to see is there anything we can do here to improve things out in terms of performance as this method will be used under very heavy load and I see lot of expensive LINQ calls like <code>ToDictionary</code>, <code>ToList</code>, <code>ForEach</code> that could be problematic under heavy load.</p> <p>Anything we can improve here? If yes - can someone provide an example?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-02T07:14:08.673", "Id": "477413", "Score": "2", "body": "Generally speaking an I/O operation is much more time consuming then a collection creation logic. So spending effort on optimising things like that might not be beneficial. If you want to optimize it then you have to first understand the characteristic of the current code and use it as a baseline for your further improvements and measurements." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-02T09:58:03.243", "Id": "477428", "Score": "2", "body": "Put your code under heavy load and see if it is too slow. If it is too slow, then profile your code and see if the linq queries are the bottleneck. And only then, if answer is yes, consider optimizing those queries." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-02T02:49:49.100", "Id": "243242", "Score": "1", "Tags": [ "c#", "multithreading" ], "Title": "Is it good idea to use expensive LINQ calls under heavy load?" }
243242
<p>I test in a bash script if a variable <code>value</code> contains digits only. There are two options, both give the valid results:</p> <pre><code>validate_is_pos_int(){ local value=$1 if ! [[ ${value//[0-9]/""} ]] then return 0 # True; $1 has digits only else return 1 # False; $1 contains other letters besides digits fi} </code></pre> <p>and the second (maybe more readable):</p> <pre><code>validate_is_pos_int(){ local value=$1 if [[ -z ${value//[0-9]/""} ]] then return 0 # True; $1 has digits only else return 1 # False; $1 contains other letters besides digits fi} </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-02T06:24:05.610", "Id": "477408", "Score": "4", "body": "Welcome to CodeReview@SE. The title describes something else than the code alternatives. Please try and [summarise as the title what the code (not the question) is there for](https://codereview.stackexchange.com/help/how-to-ask). (What is the result of your tests for, say, 42?)" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-02T03:10:56.157", "Id": "243243", "Score": "2", "Tags": [ "comparative-review", "bash" ], "Title": "What is a better practice in bash scripts to test if string is empty: [[ -z ${value//[0-9]/\"\"} ]] or ! [[ ${value//[0-9]/\"\"} ]]?" }
243243
<p>Please review my code for the problem statement below. Many Thanks.</p> <blockquote> <p>You job is to create a simple banking application.</p> <p>There should be a Bank class:</p> <ul> <li>It should have an <code>ArrayList</code>of <code>Branche</code>s</li> <li>Each Branch should have an <code>ArrayList</code>of <code>Customer</code> s</li> <li>The Customer class should have an <code>ArrayList</code>of <code>Double</code>s (transactions)</li> </ul> <p>Customer:</p> <ul> <li>Name, and the <code>ArrayList</code> of <code>Double</code>s.</li> </ul> <p>Branch:</p> <ul> <li>Need to be able to add a new customer and initial transaction amount.</li> <li>Also needs to add additional transactions for that customer/branch</li> </ul> <p>Bank:</p> <ul> <li>Add a new branch</li> <li>Add a customer to that branch with initial transaction</li> <li>Add a transaction for an existing customer for that branch</li> </ul> </blockquote> <p>Show a list of customers for a particular branch and optionally a list of their transactions Demonstration autoboxing and unboxing in your code.</p> <pre><code>import java.lang.Double; import java.util.ArrayList; public class Customer{ private String name; private ArrayList&lt;Double&gt; transactions = new ArrayList&lt;&gt;(); public Customer(String name,double initialTransaction){ this.name = name; this.transactions.add(Double.valueOf(initialTransaction)); } public String getCustomerName(){ return this.name; } public Double getInitialTransaction(){ return this.transactions.get(0); } public void addTransaction(double transaction){ this.transactions.add(Double.valueOf(transaction)); } public String getCustomerDetails(){ return getCustomerName()+&quot;\t\t\t&quot;+transactions; } } import java.lang.Double; import java.util.ArrayList; public class Branch{ private String name; private ArrayList&lt;Customer&gt; customers; public Branch(String name){ this.name = name; this.customers = new ArrayList&lt;&gt;(); } public String getBranchName(){ return this.name; } public void addCustomer(Customer customer){ if(customer!=null){ if(!searchCustomer(customer)){ this.customers.add(customer); //System.out.println(&quot;Customer with name &quot;+customer.getCustomerName()+&quot; added to branch &quot;+getBranchName()); }else{ //System.out.println(&quot;Customer with name &quot;+customer.getCustomerName()+&quot; already present in branch &quot;+getBranchName()); } }else{ //System.out.println(&quot;Customer with null values entered!!!&quot;); } } public void addTransaction(Customer customer,double transaction){ if(customer!=null || transaction&lt;=0.0){ if(searchCustomer(customer)){ this.customers.get(this.customers.indexOf(customer)).addTransaction(transaction); //System.out.println(&quot;Transaction of &quot;+transaction+&quot; added in account of Customer with name &quot;+customer.getCustomerName()); }else{ //System.out.println(&quot;Customer with name &quot;+customer.getCustomerName()+&quot; not present in branch &quot;+getBranchName()+&quot;. Please add the customer.&quot;); } }else{ //System.out.println(&quot;Customer with null values or no transaction entered!!!&quot;); } } public void printCustomerList(){ System.out.println(&quot;Customer Name \t\t Transactions&quot;); for(Customer cx:customers){ System.out.println(cx.getCustomerDetails()); } } public boolean searchCustomer(Customer customer){ for(int i=0;i&lt;this.customers.size();i++){ if(this.customers.get(i).equals(customer)){ return true; } } return false; } } import java.lang.Double; import java.util.ArrayList; public class Bank{ private String name; private ArrayList&lt;Branch&gt; branches; public Bank(String name){ this.name = name; this.branches = new ArrayList&lt;&gt;(); } public String getBankName(){ return this.name; } public void addBranch(Branch branch,Customer customer){ if(branch!=null){ if(!searchBranch(branch)){ branch.addCustomer(customer); this.branches.add(branch); System.out.println(&quot;Customer with name &quot;+customer.getCustomerName()+&quot; with an initialTransaction of &quot;+customer.getInitialTransaction().doubleValue()+&quot; is added to Branch with name &quot;+branch.getBranchName()+&quot; of bank &quot;+getBankName()); }else{ System.out.println(&quot;Branch with name &quot;+branch.getBranchName()+&quot; already present&quot;); } }else{ System.out.println(&quot;Branch with null values entered!!!&quot;); } } public void addTransaction(Branch branch, Customer customer,double transaction){ if(branch!=null || customer!=null){ if(searchBranch(branch) &amp;&amp; branch.searchCustomer(customer)){ branch.addTransaction(customer,transaction); System.out.println(&quot;Transaction of &quot;+transaction+&quot; added in account of Customer with name &quot;+customer.getCustomerName()+&quot; under branch &quot;+branch.getBranchName()+&quot; of bank &quot;+getBankName()); }else{ System.out.println(&quot;Customer with name &quot;+customer.getCustomerName()+&quot; not present in branch &quot;+branch.getBranchName()+&quot;. Please add the customer.&quot;); } }else{ System.out.println(&quot;Branch or Customer with null values entered!!!&quot;); } } public void printCustomersOfBranch(Branch branch){ if(branch!=null){ if(searchBranch(branch)){ branch.printCustomerList(); } }else{ System.out.println(&quot;Branch with null values entered!!!&quot;); } } private boolean searchBranch(Branch branch){ for(int i=0;i&lt;branches.size();i++){ if(this.branches.get(i).equals(branch)){ return true; } } return false; } } public class BankTest{ public static void main(String[] args){ Bank pnb = new Bank(&quot;Punjab National Bank&quot;); Branch peachtree = new Branch(&quot;Peach Tree&quot;); Branch rodeodrive = new Branch(&quot;Rodeo Drive&quot;); Branch goodearth = new Branch(&quot;Good Earth&quot;); Customer harsh = new Customer(&quot;Harsh&quot;,0.5); Customer nidhi = new Customer(&quot;Nidhi&quot;,600.75); Customer yuv = new Customer(&quot;Yuv&quot;,1785.95); pnb.addBranch(peachtree,harsh); pnb.addBranch(rodeodrive,nidhi); pnb.addBranch(goodearth,yuv); pnb.printCustomersOfBranch(peachtree); pnb.printCustomersOfBranch(rodeodrive); pnb.printCustomersOfBranch(goodearth); pnb.addTransaction(peachtree,harsh,500.60); pnb.addTransaction(rodeodrive,nidhi,150000.70); pnb.addTransaction(goodearth,yuv,121798.12); pnb.printCustomersOfBranch(peachtree); pnb.printCustomersOfBranch(rodeodrive); pnb.printCustomersOfBranch(goodearth); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-02T12:06:42.040", "Id": "477439", "Score": "1", "body": "Do you expect some specifc remarks on the code. About the perfs, structure, maitainability, style, .. ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-02T14:18:38.750", "Id": "477445", "Score": "0", "body": "Importing `java.lang.Double` is unnecessary, all of `java.lang.*` is imported by default." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-03T14:26:28.323", "Id": "477592", "Score": "0", "body": "@gervais.b Well I am a starter(10th time), so any feedback would be helpful. Also would like a suggestion to concentrate solely on gaining conceptual understanding or also focus more on style, structure, maintainability because I haven't come across all these in the course I am following." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-03T14:27:48.237", "Id": "477593", "Score": "0", "body": "@markspace Duly noted. Also I noted that instead of calling Double.valueOf, I could directly pass the double value which will be autoboxed." } ]
[ { "body": "<blockquote>\n <p>Demonstration autoboxing and unboxing in your code.</p>\n</blockquote>\n\n<p>You can then remove the calls to <code>Double#valueOf(double)</code> and \n<code>Double#doubleValue():doube</code>. Then you can replace <code>Double</code> with <code>double</code>\nwhen applicable (return of public methods). </p>\n\n<p><strong>Searching items in list</strong></p>\n\n<p>At some times you are using <code>List#indexOf(Object):int</code> but in other places, you \nare looping on the list to test the equality of an item (<code>searchCustomer</code>, \n<code>searchBranch</code>). </p>\n\n<p>The Javadoc of <a href=\"https://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html#indexOf(java.lang.Object)\" rel=\"nofollow noreferrer\"><code>ArrayList#indexOf(Object):int</code></a> states that :</p>\n\n<blockquote>\n <p>returns the lowest index i such that (o==null ? get(i)==null : o.equals(get(i)))</p>\n</blockquote>\n\n<p>So you can easily replace your loops in your search methods by \n<code>return theList.indexOf(something) &gt; -1</code> </p>\n\n<p>But there is still a better way to check if a list contains an item: <a href=\"https://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html#contains(java.lang.Object)\" rel=\"nofollow noreferrer\"><code>ArrayList#contains(Object):boolean</code></a></p>\n\n<p><strong>Naming</strong></p>\n\n<p>Based on the previous comment, you could also rename your <code>searchXyz</code> methods to \n<code>contains</code> or another more meaningful name. This may be a cultural issue but, \nmost of the time when \"we\" (BE_fr devs) read <code>search</code>, \"we\" expect to receive a \ncollection of found objects.</p>\n\n<p><strong>Complexity</strong></p>\n\n<p>Instead of nesting your <code>if</code>s like in <code>Branch#addTransaction(..)</code> you can <em>fail quickly</em> :</p>\n\n<pre><code>if ( customer==null || transaction &lt;= 0.0 ) {\n // fail\n} else if ( !contains(customer) ) {\n // fail \n} else {\n // This is fine\n}\n</code></pre>\n\n<p>If you rely on <code>Exception</code> for your failure you can also reduce a bit the nesting \nof your method :</p>\n\n<pre><code>if ( isThisInvalid(..) ) {\n throw new InvalidOperation(..); \n} \n\n// This is fine\n</code></pre>\n\n<p>The less path/branches you have in your code, the better it is. That's also why \nI introduced a validation method, to move the validations rules outside of the \nbusiness code. </p>\n\n<p><strong>Encapsulation</strong></p>\n\n<p>Not all your methods have to be public, try to mark as much as possible as <code>private</code>\nor <em>package protected</em> to reduce your public API. </p>\n\n<p><strong>Separation of concerns</strong></p>\n\n<p>Most of the time, for maintainability and testability concerns, you try extract \nconcerns in different classes. That's why there are some popular high-level patterns \nlike <em>MVC</em>, <em>MVP</em>, ...</p>\n\n<p>In your case you could move the printing to a dedicated class that will be \nresponsible to gather, format and print values from your model.</p>\n\n<hr>\n\n<p>Here are some excerpt of how your final code may looks like:</p>\n\n<pre><code>class Branch {\n private final ArrayList&lt;Customer&gt; customers;\n private final String name;\n\n public Branch(String name) {\n this.customers = new ArrayList&lt;&gt;();\n this.name = name;\n }\n\n public String getBranchName() {\n return this.name;\n }\n\n public ArrayList&lt;Customer&gt; getCustomers() {\n return new ArrayList&lt;&gt;(customers);\n }\n\n public void addCustomer(Customer customer) {\n if (!isValidCustomer(customer)) {\n throw new InvalidCustomerException( customer);\n }\n customers.add(customer);\n }\n\n private boolean isValidCustomer(Customer customer) {\n return customer!=null &amp;&amp;\n !contains(customer);\n }\n\n public void addTransaction(Customer customer, double transaction) {\n if (!isValidaTransaction(customer, transaction)) {\n throw new InvalidTransactionException(customer, transaction);\n }\n getCustomer(customer).addTransaction(transaction);\n this.customers.get(this.customers.indexOf(customer)).addTransaction(transaction);\n }\n\n private boolean isValidaTransaction(Customer customer, double transaction) {\n return customer!=null &amp;&amp;\n transaction &lt;= 0.0 &amp;&amp;\n contains(customer);\n }\n\n private boolean contains(Customer customer) {\n return customers.contains(customer);\n }\n\n private Customer getCustomer(Customer customer) {\n return customers.get(customers.indexOf(customer));\n }\n} \n\nclass BranchCustomersPrinter implements Consumer&lt;Bank&gt; { \n private final PrintWriter output;\n\n @Override\n public void accept(Bank bank) {\n Branch branch = bank.getBranch(branch);\n output.append(\"Customer Name \\t\\t Transactions\");\n branch.getCustomers().forEach(customer -&gt;\n output.append(customer.getCustomerName())\n .append(\"\\t\\t\")\n .append(customer.getTransactions())\n );\n output.flush();\n }\n} \n\nBank bank = ...\nbank.print(new BranchCustomersPrinter(..));\n</code></pre>\n\n<hr>\n\n<p>Note; Your validation in <code>Branch#addTransaction(..)</code> seems to be buggy. It will \naccept a <code>null</code> customer with a transaction bigger than <code>0</code>. It will also never \naccept a positive transaction. </p>\n\n<hr>\n\n<p>Note; Java uses references and since your program will always run in memory you \ndon't need to get an item from the list to update his values.</p>\n\n<pre><code>Customer c1 = new Customer(\"One\", 10);\nArrayList list = new ArrayList();\nlist.add(c1);\n\nc1.addTransaction(5); // Is the same as :\nlist.get(list.indexOf(c1)).addTransaction(5);\n</code></pre>\n\n<p>But most of the time; you have to save and retrieve the customer from a persistent \nstorage. </p>\n\n<p>This is also why <code>list.contains(c1)</code> returns <code>true</code>. Because it is effectively the \nsame \"object\"; doing the same with two customers having the same properties will \nnot work:</p>\n\n<pre><code>Customer c1 = new Customer(\"Customer\", 10); \nCustomer c2 = new Customer(\"Customer\", 10);\n\nc1.equals(c2); // false \n</code></pre>\n\n<p>But I guess that you will learn the subtleties of object references and <code>equals</code> \nsoon. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-05T15:26:51.233", "Id": "477798", "Score": "0", "body": "Doesn't this accomplish the same. Please correct me if I am wrong.\n\n getCustomer(customer).addTransaction(transaction);\n this.customers.get(this.customers.indexOf(customer)).addTransaction(transaction);" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-06T16:36:19.217", "Id": "477878", "Score": "0", "body": "It depends of how ‘getCustomer’ is implemented. But it can be the same yes. However ‘getSomething().doAnother()’ is not a good idea because it expose your implementation details. It is better to do ‘doAnother(Something on)’ so that you can change the may you store your objects. Read a bit on encapsulation to know more." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-04T07:51:13.000", "Id": "243367", "ParentId": "243244", "Score": "1" } } ]
{ "AcceptedAnswerId": "243367", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-02T03:15:44.227", "Id": "243244", "Score": "1", "Tags": [ "java", "object-oriented" ], "Title": "Feedback on ArrayList using OOPs" }
243244
<p>I'm solving the m-coloring problem using java. and I have following code that uses concept of recursion and backtracking.</p> <pre class="lang-java prettyprint-override"><code> import java.util.Arrays; public class GraphColoring { static void graphColor(int k, int m, int n, int colors[], int graph[][]) { for (int c = 1; c &lt;= m; c++) { if (isSafe(k, c, n, colors, graph)) { colors[k] = c; if (k + 1 &lt; n) graphColor(k + 1, m, n, colors, graph); } } } static boolean isSafe(int k, int c, int n, int[] colors, int graph[][]) { for (int i = 0; i &lt; n; i++) { if (graph[k][i] == 1 &amp;&amp; c == colors[i]) { return false; } } return true; } public static void main(String[] args) { int n = 4, m = 3; int[] colors = new int[n]; int graph[][] = { { 1, 1, 0, 1 }, { 1, 1, 1, 1 }, { 0, 1, 1, 1 }, { 1, 1, 1, 1 } }; graphColor(0, m, n, colors, graph); System.out.println(Arrays.toString(colors)); } } </code></pre> <blockquote> <h2>OUTPUT</h2> </blockquote> <p><code>1 2 1 3</code></p> <p>I would like review about its performance, time complexity and improvements. Also If I'm missing any corner cases please let me know as this code is tested on very few examples as I didn't find any online problem that checks its appropriate output.</p>
[]
[ { "body": "<blockquote>\n <p>Also If I'm missing any corner cases please let me know as this code is tested on very few examples as I <strong>didn't find any online problem that checks its appropriate output.</strong></p>\n</blockquote>\n\n<p>[emphasis mine]</p>\n\n<p>Graph colouring is a relatively nice problem in that regard: you can easily check the validity of the result. The only conditions are that every vertex must have a color, the number of colors must be less-than-or-equal-to <code>m</code>, and neighboring vertices don't share a color. So as a test you could generate random graphs (or for small graphs, enumerate all symmetric graphs without self-loops), color them, and theck the results. Any valid coloring is appropriate. The main problem is testing whether graphs that your algorithm decides are not m-colorable are <em>actually</em> not m-colorable.</p>\n\n<p>I suspected there was such an issue (as this algorithm never \"uncolors\" a vertex, it should be possible for it to get stuck) so I enumerated some graphs to find a concrete breaking test-case:</p>\n\n<pre><code>int n = 6, m = 3;\nint[][] graph = {\n {0, 1, 0, 0, 1, 1},\n {1, 0, 1, 1, 0, 1},\n {0, 1, 0, 1, 0, 0},\n {0, 1, 1, 0, 0, 1},\n {1, 0, 0, 0, 0, 0},\n {1, 1, 0, 1, 0, 0}};\n</code></pre>\n\n<p>This algorithm results in <code>[1, 2, 1, 3, 3, 0]</code>, the zero indicating that no valid coloring was found, but there actually are valid colorings, for example <code>[1, 2, 3, 1, 2, 3]</code>. Just to confirm that it's a valid coloring, here it is as a drawing:</p>\n\n<p><a href=\"https://i.stack.imgur.com/c4xAl.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/c4xAl.png\" alt=\"coloring\"></a></p>\n\n<p>Keep in mind though that if there is one valid coloring, there are almost always many more. Even if there are no fundamentally different colorings, the color-names can be permuted to yield a superficially different-looking coloring. So test-cases should not compare for equality with some coloring found by a different solver, that's too strict.</p>\n\n<p>To find that case I had to implement an other graph colorer that is capable of coloring the graph above, I used this small rewrite of your code:</p>\n\n<pre><code>static int[] graphColor(int m, int[][] graph) {\n int[] colors = new int[graph.length];\n // the color of the first vertex is a free pick\n colors[0] = 1;\n if (graphColorInternal(1, m, colors, graph))\n return colors;\n else\n return null;\n}\n\nstatic boolean graphColorInternal(int k, int m, int colors[], int graph[][]) {\n for (int c = 1; c &lt;= m; c++) {\n if (isSafe(k, c, colors, graph)) {\n colors[k] = c;\n if (k + 1 &lt; colors.length) {\n if (graphColorInternal(k + 1, m, colors, graph))\n return true;\n colors[k] = 0;\n }\n else\n return true;\n }\n }\n return false;\n}\n\nstatic boolean isSafe(int k, int c, int[] colors, int graph[][]) {\n for (int i = 0; i &lt; colors.length; i++) {\n if (graph[k][i] == 1 &amp;&amp; c == colors[i])\n return false;\n }\n return true;\n}\n</code></pre>\n\n<p>In addition to the line <code>colors[k] = 0;</code> which gets the solver \"unstuck\" after backtracking, there are some more changes that I would like to highlight:</p>\n\n<ul>\n<li>The function <code>graphColor</code> that is supposed to be called <em>returns</em> its result, rather than modifying a function argument. Generally you should prefer that. Output-parameters <a href=\"http://www.javapractices.com/topic/TopicAction.do?Id=37\" rel=\"nofollow noreferrer\">should be avoided</a>, unless there is a good enough reason not to.</li>\n<li><code>graphColor</code> does not take redundant parameters (<code>n</code>, which it knows from the <code>graph</code> itself).</li>\n<li>The search indicates explicitly whether it found something or failed, so the wrapper does not have to inspect the coloring to find that out.</li>\n<li>The search returns immediately after finding a valid coloring. The original algorithm does not return immediately, it tries to fill in different colors though most of it fails because <code>isSafe</code> returns <code>false</code> a lot when given a filled coloring.</li>\n</ul>\n\n<blockquote>\n <p>I would like review about <strong>its performance, time complexity</strong> and improvements.</p>\n</blockquote>\n\n<p>Not much can be done about the time complexity, not for the worst case anyway: graph coloring is NP-complete after all.</p>\n\n<p>But there are things that can be done.</p>\n\n<ul>\n<li>Rather than coloring the vertices simple in order of their index, color them in order of Most Constrained Variable (MCV) first, that is, color the vertex with the most colored neighbors first. </li>\n<li>Maintain a set of \"possible colors\" for every vertex. This makes it easy to detect early that the current partial-coloring is no good (if any vertex has an empty set of colors left, backtrack), and easy to find the MCV (uncolored vertex with the smallest set of possible colors). It also means that rather than checking <code>isSafe</code> for every color, the solver already has a list of possible colors - though of course it pays for that by maintaining those sets every time the color of a vertex is changed.</li>\n<li>Advanced: improve those sets of possible colors with the <a href=\"https://en.wikipedia.org/wiki/AC-3_algorithm\" rel=\"nofollow noreferrer\">AC-3 Algorithm</a> or similar. </li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-02T12:29:33.047", "Id": "243263", "ParentId": "243249", "Score": "2" } } ]
{ "AcceptedAnswerId": "243263", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-02T06:20:14.410", "Id": "243249", "Score": "2", "Tags": [ "java", "graph" ], "Title": "Graph coloring in Java" }
243249
<h3>Needs</h3> <ul> <li>A container holds two collections: <code>Parent</code> instances and <code>Child</code> instances; their items can be searched by name;</li> <li>A child can return a reference to its parent;</li> <li>A parent can search its children by name and return one of them by reference;</li> <li>A <code>Child</code> is read-only after creation, but new children or parents can be added at runtime;</li> </ul> <h3>Implementation</h3> <p>To do it, I choose to use <code>Rc&lt;RefCell&lt;...&gt;&gt;</code> and <code>Weak&lt;RefCell&lt;...&gt;&gt;</code> because I didn't find any other decent solution (unless maybe raw pointers):</p> <ul> <li>in the container I store strong references to <code>Parent</code> and <code>Child</code> instances in order to be sure they will be alive during all the container's life,</li> <li>and other references (<code>Parent</code>-><code>Child</code> and <code>Child</code>-><code>Parent</code>) are stored as weak references, in order to avoid cyclic references.</li> </ul> <h3>Questions</h3> <ul> <li><p>Concerning the way of handling references, is there a better way to do it?</p></li> <li><p>Assuming that no reference at all will be kept outside the container's scope, is there a way to simplify it?<br> Indeed, by looking at the last test, you can see that readability is getting a bit hard, just for a simple request like "Give me the name of ...". And beyond readability, I wonder if this does not have a runtime cost that could be avoided.</p></li> </ul> <p><em>Note</em>: The code could be improved by using <code>HashMap</code> instead of <code>Vec</code>, but my question is not dealing about this.</p> <pre><code>#![allow(dead_code)] use std::rc::{Weak, Rc}; use std::cell::RefCell; #[derive(Debug)] struct Child { name: String, parent: Weak&lt;RefCell&lt;Parent&gt;&gt;, } impl Child { fn new(name: &amp;str, parent: &amp;Rc&lt;RefCell&lt;Parent&gt;&gt;) -&gt; Child { Child { name: name.to_string(), parent: Rc::downgrade(parent), } } fn parent(&amp;self) -&gt; &amp;Weak&lt;RefCell&lt;Parent&gt;&gt; { &amp;self.parent } fn strong_parent(&amp;self) -&gt; Rc&lt;RefCell&lt;Parent&gt;&gt; { // As far as I understand, unwrap() should never panic as long as the container is still // alive: self.parent.upgrade().unwrap() } } #[derive(Debug)] struct Parent { name: String, children: Vec&lt;Weak&lt;RefCell&lt;Child&gt;&gt;&gt;, } impl Parent { fn new(name: &amp;str) -&gt; Parent { Parent { name: name.to_string(), children: vec![], } } fn add_child(&amp;mut self, child: &amp;Rc&lt;RefCell&lt;Child&gt;&gt;) { self.children.push(Rc::downgrade(child)); } fn child(&amp;self, name: &amp;str) -&gt; Option&lt;&amp;Weak&lt;RefCell&lt;Child&gt;&gt;&gt; { self.children.iter() .find(|c| c.upgrade().unwrap().borrow().name == name) } fn strong_child(&amp;self, name: &amp;str) -&gt; Option&lt;Rc&lt;RefCell&lt;Child&gt;&gt;&gt; { self.children.iter() .map(|c| c.upgrade().unwrap()) .find(|c| c.borrow().name == name) } } #[derive(Debug)] struct Container { children: Vec&lt;Rc&lt;RefCell&lt;Child&gt;&gt;&gt;, parents: Vec&lt;Rc&lt;RefCell&lt;Parent&gt;&gt;&gt;, } impl Container { pub fn new() -&gt; Container { Container { children: vec![], parents: vec![], } } pub fn add_child(&amp;mut self, name: &amp;str, parent: &amp;Rc&lt;RefCell&lt;Parent&gt;&gt;) -&gt; &amp;Rc&lt;RefCell&lt;Child&gt;&gt; { if self.child(name).is_some() { panic!(format!("Child '{}' already exists.", name)); } let child = Rc::new(RefCell::new(Child::new(name, parent))); parent.borrow_mut().add_child(&amp;child); self.children.push(child); self.children.last().unwrap() } pub fn add_parent(&amp;mut self, name: &amp;str) -&gt; &amp;Rc&lt;RefCell&lt;Parent&gt;&gt; { if self.parent(name).is_some() { panic!(format!("Parent '{}' already exists.", name)); } let parent = Rc::new(RefCell::new(Parent::new(name))); self.parents.push(parent); self.parents.last().unwrap() } pub fn parent(&amp;self, name: &amp;str) -&gt; Option&lt;&amp;Rc&lt;RefCell&lt;Parent&gt;&gt;&gt; { self.parents.iter() .find(|p| p.borrow().name == name) } pub fn child(&amp;self, name: &amp;str) -&gt; Option&lt;&amp;Rc&lt;RefCell&lt;Child&gt;&gt;&gt; { self.children.iter() .find(|c| c.borrow().name == name) } } #[cfg(test)] mod tests { use super::*; #[test] #[allow(unused_variables)] fn simple_test() { let mut container = Container::new(); let p1 = container.add_parent("parent1").clone(); let p1_c1 = container.add_child("parent1-child1", &amp;p1).clone(); let p1_c2 = container.add_child("parent1-child2", &amp;p1).clone(); // Here are tests as well as examples of how I would you use this code: // Get the parent of parent1-child1; assert_eq!(p1_c1.borrow().strong_parent().borrow().name, "parent1"); // Get a child from parent1: assert_eq!( p1.borrow().strong_child("parent1-child2").unwrap().borrow().name, "parent1-child2" ); } } <span class="math-container">```</span> </code></pre>
[]
[ { "body": "<p>Since the child is read-only after creation, couldn't you use <code>Child</code> instead of <code>RefCell&lt;Child&gt;</code>?</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-04T07:45:43.833", "Id": "477687", "Score": "0", "body": "This is a nice and appropriate simplication, thank you" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-04T00:10:59.627", "Id": "243350", "ParentId": "243250", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-02T06:49:35.047", "Id": "243250", "Score": "2", "Tags": [ "rust", "reference", "weak-references" ], "Title": "Handling Rc pointers correctly in a parent/children tree" }
243250
<p>This is a follow up for <a href="https://codereview.stackexchange.com/questions/243217/how-to-apply-python-generators-to-finding-min-and-max-values">my question</a> about optimizing solution for <em>DNA Health</em> HackerRank problem.</p> <p>Short re-cap: </p> <blockquote> <p>You are given 2 arrays (<code>genes</code> and <code>health</code>), one of which have a 'gene' name, and the other - 'gene' weight (aka <em>health</em>). You then given a bunch of strings, each containing values <code>m</code> and <code>n</code>, which denote the start and end of the slice to be applied to the <code>genes</code> and <code>health</code> arrays, and the 'gene'-string, for which we need to determine healthiness. Then we need to return health-values for the most and the least healthy strings.</p> </blockquote> <p>At the advice from AJNeufeld, I optimized my code into the following. Unfotunately, it still fails to execute on large testcases, such as <a href="https://hr-testcases-us-east-1.s3.amazonaws.com/32614/input28.txt?AWSAccessKeyId=AKIAJ4WZFDFQTZRGO3QA&amp;Expires=1591090119&amp;Signature=nz9iI5v4DWZbC1SYEPtuttdC1gg%3D&amp;response-content-type=text%2Fplain" rel="noreferrer">this one</a>.</p> <p>So, the question now is: what else can I do to make the solution less expensive?</p> <pre><code>if __name__ == '__main__': n = int(input()) genes = input().rstrip().split() genes_regex = [re.compile(f"(?={gene})") for gene in genes] health = list(map(int, input().rstrip().split())) s = int(input()) min_weight = math.inf max_weight = -math.inf for s_itr in range(s): m,n,gn = input().split() weight = 0 for i in range(int(m),int(n)+1): if genes[i] in gn: matches = len(re.findall(genes_regex[i], gn)) weight += health[i]*matches if weight &lt; min_weight: min_weight = weight if weight &gt; max_weight: max_weight = weight print(min_weight, max_weight) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-02T17:39:08.883", "Id": "477482", "Score": "0", "body": "Timing measurements for small testcase:\n\nVersion 1(original): **0.0080** averaged accross 5 attempts (100 cycles each) (min=0.006530, max=0.010242)\n\nVersion 2(current): **0.0029** averaged accross 5 attempts (100 cycles each) (min=0.002103, max=0.003921)\n\nAs you can see, version 2 is faster than version 1 almost 3 times" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-02T17:43:33.657", "Id": "477483", "Score": "0", "body": "Timing measurements for a large testcase.\n\nVersion 1: single attempt with 1 cycle - **234.6446889**\n\nVersion 2: single attempt with 1 cycle - **164.2045158**\n\nDefinitely better, but still rather expensive" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-02T20:56:00.527", "Id": "477501", "Score": "0", "body": "The measurements don't help much unless we know what the test cases looked like. Put them in the question or link to a pastebin. Or at least for the large test case: how many genes, how many gene strings, how long are the gene strings, how many (min, max) genes are tested against each gene string? Try running the profiler on you code to see where it si spending time. (My guess is the nested loops)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-02T21:07:57.213", "Id": "477503", "Score": "0", "body": "The small testcase mentioned can be found in the first question asked (https://codereview.stackexchange.com/questions/243217/how-to-apply-python-generators-to-finding-min-and-max-values). The large one I will put on pastebin a little latter, but the lists (`genes` & `health`) are 100K each, and then there are 41K+ genes to test" } ]
[ { "body": "<p>There are three obvious suggestions here.</p>\n\n<h1>Measure!</h1>\n\n<p>First, and most important: develop a timing framework to measure your changes! You can't know if a change is beneficial if all you have is \"the old version doesn't pass\" and \"the new version doesn't pass\". </p>\n\n<p>Build a standard set of test cases, and a timing framework, and subject any change to measurement in the timing framework. It's better if the timing is better, otherwise it's not.</p>\n\n<h1>Cache your results</h1>\n\n<p>The examples shown at the hackerrank site specifically include one where the same gene string is repeated twice. So it seems likely that caching your results might provide an obvious performance win. </p>\n\n<h1>Stop using the regex engine</h1>\n\n<p>This is a \"maybe.\" You're using the regex engine to get the <code>findall</code> behavior, which is sensible, since it gives you access to C code that does what you want. But using that engine comes at a price -- regex operations are traditionally slower than string operations. So see if you can write your code to do the same job without using regex calls. </p>\n\n<p>I'm honestly not sure if this will benefit you or not, since the regexes you are using are so simple. But if you pre-compute the minimum offset for each pattern, to allow for overlaps (like \"a\" -> +1, \"aa\" -> +1, \"ab\" -> +2) you should be able to scan using <code>str.find</code> or <code>str.index</code> and get what you want without any <code>re</code> calls.</p>\n\n<h1>Bonus: generator</h1>\n\n<p>Your original question asked about using generators. Because the underlying operation is so expensive, I'd suggest writing a single <code>minmax</code> function that yields both values at the same time (like <code>divmod</code> does). You can feed that function with a generator that yields up the scores:</p>\n\n<pre><code>queries = [input() for _ in range(s)]\nlow, high = minmax(gene_scores(int(l[0]), int(l[1]), l[2] for l in queries))\n</code></pre>\n\n<p>(This has nothing to do with performance. But you wanted to use them, so here's a way!)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-02T22:02:11.847", "Id": "477514", "Score": "0", "body": "Thank you, Austin\nQuick question: I'm trying to use `lru_cache` from `functools` to optimize code, and I'm getting *TypeError: unhashable type: 'list'*. In the 2nd version of the solution it is probably because of `genes_regex = [re.compile(f\"(?={gene})\") for gene in genes]` line. Or can it be the inputs? Any suggestions?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-03T00:21:57.407", "Id": "477527", "Score": "1", "body": "@DenisShvetsov since `@lru_cache` is a function decorator, it must be on a function you have written. So that's where the `list` type is being returned in error. Make sure you are caching single-item functions, since those are the ones likely to provide benefit from caching." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-02T11:31:59.377", "Id": "243259", "ParentId": "243254", "Score": "5" } }, { "body": "<h3>Aho-Corasick algorithm</h3>\n\n<p>Perhaps another approach is in order. I'd suggest the <a href=\"https://en.wikipedia.org/wiki/Aho%E2%80%93Corasick_algorithm\" rel=\"nofollow noreferrer\">Aho-Corasick</a> algorithm. Here's the original paper <a href=\"http://cr.yp.to/bib/1975/aho.pdf\" rel=\"nofollow noreferrer\">Efficient String Matching: An Aid to Bibliographic Search</a> (pdf).</p>\n\n<ol>\n<li>Create a mapping from gene to gene index and weight.</li>\n<li>Build the DFA with the all of the genes.</li>\n<li>Loop over the DNA tests</li>\n<li>Scan each DNA test using the DFA.</li>\n<li>For each gene returned by the DFA, look up the index and weight.</li>\n<li>If the index is in the allowed range for that DNA, add the weight to the running total for that DNA</li>\n<li>Keep track of the min and max scores for each DNA test</li>\n<li>Output the results</li>\n</ol>\n\n<p>Don't have time now. I'll try to code it up later.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-05T06:55:19.697", "Id": "477766", "Score": "0", "body": "This is very interesting. But maybe don't publish your code here right away. I would like to try and figure it out myself, if you don't mind" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-06T23:18:59.070", "Id": "477936", "Score": "0", "body": "Hey, @RootTwo, can you please check out https://codereview.stackexchange.com/questions/243500/aho-corasick-algorithm-to-scan-through-a-list-of-strings - it's my attempt to apply Aho-Corasick using ahocorapy (https://github.com/abusix/ahocorapy/blob/master/README.md), but it doesn't work well." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-04T02:09:31.250", "Id": "243354", "ParentId": "243254", "Score": "2" } } ]
{ "AcceptedAnswerId": "243259", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-02T07:47:20.810", "Id": "243254", "Score": "7", "Tags": [ "python", "beginner", "python-3.x", "programming-challenge" ], "Title": "Finding min and max values of an iterable on the fly" }
243254
<p>I use this function in browser automation. It pings the document in the browser to check if an element we are looking for is available (useful when there is JavaScript generated async content). If it's not available, it will retry after a given interval or times out eventually.</p> <p><strong>Example usage:</strong></p> <pre><code>function clickContinue() { return $(":contains('Continue')"); } elementFinder(clickContinue).then(el =&gt; el.click()); </code></pre> <p><strong>Function:</strong></p> <pre><code>// accepts both document.querySelector and jQuery() selector function elementFinder(selectorFn) { const interval = 500; const timeout = 8000; const maxTries = timeout / interval; function checkerFn(resolve, reject, tryCount=0) { if(tryCount &gt; maxTries) { reject(`Timeout ${timeout}ms reached when searching for element`); return; } setTimeout(() =&gt; { const el = selectorFn(); // null check is for document.querySelector, zero check is for jQuery() if(el !== null &amp;&amp; el.length !== 0) { resolve(el); return; } tryCount += 1; checkerFn(resolve, reject, tryCount) }, tryCount === 0 ? 0 : interval); } return new Promise(function(resolve, reject) { checkerFn(resolve, reject) }); } </code></pre> <p>It seems weird to me that I define a function within a function, wonder if this can be maybe done with one function or if there are some other issues.</p>
[]
[ { "body": "<p>This function will certainly do the job. Couple of nitpicks:</p>\n\n<ul>\n<li><p>You might consider replacing <code>el !== null &amp;&amp; el.length !== 0</code> with <code>el &amp;&amp; \"nodeType\" in el</code></p></li>\n<li><p>Every time the elementFinder is called, you are defining a new function in memory called <code>checkerFn</code>, instead you can reuse it, but probably you'll have to pass <code>interval</code> and <code>maxTries</code> as a parameter to it:</p></li>\n</ul>\n\n<pre><code>const finder = function(){\n function elementFinder (..){\n ...\n }\n function checkerFn (..) {\n ...\n }\n return elementFinder;\n}();\n</code></pre>\n\n<ul>\n<li><p>Consider switching to <code>requestAnimationFrame</code> (<code>rAF</code>); for tasks/animations that does not have to be executed with sub-millisecond precision can be handled by <code>rAF</code>. The good thing with rAF is that if the tab is out of focus, it won't run.</p></li>\n<li><p>If you are simultaneously searching for several elements at the same time, multiple <code>setTimeout</code>/<code>rAF</code> calls will have to be executed. For a couple of elements/tasks this is not an overhead, but if you have many, it makes sense to execute 1 <code>setTimeout</code>/<code>rAF</code> per 'tick' and process the tasks in there. For this you will need to modify your code to store tasks in some sort of ledger.</p></li>\n<li><p>I see that you are using Promises, which is a great idea, perhaps to return a <code>thenable</code> from your function which you can execute other tasks once the element is available. The problem with Promises is that you cannot 'break' out of it, you'll have to add some sort of breaking mechanism to your code. Also if you want to seamlessly support evergreen and older browsers, you'll need a Promise polyfill. </p></li>\n<li><p>Although Promises bring a lot of convenience, they certainly bring an overhead (see perf differences between Native Promises and <a href=\"http://bluebirdjs.com/docs/getting-started.html\" rel=\"nofollow noreferrer\">Bluebird's version</a>). If the sole purpose is to return a <code>thenable</code> for constructing chains, this can certainly be implemented using only <code>setTimeout</code>/<code>rAF</code>. This alleviates the need for polyfill for olderbrowsers.</p></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-03T08:21:44.557", "Id": "243302", "ParentId": "243258", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-02T11:08:25.060", "Id": "243258", "Score": "2", "Tags": [ "javascript", "recursion", "dom" ], "Title": "Recursive function with Promise and setTimeout to ping DOM" }
243258
<p>I've created a serial C++ code for gravitational N-Body calculation. Because I expect to have upwards of 8-71 sparse bodies (ie, where Barnes-Hut is not necessarily practical) and running for long periods of time, I want to make as much use of parallelization and vectorization as possible. I did try a method with mutex and conditional_variable however, I found that this implementation works significantly faster: locking and unlocking mutexes proved more overhead for relatively short functions for threads. Forgive my probably obnoxious attempt at this, it is my first attempt at anything parallel and/or vectorized and I'm still new with C++, so I expect there will be plenty of criticism. </p> <p>It is just two classes, Body and NBody and a helper namespace mathx.</p> <p><strong>Body.h</strong></p> <pre><code>#pragma once #include &lt;immintrin.h&gt; #include &lt;intrin.h&gt; struct Body { __m256d pos, vel; double mu; Body(); Body(double MU, const __m256d&amp; position, const __m256d&amp; velocity); Body(const Body&amp; orig); ~Body(); virtual __m256d grav(const __m256d &amp; R) const; void push(const __m256d &amp; acc, const __m256d &amp; dt); }; </code></pre> <p><strong>Body.cpp</strong></p> <pre><code>#include "Body.h" #include &lt;cmath&gt; Body::Body() { mu = 1; pos = _mm256_setzero_pd(); vel = _mm256_setzero_pd(); } Body::Body(double MU, const __m256d&amp; position, const __m256d&amp; velocity){ pos = position; vel = velocity; mu = MU; } Body::Body(const Body&amp; orig) { pos = orig.pos; vel = orig.vel; mu = orig.mu; } Body::~Body() { } __m256d Body::grav(const __m256d &amp; R) const { const double g = mu/(R[3]*R[3]*R[3]); return _mm256_mul_pd(_mm256_broadcast_sd(&amp;g),R); } void Body::push(const __m256d &amp; acc, const __m256d &amp; dt){ vel = _mm256_fmadd_pd(acc,dt,vel); pos = _mm256_fmadd_pd(vel,dt,pos); } </code></pre> <p><strong>NBody.h</strong></p> <pre><code> #pragma once #include "orbital/Body.h" #include &lt;vector&gt; #include &lt;atomic&gt; #include &lt;stdint.h&gt; #include &lt;thread&gt; class alignas(32) NBody { public: NBody(); ~NBody(); void addBody(const Body &amp; b); void par_leapfrog(double time); void par_step(); void setTime(double time); void setTimestep(double step); void setTimeInterval(double t_interval); void output(std::string filename); private: // Body Stuff std::vector&lt; Body &gt; bodies; std::vector&lt; double &gt; times; std::vector&lt; std::vector&lt; double * &gt; &gt; positions; // for some reason cant store __m256d void setup(); void getNThreads(); void leapfrog_halfstep(); // Time Stuff double t = 0., dt = 5, time_interval = 3600.0, t_test = 0.; __m256d _dt; // Gate / Parallel Stuff std::atomic&lt;uint_fast8_t&gt; nFinished = 0; bool done = false; bool step = false; bool accelerate = false; bool push = false; // Thread Function void worker(); // Internal Variables uint_fast8_t nBodies,nThreads,nR; std::atomic&lt;uint_fast8_t&gt; idxR, idxBody; __m256d * R; // array of vector distance between bodies }; </code></pre> <p><strong>NBody.cpp</strong></p> <pre><code>#include "NBody.h" #include &lt;utility&gt; #include "geometry/mathx.h" #include &lt;iostream&gt; #include &lt;string&gt; #include &lt;cmath&gt; NBody::NBody() { _dt = _mm256_broadcast_sd(&amp;dt); } NBody::~NBody() { } void NBody::addBody(const Body &amp; b){ bodies.push_back(b); } void NBody::par_leapfrog(double time){ setup(); leapfrog_halfstep(); // single threaded half step std::thread body_threads[nThreads]; for(uint_fast8_t i = 0; i &lt; nThreads; i++){ body_threads[i] = std::thread(&amp;NBody::worker, this); body_threads[i].detach(); } while(t &lt; time) { par_step(); if(t &gt; t_test) { times.push_back(t); t_test += time_interval; } t += dt; } done = true; // threads will destroy here } void NBody::setup() { t_test = t; nBodies = bodies.size(); done = false; positions.resize(nBodies); nR = mathx::combination(nBodies,2); R = new __m256d[nR]; // reset this step = false; accelerate = false; done = false; getNThreads(); } void NBody::leapfrog_halfstep() { // single thread this for convenience __m256d acc; __m256d dt2 = _mm256_set_pd(dt/2,dt/2,dt/2,dt/2); for(uint_fast8_t i = 0; i &lt; nBodies;i++) { acc = _mm256_setzero_pd(); for(uint_fast8_t j = 0; j &lt; nBodies; j++) { if(i != j) { __m256d R_tmp = _mm256_sub_pd(bodies[j].pos,bodies[i].pos); __m256d tmp = _mm256_mul_pd(R_tmp,R_tmp); R_tmp[3] = sqrt(tmp[0]+tmp[1]+tmp[2]); acc = _mm256_add_pd(acc,bodies[j].grav(R_tmp)); } } bodies[i].vel = _mm256_fmsub_pd(acc,dt2,bodies[i].vel); } } void NBody::getNThreads() { int max = std::thread::hardware_concurrency()-1; if (nBodies &lt; max){ nThreads = nBodies; } else { if (max &gt; 0) { nThreads = max; } else { nThreads = 2; } } } void NBody::par_step(){ // Gate 1 idxR = 0; nFinished = 0; step = true; while(nFinished &lt; nThreads){} step = false; // Gate 2 idxBody = 0; nFinished = 0; accelerate = true; while(nFinished &lt; nThreads){} accelerate = false; } void NBody::worker() { __m256d acc; uint_fast8_t i_body,j_body,ix,ix1; // Generate indexes locally uint_fast8_t is[nR]; uint_fast8_t js[nR]; uint_fast8_t idx_R[nBodies][nBodies]; unsigned int count = 0; for ( i_body = 0; i_body &lt; nBodies;i_body++) { for( j_body = i_body+1; j_body &lt; nBodies; j_body++) { is[count] = i_body; js[count] = j_body; count++; } } for(i_body = 0; i_body &lt; nBodies; i_body++){ for(j_body = 0; j_body &lt; nBodies; j_body++) { if(j_body &gt; i_body) { idx_R[i_body][j_body] = (i_body*nBodies + j_body - mathx::combination(i_body+2,2)); } else { idx_R[i_body][j_body] = (j_body*nBodies + i_body - mathx::combination(j_body+2,2)); } } } while (!done) { while(!step){if(done) return;} while(idxR &lt; nR) { ix = idxR.fetch_add(2); if(ix &gt;= nR) { break; } ix1 = ix+1; __m256d dr1 = _mm256_sub_pd(bodies[js[ix]].pos,bodies[is[ix]].pos); __m256d dr1_sq = _mm256_mul_pd( dr1,dr1 ); if(ix1 &lt; nR) { __m256d dr2 = _mm256_sub_pd(bodies[js[ix1]].pos,bodies[is[ix1]].pos); __m256d dr2_sq = _mm256_mul_pd( dr2,dr2 ); __m256d temp = _mm256_hadd_pd( dr1_sq, dr2_sq ); __m128d hi128 = _mm256_extractf128_pd( temp, 1 ); __m128d dotproduct_sqrt = _mm_sqrt_pd(_mm_add_pd( _mm256_castpd256_pd128(temp), hi128 )); dr1[3] = dotproduct_sqrt[0]; dr2[3] = dotproduct_sqrt[1]; R[ix] = std::move(dr1); R[ix1] = std::move(dr2); } else { dr1[3] = sqrt(dr1_sq[0]+dr1_sq[1]+dr1_sq[2]); R[ix] = std::move(dr1); } } nFinished++; while(!accelerate){} while(idxBody &lt; nBodies) { // this check is quick and avoids having to fetch add again i_body = idxBody++; //i_body = idxBody.fetch_add(1); if(i_body &gt;= nBodies){ break; } // Store position prior to push if (t &gt; t_test) { double pos[] = new double[3]{bodies[i_body].pos[0],bodies[i_body].pos[1],bodies[i_body].pos[2]}; positions[i_body].push_back(pos)); } // sum gravitational acclerations acc = _mm256_setzero_pd(); for(j_body = 0; j_body &lt; nBodies; j_body++) { // reverse vector (subtract) if index are reverse order if(j_body &gt; i_body) { acc =_mm256_add_pd(bodies[j_body].grav(R[idx_R[i_body][j_body]]),acc); } else if (j_body &lt; i_body) { acc =_mm256_sub_pd(bodies[j_body].grav(R[idx_R[i_body][j_body]]),acc); } } bodies[i_body].push(acc,_dt); } nFinished++; } } void NBody::setTime(double time){ t = time; } void NBody::setTimestep(double step){ dt = step; _dt = _mm256_broadcast_sd(&amp;dt); } void NBody::setTimeInterval(double t_interval){ time_interval = t_interval; } </code></pre> <p><strong>mathx.h</strong></p> <pre><code>#pragma once #include &lt;vector&gt; #include &lt;utility&gt; #define UINT unsigned int namespace mathx { double legendrePoly(UINT n, double x); double assocLegendrePoly(UINT l, UINT m, double x); const unsigned long long factorial[] = {1,1,2,6,24,120,720,5040,40320,362880,3628800,39916800,479001600,6227020800,87178291200,1307674368000,20922789888000,355687428096000,6402373705728000,121645100408832000,2432902008176640000}; double generalBinomial(double alpha, UINT k); const UINT C[11][11] = {{1},{1,1},{1,2,1},{1,3,3,1},{1,4,6,4,1},{1,5,10,10,5,1},{1,6,15,20,15,6,1},{1,7,21,35,35,21,7,1},{1,8,28,56,70,56,28,8,1},{1,9,36,84,126,126,36,9,1},{1,10,45,120,210,252,210,120,45,10,1}}; UINT combination(UINT n, UINT k); } </code></pre> <p><strong>mathx.cpp</strong></p> <pre><code> #include "mathx.h" #include &lt;cmath&gt; namespace mathx { double legendrePoly(UINT n, double x){ if (n == 0) return 1; if (n == 1) return x; double sums = 0; for (UINT k = 0; k &lt; n; k++) { if (k &gt; 3){ sums += pow(x,k) * (combination(n,k) * generalBinomial((n+k-1)*0.5,n)); } else { if(k == 0) { sums += generalBinomial((n+k-1)*0.5,n); } else { if(k == 1) { sums += x * n * generalBinomial((n+k-1)*0.5,n); } else { sums += x * n * generalBinomial((n+k-1)*0.5,n); } } } } return (1&lt;&lt;n) * sums; } double assocLegendrePoly(UINT l, UINT m, double x){ int sums = 0; for (UINT k = m; k &lt;= l; k++) { int prod = k; for (UINT j = m; m &lt; k; m++) prod *= j; sums += prod* pow(x,k-m) * combination(l,k) * generalBinomial((l+k-1)*0.5,l); } if (m % 2 == 0) return (1&lt;&lt;l) * pow((1-x*x),m/2) *sums; else return -1 * (1&lt;&lt;l) * pow((1-x*x),m*0.5) *sums; } double generalBinomial(double alpha, UINT k){ // this can be further optimized for half values required by legendre double res = 1; for (UINT i = 1; i &lt;= k; ++i) res = res * (alpha - (k + i)) / i; return res; } UINT combination(UINT n, UINT k) { if(n &lt;= 10) { return C[n][k]; } if(k &gt; n/2){ return combination(n,n-k); } UINT num = n; UINT den = k; //vectorizable for(UINT i = 1; i &lt; k; i++){ den *= i; num *= (n-i); } return num/den; } } </code></pre> <p>Thanks in advance!</p> <p>EDIT:</p> <p>Adding some of my testing calls that I used, really basic stuff I just inserted into a main function.</p> <pre><code> int test_parallel(int n, double t) { //unsigned seed1 = std::chrono::system_clock::now().time_since_epoch().count(); std::default_random_engine generator; std::uniform_real_distribution&lt;double&gt; mus (1.0,2.0); std::uniform_real_distribution&lt;double&gt; xs (-2.0,2.0); NBody sim; for(int i = 0; i&lt;n;i++) { sim.addBody(Body(mus(generator),_mm256_set_pd(0.0,xs(generator),xs(generator),xs(generator)),_mm256_set_pd(0.0,xs(generator),xs(generator),xs(generator))) ); } std::cout &lt;&lt; "start test 3 \n"; auto t1 = std::chrono::high_resolution_clock::now(); sim.par_leapfrog(t); auto t2 = std::chrono::high_resolution_clock::now(); std::cout &lt;&lt; "test function took " &lt;&lt; std::chrono::duration_cast&lt;std::chrono::milliseconds&gt;(t2-t1).count() &lt;&lt; " milliseconds \n"; return 0; } </code></pre> <pre><code>int testBody() { Body B = Body(2, _mm256_set_pd(0.0,1.0,1.0,1.0),_mm256_set_pd(0.0,-1.0,-1.0,-1.0)); __m256d dt = _mm256_set_pd(1.0,1.0,1.0,1.0); __m256d acc = _mm256_set_pd(2.0,2.0,2.0,2.0); B.push(acc,dt); if(abs(B.pos[0]-2.0) &lt; 1e-12 &amp;&amp; abs(B.pos[1]-2.0) &lt; 1e-12 &amp;&amp; abs(B.pos[2]-2.0) &lt; 1e-12) { if(abs(B.vel[0]-1.0) &lt; 1e-12 &amp;&amp; abs(B.vel[1]-1.0) &lt; 1e-12 &amp;&amp; abs(B.vel[2]-1.0) &lt; 1e-12) { return 0; } else { return 2; } } else { return 1; } } </code></pre> <pre><code>int testGravity() { Body B = Body(); B.mu = 16; __m256d R = _mm256_set_pd(2.0,0.0,2.0,0.0); __m256d g = B.grav(R); if(abs(g[1]-4.0) &lt; 1e-12 ) { if(abs(g[0]) &gt; 1e-12 ) { return 2; } return 0; } else { return 1; } } <span class="math-container">```</span> </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-02T16:49:33.663", "Id": "477476", "Score": "0", "body": "I've unit tested just about everything as part of my serial C++ code. The thing that I haven't been able to test was the NBody.cpp output because I would need to export the output and compare it to my serial, which I am currently working on. I just figured I'd post this now." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-02T16:57:48.727", "Id": "477479", "Score": "0", "body": "Since the `Vec3` class is completely superfluous, it should not be included as part of this review. You could create a source file demonstrating its use then post it as part of a different question." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-02T17:28:04.970", "Id": "477480", "Score": "0", "body": "Looks like you got something good going, but you're a bit early in the process to get it reviewed. Please, feel free to come back once you've verified your code actually does what it's supposed to do." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-08T18:20:12.843", "Id": "478087", "Score": "0", "body": "I have rolled back Rev 3 → 2. Please see [_What to do when someone answers_](https://codereview.stackexchange.com/help/someone-answers)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-08T18:27:53.003", "Id": "478088", "Score": "0", "body": "Thanks, new here, will create new one." } ]
[ { "body": "<h1>Data layout</h1>\n<p>You have already experienced first-hand a disadvantage of using &quot;1 physics vector = 1 SIMD vector&quot; (such as <code>__m256d pos</code>), causing some friction when coordinates come together:</p>\n<pre><code>__m256d temp = _mm256_hadd_pd( dr1_sq, dr2_sq );\n__m128d hi128 = _mm256_extractf128_pd( temp, 1 );\n__m128d dotproduct_sqrt = _mm_sqrt_pd(_mm_add_pd( _mm256_castpd256_pd128(temp), hi128 ));\n</code></pre>\n<p>Mixing different coordinates in the same SIMD vector leads to horizontal addition and shuffles and extraction and such. Horizontal addition is relatively expensive, equivalent to two shuffles plus a normal addition. <code>_mm256_castpd256_pd128</code> is free, but extracting the upper half is not.</p>\n<p>That strategy of using the 4th component for a different value is also a problem, causing even more extract/insert operations. As a rule of thumb, avoid indexing into SIMD vectors. It's fine to use that construct a bit in a pinch, but I would say it's overused here.</p>\n<p>There is an alternative: put the X components of 4 physics vectors together into a SIMD vector, Y in an other SIMD vector, etc. You could have groups of 4 bodies together (AoSoA), or a big array of just X and an other of Y and so on (SoA).</p>\n<p>That's a significant rewrite, but I recommend it. That <code>Vec3</code> that was mentioned, I recommend against the entire idea. It's still using SIMD against the grain. It's a really &quot;attractive looking trap&quot;, letting you express the computation in a way that feels nice, but it's not a way that results in good code.</p>\n<h1>Unnecessary move</h1>\n<p>Moving SIMD vectors is not useful. They're trivial to copy and hold no resource.</p>\n<h1>Alignment</h1>\n<p>Aligning <code>NBody</code> aligns its first field, which is an <code>std::vector</code> (so the vector object itself, not the data it holds). That's not useful, but also not harmful. <code>std::vector</code> should, as of C++17, respect the alignment of the data inside it (before 17, that was simply broken).</p>\n<h1>Scary synchronization</h1>\n<p><code>bool accelerate</code> should not be used for synchronization, it makes this construct unsafe: <code>while(!accelerate){}</code>. That loop may not terminate, or it may work as intended, it's not reliable. Using <code>atomic&lt;bool&gt;</code> would make the threads communicate safely.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-02T20:09:49.300", "Id": "477494", "Score": "0", "body": "I'll just convert all the bools to atomics, thanks! As for the rewrite of the vectors... I figured my version was suboptimal, that's part of the reason I dropped the vec3 idea too because I figured I would load all x components into an array and vectorize that big array. Should I align the individual fields including integer variables (nBodies, nThreads etc) instead?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-02T21:02:29.913", "Id": "477502", "Score": "1", "body": "@MariusPopescu don't bother aligning random things, the main data should be aligned to its natural alignment (eg `__m256d` should be aligned 32 bytes) but in C++17 that is supposed to happen automatically" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-04T13:47:55.237", "Id": "477700", "Score": "0", "body": "Thanks for your help!" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-02T19:50:37.710", "Id": "243279", "ParentId": "243268", "Score": "3" } }, { "body": "<p><strong>Basics:</strong></p>\n\n<p>Body.h/Body.cpp</p>\n\n<p>The class <code>Body</code> is extremely simple and all its functions are under 5 lines. Calling a function is a relatively heavy operation and calling a virtual function is even more so. Putting but a few operations inside a function will make it an inefficient call. Unless, the function is inlined. The compiler cannot inline functions that are hidden from compilation - so you should move all the quick functions to the header and keep cpp for the heavier stuff.</p>\n\n<p>P.S. why does this class even have a virtual function? you don't utilize the property anywhere.</p>\n\n<p><strong>Multithreading:</strong></p>\n\n<p>Inherently, when you multithread your code, the computer has to do more work. All the data synchronization and memory-ownership swapping is not cheap for low-level code. So it is quite possible that the single threaded version would run faster - or at the same speed just with single core at maximal capacity instead of all of them.</p>\n\n<p>If the number of bodies would be huge, like a few thousands, then perhaps multi-threading will improve performance. Though, the exact numbers surely depends on the platform and implementation.</p>\n\n<p>You should read more on <code>std::atomic</code> as regular operations like <code>++, --, +=, -=, =</code> are slow and usually unnecessarily so. You should read its memory model and use operations like <code>load, store, fetch_add...</code> with appropriate memory instructions.</p>\n\n<p><strong>Linear Algebra:</strong></p>\n\n<p>As suggested by @harold, you shouldn't use <code>__m256d</code> for storing x,y,z coordinates of the body but rather store's n-body's coordinates in a 3xn matrix. Also this way you can perform matrix level operations and utilize SIMD types more efficiently: e.g., you don't waste a coordinate and you can utilize AVX512 instructions which holds twice as much data as <code>__m256d</code>.</p>\n\n<p><strong>Algorithm:</strong></p>\n\n<p>You use a very basic and inaccurate algorithm for N-Body computation: <code>V(t+dt) = V(t) +dt*a(t)</code> and <code>P(t+dt) = P(t)+dt*V(t+dt)</code>.\nI think this is like first order of inaccuracy. What's the point of running the simulation for a long time if it is of such a low accuracy?</p>\n\n<p>You should check out better solutions like <a href=\"https://en.wikipedia.org/wiki/Runge%E2%80%93Kutta_methods\" rel=\"nofollow noreferrer\">Runge–Kutta methods</a>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-03T17:01:54.693", "Id": "477609", "Score": "0", "body": "The virtual function will be used later, some planets have spherical harmonics. Even this multithreaded approach is 3x faster than serial. As I understand it, += is the same as fetch add. I am rewriting the way I use SIMD. Leapfrog is symplectic, runge kutta is not, so better for long term angular momentum conservation. There are multi step symplectic methods, but I mostly wanted to figure out the parallelization first." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-03T17:30:44.690", "Id": "477611", "Score": "0", "body": "`+=` is same as `fetch_add` with memory instruction `memory_order_seq_cst`. The difference lies in memory instructions. Did you compare it with atomic-less straightforward single core in both terms of efficiency and accuracy? It could be fast because it produces wrong results." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-04T13:49:24.570", "Id": "477701", "Score": "0", "body": "I wanted to keep the most strict memory instruction so that worked out for me anyway. But yes, originally posted the code produced the same results as single core, (and no instrinsic instructions)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-04T14:51:26.590", "Id": "477707", "Score": "0", "body": "@MariusPopescu about virtual functions and low level code - if you have only a couple of low level types with only minor variations then it is better to just distinguish them via an enum or store in different vectors with different types. Keep the virtual functions / polymorphism for higher level objects. It is not advisable for it to be applied to low level types." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-08T13:10:09.923", "Id": "478053", "Score": "0", "body": "The reason for the virtual function is the that gravitational calculations for bodies with off spherical values are far more complicated, hence the reason for the polymorphism. We typically only model them for Earth, Moon, Mars, but even Sun and any body we may do longer term maneuvers in. Also perturbation terms can be added in the push calculation if needed." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-09T03:34:26.360", "Id": "478109", "Score": "0", "body": "@MariusPopescu to utilize the virtual method you'll have to store data in a rather inefficient manner as you cannot make a vector of different polymorphic types. I advise you to use some other scheme instead of virual functions - i.e., store a function pointer or have an enum that identifies the computation model." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-09T15:27:31.510", "Id": "478160", "Score": "0", "body": "I like the idea of a function pointer, I will look into doing that!" } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-03T10:00:45.890", "Id": "243308", "ParentId": "243268", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-02T14:55:42.300", "Id": "243268", "Score": "10", "Tags": [ "c++", "performance", "multithreading", "c++17", "vectorization" ], "Title": "N-Body Optimization" }
243268
<p>I am completely new to rust. My first rust code is simple text filter application for parsing log file and accumulating some information. Here is my code:</p> <pre><code>//use std::io::{self, Read}; use std::io::{self}; use regex::Regex; fn main() -&gt; io::Result&lt;()&gt; { let re_str = concat!( r"^\s+(?P&lt;qrw1&gt;\d+)\|(?P&lt;qrw2&gt;\d+)",//qrw 0|0 r"\s+(?P&lt;arw1&gt;\d+)\|(?P&lt;arw2&gt;\d+)",//arw 34|118 ); let re = Regex::new(re_str).unwrap(); //let mut buffer = String::new(); //io::stdin().read_to_string(&amp;mut buffer)?; let buffer = " 0|1 2|3\n 4|5 6|7\n 8|9 10|11\n"; let mut lines_skipped = 0; let mut m_qrw1:i32 = 0; let mut m_qrw2:i32 = 0; let mut m_arw1:i32 = 0; let mut m_arw2:i32 = 0; for line in buffer.lines() { match re.captures(line) { Some(caps) =&gt; { // I would like to shorten these long lines =&gt; let qrw1 = caps.name("qrw1").unwrap().as_str().parse::&lt;i32&gt;().unwrap(); let qrw2 = caps.name("qrw2").unwrap().as_str().parse::&lt;i32&gt;().unwrap(); let arw1 = caps.name("arw1").unwrap().as_str().parse::&lt;i32&gt;().unwrap(); let arw2 = caps.name("arw2").unwrap().as_str().parse::&lt;i32&gt;().unwrap(); if qrw1 &gt; m_qrw1 {m_qrw1 = qrw1} if qrw2 &gt; m_qrw2 {m_qrw2 = qrw2} if arw1 &gt; m_arw1 {m_arw1 = arw1} if arw2 &gt; m_arw2 {m_arw2 = arw2} } None =&gt; { lines_skipped = lines_skipped + 1; } } } println!("max qrw1: {:.2}", m_qrw1); println!("max qrw2: {:.2}", m_qrw2); println!("max arw1: {:.2}", m_arw1); println!("max arw2: {:.2}", m_arw2); Ok(()) } </code></pre> <p><sup><a href="https://play.rust-lang.org/?version=stable&amp;mode=debug&amp;edition=2018&amp;gist=e32a89603a8970905d19e932d0cbcee0" rel="nofollow noreferrer">Playground</a> </sup></p> <p>This works as expected, but I think those long chained calls which I created to get integer values of regex named capture groups are a bit ugly. How do I make them shorter/more in idiomatic rust style? I've got an advice to use ? operator instead of <code>unwrap</code> calls but I'm not sure how to apply it in this case.</p>
[]
[ { "body": "<p><code>regex::Captures</code> provides a handy <a href=\"https://docs.rs/regex/1.3.9/regex/struct.Captures.html#impl-Index%3C%26%27i%20str%3E\" rel=\"nofollow noreferrer\">implementation of <code>Index&lt;&amp;str&gt;</code></a>. This lets you pull named matches out with <code>caps[name]</code>. Combine that with a few <code>std</code> APIs and you can write the same code like this:</p>\n\n<pre class=\"lang-rust prettyprint-override\"><code>use regex::Regex;\n\nfn main() -&gt; Result&lt;(), Box&lt;dyn std::error::Error&gt;&gt; {\n let re = Regex::new(concat!(\n r\"^\\s+(?P&lt;qrw1&gt;\\d+)\\|(?P&lt;qrw2&gt;\\d+)\",\n r\"\\s+(?P&lt;arw1&gt;\\d+)\\|(?P&lt;arw2&gt;\\d+)\",\n ))\n .unwrap();\n let names = [\"qrw1\", \"qrw2\", \"arw1\", \"arw2\"];\n let buffer = \" 0|1 2|3\\n 4|5 6|7\\n 8|9 10|11\\n\";\n\n let mut maximums = [0i32; 4];\n\n for caps in buffer.lines().filter_map(|line| re.captures(line)) {\n for (&amp;name, max) in names.iter().zip(&amp;mut maximums) {\n *max = std::cmp::max(*max, caps[name].parse()?);\n }\n }\n for (&amp;name, max) in names.iter().zip(&amp;maximums) {\n println!(\"max {}: {:.2}\", name, max);\n }\n\n Ok(())\n}\n<span class=\"math-container\">```</span>\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-09T13:35:43.303", "Id": "478148", "Score": "0", "body": "Nice solution. Thanks!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-05T09:06:31.150", "Id": "243414", "ParentId": "243270", "Score": "1" } } ]
{ "AcceptedAnswerId": "243414", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-02T15:19:23.267", "Id": "243270", "Score": "2", "Tags": [ "rust" ], "Title": "How do I shorten my Rust code to get integer values from regex named capture groups?" }
243270
<p>So I'm currently using python to unscramble words that are retrieved from an OCR program, and checked in the 'dictionary'. </p> <p>The current code I am using to unscramble words is this:</p> <pre><code>import numpy as nm import pytesseract import cv2 import ctypes from PIL import ImageGrab def imToString(): # Path of tesseract executable pytesseract.pytesseract.tesseract_cmd =r'C:\Program Files (x86)\Tesseract-OCR\tesseract' while(True): # ImageGrab-To capture the screen image in a loop. # Bbox used to capture a specific area. cap = ImageGrab.grab(bbox =(687, 224, 1104, 240)) # Converted the image to monochrome for it to be easily # read by the OCR and obtained the output String. tesstr = pytesseract.image_to_string( cv2.cvtColor(nm.array(cap), cv2.COLOR_BGR2GRAY), lang ='eng') checkWord(tesstr) def checkWord(tesstr): dictionary =['orange', 'marshmellow'] scrambled = tesstr for word in dictionary: if sorted(word) == sorted(scrambled): print(word) imToString() </code></pre> <p>I want to know if there is anyway to <strong>reduce</strong> the time it takes to look through the 'dictionary', as there are many more words to go through.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-02T17:32:33.077", "Id": "477481", "Score": "3", "body": "Welcome to Code Review! What does unscrambling a word actually mean? Do you have usage examples or testcases that show what it's doing? That would make it a lot easier on the reviewers." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-03T07:36:56.660", "Id": "477550", "Score": "0", "body": "\"*many more words to go through*\" How many are we talking? Ten thousand? Ten million? Context would help a lot." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-03T14:20:06.487", "Id": "477588", "Score": "0", "body": "Can you post sample image of a screen grab with orange and/or marshmallow." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-03T22:11:59.163", "Id": "477658", "Score": "0", "body": "have you considered sorting the 'dictionary' and doing a binary search on it?" } ]
[ { "body": "<p>Like it was mentioned in the comments, it's difficult for us to tell you how to get your code faster witbout more information about the runtime context of your code. But based on what you have shown in code, I would do these modifications:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>import numpy as nm \nimport pytesseract \nimport cv2 \nimport ctypes\nfrom PIL import ImageGrab \n\ndef im_to_string(): \n\n # Path of tesseract executable \n pytesseract.pytesseract.tesseract_cmd = r'C:\\Program Files (x86)\\Tesseract-OCR\\tesseract'\n while(True): \n\n # ImageGrab-To capture the screen image in a loop. \n # Bbox used to capture a specific area. \n cap = ImageGrab.grab(bbox=(687, 224, 1104, 240))\n\n # Converted the image to monochrome for it to be easily \n # read by the OCR and obtained the output String. \n tes_str = pytesseract.image_to_string( \n cv2.cvtColor(nm.array(cap), cv2.COLOR_BGR2GRAY), \n lang ='eng') \n check_word(tes_str)\n\nwords_dictionary = ['orange', 'marshmellow']\nscrambled_words_dictionary = set(sorted(current_word) for current_word in words_dictionary)\n\ndef check_word(tes_str):\n if sorted(tes_str) in scrambled_words_dictionary:\n print(tes_str)\n\nim_to_string() \n</code></pre>\n\n<p>This is based ont the assumption that the word dictionary doesn't change between screen grabs.</p>\n\n<p>Here's some of the modifications I made to your code:</p>\n\n<ul>\n<li>I defined the word dictionary outside of <code>check_word()</code> so that it doesn't need to be recreated each time to invoke that function</li>\n<li>I created a set with the words scrambled because a set is optimized to check for membership. You are also only cheking against the scrambled words</li>\n<li>I also changed the name of the <code>dictionary</code> variable because a dictionary has a specific meaning in Python and that could be slightly confusing for someone reading your code</li>\n</ul>\n\n<p>If it's not what you were looking for, give us more precisions.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-03T20:59:27.447", "Id": "243344", "ParentId": "243273", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-02T17:11:23.300", "Id": "243273", "Score": "1", "Tags": [ "python", "sorting", "hash-map" ], "Title": "Unscramble words faster in Python" }
243273
<p>I have a file that is written DOS format and I need to replace some characters into others. I created a dictionary for that purposes, and now I have to read everyline from my stream and replace my values as I go.</p> <p>I created this piece of code in C#, however, I highly doubt that this is the way to go, since I figure that C# dictionary class <em>must</em> have a simpler way to this probably common operation. Any feedback is greatly appreciated !</p> <pre><code>public Dictionary&lt;char, string&gt; Chars { get; set; } = new Dictionary&lt;char, string&gt;(); // Called in my constructor public void CreateDictionnary() { Chars.Add('\u001b', " "); Chars.Add('\u0000', " "); // Multiple other characters that I have to replace } public List&lt;string&gt; ReplaceSpecialCharacters(List&lt;string&gt; lines) { var result = new List&lt;string&gt;(); foreach (var line in lines) { string newLine = string.Empty; foreach (var @char in line) { string replacedChar = @char.ToString(); bool keyFound = false; foreach (var entry in Chars) { if (keyFound) continue; if (@char == entry.Key) { replacedChar = entry.Value; keyFound = true; } } newLine += replacedChar; } result.Add(newLine); } return result; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-02T18:57:23.830", "Id": "477486", "Score": "0", "body": "Welcome to code review, I suggest you look at this [stackoverflow question and answer](https://stackoverflow.com/questions/12169443/get-dictionary-value-by-key). It's really not clear that this question belongs on code review." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-02T18:59:53.503", "Id": "477487", "Score": "1", "body": "I understand how a dictionary works, I'm more interested if the way I did it is the correct way (my solution works, however a bit of code review would help :))" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-02T20:20:17.587", "Id": "477496", "Score": "0", "body": "`I understand how a dictionary works` if `Chars` is your directory, the code presented suggests otherwise." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-02T20:34:28.893", "Id": "477497", "Score": "0", "body": "@greybeard care to explain ? And yes `Chars` is my dictionary, I'll add it's definition in the question (not my directory...)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-02T20:39:17.370", "Id": "477499", "Score": "1", "body": "Also without seeing the actual dictionary, it's hard to come up with a viable review. @greybeard is probably talking about looping through the entries in the dictionary instead of using indexing. Which does show an obvious lack of knowledge about how a dictionary works." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-02T20:47:17.767", "Id": "477500", "Score": "1", "body": "I added my dictionary definition. I used a dictionary because I thought that I want to change one value for another (`key` to find for `value` to replace) and I wanted to group it in the same function (where I defined my dict). I'm aware I could've done a simple class with 2 properties, but that's why I posted the question. I want to see what is the better way to replace my characters encountered in my list of strings." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-03T04:33:27.377", "Id": "477544", "Score": "0", "body": "`care to explain [the code presented suggests lack of understanding how a Dictionary works]` not really - what would have kept me? The basic *value for key @char* would be `Chars[@char]`, not an \"linear\"/O(n) search through the key set.." } ]
[ { "body": "<p>The main suggestion I'd make is to use <code>Dictionary&lt;char,char&gt;</code>. This allows to work with char collections and convert them to strings rather than continuously concatenating strings. </p>\n\n<p>This also allows you to leverage LINQ to do the replacement and shorten your code tremendously. </p>\n\n<p>It could look like this:</p>\n\n<pre><code>public Dictionary&lt;char, char&gt; Chars { get; set; } = new Dictionary&lt;char, char&gt;();\n\n// Called in my constructor\npublic void CreateDictionnary()\n{\n Chars.Add('\\u001b', ' ');\n Chars.Add('\\u0000', ' ');\n // Multiple other characters that I have to replace\n}\npublic List&lt;string&gt; ReplaceSpecialCharacters(List&lt;string&gt; lines)\n{\n for(int i = 0; i &lt; lines.Count; ++i)\n {\n lines[i] = new string(lines[i].Select(x =&gt; Chars.ContainsKey(x) ? Chars[x] : x).ToArray());\n }\n return lines;\n}\n</code></pre>\n\n<p>Incidentally this lowers the complexity from O(n²m),the total number of characters squared times the number of entries in the dictionary, to O(n²). Which since you're dealing with strings is probably about the best you can get. If you want it better, storing the data as char arrays instead of strings allows the replacement to be in-place instead of creating new strings. This could be done in O(n) complexity.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-03T12:23:20.230", "Id": "477569", "Score": "0", "body": "OK, I see thanks a lot !" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-03T17:47:52.723", "Id": "477619", "Score": "1", "body": "You can simplify the `Select`-statement to: `x => CharsT.TryGetValue(x, out char y) ? y : x` which in fact saves you a `ContainsKey()`-call because the dictionary's indexer in fact calls `ContainsKey()` itself." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-03T17:53:48.327", "Id": "477621", "Score": "0", "body": "BtW: I think I would change the return type to `IEnumerable<string>` and then `yield return` the new string directly. IMO it is bad design if you both change the argument list in place and return that list as the result as if it is a new list. At least you should describe the behavior in a comment." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-03T02:55:02.273", "Id": "243295", "ParentId": "243276", "Score": "5" } }, { "body": "<p>why not using <code>Replace</code> directly ? not sure why no one suggested though. It would be much faster and simpler. </p>\n\n<pre><code>public static IEnumerable&lt;string&gt; ReplaceSpecialCharacters(IEnumerable&lt;string&gt; lines)\n{\n if(lines == null) { throw new ArgumentNullException(nameof(lines)); }\n\n StringBuilder sb = new StringBuilder();\n\n foreach(var line in lines)\n { \n sb.Clear();\n sb.Append(line);\n\n foreach(var character in Chars)\n {\n sb.Replace(character.Key, character.Value); \n }\n\n yield return sb.ToString();\n }\n}\n</code></pre>\n\n<p>using <code>Replace</code> would replace the old character with the new one, if there is no match, it would return the original string. So, this would eliminate the need of checking the key, as the <code>Replace</code> will handle that for you. </p>\n\n<p>Using <code>StringBuilder</code> would minimize the string allocation overhead, especially with large amount of <code>string</code>s. Also, it would give you more performance.</p>\n\n<p>since we used <code>yield return</code> we also need to clear the stringbuilder then append the new line <code>sb.Clear();</code></p>\n\n<p>Finally, return the results as <code>IEnumerable&lt;string&gt;</code>, this would give you more compatibility with other collections. So, instead of just return or accept <code>List&lt;string&gt;</code> the method can accept any type of collection that implements <code>IEnumerable&lt;string&gt;</code> such as <code>List&lt;string&gt;</code> , <code>Collection&lt;string&gt;</code>, <code>string[]</code> and many others. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-04T17:14:32.517", "Id": "243386", "ParentId": "243276", "Score": "2" } } ]
{ "AcceptedAnswerId": "243295", "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-02T18:37:34.330", "Id": "243276", "Score": "4", "Tags": [ "c#", "performance", "hash-map" ], "Title": "Replacing all keys found in a dictionary for its value in a list" }
243276
<p>I am implementing a simple recursive Depth-First Search algorithm on graphs, using StateT and ReaderT for encapsulating all the required information.</p> <p><strong>Pre-requisite definitions</strong></p> <pre class="lang-hs prettyprint-override"><code>type Vertex = Int type Cost = Int data Edge = Edge { vertex:: Vertex, cost:: Cost } deriving (Eq, Show, Ord) newtype Graph = Graph { adjacencyList :: Map.Map Vertex [Edge] } deriving (Eq, Show) type DFSState = ([Vertex], [Vertex]) type Env = Graph type DFSNextState = ReaderT Env (StateT DFSState Identity) Vertex </code></pre> <p>and then the main function:</p> <pre class="lang-hs prettyprint-override"><code>{-# LANGUAGE FlexibleContexts #-} dfsGetNext :: DFSNextState dfsGetNext = do graph &lt;- ask s &lt;- get let candidates = fst s let visited = snd s let ret = case candidates of [] -&gt; return 0 :: DFSNextState (x:xs) -&gt; if elem x visited then put (xs, visited) &gt;&gt; (return 1 :: DFSNextState) else put ((getNeighbors x graph) ++ xs, visited ++ [x]) &gt;&gt; (return 1 :: DFSNextState) ret </code></pre> <p>I can then simply run the algorithm for n steps and get the nodes visited in a depth-first fashion using</p> <pre class="lang-hs prettyprint-override"><code>dfsStartState :: DFSState dfsStartState = ([0], []) dfsSteps = replicateM 13 dfsGetNext runStateT (runReaderT dfsSteps graph) dfsStartState </code></pre> <p>Questions:<br> 1) Is my style in the main function good? Can it be simplified?<br> 2) Is there a way to remove the magic number (13 in this case) for replicateM? Is there a replicate until which I could use for this?</p> <p><strong>Update</strong> I added a replicateMUntil function myself:</p> <pre class="lang-hs prettyprint-override"><code>{-# LANGUAGE RankNTypes, KindSignatures #-} replicateMUntil :: forall (m :: * -&gt; *) a. Monad m =&gt; (m a -&gt; m Bool) -&gt; m a -&gt; m [a] replicateMUntil f ma = do res &lt;- f ma if res then liftM2 (:) ma (replicateMUntil f ma) else return [] </code></pre> <p>The driver now becomes:</p> <pre class="lang-hs prettyprint-override"><code>isNextAvailable :: DFSNextState -&gt; ReaderT Env (StateT DFSState Identity) Bool isNextAvailable nextState = do s &lt;- get return (fst s /= []) dfsStartState :: DFSState dfsStartState = ([0], []) dfsSteps = replicateMUntil isNextAvailable dfsGetNext runStateT (runReaderT dfsSteps graph) dfsStartState </code></pre>
[]
[ { "body": "<h3>The small things</h3>\n\n<pre><code> s &lt;- get\n let candidates = fst s\n let visited = snd s\n</code></pre>\n\n<p>could be simplified to</p>\n\n<pre><code> (candidates, visited) &lt;- get\n</code></pre>\n\n<p>(It is technically a little bit stricter but it's not a problem because you don't rely on laziness here.)</p>\n\n<pre><code> let ret = blah in\n ret\n</code></pre>\n\n<p>is equivalent to</p>\n\n<pre><code> blah\n</code></pre>\n\n<p>At the end of <code>dfsGetNext</code> you return either <code>0</code> or <code>1</code>, which is strange because the return type is <code>Vertex</code>, and although it is a synonym for <code>Int</code> (so this type checks), <code>0</code> and <code>1</code> don't look like vertices.</p>\n\n<p>My guess is that you intended either:</p>\n\n<ul>\n<li>to return a boolean to indicate whether the DFS ended, so <code>Bool</code> would be a more appropriate type;</li>\n<li>to return the visited vertex, so, rather than returning dummy sentinel values, <code>Maybe Vertex</code> would be a more appropriate type.</li>\n</ul>\n\n<p>Assuming that <code>0</code> and <code>1</code> are meant to be booleans, and with the other changes above, we get:</p>\n\n<pre class=\"lang-hs prettyprint-override\"><code>-- Also isolating the monad, and applying it to the result type in the function instead\ntype DFS = ReaderT Env (StateT DFSState Identity)\n\ndfsGetNext :: DFS Bool\ndfsGetNext = do\n graph &lt;- ask\n (candidates, visited) &lt;- get\n case candidates of\n [] -&gt; return False\n (x:xs) -&gt; if elem x visited \n then put (xs, visited) &gt;&gt; return True\n else put ((getNeighbors x graph) ++ xs, visited ++ [x]) &gt;&gt; return True\n</code></pre>\n\n<h3>Getting fancy</h3>\n\n<p>There's a more direct implementation of DFS. To do a DFS starting from a vertex <code>v</code>:</p>\n\n<ol>\n<li>If <code>v</code> has already been visited, stop; otherwise...</li>\n<li>Visit <code>v</code></li>\n<li>Recursively run a DFS from each neighbor of <code>v</code></li>\n</ol>\n\n<p>In particular, this description doesn't require you to explicitly keep track of \"pending candidate vertices\", nor to iterate a \"single step\" function like <code>dfsGetNext</code>; the DFS is directly defined.</p>\n\n<pre class=\"lang-hs prettyprint-override\"><code>-- The state now only contains the visited vertices, not the candidates (which is implicit in the recursive structure of dfsFrom)\ntype DFS = ReaderT Graph (State Visited)\n\ndfsFrom :: Vertex -&gt; DFS ()\ndfsFrom v = do\n visited &lt;- get\n if v `elem` visited then -- 1\n pure ()\n else do\n put (visited ++ [v]) -- 2\n graph &lt;- ask\n let neighbors = getNeighbors v graph\n for_ neighbors dfsFrom -- 3\n</code></pre>\n\n<p>Now you can \"run\" that DFS, interpreting it as a function as follows:</p>\n\n<pre class=\"lang-hs prettyprint-override\"><code>-- dfs from 0\ndfs :: Graph -&gt; [Vertex]\ndfs graph = dfsFrom 0 `runReaderT` graph `execState` []\n</code></pre>\n\n<p>Your \"single step\" version does have one distinguishing feature, which is that you can easily interrupt the DFS at any time to inspect the state for example. But you can also do that with the recursive version, by passing a function (<code>visit</code> below) that will be called when visiting a node. Clients of the DFS are free to define it however they wish.</p>\n\n<p>It's also useful to generalize the <code>DFS</code> monad to support additional effects relevant to users rather than to the DFS itself. This is straightforward since you're already using monad transformers, by changing the base monad from <code>Identity</code> to something else. Here I chose <code>IO</code> for simplicity and concreteness, but it might as well be a type parameter <code>m</code>.</p>\n\n<pre class=\"lang-hs prettyprint-override\"><code>type DFSIO = ReaderT Graph (StateT Visited IO)\n\ndfsFromIO :: (Vertex -&gt; DFSIO ()) -&gt; Vertex -&gt; DFSIO ()\ndfsFromIO visit v = do\n visited &lt;- get\n if v `elem` visited then\n pure ()\n else do\n visit v\n put (visited ++ [v])\n graph &lt;- ask\n let neighbors = getNeighbors v graph\n for_ neighbors (dfsFromIO visit)\n</code></pre>\n\n<p>Another possibility is to call <code>visit</code> at the very start of the function, before checking whether the vertex was visited, or at the very end, on the neighboring vertices, where the function could also have access to the cost of the edges being crossed.</p>\n\n<p>Running this new version <code>dfsFromIO</code> is as straightforward as running <code>dfsFrom</code> (only replacing <code>execState</code> with <code>execStateT</code> since the base monad is no longer <code>Identity</code>):</p>\n\n<pre class=\"lang-hs prettyprint-override\"><code>-- dfs from 0\ndfsIO :: (Vertex -&gt; DFSIO ()) -&gt; Graph -&gt; IO [Vertex]\ndfsIO visit graph = dfsFromIO visit 0 `runReaderT` graph `execStateT` []\n</code></pre>\n\n<p>For example you can print every visited vertex as follows:</p>\n\n<pre class=\"lang-hs prettyprint-override\"><code>main :: IO ()\nmain = void (dfsIO (\\v -&gt; liftIO (print v)))\n</code></pre>\n\n<hr>\n\n<p>Full gist: <a href=\"https://gist.github.com/Lysxia/4733f8d670c84e5b886f74d2d106d1f5\" rel=\"nofollow noreferrer\">https://gist.github.com/Lysxia/4733f8d670c84e5b886f74d2d106d1f5</a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-05T14:52:07.457", "Id": "243429", "ParentId": "243278", "Score": "2" } } ]
{ "AcceptedAnswerId": "243429", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-02T19:34:25.460", "Id": "243278", "Score": "2", "Tags": [ "haskell" ], "Title": "Feedback on simple DFS" }
243278
<p>I written my own calculator script in javascript! It is a basic one, but works really well. I am just wondering if there is any way to make this script more efficient &amp; clean. On first look, I feel like I did some redundant stuff in it, however I am a beginner and in no right to judge the code on my own.</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-js lang-js prettyprint-override"><code>window.onload = () =&gt; { const calculator = document.querySelector('form[name = "calculator"]') const btns = document.querySelectorAll(`form[name = "calculator"] table tr input[type = "button"]`) btns.forEach((button) =&gt; { if(button.value != 'c' &amp;&amp; button.value != '='){ button.addEventListener('click', () =&gt; { calculator.display.value += button.value }) } else { if (button.value == 'c') { button.addEventListener('click', () =&gt; { calculator.display.value = ''; }) } else if (button.value == '=') { button.addEventListener('click', () =&gt; { calculator.display.value = eval(calculator.display.value); }) } } }) }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt;&lt;/head&gt; &lt;/body&gt; &lt;!-- Page Contents !--&gt; &lt;form name = "calculator"&gt; &lt;table&gt; &lt;tr&gt; &lt;input type = "text" name = "display" id = "display" disabled&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;&lt;input type = "button" name = "one" value = "1"&gt;&lt;/td&gt; &lt;td&gt;&lt;input type = "button" name = "two" value = "2"&gt;&lt;/td&gt; &lt;td&gt;&lt;input type = "button" name = "three" value = "3"&gt;&lt;/td&gt; &lt;td&gt;&lt;input type = "button" name = "plus" value = "+"&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;&lt;input type = "button" name = "four" value = "4"&gt;&lt;/td&gt; &lt;td&gt;&lt;input type = "button" name = "five" value = "5"&gt;&lt;/td&gt; &lt;td&gt;&lt;input type = "button" name = "six" value = "6"&gt;&lt;/td&gt; &lt;td&gt;&lt;input type = "button" name = "minus" value = "-"&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;&lt;input type = "button" name = "seven" value = "7"&gt;&lt;/td&gt; &lt;td&gt;&lt;input type = "button" name = "eight" value = "8"&gt;&lt;/td&gt; &lt;td&gt;&lt;input type = "button" name = "nine" value = "9"&gt;&lt;/td&gt; &lt;td&gt;&lt;input type = "button" name = "multiplicatio" value = "*"&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;&lt;input type = "button" name = "clear" value = "c"&gt;&lt;/td&gt; &lt;td&gt;&lt;input type = "button" name = "0" value = "0"&gt;&lt;/td&gt; &lt;td&gt;&lt;input type = "button" name = "equal" value = "="&gt;&lt;/td&gt; &lt;td&gt;&lt;input type = "button" name = "division" value = "/"&gt;&lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;/form&gt; &lt;script src = "script.js"&gt;&lt;/script&gt; &lt;/body&gt; &lt;/html&gt;</code></pre> </div> </div> </p> <p>Are there any ways to make this script "better"? Thanks for the help.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-03T08:18:31.473", "Id": "477555", "Score": "1", "body": "I don't have the time writing a full review, but in general, seeing `eval` being used should raise a red flag. You don't want to use `eval` in almost any case. However, changing your code to don't use eval is not trivial though, as you would need to write some sort of simple tokenizer/parser/interpreter to evaluate the expressions entered into the calculator. Your `if` can also be rewritten using `switch ... case`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-03T14:22:36.213", "Id": "477590", "Score": "0", "body": "@C5H8NNaO4: `eval` is not advisable for scripting logic, but for simple mathematical parsing it seems fine. There's no attack vector (it's a local calculator) and it's a clever way to circumvent the complexity of writing your own parser and instead relying one one you have available in JS anyway." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-03T20:03:06.543", "Id": "477637", "Score": "1", "body": "It is, however, very easy to crash the program by inputting an improperly formatted equation. Just enter any of the operators not followed by a number and hit =. Some basic error checking should be used to prevent this. Possibly just a matter of adding a `try/catch` around any use of `eval` to make sure it parses. But writing a proper parser would be much better and safer in general." } ]
[ { "body": "<p>Yes, It can be better in many ways just replace all your code with this:</p>\n\n<p>The first thing I did is made the code formatting just a bit better.\nthen I added a title tag a webpage cannot go on without a title\nafter that I include the meta tags for the UTF-8 encoding and then the viewport meta tag for responsiveness. I also corrected your opening body tag you wrote it as the closing body tag.</p>\n\n<p>Tip: Use vscode as your code editor and add the prettier extension with it to format your code better.</p>\n\n<pre><code>&lt;!DOCTYPE html&gt;\n&lt;html&gt;\n &lt;head&gt;\n &lt;!-- These meta tags should be here --&gt;\n &lt;meta charset=\"UTF-8\" /&gt;\n &lt;meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" /&gt;\n &lt;!-- Your page can't go on without a title --&gt;\n &lt;title&gt;Your Page should have a title&lt;/title&gt;\n &lt;/head&gt;\n &lt;body&gt;\n &lt;!-- Page Contents !--&gt;\n &lt;form name = \"calculator\"&gt;\n &lt;table&gt;\n &lt;tr&gt;\n &lt;input type = \"text\" name = \"display\" id = \"display\" disabled&gt;\n &lt;/tr&gt;\n &lt;tr&gt;\n &lt;td&gt;&lt;input type = \"button\" name = \"one\" value = \"1\"&gt;&lt;/td&gt;\n &lt;td&gt;&lt;input type = \"button\" name = \"two\" value = \"2\"&gt;&lt;/td&gt;\n &lt;td&gt;&lt;input type = \"button\" name = \"three\" value = \"3\"&gt;&lt;/td&gt;\n &lt;td&gt;&lt;input type = \"button\" name = \"plus\" value = \"+\"&gt;&lt;/td&gt;\n &lt;/tr&gt;\n &lt;tr&gt;\n &lt;td&gt;&lt;input type = \"button\" name = \"four\" value = \"4\"&gt;&lt;/td&gt;\n &lt;td&gt;&lt;input type = \"button\" name = \"five\" value = \"5\"&gt;&lt;/td&gt;\n &lt;td&gt;&lt;input type = \"button\" name = \"six\" value = \"6\"&gt;&lt;/td&gt;\n &lt;td&gt;&lt;input type = \"button\" name = \"minus\" value = \"-\"&gt;&lt;/td&gt;\n &lt;/tr&gt;\n &lt;tr&gt;\n &lt;td&gt;&lt;input type = \"button\" name = \"seven\" value = \"7\"&gt;&lt;/td&gt;\n &lt;td&gt;&lt;input type = \"button\" name = \"eight\" value = \"8\"&gt;&lt;/td&gt;\n &lt;td&gt;&lt;input type = \"button\" name = \"nine\" value = \"9\"&gt;&lt;/td&gt;\n &lt;td&gt;&lt;input type = \"button\" name = \"multiplicatio\" value = \"*\"&gt;&lt;/td&gt;\n &lt;/tr&gt;\n &lt;tr&gt;\n &lt;td&gt;&lt;input type = \"button\" name = \"clear\" value = \"c\"&gt;&lt;/td&gt;\n &lt;td&gt;&lt;input type = \"button\" name = \"0\" value = \"0\"&gt;&lt;/td&gt;\n &lt;td&gt;&lt;input type = \"button\" name = \"equal\" value = \"=\"&gt;&lt;/td&gt;\n &lt;td&gt;&lt;input type = \"button\" name = \"division\" value = \"/\"&gt;&lt;/td&gt;\n &lt;/tr&gt;\n &lt;/table&gt;\n &lt;/form&gt;\n &lt;script src = \"script.js\"&gt;&lt;/script&gt;\n &lt;/body&gt;\n&lt;/html&gt;\n</code></pre>\n\n<p>The Js part</p>\n\n<p>The only thing I did with the Javascript is made the code formatting a lot more readable</p>\n\n<pre><code>window.onload = () =&gt; {\n const calculator = document.querySelector('form[name = \"calculator\"]');\n const btns = document.querySelectorAll(\n `form[name = \"calculator\"] table tr input[type = \"button\"]`\n );\n btns.forEach((button) =&gt; {\n if (button.value != \"c\" &amp;&amp; button.value != \"=\") {\n button.addEventListener(\"click\", () =&gt; {\n calculator.display.value += button.value;\n });\n } else {\n if (button.value == \"c\") {\n button.addEventListener(\"click\", () =&gt; {\n calculator.display.value = \"\";\n });\n } else if (button.value == \"=\") {\n button.addEventListener(\"click\", () =&gt; {\n calculator.display.value = eval(calculator.display.value);\n });\n }\n }\n });\n};\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-03T00:00:28.643", "Id": "477523", "Score": "1", "body": "Oh okay, so all my issues were with the formatting and not the code itself?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-03T07:49:55.820", "Id": "477552", "Score": "3", "body": "Only formatting the code without at least describing why this is better is off topic for this site." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-03T12:12:49.753", "Id": "477566", "Score": "0", "body": "@DanielP533 Not just the formatting you did not put the meta tags and did not give it a title and the Js seems fine." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-03T12:15:32.063", "Id": "477567", "Score": "0", "body": "@RoToRa I have explained my question a bit more now, please check." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-03T12:15:53.170", "Id": "477568", "Score": "0", "body": "@DanielP533 I have explained my question a bit more now, please check" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-02T23:10:21.340", "Id": "243288", "ParentId": "243280", "Score": "5" } }, { "body": "<p>You have two errors in the HTML: </p>\n\n<ul>\n<li><p>A <code>&lt;title&gt;</code> element is required.</p></li>\n<li><p>There is a closing <code>&lt;/body&gt;</code> tag instead of an opening tag <code>&lt;body&gt;</code> tag at the beginning.</p></li>\n</ul>\n\n<p>Furthermore in the HTML :</p>\n\n<ul>\n<li><p>The comment <code>&lt;!-- Page Contents !--&gt;</code> is pointless.</p></li>\n<li><p>It is convention to write attributes without spaces around the equals sign.</p></li>\n<li><p>Don't use a (disabled) <code>&lt;input&gt;</code> for output. HTML specifically provides the <a href=\"https://developer.mozilla.org/en-US/docs/Web/HTML/Element/output\" rel=\"nofollow noreferrer\"><code>&lt;output&gt;</code></a> element for this.</p></li>\n<li><p>Don't add unnecessary attributes if you don't use them, such as the <code>id</code> on the display or the <code>name</code>s on the buttons.</p></li>\n</ul>\n\n<p>On to the JavaScript:</p>\n\n<ul>\n<li><p>Don't use the <code>on...</code> event listener properties, but use <code>addEventListener</code> like you did for the button click listener. </p></li>\n<li><p>It's not wrong, but uncommon to select elements using the <code>name</code> attribute. A class is the usual way.</p></li>\n<li><p>For the form selector string you correctly use single quotes, but for the button selector string you use a template string with backticks (<code>`</code>) unnecessarily. Use single quotes there too.</p></li>\n</ul>\n\n<p>Also the button selector is unnecessarily long. Just <code>form[name=\"calculator\"] input[type=\"button\"]</code> is sufficient. Considering you already have a reference to the form you could call <code>querySelectorAll</code> on that:</p>\n\n<pre><code>const calculator = document.querySelector('form[name=\"calculator\"]');\nconst btns = calculator.querySelectorAll('input[type=\"button\"]');\n</code></pre>\n\n<p>Looping over all buttons and then assigning the event handlers based on <code>if</code> constraints isn't really practical. It would be better to select the \"clear\" and \"equal\" buttons directly and give all numerical and operator buttons a class to select them:</p>\n\n<pre><code>calculator.querySelector('button[name=\"clear\"]').addEventListener(\"click\", ...);\n\ncalculator.querySelector('button[name=\"equal\"]').addEventListener(\"click\", ...);\n\nconst btns = calculator.querySelectorAll('input.numerical, input.operator').forEach(\n button =&gt; button.addEventListener(\"click\", ...);\n) \n</code></pre>\n\n<p>Finally the biggest problem, for two reasons: <code>eval</code>.</p>\n\n<ol>\n<li><p>Generally using <code>eval</code> is a bad idea. See: <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval#Never_use_eval!\" rel=\"nofollow noreferrer\">Never use eval!</a></p></li>\n<li><p>Your program isn't really a calculator. It's an on-screen keyboard that evaluates (potentially invalid) expressions.</p></li>\n</ol>\n\n<p>At the very least you should replace <code>eval</code> with <code>Function</code> (as the above link demonstrates) and catch any errors it throws. Better would be to check if the entered expression is valid before evaluating it (or even better yet stop the user entering an invalid expression in the first place). Finally try evaluating the expression yourself, or write a application that doesn't build an expression, but calculates as you type just like a real calculator.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-03T13:28:50.100", "Id": "477581", "Score": "0", "body": "Finally, I added the long querySelector because I wanted to be specific and which buttons were the calculator's and which weren't. You are right though, I should have used classes for this" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-03T13:31:54.383", "Id": "477583", "Score": "1", "body": "Also, thanks for the `eval` understanding. Now I know never to use eval(). I followed a tutorial to get that one. Thanks for the help though. I'm changing the solution to be yours because you helped me with my JS code and didn't just throw some sprinkles at my html." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-03T13:43:07.307", "Id": "477585", "Score": "0", "body": "is window.Function() safe?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-03T15:16:43.033", "Id": "477603", "Score": "1", "body": "@DanielP533 Unfortunately you gain nothing using `new Function` over `eval`, it boils down to the very same mechanism. It's not safe(r)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-03T16:14:00.450", "Id": "477604", "Score": "0", "body": "@DanielP533 Yes you are right but your code should be readable and maintainable so XYBO's answer also seems correct." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-03T09:00:16.997", "Id": "243306", "ParentId": "243280", "Score": "2" } }, { "body": "<h2>Good Things</h2>\n\n<p>For a beginner this looks like a good start. The markup is fairly clean. In the JavaScript code the variables have good scope - i.e. limited to functions, <code>const</code> is used instead of <code>let</code> for variables that don't get re-assigned (which is all variables).</p>\n\n<h2>Suggestions</h2>\n\n<h3>Delegating events</h3>\n\n<p>I would recommend using <a href=\"https://davidwalsh.name/event-delegate\" rel=\"nofollow noreferrer\">event delegation</a>. Instead of adding click handlers to each button, add a single event handler to the form or another container element and determine the action based on the <code>event.target</code> - e.g. using class names or other attributes. The <code>forEach</code> callback could be altered slightly for this.</p>\n\n<h3>Referencing the form in JavaScript</h3>\n\n<p>The form can be accessed via a property on <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Document\" rel=\"nofollow noreferrer\"><code>Document</code></a> - i.e. <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Document/forms\" rel=\"nofollow noreferrer\"><code>document.forms</code></a> - so instead of using <code>querySelector()</code> </p>\n\n<blockquote>\n<pre><code>const calculator = document.querySelector('form[name = \"calculator\"]')\n</code></pre>\n</blockquote>\n\n<p>Access it via the property of <code>document</code>:</p>\n\n<pre><code>const calculator = document.forms.calculator;\n</code></pre>\n\n<p>This avoids excess DOM queries.</p>\n\n<p>The elements could also be accessed via <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement/elements\" rel=\"nofollow noreferrer\"><code>HTMLFormElement.elements</code></a> - e.g. <code>document.forms.calculator.elements.clear</code></p>\n\n<h3>Line terminators</h3>\n\n<p>Semicolons aren't required for all lines except <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#Automatic_semicolon_insertion\" rel=\"nofollow noreferrer\">a handful of statements</a> so <a href=\"https://www.freecodecamp.org/news/codebyte-why-are-explicit-semicolons-important-in-javascript-49550bea0b82/\" rel=\"nofollow noreferrer\">as this blog post</a> explains it is best to use them to avoid unintentional behavior in your code. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-03T21:40:13.767", "Id": "477653", "Score": "0", "body": "Thanks. I'm reading up on Event Delegation right now" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-03T22:07:17.610", "Id": "477657", "Score": "0", "body": "https://pastebin.com/NxvVb8MY This is my new script" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-03T15:48:33.947", "Id": "243329", "ParentId": "243280", "Score": "1" } } ]
{ "AcceptedAnswerId": "243306", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-02T19:54:55.337", "Id": "243280", "Score": "11", "Tags": [ "javascript", "beginner", "html", "calculator", "dom" ], "Title": "Simple Calculator Script" }
243280
<p>I am working on some custom rules in a time managment system and need to know how many hours in a shift have been before a certain time (19:00pm) and how many hours after. Shifts can start in the evening and finish in the morning so need to take that into account.</p> <p>So far I have the below (this is just a snippet for one day) however it seems very clumsy and eloborate what I have written, can't help but feel I am missing a simpler solution, anyone have any ideas?</p> <pre><code> DateTime cutOffTime = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 19, 00, 00); string cutOffTimeOfDay = GetTimeOfDayFromDateTime(cutOffTime); double baseMondayHours = 10.00; baseMondayHours = (baseMondayHours - 0.5); if (GetTimeOfDayOnlyFromDateTime(monday.ShiftStart.Value) == "AM" &amp;&amp; GetTimeOfDayOnlyFromDateTime(monday.ShiftEnd.Value) == "PM" &amp;&amp; monday.ShiftEnd.Value.TimeOfDay &lt; cutOffTime.TimeOfDay) { postCutOffMondayHours = 0; baseMondayHours = monday.HoursWorked.Value; } else { string endTimeOfDay = GetTimeOfDayFromDateTime(monday.ShiftEnd.Value); double hoursAfterCutOff = GetDuration(cutOffTimeOfDay, endTimeOfDay); postCutOffMondayHours = hoursAfterCutOff; baseMondayHours = (baseMondayHours - hoursAfterCutOff); } public static string GetTimeOfDayFromDateTime(DateTime d) { return d.ToString("HH:mm") + " " + d.ToString("tt", CultureInfo.InvariantCulture); } public static string GetTimeOfDayOnlyFromDateTime(DateTime d) { return d.ToString("tt", CultureInfo.InvariantCulture).ToUpper(); } public static double GetDuration(string startTime, string endTime) { DateTime start = DateTime.Parse(startTime); DateTime end = DateTime.Parse(endTime); if (start &gt; end) end = end.AddDays(1); TimeSpan duration = end.Subtract(start); return duration.TotalHours; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-02T20:36:42.940", "Id": "477498", "Score": "0", "body": "Can you post the class that variable `monday` was created with?" } ]
[ { "body": "<p>I agree with your summation that it is clumsy. I see you like to <strong>stringly</strong> type objects, such as <code>GetTimeOfDayFromDateTime</code>. It would be neater to just get the time of day as a <code>TimeSpan</code>. Also, you may have several overloads accepting different input arguments, so you don't need to include the <code>FromDateTime</code> in the name.</p>\n\n<pre><code>public static TimeSpan GetTimeOfDay(DateTime d) =&gt; d - d.Date;\n</code></pre>\n\n<p>Or if you want to simply check AM versus PM, you could use the DateTime.Hour. If the hour is &lt; 12, it's AM. Otherwise, it's PM.</p>\n\n<p>Now GetDuration doesn't have to accept string inputs. They can accept the TimeSpan (i.e. time of day) for start and end, or just better yet, just subtract the 2 DateTime objects.</p>\n\n<p>This just looks clumsy:</p>\n\n<pre><code>double baseMondayHours = 10.00;\nbaseMondayHours = (baseMondayHours - 0.5);\n</code></pre>\n\n<p>Cleaner would be either:</p>\n\n<pre><code>double baseMondayHours = 10.0 - 0.5;\n</code></pre>\n\n<p>or directly</p>\n\n<pre><code>double baseMondayHours = 9.5;\n</code></pre>\n\n<p>Another tip to keep in mind: Subtracting dates can produce bad results if the Kind of each DateTime is different. Doesn't seem to be the case here, but be forewarned.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-03T08:56:14.707", "Id": "477557", "Score": "0", "body": "Getting AM/PM: https://stackoverflow.com/questions/7875259/how-do-i-get-the-am-pm-value-from-a-datetime" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-02T20:49:55.430", "Id": "243284", "ParentId": "243281", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-02T20:11:40.583", "Id": "243281", "Score": "1", "Tags": [ "c#", "datetime" ], "Title": "Working out how many hours worked after a certain time" }
243281
<p>I'm after a pythonic and <em>pandemic</em> (from <em>pandas</em>, pun not intended =) way to pivot some rows in a dataframe into new columns.</p> <p>My data has this format:</p> <pre><code> dof foo bar qux idxA idxB 100 101 1 10 30 50 101 2 11 31 51 101 3 12 32 52 102 1 13 33 53 102 2 14 34 54 102 3 15 35 55 200 101 1 16 36 56 101 2 17 37 57 101 3 18 38 58 102 1 19 39 59 102 2 20 40 60 102 3 21 41 61 </code></pre> <p>The variables <code>foo</code>, <code>bar</code> and <code>qux</code> actually have 3 dimensional coordinates, which I would like to call <code>foo1</code>, <code>foo2</code>, <code>foo3</code>, <code>bar1</code>, ..., <code>qux3</code>. These are identified by the column <code>dof</code>. Each row represents one axis in 3D, <code>dof == 1</code> is the x axis, <code>dof == 2</code> the y axis and <code>dof == 3</code> is the z axis.</p> <p>So, here is the final dataframe I want:</p> <pre><code> foo1 bar1 qux1 foo2 bar2 qux2 foo3 bar3 qux3 idxA idxB 100 101 10 30 50 11 31 51 12 32 52 102 13 33 53 14 34 54 15 35 55 200 101 16 36 56 17 37 57 18 38 58 102 19 39 59 20 40 60 21 41 61 </code></pre> <hr> <p>Here is what I have done.</p> <pre><code>import pandas as pd data = [[100, 101, 1, 10, 30, 50], [100, 101, 2, 11, 31, 51], [100, 101, 3, 12, 32, 52], [100, 102, 1, 13, 33, 53], [100, 102, 2, 14, 34, 54], [100, 102, 3, 15, 35, 55], [200, 101, 1, 16, 36, 56], [200, 101, 2, 17, 37, 57], [200, 101, 3, 18, 38, 58], [200, 102, 1, 19, 39, 59], [200, 102, 2, 20, 40, 60], [200, 102, 3, 21, 41, 61], ] df = pd.DataFrame(data=data, columns=['idxA', 'idxB', 'dof', 'foo', 'bar', 'qux']) df.set_index(['idxA', 'idxB'], inplace=True) # # Here is where the magic happens - and I'm not too happy about this implementation # # Create an ampty dataframe with the same indexes df2 = df[df.dof == 1].reset_index()[['idxA', 'idxB']] df2.set_index(['idxA', 'idxB'], inplace=True) # Loop through each DOF and add columns for `bar`, `foo` and `qux` manually. for pivot in [1, 2, 3]: df2.loc[:, 'foo%d' % pivot] = df[df.dof == pivot]['foo'] df2.loc[:, 'bar%d' % pivot] = df[df.dof == pivot]['bar'] df2.loc[:, 'qux%d' % pivot] = df[df.dof == pivot]['qux'] </code></pre> <p>However I'm not too happy with these <code>.loc</code> calls and incremental column additions inside a loop. I thought that <code>pandas</code> being awesome as it is would have a neater way of doing that. </p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-03T01:55:12.943", "Id": "477537", "Score": "0", "body": "I'm too lazy to try an implementation, but perhaps you should look into a multi-index where the innermost index has size 3." } ]
[ { "body": "<h1><code>groupby</code></h1>\n\n<p>When iterating over the values in a column, it is bad practice to hardcode the values (<code>for pivot in [1, 2, 3]</code>). A better way would have been <code>for pivot in df[\"dof\"].unique()</code>, but the best way is with <a href=\"https://pandas.pydata.org/pandas-docs/stable/user_guide/groupby.html\" rel=\"nofollow noreferrer\"><code>DataFrame.groupby</code></a> </p>\n\n<p>To see what happens in the <code>groupby</code>, I try it first with an iteration, and printing the groups</p>\n\n<pre><code>for pivot, data in df.groupby(\"dof\"):\n print(pivot)\n print(data)\n</code></pre>\n\n<p>Then I get to work with one of the <code>data</code> to mold it the way I want. In this case, we don't need the column <code>dof</code> any more, since we have it in the <code>pivot</code> variable, and we rename the columns using <code>rename</code></p>\n\n<pre><code>for pivot, data in df.groupby(\"dof\"):\n print(pivot)\n print(\n data.drop(columns=\"dof\").rename(\n mapper={\n column_name: f\"{column_name}{pivot}\"\n for column_name in data.columns\n },\n axis=1,\n )\n )\n</code></pre>\n\n<p>Then we can use <code>pd.concat</code> to stitch it together</p>\n\n<pre><code>pd.concat(\n [\n data.drop(columns=\"dof\").rename(\n mapper={\n column_name: f\"{column_name}{pivot}\"\n for column_name in data.columns\n },\n axis=1,\n )\n for pivot, data in df.groupby(\"dof\")\n ],\n axis=1,\n)\n</code></pre>\n\n<h1>unstack</h1>\n\n<p>An alternative is with <code>unstack</code>:</p>\n\n<p>From you description, <code>dof</code> is part of the index, so add it there. Then you can use <code>DataFrame.unstack</code> to bring it to the columns.</p>\n\n<blockquote>\n<pre><code>df2 = df.set_index(\"dof\", append=True).unstack(\"dof\")\n</code></pre>\n</blockquote>\n\n<pre><code> foo foo foo bar bar bar qux qux qux\ndof 1 2 3 1 2 3 1 2 3\nidxA idxB \n100 101 10 11 12 30 31 32 50 51 52\n100 102 13 14 15 33 34 35 53 54 55\n200 101 16 17 18 36 37 38 56 57 58\n200 102 19 20 21 39 40 41 59 60 61\n</code></pre>\n\n<p>If you are okay with a <a href=\"https://pandas.pydata.org/pandas-docs/stable/user_guide/advanced.html\" rel=\"nofollow noreferrer\"><code>MultiIndex</code></a>, which will be handier then the concatenated strings in most cases, you can leave it at that. If you want it in the form you have it, you can do <code>df2.columns = df2.columns.map(lambda x: f\"{x[0]}{x[1]}\")</code>. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-03T11:42:47.927", "Id": "243318", "ParentId": "243283", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-02T20:31:25.157", "Id": "243283", "Score": "2", "Tags": [ "python", "pandas" ], "Title": "Pivot some rows to new columns in DataFrame" }
243283
<p>OK, you don't really have to read it all, but I think you get the basic Idea. Does anyone have anything small that could make my code better? I just found out about "global" and "lower()". Is there any small thing you can give me that could improve my code a lot, or at least save me some time?</p> <pre><code>global myname global move2 global move1 def script(): print("Made by Chase - Winner Playz") print("This is your Pokemon Journey!") print("Thanks for playing... and a little sidenote... CATCHING IS CURRENTLY DISABLED, IF YOU TRY TO CATCH IT MIGHT CRASH") print("DO NOT make any typos, this will result in you having to start the entire game over, there is no way to save progress") print("PLEASE READ EVERYTHING, I KNOW ITS A LOT, BUT PLEASE DO OR IT WON'T MAKE ANY SENSE") print("There are 3 starters in the lab, and they all seem quite skilled") starter = input("What will YOU choose? You can pick, Geodude, Drowzee, or Tyrogue").lower() #if starter == "view": #print("Geodude - Rock pokemon, Evolves into Graveler, Then Golem, Moveset: Earthquake, Rock Slide, Defense Curl, Tackle") #print("Drowzee - Psychic pokemon, Evolves into Hypno, Moveset: Hypnosis, Psychic, Dream Eater, Light Screen") #print("Charmander - Fire pokemon, Evolves into Charmaleon, then Charizard, Moveset: Blast Burn, Flame Thrower, Headbutt, Scary Face") if starter == "geodude": print("Great choice! You decided on the Rock pokemon Geodude!") nicknamequestion = input("Would you like to nickname Geodude? (Yes or No?)").lower() if nicknamequestion == "yes": myname = input("What would you like to nickname it?") print("OK, your Geodude's new name is now",myname) print("Also note that you will not be able to use any of the pokemon that you catch (Catching is currently not working anyway)") print("You start your journey by walking into your first patch of grass...") print("A wild Rattata appeared!") print("Go",myname, "!") q1 = input("Would you like to attack, or try to catch it?").lower() if q1 == "attack" or "attack it": move1 = input("What would you like to use? Earthquake or Rock Slide?").lower() if move1 == "earthquake": print("You one shotted it, Fantastic!", myname, "is now level 6!") print("You move on...") print("You are now in Viridian City... but the gym seems to be locked") print("The gym's note say's...") print("The gym will be open after you collect another 2 badges") print("You move on to the next city...") print("There are a couple of trainers that want to battle you") print("For you're times sake, you will only have to do one of them, the others will be done for you") print("The trainer sent out Charmaleon") print("Go", myname) move2 = input("What would you like to use? Earthquake or Rock Slide?") elif move1 == "rockslide" or "rock slide": print("Enemy rattata is left with 6 health!") print("Enemy Rattata used Tackle") print(myname, "is left with 19 health") move5 = input("What would you like to use? Earthquake or Rock slide?").lower() if move5 == "earthquake" or "rock slide" or "rockslide": print("You defeated enemy Rattata, Geodude leveld up!") print("You move on...") print("You are now in Viridian City... but the gym seems to be locked") print("The gym's note say's...") print("The gym will be open after you collect another 2 badges") print("You move on to the next city...") print("There are a couple of trainers that want to battle you") print("For you're times sake, you will only have to do one of them, the others will be done for you") print("The trainer sent out Charmaleon") print("Go", myname) move2 = input("What would you like to use? Earthquake or Rock Slide?") if move2 == "earthquake": print("It's super effective!") print("You one shotted it, great", myname, "!") print(myname, "is now level 7!") print("You battled the other trainers, and your", myname, "is level 9") print("This game doesnt follow actual pokemon, so your geodude will evolve at level 10") print("You see a gym in a distance, and it looks like it's in Pewter city") print("On your way there, a trainer want's to battle you, you accept") print("The trainer sent out Hitmonchan!") print("Oh, he has an advantage, but I think you can do this...") print("I'm counting on you... Go", myname) print("Enemy Hitmonchan used Mega Punch") print("Enemy Hitmonchan's attack missed") move3 = input("What would you like to use? Earthquake or Rock slide?").lower() if move3 == "Earthquake": print("Hitmonchan lost half of it's health!") print("Enemy Hitmonchan used Mega Punch") print(myname, "is left with 7 health!") move4 = input("What would you like to use? Earthquake or Rock slide?").lower() if move4 == "earthquake": print("Enemy Hitmonchan fainted!") print(myname, "leveled up to level 10!") print("Alright", myname, "awesome!") print("What!? Geodude is evolving") print("...") print("Conratulations! Your Geodude evolved into a Graveler!") print("You one shotted it, Fantastic!", myname, "is now level 6!") print("You move on...") print("You are now in Viridian City... but the gym seems to be locked") print("The gym's note say's...") print("The gym will be open after you collect another 2 badges") print("You move on to the next city...") print("There are a couple of trainers that want to battle you") print("For you're times sake, you will only have to do one of them, the others will be done for you") print("The trainer sent out Charmaleon") print("Go", myname) move2 = input("What would you like to use? Earthquake or Rock Slide?") if move2 == "earthquake": print("It's super effective!") print("You one shotted it, great", myname,"!") print(myname, "is now level 7!") print("You battled the other trainers, and your", myname, "is level 9") print("This game doesnt follow actual pokemon, so your geodude will evolve at level 10") print("You see a gym in a distance, and it looks like it's in Pewter city") print("On your way there, a trainer want's to battle you, you accept") print("The trainer sent out Hitmonchan!") print("Oh, he has an advantage, but I think you can do this...") print("I'm counting on you... Go", myname) print("Enemy Hitmonchan used Mega Punch") print("Enemy Hitmonchan's attack missed") move3 = input("What would you like to use? Earthquake or Rock slide?").lower() if move3 == "Earthquake": print("Hitmonchan lost half of it's health!") print("Enemy Hitmonchan used Mega Punch") print(myname, "is left with 7 health!") move4 = input("What would you like to use? Earthquake or Rock slide?").lower() if move4 == "earthquake": print("Enemy Hitmonchan fainted!") print(myname, "leveled up to level 10!") print("Alright", myname, "awesome!") print("What!? Geodude is evolving") print("...") print("Conratulations! Your Geodude evolved into a Graveler!") if nicknamequestion == "no": print("Also note that you will not be able to use any of the pokemon that you catch (Catching is currently not working anyway)") print("You start your journey by walking into your first patch of grass...") print("A wild Rattata appeared!") print("Go Geodude!") q1 = input("Would you like to attack, or try to catch it?").lower() if q1 == "attack" or "attack it": move1 = input("What would you like to use? Earthquake or Rock Slide?").lower() if move1 == "earthquake": print("You one shotted it, Fantastic! Your Geodude is now level 6!") print("You move on...") print("You are now in Viridian City... but the gym seems to be locked") print("The gym's note say's...") print("The gym will be open after you collect another 2 badges") print("You move on to the next city...") print("There are a couple of trainers that want to battle you") print("For you're times sake, you will only have to do one of them, the others will be done for you") print("The trainer sent out Charmaleon") print("Go Geodude!") move2 = input("What would you like to use? Earthquake or Rock Slide?") if move2 == "earthquake": print("It's super effective!") print("You one shotted it, great Geodude!") print("Geodude is now level 7!") print("You battled the other trainers, and your Geodude is level 9") print("This game doesnt follow actual pokemon, so your geodude will evolve at level 10") print("You see a gym in a distance, and it looks like it's in Pewter city") print("On your way there, a trainer want's to battle you, you accept") print("The trainer sent out Hitmonchan!") print("Oh, he has an advantage, but I think you can do this...") print("I'm counting on you... Go Geodude") print("Enemy Hitmonchan used Mega Punch") print("Enemy Hitmonchan's attack missed") move3 = input("What would you like to use? Earthquake or Rock slide?").lower() if move3 == "Earthquake": print("Hitmonchan lost half of it's health!") print("Enemy Hitmonchan used Mega Punch") print("Geodude is left with 7 health!") move4 = input("What would you like to use? Earthquake or Rock slide?").lower() if move4 == "earthquake": print("Enemy Hitmonchan fainted!") print("Geodude leveled up to level 10!") print("Alright Geodude, awesome!") print("What!? Geodude is evolving") print("...") print("Conratulations! Your Geodude evolved into a Graveler!") if move2 == "rock slide" or "rockslide": print("It's super effective!") print("You one shotted it, great Geodude!") print("Geodude is now level 7!") print("You battled the other trainers, and your Geodude is level 9") print("This game doesnt follow actual pokemon, so your geodude will evolve at level 10") print("You see a gym in a distance, and it looks like it's in Pewter city") print("On your way there, a trainer want's to battle you, you accept") print("The trainer sent out Hitmonchan!") print("Oh, he has an advantage, but I think you can do this...") print("I'm counting on you... Go Geodude") print("Enemy Hitmonchan used Mega Punch") print("Enemy Hitmonchan's attack missed") move3 = input("What would you like to use? Earthquake or Rock slide?").lower() if move3 == "Earthquake": print("Hitmonchan lost half of it's health!") print("Enemy Hitmonchan used Mega Punch") print("Geodude is left with 7 health!") move4 = input("What would you like to use? Earthquake or Rock slide?").lower() if move4 == "earthquake": print("Enemy Hitmonchan fainted!") print("Geodude leveled up to level 10!") print("Alright Geodude, awesome!") print("What!? Geodude is evolving") print("...") print("Conratulations! Your Geodude evolved into a Graveler!") elif move1 == "rock slide" or "rockslide": print("You almost one shotted it... ") print("Enemy Rattata used Tackle!") print("It's not very effective...") move2 = input("What would you like to use? Earthquake or Rock Side?").lower() if move2 == "earthquake" or "rockslide" or "rock slide": print("Congrats! You defeated the Rattata, and your Geodude has leveled up!") print("You move on...") print("You are now in Viridian City... but the gym seems to be locked") print("The gym's note say's...") print("The gym will be open after you collect another 2 badges") print("You move on to the next city...") print("There are a couple of trainers that want to battle you") print("For you're times sake, you will only have to do one of them, the others will be done for you") print("The trainer sent out Charmaleon") print("Go Geodude!") move2 = input("What would you like to use? Earthquake or Rock Slide?") if move2 == "earthquake": print("It's super effective!") print("You one shotted it, great Geodude!") print("Geodude is now level 7!") print("You battled the other trainers, and your Geodude is level 9") print("This game doesnt follow actual pokemon, so your geodude will evolve at level 10") print("You see a gym in a distance, and it looks like it's in Pewter city") print("On your way there, a trainer want's to battle you, you accept") print("The trainer sent out Hitmonchan!") print("Oh, he has an advantage, but I think you can do this...") print("I'm counting on you... Go Geodude") print("Enemy Hitmonchan used Mega Punch") print("Enemy Hitmonchan's attack missed") move3 = input("What would you like to use? Earthquake or Rock slide?").lower() if move3 == "Earthquake": print("Hitmonchan lost half of it's health!") print("Enemy Hitmonchan used Mega Punch") print("Geodude is left with 7 health!") move4 = input("What would you like to use? Earthquake or Rock slide?").lower() if move4 == "earthquake": print("Enemy Hitmonchan fainted!") print("Geodude leveled up to level 10!") print("Alright Geodude, awesome!") print("What!? Geodude is evolving") print("...") print("Conratulations! Your Geodude evolved into a Graveler!") #elif q1 == "catch" or "Catch it" or "Catch" or "catch it": #print("You threw the Pokeball... and you CAUGHT IT!") if starter == "drowzee": print("Great choice! You decided on the Psychic pokemon Drowzee!") nicknamequestion = input("Would you like to nickname Geodude? (Yes or No?)").lower() if nicknamequestion == "yes": myname = input("What would you like to nickname it?") print("OK, your Drowzee's new name is now",myname) print("Also note that you will not be able to use any of the pokemon that you catch (Catching is currently not working anyway)") print("You start your journey by walking into your first patch of grass...") print("A wild Rattata appeared!") print("Go", myname, "!") q1 = input("Would you like to attack, or try to catch it?").lower() if q1 == "attack" or "attack it": move1 = input("What would you like to use? Psychic or Headbutt?").lower() if move1 == "psychic": print("You one shotted it, Fantastic!", myname, "is now level 6!") print("You move on...") print("You are now in Viridian City... but the gym seems to be locked") print("The gym's note say's...") print("The gym will be open after you collect another 2 badges") print("You move on to the next city...") print("There are a couple of trainers that want to battle you") print("For you're times sake, you will only have to do one of them, the others will be done for you") print("The trainer sent out Charmaleon") print("Go", myname) move2 = input("What would you like to use? Earthquake or Rock Slide?") if move2 == "earthquake": print("It's super effective!") print("You one shotted it, great", myname,"!") print(myname, "is now level 7!") print("You battled the other trainers, and your", myname, "is level 9") print("This game doesnt follow actual pokemon, so your geodude will evolve at level 10") print("You see a gym in a distance, and it looks like it's in Pewter city") print("On your way there, a trainer want's to battle you, you accept") print("The trainer sent out Hitmonchan!") print("Oh, he has an advantage, but I think you can do this...") print("I'm counting on you... Go", myname) print("Enemy Hitmonchan used Mega Punch") print("Enemy Hitmonchan's attack missed") move3 = input("What would you like to use? Earthquake or Rock slide?").lower() if move3 == "Earthquake": print("Hitmonchan lost half of it's health!") print("Enemy Hitmonchan used Mega Punch") print(myname, "is left with 7 health!") move4 = input("What would you like to use? Earthquake or Rock slide?").lower() if move4 == "earthquake": print("Enemy Hitmonchan fainted!") print(myname, "leveled up to level 10!") print("Alright", myname, "awesome!") print("What!? Geodude is evolving") print("...") print("Conratulations! Your Geodude evolved into a Graveler!") print("Also note that you will not be able to use any of the pokemon that you catch (Catching is currently not working anyway)") print("You start your journey by walking into your first patch of grass...") print("A wild Rattata appeared!") print("Go Drowzee!") q1 = input("Would you like to attack, or try to catch it?").lower() if q1 == "attack" or "attack it": move1 = input("What would you like to use? Psychic or Headbutt?").lower() if move1 == "psychic": print("You one shotted it, Fantastic! Your Drowzee is now level 6!") print("You move on...") print("You are now in Viridian City... but the gym seems to be locked") print("The gym's note say's...") print("The gym will be open after you collect another 2 badges") print("You move on to the next city...") print("There are a couple of trainers that want to battle you") print("For you're times sake, you will only have to do one of them, the others will be done for you") print("The trainer sent out Charmaleon") print("Go Drowzee!") move2 = input("What would you like to use? Psychic or Headbutt?") if move2 == "psychic": print("You one shotted it, great Drowzee!") print("Drowzee is now level 7!") print("You battled the other trainers, and your Drowzee is level 9") print("This game doesnt follow actual pokemon, so your Drowzee will evolve at level 10") elif move1 == "headbutt" or "head butt": print("You almost one shotted it... ") print("Enemy Rattata used Tackle!") print("Drowzee has 17 health remaining!") move2 = input("What would you like to use? Psychic or Headbutt?").lower() if move2 == "psychic" or "head butt" or "headbutt": print("Congrats! You defeated the Rattata, and your Drowzee has leveled up!") print("You move on...") print("You are now in Viridian City... but the gym seems to be locked") print("The gym's note say's...") print("The gym will be open after you collect another 2 badges") print("You move on to the next city...") print("There are a couple of trainers that want to battle you") print("For you're times sake, you will only have to do one of them, the others will be done for you") print("The trainer sent out Charmaleon") print("Go Drowzee!") move2 = input("What would you like to use? Psychic or Headbutt?").lower() if move2 == "psychic": print("You one shotted it, great Drowzee!") print("Drowzee is now level 7!") print("You battled the other trainers, and your Drowzee is level 9") print("This game doesnt follow actual pokemon, so your Drowzee will evolve at level 10") elif q1 == "catch" or "Catch it" or "Catch" or "catch it": print("You threw the Pokeball... and you CAUGHT IT!") </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-02T21:44:56.977", "Id": "477510", "Score": "0", "body": "Hello there, Welcome to codereview, Your code can easily be understood but it is recommended that you explain your code a bit at the start." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-02T21:47:14.613", "Id": "477512", "Score": "0", "body": "Oh OK, sorry about that" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-02T21:48:28.897", "Id": "477513", "Score": "0", "body": "It's Python BTW, for anyone who doesn't know. sorry for not clarifying that earlier" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-03T10:45:26.773", "Id": "477562", "Score": "0", "body": "You surely will like https://twinery.org/2/ to write interactive stories very simply for free" } ]
[ { "body": "<p><strong>Bug</strong></p>\n\n<pre><code>elif q1 == \"catch\" or \"Catch it\" or \"Catch\" or \"catch it\":\n</code></pre>\n\n<p>Because:</p>\n\n<pre><code>&gt;&gt;&gt; q1 = \"a\"\n&gt;&gt;&gt; q1 == \"catch\" or \"Catch it\" or \"Catch\" or \"catch it\"\n'Catch it'\n&gt;&gt;&gt; \"catch\" == \"catch\" or \"Catch it\" or \"Catch\" or \"catch it\"\nTrue\n&gt;&gt;&gt; \"0\" == \"catch\" or \"Catch it\" or \"Catch\" or \"catch it\"\n'Catch it'\n</code></pre>\n\n<p>So it is true for all strings.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-03T09:35:56.360", "Id": "477558", "Score": "2", "body": "Eyup you are correct." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-03T14:41:08.260", "Id": "477594", "Score": "0", "body": "Wait, what exactly was done with the code here?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-03T22:24:47.577", "Id": "477661", "Score": "0", "body": "@Chase-WinnerPlayz `elif q1 in [\"catch\", \"Catch it\", \"Catch\", \"catch it\"]:` but you could make it easier with `elif q1.lower().startswith('catch'):` and cover everything starting with \"catch\"" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-03T06:53:36.680", "Id": "243300", "ParentId": "243286", "Score": "2" } } ]
{ "AcceptedAnswerId": "243300", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-02T21:43:02.957", "Id": "243286", "Score": "4", "Tags": [ "python", "pokemon" ], "Title": "Pokemon Journey" }
243286
<p>We have published a product today called MMMR.js this product is licensed under the MIT license and is built by Syed Mohammad Sannan.</p> <p>The uniqueness of this product is that it is built with and for Javascript though there are many libraries out there such as NumPY, SciPY, and much much more but they are built for Python or another language and there isn't one for JavaScript that is where MMMR.js comes.</p> <p><a href="https://github.com/SannanOfficial/MMMR.js" rel="nofollow noreferrer">here</a>.</p> <p>This is the source code of MMMR.js:</p> <pre><code>// Mean - The average value. // Median - The mid point value. // Mode - The most common value. // Range The smallest and the biggest value. // This is Mean. // Mean returns the average value from an array of numbers. // To call/run this function we can type mean(Your array of numbers separated with commas ','); const mean = (numbers) =&gt; { let total = 0, i; for (i = 0; i &lt; numbers.length; i += 1) { total += numbers[i]; } return total / numbers.length; }; // This is Median. // Median returns the middle point value from an array of numbers. // To call/run this function we can type median(Your array of numbers separated with commas ','); const median = (numbers) =&gt; { const sorted = numbers.slice().sort((a, b) =&gt; a - b); const middle = Math.floor(sorted.length / 2); if (sorted.length % 2 === 0) { return (sorted[middle - 1] + sorted[middle]) / 2; } return sorted[middle]; }; // This is Mode. // Mode returns the most common/used value from an array of string, numbers, etc. // To call/run this function we can type mode(your array of numbers); const mode = (a) =&gt; { a.sort((x, y) =&gt; x - y); let bestStreak = 1; let bestElem = a[0]; let currentStreak = 1; let currentElem = a[0]; for (let i = 1; i &lt; a.length; i++) { if (a[i - 1] !== a[i]) { if (currentStreak &gt; bestStreak) { bestStreak = currentStreak; bestElem = currentElem; } currentStreak = 0; currentElem = a[i]; } currentStreak++; } return currentStreak &gt; bestStreak ? currentElem : bestElem; }; // This is Range. // Range is basically a function used to return the smallest and the biggest values from an array of numbers. // To call/run this function we can type range(your array of numbers); const range = (value) =&gt; { value.sort(); return [value[0], value[value.length - 1]]; } </code></pre> <p>We just wanted you to review this code and tell us is this library user-friendly, maintainable and what improvements can we add to this.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-04T16:07:01.757", "Id": "477713", "Score": "2", "body": "From [the link in my last comment](https://codereview.stackexchange.com/help/someone-answers): \"**What should I _not_ do? Do not change the code in the question after receiving an answer.** Incorporating advice from an answer into the question violates the question-and-answer nature of this site.\". I encourage you to read the section titled **I improved my code based on the reviews. What next?** especially option #1" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-13T11:49:40.120", "Id": "478585", "Score": "0", "body": "Thank you, BYTES Genesis, for this wonderful library I use Python for machine learning projects but in this project, I had to use Js I was looking for a library like this on the internet but did not find any other but then I stumbled upon MMMR.js which helped me do all my work related to mean median mode and range in Javascript. I also used Math.js a little bit but because of its less user-friendliness, I used MMM.js in the cases of Mean Median Mode and Range in Js." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-13T11:53:04.527", "Id": "478587", "Score": "0", "body": "@NANO You are welcome If you like to please drop an answer and tell us what can be done to make MMMR.js better." } ]
[ { "body": "<h1>Comments</h1>\n\n<p>The comments such a <code>This is Mean.</code> are pointless.</p>\n\n<p>And the comment </p>\n\n<pre><code>// To call/run this function we can type mean(Your array of numbers separated with commas ',');\n</code></pre>\n\n<p>is a bit strange. Are they targeting people who don't know basic JavaScript syntax? Then why mention commas, but not the brackets (<code>[...]</code>) needed for an array.</p>\n\n<p>It probably would be a good idea to instead use a standard comment format for documentation such as <a href=\"https://jsdoc.app/\" rel=\"noreferrer\">jsdoc</a>.</p>\n\n<h1>Sorting</h1>\n\n<p>The comparison function used for sorting (<code>(a, b) =&gt; a - b</code>) is pointless, because that is the default.</p>\n\n<h1>Mutating the input array</h1>\n\n<p>In <code>median</code> you are creating a copy of the input array with <code>.slice()</code> before sorting it, so that it isn't modified, which is a good thing. You should do the same in <code>mode</code> and <code>range</code>.</p>\n\n<h1>Validating the input</h1>\n\n<p>You should consider validating the input. <code>mean</code>, <code>mode</code> and <code>range</code> break or give unexpected results if you give them an empty array. It's probably best to check if they are receiving an array at all. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-04T14:27:12.590", "Id": "477705", "Score": "0", "body": "Thanks for your feedback we will implement the changes ASAP." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-04T15:04:35.880", "Id": "477709", "Score": "1", "body": "Your changes were made except for the input validation because It is not necessary this library provides a basic structure for MMMR which programmers can use in Javascript without manually programming it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-05T08:24:08.643", "Id": "477770", "Score": "2", "body": "If you don't validate the input, then clearly document that and the expected input." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-05T13:08:36.217", "Id": "477786", "Score": "1", "body": "Yes thank you we will." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-04T14:13:10.490", "Id": "243379", "ParentId": "243287", "Score": "8" } }, { "body": "<p>Rotara already mentioned some great points - the comments can definitely be improved and follow common conventions, sorting should happen on copies of the data instead of the original data, and the input should be validated. Consider the case of <code>mean</code> when an empty array is passed in. The value of <code>numbers.length</code> will be <code>0</code> so this leads to division by zero, which results in <code>NaN</code>. Perhaps it would be wise to <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/throw\" rel=\"nofollow noreferrer\"><code>throw</code></a> an exception in that case.</p>\n<p>Let's look at the <code>mean()</code> function. It has a traditional <code>for</code> loop, though the iterator variable, i.e. <code>i</code>, is only used to dereference values in the array. That could be changed to the simpler syntax of a <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of\" rel=\"nofollow noreferrer\"><code>for...of</code> loop</a></p>\n<pre><code>const mean = (numbers) =&gt; {\n let total = 0;\n\n for (const num of numbers) {\n total += num;\n }\n return total / numbers.length;\n};\n</code></pre>\n<p>Moreover, a functional approach could be used with <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce\" rel=\"nofollow noreferrer\"><code>Array.reduce()</code></a>:</p>\n<pre><code>const sum = (a, b) =&gt; a + b\nconst mean = numbers =&gt; {\n return numbers.reduce(sum, 0) / numbers.length;\n}\n</code></pre>\n<p>I tried these various functions with an array of five elements, as well as <a href=\"https://jsperf.com/mean-comparison\" rel=\"nofollow noreferrer\">fifteen elements</a>. It seems the original code is somewhat faster than the other approaches in FF and Chrome. So for a library that may be used with many projects it may make sense to keep with the original syntax. While I don't condone plagiarism I did peek at the source of <a href=\"https://mathjs.org/\" rel=\"nofollow noreferrer\">mathjs</a> and saw that its <a href=\"https://github.com/josdejong/mathjs/blob/develop/src/function/statistics/mean.js#L78\" rel=\"nofollow noreferrer\"><code>mean()</code></a> uses a custom function <a href=\"https://github.com/josdejong/mathjs/blob/develop/src/utils/collection.js#L27\" rel=\"nofollow noreferrer\"><code>deepForEach()</code></a> which is basically a traditional <code>for</code> loop. As <a href=\"https://hacks.mozilla.org/2015/04/es6-in-depth-iterators-and-the-for-of-loop/\" rel=\"nofollow noreferrer\">this article</a> explains, the <code>for...of</code> loop uses an iterator method for each iteration and that is the cause of the slower execution.</p>\n<p>As <a href=\"https://www.freecodecamp.org/news/how-to-optimize-your-javascript-apps-using-loops-d5eade9ba89f/\" rel=\"nofollow noreferrer\">this freecodecamp article</a> explains:</p>\n<blockquote>\n<p>“<em>The first step in optimizing the amount of work in a loop is to minimize the number of object members and array item lookups.</em></p>\n</blockquote>\n<blockquote>\n<p><em>You can also increase the performance of loops by reversing their order. In JavaScript, reversing a loop does result in a small performance improvement for loops, provided that you eliminate extra operations as a result.</em>”</p>\n</blockquote>\n<p>This means two optimizations for those loops would be to do one of the following:</p>\n<ul>\n<li><p>store length of the array in a separate variable instead of comparing the property each time</p>\n<pre><code> for (let i = 0, const l = numbers.length; i &lt; l; i += 1) {\n</code></pre>\n</li>\n<li><p>add Items in reverse to eliminate steps</p>\n<pre><code> // minimizing property lookups and reversing\n for (let i = numbers.length; i--; ){\n</code></pre>\n<p>This could also be written as a <code>while</code> loop</p>\n</li>\n</ul>\n<p>Notice <code>let i</code> can be moved inside the <code>for</code> loop since the scope can be limited to just that block.</p>\n<p>I also compared the <code>mode</code> function with the <a href=\"https://github.com/josdejong/mathjs/blob/develop/src/function/statistics/mode.js#L47\" rel=\"nofollow noreferrer\">mathjs implementation for the same function</a>. It appears that implementation uses a mapping of values to counts, which would require more memory. It also returns an array of all values that have the most number of occurrences. The MMMRjs implementation appears to return the first value that contains the maximum number of occurrences. This should be documented in the comments.</p>\n<p>Beyond that I don't see much to suggest, except maybe <strong>unit tests</strong> to cover all scenarios that should be handled by the code. The code looks decently written, especially using <code>const</code> and <code>let</code> where appropriate. It also has consistent indentation of nesting levels.</p>\n<hr />\n<h3>Addition June 10, 2020</h3>\n<p>You mentioned <a href=\"https://codereview.stackexchange.com/questions/243287/mmmrjs-a-product-of-bytes-genesis#comment478018_243539\">&quot;<em>Most of the points mentioned in Ratora's answer were already implemented please check the updated source code by downloading the library from the link given above</em>&quot;</a>. I noticed that <code>range</code> was updated to call <code>slice()</code> on the input array before calling <code>sort</code>. However the returned array is not stored or used in the <code>return</code> statement. Thus the output may be incorrect if the values aren't already sorted. See the snippet below for a demonstration.</p>\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 range = (numbers) =&gt; {\n numbers.slice().sort();\n return [numbers[0], numbers[numbers.length - 1]];\n};\nconst nums = Object.freeze([0.4, 0.2, 0.3]);\nconst expected = [0.2, 0.4];\nconst outputRange = range(nums);\nconsole.log('output from range(): ', outputRange);\nconsole.log('expected output: ', expected);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-08T10:30:00.167", "Id": "478018", "Score": "0", "body": "Yes, Sam, you are correct we will try to make some changes ASAP.\nMost of the points mentioned in Ratora's answer were already implemented please check the updated source code by downloading the library from the link given above." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-08T15:29:56.967", "Id": "478079", "Score": "0", "body": "If you would like the updated code reviewed then please consider posting [a follow-up question](https://codereview.meta.stackexchange.com/q/5524/120114)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-08T21:04:54.437", "Id": "478095", "Score": "0", "body": "@SamOnela thank you for telling but we don't want it to be reviewed I was just telling that the fixes told by Rotora were done." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-10T13:31:15.380", "Id": "478263", "Score": "0", "body": "Okay I have added another section that covers the updated `range()` function" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-10T15:29:23.900", "Id": "478286", "Score": "0", "body": "Thank you for the updated answer, Sam, we will do the changes asap" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-10T15:36:15.947", "Id": "478287", "Score": "0", "body": "Thank you Sam We have updated the code again with the new changes." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-08T05:34:41.187", "Id": "243539", "ParentId": "243287", "Score": "6" } }, { "body": "<h2>Not an O(n) MMMR library</h2>\n<p>There are a lot unnecessary inefficiency on that code. For big data, it makes a lot difference.</p>\n<p>The current version, time complexity-wise...\n<span class=\"math-container\">$$\\text{ mean() and mode() are }O(n)$$</span>. <span class=\"math-container\">$$\\text{range() and median() are } O(n .log(n))$$</span>.</p>\n<p>All could be implemented in average time complexity O(n). Not only that, checking if the list is ordered, taking the mean, max, min and mode could be done with one loop.</p>\n<p>Once, you have checked the list is ordered, the median can be calculated as in this code. If is not, you can use &quot;Median find algorithm&quot;: <a href=\"https://rcoh.me/posts/linear-time-median-finding/\" rel=\"nofollow noreferrer\">https://rcoh.me/posts/linear-time-median-finding/</a></p>\n<p>Just as example, the code below shows how to detect ordering, and how to find the max, the min and the mean of a list. Now, you can implement &quot;Median Finding&quot; and add the mode calculation to have an efficient MMMR library.</p>\n<pre><code>\nconst medianFromSorted = (numbers) =&gt; {\n const middle = Math.floor(numbers.length / 2);\n if (numbers.length % 2 === 0) {\n return (numbers[middle - 1] + numbers[middle]) / 2;\n }\n return numbers[middle];\n};\n\n\nconst mmr = (numbers) =&gt; {\n\n if (numbers.length === 0) {\n return {mean: undefined, moda: undefined, median: undefined, range: undefined};\n }\n if (numbers.length === 1) {\n return {mean: numbers[0], moda: numbers[0], median: numbers[0], range: [numbers[0], numbers[0]]};\n }\n let total = 0, i;\n let asc = numbers[0] &lt;= numbers[1];\n let desc = numbers[0] &gt;= numbers[1];\n let min = numbers[0];\n let max = numbers[0];\n let previous = numbers[0];\n\n for (i = 0; i &lt; numbers.length; i++) {\n total += numbers[i];\n if (numbers[i] &lt; min)\n min = numbers[i];\n if (numbers[i] &gt; max)\n max = numbers[i];\n asc = asc &amp;&amp; (previous &lt;= numbers[i]);\n desc = desc &amp;&amp; (previous &gt;= numbers[i]);\n previous = numbers[i];\n }\n let median;\n if (asc || desc)\n median = medianFromSorted(numbers);\n else\n median = medianFinding(numbers);\n\n return {\n mean: total / numbers.length,\n median: median,\n range: [min, max]\n }\n\n};\n<span class=\"math-container\">```</span>\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-12T08:16:30.990", "Id": "478462", "Score": "0", "body": "Thank you very much your feedback and suggestions were helpful and we will see what we can do." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-12T04:05:12.783", "Id": "243747", "ParentId": "243287", "Score": "2" } } ]
{ "AcceptedAnswerId": "243379", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-02T21:58:02.260", "Id": "243287", "Score": "12", "Tags": [ "javascript", "ecmascript-6", "mathematics", "library", "ai" ], "Title": "MMMRjs a product of BYTES Genesis" }
243287
<p>For homework, I had to parse CPUID instruction output in C, which required a lot of specific bit-manipulation like:</p> <pre><code>(eax &amp; CACHE_LEVEL) &gt;&gt; 5 </code></pre> <p>I calculated the mask <code>CACHE_LEVEL</code> and the amount that was needed to be right-shifted by hand. It was a pain, so I decided to write a couple Python functions to help with this.</p> <p>For example:</p> <pre><code>&gt;&gt;&gt; eax = 0x4004121 # Taken from a register after executing a CPUID instruction with leaf-4 indicated &gt;&gt;&gt; parse_out_bits(eax, 5, 7) # Return the value at bits 5 to 7 (inclusive) 1 # This is an L1 cache </code></pre> <p>Indices are 0-based and inclusive.</p> <p>Where <code>eax</code> is the following, and I want the value of the bits from <code>S</code> to <code>E</code>:</p> <pre><code> E S 100 0000 0000 0100 0001 0010 0001‬ </code></pre> <p>I'd like notes on anything here, but specifically how this could be done better in terms of bit manipulation.</p> <pre><code>from typing import Generator def bit_place_values(start_index: int, end_index: int) -&gt; Generator[int, None, None]: acc = 1 &lt;&lt; start_index for _ in range(start_index, end_index + 1): yield acc acc &lt;&lt;= 1 def parse_out_bits(bit_field: int, start_index: int, end_index: int) -&gt; int: mask = sum(bit_place_values(start_index, end_index)) return (mask &amp; bit_field) &gt;&gt; start_index </code></pre>
[]
[ { "body": "<p>This is not the kind of thing you should loop for. Just calculate a mask:</p>\n\n<pre><code>def parse_out_bits(bit_field: int, start_index: int, end_index: int) -&gt; int:\n mask = (1 &lt;&lt; (end_index - start_index + 1)) - 1\n return (bit_field &gt;&gt; start_index) &amp; mask\n</code></pre>\n\n<p>In English:</p>\n\n<ul>\n<li>If you're getting bits 5-7, that's 3 bits</li>\n<li>2^3 == 8, - 1 = 7 (or 111 in binary - that is your mask)</li>\n<li>Shift the field right by 5 to put the bits of interest in the least-significant position</li>\n<li>And-mask them to get the result.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-03T00:23:10.520", "Id": "477529", "Score": "0", "body": "Nice. But gosh, bit arithmetic is hard for me to read. (you've got it quite nice tho)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-03T00:20:18.093", "Id": "243290", "ParentId": "243289", "Score": "8" } } ]
{ "AcceptedAnswerId": "243290", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-03T00:04:48.880", "Id": "243289", "Score": "7", "Tags": [ "python", "python-3.x", "homework", "bitwise" ], "Title": "Parsing a sequence of bits out of a bit field" }
243289
<p>I made this because I couldn't find any good C# classes/libraries that allow you to dump the contents of a process' memory into a file or a byte array. I haven't tested this on 32 bit systems but it works in both x86 and x64 on my 64 bit system. I've been mostly testing this on the notepad process which executes pretty quickly, but I've also tried this on the steam process with 120 mb memory which worked but took around 30 seconds. How can I improve this and what bugs have I overlooked? Any feedback is appreciated, thanks.</p> <p>MemoryDump.cs</p> <pre><code>using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Runtime.InteropServices; using System.Text; namespace MemoryDumper { public struct Chunk { public Dumper.MEMORY_BASIC_INFORMATION MemoryInformation; public byte[] Bytes; } public class MemoryDump { public MemoryDump(Chunk[] chunks) { Chunks = chunks; long bytesSum = 0; foreach (var chunk in chunks) bytesSum += chunk.Bytes.Length; Bytes = new byte[bytesSum]; int byteOffset = 0; foreach (var chunk in chunks) { for (int i = 0; i &lt; chunk.Bytes.Length; i++) { Bytes[byteOffset + i] = chunk.Bytes[i]; } byteOffset += chunk.Bytes.Length; } } public readonly Chunk[] Chunks; public readonly byte[] Bytes; public string BytesString { get { byte[] cleansedBytes = Bytes; for (int i = 0; i &lt; Bytes.Length; i++) cleansedBytes[i] = (byte)ToChar(cleansedBytes[i]); return Encoding.UTF8.GetString(cleansedBytes); } } public static char ToChar(byte bt) { bool isPrintable = bt &gt;= 32 &amp;&amp; bt &lt;= 126; return isPrintable ? (char)bt : '.'; } [Flags] public enum DumpSaveOptions { // ex: 43 6F 77 4E 61 74 69 6F 6E BytesArray = 1, // ex: CowNation BytesString = 2, // ex: 43 6F 77 4E 61 74 69 6F 6E | CowNation Both = BytesArray | BytesString }; public void Save(string filePath, DumpSaveOptions options = DumpSaveOptions.Both, int bytesPerLine = 56) { if (!File.Exists(filePath)) throw new Exception("File '" + filePath + "' doesn't exist"); bool bytesArray = (options &amp; DumpSaveOptions.BytesArray) != 0; bool bytesString = (options &amp; DumpSaveOptions.BytesString) != 0; StreamWriter streamWriter = new StreamWriter(filePath); for (int i = 0; i &lt; Bytes.Length / bytesPerLine; i++) { // the bytes for this line byte[] lineBytes = new byte[bytesPerLine]; Array.Copy(Bytes, i * bytesPerLine, lineBytes, 0, bytesPerLine); string line = ""; string dataString = ""; foreach (byte bt in lineBytes) { if (bytesArray) { string b = bt.ToString("X"); line += (b.Length == 1 ? "0" + b : b) + " "; } if (bytesString) dataString += ToChar(bt); } line += (bytesArray &amp;&amp; bytesString ? "| " : "") + dataString; streamWriter.WriteLine(line); } streamWriter.Close(); } } public class Dumper { #region IMPORTS [DllImport("kernel32.dll")] static extern IntPtr OpenProcess(ProcessAccessFlags dwDesiredAccess, bool bInheritHandle, int dwProcessId); [DllImport("kernel32.dll", SetLastError = true)] static extern bool ReadProcessMemory( IntPtr hProcess, IntPtr lpBaseAddress, byte[] lpBuffer, int nSize, out IntPtr lpNumberOfBytesRead); [DllImport("kernel32.dll")] static extern void GetSystemInfo(out SYSTEM_INFO lpSystemInfo); [DllImport("kernel32.dll", SetLastError = true)] static extern int VirtualQueryEx(IntPtr hProcess, IntPtr lpAddress, out MEMORY_BASIC_INFORMATION lpBuffer, uint dwLength); #endregion #region ENUMS public enum AllocationProtectEnum : uint { PAGE_EXECUTE = 0x00000010, PAGE_EXECUTE_READ = 0x00000020, PAGE_EXECUTE_READWRITE = 0x00000040, PAGE_EXECUTE_WRITECOPY = 0x00000080, PAGE_NOACCESS = 0x00000001, PAGE_READONLY = 0x00000002, PAGE_READWRITE = 0x00000004, PAGE_WRITECOPY = 0x00000008, PAGE_GUARD = 0x00000100, PAGE_NOCACHE = 0x00000200, PAGE_WRITECOMBINE = 0x00000400 } public enum StateEnum : uint { MEM_COMMIT = 0x1000, MEM_FREE = 0x10000, MEM_RESERVE = 0x2000 } public enum TypeEnum : uint { MEM_IMAGE = 0x1000000, MEM_MAPPED = 0x40000, MEM_PRIVATE = 0x20000 } [Flags] enum ProcessAccessFlags : uint { All = 0x001F0FFF, Terminate = 0x00000001, CreateThread = 0x00000002, VirtualMemoryOperation = 0x00000008, VirtualMemoryRead = 0x00000010, VirtualMemoryWrite = 0x00000020, DuplicateHandle = 0x00000040, CreateProcess = 0x000000080, SetQuota = 0x00000100, SetInformation = 0x00000200, QueryInformation = 0x00000400, QueryLimitedInformation = 0x00001000, Synchronize = 0x00100000 } #endregion #region STRUCTS public struct MEMORY_BASIC_INFORMATION { public IntPtr BaseAddress; public IntPtr AllocationBase; public AllocationProtectEnum AllocationProtect; public IntPtr RegionSize; public StateEnum State; public AllocationProtectEnum Protect; public TypeEnum Type; } [StructLayout(LayoutKind.Sequential)] public struct SYSTEM_INFO { public ushort processorArchitecture; ushort reserved; public uint pageSize; public IntPtr minimumApplicationAddress; public IntPtr maximumApplicationAddress; public IntPtr activeProcessorMask; public uint numberOfProcessors; public uint processorType; public uint allocationGranularity; public ushort processorLevel; public ushort processorRevision; } #endregion public static MemoryDump Dump(Process process) { if (process == Process.GetCurrentProcess()) // a recursive memory allocation loop happens in this case until it runs out of memory throw new Exception("Cannot dump the memory of this process"); List&lt;Chunk&gt; chunks = new List&lt;Chunk&gt;(); SYSTEM_INFO systemInfo = new SYSTEM_INFO(); GetSystemInfo(out systemInfo); IntPtr minimumAddress = systemInfo.minimumApplicationAddress; IntPtr maximumAddress = systemInfo.maximumApplicationAddress; IntPtr processHandle = OpenProcess(ProcessAccessFlags.QueryInformation | ProcessAccessFlags.VirtualMemoryRead, false, process.Id); if (processHandle == IntPtr.Zero) throw new Exception("Cannot get a handle to process"); while (minimumAddress.ToInt64() &lt; maximumAddress.ToInt64()) { MEMORY_BASIC_INFORMATION memoryInformation = new MEMORY_BASIC_INFORMATION(); VirtualQueryEx(processHandle, minimumAddress, out memoryInformation, (uint)Marshal.SizeOf(typeof(MEMORY_BASIC_INFORMATION))); // check if this chunk is accessible if (memoryInformation.Protect == AllocationProtectEnum.PAGE_READWRITE &amp;&amp; memoryInformation.State == StateEnum.MEM_COMMIT) { byte[] buffer = new byte[memoryInformation.RegionSize.ToInt64()]; ReadProcessMemory(processHandle, memoryInformation.BaseAddress, buffer, memoryInformation.RegionSize.ToInt32(), out IntPtr bytesRead); chunks.Add(new Chunk { MemoryInformation = memoryInformation, Bytes = buffer }); } // move to the next chunk try { minimumAddress = new IntPtr(minimumAddress.ToInt64() + memoryInformation.RegionSize.ToInt64()); } catch (OverflowException) { break; } } return new MemoryDump(chunks.ToArray()); } } } </code></pre> <p>Example Usage:</p> <pre><code> var dump = Dumper.Dump(Process.GetProcessesByName("notepad")[0]); dump.Save("dump.txt"); File.WriteAllText("bytesString.txt", dump.BytesString); </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-09-30T09:20:05.177", "Id": "490393", "Score": "0", "body": "I tried it and I have to cast all ToInt64() to ulong (like (ulong)maximumAddress.ToInt64()), otherwise I end up with negative values. Other than that it worked, but the text I typed into Notepad doesn't show up in your dump." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-09-30T16:00:06.580", "Id": "490417", "Score": "0", "body": "Is the question still valid? Still need advice?" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-03T01:38:52.843", "Id": "243292", "Score": "2", "Tags": [ "c#", ".net", "pointers", "windows", "memory-optimization" ], "Title": "C# class to dump the memory of a process in several formats" }
243292
<p>As told by experts, I am re-posting the code review request with the code.</p> <p>Brief Description:</p> <ol> <li><p>from outside sha256() will be called with parameter having UTF-16 character set.</p></li> <li><p>then after prepareData() and initializing variables, the hash() will be called with converted binary message string (having pad and 64 bits message length appended) as parameter inside sha256(). The number of calls is ((total message length) / 512). Each hash function includes 64 internal rounds.</p></li> <li><p>With that the initialized hash value 8 * (32 bits) = 256 bits initialized hash value will be updated to final value in the last loop. After adding those up to a string, we are getting the final hash value of 256 bits.</p></li> </ol> <p>I just want to get my code reviewed, and any suggestion or help will be worth to welcome.</p> <p>The following is my script.js file.</p> <pre><code>var H = []; var W = []; function sha256 (input) { var output = ""; input = prepareInputBits (input); var n = Math.floor (input.length / 512); prepareData(); for (i = 0; i &lt; n; i++) { // (n * 512 bits) chunk hash (input.substr (i * 512, 512)); } for (i = 0; i &lt; H.length; i++) { output += H[i]; } output = convertBase2To16 (output); return output; } function hash (input) { // 512 bits in var i; let sigma0 = ""; let sigma1 = ""; /* ** 64 rounds = (16 + 48) rounds ** for first 16 rounds, 512 bits = 16 * 32 bits = 16 words ** for next 48 rounds, calculate round word, W[i] */ for (i = 0; i &lt; 64; i++) { if (i &lt; 16) { W[i] = input.substr(32 * i, 32); } else { sigma0 = bitsXor (bitsXor (rotateRight (W[i-15], 7), rotateRight (W[i-15], 18)), shiftRight (W[i-15], 3)); sigma1 = bitsXor (bitsXor (rotateRight (W[i-2], 17), rotateRight (W[i-2], 19)), shiftRight (W[i-2], 10)); W[i] = bitsAdd (W[i-16], W[i-7]); W[i] = bitsAdd (W[i], bitsAdd (sigma0, sigma1)); } } let t0 = null; let t1 = null; for (var round = 0; round &lt; 64; round++) { t0 = bitsAdd (H[7], bitsAdd (bitsAdd (Ep1(H[4]), Ch(H[4], H[5], H[6])), bitsAdd (_K[round], W[round]))); t1 = bitsAdd (Ep0(H[0]), Maj(H[0], H[1], H[2])); H[7] = H[6]; H[6] = H[5]; H[5] = H[4]; H[4] = bitsAdd (H[3], t0); H[3] = H[2]; H[2] = H[1]; H[1] = H[0]; H[0] = bitsAdd (t0, t1); } } function prepareInputBits (input) { // binary-message + padding (1000...) + message-length (64 bits) =&gt; 0 (modulo 512) var output = ""; var i, x; // converting character ASCII or UTF to hex-number (16 bits each) string for (i = 0; i &lt; input.length; i++) { x = convertBase10To2 (input.charCodeAt(i)); output += padLeftZeroes (x, (16 - x.length)); } // getting 64 bit message length let msgLen = convertBase10To2 (output.length); msgLen = padLeftZeroes (msgLen, 64 - msgLen.length); x = output.length % 512; // getting extra bits length let nP = 0; // number of zeroes in pad if (x == 0) { // add new block nP = 512 - 65; // 65 = 64 + 1 } else if (x &gt; 447) { // add new block nP = (512 - x) + (512 - 65); } else { // use last block nP = 512 - x - 65; } output = output + "1" + padLeftZeroes ("", nP) + msgLen; console.log(output); return output; } function prepareData() { var i; // initialize hash value with base hash constants H = []; for (i = 0; i &lt; 8; i++) { H.push(_H[i]); } // initialize word with 64 empty string W = []; for (i = 0; i &lt; 64; i++) { W.push(""); } } // *** basic hash functions *** function Ch (E, F, G) { return bitsXor (bitsAnd (E, F), bitsAnd (bitsNot (E), G)); } function Maj (A, B, C) { return bitsXor (bitsXor (bitsAnd (A, B), bitsAnd (B, C)), bitsAnd (C, A)); } function Ep0 (A) { return bitsXor (bitsXor (rotateRight(A, 2), rotateRight(A, 13)), rotateRight(A, 22)); } function Ep1 (E) { return bitsXor (bitsXor (rotateRight(E, 6), rotateRight(E, 11)), rotateRight(E, 25)); } // *** basic binary functions *** function padLeftZeroes (input, numberOfZeroes) { var initialZeroes = ""; for (var i = 0; i &lt; numberOfZeroes; i++) { initialZeroes += "0"; } return (initialZeroes + input); } function convertBase10To2 (input) { var output = ""; while (input != 0) { output = (input % 2) + output; input = Math.floor(input / 2); } return output; } function convertBase2To10 (base2s) { var base10n = 0; for (var i = 0; i &lt; base2s.length; i++) { base10n = 2 * base10n + ((base2s[i] == "1") ? 1 : 0); } return base10n; } function convertBase2To16 (input) { let listNibbles = ["0000", "0001", "0010", "0011", "0100", "0101", "0110", "0111", "1000", "1001", "1010", "1011", "1100", "1101", "1110", "1111"]; let listDigits = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F']; let output = ""; var x = (input.length % 4); if (x != 0) { input = padLeftZeroes(input, 4 - x); } for (var i = 0; i &lt; input.length; i += 4) { for (var j = 0; j &lt; 16; j++) { if (input.substr(i, 4) == listNibbles[j]) { break; } } output += listDigits[j]; } return output; } function convertToNibbles (input) { var output = ""; for (var i = 0; i &lt; input.length; i += 4) { output += getNibble (input.substr(i, 4)); } return output; } function getNibble (base2s) { var base16s = ""; const list = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F"]; base16s = list[convertBase2To10 (base2s)]; return base16s; } // *** basic bits functions *** function shiftRight (input, numberOfBits) { var output = ""; output = input.substring(0, numberOfBits); output = padLeftZeroes(output, input.length - numberOfBits); return output; } function rotateLeft (input, numberOfBits) { var output = ""; output = input.substring(numberOfBits, input.length) + input.substring(0, numberOfBits); return output; } function rotateRight (input, numberOfBits) { var output = ""; output = input.substring(input.length - numberOfBits, input.length) + input.substring(0, input.length - numberOfBits); return output; } // *** basic gate functions *** function bitNot (x) { return (x == '0') ? '1' : '0'; } function bitOr (x, y) { return (x == '1' || y == '1') ? '1' : '0'; } function bitXor (x, y) { return (x == y) ? '0' : '1'; } function bitAnd (x, y) { return (x == '0' || y == '0') ? '0' : '1'; } // *** bunch gates functions *** function bitsOr (a, b) { var c = ""; if (a.length != b.length) { a = padLeftZeroes (a, b.length - a.length); b = padLeftZeroes (b, a.length - b.length); } for (var i = 0; i &lt; a.length; i++) { c += bitOr (a[i], b[i]); } return c; } function bitsAnd (a, b) { var c = ""; if (a.length != b.length) { a = padLeftZeroes(a, b.length - a.length); b = padLeftZeroes(b, a.length - b.length); } for (var i = 0; i &lt; a.length; i++) { c += bitAnd (a[i], b[i]); } return c; } function bitsNot (a) { var b = ""; for (var i = 0; i &lt; a.length; i++) { b += bitNot (a[i]); } return b; } function bitsXor (a, b) { var c = ""; if (a.length != b.length) { a = padLeftZeroes(a, b.length - a.length); b = padLeftZeroes(b, a.length - b.length); } for (var i = 0; i &lt; a.length; i++) { c += bitXor (a[i], b[i]); } return c; } // basic arithmetic functions function bitAdd (c_in, x, y) { let xor = bitXor (x, y); let c_out = bitOr (bitAnd (x, y), bitAnd (c_in, xor)); let s = bitXor (c_in, xor); return (c_out + s); } function bitsAdd (a, b) { var i = 0; var s = ""; var c = '0'; let x = ""; if (a.length != b.length) { a = padLeftZeroes (a, b.length - a.length); b = padLeftZeroes (b, a.length - b.length); } for (i = a.length - 1; i &gt;= 0; i--) { x = bitAdd (c, a[i], b[i]); c = x[0]; s = x[1] + s; } s = c + s; return trimNumber (s, a.length); } function trimNumber (input, bitsLength) { let x = input.length - bitsLength; return input.substr (x, bitsLength); } </code></pre> <p>And the following is my data.js file content</p> <pre><code>const _K = [ "01000010100010100010111110011000", "01110001001101110100010010010001", "10110101110000001111101111001111", "11101001101101011101101110100101", "00111001010101101100001001011011", "01011001111100010001000111110001", "10010010001111111000001010100100", "10101011000111000101111011010101", "11011000000001111010101010011000", "00010010100000110101101100000001", "00100100001100011000010110111110", "01010101000011000111110111000011", "01110010101111100101110101110100", "10000000110111101011000111111110", "10011011110111000000011010100111", "11000001100110111111000101110100", "11100100100110110110100111000001", "11101111101111100100011110000110", "00001111110000011001110111000110", "00100100000011001010000111001100", "00101101111010010010110001101111", "01001010011101001000010010101010", "01011100101100001010100111011100", "01110110111110011000100011011010", "10011000001111100101000101010010", "10101000001100011100011001101101", "10110000000000110010011111001000", "10111111010110010111111111000111", "11000110111000000000101111110011", "11010101101001111001000101000111", "00000110110010100110001101010001", "00010100001010010010100101100111", "00100111101101110000101010000101", "00101110000110110010000100111000", "01001101001011000110110111111100", "01010011001110000000110100010011", "01100101000010100111001101010100", "01110110011010100000101010111011", "10000001110000101100100100101110", "10010010011100100010110010000101", "10100010101111111110100010100001", "10101000000110100110011001001011", "11000010010010111000101101110000", "11000111011011000101000110100011", "11010001100100101110100000011001", "11010110100110010000011000100100", "11110100000011100011010110000101", "00010000011010101010000001110000", "00011001101001001100000100010110", "00011110001101110110110000001000", "00100111010010000111011101001100", "00110100101100001011110010110101", "00111001000111000000110010110011", "01001110110110001010101001001010", "01011011100111001100101001001111", "01101000001011100110111111110011", "01110100100011111000001011101110", "01111000101001010110001101101111", "10000100110010000111100000010100", "10001100110001110000001000001000", "10010000101111101111111111111010", "10100100010100000110110011101011", "10111110111110011010001111110111", "11000110011100010111100011110010" ]; var _H = [ "01101010000010011110011001100111", "10111011011001111010111010000101", "00111100011011101111001101110010", "10100101010011111111010100111010", "01010001000011100101001001111111", "10011011000001010110100010001100", "00011111100000111101100110101011", "01011011111000001100110100011001" ]; function abc() { var list = [ "428a2f98", "71374491", "b5c0fbcf", "e9b5dba5", "3956c25b", "59f111f1", "923f82a4", "ab1c5ed5", "d807aa98", "12835b01", "243185be", "550c7dc3", "72be5d74", "80deb1fe", "9bdc06a7", "c19bf174", "e49b69c1", "efbe4786", "0fc19dc6", "240ca1cc", "2de92c6f", "4a7484aa", "5cb0a9dc", "76f988da", "983e5152", "a831c66d", "b00327c8", "bf597fc7", "c6e00bf3", "d5a79147", "06ca6351", "14292967", "27b70a85", "2e1b2138", "4d2c6dfc", "53380d13", "650a7354", "766a0abb", "81c2c92e", "92722c85", "a2bfe8a1", "a81a664b", "c24b8b70", "c76c51a3", "d192e819", "d6990624", "f40e3585", "106aa070", "19a4c116", "1e376c08", "2748774c", "34b0bcb5", "391c0cb3", "4ed8aa4a", "5b9cca4f", "682e6ff3", "748f82ee", "78a5636f", "84c87814", "8cc70208", "90befffa", "a4506ceb", "bef9a3f7", "c67178f2" ]; list = ["6a09e667", "bb67ae85", "3c6ef372", "a54ff53a", "510e527f", "9b05688c", "1f83d9ab", "5be0cd19"]; const hex = { "0" : "0000", "1" : "0001", "2" : "0010", "3" : "0011", "4" : "0100", "5" : "0101", "6" : "0110", "7" : "0111", "8" : "1000", "9" : "1001", "a" : "1010", "b" : "1011", "c" : "1100", "d" : "1101", "e" : "1110", "f" : "1111" }; for (var i = 0; i &lt; list.length; i++) { var str = list[i]; var output = ""; for (var j = 0; j &lt; str.length; j++) { output += hex[str[j]]; } console.log(output); } } </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-03T03:57:57.633", "Id": "243296", "Score": "2", "Tags": [ "javascript", "strings", "html", "cryptography", "hashcode" ], "Title": "SHA-256 implementation in JS (core codes)" }
243296
<p>I'm trying to create a node editor "framework" (IDK what to call it, but essentially there is no GUI and should be implemented using these classes), similar to <a href="https://rete.js.org/#/" rel="nofollow noreferrer">rete.js</a>, <a href="https://docs.unrealengine.com/en-US/Engine/Blueprints/index.html" rel="nofollow noreferrer">blueprints</a>(maybe an exception since there are events involved), <a href="https://github.com/Nelarius/imnodes" rel="nofollow noreferrer">imnodes</a>, etc; and am creating a pin class/struct.</p> <p>A pin, in this case, is the small things you actually connect (those circles on the sides of the actual nodes which can be inputs or outputs).</p> <p>I'm using a single header, since almost everything I look into recommends using it for templated classes.</p> <p>I think there are many problems in the code in general, but another thing that has been bugging me is the naming of classes, enums, members, etc., especially the naming of PinType, InputOutputCount (including the members itself), IOCount.</p> <pre class="lang-cpp prettyprint-override"><code>#pragma once #include &lt;string&gt; #include &lt;vector&gt; enum PinType {//Whether or not the pin takes in values from other pins(input) or gives the value to other pins(output). TODO: Name change. INPUT, OUTPUT }; enum InputOutputCount {//How many stuff the pin can take in or give out. TODO: Name change. NOTHING = 0,//Is this redundant? ONE = 1, MULTIPLE = -1 }; struct PinAbstract {//An abstract superclass for the actual Pin class, in order to store it in vectors, since Pin is a templated class. PinType Type; InputOutputCount IOCount = ONE; virtual ~PinAbstract() = 0;//Don't know much about destructors, but this was the only thing that worked for me. }; template &lt;class T&gt; struct Pin : public PinAbstract {//The actual pin class std::string Title = "Title";//The title of the pin T* Value = nullptr;//The value passed or being given. std::vector&lt;Pin&lt;T&gt;*&gt; Connections = {};//The other pins this pin is connected to. NOTE: same template type since two connected pins should be of same type. So a string input only takes in from a string output. }; template &lt;class T&gt; void ConnectPins(Pin&lt;T&gt; *pin1, Pin&lt;T&gt; *pin2) {//NOTE: same template type for the same reason above. if (((pin1-&gt;Type == OUTPUT &amp;&amp; pin2-&gt;Type == INPUT) || (pin1-&gt;Type == INPUT &amp;&amp; pin2-&gt;Type == OUTPUT)) &amp;&amp; ((int)pin1-&gt;IOCount - pin1-&gt;Connections.size() != 0 &amp;&amp; (int)pin2-&gt;IOCount - pin2-&gt;Connections.size() != 0)) { /*Only connect input with output and vice-versa AND make sure that connection doesn't exceed max connections of any one of the pins*/ pin1-&gt;Connections.push_back(pin2); pin2-&gt;Connections.push_back(pin1); } } </code></pre> <p>Any sort of help is greatly appreciated. Including things that are not even code, including naming fixes, general strategies, etc.</p>
[]
[ { "body": "<p>One thing that you should avoid, if possible, is the use of raw pointers, from my point of view you should convert them on shared pointers by default and once your software evolves check if you need a more specific type, such as a unique pointer. On the other hand, if you can not avoid the use of a raw pointer is fine if you have tests that cover that, but as a good practise I would recommend to use shared/unique pointers by default to avoid memory issues and try to stay away of raw pointers as much as you can.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-03T16:33:17.583", "Id": "477606", "Score": "0", "body": "Really sorry for the late reply, I asked this question at late night, with the expectation to receive answers much later. But thanks a lot for the answer. I don't know much about smart pointers, shared pointers, etc., but I will try to learn about it and how to use it, especially since it's considered safer than raw pointers. I will keep the post open for now, for any more possible answers. Thank you nonetheless!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-03T18:52:13.467", "Id": "477631", "Score": "0", "body": "Also, another question, what exactly needs to be a shared pointer? All of the pointers in the code, just the value pointer, or the `Pin<T>*`?" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-03T08:38:10.090", "Id": "243305", "ParentId": "243301", "Score": "1" } }, { "body": "<h1>Input and output count</h1>\n<pre><code>enum InputOutputCount {\n NOTHING = 0, //Is this redundant?\n ONE = 1,\n MULTIPLE = -1\n};\n</code></pre>\n<p>Yes, I think a pin that does not allow anything to connect to it is redundant. This could be replaced with a simple <code>bool</code> that indicates whether multiple connections are allowed or not.</p>\n<p>Note that it doesn't make sense to restrict the number of connections to an output pin, there is nothing ambiguous about that. However, for input pins there is ambiguity: what should you do if there are multiple, different values on the input? Do you pick one, sum them, average them, multiply them? So there it does make sense to restrict the input to just one connection.</p>\n<h1>Make <code>Pin::Value</code> a reference</h1>\n<p>Does it make sense for Value to be a null pointer? After setting the pointer, can the pointer change? If the answer to both of these questions is no, then it is better to make it a reference, like so:</p>\n<pre><code>template &lt;class T&gt;\nstruct Pin: PinAbstract {\n ...\n T &amp;value;\n ...\n};\n</code></pre>\n<p>You should add a constructor that initializes the reference, so that it is not possible to construct a concrete Pin without a correct reference. You can also use this to ensure the title is always set to something useful, like so:</p>\n<pre><code>template &lt;class T&gt;\nstruct Pin: PinAbstract {\n const std::string Title;\n T &amp;value;\n std::vector&lt;Pin&gt; Connections;\n\n Pin(T &amp;value, const std::string &amp;title): Value(value), Title(title) {}\n};\n</code></pre>\n<h1>Return an error if a connection cannot be made</h1>\n<p>Your function <code>ConnectPins()</code> silently ignores errors when trying to connect two incompatible pins together. Consider adding some way of reporting an error. It can be as simple as returning a <code>bool</code> indicating success, or you could <code>throw</code> an <a href=\"https://en.cppreference.com/w/cpp/error/invalid_argument\" rel=\"nofollow noreferrer\">exception</a>. This could then be used by the UI to display an error message.</p>\n<h1>Pass pins by reference to <code>ConnectPins()</code></h1>\n<p>Similar to why you might want to use a reference instead of a pointer for <code>Pin::Value</code>, since you should never pass a NULL pointer to <code>ConnectPins()</code>, it is better to pass them by reference:</p>\n<pre><code>template &lt;class T&gt;\nbool ConnectPins(Pin&lt;T&gt; &amp;pin1, Pin&lt;T&gt; &amp;pin2) {\n if (pin1.Type != pin2.Type)\n return false;\n ...\n\n pin1.Connections.push_back(&amp;pin2);\n pin2.Connections.push_back(&amp;pin1);\n return true;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-28T11:32:01.400", "Id": "256532", "ParentId": "243301", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-03T08:01:19.060", "Id": "243301", "Score": "3", "Tags": [ "c++", "template" ], "Title": "Is this good c++ code for a pin/socket for a node editor?" }
243301
<p>I would like to request iOS developer community to please review my POC i.e. [GithubUserFinder][1] which I have created as part of job screening test at T-mobile Bengaluru.</p> <p>I have around 2 years of experience in programming and I got 24 hours to complete this POC.</p> <p>Below is the feedback I got through mail by recruiter: <strong>As for Pooja, I will say probably no. Their code quality is a bit messy and sparse. They are missing a portion of the assignment and their resume doesn’t look the best, they are missing a year of work.</strong></p> <p>I request them to provide some pointer on 'messy and sparse code' or what is 'missing' in assignment but there was no reply.</p> <p>Kindly request you guys to please go through my POC i.e [GithubUserFinder][1] and provide your valuable comments.</p> <p><strong>Here is the code for User search feature:</strong></p> <h3>1. ViewController (search users)</h3> <pre><code>import UIKit import Alamofire class ViewController: UIViewController { @IBOutlet private weak var tableView: UITableView! @IBOutlet private weak var searchBar: UISearchBar! //datasource private var users: [User] = [] { didSet { tableView.reloadData() } } private enum constants { static let userCellNibName = "UserCell" static let cellReuseIdentifier = "Cell" static let searchUsersPlaceholderText = "Search Users" static let segueIdentifier = "detailSegue" static let placeholderImageName = "placeholder" } //MARK:- View life cycle override func viewDidLoad() { super.viewDidLoad() setupSearchBar() setUpTableView() } override func viewWillAppear(_ animated: Bool) { if let indexPath = tableView.indexPathForSelectedRow { tableView.deselectRow(at: indexPath, animated: true) } } //MARK:- Setup private func setUpTableView() { tableView.register(UINib(nibName: constants.userCellNibName, bundle: nil), forCellReuseIdentifier: constants.cellReuseIdentifier) } private func setupSearchBar() { searchBar.placeholder = constants.searchUsersPlaceholderText } private func searchUsers(for name: String) { ServiceManager.getUsers(for: name) {[weak self] (response) in guard let self = self else { return } guard let response = response as? SearchResponse else { return } self.users = response.users } } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == constants.segueIdentifier { guard let destinationVC = segue.destination as? UserDetailViewController else { return } destinationVC.user = sender as? User } } } //MARK:- TableView datasource extension ViewController: UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -&gt; Int { return users.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -&gt; UITableViewCell { guard let cell: UserCell = tableView.dequeueReusableCell(withIdentifier: constants.cellReuseIdentifier, for: indexPath) as? UserCell else { return UITableViewCell() } let user = users[indexPath.row] cell.populate(user: user) return cell } } extension ViewController: UITableViewDelegate { func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) performSegue(withIdentifier: constants.segueIdentifier, sender: users[indexPath.row]); } } //MARK:- SearchResultBar delegate extension ViewController: UISearchBarDelegate { func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) { if let text = searchBar.text, !text.isEmpty { searchUsers(for: text) } else { users = [] } } func searchBarSearchButtonClicked(_ searchBar: UISearchBar) { searchBar.endEditing(true) } } </code></pre> <h3>2. TableView Cell (UserCell.swift)</h3> <pre><code>import UIKit import AlamofireImage class UserCell: UITableViewCell { @IBOutlet private weak var userImageView: UIImageView! @IBOutlet private weak var nameLabel: UILabel! @IBOutlet private weak var repoLable: UILabel! private enum constants { static let placeholderImageName = "placeholder" } func populate(user: User) { nameLabel.text = user.login let placeholderImage = UIImage(named: constants.placeholderImageName) if let imageUrl = URL(string: user.avatarUrl) { userImageView.af.setImage(withURL: imageUrl, cacheKey: "\(AppConstants.kCacheImagekey)\(user.id)", placeholderImage: placeholderImage); } } } </code></pre> <h3>3. Service Manager (ServiceManager.swift)</h3> <pre><code>import Foundation import Alamofire enum ServiceType { case users case details case repos } class ServiceManager { typealias CompletionHandler = (_ response:Any?) -&gt; Void private static let baseUrl = "https://api.github.com/" // Add your client Id and client secret here.. private static let clientId = "" private static let clientSecret = "" private static func getMethod(type: ServiceType) -&gt; String { switch type { case .users: return "search/users?q=" case .details, .repos: return "users/" } } private static func clientIdSecret() -&gt; String { //Add your client Id and client secret if you hit max hour limit which is only // 50-60 request per hour. And enable this. //return "&amp;client_id=\(ServiceManager.clientId)&amp;client_secret=\(ServiceManager.clinetSecret)" return "" } public static func getUsers(for query: String, completion: @escaping CompletionHandler) { let url = baseUrl + getMethod(type: .users) + query + clientIdSecret() AF.request(url, parameters: nil).validate() .responseDecodable(of: SearchResponse.self) { response in guard let result = response.value else { //TODO:- Currently the errors are not handled. return } completion(result) } } public static func getDetails(for query: String, completion: @escaping CompletionHandler) { let url = baseUrl + getMethod(type: .details) + query AF.request(url, parameters: nil).validate() .responseDecodable(of: UserDetails.self) { response in guard let result = response.value else { return } completion(result) } } public static func getRepos(for query: String, completion: @escaping CompletionHandler) { let url = baseUrl + getMethod(type: .repos) + query + "/repos" AF.request(url, parameters: nil).validate() .responseDecodable(of: [Repo].self) { response in guard let result = response.value else { return } completion(result) } } } </code></pre> <h3>4. Model (Users.swift)</h3> <pre><code>import Foundation struct SearchResponse: Decodable { let users: [User] enum CodingKeys: String, CodingKey { case users = "items" } } struct User: Decodable { let login: String let id: Int let avatarUrl: String let url: String let reposUrl: String enum CodingKeys: String, CodingKey { case login = "login" case id = "id" case avatarUrl = "avatar_url" case url = "url" case reposUrl = "repos_url" } } [1]: https://github.com/pooja-iosTech13/GithubUserFinder </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-05T01:48:03.733", "Id": "477876", "Score": "1", "body": "This code doesn't look messy at all, though there are some chances of improvement but considering your experience it looks good to me. Keep it up." } ]
[ { "body": "<p>I cannot review all aspects of your code, but here are some remarks which might be helpful.</p>\n\n<h3>JSON decoding</h3>\n\n<p>In the definition of <code>User.CodingKeys</code> one can omit the raw values of keys which are equal to the case name:</p>\n\n<pre><code>struct User: Decodable {\n let login: String \n let id: Int\n let avatarUrl: String\n let url: String\n let reposUrl: String\n\n enum CodingKeys: String, CodingKey {\n case login // Instead of: case login = \"login\" ...\n case id\n case avatarUrl = \"avatar_url\"\n case url\n case reposUrl = \"repos_url\"\n }\n}\n</code></pre>\n\n<p>And the conversion from “snake-case” (in the JSON API) to “camel-case” (in the Swift API) can be done by setting a <code>keyDecodingStrategy</code> on the <code>JSONDecoder</code> in <code>getUsers()</code>:</p>\n\n<pre><code>let decoder = JSONDecoder()\ndecoder.keyDecodingStrategy = .convertFromSnakeCase\nAF.request(url, parameters: nil).validate()\n .responseDecodable(of: SearchResponse.self, decoder: decoder) { response in\n // ...\n}\n</code></pre>\n\n<p>which makes the <code>User.CodingKeys</code> obsolete:</p>\n\n<pre><code>struct User: Decodable {\n let login: String\n let id: Int\n let avatarUrl: String\n let url: String\n let reposUrl: String\n}\n</code></pre>\n\n<h3>Unnecessary conversions to/from <code>Any</code></h3>\n\n<p>The functions in <code>ServiceManager</code> all take a callback argument of type <code>(_ response:Any?) -&gt; Void</code>. The (correctly typed) response from AlamoFile is therefore cast to <code>Any?</code>, and then cast back to the correct type in the caller of that function.</p>\n\n<p>It becomes simpler with a callback that takes the proper type, e.g. in <code>getUsers()</code>:</p>\n\n<pre><code>public static func getUsers(for query: String, completion: @escaping (SearchResponse) -&gt; Void) {\n // ...\n AF.request(url, parameters: nil).validate()\n .responseDecodable(of: SearchResponse.self, decoder: decoder) { response in\n guard let result = response.value else { ... }\n completion(result)\n }\n}\n</code></pre>\n\n<p>which allows to get rid of the conditional case in the calling function <code>searchUsers()</code>:</p>\n\n<pre><code>ServiceManager.getUsers(for: name) {[weak self] (response) in\n guard let self = self else { return }\n // guard let response = response as? SearchResponse else { return }\n // ^-- No longer needed.\n self.users = response.users\n print(\"RESPONSE\", name, response.users.count)\n}\n</code></pre>\n\n<h3>Handle rate limits and paginated responses</h3>\n\n<p>Of course the first thing I did was to download your code and compile the app. That worked flawlessly, it compiled without warnings. Great!</p>\n\n<p>Then I ran the app in the iOS Simulator. At first it seemed to work correctly, but then I typed my GitHub user name into the search field: No result – what is that? OK, delete the search field and try again: Now the tableview wasn't updated at all. Nothing seemed to happen anymore.</p>\n\n<p>To isolate the problem, I added a </p>\n\n<pre><code>print(\"ERROR\", response.error)\n</code></pre>\n\n<p>in the failure part of <code>getUsers()</code>. This revealed that after some time, the GitHub API responded with an HTTP error 403. And indeed, the <a href=\"https://developer.github.com/v3/search/\" rel=\"nofollow noreferrer\">GitHub Search API documentation</a> states that search requests are limited to 30 requests per minute, and even to 10 requests per minute for unauthenticated users.</p>\n\n<p>There is not much one can do about this limit, but a small remedy might be a “delayed search”: If the users type \"ABCD\" then there is no need to search for \"A\", then for \"AB\", \"ABC\", and finally for \"ABCD\". If you start a short timer after each modification to the search text, and start the actual search only if the search text is not modified for some time then the number of search requests is already reduces.</p>\n\n<p>You could also <em>cache</em> search results in order to submit fewer requests.</p>\n\n<p>Also GitHub responses are <a href=\"https://developer.github.com/v3/#pagination\" rel=\"nofollow noreferrer\">paginated</a> to 30 items by default. This can be increased to 100 at most, but even then you'll normally not get all items with a single request.</p>\n\n<p>The <a href=\"https://developer.github.com/v3/#link-header\" rel=\"nofollow noreferrer\">link header</a> in the search response contains the necessary information. You can use that to either</p>\n\n<ul>\n<li>issue more request for the remaining items. Perhaps only when the user actually scrolls to the end of the current list, again in order to limit the number of requests.</li>\n<li>or just display “More ...” at the end of the list, so that the user knows that there are more items than are currently displayed.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-07T07:39:07.797", "Id": "477946", "Score": "0", "body": "Thanks Martin. \nFor the rate limit issue one needs to add \n// Add your client Id and client secret here.. \nprivate static let clientId = \"\" \nprivate static let clientSecret = \"\"\n\nCan you add your comment on the Feedback which I have got on this code from recruiter? \n*** As for Pooja, I will say probably no. Their code quality is a bit messy and sparse. They are missing a portion of the assignment and their resume doesn’t look the best, they are missing a year of work.***" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-07T08:37:17.260", "Id": "477950", "Score": "0", "body": "@PoojaSingh: Even as authenticated user the rate of search requests is limited, therefore I suggested to reduce the number of requests, if possible. It is up to you to decide which feedback you want to incorporate in your code. – Your code does not look “messy” to me (that is a pretty vague feedback anyway). I cannot comment on the other parts because I did not set the assignment and do not know your resume. I have said everything about your code that I wanted to say." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-05T19:57:31.713", "Id": "243443", "ParentId": "243304", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-03T08:32:20.960", "Id": "243304", "Score": "4", "Tags": [ "swift", "ios" ], "Title": "POC for GithubUserFinder" }
243304
<blockquote> <p>Develop a smart application as Student Grade Calculator(SGC).</p> <p>Create a class Student with following private attribute :</p> <p><code>int id</code>, <code>String name</code>, <code>marks</code>(integer array), <code>float average</code> and <code>char grade</code>. Include appropriate getters and setters methods and constructor.</p> <p><code>public void calculateAvg()</code> - This method should calculate average and set average mark for the current student.</p> <p>public void findGrade()- This method should set the grade based on the average calculated. If the average is between 80 and 100 then, then return grade as 'O', else 'A' .If the student gets less than 50 in any of the subjects then return grade as 'F'. Using appropriate setter method set the grade to the student.</p> <p>(Note : number of subject should be greater than zero, if not display as 'Invalid number of subject' and get number of subject again, Assume mark for a subject should be in the range 0 - 100. If not display a message "Invalid Mark" and get the mark again)</p> <p>Write a class StudentMain and write the main method.</p> <p>In this class, write a method</p> <p><code>public static Student getStudentDetails()</code> - this method should get the input from the user for a student, create a student object with those details and return that object.</p> <p>In main create student’s object by invoking the getStudentDetails method. Also calculate average and grade for that student object using appropriate methods.</p> <p>SGC app should get the input and display the output as specified in the snapshot:</p> <pre><code>Sample Input 1: Enter the id: 123 Enter the name: Tom Enter the no of subjects: 3 Enter mark for subject 1: 95 Enter mark for subject 2: 80 Enter mark for subject 3: 75 Sample Output 1: Id:123 Name:Tom Average:83.33 Grade:O Sample Input 2: Enter the id: 123 Enter the name: Tom Enter the no of subjects: 0 Invalid number of subject Enter the no of subjects: 3 Enter mark for subject 1: 75 Enter mark for subject 2: 49 Enter mark for subject 3: 90 Sample Output 2: Id:123 Name:Tom Average:71.33 Grade:F </code></pre> </blockquote> <hr> <pre><code>public class Student{ private int id; private String name; private Integer[] marks; private float average; private char grade; public Student(int id, String name, Integer[] marks){ this.id=id; this.name=name; this.marks=marks; } public void setId(int id){ this.id=id; } public int getId(){ return id; } public void setName(String name){ this.name=name; } public String getName(){ return name; } public Integer[] setMarks(Integer[] marks){ return this.marks = getMarks(); } public Integer[] getMarks(){ return marks; } public void setAverage(float average){ this.average=average; } public float getAverage(){ return average; } public void setGrade(char grade){ this.grade=grade; } public char getGrade(){ return grade; } public void calculateAvg(){ StudentMain sm = new StudentMain (); int sum=0; //int no=0; for(int i=0;i&lt;marks.length;i++){ sum+=marks[i]; } float avg=sum/sm.n; //System.out.println(sum); setAverage(avg); } public void findGrade(){ float avg=getAverage(); if (avg&gt;+80 &amp;&amp; avg&lt;+100){ setGrade('O'); } else if (avg&gt;=50 &amp;&amp; avg&lt;80){ setGrade('A'); } else { setGrade('F'); } } } </code></pre> <pre><code>import java.util.*; import java.io.*; public class StudentMain{ static Scanner sc = new Scanner(System.in); static int n; static List&lt;Integer&gt; al = new ArrayList&lt;Integer&gt;(); public static Student getStudentDetails(){ System.out.println("Enter the id:"); int id=sc.nextInt(); System.out.println("Enter name:"); String name=sc.next(); System.out.println("Enter the no of subjects"); n = sc.nextInt(); if (n&lt;=0){ System.out.println("Invalid number of subjects"); System.out.println("Enter the number of subjects"); n=sc.nextInt(); } //List&lt;Integer&gt; al = new ArrayList&lt;Integer&gt;(); for (int i=0; i&lt;n;i++){ int t=i+1; System.out.println("Enter mark for subject" +t); int m =sc.nextInt(); //List&lt;Integer&gt; al = new ArrayList&lt;Integer&gt;(); //System.out.println(m); al.add(m); } Integer[] marks = new Integer[al.size()]; for (int i =0; i&lt;al.size(); i++){ marks[i] = al.get(i); } for (Integer x : marks){ //return marks; } //int [] marks = null; Student s = new Student(id,name,marks); return s; } public static void main (String[] args) { Student s2 = getStudentDetails(); System.out.println("Id:" + s2.getId()); System.out.println("Name:" + s2.getName()); s2.calculateAvg(); System.out.println("Average:"+s2.getAverage()); s2.findGrade(); System.out.println("Grade:"+s2.getGrade()); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-04T07:32:16.490", "Id": "477684", "Score": "1", "body": "Why is this question being downvoted and flagged to be closed? I see nothing wrong with it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-04T13:22:35.507", "Id": "477698", "Score": "0", "body": "It appears that the poster has included the full specification that they received for the problem, what is unclear to those that down voted or VTC?" } ]
[ { "body": "<p>First off, I must say the task as written is not very good. It encourages some bad practices, mostly requiring separate <code>calculateAvg()</code> and <code>findGrade()</code> methods. Instead this functionality should be integrated in <code>getAverage()</code> and <code>getGrade()</code>.</p>\n\n<h1>Class <code>StudentMain</code></h1>\n\n<p>All three static fields are unnecessary. They are only used/needed inside the method <code>getStudentDetails()</code> so they should be local variables inside that method. And the case of the field <code>n</code> is especially bad, since it is accessed later on in a way that never should be used (more on that later).</p>\n\n<p>Furthermore the names are bad. Don't unnecessarily abbreviate them and do call them after what they hold, not what they are. <code>sc</code> should be called <code>scanner</code> and <code>al</code> should be called <code>marks</code>.</p>\n\n<h2>Method <code>getStudentDetails()</code></h2>\n\n<p>Don't leave in commented out code lines and remove the <code>for</code> loop that doesn't do anything. </p>\n\n<p>You are missing the part of the task requiring you check that the marks are between 0 and 100.</p>\n\n<p>There is no need to manually copy the contents of the <code>ArrayList</code> to an array. For one <code>List</code>s have a method <a href=\"https://docs.oracle.com/javase/8/docs/api/java/util/List.html#toArray-T:A-\" rel=\"nofollow noreferrer\"><code>toArray()</code></a> to do that for you (although it is a bit awkward to use due to limitations of the Java language).</p>\n\n<p>But more importantly, since know the number of elements ahead of time, it would be sensible to store the marks directly in an array:</p>\n\n<pre><code>Integer[] marks = new Integer[n];\n\nfor (int i = 0; i &lt; n; i++) { // It is convention to use spaced around operators\n int subjectNr = i + 1; // Use readable variable names, not random single letters\n System.out.println(\"Enter mark for subject \" + subjectNr);\n int mark = sc.nextInt();\n marks[i] = mark;\n}\n</code></pre>\n\n<h1>class <code>Student</code></h1>\n\n<p>Another of the weaknesses of this task is requirement to add \"appropriate\" setters. I'd argue that it's appropriate to have no setters at all, since they are not needed.</p>\n\n<h2>Method <code>calculateAvg()</code></h2>\n\n<p>This method contains the biggest flaw in your code. This class should never access the field <code>n</code> from <code>StudentMain</code> for many reasons:</p>\n\n<ul>\n<li>The class <code>Student</code> has no business even to know about <code>StudentMain</code>. A method in <code>Student</code> should only access its parameters and members (fields and methods) of <code>Student</code>.</li>\n<li>Since <code>n</code> is static there only one value, but if you had more than one <code>Student</code> there is a good chance, that the value <code>n</code> contains the information from a different <code>Student</code> than the one you are currently calculating the average of.</li>\n<li><code>StudentMain</code> only contains static members, so creating a new instance with <code>new</code> is generally pointless. Actually your IDE/compiler should be warning you about accessing the static field <code>n</code> via an instance. Especially as a beginner you should consider warnings errors.</li>\n<li>You don't even need to get the number of marks from <code>StudentMain</code>. <code>marks.length</code> contains the same information.</li>\n</ul>\n\n<h2>Method <code>findGrade()</code></h2>\n\n<p>You have some errors in here. </p>\n\n<ul>\n<li>Averages of exactly 80 or 100 will return an 'F'.</li>\n<li>The task asks you return an 'F' if the student has less than 50 in any subject, not less than 50 in average.</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-04T08:53:57.720", "Id": "243368", "ParentId": "243309", "Score": "7" } }, { "body": "<pre class=\"lang-java prettyprint-override\"><code> private Integer[] marks;\n</code></pre>\n\n<p><a href=\"https://docs.oracle.com/javase/tutorial/java/data/autoboxing.html\" rel=\"nofollow noreferrer\">There's a difference between int and Integer</a>, be aware of it.</p>\n\n<hr>\n\n<pre class=\"lang-java prettyprint-override\"><code>private char grade;\n</code></pre>\n\n<p>For better clarity, you want to use an <code>enum</code>:</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>public enum Grade {\n O,\n A,\n B,\n C,\n D,\n E,\n F\n}\n</code></pre>\n\n<p>You could even assign it ranges, which would make it easy to fetch one:</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>public enum Grade {\n O(80, 100),\n A(50, 80),\n F(0, 50);\n\n private int lowerBound;\n private int upperBound;\n\n private Grade(int lowerBound, int upperBound) {\n this.lowerBound = lowerBound;\n this.upperBound = upperBound;\n }\n\n public static final Grade getGrade(float gradeAverage) {\n for (Grade grade : values()) {\n if (grade.lowerBound &gt;= gradeAverage &amp;&amp; grade.upperBound &lt;= gradeAverage) {\n return grade;\n }\n }\n\n return null; // IllegalStateException?\n }\n}\n</code></pre>\n\n<hr>\n\n<pre class=\"lang-java prettyprint-override\"><code>public Integer[] setMarks(Integer[] marks){\n return this.marks = getMarks();\n}\n</code></pre>\n\n<p>That's an odd pattern I haven't seen before, the traditional pattern is to return nothing. But [the fluent pattern](<a href=\"https://en.wikipedia.org/wiki/Fluent_interface#Java0\" rel=\"nofollow noreferrer\">https://en.wikipedia.org/wiki/Fluent_interface#Java0</a> is also very nice:</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>public Student setMarks(Integer[] marks){\n this.marks = marks;\n\n return this;\n}\n</code></pre>\n\n<hr>\n\n<pre class=\"lang-java prettyprint-override\"><code>return this.marks = getMarks();\n</code></pre>\n\n<p>That's a nice typo.</p>\n\n<hr>\n\n<pre class=\"lang-java prettyprint-override\"><code>public void calculateAvg(){\n StudentMain sm = new StudentMain ();\n int sum=0;\n //int no=0;\n for(int i=0;i&lt;marks.length;i++){\n sum+=marks[i];\n }\n float avg=sum/sm.n;\n //System.out.println(sum);\n setAverage(avg);\n}\n</code></pre>\n\n<p>Now that's an odd one, and an error I believe. You don't want to create a new instance of <code>StudentMain</code> here, you want to pass the values you need.</p>\n\n<hr>\n\n<pre class=\"lang-java prettyprint-override\"><code>float avg=sum/sm.n;\n</code></pre>\n\n<p>That's a bug, dividing and <code>int</code> by an <code>int</code> will yield an <code>int</code>, not a <code>float</code>:</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>float result = 5/2; // == 2 int\nfloat result = 5/(float)2; // == 2.5 float\n</code></pre>\n\n<hr>\n\n<pre class=\"lang-java prettyprint-override\"><code>if (avg&gt;+80 &amp;&amp; avg&lt;+100){\n setGrade('O');\n} \nelse if (avg&gt;=50 &amp;&amp; avg&lt;80){\n setGrade('A');\n}\nelse {\n setGrade('F');\n}\n</code></pre>\n\n<p>That's another bug, a student with a perfect 100 (though, unlikely because of <code>float</code>), will get an <code>F</code>.</p>\n\n<p>Also, the leading \"+\" is unconventional.</p>\n\n<hr>\n\n<pre class=\"lang-java prettyprint-override\"><code>static Scanner sc = new Scanner(System.in);\nstatic int n;\nstatic List&lt;Integer&gt; al = new ArrayList&lt;Integer&gt;();\n</code></pre>\n\n<p>Stop shorting your (variable) names, you're gaining <strong><em>nothing</em></strong> from it, the code is only harder to read because of it.</p>\n\n<hr>\n\n<p>Also, keep your code clean, use git or mercurial and commit your code and then remove what you don't need anymore.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-04T20:52:59.190", "Id": "477738", "Score": "0", "body": "Why would a perfect 100 be \"unlikely because of `float`\"? I very much doubt that. Java guarantees that `300.0 / 3.0 == 100.0`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-05T18:17:17.177", "Id": "477820", "Score": "0", "body": "@RolandIllig My point, the test is for `value < 100`, so if somebody does a perfect score, they will get an \"F\"." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-06T22:15:47.303", "Id": "477923", "Score": "0", "body": "And what does this have to do with `float`?" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-04T17:31:15.100", "Id": "243387", "ParentId": "243309", "Score": "1" } }, { "body": "<p>Some Basic things i would like to mention here</p>\n\n<p><strong>1. Why did you use Wrapper class Integer</strong>\nwhen you had to create array of integer you have option of int[] or Integer[],\nfor using wrapper classes you should have reasons to use it, please read the use cases of wrapper class</p>\n\n<p><strong>2. Variable names</strong>\nAlways give your variable meaningful name, because it is not just about writing the code but also the maintainability and readability of code.</p>\n\n<p><strong>3. Your calculateAvg() method</strong>\nWhy are you accessing main class here, you have array to get the size(which is equal to the number of subject)</p>\n\n<p><strong>4. While taking input subject marks</strong>\nDirectly use int[] not list, that way you need not do the conversation from list to array.</p>\n\n<p><strong>5. enum for the grade</strong>\nyou can use enum for the grade that way you will not have constants in your code base.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-06T22:17:53.693", "Id": "477924", "Score": "0", "body": "This answer is not useful for a beginner because it is way too abstract. For a beginner, it is important to get clear advice at what to do exactly, not just a high level overview." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-07T01:44:09.430", "Id": "477937", "Score": "0", "body": "I am not talking about some random java concept i have picked these points from his code only, and moreover these are not java advanced topic too." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-07T06:35:20.420", "Id": "477944", "Score": "0", "body": "A beginner typically does not know how to \"use enum\", and the \"use cases of wrapper class\" is an advanced concept. A few links to useful tutorials would be helpful. Especially \"maintainability and readability\" are not known yet to the OP, otherwise the code would look completely different. It's as if I would tell you \"add more quality to your answer\"." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-05T04:06:28.537", "Id": "243406", "ParentId": "243309", "Score": "-1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-03T10:01:51.130", "Id": "243309", "Score": "4", "Tags": [ "java", "homework" ], "Title": "Student Grade Calculation" }
243309
<p>This code gets detailed information about a particular game from an online database using an API Get request. The question I have doesn't pertain to the request but is more about the code itself. The code works. I just think it is long for what needs to be done though. I was wondering if this code is able to be refactored because there are a few places the code just looks the same. I have been trying for last couple of days to get this done with no avail. Any help will be appreciated.</p> <pre><code>def self.get_game_details(game_selection) if Game.all[game_selection.to_i - 1].description == nil response = RestClient.get("#{DETAIL_URL}#{Game.all[game_selection.to_i - 1].slug}", headers = {"x-rapidapi-host" =&gt; ENV["HOST"], "x-rapidapi-key" =&gt; ENV["API_KEY"]}) data = JSON.parse(response.body) Game.all[game_selection.to_i - 1].description = data["description"] Game.all[game_selection.to_i - 1].released = data["released"] Game.all[game_selection.to_i - 1].metacritic_rating = data["metacritic"] unless data["metacritic"] == nil # default to 0 if no data data["ratings"].each do |rating| case rating["title"] when "recommended" Game.all[game_selection.to_i - 1].recommended_rating = rating["percent"] unless rating["percent"] == nil # # default to 0.0 if no data when "exceptional" Game.all[game_selection.to_i - 1].exceptional_rating = rating["percent"] unless rating["percent"] == nil # # default to 0.0 if no data when "meh" Game.all[game_selection.to_i - 1].meh_rating = rating["percent"] unless rating["percent"] == nil # # default to 0.0 if no data when "skip" Game.all[game_selection.to_i - 1].skip_rating = rating["percent"] unless rating["percent"] == nil # # default to 0.0 if no data end end end end </code></pre>
[]
[ { "body": "<p>My approach to your code:</p>\n\n<pre><code># If this data isn't going to change, using constants would be good enough\nHEADERS = { 'x-rapidapi-host' =&gt; ENV['HOST'],\n 'x-rapidapi-key' =&gt; ENV['API_KEY'] }.freeze\n\ndef self.get_game_details(game_selection)\n # If Game is an ActiveRecord class, probably you should modify this to look\n # for the specific record instead of loading everything with .all\n # If is just a PORO, forget what I said.\n game = Game.all[game_selection.to_i - 1]\n return if game.description.present?\n\n response = RestClient.get(\"#{DETAIL_URL}#{slug}\", HEADERS)\n data = JSON.parse(response.body)\n game.details = data\nend\n\nclass Game\n ALLOWED_RATINGS = %w[recommended exceptional meh skip].freeze\n\n # Moved most of the assigning logic into the Game class. This is debatible as\n # I could use a Service class or another pattern for this, but as I don't\n # know your code's nature, to me looks like the quickest way.\n def details=(data)\n self.description = data['description']\n self.released = data['released']\n # .presence will return nil for blank strings, empty arrays, etc, then with\n # || you will default the value to 0, as:\n #\n # nil || 0 # =&gt; 0\n self.metacritic_rating = data['metacritic'].presence || 0\n\n data['ratings'].each { |rating| self.rating = rating }\n end\n\n def rating=(rating)\n # .send method can run any method of this class, so better to check if the\n # value is valid first\n return unless ALLOWED_RATINGS.include? rating['title']\n\n send(\"#{rating['title']}_rating=\", rating['percent'].presence || 0.0)\n end\nend\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-04T04:55:05.180", "Id": "243359", "ParentId": "243310", "Score": "0" } }, { "body": "<p>As there is already an answer which is a good starting point, I just wanted to point out some flaws in your code which might help to improve it.</p>\n\n<h2>Use instances instead of class methods</h2>\n\n<p>I assume you want to do something like this <code>Game.get_game_details</code> which makes sense. However, maybe you should wrap the code in the class method in an instance to leverage local state and make it more readable. Here is an example:</p>\n\n<pre class=\"lang-rb prettyprint-override\"><code>def self.get_game_details(game_selection)\n Game.new(RemoteGame.new(game_selection.to_i - 1).to_h)\nend\n\nclass RemoteGame\n HEADERS = { \"x-rapidapi-host\" =&gt; ENV[\"HOST\"], \"x-rapidapi-key\" =&gt; ENV[\"API_KEY\"]\n}.freeze\n\n def initialize(id)\n @id = id\n end\n\n def to_h\n JSON.parse(response.body)\n end\n\n private\n\n attr_reader :id\n\n def response\n RestClient.get(\"#{DETAIL_URL}#{game.slug}\", headers)\n end\n\n def game\n @_game ||= Game.all[id].slug\n end\nend\n</code></pre>\n\n<h2>Naming</h2>\n\n<p>Disclaimer: These are just assumptions!</p>\n\n<p>If the <code>get_game_details</code> is on <code>Game</code> you should consider remove <code>game_details</code> as it's already implicit in the class name. Better might be <code>Game.find</code>.</p>\n\n<p>The method parameter <code>game_selection</code> looks more like an <code>id</code> or <code>slug</code>, you should consider renaming it to reflect the name.</p>\n\n<h2>Data structure to store local Games</h2>\n\n<p>You always need to subtract <code>-1</code> from the <code>id</code> so it seems like your local data structure has a different index than your remote data structure. Consider bringing them in sync. One assumption is that you use an array locally which is 0 indexed. \nMaybe you should use a key / value store instead (Hash).</p>\n\n<pre class=\"lang-rb prettyprint-override\"><code>class Game\n @local_repository = {}\n\n class &lt;&lt; self\n attr_accessor :local_repository\n\n def all\n local_repository\n end\n\n def find(id)\n local_repository[id]\n end\n end\nend\n\ngame = Game.new(id: 1, name: \"Name\")\nGame.all[game.id] = game\nGame.find(1)\n</code></pre>\n\n<h1>Rating associations</h1>\n\n<p>As your remote data structure already indicates, a <code>Game</code> has many <code>Ratings</code>. You should reflect that with a composition in your architecture. </p>\n\n<pre class=\"lang-rb prettyprint-override\"><code>class Rating\n attr_reader :name, :percentage\n\n def initialize(name, percentage)\n @name = name\n @percentage = percentage\n end\nend\n\nclass Game\n def ratings\n @_ratings ||= []\n end\nend\n\ngame = Game.new\ngame.ratings &lt;&lt; Rating.new(\"Recommended\", 50)\n</code></pre>\n\n<p>Another indicator that a class is missing here is that you have the same pre / suffix for several methods:</p>\n\n<ul>\n<li>recommended_rating</li>\n<li>exceptional_rating</li>\n<li>meh_rating</li>\n<li>skip_rating</li>\n</ul>\n\n<p>These methods all have the <code>_rating</code> suffix so we should extract a <code>Rating</code> class. This also gives us the flexibility to add another rating in the future very easily. Instead of adding another method to <code>Game</code>, we only need to create a new instance of <code>Rating</code> (<a href=\"https://en.wikipedia.org/wiki/Open%E2%80%93closed_principle\" rel=\"nofollow noreferrer\">https://en.wikipedia.org/wiki/Open%E2%80%93closed_principle</a>). </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-08T10:14:29.927", "Id": "243551", "ParentId": "243310", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-03T10:05:52.327", "Id": "243310", "Score": "1", "Tags": [ "ruby" ], "Title": "API Get Request to pull data from an online database" }
243310
<p>I have tried to check whether the ports of a host from port 0 to port 1023 is open or not. Could someone please review this code and provide feedback.</p> <pre><code>#include&lt;stdio.h&gt; #include&lt;stdlib.h&gt; #include&lt;string.h&gt; #include&lt;sys/socket.h&gt; #include&lt;sys/types.h&gt; #include&lt;netdb.h&gt; #include&lt;error.h&gt; #include&lt;errno.h&gt; char *convert_int_to_string(int num); char *convert_int_to_string(int num) { int tmp; int i = 0; int j = 0; static char a[5] = {'0'}; while (num &gt; 0) { tmp = num % 10; a[i++] = tmp + '0'; num = num / 10; } a[i] = '\0'; for (j = 0; j &lt; i / 2; j++) { tmp = a[j]; a[j] = a[i - j - 1]; a[i - j - 1] = tmp; } return a; } int main(int argc, char **argv) { int status; char *node; char *port_no; int sock_fd; int i = 0; struct addrinfo hints, *serviceinfo; if (argc != 2) error(1, errno, "Too many or few arguments\n"); node = argv[1]; memset(&amp;hints, 0, sizeof hints); hints.ai_family = AF_INET; hints.ai_socktype = SOCK_STREAM; for (i = 0; i &lt; 1024; i++) { port_no = convert_int_to_string(i); status = getaddrinfo(node, port_no, &amp;hints, &amp;serviceinfo); if (status != 0) { error(1, errno, "error in getaddrinfo() function call\n"); } sock_fd = socket(serviceinfo-&gt;ai_family, serviceinfo-&gt;ai_socktype, serviceinfo-&gt;ai_protocol); if (sock_fd == -1) error(1, errno, "error in socket() function call\n"); status = connect(sock_fd, serviceinfo-&gt;ai_addr, serviceinfo-&gt;ai_addrlen); if (status != -1) printf("Port : %s is open\n", port_no); else printf("Port : %s is closed\n", port_no); } } </code></pre>
[]
[ { "body": "<ol>\n<li>Use getaddrinfo only once, to resolve the host. Do the port number iteration directly yourself. While it might be more complicated, it also doesn't call for repeated hostname resolutions. This also allows you to eliminate <code>convert_int_to_string()</code></li>\n<li>If you don't want IPv4 <strong>and</strong> IPv6 (which seems to be indicated by specifying AF_INET, you might be better off using the older functions. This eliminates the complexity noted before.</li>\n<li>As the last step in the loop, you <strong>MUST</strong> <code>close</code> the socket. Otherwise, you will wind up with 1027 open descriptors. Since current linux systems have a limit of 1024 open descriptors, your program will terminate early without this. Other OSes will have similar limits. Since you only ever need 4 open descriptors (or maybe 5 depending on getaddrinfo()), you should do the cleanup.</li>\n<li>I suggest localizing variables where possible.</li>\n<li>In convert_int_to_string(), if you start at the end of the buffer and work backwards, you can return the point in the buffer that you have reached instead of reversing the text. Alternatively, <code>snprintf(a, sizeof(a), \"%d\", num);</code> works well.</li>\n<li>Passing <code>errno</code> to <code>error()</code> is a mistake if <code>errno</code> isn't set. This includes the wrong number of arguments error (no number) and the call to <code>getaddrinfo()</code> (which returns an error number and has its own function to make it a string).</li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-03T11:19:53.570", "Id": "243316", "ParentId": "243311", "Score": "7" } }, { "body": "<p>Here are some things that may help you improve your program.</p>\n\n<h2>Use only required <code>#include</code>s</h2>\n\n<p>The code uses nothing from <code>&lt;stdlib.h&gt;</code>, so that header can and should be omitted. Only include files that are actually needed. This makes the code easier to understand and maintain and also may slightly speed up compiling.</p>\n\n<h2>Try to write portable code</h2>\n\n<p>Things that are guaranteed by the C standard are absolutely portable to conforming compilers on all platforms. Things that are specified by POSIX standards are portable to the subset of machines that conform to POSIX. Your life will be easier if you aim for those. Things that are compiler extensions, such as <code>error</code> are not necessarily portable to other machines. For that reason, I'd suggest that instead of using <code>error</code> in this program (which is a GNU extension), you could use <code>printf</code> and <code>return</code> or <code>exit</code>. For example, instead of this:</p>\n\n<pre><code>if (argc != 2)\n error(1, errno, \"Too many or few arguments\\n\");\n</code></pre>\n\n<p>Write this:</p>\n\n<pre><code>if (argc != 2) {\n printf(\"Incorrect number of arguments.\\n\"\n \"Usage: %s node\\n\"\n \"where node is the IPv4 address of a machine to be scanned.\\n\", argv[0]);\n return 1;\n}\n</code></pre>\n\n<h2>Think about the user</h2>\n\n<p>In the code above giving the user an error message saying \"Too many or few arguments\" is likely to be a frustrating experience for the user. You say what's wrong from the <em>program's</em> point of view, but don't say what to do differently from the <em>user's</em> point of view. The suggested text above does both.</p>\n\n<h2>Use standard library functions</h2>\n\n<p>The <code>convert_int_to_string</code> has a bug (it returns a null string if the passed number is zero) and isn't really needed anyway. You could either use <code>snprintf</code> or write a function to increment a text version of the port.</p>\n\n<h2>Understand library calls</h2>\n\n<p>The <code>getaddrinfo</code> call returns a linked list in <code>serviceinfo</code> but this program never frees that memory. You should instead call <code>freeaddrinfo(serviceinfo);</code> and both should be <em>outside</em> the loop. You may also consider trying each of the items in that linked list; it's common, for instance that <code>localhost</code> resolves to both <code>::1</code> and <code>127.0.0.1</code> and also common for ports to be open on only IPv6 or only IPv4.</p>\n\n<h2>Don't use up resources</h2>\n\n<p>The number of simultaneously open file handles is typically set per system. If you're running Linux, you can use the <code>ulimit -n</code> command to find out how many are available on your system. A typical value is 1024, but remember that <code>stdin</code>, <code>stdout</code> and <code>stderr</code> are 3 of those. Any other open files also subtract from that. This means that it's easy to run out of them unless you close handles as soon as you are finished with them. In this case, it means that every call to <code>socket</code> must be paired with a corresponding <code>close(sock_fd);</code> or you are likely to run out of handles. Generally: free memory you allocate and close file descriptors you open.</p>\n\n<h2>Don't forget about IPv6</h2>\n\n<p>There doesn't seem to be a good reason to restrict this code to IPv4 only when it could work just as well with IPv6. To accommodate either, simply delete the line that sets <code>hints.ai_family</code>.</p>\n\n<h2>Understand real world consequences</h2>\n\n<p>Running a port scan should only be done on computers that are yours or on computers for which you have permission to do so. Smart security professionals get such permission <em>in writing</em> before commencing. See <a href=\"https://www.sans.org/reading-room/whitepapers/legal/ethics-legality-port-scanning-71\" rel=\"nofollow noreferrer\">this SANS whitepaper</a> for more information on this topic.</p>\n\n<h2>An example</h2>\n\n<p>One way to apply these suggestions could look like this:</p>\n\n<pre><code>int main(int argc, char **argv)\n{\n if (argc != 2) {\n printf(\"Incorrect number of arguments.\\n\"\n \"Usage: %s node\\n\"\n \"where node is the IP address of a machine to be scanned.\\n\", argv[0]);\n return 1;\n }\n static struct addrinfo hints = { .ai_socktype = SOCK_STREAM };\n struct addrinfo *serviceinfo;\n if (getaddrinfo(argv[1], NULL, &amp;hints, &amp;serviceinfo) != 0) {\n puts(\"error in getaddrinfo() function call\");\n return 1;\n }\n for (struct addrinfo* svc = serviceinfo; svc; svc = svc-&gt;ai_next) {\n for (unsigned port_no = 0; port_no &lt; 1024; port_no++) {\n int sock_fd = socket(svc-&gt;ai_family, svc-&gt;ai_socktype, svc-&gt;ai_protocol);\n if (sock_fd == -1) {\n puts(\"error in socket() function call\");\n freeaddrinfo(serviceinfo);\n return 1;\n }\n if (svc-&gt;ai_family == AF_INET) {\n ((struct sockaddr_in *)(svc-&gt;ai_addr))-&gt;sin_port = htons(port_no);\n } else if (svc-&gt;ai_family == AF_INET6) {\n ((struct sockaddr_in6 *)(svc-&gt;ai_addr))-&gt;sin6_port = htons(port_no);\n }\n if (connect(sock_fd, svc-&gt;ai_addr, svc-&gt;ai_addrlen) != -1) {\n printService(svc);\n printf(\"Port %u is open\\n\", port_no);\n }\n close(sock_fd);\n }\n }\n freeaddrinfo(serviceinfo);\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-03T18:33:49.060", "Id": "477626", "Score": "0", "body": "Minor: `unsigned port_no; ... printf(\"Port : %d is open\\n\", port_no);` --> `%u`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-03T18:34:28.733", "Id": "477627", "Score": "0", "body": "@chux-ReinstateMonica: good idea! I've also eliminated setting the socktype explicitly: `static struct addrinfo hints = { .ai_socktype = SOCK_STREAM };` The other point is valid, too, but I didn't alter the code for that." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-03T18:36:37.387", "Id": "477628", "Score": "0", "body": "Curious, why `static` in `static struct addrinfo hints`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-03T18:38:47.123", "Id": "477630", "Score": "1", "body": "It's because `static` results in *implicit initialization* for every field member. If it were not `static` in this case, the un-named fields would be uninitialized. It's a subtle but important point." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-03T21:23:34.277", "Id": "477649", "Score": "0", "body": "I suppose this is purely stylistic, but I would return `EXIT_FAILURE` instead of the literal `1`. I would also add more whitespace to make it easier to read. What is `printService`? Is that a helper function that needs to be written? If so, it seems like it would make sense to print the more detailed information *after* the notice that the port is open." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-03T22:02:21.307", "Id": "477655", "Score": "0", "body": "@CodyGray One could use `EXIT_FAILURE` which is the only failure code *defined* in the C standard but other values are allowed. On POSIX systems, at least the low 7 bits are always passed back to the OS as a return value. Note that \"always\" is a dangerous word, but in practice, it's so. For `printService`, yes, it's a helper function as you have guessed. I have a generic one I use (and reuse) but one could create a specialized version that also includes the port status." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-03T22:05:23.300", "Id": "477656", "Score": "0", "body": "Also on return values, it would be nice if different conditions returned different error codes (and it would be better if they were `const` or `#define` rather than \"magic numbers\") but I leave this to the OP for further refinement." } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-03T13:04:25.627", "Id": "243323", "ParentId": "243311", "Score": "7" } } ]
{ "AcceptedAnswerId": "243323", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-03T10:12:46.910", "Id": "243311", "Score": "4", "Tags": [ "c", "linux", "networking", "unix" ], "Title": "Implementation of portscanner for a host" }
243311
<p>Given a Singly Linked-List, write a function to delete the linked list recursively. Below is my attempt. I am confused if I should use <strong>del</strong> keyword to delete the nodes or below method is better. I don't know if it is memory efficient this way.I'd appreciate any critique of what I could do better.</p> <pre><code>class SLLNode: def __init__(self, data): self.data = data self.next = None class SLL: def __init__(self): self.head = None def append(self, data): temp = SLLNode(data) if self.head is None: self.head = temp else: current = self.head while current.next is not None: current = current.next current.next = temp def delete_a_linked_list_using_recursion(head): if head is None: return head head = head.next return delete_a_linked_list_using_recursion(head) """driver's code""" sll = SLL() sll.append(1) sll.append(2) sll.append(3) sll.append(4) head = delete_a_linked_list_using_recursion(sll.head) </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-03T11:39:30.023", "Id": "243317", "Score": "1", "Tags": [ "python", "python-3.x", "object-oriented", "linked-list", "recursion" ], "Title": "Delete a linked list using recursion in Python" }
243317
<p>The problem I need is to solve, is a linear optimization problem where we need to to minimize parcel delivery costs by assigning nodes as hubs, which supposedly will reduce costs. </p> <p>In my code 'nodes' represents the number of nodes of a given set N. Then 'flows' is a list with the flow x_{ij} from a node i to a node j. In a similar way the list 'costs' is established. 'estab' is a list with the fixed costs f_i for establishing a hub. </p> <p>A route from node i to node j is given by the sum of (chi*costs(i,k)+alpha*costs(k,l)+delta*costs(l,j), where there are indeed three parts: collection, transfer and distribution. </p> <p>The problem it-self is solved. The implementation, however, is the issue. Firstly, running this gives 'UserWarning: Overwriting previously set objective'. Secondly, the result is that every node is assigned as a hub, which seems unlikely. </p> <p>Thanks in advance!</p> <pre><code>from pulp import * nodes = range(10) flows = [[75,37,55,19,20,18,57,17,19,16], [26,38,25,27,18,23,38,20,12,17], [67,39,51,22,24,21,71,20,23,19], [17,33,19,25,16,23,40,23,11,19], [17,25,21,19,23,18,73,20,24,19], [12,18,12,16,11,17,37,22,10,18], [82,78,90,68,95,73,312,99,110,110], [35,42,36,48,36,58,173,90,41,92], [12,12,15,10,19,11,68,15,24,20], [22,25,23,28,23,33,109,51,30,63]] costs = [[0,20,16,23,23,30,32,33,36,36], [20,0,20,13,25 ,19,30,25,38,31], [16,20,0,14,7,19,16,18,21,21], [23,13,14,0,14,7,18,13,27,18], [23,25,7,14,0,16,9,13,14,14], [30,19,19,7,16,0,16,8,25,13], [32,30,16,18,9,16,0,9,10,7], [33,25,18,13,13,8,9,0,18,5], [36,38,21,27,14,25,10,18,0,14], [36,31,21,18,14,13,7,5,14,0]] estab = [28767,28377,29774,24301,25853,20763,34166,33859,24718,33686] chi = 3 #multiplier costs of collection alpha = 1 #multiplier costs of transfer delta = 2 #multiplier costs of distribution estab_dict = dict(zip(nodes,estab)) Parcdelco = LpProblem('Parcdelco', LpMinimize) con = LpVariable.dicts('Connection', (nodes,nodes),0,1,LpInteger) routes = [(i,k,l,j) for i in nodes for k in nodes for l in nodes for j in nodes] path = LpVariable.dicts('Path', (nodes,nodes,nodes,nodes),0,1,LpInteger) for i in nodes: for j in nodes: Parcdelco += lpSum([flows[i][j]*lpSum([path[i][k][l][j]*(chi*costs[i][k]+alpha*costs[k][l]+delta*costs[l][j]) for (i,k,l,j) in routes])])\ +lpSum([con[i][i]*estab_dict[i] for i in nodes]) for i in nodes: Parcdelco += lpSum([con[i][i]]) &gt;= 1 for i in nodes: for j in nodes: Parcdelco += lpSum([con[i][j]]) == 1 for i in nodes: for k in nodes: Parcdelco += con[i][k] &lt;= con[k][k] for i in nodes: for k in nodes: for l in nodes: for j in nodes: Parcdelco += path[i][k][l][j] &lt;= con[i][k] + con[j][l] for i in nodes: for k in nodes: for l in nodes: for j in nodes: Parcdelco += path[i][k][l][j] &gt;= (1/2)*(con[i][k] + con[j][l] - 1) Parcdelco.solve() for i in nodes: print(value(con[i][i])) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-03T13:31:54.447", "Id": "477584", "Score": "2", "body": "\"Secondly, the result is that every node is assigned as a hub, which seems unlikely.\" So the output is likely incorrect? Please take a look at the [help/on-topic]." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-03T12:18:57.733", "Id": "243321", "Score": "1", "Tags": [ "python" ], "Title": "Linear Optimization code Python using Pulp" }
243321
<p>I'm sure my question exists on the internet, i just don't know the right formulations.</p> <p>I have a data-sample as input for a NN. This sample has the shape (1, 8, 28, 80). Basically it is 80 timesteps of an image. -> y=8, x=28, time=80</p> <p>i can extract the image at time=0 with:</p> <pre><code>np_img = image.data.numpy() # shape (1, 8, 28, 80) t0 = np_img[:, :, :, 0][0] </code></pre> <p>in order to be able to plot the images at each timestamp below each other, resulting in an array of (640, 28), ergo concatenating along the y-axis I do:</p> <pre><code>amount_timeslots = img.shape[-1] new_array = img[:, :, :, 0][0] for i in range(1, amount_timeslots): ti = img[:, :, :, i][0] new_array = np.concatenate((new_array, ti)) new_array.shape # (640, 28) </code></pre> <p>Is there a more pythonic way by using build in numpy magic to do this?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-03T13:30:41.087", "Id": "477582", "Score": "0", "body": "@MaartenFabré that returns (28,640) and the values seem to be not in the right order (so .T does help changing the dimensions but the values are wrong)" } ]
[ { "body": "<h1>concatenate</h1>\n\n<p>There is no need to do the concatenation pairwise <code>np.concatenate([img[:, :, :, i][0] for i in range(img.shape[-1])])</code> should improve the speed already</p>\n\n<h1><code>numpy.moveaxis</code></h1>\n\n<p>You can use <a href=\"https://numpy.org/doc/stable/reference/generated/numpy.moveaxis.html#numpy.moveaxis\" rel=\"nofollow noreferrer\"><code>numpy.moveaxis</code></a></p>\n\n<pre><code>new_array2 = np.concatenate(np.moveaxis(img[0],(0,1,2), (1,2,0)))\n</code></pre>\n\n<p>To check whether the result is the same:</p>\n\n<pre><code>assert np.array_equal(new_array, new_array2)\n</code></pre>\n\n<h1>Other improvements</h1>\n\n<p>Since you don't use the first axis of the image, you can do <code>np_img = image.data.numpy()[0]</code> so prevent you repeating the <code>[0]</code> in all subsequent code</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-04T15:15:53.760", "Id": "243384", "ParentId": "243322", "Score": "3" } } ]
{ "AcceptedAnswerId": "243384", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-03T12:44:09.510", "Id": "243322", "Score": "3", "Tags": [ "python", "array", "numpy" ], "Title": "Numpy array slicing/reshape/concatination" }
243322
<p>I use Electron with NodeJS but this is mainly a javascript question. I got tired of build processes and being dependent of frameworks like Vue so I started my own.</p> <h2>Setup in <code>index.html</code></h2> <pre class="lang-html prettyprint-override"><code>&lt;head&gt;&lt;/head&gt; &lt;body&gt; &lt;div id="home"&gt;&lt;/div&gt; &lt;script&gt; var components = {}; // component(name) var component = (name) =&gt; components[name].html(); // Put components into components{} const componentpath = path.join(__dirname, './snippets2'); glob.sync(`${componentpath}/**/*.js`).forEach((file) =&gt; { components[path.parse(file).name] = require(file); }); // Created hook before anything else for (const key in components) { const component = components[key]; if (component.hasOwnProperty('created')) { component.created(); } }; // Place to HTML document.querySelector('#home').innerHTML = component('body'); // Init components after HTML is placed for (const key in components) { const component = components[key]; if (component.hasOwnProperty('init')) { component.init(); } }; &lt;/script&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <h2>A component example</h2> <pre class="lang-js prettyprint-override"><code>module.exports = { html() { return /*html*/ ` &lt;div&gt; Some HTML ${component('someOtherComponent')} &lt;/div&gt; `; }, created() { this.myCustomMethod(); }, init() { console.log("After HTML is placed on site"); }, myCustomMethod() { console.log("Custom method, before HTML is placed on site"); } }; </code></pre> <p>Is it a good approach? Are there any pitfalls with it that you see?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-04T12:35:29.437", "Id": "477695", "Score": "0", "body": "how do you trigger a re-render ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-04T12:44:45.077", "Id": "477696", "Score": "0", "body": "@kemicofaghost So far I don't use a store/state two way data binding. Instead I use a more traditional way. I have a function named update(). It updates an array of values (not in the example) within the scope. Then it runs html() again which uses the new values in the array. I use innerHTML to put it back to the DOM. Not very fancy but so far it has worked well." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-03T13:40:15.097", "Id": "243325", "Score": "1", "Tags": [ "javascript" ], "Title": "A component approach instead of Vue" }
243325
<p>Basically I have done a code for a project which works with a shift and ctrl selection. The program consists of a chart with specified points, which the user is able to select with the different key controls in order to move them. The highlightedIndex is a list of int. I am also working with WPF and later on I have to bind this with a DataGrid, so I do not know if this is the right approach or is any easier way to get this done with the Binding from WPF. <a href="https://i.stack.imgur.com/7rjFa.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/7rjFa.png" alt=""></a> I want to be able to select the points with Ctrl or Shift as Windows works, it should look like this.</p> <pre><code>public partial class MainWindow : Window { public ChartValues&lt;ObservablePoint&gt; Chartvalues { get; set; } public SeriesCollection SeriesCollection { get; set; } public CartesianMapper&lt;ObservablePoint&gt; Mapper { get; set; } public Brush DangerBrush { get; set; } private int movingPointIdx = -1; //-1: no point moving private const int roundedNumber = 2; private const double min_offset = 0.01; private List&lt;int&gt; highlightedIndex = new List&lt;int&gt;(); private int lastClickedPointIdx = -1; int firstvaluepoint = 0; public MainWindow() { InitializeComponent(); Chartvalues = new ChartValues&lt;ObservablePoint&gt;(); InitPoints(); Mapper = Mappers.Xy&lt;ObservablePoint&gt;() .X(item =&gt; item.X) .Y(item =&gt; item.Y) .Stroke((item, index) =&gt; highlightedIndex.Contains(index) ? DangerBrush : null); DangerBrush = new SolidColorBrush(Color.FromRgb(253, 23, 23)); var lineSeries = new LineSeries { Title = "Line 1", Values = Chartvalues, StrokeThickness = 4, Fill = Brushes.Transparent, PointGeometrySize = 15, LineSmoothness = 0.2, Configuration = Mapper, DataLabels = false, }; SeriesCollection = new SeriesCollection { lineSeries }; DataContext = this; } private void InitPoints() //plot the values of the chart { Chartvalues.Clear(); double[] xvals = { 0, 2, 3, 4, 5, 6, 7, 8, 9 }; double[] yvals = { 0, 1, 2, 3, 1, 2, 3, 1, 2 }; for (int i = 0; i &lt; xvals.Length; i++) { Chartvalues.Add(new ObservablePoint { X = xvals[i], Y = yvals[i] }); } } private void ChartOnDataClick(object sender, ChartPoint p) { Chartvalues = (ChartValues&lt;ObservablePoint&gt;)SeriesCollection[0].Values; foreach (ObservablePoint val in Chartvalues) { if (val.X == p.X &amp;&amp; val.Y == p.Y) //this is the clicked point { movingPointIdx = Chartvalues.IndexOf(val); //get index of currently clicked point Chartvalues[movingPointIdx].X = Chartvalues[movingPointIdx].X; //highlights selected point KeyPressed(); } } } private void KeyPressed() { bool shiftclick = false; int firstselectedpoint = 0; if (Keyboard.IsKeyDown(Key.LeftCtrl) || Keyboard.IsKeyDown(Key.RightCtrl)) //Ctrl { if (highlightedIndex.Contains(movingPointIdx)) //remove point if already is in the highlightedIndex list { highlightedIndex.Remove(movingPointIdx); firstselectedpoint = movingPointIdx; shiftclick = false; return; } else //otherwise add it to the highlightedIndex list { highlightedIndex.Add(movingPointIdx); highlightedIndex.Sort(); firstselectedpoint = movingPointIdx; shiftclick = false; } } else if (Keyboard.IsKeyDown(Key.LeftShift) || Keyboard.IsKeyDown(Key.RightShift)) //Shift { if (!shiftclick) { highlightedIndex.Clear(); shiftclick = true; } if (lastClickedPointIdx &gt; -1) //highlights all points { if (firstvaluepoint &gt; firstselectedpoint) { for (int i = firstselectedpoint; i &lt;= firstvaluepoint; i++) { highlightedIndex.Add(i); } } else { for (int i = firstvaluepoint; i &lt;= firstselectedpoint; i++) { highlightedIndex.Add(i); } } } } else //no modifier key pressed -&gt; only add the current point to the list { highlightedIndex.Clear(); highlightedIndex.Add(movingPointIdx); } lastClickedPointIdx = movingPointIdx; if (!shiftclick) firstvaluepoint = firstselectedpoint; } private void ChartOnMouseMove(object sender, MouseEventArgs e) { if (e.LeftButton != MouseButtonState.Pressed) return; if (movingPointIdx == -1) return; var newPoint = diagram.ConvertToChartValues(e.GetPosition(diagram)); Chartvalues[movingPointIdx].X = Math.Round(newPoint.X, roundedNumber); Chartvalues[movingPointIdx].Y = Math.Round(newPoint.Y, roundedNumber); CheckForOnePointBoundaries(Chartvalues[movingPointIdx].X); } private void CheckForOnePointBoundaries(double xBoundary)//checks if the point has reacher his boundary (next or last point) { double leftBoundary = 0; double rightBoundary = Chartvalues[Chartvalues.Count - 1].X; if (movingPointIdx &gt; 0) leftBoundary = Chartvalues[movingPointIdx - 1].X + min_offset; if (movingPointIdx &lt; Chartvalues.Count - 1) rightBoundary = Chartvalues[movingPointIdx + 1].X - min_offset; if (xBoundary &lt; leftBoundary) { Chartvalues[movingPointIdx].X = leftBoundary; } else if (xBoundary &gt; rightBoundary) { Chartvalues[movingPointIdx].X = rightBoundary; } } private void ChartOnMouseLeftButtonUp(object sender, MouseButtonEventArgs e) =&gt; movingPointIdx = -1; // deactivate point moving private void AddPoints(object sender, MouseButtonEventArgs e) { if (e.ChangedButton == MouseButton.Left) { var newPoint = diagram.ConvertToChartValues(e.GetPosition(diagram)); var addedPoint = new ObservablePoint(Math.Round(newPoint.X, roundedNumber), Math.Round(newPoint.Y, roundedNumber)); Chartvalues.Add(addedPoint); SortChartValues(); highlightedIndex.Clear(); for (int i = 0; i &lt; Chartvalues.Count; i++) { if (addedPoint.X == Chartvalues[i].X) // adds the clicked point to the list { highlightedIndex.Add(i); i = Chartvalues.Count; } } } } private void SortChartValues() { List&lt;Point&gt; list = new List&lt;Point&gt;(); foreach (ObservablePoint val in Chartvalues) { list.Add(new Point(val.X, val.Y)); } list = list.OrderBy(p =&gt; p.X).ToList(); Chartvalues.Clear(); for (int i = 0; i &lt; list.Count; i++) { Chartvalues.Add(new ObservablePoint { X = list[i].X, Y = list[i].Y }); } } private void RemovePoints(object sender, RoutedEventArgs e) { if (movingPointIdx == -1) return; if (Chartvalues.Count &gt; 1) { Chartvalues.RemoveAt(movingPointIdx); highlightedIndex.RemoveAt(movingPointIdx); movingPointIdx = -1; } } } </code></pre> <p><strong>XAML</strong></p> <pre><code>&lt;Grid&gt; &lt;lvc:CartesianChart Margin="10,35,27,5" x:Name="diagram" LegendLocation="Top" Series="{Binding SeriesCollection}" DataClick="ChartOnDataClick" DisableAnimations="True"/&gt; &lt;/Grid&gt; </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-03T17:32:33.497", "Id": "477614", "Score": "0", "body": "Where is `highlightedIndex` defined? It looks like this is all a method part of a class. Please share the rest of the class as well, preferably with a small usage example." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-03T18:09:19.973", "Id": "477623", "Score": "0", "body": "@Mast iÍ have already upload the whole class, what do you mean by usage example? Like a screenshot?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-03T18:26:10.080", "Id": "477624", "Score": "0", "body": "@Mast the highlightedIndex is initialized in the _ctor_ and filled in the _KeySelection()_ method" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-03T19:24:46.817", "Id": "477632", "Score": "0", "body": "Did you use your class to create that plot? If so, when you share the code that created it that's exactly what I meant with a usage example." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-03T19:38:44.063", "Id": "477636", "Score": "1", "body": "@Mast Yes I used it to plot those values and I used Livecharts_ for the diagram." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-04T18:22:02.380", "Id": "477726", "Score": "0", "body": "What exactly does the KeyPressed() method and who calls the KeySelection() method?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-04T23:35:08.960", "Id": "477752", "Score": "0", "body": "@JanDotNet actually both are the same method but I chnaged the name of one and forgot to do it for all them. The Ctrl-Key condition add the selected points to the List and if it is already in it, it is deleted. I also added two lines one for a bool to enable the Shift-Key, because they can work together. I mean if you select in Windows different files (CTRL) and the you press shift and click in another file it should select from the last file you selected with Ctrl to the file selected with shift (I don´t know if I am explaining)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-04T23:35:59.897", "Id": "477753", "Score": "0", "body": "It is basically what it does and the Shift works similar, if nothing is selected and you select a point / file (to compare with windows) it should select all the points from left to right or in the default case from top to bottom, the last condition is only to add the current point to the list if no key is pressed" } ]
[ { "body": "<p>Welcome to code review.</p>\n\n<p><strong>Avoid using writable instance variables</strong></p>\n\n<p>Using writable instance variables in various methods should be avoided if possible, because the code becomes very fast complex.</p>\n\n<p>For example the property 'Chartvalues' will be set in 'constructor' and in method 'ChartOnDataClick' and used in other methods.</p>\n\n<p>This desing can be simply improved by using a read-only property:</p>\n\n<pre><code>public ChartValues&lt;ObservablePoint&gt; Chartvalues =&gt; (ChartValues&lt;ObservablePoint&gt;)SeriesCollection[0].Values\n</code></pre>\n\n<p>and changing the initialization like:</p>\n\n<pre><code>public MainWindow()\n{\n ....\n var lineSeries = new LineSeries\n {\n Title = \"Line 1\",\n Values = new ChartValues&lt;ObservablePoint&gt;(GetInitialPoints()),\n StrokeThickness = 4,\n ....\n}\n\nprivate IEnumerable&lt;ObservablePoint&gt; GetInitialPoints() //plot the values of the chart\n{\n double[] xvals = { 0, 2, 3, 4, 5, 6, 7, 8, 9 };\n double[] yvals = { 0, 1, 2, 3, 1, 2, 3, 1, 2 };\n\n for (int i = 0; i &lt; xvals.Length; i++)\n {\n yield new ObservablePoint { X = xvals[i], Y = yvals[i] };\n }\n}\n</code></pre>\n\n<p><strong>Use Keyboard.Modifiers instead of checking modifier keys seperatly</strong></p>\n\n<ul>\n<li>Instead of <code>Keyboard.IsKeyDown(Key.LeftCtrl) || Keyboard.IsKeyDown(Key.RightCtrl)</code> the simpler form <code>(Keyboard.Modifiers &amp; ModifierKeys.Control) != 0</code> can be used.</li>\n</ul>\n\n<p><strong>Keep it simple</strong></p>\n\n<ul>\n<li><code>shiftclick</code> is actually not necessary. You can remove the variable and lots of code with it.</li>\n</ul>\n\n<p><strong>Name event handlers like event handlers</strong></p>\n\n<ul>\n<li>It is a good style to name event handler like event handler and extract functional code to methods.</li>\n</ul>\n\n<p>For example:</p>\n\n<pre><code>private void MouseClickedEventHandler(object sender, MouseButtonEventArgs e)\n{\n if (e.ChangedButton == MouseButton.Left)\n {\n var newPoint = diagram.ConvertToChartValues(e.GetPosition(diagram));\n AddPoint(newPoint);\n }\n}\n\nprivate void AddPoint(Point newPoint)\n{\n var addedPoint = new ObservablePoint(Math.Round(newPoint.X, roundedNumber), Math.Round(newPoint.Y, roundedNumber));\n Chartvalues.Add(addedPoint);\n\n SortChartValues();\n highlightedIndex.Clear();\n\n for (int i = 0; i &lt; Chartvalues.Count; i++) \n {\n if (addedPoint.X == Chartvalues[i].X) // adds the clicked point to the list\n {\n highlightedIndex.Add(i);\n i = Chartvalues.Count;\n }\n }\n}\n</code></pre>\n\n<p><strong>When complexity increases, use object oriented design to keep it maintainable</strong></p>\n\n<p>The problem with writing all that event handling code in one class with global states (writable instance variables) is, that it does not scale. For your use case it may work... but adding new use cases will very likly break exiting functionality and code becomes unmaintainable.</p>\n\n<p>Fortunately, we are working with a programming language supporting advanced object oriented design, so why not using it.</p>\n\n<p>We have a chart that we want to interact with. At any given time, we are in a certain <em>logical state</em> (e.g.: Idle, Point selected, Moving selection rectangle, ...) and incoming events can change the current <em>logical state</em> to another one.</p>\n\n<p>Instead of having one global state (all writable instance variables) where the <em>logical state</em> can be derived from, why not designing the <em>logical states</em> directly? This design is already known as <a href=\"https://en.wikipedia.org/wiki/State_pattern\" rel=\"nofollow noreferrer\">state pattern</a>.</p>\n\n<p>In your case, state diagram may look like:\n<a href=\"https://i.stack.imgur.com/SOj0M.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/SOj0M.png\" alt=\"enter image description here\"></a></p>\n\n<p>Corresponding implementation of the state pattern may look like:</p>\n\n<pre><code>internal interface IChartContext\n{\n ChartPoint AddPoint(Point position);\n void Select(ChartPoint chartPoint);\n void ToggleSelection(ChartPoint chartPoint);\n void ExtendSelection(ChartPoint chartPoint);\n void ChangeState(State state);\n}\n\ninternal abstract class State\n{\n protected State(IChartContext ctx)\n {\n this.Ctx = ctx;\n }\n\n public virtual void OnLeftMouseUp(MouseButtonEventArgs e) { }\n public virtual void OnLeftMouseDown(MouseButtonEventArgs e) { }\n public virtual void OnMouseMove(MouseEventArgs e) { }\n\n internal IChartContext Ctx { get; }\n}\n\ninternal class IdleState : State\n{\n public IdleState(IChartContext ctx) : base(ctx) { }\n\n public override void OnLeftMouseDown(MouseButtonEventArgs e)\n {\n var point = e.GetPosition(this.Ctx.DrawingArea);\n var point = this.Ctx.AddPoint(point);\n this.Ctx.ChangeState(new PointMovingState(this.Ctx, point));\n }\n\n public override void OnMouseMove(MouseEventArgs e)\n {\n var point = e.GetPosition(this.Ctx.DrawingArea);\n var chartPoint = this.Ctx.GetChartPoint(point);\n if (chartPoint != null)\n {\n this.Ctx.ChangeState(new MouseOverPoint(this.Ctx, chartPoint));\n }\n }\n}\n\ninternal class PointMovingState : State\n{\n private readonly ChartPoint chartPoint;\n\n public PointMovingState(IChartContext ctx, ChartPoint chartPoint) : base(ctx) \n {\n this.chartPoint = chartPoint;\n }\n\n public override void OnMouseMove(MouseEventArgs e)\n {\n var point = e.GetPosition(this.Ctx.DrawingArea);\n this.chartPoint.X = point.X;\n this.chartPoint.Y = point.Y;\n }\n\n public override OnLeftMouseUp(MouseButtonEventArgs e)\n {\n this.Ctx.ChangeState(new MouseOverPoint(this.Ctx, point));\n }\n}\n\ninternal class MouseOverPoint : State\n{\n private readonly ChartPoint chartPoint;\n\n public MouseOverPoint(IChartContext ctx, ChartPoint chartPoint) : base(ctx)\n {\n this.chartPoint = chartPoint;\n }\n\n public override void OnMouseMove(MouseEventArgs e)\n {\n var point = e.GetPosition(this.Ctx.DrawingArea);\n var chartPoint = this.Ctx.GetChartPoint(point);\n if (chartPoint == null)\n {\n this.Ctx.ChangeState(new IdleState(this.Ctx));\n }\n if (chartPoint != this.chartPoint)\n {\n this.Ctx.ChangeState(new MouseOverPoint(this.Ctx, chartPoint));\n }\n }\n\n public override OnLeftMouseDown(MouseButtonEventArgs e)\n {\n if (Keyboard.Modifiers &amp; ModifierKeys.Control != 0)\n {\n this.Ctx.ToggleSelection(this.chartPoint);\n }\n else if (Keyboard.Modifiers &amp; ModifierKeys.Shift != 0)\n {\n this.Ctx.ExtendSelection(this.chartPoint);\n }\n else\n {\n this.Ctx.Select(this.chartPoint);\n }\n\n this.Ctx.ChangeState(new PointMovingState(this.Ctx, point));\n }\n}\n\n\npublic partial class MainWindow : Window, IChartContext\n{\n private State state;\n\n public MainWindow()\n {\n InitializeComponent();\n\n // initialization logic \n this.state = new IdleState(this);\n }\n\n public ChartPoint AddPoint(Point position) {\n // add logic for adding point \n }\n void Select(ChartPoint chartPoint) {\n // add logic for select single point\n }\n void ToggleSelection(ChartPoint chartPoint) {\n // add logic for toggle selection\n }\n void ExtendSelection(ChartPoint chartPoint) {\n // add logic for extend selection\n }\n void ChangeState(State state) {\n this.state = state;\n }\n\n private void ChartOnMouseLeftButtonUp(object sender, MouseButtonEventArgs e) =&gt; this.state.OnLeftMouseUp(e); \n private void ChartOnMouseLeftButtonDown(object sender, MouseButtonEventArgs e) =&gt; this.state.OnLeftMouseDown(e); \n private void ChartOnMouseMove(object sender, MouseEventArgs e) =&gt; this.state.OnMouseMove(e);\n}\n</code></pre>\n\n<p>Even if there is a lot of structual code, that design allows complex chart interaction and will scale with complexity. Therefore it is possible to add more use cases (states and transistions) without touching (and break) existing functionality.</p>\n\n<p>For very simple use cases it may be over-engineered, but in your case I would think about using that pattern.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-07T13:23:14.657", "Id": "243516", "ParentId": "243326", "Score": "0" } } ]
{ "AcceptedAnswerId": "243516", "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-03T13:45:31.280", "Id": "243326", "Score": "4", "Tags": [ "c#", "performance", "wpf" ], "Title": "Shift selection" }
243326
<p>[Base on <a href="https://codeforces.com/contest/1360/problem/G]" rel="nofollow noreferrer">https://codeforces.com/contest/1360/problem/G]</a></p> <p>So my logic is to process each column at a time and find <code>b</code> rows such that the total 1s in them is less than a and if there are many candidates I take the rows with least 1s.</p> <pre><code>import Data.List import Data.Array import Control.Monad -- import Debug.Trace -- debug = flip trace main :: IO () main = do t &lt;- read &lt;$&gt; getLine -- testcases replicateM_ t $ do n : m : a : b : _ &lt;- (map read . words &lt;$&gt; getLine) :: IO [Int] mapM putStrLn $ case solve n m a b of Just mat -&gt; "YES" : [ concatMap show [ mat ! (i, j) | j &lt;- [1 .. m] ] | i &lt;- [1 .. n] ] Nothing -&gt; ["NO"] -- solve :: Int -&gt; Int -&gt; Int -&gt; Int -&gt; Maybe (Array (Int, Int) Int) solve n m a b = go (array (1, n) . zip [1 .. n] $ repeat 0) -- rowcnts (array ((1, 1), (n, m)) [ ((i, j), 0) | i &lt;- [1 .. n], j &lt;- [1 .. m] ]) -- matrix 1 -- column where go rowcnts mat c | length idxs /= b = Nothing -- not enough rows | c == m = if all (== a) (elems rowcnts') then Just mat' else Nothing -- last column to process | otherwise = go rowcnts' mat' (c + 1) -- recurse for next column where idxs = take b . filter (\i -&gt; (rowcnts ! i) &lt; a) $ sortOn (rowcnts !) [1 .. n] -- candidate rows rowcnts' = accum (+) rowcnts . zip idxs $ repeat 1 --`debug` show (elems rowcnts) mat' = mat // [ ((idx, c), 1) | idx &lt;- idxs ] </code></pre> <p>I wish to ask how can I write better code which might be concise and cleaner.</p>
[]
[ { "body": "<p>You don't need to collect the rows in a matrix because you only touch each row once, and you don't need Data.Array because you only ever process a whole row. The check at the end makes the checks in the middle functionally superfluous. <code>mapAccumL</code> captures the explicit recursion.</p>\n\n<pre><code>main :: IO ()\nmain = do\n t &lt;- readLn\n replicateM_ t $ do\n [n,m,a,b] &lt;- map read . words &lt;$&gt; getLine\n mapM putStrLn $ case solve n m a of\n (colcnts, rows) | all (==b) colcnts -&gt; \"YES\" : map (concatMap show) rows\n _ -&gt; [\"NO\"]\n\nsolve :: Int -&gt; Int -&gt; Int -&gt; ([Int], [[Int]])\nsolve n m a = mapAccumL go (replicate m 0) [1..n] where\n go colcnts c = (zipWith (+) row colcnts, row) where row\n = map fst $ sortOn snd $ zip (replicate a 1 ++ repeat 0)\n $ map fst $ sortOn snd $ zip [1..] colcnts\n</code></pre>\n\n<p>Note that your entire approach doesn't obviously find a solution if there is one. Can you prove that?</p>\n\n<p>Edit: I thought you process each row at a time. Easy to mix up since the approaches are symmetric :). I choose the row-at-a-time approach, since they can be directly printed.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-04T07:12:55.357", "Id": "477681", "Score": "0", "body": "It passes for all the test cases so I have a reason to believe it finds a solution in all the cases, but I will need to prove that formally." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-03T18:52:05.673", "Id": "243337", "ParentId": "243330", "Score": "1" } } ]
{ "AcceptedAnswerId": "243337", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-03T15:59:00.403", "Id": "243330", "Score": "0", "Tags": [ "haskell" ], "Title": "Find a n x m binary matrix with exactly a 1's in all rows and b 1's in all columns" }
243330
<p><strong>Hello everyone!</strong> I wrote a class Vector.So, I want to find out how can i upgrade it for better performance of my vector. Here is the code:</p> <pre><code>template &lt;typename Type&gt; class Vector { private: size_t _size; size_t _capacity; Type* _data; public: Vector(size_t capacity = 0); Vector(const Vector&amp; vec); Vector&amp; push_back(const Type&amp; elem); Vector&amp; resize(size_t new_size); }; template&lt;typename Type&gt; Vector&lt;Type&gt;&amp; Vector&lt;Type&gt;::push_back(const Type&amp; elem) { if (_size == _capacity) { if (_capacity &lt; 10) resize(_capacity + 10); else resize(_capacity * 1.5); //resize(_capacity &lt; 10 ? _capacity + 10 : 1.5*_capacity); } _data[_size++] = elem; return *this; } template&lt;typename Type&gt; Vector&lt;Type&gt;&amp; Vector&lt;Type&gt;::resize(size_t new_size) { _capacity = new_size; _size = _capacity &lt; _size ? _capacity : _size; Type* tmp = new Type[_capacity]; if (!tmp) throw "Out of memory"; for (int i = 0; i &lt; _size; ++i) //tmp[i] = _data[i]; tmp[i] = std::move(_data[i]); if (!_data) delete[] _data; _data = tmp; } </code></pre> <p>There are also different constructors, iterators, overloading of operators and so on. I will add it later if someone need it.</p> <p>Update: This code is a prototype of a STL vector, so, function push_back add new value to the vector and there is no problem with it but I want to find out if this push_back member-function can be upgraded. The example:</p> <pre><code>Vector&lt;int&gt; vec; // zero elements vector vec.push_bacK(1); // now vector is {1} vec.push_back(2); // now vector is {1,2} </code></pre> <p><strong>Thank you in advance!</strong></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-03T17:03:56.557", "Id": "477610", "Score": "0", "body": "What's the code supposed to do? What made you write this and what problem does it solve?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-05T03:49:51.133", "Id": "477759", "Score": "1", "body": "Please have a look at the series of articles I wrote on vector: https://lokiastari.com/series/" } ]
[ { "body": "<h2>Code Review</h2>\n\n<p>The first mistake is that you don't implement the rule of 3 correctly.<br>\nYour class owns a RAW pointer and though you implement the copy constructor you don't implement the copy assignment operator. As a result your object can easily be broken:</p>\n\n<pre><code>{\n Vector&lt;int&gt; a;\n Vector&lt;int&gt; b;\n\n a.push_back(12);\n b = a; // Copy assignment.\n // The compiler implemented this function.\n // and simply does a shallow copy.\n //\n // As a result b lost its original pointer (leaked)\n // and now both `a` and `b` _data point at the same\n // piece of memory. Not a problem yet.\n\n\n b.push_back(13); // expect b to be {12, 13}\n // expect a to be {12} but is actually {12, 13}\n // Though the size of a is still 1.\n // But if we add a value to a it will overwrite\n // The value in b (as they are sharing memory).\n\n\n}\n// `a` and `b` go out of scope and should call delete on the pointer.\n// This will result in a double delete.\n</code></pre>\n\n<p>Though you don't actually implement the destructor.<br>\nSo you will not actually have a double delete but instead leak more memory.</p>\n\n<hr>\n\n<p>As a side note you don't provide move semantics:</p>\n\n<pre><code>Vector(Vector&lt;Type&gt;&amp;&amp; move) noexcept;\nVector&amp; operator=(Vector&lt;Type&gt;&amp;&amp; move) noexcept;\n</code></pre>\n\n<p>Also when putting data into your vector you may want to think about moving the value into the vector rather than copying it.</p>\n\n<pre><code>void push_back(Type&amp;&amp; move);\n</code></pre>\n\n<p>If you want to get advance you can set up build the <code>Type</code> inplace.</p>\n\n<pre><code>template&lt;typename... Param&gt;\nvoid emplace_back(Param&amp;&amp; p...);\n</code></pre>\n\n<hr>\n\n<p>Prefer not to use a leading underscore on identifiers.</p>\n\n<pre><code>size_t _size;\nsize_t _capacity;\nType* _data;\n</code></pre>\n\n<p>You don't break any rules. But the rules are non obvious. So even if you don't break them the next developer writing the code may change something slightly and break the rules.</p>\n\n<p>See: <a href=\"https://stackoverflow.com/q/228783/14065\">What are the rules about using an underscore in a C++ identifier?</a></p>\n\n<p>Note: A trailing underscore is fine.</p>\n\n<hr>\n\n<p>You have a capacity, but no way to change the value of capacity.</p>\n\n<p>You have a <code>resize()</code> but no <code>reserve()</code>.</p>\n\n<pre><code> Vector&amp; resize(size_t new_size);\n</code></pre>\n\n<p>Not sure why you return a reference from <code>resize()</code>, its not bad (it allows chaining) but a bit unexpected.</p>\n\n<hr>\n\n<p>I think you have this the wrong way around.</p>\n\n<pre><code> _size = _capacity &lt; _size ? _capacity : _size;\n</code></pre>\n\n<hr>\n\n<p>This will never happen</p>\n\n<pre><code> if (!tmp) throw \"Out of memory\";\n</code></pre>\n\n<p>The <code>new</code> operator will never return null. If it can not allocate memory it will throw an exception. So no need to do this manual check.</p>\n\n<p>But if it did work like you expected you should not throw until you have put the object back to its original state.</p>\n\n<hr>\n\n<p>It is perfectly fine to call delete on a <code>nullptr</code>.</p>\n\n<pre><code> if (!_data)\n delete[] _data;\n</code></pre>\n\n<p>This test is just a pesimization of the normal case.</p>\n\n<hr>\n\n<p>Things go badly here:</p>\n\n<pre><code> // You change the capacity and size here. \n _capacity = new_size;\n _size = _capacity &lt; _size ? _capacity : _size;\n\n // So this new can technically throw.\n Type* tmp = new Type[_capacity];\n\n // If it does your object is no longer \n // an a valid state (as size and capacity no longer match \n // what is pointed at by _data\n\n // Thus you have violated the strong exception guarantee.\n</code></pre>\n\n<hr>\n\n<p>Yes this is fine:</p>\n\n<pre><code> for (int i = 0; i &lt; _size; ++i)\n //tmp[i] = _data[i];\n tmp[i] = std::move(_data[i]);\n</code></pre>\n\n<p>But you should always use braces <code>{}</code> around sub expressions.</p>\n\n<pre><code> for (int i = 0; i &lt; _size; ++i) {\n //tmp[i] = _data[i];\n tmp[i] = std::move(_data[i]);\n }\n</code></pre>\n\n<p>But I would simply use the standard functions:</p>\n\n<pre><code> std::move(data, data + size, tmp);\n</code></pre>\n\n<hr>\n\n<p>The best way way to implement this is more like this:</p>\n\n<pre><code>template&lt;typename Type&gt;\nVector&lt;Type&gt;&amp; Vector&lt;Type&gt;::resize(size_t tryThisSize)\n{\n size_t newSize = tryThisSize;\n size_t newCapacity = _capacity &lt; newSize ? newSize : _capacity;\n Type* newData = new Type[newCapacity];\n\n std::move(_data, _data + _size, newData);\n\n // All the work has been done\n // The current object is still in the old state.\n // But all the data is correctly in the new variables.\n // So let us swap the current and new state.\n\n using std::swap;\n swap(newSize, _size);\n swap(newCapacity, _capacity);\n swap(newData, _data);\n\n delete [] newData; // Remember this is the old data.\n // We swapped this objects pointer int here.\n\n return *this;\n }\n</code></pre>\n\n<p>I go into a lot more details in my articles.</p>\n\n<hr>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-05T04:47:27.007", "Id": "477760", "Score": "0", "body": "Thank you! I will definitely check your articles" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-05T04:26:28.200", "Id": "243407", "ParentId": "243331", "Score": "2" } } ]
{ "AcceptedAnswerId": "243407", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-03T16:28:44.283", "Id": "243331", "Score": "-1", "Tags": [ "c++", "algorithm", "vectors" ], "Title": "Push_back algorithm for Vector" }
243331
<p>I have this python script that uses pandas read an excel sheet then to update a sqlite db it works perfectly just wondering if I can speed it up as I am at about 70k lines</p> <pre><code>""" Created on Thu Aug 1 14:11:01 2019 @author: Shane Pitts """ # -*- coding: utf-8 -*- import sqlite3 from sqlite3 import Error import pandas as pd import shutil #Takes DB File path then creates connection to it def create_connection(db_file): """ create a database connection to a SQLite database """ try: conn = sqlite3.connect(db_file) return conn print(sqlite3.version) except Error as e: print(e) return None #updates reported table def update_dupi_reported(conn, dupi, userID, op): with conn: cur = conn.cursor() cur.execute("UPDATE reported SET dupi = :dupi WHERE userID = :userID AND operator = :op", {'dupi':dupi, 'userID':userID, 'op':op}) #updates blocked table def update_dupi_blocked(conn, dupi, userID, op): with conn: cur = conn.cursor() cur.execute("UPDATE blocked SET dupi = :dupi WHERE userID = :userID AND operator = :op", {'dupi':dupi, 'userID':userID, 'op':op}) def Count(): #Creates a dataframe with the Excel sheet information df = pd.DataFrame() df = pd.read_excel("/root/Shane_db/Count.xlsx") #Assigns a variable to the DataBase database = "/root/Shane_db/db.db" # create a database connection conn = create_connection(database) cur = conn.cursor() #Runs through the DataFrame once for reported for i in df.index: userID = df['userID'][i] dupi = df['dupi'][i] op = df['operator'][i] print(i) with conn: update_dupi_reported(conn, dupi, userID, op) #Runs through a Second time for blocked for x in df.index: userID = df['userID'][x] dupi = df['dupi'][x] op = df['operator'][x] print(x) with conn: update_dupi_blocked(conn, dupi, userID, op) shutil.copy("/root/Shane_db/db.db", "/var/www/html/site/db.db") if __name__ == '__main__': Count() </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-03T16:48:08.730", "Id": "477608", "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](https://codereview.meta.stackexchange.com/q/2436) for guidance on writing good question titles." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-03T18:26:20.370", "Id": "477625", "Score": "0", "body": "@SᴀᴍOnᴇᴌᴀ I don't mean this in any rude way at all would this be a better title?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-03T18:36:54.293", "Id": "477629", "Score": "0", "body": "It is better... though keywords like [tag:pandas] and [tag:excel] are not as beneficial since the question has some of those as tags... if you had a description of how the data is used (e.g. for some type of report) that could help add clarity for reviewers (either in the title and/or description)" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-03T16:29:04.703", "Id": "243332", "Score": "2", "Tags": [ "python", "python-3.x", "pandas", "sqlite" ], "Title": "Uploading to DB from Excel with Pandas" }
243332
<p><strong>Question</strong>:<br> You are given <code>n</code> words. Some words may repeat. For each word, print its number of occurrences. The output order should correspond with the input order of appearance of the word.</p> <p><strong>Sample Input</strong>:</p> <pre><code>4 bcdef abcdefg bcde bcdef </code></pre> <p><strong>Sample Output</strong></p> <pre><code>3 2 1 1 </code></pre> <p>Here's what I came up with:</p> <pre class="lang-py prettyprint-override"><code>n = int(input()) array = [] elements = {} for index in range(n): value = input() if value not in array: array.append(value) elements[value] = 1 else: elements[value] += 1 print(len(elements)) print(*(i for i in elements.values()), end=' ') </code></pre> <p>I stress tested it on <a href="https://p.ip.fi/IwRU" rel="nofollow noreferrer">Try it Online</a> with the <a href="https://www.random.org/strings/?num=10000&amp;len=20&amp;loweralpha=on&amp;unique=off&amp;format=html&amp;rnd=new" rel="nofollow noreferrer">random string generator</a> and found the runtime to be around 1.98s. But I'm getting TLE on the coding platform. How do I improve the speed (bit offtopic - is there any other approach)?</p>
[]
[ { "body": "<h1>TLE</h1>\n\n<p>You're probably getting a TLE because,</p>\n\n<pre><code>if value not in array:\n</code></pre>\n\n<p>Is a O(N) operation meaning it has to traverse the entire array (worst case) to check if the value exists in the array</p>\n\n<p>I can understand why you felt the need to have an extra array, because of dictionaries are not ordered. </p>\n\n<p>But you can make use of the <a href=\"https://docs.python.org/3/library/collections.html#collections.OrderedDict\" rel=\"nofollow noreferrer\"><code>collections.OrderedDict</code></a> module, to have an ordered dictionary!</p>\n\n<h1>Other</h1>\n\n<ol>\n<li><p>join!</p>\n\n<pre><code>print(*(i for i in elements.values()), end=' ')\n</code></pre>\n\n<p>This can be done cleaner with joining the values instead of unpacking</p>\n\n<pre><code>print(\" \".join(map(str, e.values())))\n</code></pre></li>\n<li><p>Counter</p>\n\n<p>Python is often described as batteries included,</p>\n\n<p>Your <code>element</code> dictionary is the same the <a href=\"https://docs.python.org/3/library/collections.html#collections.Counter\" rel=\"nofollow noreferrer\"><code>collections.Counter</code></a></p></li>\n</ol>\n\n<h1>Code</h1>\n\n<p>We can make an <code>OrderedCounter</code> class to combine these two and make get the most out of the included modules.</p>\n\n<pre><code>from collections import Counter, OrderedDict\n\nclass OrderedCounter(Counter, OrderedDict):\n pass\n\nc = OrderedCounter(input() for _ in range(int(input())))\nprint(len(c))\nprint(\" \".join(map(str, c.values())))\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-05T11:34:46.667", "Id": "477781", "Score": "0", "body": "This is clever. Thank you so much!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-04T16:16:49.480", "Id": "243385", "ParentId": "243333", "Score": "3" } } ]
{ "AcceptedAnswerId": "243385", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-03T16:59:05.210", "Id": "243333", "Score": "2", "Tags": [ "python", "performance", "programming-challenge" ], "Title": "Count \"Word Order\" with further optimization" }
243333
<p>I am currently taking an introductory course in computer architecture. Our goal was to write a dot-product function in x86 Assembly which would use SSE and SIMD (without AVX). </p> <p>I am not to that confident with my solution:</p> <pre><code>#include &lt;time.h&gt; #define NUM 25600 //Example: scalarProduct using SIMD extern float scalarProduct(float *, float *, int size); float vsC(float * a, float * b, int size){ float sum = 0; for(int i = 0; i &lt; size; i++){ sum += b[i]*a[i]; } return sum; } int main(int argc, char ** argv){ float * a = malloc(NUM * sizeof(double)); float * b = malloc(NUM * sizeof(double)); for(int i = 0; i &lt; NUM; i++){ a[i] = 1; b[i] = 1.0/(i+1); } clock_t start, end; double cpu_time_used; start = clock(); float sum = scalarProduct(a,b,NUM); end = clock(); cpu_time_used = ((double) (end - start))/CLOCKS_PER_SEC; printf("%.15f\n", cpu_time_used); printf("Solution %.15f\n", (double)(sum)); start = clock(); sum = vsC(a,b,NUM); end = clock(); cpu_time_used = ((double) (end - start))/CLOCKS_PER_SEC; printf("%.15f\n", cpu_time_used); printf("Solution %.15f\n", (double)(sum)); } </code></pre> <p>Assembly File</p> <pre><code>.intel_syntax noprefix .text .global scalarProduct scalarProduct: mov rax, rdx xorps xmm0, xmm0 mov rcx, 0 start: cmp rax, 4 jl end movdqu xmm3, [rsi + rcx] movdqu xmm2, [rdi + rcx] vmulps xmm1, xmm2, xmm3 haddps xmm7, xmm1 haddps xmm7, xmm7 psrldq xmm7, 4 //Shift to pos0 addss xmm0, xmm7 xorps xmm7, xmm7 sub rax, 4 add rcx, 16 jmp start end: cmp rax, 0 je ret dec rax movss xmm1, [rsi + rcx] movss xmm2, [rdi + rcx] mulss xmm1, xmm2 addss xmm0, xmm1 add rcx, 4 jmp end ret: ret </code></pre> <p>Obviously, this Assembly - Code is far from perfect. How could I do better using basic SIMD and SSE?</p> <p>The second thing which made me wonder is, I indeed outperformed GCC on a Xeon processor, which is irritating. </p> <p>Compiling the code with:</p> <pre><code>gcc -o main -O7 main.c scalarProduct.S </code></pre> <p>Shows the following result:</p> <pre><code>./main 0.000015000000000 Solution 10.727574348449707 0.000026000000000 Solution 10.727569580078125 </code></pre> <p>How would I have to improve my C Code so that GCC can step up?</p> <p><strong>DISCLAIMER:</strong></p> <p><strong>My homework does not affect my grades and its editing is optional.</strong></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-06T19:42:21.277", "Id": "477905", "Score": "0", "body": "If you've done some improvements (in the asm or C code or both) I'd be interested what you did and what the new times are. You don't have to say, I'm just curious" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-08T10:18:32.380", "Id": "478017", "Score": "0", "body": "Today, I actually have some time to try SIMD intrinsics. So I will do that. I will also go for the multiple accumulators if I have some time left. \nI am also curious. and will notify you. \n\nI actually do think that your idea with multiple accumulators is pretty cool and of course a massive improvement.." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-08T12:55:51.733", "Id": "478050", "Score": "0", "body": "Hey, I have released some C - intrinsic code!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-08T13:09:48.353", "Id": "478052", "Score": "0", "body": "An annoying thing about AVX is that the 128bit halves are mostly independent. Therefore \"double _mm_hadd_ps\" works to horizontally sum 4 floats, but \"triple _mm256_hadd_ps\" does not work to horizontally sum 8 floats. You could use [this solution](https://stackoverflow.com/a/18616679/555045)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-08T13:14:55.513", "Id": "478056", "Score": "0", "body": "Hey, thank you. I used the function you provided in the link with the inline-modifier." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-08T13:42:19.837", "Id": "478066", "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)*. Please post a follow-up question instead and feel free to cross-link between them." } ]
[ { "body": "<blockquote>\n<p>How could I do better using basic SIMD and SSE?</p>\n</blockquote>\n<p>The most important things are:</p>\n<h1>Delay horizontal addition as long as possible</h1>\n<p><code>haddps</code> costs two shuffles and a normal addition. It is used twice, plus a shift and scalar-add. That's a lot of cost, and none of it is necessary: the main loop can just use <code>addps</code>. When the main loop is done, then you still need horizontal addition, but that cost is only paid once so it's not bad.</p>\n<p>By the way, you can horizontally sum <code>xmm1</code> like this:</p>\n<pre><code>haddps xmm1, xmm1\nhaddps xmm1, xmm1\n</code></pre>\n<p>No pre-zeroed register required, and no shift. It wastes a lot of work that <code>haddps</code> does, but it's short and simple.</p>\n<h1>Use multiple accumulators</h1>\n<p>When accumulating via <code>addps</code>, its latency becomes a bottleneck. <code>mulps</code> can be executed once or twice per cycle depending on the architecture, while <code>addps</code> has a latency of 3 to 4. Two <code>mulps</code> per cycles is not a reachable goal for a dot product (too much data needs to be loaded), but one per cycle is. Using a single accumulator means the loop is (eventually) limited to 1 iteration every 3 (or 4) cycles, it can get started quicker but a backlog of dependent <code>addps</code> builds up until it start to block progress.</p>\n<p>Using multiple accumulators fixes that issue by spreading the work across some independent <code>addps</code>, so progress can be made faster.</p>\n<p>As a bonus, the <code>haddps</code> after the loop has more useful work to do.</p>\n<h1>Use a 1-jump loop</h1>\n<pre><code>start:\n cmp rax, 4\n jl end\n ...\n jmp start\n</code></pre>\n<p>Is a 2-jump loop, but you can make it a 1-jump loop like this:</p>\n<pre><code> jmp loopentry\nstart:\n ...\nloopentry:\n cmp rax, 4\n jnl start\n</code></pre>\n<p>There are still two jumps, but one of them is not in the loop anymore.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-03T20:43:07.693", "Id": "243342", "ParentId": "243338", "Score": "4" } }, { "body": "<p>While harold reviewed your assembly code, I'll just comment on how you are compiling your C code:</p>\n\n<h1>Increase the duration of the benchmark</h1>\n\n<p>Your code runs for a very short amount of time, only tens of microseconds. This is too short to get accurate measurements:</p>\n\n<ul>\n<li><code>clock()</code> only has a resolution of a microsecond, so this is not insignificant compared to the duration.</li>\n<li>the processor's caches, branch predictors and prefetchers might not have had time to fully warm up.</li>\n<li>interrupts and other processes running on your system add noise.</li>\n</ul>\n\n<p>Aim to run your benchmarks for at least a second. That might be easier said than done: if you increase the size of the arrays you might become memory bandwidth bound instead of CPU bound. And if you naively just repeat the computations with the small array, the compiler might notice and just calculate the sum once and the multiply it by the number of repeats, depending on the level of optimization used.</p>\n\n<h1>Use a proper optimization level</h1>\n\n<p>There is no such thing as <code>-O7</code>. The highest supported optimization level for GCC is <code>-O3</code>. However, even that does not enable all possible optimzations. In particular, GCC is a bit careful when it comes to floating point math, and tries to ensure the code is correct even if there are infinities, NaNs and denormals. It also knows that floating point math is not strictly associative and commutative, and so will try to keep operations in the same order as you specified them, which prevents it from using some vectorization tricks. If you don't care about that, you can enable <code>-ffast-math</code>, or use <code>-Ofast</code>.</p>\n\n<h1>Consider using <code>-mtune=...</code> and/or <code>-march=...</code></h1>\n\n<p>If you don't specify any specific CPU, then on an x86-64 platform, GCC will output code that can run on any 64-bit Intel or AMD CPU, and might not be able to use certain SSE instructions that are not available in the x86-64 baseline. Also, the compiler will assume a certain CPU for instruction timing, delay slots, and other micro-architecural optimizations, which might not be ideal for the Xeon CPU you are running the code on. Typically you would use <code>-march=native</code> to ensure the compiler will provide code using all features of the CPU you are compiling on, but that might cause it to use AVX instructions if your CPU supports those.</p>\n\n<h1>Consider using SSE intrinsics</h1>\n\n<p>Instead of having a pure assembly version and a pure C version, you can have something inbetween by using <a href=\"https://software.intel.com/sites/landingpage/IntrinsicsGuide/#\" rel=\"noreferrer\">SSE intrinsics</a>. These are functions that are compiled into specific CPU instructions. However, the function arguments and return values are just variables (either regular ones or special vector type variables), not registers. The compiler will pick registers as it sees fit, and will also be able to reorder the intrinsics calls if possible, using its knowledge about the CPU's micro-architecture, and if you use the intrinsics in a loop then the compiler can unroll the loop for you.</p>\n\n<p>While GCC and Clang are able to vectorize certain loops, they are quite bad at using horizontal operations such as <code>haddps</code>, so if you help it by using intrinsics you might get code comparable to the best hand-optimized assembly.</p>\n\n<h1>Some results</h1>\n\n<p>If I increase the size of the array to <code>25600000</code>, and compile with <code>-O7</code> (which will effectively be <code>-O3</code>), I get the following results on an AMD Ryzen 9 3900X:</p>\n\n<pre><code>0.008444000000000\nSolution 16.000000000000000\n0.018092000000000\nSolution 15.403682708740234\n</code></pre>\n\n<p>With <code>-Ofast</code> I get:</p>\n\n<pre><code>0.008399000000000\nSolution 16.000000000000000\n0.006617000000000\nSolution 16.419670104980469\n</code></pre>\n\n<p>So clearly there is a speed-up when going to <code>-Ofast</code>, but the resulting solution is also different.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-03T20:47:30.240", "Id": "243343", "ParentId": "243338", "Score": "5" } } ]
{ "AcceptedAnswerId": "243343", "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-03T19:16:04.657", "Id": "243338", "Score": "5", "Tags": [ "c", "assembly", "simd", "sse" ], "Title": "SSE Assembly vs GCC Compiler - Dot Product" }
243338
<p>This is a follow up of <a href="https://codereview.stackexchange.com/questions/243130/a-simple-definite-integrator-class-of-a-single-variable-in-c">A simple definite integrator class of a single variable in C++</a></p> <p>I took most of the advice from the user: <a href="https://codereview.stackexchange.com/users/224452/emma-x">emma-x</a> and some from user: <a href="https://codereview.stackexchange.com/users/82535/sudo-rm-rf-slash">sudo-rm-rf-slash</a></p> <hr> <p>Here is my fully revised code:</p> <p><strong>Integrator.h</strong></p> <pre><code>#pragma once #include &lt;type_traits&gt; template &lt;typename Field&gt; struct Limits { Field lower; Field upper; constexpr Limits(Field a = 0, Field b = 0) : lower{ a }, upper{ b } {} }; template &lt;typename LimitType, typename Func&gt; class Integrator { private: Limits&lt;LimitType&gt; limits_; size_t step_size_; Func integrand_; public: Integrator(Limits&lt;LimitType&gt; limits, size_t stepSize, Func integrand) : limits_{ limits }, step_size_{ stepSize }, integrand_{ integrand } {} Limits&lt;LimitType&gt; limits() const { return limits_; } Func* integrand() { return &amp;integrand_; } // This is always a 1st order integration! constexpr auto evaluate() { if (limits_.lower == limits_.upper) { return 0.0; } else if (limits_.lower &gt; limits_.upper) { limits_ = Limits{ limits_.upper, limits_.lower }; auto distance = limits_.upper - limits_.lower; auto dx = distance / step_size_; return -calculate(dx); } else { auto distance = limits_.upper - limits_.lower; auto dx = distance / step_size_; return calculate(dx); } } // This will perform a second order of integration where the inner limits are defined // by [lower, y] where "upper" is not used directly. This may be expanded in the future... template&lt;typename ValueType&gt; constexpr ValueType doubleIntegral(Limits&lt;LimitType&gt; innerLimits) { // Currently the inner upper bound is not being used, if it is &lt;= lower bound, // it will default to lower bound + 1, just to ensure that an integration is // is calculated. Eventually this may be expanded to return true values // such as 0 when the lower and upper bounds are equal or the (-)integration if a &gt; b. if (innerLimits.upper &lt;= innerLimits.lower) innerLimits.upper = innerLimits.lower + static_cast&lt;LimitType&gt;(1); ValueType sum = 0; ValueType dy = (ValueType)(limits_.upper - limits_.lower) / step_size_; for (size_t i = 0; i &lt; step_size_; i++) { ValueType yi = (ValueType)(limits_.lower + i * dy); ValueType dx = (yi - innerLimits.lower) / step_size_; Integrator inner{ innerLimits, step_size_, integrand_ }; sum += inner.calculate(dx) * dy; } return sum; } private: template&lt;typename ValueType&gt; constexpr auto calculate(ValueType dx) -&gt; std::enable_if_t&lt;std::is_invocable_v&lt;Func&amp;, ValueType&amp;&gt;, ValueType&gt; { ValueType result = 0.0; for (size_t i = 0; i &lt; step_size_; ++i) { auto dy = integrand_(limits_.lower + i * dx); auto area = dy * dx; result += area; } return result; } }; </code></pre> <p><strong>main.cpp</strong></p> <pre><code>#include &lt;iostream&gt; #include &lt;exception&gt; #include &lt;cmath&gt; #include "Integrator.h" constexpr double PI = 3.14159265358979; double funcA0(double x) { return x; } template &lt;typename T&gt; constexpr T funcA(T x) { return x; } template &lt;typename T&gt; constexpr T funcB(T x) { return x * x; } template &lt;typename T&gt; T funcC(T x) { return sin(x); } template &lt;typename T&gt; constexpr T funcD(T x) { return (0.5*(x*x) + (3 * x) - (1 / x)); } double funcE(double x) { return cos(x); } int main() { try { std::cout &lt;&lt; "Integration of f(x) = x from a=3.0 to b=3.0 with an expected output of 0\n"; std::cout &lt;&lt; "Testing non template function object\n"; Integrator integratorA0A{ Limits{3.0, 3.0}, 10000, funcA0 }; std::cout &lt;&lt; integratorA0A.evaluate() &lt;&lt; '\n'; std::cout &lt;&lt; "Testing non template function object by reference\n"; Integrator integratorA0B{ Limits{3.0, 3.0}, 10000, &amp;funcA0 }; std::cout &lt;&lt; integratorA0B.evaluate() &lt;&lt; '\n'; std::cout &lt;&lt; "Testing function template object\n"; Integrator integratorA0C{ Limits{3.0, 3.0}, 10000, funcA&lt;double&gt; }; std::cout &lt;&lt; integratorA0C.evaluate() &lt;&lt; '\n'; std::cout &lt;&lt; "Testing function template object by reference\n"; Integrator integratorA0D{ Limits{3.0, 3.0}, 10000, &amp;funcA&lt;double&gt; }; std::cout &lt;&lt; integratorA0D.evaluate() &lt;&lt; '\n'; std::cout &lt;&lt; "\nIntegration of f(x) = x from a=3.0 to b=5.0 with an expected output of 8\n"; std::cout &lt;&lt; "Testing non template function object\n"; Integrator integratorA1A{ Limits{3.0, 5.0}, 10000, funcA0 }; std::cout &lt;&lt; integratorA1A.evaluate() &lt;&lt; '\n'; std::cout &lt;&lt; "Testing non template function object by reference\n"; Integrator integratorA1B{ Limits{3.0, 5.0}, 10000, &amp;funcA0 }; std::cout &lt;&lt; integratorA1B.evaluate() &lt;&lt; '\n'; std::cout &lt;&lt; "Testing function template object\n"; Integrator integratorA1C{ Limits{3.0, 5.0}, 10000, funcA&lt;double&gt; }; std::cout &lt;&lt; integratorA1C.evaluate() &lt;&lt; '\n'; std::cout &lt;&lt; "Testing function template object by reference\n"; Integrator integratorA1D{ Limits{3.0, 5.0}, 10000, &amp;funcA&lt;double&gt; }; std::cout &lt;&lt; integratorA1D.evaluate() &lt;&lt; '\n'; std::cout &lt;&lt; "\nIntegration of f(x) = x from a=5.0 to b=3.0 with an expected output of -8\n"; std::cout &lt;&lt; "Testing non template function object\n"; Integrator integratorA2A{ Limits{5.0, 3.0}, 10000, funcA0 }; std::cout &lt;&lt; integratorA2A.evaluate() &lt;&lt; '\n'; std::cout &lt;&lt; "Testing non template function object by reference\n"; Integrator integratorA2B{ Limits{5.0, 3.0}, 10000, &amp;funcA0 }; std::cout &lt;&lt; integratorA2B.evaluate() &lt;&lt; '\n'; std::cout &lt;&lt; "Testing function template object\n"; Integrator integratorA2C{ Limits{5.0, 3.0}, 10000, funcA&lt;double&gt; }; std::cout &lt;&lt; integratorA2C.evaluate() &lt;&lt; '\n'; std::cout &lt;&lt; "Testing function template object by reference\n"; Integrator integratorA2D{ Limits{5.0, 3.0}, 10000, &amp;funcA&lt;double&gt; }; std::cout &lt;&lt; integratorA2D.evaluate() &lt;&lt; '\n'; std::cout &lt;&lt; "\n\nIntegration of f(x) = x^2 from a=2.0 to b=20.0 with an expected output of 2664\n"; Integrator integratorB{ Limits{2.0, 20.0}, 10000, &amp;funcB&lt;double&gt; }; std::cout &lt;&lt; integratorB.evaluate() &lt;&lt; '\n'; std::cout &lt;&lt; "\n\nIntegration of f(x) = sin(x) from a=0.0 to b=" &lt;&lt; PI &lt;&lt; " with an expected output of 2\n"; Integrator integratorC{ Limits{0.0, PI}, 10000, &amp;funcC&lt;double&gt; }; std::cout &lt;&lt; integratorC.evaluate() &lt;&lt; '\n'; std::cout &lt;&lt; "\n\nIntegration of f(x) = (1\\2)x^2 + 3x - (1\\x) from a=1.0 to b=10.0 \nwith an expected output of 312.6974\n"; Integrator integratorD{ Limits{1.0, 10.0 }, 10000, &amp;funcD&lt;double&gt; }; std::cout &lt;&lt; integratorD.evaluate() &lt;&lt; '\n'; std::cout &lt;&lt; "\n\nTesting Double Integration of f(x) = (1\\2)x^2 + 3x - (1\\x) from [3,5] and [1,y]\nwith an expected output of 65.582\n"; Integrator integrator2D{ Limits{3, 5}, 10000, &amp;funcD&lt;double&gt; }; std::cout &lt;&lt; integrator2D.doubleIntegral&lt;double&gt;(1.0) &lt;&lt; '\n'; std::cout &lt;&lt; "\n\nTesting Double Integration of f(x) = cos(x) from [0," &lt;&lt; PI / 2 &lt;&lt; "] and [0.25,y]\nwith an expected output of 0.61137\n"; Integrator integratorE{ Limits{0.0, PI / 2}, 10000, &amp;funcE }; std::cout &lt;&lt; integratorE.doubleIntegral&lt;double&gt;(0.25) &lt;&lt; '\n'; } catch (const std::exception&amp; e) { std::cerr &lt;&lt; e.what() &lt;&lt; std::endl; return EXIT_FAILURE; } return EXIT_SUCCESS; } </code></pre> <p><strong>Output</strong></p> <pre><code>Integration of f(x) = x from a=3.0 to b=3.0 with an expected output of 0 Testing non template function object 0 Testing non template function object by reference 0 Testing function template object 0 Testing function template object by reference 0 Integration of f(x) = x from a=3.0 to b=5.0 with an expected output of 8 Testing non template function object 7.9998 Testing non template function object by reference 7.9998 Testing function template object 7.9998 Testing function template object by reference 7.9998 Integration of f(x) = x from a=5.0 to b=3.0 with an expected output of -8 Testing non template function object -7.9998 Testing non template function object by reference -7.9998 Testing function template object -7.9998 Testing function template object by reference -7.9998 Integration of f(x) = x^2 from a=2.0 to b=20.0 with an expected output of 2664 2663.64 Integration of f(x) = sin(x) from a=0.0 to b=3.14159 with an expected output of 2 2 Integration of f(x) = (1\2)x^2 + 3x - (1\x) from a=1.0 to b=10.0 with an expected output of 312.6974 312.663 Testing Double Integration of f(x) = (1\2)x^2 + 3x - (1\x) from [3,5] and [1,y] with an expected output of 65.582 65.5725 Testing Double Integration of f(x) = cos(x) from [0,1.5708] and [0.25,y] with an expected output of 0.61137 0.611325 </code></pre> <hr> <hr> <p><strong>List of Fixed Issues:</strong></p> <ul> <li>I removed the default destructor</li> <li>I removed the unnecessary member variables and their equivalent functions. <ul> <li>I'm now caching them on the stack.</li> </ul></li> <li>I removed the member function from the <code>Limits</code> struct.</li> <li>I also removed the <code>swap</code> from the limits. <ul> <li>if <code>a==b</code> then the integral is <code>0</code> and </li> <li>if <code>a&gt;b</code> then the integral is <code>(-)</code> the integral from <code>b to a</code>.</li> <li>These checks for the limits of integration I moved into the <code>Integrator</code> class.</li> </ul></li> <li>I tried to make sure everything follows <code>RAII</code>.</li> <li>The class now works in a <code>constexpr</code> context provided the function objects are <code>constexpr</code>.</li> <li>I moved the loop calculations for the approximation from the <code>evaluate</code> function and moved it in its own private member function.</li> <li>I'm using <code>{}</code> initialization for all object instantiations.</li> <li>I templated both classes.</li> <li>I can also pass in a function object that is also templated.</li> </ul> <hr> <p>All of the changes to my classes are all based on the advice of the user <code>Emma X</code>. I did take some of the advice from user <code>sudo-rm-rf-slash</code> in that I read up on the links that they had provided. As for changing the structure of the code from a <code>class</code> to be just a set of <code>functions</code> I did not. I have my own reasons why I want this to be a class object. I plan on expanding this later for doing different types of integrations and I will need for this class to keep track of its integrand and its limits of integration.</p> <p>Yes, I do understand that the current implementation is based on <code>Riemann Sums</code>. This is the intentional base structure of my class since it is the simplest form in approximate integrals. Eventually, I plan on expanding this to incorporate different methods and algorithms. These will be in the form of member functions naming them according to their algorithm. </p> <hr> <p><strong>Other changes that were made:</strong></p> <ul> <li>I renamed <code>integrate</code> to <code>doubleIntegral</code></li> <li>I also changed its signature to take a <code>Limits</code> struct instead of 2 individual parameters.</li> <li>I also removed the local <code>innerLimits</code> variable since it is now being passed in, and just updated it accordingly if needed.</li> <li>In both the <code>evaluate</code> and <code>doubleIntegral</code> function, I have early returns if the limits are equal.</li> <li>I only have a check to see if <code>a &gt; b</code> for the 1st order integration to return the <code>(-)</code>integral. I did not apply this behavior to the <code>doubleIntegral</code> function yet.</li> <li>I removed a lot of unnecessary local variables in my functions and inlined many of the calculations.</li> <li>Finally I added a sanity check to make sure that the template argument that is passed into the construct is an <code>invokable</code> object.</li> <li>The last of the changes, I modified my driver program slightly to show different cases of the same function being used in different contexts and to show the results when the limits are equal, less than and greater than... and I added a second example of a double integration using a trig function. </li> </ul> <hr> <hr> <p><strong>Where Do I go from here?</strong></p> <ul> <li>I'd like to know how to incorporate the <code>innerLimit</code>'s <code>upper</code> into the calculations when calculating <code>doubleIntegral</code>.</li> <li>I'd like to know if there is any room for improvements, efficiency, readability, portability, etc.</li> <li>Are there still any existing code smells? <ul> <li><em>-Note-</em> I mentioned this in the previous post, I'm not concerned with <code>namespace</code>, that can be done at any time!</li> </ul></li> <li>User: <code>Emma X</code> had mentioned the use of <code>[[nodiscard]]</code> however, I'm not familiar with its use... I've never really used that feature of C++ before. It is new to me.</li> <li>I have not yet tried to use <code>lambdas</code> within this code yet as that is on my todo list.</li> <li>I would also like to be able to add in the ability or the concept to incorporate <code>infinity</code> as the limits of integration and since this is a numerical type integrator, only the upper or lower bound can go to either + or - infinity, but not both. I'm not at the stage of returning back a family of functions with a constant of integration... That's a little beyond my skills at the moment since that would involved a function lookup table and an extensive parser. </li> </ul> <p>Let me know what you think, I look forward to your advice, constructive criticism, opinions, positions, and all feedback is welcomed!</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-03T21:26:27.080", "Id": "477650", "Score": "1", "body": "How do you argue that initializing the loop variable before the `for`-loop helps with optimization? It [compiles to the same assembly](https://godbolt.org/z/2Uiztn), but your way is worse in terms of readability and scoping." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-03T23:17:11.393", "Id": "477663", "Score": "0", "body": "@EmmaX Well, it may not make a difference these days, compilers have improved quite a bit, but I only have to declare and initialize it once outside the loop, then just iterate through the loop. This is an old trick going back to when I first started learning the C/C++ languages... These days, the compilers will probably optimize it anyway... Then again this trick is commonly used for extreme efficiency when working with \"nested loops\" and it usually pertains to the inner loop's counter." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-04T01:20:35.320", "Id": "477665", "Score": "2", "body": "@EmmaX After thinking about it for a little while, yeah it's not necessary to have the counters outside of the for loops... If there were to be any kind of gain it would be minimal at best and the tradeoff for readability simply outweighs it. So I reverted my code to put them back in their respective for loops and I removed the highlighted bullet that mentions them." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-03T19:35:19.867", "Id": "243339", "Score": "4", "Tags": [ "c++", "performance", "algorithm", "c++17", "numerical-methods" ], "Title": "Integrator 2.0: A Simple Integrator in C++17" }
243339
<p>I am new to Python and following tutorials. This one I came across was for TKinter, and throughout I felt I re-wrote the same lines of code time and time again which I wondered if it could be better written.</p> <p>I am interested to know how you would improve this code.</p> <p>Thanks.</p> <p>(First time posting, hope it's ok).</p> <pre><code>from tkinter import * from PIL import ImageTk, Image root = Tk() root.title("Learn to code") root.iconbitmap("C:\\palmTree.ico") #random images my_img1 = ImageTk.PhotoImage(Image.open("C:\\mountainLake.jpg")) my_img2 = ImageTk.PhotoImage(Image.open("C:\\freedom.jpg")) my_img3 = ImageTk.PhotoImage(Image.open("C:\\streetCoffee.jpg")) my_img4 = ImageTk.PhotoImage(Image.open("C:\\surfBoarding.jpg")) my_img5 = ImageTk.PhotoImage(Image.open("C:\\oldFence.jpg")) image_list = [my_img1, my_img2, my_img3, my_img4, my_img5] my_label = Label(image=my_img1) my_label.grid(row=0,column=0,columnspan=3) def forward(image_number): global my_label global button_forward global button_back my_label.grid_forget() my_label = Label(image=image_list[image_number-1]) button_forward = Button(root, text="&gt;&gt;", command=lambda: forward(image_number+1)) button_back = Button(root, text="&lt;&lt;", command=lambda: back(image_number-1)) if image_number == 5: button_forward = Button(root, text = "&gt;&gt;", state=DISABLED) my_label.grid(row=0,column=0,columnspan=3) button_back.grid(row=1, column=0) button_forward.grid(row=1, column=2) def back(image_number): global my_label global button_forward global button_back my_label.grid_forget() my_label = Label(image=image_list[image_number-1]) button_forward = Button(root, text="&gt;&gt;", command=lambda: forward(image_number+1)) button_back = Button(root, text="&lt;&lt;", command=lambda: back(image_number-1)) if image_number == 1: button_back = Button(root, text = "&lt;&lt;", state=DISABLED) my_label.grid(row=0,column=0,columnspan=3) button_back.grid(row=1, column=0) button_forward.grid(row=1, column=2) button_back = Button(root, text="&lt;&lt;", command=back, state=DISABLED) button_quit = Button(root, text="Quit", command=root.quit) button_forward = Button(root, text="&gt;&gt;", command=lambda: forward(2)) button_back.grid(row=1, column=0) button_quit.grid(row=1, column=1) button_forward.grid(row=1, column=2) root.mainloop() <span class="math-container">```</span> </code></pre>
[]
[ { "body": "<h2>Specific suggestions</h2>\n\n<ol>\n<li>Usually when you find yourself numbering variables it's time to put all of them in an iterable of some sort. In your case I would simply inline <code>my_img1</code> etc. into <code>image_list</code>.</li>\n<li>Usually names like <code>images</code> would be used instead of <code>image_list</code>. Python is a duck typed language, so it doesn't really matter which type of iterable you use for the code which does the iterating.</li>\n<li><p>Rather than running the main code like <code>root.mainloop()</code> the Pythonic way to do it is this:</p>\n\n<pre><code>if __name__ == \"__main__\":\n main()\n</code></pre>\n\n<p>This ensures that the code doesn't run when importing from your file, making it possible to import into a bigger program.</p></li>\n<li>Importing <em>everything</em> from a module is considered an antipattern - it makes it easier to end up with name collisions and it makes it harder to see at a glance where something was imported from.</li>\n<li>Refer to existing data structures whenever possible. One example is <code>if image_number == 5</code>, which would be better as <code>if image_number == len(image_list)</code>.</li>\n<li>Avoid doing unnecessary work. For example, you create an object and assign it to <code>button_forward</code>, then you check whether you have to create a <em>different</em> object to assign to the same variable, in which case the original work was wasted (or in the worst case, had detrimental side effects). I would instead use an <code>if</code>/<code>else</code> to assign <code>button_forward</code> only once.</li>\n<li><code>global</code>s are considered a big code smell these days. A preferable pattern is to pass around exactly the values which each function/method needs. That way the code is much easier to debug. In fact, this is pretty much the perfect example of something which should be encapsulated in one or more classes. That way you have a natural place to keep track of state like <code>image_number</code>, and won't have to pass it around between methods.</li>\n<li>It doesn't seem like a stretch that the images would be the user input to this application. If so it would be better to provide them using <a href=\"https://docs.python.org/3/library/argparse.html\" rel=\"nofollow noreferrer\"><code>argparse</code></a>.</li>\n</ol>\n\n<h2>Tool support suggestions</h2>\n\n<ol>\n<li><a href=\"https://github.com/ambv/black\" rel=\"nofollow noreferrer\"><code>black</code></a> can automatically format your code to be more idiomatic. It'll do things like adjusting the vertical and horizontal spacing, while keeping the functionality of the code unchanged.</li>\n<li><p><a href=\"https://gitlab.com/pycqa/flake8\" rel=\"nofollow noreferrer\"><code>flake8</code></a> can give you hints to write idiomatic Python. I would start with this configuration:</p>\n\n<pre><code>[flake8]\nmax-complexity = 4\nignore = W503,E203\n</code></pre></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-04T05:15:54.480", "Id": "243360", "ParentId": "243340", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-03T20:03:29.430", "Id": "243340", "Score": "5", "Tags": [ "python", "tkinter" ], "Title": "A Python Tkinter GUI which you can flick between images" }
243340
<p>I had this question in an interview recently. Given a sorted array of integers, return a list of those integers squared, with the squares sorted. So given an array of these numbers:</p> <pre><code>-5, -3, 1, 2, 4 </code></pre> <p>the result should be this:</p> <pre><code>1 4 9 16 25 </code></pre> <p>I came up with this solution using Java 8 streams, but is there a way to do this without the call to <code>Array.sort</code>?</p> <pre><code>public static int[] sortedSquares(int[] arr) { arr = Arrays.stream(arr).map(i -&gt; i * i).toArray(); Arrays.sort(arr); return arr; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-04T01:20:49.323", "Id": "477666", "Score": "3", "body": "Yes, there is a linear solution. Find the minimal element. Its square is guaranteed to be minimal. Now think of two indices traversing the array to the left and to the right from the minimal element, producing squares in a desired order." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-04T01:33:57.520", "Id": "477667", "Score": "0", "body": "In the example, the minimal element of the original array is -5, but its square is +25, which is not the minimal square (which would be +1 squared = 1), so how would this work?. (The original array is guaranteed to be sorted, by the way. At least that's the way the problem was stated to me.)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-04T01:40:37.960", "Id": "477668", "Score": "2", "body": "Sorry, minimal `abs`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-04T17:33:11.267", "Id": "477724", "Score": "0", "body": "@vnp no need for `abs`, just take the first nonnegative element and see how its sum with its previous element compares to zero." } ]
[ { "body": "<p>One way to be more concise is to use the <code>Stream.sorted()</code> method right in the stream:</p>\n\n<pre><code>public static int[] sortedSquares(int[] arr) {\n arr = Arrays.stream(arr).map(i -&gt; i * i).sorted().toArray();\n return arr;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-04T11:10:27.263", "Id": "477692", "Score": "0", "body": "At this point is there any point in not just using `return Arrays.`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-04T12:29:18.393", "Id": "477694", "Score": "1", "body": "Yes that's viable." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-04T01:47:09.483", "Id": "243353", "ParentId": "243349", "Score": "0" } }, { "body": "<p>For an interview, this is bad code. It is <span class=\"math-container\">\\$O(n \\log n)\\$</span>. But it can be done in <span class=\"math-container\">\\$O(n)\\$</span> time. Your code does not show your skills in that direction. Also, many interviewers (justifiably) will be unhappy for using streams. Streams may look cute but at scale like Gmail, they cause performance problems.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-09T04:44:42.483", "Id": "481512", "Score": "0", "body": "How would you code this so it's \\$O(n)\\$?" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-29T15:05:39.203", "Id": "244715", "ParentId": "243349", "Score": "2" } } ]
{ "AcceptedAnswerId": "243353", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-04T00:05:18.940", "Id": "243349", "Score": "5", "Tags": [ "java", "algorithm", "interview-questions", "stream" ], "Title": "Sorting squares of an integer array" }
243349
<p>I started learning from the book: head first design patterns. As I am trying out different programs in the book, I am compiling them in this one demo app. Below is the code for its driver function. Can anyone guide me with any improvements to the program (related to style, programming, formatting, how to test, is it better to have try/catch/finally or throw exceptions and stuff like that or anything else) in this driver code?</p> <p><strong>Demo Driver Code:</strong></p> <pre><code>package com.aviralgarg; import java.util.Scanner; import static com.aviralgarg.strategy.Main.runDuckSimulator; public class Main { public static void main(String[] args) { try { demoLoop(); } catch (Exception e) { e.printStackTrace(); } finally { System.err.println("Something went horribly wrong!"); } } private static void demoLoop() { while (true) { showOptions(); Scanner scanner = new Scanner(System.in); int option = scanner.nextInt(); switch (option) { case 0 -&gt; System.exit(0); case 1 -&gt; showDesignPrinciples(); case 2 -&gt; runDuckSimulator(); default -&gt; System.err.println("Please select a valid option."); } showHorizontalLine(); } } private static void showHorizontalLine() { System.out.println("------------------------------------------------------------------------------------"); } private static void showOptions() { System.out.println("\nPick one of the following options:" + "\n\t1. Show design principles" + "\n\t2. Strategy pattern - Run the Duck Simulator" + "\n\t0. Exit"); } private static void showDesignPrinciples() { System.out.println("Design Principles:" + "\n1. Identify the aspects of your application that vary and separate them from what stays the same." + "\n2. Program to an interface, not an implementation." + "\n3. Favor composition over inheritance." + "\n\n"); } } </code></pre> <p>Entire repository can be found here: <a href="https://github.com/aviral-garg/design-patterns" rel="nofollow noreferrer">https://github.com/aviral-garg/design-patterns</a>. Any improvement in rest of those functions would be appreciated as well. Or I can just ask a separate question for that since the strategy design pattern is split into several different files and is quite abstracted away from this driver code.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-04T04:44:16.557", "Id": "477674", "Score": "0", "body": "your question here doesn provide any desgin pattern - your implemention of the *Stratgey Pattern* is hidden beneath the `com.aviralgarg.strategy` package - maybe you post them in a follow up question?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-04T06:30:03.907", "Id": "477677", "Score": "0", "body": "You should post all the source files. Please read the rules." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-04T22:08:07.323", "Id": "477746", "Score": "0", "body": "Thanks for the advice from both of you. Now I am only asking for improvement only on this driver code. And I will be asking for review on my code for strategy and other design patterns in separate questions for better communication." } ]
[ { "body": "<p><strong>main</strong></p>\n\n<p>It is not considered good practice to just catch <em>every</em> possible exception like this. You should always specify which exceptions are possible and should be catched. In this specific case, the <code>try-catch</code>-statement is not necessary at all, because you are catching all possible exceptions in <code>demoLoop</code> already:</p>\n\n<pre><code>public static void main(String[] args) {\n demoLoop();\n}\n</code></pre>\n\n<p><strong>demoLoop</strong></p>\n\n<p>Are you trusting the user with making correct inputs? If the user does enter a String instead of a number, your program will crash. You can solve this problem by using the following snippet:</p>\n\n<pre><code>private static void demoLoop() {\n Scanner scanner = new Scanner(System.in);\n showOptions();\n int option;\n while(true) {\n try {\n option = scanner.nextInt();\n if(option &gt; 2 || option &lt; 0) {\n throw new InputMismatchException();\n }\n break;\n }\n catch(InputMismatchException e) {\n System.out.println(\"Enter 0, 1 or 2!\");\n scanner.nextLine();\n }\n }\n}\n</code></pre>\n\n<p>(don't forget to <code>import java.util.InputMismatchException;</code>)</p>\n\n<p>I also don't like the way how you use the <a href=\"https://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html\" rel=\"nofollow noreferrer\">switch-case</a>-statement, but this is probably just a matter of taste. I prefer the standard way:</p>\n\n<pre><code>switch (option) {\n case 0 : \n System.exit(0);\n break;\n case 1 : \n showDesignPrinciples();\n break;\n case 2 : \n runDuckSimulator();\n break;\n default : \n System.err.println(\"Please select a valid option.\");\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-05T19:53:28.207", "Id": "243441", "ParentId": "243351", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-04T00:38:33.677", "Id": "243351", "Score": "4", "Tags": [ "java", "console" ], "Title": "command-line demo app" }
243351
<p>The following bash script was made to retrieve some local repository information in order to be used to display a condensed <code>git status</code> in terminal PS1 prompt.</p> <p>It performs some simple greps over (<code>git status</code>) <code>--short</code> version text to display 6 repository status: <strong>Commits ahead, commits behind, added files, modifiled files, untracked files and deleted files</strong></p> <pre><code>#!/bin/bash if [[ $(find .git 2&gt; /dev/null | wc -l) &gt; 0 ]]; then local branch="$(git branch | grep '*' | cut -d ' ' -f 2)" local remote="$(git remote)/$branch" local status="" # Commits ahead local ahead=$(git rev-list --count $remote..$branch) [[ $ahead &gt; 0 ]] &amp;&amp; status="$status ⭑$ahead" # Commits behind local behind=$(git rev-list --count $branch..$remote) [[ $behind &gt; 0 ]] &amp;&amp; status="$status !$behind" # Added files A=$(git status -s | grep -Pc "^[RAM]..") [[ $A &gt; 0 ]] &amp;&amp; status="$status +$A" # Modifiled files M=$(git status -s | grep -Pc "^.M.") [[ $M &gt; 0 ]] &amp;&amp; status="$status ~$M" # Untracked files U=$(git status -s | grep -c "?? ") [[ $U &gt; 0 ]] &amp;&amp; status="$status ·$U" # Deleted files D=$(git status -s | grep -Pc "^.D.") [[ $D &gt; 0 ]] &amp;&amp; status="$status -$D" echo "$branch$status" fi </code></pre> <p>By now, I'm actually using this code inside a <code>.bashrc</code> function and, accordingly calling it through my PS1 variable:</p> <p><a href="https://i.stack.imgur.com/SLEOg.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/SLEOg.png" alt="enter image description here"></a></p> <p>It would be nice to receive some code review about <code>grep</code> and <code>git</code> usage, <code>bash</code> organization, syntax, readability and other improvements. I'm also interested in best practices over have function calls from PS1.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-04T01:33:08.227", "Id": "243352", "Score": "1", "Tags": [ "beginner", "algorithm", "bash", "git" ], "Title": "A simple git_status to prompt" }
243352
<p>I wrote some code that reads the output of the <code>rcon users</code> command on the CS 1.6 console. It then notifies me of any players that are not in my whitelist.csv or are in my blacklist. The program requires 3 files as inputs:</p> <ol> <li>A text file containing the raw output of the <code>rcon users</code> command on CS 1.6 console.</li> <li>A CSV file containing the SteamID and name of the white-listed players.</li> <li>A CSV file containing the SteamID and name of the black-listed players.</li> </ol> <pre><code>#!/usr/bin/env python3 import csv import re class WhiteListVerifier: """ Class to check if non-white-listed players are playing CS. """ def __init__(self, users_filepath, whitelist_filepath, blacklist_filepath): """ Get filepaths and load the following files: users file , whitelist file and blacklist file users_filepath: Path to a text file which contains the raw output of the 'rcon users' in the in-game console. whitelist_filepath: Path to a csv file which contains Steam IDs and player-names of the white-listed players. blacklist_filepath: Path to a csv file which contains Steam IDs, player-names and alert-message for the black-listed players. """ with open(users_filepath) as f: self.users_rawcontents = f.read() self.whitelist = list(csv.DictReader(open(whitelist_filepath))) self.blacklist = list(csv.DictReader(open(blacklist_filepath))) def get_playername(self, steamid, player_records): """ Function to return name of a person if steamid exits in given records and return 'Unknown' otherwise. """ for player in player_records: if steamid == player['Steam_ID']: return player['Player_Name'] return 'Unknown' def get_active_users_steamids(self): """ Function to extract the Steam IDs using output of 'rcon users' command. """ active_users_steamids = re.findall(r'STEAM_[0-5]:[01]:\d+', self.users_rawcontents) return active_users_steamids def verify_steamids(self): """ Function to alert if people other than the ones mentioned in the whitelist are playing. """ active_users_steamids = self.get_active_users_steamids() num_nonwhitelisted_users = 0 for active_user in active_users_steamids: player = self.get_playername(active_user, self.whitelist) if player is 'Unknown': num_nonwhitelisted_users += 1 nonwhitelisted_playername = self.get_playername(active_user, self.blacklist) print('-- nonwhitelisted player: '+str(nonwhitelisted_playername)) print('&gt;&gt; Total number of non-whitelisted players: '+str(num_nonwhitelisted_users)) if __name__ == '__main__': checker = WhiteListVerifier('data/users.txt', 'data/whitelist.csv', 'data/blacklist.csv') checker.verify_steamids() </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-04T07:38:16.277", "Id": "477686", "Score": "0", "body": "Why is there both a blacklist and whitelist? What does it mean for a player to neither be on the whitelist nor blacklist?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-04T08:23:15.260", "Id": "477689", "Score": "0", "body": "Whitelist is for people with whom I play regularly. Blacklist is for people that I don't want to play with. And if I see a new id which is neither on my whitelist or blacklist, I'll ask them if I know them personally." } ]
[ { "body": "<p>This works, but is essentially O(N**2); you can make it O(N) fairly easily by turning your whitelist/blacklist into dicts:</p>\n\n<pre><code>def __init__(self, users_filepath, whitelist_filepath, blacklist_filepath):\n \"\"\"\n Get filepaths and load the following files: users file , whitelist file and blacklist file\n\n users_filepath: Path to a text file which contains the raw output of the 'rcon users' in the in-game console.\n whitelist_filepath: Path to a csv file which contains Steam IDs and player-names of the white-listed players.\n blacklist_filepath: Path to a csv file which contains Steam IDs, player-names and alert-message for the black-listed players.\n \"\"\"\n with open(users_filepath) as f:\n self.users_rawcontents = f.read()\n raw_whitelist = list(csv.DictReader(open(whitelist_filepath)))\n raw_blacklist = list(csv.DictReader(open(blacklist_filepath)))\n self.whitelist = { p['Steam_ID']: p for p in raw_whitelist }\n self.blacklist = { p['Steam_ID']: p for p in raw_blacklist }\n\ndef get_playername(self, steamid, player_records):\n \"\"\"\n Function to return name of a person if steamid exits in given records \n and return 'Unknown' otherwise.\n \"\"\"\n return player_records.get(steamid, 'Unknown')\n</code></pre>\n\n<p>So instead of iterating over the entire list of player_records every time you look someone up, it iterates over your whitelist and blacklist each <em>once</em> at startup-time, making them thereafter be O(1) to search by steamid (which is the only kind of search you ever do).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-04T19:46:57.960", "Id": "477736", "Score": "1", "body": "Thanks a lot! I really should have thought about using hash maps instead of iterating over a list over and over to find something. Again, thanks! I appreciate it." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-04T19:02:02.023", "Id": "243392", "ParentId": "243355", "Score": "2" } } ]
{ "AcceptedAnswerId": "243392", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-04T02:20:27.030", "Id": "243355", "Score": "2", "Tags": [ "python", "python-3.x", "steam" ], "Title": "Steam whitelist checker for CS 1.6" }
243355
<p>I have built this Generic Graph traverser, I have this implemented with DFS, I feel it will work equally fine with BFS too. </p> <p><em>What do you think of this implementation?</em> </p> <p>I want help in reviewing the <code>Visitor</code> interface. Should I have Generics in it or just use the base <code>Object</code>?</p> <pre><code>public abstract class GraphTraverser { protected final Visitor visitor; public GraphTraverser(Visitor visitor) { this.visitor = visitor; } public abstract void traverse(Object startNode); } </code></pre> <p><strong>Generic DFS</strong> </p> <pre><code>public class DepthFirstSearch extends GraphTraverser { public DepthFirstSearch(Visitor visitor) { super(visitor); } public void traverse(Object startNode) { visitor.reset(); traverse(startNode, 1); } private boolean traverse(Object obj, int nodeCount) { if (visitor.preVisit(obj, nodeCount)) { visitor.visit(obj, nodeCount); return true; } List&lt;? extends Object&gt; objs = visitor.getNeighbours(obj); visitor.visit(obj, nodeCount); for (Object o : objs) { if (traverse(o, nodeCount + 1)) { return true; } } visitor.postVisit(obj); return false; } } </code></pre> <p><strong>Visitor Interface</strong></p> <pre><code>import java.util.List; public interface Visitor { boolean preVisit(Object obj, int nodeVisitCount); void postVisit(Object obj); void visit(Object obj, int i); List&lt;? extends Object&gt; getNeighbours(Object obj); Object getResult(); void unVisit(Object obj); void reset(); } </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-04T02:41:49.333", "Id": "243356", "Score": "2", "Tags": [ "java", "algorithm", "design-patterns", "graph", "generics" ], "Title": "Generic Graph Traverser" }
243356
<p>Just for practice purposes, I written a basic client sided login/signup system that allows you to make an account, and then log into the account from my webpage. What it does is append to an object known as <code>database</code> for every new account made, and when you sign in, it loops through the database and see if your credentials match any account information.</p> <p>There's a couple of noticable problems with my script. One being that I believe that I didn't follow the DRY principle to the fullest. I felt like I repeated myself a couple of times, and wondering if that can be avoided. The second problem is that looping through the "database" object may not be the most efficient solution, especially since the longer the table, the longer it may take. There may be a solution that is more efficient in performance that I am unaware of.</p> <p>Other than that I would just like general feedback, tips, and red flags (if any) in my code. I am trying to improve myself as a JavaScript developer, and that requires feedback of my script from my peers.</p> <p>TL;DR: I am a new programmer, so sorry if this is a bad question or if I have terrible code. I am still learning.</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-js lang-js prettyprint-override"><code>const database = [] function usp(parent) { return [parent.username.value, parent.password.value] } window.onload = () =&gt; { const create = document.forms.createAcount; const log = document.forms.logIN; create.addEventListener('click', (e) =&gt; { if(e.target == create.submit){ const information = usp(create); database.push({user : information[0], pass : information[1]}); console.log(database) } }); log.addEventListener('click', (e) =&gt; { if (e.target == log.submit) { const information = usp(log); for (let x of database) { if (x.user == information[0] &amp;&amp; x.pass == information[1]) { alert(`You successfully logged into your account! Welcome to my website ${information[0]}`) } } } }) }</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>#createAcount { background-color: skyblue; } #logIN { background-color: lightgreen; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt;SignUp!&lt;/title&gt; &lt;link rel = "stylesheet" href = 'style.css'&gt; &lt;/head&gt; &lt;body&gt; &lt;h1&gt;Sign Up&lt;/h1&gt; &lt;form name = "createAcount" id = "createAcount"&gt; &lt;h1&gt;Create a Username&lt;/h1&gt; &lt;input type = 'text' placeholder="Falkyraizu" name = 'username' maxlength=20&gt; &lt;h1&gt;Create a password&lt;/h1&gt; &lt;input type = 'password' placeholder="password" name = 'password' maxlength=20&gt; &lt;h2&gt;Done&lt;/h2&gt; &lt;input class = 'reset' type = 'button' value = "Reset" name = 'reset'&gt; &lt;input class = 'submit' type = 'button' value = "Submit" name = 'submit'&gt; &lt;/form&gt; &lt;h1&gt;Log In&lt;/h1&gt; &lt;form name = "logIN" id = "logIN"&gt; &lt;h1&gt;What is your userName&lt;/h1&gt; &lt;input type = 'text' placeholder="Falkyraizu" name = "username" maxlength=20&gt; &lt;h1&gt;What is your password&lt;/h1&gt; &lt;input type = 'password' placeholder="password" name = "password" maxlength=20&gt; &lt;h2&gt;Done&lt;/h2&gt; &lt;input class = 'reset' type = 'button' value = "Reset" name = 'reset'&gt; &lt;input class = 'submit' type = 'button' value = "Submit" name = 'submit'&gt; &lt;/form&gt; &lt;script src = "script.js"&gt;&lt;/script&gt; &lt;/body&gt; &lt;/html&gt;</code></pre> </div> </div> </p> <p>Side Note: If you notice something else that can be fixed such as my HTML, you can also include it in your response, however I would still like my main problems fixed (read above if you missed it). Thanks for the help!</p>
[]
[ { "body": "<p>This code appears to be fairly clean and reduced well to me, I don't see much in the way of any DRY violations, but if you're looking for any places for tightening up your code:</p>\n\n<p>If you can use the newer javascript goodies, then use array <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment\" rel=\"nofollow noreferrer\">destructuring assignment</a> and <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer#Property_definitions\" rel=\"nofollow noreferrer\">object shorthand assignment</a></p>\n\n<p>Given</p>\n\n<pre><code>function usp(parent) {\n return [parent.username.value, parent.password.value];\n}\n</code></pre>\n\n<p>Then</p>\n\n<pre><code>const [user, pass] = usp(create);\ndatabase.push({ user, pass });\n</code></pre>\n\n<p>and use '==' with caution as it isn't strictly equal, it will attempt a type coercion, i.e. <code>'5' == 5</code> is true, where as '===' won't, i.e. <code>'5' === 5</code> is false. As a rule, you will almost <em>always</em> want to use '===', only reach for '==' when necessary.</p>\n\n<p><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators\" rel=\"nofollow noreferrer\">Comparison operators</a></p>\n\n<pre><code>const [user, pass] = usp(log);\nfor (const x of database) {\n if (x.user === user &amp;&amp; x.pass === pass) {\n ...\n }\n}\n</code></pre>\n\n<p>Looping through <em>any</em> data structure has an <code>O(n)</code> complexity, there's nothing really you can do here, but this is completely fine as any increases in data size is a linear increase in processing.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-04T05:56:30.480", "Id": "243361", "ParentId": "243358", "Score": "1" } } ]
{ "AcceptedAnswerId": "243361", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-04T03:12:51.710", "Id": "243358", "Score": "0", "Tags": [ "javascript", "beginner", "object-oriented", "html", "css" ], "Title": "Best method to further execute the DRY principle and/or raise performance in my script? (client login/signup system)" }
243358
<p>Suppose I have a vector containing n elements. I want to find out the number of previous elements greater than its element at present index <code>i</code>. I want to find <code>A[i] &gt; A[j] &amp;&amp; i &lt; j</code> for all elements of the vector.</p> <p>Constraints:</p> <pre><code>1 &lt;= t &lt;= 1000 1 &lt;= n &lt;= 10^5 1 &lt;= A[i] &lt;=10^5 </code></pre> <p>My code:</p> <pre><code>#include&lt;bits/stdc++.h&gt; using namespace std; int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); int t; cin &gt;&gt; t; while(t--) { int n,a,i,j; cin &gt;&gt; n; vector&lt;int&gt;v1; for(i=0;i&lt;n;i++) { cin &gt;&gt; a; v1.push_back(a); } int cnt=0,sum=0; for(i=0;i&lt;n;i++) { if( i!=0) { for(j=0;j&lt;i;j++) { if(v1[i]&lt;v1[j]) { cnt++; } } } // cout &lt;&lt; cnt &lt;&lt; " "; sum=sum+cnt; cnt=0; } cout &lt;&lt; sum &lt;&lt; '\n'; } } </code></pre> <p>This code is running fine for all the test cases except only one. It is showing the Time limit exceeded for one of the test cases. Can anyone help me?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-04T11:48:18.057", "Id": "477693", "Score": "0", "body": "What are `t` and `n`?" } ]
[ { "body": "<p>I don't think there is a logic error in what you have posted. And even though there are details that would make it nicer (the cycle can for example run from <code>i=1</code>, questionable use of <code>bits/stdc++.h</code> header, long variable scopes and similar), it should do its job.</p>\n\n<p>I suggest to think about time complexity of the algorithm. Your brute force approach will have quadratic complexity and may be too slow when the input is large.</p>\n\n<p>There are different approaches that you can try. For example, I see you tagged your post with <code>binary-search</code> tag. Why? You could for example keep your vector <strong>sorted</strong> as the user enters the values. When adding a new number, find where it belongs (you can do it by bisection - with logarithmic complexity). All numbers to the left are smaller, the ones on the right are larger. Then insert the number and repeat. How to do it exactly is up to you, if you're allowed to use C++ algorithms, <code>std::lower_bound</code> and <code>std::vector::insert</code> will do the hard work for you.</p>\n\n<p>You can of course craft some tree structure of your own to do something along those lines.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-04T12:50:26.800", "Id": "243373", "ParentId": "243363", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-04T06:14:06.627", "Id": "243363", "Score": "2", "Tags": [ "c++", "programming-challenge", "array", "time-limit-exceeded", "binary-search" ], "Title": "Count number of previous elements greater than its element at present index" }
243363
<p>I want to calculate the correlation time. First I calculate the auto-correlation function:</p> <p><span class="math-container">$$ \begin{align} \chi(t) = &amp;\frac{1}{t_{max}-t}\sum\limits_{t'=0}^{t_{max}-t}m(t')m(t'+t)\\ &amp;-\frac{1}{t_{max}-t}\sum\limits_{t'=0}^{t_{max}-t}m(t')\frac{1}{t_{max}-t}\sum\limits_{t'=0}^{t_{max}-t}m(t'+t)\\ &amp;\sim e^{-t/\tau} \end{align} $$</span></p> <p>The correlation-time can be calculated by fitting autocorrelation function. I.e., <span class="math-container">\$\chi(t)\$</span> in exponential. For this I have written the following code:</p> <pre><code>def autocorrelation(M): start_time = time.time() tau = 1 sweeps = len(M) auto = np.zeros(sweeps) for t in range(sweeps): some_time = sweeps-t first_term = np.average(M[:some_time]*M[t:sweeps]) S1 = np.average(M[:some_time]) S2 = np.average(M[t:sweeps]) auto_temp = first_term - S1*S2 if auto_temp &gt; 0: auto[t] = auto_temp else:#remove oscillating part break if auto[0] != 0: auto = auto[auto&gt;0] auto = auto/auto[0] #normalization len_auto = len(auto) if len_auto &gt; 1: #draw a straight line if you have atleast two points tau = int(-1/np.polyfit(np.arange(len_auto), np.log(auto), 1, w=np.sqrt(auto))[0]) tau = max(tau,1) logging.info(f"Correlation time = {tau}") return tau </code></pre> <p>If you put in list <code>M = m</code>, the function will calculate autocorrelation function and return correlation time, i.e, <span class="math-container">\$\tau\$</span> I also thought of using NumPy's <code>correlate</code> and <code>convolve</code>, but I could not understand them well. I tried <code>auto_convolve = numpy.convolve(m,m,mode = "same")</code>, after normalization, the <code>auto/auto[0]</code> was not same as <code>auto_convolve/auto_convolve[0]</code></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-04T22:07:01.567", "Id": "477745", "Score": "0", "body": "Please can you check the equation. Why do you have \\$\\frac{1}{t_{max}-t}\\$ twice in the second line of the equation and not just simplify to \\$\\frac{1}{(t_{max}-t)^2}\\$. Additionally please use parentheses in situations like the above it's unclear what is inside the Sigma, is that a nested Sigma?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-05T01:50:08.680", "Id": "477757", "Score": "0", "body": "It's because there are two averages in the second term. I tried putting parenthesis, but it showed error: `Your post appears to contain code that is not properly formatted as code.`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-05T03:20:15.120", "Id": "477758", "Score": "0", "body": "The second term in expression of \\$\\chi(t)\\$ is \\$\\bigg(\\frac{1}{t_{max}-t}\\sum\\limits_{t'=0}^{t_{max}-t}m(t')\\bigg)\\bigg(\\frac{1}{t_{max}-t}\\sum\\limits_{t'=0}^{t_{max}-t}m(t'+t)\\bigg)\\$." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-04T09:26:58.360", "Id": "243369", "Score": "1", "Tags": [ "python", "python-3.x", "numpy" ], "Title": "Calculation Correlation Time" }
243369
<p>I want to create a MVVM-C project, but also adequately test it. Naturally I want to create such a project that can access a Network Service.</p> <p>Any comments or thoughts on this approach?</p> <p>DependencyFactory:</p> <pre><code>protocol Factory { var networkManager: HTTPManagerProtocol { get } func makeInitialViewModel(coordinator: Coordinator) -&gt; InitialViewModel func makeInitialView(viewModel: InitialViewModel) -&gt; InitialView func makeDetailView(viewModel: DetailViewModel) -&gt; DetailView func makeDetailViewModel(coordinator: Coordinator) -&gt; DetailViewModel } // replace the DependencyContainer for tests class DependencyFactory: Factory { var networkManager: HTTPManagerProtocol = HTTPManager() // should not return an optional at the end of this project func makeInitialCoordinator() -&gt; ProjectCoordinator { let coordinator = ProjectCoordinator(factory: self) return coordinator } func makeInitialView(viewModel: InitialViewModel) -&gt; InitialView { let view = InitialView() return view } func makeInitialViewModel(coordinator: Coordinator) -&gt; InitialViewModel { let viewModel = InitialViewModel(coordinator: coordinator, networkManager: networkManager) return viewModel } func makeDetailView(viewModel: DetailViewModel) -&gt; DetailView { let view = DetailView() return view } func makeDetailViewModel(coordinator: Coordinator) -&gt; DetailViewModel { let viewModel = DetailViewModel(coordinator: coordinator, networkManager: networkManager) return viewModel } } </code></pre> <p>A basic HTTPManager (that doesn't really touch the network, but you get the point!)</p> <pre><code>protocol HTTPManagerProtocol { func get(url: URL, completionBlock: @escaping (Result&lt;Data, Error&gt;) -&gt; Void) } class HTTPManager: HTTPManagerProtocol { public func get(url: URL, completionBlock: @escaping (Result&lt;Data, Error&gt;) -&gt; Void) { DispatchQueue.main.asyncAfter(deadline: .now() + 2) { let data = Data(&quot;The Data from HTTPManager&quot;.utf8) completionBlock(.success(data)) } } } </code></pre> <p>Project Coordinator</p> <pre><code>protocol Coordinator: class { func start(_ navigationController: UINavigationController) func moveToDetail() } class ProjectCoordinator: Coordinator { var childCoordinators = [Coordinator]() var navigationController: UINavigationController? private var factory: Factory init(factory: Factory) { self.factory = factory } func start(_ navigationController: UINavigationController) { let vc = InitialViewController(factory: factory, coordinator: self) self.navigationController = navigationController navigationController.pushViewController(vc, animated: true) } func moveToDetail() { let vc = DetailViewController(factory: factory, coordinator: self) navigationController?.pushViewController(vc, animated: true) } } </code></pre> <p>InitialModel</p> <pre><code>struct InitialModel : Codable { let dataString : String } </code></pre> <p>InitialView</p> <pre><code>final class InitialView: UIView { let traverseButton = UIButton(type: .custom) let networkButton = UIButton(type: .custom) let networkLabel = UILabel() override init(frame: CGRect) { super.init(frame: frame) setup() } required init?(coder: NSCoder) { fatalError(&quot;init(coder:) has not been implemented&quot;) } private func setup() { self.backgroundColor = .red traverseButton.frame = CGRect(x: 0, y: 0, width: 200, height: 100) traverseButton.setTitle(&quot;Go to Detail&quot;, for: .normal) traverseButton.setTitleColor(.black, for: .normal) traverseButton.isUserInteractionEnabled = true self.addSubview(traverseButton) traverseButton.translatesAutoresizingMaskIntoConstraints = false traverseButton.centerXAnchor.constraint(equalTo: self.centerXAnchor).isActive = true traverseButton.centerYAnchor.constraint(equalTo: self.centerYAnchor).isActive = true networkButton.frame = CGRect(x: 0, y: 0, width: 200, height: 100) networkButton.setTitle(&quot;Make Network Call&quot;, for: .normal) networkButton.setTitleColor(.black, for: .normal) networkButton.isUserInteractionEnabled = true self.addSubview(networkButton) networkButton.translatesAutoresizingMaskIntoConstraints = false networkButton.centerXAnchor.constraint(equalTo: self.centerXAnchor).isActive = true networkButton.centerYAnchor.constraint(equalTo: self.centerYAnchor, constant: 100).isActive = true networkLabel.text = &quot;No network calls made&quot; networkLabel.backgroundColor = .purple self.addSubview(networkLabel) networkLabel.translatesAutoresizingMaskIntoConstraints = false networkLabel.centerXAnchor.constraint(equalTo: self.centerXAnchor).isActive = true networkLabel.centerYAnchor.constraint(equalTo: self.centerYAnchor, constant: 200).isActive = true networkLabel.widthAnchor.constraint(equalToConstant: 300).isActive = true networkLabel.heightAnchor.constraint(equalToConstant: 100).isActive = true } func setNetworkLabel(text: String){ networkLabel.text = text } } </code></pre> <p>InitialViewController</p> <pre><code>class InitialViewController: UIViewController { private var coordinator: Coordinator? private var factory: Factory? var intialView: InitialView? lazy var viewModel: InitialViewModel? = { return factory?.makeInitialViewModel(coordinator: coordinator!) }() init(factory: Factory, coordinator: Coordinator) { self.factory = factory self.coordinator = coordinator super.init(nibName: nil, bundle: nil) } required init?(coder: NSCoder) { fatalError(&quot;init(coder:) has not been implemented&quot;) } override func loadView() { if let initialView = factory?.makeInitialView(viewModel: viewModel!) { initialView.traverseButton.addTarget(self, action: #selector(traverseButton(_:)), for: .touchDown) initialView.networkButton.addTarget(self, action: #selector(networkButton), for: .touchDown) self.intialView = initialView self.view = initialView } } override func viewDidLoad() { super.viewDidLoad() } @IBAction func traverseButton(_ sender: UIButton) { coordinator?.moveToDetail() } @IBAction func networkButton(_ sender: UIButton) { viewModel?.fetchData(completion: { data in switch data { case .failure: fatalError() case .success(let data): if let data = data.first { self.intialView?.setNetworkLabel(text: data.dataString) } } }) } } </code></pre> <p>InitialViewModel</p> <pre><code>class InitialViewModel { private var networkManager: HTTPManagerProtocol? init(coordinator: Coordinator?, networkManager: HTTPManagerProtocol) { self.networkManager = networkManager } func fetchData(completion: @escaping (Result&lt;[InitialModel], Error&gt;) -&gt; Void) { networkManager?.get(url: URL(string: &quot;NOURL&quot;)!, completionBlock: { result in DispatchQueue.main.async { switch result { case .failure: completion(.failure(NSError())) case .success(let data): if let str = String(data: data, encoding: .utf8) { let model = InitialModel(dataString: str) completion(.success([model])) } } } }) } } </code></pre> <p>DetailViewController</p> <pre><code>class DetailViewController: UIViewController { weak var coordinator: Coordinator? private var factory: Factory? var detailView: DetailView? lazy var viewModel: DetailViewModel? = { return factory?.makeDetailViewModel(coordinator: coordinator!) }() init(factory: Factory, coordinator: Coordinator) { self.factory = factory self.coordinator = coordinator super.init(nibName: nil, bundle: nil) } required init?(coder: NSCoder) { fatalError(&quot;init(coder:) has not been implemented&quot;) } override func loadView() { if let detailView = factory?.makeDetailView(viewModel: viewModel!) { self.detailView = detailView self.view = detailView } } override func viewDidLoad() { super.viewDidLoad() } } </code></pre> <p>DetailViewModel</p> <pre><code>class DetailViewModel { private var networkManager: HTTPManagerProtocol? init(coordinator: Coordinator?, networkManager: HTTPManagerProtocol) { self.networkManager = networkManager } } </code></pre> <p>DetailView</p> <pre><code>final class DetailView: UIView { override init(frame: CGRect) { super.init(frame: frame) setup() } required init?(coder: NSCoder) { fatalError(&quot;init(coder:) has not been implemented&quot;) } private func setup() { self.backgroundColor = .blue } } </code></pre>
[]
[ { "body": "<h1>Factories/DI</h1>\n<p>Split into modules or something. For now OK, but if your app gets bigger and your single factory depends on everything it becomes rather hard to maintain. Could be as easy as adding extensions to your Factory protocol for every module. You still have everything in the same class, but your source code is more separated.</p>\n<p>makeInitialView, makeDetailView: Get rid of the viewModel parameter as it is not used. You might even consider directly creating your views in the view controller as they have no other dependencies.</p>\n<h1>Coordinators</h1>\n<p>You should split your Coordinator protocol into a abstract coordinator protocol and a protocol for the project coordinator. Like this each child coordinator you add to your ProjectCoordinator also needs to have a moveToDetail() method. This is probably not what you want.</p>\n<p>Passing the factory to the root coordinator is a good practice. Passing it on to the view controllers from there is not a good idea though. Better to have the factory create the View Controller itself. So you may want to add an <code>makeInitialViewController(coordinator: Coordinator) -&gt; InitialViewController</code> method.</p>\n<h1>View Controllers</h1>\n<p>As I said, they should not know about the factory. The properties for their dependencies (coordinator and factory) should not be optional. You cannot construct the ViewController without them (the init-parameters are not optional) so there is no need to deal with with the fact that they are optional.</p>\n<p>The exception might be the Coordinator, but it also should be weak. Currently you have a strong retain cycle here (ProjectCoordinator (1) -&gt; NavigationController -&gt; InitialViewController -&gt; ProjectCoordinator (1)). This does not matter, there will be no memory leak as the cycle will be broken at when the view controller is popped from the navigation stack. You can arrange this for every coordinator and get away with the cycles, but long-term it will be easier to just always use weak references from the view controller back to its coordinator. Its easy to forget breaking that cycle.</p>\n<p>You deal with the optionals by force-unwrapping (which in your case should be fine), but this makes the code really hard to understand. Every time you see the <code>!</code> you must mentally check whether this is OK or a crashing bug waiting to happen. If you are not careful and accept them as okay it is only a matter of time until you create a crash. If there is no choice but to force-unwrap something you should always add a comment that explains why it is not a problem.</p>\n<p>To support the lazy creation of the view model you might want to inject a <code>Provider</code> for your view model instead of the factory. This could be as simple as a closure: <code>typealias Provider&lt;T&gt; = () -&gt; T</code></p>\n<h1>Networking</h1>\n<p>You should add <code>[weak self]</code> in your callback closure. If the user navigates away from your screen before the request finishes you shouldn’t do any extra work to set up views that are not visible anyways. It would be even better to cancel the request when the user navigates away. No need to waste bandwidth for data the user is not going to see. But this depends on your exact flow and use case.</p>\n<p>Small things:</p>\n<p>Not really important, but here are some small things that should be fixed:</p>\n<p>You shouldnt create a NSError() like this. Even shows this message in the console:</p>\n<pre><code>-[NSError init] called; this results in an invalid NSError instance. It will raise an exception in a future release. Please call errorWithDomain:code:userInfo: or initWithDomain:code:userInfo:. This message shown only once.\n</code></pre>\n<p>Better just return <code>nil</code> in <code>required init?(coder: NSCoder)</code> than calling fatalError. You also can mark them as unavailable <code>@available(*, unavailable)</code> so you dont ahve to deal with that in subclasses.</p>\n<p>Activate all constraints at the same time using NSLayoutConstraint.activate([]) instead of activating each seperately.</p>\n<p>Remove your override-Methods if they do nothing but call super. Its just unneccesary clutter.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-11T16:26:55.823", "Id": "478380", "Score": "0", "body": "Thank you. Should the factory make the ViewModels, and pass them to the ViewControllers or should the ViewControllers create the ViewModels?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-12T16:26:36.353", "Id": "478526", "Score": "1", "body": "Most things should be created by the factory. If it needs any external dependencies it should be created by the factory. Otherwise the object that actually creates them needs those dependencies, even if it otherwise doesn’t need them. The whole point behind DI is that each object gets only the dependencies it needs." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-11T14:55:11.097", "Id": "243719", "ParentId": "243371", "Score": "5" } } ]
{ "AcceptedAnswerId": "243719", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-04T10:42:38.187", "Id": "243371", "Score": "2", "Tags": [ "swift" ], "Title": "MVVM-C Swift with Dependency injection" }
243371
<p>I have a following table in a flask app</p> <pre><code>class Price(db.Model): __tablename__ = "prices" id = db.Column(db.Integer, primary_key=True) country_code = db.Column(db.String(2), nullable=False) value = db.Column(db.Float(precision=2), nullable=False) start = db.Column(db.DateTime(timezone=True), nullable=False) end = db.Column(db.DateTime(timezone=True), nullable=False) price_type = db.Column(db.String(32), nullable=False) </code></pre> <p>The following parameters are being taken as input to the <code>get</code> method</p> <pre><code>from flask_restx import Resource, reqparse, inputs parser = reqparse.RequestParser() parser.add_argument("country_code", default=None, type=str, choices=("DE", "NL"), help="Country code") parser.add_argument("price_type", default=None, type=str, help="Price type") parser.add_argument("page", default=1, type=int, help="Page Number") parser.add_argument("limit", default=24, type=int, help="Number of items to be displayed on one page") parser.add_argument("value_from", type=float, help="Starting value to filter values") parser.add_argument("value_to", type=float, help="Ending value to filter values") parser.add_argument("sort", default="start", type=str, choices=("id", "country_code", "value", "start", "end", "price_type"), help="Column to sort on") parser.add_argument("dir", default="asc", type=str, choices=("asc", "desc"), help="Sort the column by ascending or descending") parser.add_argument("start", type=inputs.date, help="Start date (YYYY-MM-DD)") parser.add_argument("end", type=inputs.date, help="End date (YYYY-MM-DD)") @ns.route("/") class Prices(Resource) @ns.expect(parser, validate=True) def get(self): args = parser.parse_args() return DatabaseService.read_list(**args) </code></pre> <p>where <code>ns</code> is a namespace I am using</p> <p>I am currently working on enabling filtering on the table and I have the following code:</p> <pre><code>class DatabaseService: @staticmethod def read_list(**filters): page = filters.pop('page') limit = filters.pop('limit') direction = filters.pop('dir') sort = filters.pop('sort') start_date = filters.pop('start') end_date = filters.pop('end') value_from = filters.pop('value_from') value_to = filters.pop('value_to') if all(filters[c] is not None for c in ('country_code', 'price_type')): print('Both are not none') items = Price.query.filter_by(**filters) elif all(filters[c] is None for c in ('country_code', 'price_type')): print('Both are none') items = Price.query elif filters['country_code'] is None: filters.pop('country_code') items = Price.query.filter_by(**filters) elif filters['price_type'] is None: filters.pop('price_type') items = Price.query.filter_by(**filters) </code></pre> <p>The code shown above works perfectly fine, but I was wondering if there is more efficient way of filtering the data. For example, if there is a way to combine the last 2 <code>elif</code> statements into one and do the filtering using <code>filter_by</code> or <code>filter</code></p> <p><strong>Sample Data</strong></p> <pre><code>{ "items": [ { "id": 1, "value": 21.4, "start": "2020-05-12T00:00:00+02:00", "end": "2020-05-12T01:00:00+02:00", "country_code": "DE", "price_type": "DAY_AHEAD" }, { "id": 2, "value": 18.93, "start": "2020-05-12T01:00:00+02:00", "end": "2020-05-12T02:00:00+02:00", "country_code": "DE", "price_type": "DAY_AHEAD" }, { "id": 3, "value": 18.06, "start": "2020-05-12T02:00:00+02:00", "end": "2020-05-12T03:00:00+02:00", "country_code": "LU", "price_type": "DAY_AHEAD" }, { "id": 4, "value": 17.05, "start": "2020-05-12T03:00:00+02:00", "end": "2020-05-12T04:00:00+02:00", "country_code": "DE", "price_type": "TODAY" }]} </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-04T21:10:05.307", "Id": "477740", "Score": "0", "body": "[Cross-posted on Stack Overflow](https://stackoverflow.com/q/62194096/1014587)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-04T22:25:54.070", "Id": "477749", "Score": "0", "body": "Your title should state what your code does. Please read the relevant pages in the help center." } ]
[ { "body": "<p>I think this should work:</p>\n\n<pre><code>extras = ('country_code', 'price_type')\n\nfor field in extras:\n if filters[field] is None:\n filters.pop(field)\n\nif any(field in filters for field in extras):\n items = Price.query.filter_by(**filters)\nelse:\n items = Price.query\n</code></pre>\n\n<p>The key is realizing that if there are <em>any</em> filters defined, you have to <code>.filter_by()</code> them. Note that this doesn't affect the actual query efficiency, which is database dependent.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-04T18:47:20.343", "Id": "243391", "ParentId": "243372", "Score": "2" } } ]
{ "AcceptedAnswerId": "243391", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-04T12:02:07.963", "Id": "243372", "Score": "1", "Tags": [ "python", "python-3.x", "flask", "sqlalchemy" ], "Title": "How to make the filtering queries more efficient using flask sqlalchemy?" }
243372
<p>I am a beginner in Python, as you will see looking at my notes. This is a program that simulates seat booking in a cinema for example. The program stores the users name as a key and the seat(s) they have chosen in a dictionary as key-value pairs.</p> <p>What are the ways I can improve this program? I have used one function. Would defining more functions make my program cleaner and more concise. Please don't comments too hard, I'm working on making them more concise.</p> <pre><code># Ticket Booking System. def print_tickets(): """Print the tickets of the user.""" for user_name, seats in user_tickets.items(): print(f"\nYou, {user_name.title()}, have chosen {len(seats)} seat(s).") for seat in seats: print(f"\tSeat number: {seat}") # Empty dictionary to store info later on. user_tickets = {} # List of seats the user can choose from. available_seats = ['1a', '2a', '19b', '20d', '21e', '13g', '15f', '14f', '13a', '12g' ] # All prompts. start_prompt = "\nWould you like to start booking your ticket? (yes/no) " wanted_seats_prompt = "\nHow many seats are you booking today?" wanted_seats_prompt += "\nEnter the number: " name_prompt = "What is your name? " seat_prompt = "\nPlease enter the number of the seat you would like to book: " go_again_prompt = "Would you like to let someone else book their tickets? (yes/no) " print("Welcome To The Seat Booking Portal!") # Ask the user if he would like to start booking their tickets. start = input(start_prompt) if start.lower() == 'yes': # Runs until it reaches a break statement. while True: # Empty list to store the seat(s) the user has chosen. seats = [] # Find out how many times to run the while loop. wanted_seats = input(wanted_seats_prompt) # Convert the string representation of the number to an integer representation. wanted_seats = int(wanted_seats) # If the user has asked for more seats than the number of seats # available execute this block. if wanted_seats &gt; len(available_seats): print(f"\n--I'm sorry, we only have {len(available_seats)} " "seats available--") print("--Please try again--") continue # Ask for the users name. user_name = input(name_prompt) # Run until the user has chosen the requested number of seats. while True: # Show the user the available seats. print("\nHere are the available seats:") for seat in available_seats: print(seat) # Ask the user for their chosen seat number. seat = input(seat_prompt) # If the user has entered a seat that is in the 'available_seats' # list; remove it from the 'available_seats' list. if seat in available_seats: available_seats.remove(seat) # The user has entered a seat that is not in the 'avialbe_seats' list. # Ask for their seat again. else: print("\n--I'm sorry you have chosen an invalid seat--" "\n-Please try again-") continue # Add the chosen seat to the 'seats' list seats.append(seat) # If the user has said that they are going to book more than one seat # go through this seat booking 'while' loop again. if wanted_seats &gt; 1: print("\nYou can now choose another seat.") # The loop will run a limited number of times. # It will only 'continue' when there is more than one 'wanted_seat'. wanted_seats-=1 continue else: break # Add the 'user_name' variable and 'seats' list to the 'user_tickets' dictionary. user_tickets[user_name] = seats #If their are any available seats left ask the user if he # wants to let another person book their tickets. if available_seats: go_again = input(go_again_prompt) if go_again == 'no': break else: break print_tickets() print("\nWe will now redirect you to the payment portal." "\nThank You for choosing us.") else: print("You can always come by later!") </code></pre>
[]
[ { "body": "<p>I guess you are aware more or less of this (given your PS), but comments have to be there just when they are useful. Some of them that you should remove:</p>\n\n<pre><code># Empty dictionary to store info later on.\n# List of seats the user can choose from.\n# All prompts.\n# Runs until it reaches a break statement.\n# Find out how many times to run the while loop.\n# Convert the string representation of the number to an integer representation.\n# If the user has asked for more seats than the number of seats\n # available execute this block.\n# Ask for the users name.\n</code></pre>\n\n<p>And you get the idea. Comments don't have to be redundant with the code, and they don't explain always what the code does, but they explain something that is not obvious reading the code. Also, in this case, they make more difficult reading the script, given the extension of them. </p>\n\n<p>Also, do you even need a function at all? It is only used once, so unless you are going to extend the code in the future, you could just place those lines of code where the call of the function is. </p>\n\n<p>Instead of having several prints in a row, you could use triple quote string, as follows:</p>\n\n<pre><code>print(f\"\"\"\\n--I'm sorry, we only have {len(available_seats)} \n seats available--\n --Please try again--\"\"\")\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-04T14:20:18.770", "Id": "243380", "ParentId": "243378", "Score": "2" } } ]
{ "AcceptedAnswerId": "243380", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-04T14:12:34.803", "Id": "243378", "Score": "1", "Tags": [ "python", "beginner", "python-3.x" ], "Title": "Ticket Booking Program" }
243378
<h1>Background</h1> <p><strong>About the Fleissner-Grille</strong></p> <p>The Fleissner-Grille is a really easy possibility to encrypt text. You just have to take a grid of size <em>n*n</em> with <em>(n*n)/4</em> holes (<a href="https://upload.wikimedia.org/wikipedia/commons/a/af/Fleissner%27s_stencil.svg" rel="nofollow noreferrer">example</a>). You then just write one letter in one hole. After you've filled every hole with a letter, you just turn the grille by 90° degrees and start again. One requirement that this works is that the grille is not symmetric. Otherwise you would overwrite letters.</p> <p>To create such a grille, you can just fill one quarter of the grille with the number 1-4. Then you turn this quarter by 90° degrees and apply the formula <span class="math-container">$$z = z \% 4 + 1$$</span> to every number. An example on how that works is available <a href="https://upload.wikimedia.org/wikipedia/commons/7/7e/Fleissner-generation.svg" rel="nofollow noreferrer">here</a>.[1]</p> <p><strong>About this project</strong></p> <p>The basis of this project is already covered <a href="https://codereview.stackexchange.com/questions/233861/fleissner-grille-turning-grille-in-java">here</a>, but I changed a lot since I asked this question:</p> <ul> <li><p>Added GUI: The last version of this project was just running in the terminal. I now added the following GUI:</p> <blockquote> <p><a href="https://i.stack.imgur.com/e2Tsm.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/e2Tsm.png" alt="enter image description here"></a></p> <p><a href="https://i.stack.imgur.com/v98R0.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/v98R0.png" alt="enter image description here"></a></p> </blockquote></li> <li><p>Changed codestructure: In the last version, I just worked through the problem in a very procedural way. I now tried to structure my code in a better way: I used classes and more methods.</p></li> <li><p>The grille-size is no longer fixed: The longer the entered text is, the bigger the grille is.</p></li> </ul> <hr> <h1>Code</h1> <p><code>Control.java</code></p> <pre><code>package Fleissner; import javax.swing.SwingUtilities; public class Control { // Just to start GUI public static void main(String[] args) { SwingUtilities.invokeLater(Gui::new); } } </code></pre> <p><code>Fleissner.java</code></p> <pre><code>package Fleissner; import java.lang.Math; // needed for sqrt() public class Fleissner { private int grilleSize; // size of the grille: if the grille has a size of 6x6, this variable // equals to 36. private int substringSize; // grilleSize / 4 private int sizeSqrt; // sqrt(grilleSize) private String text; // text that will be encrypted private char[][] out; // output private int[][] grille; // The turning grille public Fleissner(String text) { this.text = text; // determine needed grille-size int length = text.length(); if (length == 0) { length++; } while (true) { // grilles with size &gt; 64 cannot be displayed if (length &gt; 64) { grilleSize = 64; substringSize = grilleSize / 4; sizeSqrt = (int) Math.sqrt((double) grilleSize); break; } // conditions for grille-size-numbers. // Possible are - for example - 2x2, 4x4, 6x6 and 8x8 if (Math.sqrt((double) length) % 2 == 0 &amp;&amp; length % 4 == 0) { grilleSize = length; substringSize = grilleSize / 4; sizeSqrt = (int) Math.sqrt((double) grilleSize); break; } length++; } } public String fleissnerEncryption() { // If text is too short for grille, the grille will be filled up with random chars ('a' - 'z') if (text.length() &lt; grilleSize) { while (text.length() &lt; grilleSize) { text = text + (char) ('a' + (int) (Math.random() * (('z' - 'a') + 1))); } } // Case that text is too long if (text.length() != grilleSize) { text = safeSubstring(text, 0, grilleSize); } out = encrypt(); //Convert array "out" to String in desired format String result = "Encrypted: "; int length = result.length(); result += "| Grille:\n"; for (int i = 0; i &lt; out.length; i++) { for (int j = 0; j &lt; out[0].length; j++) { if (j == sizeSqrt) { for (int k = 0; k &lt; length - 2 * sizeSqrt; k++) { result += " "; } result += "| "; } result += out[i][j] + " "; } result += "\n"; } return result; } private char[][] encrypt() { grille = creategrille(); //The text now gets split up to substrings with length substringSize. //Then the grille gets filled up with the chars. String subText = safeSubstring(text, 0, substringSize); int[] ar = {0 * substringSize, 1 * substringSize, 2 * substringSize, 3 * substringSize, 4 * substringSize}; out = new char[sizeSqrt][sizeSqrt * 2]; int count = 0; while (count &lt; grilleSize / substringSize) { int row = 0; int col = 0; int i = 0; //Filling grille with transposed chars while (i &lt; subText.length()) { if (grille[row][col] == 1) { out[row][col] = subText.charAt(i); i = i + 1; if (col &lt; sizeSqrt - 1) { col = col + 1; } else if (row &lt; sizeSqrt - 1) { row = row + 1; col = 0; } } else if (col &lt; sizeSqrt - 1) { col = col + 1; } else if (row &lt; sizeSqrt - 1) { row = row + 1; col = 0; } } count = count + 1; int m = ar[count]; int n = m + substringSize; subText = safeSubstring(text, m, n); grille = rotate(grille); } //Filling 2nd part of the array with the grille (needed for decrypting) for (int k = 0; k &lt; out.length; k++) { for (int l = sizeSqrt; l &lt; out[0].length; l++) { int radix = 10; out[k][l] = Character.forDigit(grille[k][l - sizeSqrt], radix); } } return out; } // This method creates a random grille private int[][] creategrille() { final int n = sizeSqrt / 2; int[][] a2 = new int[n][n]; for (int i = 0; i &lt; n; ++i) { for (int j = 0; j &lt; n; ++j) { a2[i][j] = (int) ((Math.random()) * 4 + 1); } } int[][] a3 = getMatrix(a2); int[][] a4 = getMatrix(a3); int[][] a5 = getMatrix(a4); int[][] result = new int[sizeSqrt][sizeSqrt]; /* * Filling result-array like this: * [ (a2), (a3) ] * [ (a5), (a4) ] */ for (int i = 0; i &lt; n; i++) { for (int j = 0; j &lt; n; j++) { result[i][j] = a2[i][j]; result[i + n][j] = a5[i][j]; result[i][j + n] = a3[i][j]; result[i + n][j + n] = a4[i][j]; } } return result; } //Rotates the matrix and applies formula private int[][] getMatrix(int[][] a2) { int[][] result = rotate(a2); for (int i = 0; i &lt; result.length; i++) { for (int j = 0; j &lt; result.length; j++) { result[i][j] = result[i][j] % 4 + 1; } } return result; } // This method rotates the "grille" clockwise 45 degrees private int[][] rotate(int[][] a1) { int n = a1.length; int[][] rotated = new int[n][n]; for (int i = 0; i &lt; n; ++i) { for (int j = 0; j &lt; n; ++j) { rotated[i][j] = a1[n - j - 1][i]; } } return rotated; } // Method to divide String into smaller substrings. private String safeSubstring(String str, int start, int end) { String out = ""; if (end &gt; str.length() - 1) { end = str.length(); } while (start &lt; end) { out = out + str.charAt(start); start = start + 1; } return out; } } </code></pre> <p><code>Gui.java</code></p> <pre><code>/* Attribution: * Question by shareef(https://stackoverflow.com/users/944593/shareef): * https://stackoverflow.com/questions/30370220/how-to-diable-break-line-keystroke-enter-e-g-in-jtextarea-in-swing-java * Answer by Normal design (https://stackoverflow.com/users/4919947/normal-design) */ package Fleissner; import java.awt.Dimension; import java.awt.Font; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextArea; public class Gui { private JTextArea outputArea; public Gui() { //JFrame JFrame frame = new JFrame("Fleissner-Encryption"); frame.setSize(500, 300); frame.setMinimumSize(new Dimension(500, 300)); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //JPanel JPanel panel = new JPanel(new GridBagLayout()); //Creating textArea for input JTextArea inputArea = new JTextArea(); inputArea.setColumns(50); inputArea.setRows(4); inputArea.setLineWrap(true); inputArea.getDocument().putProperty("filterNewlines", Boolean.TRUE); //Make line-breaks impossible inputArea.setFont(new Font("monospaced", Font.PLAIN, 12)); JScrollPane input = new JScrollPane(inputArea); //Creating button JButton button = new JButton("Encrypt"); button.setFont(new Font("Arial", Font.PLAIN, 20)); button.addActionListener(e -&gt; encrypt(inputArea.getText())); //Creating textArea for output outputArea = new JTextArea(); outputArea.setEditable(false); outputArea.setColumns(50); outputArea.setRows(10); outputArea.setLineWrap(true); outputArea.setFont(new Font("monospaced", Font.PLAIN, 12)); JScrollPane output = new JScrollPane(outputArea); //Layout GridBagConstraints gbc = new GridBagConstraints(); gbc.weighty = 5; gbc.gridwidth = GridBagConstraints.REMAINDER; //Add everything to panel panel.add(input, gbc); panel.add(button, gbc); panel.add(output, gbc); //Add everything to frame frame.add(panel); frame.setVisible(true); } //Connection to class Fleissner private void encrypt(String text) { Fleissner fleissner = new Fleissner(text); String result = fleissner.fleissnerEncryption(); outputArea.setText(result); } } </code></pre> <hr> <h1>Question</h1> <ul> <li>How can the code be improved in general?</li> <li>What improvements are possible in regard to the GUI?</li> <li>How can the codestructure be improved?</li> </ul> <hr> <p>[1] Wikipedia contributors. (2019, March 13, 05:57 UTC), <em>Fleißnersche Schablone</em>. In <em>Wikipedia, Die freie Enzykopädie</em>. Retrieved June 4, 2020, 17:20 UTC from <a href="https://de.wikipedia.org/w/index.php?title=Flei%C3%9Fnersche_Schablone&amp;oldid=186533989" rel="nofollow noreferrer">https://de.wikipedia.org/w/index.php?title=Flei%C3%9Fnersche_Schablone&amp;oldid=186533989</a></p> <hr>
[]
[ { "body": "<p>In my opinion, the code is great and well separated (ui vs logic), good job!</p>\n\n<p>I have some suggestions.</p>\n\n<h2>Use <code>java.lang.StringBuilder</code> to concatenate String in a loop.</h2>\n\n<p>It's generally more efficient to use the builder in a loop, since the compiler is unable to make it efficient in a loop; since it creates a new String each iteration. There are lots of good explanations with more details on the subject.</p>\n\n<ul>\n<li><a href=\"http://www.pellegrino.link/2015/08/22/string-concatenation-with-java-8.html\" rel=\"nofollow noreferrer\">http://www.pellegrino.link/2015/08/22/string-concatenation-with-java-8.html</a></li>\n<li><a href=\"https://javapapers.com/java/java-string-vs-stringbuilder-vs-stringbuffer-concatenation-performance-micro-benchmark/\" rel=\"nofollow noreferrer\">https://javapapers.com/java/java-string-vs-stringbuilder-vs-stringbuffer-concatenation-performance-micro-benchmark/</a></li>\n<li><a href=\"https://www.baeldung.com/java-strings-concatenation\" rel=\"nofollow noreferrer\">https://www.baeldung.com/java-strings-concatenation</a></li>\n</ul>\n\n<h2>Use the enhanced <code>for</code> loop when possible</h2>\n\n<p>In this case, it will make the code shorter.</p>\n\n<p><code>Fleissner#fleissnerEncryption</code></p>\n\n<p><strong>Before</strong></p>\n\n<pre class=\"lang-java prettyprint-override\"><code>for (int i = 0; i &lt; out.length; i++) {\n //[...]\n result += out[i][j] + \" \";\n}\n</code></pre>\n\n<p><strong>After</strong></p>\n\n<pre class=\"lang-java prettyprint-override\"><code>for (char[] chars : out) {\n //[...]\n result += chars[j] + \" \";\n}\n</code></pre>\n\n<h2>You can simplify the array in <code>Fleissner#encrypt</code> since \"<span class=\"math-container\">\\$0 * n = 0\\$</span>\" and \"<span class=\"math-container\">\\$1 * n = n\\$</span>\"</h2>\n\n<p><strong>Before</strong></p>\n\n<pre class=\"lang-java prettyprint-override\"><code>int[] ar = {0 * substringSize, 1 * substringSize, 2 * substringSize, 3 * substringSize, 4 * substringSize};\n</code></pre>\n\n<p><strong>After</strong></p>\n\n<pre class=\"lang-java prettyprint-override\"><code>int[] ar = {0, substringSize, 2 * substringSize, 3 * substringSize, 4 * substringSize};\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-05T14:43:16.110", "Id": "477793", "Score": "0", "body": "Thanks for your feedback. What do you think about the constructor of the Fleissner-Class? Should I put the code needed to determine the grille-size in a seperate method, or is it ok to do this calculation in the constructor?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-05T15:01:08.103", "Id": "477794", "Score": "1", "body": "@vulpini99 In my opinion, there are no issues to do some calculation in the constructor, since you would need to pass the data to it if not. Another alternative that I see is you could set the constructor private and create a static builder method that instantiate the instance and pass the calculated values to the constructor. This method will allow you the group the logic of the calculations and remove them from the constructor and be easy to use." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-05T13:02:56.930", "Id": "243422", "ParentId": "243388", "Score": "2" } }, { "body": "<p>The code is well structured and division between math core and gui is neat, some my thoughts about math part.\nYour <code>Fleissner</code> constructor is the following:</p>\n\n<blockquote>\n<pre><code>public Fleissner(String text) {\n this.text = text;\n // determine needed grille-size\n int length = text.length();\n if (length == 0) {\n length++;\n }\n while (true) {\n // grilles with size &gt; 64 cannot be displayed\n if (length &gt; 64) {\n grilleSize = 64;\n substringSize = grilleSize / 4;\n sizeSqrt = (int) Math.sqrt((double) grilleSize);\n break;\n }\n // conditions for grille-size-numbers.\n // Possible are - for example - 2x2, 4x4, 6x6 and 8x8\n if (Math.sqrt((double) length) % 2 == 0 &amp;&amp; length % 4 == 0) {\n grilleSize = length;\n substringSize = grilleSize / 4;\n sizeSqrt = (int) Math.sqrt((double) grilleSize);\n break;\n }\n length++;\n }\n }\n}\n</code></pre>\n</blockquote>\n\n<p>You can construct a maximal grille of 8 X 8 characters, with possible options of 2 X 2, 4 X 4, 6 X 6 and 8 X 8 grilles according to the length of the string you are using; you can achieve the same result in a less complicate the way like this:</p>\n\n<pre><code>public Fleissner(String text) {\n this.text = text;\n final int l = text.length();\n int length = 2;\n for (;l &gt; length * length &amp;&amp; length &lt; 8; length += 2);\n this.grilleSize = length * length;\n this.substringSize = grilleSize / 4;\n this.length = length; \n}\n</code></pre>\n\n<p>In your method <code>fleissnerEncryption</code> you have the following lines:</p>\n\n<blockquote>\n<pre><code>if (text.length() &lt; grilleSize) {\n while (text.length() &lt; grilleSize) {\n text = text + (char) ('a' + (int) (Math.random() * (('z' - 'a') + 1)));\n }\n}\n</code></pre>\n</blockquote>\n\n<p>You can use <code>Random.ints</code> method and rewrite like this:</p>\n\n<pre><code>int l = text.length();\nif (l &lt; grilleSize) {\n new Random().ints(grilleSize - l, 'a', 'z' + 1)\n .forEach(i -&gt; { text = text + (char)i; });\n}\n</code></pre>\n\n<p>The most complicate part is about writing the String result; you have the following lines:</p>\n\n<blockquote>\n<pre><code>String result = \"Encrypted: \";\nint length = result.length();\nresult += \"| Grille:\\n\";\nfor (int i = 0; i &lt; out.length; i++) {\n for (int j = 0; j &lt; out[0].length; j++) {\n if (j == sizeSqrt) {\n for (int k = 0; k &lt; length - 2 * sizeSqrt; k++) {\n result += \" \";\n }\n result += \"| \";\n }\n result += out[i][j] + \" \";\n }\n result += \"\\n\";\n}\n</code></pre>\n</blockquote>\n\n<p>Using <code>String.join</code> method and <code>Collections.nCopies</code> you can rewrite it in the following way:</p>\n\n<pre><code>String result = \"Encrypted: \";\nl = result.length();\nString spaces = String.join(\"\", Collections.nCopies(l - 2 * length, \" \"));\nresult += \"| Grille:\\n\";\nfor (char[] row : out) {\n result += String.join(\" \", new String(Arrays.copyOfRange(row, 0, length)).split(\"\"));\n result += spaces;\n result += \" | \";\n result += String.join(\" \", new String(Arrays.copyOfRange(row, length, row.length)).split(\"\"));\n result += \"\\n\";\n}\n\nreturn result;\n</code></pre>\n\n<p>The method <code>fleissnerEncryption</code> can be rewritten like this:</p>\n\n<pre><code>public String fleissnerEncryption() {\n\n // If text is too short for grille, the grille will be filled up with random chars ('a' - 'z')\n int l = text.length();\n if (l &lt; grilleSize) {\n new Random().ints(grilleSize - l, 'a', 'z' + 1)\n .forEach(i -&gt; { text = text + (char)i; });\n }\n\n if (l != grilleSize) {\n text = safeSubstring(text, 0, grilleSize);\n }\n\n out = encrypt();\n\n //Convert array \"out\" to String in desired format\n String result = \"Encrypted: \";\n l = result.length();\n String spaces = String.join(\"\", Collections.nCopies(l - 2 * length, \" \"));\n result += \"| Grille:\\n\";\n for (char[] row : out) {\n result += String.join(\" \", new String(Arrays.copyOfRange(row, 0, length)).split(\"\"));\n result += spaces;\n result += \" | \";\n result += String.join(\" \", new String(Arrays.copyOfRange(row, length, row.length)).split(\"\"));\n result += \"\\n\";\n }\n\n return result;\n}\n</code></pre>\n\n<p>The following line in your code :</p>\n\n<blockquote>\n<pre><code>int[] ar = {0 * substringSize, 1 * substringSize, 2 * substringSize, 3 * substringSize, 4 * substringSize};\n</code></pre>\n</blockquote>\n\n<p>It can be rewritten with <code>IntStream</code> :</p>\n\n<pre><code>int[] ar = IntStream.rangeClosed(0, 5).map(i -&gt; i * substringSize).toArray();\n</code></pre>\n\n<p>The name of your package <code>Fleissner</code> should be <code>fleissner</code>. By convention, package names usually start with a lowercase letter</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-08T15:58:36.067", "Id": "243567", "ParentId": "243388", "Score": "1" } } ]
{ "AcceptedAnswerId": "243422", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-04T17:44:30.550", "Id": "243388", "Score": "6", "Tags": [ "java" ], "Title": "Fleissner-Grille / Turning-Grille" }
243388
<p>I am new to JavaScript so I am not sure if it's bad practice to nest a for loops inside of each other.</p> <p>This script simply takes a WordPress HTML menu and restructures it into a format better suited to my requirements. </p> <p>Below you can see the original HTML, the JS and the new HTML output by the JS.</p> <p>The nested "for of" loop checks the deepest anchor tags to see if the <code>href</code> matched the window and gives it a "is-active" class if it does. Should this "for of" loop be in its own function or is the nesting okay?</p> <p>Is there a better way to write the JS?</p> <p>Original HTML:</p> <pre><code>&lt;aside class="menu"&gt; &lt;ul class="menu-list"&gt; &lt;li class="menu-label"&gt; &lt;a&gt;Label 1&lt;/a&gt; &lt;ul class="sub-menu"&gt; &lt;li&gt;&lt;a href="#"&gt;link&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;link&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;link&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;link&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;link&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;li class="menu-label"&gt; &lt;a&gt;Label 2&lt;/a&gt; &lt;ul class="sub-menu"&gt; &lt;li&gt;&lt;a href="#"&gt;link&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;link&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;link&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;link&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;link&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/aside&gt; </code></pre> <p>JS</p> <pre><code>const menuWrapper = document.querySelector(`aside.menu`); const badMenu = document.querySelector(`.menu-list`); const badMenuItems = document.querySelectorAll(`.menu-label`); function fixMenus(menu, items) { // Remove old menu menu.remove(); let fixedMenu = ``; // Iterate through and build new menu items.forEach(x =&gt; { const labels = x.children[0].innerHTML; const subMenus = x.children[1]; const subItems = x.children[1].children; //Set "is-active" to anchor tag for (let i of subItems) { if (i.firstElementChild.href === window.location.href) { i.firstElementChild.classList.add(`is-active`) } } //Build new menu fixedMenu += ` &lt;p class="menu-label"&gt;${labels}&lt;/p&gt; &lt;ul class="menu-list"&gt; ${subMenus.innerHTML} &lt;/ul&gt; `; }); return fixedMenu; } const sideMenus = fixMenus(badMenu, badMenuItems); menuWrapper.insertAdjacentHTML(`beforeend`, sideMenus); </code></pre> <p>NEW HTML (rebuild, returned from the JS)</p> <pre><code>&lt;aside class="menu"&gt; &lt;p class="menu-label"&gt;Label 1&lt;/p&gt; &lt;ul class="menu-list"&gt; &lt;li&gt;&lt;a class="is-active" href="#"&gt;link&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;link&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;link&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;link&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;link&lt;/a&gt;&lt;/li&gt; &lt;/ul &gt; &lt;p class="menu-label"&gt;Label 2&lt;/p&gt; &lt;ul class="menu-list"&gt; &lt;li&gt;&lt;a href="#"&gt;link&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;link&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;link&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;link&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;link&lt;/a&gt;&lt;/li&gt; &lt;/ul &gt; &lt;/aside&gt; </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-04T18:53:13.440", "Id": "477730", "Score": "4", "body": "Welcome to Code Review! \"This script simply takes a poorly organised menu and rebuilds it.\" Can you tell us more about what you mean by this? What's the goal of the code?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-04T18:56:54.693", "Id": "477733", "Score": "0", "body": "It just takes in a HTML menu and reorganises it. The original menu is structured poorly and the script changes the structure." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-04T19:00:36.487", "Id": "477734", "Score": "0", "body": "@Mast I have edited the original post and added some more info" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-04T20:22:03.153", "Id": "477737", "Score": "1", "body": "Much better, thank you. I hope you get some good reviews." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-04T22:24:54.237", "Id": "477748", "Score": "2", "body": "Your title should state what the code does, not your concerns about the code. Please read the relevant pages in the help center." } ]
[ { "body": "<blockquote>\n<p>Is there a better way to write the JS?</p>\n</blockquote>\n<p>Yes there is.</p>\n<p>First off, lets face it, your function <code>fixMenus</code> looks quite complex and a double for loop in one function is usually a big &quot;no no&quot; sign. Any company with a coding standard would want this to be different.</p>\n<p>You have a double for loop with some conditions and some HTML building. That's a lot for one function and it looks hard to test accurately.</p>\n<p>Your function does the following things</p>\n<ol>\n<li>Loops through each menu</li>\n<li>Destructures some data</li>\n<li>Loops through a sublist to apply a class</li>\n<li>Applies the new menu to the variable</li>\n</ol>\n<p>So instead of having one function handle all this, let's break it up.</p>\n<h1>Make small simple functions that are easy to test</h1>\n<p>The concept of Test Driven Development (TDD) forces you to write code that is:</p>\n<ol>\n<li>Easy to understand</li>\n<li>Easy to test</li>\n</ol>\n<p>This by itself already forces you to write better code and smaller functions.</p>\n<p>You're probably not doing TDD, but writing code <em>as if you were</em> is already a great step!</p>\n<h2>Focus on the simple tasks</h2>\n<ul>\n<li><code>fixMenus</code> should call <code>generateMenus</code> and ultimately <code>generateMenu</code></li>\n<li>Use Array#map and Array#join instead of <code>forEach</code></li>\n<li>create a function to update the actives</li>\n<li>create a function to generate your html string</li>\n</ul>\n<pre><code>function updateActives(subItems){\n for (let i of subItems) {\n if (i.firstElementChild.href === window.location.href) {\n i.firstElementChild.classList.add(`is-active`);\n }\n }\n}\n\nfunction createMenu(labels, subMenus){\n return `\n &lt;p class=&quot;menu-label&quot;&gt;${labels}&lt;/p&gt;\n &lt;ul class=&quot;menu-list&quot;&gt;\n ${subMenus}\n &lt;/ul&gt;\n `\n}\n\nfunction generateMenu(item){\n const {children:[elem1, elem2]} = item;\n updateActives(elem2.children);\n return createMenu(elem1.innerHTML, elem2.innerHTML);\n}\n\nfunction generateMenus(items){\n return items.map(item =&gt; generateMenu(item)).join(&quot;&quot;);\n}\n\nfunction fixMenus(menu, items){\n menu.remove();\n return generateMenus(items);\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-05T17:14:14.427", "Id": "477814", "Score": "2", "body": "Awesome, thanks. I had a feeling I wasn't doing things right. I have learned a lot from this." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-05T13:58:08.777", "Id": "243427", "ParentId": "243390", "Score": "4" } } ]
{ "AcceptedAnswerId": "243427", "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-04T18:29:08.807", "Id": "243390", "Score": "6", "Tags": [ "javascript" ], "Title": "Nesting \"for of\" inside of a \"forEach\"" }
243390
<p>I am trying to learn how to effectively use error handling in my code. To do this, I have created a class inside <code>main.py</code> which reads the value of a specified curve at a specified date.</p> <p>I then have my file <code>data_reader.py</code>, which reads in the specified curve (into a Pandas dataframe) from a CSV file. The index of this curve is a date.</p> <p>Finally, I have my error handling file, <code>error_handler.py</code>.</p> <p><code>main.py</code></p> <pre><code>from data_reader import read_curve from datetime import datetime, timedelta import sys from error_handler import CustomException, CurveValueNotFoundError def get_curve_value(curve_name, lookup_date): lookup_date = datetime.strptime(lookup_date, '%d/%m/%Y') curve_value = None tries_remaining = 5 while curve_value is None: try: curve_value = read_curve(curve_name, lookup_date, tries_remaining) return curve_value except CurveValueNotFoundError as e: e.return_to_user() tries_remaining -= 1 lookup_date -= timedelta(days=1) except CustomException as e: e.return_to_user() if e.fatal: sys.exit(1) if __name__ == '__main__': print('Curve value: {}'.format(get_curve_value('RPI2019', '30/06/2019'))) </code></pre> <p><code>data_reader.py</code></p> <pre><code>import pandas as pd import pathlib import error_handler def read_curve(curve_name, lookup_value, tries_remaining): try: curve = pd.read_csv('{}/curves/{}.csv'.format(str(pathlib.Path().absolute()), curve_name), index_col='Date', parse_dates=True) val = float(curve.loc[lookup_value]) return val except pd.errors.EmptyDataError as e: raise error_handler.NoCurveValuesError(curve_name, __name__, fatal=True) except FileNotFoundError: raise error_handler.CurveNotFoundError(curve_name, __name__, fatal=True) except KeyError: raise error_handler.CurveValueNotFoundError(curve_name, lookup_value, tries_remaining, __name__) except Exception as e: raise error_handler.CustomException(e, __name__, fatal=True) </code></pre> <p><code>error_handler.py</code></p> <pre><code>class CustomException(Exception): def __init__(self, message, raised_from, fatal): self.message = message self.raised_from = raised_from self.fatal = fatal def return_to_user(self): print("The following error occurred in the module {}.py: {}".format(self.raised_from, self.message)) class CurveNotFoundError(CustomException): def __init__(self, curve_name, raised_from, fatal=True): message = "The curve {} could not be found.".format(curve_name) CustomException.__init__(self, message, raised_from, fatal) class NoCurveValuesError(CustomException): def __init__(self, curve_name, raised_from, fatal=True): message = "The curve {} was successfully loaded but contains no data.".format(curve_name) CustomException.__init__(self, message, raised_from, fatal) class CurveValueNotFoundError(CustomException): def __init__(self, curve_name, lookup_value, tries_remaining, raised_from, fatal=False): message = "The curve {} is not defined for the lookup '{}'. Tries remaining: {}.".format(curve_name, lookup_value, tries_remaining) CustomException.__init__(self, message, raised_from, fatal) if tries_remaining == 0: raise CustomException("Too many missing values", __name__, fatal=True) </code></pre> <p>Errors that should terminate execution include:</p> <ul> <li><p>If the CSV file containing the user-specified curve cannot be found</p></li> <li><p>If the CSV file for the curve is empty</p></li> <li><p>If, after 5 tries (changing the lookup date by -1 days per try), no curve values can be found</p></li> </ul> <p>Is my approach towards error handling (including my handling of fatal / non-fatal errors) a good approach? How can I improve this? </p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-04T20:20:21.727", "Id": "243393", "Score": "4", "Tags": [ "python", "python-3.x", "error-handling" ], "Title": "Error handling best practices using a custom error handling module" }
243393
<p>I'm new GO coder (stared this Sunday) coming from different backgrounds, I wrote the below code based on my understanding of Go within these couple of days, and impacted of my experience in other languages, I like to share for Go experts review/comments and feedback.</p> <pre class="lang-golang prettyprint-override"><code>package main import ( "fmt" "log" "sort" "time" ) const ( layoutISO = "2006-01-02" layoutUS = "January 2, 2006" custom = "1/2/2006" ) type Inventories []Inventory type Inventory struct { //instead of: map[string]map[string]Pairs Warehouse string Item string Batches Lots } type Lots []Lot type Lot struct { Date time.Time Key string Value float64 } func main() { fmt.Println("Hello, 世界") date := "12/31/19" // "1999-12-31" t, _ := time.Parse(custom, date) var inventories = new(Inventories) var inventory = new(Inventory) // Or = Inventory{} both are working //warehouse[item[batch, qty]] inventory.Warehouse = "DMM" inventory.Item = "Helmet" inventory.Batches = append(inventory.Batches, Lot{t, "Jan", 10}) inventory.InsertBatch(Lot{time.Now(), "Jan", 30}) inventory.Batches.Insert(Lot{time.Now(), "Feb", 30}) fmt.Printf("\nBefore grouping: %v %T\n", inventory, inventory) x := Inventory{ Warehouse: "DMM", Item: "Gloves", Batches: Lots{ Lot{mustTime(time.Parse(custom, "1/7/2020")), "Jan", 50}, Lot{mustTime(time.Parse(custom, "2/1/2020")), "Feb", 20}, Lot{mustTime(time.Parse(custom, "1/5/2020")), "Jan", 40}, Lot{mustTime(time.Parse(custom, "2/9/2020")), "Feb", 60}, }, } fmt.Printf("\nBefore grouping: %v %T\n", x, x) // Below can be used for grouping batches in each warehouse seperatly, this can be combined in the lines under // inventory.Batches.Group() // x.GroupBatches() // fmt.Printf("\nAfter grouping: %v %T\n", inventory, inventory) // fmt.Printf("\nAfter grouping: %v %T\n", x, x) // Above can be replaced by below inventories.Insert(*inventory) inventories.Insert(x) inventories.GroupBatches() fmt.Printf("\nInventories after gouping batches: %v %T\n", inventories, inventories) inventories.SortBatches() fmt.Printf("\nInventories after sorting batches: %v %T\n", inventories, inventories) } func (i *Inventories) Insert(x Inventory) { *i = append(*i, x) } func (i *Inventories) GroupBatches() { inv := new(Inventories) for _, el := range *i { el.GroupBatches() inv.Insert(el) } (*i).ReplaceBy(inv) } func (i *Inventories) SortBatches() { inv := new(Inventories) for _, el := range *i { sort.Sort(Lots(el.Batches)) inv.Insert(el) } (*i).ReplaceBy(inv) } func (i *Inventories) ReplaceBy(x *Inventories) { *i = *x } func (i *Inventory) InsertBatch(x Lot) { (*i).Batches = append((*i).Batches, x) } func (i *Inventory) GroupBatches() { (*i).Batches.Group() } func (p *Lots) Group() { lots := new(Lots) lots.FromMap(p.Map()) p.ReplaceBy(lots) } func (p *Lots) FromMap(m map[string]float64) { for k, v := range m { (*p).Insert(Lot{time.Now(), k, v}) } } // Below to enable sorting: sort.Sort(Lots(lots)) func (l Lots) Len() int { return len(l) } func (l Lots) Less(i, j int) bool { return (l[i].Date).Before(l[j].Date) } // { return l[i].Key &lt; l[j].Key } func (l Lots) Swap(i, j int) { l[i], l[j] = l[j], l[i] } func (p *Lots) Insert(x Lot) { *p = append(*p, x) } func (p *Lots) ReplaceBy(x *Lots) { *p = *x } func (p *Lots) Map() map[string]float64 { sum := make(map[string]float64) for _, el := range *p { sum[el.Key] = sum[el.Key] + el.Value } return sum } type Interface interface { // Len is the number of elements in the collection. Len() int // Less reports whether the element with // index i should sort before the element with index j. Less(i, j int) bool // Swap swaps the elements with indexes i and j. Swap(i, j int) } func mustTime(t time.Time, err error) time.Time { failOnError(err) return t } func failOnError(err error) { if err != nil { log.Fatal("Error:", err) panic(err) } } </code></pre> <p>The above code is fully functioning, and give the results as below:</p> <pre class="lang-bsh prettyprint-override"><code>[Running] go run "d:\goplay\grouping.go" Hello, 世界 Before grouping: &amp;{DMM Helmet [{0001-01-01 00:00:00 +0000 UTC Jan 10} {2020-06-05 00:26:16.9165066 +0300 +03 m=+0.006981101 Jan 30} {2020-06-05 00:26:16.9165066 +0300 +03 m=+0.006981101 Feb 30}]} *main.Inventory Before grouping: {DMM Gloves [{2020-01-07 00:00:00 +0000 UTC Jan 50} {2020-02-01 00:00:00 +0000 UTC Feb 20} {2020-01-05 00:00:00 +0000 UTC Jan 40} {2020-02-09 00:00:00 +0000 UTC Feb 60}]} main.Inventory Inventories after gouping batches: &amp;[{DMM Helmet [{2020-06-05 00:26:16.9175045 +0300 +03 m=+0.007979001 Jan 40} {2020-06-05 00:26:16.9175045 +0300 +03 m=+0.007979001 Feb 30}]} {DMM Gloves [{2020-06-05 00:26:16.9175045 +0300 +03 m=+0.007979001 Jan 90} {2020-06-05 00:26:16.9175045 +0300 +03 m=+0.007979001 Feb 80}]}] *main.Inventories Inventories after sorting batches: &amp;[{DMM Helmet [{2020-06-05 00:26:16.9175045 +0300 +03 m=+0.007979001 Jan 40} {2020-06-05 00:26:16.9175045 +0300 +03 m=+0.007979001 Feb 30}]} {DMM Gloves [{2020-06-05 00:26:16.9175045 +0300 +03 m=+0.007979001 Jan 90} {2020-06-05 00:26:16.9175045 +0300 +03 m=+0.007979001 Feb 80}]}] *main.Inventories [Done] exited with code=0 in 3.624 seconds <span class="math-container">```</span> </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-04T22:23:36.853", "Id": "477747", "Score": "1", "body": "Your title should state what your code does. Please read the relevant pages in the help center." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-04T22:06:05.110", "Id": "243396", "Score": "2", "Tags": [ "go" ], "Title": "Basic functional programming understanding in GO" }
243396
<p>I developed Awk code to print all primes till N where N is given as command line argument. I think I took pretty much all the optimizations into account. Could someone help if it could be optimized even more. The code is as follows:</p> <pre><code>#!/usr/bin/awk -f BEGIN{ for (i=oddify(ARGV[1]); i&gt;2; i=i-2){ flag=1 #prime for(j=3; j&lt;=ceil(sqrt(i)); j=j+2){ if (i%j==0){ flag=0 #not prime break } } if (flag==1){printf("%d\n", i) } } printf("2\n") } function ceil(n){ return (n == int(n)) ? n : int(n)+1 } function oddify(n){ return (n%2 != 0) ? n : n-1 } </code></pre> <p>How to run: <code>awk -f prime.awk 10000</code></p>
[]
[ { "body": "<p>Bug: when I run the program with argument 1, it prints 2 even though 2 > 1.</p>\n\n<p>The code is not optimized at all. It computes <code>ceil</code> and <code>sqrt</code> way too often, in a way that is obvious to optimize. All other prime programs on this site already do that, have a look at them.</p>\n\n<p>The code is not optimized enough. It contains <code>i = i + 2</code>, which should have been <code>i += 2</code> from the beginning. A third of these calls can be omitted using the standard prime searching technique that has been mentioned more than enough on this site.</p>\n\n<p>The variable name <code>flag</code> is terrible. It should be <code>is_prime</code> instead.</p>\n\n<p>Having the most interesting code in the <code>BEGIN</code> block is bad design. You should define a function <code>is_prime</code> and another function <code>print_primes_up_to</code>. This allows you to declare <code>i</code> and <code>j</code> as local variables.</p>\n\n<p>In the function <code>ceil</code>, the parameter name <code>n</code> is confusing since this name implies to the human reader that it is a natural number. In reality it is a floating point number though. A better name for this variable is <code>x</code>.</p>\n\n<p>The code is missing some documentation. It should clearly state up to which number it reports correct results. It should also state the first number for which a wrong result is printed. Internally, many AWK implementations use 64-bit floating point numbers, therefore I guess this number is somewhere around <span class=\"math-container\">\\$2^{53}\\$</span>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-05T02:40:46.290", "Id": "243402", "ParentId": "243398", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-05T00:47:23.180", "Id": "243398", "Score": "3", "Tags": [ "awk" ], "Title": "An Awk program to find all primes till N" }
243398
<p>I'm pretty new to Python and really new to PyGame. My snake game runs, but I guess that's not really saying much. I would appreciate feedback on the layout, techniques, or best practices of my code.</p> <pre><code>import pygame,sys,random,time from pygame.locals import * #Setup pygames# pygame.init() #Setup the window# WINDOWWIDTH = 400 WINDOWHEIGHT = 400 windowSurface = pygame.display.set_mode( (WINDOWWIDTH,WINDOWHEIGHT), 0, 32 ) pygame.display.set_caption('Snake') mainClock = pygame.time.Clock() #Direction Variables# U = 'up' D = 'down' L = 'left' R = 'right' #Set up the colors# BLACK = (0,0,0) WHITE = (255,255,255) RED = (255,0,0) GREEN = (0,255,0) BLUE = (0,0,255) YELLOW = (255,255,102) #All the food code stuff# FOODS = [] FOODSIZE = 10 FOODS.append(pygame.Rect(random.randint(FOODSIZE,WINDOWWIDTH-2*FOODSIZE), random.randint(FOODSIZE,WINDOWHEIGHT-2*FOODSIZE),FOODSIZE,FOODSIZE)) #Code for the game over screen# font_style = pygame.font.SysFont(None, 50) font_style1 = pygame.font.SysFont(None, 25) score_font = pygame.font.SysFont('sfcompactroundedregularotf',25) #function you call to dispplay the GAME OVER message# def message(msg1,msg2,msg3,color): mesg1 = font_style.render(msg1,True,color) mesg2 = font_style1.render(msg2,True,color) mesg3 = font_style1.render(msg3,True,color) windowSurface.blit(mesg1,[WINDOWWIDTH/4, WINDOWHEIGHT/3]) windowSurface.blit(mesg2,[WINDOWWIDTH/4+50, WINDOWHEIGHT/3+40]) windowSurface.blit(mesg3,[WINDOWWIDTH/4+50, WINDOWHEIGHT/3+60]) #function that you can call to display the score to the screen# def yourScore(score): msgScore = score_font.render('Score:' + str(score),True,YELLOW) windowSurface.blit(msgScore,[0,0]) #Define the snake class# snakeSize = 10 class Snake: size = 10 def __init__(self,rect,color,direc): self.rect = rect self.color = color self.direc = direc #Draws the snake onto the screen# def ourSnake(snakeSize,snakeList): for x in snakeList: pygame.draw.rect(windowSurface, WHITE,[x[0],x[1],snakeSize,snakeSize]) #We define the main game loop# def main(): gameClose = False #value to check if the player has lost# player = Snake(pygame.Rect(WINDOWWIDTH/2,WINDOWHEIGHT/2,snakeSize,snakeSize),WHITE,U) #Build the players initial snake# SPEED = 10 #Speed of the snake# snakeLength = 1 #Initial length of the snake, to be incremented after contact with food# snakeList = [] while True: #Creates a seperate loop that occurs after the game has been lost# while gameClose == True: windowSurface.fill(WHITE) message('GAME OVER!','Press P to play','Press Q to quit',BLUE) pygame.display.update() #Defines which keys exit and which restarts the game# for event in pygame.event.get(): if event.type == pygame.KEYDOWN: if event.key == pygame.K_q: pygame.quit() sys.exit() if event.key == pygame.K_p: main() #Check for events# for event in pygame.event.get(): #QUIT event type# if event.type == QUIT: pygame.quit() sys.exit() #Define wha the arrow and wasd keys do# if event.type == KEYDOWN: if event.key == K_LEFT or event.key == K_a: player.direc = L if event.key == K_RIGHT or event.key == K_d: player.direc = R if event.key == K_UP or event.key == K_w: player.direc = U if event.key == K_DOWN or event.key == K_s: player.direc = D if event.key == K_ESCAPE: pygame.quit() sys.exit() #Defines how the snake will move around the screen# #Also sets up bounds on the snake i.e. the edges of the screen# if player.direc == D and player.rect.bottom &lt; WINDOWHEIGHT: player.rect.bottom += SPEED if player.direc == U and player.rect.top &gt; 0: player.rect.top -= SPEED if player.direc == R and player.rect.right &lt; WINDOWWIDTH: player.rect.right += SPEED if player.direc == L and player.rect.left &gt; 0: player.rect.left -= SPEED #Draw the black background# windowSurface.fill(BLACK) #Draws foods onto the screen# for i in range(len(FOODS)): pygame.draw.rect(windowSurface,GREEN,FOODS[i]) #Handles the collision of the sanke with the foods# #Removes the foods and appends a new food to the list the increments the snake length# for food in FOODS: if player.rect.colliderect(food): FOODS.remove(food) FOODS.append(pygame.Rect(random.randint(FOODSIZE,WINDOWWIDTH-2*FOODSIZE), random.randint(FOODSIZE,WINDOWHEIGHT-2*FOODSIZE),FOODSIZE,FOODSIZE)) snakeLength += 1 #Ends the game if the snake hits the boundaries of the screen# if (player.rect.bottom &gt;= WINDOWHEIGHT or player.rect.top &lt;= 0 or player.rect.left &lt;= 0 or player.rect.right &gt;= WINDOWWIDTH): gameClose = True #Prints the entire length of the snake# #################################### snakeHead = [] snakeHead.append(player.rect.left) snakeHead.append(player.rect.top) snakeList.append(snakeHead) if len(snakeList) &gt; snakeLength: del snakeList[0] ourSnake(snakeSize, snakeList) #################################### #Causes a game over if the snake runs into itself# for x in snakeList[:-1]: if x == snakeHead: gameClose = True #Displays your score to the screen# yourScore(snakeLength - 1) pygame.display.update() mainClock.tick(10) pygame.quit() sys.exit() main() </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-05T01:18:23.540", "Id": "243399", "Score": "4", "Tags": [ "python", "python-3.x", "pygame", "snake-game" ], "Title": "Snake-game using Python 3 and PyGame" }
243399
<p>I am building a browser based Pre-Flop HUD that for now just tracks VPIP, PFR and number of hands played for an opponent (<a href="https://pokercopilot.com/poker-statistics/vpip-pfr" rel="nofollow noreferrer">https://pokercopilot.com/poker-statistics/vpip-pfr</a>). I am currently using local storage to store my data. In the future I will use a better persistence strategy, add more features, and find a way to de-couple the user interface without just putting it in the functions I have now. I used an object literal approach without classes right now to try out some basic decomposition with simple functions for practice. Right now the only functionality I have is adding a player to Local Storage and getting all players from Local Storage.</p> <p>Any suggestions for improvement are welcome. But I do have a couple questions:</p> <ol> <li><p>Is there a benefit to using Classes? Right now I don't see the benefit of having a handle, like, <code>player1 = new Player(arg,arg,etc...)</code>, <code>player2 = new Player(arg,arg, etc...)</code>...</p></li> <li><p>Is there a better way to store to Local Storage? I don't think storing each player with their own key and having a ton of entries is a good idea.</p></li> <li><p>In my function <code>addPlayer()</code> should I be calling <code>savePlayersToStorage</code> in my <code>localStorageUtils.js</code>?</p></li> </ol> <p><code>Main.js</code> <strong>file = entry point for my program</strong></p> <pre><code> /********************************** * This is the program driver, that * will call other functions * *******************************/ import { addPlayer } from "./player.js"; import { savePlayersToStorage, getPlayersFromStorage, } from "./LocalStorageUtilsObjectLiteral.js"; function main() { let newPlayer = "Doug Polk"; const localStorageKey = "stored_players"; let players = getPlayersFromStorage(localStorageKey); //array of player objects in localStorage players.push(addPlayer(newPlayer)); savePlayersToStorage(localStorageKey, JSON.stringify(players)); } main(); </code></pre> <p><code>Player.js</code> <strong>addPlayer creates and returns an object literal</strong></p> <pre><code>function addPlayer(name) { let player = { uuid: Date.now(), name: name, vpipActionCount: 0, //The number of times a player voluntarily put money into the pot Pre-Flop, whether calling or raising. pfrActionCount: 0, //The number of times a player raised pre-flop, this includes 3-bets. vpipPercentage: 0, //The percentage of hands a player has played, can be between 0 and 100% pfrPercentage: 0, //The percentage of hands a player has raised pre-flop, can be between 0 and 100%, but can never be higher than vpipPercentage totalHandsTracked: 0, //The number of hands tracked for a player callAction: function () { this.totalHands++; this.vpipActionCount++; }, raiseAction: function () { this.totalHands++; this.pfrActionCount++; }, foldAction: function () { this.totalHands++; }, calculateVpipPercentage: function () { this.vpip = (this.vpipActionCount * 100) / this.totalHands; }, calculatePfrPercentage: function () { this.pfrPercentage = (this.pfrActionCount * 100) / this.totalHands; }, getVpipPercentage: function () { return this.vpipPercentage; }, getPfrPercentage: function () { return this.pfrPercentage; }, }; return player; } export { addPlayer }; </code></pre> <p><code>LocalStorageUtils.js</code> <strong>Functions to get and save players to Local Storage</strong></p> <pre><code>function savePlayersToStorage(localStorageKey, playersArray) { if (localStorage.getItem(localStorageKey === null)) { localStorage.setItem(localStorageKey); } localStorage.setItem(localStorageKey, playersArray); } function getPlayersFromStorage(localStorageKey) { if (localStorage.getItem(localStorageKey === null)) { localStorage.setItem(localStorageKey); } let players = JSON.parse(localStorage.getItem(localStorageKey)); return players; } export { savePlayersToStorage, getPlayersFromStorage }; </code></pre>
[]
[ { "body": "<h1>To Your Questions</h1>\n<blockquote>\n<ol>\n<li>Is there a benefit to using Classes? Right now I don't see the benefit of having a handle, like, <code>player1 = new Player(arg,arg,etc...)</code>, <code>player2 = new Player(arg,arg, etc...)</code>...</li>\n</ol>\n</blockquote>\n<p>Maybe there are benefits, but I can't think of any serious ones now.</p>\n<p>The current version is similar to the <a href=\"https://en.wikipedia.org/wiki/Factory_method_pattern\" rel=\"nofollow noreferrer\">factory pattern</a>, where the creation of an object is abstracted by a factory - in this case <code>addPlayer</code>:</p>\n<pre><code>const player = addPlayer('Harry Potter');\n</code></pre>\n<hr />\n<blockquote>\n<ol start=\"2\">\n<li>Is there a better way to store to Local Storage? I don't think storing each player with their own key and having a ton of entries is a good idea.</li>\n</ol>\n</blockquote>\n<p>I think storing all players under one key is sufficient and the easiest to manage. But you can get the best of both worlds:</p>\n<p>Currently you are saving an array of players. Instead you could save a map where the key is a unique attribute of the player (maybe the name or an id) and the player itself. The benefit would be that you do not need to loop through an array to find a player:</p>\n<pre><code>function getPlayersFromStorage(key) {\n /* ... read from storage ... */;\n /* return has the form:\n {\n playername: player\n }\n */\n}\n\nconst players = getPlayersFromStorage(localStorageKey);\nconst harryPotter = players[&quot;Harry Potter&quot;];\n</code></pre>\n<p>This is only necessary if you need to find players directly.</p>\n<hr />\n<blockquote>\n<ol start=\"3\">\n<li>In my function <code>addPlayer()</code> should I be calling <code>savePlayersToStorage</code> in my <code>localStorageUtils.js</code>?</li>\n</ol>\n</blockquote>\n<p>It depends. Currently the method name <code>addPlayer</code> does not represent what the method does. When I first read the name I thought: <em>&quot;Ah ok, this methods put a player in some collection or maybe the local storage&quot;</em>. But then I read the following line and get confused:</p>\n<blockquote>\n<pre><code>players.push(addPlayer(newPlayer));\n</code></pre>\n</blockquote>\n<p>A better name for <code>addPlayer</code> would be <code>createPlayer</code> and I would not call <code>savePlayersToStorage</code> in it, to have smaller and side effect free functions.</p>\n<h1>Change Persistenz</h1>\n<blockquote>\n<p>I am currently using local storage to store my data. In the future I will use a better persistence strategy</p>\n</blockquote>\n<p>Currently, only the <code>main.js</code> depends on localStorage, and knows the implementation details, which would make it easier to change it in the future. However, to make it easier to change, especially as the code grows and more files depend on the persistence implementation, it should be abstracted as much as possible:</p>\n<pre><code>class LocalStorage {\n getAll() { /* ... */ }\n getByName() { /* ... */ }\n save() { /* ... */ }\n}\n\nclass OtherStorage {\n getAll() { /* ... */ }\n getByName() { /* ... */ }\n save() { /* ... */ }\n}\n</code></pre>\n<p>When your different storage strategies share the same interface they are easy interchange able:</p>\n<pre><code>// Main.js\n\nconst storage = new LocalStorage('my-storage-key');\n# const storage = new OtherStorage(/* dependencies */);\n\nfunction main() {\n const players = storage.getAllPlayers();\n const harryPotter = storage.getPlayerByName('Harry Potter');\n\n const newPlayer = createPlayer('Ron Weasley');\n const storage.save(newPlayer);\n}\n</code></pre>\n<h1>Read from Store</h1>\n<blockquote>\n<pre><code>function getPlayersFromStorage(localStorageKey) {\n if (localStorage.getItem(localStorageKey === null)) {\n localStorage.setItem(localStorageKey);\n }\n let players = JSON.parse(localStorage.getItem(localStorageKey));\n\n return players;\n}\n</code></pre>\n</blockquote>\n<p>When reading from the store we set an item if the key does not exists with <code>localStorage.setItem(localStorageKey)</code>. To set an item is not the responsibility for <em>reading</em> data. Instead we could add some logic which is related for reading. For example if there is stored data under the given key:</p>\n<pre><code>function getPlayersFromStorage(localStorageKey) {\n const fromStore = localStorage.getItem(localStorageKey);\n \n if (fromSore) {\n return [];\n }\n \n return JSON.parse(fromStore);\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-03T09:17:44.503", "Id": "244930", "ParentId": "243401", "Score": "0" } } ]
{ "AcceptedAnswerId": "244930", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-05T01:55:24.380", "Id": "243401", "Score": "2", "Tags": [ "javascript", "object-oriented" ], "Title": "Adding and Retrieving Players in a simple Pre-Flop Poker Hud with Local Storage" }
243401
<p>I'm working to understand Big O notation. As such I'm going through examples and the algorithm below generates the permutations for a given input string which contains only distinct characters. IE no duplicated or repeated characters in the input string.</p> <p>My thought process was to take each character and place it at every position within any previously generated strings.</p> <ul> <li>The single character string "a" can only generate "a".</li> <li>With "ab" the first character generates "a", as above. The next character 'b' would then be added before and after it to generate "ba" and "ab".</li> <li>With "abc" this would effectively take the list generated above and repeat the same procedure placing c at position 0, 1, and 2 producing <ul> <li>From "ba": "cba", "bca", "bac"</li> <li>From "ab": "cab", "acb", "abc"</li> </ul></li> <li>Etc...</li> </ul> <p>The nested loops, <code>foreach</code> and <code>for</code>, is a big flag as to how inefficient my current implementation is, <span class="math-container">\$O(n * n * n) = O(n^3)\$</span> if I've understood the notation correctly. How can I improve the structure to remove this nesting?</p> <pre><code>public class StringPermutation { public List&lt;string&gt; Generate(string source) { var list = new List&lt;string&gt;(); foreach (var c in source) //O(source.Length) { if (list.Count == 0) { list.Add(c.ToString()); } else { var beingBuilt = new List&lt;string&gt;(); foreach (var tempString in list) //O(list.Count) { for (int i = 0; i &lt; tempString.Length + 1; i++) //O(tempString.Length) { var built = tempString.Insert(i, c.ToString()); beingBuilt.Add(built); } } list = beingBuilt; } } return list; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-05T06:47:32.470", "Id": "477763", "Score": "0", "body": "How should your solution handle the following inputs: `aa`, `AaA`, `a a`? In other words do you need to have distinct result set?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-05T06:52:05.060", "Id": "477764", "Score": "0", "body": "I have only tested with lowercase distinct input of “a”, “ab”, “abc”, “abcde”, etc appending with the next letter. I’m staying with the simpler input string for now to get more experience." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-05T07:17:59.840", "Id": "477767", "Score": "0", "body": "In order to reduce Big O you should tackle the problem in a different way, which means you are looking for a different algorithm than this. For example using recursion tree. But as far as I know here we should not suggest alternative solutions, rather stick with your code and review that. But by reviewing your code we would not able to reduce the Big O :(" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-05T07:34:57.370", "Id": "477768", "Score": "0", "body": "I usually only know brute force methods to achieve a solution. I assume that if a more appropriate algorithm were available that would Be fair game for a review. Do you have a link of the name of the structure I should search for?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-05T07:54:02.743", "Id": "477769", "Score": "0", "body": "Search for *\"permutation with recursion tree\"* and you will find a couple of good really materials. If you search for \"c# all permutations of an array\" then you will find that SO thread, which will present **O(n)** and even **O(nlog(n))** solutions." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-05T10:56:18.990", "Id": "477775", "Score": "3", "body": "@PeterCsala \"But as far as I know here we should not suggest alternative solutions\" you are allowed to do this you just have to explain how it's better than the OP's code. Which is the only requirement when posting an answer, to teach (not give) the OP something better. For example contrast \"Use this <code dump>\" and \"You can improve the above by using <algorithm name> as it reduced Big O from \\$O(n^3)\\$ to \\$O(n^2)\\$.\"" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-05T12:58:50.407", "Id": "477784", "Score": "2", "body": "Note that the complexity of this algorithm is not O(n^3) but O(n*n!). The length of `list` in the kth iteration is (k-1)! and the insert operation generates a copy of the string with the new character inserted, which takes O(k) time." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-05T13:28:28.467", "Id": "477787", "Score": "2", "body": "Sorry, in my previous comment, I have missed the innermost loop, which adds another factor of k to the execution time of the kth iteration of the main loop, probably making the algorithm take O(n^2*n!) only." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-05T15:58:55.210", "Id": "477808", "Score": "0", "body": "@M.Doerner i.e. O(MG)? ;-)" } ]
[ { "body": "<p>Before making some general remarks about the C# code, I would like to explain why the complexity of this algorithm is already optimal, even though it is not the standard approach to tackle this problem. </p>\n\n<h2>Complexity Analysis</h2>\n\n<p>As already stated in a comment, your complexity analysis is way off. The problem is your assumption that the loop over <code>list</code> only multiplies the runtime by the length <span class=\"math-container\">\\$n\\$</span> of the source. However, the list grows each iteration of the outer loop.</p>\n\n<h3>How complex is it really?</h3>\n\n<p>To determine the real complexity, we have to have a closer look at what happens inside the outer loop. By design, the <code>list</code> will contain all permutations of the first <span class=\"math-container\">\\$(k-1)\\$</span> elements when the <span class=\"math-container\">\\$k^{th}\\$</span> iteration starts. Each element of <code>list</code> has length <span class=\"math-container\">\\$(k-1)\\$</span>, accordingly, and there are <span class=\"math-container\">\\$(k-1)!\\$</span> of them. So, in the <span class=\"math-container\">\\$k^{th}\\$</span> iteration, we generate <span class=\"math-container\">\\$((k-1)+1)\\cdot(k-1)! = k!\\$</span> new permutations. Since we have to save a new string of length <span class=\"math-container\">\\$k\\$</span> each time, which takes time <span class=\"math-container\">\\$k\\$</span>, up to a constant offset and multiplication with a constant, for each iteration we need <span class=\"math-container\">\\$k\\cdot k!\\$</span> character operations. This leaves us with a total runtime of <span class=\"math-container\">\\$\\sum_{k=1}^nk\\cdot k!\\$</span>.</p>\n\n<p>It is not really straight forward that this is smaller than a multiple of <span class=\"math-container\">\\$n\\cdot n!\\$</span>, i.e. that the complexity of the algorithm is <span class=\"math-container\">\\$O(n\\cdot n!)\\$</span>. As a first step, we can reduce the problem a bit using the fact that <span class=\"math-container\">\\$k\\leq n\\$</span>.</p>\n\n<p><span class=\"math-container\">\\$\\sum_{k=1}^nk\\cdot k! \\leq n \\cdot \\sum_{k=1}^nk! = n \\cdot n! \\cdot \\sum_{k=1}^n\\frac{k!}{n!}\\$</span></p>\n\n<p>Now, let us make a convenient approximation for the items in the sum on the rhs, using that <span class=\"math-container\">\\$ \\frac{1}{m} \\leq \\frac{1}{l} \\$</span> for <span class=\"math-container\">\\$ m \\geq l \\$</span>.</p>\n\n<p><span class=\"math-container\">\\$ \\frac{k!}{n!} = \\frac{1}{\\prod_{m=k+1}^n m} \\leq \\frac{1}{\\prod_{m=k+1}^n (m-k)} = \\frac{1}{\\prod_{l=1}^{n-k}l} = \\frac{1}{(n-k)!} \\$</span></p>\n\n<p>This approximation allows us to get on the track of the argument used in the complexity analysis of the approach to generate permutations more often used in literature, namely generating all prefixes of permutations of the string of increasing length via recursion.</p>\n\n<p><span class=\"math-container\">\\$ \\sum_{k=1}^n\\frac{k!}{n!} \\leq \\sum_{k=1}^n\\frac{1}{(n-k)!} = \\sum_{m=0}^{n-1}\\frac{1}{m!} \\leq \\sum_{m=0}^{\\infty}\\frac{1}{m!} = e\\$</span></p>\n\n<p>In the second equation, we used the the substitution <span class=\"math-container\">\\$m=n-k\\$</span>, which turns the summation order around. Moreover, for the last argument, one has to know that the exponential function is defined as function <span class=\"math-container\">\\$e^x = \\sum_{n=0}^\\infty \\frac{x^n}{n!}\\$</span>.</p>\n\n<p>The argument about convergence to a constant is similar in nature to that in the analysis of the average insert time into a dynamic array, which is often presented in CS classes. That argument uses a different series, though.</p>\n\n<h3>Why is this optimal?</h3>\n\n<p>To see that a <span class=\"math-container\">\\$O(n\\cdot n!)\\$</span> is optimal is not too hard. We know that there are <span class=\"math-container\">\\$n!\\$</span> many permutations and that we have to generate a string of length <span class=\"math-container\">\\$n\\$</span> for each, which each takes a number of character operations proportional to the length. So, we end up with at least <span class=\"math-container\">\\$n\\cdot n!\\$</span> character operations.</p>\n\n<h2>General Remarks</h2>\n\n<p>To be honest, I cannot find a lot to improve here regarding the coding style. One could separate the contents of the outer loop into a separate private function <code>Permutations(List&lt;string&gt; permutationsOfPrefix, char nextCharacter)</code>, but I think it is equally as valid to keep the algorithm contained in one single method, especially since it is not very long. I also do not think that using LINQ here would improve the readability.</p>\n\n<p>One point I think could be improved is there, though, the naming of variables. 'list' is a very generic name. I think <code>permutationsOfPrefix</code> would be more fitting. Accordingly, <code>tempString</code> could be <code>permutation</code> or <code>permutationOfPrefix</code> and <code>beingBuilt</code> could be <code>permutationsWithNextCharacter</code>. That would describe a bit better what is going on. Similarly, the <code>i</code> in the for loop could be named <code>insertionIndex</code>. </p>\n\n<p>Another possible improvement is to explicitly check whether the input string is <code>null</code> or empty at the start, to return an empty list in this case and, otherwise, to initialize <code>list</code> with the first character contained. This would allow to remove the if-else-statement inside the outer loop. However, it would require to iterate over <code>source.Drop(1)</code> in the outer loop.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-05T19:55:54.490", "Id": "243442", "ParentId": "243408", "Score": "5" } }, { "body": "<p>M.Doerner has explained the time complexity thoroughly, so I won't dive into that again. Instead I have refactored your solution in a way that makes your rather unorthodox algorithm more efficient (cuts the time with more than a half - but with same time complexity). See my inline comment below.</p>\n<pre><code>// HH: Return an IEnumerable&lt;string&gt; to make it possible to yield return each permutation when ready\npublic IEnumerable&lt;string&gt; GenerateReview(string source)\n{\n // HH: Start with a list with an empty string in order to have a uniform loop for all elements in source\n var permutations = new List&lt;string&gt; { &quot;&quot; };\n int capacity = 1; // HH: The capacity (count of permutations) in the next list of permutations\n\n // HH: Use a for loop (which is often faster than foreach) and because the index is used below\n for (int j = 0; j &lt; source.Length; j++)\n {\n // HH: Make the current char a string once\n string currentChar = source[j].ToString();\n // HH: Next permutation list is initialized with its number of permutations as capacity\n var nextPermutations = new List&lt;string&gt;(capacity *= (j + 1));\n\n foreach (var permutation in permutations)\n {\n for (int i = 0; i &lt; permutation.Length + 1; i++)\n {\n var nextPermutation = permutation.Insert(i, currentChar);\n nextPermutations.Add(nextPermutation);\n // HH: If at the last char in source - then yield return the full permutation\n if (j == source.Length - 1)\n yield return nextPermutation;\n }\n }\n\n permutations = nextPermutations;\n }\n}\n</code></pre>\n<p>It has still the same huge memory consumption for larger inputs. For instance a string like <code>&quot;ABCDEFGHIJK&quot;</code> will build a list of <code>11! = 39,916,800</code> strings before the method finally returns.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-06T12:17:52.737", "Id": "243473", "ParentId": "243408", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "9", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-05T04:46:35.997", "Id": "243408", "Score": "8", "Tags": [ "c#", "algorithm", "combinatorics" ], "Title": "Method to generate a List<string> containing permutation of an input string" }
243408
<p>The task is to write a function, which capitalize the first letter of all words in a string. For this we'll class a word as any characters separated by a blank. Because the standard <a href="https://ruby-doc.org/core-2.6/String.html#method-i-capitalize" rel="nofollow noreferrer"><code>String.capitalize</code></a> method only capitalizes the first character of the string I have written the following.</p> <p>Could the task be accomplished with writing less code? Any other improvements-suggestions concerning the function?</p> <p>Here's the code I have written:</p> <pre><code>def capitalizeAllWords(str) caps = str.split(" ").map do |word| word.capitalize end caps.join " " end puts capitalizeAllWords "Red orange green blue indigo violet" # Prints: "Red Orange Green Blue Indigo Violet" </code></pre>
[]
[ { "body": "<p>You could make it a one liner. If you want to get fancy checkout Rail's implementation <a href=\"https://apidock.com/rails/v5.2.3/ActiveSupport/Inflector/titleize\" rel=\"nofollow noreferrer\">https://apidock.com/rails/v5.2.3/ActiveSupport/Inflector/titleize</a></p>\n\n<pre><code>str.split.map(&amp;:capitalize).join(' ')\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-05T05:52:20.757", "Id": "477761", "Score": "0", "body": "Cool! Exactly, what I was looking for. Thanks a lot." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-05T06:06:00.520", "Id": "477762", "Score": "5", "body": "You have presented an alternative solution, but haven't reviewed the code. At least add *some* remarks on the original code. *What do you think of the five lines?* Afterwards, please explain your reasoning (why your code is better than the original) so that the author and other readers can learn from your thought process." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-05T05:28:50.563", "Id": "243410", "ParentId": "243409", "Score": "2" } }, { "body": "<p>I would solve this using a regular expression. like this:</p>\n<pre><code>def capitalizeAllWords(str)\n str.gsub(/\\b\\w/, &amp;:capitalize)\nend\n</code></pre>\n<p>where <code>\\b</code> matches a work break and <code>\\w</code> matches a word character</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-12T17:53:44.793", "Id": "243785", "ParentId": "243409", "Score": "1" } } ]
{ "AcceptedAnswerId": "243410", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-05T05:20:05.933", "Id": "243409", "Score": "5", "Tags": [ "ruby" ], "Title": "Ruby function to capitalize all words in a string" }
243409
<p>The idea was to write a context manager that would calculate energy consumption for the given machine learning pipeline running on a GPU. It does it by polling the current power consumption using the nvidia bindings library pynvml.</p> <p>The energy consumption is then calculated in KWh. The total pipeline consumption is the sum of the second-wise consumption over all the working time.</p> <p><span class="math-container">$$ \text{energy_consumption} = \text{current_power} * 1 / 3600 * 1/1000 $$</span></p> <p>Where 1/3600 — one second in hours, 1/1000 — to transform watts to kilowatts. </p> <p>There are two display options: live updates in a terminal or by writing a log file. </p> <p>Programmatically it works in the following way:</p> <p>Upon entering the context manager <code>PowerWatcher</code> spawns a new process which executes the <code>_watch_power</code> function. This function polls the GPU every 1 second, until it receives the SIGKILL or SIGTERM. In order to handle the signal properly, e.g. to close the log file, it uses the <code>_GracefulKiller</code>, which redefines the standard behavior: instead of termination, it just sets the <code>self.kill_now</code> flag to True. At the end of the block inside the context manager, it terminates the process with <code>_watch_power</code>. Finally, the total amount of energy, consumed by the pipeline is returned from the manager with the help of the <code>_ValueContainer</code>.</p> <p>Project repo: <a href="https://github.com/WGussev/PowerWatcher/tree/dev" rel="nofollow noreferrer">https://github.com/WGussev/PowerWatcher/tree/dev</a></p> <p>There are three questions, which I find particularly important:</p> <ol> <li>Is my way of passing information between the Processes correct?</li> <li>Is it OK to use the custom object <code>_ValueContainer</code> to pass a value from my context manager? </li> <li>Is the project structure appropriate, taking into account that I plan to distribute the package via PyPI?</li> </ol> <p>Usage example:</p> <pre><code>with PowerWatcher() as pw: ... do your ML-stuff ... print(pw.value) # get the overall consumption </code></pre> <pre><code>""" PowerWatcher -- python3 context manager to log power consumption of any ML-pipeline running on a Nvidia GPU. """ import signal import time from datetime import datetime from multiprocessing import Process, Pipe from multiprocessing.connection import Connection from pathlib import Path from pynvml import nvmlDeviceGetPowerUsage, nvmlDeviceGetHandleByIndex, nvmlInit class _GracefulKiller: """ SIGINT and SIGTERM catcher. Modifies process interruption behaviour: the kill_now flag is set to True instead of actually exiting the process. taken from: https://stackoverflow.com/questions/18499497/how-to-process-sigterm-signal-gracefully """ kill_now = False def __init__(self): signal.signal(signal.SIGINT, self.exit_gracefully) signal.signal(signal.SIGTERM, self.exit_gracefully) def exit_gracefully(self, signum, frame): """ Set kill_now flag. :param signum: required by signal.signal, not used directly :param frame: required by signal.signal, not used directly :return: """ self.kill_now = True class _ValueContainer: """Container to return values from a context manager.""" def __init__(self): self.value = 0 def update(self, value): """ Update stored value. :param value: a value to store. :return: """ self.value = value def _watch_power(logfile: Path = None, sender: Connection = None, display: bool = True): """ Poll GPU and log/display current power consumption. Update frequency: every 1 second. :param logfile: logfile path (the file will be created/overwritten). :param sender: sender-end connection. :param display: display consumption in terminal. :return: None """ if (logfile is None) and (display is False): raise ValueError('You should log and/or display consumption') total = 0 killer = _GracefulKiller() nvmlInit() handle = nvmlDeviceGetHandleByIndex(0) if logfile is not None: f = open(logfile, 'w') while not killer.kill_now: # exit gracefully power = int(nvmlDeviceGetPowerUsage(handle)) / 1000 # strangely nvidia outputs milliwatts total += power / 3600 / 1000 # convert to kWh if display: print(f'\r{datetime.now().strftime("%H:%M:%S")} {total:.5f} kWh so far', end='') if logfile is not None: f.write(f'{datetime.now()} {power}\n') time.sleep(1) if display: print('', end='\n') if sender is not None: sender.send(total) class PowerWatcher: """ Context manager to track pipeline energy consumption. Update frequency: every 1 second. with PowerWatcher() as pw: ... your pipeline ... pw.total # get results """ def __init__(self, logfile: Path = None, display: bool = True): """ :param logfile: logfile path. :param display: consumption display toggle. """ self.logfile = logfile self.display = display self.total = _ValueContainer() def __enter__(self): """Run upon entering the context.""" return self.start() def __exit__(self, exc_type, exc_value, traceback): """ Run on context exit. :param exc_type: required by Context Manager syntax but not really used here :param exc_value: required by Context Manager syntax but not really used :param traceback: required by Context Manager syntax but not really used :return: """ self.stop() def start(self): """Start manually.""" self.recv_end, send_end = Pipe(False) self.watcher = Process(target=_watch_power, args=(self.logfile, send_end, self.display,)) self.watcher.start() return self.total def stop(self): """Stop manually.""" self.watcher.terminate() self.total.update(self.recv_end.recv()) </code></pre> <p>Project tree: <a href="https://i.stack.imgur.com/QfU6y.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/QfU6y.png" alt="enter image description here"></a></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-05T12:36:22.757", "Id": "477783", "Score": "0", "body": "@Peilonrayz Sure, thank you, I've added some edits explaining the project. Hope, it'll be helpful" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-05T16:02:16.557", "Id": "477809", "Score": "0", "body": "Thank you for the added description, that's great! :D" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-05T08:45:58.557", "Id": "243412", "Score": "3", "Tags": [ "python", "python-3.x", "machine-learning" ], "Title": "Nvidia Energy Consumption Watcher" }
243412
<p>Code is running ok but need to be reviewed for any limitations / possible improvements. Not sure will work in all scenarios because of the number of ifs and else and length of the macro. Referred to <a href="https://stackoverflow.com/questions/62196686/comparing-2-column-ranges">this question</a> on Stack Overflow.</p> <pre><code>Sub StringCompare2() Dim Rg_1 As Range, Rg_2 As Range, Rg_3 As Range Dim cL_1 As Range, cL_2 As Range, cL_3 As Range Dim arr_1, arr_2 Dim xTxt As String, i As Long, j As Long, Ln As Long Dim xDiffs As Boolean On Error Resume Next If ActiveWindow.RangeSelection.Count &gt; 1 Then xTxt = ActiveWindow.RangeSelection.AddressLocal Else xTxt = ActiveSheet.UsedRange.AddressLocal End If lOne: Set Rg_1 = Application.InputBox("Range A:", "Kutools for Excel", xTxt, , , , , 8) If Rg_1 Is Nothing Then Exit Sub If Rg_1.Columns.Count &gt; 1 Or Rg_1.Areas.Count &gt; 1 Then MsgBox "Multiple ranges or columns have been selected ", vbInformation, "Kutools for Excel" GoTo lOne End If lTwo: Set Rg_2 = Application.InputBox("Range B:", "Kutools for Excel", "", , , , , 8) If Rg_2 Is Nothing Then Exit Sub If Rg_2.Columns.Count &gt; 1 Or Rg_2.Areas.Count &gt; 1 Then MsgBox "Multiple ranges or columns have been selected ", vbInformation, "Kutools for Excel" GoTo lTwo End If Set Rg_3 = Rg_2.Offset(0, 1) For Each cL_3 In Rg_3 i = i + 1 If cL_3.Offset(0, -2) = "" And cL_3.Offset(0, -1) = "" Then cL_3 = "" cL_3.Interior.Color = rgbLightGray GoTo NextCL3 End If If cL_3.Offset(0, -2) = "" And cL_3.Offset(0, -1) &lt;&gt; "" Then cL_3 = cL_3.Offset(0, -1) cL_3.Font.Color = vbBlue cL_3.Interior.Color = rgbOrange GoTo NextCL3 End If If cL_3.Offset(0, -2) &lt;&gt; "" And cL_3.Offset(0, -1) = "" Then cL_3 = cL_3.Offset(0, -2) cL_3.Font.Color = rgbLightGray cL_3.Font.Strikethrough = True cL_3.Interior.Color = rgbBlack GoTo NextCL3 End If If cL_3.Offset(0, -2) = cL_3.Offset(0, -1) Then cL_3 = cL_3.Offset(0, -1) cL_3.Font.Color = vbBlack cL_3.Interior.Color = rgbLightGreen GoTo NextCL3 End If arr_1 = Split(Rg_1(i, 1), " ", , vbTextCompare) arr_2 = Split(Rg_2(i, 1), " ", , vbTextCompare) For j = 0 To UBound(arr_1) + UBound(arr_2) Ln = Len(cL_3) If Ln = 0 Then If arr_1(j) = arr_2(j) Then cL_3.Value = arr_2(j) cL_3.Font.Color = vbBlack cL_3.Font.Strikethrough = False Else cL_3.Value = arr_1(j) &amp; " " &amp; arr_2(j) cL_3.Characters(1, Len(arr_1(j))).Font.Strikethrough = True cL_3.Characters(1, Len(arr_1(j))).Font.Color = rgbLightGray cL_3.Characters(Len(arr_1(j)) + 2, Len(arr_2(j))).Font.Strikethrough = False cL_3.Characters(Len(arr_1(j)) + 2, Len(arr_2(j))).Font.Color = vbRed End If Else If j &gt; UBound(arr_1) Then cL_3.Characters(Len(cL_3) + 1, Len(" " &amp; arr_2(j))).Insert (" " &amp; arr_2(j)) cL_3.Characters(Len(cL_3) - Len(" " &amp; arr_2(j)) + 1, Len(" " &amp; arr_2(j))).Font.Color = vbRed cL_3.Characters(Len(cL_3) - Len(" " &amp; arr_2(j)) + 1, Len(" " &amp; arr_2(j))).Font.Strikethrough = False Else If j &gt; UBound(arr_2) Then cL_3.Characters(Len(cL_3) + 1, Len(" " &amp; arr_1(j))).Insert (" " &amp; arr_1(j)) cL_3.Characters(Len(cL_3) - Len(" " &amp; arr_1(j)) + 1, Len(" " &amp; arr_1(j))).Font.Color = rgbLightGray cL_3.Characters(Len(cL_3) - Len(" " &amp; arr_1(j)) + 1, Len(" " &amp; arr_1(j))).Font.Strikethrough = True Else If arr_1(j) = arr_2(j) Then cL_3.Characters(Len(cL_3) + 1, Len(" " &amp; arr_2(j))).Insert (" " &amp; arr_2(j)) cL_3.Characters(Len(cL_3) - Len(" " &amp; arr_2(j)) + 2, Len(" " &amp; arr_2(j))).Font.Color = vbBlack cL_3.Characters(Len(cL_3) - Len(" " &amp; arr_2(j)) + 2, Len(" " &amp; arr_2(j))).Font.Strikethrough = False Else cL_3.Characters(Len(cL_3) + 1, Len(" " &amp; arr_1(j) &amp; " " &amp; arr_2(j))).Insert _ (" " &amp; arr_1(j) &amp; " " &amp; arr_2(j)) cL_3.Characters(Len(cL_3) - Len(" " &amp; arr_1(j) &amp; " " &amp; arr_2(j)) + 2, Len(arr_1(j))).Font.Strikethrough = True cL_3.Characters(Len(cL_3) - Len(" " &amp; arr_1(j) &amp; " " &amp; arr_2(j)) + 2, Len(arr_1(j))).Font.Color = rgbLightGray cL_3.Characters(Len(cL_3) - Len(" " &amp; arr_2(j)) + 2, Len(arr_2(j))).Font.Strikethrough = False cL_3.Characters(Len(cL_3) - Len(" " &amp; arr_2(j)) + 2, Len(arr_2(j))).Font.Color = vbRed End If End If End If End If Next NextCL3: Erase arr_1: ReDim arr_1(0) Erase arr_2: ReDim arr_2(0) Next End Sub </code></pre> <p><a href="https://i.stack.imgur.com/wDDER.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/wDDER.png" alt="enter image description here"></a></p>
[]
[ { "body": "<p>Here are some examples that show pretty odd results:</p>\n\n<p><a href=\"https://i.stack.imgur.com/X8yAa.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/X8yAa.png\" alt=\"enter image description here\"></a></p>\n\n<p>What I would expect as result is something like</p>\n\n<p><a href=\"https://i.stack.imgur.com/0KhKm.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/0KhKm.png\" alt=\"enter image description here\"></a></p>\n\n<p>Especially here </p>\n\n<p><a href=\"https://i.stack.imgur.com/KMKLr.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/KMKLr.png\" alt=\"enter image description here\"></a> </p>\n\n<p>where it says that <code>if</code> and <code>this</code> were deleted and added at the same place: <code>if this</code> should definitely be black.</p>\n\n<p><a href=\"https://i.stack.imgur.com/0QDno.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/0QDno.png\" alt=\"enter image description here\"></a></p>\n\n<hr>\n\n<p>Also here </p>\n\n<p><a href=\"https://i.stack.imgur.com/yZmz1.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/yZmz1.png\" alt=\"enter image description here\"></a> </p>\n\n<p>it says every single word was deleted and replaced by something else while you could just do the following </p>\n\n<p><a href=\"https://i.stack.imgur.com/TkhGO.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/TkhGO.png\" alt=\"enter image description here\"></a> </p>\n\n<p>and keep at least <code>to proove you wrong</code>. Note that this is only one possible solution and there are more than one for each comparison. To find the best solution you would need to calculate all possibilities and use a good criteria to decide which one of them would be the best one.</p>\n\n<p>As I already explained in <a href=\"https://stackoverflow.com/questions/58628570/how-can-i-output-the-matching-portion-of-two-strings-while-having-the-charact/58628990#58628990\">this answer</a> the probelem to solve is <strong>a way</strong> more complex than you see in the first moment. </p>\n\n<p>Especially if you want a <em>by charater</em> solution like the OP stated </p>\n\n<p><a href=\"https://i.stack.imgur.com/swNUc.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/swNUc.png\" alt=\"enter image description here\"></a></p>\n\n<p>and not a much simpler <em>by word</em> solution (as you tried).</p>\n\n<p>I see no simple answer to the issue beyond what I showed in the linked answer (using the dynamic programming technique).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-05T15:29:54.210", "Id": "477799", "Score": "0", "body": "Totally agree with you. That was my intention to show the case of cell C9 of the screen shot I submitted. Addition of just one word at the beginning made the entire replacement as new addition as it compares word by word and not by characters. Thanks for the link.. its a good food for thought over the weekend. Though, with my limited skills in Excel/ VBA, I don't see any road further on this. Thanks." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-05T13:32:36.773", "Id": "243425", "ParentId": "243417", "Score": "3" } } ]
{ "AcceptedAnswerId": "243425", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-05T10:44:12.700", "Id": "243417", "Score": "2", "Tags": [ "vba", "excel" ], "Title": "Compare text in two excel ranges, highlighting additions and strikethrough deletions" }
243417
<p>I've been trying to learn React and I'm currently building a time-tracking application. The-end goal of the app will be for users to be able to track time against different tasks from different projects.</p> <p>This is the stopwatch component I have built, with a start, end and reset button, and I would like to get a code review to see if I'm on the right path in terms of clean code and the use of React hooks.</p> <pre><code> import * as React from "react"; import styled from "styled-components"; import { useState, useEffect } from "react"; export interface IStopwatchProps {} export interface IStopwatchState {} const StartButton = styled.button` background: green; border-radius: 3px; border: 2px solid; color: white; margin: 0 1em; padding: 0.25em 1em; `; const StopButton = styled.button` background: red; border-radius: 3px; border: 2px solid; color: white; margin: 0 1em; padding: 0.25em 1em; `; const ResetButton = styled.button` background: white; border-radius: 3px; border: 2px solid; color: black; margin: 0 1em; padding: 0.25em 1em; `; const Stopwatch: React.FunctionComponent&lt;IStopwatchProps&gt; = ( props ): React.ReactElement =&gt; { const [seconds, setSeconds] = useState(0); const [minutes, setMinutes] = useState(0); const [hours, SetHours] = useState(0); const [displaySeconds, setDisplaySeconds] = useState("00"); const [displayMinutes, setDisplayMinutes] = useState("00"); const [displayHours, setDisplayHours] = useState("00"); const [isStopWatchRunning, setStopwatchState] = useState(false); const toggleState = () =&gt; setStopwatchState(!isStopWatchRunning); const resetStopwatch = () =&gt; { setSeconds(0); setMinutes(0); SetHours(0); setDisplaySeconds("00"); setDisplayMinutes("00"); setDisplayHours("00"); setStopwatchState(false); }; const setDisplayValue = (timeValue: number): string =&gt; { return timeValue &gt; 9 ? "" + timeValue.toString() : "0" + timeValue.toString(); }; useEffect(() =&gt; { let interval: number = 0; if (isStopWatchRunning) { interval = window.setInterval(() =&gt; { let displayValueSeconds = setDisplayValue(seconds); setDisplaySeconds(displayValueSeconds); let displayValueMinutes = setDisplayValue(minutes); setDisplayMinutes(displayValueMinutes); let displayValueHours = setDisplayValue(hours); setDisplayHours(displayValueHours); setSeconds(seconds + 1); if (seconds === 59) { setSeconds(0); setMinutes(minutes + 1); } if (minutes === 59) { setMinutes(0); SetHours(hours + 1); } }, 1000); } else if (!isStopWatchRunning &amp;&amp; seconds !== 0) { clearInterval(interval); } return () =&gt; clearInterval(interval); }, [isStopWatchRunning, seconds, minutes, hours]); return ( &lt;div&gt; &lt;StartButton onClick={toggleState}&gt;Start&lt;/StartButton&gt; &lt;StopButton onClick={toggleState}&gt;End&lt;/StopButton&gt; &lt;ResetButton onClick={resetStopwatch}&gt;Reset&lt;/ResetButton&gt; &lt;h1&gt; {displayHours} : {displayMinutes} : {displaySeconds} &lt;/h1&gt; &lt;/div&gt; ); }; export default Stopwatch; <span class="math-container">```</span> </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-05T17:24:41.910", "Id": "477816", "Score": "1", "body": "Maybe a rule of thumb that can help you: if you have 2 (or more) states that are always changing together, then they can be only one state. For example in the above example, it feels that you need only 2 states (maybe 3 for the `interval`): one to model if the watch is running or not and one for the number of seconds passed. Everything else can be computed during each render from this number of seconds. Doing it like that would probably help simplify the code a lot." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-05T11:12:59.023", "Id": "243420", "Score": "1", "Tags": [ "react.js", "typescript" ], "Title": "React with Typescript - stopwatch component" }
243420
<p>I'm sending and receiving data over an interface (serial in this case) with the following behaviour:</p> <ul> <li>The receiver sends back an Ack message if a message is delivered successfully.</li> <li>If an Ack is not received within a timeout, the command should be re-sent limited a number of times.</li> <li>Multiple clients may request sending at the same time, but no new commands should be sent until an Ack for the last command is received or it times out. Other sending commands shall wait until the channel is unreserved or they time out.</li> </ul> <p>The algorithm to do this is fairly simple. (Feel free to say so if you think it can be improved):</p> <p><a href="https://i.stack.imgur.com/p6hjK.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/p6hjK.png" alt="flow diagram" /></a></p> <p>The implementation in Go works as expected. I just feel there might be a smarter way to do it:</p> <pre class="lang-golang prettyprint-override"><code>package main import ( &quot;fmt&quot; &quot;math/rand&quot; &quot;time&quot; ) /****** Simulating the receiver behaviour ******/ var receiveChannel = make(chan string, 1) // Used to read messages from the interface func Read() string { return &lt;-receiveChannel } // Used to write messages to the interface func Write(data string) { // Randomly drop 50% of packets if n := rand.Intn(100); n &lt; 50 { receiveChannel &lt;- &quot;ACK&quot; } } /*******************************************/ var ackChannel = make(chan bool, 1) var sendChannel = make(chan string, 1) func run() { for { if Read() == &quot;ACK&quot; { ackChannel &lt;- true } } } func sendWrapper(data string) error { // Reserve the sending channel timeoutTimer := time.NewTimer(1 * time.Second) select { // This should block until sendChannel has a free spot or times out case sendChannel &lt;- data: timeoutTimer.Stop() fmt.Printf(&quot;Send chan reserved for command id=%v\n&quot;, data) case &lt;-timeoutTimer.C: return fmt.Errorf(&quot;timed out while waiting for send channel to be free. id=%v&quot;, data) } attempts := 2 err := send(data, attempts) // Free up the sending channel select { case x := &lt;-sendChannel: fmt.Printf(&quot;Send channel cleared %v\n&quot;, x) default: fmt.Printf(&quot;Send channel is empty. This should never happen!\n&quot;) } return err } func send(data string, attempts int) error { // Send data Write(data) // Wait for an ACK to be received ackTimeoutTimer := time.NewTimer(time.Millisecond * 100) select { case &lt;-ackChannel: ackTimeoutTimer.Stop() case &lt;-ackTimeoutTimer.C: // Retry again if attempts &gt; 1 { return send(data, attempts-1) } return fmt.Errorf(&quot;Timed out while waiting for ack. id=%v&quot;, data) } fmt.Printf(&quot;Frame sent and acked id=%v\n&quot;, data) return nil } /****** Testing ******/ func main() { go run() // Multiple goroutines sending data for i := 0; i &lt; 7; i++ { go func() { x := i if err := sendWrapper(fmt.Sprint(x)); err != nil { fmt.Println(err.Error()) } else { fmt.Printf(&quot;Sending successful. i=%v\n&quot;, x) } }() time.Sleep(10 * time.Millisecond) } time.Sleep(4 * time.Second) } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-08T19:31:09.793", "Id": "478093", "Score": "0", "body": "i would not use async style for a synchronous read/write api. Especially if you can handle only one command at a time. imo, for each write, there is a read with timeout, once the read pass, if it timedout, retry, if it acked process next command. Also it is unclear if multiple clients will be querying the same interface concurrently or not." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-10T13:51:46.477", "Id": "478270", "Score": "0", "body": "@mh-cbon thanks for the comment. I updated the question to mention that multiple clients may concurrently request to send, but only one command is sent at a time. This is shown in the first conditional block in the diagram.\n\nI'm afraid I don't get what you mean by \"i would not use async style for a synchronous read/write api\". Would you care to elaborate? Sending is synchronous. Requesting to send, however, is not." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-10T14:12:37.377", "Id": "478272", "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)*." } ]
[ { "body": "<p>You have at least one bug.</p>\n\n<hr>\n\n<p>The closure from your code:</p>\n\n<pre><code>package main\n\nimport (\n \"fmt\"\n \"time\"\n)\n\nfunc main() {\n for i := 0; i &lt; 7; i++ {\n go func() {\n x := i\n fmt.Printf(\"Sending successful. i=%v\\n\", x)\n }()\n }\n time.Sleep(4 * time.Second)\n}\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code>$ go run closure.go\nSending successful. i=7\nSending successful. i=7\nSending successful. i=7\nSending successful. i=7\nSending successful. i=7\nSending successful. i=7\nSending successful. i=7\n$\n</code></pre>\n\n<p>The <code>x := i</code> statement is in the wrong place. It should be:</p>\n\n<pre><code>package main\n\nimport (\n \"fmt\"\n \"time\"\n)\n\nfunc main() {\n for i := 0; i &lt; 7; i++ {\n x := i\n go func() {\n fmt.Printf(\"Sending successful. i=%v\\n\", x)\n }()\n }\n time.Sleep(4 * time.Second)\n}\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code>$ go run closure.go\nSending successful. i=4\nSending successful. i=5\nSending successful. i=1\nSending successful. i=3\nSending successful. i=2\nSending successful. i=0\nSending successful. i=6\n$\n</code></pre>\n\n<hr>\n\n<p>Reference:</p>\n\n<p><a href=\"https://golang.org/doc/faq\" rel=\"nofollow noreferrer\">Go: Frequently Asked Questions (FAQ)</a></p>\n\n<p><a href=\"https://golang.org/doc/faq#closures_and_goroutines\" rel=\"nofollow noreferrer\">What happens with closures running as\ngoroutines?</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-10T14:00:59.893", "Id": "478271", "Score": "0", "body": "Thanks. I updated the code" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-05T18:14:57.917", "Id": "243437", "ParentId": "243423", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-05T13:08:54.040", "Id": "243423", "Score": "2", "Tags": [ "algorithm", "go" ], "Title": "Blocking send and receive algorithm in Go" }
243423
<p>Does this process look protected from SQL injection attacks? </p> <p>Is there something I could possibly change to make it more protected?</p> <pre><code>&lt;?php include("../include/database.php"); if(isset($_POST['details'])) { $values = $_POST['details']; $param1 = htmlspecialchars(trim($values['param1'])); $param2 = htmlspecialchars(trim($values['param2'])); $conditions = []; $parameters = []; if (!empty($param1)) { $conditions[] = 'COLUMN1 LIKE ?'; $parameters[] = $param1."%"; } if (!empty($param2)) { $conditions[] = 'COLUMN2 = ?'; $parameters[] = $param2."%"; } try { $conn-&gt;setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $select = "SELECT COLUMN1, COLUMN2 FROM table"; if ($conditions) { $select .= " WHERE ".implode(" AND ", $conditions); } $stmt = $conn-&gt;prepare($select); $stmt-&gt;execute($parameters); $out = array(); while ($row = $stmt-&gt;fetch(PDO::FETCH_ASSOC)) { $out[] = $row; } echo json_encode($out); } catch(PDOException $e) { echo "Error: " . $e-&gt;getMessage(); } $conn = null; } ?&gt; </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-05T13:38:42.337", "Id": "477788", "Score": "2", "body": "It looks safe but it's twice the size it should be. For example in your other question you were using fetchAll() but now for some reason you don't" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-05T14:08:34.583", "Id": "477790", "Score": "1", "body": "You are intentionally looking for a literal `%` at the end of the second param? `$param2.\"%\";` And a separate question: what is the desired query if someone wants to search for the string `0`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-05T14:41:22.263", "Id": "477791", "Score": "0", "body": "@YourCommonSense - Are you referring to another question I asked on StackExchange? In regards to not using fetchAll(), I wasn't thinking about it. I wrote the script using fetch() and I got back the necessary results." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-05T14:43:15.767", "Id": "477792", "Score": "0", "body": "@mickmackusa - Yes, I was allowing the user to type in just a few letters. I'm not entirely sure what you mean about searching for the string 0. Would you please elaborate?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-05T21:05:12.737", "Id": "477835", "Score": "1", "body": "What does your code do? I get you're looking for vulnerabilities when interacting with SQL but a short description goes a long way. Additionally site policy is to be a short synopsis of your code, not what you want out of a review. Please [edit] your code to ammend these issues." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-05T21:07:35.160", "Id": "477836", "Score": "1", "body": "Is this only the target of an ajax call? You are not writing to the database. Do you need to use POST? Do you actually mean to use LIKE on both conditions in the WHERE?" } ]
[ { "body": "<p>It looks like your script is part of a basic ajax searching technique.</p>\n\n<ul>\n<li><code>$_POST</code> is typically used when writing to the database (or when there is a distinct reason that <code>$_GET</code> is unsuitable). Since you are merely SELECTing data, just use <code>$_GET</code>.</li>\n<li>if you are going to validate your incoming data, don't bother acquiring resources until after you have validated the incoming data and determined that it qualifies for a trip to the database. If you are going to default to SELECTing the whole table, then it doesn't matter.</li>\n<li>it looks like if params 1 and 2 are missing, you are happy to perform a full table SELECT. So why deny the full table SELECT if <code>details</code> isn't declared?</li>\n<li><code>empty()</code> is greedy -- it is looking for any falsey value. Even the string <code>0</code> - which has a length of 1 - is deemed empty. Perhaps do a <code>strlen()</code> check instead.</li>\n<li>I don't think that trimming should be forced on the data if part of a search string -- maybe the user wants to include the space.</li>\n<li>don't <code>htmlspecialchars()</code> as an attempt to improve security. The prepared statement is going to protect you from string injections. This call should be used when printing to screen, not querying the db.</li>\n<li>I think you have a typo in your second WHERE condition in that you mean to use a second LIKE but you have used <code>=</code> and kept the <code>%</code> appended to the value.</li>\n<li>I recommend that you design your table names and column names as lowercase strings to differentiate them from MYSQL keywords.</li>\n<li>you are not performing an data manipulations on the result set in this layer, so it will be more direct to <code>fetchAll()</code></li>\n<li>always provide a response string from this script; ideally every response should be json so that your response receiving script can be simpler.</li>\n<li>never show end users the raw error message. Give them a vague indication of an error and nothing more.</li>\n<li>As @YourCommonSense commented, you should move your <code>$conn-&gt;setAttribute</code> call your include file.</li>\n<li>Normal execution of your script will not be generating any errors. Catching the errors will prevent the logging of the errors. I recommend removing the try catch block. For continued researching, <a href=\"https://codereview.stackexchange.com/a/227420/141885\">start here</a>. </li>\n</ul>\n\n<p>Code:</p>\n\n<pre><code>$conditions = [];\n$parameters = []; \n\nforeach (['param1' =&gt; 'COLUMN1', 'param2' =&gt; 'COLUMN2'] as $param =&gt; $column) {\n if (isset($_GET['details'][$param]) &amp;&amp; strlen($_GET['details'][$param])) {\n $conditions[] = $column . \" LIKE ?\";\n $parameters[] = $_GET['details'][$param] . \"%\";\n }\n}\n\ninclude(\"../include/database.php\");\n$select = \"SELECT COLUMN1, COLUMN2 FROM table\";\nif ($conditions) {\n $select .= \" WHERE \" . implode(\" AND \", $conditions);\n} \n$stmt = $conn-&gt;prepare($select);\n$stmt-&gt;execute($parameters);\necho json_encode($stmt-&gt;fetchAll(PDO::FETCH_ASSOC));\n</code></pre>\n\n<hr>\n\n<p>In your ajax call, do not tell declare the response type as <code>html</code> -- it's not html, it is json. In doing so, you won't need to <code>parse</code> it.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-06T10:17:25.970", "Id": "477854", "Score": "0", "body": "Two corrections if you let me: `setAttribute` should be moved to database.php. PDOException **must** be logged and for this purpose and error is better to be served by a centralized error handler than a direct catch" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-06T10:23:58.027", "Id": "477856", "Score": "0", "body": "I am absolutely certain that you know more and are far more passionate about appropriate error handling than me. Are you intending to edit my post? Or wanting me to? I don't want to accidentally override your edit." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-06T10:27:43.360", "Id": "477857", "Score": "0", "body": "I forgot to advise about `$_GET` over `$_POST` when reading from the database. I am spending time with my wife right now, so I'll edit later." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-06T10:29:39.180", "Id": "477858", "Score": "0", "body": "I didn't think about editing, just thought the comment would serve as well. and yes, I agree about $_GET for the search." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-06T10:35:20.113", "Id": "477860", "Score": "3", "body": "Maybe it would be best if you posted an answer to talk about the error reporting. I don't think I can predict your preferred handling. I think I'd like to see it. In my own project, I would only want a handling technique that would not damage the UX. This way you can advise about the `setAttribute()` placement as well -- which I fully agee with." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-08T13:13:11.853", "Id": "478055", "Score": "0", "body": "I am getting a 500 error. Trying to diagnose..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-08T13:24:50.550", "Id": "478057", "Score": "1", "body": "My bad -- semicolon inside of `$response`. And as YCS said, please move `$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);` to inside your include file." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-08T13:26:37.727", "Id": "478058", "Score": "0", "body": "Actually, I think I found the problem. In the foreach, where $param => $column, I don't think $column is being set. When I print the array, it looks like this: \n\n Array\n(\n [0] => LIKE ?\n [1] => LIKE ?\n)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-08T13:28:04.290", "Id": "478059", "Score": "0", "body": "Should I just post a question on StackOverflow?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-08T13:28:13.597", "Id": "478060", "Score": "2", "body": "@JohnBeasley you are correct. Fixed that too. Nah, don't bother posting on SO, it's my responsibility to fix my dodgy snippet." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-08T13:35:11.523", "Id": "478061", "Score": "0", "body": "Updated per your suggestion, and the conditions are now showing the columns, but I am still getting a 500 error. Still diagnosing..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-08T13:36:23.800", "Id": "478062", "Score": "1", "body": "I'll be awake for a few more minutes." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-08T13:37:37.880", "Id": "478063", "Score": "0", "body": "The error seems to isolated to this part: $response = [\n 'status' => 'success',\n 'data' => $stmt->fetchAll(PDO::FETCH_ASSOC);\n ]; I can comment out 'data' => $stmt->fetchAll(PDO:FETCH_ASSOC); and I am getting 'success' in the console." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-08T13:46:34.430", "Id": "478068", "Score": "1", "body": "Yes, I have corrected that line in my answer. See the unwanted `;` after fetchAll()?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-08T14:06:12.487", "Id": "478071", "Score": "0", "body": "Well, I removed the semicolon, and I was no longer getting any errors. Problem is, I wasn't getting any data back either. I happened to change your $response = [] over to what I originally had using the while(), and then passing the $out variable. I indeed get data back using the while(). Does that make sense?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-08T22:06:55.197", "Id": "478097", "Score": "0", "body": "Regarding: https://stackoverflow.com/q/62134103/2943403 You need to be informing your ajax call to expect `json` not `html` -- then you won't need to `parse` the return value. Also, you will need need to check that `status` property before trying to access the `data` property (subarray) of the response. I'd like to know the feedback from your XHR tab of Developer tools." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-09T13:19:37.183", "Id": "478145", "Score": "0", "body": "Check out https://stackoverflow.com/questions/57166562/change-datatable-cell-background-function - The way I return the datatable in that question is similar to how I'm returning the datatable in this case." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-09T21:55:16.713", "Id": "478217", "Score": "2", "body": "@JohnBeasley I've updated my answer." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-10T13:46:53.383", "Id": "478269", "Score": "0", "body": "Thank you for your help. Everything works like a charm. I do appreciate it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-12T05:48:14.713", "Id": "478439", "Score": "0", "body": "Well, I need inspiration to write a good answer but this birdie is hard to catch and you never know when it dawns on you. Luckily it clicked though for the different question. @JohnBeasley please see my answer to the other question, which is largely applicable to your case in regard of general error reporting, https://codereview.stackexchange.com/a/243749/101565" } ], "meta_data": { "CommentCount": "20", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-05T22:05:07.000", "Id": "243449", "ParentId": "243424", "Score": "5" } } ]
{ "AcceptedAnswerId": "243449", "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-05T13:15:22.793", "Id": "243424", "Score": "2", "Tags": [ "php", "mysql", "pdo", "sql-injection" ], "Title": "Does this PDO process look protected from SQL injection?" }
243424
<p>I have just finished implementing a version of Conway's Game of Life using Java.</p> <p>Being only a college student, I am sure that my code is no where near perfect, and was wondering if you could look at my code. What can I improve on? Are there faster ways to implement certain areas of my code? Is there excess code that I can trim away? Is there a smarter way of implementing Conway's Game of Life?</p> <p><strong>EDIT:</strong></p> <p>In hopes of receiving more feedback, here is the theory behind my implementation:</p> <p>For reference, here are the rules for Conway's game of life (taken from wikipedia):</p> <ol> <li>Any live cell with fewer than two live neighbors dies, as if by underpopulation.</li> <li>Any live cell with tow or three live neighbors live on to the next generation.</li> <li>Any live cell with more than three live neighbors dies, as if by overpopulation</li> <li>Any dead cell with exactly three live neighbors becomes a live cell, as if by reproduction.</li> </ol> <p>Overview:</p> <ol> <li>A different outlook on Conway's Game of Life</li> <li>Unspoken rules</li> <li>Explanation of important methods (and data structures used)</li> </ol> <p><strong>A different outlook on Conway's Game of Life</strong></p> <p>Let us first imagine the Game of Life as a n x n grid (we will also assume that this grid has coordinates such that the bottom left hand corner is denoted as (0,0) and the top right hand corner is denoted as (n,n) where n is a positive integer). This 2-Dimensional grid represents a group of n*n number of cells. Each grid block can be thought of as a cell, which not only stores a Boolean value (dead or alive) to describe the cell’s status, but also details its location via its coordinates. In addition, the current state of all cells determines which cells will die, continue to live, or be born in the next generation in accordance to the rules found above.</p> <p>In a different perspective, however, Conway’s game of life is very similar to the game minesweeper. We can think of an alive cell as a mine, and its neighbors storing the number of mines that are closest to it. In this way, we are able to easily use the rules above to determine the future generation (particularly which cells will die, and which cells will be born).</p> <p>What about the cells that are currently alive you might ask? Well, we can easily represent these as an integer greater than 10, where the one’s place indicates how many alive neighbors the currently alive cell has, and the ten’s places indicates that the cell is alive. </p> <p><strong>Unspoken rules</strong></p> <p>One observation that occurred to me is that the game of life is only concerned about alive cells. Only cells that are alive can die, cells that continue to live have to already be living, and cells can only be born if they have neighbors that are alive. As a result, checking the entire grid (time complexity: O(n^2)) to determine the future generation of cells would be a complete waste. It would be a lot faster if I stored all the currently alive cells and checked each alive cell along with their neighbors to determine the next generation (which is exactly what I did).</p> <p><strong>Explanation of important methods (and data structures used)</strong></p> <p>birth(): iterates over a HashMap containing a key-value pair of all alive cells along with its neighbors. If the key-value pair follows the game of life’s rules above, the key (an integer value that represents the location of a cell) is then pushed onto a stack that contains the next generation of alive cells. After each iteration, the value of the grid is reset to 0, and the key-value pair is removed from the HashMap.</p> <p>insertAlive(): pops the stack and inserts the alive cell into the grid. Inserting a live cell follows the structure of minesweeper (neighbors of a live cell will be incremented by 1 and the alive cell will be incremented by 10 to denote that it is alive). All of the neighbors and alive cells are then put into a HashMap so that birth() can run properly</p> <p>printBoard() (should be named boardToString): uses a stringbuilder to format the grid into a string.</p> <p><strong>Note</strong>: most comments have been taken out because they don't add much to the readability of the code</p> <p><code>CellularAutomaton.java</code></p> <pre><code>package first; public abstract class CellularAutomaton{ public abstract String lifeCycle(); public abstract boolean rules(int num); } </code></pre> <p><code>GameOfLife.java</code></p> <pre class="lang-java prettyprint-override"><code>package first; import java.util.Stack; import java.util.HashMap; import java.util.Iterator; import java.util.Map; public class GameOfLife extends CellularAutomaton { int board[][]; int dim; Stack&lt;Integer&gt; stackCells; HashMap&lt;Integer, Integer&gt; hmapCells; public gameOfLife(int d, Stack&lt;Integer&gt; s){ board = new int[d][d]; dim = d; stackCells = s; hmapCells = new HashMap&lt;&gt;(); } public boolean rules(int num){ return num == 3 || num == 12 || num == 13; } private void birth() { Iterator&lt;Map.Entry&lt;Integer,Integer&gt;&gt; it=hmapCells.entrySet().iterator(); while(it.hasNext()) { Map.Entry&lt;Integer,Integer&gt; pair = it.next(); int key = pair.getKey(); if(rules(pair.getValue())){ stackCells.add(key); } board[key/dim][key%dim] = 0; it.remove(); } } private void insertAlive() { while(!stackCells.isEmpty()) { int cell = stackCells.pop(); int x = cell / dim; int y = cell % dim; int startX = (x &lt;= 0) ? 0 : x - 1; int startY = (y &lt;= 0) ? 0 : y - 1; int endX = (x &gt;= dim - 1) ? x + 1 : x + 2; int endY = (y &gt;= dim - 1) ? y + 1 : y + 2; for(int i = startX; i &lt; endX; ++i) { for(int j = startY; j &lt; endY; ++j) { hmapCells.put(i * dim + j, ++board[i][j]); } } hmapCells.put(cell, board[x][y] += 9); } } private String printBoard() { StringBuilder s = new StringBuilder(); for(int elements[] : board) { for(int element : elements) { if(element &gt;= 10){ s.append("* "); } else { s.append(" "); } } s.append("\n"); } return s.toString(); } public String lifeCycle() { birth(); insertAlive(); return printBoard(); } } </code></pre> <p><code>Simulation.java</code></p> <pre><code>package first; import java.util.Stack; public class Simulation { public static void main(String args[]) throws InterruptedException{ int dim = 70; Stack&lt;Integer&gt; init = new Stack&lt;&gt;(); //all vals pushed to init is of the form: xPos * dim + yPos init.push(351); init.push(352); init.push(421); init.push(422); init.push(245); init.push(246); init.push(315); init.push(316); init.push(361); init.push(431); init.push(501); init.push(292); init.push(572); init.push(223); init.push(643); init.push(224); init.push(644); init.push(435); init.push(296); init.push(576); init.push(367); init.push(437); init.push(507); init.push(438); init.push(231); init.push(301); init.push(371); init.push(232); init.push(302); init.push(372); init.push(163); init.push(443); init.push(165); init.push(445); init.push(95); init.push(515); GameOfLife gOL = new GameOfLife(dim, init); while(true) { System.out.print(gOL.lifeCycle()); Thread.sleep(100); System.out.print("\033[H\033[2J"); } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-05T18:12:26.010", "Id": "477819", "Score": "4", "body": "You've made a point of saying this is a different implementation, but there is nothing to explain the theory behind your implementation or the relatively obscure algorithms and formulas you're using." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-15T13:51:18.453", "Id": "478820", "Score": "1", "body": "This is a popular exercise so I would also advise you to take a look at the implementations you can find online: it's very instructive. I especially like [this gist](https://gist.github.com/timyates/112627bf46040a8099ac) that shows a reactive implementation in Java 8 (using RxJava) — not saying it would be a good _production_ code though." } ]
[ { "body": "<p>I just have one small recommendation regarding readability. When you have a method called <code>printBoard</code>, you would normally expect it to <em>print out the board</em>. A better name for that method would be <code>boardToString</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-05T14:13:27.230", "Id": "243428", "ParentId": "243426", "Score": "5" } }, { "body": "<p>First of all, I think the algorithm is pretty smart which is, for my humble experience, not so common for a college student. So congrats if you came up with it by yourself! If you're looking for smart implementations I would recommend functional ones, e.g. <a href=\"https://gist.github.com/ihabunek/81e7da0c705689fe743a#file-1-short-life-hs\" rel=\"nofollow noreferrer\">in Haskell</a>; see also <a href=\"https://codegolf.stackexchange.com/questions/3434/shortest-game-of-life\">Shortest game of life</a>.</p>\n<p>Now, beware of smartness. A good code should be <strong>easy to read</strong>, <strong>easy to understand</strong>. This is of course not always possible when dealing with complex algorithm but I believe that it should be a target.</p>\n<blockquote>\n<p><em>jjjjjjjjjjjj said:</em><br />\nNote: most comments have been taken out because they don't add much to the readability of the code</p>\n</blockquote>\n<p>The point of comments is to help people understand your code (generally speaking, focus on the &quot;why&quot; rather than on the &quot;what&quot;). Here, to help people understand you had to add <em>a lot</em> of text to your post. Ideally this isn't needed because the code is:</p>\n<ul>\n<li>self-documented,</li>\n<li>commented to clear complex/implicit stuff up.</li>\n</ul>\n<p>For instance, here is a quick rewrite of your code in an attempt to make the code more expressive:</p>\n<p><code>GameOfLife.java</code></p>\n<pre class=\"lang-java prettyprint-override\"><code>/**\n * Computes the next state of the automaton by using Conway's original rules.\n */\npublic class GameOfLife extends CellularAutomaton {\n\n /**\n * Stores all cells in a two-dimensional matrix. The value stored is\n * the number of live neighbors of the cell, +10 if the cell is alive.\n */\n private int board[][];\n private int dim;\n /*\n * index(cell) = cellX * dim + cellY\n */\n private Stack&lt;Integer&gt; indexesOfCellsAliveAtNextGeneration;\n private HashMap&lt;Integer, Integer&gt; cellsMaybeAliveAtNextGeneration;\n\n public GameOfLife(int d, Stack&lt;Integer&gt; s){\n board = new int[d][d];\n dim = d;\n indexesOfCellsAliveAtNextGeneration = s;\n cellsMaybeAliveAtNextGeneration = new HashMap&lt;&gt;();\n }\n\n public String newGeneration() {\n populateWorldWithAliveCellsFromPreviousGeneration();\n computeCellsMaybeAliveAtNextGeneration();\n return boardAsString();\n }\n\n private void populateWorldWithAliveCellsFromPreviousGeneration() {\n for (Map.Entry&lt;Integer, Integer&gt; cell : cellsMaybeAliveAtNextGeneration.entrySet()) {\n int cellIndex = cell.getKey();\n int cellValue = cell.getValue();\n \n if(willBeAlive(cellValue)){\n indexesOfCellsAliveAtNextGeneration.add(cellIndex);\n }\n\n board[cellIndex/dim][cellIndex%dim] = 0;\n }\n }\n\n private static boolean willBeAlive(int cell){\n return (!isAlive(cell) &amp;&amp; nbOfNeighbors(cell) == 3) \n || (isAlive(cell) &amp;&amp; (nbOfNeighbors(cell) == 2 || nbOfNeighbors(cell) == 3));\n }\n \n private static boolean isAlive(int cell) {\n return cell &gt;= 10;\n }\n \n private static int nbOfNeighbors(int cell) {\n return cell % 10;\n }\n\n private void computeCellsMaybeAliveAtNextGeneration() {\n cellsMaybeAliveAtNextGeneration.clear();\n\n while(!indexesOfCellsAliveAtNextGeneration.isEmpty()) {\n int cellIndex = indexesOfCellsAliveAtNextGeneration.pop();\n\n int cellX = cellIndex / dim;\n int cellY = cellIndex % dim;\n int topLeftNeighbourX = (cellX &lt;= 0) ? 0 : cellX - 1;\n int topLeftNeighbourY = (cellY &lt;= 0) ? 0 : cellY - 1;\n int bottomRightNeighbourX = (cellX &gt;= dim - 1) ? cellX + 1 : cellX + 2;\n int bottomRightNeighbourY = (cellY &gt;= dim - 1) ? cellY + 1 : cellY + 2;\n\n // Iterate through every cell's neighbor to increate their neighbor number\n\n for(int i = topLeftNeighbourX; i &lt; bottomRightNeighbourX; ++i) {\n for(int j = topLeftNeighbourY; j &lt; bottomRightNeighbourY; ++j) {\n boolean isNeighbor = i != cellX || j != cellY;\n if (isNeighbor) {\n int neighborIndex = i * dim + j;\n cellsMaybeAliveAtNextGeneration.put(neighborIndex, incrementedNumberOfNeighbors(i, j));\n }\n }\n }\n cellsMaybeAliveAtNextGeneration.put(cellIndex, makeAlive(cellX, cellY));\n }\n }\n \n private int incrementedNumberOfNeighbors(int x, int y) {\n return ++board[x][y];\n }\n \n private int makeAlive(int x, int y) {\n return board[x][y] += 10;\n }\n\n private String boardAsString() {\n StringBuilder s = new StringBuilder();\n\n for(int[] cells : board) {\n for(int cell : cells) {\n if(isAlive(cell)){\n s.append(&quot;* &quot;);\n }\n else {\n s.append(&quot; &quot;);\n }\n }\n s.append(&quot;\\n&quot;);\n }\n\n return s.toString().trim();\n }\n}\n</code></pre>\n<p>I mostly renamed some variables/methods and introduced some utility methods. The code is a bit longer ands feels more verbose but is IMHO also easier to understand. It is still very procedural (which is not bad per se, especially for such a simple program) but you may want to try to add more expressiveness by introducing new classes such as <code>Board</code> or <code>Cell</code>. You'll find such OO implementations <a href=\"https://github.com/dersoz/Game-of-Life\" rel=\"nofollow noreferrer\">on GitHub</a>.</p>\n<p>Your code may also run into memory issues with large boards. Indeed, your <code>board[][]</code> variable stores <em>all</em> the cells, even dead ones. With a 10000 x 10000 board containing only ~5/6 cells you'll waste a lot of memory. A solution is to use a <a href=\"https://en.wikipedia.org/wiki/Sparse_matrix\" rel=\"nofollow noreferrer\">sparse array</a> (basically, a set containing only alive cells).</p>\n<p>As a side note, a few years ago I also tried to model a highly-configurable GoL in a &quot;pure&quot; OO way; my code <a href=\"https://github.com/echebbi/game-of-life\" rel=\"nofollow noreferrer\">is on GitHub</a> if you want to check it out. The method computing the next generation of the world is <a href=\"https://github.com/echebbi/game-of-life/blob/e3c6533f55f88777ab045f385336c21ab7cc00ae/src/main/java/fr/kazejiyu/gameoflife/game/ImmutableGeneration.java#L194-L204\" rel=\"nofollow noreferrer\">ImmutableGeneration::nextGeneration</a>; given a set of alive cells, it basically: 1) compute all neighbors cells then 2) keep only those that will be alive. Rules indicating whether a cell will be alive or dead are implemented in <a href=\"https://github.com/echebbi/game-of-life/blob/e3c6533f55f88777ab045f385336c21ab7cc00ae/src/main/java/fr/kazejiyu/gameoflife/game/rules/Rule.java#L50-L58\" rel=\"nofollow noreferrer\">Rule.java</a>.</p>\n<hr />\n<p><strong>EDIT</strong>: <em><strong>personal</strong></em> opinion on conciseness versus verbosity when it comes to naming to answer a comment</p>\n<p>First of all, I believe that there are no right answers: it's all about tradeoffs and personal preferences. Naming is hard and you'll find plenty of articles on the subject.</p>\n<blockquote>\n<p>There are only two hard things in Computer Science: cache invalidation and naming things<br />\n— Phil Karlton</p>\n</blockquote>\n<p>My take is that conciveness is pleasant but can lead to ambiguities. And ambiguity, especially hidden one, is a threat. The first example that comes to my mind is mistakenly mixing units:</p>\n<pre class=\"lang-java prettyprint-override\"><code>// Everything looks good...\ndouble pathLength = distanceFromGoal + distanceToTarget;\n\n// ... but adding units makes easy to spot bugs\ndouble pathLengthInKilometers = distanceFromGoalInMeters + distanceToTargetInMillimeters;\n</code></pre>\n<p>That being said, long names do make the code harder to read. They can be reduced by taking two things into account:</p>\n<ul>\n<li>the context (e.g. name of the enclosing method / class / package),</li>\n<li>the scope (a local variable in a 3-line method may be fine with a short name whereas a function used multiple times across the whole codebase may need a longer one).</li>\n</ul>\n<p>That's also what is advised by <a href=\"https://google.github.io/styleguide/cppguide.html#General_Naming_Rules\" rel=\"nofollow noreferrer\">Google's naming conventions</a>.</p>\n<p>As a last note, as you suggested very long names may be seen as code smells. Usually, the issue is <a href=\"https://dzone.com/articles/single-responsibility-principle-done-right\" rel=\"nofollow noreferrer\">a lack of cohesion</a> (the class/method does too much different things — once again, no clear metrics on this, it's up to developer's feeling). For instance, in the code I proposed we may think of <code>populateWorldWithAliveCellsFromPreviousGeneration</code> as a method holding responsibilities: 1) computing the cells that will be alive at the next generation and 2) populating the world. We could thus split it in two: <code>populateWorldWith(aliveCellsFromPreviousGeneration())</code>.</p>\n<p>In the same way we could gather the attributes which name ends with &quot;atNextGeneration&quot; under a new <code>Generation</code> class:</p>\n<pre class=\"lang-java prettyprint-override\"><code>public class GameOfLife extends CellularAutomaton {\n\n private Generation lastGeneration;\n\n public String newGeneration() {\n this.lastGeneration = lastGeneration.nextGeneration();\n return this.lastGeneration.toString();\n }\n}\n\npublic class Generation {\n\n public Generation nextGeneration() {\n return new Generation(aliveAtNextGeneration(this.aliveCells));\n }\n\n ...\n\n}\n</code></pre>\n<p>But splitting the logic into too much classes will also increase the architecture complexity and make harder to understand the flow.</p>\n<p>As a conclusion I would advise you to keep in mind that any piece of code is susceptible to be modified by developers having no previous knowledge on the project and who must understand what the code does and <strong>why</strong> it does it so that they can maintain it or reuse parts without introducing regressions. There's no silverbullet: only tradeoffs, and what matters when you make a choice is that:</p>\n<ul>\n<li>you can identify the tradeoff,</li>\n<li>you understand the pros and cons of each alternative and choose one of them knowingly.</li>\n</ul>\n<p>(but don't push too much pressure on you: <a href=\"https://en.wikipedia.org/wiki/KISS_principle\" rel=\"nofollow noreferrer\">KISS</a> and remember that code can be refactored thereafter)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-18T05:19:50.800", "Id": "479163", "Score": "0", "body": "Thank you so much for your comment. I am so glad you commented because I would have never thought about only storing the alive cells (this changes a lot of my code, and in my opinion makes it a lot better). I wanted to ask a bit about your opinion on the balance between being clear with variable names and being concise. In other words, how can you determine when the program is too verbose? Does that mean that you have to spend an extraordinarily long time creating the right variable names or that there is something faulty with your logic and design of the code? Thanks again." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-18T14:48:48.607", "Id": "479222", "Score": "1", "body": "I edited my answer to share my view on it. It's a lot of text basically saying that \"there are no right answers, it's all about trade-offs so think about pros and cons when making a choice\"." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-15T16:35:20.423", "Id": "243929", "ParentId": "243426", "Score": "4" } } ]
{ "AcceptedAnswerId": "243929", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-05T13:56:22.727", "Id": "243426", "Score": "5", "Tags": [ "java" ], "Title": "Java: Conway's Game of Life" }
243426
<p>I want to join two fragments into one string with a separator, but when one of the fragments is empty I only want one of them.</p> <p>I have two implementations. The first is long and slightly repetitive, but I believe it is easier to understand, since it is a more step-by-step description of the process. The second is <em>way</em> shorter, but less self-explanatory. It uses the <code>Where</code> method, and it may not be clear to everybody what the semantics of <code>$_</code> are. Maybe both approaches can even be merged into an even better implementation.</p> <p>Which would you recommend?</p> <p>Version 1:</p> <pre><code>if ($Fragment1.Length -ne 0 -and $Fragment2.Length -ne 0) { $String = $Fragment2 + $Seperator + $Fragment2 } elseif ($Fragment1.Length -ne 0) { $String = $Fragment1 } elseif ($Fragment2.Length -ne 0) { $String = $Fragment2 } else { $String = $null } </code></pre> <p>Version 2:</p> <pre><code>$String = @($Fragment2, $Fragment1).Where({$_.Length -ne 0}) -join $Seperator </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-05T15:44:20.467", "Id": "477803", "Score": "0", "body": "As someone who doesn't use PowerShell I find the second easier to read." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-05T15:45:07.820", "Id": "477804", "Score": "0", "body": "OK, so you'd recommend V2?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-05T15:46:28.687", "Id": "477805", "Score": "0", "body": "Not really. I would use it. But I wouldn't recommend you to use it as you find it harder to read." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-05T15:49:44.803", "Id": "477806", "Score": "0", "body": "I'd like to make it clear that I'm not saying I dislike it. I am concerned about the readability of my code. I prefer version 2 myself." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-05T16:20:05.207", "Id": "477811", "Score": "0", "body": "No matter which implementation you choose, you should extract this code into a function called JoinSkipEmpty. This way it doesn't matter that much if the code is complicated or not since the name already expresses everything you need to know about the function. Oh, and please write `Separator` instead of `Seperator`. Your IDE should have told you this spelling mistake." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-05T16:29:19.213", "Id": "477812", "Score": "0", "body": "Sorry for the typo. Originally, it said something else, and I search-and-replaced it. Will correct." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-05T22:13:15.287", "Id": "477837", "Score": "0", "body": "if your input is ONE item, do you want to end up with `ItemSeparator` or just `Item`? ///// in any case, the `-join` operator is THE way to do what you are doing. it's fast, concise, well understood, and will NOT add the separator to the end of the things to be joined. if you need `ItemSeparator`, then you can add that with standard concatenation [the `+` operator]." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-06T00:36:34.403", "Id": "477842", "Score": "0", "body": "Yes, you're right, but `-join` doesn't do what I want. Notably, `\"fragment\", \"\" -join \"-\"` returns `\"fragment-\"`. I want to weed out the empty fragment." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-06T14:06:29.397", "Id": "477867", "Score": "0", "body": "i missed your reply since you didn't tag me. [*grin*] please take a look at my Answer for what i meant about `-join` being the way to go with this." } ]
[ { "body": "<p>here is what i meant about the <code>-join</code> operator being the way to go. [<em>grin</em>] you DO need to filter out the blank/null items, but once that is done things work neatly. i included two filters ... the basic <code>$_</code> test just uses the way that \"nothing\" and \"blank\" are coerced to booleans. the other uses the builtin <code>[string]::IsNullOrEmpty()</code> static method. </p>\n\n<pre><code># build some string arays to test with\n$1st = 'One', 'Two', 'Three'\n$2nd = 'Wun', $Null, 'Tree'\n$3rd = '', 'Too', ''\n$4th = 'A', 'B', ''\n\n$Separator = '-'\n\n# the leading comma forces the arrays to remain individual arrays instead of merging into one\nforeach ($Item in (,$1st + ,$2nd + ,$3rd + ,$4th))\n {\n 'Original ...'\n $Item\n 'Unfiltered [will glitch with empty items] ...'\n $Item -join $Separator\n 'Filtered with basic \".Where()\" test ...'\n $Item.Where({$_}) -join $Separator\n 'Filtered with explicit test ...'\n $Item.Where({-not [string]::IsNullOrEmpty($_)}) -join $Separator\n '=' * 30\n }\n</code></pre>\n\n<p>output ... </p>\n\n<pre><code>Original ...\nOne\nTwo\nThree\nUnfiltered [will glitch with empty items] ...\nOne-Two-Three\nFiltered with basic \".Where()\" test ...\nOne-Two-Three\nFiltered with explicit test ...\nOne-Two-Three\n==============================\nOriginal ...\nWun\nTree\nUnfiltered [will glitch with empty items] ...\nWun--Tree\nFiltered with basic \".Where()\" test ...\nWun-Tree\nFiltered with explicit test ...\nWun-Tree\n==============================\nOriginal ...\n\nToo\n\nUnfiltered [will glitch with empty items] ...\n-Too-\nFiltered with basic \".Where()\" test ...\nToo\nFiltered with explicit test ...\nToo\n==============================\nOriginal ...\nA\nB\n\nUnfiltered [will glitch with empty items] ...\nA-B-\nFiltered with basic \".Where()\" test ...\nA-B\nFiltered with explicit test ...\nA-B\n==============================\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-06T14:05:26.050", "Id": "243476", "ParentId": "243431", "Score": "0" } }, { "body": "<p>On PowerShell v6+, I would do the following:</p>\n<pre><code>$String = $Fragment1, $Fragment2 |\n Where-Object { -not [System.String]::IsNullOrWhiteSpace($_) } |\n Join-String -Separator $Separator\n</code></pre>\n<p>You could use <code>[System.String]::IsNullOrEmpty()</code> instead of <code>[System.String]::IsNullOrWhiteSpace()</code>, but I find <code>[System.String]::IsNullOrWhiteSpace()</code> to be the desired functionality in almost all cases.</p>\n<p>On Windows PowerShell (versions prior to v6), the <code>Join-String</code> command doesn't exist. There I would use:</p>\n<pre><code>$String = ($Fragment1, $Fragment2 |\n Where-Object { -not [System.String]::IsNullOrWhiteSpace($_) }) -join $Separator\n</code></pre>\n<p>The <code>@().Where({ ... })</code> method is fairly obscure, so I tend to avoid it.</p>\n<blockquote>\n<p>it may not be clear to everybody what the semantics of <code>$_</code> are.</p>\n</blockquote>\n<p>I'm not sure it's valuable to consider this possibility. Simply put, if your reader doesn't understand the semantics of <code>$_</code>, then they cannot read PowerShell. It's a ubiquitous and pervasive variable both in practice and in design.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-01T14:02:19.593", "Id": "244833", "ParentId": "243431", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "9", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-05T15:38:03.580", "Id": "243431", "Score": "3", "Tags": [ "strings", "comparative-review", "powershell" ], "Title": "Smartly joining possibly empty strings" }
243431
<p>I quite often find myself checking whether a given value is present in a given, possibly nested, container. For example, is <code>int val</code> present in the nested container <code>vector&lt;vector&lt;int&gt;&gt; values</code>? To me this looks like a good opportunity to practice with template functions while also cleaning my code. I wrote the following recursive template function for this.</p> <p>Do you have any suggestion to improve this? E.g, can it be shortened, can it be made more readable or more efficient, is the concept of namespaces correctly used, or should I maybe use a different coding style?</p> <p><strong>Note</strong>: I use gco as an abbreviation for General Container Operations.</p> <pre><code>// gco.h #pragma once #include &lt;algorithm&gt; namespace bs { namespace gco { /* * This function checks whether 'val' is found in the * given container 'source'. The function searches multiple * levels deep until it finds the same type as 'val' */ template&lt;typename T1, template &lt;typename&gt; typename Container, typename T2&gt; bool contains (Container&lt;T1&gt; const &amp;source, T2 const &amp;val) { if constexpr (std::is_same&lt;T1, T2&gt;::value) return std::find(std::cbegin(source), std::cend(source), val) != std::cend(source); else { for (auto const &amp;el: source) if (contains(el, val)) return true; return false; } } } } </code></pre> <p><strong>EDIT:</strong> minimum working example</p> <pre><code>#include "./gco.h" #include &lt;vector&gt; using namespace std; using namespace bs; int main() { vector&lt;int&gt; source_1 = {1, 2, 3, 4}; vector&lt;vector&lt;int&gt;&gt; source_2 = {{1,2}, {3,4}}; /* * 1) search a single int in a vector * 2) search a single int in a nested vector * 3) search a vector in a nested vector * * The following should print 1 0 1 0 1 0 */ cout &lt;&lt; gco::contains(source_1, 4) &lt;&lt; endl &lt;&lt; gco::contains(source_1, 5) &lt;&lt; endl &lt;&lt; gco::contains(source_2, 4) &lt;&lt; endl &lt;&lt; gco::contains(source_2, 5) &lt;&lt; endl &lt;&lt; gco::contains(source_2, vector&lt;int&gt;({1,2})) &lt;&lt; endl &lt;&lt; gco::contains(source_2, vector&lt;int&gt;({1,3})) &lt;&lt; endl; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-08T11:00:42.787", "Id": "478023", "Score": "1", "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)*." } ]
[ { "body": "<p>Neat idea.</p>\n<pre><code>template&lt;typename T1, template &lt;typename&gt; typename Container, typename T2&gt;\nbool contains (Container&lt;T1&gt; const &amp;source, T2 const &amp;val)\n</code></pre>\n<p>I’m not sure a template template parameter is necessary here, or even a good idea. It prevents the function from being used with containers that <em>aren’t</em> templates… or that aren’t the kind of templates you expect.</p>\n<p>There is a standard definition for “<a href=\"https://en.cppreference.com/w/cpp/named_req/Container\" rel=\"nofollow noreferrer\">container</a>”. (There’s also a more-or-less matching proposed concept in the range-v3 library.) Under that definition you could get <code>T1</code> as <code>typename Container::value_type</code>.</p>\n<pre><code>if constexpr (std::is_same&lt;T1, T2&gt;::value)\n</code></pre>\n<p>I don’t think <code>is_same</code> is the test you really want to be applying here, because it precludes all kinds of useful cases. For example, let’s say you have a vector of strings, and the key you want to search for is a <code>string_view</code>:</p>\n<pre><code>auto strings = std::vector&lt;std::string&gt;{/*...*/};\n\nauto const search_key = &quot;to be found&quot;sv;\n\n// This won't work\nif (contains(strings, search_key))\n // ...\n</code></pre>\n<p>What you want is really the C++20 concept <code>std::equality_comparable_with</code>. Lacking concepts in C++17, you could roll a type trait that does the same test.</p>\n<pre><code>return std::find(std::cbegin(source), std::cend(source), val) != std::cend(source);\n</code></pre>\n<p>Using the fully-qualified forms of <code>std::cbegin</code> and <code>std::cend</code> prevents ADL, which could break basically any container not defined in the <code>std</code> namespace.</p>\n<p>You should use the standard pattern:</p>\n<pre><code>using std::cbegin;\nusing std::cend;\n\nreturn std::find(cbegin(source), cend(source), val) != cend(source);\n</code></pre>\n<p>Also, I’d suggest using <code>begin</code> and <code>end</code> rather than <code>cbegin</code> and <code>cend</code>. Why? Because it doesn’t matter, since <code>source</code> is <code>const</code>, but third-party containers may not have bothered to add support for <code>cbegin</code> and <code>cend</code> (<code>begin</code> and <code>end</code> should be universal).</p>\n<p>I think you really need some additional type traits (or concepts, if you’re targeting C++20) to make this work. First, a type trait <code>is_container</code> would be very handy for making the function produce better errors, and for helping with the internals:</p>\n<pre><code>template &lt;typename Container, typename T&gt;\nauto contains(Container const&amp; source, T const&amp; val) -&gt;\n std::enable_if_t&lt;is_container_v&lt;Container&gt;, bool&gt;\n</code></pre>\n<p>Or perhaps, rather than using SFINAE, you could use a <code>static_assert</code>:</p>\n<pre><code>template &lt;typename Container, typename T&gt;\nauto contains(Container const&amp; source, T const&amp; val) -&gt; bool\n{\n static_assert(is_container_v&lt;Container&gt;);\n</code></pre>\n<p>You could also use an <code>equality_comparable_with</code> trait, to allow for more flexibility:</p>\n<pre><code>template &lt;typename Container, typename T&gt;\nauto contains(Container const&amp; source, T const&amp; val) -&gt; bool\n{\n if constexpr (is_equality_comparable_with_v&lt;typename Container::value_type, T&gt;)\n // ...\n</code></pre>\n<p>Those two type traits will also help when testing for whether recursion is possible.</p>\n<pre><code>template &lt;typename Container, typename T&gt;\nauto contains(Container const&amp; source, T const&amp; val) -&gt; bool\n{\n if constexpr (is_equality_comparable_with_v&lt;typename Container::value_type, T&gt;)\n // just use std::find\n else if constexpr (is_container_v&lt;typename Container::value_type&gt;)\n // recurse\n else\n // error\n</code></pre>\n<p>Those type traits will help a <em>lot</em> when there are problems; they can make a huge difference in the size and readability of the error messages you get if you’re dealing with deeply nested containers.</p>\n<p>Other than that, the only other thing I can think to suggest is to make the function <code>constexpr</code>. Because why not?</p>\n<h1>Questions</h1>\n<h2>You say &quot;containers that aren’t templates&quot; and &quot; templates you expect&quot;, can you add 1 or 2 examples of this?</h2>\n<p>In order for a container-like type to work with your template template parameter, 3 things must be true:</p>\n<ol>\n<li>It must be a template.</li>\n<li>It must have 1 template type parameter (with any subsequent template parameters aliased or defaulted away).</li>\n<li>That parameter must be the same as the container’s value type.</li>\n</ol>\n<p>For an example that fails the first case: <code>std::filesystem::directory_iterator</code>. It is not a template. So this works:</p>\n<pre><code>auto dir = std::filesystem::directory_iterator(&quot;.&quot;);\nif (std::find(begin(dir), end(dir), &quot;foo&quot;) != end(dir))\n std::cout &lt;&lt; &quot;foo is in current working directory&quot;;\n</code></pre>\n<p>but this won’t work:</p>\n<pre><code>auto dir = std::filesystem::directory_iterator(&quot;.&quot;);\nif (gco::contains(dir, &quot;foo&quot;))\n std::cout &lt;&lt; &quot;foo is in current working directory&quot;;\n</code></pre>\n<p>For an example that fails the second case: <code>std::array</code>. Your function expects a template with a single type parameter (and anything else defaulted away). <code>std::array</code> has a type parameter… and a non-type parameter (which is not defaulted). It’s certainly a container, and a template, but not the kind of template you expect.</p>\n<p>So this works:</p>\n<pre><code>auto numbers = std::array&lt;int, 5&gt;{1, 2, 3, 4, 5};\nif (std::find(begin(numbers), end(numbers), 3) != end(numbers))\n std::cout &lt;&lt; &quot;found 3&quot;;\n</code></pre>\n<p>but this won’t work:</p>\n<pre><code>auto numbers = std::array&lt;int, 5&gt;{1, 2, 3, 4, 5};\nif (gco::contains(numbers, 3))\n std::cout &lt;&lt; &quot;found 3&quot;;\n</code></pre>\n<p>For an example that fails the third case… I can’t think of anything off the top of my head. This would require a container template whose first template parameter is not the container’s value type. That would be an odd thing to do (there’s certainly nothing like that in the standard library)… but it could happen!</p>\n<h2>You suggest to use the standard definition for container. Can you show me how this is done?</h2>\n<p>In a perfect world, the standard library would have done this for you. (And it <em>will</em> do it for you, but not until C++20.)</p>\n<p>But if we’re going to get into this, we really need to tighten up some terminology. I don’t think you want <code>contains()</code> to be a <em>container</em> operation. I think you want it to be a <em>range</em> operation.</p>\n<p>In C++ lingo, a <em>container</em> is a type that <em>holds</em> a bunch of stuff. <code>std::vector</code>, <code>std::list</code>, <code>std::map</code>, and so on, they’re all containers. They <em>own</em> their contents; when the container is destroyed, so are all the contents.</p>\n<p>But there are other things that are container-like but not containers. As of C++17, there are also <em>views</em>.</p>\n<p>A <em>view</em> is a type that provides a container-like view of stuff, but <em>does not hold that stuff</em>. As of C++17, the only view in the standard library (unless I’m forgetting something) is <code>std::string_view</code>, though there are lot more in the pipes, like C++20’s <code>std::span</code>. <code>std::string_view</code> does not <em>own</em> its contents. By contrast, <code>std::string</code>, which <em>is</em> a container, does.</p>\n<p>I’m pretty sure you’d want <code>gco::contains()</code> to work with <code>std::string_view</code>. So obviously you want to support more than just containers.</p>\n<p>And there are still other things that are neither containers nor views, but still seem like they should be able to work with <code>gco::contains()</code>. There’s nothing really in the standard library yet, but there’s a <em>lot</em> coming in future. For example, coroutines would bring generators. I can imagine a function that checks whether a number is part of the Fibonacci sequence that works something like this:</p>\n<pre><code>// fibonacci_sequence() is a generator that returns successive\n// elements in the Fibonacci sequence: 1, 2, 3, 5, 8, 13, ...\nif (gco::contains(fibonacci_sequence(), number))\n std::cout &lt;&lt; number &lt;&lt; &quot; is in the Fibonacci sequence&quot;;\n</code></pre>\n<p>The generic C++ concept that covers both containers and views and more (including types that provides a container-like view of stuff, but not only don’t own the stuff, <em>the stuff might not actually exist</em>) is <em>range</em>. C++20 will be bringing a long-awaited range library, but C++ has been taking baby steps to support ranges since all the way back in C++11, with the range-<code>for</code>-loop.</p>\n<p>I think what you’re making is not a library of generalized <em>container</em> operations, but rather a <em>range</em> library.</p>\n<p>Now, if this were C++20, everything would be trivial. You could just do:</p>\n<pre><code>template &lt;typename&gt; struct dependent_false : std::false_type {};\n\ntemplate &lt;typename T&gt;\nconstexpr auto dependent_false_v = dependent_false&lt;T&gt;::value;\n\ntemplate &lt;std::input_range Container, typename T&gt;\nconstexpr auto contains(Container const&amp; source, T const&amp; val) -&gt; bool\n{\n using value_type = std::ranges::range_value_t&lt;Container&gt;;\n\n using std::begin;\n using std::end;\n\n if constexpr (std::equality_comparable_with&lt;value_type, T&gt;)\n return std::find(begin(source), end(source), val) != end(source);\n else if constexpr (std::input_range&lt;T&gt;)\n return std::any_of(begin(source), end(source), [&amp;val](auto&amp;&amp; el) { return contains(el, val); });\n else\n static_assert(dependent_false_v&lt;Container&gt;);\n}\n</code></pre>\n<p>Unfortunately, in C++17, you don’t have concepts, so you have to roll your own type traits to do the tests.</p>\n<p>Okay, so… how? Well, the first thing you need to do is figure out what the requirements are. A minimal range is anything that works with range-<code>for</code>. That requires at least:</p>\n<ul>\n<li><code>begin()</code></li>\n<li><code>end()</code></li>\n<li>that the return types of <code>begin()</code> and <code>end()</code> can be equality-compared</li>\n<li>that the return type of <code>begin()</code> supports <code>operator++</code>; and</li>\n<li>probably a few other things I’m forgetting.</li>\n</ul>\n<p>You can test the first two requirements with something like:</p>\n<pre><code>template &lt;typename Range&gt;\nconstexpr auto adl_begin(Range&amp;&amp; r)\n{\n using std::begin;\n return begin(r);\n}\n\ntemplate &lt;typename Range&gt;\nconstexpr auto adl_end(Range&amp;&amp; r)\n{\n using std::end;\n return end(r);\n}\n\ntemplate &lt;typename T, typename = void&gt;\nstruct has_begin_support : std::false_type {};\n\ntemplate &lt;typename T&gt;\nstruct has_begin_support&lt;T, std::void_t&lt;decltype(adl_begin(std::declval&lt;T&gt;()))&gt; : std::true_type {};\n\ntemplate &lt;typename T, typename = void&gt;\nstruct has_end_support : std::false_type {};\n\ntemplate &lt;typename T&gt;\nstruct has_end_support&lt;T, std::void_t&lt;decltype(adl_end(std::declval&lt;T&gt;()))&gt; : std::true_type {};\n</code></pre>\n<p>Then make similar type traits to check that the return type of <code>begin()</code> is equality comparable with the return type of <code>end()</code>, and that the return type of <code>begin()</code> is an input iterator, and so on… and eventually put it all together as a single type trait.</p>\n<p>Yes, that’s a shitload of work (unless you use a library like <a href=\"https://ericniebler.github.io/range-v3/\" rel=\"nofollow noreferrer\">range-v3</a> which I <em>HIGHLY</em> recommend), but that’s why C++ programmers get the big bucks.</p>\n<p>Now, this next bit is an opinionated rant:</p>\n<blockquote class=\"spoiler\">\n<p> <p>Honestly, I’ve started suggesting to programmers to consider targeting C++20, rather than C++17, even though C++20 isn’t fully officially out yet, and compiler support is as yet anemic. C++20 is the biggest update to C++ since C++11… and it might be even <em>bigger</em>. <em>EVERYTHING</em> will change once C++20 is the norm, probably even far more so than it did when C++11 came around. The amount of code you’d have to write to do <code>contains()</code> <em>well</em> in C++17 is dozens and dozens, if not <em>hundreds</em> of lines of arcane SFINAE crap that only experts understand with bullshit like <code>enable_if</code> and <code>void_t</code>. In C++20? It’s like, 10-12 lines, all obvious, simple, and brief (well, except maybe for the <code>dependent_false</code> trick, but that might not even be necessary, depending on how clear compiler errors are in C++20 mode).</p>\n\n <p>So it might be worth your while to hold off on writing a container ops library, and for now spend the time reading up on what’s coming in C++: like concepts, modules, and particularly the ranges library. Then when you’re ready, hopefully compiler support will have caught up, and you can roll out this library easily.</p>\n\n <p>If you <em>really</em> want to target C++17 with your library, that’s fine—there’s very little you <em>can’t</em> do in C++17 (it’s just <em>MUCH</em> easier in C++20). Just understand that you will be diving into a deep, deep well of very, very complicated stuff, and—and this is the worst part—even if you just want to do it for the learning experience, it will be mostly a waste of time, because the skills you’ll learn will be obsolete in a few months.</p></p>\n</blockquote>\n<h2>you suggest either using 'std::enable_if_t' or a static_assert. Is one of the two preferred or more common?</h2>\n<p>That’s an engineering question, meaning the answer is: there is no right answer; it depends on what you want.</p>\n<p>Both methods will trigger a compile error if the constraints are not met. The difference is how.</p>\n<p><code>static_assert</code> is easier to understand. If the constraint fails, the compile just dies. That’s it. Nothing fancy. It’s so brutally simple, that it actually requires tricks to make it <em>not</em> fail when you don’t want it to. If you look at the C++20 version of <code>contains()</code> I wrote above, the static assert uses <code>dependent_false</code>:</p>\n<pre><code>static_assert(dependent_false_v&lt;Container&gt;);\n</code></pre>\n<p>If I’d just done:</p>\n<pre><code>static_assert(false);\n</code></pre>\n<p>it would just fail, always. Literally always—no code that uses <code>contains()</code> would compile. “But,” you say, “that <code>static_assert</code> is in the <code>else</code> part of an <code>if constexpr</code>!” Doesn’t matter. <code>static_assert</code> doesn’t care. When that function is compiled, if the compiler sees <code>static_assert(false)</code>, it just dies immediately, before even bothering to check the rest of the function, before even realizing which branch of the <code>if constexpr</code> it’s in. The <code>dependent_false</code> trick is a way to confuse the compiler temporarily: it doesn’t see the false until <em>after</em> it parses everything in the function… at which point it then sees it’s in an <code>else</code> that doesn’t apply, so it ignores the assertion.</p>\n<p><code>enable_if</code> is more complicated. What it does (assuming you use it right) is <em>remove the function from the overload set temporarily</em>.</p>\n<p>To understand what that means, imagine you have two overloads of <code>template &lt;typename T&gt; foo(T)</code> with different return types, then you call <code>foo(0)</code> (with <code>T</code> as an <code>int</code>):</p>\n<pre><code>template &lt;typename T&gt;\nauto foo(T) -&gt; T { std::cout &lt;&lt; &quot;int&quot;; return {}; }\n\ntemplate &lt;typename T&gt;\nauto foo(T) -&gt; typename T::value_type { std::cout &lt;&lt; &quot;T::value_type&quot;; return {}; }\n\nfoo(0); // what happens?\n</code></pre>\n<p>Well, first the compiler collects all the possibilities. So the overload set consists of both <code>foo()</code> functions.</p>\n<p>Then the compiler eliminates obvious failures. In this case, <code>foo(0)</code> can’t <em>possibly</em> be calling the overload that returns <code>T::value_type</code>… because <code>int</code> does not have a <code>value_type</code> subtype: <code>int::value_type</code> is nonsense. So that overload is eliminated, leaving only the overload that returns <code>T</code>.</p>\n<p>With only one possibility left, the compiler accepts that <code>foo(0)</code> means the first overload. The program compiles, and prints “int”.</p>\n<p>If you try to use a <code>std::string</code> (which has a <code>value_type</code>) instead of an <code>int</code>, <em>both</em> overloads are valid, and you’ll get an error because the call is ambiguous.</p>\n<p>What <code>enable_if</code> does is gives you control over the elimination step. It basically says “only include this function in the set of potential overloads if the condition is true”. If the condition is false, then it’s as if the function doesn’t exist.</p>\n<p>Why is that cool? Well consider if you did this:</p>\n<pre><code>template &lt;typename Container, typename T&gt;\nauto contains(Container const&amp; source, T const&amp; val) -&gt; bool\n{\n static_assert(is_container_v&lt;Container&gt;);\n</code></pre>\n<p>Then when you call <code>contains(something, other)</code> and <code>something</code> is not a container, the <code>static_assert</code> fires, and the whole compile dies. That may be exactly what you want.</p>\n<p><em>But</em>!… Maybe if <code>something</code> is not a container, there is some other overload of <code>contains()</code> that might be suitable (“contains” is a common name, after all!).</p>\n<p>So if you did this:</p>\n<pre><code>template &lt;typename Container, typename T&gt;\nauto contains(Container const&amp; source, T const&amp; val) -&gt;\n std::enable_if_t&lt;is_container_v&lt;Container&gt;, bool&gt;\n</code></pre>\n<p>(or used a concept; a concept basically does the same thing as <code>enable_if</code>), then called <code>contains(something, other)</code> where <code>something</code> is not a container, you don’t <em>immediately</em> get a compile failure. Instead, this function just… disappears. Like it was never written. The compiler goes on searching for all the other overloads of <code>contains()</code> (for everything that is <em>not</em> a container), and if it finds a match, then good! If not, well, then that’s an error as always.</p>\n<p>So that’s the difference:</p>\n<ul>\n<li>With <code>static_assert</code>, if someone calls <code>contains()</code> with inappropriate arguments, the compile just dies immediately, even if there are other (and better) possibilities that might work.</li>\n<li>With <code>enable_if</code>, if someone calls <code>contains()</code> with inappropriate arguments… the compiler just pretends the function doesn’t exist, and keeps looking for other possibilities. If it finds one, it uses it. If not, then that’s an error as always.</li>\n</ul>\n<p>Which one is preferred? It depends on what you want.</p>\n<p>If you can be reasonably sure that no one will ever name another function <code>contains()</code> that might be confused with your function (which is a perfectly reasonable assumption!), then <code>static_assert</code> is just fine. But if you think you might be sharing the name <code>contains()</code> with other stuff… maybe you might not want to trigger a hard error right away; maybe you might want your function to “step aside” to give other functions with the same name a chance.</p>\n<p>Hope all this helps!</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-11T13:50:05.107", "Id": "478359", "Score": "2", "body": "Ah, yes, I think it’s preferred that you ask for another review with the updated code, rather than extending this review. But I can answer your questions, though since they require complicated answers, I’ll extend the review above and add the answers there." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-11T14:15:05.303", "Id": "478362", "Score": "0", "body": "Great review. Well done!" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-07T00:15:26.310", "Id": "243503", "ParentId": "243432", "Score": "7" } } ]
{ "AcceptedAnswerId": "243503", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-05T15:49:25.147", "Id": "243432", "Score": "6", "Tags": [ "c++", "template", "c++17" ], "Title": "Checking if a value is in a container" }
243432
<p>I've written a simple mesh class. The purpose of it is to build a mesh, draw it to the screen, and provide some means by which the mesh can be transformed/scaled, etc. This was done with GLAD, GLFW, GLM, and OpenGL.</p> <pre><code>/* The mesh class takes vertex data, binds VAOs, VBOs, drawing orders, etc, and draws it. Other classes can inherit from this class. */ class Mesh { private: //------------------------------------------------------------------------------------------- // GLenum: drawing mode (ie GL_STATIC_DRAW) and primitive type (ie GL_TRIANGLES) GLenum DRAW_MODE, PRIMITIVE_TYPE; //------------------------------------------------------------------------------------------- // Vertex buffer object, vertex array object, element buffer object unsigned int VBO, VAO, EBO; protected: //------------------------------------------------------------------------------------------- // Vectors holding vertex and index data std::vector&lt;Vertex&gt; vertices; std::vector&lt;unsigned int&gt; indices; //------------------------------------------------------------------------------------------- void init() { // Generate vertex arrays glGenVertexArrays(1, &amp;VAO); // Generate VBO glGenBuffers(1, &amp;VBO); // Generate EBO glGenBuffers(1, &amp;EBO); // Bind the VAO glBindVertexArray(VAO); // Bind the buffer glBindBuffer(GL_ARRAY_BUFFER, VBO); // Detail the VBO buffer data - attach the vertices glBufferData(GL_ARRAY_BUFFER, vertices.size() * sizeof(Vertex), &amp;vertices[0], DRAW_MODE); // Bind the indices glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO); // Detail the EBO data glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices.size() * sizeof(unsigned int), &amp;indices[0], DRAW_MODE); glEnableVertexAttribArray(0); // Tell OpenGL how the vertex data is structured glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)0); glBindVertexArray(0); } //------------------------------------------------------------------------------------------- void set_vertices(std::vector&lt;Vertex&gt; _vertices) { vertices = _vertices; } //------------------------------------------------------------------------------------------- void set_indices(std::vector&lt;unsigned int&gt; _indices) { indices = _indices; } //------------------------------------------------------------------------------------------- void set_primitive_type(GLenum _PRIMITIVE_TYPE) { PRIMITIVE_TYPE = _PRIMITIVE_TYPE; } //------------------------------------------------------------------------------------------- void set_draw_mode(GLenum _DRAW_MODE) { DRAW_MODE = _DRAW_MODE; } public: //------------------------------------------------------------------------------------------- Mesh(std::vector&lt;Vertex&gt; _vertices, std::vector&lt;unsigned int&gt; _indices, GLenum _DRAW_MODE = GL_STATIC_DRAW, GLenum _PRIMITIVE_TYPE = GL_TRIANGLES) { this-&gt;vertices = _vertices; this-&gt;indices = _indices; this-&gt;DRAW_MODE = _DRAW_MODE; this-&gt;PRIMITIVE_TYPE = _PRIMITIVE_TYPE; //std::cout &lt;&lt; vertices[0].position.x &lt;&lt; std::endl; init(); } //------------------------------------------------------------------------------------------- // Constructor for an empty mesh. Note: it MUST RECIEVE VERTEX DATA Mesh(GLenum _DRAW_MODE = GL_STATIC_DRAW, GLenum _PRIMITIVE_TYPE = GL_TRIANGLES) { this-&gt;DRAW_MODE = _DRAW_MODE; this-&gt;PRIMITIVE_TYPE = _PRIMITIVE_TYPE; } //------------------------------------------------------------------------------------------- virtual ~Mesh() { glDeleteVertexArrays(1, &amp;VAO); glDeleteBuffers(1, &amp;VBO); glDeleteBuffers(1, &amp;EBO); } //------------------------------------------------------------------------------------------- virtual void update() {} //------------------------------------------------------------------------------------------- void draw() { // Bind the EBO glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO); // Bind the vertex array object glBindVertexArray(VAO); // Ready to draw glDrawElements(PRIMITIVE_TYPE, indices.size(), GL_UNSIGNED_INT, 0); // Unbind the vertex array (although this isn't entirely necessary) glBindVertexArray(0); } //------------------------------------------------------------------------------------------- /* Now I will introduce some simple mesh transformation functions */ void move(glm::vec3 _position) { // Transform each vertex in the given vector to achieve the desired effect for (std::size_t i = 0; i &lt; vertices.size(); i++) { vertices[i].position += _position; } } //------------------------------------------------------------------------------------------- void scale(float factor) { // Initalise as identity matrix glm::mat3 scaling_matrix = glm::mat3(); // Multiply by the scaling factor scaling_matrix = factor * scaling_matrix; // Apply the transformation for (std::size_t i = 0; i &lt; vertices.size(); i++) { vertices[i].position = scaling_matrix * vertices[i].position; } } }; </code></pre> <p>I have also made a simple application of the mesh class: drawing a plane.</p> <pre><code>// A simple plane, the test shape that we'll use for drawing class Plane : public Mesh { private: //------------------------------------------------------------------------------------------- // Amount of vertices in the x direction std::size_t SIZE_X = 100; // Amount of vertices in the y direction std::size_t SIZE_Y = 100; // Width between vertices (x direction) std::size_t VERTEX_WIDTH = 1; // 'Height' between vertices (y direction) std::size_t VERTEX_HEIGHT = 1; //------------------------------------------------------------------------------------------- std::vector&lt;Vertex&gt; vertices; std::vector&lt;unsigned int&gt; indices; //------------------------------------------------------------------------------------------- // Set up the plane void create_mesh_plane() { const int w = SIZE_X + 1; for (std::size_t i = 0; i &lt; SIZE_X + 1; i++) { for (std::size_t j = 0; j &lt; SIZE_Y + 1; j++) { Vertex v; v.position.x = i * VERTEX_WIDTH; v.position.y = j * VERTEX_HEIGHT; v.position.z = 0; vertices.push_back(v); unsigned int n = j * (SIZE_X + 1) + i; if (j &lt; SIZE_Y &amp;&amp; i &lt; SIZE_X) { // First face indices.push_back(n); indices.push_back(n + 1); indices.push_back(n + w); // Second face indices.push_back(n + 1); indices.push_back(n + 1 + w); indices.push_back(n + 1 + w - 1); } } } //------------------------------------------------------------------------------------------- set_vertices(vertices); set_indices(indices); set_primitive_type(GL_TRIANGLES); set_draw_mode(GL_STATIC_DRAW); init(); } public: //------------------------------------------------------------------------------------------- Plane() { create_mesh_plane(); } //------------------------------------------------------------------------------------------- ~Plane() { } }; </code></pre> <p>This code works, and you can instantiate a plane object and draw it in your render function and it will work quickly and nicely.</p> <p>I'm looking at a review on this code because it's going to become a centrepiece of future things I work on with OpenGL and am concerned about the efficiency, particularly:</p> <ul> <li><p>Multiple instantiations of mesh-like objects lead to multiple VBOs, causing unnecessary buffer switches.</p></li> <li><p>The vectors seem like an incredibly inefficient way of storing the data. Particularly because as can be seen in my move() and scale() functions, I'm iterating over them, which is <em>extremely</em> slow in realtime and very detrimental to performance. Also, if I want to dynamically update mesh vertex data (I added a virtual update function for this purpose) it would be extremely slow.</p></li> <li><p>I could probably split up the init() function such that it doesn't have to be recalled every time the vertex data changes (ie, the drawing order is still the same, I could just feed in the new vertex data if I wanted to update the vertex data of the mesh during its existence).</p></li> </ul> <p>I'd be grateful for any feedback.</p>
[]
[ { "body": "<ul>\n<li><p>Use lower case for data members. It's fine for VBO, VAO, EBO since they are abbreviations (and you might consider renaming them as well), but change <code>DRAW_MODE</code> and <code>PRIMITIVE_TYPE</code> to lower case.</p></li>\n<li><p>Presumably, <code>Vertex</code> is a struct containing just 3 floats for the position. When setting the attributes, you have a single call to set attribute 0. What happens when you expand your <code>Vertex</code> struct to contain normals, color, uv coordinates, tangents, et cetera? Okay, then you can go back into your <code>init</code> function and add those attributes. But what if a certain mesh doesn't contain color data? Since you have hardcoded the attributes, you have no way of changing it without breaking some other meshes.</p></li>\n<li><p>You can use <code>vertices.data()</code> instead of <code>&amp;vertices[0]</code>.</p></li>\n<li><p>Don't use identifiers beginning with an underscore. <a href=\"https://stackoverflow.com/questions/228783/what-are-the-rules-about-using-an-underscore-in-a-c-identifier\">See here</a>.</p></li>\n<li><p>Pass the vectors using const reference.</p></li>\n<li><p>Consider using <code>std::move</code> if you're not going to be using the vector again.</p></li>\n<li><p><code>this</code> is usually omitted by C++ programmers unless one needs to explicitly refer to the current object.</p></li>\n<li><p>In <code>draw()</code> you don't need to bind the index buffer again.</p></li>\n<li><p>As you mentioned, updating each vertex is horrible tactic. If you have a mesh with 10000 vertices, you will have spent a good part of the time available updating each mesh. Also it might be possible that certain entities share the mesh data (they might be instanced). If you update the data in the mesh, they will all get updated.</p>\n\n<p>Here's a way to change it. Each entity has a handle to a Mesh (or a pointer) and a model matrix. Any update to position or scale or rotation is reflected in a change to the model matrix. Then, when rendering the entity, you bind your mesh's vertex array and pass the model matrix to the shader, which then combines it with the view-projection matrix to render the object. </p>\n\n<p>You can of course do other optimizations, such as instanced rendering.</p></li>\n<li><p>You have two duplicate <code>vertices</code> and <code>indices</code> vectors, one inherited from <code>Mesh</code> and other you declare as private. </p></li>\n<li><p>Consider using move semantics on objects that you're throwing away after use, such as the <code>Vertex</code> in <code>create_mesh_plane()</code>. </p></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-05T21:02:40.240", "Id": "243447", "ParentId": "243434", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-05T17:02:21.830", "Id": "243434", "Score": "3", "Tags": [ "c++", "object-oriented", "inheritance", "opengl" ], "Title": "OpenGL Mesh Class" }
243434
<p>I have this code in my ViewModel which searches a List of Items, the <code>OnSearchAsync(string searchQuery)</code> gets executed by a Command which is bound to <code>TextChanged</code> <code>Entry</code> Event</p> <p>The <code>ObservableCollection&lt;Items&gt;</code> Collection is bound to <code>CollectionView</code>. There are 200 Items max in this Collection</p> <p>I'm wondering if my Code could be improved or if I'm doing this wrong.</p> <pre><code>private async void OnSearchAsync(string searchQuery) { if (string.IsNullOrEmpty(searchQuery) || searchQuery.Length &lt; 2) { if (Items?.Count == _backupItems.Count) { return; } Items = new ObservableCollection&lt;Item&gt;(_backupItems); await RaisePropertyChanged(nameof(Items)); return; } try { await Task.Run(async () =&gt; { var result = Search(searchQuery); if (result == null) { Items = null; return; } var results = result.ToList(); if (results.Count == 0) { Items = null; return; } Items = new ObservableCollection&lt;Item&gt;(results); await RaisePropertyChanged(nameof(Items)); } catch (Exception ex) { _logger.Error(this, ex); } } public IEnumerable&lt;Item&gt; Search(string text) { try { return _backupItems.Where(x =&gt; x.Property1.Text.CaseContains(text) || x.Property2.Text.CaseContains(text) || x.Property3.Text.CaseContains(text) || x.Property4.Text.CaseContains(text)); } catch (Exception ex) { _logger.Error(this, ex); } return null; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-29T18:32:24.953", "Id": "480485", "Score": "0", "body": "Is there a specific reason why you are re-instantiating your observable collection instead of simply clearing it and adding new items to it? I was also wondering about the async RaisePropertyChanged method" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-05T17:24:09.643", "Id": "243435", "Score": "1", "Tags": [ "c#", "xamarin" ], "Title": "Xamarin.Forms Search ObservableCollection" }
243435
<p>I made a program which simulates taking an order for 3 meals and a dessert. It's like those packaged food companies you see on Instagram. It asks for a name, and then goes on to ask what they want for each mealtime and stores their orders in a dictionary. I defined two <em>functions</em>, they help out a lot and make it much easier. You can also only choose from the respected menu for each mealtime; you can't choose from the dessert menu for breakfast. I think I have two many <em>break</em> statements, I think the program gets too complicated towards the end. How can clean the program up?</p> <pre><code>def show_menu(meals, meal_time): """Print each element in the list.""" print(f"\n{meal_time.title()}:") for meal in meals: print(f"\t-{meal.title()}") def get_user_meal(menu): """Takes orders for each meal and stores it in a dictionary.""" while True: if menu == breakfast_menu: breakfast = input(breakfast_prompt) breakfast = breakfast.lower() if breakfast not in menu: print(f"---Please choose from the breakfast menu!---") continue else: user_meals['breakfast'] = breakfast break if menu == lunch_menu: lunch = input(lunch_prompt) lunch = lunch.lower() if lunch not in menu: print(f"---Please choose from the lunch menu!---") continue else: user_meals['lunch'] = lunch break if menu == dinner_menu: dinner = input(dinner_prompt) dinner = dinner.lower() if dinner not in menu: print(f"---Please choose from the dinner menu!---") continue else: user_meals['dinner'] = dinner break if menu == dessert_menu: dessert = input(dessert_prompt) dessert = dessert.lower() if dessert not in menu: print(f"---Please choose from the dessert menu!---") continue else: user_meals['dessert'] = dessert break user_meals = {} # Menus from which the user can choose meals from. breakfast_menu = ['omelet', 'cheese platter', 'ham sandwich'] lunch_menu = ['steak', 'chicken breast', 'fish and chips', 'tacos'] dinner_menu = ['lasagna', 'pizza', 'salad', 'cod fish'] dessert_menu = ['chocolate cake', 'ice cream', 'chocolate mousse'] # All prompts that will be used. name_prompt = "\nWhat's your name? " breakfast_prompt = "\nWhat would you like for breakfast? " lunch_prompt = "\nWhat about for lunch? " dinner_prompt = "\nHow about for dinner? " dessert_prompt = "\nAnything sweet perhaps for dessert? " read_back_prompt = "\n\nWould you like for me to read back your meals? (yes/no) " evaluate_prompt = "\nDid I get everything? (yes/no) " confirm_prompt = "\nPlease enter 'confirm' to proceed or 'decline' to quit: " print("Welcome to MealPlanner!") while True: name = input(name_prompt) # Show the user the menus print("\nHere is what we are offering for todays meals:") show_menu(breakfast_menu,'breakfast') show_menu(lunch_menu,'lunch') show_menu(dinner_menu,'dinner') show_menu(dessert_menu,'dessert') while True: # Ask the user for his meal choices for each mealtime. get_user_meal(breakfast_menu) get_user_meal(lunch_menu) get_user_meal(dinner_menu) get_user_meal(dessert_menu) # Reads back the order if the user asked for it. read_back = input(read_back_prompt) if read_back.lower() == 'yes': print(f"\nFor breakfast you ordered a tasty plate of {user_meals['breakfast'].title()}, " f"\nfor lunch you asked for a simmering plate of {user_meals['lunch'].title()}, " f"\nfor the last meal of the day you ordered a savory plate of {user_meals['dinner'].title()}, " f"\nand to curb your sweet tooth you ordered a mouth-watering plate of {user_meals['dessert'].title()}.") rb_evaluate = input(evaluate_prompt) # If the user has changed his mind start from the top of this while loop. if rb_evaluate.lower() == 'no': print("I'm sorry may I take your order again?") continue else: break else: break # If the user has already seen his orders no need to show him again, so we just ask him for conformation. if read_back.lower() == 'yes': confirm = input(confirm_prompt) if confirm.lower() == 'decline': break # If the user didn't ask for the read back then show the orders before asking for conformation. else: print("\nYour order:") for key, value in user_meals.items(): print(f"\t{key.title()}: {value.title()}") confirm = input(confirm_prompt) if confirm.lower() == 'decline': break print(f"\nThank you for your order {name.title()}!" "\nWe will deliver your order in a few minuets." "\nThank you for choosing MealPlanner!") break </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-05T18:00:55.243", "Id": "243436", "Score": "3", "Tags": [ "python", "beginner", "python-3.x" ], "Title": "Model Program For Food Orders - Too many 'break' statements" }
243436
<p>As an old COBOL coder, all this OOP stuff is foriegn. Would someone please take a look at this program? I'm looking for suggestions for ways to improve this program. While it works, I'm sure there's many way to make it better, particularly in the areas of memory management, OOP methodology, and idioms. Any advice is welcome. Thanks!</p> <p>Edit: Here's the complete listing:</p> <pre><code>// FILE: translate.cpp // STANDARD: C++17 // AUTHOR: Phil Huffman // // PURPOSE: // This is a python program that reads a text file and writes a text file with // a name derived from the name of the input file (e.g. d.txt -&gt; d.OUT.txt). // It reads the first data set, determines where the protein sequence is in the // count. Then, in every subsequent data set, the program will only return data // that is related to that count. This will replace data that does that does // not precisely align with sequence positions from the first data set (whether // they are a dash or a letter). The output file will have the same number of // data sets as the input file. The proteins sequence of the first data set is // unchanged. In the remaining data sets, each character of the sequence is // unchanged if the corresponding character of the first sequence is a letter. // Otherwise, it is replaced with the specified replacement character. // If none is specified, the default '+' will be used. // // OVERALL METHOD: // The general tasks are: // 1. Parse command line building a vector of file names // 2. Instantiate a DataSet object // 3. Repeat step 2 until all file names have been used. // // CLASSES: // InputParser // // DataSet // // FUNCTIONS: // None. // // DATA FILES: // plain text files as indicated in command line #include &lt;array&gt; #include &lt;fstream&gt; #include &lt;iostream&gt; #include &lt;sstream&gt; #include &lt;string&gt; #include &lt;vector&gt; class InputParser { public: InputParser (int &amp;argc, char **argv){ for (int i=1; i &lt; argc; ++i) this-&gt;tokens.push_back(std::string(argv[i])); } const std::string&amp; getCmdOption(const std::string &amp;option) const{ std::vector&lt;std::string&gt;::const_iterator itr; itr = std::find(this-&gt;tokens.begin(), this-&gt;tokens.end(), option); if (itr != this-&gt;tokens.end() &amp;&amp; ++itr != this-&gt;tokens.end()){ return *itr; } static const std::string empty_string(""); return empty_string; } bool cmdOptionExists(const std::string &amp;option) const{ return std::find(this-&gt;tokens.begin(), this-&gt;tokens.end(), option) != this-&gt;tokens.end(); } private: std::vector &lt;std::string&gt; tokens; }; class DataSet { public: DataSet(const std::string fname, const std::string out_id, char sub_char, int line_length) { this-&gt;ifn = fname; this-&gt;ofn = fname; this-&gt;oid = out_id + "."; this-&gt;sc = sub_char; this-&gt;ll = line_length; make_ofn(); read_file(); parse_raw(); get_results(); } void write_to_file() { long l; // length of output line long b; // start of output line in sequence DataSet_item dsi; // current dataset item std::ofstream out; out.open(this-&gt;ofn); if(out.is_open()) { for(auto i = data.begin(); i != data.end(); i++) { dsi = *i; out &lt;&lt; dsi.name &lt;&lt; std::endl; for(b = 0; b &lt; dsi.seq.size(); b += this-&gt;ll) { l = this-&gt;ll; while(b + l &gt; dsi.seq.size()) { l--; } out &lt;&lt; dsi.seq.substr(b, l) &lt;&lt; std::endl; } } std::cout &lt;&lt; this-&gt;data.size() &lt;&lt; " data set items written to " &lt;&lt; this-&gt;ofn &lt;&lt; std::endl; } else { std::cerr &lt;&lt; ofn &lt;&lt; " was not opened." &lt;&lt; std::endl; } out.close(); } private: struct DataSet_item { std::string name; std::string seq; }; int ll; // line length char sc; // substitution char std::string oid; // makes output file name different std::string ifn; // input file name std::string ofn; // output file name std::vector&lt;DataSet_item&gt; data; // where the action is std::vector&lt;std::string&gt; raw; // raw data from input file void read_file() { std::ifstream file(this-&gt;ifn); std::string str; while (std::getline(file, str)) { this-&gt;raw.emplace_back(str); } } void get_results() { DataSet_item dsi; dsi = this-&gt;data[0]; std::string seq_0 = dsi.seq; for(long n = 1; n &lt; data.size(); n++) { dsi = this-&gt;data[n]; for(long i = 0; i &lt; dsi.seq.size(); i++) { if(!isalpha(seq_0[i])) { dsi.seq[i] = this-&gt;sc; } } data[n] = dsi; } } std::string get_name(std::string s) { int start = s.find('['); int end = s.find(']'); int len = end - start; return "&gt;" + s.substr(start + 1, len - 1); } void cleanup_seq(std::string &amp;s) { long i = 0; while(i &lt; s.size()) { if(s[i] == '\n') { s.erase(i, 1); } else { i++; } } } void make_ofn() { size_t pos = this-&gt;ofn.rfind('.'); pos = (pos == std::string::npos) ? this-&gt;ofn.size(): pos + 1; this-&gt;ofn.insert(pos, this-&gt;oid); } void parse_raw() { DataSet_item dsi; dsi.name = ""; dsi.seq = ""; std::string line = ""; for(auto e = this-&gt;raw.begin(); e != this-&gt;raw.end(); e++) { line = *e; if(line[0] == '&gt;') { augment_data(dsi); dsi.name = get_name(line); dsi.seq = ""; } else { dsi.seq += line; } } augment_data(dsi); } void augment_data(DataSet_item &amp;dsi) { cleanup_seq(dsi.seq); if(!dsi.name.empty() &amp;&amp; !dsi.seq.empty()) { this-&gt;data.emplace_back(dsi); } } }; int main(int argc, char **argv){ InputParser input(argc, argv); if(input.cmdOptionExists("-h")){ std::cout &lt;&lt; "Usage: translate -s + -l 60 -o OUT &lt;at least one file name&gt;\n" &lt;&lt; "\ts:\tSubstitution char, default = '+'\n" &lt;&lt; "\t\tOnly first character will be used.\n" &lt;&lt; "\tl:\tMax output length, default = 60\n" &lt;&lt; "\to:\tOutput identifier, default = \"OUT\"\n" &lt;&lt; "\t\tOne or more file names.\n" &lt;&lt; "\t\tThese files must be simple text files.\n"; } int lineLen = 60; const std::string &amp;lineLength = input.getCmdOption("-l"); if(lineLength.size() &gt; 0) { lineLen = std::stoi(lineLength); } std::string out_id = "OUT"; const std::string &amp;oout_id = input.getCmdOption("-o"); if(oout_id.size() &gt; 0) { out_id = oout_id; } char sc = '+'; const std::string &amp;substitutionChar = input.getCmdOption("-s"); if(substitutionChar.size() &gt; 0) { sc = substitutionChar[0]; } std::vector &lt;std::string&gt; fns; int i = 1; while(i &lt; argc) { if(argv[i][0] == '-') { i++; } else { fns.emplace_back(argv[i]); } i++; } std::string ts; for (auto i = fns.begin(); i !=fns.end(); i++) { ts = *i; DataSet data(ts, out_id, sc, lineLen); data.write_to_file(); } return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-05T19:14:32.807", "Id": "477821", "Score": "4", "body": "Are you able to add a bit more context as to what this program is actually supposed to do, and edit the title to reflect taht?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-05T19:32:36.007", "Id": "477824", "Score": "1", "body": "This is hardly written in OO style. What's the goal of the program?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-05T20:54:40.843", "Id": "477832", "Score": "2", "body": "I [changed the title](https://codereview.stackexchange.com/posts/243439/revisions) so that it describes what the code does per [site goals](https://codereview.stackexchange.com/questions/how-to-ask): \"_State what your code does in your title, not your main concerns about it._\". Feel free to [edit] and give it a different title if there is something more appropriate. Also, the comment at the beginning of the code contains \"`This is a python program`\" yet it is C++ code with the C++ tag..." } ]
[ { "body": "<p><strong>General comments</strong></p>\n\n<p>It is rarely necessary to use the <code>this</code> keyword to access member variables (typically this is used to disambiguate between local variables/parameters and member variables that have the same name). So you can remove all of the <code>this-&gt;</code> uses in your code.</p>\n\n<p>Usually the <code>class</code> keyword is kept on the same line as the class name. Visually, putting it on a line of its own splits the declaration up unnecessarily and makes it harder for me to figure out what it is doing. The declaration of the local <code>DataSet_item</code> struct is even harder to figure out.</p>\n\n<p>Use consistent spacing. You have <code>const{</code> in some places (without a space; you can use <code>const {</code>). Elsewhere, you're breaking up type names with spaces (<code>std::vector &lt;std::string&gt;</code>) where normally there is no space between a template name and its parameters. There should be a space between keywords and the <code>(</code> for the expression that follows, and a space between the <code>)</code> and <code>{</code> for blocks.</p>\n\n<p><strong>InputParser class</strong></p>\n\n<p>This <code>InputParser</code> constructor should not take the <code>argc</code> parameter by reference. Just pass it as <code>int argc</code>.</p>\n\n<p>The loop body can be simplified to <code>tokens.emplace_back(argv[i]);</code>. Or you can take advantage of one of vector's constructors with</p>\n\n<pre><code>InputParser(int argc, char **argv): tokens{argv + 1, argv + argc}\n{\n}\n</code></pre>\n\n<p>Usually returning a reference from a function is risky, because if the thing that is referenced is destroyed before the user of the return value is done using it you can access a dangling reference. <code>getCmdOption</code> would be safer if it returned a <code>string</code>, not a <code>string &amp;</code>. It would then avoid the need for constructing a static string object to return if the option isn't found. The downside is having to construct extra string objects but these are relatively cheap.</p>\n\n<p>Use the <code>auto</code> keyword for complicated variable types. In <code>getCmdOption</code>, you don't need to type out that whole iterator name (which is easy to get wrong). Just use <code>auto itr = std::find(tokens.begin(), tokens.end(), option);</code>. <code>empty_string</code> doesn't need to have that initial value passed, since the default constructor for a string constructs an empty string (<code>static const std::string empty_string;</code>). Although if you change the return type to a string you can dispense with that line and just use <code>return {};</code> or <code>return std::string{};</code>.</p>\n\n<p>Unless you're always working with a narrow editor, there's no real reason to split the return in <code>cmdOptionExists</code> onto two lines. (There is also some discussion on where that operator goes when splitting lines like this; I prefer to put it at the end of the previous line.)</p>\n\n<p><strong>DataSet class</strong></p>\n\n<p>There is no reason to make value parameters const, and you should make use of the constructor initializer list. Variables in the list should be listed in their declaration order, since that is the order the compiler will construct them.</p>\n\n<pre><code>DataSet(std::string fname, std::string out_id, char sub_char, int line_length):\n ll(line_length), sc(sub_char), oid(out_id + '.'), ifn(fname), ofn(std::move(fname))\n{\n // ...\n}\n</code></pre>\n\n<p>Declare variables as close as possible to their initial use. In <code>write_to_file</code>, <code>l</code>, <code>b</code>, and <code>dsi</code> can be declared later. The output stream can be opened in the constructor call, the for loop can use a <a href=\"https://en.cppreference.com/w/cpp/language/range-for\" rel=\"nofollow noreferrer\">ranged-based for loop</a>, and you don't need to check for going past the end for <a href=\"https://en.cppreference.com/w/cpp/string/basic_string/substr\" rel=\"nofollow noreferrer\"><code>substr</code></a>. You can leave the <code>std::</code> off of the <code>endl</code> uses due to <a href=\"https://stackoverflow.com/questions/8111677/what-is-argument-dependent-lookup-aka-adl-or-koenig-lookup\">Koenig lookup</a>:</p>\n\n<pre><code>std::ofstream out{ofn};\nif (out.is_open()) {\n for (const auto &amp;dsi: data) {\n out &lt;&lt; dsi.name &lt;&lt; endl;\n for (std::size_t b = 0, len = dsi.seq.size(); b &lt; len; b += ll) {\n out &lt;&lt; dsi.seq.substr(b, ll) &lt;&lt; endl;\n }\n }\n} else // ...\n</code></pre>\n\n<p>You can omit <code>out.close()</code> since the destructor will do that for you.</p>\n\n<p>In <code>read_file</code>, you can use <code>raw.emplace_back(std::move(str));</code> to avoid making a copy of the string.</p>\n\n<p><code>get_results</code> is doing a bunch of work it doesn't need to. It could do with a better name, as any function name that starts with <code>get</code> can be expected to return a value in some way. It also assumes that <code>data</code> is not empty.</p>\n\n<pre><code>void get_results() {\n if (data.empty()) return;\n auto seq_0 = data[0].seq;\n for (std::size_t n = 1, sz = data.size(); n &lt; sz; ++n) {\n auto &amp;dsi = data[n];\n size_t i = 0;\n for (auto &amp;ch: dsi.seq) {\n if (!isalpha(seq_0[i]))\n ch = sc;\n }\n }\n}\n</code></pre>\n\n<p><code>get_name</code> will have problems if one or both of the <code>'['</code> or <code>']'</code> characters are not found in the string.</p>\n\n<p><code>cleanup_seq</code> should make use of <a href=\"https://en.cppreference.com/w/cpp/string/basic_string/erase2\" rel=\"nofollow noreferrer\"><code>std::erase</code></a>:</p>\n\n<pre><code>void cleanup_seq(std::string &amp;s) {\n std::erase(s.begin(), s.end(), '\\r');\n}\n</code></pre>\n\n<p><code>make_ofn</code> will misbehave if the filename does not have a period but a directory name earlier in the path does.</p>\n\n<p>In <code>parse_raw</code>, you don't need to assign initial values to <code>dsi.name</code>, <code>dis.seq</code>, or <code>line</code>, since the default string constructor will create an empty string. And the for loop can use the ranged-based for loop mentioned earlier. Rather than assigning an empty string to <code>dsi.seq</code> to clear it, you can use <code>dsi.seq.clear();</code>.</p>\n\n<p><strong>The <code>main</code> function</strong></p>\n\n<p>When processing the <code>\"-h\"</code> option, you should abort execution (i.e., return) after displaying the help.</p>\n\n<p>Your input parsing assumes that any flag option is followed by a parameter value. This is not error checked. The loop that processes these arguments can get out of sync for bad input (and adding a comment to the <code>i++</code> when skipping a parameter would clear up initial confusion, since it looks like you're double incrementing. You already have all that data in <code>input</code>, so could you take advantage of that?</p>\n\n<p>The final for loop can be a range-based for loop.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-06T21:05:55.777", "Id": "477918", "Score": "0", "body": "This is just what I was hoping for. Thank you." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-06T17:42:26.223", "Id": "243490", "ParentId": "243439", "Score": "3" } } ]
{ "AcceptedAnswerId": "243490", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-05T19:05:36.873", "Id": "243439", "Score": "4", "Tags": [ "c++", "object-oriented", "memory-management" ], "Title": "protein sequence translator using basic text manipulation" }
243439
<p>I've recently started working on an Angular 7 project (I'm pretty new to Angular and RxJS), and I was requested to implement this new functionality:</p> <p><strong>The Problem</strong></p> <p>I have to implement a component to show some data fetched from a server via a service, and allow the user to edit it. The HTTP call can be triggered after selecting an option from a dropdown in the header of the page. When I get the response from the HTTP call, the user should be able to edit this data (using a form). If data is modified (= the page form is dirty), trying to change option in the dropdown should cause a warning modal to be displayed, and the HTTP call to fetch corresponding data shouldn't be performed. The value in the dropdown should be the last one for which the HTTP call was performed successfully (so, even in case of errors while requesting data to server, the dropdown value should be set accordingly). The user can discard the changes he made pressing a <strong><em>Discard Changes</em></strong> button: A confirmation modal will be shown and, if the user confirms to discard changes, the data must be downloaded again from the server</p> <p><strong>My Attempt</strong></p> <p>So far, I've tried this approach:</p> <pre><code>private destroyed$ = new Subject(); private triggerReload$ = new Subject(); private previousPhase: number; public numericTextboxLowerBound = 0; public numericTextboxUpperBound = 100; public pageData: ProportionOfEffortByRoleIdeal = null; public phases: KeyValue&lt;number, string&gt;[] = []; public filterForm: FormGroup; public pageForm: FormGroup; public phaseSelect: FormControl; public roleRatios: FormArray; constructor( private activatedRoute: ActivatedRoute, private formBuilder: FormBuilder, private modalService: ModalService, private roleService: RoleService, private translateService: TranslateService ) { } initFilterFormControls() { this.phaseSelect = this.formBuilder.control(null); } initFilterForm() { this.filterForm = this.formBuilder.group({ phaseSelect: this.phaseSelect }); } initPageFormControls() { this.roleRatios = this.formBuilder.array([]); } initPageForm() { this.pageForm = this.formBuilder.group({ roleRatios: this.roleRatios }); } createWbsItemFormGroup(sourceItem: WbsItem): FormGroup { return this.formBuilder.group({ WorkStreamID: this.formBuilder.control(sourceItem.id, Validators.required), RoleList: this.formBuilder.array( sourceItem.roleEfforts.map((effort) =&gt; this.formBuilder.group({ ID: this.formBuilder.control(effort.key, Validators.required), Value: this.formBuilder.control(effort.value * this.numericTextboxUpperBound) })), ArrayValidators.sumEqualTo(ValidationErrorName.EstimateByRoleArraySum, this.numericTextboxUpperBound, 'Value', sourceItem.name)) }); } initPageFormData(data: ProportionOfEffortByRoleIdeal) { while (this.roleRatios.length &gt; 0) { this.roleRatios.removeAt(0); } data.wbsItems.forEach((item) =&gt; { item.children.forEach((activity) =&gt; { this.roleRatios.push(this.createWbsItemFormGroup(activity)); }); }); if (data.isReadOnly) { this.pageForm.disable({ emitEvent: false }); } else { this.pageForm.enable({ emitEvent: false }); } this.pageForm.markAsUntouched(); this.pageForm.markAsPristine(); } ngOnInit() { this.initFilterFormControls(); this.initFilterForm(); this.initPageFormControls(); this.initPageForm(); this.phases = this.activatedRoute.parent.snapshot.data.phasesList as KeyValue&lt;number, string&gt;[]; this.previousPhase = this.phaseSelect.value; const phaseChange$ = this.phaseSelect.valueChanges.pipe( takeUntil(this.destroyed$), filter(() =&gt; { if (this.pageForm.dirty) { this.modalService.pendingChanges(); this.phaseSelect.setValue(this.previousPhase, { emitEvent: false }); return false; } return true; }) ); merge(this.triggerReload$, phaseChange$).pipe( takeUntil(this.destroyed$), switchMap(() =&gt; this.getPageData()), filter((data) =&gt; data !== null), tap((next) =&gt; { this.previousPhase = this.phaseSelect.value; this.initPageFormData(next); }) ).subscribe((next) =&gt; this.pageData = next); } ngOnDestroy(): void { this.destroyed$.next(); this.destroyed$.complete(); } openDiscardChangesDialog() { this.modalService.discard().pipe(take(1)).subscribe((confirmDiscard) =&gt; confirmDiscard &amp;&amp; this.triggerReload$.next()); } getPageData(): Observable&lt;ProportionOfEffortByRoleIdeal&gt; { return this.roleService.GetRoleRatioByPhaseAsync( +this.activatedRoute.parent.snapshot.paramMap.get(RouteParamKey.ChunkVersionID), +this.phaseSelect.value ).pipe( map((operationResult) =&gt; { if (operationResult.isResultOK &amp;&amp; operationResult.hasResult) { const result = operationResult.result as ProportionOfEffortByRoleResponse; const idealResult: ProportionOfEffortByRoleIdeal = { isReadOnly: result.isReadOnly || result.userRoleAccessLevel[0].isReadOnly, roles: result.roleRatioWorkStreams[0].roleList.sort((a, b) =&gt; a.order - b.order).map( (role) =&gt; ({ key: role.id, value: role.roleName })), wbsItems: this.createWbsItems(result.roleRatioWorkStreams, false) }; return idealResult; } throw new Error(); }), catchError((error) =&gt; { this.modalService.error(this.translateService.instant('msg_error_generic')); this.phaseSelect.setValue(this.previousPhase, { emitEvent: false }); return of(null); }) ); } </code></pre> <ul> <li><code>phaseChange$</code> is a local variable I use to keep track of when the user selects a different option in the header dropdown: <code>phaseSelect</code> is the FormControl for the dropdown in the header: I listen to its <code>valueChanges</code>, which emits a value every time the user selects a new option. I then apply <code>filter</code> to check for changes in the page form (where data can be edited by the user), and if I find there's some pending changes, I prevent the emission of a value, setting the value of the dropdown to the value when the last successful request was performed</li> <li><code>triggerReload$</code>, as the name might suggest, is a Subject I use to trigger the HTTP call when the user confirms to discard changes in the form</li> <li>Since the HTTP call to fetch data from the server should be performed either when the user discards the changes he made in the form or when the user chooses a new option in the dropdown in the header, I apply the <code>merge</code> operator to <code>phaseChange$</code> and <code>triggerReload$</code>, and subscribe to the HTTP call by using the <code>switchMap</code> operator.</li> <li>In the <code>getPageData()</code> function, where I invoke the service method to perform the HTTP call, I use <code>catchError</code> to handle error situations: other than returning a default null value, even here I restore the value for the header dropdown</li> </ul> <p><strong>Question</strong></p> <p>The code I attached <strong><em>seems</em></strong> to work, but I'm not convinced it is a good solution; so, my question is: is there some better way to achieve the desired behaviour? For example, is there some way <code>this.phaseSelect.setValue(this.previousPhase, { emitEvent: false });</code> can be executed only once to avoid code repetitions?</p> <p>Thanks in advance</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-05T16:13:33.150", "Id": "243440", "Score": "3", "Tags": [ "javascript", "angular-2+", "typescript", "rxjs" ], "Title": "RxJS - Prevent valueChange of one form control if another form group is dirty OR an HTTP error has occurred" }
243440
<p>I haven't used C++ in over a decade, so to learn modern C++ (17) I built a JSON reader based on a pushdown automata (<a href="https://en.wikipedia.org/wiki/Pushdown_automaton" rel="noreferrer">PDA</a>).</p> <p>The general idea is this:</p> <ul> <li>A stream is passed to <code>JsonReader</code></li> <li><code>JsonReader</code> calls <code>ParserStatesManager</code>, which returns the next state based on the top of the PDA stack, and optionally by reading in an input char</li> <li><code>JsonReader::ProcessState</code> then process the returned state - pops/pushes the PDA stack, optionally copies the input char to the current <code>JValue</code>, etc</li> <li>Loop until input is finished or until the error state is reached</li> </ul> <p>Since this is the first time I've touched C++ in a very long time, I'm looking for tips or suggestions on:</p> <ul> <li><strong>Is this good, clean, idiomatic C++17?</strong> <ul> <li>Is the project layout and class structure what you would expect? </li> <li>I have some header-only classes, is that okay?</li> <li>Are things named right?</li> <li>Is there any code in headers which should be in implementation files, or vice versa?</li> <li>Are rvalues/lvalues, references, <code>const</code>, <code>auto</code>, and other C++ features being used correctly?</li> <li>I wrote Java-esq getters and setters for private members - is this the idiomatic C++ way for accessors/mutators?</li> </ul></li> <li><strong>Performance - any issues I've overlooked?</strong> <ul> <li>Any excessive copying or other issues?</li> <li>I'm not using pointers anywhere - all memory is either on the stack or managed by STL classes (like vector), is that okay?</li> </ul></li> </ul> <p>And of course, any other suggestions for improvement would be greatly appreciated.</p> <p>The full project is here - <a href="https://github.com/marklar423/jsonreadercpp" rel="noreferrer">https://github.com/marklar423/jsonreadercpp</a> - and I've added the main relevant files below</p> <p><strong>main.cc</strong> - showing usage</p> <pre><code>int main(int argc, char *argv[]) { JsonReader parser; std::optional&lt;JValue&gt; parsed_json = parser.ParseJsonString(cin); if (parsed_json.has_value()) PrintJsonTree(parsed_json.value()); else cout &lt;&lt; "No root object in JSON\n"; return 0; } </code></pre> <p><strong>JsonReader.h</strong> - This is the main class that parses the JSON. </p> <p>I'm including all the <code>#include</code>s in this one, as an example of how I use them in the project. <code>#include</code>s are omitted in subsequent files for brevity.</p> <pre><code>#ifndef JSONREADERCPP_JSONDESERIALIZER_H_ #define JSONREADERCPP_JSONDESERIALIZER_H_ #include &lt;optional&gt; #include &lt;iostream&gt; #include "jsonreadercpp/JValue.h" #include "jsonreadercpp/statemachine/ParserStatesSymbols.h" #include "jsonreadercpp/statemachine/ParserStatesManager.h" #include "jsonreadercpp/statemachine/ParserValueStack.h" #include "jsonreadercpp/statemachine/ParserMachineStack.h" namespace jsonreadercpp { class JsonReader { public: JsonReader(std::ostream&amp; error_output_stream = std::cerr, std::ostream&amp; debug_output_stream = std::cout, bool debug_output = false); std::optional&lt;JValue&gt; ParseJsonString(std::istream&amp; input); private: std::ostream&amp; error_output_stream_; std::ostream&amp; debug_output_stream_; bool debug_output_; ParserStatesManager states_manager_; ParserStatesManager::NextTransition ProcessState(std::istream&amp; input, ParserStateType current_state_type, ParserValueStack&amp; value_stack, ParserMachineStack&amp; machine_stack); }; } #endif </code></pre> <p><strong>JsonReader.cc</strong></p> <pre><code>#include "jsonreadercpp/JsonReader.h" using std::string; using std::pair; using std::optional; namespace jsonreadercpp { JsonReader::JsonReader(std::ostream&amp; error_output_stream /*= std::cerr*/, std::ostream&amp; debug_output_stream /*= std::cout*/, bool debug_output /*= false*/) : states_manager_(), error_output_stream_(error_output_stream), debug_output_stream_(debug_output_stream), debug_output_(debug_output) { } optional&lt;JValue&gt; JsonReader::ParseJsonString(std::istream&amp; input) { auto current_state_type = ParserStateType::Start; ParserValueStack value_stack; ParserMachineStack machine_stack; char processed_char = '\0'; bool finished_input = false, has_error = false; int line_num = 1, char_num = 0, line_char_start = 0; input &gt;&gt; std::noskipws; while (!finished_input &amp;&amp; !has_error) { if (debug_output_) debug_output_stream_ &lt;&lt; '[' &lt;&lt; char_num &lt;&lt; ']' &lt;&lt; processed_char &lt;&lt; " =&gt; " &lt;&lt; ParserStateTypeName(current_state_type) &lt;&lt; "\n"; if (current_state_type == ParserStateType::Error) { error_output_stream_ &lt;&lt; "Error: Unexpected \"" &lt;&lt; processed_char &lt;&lt; "\"" &lt;&lt; " at Line:" &lt;&lt; line_num &lt;&lt; ", Line Position:" &lt;&lt; (char_num - line_char_start) &lt;&lt; ", Global Position:" &lt;&lt; char_num &lt;&lt; "\n"; has_error = true; } else { auto next_transition_container = ProcessState(input, current_state_type, value_stack, machine_stack); processed_char = next_transition_container.processed_char; current_state_type = next_transition_container.transition.next_state; finished_input = next_transition_container.finished_input; if (processed_char != '\0') char_num++; if (processed_char == '\n') { line_num++; line_char_start = char_num; } } } optional&lt;JValue&gt; result; if (!has_error) { if (value_stack.GetSize() &gt; 1) { error_output_stream_ &lt;&lt; "Error: Unexpected end of input, JSON isn't complete\n"; } else { result = std::move(value_stack.RemoveRootValue()); } } return result; } ParserStatesManager::NextTransition JsonReader::ProcessState(std::istream&amp; input, ParserStateType current_state_type, ParserValueStack&amp; value_stack, ParserMachineStack&amp; machine_stack) { //get next state auto stack_symbol = (machine_stack.GetSize() &gt; 0) ? machine_stack.GetTop() : ParserStackSymbol::None; auto next_transition_container = states_manager_.GetNextTransition(current_state_type, input, stack_symbol); const auto&amp; next_transition = next_transition_container.transition; if (!next_transition_container.finished_input) { //stack actions machine_stack.PopPush(next_transition.stack_pop, next_transition.stack_push); //input actions value_stack.AccumulateInput(next_transition_container.processed_char, next_transition.char_destination, current_state_type); //JValue actions if (next_transition.value_action == ParserValueAction::Push || next_transition.value_action == ParserValueAction::PushPop) { value_stack.PushJValue(next_transition.value_push_type.value()); } if (next_transition.value_action == ParserValueAction::Pop || next_transition.value_action == ParserValueAction::PushPop) { value_stack.PopJValue(); } } return next_transition_container; } } </code></pre> <p><strong>JValue.h</strong></p> <pre><code>namespace jsonreadercpp { enum class JValueType { String, Number, Boolean, Null, Object, Array }; class JValue { public: //create an object, array, or null JValue(JValueType value_type) : JValue(value_type, {}) {} //create a scalar value JValue(std::string value) : JValue(JValueType::String, {value}) {} JValue(double value) : JValue(JValueType::Number, {value}) {} JValue(bool value) : JValue(JValueType::Boolean, {value}) {} JValue(JValue&amp;&amp; other) = default; JValue&amp; operator=(JValue&amp;&amp; other) = default; JValue Clone() const { return JValue(*this); } std::optional&lt;std::string&gt; GetStringValue() const; std::optional&lt;double&gt; GetNumberValue() const; std::optional&lt;bool&gt; GetBooleanValue() const; std::string GetName() const { return name_; } JValueType GetValueType() const { return value_type_; } size_t GetNumberOfChildren() const { return children_.size(); } const auto&amp; GetChildren() const { return children_; } bool HasProperty(const std::string&amp; name) { return children_name_indexes_.find(name) != children_name_indexes_.end(); } //returns false if this parent object is not an array //takes an rvalue since JValue can only be moved (or Clone()d and then moved) bool AddArrayChild(JValue&amp;&amp; value); //returns true if no property with this name already exists, false otherwise //takes an rvalue since JValue can only be moved (or Clone()d and then moved) bool AddObjectChild(std::string name, JValue&amp;&amp; value); //returns true if the element exists, false otherwise bool RemoveChild(size_t index); //returns true if the element exists, false otherwise bool RemoveChild(const std::string&amp; name); //get the nth child element, either object property or array item const JValue&amp; operator[](size_t index) const { return children_.at(index); } //get an object property by name const JValue&amp; operator[](const std::string&amp; name) const { return this[children_name_indexes_.at(name)]; } const auto begin() const { return children_.begin(); } const auto end() const { return children_.end(); } private: JValue(JValueType value_type, std::variant&lt;std::string, double, bool&gt; value); //a copy is recursive and copies all children; it's very expensive //force the user to use the clone() method so that it doesn't happen by accident JValue(const JValue&amp; other); JValue&amp; operator=(const JValue&amp; other); std::vector&lt;JValue&gt; CopyChildren(const JValue&amp; other); std::string name_; JValueType value_type_; std::vector&lt;JValue&gt; children_; std::unordered_map&lt;std::string, size_t&gt; children_name_indexes_; std::variant&lt;std::string, double, bool&gt; value_; }; } </code></pre> <p><strong>JValue.cc</strong></p> <pre><code>namespace jsonreadercpp { JValue::JValue(JValueType value_type, std::variant&lt;std::string, double, bool&gt; value) : name_(""), value_type_(value_type), children_(), children_name_indexes_(), value_(value) { } JValue::JValue(const JValue&amp; other) : name_(other.name_), value_type_(other.value_type_), children_(std::move(CopyChildren(other))), children_name_indexes_(other.children_name_indexes_), value_(other.value_) { } JValue&amp; JValue::operator=(const JValue&amp; other) { name_ = other.name_; value_type_ = other.value_type_; children_ = std::move(CopyChildren(other)); children_name_indexes_ = other.children_name_indexes_; value_ = other.value_; } std::vector&lt;JValue&gt; JValue::CopyChildren(const JValue&amp; other) { std::vector&lt;JValue&gt; copy; copy.reserve(other.children_.size()); for (const auto&amp; child : other.children_) { copy.emplace_back(child.Clone()); } return copy; } std::optional&lt;string&gt; JValue::GetStringValue() const { switch (this-&gt;value_type_) { case JValueType::String: return {std::get&lt;string&gt;(this-&gt;value_) }; case JValueType::Number: return {std::to_string(std::get&lt;double&gt;(this-&gt;value_))}; case JValueType::Boolean: return {std::get&lt;bool&gt;(this-&gt;value_) ? "true" : "false"}; case JValueType::Null: return {""}; default: return {}; } } std::optional&lt;double&gt; JValue::GetNumberValue() const { if (this-&gt;value_type_ == JValueType::Number) return { std::get&lt;double&gt;(this-&gt;value_) }; return {}; } std::optional&lt;bool&gt; JValue::GetBooleanValue() const { if (this-&gt;value_type_ == JValueType::Boolean) return { std::get&lt;bool&gt;(this-&gt;value_) }; return {}; } bool JValue::AddArrayChild(JValue&amp;&amp; value) { bool success = false; if (this-&gt;value_type_ == JValueType::Array) { success = true; //move() here is superfluous, but leaving it just in case `value` changes to a regular value in the future this-&gt;children_.emplace_back(std::move(value)); } return success; } bool JValue::AddObjectChild(std::string name, JValue&amp;&amp; value) { bool success = false; if (this-&gt;value_type_ == JValueType::Object &amp;&amp; name.length() &gt; 0 &amp;&amp; !this-&gt;HasProperty(name)) { success = true; value.name_ = name; //move() here is superfluous, but leaving it just in case `value` changes to a regular value in the future this-&gt;children_.emplace_back(std::move(value)); this-&gt;children_name_indexes_[name] = this-&gt;children_.size() - 1; } return success; } bool JValue::RemoveChild(size_t index) { bool exists = false; if (index &lt; this-&gt;children_.size()) { exists = true; string child_name = this-&gt;children_[index].name_; this-&gt;children_.erase(this-&gt;children_.begin() + index); if (this-&gt;children_name_indexes_.find(child_name) != this-&gt;children_name_indexes_.end()) this-&gt;children_name_indexes_.erase(child_name); } return exists; } bool JValue::RemoveChild(const string&amp; name) { bool exists = false; auto kvp = this-&gt;children_name_indexes_.find(name); if (kvp != this-&gt;children_name_indexes_.end()) { exists = true; this-&gt;RemoveChild(kvp-&gt;second); this-&gt;children_name_indexes_.erase(name); } return exists; } } </code></pre> <p><strong>statemachine/ParserMachineStack.h</strong></p> <pre><code>namespace jsonreadercpp { class ParserMachineStack { public: void PopPush(ParserStackSymbol stack_pop, ParserStackSymbol stack_push); ParserStackSymbol GetTop() const { return state_machine_stack_.top(); } size_t GetSize() const { return state_machine_stack_.size(); } private: std::stack&lt;ParserStackSymbol&gt; state_machine_stack_; }; } </code></pre> <p><strong>statemachine/ParserMachineStack.cc</strong></p> <pre><code>namespace jsonreadercpp { void ParserMachineStack::PopPush(ParserStackSymbol stack_pop, ParserStackSymbol stack_push) { if (stack_pop != stack_push) { if (stack_pop != ParserStackSymbol::None) this-&gt;state_machine_stack_.pop(); if (stack_push != ParserStackSymbol::None) this-&gt;state_machine_stack_.push(stack_push); } } } </code></pre> <p><strong>statemachine/ParserState.h</strong></p> <pre><code>namespace jsonreadercpp { class ParserState { public: using TransitionLookup = std::unordered_map&lt;ParserInputSymbol, std::unordered_map&lt;ParserStackSymbol, ParserStateTransition&gt;&gt;; ParserState(ParserStateType type, std::initializer_list&lt;ParserStateTransition&gt; transitions = {}, ParserStateTransition else_transition = {ParserInputSymbol::None, ParserStateType::Error}) : state_type_(type), transitions_(), else_transition_(else_transition) { for (auto&amp; transition : transitions) { this-&gt;AddTransition(transition); } } ParserStateType GetStateType() const { return state_type_; } const TransitionLookup&amp; GetTransitions() const { return transitions_; }; const ParserStateTransition&amp; GetElseTransition() const { return else_transition_; }; bool HasTransition(ParserInputSymbol input_symbol, ParserStackSymbol stack_symbol) const; const ParserStateTransition&amp; GetTransition(ParserInputSymbol input_symbol, ParserStackSymbol stack_symbol) const { return transitions_.at(input_symbol).at(stack_symbol); } const ParserStateTransition&amp; GetTransitionOrElse(ParserInputSymbol input_symbol, ParserStackSymbol stack_symbol) const { return HasTransition(input_symbol, stack_symbol) ? GetTransition(input_symbol, stack_symbol) : else_transition_; } void AddTransition(ParserStateTransition transition) { transitions_[transition.input].emplace(transition.stack_pop, transition); } private: ParserStateType state_type_; TransitionLookup transitions_; ParserStateTransition else_transition_; }; } </code></pre> <p><strong>statemachine/ParserState.cc</strong></p> <pre><code>namespace jsonreadercpp { bool ParserState::HasTransition(ParserInputSymbol input_symbol, ParserStackSymbol stack_symbol) const { bool found = false; auto find_input = this-&gt;transitions_.find(input_symbol); if (find_input != this-&gt;transitions_.end()) { auto&amp; stack_map = find_input-&gt;second; auto find_stack = stack_map.find(stack_symbol); found = (find_stack != stack_map.end()); } return found; } } </code></pre> <p><strong>statemachine/ParserStatesManager.h</strong></p> <pre><code>namespace jsonreadercpp { class ParserStatesManager { public: struct NextTransition { const ParserStateTransition&amp; transition; bool finished_input; char processed_char; NextTransition(const ParserStateTransition&amp; transition, bool finished_input = false, char processed_char = '\0') : transition(transition), finished_input(finished_input), processed_char(processed_char) {} }; ParserStatesManager() : states_(jsonreadercpp::states::CreateStatesMap()) {} NextTransition GetNextTransition(ParserStateType current_state_type, std::istream&amp; input, ParserStackSymbol stack_top) const; private: std::unordered_map&lt;ParserStateType, ParserState&gt; states_; }; } </code></pre> <p><strong>statemachine/ParserStatesManager.cc</strong></p> <pre><code>namespace jsonreadercpp { ParserStatesManager::NextTransition ParserStatesManager::GetNextTransition(ParserStateType current_state_type, std::istream&amp; input, ParserStackSymbol stack_top) const { //order of operations: None, None -&gt; * | None, X -&gt; * | X, None -&gt; * | X, Y -&gt; * const auto&amp; current_state_iter = states_.find(current_state_type); if (current_state_iter == states_.end()) { std::cerr &lt;&lt; "Unable to find state " &lt;&lt; ParserStateTypeName(current_state_type) &lt;&lt; "\n"; exit(1); } else { const auto&amp; current_state = current_state_iter-&gt;second; if (current_state.HasTransition(ParserInputSymbol::None, ParserStackSymbol::None)) { //None, None -&gt; * return { current_state.GetTransition(ParserInputSymbol::None, ParserStackSymbol::None) }; } else if (stack_top != ParserStackSymbol::None &amp;&amp; current_state.HasTransition(ParserInputSymbol::None, stack_top)) { //None, X -&gt; * return { current_state.GetTransition(ParserInputSymbol::None, stack_top) }; } else { char c = '\0'; if (input &gt;&gt; c) { ParserInputSymbol input_symbol = jsonreadercpp::CharToInputSymbol(c); //X, None -&gt; * if (current_state.HasTransition(input_symbol, ParserStackSymbol::None)) return { current_state.GetTransition(input_symbol, ParserStackSymbol::None), false, c }; //X, Y -&gt; * else if (current_state.HasTransition(input_symbol, stack_top)) return { current_state.GetTransition(input_symbol, stack_top), false, c }; else return { current_state.GetElseTransition(), false, c }; } else { //no more input to read //there should be no more states, but we need to return something, sooo return { current_state.GetElseTransition(), true, '\0' }; } } } } } </code></pre> <p><strong>statemachine/ParserStateTransition.h</strong></p> <pre><code>namespace jsonreadercpp { struct ParserStateTransition { ParserInputSymbol input; ParserStateType next_state; ParserStackSymbol stack_pop; ParserStackSymbol stack_push; ParserCharDestination char_destination; ParserValueAction value_action; std::optional&lt;JValueType&gt; value_push_type; ParserStateTransition(ParserInputSymbol input, ParserStateType next_state) : input(input), next_state(next_state), stack_pop(ParserStackSymbol::None), stack_push(ParserStackSymbol::None), char_destination(ParserCharDestination::None), value_action(ParserValueAction::None), value_push_type() { } ParserStateTransition&amp; SetStack(ParserStackSymbol stack_pop, ParserStackSymbol stack_push) { this-&gt;stack_pop = stack_pop; this-&gt;stack_push = stack_push; return *this; } ParserStateTransition&amp; SetCharDestination(ParserCharDestination char_destination) { this-&gt;char_destination = char_destination; return *this; } ParserStateTransition&amp; SetValueAction(ParserValueAction value_action, std::optional&lt;JValueType&gt; value_push_type) { this-&gt;value_action = value_action; this-&gt;value_push_type = value_push_type; return *this; } }; } </code></pre> <p><strong>statemachine/ParserValueStack.h</strong></p> <pre><code>namespace jsonreadercpp { class ParserValueStack { public: void AccumulateInput(char input_char, ParserCharDestination destination, ParserStateType current_state_type); void PushJValue(JValueType type); void PopJValue(); std::optional&lt;JValue&gt; RemoveRootValue(); size_t GetSize() const { return value_stack_.size(); } private: std::stack&lt;std::pair&lt;std::string, JValue&gt;&gt; value_stack_; std::stringstream property_name_; std::stringstream scalar_value_; //collected unicode digits wchar_t unicode_code_point_ = 0; ParserCharDestination unicode_destination_; char ProcessEscapeCharInput(char input_char, ParserCharDestination destination, ParserStateType current_state_type); //Translate a character into the corresponding escape char, //i.e. 'n' to '\n', 't' to '\t', etc char TranslateEscapeChar(char escaped); //Collects hex codes into unicode_code_point_, //in the order it appears in the JSON string (big endian) void CollectUnicodeCodePoint(char input_char); std::string TranslatUnicodeCodePoint(); }; } </code></pre> <p><strong>statemachine/ParserValueStack.cc</strong></p> <pre><code>namespace jsonreadercpp { void ParserValueStack::AccumulateInput(char input_char, ParserCharDestination destination, ParserStateType current_state_type) { input_char = ProcessEscapeCharInput(input_char, destination, current_state_type); if (input_char != '\0') { if (destination == ParserCharDestination::Name) this-&gt;property_name_ &lt;&lt; input_char; else if (destination == ParserCharDestination::Value) this-&gt;scalar_value_ &lt;&lt; input_char; } } void ParserValueStack::PushJValue(JValueType type) { optional&lt;JValue&gt; new_value; if (type == JValueType::Array || type == JValueType::Object || type == JValueType::Null) { new_value.emplace(type); } else { string accumulated_chars = this-&gt;scalar_value_.str(); if (type == JValueType::String) new_value.emplace(accumulated_chars); else if (type == JValueType::Number) new_value.emplace(std::stod(accumulated_chars)); else if (type == JValueType::Boolean) new_value.emplace(accumulated_chars == "true"); } //add the new value to the top of the stack this-&gt;value_stack_.emplace(this-&gt;property_name_.str(), std::move(new_value.value())); //clear the accumulated values this-&gt;property_name_.str(""); this-&gt;scalar_value_.str(""); } void ParserValueStack::PopJValue() { if (this-&gt;value_stack_.size() &gt; 1) //root value? { pair&lt;string, JValue&gt; top_value(std::move(this-&gt;value_stack_.top())); this-&gt;value_stack_.pop(); auto&amp; parent_pair = this-&gt;value_stack_.top(); auto&amp; parent_value = parent_pair.second; if (parent_value.GetValueType() == JValueType::Array) { parent_value.AddArrayChild(std::move(top_value.second)); } else if (parent_value.GetValueType() == JValueType::Object) { parent_value.AddObjectChild(std::move(top_value.first), std::move(top_value.second)); } } } optional&lt;JValue&gt; ParserValueStack::RemoveRootValue() { optional&lt;JValue&gt; result; if (value_stack_.size() == 1) { result.emplace(std::move(value_stack_.top().second)); value_stack_.pop(); } return result; } char ParserValueStack::ProcessEscapeCharInput(char input_char, ParserCharDestination destination, ParserStateType current_state_type) { if (current_state_type == ParserStateType::EscapeChar) { input_char = (input_char == 'u') ? '\0' : TranslateEscapeChar(input_char); } else if (current_state_type == ParserStateType::UnicodeValue || current_state_type == ParserStateType::UnicodeProperty) { //collect unicode code point for later this-&gt;CollectUnicodeCodePoint(input_char); input_char = '\0'; this-&gt;unicode_destination_ = destination; } else if (this-&gt;unicode_code_point_ &gt; 0) { //we have a previously collected unicode code point, save it now if (this-&gt;unicode_destination_ == ParserCharDestination::Name) this-&gt;property_name_ &lt;&lt; TranslatUnicodeCodePoint(); else if (this-&gt;unicode_destination_ == ParserCharDestination::Value) this-&gt;scalar_value_ &lt;&lt; TranslatUnicodeCodePoint(); this-&gt;unicode_code_point_ = 0; } return input_char; } char ParserValueStack::TranslateEscapeChar(char escaped) { switch (escaped) { case 'b': return '\b'; case 'f': return '\f'; case 'n': return '\n'; case 'r': return '\r'; case 't': return '\t'; } return escaped; } void ParserValueStack::CollectUnicodeCodePoint(char input_char) { std::stringstream ss; ss &lt;&lt; input_char; //convert the hex char to a number unsigned char hex_num; ss &gt;&gt; std::hex &gt;&gt; hex_num; //each hex digit represents 1/2 a byte, so shift by 4 this-&gt;unicode_code_point_ = (this-&gt;unicode_code_point_ &lt;&lt; 4) | (hex_num &amp; 0x0F); } std::string ParserValueStack::TranslatUnicodeCodePoint() { //reset the conversion state std::wctomb(nullptr, 0); std::string utf_chars(MB_CUR_MAX, '\0'); int num_bytes = std::wctomb(&amp;utf_chars[0], unicode_code_point_); return utf_chars; } } </code></pre> <p><code>jsonreadercpp::states::CreateStatesMap()</code> is defined as:</p> <pre><code>unordered_map&lt;ParserStateType, ParserState&gt; CreateStatesMap() { ParserState states[] { CreateStartState(), CreateFinishState(), CreateRootObjectState(), CreateObjectState(), &lt;etc&gt; }; unordered_map&lt;ParserStateType, ParserState&gt; states_map; for (auto&amp; state : states) { auto state_type = state.GetStateType(); states_map.emplace(state_type, std::move(state)); } return states_map; } </code></pre> <p>and the CreatexxxState functions are all basically the same, here's a sample:</p> <pre><code>ParserState CreateObjectState() { return ParserState(ParserStateType::Object, { { ParserInputSymbol::Whitespace, ParserStateType::Object }, ParserStateTransition(ParserInputSymbol::CloseBrace, ParserStateType::PostObject) .SetStack(ParserStackSymbol::Object, ParserStackSymbol::None) .SetValueAction(ParserValueAction::Pop, {}), { ParserInputSymbol::DoubleQuote, ParserStateType::PropertyString } }, { ParserInputSymbol::None, ParserStateType::Error } ); } </code></pre> <p>Thanks!</p>
[]
[ { "body": "<p>I’m going to review your code in the order you’ve presented it in the opening post, simply because that’s the most orderly way to go about it from my perspective. I’ll mention overarching design issues along the way, and then include a section at the end collecting them all together. And I’ll be answering most, if not all, of the questions along the way. I hope that won’t be too confusing for you!</p>\n<p>Also, do note that I can’t really give a full and comprehensive review of the entire design, because, well, that’s just too big a job for a Saturday morning. I’ll try and give some big-picture suggestions, of course. But this review won’t be anything close to “complete”.</p>\n<p>So let’s start at the top!</p>\n<h2><code>main.cc</code></h2>\n<p>I’m so glad you included a usage example; I’ve seen far too many people post entire libraries here without a single usage example. In my opinion, the usage example is the most important part of a library’s documentation. If a library doesn’t incude good, clear, practical usage examples, I won’t even look at it.</p>\n<p>The big question that jumps out at me from your usage example is: why have you chosen not to use the standard input pattern? For virtually every type <code>T</code>, if I want to read it from a stream, I do:</p>\n<pre><code>auto t = T{};\nif (input &gt;&gt; t)\n // use t\nelse\n // handle error\n</code></pre>\n<p>So why have you chosen to do:</p>\n<pre><code>auto parser = JsonReader{};\nauto parsed_json = parser.ParseJsonString(std::cin);\n\nif (parsed_json.has_value())\n // retrieve value as `auto value = std::move(parsed_json).value();` then use it\nelse\n // handle error\n</code></pre>\n<p>instead of:</p>\n<pre><code>auto value = JValue{JValueType::Null}; // Could this not just be JValue{}?\nif (std::cin &gt;&gt; value)\n // use value\nelse\n // handle error\n</code></pre>\n<p>That would allow me to write more generic code (as shown in the first code block above, with <code>T</code>).</p>\n<p>I guess what I’m asking is:</p>\n<ul>\n<li>Is there any purpose to the <code>JsonReader</code> object outside of the actual parsing? Is there any purpose to it once parsing is done? (I know you use it for debug output… but that’s kind of a library development thing, not something that <em>users</em> of the library should use, right?)</li>\n<li>Is there any reason not to use the error detection/reporting built into standard streams? You use <code>parsed_json.has_value()</code> to check whether parsing succeded or not… doesn’t that just give the same information as <code>bool{std::cin}</code>? (Except the stream can give much more information, like whether parsing failed because the content was bad (badly formatted JSON) or the stream was bad (like a network disconnection). Not to metion that exceptions could (and should) be used.)</li>\n</ul>\n<p>It’s not that your design using a state machine to parse JSON is wrong—quite the opposite. It just seems to me that the entire <code>JsonReader</code> class should be an implementation detail hidden within a standard extractor like <code>auto operator&gt;&gt;(std::istream&amp;, JValue&amp;)</code>.</p>\n<h2><code>JsonReader.h</code> &amp;&amp; <code>JsonReader.cc</code></h2>\n<p>These are both cool. I could nitpick some criticisms, but they’re really more matters of taste than things that are really <em>wrong</em> with your code.</p>\n<ul>\n<li>Not a fan of using <code>.h</code> for C++ headers. <code>.h</code> to me (and to most IDE’s, file managers, etc.) means a C header. In this case, I’d recommend <code>.hh</code> to go with <code>.cc</code>.</li>\n<li>Not a fan of default arguments, generally. They hide the complexity of a call, so that you may be invisibly constructing a half-dozen expensive objects and have no clue, and they can cause a lot of problems with overloading. In this case, I’d probably design the class with two or three constructors: one with no arguments, one that takes the two streams by ref, and maybe a third that only takes the error stream by ref. Within the class, I’d only keep <em>pointers</em> to the streams that default to <code>nullptr</code> (or maybe the error stream would default to <code>std::cerr</code>), and only do debug/error output if the respective pointer is non-null. There’d be no need for the <code>debug_output_</code> flag then.</li>\n<li>Also not a fan of the using declarations at namespace scope. I mean, they’re within the implementation file, which is certainly better than being in the header. But I don’t see any benefit to using something like <code>std::string</code> unqualified. (Plus, you don’t actually <em>use</em> any of those types unqualified at namespace scope; you could just as well include those <code>using</code> statements within the functions, if you really, really wanted them.)</li>\n<li>And, not a fan of declaring/defining multiple variables on a single line (like: <code>int line_num = 1, char_num = 0, line_char_start = 0;</code>). Every style guide I’ve ever used forbids this.</li>\n</ul>\n<p>There is a <em>dire</em> lack of commenting throughout your code. You don’t need to say what every single line is doing, but you should at least explain the gross outline of what’s going on. For example, <code>JsonReader::ParseJsonString()</code> is essentially a <code>while</code> loop that does all the work, followed by a short block to actually extract the result. I have puzzled that out by meticulously reading the code… but I shouldn’t have had to. There should be a comment explaining that the <code>while</code> loop will only exit when the input is exhausted, or there’s an error, and that <code>value_stack</code> must have only a single item in it at that point, and so on. And that’s just the beginning: what, for example, is <code>ProcessState()</code> doing to <code>input</code>? Is it reading a single character? Possibly several? It doesn’t even help to read <code>ProcessState()</code>’s code, because that just leads to <em>another</em> question—what is <code>GetNextTransition()</code> doing to <code>input</code>, etc..</p>\n<p>Comments should be telling me what all the relevant state at each point is expected to be. I shouldn’t have to guess (or utter a curse, sigh, set a bookmark, then go digging through an entire library of code to find where a specific function/type is defined, only to have to read <em>that</em> function/type’s code, then come back to the bookmark… <em>HOPEFULLY</em>… though it’s just as likely I’ll be forced down a further rabbit hole, requiring <em>another</em> curse, sigh, bookmark, etc.). Basically, the moment I have to stop reading a function’s code and go digging elsewhere for answers, that’s when I’d put the “FAILED” stamp on a code review.</p>\n<p>Digging a little deeper… do you really need <code>has_error</code>? I mean, the moment you detect an error, you log it then break out of the loop, and then ultimately just return the empty <code>optional</code>. Why not just return the empty <code>optional</code> right away and simplify the rest of the function? You also won’t need the <code>else</code> in the loop anymore.</p>\n<p>Similarly, if <code>value_stack.GetSize() &gt; 1</code>, you can just return right away. I know there’s a case to be made for having a single exit point for functions at the end, but when that’s being done at the expense of creating a complex spaghetti mess of flags and conditionals to worm around error states, you’d be doing yourself (and your code’s readers) a favour to relax that rule a bit, at least for errors that require bailing immediately.</p>\n<pre><code>result = std::move(value_stack.RemoveRootValue());\n</code></pre>\n<p>You don't need the <code>move()</code> here. <code>RemoveRootValue()</code> already returns an rvalue. Moves are automatic in C++ wherever possible. Generally, you only need to explicitly ask for a move when an object will continue to exist afterwards. So:</p>\n<pre><code>x = get_thing();\n</code></pre>\n<p>won’t need a <code>move()</code> (assuming <code>get_thing()</code> doesn’t return a reference), because the “thing” returned from <code>get_thing()</code> is a temporary that ceases to exist by the time the statement ends. Meanwhile:</p>\n<pre><code>// y = get_thing();\nx = y;\n</code></pre>\n<p>would need a <code>move()</code>, because <code>y</code> will continue to exist after the assignment statement.</p>\n<p>Put altogether, <code>JsonReader::ParseJsonString</code> could be simplified to something like this:</p>\n<pre><code>optional&lt;JValue&gt; JsonReader::ParseJsonString(std::istream&amp; input) \n{\n // Set up the variables you need for the loop.\n auto current_state_type = ParserStateType::Start;\n // ...\n \n // Input loop.\n do\n {\n // Trace statement.\n if (debug_output_)\n // ...\n \n // Error check.\n if (current_state_type == ParserStateType::Error)\n {\n error_output_stream_ &lt;&lt; // ...\n \n return {}; // or return std::nullopt;\n }\n \n // Actual work of loop.\n auto next_transition_container = ProcessState(input, current_state_type, value_stack, machine_stack);\n // ...\n } while (!finished_input);\n \n // Parsing done, but was it done completely?\n if (value_stack.GetSize() &gt; 1)\n {\n error_output_stream_ &lt;&lt; // ...\n \n return {};\n }\n \n // Now we're really done.\n return value_stack.RemoveRootValue();\n}\n</code></pre>\n<p>This isn’t necessarily “correct” (meaning the original code isn’t necessarily “wrong”), but there’s a lot less cognitive burden keeping track of error states. Errors break the flow the moment they’re found, they’re not trucked around for dozens of lines through branches, loops, and other control flow.</p>\n<h2><code>JValue.h</code> &amp; <code>JValue.cpp</code></h2>\n<p>This is the part of the library that I think is, by <em>far</em>, the most important. It’s also the part I think is the most problematic.</p>\n<p>For any of this input stuff to be really useful, it has to read the JSON data into a C++ object that is really useful. I always tell my students that in C++, it’s all about the types: if you get the types right, everything else just falls into place. If you get them wrong….</p>\n<p>Fundamentally, a JSON value is nothing more than a sum of:</p>\n<ul>\n<li>null</li>\n<li>boolean</li>\n<li>number</li>\n<li>string</li>\n<li>array (just a vector of JSON values)</li>\n<li>object (a map of string-&gt;JSON values)</li>\n</ul>\n<p>This is a somewhat recursive type because arrays and objects can hold JSON values. But otherwise… that’s just:</p>\n<pre><code>using json_value = std::variant&lt;\n std::monostate,\n bool,\n double,\n std::string,\n json_array,\n json_object\n&gt;\n</code></pre>\n<p>The only “tricky” part here is defining <code>json_array</code> and <code>json_object</code> before <code>json_value</code>.</p>\n<p>Now, to be clear, I do <em>NOT</em> recommend doing that. A JSON value is a distinct type, and should not be handwaved away with a slapdash alias of a vocabulary type. You should definitely have a JSON value class. But <em>internally</em>, the class needs to be little more than just that variant. Really, this is all you need:</p>\n<pre><code>class json_value\n{\n using value_type = std::variant&lt;\n std::monostate,\n bool,\n long double,\n std::string,\n // As of C++17, vectors can use incomplete types,\n // so this is cool:\n std::vector&lt;json_value&gt;,\n // Maps (and hash maps) cannot use incomplete types, so we\n // can't use std::map or std::unordered_map. However, Boost's\n // containers allow incomplete types, so:\n boost::container::map&lt;std::string, json_value&gt;\n // You could also use boost::container::flat_map, which would\n // probably be more efficient. Or it might even be worthwhile\n // to roll your own (flat) map that accepts incomplete types\n // for the values. Or maybe you just need an &quot;incomplete pair&quot;\n // type. (The trick you used, with a vector for the values and\n // a map with string key-&gt;index into the vector is clever, but\n // probably overkill, and not very efficient. You could\n // probably get away with just a vector of JValue and a vector\n // of std::string, and make sure the indexes match.)\n &gt;;\n\n value_type _value;\n \npublic:\n // You need an interface, of course, but it doesn't need to be OTT.\n // Just take a look at std::variant - it has, like, 3 or 4 member\n // functions, and maybe a half-dozen non-member functions.\n};\n</code></pre>\n<p><code>JValue</code> as you’ve written it already more-or-less apes <code>std::variant</code>… except much less efficiently. For example, if the JValue only holds a <code>bool</code>, you still have to pay for constructing and trucking around:</p>\n<ul>\n<li>a string (for the non-existent name; actually, I’m baffled about the existence of this member at all—you seem to duplicate the name in both <code>_name</code> and <code>children_name_indexes_[name]</code>)</li>\n<li>a vector (for the non-existent children)</li>\n<li>a hash map (for the non-existent member names)</li>\n<li>a <code>JValueType</code> discriminator, even though the variant already knows that it holds a <code>bool</code></li>\n</ul>\n<p>And of course, you have to be careful to keep all these various moving compments in sync.</p>\n<p>But the biggest problem is how clunky the user interface is. <code>JValue</code> seems so unnecessarily hard to use.</p>\n<p>Let’s start right at the beginning. A JSON value is one of:</p>\n<ul>\n<li>null</li>\n<li>boolean</li>\n<li>number</li>\n<li>string</li>\n<li>array</li>\n<li>object</li>\n</ul>\n<p>So what’s it like creating a <code>JValue</code> in each of these cases?</p>\n<pre><code>// null\nauto v = JValue{JValueType::Null};\n</code></pre>\n<p>Ehhh. I mean… could be worse? But it also could just be: <code>auto v = JValue{};</code>. I mean, why not default to null anyway?</p>\n<pre><code>// boolean\nauto v = JValue{true};\nauto v = JValue{false};\n</code></pre>\n<p>Cool.</p>\n<pre><code>// number\nauto v = JValue{6.28};\n</code></pre>\n<p>Cool… <em>but</em>… did you try this: <code>v = JValue{0};</code>?</p>\n<pre><code>// string\nauto v = JValue{&quot;char array&quot;};\nauto v = JValue{&quot;std::string&quot;s};\n</code></pre>\n<p>Cool… <em>but</em>… did you try this: <code>v = JValue{&quot;std::string_view&quot;sv};</code>?</p>\n<p>All that’s left are arrays and objects… and here’s where things get tragic. If I have a vector of strings, I would like to simply be able to do:</p>\n<pre><code>auto v = JValue{strings};\n</code></pre>\n<p>and get a <code>JValue</code> that has type <code>JValueType::Array</code>, with all the elements being the strings from the vector. But I can’t do that. I have to do this:</p>\n<pre><code>auto v = JValue{JValueType::Array};\n\n// Nope:\n// std::copy(begin(strings), end(strings), std::back_inserter(v));\n\n// Nope (AddArrayChild() wants an rvalue for some reason):\n// std::for_each(begin(strings), end(strings), [&amp;v](auto&amp;&amp; string) { v.AddArrayChild(string); });\n\n// Works, but it shouldn't (I'll explain later):\n// std::for_each(begin(strings), end(strings), [&amp;v](auto&amp;&amp; string) { v.AddArrayChild(std::string{string}); });\n\nstd::for_each(begin(strings), end(strings), [&amp;v](auto&amp;&amp; string) { v.AddArrayChild(JValue{string}); });\n</code></pre>\n<p>Given a vector of things that can be converted to <code>JValue</code> (<code>std::string</code> or <code>double</code> or <code>int</code> or <code>bool</code> or even <code>JValue</code>), why can’t I do this?:</p>\n<pre><code>auto v = JValue{items};\n\n// or:\nauto v = JValue(begin(items), end(items))?\n</code></pre>\n<p>Even cooler would be if the constructor were smart enough to detect if the value type of <code>items</code> can work with a structured binding like <code>auto [k, v] = value_type{};</code>, and that the type of <code>k</code> is convertible to <code>std::string</code>, and if so, create an object value:</p>\n<pre><code>auto items_1 = std::vector{&quot;a&quot;s, &quot;b&quot;s, &quot;c&quot;s};\nauto items_2 = std::vector{\n std::tuple{&quot;n0&quot;s, 0},\n std::tuple{&quot;n1&quot;s, 1},\n std::tuple{&quot;n2&quot;s, 2}\n};\n\nauto v_1 = JValue{items_1}; // = [ &quot;a&quot;, &quot;b&quot;, &quot;c&quot; ]\nauto v_2 = JValue{items_2}; // = { &quot;n0&quot; : 0, &quot;n1&quot; : 1, &quot;n2&quot; : 2 }\n</code></pre>\n<p>I’m not advocating for any particular interface; I’m just pointing out options. The key point I want to make is that <code>JValue</code> is <em>both</em> too difficult <em>and</em> too easy to construct. It’s too difficult for the reasons I mentioned above. And it’s too <em>easy</em> because the constructors are not marked <code>explicit</code>, as they almost certainly should be. There doesn’t seem to be any good reason to allow implicit conversions to JSON values.</p>\n<p>Speaking of too difficult:</p>\n<pre><code>JValue Clone() const { return JValue(*this); }\n</code></pre>\n<p>When I saw this function, I was absolutely baffled at first. Normally you don’t see “clone” functions in non-polymorphic types. And the type is totally copyable—it has copy ops, and they’re even used in <code>Clone()</code>. Until I saw the comments further below in the code I was scratching my head about the point of this function.</p>\n<p>Nor does the logic in the comment make much sense either. You seem to have a strange fear of copying in C++. You mention concerns about “excessive copying” in your questions, and your code has a bunch of peculiar (mis)uses of rvalue references that often don’t even do anything, and ironically, will probably make code <em>less</em> efficient.</p>\n<p>Don’t treat the language like an enemy you have to fight or outsmart. And, most importantly, don’t write code that assumes users are incompetent. Yes, definitely defend against reasonable mistakes. But… when I want a copy of a value, that’s not a mistake. And if I <em>do</em> make a copy I didn’t need or want… well, frankly, that’s <em>my</em> problem, not a problem with the type being “too easy to copy”. “Accidental” copying isn’t something you should be assuming people are doing that often—the standard library doesn’t make that assumption, for example: classes like <code>std::vector</code> and <code>std::list</code> can be <em>very</em> expensive to copy… but you don’t see them making life more difficult for users by deleting or hiding their copy constructors.</p>\n<p>Don’t punish competent users of your library at the expense of coders who don’t really know what they’re doing. <em>Let</em> the latters’ code be slow and inefficient… that way they’ll be motivated to learn from their mistakes.</p>\n<p>I note that you discovered yourself how clunky and hard to use your type is: you’re forced to have its functions take <code>JValue&amp;&amp;</code> parameters because copying doesn’t work (not mention the need for <code>CopyChildren()</code> and the fact that you’re forced to manually write the copy ops). That should be a sign: if your class is even frustrating to use <em>in its own interface</em>… maybe it’s time to reassess.</p>\n<pre><code>std::optional&lt;std::string&gt; GetStringValue() const;\nstd::optional&lt;double&gt; GetNumberValue() const;\nstd::optional&lt;bool&gt; GetBooleanValue() const;\n</code></pre>\n<p>This may be more opinionated than “standard thinking”, but I think this is an abuse of <code>std::optional</code>.</p>\n<p>While it may “work” for this context, this doesn’t really seem to fit the <em>semantics</em> of <code>std::optional</code>. When I see <code>std::optional</code> used as a return type, that says to me “this function is getting a value that might be there, but might not, and (this is the important part) <em>that is not an error</em>”. For example, a class that holds a person’s name might have a <code>middle_name()</code> function that gets the person’s middle name. But it’s perfectly acceptable for a person to have no middle name, so that function could possibly return <code>std::optional&lt;std::string&gt;</code>.</p>\n<p>But in the case of a JSON value, it’s not perfectly cool if you ask for the string value and there’s none there. If that happens… you’ve screwed up. You failed to check for whether the value type is string or not. Optional is the wrong semantic for that. The string value is not “optional”; if the value type is string, then it <em>MUST</em> be there, and if the value type is not string, then it <em>MUST NOT</em> be there.</p>\n<p>And in fact, <code>std::optional</code> is not just wrong semantically here… it actually makes code less efficient. Because if the string value <em>is</em> there, then it has to be copied into the <code>optional</code> object. That copy is completely unnecessary.</p>\n<p>I always tell my students to look to the standard library. See what it does in cases similar to what you’re doing, and figure out why. Chances are, there are damn good reasons.</p>\n<p>In this case, the closest analogue to <code>JValue</code> is a <code>std::variant</code> like the one I described above. So, okay, what does <code>std::variant</code> do? Does it return a <code>std::optional</code> for the alternative you ask for? No, it does not. If you ask for a type or index, and the variant doesn’t hold that alternative, it simply throws a <code>std::bad_variant_access</code>. If it does hold the alternative you want, you get a reference… no copying necessary. (There’s also <code>std::get_if</code>, that returns a pointer or <code>nullptr</code>, but again, no copying.)</p>\n<p>This is what code with your current interface looks like:</p>\n<pre><code>if (auto&amp;&amp; str = val.GetStringValue(); str)\n // now we can work with *str, which is a copy of the string in val\nelse\n // val didn't hold a string\n</code></pre>\n<p>By contrast, suppose <code>GetStringValue()</code> returned a <code>std::string const&amp;</code>, and throws if the value isn’t a string type:</p>\n<pre><code>if (val.GetValueType() == JValueType::String)\n // now we can work with val.GetStringValue(), which is a reference - no copying is done\nelse\n // val didn't hold a string\n</code></pre>\n<p>Not that different! However, it can be much more efficient, because it avoids copying a string.</p>\n<pre><code>std::string GetName() const { return name_; }\n</code></pre>\n<p>As I mentioned, I’m not really sure of the point of <code>_name</code>. But in any case, this accessor makes an unnecessary copy. You could return a <code>std::string const&amp;</code>, and also make it <code>noexcept</code>.</p>\n<pre><code>bool JValue::AddArrayChild(JValue&amp;&amp; value)\n{\n bool success = false;\n\n if (this-&gt;value_type_ == JValueType::Array)\n {\n success = true;\n //move() here is superfluous, but leaving it just in case `value` changes to a regular value in the future\n this-&gt;children_.emplace_back(std::move(value)); \n }\n\n return success;\n}\n</code></pre>\n<p>Couple things here.</p>\n<p>First, the comment is wrong. <code>std::move()</code> is absolutely <em>not</em> superfluous there. If this weren’t a member function, it wouldn’t compile without the <code>std::move()</code>, because the copy constructor is private. (If you don’t believe me, you can try commenting out <code>Clone()</code> and deleting the copy ops to see for yourself.)</p>\n<p>You see, <code>value</code> is an rvalue reference… but it is not an rvalue. An rvalue reference <em>takes</em> (ie, binds to) rvalues… but it is not an rvalue itself. The function can only be called with rvalue arguments… but <em>within the function</em>, the argument is an lvalue.</p>\n<p>The easiest way to understand when something is an rvalue is to ask: “can this be used after this point?”. In that function, if you did <code>this-&gt;children_.emplace_back(value);</code>, could <code>value</code> be used again after that line? Why yes, yes it could. You could even repeat that line to add two copies of <code>value</code> to <code>children_</code>. Therefore, <code>value</code> is not an rvalue.</p>\n<p>The second thing is: this function really shouldn’t be taking its argument as an rvalue reference. What’s the point? The general rule for (non-template) function parameters is:</p>\n<ul>\n<li>If the function is only <em>using</em> the parameter’s value, and not <em>taking</em> it (for example, only inspecting or viewing it), take the parameter as <code>const&amp;</code>.</li>\n<li>If the function is <em>taking</em> the parameter’s value (for example, taking the value for an object’s data member, or otherwise storing it somewhere), take the parameter by value.</li>\n<li>(RARE! Prefer returning.) If the function is <em>changing</em> the parameter’s value, take it by <code>&amp;</code> (non-<code>const</code>).</li>\n</ul>\n<p>Note there’s nothing there about <code>&amp;&amp;</code>. That’s because the only time you should ever use <code>&amp;&amp;</code> parameters is in special cases for optimization purposes. (The rule is different for function templates, where <code>&amp;&amp;</code> is a forwarding reference. But that’s not relevant here.)</p>\n<p>Finally… for what this function actually does, it’s sure complicated. That’s because of all the acrobatics you do with the <code>success</code> flag. Is that really necessary? Why not:</p>\n<pre><code>bool JValue::AddArrayChild(JValue value)\n{\n if (value_type_ == JValueType::Array)\n {\n children_.emplace_back(std::move(value));\n return true;\n }\n\n return false;\n}\n</code></pre>\n<p>Or even better, in my opinion:</p>\n<pre><code>bool JValue::AddArrayChild(JValue value)\n{\n if (value_type_ != JValueType::Array)\n return false;\n\n children_.emplace_back(std::move(value));\n return true;\n}\n</code></pre>\n<p>That seems to require the least amount of cognitive overhead. Once the check is done at the top of the function, you know that everything’s kosher from there on out; you don’t need to be thinking, “okay, at this line, are we in a state where we’re dealing with an error or failure or not?” or keeping track of scopes or anything.</p>\n<p>All of the same comments apply to <code>JValue::AddObjectChild()</code>, with one extra issue: exception safety. Consider the meat of the function:</p>\n<pre><code>value.name_ = name;\n// If the above throws an exception, no problem.\n\nthis-&gt;children_.emplace_back(std::move(value));\n// If the above throws an exception, also no problem.\n\nthis-&gt;children_name_indexes_[name] = this-&gt;children_.size() - 1;\n// But what if *this* throws? Now you have an element in children_ that\n// is unaccounted for in children_name_indexes_. Your object is broken.\n</code></pre>\n<p>This is the kind of headache that sometimes arises when you try to spread your class’s invariants across multiple data members. You should always aim for at least the strong exception guarantee: the function will either succeed, or, if it fails (particularly with an exception), it will have no (meaningful) effect.</p>\n<p>In this case, a potential fix is to wrap the last line in a <code>try</code> block that pops the back off the <code>children_</code> vector in the <code>catch</code> (and then rethrows), or to use some kind of “on fail” mechanism that does the same.</p>\n<pre><code>//returns true if the element exists, false otherwise\nbool RemoveChild(size_t index);\n//returns true if the element exists, false otherwise\nbool RemoveChild(const std::string&amp; name);\n</code></pre>\n<p>I’m really not a fan of this kind of interface. If you try to remove an index or name that doesn’t exist, that’s not just an “oh, well, it happens” kind of thing… <em>you have screwed up</em>. Something is seriously wrong your code and its logic. You should have that fact thrown in your face, so that you know and can fix it. It shouldn’t be something you can just ignore, especially by default.</p>\n<p>This same idea applies to the add functions as well, and to the accessors. I would call this class’s interface bad, because if I screw up, the class simply… covers that up. Mistakes vanish into return values that can just be ignored, and disappear into the æther. That’s not good; that’s very, very bad.</p>\n<p>I think a good interface is one that doesn’t reward lazy or sloppy coding. Quite the opposite, I think a good interface is one that rewards good practices, and punishes stupidity mercilessly. If you do something dumb, then the program should straight-up crash. It should do so loudly and dramatically. It should produce an error message, a core dump, and play a fart sound through the speakers.</p>\n<p>What am I talking about? Well, for example, I think the remove functions should look like this:</p>\n<pre><code>auto JValue::RemoveChild(std::size_t index) -&gt; void\n{\n children_name_indexes_.erase(\n std::find_if(begin(children_name_indexes), end(children_name_indexes),\n [index](auto&amp;&amp; item)\n {\n return std::get&lt;1&gt;(item) == index;\n }));\n \n children_.erase(children_.begin() + index);\n}\n\nauto JValue::RemoveChild(std::string const&amp; name) -&gt; void\n{\n auto const i = children_name_indexes_.find(name);\n \n children_.erase(children_.begin() + std::get&lt;1&gt;(*i));\n children_name_indexes_.erase(i);\n}\n</code></pre>\n<p>“But Indi!” you say, “if you try removing an out-of-bounds index or a non-existent name with that code, that’s UB!” Fine. Then just don’t do that.</p>\n<p>“But–but accidents!” Okay, if you accidentally remove an out-of-bounds index or a non-existent name, that should trigger some kind of panic that you can’t miss—like a crash—that would prompt you to use your debugger, find the problem, and fix it… you should <em>not</em> be shipping the program to your clients with that kind of bug hidden in it. At most you could maybe add some asserts in the functions that check that the index/name is valid… but those should disappear in release mode. I don’t want to pay for checks that should never fail, and no well-written code should ever cause those checks to fail.</p>\n<p><em>If</em> you decide you want to write code that potentially allows for non-existent indexes or names, then <em>you</em> should pay for it:</p>\n<pre><code>// q is some potentially non-existent index/name\n\n// index:\nif (q &gt;= 0 and q &lt; val.GetNumberOfChildren())\n val.RemoveChild(q);\nelse\n // handle the error case\n\n// name:\nif (val.HasProperty(q))\n val.RemoveChild(q);\nelse\n // handle the error case\n</code></pre>\n<p>But when I know for sure the name/index is valid, I don’t want to pay for those unnecessary checks. I just want to do <code>val.RemoveChild(q)</code>.</p>\n<p>As I mentioned, this same kind of thinking applies to the add functions as well. Adding a child to a value that isn’t an array isn’t an “oops” that should just be shrugged off. That’s a sign of a serious logic error in your code. <code>AddArrayChild()</code> should straight-up throw or terminate, or crash due to UB if you try to add a child to a non-array value. Personally, I’d recommend just making it UB, at least in release mode, so that programmers that don’t screw up don’t pay for the checks.</p>\n<p>Whew, I think that’s it for <code>JValue</code>. That was a lot, but like I said, I think <code>JValue</code> is the most critical part of your code. If <code>JValue</code> is done right, everything else becomes simple.</p>\n<p>I’m going to skip down to <code>ParserValueStack</code>, because, honestly, all of the state machine stuff looks fine to me. My opinion is that it’s over-engineered for parsing JSON—JSON is a pretty simplistic format, after all—but that doesn’t make it “wrong” or “bad”.</p>\n<h2><code>ParserValueStack.h</code> &amp; <code>ParserValueStack.cc</code></h2>\n<p>There are some problems with this class, mostly related to Unicode, and unnecessary copying of strings.</p>\n<pre><code>std::stringstream property_name_;\nstd::stringstream scalar_value_; \n</code></pre>\n<p>I’m not sure why you need string streams for these. All you do with them is append characters and strings, both tasks that <code>std::string</code> handles just fine. You don’t actually do anything that requires a stream.</p>\n<p>Worse, using string streams mean you end up having to make a bunch of unnecessary copies. Check out what’s going on in <code>PushJValue</code>:</p>\n<pre><code>void ParserValueStack::PushJValue(JValueType type)\n{\n optional&lt;JValue&gt; new_value;\n\n if (type == JValueType::Array || type == JValueType::Object || type == JValueType::Null)\n {\n new_value.emplace(type);\n }\n else\n {\n string accumulated_chars = this-&gt;scalar_value_.str();\n // This makes a copy of the string in scalar_value_.\n\n if (type == JValueType::String)\n new_value.emplace(accumulated_chars);\n // This makes *ANOTHER* copy of the same string.\n else if (type == JValueType::Number)\n new_value.emplace(std::stod(accumulated_chars));\n // This is okay.\n else if (type == JValueType::Boolean)\n new_value.emplace(accumulated_chars == &quot;true&quot;);\n // This is okay.\n }\n\n //add the new value to the top of the stack\n this-&gt;value_stack_.emplace(this-&gt;property_name_.str(), std::move(new_value.value()));\n // This makes a copy of the string in property_name_.\n\n //clear the accumulated values\n this-&gt;property_name_.str(&quot;&quot;);\n this-&gt;scalar_value_.str(&quot;&quot;);\n}\n</code></pre>\n<p>As long as you’re using string streams, copies are unavoidable (C++20 fixes this).</p>\n<p>Instead, suppose <code>property_name_</code> and <code>scalar_value_</code> were strings. All the places you use <code>operator&lt;&lt;</code>, just use <code>operator+=</code> instead. And <code>PushJValue()</code> could become:</p>\n<pre><code>void ParserValueStack::PushJValue(JValueType type)\n{\n optional&lt;JValue&gt; new_value;\n\n if (type == JValueType::Array || type == JValueType::Object || type == JValueType::Null)\n {\n new_value.emplace(type);\n }\n else\n {\n if (type == JValueType::String)\n new_value.emplace(std::move(scalar_value_));\n // No copying, just a move. This is fine because\n // scalar_value_ is never used again (until it's\n // reset).\n else if (type == JValueType::Number)\n new_value.emplace(std::stod(scalar_value_));\n // This is okay.\n else if (type == JValueType::Boolean)\n new_value.emplace(scalar_value_ == &quot;true&quot;);\n // This is okay.\n }\n\n //add the new value to the top of the stack\n this-&gt;value_stack_.emplace(std::move(this-&gt;property_name_), std::move(new_value.value()));\n // No copying, just a move. Also fine because property_name_ is\n // not used again.\n\n //clear the accumulated values\n this-&gt;property_name_ = std::string{};\n this-&gt;scalar_value_ = std::string{};\n // These variables may or may not have been moved from\n // (property_value_ is definitely moved-from, scalar_value_ might\n // be). Either way, we can reset them this way safely.\n}\n</code></pre>\n<p>Another benefit from doing it this way is that it makes exception safety easier. This function still isn’t entirely exception safe (if <code>value_stack_.emplace()</code> throws, <code>scalar_value_</code> might be moved-from, which would be bad). But it’s definitely closer. Those assignments at the end are totally no-fail.</p>\n<p>Before I get into the Unicode stuff, there’s one more function I want to call attention to:</p>\n<pre><code>void ParserValueStack::CollectUnicodeCodePoint(char input_char)\n{\n std::stringstream ss;\n ss &lt;&lt; input_char;\n\n //convert the hex char to a number \n unsigned char hex_num;\n ss &gt;&gt; std::hex &gt;&gt; hex_num;\n\n //each hex digit represents 1/2 a byte, so shift by 4\n this-&gt;unicode_code_point_ = (this-&gt;unicode_code_point_ &lt;&lt; 4) | (hex_num &amp; 0x0F);\n}\n</code></pre>\n<p>This function is <em>exceptionally</em> inefficient for what it does. Consider: you have a character <code>input_char</code> that is one of 0–9, a–f, or A–F (we’re assuming it <em>MUST</em> be one of those, because the function does no error checking), and all you want to do is convert that to the value 0–9 (if it’s a digit) or 10–15 (if it’s a letter). For that, you construct a stream (which is a whole lot of baggage) that does both input and output (more baggage) that constructs a string internally, and then you use the stream’s conversion operator.</p>\n<p>Not only is that wildly expensive for the task… it might not even work. If the global locale isn’t what you think it is, you could get weird results. What you <em>should</em> do is <code>ss.imbue(std::locale::classic());</code> before doing anything else.</p>\n<p>All you want to do is a simple, non-locale-aware conversion. <code>std::from_chars()</code> is actually built for that kind of thing, with JSON specifically in mind. Unfortunately, it won’t help much if you’re working one character at a time.</p>\n<p>For the digits, things are easy: the standard guarantees that digits are contiguous. So you can just do <code>input_char - '0'</code>. For the letters, which are <em>not</em> guaranteed to be contiguous… things are trickier, but not <em>difficult</em>. You have options. You could create a static <code>constexpr</code> lookup table. You could <code>static_assert</code> that the letters <em>are</em> contiguous, then simply do <code>input_char - 'A'</code> or <code>input_char - 'a'</code>. Whatever floats your boat.</p>\n<p>You might end up with something like this:</p>\n<pre><code>void ParserValueStack::CollectUnicodeCodePoint(char input_char)\n{\n auto hex_num = 0uL; // we'll worry about the right type for this later\n\n if (input_char &lt;= '0' and input_char &gt;= '9')\n {\n hex_num = input_char - '0'; // might need a static_cast, but we'll worry about that later\n }\n else\n {\n static constexpr auto hex_map = std::array&lt;std::tuple&lt;char, unsigned char&gt;, 12&gt;{\n {'a', 10},\n {'b', 11},\n // ...\n {'A', 10},\n {'B', 11},\n // ...\n };\n\n for (auto const [c, v] : hex_map)\n if (c == input_char)\n hex_num = v;\n }\n\n unicode_code_point_ = (unicode_code_point_ &lt;&lt; 4) | (hex_num &amp; 0x0FuL);\n}\n</code></pre>\n<p>No heap allocations, and even if the lookup is required, the entire lookup table can fit in a single cache line (it’s 24 bytes), and the lookup can possibly be vectorized.</p>\n<p>But now we come to the Unicode problem, and… well, Unicode in C++ is a fucking quagmire.</p>\n<p>The first problem is that you seem to assume that <code>wchar_t</code> is a Unicode type. It’s not. In fact, I believe on Windows it can’t even hold a complete Unicode value (though it can on Linux). Basically, <code>wchar_t</code> is a mistake. Never use it. Forget it even exists.</p>\n<p>That extends to everything associated with <code>wchar_t</code>, like <code>std::wctomb()</code>. That function does not do what you think it does; it does <em>not</em> convert from UTF-32 to UTF-8 (or maybe it does? it depends).</p>\n<p>The type you should use for <code>unicode_code_point_</code> is not <code>wchar_t</code>, it’s <code>char32_t</code>.</p>\n<p>But that’s only half the issue.</p>\n<p>You see, you seem to be assuming that a <code>std::string</code> holds UTF-8 (judging by the variable name <code>utf_chars</code>). Not so, unfortunately. That’s not the case on Windows (as far as I know; I don’t mess with Windows anymore).</p>\n<p>Okay, but whatever, right? Whatever the encoding of <code>std::string</code>, you just use <code>c32rtomb()</code> and that’s that, right?</p>\n<p>Yes… but no. I mean, yes, it is correct that you can convert UTF-32 to <code>std::string</code> bytes using <code>c32rtomb()</code>. The problem is that your code doesn’t take into account that <code>std::string</code>’s encoding might be <em>state-dependent</em>. Because of that, the generated code should be be correct, but fugly.</p>\n<p>I think it will be easier to illustrate the problem than try to explain it. Let’s assume that you changed <code>unicode_code_point_</code> to be <code>char32_t</code>, and rewrite <code>TranslatUnicodeCodePoint()</code> accordingly:</p>\n<pre><code>std::string ParserValueStack::TranslatUnicodeCodePoint()\n{\n auto state = std::mbstate_t{};\n auto chars = std::string(MB_CUR_MAX, char{});\n\n auto num_bytes = std::c32rtomb(chars.data(), unicode_code_point_, &amp;state);\n // should check that num_bytes != -1, but whatever\n chars.resize(num_bytes);\n\n return chars;\n}\n</code></pre>\n<p>This is basically the same as what you currently have, just using <code>std::c32rtomb()</code> instead of <code>std::wctomb()</code>.</p>\n<p>The issue is that you’re doing the conversion one character at a time. This isn’t a problem at all if <code>std::string</code>’s encoding isn’t state-dependent. But if it is, things still “work”… just not very well.</p>\n<p>For example, suppose the encoding of <code>std::string</code> is an old-school JIS (Japanese ASCII) encoding, and the input is <code>ABC\\u30A2\\u30A3\\u30A4DEF</code> (“ABCアイウDEF”). What you’d <em>like</em> to get is “ABC{shift-out}123{shift-in}DEF”—the “1” there is shifted to “ア”, “2” there is shifted to “イ”, and the “3” there is shifted to “ウ”. If you just ditch the shift state, then <code>TranslatUnicodeCodePoint()</code> might convert “\\u30A2” to “{shift-out}1{shift-in}”. Then, next, “\\u30A3” becomes “{shift-out}2{shift-in}”, giving you “ABC{shift-out}1{shift-in}{shift-out}2{shift-in}”… and “\\u30A4” becomes “{shift-out}3{shift-in}”, giving you “ABC{shift-out}1{shift-in}{shift-out}2{shift-in}{shift-out}3{shift-in}”.</p>\n<p>You can probably fix this by building the string up out of <code>char32_t</code> values as a <code>std::u32string</code>, then converting the whole thing to a <code>std::string</code> in one shot, rather than character by character. But frankly, I don’t know if it’s worth caring about. It’s 2020, and Unicode is the way of future; shifted encodings are probably ancient history now.</p>\n<p>So, all good?</p>\n<p>Well, no. (See? Quagmire.)</p>\n<p>The problem is that JSON only allows for 16-bit Unicode values. So how does one handle code points outside of the 16-bit range? By using surrogates. For example pile-of-poo () has hex code 1F4A9. To encode that in a JSON string, you’d need to do <code>&quot;\\uD83D\\uDCA9&quot;</code>.</p>\n<p>See the problem? Your code works with individual characters and assumes the characters are complete. It will read <code>\\uD83D</code>, try to convert that with <code>std::c32rtomb()</code>, which will fail, because that’s not a valid code point. The next read of <code>\\uDCA9</code> will similarly fail.</p>\n<p>So maybe you should try using <code>char16_t</code> values and <code>std::string16_t</code>? No, that will only shift the problem. Now you could handle <code>&quot;\\uD83D\\uDCA9&quot;</code> correctly, but not <code>&quot;&quot;</code>.</p>\n<p>Quagmire.</p>\n<p>What’s the best solution here? </p>\n<p>I can only offer you some suggestions:</p>\n<ul>\n<li>Don’t work character-by-character. That’s almost never the right thing to do when dealing with Unicode, or any character encoding other than trivial ASCII stuff. (“Character” doesn’t even make sense in most contexts.)</li>\n<li>Watch out for surrogates. Once you’ve collected a potential Unicode code point, check to see if it matches <code>0b1101'10??'????'????</code> or <code>0b1101'11??'????'????</code>. If so, there should be a matching pair to go along with it. If there’s <em>not</em> a matching partner, you have an invalid Unicode sequence (you can also get those from other misuses of Unicode escapes). You should decide how to handle those.</li>\n</ul>\n<p>What a huge mess Unicode created, eh?</p>\n<h1>Questions</h1>\n<p>Okay, that should probably do it for the code review… now for the questions.</p>\n<ul>\n<li><p>Is this good, clean, idiomatic C++17?</p>\n<p>Sure, looks okay to me.</p>\n</li>\n<li><p>Is the project layout and class structure what you would expect?</p>\n<p>I could mostly find what I was looking for without too much digging, so yes.</p>\n</li>\n<li><p>I have some header-only classes, is that okay?</p>\n<p>Definitely. There is actually good reason to try to make the entire library header-only (which is something that wouldn’t be too hard to achieve in your case). There’s not really anything to be gained from implementation files, except faster compilation, and less recompiling when details are tweaked.</p>\n</li>\n<li><p>Are things named right?</p>\n<p>I won’t say no.</p>\n</li>\n<li><p>Is there any code in headers which should be in implementation files, or vice versa?</p>\n<p> “Should be” according to whose rules or what requirements?</p>\n<p>There are reasons to prefer an entirely header-only library, but there are also cons. For something as simple as a JSON library, it could probably be completely header-only with no real cons.</p>\n</li>\n<li><p>Are rvalues/lvalues, references, const, auto, and other C++ features being used correctly?</p>\n<p>No. There seems to be some confusion about lvalues and rvalues, and references thereof, but I don’t see any real <code>const</code> issues. Same for <code>auto</code>.</p>\n<p>The one major feature I think isn’t being used correctly has to do with the disabling of copying in what is (or <em>should</em> be) a <a href=\"https://en.cppreference.com/w/cpp/concepts/regular\" rel=\"nofollow noreferrer\">regular</a> value type.</p>\n</li>\n<li><p>I wrote Java-esq getters and setters for private members - is this the idiomatic C++ way for accessors/mutators?</p>\n<p>Sure. I mean, if you need a getter and setter for a private member, it’s worth asking whether it should be private at all. If it won’t cause the invariants to break, you might as well make it public. But if it needs to be private, and its needs setters and getters, then so be it.</p>\n</li>\n<li><p>Performance - any issues I've overlooked?</p>\n<p>I haven’t run any tests, but I am <em>highly</em> suspicious of the overall performance of the design. Parsing a JSON string character by character—updating a state machine with every one—seems like the most painfully slow and tedious way to do it.</p>\n<p>Indeed, the idea of a <em>literal</em> state machine to parse JSON seems like overengineering to me. It seems to me that if you wrote a JSON parser in the simplest and most straightforward way, you’d end up with a <em>logical</em> PDA that uses the function call stack as the stack. And it would probably be orders of magnitude faster, because it’s not literally pushing and popping states from a dynamically-allocated stack, but merely calling and returning from functions.</p>\n</li>\n<li><p>Any excessive copying or other issues?</p>\n<p>Generally no.</p>\n</li>\n<li><p>I'm not using pointers anywhere - all memory is either on the stack or managed by STL classes (like vector), is that okay?</p>\n<p>Pointers are not just about memory. They’re also useful for representing optional stuff—in some ways better than <code>std::optional</code>.</p>\n<p>This doesn’t come up in your design, but consider a function that takes an optional parameter, like, say, a function that joins a sequence of strings with an optional delimiter. So the function could be like: <code>std::string join(std::vector&lt;std::string&gt; items, std::optional&lt;std::string&gt; delimiter)</code>. If you already have the delimiter string lying around, or you read it from somewhere, you have to copy it into an <code>std::optional</code> to use it with this function. By contrast, if the function was: <code>std::string join(std::vector&lt;std::string&gt; items, std::string const* delimiter)</code>, you could simply point to the delimiter string. Or pass <code>nullptr</code> if you don’t want one. No copies are needed.</p>\n<p>It seems like you’ve misunderstood advice about modern C++. It’s not “no raw pointers”. It’s “no <em>owning</em> raw pointers”. Non-owning pointers are still okay (mostly). It’s actually more complicated than that, but basically, raw pointers do have their uses. You don’t seem to have come across any of those uses in your code, and that’s fine.</p>\n</li>\n</ul>\n<h1>Summary</h1>\n<p>All in all, I’d say this is good code.</p>\n<p>It may be a bit much (and, by extension, a bit slow) for parsing something as simple as JSON, but the neat thing about your design is that’s not really a fatal shortcoming. You can basically take all of the guts of your library, simply replace the various states, and have a perfectly functional parser for <em>any</em> format… including ones much more complex than JSON.</p>\n<p>The one weak link is the <code>JValue</code> class, which should be the centrepiece of your library, but instead feels kludgy and difficult to work with. If that was made more user-friendly, it would really help make the parsing facilities more attractive. (And it would probably make them easier to write, too.)</p>\n<p>And, of course, there’s the whole Unicode mess… but that’s not really your fault. All of the complexity comes from the poor support in C++, and the fact that crap like UTF-16 even exists. Fixing that could be a project all on its own.</p>\n<p>My suggestion for a possible next step would be to extract all of the JSON-specific stuff out of the automaton code, so that the machine itself is completely abstract, and could be used for any purpose—not just parsing, either. I think you’ve got a good idea here, and good code structure, so you have a solid base to build from.</p>\n<h1>Addendums</h1>\n<h2>Writing an extractor</h2>\n<p>If you’re not worrying about throwing custom exceptions—which complicates things a <em>lot</em>—or different character types or any of that other fun stuff that makes IOstreams a nightmare, writing a custom extractor is actually pretty simple. You’ve already done 95% of the work already, in fact!</p>\n<p>IOstreams recognizes two different types of “error”: “bad” and “fail”.</p>\n<p>“Bad” means the <em>stream</em> is broken. Like, the hard-drive failed while reading a file, or the network disconnected while downloading data; that kind of thing. Or something else went wonky in the internals of the stream (like the buffer was a null pointer, and so on). It’s considered an unrecoverable error (because even if you can recreate, reopen, or reconnect the stream, you generally won’t be where you were before—you’d have to start parsing all over).</p>\n<p>“Fail” is what you’re looking for; it means that the attempted extraction failed. For example, attempting to extract an <code>int</code> from “xyz” will fail. In your case, attempting to extract JSON data from malformed JSON would fail.</p>\n<p>To set the fail bit, you just do:</p>\n<pre><code>stream.setstate(std::ios_base::failbit);\n</code></pre>\n<p>Note that depending on the stream’s setup, this might throw an exception. That’s not a problem—if it happens, it means the user specifically asked for it to happen—but be aware of it for exception safety reasons.</p>\n<p>So your extractor could be as simple as:</p>\n<pre><code>auto operator&gt;&gt;(std::istream&amp; in, JValue&amp; val) -&gt; std::istream&amp;\n{\n // You can check that the stream is good before bothering to try\n // any parsing. It's not necessary, of course; you already handle\n // stream errors within the state machine.\n if (in)\n {\n JsonReader parser;\n if (auto parsed_json = parser.ParseJsonString(in); parsed_json)\n // A neat side effect of parsing into a temporary and then\n // moving into the out parameter is that you automatically\n // get the strong exception guarantee. If any exceptions\n // are thrown anywhere, val is not touched.\n val = std::move(*parsed_json);\n else\n in.setstate(std::ios_base::failbit);\n }\n\n return in;\n}\n</code></pre>\n<p>That’s pretty much it.</p>\n<p>Now, since I got on the subject of IOstreams, I do have a couple of suggestions for making your library play a little nicer with IOstreams….</p>\n<p>To do your input, you read a character at a time from the stream. That’s fine… <em>but</em>… the mechanism you choose to use is <code>operator&gt;&gt;(char)</code>.</p>\n<p>The reason this is a problem is because <code>operator&gt;&gt;</code> is a <em>formatted</em> input function. As you probably already noticed, that means it skips whitespace… which is why you had to use <code>input &gt;&gt; std::noskipws;</code> in <code>JsonReader::ParseJsonString()</code> (which you then fail to revert, which could annoy users when they find their stream suddenly no longer ignoring whitespace after reading JSON).</p>\n<p>Since you handle all your whitespace manually, you’re better off using an <em>unformatted</em> input function. <a href=\"https://en.cppreference.com/w/cpp/io/basic_istream/get\" rel=\"nofollow noreferrer\">istream::get()</a> is what the doctor ordered.</p>\n<p>In <code>ParserStatesManager::GetNextTransition()</code>, just replace:</p>\n<pre><code>else\n{\n char c = '\\0';\n if (input &gt;&gt; c)\n {\n</code></pre>\n<p>with:</p>\n<pre><code>else\n{\n char c = '\\0';\n if (input.get(c))\n {\n</code></pre>\n<p>and you’re golden. Now you can remove the <code>input &gt;&gt; std::noskipws;</code> line in <code>JsonReader::ParseJsonString()</code>, and not have to worry about keeping track of the stream’s whitespace-skipping state.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-07T17:21:57.393", "Id": "477965", "Score": "0", "body": "Wow! This is wonderful - thank you so much for taking the time and really getting into it; this is super helpful and exactly what I was looking for! I'm going to spend some time reworking, especially the JValue class." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-07T17:22:09.243", "Id": "477966", "Score": "0", "body": "One question - would you mind pointing me at an example of a proper overload of the >> operator for istream? I'm specifically trying to understand how to signal errors and where to put error messages. Thanks again!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-11T13:30:11.417", "Id": "478356", "Score": "1", "body": "Hm, I’m not aware of any good, up-to-date references on writing extractors… but it’s so simple (because you’ve already done all the heavy lifting), I’ll just extend the answer." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-13T17:55:35.577", "Id": "478626", "Score": "0", "body": "It's worth pointing out that if you have return values the user _should_ use, flagging them [[nodiscard]] is a good idea. Maybe not all coding style guidelines allow for it but in your case it should be OK. Calling `getString()` and ignoring the string is probably always a programmer error." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-06T23:37:09.630", "Id": "243501", "ParentId": "243445", "Score": "8" } }, { "body": "<p>Bug:</p>\n\n<pre><code>const JValue&amp; operator[](const std::string&amp; name) const \n{ \n return this[children_name_indexes_.at(name)]; \n}\n</code></pre>\n\n<p>This won't do what you want. This is a plain UB nonsense. It should've been:</p>\n\n<pre><code>const JValue&amp; operator[](const std::string&amp; name) const \n{ \n return (*this)[children_name_indexes_.at(name)];\n // or\n // return operator[](children_name_indexes_.at(name)); \n}\n</code></pre>\n\n<p>About <code>auto</code> usage:</p>\n\n<pre><code>auto stack_symbol = (machine_stack.GetSize() &gt; 0) ? machine_stack.GetTop() : ParserStackSymbol::None; \n\nauto next_transition_container = states_manager_.GetNextTransition(current_state_type, input, stack_symbol);\nconst auto&amp; next_transition = next_transition_container.transition;\n</code></pre>\n\n<p>All of these should be named types instead of <code>auto</code>. Abusing <code>auto</code> makes harder to reason about types one works with.</p>\n\n<p>It is helpful to use <code>auto</code> for user-doesn't-care types like incomprehensible iterators or in template cases when one doesn't know the type at all. Usually, it is fine to use for-loop though <code>for(auto&amp;&amp; elem : some_vector_or_map)</code> as it is normally clear what type that is.</p>\n\n<p>Error Reporting Mechanism:</p>\n\n<pre><code>JsonReader(std::ostream&amp; error_output_stream = std::cerr, \n std::ostream&amp; debug_output_stream = std::cout, bool debug_output = false);\n</code></pre>\n\n<p>It is fine to use some tools for debugging but users shouldn't be bothered with debug/error output streams. Throw an exception that describes what's the problem. Nobody likes exceptions but this the best way to deal with this problem. At most add an option to obtain the reported error without any throws.</p>\n\n<p>If you write it for a specific library then use their logger class instead of <code>std::cout</code> or <code>std::ostream</code>. As these aren't good for logging in general. If any multithreaded code does multi-threaded printing you will end up with corrupted logs and <code>std::ostream</code> doesn't have any suitable API to deal with it. </p>\n\n<p>Main Issue: <strong>API</strong></p>\n\n<p>boost utilizes their <code>property_tree</code> for parsing/storing json. </p>\n\n<p>In this property tree one can easily access value stored even in grand-grand-children.</p>\n\n<pre><code> int a = boost_aptree.get&lt;int&gt;(\"a.long.path.to.the.value\");\n</code></pre>\n\n<p>In your case it would have to be something like:</p>\n\n<pre><code> int a = (int)aparsedJson[\"a\"][\"long\"][\"path\"][\"to\"][\"the\"][\"value\"].GetNumberValue().value();\n</code></pre>\n\n<p>It is not even so horrible when you write it knowing the path but what about when you want to forward the path to some other place?</p>\n\n<p>Also if one wants to make it safe from exceptions and obtain in optional form in boost one would have to write just <code>get_optional</code> instead of <code>get</code> and in your case it would be a nightmare of a bunch of lines.</p>\n\n<p>Same is true for setting values and not just getting them.</p>\n\n<p>I believe boost also utilizes some smart lookup mechanism separate from the tree structure while in yours each node has its own lookup (the unordered_map) and it is only one level deep - which is totally inefficient as when there are several child-levels to the json. It has to apply a string lookup for each level of depth.</p>\n\n<p>Summary:</p>\n\n<p>Overall I agree with @indi answer, I just added a couple of points he missed or I felt he didn't address enough. Overall, the code is written well in a clean way.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-07T17:22:25.050", "Id": "477967", "Score": "0", "body": "Good catches - thanks!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-07T00:28:39.667", "Id": "243504", "ParentId": "243445", "Score": "3" } } ]
{ "AcceptedAnswerId": "243501", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-05T20:42:36.287", "Id": "243445", "Score": "7", "Tags": [ "c++", "json", "c++17" ], "Title": "JSON reader based on a pushdown automata" }
243445
<p>I need to add some characters to a String before using it for an API call. The idea is to add a <code>"</code> char both at the beginning and at the end of the String, to make sure the API does an exact search for the input string.</p> <p>Version 1:</p> <pre><code>StringBuilder(escapeJava(query)) .insert(0, DOUBLE_QUOTE_CHAR) .append(DOUBLE_QUOTE_CHAR) .toString(); </code></pre> <p>Version 2:</p> <pre><code>String.format("%c" + escapeJava(query) + "%c", DOUBLE_QUOTE_CHAR, DOUBLE_QUOTE_CHAR) </code></pre> <p>I prefer the readability of the first one, but I don't think it will be as quick as the second version, and might look like overkill. </p>
[]
[ { "body": "<p>Version 1 uses <code>insert(0, ...)</code> which has to move over all the characters already in the <code>StringBuilder</code>'s buffer, so is unnecessarily wasting time.</p>\n\n<p>A more efficient construct would be:</p>\n\n<pre><code>StringBuilder().append(DOUBLE_QUOTE_CHAR)\n .append(escapeJava(query))\n .append(DOUBLE_QUOTE_CHAR)\n .toString();\n</code></pre>\n\n<p>Version 2 uses <code>StringBuilder</code> under the hood, to construct <code>\"%c\" + escapeJava(query) + \"%c\"</code>, so your belief the second version is faster may be in error.</p>\n\n<p>Which leads us to the most efficient, most readable version:</p>\n\n<pre><code>DOUBLE_QUOTE_CHAR + escapeJava(query) + DOUBLE_QUOTE_CHAR;\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-05T22:32:44.537", "Id": "477838", "Score": "1", "body": "Does it really make a difference to performance?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-05T22:39:18.213", "Id": "477839", "Score": "1", "body": "@Peilonrayz Somehow, I doubt this is the performance bottleneck of the application. But avoiding the memcopy caused by `insert` will be a win, as will avoiding the `format`. I'll run some performance numbers later, but as always, with hotspot JIT optimizations, getting accurate profiling requires careful work." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-05T22:42:49.100", "Id": "477840", "Score": "0", "body": "True, true. Coming from Python I've gained an, unhealthy, level of scepticism between theory and practice. Sometimes there's magic optimizations that are really quite odd. If it's lots of work, don't bother :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-06T14:36:23.113", "Id": "477871", "Score": "1", "body": "If you want to improve performance then use the length of the escaped query + 2 as initial capacity of the `StringBuilder`; that will avoid multiple allocations happening out of view. Note that using the plus operator twice may use **two** string builders - although in the end that's implementation specific of course. All this doesn't matter if it is not in the critical part though, so yeah, the last one is definitely the most easy to read." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-05T22:21:17.503", "Id": "243450", "ParentId": "243448", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-05T21:51:42.550", "Id": "243448", "Score": "1", "Tags": [ "java", "strings", "comparative-review" ], "Title": "Encasing a string in double quotes" }
243448
<p>i'm doing a Core for a Tic Tac Toe game.</p> <p>I have my code with a dynamic size of the board (can be 2x2 to 10x10, if is 7x7 we need a 7 characters in a row to win , if is 4x4 we need 4 etc) , This code works for any matrix with any size and give me a bool state if someone won the game (they can use any character to mark on the matrix, like X or O). This code skips the empty strings ("") and zeros ("0"). </p> <p>The Matrix Validator Code (Where i send the matrix i wanna check)</p> <pre><code>public class MatrixValidator { private string[,] Matrix { get; set; } private string[] Vector { get; set; } public MatrixValidator(string[,] matrix) { this.Vector = new string[matrix.GetLength(0)]; this.Matrix = matrix; } public bool MatrixHasWinner() { return HorizontalValidator() || VerticalValidator() || MainDiagonalValidator() || SecondDiagonalValidator(); } private bool HorizontalValidator() { bool Control = false; for (int i = 0; i &lt; this.Matrix.GetLength(1); i++) { Array.Clear(Vector, 0, Vector.Length); for (int j = 0; j &lt; this.Matrix.GetLength(0); j++) { this.Vector[j] = this.Matrix[i, j]; } if (!ArrayValidator.HasBlank(this.Vector)) Control = ArrayValidator.HasSameValues(this.Vector); } return Control; } private bool VerticalValidator() { bool Control = false; for (int j = 0; j &lt; this.Matrix.GetLength(0); j++) { Array.Clear(Vector, 0, Vector.Length); for (int i = 0; i &lt; this.Matrix.GetLength(1); i++) { this.Vector[i] = this.Matrix[i, j]; } if (!ArrayValidator.HasBlank(this.Vector)) Control = ArrayValidator.HasSameValues(this.Vector); } return Control; } private bool MainDiagonalValidator() { bool Control = false; Array.Clear(Vector, 0, Vector.Length); for (int i = 0; i &lt; this.Matrix.GetLength(0); i++) { for (int j = 0; j &lt; this.Matrix.GetLength(1); j++) { if (i == j) this.Vector[j] = this.Matrix[i, j]; } } if (!ArrayValidator.HasBlank(this.Vector)) Control = ArrayValidator.HasSameValues(this.Vector); return Control; } private bool SecondDiagonalValidator() { bool Control = false; Array.Clear(Vector, 0, Vector.Length); for (int i = 0; i &lt; this.Matrix.GetLength(1); i++) { for (int j = 0; j &lt; this.Matrix.GetLength(0); j++) { if (i + j == this.Matrix.GetLength(0) - 1) this.Vector[i] = this.Matrix[i, j]; } } if (!ArrayValidator.HasBlank(this.Vector)) Control = ArrayValidator.HasSameValues(this.Vector); return Control; } } </code></pre> <p>The Array Validator Code (Where i send the line, array i wanna check)</p> <pre><code>public static class ArrayValidator { public static bool HasBlank(string[] vector) { return (vector.Contains("") || vector.Contains("0")); } public static bool HasSameValues(string[] vector) { var v = vector.Distinct().Count(); if (v == 1) return true; else return false; } } </code></pre> <p>Program.cs (The usage of my code)</p> <pre><code>static void Main(string[] args) { string[,] matrix = { { "X", "X", "X", "X" }, { "O", "", "", "" }, { "", "", "", "" }, { "O", "", "O", "" } }; // X Wins MatrixValidator matrixValidator = new MatrixValidator(matrix); Console.WriteLine(matrixValidator.MatrixHasWinner()); Console.ReadKey(); } </code></pre> <p>What changes can i do to improve this code? Maybe it is not implemented with SOLID? I need help</p>
[]
[ { "body": "<p>Here some some gentle suggestions for this particular implementation:</p>\n\n<ul>\n<li>This isn't really a \"validator\" as it doesn't validate anything. Maybe consider \"evaluator\" or something along those lines.</li>\n<li>When you receive the Matrix, you can store the value of <code>this.Matrix.GetLength(0)</code> and use it instead of calling it multiples times. Since you know the Matrix is always NxN, you know that the first dimension length will always match the second dimension length (in other words, <code>this.Matrix.GetLength(1) == this.Matrix.GetLength(0)</code>)</li>\n<li>You aren't checking to see if the Matrix is <em>actually</em> an NxN matrix. What if the user passed in a 4x3?</li>\n<li>You are doing quite a bit of copying for no strong benefit. If every item in a row, column or diagonal is the same, then you know there's a win. So, see if a character matches the one next to it. If not, then you know there's no win. If it is a match, check the next one. You don't need to copy that to another array and the do the distinct. If you did that, you'd significantly reduce the lines of code and complexity. Maybe something like: <code>if (matrix[i,j] != matrix[i + 1,j]) return false;</code> Obviously you'll need some bounds checking, etc.</li>\n<li>Other than <code>MatrixHasWinner</code>, there's literally nothing in your code that suggests this is for a game of tic-tac-toe. You are using very generic names (matrix, vector) and not assigning any context to that. Matrix could be GameBoard. Vector could be Row or Column (though, as I said above, you don't really need it).</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-06T02:06:35.900", "Id": "243456", "ParentId": "243451", "Score": "4" } } ]
{ "AcceptedAnswerId": "243456", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-05T23:05:46.867", "Id": "243451", "Score": "2", "Tags": [ "c#", "tic-tac-toe" ], "Title": "C# Tic Tac Toe Game with SOLID" }
243451
<p>Probably a dumb question but just can't seem to make a decision here. </p> <p>I'm building a C# class library that I intend for other developers to use. Let's say one of these classes contains a method that accesses a remote resource and maps it to an object:</p> <pre><code>public class FooClient { public async Task&lt;Foo&gt; ShowAsync(string name, ...) { return await DoStuffAsync(name); } } </code></pre> <p>Where <code>name</code> identifies this remote resource. Let's also say that this resource can be identified by a numerical <code>id</code>, and that I can pass <code>id.ToString()</code> as <code>name</code> to this method and retrieve the same resource. So, I want an overload:</p> <pre><code>public class FooClient { public async Task&lt;Foo&gt; ShowAsync(string name, ...) { return await DoStuffAsync(name); } public Task&lt;Foo&gt; ShowAsync(long id, ...) { return ShowAsync(id.ToString(), ...); } } </code></pre> <p>According to the <a href="https://docs.microsoft.com/en-us/dotnet/standard/design-guidelines/member-overloading" rel="nofollow noreferrer">Microsoft docs</a>, I should avoid <em>arbitrarily</em> varying parameter names, so I'm tempted to do something like this:</p> <pre><code>public class FooClient { public async Task&lt;Foo&gt; ShowAsync(string foo, ...) { return await DoStuffAsync(foo); } public Task&lt;Foo&gt; ShowAsync(long foo, ...) { return ShowAsync(foo.ToString(), ...); } } </code></pre> <p>But I'm afraid that, in this case, it would be more descriptive to have different names for the parameters, even though they identify the same resource. What should I do?</p>
[]
[ { "body": "<p>To answer your direct question - always name your parameters to match the intent of the type. If they are passing in an Id, call it an Id. What Microsoft is saying is if you had the following:</p>\n\n<pre><code> public async Task&lt;Foo&gt; ShowAsync(string name, ...)\n {\n return await DoStuffAsync(foo);\n }\n public Task&lt;Foo&gt; ShowAsync(string resourceName, int id, ...)\n {\n return ShowAsync(resourceName + foo.ToString(), ...);\n }\n</code></pre>\n\n<p>In that case, <code>name</code> and <code>resourceName</code> represent the exact same concept: they are both the name of the resource. If you are using the same type and concept within overloads, always keep the name the same. For this, you are changing the type and concepts so change the name to match the concept.</p>\n\n<p>With that said...</p>\n\n<p>In this particular instance, I <em>personally</em> probably wouldn't use overloading and would, instead, say <code>ShowBynameAsync</code> and <code>ShowByIdAsync</code>. </p>\n\n<p>Downside - there's two <em>distinct</em> methods.</p>\n\n<p>A potential upside is that no matter how the developer uses your API, it's always clear (to future readers) what they are passing in. Also, it's extremely clear what's being requested. You could still delegate the \"showing\" to <code>ShowByNameAsync</code>.</p>\n\n<p>It's not \"wrong\" to use overloading here and not \"right\" to use descriptive method names. Just a preference.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-06T01:42:49.057", "Id": "243454", "ParentId": "243452", "Score": "3" } } ]
{ "AcceptedAnswerId": "243454", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-05T23:08:39.693", "Id": "243452", "Score": "1", "Tags": [ "c#", "api", "library", "overloading" ], "Title": "Varying Parameter Names in Method Overloads" }
243452
<p>After spending a few months learning python I decided to build a basic Rock Paper Scissors game.</p> <p>Basic construct of the game:</p> <ul> <li>Allows you to pick best of 3,5,7</li> <li>Allows you to put in the name</li> <li>Computer choices are completely random</li> </ul> <p>I know there are probably a million different ways to write this code. But based on the way that I built it, are there any ways to make my code more efficient?</p> <pre class="lang-py prettyprint-override"><code># Rock Paper Scissors import random as rdm print("Welcome to Rock/Paper/Scissors!!! \n") gl = input("Would you like to play a best of 3, 5 or 7: ") while gl not in ["3", "5", "7"]: gl = input("Incorrect Response, please select 3, 5, or 7: ") gl = int(gl) human_1 = input("Please enter your name: ") GameOptions = ['Rock', 'Paper', 'Scissors'] hmn_score = 0 cpt_score = 0 rps_running = True def rps(): global cpt_score, hmn_score while rps_running: hmn_temp = input("""Please select from the following: 1 - Rock 2 - Paper 3 - Scissors \n""") while hmn_temp not in ["1", "2", "3"]: print("That was not a acceptable input!") hmn_temp = input("""Please select from the following: 1 - Rock 2 - Paper 3 - Scissors \n""") hmn_final = int(hmn_temp) - 1 print('You Chose: ' + GameOptions[hmn_final]) cpt = rdm.randint(0, 2) print('Computer Chose: ' + GameOptions[cpt] + '\n') if hmn_final == cpt: print('Tie Game!') elif hmn_final == 0 and cpt == 3: print('You Win') hmn_score += 1 elif hmn_final == 1 and cpt == 0: print('You Win') hmn_score += 1 elif hmn_final == 2 and cpt == 1: print('You Win') hmn_score += 1 else: print('You Lose') cpt_score += 1 game_score() game_running() def game_score(): global cpt_score, hmn_score print(f'\n The current score is {hmn_score} for you and {cpt_score} for the computer \n') def game_running(): global rps_running, gl if gl == 3: if hmn_score == 2: rps_running = False print(f"{human_1} Wins!") elif cpt_score == 2: rps_running = False print(f"Computer Wins!") else: rps_running = True elif gl == 5: if hmn_score == 3: rps_running = False print(f"{human_1} Wins!") elif cpt_score == 3: rps_running = False print(f"Computer Wins!") else: rps_running = True elif gl == 7: if hmn_score == 4: rps_running = False print(f"{human_1} Wins!") elif cpt_score == 4: rps_running = False print(f"Computer Wins!") else: rps_running = True rps() </code></pre>
[]
[ { "body": "<h1>Names</h1>\n\n<p>I've renamed:</p>\n\n<ul>\n<li><code>hmn_*</code> -> <code>human_*</code></li>\n<li><code>cpt_*</code> -> <code>computer_*</code></li>\n<li><code>g1</code> -> <code>max_score</code></li>\n<li><code>human_1</code> -> <code>human_name</code></li>\n<li><code>game_score</code> -> <code>print_scores</code></li>\n<li><code>game_running</code> -> <code>check_scores</code></li>\n<li><code>rps</code> -> <code>start</code></li>\n<li><code>rps_running</code> -> <code>running</code></li>\n<li><code>rdm</code> -> <code>random</code> </li>\n<li><code>GameOptions</code> -> <code>GAME_OPTIONS</code> (we usually use pascal case for a <code>class</code> in Python, and capitalization for variable constants)</li>\n</ul>\n\n<p>Reason for all this renaming was to make it clear to an outside reader what all the variables mean without having to look past their declaration. If you ever revisit this code, you don't want to have to dive deep into it every time.</p>\n\n<p>As for renaming the functions, we are now able to tell what they do without diving into their bodies. For example, <code>print_scores</code> clearly tells us that it prints the status of the scores.</p>\n\n<h1><code>check_scores</code></h1>\n\n<p>Currently you have three different outer <code>if</code>s corresponding to <code>max_score</code> equaling 3, 5 or 7. In each of these <code>if</code>s, you check if <code>human_score</code> or <code>computer_score</code> are greater than half of the total possible score. This entire function can be simplified by making this comparison work for any value of <code>max_score</code>:</p>\n\n<pre><code>def check_scores():\n global running, max_score\n\n if human_score &gt; max_score / 2:\n running = False\n print(f\"{human_1} Wins!\")\n\n elif computer_score &gt; max_score / 2:\n running = False\n print(\"Computer Wins!\")\n</code></pre>\n\n<p>Since <code>check_scores</code> can only be possibly called if <code>running == True</code>, we don't need to reassign it to <code>True</code> in the <code>else</code>, so we can get rid of that.</p>\n\n<h1><code>start</code></h1>\n\n<p>You can make the <code>input</code> call for <code>human_temp</code> a function such that the prompt isn't specified twice in the code:</p>\n\n<pre><code>def get_human_temp():\n return input(\"\"\"Please select from the following:\n 1 - Rock\n 2 - Paper\n 3 - Scissors\n \\n\"\"\")\n</code></pre>\n\n<p>This changes the <code>human_temp</code> <code>while</code> loop to:</p>\n\n<pre><code>human_temp = get_human_temp()\n\nwhile human_temp not in [\"1\", \"2\", \"3\"]:\n print(\"That was not a acceptable input!\")\n human_temp = get_human_temp()\n</code></pre>\n\n<p>Ah, this is a do-while loop! If you're on Python 3.8, you can use the <a href=\"https://www.python.org/dev/peps/pep-0572/\" rel=\"nofollow noreferrer\">walrus operator</a>:</p>\n\n<pre><code>while (human_temp := get_human_temp()) not in [\"1\", \"2\", \"3\"]:\n print(\"That was not a acceptable input!\")\n</code></pre>\n\n<p>For your entire chain of <code>elif</code>s checking whether the human won, a more concise way to do is it to check if <code>human_final - 1 == computer</code>. This works for any <code>human_final</code> except 0. To make it work for 0, we would need to check <code>human_final + 2 == computer</code>. We can combine these two checks concisely as follows:</p>\n\n<pre><code>if human_final == computer:\n print('Tie Game!')\n\nelif computer in (human_final - 1, human_final + 2):\n print('You Win')\n human_score += 1\n\nelse:\n print('You Lose')\n computer_score += 1\n</code></pre>\n\n<p>I believe that <code>elif human_final == 0 and computer == 3</code> was a subtle bug in your original code, <code>computer</code> should have been checked against 2.</p>\n\n<p>You can think of the <code>elif</code> as checking whether <code>human_final</code> is one ahead of <code>computer</code> in <code>GAME_OPTIONS</code>, while accounting for wrapping around <code>GAME_OPTIONS</code>.</p>\n\n<h1>Global State</h1>\n\n<p>There's a lot of global state in your program (show by all the <code>global</code> calls). We can use a <code>class</code> to store the state for each specific game. This state includes <code>max_score</code> (describes when a particular game ends), <code>human_name</code> (describes who is playing the game) and <code>human_score</code> / <code>computer_score</code> / <code>running</code> (describes current state of the game). Let's call this <code>class</code> <code>Game</code>, with an initialization method like this:</p>\n\n<pre><code>def __init__(self, max_score, human_name):\n self.max_score = max_score\n self.human_name = human_name\n\n self.human_score = 0\n self.computer_score = 0\n self.running = False\n</code></pre>\n\n<p>We would then put all of your methods using global state in <code>Game</code>, with <code>self</code> prepended to all the variables we have here in our <code>__init__</code> method.</p>\n\n<p>As for the code that is run before we even start the game (the code responsible for fetching <code>human_name</code> and <code>max_score</code>), we can put this in an <code>if __name__ == \"__main__\"</code> block. This makes it so we can use <code>Game</code> <a href=\"https://stackoverflow.com/questions/419163/what-does-if-name-main-do\">from another module</a> without having all the <code>input</code>-specific code running. </p>\n\n<p>Here's the final code, with some very slight consistency changes (such as standardizing the type of quotation mark you use, and getting rid of unnecessary <code>f</code>s at the beginning of unformatted strings):</p>\n\n<pre><code># Rock Paper Scissors\n\nimport random\n\n\ndef get_human_temp():\n return input(\"\"\"Please select from the following:\n 1 - Rock\n 2 - Paper\n 3 - Scissors\n \\n\"\"\")\n\n\nGAME_OPTIONS = [\"Rock\", \"Paper\", \"Scissors\"]\n\n\nclass Game:\n def __init__(self, max_score, human_name):\n self.max_score = max_score\n self.human_name = human_name\n\n self.human_score = 0\n self.computer_score = 0\n self.running = False\n\n def print_scores(self):\n print(f\"\\n The current score is {self.human_score} for you and {self.computer_score} for the computer \\n\")\n\n def check_scores(self):\n if self.human_score &gt; self.max_score / 2:\n self.running = False\n print(f\"{self.human_name} Wins!\")\n\n elif self.computer_score &gt; self.max_score / 2:\n self.running = False\n print(\"Computer Wins!\")\n\n def start(self):\n self.running = True\n\n while self.running:\n while (human_temp := get_human_temp()) not in [\"1\", \"2\", \"3\"]:\n print(\"That was not a acceptable input!\")\n\n human_final = int(human_temp) - 1\n print(f\"You Chose: {GAME_OPTIONS[human_final]}\")\n\n computer = random.randint(0, 2)\n print(f\"Computer Chose: {GAME_OPTIONS[computer]}\\n\")\n\n if human_final == computer:\n print(\"Tie Game!\")\n\n elif computer in (human_final - 1, human_final + 2):\n print(\"You Win\")\n self.human_score += 1\n\n else:\n print(\"You Lose\")\n self.computer_score += 1\n\n self.print_scores()\n self.check_scores()\n\n\nif __name__ == \"__main__\":\n print(\"Welcome to Rock/Paper/Scissors!!! \\n\")\n\n max_score = input(\"Would you like to play a best of 3, 5 or 7: \")\n\n while max_score not in [\"3\", \"5\", \"7\"]:\n max_score = input(\"Incorrect Response, please select 3, 5, or 7: \")\n\n max_score = int(max_score)\n human_name = input(\"Please enter your name: \")\n\n game = Game(max_score, human_name)\n game.start()\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-08T19:29:19.633", "Id": "478092", "Score": "1", "body": "Wow this is fantastic! Thank you so much for spending the time to not only go through the code but to rewrite it. I will definitely take what you've outlined and use it to improve on subsequent projects." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-06T16:28:47.237", "Id": "243482", "ParentId": "243453", "Score": "1" } } ]
{ "AcceptedAnswerId": "243482", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-06T00:53:02.273", "Id": "243453", "Score": "2", "Tags": [ "python", "python-3.x", "game", "rock-paper-scissors" ], "Title": "Rock, Paper Scissors Game" }
243453
<p>I am a newbie and have been following a tutorial I bought on <a href="https://www.udemy.com/" rel="nofollow noreferrer">Udemy</a>. But I was told it is old and teaches bad code practices. I used this in some code from my old projects. Now I'd like to know how secure it is.</p> <h3>Posts Upload:</h3> <pre><code>&lt;?php error_reporting(-1); require 'config/connect.php'; require 'auth_login.php'; require 'includes/header.php'; // just define at the top of the script index.php $username = ''; $username = isset($_SESSION['username']) ? $_SESSION['username'] : ''; //Initializing variable $body = &quot;&quot;; //Initialization value; Examples //&quot;&quot; When you want to append stuff later //0 When you want to add numbers later //isset() $body = isset($_POST['body']) ? $_POST['body'] : ''; //empty() $body = !empty($_POST['body']) ? $_POST['body'] : ''; if(isset($_POST['bts'])) { if (empty($_POST[&quot;body&quot;])) { echo&quot;You didn't enter anything . &lt;a href= profile.php&gt;Try again&lt;/a&gt;&quot;; } else { $body = $_POST[&quot;body&quot;]; $sql = &quot;INSERT INTO posts (username, body ) VALUES ('&quot; . $username . &quot;', '&quot; . $body . &quot;')&quot;; if(mysqli_query($conn, $sql)){ header('Location: profile.php'); die(); } else{ echo &quot;&lt;br&gt;error posting . &lt;br&gt; &lt;a href= profile.php&gt;Try again&lt;/a&gt; &quot; . mysqli_error($conn); } } } ?&gt; </code></pre> <h3>Profile pic upload and fetch:</h3> <pre><code>&lt;?php $username = trim( isset($_SESSION['username']) ? $_SESSION['username'] : &quot;&quot; ); $userPic = isset($_SESSION['userPic']) ? $_SESSION['userPic'] : &quot;&quot;; $info = date('Y-m-d_H-i-s'); if(!empty($username)) { if (isset($_FILES['fileToUpload'])) { $errors= array(); $file_name = $_FILES['fileToUpload']['name']; $file_size = $_FILES['fileToUpload']['size']; $width = 1500; $height = 1500; $file_tmp = $_FILES['fileToUpload']['tmp_name']; $file_type = $_FILES['fileToUpload']['type']; $tmp = explode('.',$_FILES['fileToUpload']['name']); $file_ext=strtolower (end ($tmp)); $extensions= array(&quot;jpeg&quot;,&quot;jpg&quot;,&quot;png&quot;); if(in_array($file_ext,$extensions)=== false){ $errors[]=&quot;extension not allowed, please choose a JPEG or PNG file.&quot;; } if ($file_size &gt; 8097152) { $errors[] = 'File size must be 2 MB'; } if ($width &gt; 1500 || $height &gt; 1500) { echo&quot;File is to large&quot;; } if(empty($errors)==true) { $userPic = date('Y-m-d_H-i-s').$file_name; move_uploaded_file($file_tmp,&quot;uploads/&quot;.$userPic); $stmt = $conn-&gt;prepare(&quot;UPDATE users SET userPic=?, date_time=? WHERE username = ?&quot;); $date_time = date(&quot;Y-m-d H:i:s&quot;); $stmt-&gt;bind_param('sss', $userPic, $date_time, $username); /* execute prepared statement */ $stmt-&gt;execute(); printf(&quot;&quot;, $conn-&gt;affected_rows); /* close statement and connection */ } } } else { echo &quot;Invalid Username&quot;; } ?&gt; &lt;?php $getimg = mysqli_query($conn,&quot;SELECT userPic, date_time FROM users WHERE username='&quot;.mysqli_real_escape_string( $conn, $username ).&quot;'&quot;); $rows=mysqli_fetch_array($getimg); $img = $rows['userPic']; ?&gt; </code></pre> <h3>Posts fetch:</h3> <pre><code>&lt;?php $username = isset($_SESSION['username']) ? $_SESSION['username'] : ''; $username = trim(isset($_GET['username']) ? $_GET['username'] : $username); //Write the query $sql = &quot;SELECT * FROM posts WHERE username = '&quot; . $username. &quot;' ORDER BY post_id DESC &quot;; $result = $conn-&gt;query($sql); if ($result-&gt;num_rows &gt; 0) { // output data of each row while($row = $result-&gt;fetch_assoc()) { echo '&lt;div id=&quot;rcorners2&quot;&gt;'; echo '&lt;p id=&quot;p2&quot;&gt;' .$row['username']. '&lt;/p&gt;'; echo '&lt;p id=&quot;p4&quot;&gt;' .$row['date_time']. '&lt;/p&gt;'; echo '&lt;hr id=&quot;hr2&quot;&gt;'; echo '&lt;p id=&quot;p3&quot;&gt;' .$row['body']. '&lt;/p&gt;'; echo '&lt;div class=&quot;test&quot;&gt; &lt;a href=&quot;#&quot; class=&quot;fill-div&quot;&gt;&lt;/a&gt;&lt;/div&gt;'; echo'&lt;/div&gt;'; echo'&lt;/br&gt;'; } } else { echo '&lt;center&gt;&lt;b&gt;&lt;p style=&quot;font-size: 30px; color: #262626;&quot;&gt; Write your first post&lt;/p&gt;&lt;/b&gt;&lt;/center&gt;'; } ?&gt; </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-06T03:25:34.223", "Id": "477845", "Score": "6", "body": "Why are you developing a php5 application?!? There is no excuse for developing on deprecated versions of php. Do you actually want to allow anonymous posting? Honestly, your queries are VERY susceptible to breakage and malicious injection." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-06T13:47:40.310", "Id": "477865", "Score": "0", "body": "Yeah this project is about 3 or 4 years old. I just picked it up again to gain some understanding." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-06T15:33:39.647", "Id": "477874", "Score": "3", "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)*." } ]
[ { "body": "<p>Please read about <a href=\"https://phpdelusions.net/sql_injection\" rel=\"nofollow noreferrer\">sql injection</a>. Basically you should be using <a href=\"https://phpdelusions.net/sql_injection#prepared\" rel=\"nofollow noreferrer\">prepared statements</a> with parameters for executing SQL queries - either <a href=\"https://www.php.net/manual/en/pdo.prepare.php\" rel=\"nofollow noreferrer\"><code>PDO::prepare()</code></a> or <a href=\"https://www.php.net/manual/en/mysqli.prepare.php\" rel=\"nofollow noreferrer\"><code>mysqli_prepare()</code></a>. If that isn't enough of a clue, consider the case where <code>$_POST['body']</code> contains something like <code>body');DROP TABLE users;</code> or some variant that leads to successful <code>WHERE</code> conditions that end up dropping one or more tables. <a href=\"https://stackoverflow.com/a/60496/1575353\">This Stack Overflow post</a> also has more information. </p>\n\n<p>As <a href=\"https://codereview.stackexchange.com/questions/243457/post-submission-pic-upload-and-posts-fetch-security#comment477845_243457\">a comment</a> alludes to, the code appears to be using PHP 5 or earlier features. As of the time of writing, <a href=\"https://www.php.net/supported-versions.php\" rel=\"nofollow noreferrer\">PHP 7 has LTS for version 7.4</a>, and 5.6 or anything earlier is in End of Life support, meaning \"<em>A release that is no longer supported. Users of this release should upgrade as soon as possible, as they may be exposed to unpatched security vulnerabilities.</em>\"<sup><a href=\"https://www.php.net/supported-versions.php\" rel=\"nofollow noreferrer\">1</a></sup>. </p>\n\n<p>There are many newer features added in PHP <a href=\"https://www.php.net/manual/en/migration70.new-features.php\" rel=\"nofollow noreferrer\">7.0</a>, <a href=\"https://www.php.net/manual/en/migration71.new-functions.php\" rel=\"nofollow noreferrer\">7.1</a>, <a href=\"https://www.php.net/manual/en/migration72.new-features.php\" rel=\"nofollow noreferrer\">7.2</a>, <a href=\"https://www.php.net/manual/en/migration73.new-features.php\" rel=\"nofollow noreferrer\">7.3</a> and <a href=\"https://www.php.net/manual/en/migration74.new-features.php\" rel=\"nofollow noreferrer\">7.4</a> with things that can simplify your code like: </p>\n\n<ul>\n<li><a href=\"https://www.php.net/manual/en/migration70.new-features.php#migration70.new-features.null-coalesce-op\" rel=\"nofollow noreferrer\">the null coalescing operator</a></li>\n<li><a href=\"https://www.php.net/manual/en/migration74.new-features.php#migration74.new-features.core.null-coalescing-assignment-operator\" rel=\"nofollow noreferrer\">Null coalescing assignment operator</a></li>\n<li><a href=\"https://www.php.net/manual/en/migration54.new-features.php\" rel=\"nofollow noreferrer\">short array syntax (PHP 5.4)</a> - e.g. <code>$a = [1, 2, 3, 4];</code></li>\n</ul>\n\n<hr>\n\n<p>The nesting levels of this code isn't totally bad, but it does seem slightly off - e.g. </p>\n\n<blockquote>\n<pre><code>$body = !empty($_POST['body']) ? $_POST['body'] : '';\n\n if(isset($_POST['bts'])) {\n\n if (empty($_POST[\"body\"])) {\n echo\"You didn't enter anything . &lt;a href= profile.php&gt;Try again&lt;/a&gt;\";\n } else {\n $body = $_POST[\"body\"];\n\n $sql = \"INSERT INTO posts (username, body ) VALUES ('\" . $username . \"', '\" . $body . \"')\";\n\n if(mysqli_query($conn, $sql)){ \n</code></pre>\n</blockquote>\n\n<p>Why does it keep incrementing spaces by two characters, even if a new block level is not introduced?</p>\n\n<p>Then the closing braces are all on the same level??</p>\n\n<blockquote>\n<pre><code>} \n} \n}\n?&gt;\n</code></pre>\n</blockquote>\n\n<hr>\n\n<p>There are some excess assignment statements:</p>\n\n<blockquote>\n<pre><code>// just define at the top of the script index.php\n$username = ''; \n$username = isset($_SESSION['username']) ? $_SESSION['username'] : '';\n</code></pre>\n</blockquote>\n\n<p>The second assignment to <code>$username</code> makes the first assignment useless.</p>\n\n<blockquote>\n<pre><code>//Initializing variable\n$body = \"\"; //Initialization value; Examples\n //\"\" When you want to append stuff later\n //0 When you want to add numbers later\n//isset()\n$body = isset($_POST['body']) ? $_POST['body'] : '';\n//empty()\n$body = !empty($_POST['body']) ? $_POST['body'] : '';\n</code></pre>\n</blockquote>\n\n<p>Here the second assignment of <code>$body</code> also makes the first assignment of it superfluous. </p>\n\n<hr>\n\n<p>It appears <code>$width</code> and <code>$height</code> are set initially:</p>\n\n<blockquote>\n<pre><code>$width = 1500;\n $height = 1500;\n</code></pre>\n</blockquote>\n\n<p>And then they don’t appear to be updated. Then the following conditions never appear to have a chance at evaluating to <code>true</code>:</p>\n\n<blockquote>\n<pre><code>if ($width &gt; 1500 || $height &gt; 1500) {\n\n echo\"File is to large\";\n}\n</code></pre>\n</blockquote>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-06T06:23:09.340", "Id": "243464", "ParentId": "243457", "Score": "6" } }, { "body": "<p>Alas, an online search for 'php tutorial' returns plenty of <strong>outdated</strong> tutorials, some of which are downright <strong>dangerous</strong> (SQL injections). It's no wonder newcomers to PHP perpetuate bad code and bad practices. This kind of code does not belong in 2020, nowadays developers are expected to use <strong>development frameworks</strong> and not Notepad or some variant - <a href=\"https://laravel.com/docs/7.x/database#running-queries\" rel=\"nofollow noreferrer\">Example</a></p>\n\n<hr>\n\n<p>I think there are logical flaws in your code, for example:</p>\n\n<pre><code>$username = isset($_SESSION['username']) ? $_SESSION['username'] : '';\n</code></pre>\n\n<p>That means: if <code>$_SESSION['username']</code> is not set then <code>$username = '';</code> but you proceed with the rest of the code anyway, and therefore insert a blank username in your table ?</p>\n\n<p>If you use session variables then you have to make sure that the session is still active and in a valid state.</p>\n\n<p>This code does not look like a finished product. Yes, it is <strong>vulnerable</strong> (SQL injections). Try to hack your site using <a href=\"http://sqlmap.org/\" rel=\"nofollow noreferrer\">SQLmap</a>, even with default options it might very well be able to dump your database. Maybe upload a shell too, leading to total compromise of your server (in addition to the data leak).</p>\n\n<p>AFAIk PHP does not allow stacked queries in order to mitigate possible injections but there are still plenty of ways the code can be abused. Note that a SQL injection is not always exploitable but it is nonetheless pretty serious.</p>\n\n<p>You must stop these coding practices immediately or you will get into trouble. If you have code like this in production you need to patch it. At a minimum, use prepared queries whenever user-supplied input is involved.</p>\n\n<p>If you deliver defective code to clients you should consider your legal liability. If your code results in a data breach you might be prosecuted for failure to observe minimum security standards (in America perhaps, you can be sued for anything by anybody). Otherwise your reputation could take a hit. There is no excuse for code like that in 2020.</p>\n\n<hr>\n\n<p><strong>File uploads</strong> are also dangerous and there are quite a few ways they can be abused.\nSee for example:</p>\n\n<ul>\n<li><a href=\"https://owasp.org/www-community/vulnerabilities/Unrestricted_File_Upload\" rel=\"nofollow noreferrer\">Owasp - Unrestricted File Upload</a></li>\n</ul>\n\n<p>In your code you make no effort to <strong>sanitize</strong> the file name, that may contain stuff like: <code>../../</code> or characters that are invalid on the local (server) file system.</p>\n\n<p>There are very few checks, the most important being the check on the extension.</p>\n\n<p>The relevant lines are:</p>\n\n<pre><code>$file_name = $_FILES['fileToUpload']['name'];\n$userPic = date('Y-m-d_H-i-s').$file_name;\nmove_uploaded_file($file_tmp,\"uploads/\".$userPic);\n</code></pre>\n\n<p>I have made some tests on a Linux machine in an attempt to defeat your code and upload a PHP shell. I can for example upload names that contain a carriage return. I have tried null byte injections too but I think PHP now has built-in protection.</p>\n\n<p><strong>An old version of PHP could be vulnerable.</strong> In particular check out this bug report: <a href=\"https://bugs.php.net/bug.php?id=69207\" rel=\"nofollow noreferrer\">Sec Bug #69207 move_uploaded_file allows nulls in path</a>. This is the situation you want to avoid.</p>\n\n<p>The point is that you rely on a file name that is supplied by the user (browser) and can be manipulated using a proxy or some tool like Burp. I have not tried Unicode tricks like RTL (right to left) makers or whatever, I will leave the exercise to interested readers.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-07T16:51:13.180", "Id": "243521", "ParentId": "243457", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-06T02:47:47.590", "Id": "243457", "Score": "4", "Tags": [ "beginner", "php", "mysql", "mysqli", "php5" ], "Title": "Security of post submission, picture upload and post fetch" }
243457
<p>I'm developing a complex app with Spring Boot and MongoDB. I have a <code>Video</code> class like the following. Note: All getters setters are omitted.</p> <pre><code>class Video{ ObjectId _id; private List&lt;OReelOCategoryLGroup&gt; listOfReelIdCategoryIdAndGroups; //some other fields } public class OReelOCategoryLGroup { ObjectId reelId; ObjectId categoryId; List&lt;Group&gt; groups; } public class Group { ObjectId _id; Boolean isMandatory=false; String dueDate; } </code></pre> <p>I am receiving the following structure from the front-end.</p> <pre><code>{ "reelId":"5eda6be5b31e96f58b3a7c65", "groupId":"5eda6bed217c01319701aea0", "category":[ { "categoryId":"5eda6bf48ebcb19e031f2aa2", "videoId":["5eda6bff1230f45ae4b7e54a","5eda6c0464ba746e243a4d6d","5eda6c0eed64b31232bf1095"] }, { "categoryId":"5eda6bf48ebcb19e031f2aa2", "videoId":["5eda6c14214ca295b6473c78"] } ] } </code></pre> <p>The representation of the class is </p> <pre><code>public class OReelLCategoryOGroup { ObjectId reelId; ObjectId groupId; List&lt;OIdOVideoId&gt; category; } public class OIdOVideoId { ObjectId categoryId; List&lt;ObjectId&gt; videoId; } </code></pre> <p>I want to update <strong>OReelLCategoryOGroup</strong> to each and every <code>videoId</code> what I receive from front-end. So I coded</p> <pre><code>public String addVideoToCurrentGroupFromAnotherReel(OReelLCategoryOGroup list) { Set&lt;ObjectId&gt; notFoundIds = new HashSet&lt;&gt;(); for (OIdOVideoId cat : list.getCategory()) { for (ObjectId vId : cat.getVideoId()) { Optional&lt;Video&gt; video = videoRepository.findBy_id(vId); if (video.isPresent()) { Video v=video.get(); OReelOCategoryLGroup flat = new OReelOCategoryLGroup(); Group group = new Group(); group.set_id(list.getGroupId()); group.setIsMandatory(false); flat.setReelId(list.getReelId()); flat.setCategoryId(cat.getCategoryId()); flat.setGroups(Arrays.asList(group)); v.getListOfReelIdCategoryIdAndGroups().add(flat); save(v); } else { notFoundIds.add(vId); } } } if (notFoundIds.size() &gt; 0) { return "Few videos successfully added to group, but " + notFoundIds.toString() + " are not found in database"; } return "Videos successfully added to group"; } </code></pre> <p>Here the complicity is <span class="math-container">\$O(n^2)\$</span>. But if <code>listOfReelIdCategoryIdAndGroups</code> contains <code>reelId == list.getReelId() &amp;&amp; categoryId == cat.getCategoryId()</code> then I have to add the <strong>group</strong> to that list of groups. If I'm going to check it, there will be another loop inside the nested loop. So complexity is <span class="math-container">\$O(n^3)\$</span>. </p> <pre><code>for (OIdOVideoId cat : list.getCategory()) { for (ObjectId vId : cat.getVideoId()) { if (video.isPresent()) { for(OReelOCategoryLGroup g:v.getListOfReelIdCategoryIdAndGroups()){ if(g.getReelId()==list.getReelId() &amp;&amp; g.getCategoryId()==cat.getCategoryId()){ g.getGroups().add(group); }else{ // insert } } } } } </code></pre> <p>I feel this is inefficient. Is there any way to overcome to this problem with Java 8, Stream API? </p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-06T12:28:42.870", "Id": "477861", "Score": "1", "body": "I suggest you merge all your code blocks into one. This has two benefits ① The description is easier to read ② The code is easier to copy and improve." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-06T03:09:46.300", "Id": "243459", "Score": "1", "Tags": [ "java", "spring" ], "Title": "Flatten nested lists in Java" }
243459
<p>I have often wondered how one would deal with dynamically sized arrays in C, since the only thing close is using malloc and realloc with pointers. To find out how they work I decided that I should create a dynamic array in C.</p> <p><code>xvec.h</code></p> <pre><code>#ifndef XVEC_C_XVEC_H #define XVEC_C_XVEC_H #include &lt;stdlib.h&gt; #include &lt;string.h&gt; /*needed for increasing capacity*/ static inline size_t upper_power_of_two(size_t v) { v--; v |= v &gt;&gt; 1; v |= v &gt;&gt; 2; v |= v &gt;&gt; 4; v |= v &gt;&gt; 8; v |= v &gt;&gt; 16; //only needed for 64 bit mode if (sizeof (size_t) == 8) v |= v &gt;&gt; 32; v++; return v; } typedef struct xvec_base { size_t cap, len; } xvec_base; #define XVEC_ALEN(a) (sizeof(a) / sizeof(*a)) static inline size_t *xvec_len_ptr(void *v) { return &amp;((xvec_base *) v - 1)-&gt;len; } static inline size_t *xvec_cap_ptr(void *v) { return &amp;((xvec_base *) v - 1)-&gt;cap; } static inline size_t xvec_len(void* v) { return ((xvec_base *) v - 1)-&gt;len; } static inline size_t xvec_cap(void* v) { return ((xvec_base *) v - 1)-&gt;cap; } /* how to use * T = type * ... = items to initialize the array with */ #define xvec_new(T, ...) \ ({ \ const T __args[] = {__VA_ARGS__}; \ const size_t initial_size = 16+XVEC_ALEN(__args); \ xvec_base *_v = (xvec_base*)malloc(sizeof(xvec_base) + sizeof(T) * initial_size); \ _v-&gt;cap = initial_size; \ _v-&gt;len = XVEC_ALEN(__args); \ T* v = (T*)(_v+1); \ memcpy(v,__args,sizeof(__args)); \ v; \ }) \ /* how to use * v = container * size = the size to resize to */ #define xvec_resize(v, size) \ ({ \ const size_t _size = size; \ size_t* _len = xvec_len_ptr(v); \ size_t* _cap = xvec_cap_ptr(v); \ if(_size &gt; *_len) { \ xvec_reserve(v,_size); \ _len = xvec_len_ptr(v); \ /*clear memory after resizing*/ \ memset(v+*_len,0, (*_cap-*_len)*sizeof(*v)); \ } \ *_len = _size; \ v; \ }) #define xvec_reserve(v, size) \ ({ \ const size_t s = size; \ size_t* _cap = xvec_cap_ptr(v); \ if(s &gt; *_cap) { \ *_cap = s; \ v = (__typeof__(v))((char*)realloc((xvec_base*)v-1,sizeof(xvec_base) + sizeof(*v)*(*_cap))+sizeof(xvec_base)); \ } \ v; \ }) #define xvec_free(v) free((xvec_base*)v-1) #define xvec_pop(v) ({v[(*xvec_len_ptr(v))--];}) /*how to use * v = container * ... = items to insert */ #define xvec_push(v, ...) \ ({ \ const __typeof__(*v) __args[] = {__VA_ARGS__}; \ size_t* _len = xvec_len_ptr(v); \ size_t* _cap = xvec_cap_ptr(v); \ if(*_len + XVEC_ALEN(__args) &gt;= *_cap) { \ xvec_reserve(v,upper_power_of_two(*_len+XVEC_ALEN(__args))); \ _len = xvec_len_ptr(v); \ } \ for(size_t i = 0; i &lt; XVEC_ALEN(__args); ++i) { \ v[(*_len)++] = __args[i]; \ } \ v; \ }) /*how to use * v = container * index = where to insert * ... = items to insert */ #define xvec_insert(v, index, ...) \ ({ \ const size_t _n = index; \ const __typeof__(*v) __args[] = {__VA_ARGS__}; \ size_t* _len = xvec_len_ptr(v); \ size_t* _cap = xvec_cap_ptr(v); \ if(*_len + XVEC_ALEN(__args) &gt;= *_cap) { \ xvec_reserve(v,upper_power_of_two(*_len+XVEC_ALEN(__args))); \ _len = xvec_len_ptr(v); \ } \ memcpy(v+_n+XVEC_ALEN(__args),v+_n, \ sizeof(*v)*(*_len-_n)); \ memcpy(v+_n,&amp;__args[0], \ XVEC_ALEN(__args)*sizeof(*v)); \ *_len += XVEC_ALEN(__args); \ v; \ }) /* how to use * v = container * index = where to remove */ #define xvec_remove(v, index) \ ({ \ const size_t _index = index; \ size_t *_len = xvec_len_ptr(v); \ memcpy(v+_index,v+_index+1,sizeof(*v)*(*_len-_index)); \ (*_len)--; \ v; \ }) /* how to use * v = container * first = the first item to be removed * last = the last item to be removed */ #define xvec_remove_range(v, first, last) \ ({ \ const size_t _first = first; \ const size_t _last = last; \ const size_t _n = _last-_first+1; \ size_t *_len = xvec_len_ptr(v); \ memcpy(v+_first,v+_last+1,sizeof(*v)*(*_len-_last)); \ *_len-=_n; \ v; \ }) /* how to use * v = container */ #define xvec_copy(v) \ ({ \ __typeof__(v) new_xvec = xvec_new(typeof(v)); \ xvec_resize(new_xvec,xvec_len(v)); \ memcpy(new_xvec,v,xvec_len(v)*sizeof(*v)); \ new_xvec; \ }) #endif //XVEC_C_XVEC_H </code></pre> <p>Here is a test case:</p> <p><code>test.c</code></p> <pre><code>#include "xvec.h" #include &lt;stdio.h&gt; int main() { int *v = xvec_new(int,987654321); xvec_push(v, 1); xvec_push(v, 1); xvec_push(v, 1, 7, 8, 9, 10, 11); v[2] = 2; xvec_insert(v, 0, 12, 3, 5, 6, 7, 8, 9, 10); xvec_insert(v, 0, 1, 2, 3, 4); xvec_insert(v, 0, 1, 2, 3, 4); xvec_insert(v, 0, 1, 2, 3, 4); xvec_insert(v, 0, 1, 2, 3, 4); xvec_pop(v); xvec_insert(v, xvec_len(v), 1, 2, 3, 4); xvec_remove_range(v,xvec_len(v)-2,xvec_len(v)-1); xvec_remove(v,xvec_len(v)-2); xvec_reserve(v,70); xvec_resize(v,3453); xvec_resize(v,32); int* t= xvec_copy(v); t[31] = -1; printf("%zu\n", xvec_cap(v)); for (int i = 0; i &lt; xvec_len(v); ++i) { printf("%d\n", v[i]); } printf("%d\n",t[31]); xvec_free(v); xvec_free(t); } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-06T12:41:47.283", "Id": "477862", "Score": "0", "body": "Why does the dynamic array not shrink (reduce allocations) with `xvec_resize()`?" } ]
[ { "body": "<p>IMO this kind of error prone, hard to maintain macros should be avoided at any price.</p>\n\n<p>If I was doing it I would do something like this (assuming gcc):</p>\n\n<pre><code>typedef struct\n{\n size_t nelem;\n size_t elemsize;\n char arr[];\n}DARR_t;\n\n\n#define INLINE inline __attribute__((always_inline))\n#define arr_init(nelem,type) _arr_init(nelem, sizeof(type))\n\nstatic INLINE void *_arr_init(size_t numelements, size_t elemsize)\n{\n DARR_t *p = malloc(numelements * elemsize + sizeof(*p));\n if(p)\n {\n p -&gt; nelem = numelements;\n p -&gt; elemsize = elemsize;\n }\n return p ? p -&gt; arr : (void *)p;\n}\n\n#define arr_append(ptr, type, ...) _arr_append(ptr, &amp;(type []){__VA_ARGS__}, sizeof((type []){__VA_ARGS__})/sizeof(type))\n\nstatic INLINE void *_arr_append(void *arr, void *val, size_t size)\n{\n DARR_t *p = arr - offsetof(DARR_t, arr), *tmp;\n\n tmp = realloc(p, (p -&gt; nelem + size) * p -&gt; elemsize + sizeof(*tmp));\n if(tmp) \n {\n memcpy(&amp;tmp -&gt; arr[tmp -&gt; nelem * tmp -&gt; elemsize], val, tmp -&gt; elemsize * size);\n tmp -&gt; nelem++;\n\n }\n return tmp ? tmp -&gt; arr : (void *)tmp;\n}\n</code></pre>\n\n<p>etc, etc</p>\n\n<p>But if I want to use dynamic arrays I would rather use C++.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-06T17:53:50.920", "Id": "477893", "Score": "0", "body": "@chux-ReinstateMonica good spot - I almost never sizeof types. Why did I do it here? Even I do not know" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-06T17:56:28.307", "Id": "477895", "Score": "0", "body": "`return p ? p -> arr : (void *)p` this time you are not right. If the pointer types in conditional expression are different (except `void*`) - gcc emits the warning. To suppress it it cast is needed (or NULL) https://godbolt.org/z/oKgvDe" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-06T13:35:17.907", "Id": "243474", "ParentId": "243462", "Score": "2" } } ]
{ "AcceptedAnswerId": "243474", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-06T05:51:39.373", "Id": "243462", "Score": "3", "Tags": [ "c" ], "Title": "Made a dynamic array in C" }
243462
<blockquote> <p>Problem statement</p> <p>In simple words it say, count total Strongly connected components in the graph.</p> </blockquote> <p>All edges are undirected. I have the following code that uses <code>kosaraju</code> <code>2DFS</code> approach.</p> <pre class="lang-java prettyprint-override"><code>import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; public class AirlineProblem { private static boolean[] visited = null; private static boolean[] reverseVisited = null; private static ArrayList&lt;ArrayList&lt;Integer&gt;&gt; adj = null; private static ArrayList&lt;ArrayList&lt;Integer&gt;&gt; adjr = null; private static boolean[] indegree0 = null; public static void main(String[] args) { String[] airports = { "BGI", "CDG", "DEL", "DOH", "DSM", "EWR", "EYW", "HND", "ICN", "JFK", "LGA", "LHR", "ORD", "SAN", "SFO", "SIN", "TLV", "BUD" }; String[][] routes = { { "DSM", "ORD" }, { "ORD", "BGI" }, { "BGI", "LGA" }, { "SIN", "CDG" }, { "CDG", "SIN" }, { "CDG", "BUD" }, { "DEL", "DOH" }, { "DEL", "CDG" }, { "TLV", "DEL" }, { "EWR", "HND" }, { "HND", "ICN" }, { "HND", "JFK" }, { "ICN", "JFK" }, { "JFK", "LGA" }, { "EYW", "LHR" }, { "LHR", "SFO" }, { "SFO", "SAN" }, { "SFO", "DSM" }, { "SAN", "EYW" } }; String startingAirport = "LGA"; System.out.println(solution(airports, routes, startingAirport)); } public static int solution(String[] airports, String[][] routes, String startingAirport) { int n = airports.length; HashMap&lt;String, Integer&gt; airportsMap = new HashMap&lt;&gt;(); for (int i = 0; i &lt; n; ++i) airportsMap.put(airports[i], i); adj = new ArrayList&lt;&gt;(n); adjr = new ArrayList&lt;&gt;(n); for (int i = 0; i &lt; n; i++) { adj.add(new ArrayList&lt;Integer&gt;()); adjr.add(new ArrayList&lt;Integer&gt;()); } for (String[] route : routes) { adj.get(airportsMap.get(route[0])).add(airportsMap.get(route[1])); adjr.get(airportsMap.get(route[1])).add(airportsMap.get(route[0])); } visited = new boolean[n]; reverseVisited = new boolean[n]; indegree0 = new boolean[n]; for (int i = 0; i &lt; n; i++) if (visited[i] == false) dfs1(i); int counter = 0; for (int i = 0; i &lt; n; ++i) if (indegree0[i] == true &amp;&amp; airportsMap.get(startingAirport) != i) counter++; return counter; } private static void dfs1(int node) { visited[node] = true; boolean hasParent = false; for (int i : adjr.get(node)) if (visited[i] == false) { hasParent = true; Arrays.fill(reverseVisited, false); dfs1(i); } if (hasParent == false) { indegree0[node] = true; reverseVisited[node] = true; for (int i : adj.get(node)) if (reverseVisited[i] == false) dfs2(i); } } private static void dfs2(int node) { visited[node] = true; reverseVisited[node] = true; indegree0[node] = false; for (int i : adj.get(node)) if (reverseVisited[i] == false) dfs2(i); } } </code></pre> <p>I would like review about the efficiency, performance and programming paradigm I used. I would also be interested if some tasks can be automated by using a library.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-06T05:52:48.393", "Id": "243463", "Score": "1", "Tags": [ "java", "graph", "depth-first-search" ], "Title": "Kosaraju Algorithm in Java" }
243463
<p>I have huge number of text files, each several hundred MB in size. Unfortunately, they are not all fully standardized in any one format. Plus there is a lot of legacy in here, and a lot of junk and garbled text. I wish to check all of these files to find rows with a valid email ID, and if it exists then print it to a file named the first-char of the email ID. Hence, multiple text files get parsed and organized into files named a-z and 0-9. In case the email address starts with a special character, then it will get written into a file called "_" underscore. The script also trims the rows to remove whitespaces; and replaces single and double quotes (this is an application requirement)</p> <p>My script works fine. There are no errors or bugs in it. But it is incredibly slow. My question: <strong>is there a more efficient way to achieve this?</strong> Parsing 30 GB logs takes me about 12 hrs - way too much! Will grep/cut/sed/another be any faster?</p> <p><strong>Sample txt File</strong></p> <pre><code>!bar@foo.com,address #john@foo.com;address john@foo.com;address µÖ email1@foo.com;username;address email2@foo.com;username email3@foo.com,username;address [spaces at the start of the row] email4@foo.com|username|address [tabs at the start of the row] </code></pre> <p><strong>My Code:</strong></p> <pre><code>awk -F'[,|;: \t]+' '{ gsub(/^[ \t]+|[ \t]+$/, "") if (NF&gt;1 &amp;&amp; $1 ~ /^[[:alnum:]_.+-]+@[[:alnum:]_.-]+\.[[:alnum:]]+$/) { gsub(/"/, "DQUOTES") gsub("\047", "SQUOTES") r=gensub("[,|;: \t]+",":",1,$0) a=tolower(substr(r,1,1)) if (a ~ /^[[:alnum:]]/) print r &gt; a else print r &gt; "_" } else print $0 &gt; "ErrorFile" }' *.txt </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-06T15:56:12.433", "Id": "481256", "Score": "0", "body": "Is it necessary to keep the entire line or just the email address? Also, does case matter to you? That is, would it hurt if all characters were converted to lowercase?" } ]
[ { "body": "<p>Don't know if this is affecting your performance, but one thing to check is that you are using an up-to-date version of <code>awk</code>. In particular, the version of <code>awk</code> that ships on MacOS is very slow. You may get dramatic difference by installing the latest GNU gawk. I've measured order of magnitude performance improvements by upgrading. (On MacOS, Homebrew and MacPorts are two popular package managers that can install the latest version.)</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-06T09:46:05.407", "Id": "243469", "ParentId": "243465", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-06T06:48:42.043", "Id": "243465", "Score": "1", "Tags": [ "time-limit-exceeded", "bash", "awk" ], "Title": "Extracting emails from log files" }
243465
<p>I am trying to solve a problem where I need to find the number of bracket sequences <span class="math-container">\$p\$</span> and <span class="math-container">\$q\$</span> such that for a given bracket sequence s. I have that <span class="math-container">\$p + s + q\$</span> is a valid bracket sequence. Also <span class="math-container">\$|p+s+q| = 2n\$</span>.</p> <p>We can use dynamic programming here, i.e. let <code>dp[i][j]</code> = the number of bracket sequences (which are a prefix of a valid bracket sequence) with <span class="math-container">\$i\$</span> <code>(</code>'s and <span class="math-container">\$j\$</span> <code>)</code>'s. Also <span class="math-container">\$i\ge j\$</span>.</p> <p>Now we have </p> <p><span class="math-container">\$\displaystyle dp(i, j)= \begin{cases} 0&amp;i&lt;j\text{ or }i&lt;0\text{ or }j&lt;0\\ 1&amp;j=0\\ dp(i-1, j)+dp(i, j-1)&amp;\text{otherwise} \end{cases}\$</span></p> <p>Now let us suppose </p> <ul> <li><span class="math-container">\$p\$</span> has <span class="math-container">\$x\$</span> <code>(</code>'s and <span class="math-container">\$y\$</span> <code>)</code>'s</li> <li><span class="math-container">\$s\$</span> has <span class="math-container">\$l\$</span> <code>(</code>'s and <span class="math-container">\$r\$</span> <code>)</code>'s.</li> </ul> <p>Then we must have <span class="math-container">\$y\ge x\$</span> for <span class="math-container">\$p\$</span> to be valid, <span class="math-container">\$x+l\ge y+r\$</span> for <span class="math-container">\$p+s\$</span> to be valid and the same must hold for <span class="math-container">\$p+s_i\$</span> i.e. in any prefix <span class="math-container">\$s_i\$</span> of <span class="math-container">\$s\$</span> appended to <span class="math-container">\$p\$</span>.</p> <p>So we have <span class="math-container">\$x+l_i\ge y+r_i\$</span> or <span class="math-container">\$x-y+l_i-y_i\ge 0\$</span>. We have <span class="math-container">\$x-y+l_i-y_i\ge x-y+\min_i\{l_i-r_i\}\ge0\$</span>. So we need to have <span class="math-container">\$x+\min_i\{l_i-r_i\}\ge y\$</span></p> <p>So we can loop over all possible values of <span class="math-container">\$x,y\$</span> and see if we can find <span class="math-container">\$p,q\$</span>. Number of ways of <span class="math-container">\$p\$</span> will be <code>dp[x][y]</code>. Now if we reverse all brackets in <span class="math-container">\$p+s+q\$</span> (which is also a valid sequence), we can see that <span class="math-container">\$q\$</span> has <span class="math-container">\$n-y-r\$</span> <code>(</code>'s and <span class="math-container">\$n-x-l\$</span> <code>)</code>'s. So the number of ways of that is <code>dp[n-y-r][n-x-l]</code></p> <p>Note: I need to find the solution mod <span class="math-container">\$10^9+7\$</span>. You can find more details <a href="https://codeforces.com/contest/629/problem/C" rel="nofollow noreferrer">here</a>. </p> <p>This is the solution that I came up with. I am facing high memory usage (i)How can I improve the memory usage? (ii) Also is there a way I can make it more concise?</p> <p>The only problem could be the <span class="math-container">\$dp\$</span> which will hold <span class="math-container">\$n^2\$</span> entries of <code>Int64</code></p> <pre><code>import Data.Array import Data.Int import Data.List import Data.Function import Control.Monad main :: IO () main = do [n', m] &lt;- map read . words &lt;$&gt; getLine -- n'=2n, m=|s| s &lt;- getLine print $ solve n' s solve n' s = let n = n' `div` 2 -- number of ( or ) l = length $ filter (== '(') s r = length s - l mm = 10 ^ 9 + 7 :: Int64 arr = array ((0, 0), (n, n)) [ ((i, j), f i j) | i &lt;- [0 .. n], j &lt;- [0 .. n] ] -- the dp array f i j | j == 0 -- base case dp = 1 | j &gt; i -- invalid sequence = 0 | otherwise = let left = if i &gt; 0 then arr ! (i - 1, j) else 0 down = if j &gt; 0 then arr ! (i, j - 1) else 0 in (left + down) `mod` mm minVal = minimum $ scanl (\v c -&gt; if c == '(' then v + 1 else v - 1) 0 s -- min li - ri in (`mod` mm) . sum $ [ let leftWays = arr ! (x, y) rightWays = arr ! (n - y - r, n - x - l) in (leftWays * rightWays) `mod` mm | x &lt;- [0 .. n - l] -- x+l&lt;=n , y &lt;- [0 .. x + l - r] -- y &lt;= x, y + r &lt;= x - l , x + minVal &gt;= y -- x + min (li - ri) &gt;= y ] </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-06T18:28:04.830", "Id": "477899", "Score": "0", "body": "The n^2 entries is most likely the problem since the memory limit is 256MB and n could be as large as 100,000, meaning that you would have less than a byte for each of the n^2 entries. One solution is to only have one row of the array in memory at a time." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-07T05:42:14.207", "Id": "477943", "Score": "0", "body": "@Li-yaoXia I noticed that \\$(n-\\min \\{l, r\\})^2\\$ array also suffices for this problem" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-06T07:19:18.370", "Id": "243466", "Score": "2", "Tags": [ "programming-challenge", "haskell" ], "Title": "Finding number of brackets sequences of length n containing a specific string s" }
243466
<p>I came across this question on Leetcode. The question description is as follows:</p> <blockquote> <p>There are several cards arranged in a row, and each card has an associated number of points. The points are given in the integer array cardPoints. In one step, you can take one card from the beginning or from the end of the row. You have to take exactly k cards. Your score is the sum of the points of the cards you have taken.</p> <p>Return the maximum score you can obtain.</p> <p>Sample testcases</p> <pre><code>cardPoints = [1,2,3,4,5,6,1], k = 3 =&gt; Output is 12 cardPoints = [2,2,2], k = 2 =&gt; Output is 4 cardPoints = [9,7,7,9,7,7,9], k = 7 =&gt; Output is 55 cardPoints = [1,1000,1], k = 1 =&gt; Output is 1 </code></pre> </blockquote> <p>After looking at the discussion forums, I realized that this could be converted into a sliding window problem where we have to find the <code>smallest subarray sum of length len(cardPoints) - k</code>. While I do understand this, The initial method I tried was brute-force recursive and using dynamic programming to cache intermediate results. Despite this, it still results in a timeout. Is there any other optimization I can make to make my code run faster using this approach?</p> <pre><code>class Solution { public: int maxScoreUtil(int left, int right,vector&lt;int&gt;&amp; cardPoints, int k,vector&lt;vector&lt;int&gt;&gt;&amp; dp){ if(k == 0 || left == cardPoints.size() || right &lt; 0) return 0; if(dp[left][right] != -1) return dp[left][right]; int val_1 = maxScoreUtil(left+1,right,cardPoints,k-1,dp) + cardPoints[left]; int val_2 = maxScoreUtil(left,right-1,cardPoints,k-1,dp) + cardPoints[right]; return dp[left][right] = max(val_1,val_2); } int maxScore(vector&lt;int&gt;&amp; cardPoints, int k) { int n = cardPoints.size(); vector&lt;vector&lt;int&gt;&gt; dp(n+1, vector&lt;int&gt;(n+1, -1)); return maxScoreUtil(0,n-1,cardPoints,k,dp); } };I </code></pre> <p>Before using DP =&gt; 16/40 test cases passed followed by TLE<br /> After using DP =&gt; 31/40 test cases passed followed by TLE</p>
[]
[ { "body": "<p>You recursive solution takes numbers from <code>[0..left]</code> and <code>[right..n-1]</code> where <code>(left+1)+(n-right) &lt;= k</code> So even if there are k ways to select some elements from left and others from right, i.e. <code>(0,k), (1,k-1), ... (k,0)</code>. You look at far more a bigger sample space, in worst case, it would be <span class=\"math-container\">\\$O(n^2)\\$</span>. I don't think much can be done with this approach.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-06T09:47:50.310", "Id": "243470", "ParentId": "243467", "Score": "2" } }, { "body": "<p>RE60K has already critiqued your algorithm, so I'll just leave some minor comments on the code style. These comments won't help you beat the time limit, but they are good habits to get into if you're going to take a coding interview someday, for example.</p>\n\n<p>Your <code>class Solution</code> has only public members. Classes with all public members are frequently defined as <code>struct</code>s instead.</p>\n\n<p>In fact, your class has no data members! Classes with no data members should probably just be free functions. See <a href=\"https://quuxplusone.github.io/blog/2020/05/28/oo-antipattern/\" rel=\"nofollow noreferrer\">The \"OO\" Antipattern</a>.</p>\n\n<p>Alternatively, you could keep the class as a sort of \"namespace\" for these two functions, but mark both functions <code>static</code>, so that you don't waste CPU cycles passing around a <code>this</code> pointer that you'll never use. In this case, you should also mark <code>maxScoreUtil</code> as <code>private</code> because it should never be called by anyone outside the class itself.</p>\n\n<p><em>Alternatively</em>, notice that your current code is paying for a <code>this</code> pointer <em>and also</em> paying to pass <code>dp</code> as the last argument to <code>maxScoreUtil</code>! It should only ever pay for one or the other. If <code>dp</code> always points to the same vector, maybe <code>dp</code> should be a data member of <code>class Solution</code>.</p>\n\n<p>In all of these cases, the elements of <code>cardPoints</code> are not intended to be modified, so you should mark that parameter as <code>const</code>.</p>\n\n<p>To summarize: Right now your code's skeleton is</p>\n\n<pre><code>class Solution {\npublic:\n int maxScoreUtil(int left, int right,vector&lt;int&gt;&amp; cardPoints, int k,vector&lt;vector&lt;int&gt;&gt;&amp; dp);\n int maxScore(vector&lt;int&gt;&amp; cardPoints, int k);\n};\n</code></pre>\n\n<p>but it should probably be either</p>\n\n<pre><code>class Solution {\n static int maxScoreImpl(int left, int right, const vector&lt;int&gt;&amp; cardPoints, int k, vector&lt;vector&lt;int&gt;&gt;&amp; dp);\npublic:\n static int maxScore(const vector&lt;int&gt;&amp; cardPoints, int k);\n};\n</code></pre>\n\n<p>or</p>\n\n<pre><code>static int maxScoreImpl(int left, int right, const vector&lt;int&gt;&amp; cardPoints, int k, vector&lt;vector&lt;int&gt;&gt;&amp; dp);\nint maxScore(const vector&lt;int&gt;&amp; cardPoints, int k);\n</code></pre>\n\n<p>or arguably</p>\n\n<pre><code>class Solution {\n vector&lt;vector&lt;int&gt;&gt; dp;\n vector&lt;int&gt; cardPoints;\n int maxScoreImpl(int left, int right, int k);\npublic:\n static int maxScore(vector&lt;int&gt; cardPoints, int k) {\n int n = cardPoints.size();\n Solution s{ vector&lt;vector&lt;int&gt;&gt;(n+1, vector&lt;int&gt;(n+1, -1)), std::move(cardPoints) };\n return s.maxScoreImpl(0, n-1, k);\n }\n};\n</code></pre>\n\n<hr>\n\n<p>Notice that I've quietly changed your <code>maxScoreUtil</code> to <code>maxScoreImpl</code> (for \"implementation\"); that's the usual convention for an internal implementation function. \"Util\" (for \"utilities\") is more often used as a namespace or class name for <em>general-purpose</em> utility functions.</p>\n\n<hr>\n\n<pre><code> if(k == 0 || left == cardPoints.size() || right &lt; 0)\n return 0;\n</code></pre>\n\n<p>Surely this should say <code>... || right &lt; left</code>. Also, here and on the next line, you should get in the habit of curly-bracing any time you indent. It'll save you a lot of debugging someday. Consider the difference between</p>\n\n<pre><code>if (failed) {\n puts(\"oops, exiting\");\n exit(0);\n}\n</code></pre>\n\n<p>and</p>\n\n<pre><code>if (failed)\n puts(\"oops, exiting\");\n exit(0);\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-07T04:28:49.803", "Id": "477941", "Score": "0", "body": "Thanks a lot for the comments, will definitely keep them in mind!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-06T14:06:26.277", "Id": "243477", "ParentId": "243467", "Score": "3" } } ]
{ "AcceptedAnswerId": "243470", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-06T07:29:01.590", "Id": "243467", "Score": "1", "Tags": [ "c++", "programming-challenge", "recursion", "time-limit-exceeded", "dynamic-programming" ], "Title": "Recursive brute-force approach to maximum points you can obtain from cards" }
243467
<p>I have implemented directed graph and Dijkstra algorithm using heap in Python.</p> <p>I first implemented an abstract base class <code>WeightedGraph</code>, of which <code>DirectedGraph</code> is a subclass. The <code>DirectedGraph</code> uses an adjacency map as its internal representation. I then implemented the method <code>single_source_shortest_paths</code>, which uses the Dijkstra algorithm, which in turn uses a <code>HeapQueue</code> that I implemented in another module <code>heap_queue</code>.</p> <p>Before going to the codes, let's look at an example.</p> <p><strong>An Example</strong></p> <p>We can add nodes and edges as usual. When adding an edge, if any node in the edge does not already exist, that node is automatically added.</p> <pre><code>&gt;&gt;&gt; g = DirectedGraph() &gt;&gt;&gt; g.add_node(0) &gt;&gt;&gt; g.add_node(1) &gt;&gt;&gt; g.add_node(2) &gt;&gt;&gt; &gt;&gt;&gt; g.add_edge(start=0, end=1, weight=3) &gt;&gt;&gt; g.add_edge(start=1, end=2, weight=2) &gt;&gt;&gt; g.add_edge(start=3, end=4, weight=3) &gt;&gt;&gt; g.add_edge(start=4, end=3, weight=2) &gt;&gt;&gt; g.add_edge(start=0, end=3, weight=1) &gt;&gt;&gt; g.add_edge(start=3, end=1, weight=1) &gt;&gt;&gt; g.add_edge(start=2, end=4, weight=1) </code></pre> <p>In the above, when adding the edge <code>(3, 4)</code>, the nodes <code>3</code> and <code>4</code> are automatically added. The graph <code>g</code> now looks like this:</p> <p><a href="https://i.stack.imgur.com/s9pDv.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/s9pDv.png" alt="enter image description here"></a></p> <p>We can list out all the nodes, edges and out-neighbors of a given node. Each edge is represented as a <code>namedtuple</code>.</p> <pre><code>&gt;&gt;&gt; list(g.nodes) [0, 1, 2, 4, 3] &gt;&gt;&gt; &gt;&gt;&gt; for edge in g.edges: ... print(edge) DirectedEdge(start=0, end=1, weight=3) DirectedEdge(start=0, end=3, weight=1) DirectedEdge(start=1, end=2, weight=2) DirectedEdge(start=2, end=4, weight=1) DirectedEdge(start=4, end=3, weight=2) DirectedEdge(start=3, end=4, weight=3) DirectedEdge(start=3, end=1, weight=1) &gt;&gt;&gt; &gt;&gt;&gt; for neighbor, weight in g.neighbors(3): ... print(f'neighbor={neighbor}, weight={weight}') neighbor=4, weight=3 neighbor=1, weight=1 </code></pre> <p>Now comes the meat, the <code>single_source_shortest_paths</code> method, which finds the shortest paths to multiple targets from a single source. It returns a dictionary whose keys are the given targets and values are the corresponding shortest paths.</p> <pre><code>&gt;&gt;&gt; g.single_source_shortest_paths(start=0, targets=range(5)) {0: [0], 1: [0, 3, 1], 2: [0, 3, 1, 2], 3: [0, 3], 4: [0, 3, 4]} </code></pre> <p>If any target is unreachable, its path is simply an empty list.</p> <pre><code>&gt;&gt;&gt; g.single_source_shortest_paths(start=4, targets=[0, 2]) {0: [], 2: [4, 3, 1, 2]} </code></pre> <p><strong>The Code</strong></p> <p>The code of <code>WeightedGraph</code> and <code>DirectedGraph</code> is as follow:</p> <pre><code>import abc from collections import namedtuple from heap_queue import HeapQueue DirectedEdge = namedtuple('DirectedEdge', 'start end weight') INF = float('inf') class WeightedGraph(abc.ABC): """An abstract base class for a weighted graph.""" @abc.abstractmethod def add_node(self, label): """Add a node with the given label. No effect if a node with the given label already exists. """ @abc.abstractmethod def add_edge(self, start, end, weight): """Add an edge from start to end with the given weight. Add the nodes automatically if not already exist. Overwrite the weight if the edge already exists. """ @abc.abstractmethod def remove_node(self, label): """Remove the node with the given label. Remove all edges at the node automatically. Raise a ValueError if the node does not exist. """ @abc.abstractmethod def remove_edge(self, start, end): """Remove the edge from start to end. Raise a ValueError if the edge does not exist """ @property @abc.abstractmethod def nodes(self): """Return an iterator over all nodes.""" @property @abc.abstractmethod def edges(self): """Return an iterator over all edges.""" @property @abc.abstractmethod def node_count(self): """Return the number of nodes.""" @property @abc.abstractmethod def edge_count(self): """Return the number of edges.""" @abc.abstractmethod def neighbors(self, label): """Return an iterator, in which each item is an (neighbor, weight) pair, where neighbor is an out-neighbor of the node with the given label and weight is the weight of the corresponding edge. Raise a ValueError if the node does not exist. """ @abc.abstractmethod def degree(self, label): """Return the (out-)degree of the node with the given label. Raise a ValueError if the node does not exist. """ @abc.abstractmethod def weight(self, start, end): """Return the weight of the edge from start to end. Raise a ValueError if the edge does not exist. """ class DirectedGraph(WeightedGraph): """Implement a directed weighted graph using adjacency map.""" def __init__(self): """Initialize the graph with an adjacency map.""" self._adjacency = {} def add_node(self, label): # if no such node, initialize the corresponding neighbour dict self._adjacency.setdefault(label, {}) def add_edge(self, start, end, weight): self._adjacency.setdefault(end, {}) # extract the neighbour dict of start and set weight nbr_dict = self._adjacency.setdefault(start, {}) nbr_dict[end] = weight def remove_node(self, label): if label not in self._adjacency: raise ValueError(f'no node {label}') else: del self._adjacency[label] # delete all edges whose end node is the given node for _, nbr_dict in self._adjacency.items(): nbr_dict.pop(label, None) def remove_edge(self, start, end): try: del self._adjacency[start][end] # Two cases result in a KeyError # Case 1: start node does not exist, or # Case 2: start node exists but no edge from it to the end node except KeyError: raise ValueError(f'no edge from {start} to {end}') @property def nodes(self): yield from self._adjacency @property def edges(self): """Iterate over all edges. Each edge is represented as a namedtuple of the form DirectedEdge(start, end, weight). """ for start, nbr_dict in self._adjacency.items(): for end, weight in nbr_dict.items(): yield DirectedEdge(start, end, weight) @property def node_count(self): return len(self._adjacency) @property def edge_count(self): return sum(len(nbr_dict) for nbr_dict in self._adjacency.values()) def neighbors(self, label): if label not in self._adjacency: raise ValueError(f'no node {label}') # return iter instead of yield from, otherwise ValueError is never # raised upon the initialization of the generator else: nbr_dict = self._adjacency[label] return iter(nbr_dict.items()) def degree(self, label): if label not in self._adjacency: raise ValueError(f'no node {label}') else: return len(self._adjacency[label]) def weight(self, start, end): try: return self._adjacency[start][end] # similar to remove_edge, two cases result in a KeyError except KeyError: raise ValueError(f'no edge from {start} to {end}') def single_source_shortest_paths(self, start, targets): """Find the shortest paths to multiple targets from a single source. Return a dictionary whose keys are the given targets and values are the corresponding shortest paths. """ targets = list(targets) # check all nodes exist if start not in self._adjacency: raise ValueError(f'no node {start}') for target in targets: if target not in self._adjacency: raise ValueError(f'no node {target}') # use dijkstra to obtain the shortest-path tree, which # is then used to construct a path for each target result = {} came_from = self._dijkstra(start, targets) for target in targets: if target not in came_from: # no path from start to target path = [] else: path = DirectedGraph._construct_path(came_from, target) result[target] = path return result def _dijkstra(self, start, targets): """A helper method that implements the Dijkstra algorithm. Return the shortest-path tree represented as a dict came_from. """ came_from = {start: None} targets = set(targets) # initialize the cost of every node to be infinity, except the start frontier = HeapQueue((node, INF) for node in self.nodes) frontier.push(start, 0) while targets: # node popped from the queue already has its shortest path found, # can be safely discarded cur_node, cur_cost = frontier.pop() targets.discard(cur_node) for nxt_node, weight in self.neighbors(cur_node): # only relax the nodes to which shortest paths are not yet found if nxt_node in frontier: nxt_cost = cur_cost + weight # if new cost less than the current cost, update it if nxt_cost &lt; frontier[nxt_node]: frontier.push(nxt_node, nxt_cost) came_from[nxt_node] = cur_node return came_from @staticmethod def _construct_path(came_from, target): """Given the shortest-path tree came_from, find the path from start to the given target. """ cur_node = target path = [] # backtrack from target until hitting the beginning while cur_node is not None: path.append(cur_node) cur_node = came_from[cur_node] # the path is in the reversed order path.reverse() return path </code></pre> <p>In the module <code>heap_queue</code>, the code of <code>HeapQueue</code> is as follow:</p> <pre><code>class HeapQueue: """Implement a priority queue in the form of a min-heap. Each entry is an (item, key) pair. Item with a lower key has a higher priority. Item must be hashable and unique. No duplicate items. Pushing an existing item would update its key instead. """ def __init__(self, entries=None): """ :argument: entries (iterable of tuples): an iterable of (item, key) pairs """ if entries is None: self._entries = [] self._indices = {} else: self._entries = list(entries) self._indices = {item: idx for idx, (item, _) in enumerate(self._entries)} self._heapify() def _heapify(self): """Enforce the heap properties upon initializing the heap.""" start = len(self) // 2 - 1 for idx in range(start, -1, -1): self._down(idx) def __contains__(self, item): """Return True if the item is in the heap.""" return item in self._indices def __len__(self): """Number of entries remaining in the heap.""" return len(self._entries) def __iter__(self): """Iterate over all items.""" for item, _ in self._entries: yield item """Helper methods""" def _swap(self, idx1, idx2): """Swap two entries.""" item1, _ = self._entries[idx1] item2, _ = self._entries[idx2] self._indices[item1] = idx2 self._indices[item2] = idx1 self._entries[idx1], self._entries[idx2] = self._entries[idx2], self._entries[idx1] def _up(self, idx): """Bring a violating entry up to its correct position recursively.""" if idx == 0: return parent = (idx - 1) // 2 # compare key with the parent if self._entries[idx][1] &lt; self._entries[parent][1]: self._swap(idx, parent) self._up(parent) def _smaller_child(self, idx): """Find the child with smaller key. If no child, return None.""" left = 2 * idx + 1 # case 1: no child if left &gt;= len(self): return None right = left + 1 # case 2: only left child if right == len(self): return left # case 3: two children if self._entries[left][1] &lt; self._entries[right][1]: return left else: return right def _down(self, idx): """Bring a violating entry down to its correct position recursively.""" child = self._smaller_child(idx) if child is None: return # compare key with the child with smaller key if self._entries[idx][1] &gt; self._entries[child][1]: self._swap(idx, child) self._down(child) """Priority queue operations""" def __getitem__(self, item): """Return the key of an item. If the item does not exist, raise a KeyError.""" if item not in self._indices: raise KeyError(f"{item} not found") idx = self._indices[item] _, key = self._entries[idx] return key def peek(self): """Return the item with the minimum key.""" item, _ = self._entries[0] return item def push(self, item, key): """Push an item into the heap with a given key. If the item already exists, update its key instead. """ if item not in self._indices: # insert the new item to the end and bring it up to the correct position idx = len(self) self._entries.append((item, key)) self._indices[item] = idx self._up(idx) else: # the item already exists, find its index and update its key idx = self._indices[item] item, old_key = self._entries[idx] self._entries[idx] = (item, key) # bring the entry to the correct position if key &lt; old_key: self._up(idx) if key &gt; old_key: self._down(idx) def pop(self): """Remove the item with the minimum key. The resulting (item, key) pair is also returned.""" # after swapping the first and the last entry, # the required entry goes from the beginning to the end self._swap(0, len(self) - 1) item, key = self._entries.pop() del self._indices[item] self._down(0) return item, key </code></pre> <p>What improvement can I make on my code? Any advice is appreciated. Thank you.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-06T09:42:58.367", "Id": "477852", "Score": "0", "body": "We'll, first of all, in the `__init__` method of `HeapQueue` you can set the default value of the `entries` parameter to `[]` instead of `None`, and then get rid of the `if else`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-06T10:19:22.610", "Id": "477855", "Score": "3", "body": "I thought we should never use mutable default arguments?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-06T10:31:06.700", "Id": "477859", "Score": "0", "body": "Oh I guess you are right, then" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-06T08:07:40.843", "Id": "243468", "Score": "1", "Tags": [ "python", "algorithm", "python-3.x", "graph", "pathfinding" ], "Title": "Directed graph and Dijkstra algorithm using heap" }
243468
<p>I am new to coding and need help with a code that won't complete. I suspect it is due to the size of the data set. I tested the code using a reduced data set and it processes fine. However, my actual data set is over 210,000 rows and is expected to grow. Is there a way to speed this up? Thank you for your assistance</p> <pre><code>Sub DupValidation() Dim wb As Workbook Dim ws1 As Worksheet Dim i As Long Dim lastrow As Long Dim lastrow2 As Long Set wb = ActiveWorkbook Set ws1 = wb.Worksheets("Tickets") lastrow = ws1.Cells(Rows.Count, 1).End(xlUp).Row ws1.Range("g2:g" &amp; lastrow).ClearContents i = 2 Do While i &lt;= lastrow If Application.CountIf(ws1.Range(ws1.Cells(2, 2), ws1.Cells(lastrow, 2)), ws1.Cells(i, 2)) &gt; 1 Then ws1.Cells(i, 7).Value = True End If i = i + 1 Loop End Sub </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-06T12:48:46.100", "Id": "477863", "Score": "2", "body": "What does your code do? I've read your title and description but other than your code being slow I'm left in the dark. Please [edit] your title and question to explain this." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-06T15:23:08.627", "Id": "477873", "Score": "0", "body": "Wouldn't a \"Highlight Duplicates\" conditional formatting rule work better for this? Or is the `True` value used for something afterwards?" } ]
[ { "body": "<p><code>CountIf</code> iterates through 210000 rows every time and you call it 210000 times. That's 44100000000 iterations.</p>\n\n<p>You'll need to find a better algorithm to compute what you want, ideally iterating only a constant amount of times over each row.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-06T10:13:53.387", "Id": "243472", "ParentId": "243471", "Score": "1" } }, { "body": "<p>Finding (and removing) duplicates is already a built-in functionality; this code is kind of reinventing the wheel. Making VBA code faster than native functionality, from what I've seen, requires thinking outside the box and manipulating memory locations.</p>\n\n<p>But let's review the code we're looking at.</p>\n\n<blockquote>\n<pre><code>Sub DupValidation()\n</code></pre>\n</blockquote>\n\n<p>Kudos for using a meaningful name! This one reads like a <em>noun</em> though; since <code>Sub</code> procedures typically <em>do something</em>, it's common practice to make their names start with a <em>verb</em>, so <code>ValidateDuplicates</code> would be a better name. The procedure is also <em>implicitly</em> <code>Public</code>; <a href=\"https://rubberduckvba.com/Features/FeatureItem/ImplicitPublicMember\" rel=\"nofollow noreferrer\">consider always using explicit modifiers</a>.</p>\n\n<p>Next we have a handful of declarations, for each of the variables used in the procedure. Again, kudos for explicitly declaring all variables (is <code>Option Explicit</code> specified?) - but consider declaring them when they're needed, as they're needed. That way it's much harder to accidentally leave <a href=\"https://rubberduckvba.com/Features/FeatureItem/VariableNotUsed\" rel=\"nofollow noreferrer\">unused variables</a> behind, like what happened to <code>lastrow2</code>.</p>\n\n<p>Rule of thumb, if there's a digit at the end of a name, it's <em>usually</em> a bad name. <code>ws1</code> could be <code>sheet</code>, or <code>ticketsSheet</code>.</p>\n\n<p>But you're not here to hear about variable naming are you.</p>\n\n<p>I'm curious why <code>Range(\"g2:g\" &amp; lastrow)</code> is good enough to get a range encompassing all cells in column G, but once inside the loop we switch to a very long-winded <code>Range(Cells, Cells)</code> call instead of just doing <code>Range(\"B2:B\" &amp; lastrow)</code> like we just did.</p>\n\n<p>Do we really need to <code>COUNTIF</code> to identify a 2nd or 3rd (or 250th) duplicate for one value?</p>\n\n<p>If we had a data structure we could quickly lookup a value from, we could put the known-dupe value in it, and then only perform the expensive <code>COUNTIF</code> when we already know we're not looking at a known duplicate value. <code>Dictionary</code> and its O(1) keyed retrieval sounds like a good tool for this.</p>\n\n<p>So instead of just writing <code>True</code> into column G, we can store the value of column B into our dictionary, and then the loop can now conditionally evaluate the countif when the dictionary doesn't already contain the value in column B.</p>\n\n<p>Actually, with a dictionary you could make the whole loop much more efficient than that.</p>\n\n<p>Start at row 2, end at lastrow: the number of iterations is known before we even start looping - the loop should be a <code>For</code> loop, not <code>Do While</code>. So we loop <code>i</code> from 2 to N, and at each row we try to add the value of column B into the dictionary. If the value already exists in there (that's O(1); CountIf is O(n)), then we know we have a dupe at that row so we write <code>True</code> to column G. After the loop, column G identifies all dupes, and the dictionary contains all the unique values. Iterating a variant array of values in-memory instead of worksheet cells would be even faster. You'll find the <code>Dictionary</code> class in the <code>Scripting</code> library if you want it early-bound.</p>\n\n<p>But then again, I doubt it would be faster than the native <em>highlight duplicates</em> functionality.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-06T16:49:01.107", "Id": "477880", "Score": "1", "body": "The second algorithm with the dictionary does not do the same as the original algorithm; it does not mark the first occurrence of the value occurring multiple times. To do that, the value saved in the dictionary should be whether the value is known to be a dupe. Then this can be used to fill column G on a second pass over column B." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-06T16:53:21.287", "Id": "477881", "Score": "0", "body": "@M.Doerner ha, good point! O(2n) is still O(n) though, so that 2-pass sweep should still perform quite decently (obviously the greater n, the more time is takes, but now it's linear not exponential)." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-06T16:01:02.187", "Id": "243480", "ParentId": "243471", "Score": "2" } }, { "body": "<p>Indeed iterating through all the rows is slowing down your code. But what about letting Excel do the work for you by using a formula?</p>\n\n<p>This is what I suggest:</p>\n\n<pre><code>Sub DupValidation()\nDim wb As Workbook\nDim ws1 As Worksheet\n\nDim i As Long\nDim lastrow As Long\nDim lastrow2 As Long\n\nSet wb = ActiveWorkbook\nSet ws1 = wb.Worksheets(\"Tickets\")\n\nlastrow = ws1.Cells(Rows.Count, 1).End(xlUp).Row\n\n\nWith ws1.Range(\"g2:g\" &amp; lastrow)\n .ClearContents\n .FormulaR1C1 = \"=IF(COUNTIF(R2C2:RC[-5],RC[-5])&gt;2,TRUE,\"\"\"\")\"\n .FormulaR1C1 = .Value2 ' To get rid off the formula\nEnd With\nEnd Sub\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-06T16:57:11.973", "Id": "243485", "ParentId": "243471", "Score": "0" } }, { "body": "<p>An implementation of <a href=\"https://codereview.stackexchange.com/a/243480/219620\">Mathieu Guindon's response</a> using a dictionary would look something like the below. Note that for the below to work, you need to add the <code>Microsoft Scripting Runtime</code> Reference.</p>\n \n<pre class=\"lang-vb prettyprint-override\"><code>Sub DupValidation()\n Dim wb As Workbook\n Dim ws1 As Worksheet\n\n Dim i As Long\n Dim lastrow As Long\n Dim lastrow2 As Long\n\n Set wb = ActiveWorkbook\n Set ws1 = wb.Worksheets(&quot;Tickets&quot;)\n\n lastrow = ws1.Cells(Rows.Count, 1).End(xlUp).Row\n\n ws1.Range(&quot;g2:g&quot; &amp; lastrow).ClearContents\n \n' i = 2\n' Do While i &lt;= lastrow\n' If Application.CountIf(ws1.Range(ws1.Cells(2, 2), ws1.Cells(lastrow, 2)), ws1.Cells(i, 2)) &gt; 1 Then\n' ws1.Cells(i, 7).Value = True\n' End If\n' i = i + 1\n' Loop\n \n \n Dim dict As New Scripting.Dictionary\n \n For i = 2 To lastrow\n If dict.Exists(ws1.Cells(i, 2)) Then\n ws1.Cells(i, 7).Value = True\n Else\n dict.Add (ws1.Cells(i, 2))\n End If\n Next i\n \nEnd Sub\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-12T14:41:30.087", "Id": "243772", "ParentId": "243471", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-06T09:54:07.150", "Id": "243471", "Score": "1", "Tags": [ "beginner", "vba", "excel" ], "Title": "Excel VBA optimizing for large data base" }
243471
<p>As part of the task, it is allowed to use slightly outdated data. It is required that only one thread per key is involved in the critical section, while the remaining threads use data from the cache despite the expired TTL. The following code is an attempt to write a function calling the delegate within a blocking section based on <a href="https://docs.microsoft.com/en-us/dotnet/api/system.threading.semaphoreslim?view=netcore-3.1" rel="nofollow noreferrer">SemaphoreSlim</a>:</p> <pre><code>/// &lt;summary&gt; /// Ensures consistency and /// avoid extra requests to /// datastore. /// &lt;/summary&gt; /// /// &lt;exception cref="ArgumentNullException"/&gt; /// &lt;exception cref="ObjectDisposedException"/&gt; /// &lt;exception cref="OperationCanceledException"/&gt; protected virtual (bool err, T val) AsCriticalLocal&lt;T&gt;(string k, string region, Func&lt;(bool err, ICacheWrapper&lt;T&gt; val)&gt; preCheck, Func&lt;(bool err, T val)&gt; method, CancellationToken token) { k = HelperIO(k, region); /* * Since this is a local cache, it * checks for the presence of data * in it. */ (bool err, ICacheWrapper&lt;T&gt; val) preCheckRes = preCheck(); SemaphoreSlim semaphore = Lock.GetOrAdd(k, f =&gt; new SemaphoreSlim (1, 1)); int m_currentCount = semaphore.CurrentCount; // Means that the value has not been removed from the cache. if (!preCheckRes.err) { // Call Wait will be blocking. if (m_currentCount == 0) { // The update is already running, so don't care about TTL. return (preCheckRes.err, preCheckRes.val.Val); } else { // The update has not been started and the data is still relevant. if (!preCheckRes.val.IsExpired) { return (preCheckRes.err, preCheckRes.val.Val); } } } (bool err, T val) output = default; try { Logger.Debug($"Cache: { Name }. Key: { k }. Lock: BLOCKED. Date: { DateTime.Now }. Type: { typeof(T) }"); semaphore.Wait(GlobalTimeout, token); preCheckRes = preCheck(); // Means that the value has not been removed from the cache. if (!preCheckRes.err) { /* * If the semaphore is involved after * updating the data in the cache and * until the TTL expires */ if (!preCheckRes.val.IsExpired) { return (preCheckRes.err, preCheckRes.val.Val); } } output = method(); } catch (Exception exception) { Logger.Error(exception); throw; } finally { if (output.err) { /* * Remove data from the cache in order to avoid * the use of outdated data since an exception * was thrown in the update section. */ preCheckRes = preCheck(); if (!preCheckRes.err) { if (preCheckRes.val.IsExpired) { Instance.Remove(HelperIO(k, region)); } } } semaphore.Release(); Logger.Debug($"Cache: { Name }. Key: { k }. Lock: RELEASED. Date: { DateTime.Now }. Type: { typeof(T) }"); } return output; } </code></pre> <hr> <p>Сhecks that there is data in the cache and the semaphore is already used to block when executing the delegate returning data from the datastore (database, etc). If the update is not started and the data is still relevant, immediately returns it:</p> <pre><code>int m_currentCount = semaphore.CurrentCount; // Means that the value has not been removed from the cache. if (!preCheckRes.err) { // Call Wait will be blocking. if (m_currentCount == 0) { // The update is already running, so don't care about TTL. return (preCheckRes.err, preCheckRes.val.Val); } else { // The update has not been started and the data is still relevant. if (!preCheckRes.val.IsExpired) { return (preCheckRes.err, preCheckRes.val.Val); } } } </code></pre> <hr> <p>If the method was not returned in the previous two paragraphs, then the <a href="https://docs.microsoft.com/en-us/dotnet/api/system.threading.semaphoreslim.wait?view=netcore-3.1#System_Threading_SemaphoreSlim_Wait_System_Int32_System_Threading_CancellationToken_" rel="nofollow noreferrer">Wait</a> method is called and the data is extracted from cache and verified again: if the data is not removed and the data is still relevant, immediately returns it. If none of the above is done, then the delegate is called, inside which the query to the datastore is executed:</p> <pre><code>semaphore.Wait(GlobalTimeout, token); preCheckRes = preCheck(); // Means that the value has not been removed from the cache. if (!preCheckRes.err) { /* * If the semaphore is involved after * updating the data in the cache and * until the TTL expires */ if (!preCheckRes.val.IsExpired) { return (preCheckRes.err, preCheckRes.val.Val); } } output = method(); </code></pre> <hr> <p>If an error occurs during operation, the data will be deleted from the cache to avoid the use of non-updated data:</p> <pre><code>finally { if (output.err) { /* * Remove data from the cache in order to avoid * the use of outdated data since an exception * was thrown in the update section. */ preCheckRes = preCheck(); if (!preCheckRes.err) { if (preCheckRes.val.IsExpired) { Instance.Remove(HelperIO(k, region)); } } } semaphore.Release(); Logger.Debug($"Cache: { Name }. Key: { k }. Lock: RELEASED. Date: { DateTime.Now }. Type: { typeof(T) }"); } </code></pre> <hr> <p><strong>UPD</strong>:</p> <p><code>preCheck</code> is a simple delegate that calls the <code>Get</code> method internally and retrieves the data from the <a href="https://docs.microsoft.com/en-us/dotnet/api/system.runtime.caching.memorycache?view=dotnet-plat-ext-3.1" rel="nofollow noreferrer">MemoryCache</a> and returns a tuple of the form <code>(bool err, T val)</code>:</p> <pre><code>{ return AsCriticalLocal(k, region, () =&gt; { ICacheWrapper&lt;T&gt; item = Get&lt;T&gt;(k, region); return (Common.IsDefault(item), item); }, () =&gt; { T val = method(); return Set(k, TTL, val, true, region); }, token); } </code></pre> <hr> <p><strong>Questions</strong>:</p> <ol> <li>Will this code be thread safe?</li> <li>Is the described goal achieved?</li> <li>What changes are worth making in terms of code structure?</li> <li>Assuming that this code works as expected, is there any point in duplicating the code where the asynchronous version of <a href="https://docs.microsoft.com/en-us/dotnet/api/system.threading.semaphoreslim.wait?view=netcore-3.1#System_Threading_SemaphoreSlim_Wait_System_Int32_System_Threading_CancellationToken_" rel="nofollow noreferrer">Wait</a> - <a href="https://docs.microsoft.com/en-us/dotnet/api/system.threading.semaphoreslim.waitasync?view=netcore-3.1#System_Threading_SemaphoreSlim_WaitAsync_System_TimeSpan_System_Threading_CancellationToken_" rel="nofollow noreferrer">WaitAsync</a> will be used for <code>async</code> methods? It is Implied that there will not be a large number of blocked threads.</li> </ol>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-08T13:39:16.313", "Id": "478064", "Score": "0", "body": "Do you want to implement a read-through cache, right? And while the data retrieval is in progress your cache should be responsive, do I understand correctly?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-08T16:28:33.523", "Id": "478083", "Score": "0", "body": "@PeterCsala, read-through - if I understood correctly what it is, then yes. Second question - yes." } ]
[ { "body": "<p>I have design and implementation suggestions as well.</p>\n\n<h3>Cache type</h3>\n\n<p>There are several different caching strategies, like: <em>read-through, write-through, refresh-ahead, cache-aside, write-behind</em>, ...</p>\n\n<p>Let's examine the following three: <strong>read-through</strong>, <strong>refresh-ahead</strong>, <strong>cache-aside</strong></p>\n\n<ul>\n<li><strong>Read-Through</strong> works in the following way:\n\n<ul>\n<li>If the content is present in the cache then it will be served from the cache </li>\n<li>otherwise it will be fetched from the storage (the source of truth)\n\n<ul>\n<li>after the retrieval is succeeded then it will store a local copy in the cache</li>\n<li>and finally the request is served from the cache</li>\n</ul></li>\n</ul></li>\n<li><strong>Refresh-Ahead</strong> works in the following way: \n\n<ul>\n<li>The content is always served from the cache</li>\n<li>If the content expires then it will fetch the data automatically without any external request.</li>\n</ul></li>\n<li><strong>Cache-Aside</strong> works in the following way:\n\n<ul>\n<li>If the content is present in the cache then it will be served from the cache</li>\n<li>When it is not present then a separate flow / process fetches the data from the source and stores the data into the cache</li>\n</ul></li>\n</ul>\n\n<p>So, let's compare them: </p>\n\n<ul>\n<li>Read-Through vs Refresh-Ahead: reactive (serves on-demand) vs proactive (fetches in the background) </li>\n<li>Refresh-Ahead vs Cache-Aside: fetch is done by the cache itself vs retrieval process is done by an external provider </li>\n<li>Read-Through vs Cache-Aside: fetch by itself on-demand vs fetch by external provider on demand or in the background</li>\n</ul>\n\n<p>Based on the requirements you should be able to decide which one is the right one for you. For further details, please <a href=\"https://docs.oracle.com/cd/E16459_01/coh.350/e14510/readthrough.htm\" rel=\"nofollow noreferrer\">this article</a>.</p>\n\n<hr>\n\n<h3>Responsiveness</h3>\n\n<p>Serving stale data during the freshest retrieval has three separate stages: </p>\n\n<ol>\n<li>Determining the freshness of the data and then branching based on the result</li>\n<li>Retrieving data, while serving other requests</li>\n<li>Updating the data in the cache</li>\n</ol>\n\n<p>I would not spend words on the first and the last one because they are the easy ones. The second phase is where concurrency / parallelism comes into the play. You need to initiate a background retrieval process to be able to serve other requests <em>simultaneously</em>. You also need to synchronize the state between these threads. In order to do so you will utilize one of the sync primitives that are provided by .NET. You have chosen the <code>SemaphoreSlim</code>, which might not be the best for this problem.</p>\n\n<p>There are different sync primitive categories:</p>\n\n<ul>\n<li>Locking constructions (<code>Monitor</code>, <code>SpinLock</code>, <code>Semaphore</code>, etc.)</li>\n<li>Blocking constructions (<code>CountdownEvent</code>, <code>ManaulResetEvent</code>, <code>SpinWait</code>, <code>Task.Wait</code>, etc.)</li>\n<li>Non-blocking constructions (<code>Interlocked</code>, <code>MemoryBarrier</code>, etc.)</li>\n</ul>\n\n<p>I would highly recommend the following webpages for further details: <a href=\"https://docs.microsoft.com/en-us/dotnet/standard/threading/overview-of-synchronization-primitives\" rel=\"nofollow noreferrer\">1</a>, <a href=\"http://dotnetpattern.com/threading-synchronization\" rel=\"nofollow noreferrer\">2</a>, <a href=\"http://kflu.github.io/2017/04/04/2017-04-04-csharp-synchronization/\" rel=\"nofollow noreferrer\">3</a> </p>\n\n<p><code>SemaphoreSlim</code> is a generalization of the <code>Monitor</code>, which means rather than guaranteeing exclusive access to a single thread rather than it can allow n threads to access the same resource. In my opinion this is not what you need. Your semaphore instance (most probably) allow only a single access, and the state of the lock is used for branching. The same could be achieved with <code>SpinLock</code> and its <code>IsHeld</code> property, but I would not recommended that because it designed for really short locking in order to prevent context-switches.</p>\n\n<p>The best fit (in my opinion) is to use one of the signaling approaches. Because what you try to achieve is that: \"until a given condition is not met (the freshest data is not available) I would like to use my fallback (give back the stale data)\"</p>\n\n<p><code>WaitHandle</code> and <code>EventWaitHandle</code> base classes do not expose their state like <code>IsHeld</code>, but calling the <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.threading.waithandle.waitone?view=netcore-3.1#System_Threading_WaitHandle_WaitOne_System_TimeSpan_\" rel=\"nofollow noreferrer\">WaitOne with zero timeout</a> will tell you instantly whether or not the other thread has <em>signaled</em> (by calling the <code>Set</code> method). </p>\n\n<hr>\n\n<h3>MemoryCache</h3>\n\n<p>I would like to also highlight that there are more than one MemoryCache. There is one under the <code>System.Runtime.Caching</code> namespace and there is another under the <code>Microsoft.Extensions.Caching.Memory</code>. Latter suits better for ASP.NET Core. Fortunately both of them are thread-safe by default.</p>\n\n<hr>\n\n<p>Last but not least, I have two other suggestions:</p>\n\n<ol>\n<li>Try to split your logic into smaller functions</li>\n<li>First try to solve the problem with sync API then when you are familiar with all the components / primitives then try to achieve the async API</li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-09T09:52:50.287", "Id": "243596", "ParentId": "243475", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-06T13:35:26.757", "Id": "243475", "Score": "3", "Tags": [ ".net", "thread-safety", "async-await", "cache" ], "Title": "Update cache with minimal blocking" }
243475
<p>I am trying to generate a Word document with two different tables inside it. For this purpose I have two similar methods where I am passing word document reference and data object and table to the similar methods. </p> <p>I am looking to make single generic method. So in different places I can use single method and passing parameters to it.</p> <p><strong>Method 1</strong>:</p> <pre><code> private static List&lt;OpenXmlElement&gt; RenderExhaustEquipmentTableDataAndNotes(MainDocumentPart mainDocumentPart, List&lt;ProjectObject&lt;ExhaustEquipment&gt;&gt; exhaustEquipment,Table table) { HtmlConverter noteConverter = new HtmlConverter(mainDocumentPart); var equipmentExhaustTypes = new Dictionary&lt;string, List&lt;ProjectObject&lt;ExhaustEquipment&gt;&gt;&gt;(); foreach (var item in exhaustEquipment) { string exhaustEquipmentName = item.TargetObject.Name; if (!equipmentExhaustTypes.ContainsKey(exhaustEquipmentName)) { equipmentExhaustTypes.Add(exhaustEquipmentName, new List&lt;ProjectObject&lt;ExhaustEquipment&gt;&gt;()); } equipmentExhaustTypes[exhaustEquipmentName].Add(item); } List&lt;OpenXmlElement&gt; notes = new List&lt;OpenXmlElement&gt;(); int noteIndex = 1; foreach (var exhaustEquipmentItem in equipmentExhaustTypes) { List&lt;string&gt; noteIndices = new List&lt;string&gt;(); for (int exhaustEquipmentConditionIndex = 0; exhaustEquipmentConditionIndex &lt; exhaustEquipmentItem.Value.Count; exhaustEquipmentConditionIndex++) { var condition = exhaustEquipmentItem.Value[exhaustEquipmentConditionIndex]; var row = new TableRow(); Run superscriptRun = new Run(new RunProperties(new VerticalTextAlignment { Val = VerticalPositionValues.Superscript })); if (exhaustEquipmentConditionIndex == 0) { row.Append(RenderOpenXmlElementContentCell(new Paragraph( new List&lt;Run&gt; { new Run(new RunProperties(), new Text(exhaustEquipmentItem.Key) { Space = SpaceProcessingModeValues.Preserve }), superscriptRun }), 1, new OpenXmlElement[] {new VerticalMerge { Val = MergedCellValues.Restart },new TableCellMargin { LeftMargin = new LeftMargin { Width = "120" }, TopMargin = new TopMargin { Width = "80" } } })); } else { row.Append(RenderTextContentCell(null, 1, null, null, new OpenXmlElement[] { new VerticalMerge { Val = MergedCellValues.Continue } })); } row.Append(RenderTextContentCell(condition.TargetObject.IsConstantVolume ? "Yes" : "No")); row.Append(RenderTextContentCell($"{condition.TargetObject.MinAirflow:R2}")); row.Append(RenderTextContentCell($"{condition.TargetObject.MaxAirflow:R2}")); if (condition.TargetObject.NotesHTML?.Count &gt; 0) { foreach (var note in condition.TargetObject.NotesHTML) { var compositeElements = noteConverter.Parse(note); var htmlRuns = compositeElements.First().ChildElements.Where(c =&gt; c is Run).Cast&lt;Run&gt;().Select(n =&gt; n.CloneNode(true)); notes.Add(new Run(htmlRuns)); noteIndices.Add(noteIndex++.ToString(CultureInfo.InvariantCulture)); } } if (exhaustEquipmentConditionIndex == exhaustEquipmentItem.Value.Count - 1 &amp;&amp; condition.TargetObject.NotesHTML?.Count &gt; 0) { superscriptRun.Append(new Text($"({String.Join(',', noteIndices)})") { Space = SpaceProcessingModeValues.Preserve }); } table.Append(row); } } List&lt;OpenXmlElement&gt; notesSection = new List&lt;OpenXmlElement&gt;(); List&lt;OpenXmlElement&gt; result = RenderNotesArray(table, notes, notesSection); return result; } </code></pre> <p>This is how I am using the above method:</p> <pre><code> var table = new Table(RenderTableProperties()); table.Append(new TableRow( RenderTableHeaderCell("Name"), RenderTableHeaderCell("Constant Volume"), RenderTableHeaderCell("Minimum Airflow", units: "(cfm)"), RenderTableHeaderCell("Wet Bulb Temperature", units: "(cfm)") )); body.Append(RenderExhaustEquipmentTableDataAndNotes(mainDocumentPart, designHubProject.ExhaustEquipment, table)); </code></pre> <p><strong>Method 2</strong>:</p> <pre><code> private static List&lt;OpenXmlElement&gt; RenderInfiltrationTableData(MainDocumentPart mainDocumentPart, List&lt;ProjectObject&lt;Infiltration&gt;&gt; infiltration,Table table) { HtmlConverter noteConverter = new HtmlConverter(mainDocumentPart); var nameByInflitrationObject = new Dictionary&lt;string, List&lt;ProjectObject&lt;Infiltration&gt;&gt;&gt;(); foreach (var infiltrationData in infiltration) { string infiltrationName = infiltrationData.TargetObject.Name; if (!nameByInflitrationObject.ContainsKey(infiltrationName)) { nameByInflitrationObject.Add(infiltrationName, new List&lt;ProjectObject&lt;Infiltration&gt;&gt;()); } nameByInflitrationObject[infiltrationName].Add(infiltrationData); } List&lt;OpenXmlElement&gt; notes = new List&lt;OpenXmlElement&gt;(); int noteIndex = 1; foreach (var inflitrationDataItem in nameByInflitrationObject) { List&lt;string&gt; noteIndices = new List&lt;string&gt;(); for (int inflitrationNameIndex = 0; inflitrationNameIndex &lt; inflitrationDataItem.Value.Count; inflitrationNameIndex++) { var dataItem = inflitrationDataItem.Value[inflitrationNameIndex]; var row = new TableRow(); Run superscriptRun = new Run(new RunProperties(new VerticalTextAlignment { Val = VerticalPositionValues.Superscript })); if (inflitrationNameIndex == 0) { row.Append(RenderOpenXmlElementContentCell(new Paragraph( new List&lt;Run&gt; { new Run(new RunProperties(), new Text(inflitrationDataItem.Key) { Space = SpaceProcessingModeValues.Preserve }),superscriptRun }), 1, new OpenXmlElement[] {new VerticalMerge { Val = MergedCellValues.Restart },new TableCellMargin { LeftMargin = new LeftMargin { Width = "120" }, TopMargin = new TopMargin { Width = "80" }} })); } else { row.Append(RenderTextContentCell(null, 1, null, null, new OpenXmlElement[] { new VerticalMerge { Val = MergedCellValues.Continue } })); } row.Append(RenderTextContentCell($"{dataItem.TargetObject.AirflowScalar.ToString("R2", CultureInfo.CurrentCulture)} cfm {EnumUtils.StringValueOfEnum(dataItem.TargetObject.InfiltrationCalculationType).ToLower(CultureInfo.CurrentCulture)}")); if (dataItem.TargetObject.NotesHTML?.Count &gt; 0) { foreach (var note in dataItem.TargetObject.NotesHTML) { var compositeElements = noteConverter.Parse(note); var htmlRuns = compositeElements.First().ChildElements.Where(c =&gt; c is Run).Cast&lt;Run&gt;().Select(n =&gt; n.CloneNode(true)); notes.Add(new Run(htmlRuns)); noteIndices.Add(noteIndex++.ToString(CultureInfo.InvariantCulture)); } } if (inflitrationNameIndex == inflitrationDataItem.Value.Count - 1 &amp;&amp; dataItem.TargetObject.NotesHTML?.Count &gt; 0) { superscriptRun.Append(new Text($"({String.Join(',', noteIndices)})") { Space = SpaceProcessingModeValues.Preserve }); } table.Append(row); } } List&lt;OpenXmlElement&gt; notesSection = new List&lt;OpenXmlElement&gt;(); List&lt;OpenXmlElement&gt; result = RenderNotesArray(table, notes, notesSection); return result; } </code></pre> <p>This is how I am using the above method:</p> <pre><code> var table = new Table(RenderTableProperties()); table.Append(new TableRow( RenderTableHeaderCell("Type"), RenderTableHeaderCell("Air Flow") )); body.Append(RenderInfiltrationTableData(mainDocumentPart, designHubProject.Infiltration, table)); </code></pre> <p>I know this is a lot of code, but are there any ways to convert these to a single method. I am using .net core.</p> <p>Any ideas or suggestions on how I can refactor these two methods into single method would be very grateful.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-06T17:37:25.960", "Id": "477887", "Score": "0", "body": "I find a lot of your question's content to be fairly redundant, after the first time you have explicitly stated that you are looking for a way to merge these two methods any more of the same request are no longer needed. Reading the same thing 4 times, 3 in the body of your question and 1 in the title, is just a poor use of peoples time." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-06T17:39:05.083", "Id": "477888", "Score": "0", "body": "Sorry for confusion, I am looking a way to extract common methods or possible make generic method out of it" } ]
[ { "body": "<p>Wow, those methods are pretty similar.</p>\n\n<p>Initially, these objects:\n<code>List&lt;ProjectObject&lt;ExhaustEquipment&gt;&gt; exhaustEquipment</code>\n<code>List&lt;ProjectObject&lt;Infiltration&gt;&gt; infiltration</code></p>\n\n<p>are only different in which template parameter refers (<code>ExhaustEquipment</code>,<code>Infiltration</code>), so you could do a generic method:</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code> //this all, could be written as a Generic method, the Generic Parameter would be\n //Infiltration or ExhaustEquipment\n private static List&lt;OpenXmlElement&gt; GenericRenderElement&lt;Element&gt;(MainDocumentPart mainDocumentPart, List&lt;ProjectObject&lt;Element&gt;&gt; element, Table table)\n\n HtmlConverter noteConverter = new HtmlConverter(mainDocumentPart);\n var nameByBusinessElement = new Dictionary&lt;string, List&lt;ProjectObject&lt;Element&gt;&gt;&gt;();\n\n string elementName;\n foreach (var element in businessDictionary)\n {\n elementName = element.TargetObject.Name;\n if (!nameByBusinessElement.ContainsKey(elementName))\n nameByBusinessElement.Add(elementName, new List&lt;ProjectObject&lt;Element&gt;&gt;());\n\n nameByBusinessElement[elementName].Add(element);\n }\n\n\n List&lt;OpenXmlElement&gt; notes = new List&lt;OpenXmlElement&gt;();\n int noteIndex = 1;\n\n foreach (var element in nameByBusinessElement)\n {\n List&lt;string&gt; noteIndices = new List&lt;string&gt;();\n for (int elementNameIdx = 0; elementNameIdx &lt; element.Value.Count; elementNameIdx++)\n {\n var dataItem = element.Value[elementNameIdx];\n var row = new TableRow();\n Run superscriptRun = new Run(new RunProperties(new VerticalTextAlignment { Val = VerticalPositionValues.Superscript }));\n\n if (elementNameIdx == 0)\n {\n row.Append(RenderOpenXmlElementContentCell(new Paragraph(\n new List&lt;Run&gt; {\n new Run(new RunProperties(), new Text(element.Key) { Space = SpaceProcessingModeValues.Preserve }),superscriptRun\n }), 1,\n new OpenXmlElement[] {new VerticalMerge { Val = MergedCellValues.Restart },new TableCellMargin {\n LeftMargin = new LeftMargin { Width = \"120\" },\n TopMargin = new TopMargin { Width = \"80\" }}\n }));\n }\n else\n {\n row.Append(RenderTextContentCell(null, 1, null, null, new OpenXmlElement[] { new VerticalMerge { Val = MergedCellValues.Continue } }));\n }\n row.Append(RenderTextContentCell($\"{dataItem.TargetObject.AirflowScalar.ToString(\"R2\", CultureInfo.CurrentCulture)} cfm {EnumUtils.StringValueOfEnum(dataItem.TargetObject.InfiltrationCalculationType).ToLower(CultureInfo.CurrentCulture)}\"));\n\n if (dataItem.TargetObject.NotesHTML?.Count &gt; 0)\n {\n foreach (var note in dataItem.TargetObject.NotesHTML)\n {\n var compositeElements = noteConverter.Parse(note);\n var htmlRuns = compositeElements.First().ChildElements.Where(c =&gt; c is Run).Cast&lt;Run&gt;().Select(n =&gt; n.CloneNode(true));\n notes.Add(new Run(htmlRuns));\n noteIndices.Add(noteIndex++.ToString(CultureInfo.InvariantCulture));\n }\n }\n\n if (elementNameIdx == element.Value.Count - 1 &amp;&amp; dataItem.TargetObject.NotesHTML?.Count &gt; 0)\n {\n superscriptRun.Append(new Text($\"({String.Join(',', noteIndices)})\") { Space = SpaceProcessingModeValues.Preserve });\n }\n table.Append(row);\n }\n }\n\n return RenderNotesArray(table, notes, new List&lt;OpenXmlElement&gt;());\n }\n</code></pre>\n\n<p>and invoke it in the other two concrete methods:</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>private static List&lt;OpenXmlElement&gt; RenderExhaustEquipmentTableDataAndNotes(MainDocumentPart mainDocumentPart, List&lt;ProjectObject&lt;ExhaustEquipment&gt;&gt; exhaustEquipment,Table table) {\n return GenericRenderElement&lt;ExhaustEquipment&gt;(mainDocumentPart, exhaustEquipment, table);\n}\n\nprivate static List&lt;OpenXmlElement&gt; RenderInfiltrationTableData(MainDocumentPart mainDocumentPart, List&lt;ProjectObject&lt;Infiltration&gt;&gt; infiltration,Table table) {\n return GenericRenderElement&lt;Infiltration&gt;(mainDocumentPart, infiltration, table);\n}\n</code></pre>\n\n<p>Well, I hope it has been helpful.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-06T17:42:41.277", "Id": "477889", "Score": "0", "body": "thanks for the input and other difference is appending data to the table rows at here `row.Append(RenderTextContentCell($\"{dataItem.TargetObject.AirflowScalar.ToString(\"R2\", CultureInfo.CurrentCulture)} cfm {EnumUtils.StringValueOfEnum(dataItem.TargetObject.InfiltrationCalculationType).ToLower(CultureInfo.CurrentCulture)}\")); `" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-06T17:44:17.723", "Id": "477890", "Score": "0", "body": "is there any way we can pass these ones from the parent method" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-06T17:53:06.290", "Id": "477892", "Score": "0", "body": "You could add a lambda as parameter, said lambda would be of generic type `<Element>` and has two parameters, `TableRow row, Element element`, when invoking the `GenericRenderElement` method you sould send the lambda as parameter, in the case of `RenderExhaustEquipmentTableDataAndNotes` as the embed procedure you need (using castings if needed), and in the case of `RenderInfiltrationTableData` as the embed procedure for `EnumUtils.StringValueOfEnum(//...`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-06T17:55:14.830", "Id": "477894", "Score": "0", "body": "Thanks for the suggestion If possible could you please paste any pseudo code" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-06T18:28:00.050", "Id": "477898", "Score": "2", "body": "@EnigmaState For your own growth you should learn how to do that yourself - teach a man to fish rather than give one. Miguel's answer and comment are good, and have told you, as far as I can tell, all you need. The code is very basic, and [you've known how to use lambdas for roughly 10 years now](https://stackoverflow.com/q/7406346), I'm sure you can do it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-06T18:34:12.403", "Id": "477900", "Score": "0", "body": "@Peilonrayz my bad since then I haven’t worked on lambda much so I lost grip on it" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-06T19:24:25.740", "Id": "477903", "Score": "0", "body": "@MiguelAvila could you please provide any pseudo code that would be very grateful to me, thanks" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-07T03:45:59.733", "Id": "477939", "Score": "0", "body": "@MiguelAvila the row need to be appended in foreach loop that is where i got confused even if we pass the lambda into it" } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-06T17:39:00.213", "Id": "243489", "ParentId": "243478", "Score": "4" } }, { "body": "<p>I'm only adding some notes here on addition of Miguel answer, his answer gives you what you asked, but what you really want is to divide this method into several methods, each method would handle one thing and only one thing. here is a list of the methods you need : </p>\n\n<ol>\n<li>Converting <code>List&lt;ProjectObject&lt;T&gt;&gt;</code> to Dictionary. </li>\n<li>Creating a Note from <code>ProjectObject&lt;T&gt;</code>.</li>\n<li>Creating a Note Indices from <code>ProjectObject&lt;T&gt;</code>.</li>\n<li>Creating <code>TableRow</code> from <code>ProjectObject&lt;T&gt;</code>.</li>\n<li>Creating <code>Run</code> for <code>ProjectObject&lt;T&gt;</code>.</li>\n</ol>\n\n<p>Then, you can create methods to use these single object return methods to return <code>IEnumerable&lt;T&gt;</code> in which would create multiple objects of each method \n like creating multiple notes, rows, runs ..etc.</p>\n\n<p>if you do this, it'll be very easy to reuse and maintain. and then, you can overload them to add some other requirements, for instance, for the <code>TableRow</code>, you can add <code>RenderTextContentCell</code> overload. </p>\n\n<p>Another thing is to make use of <code>interface</code>. If you implemented an interface that would be implemented on <code>Infiltration</code> and <code>ExhaustEquipment</code>, you would be able to pass that interface to the method instead of the concrete object name like this </p>\n\n<pre><code>private static List&lt;OpenXmlElement&gt; RenderInfiltrationTableData(\n MainDocumentPart mainDocumentPart, \n List&lt;ProjectObject&lt;IExhaustInfiltration&gt;&gt; exhaustOrInfiltration,\n Table table) \n { ... }\n</code></pre>\n\n<p>with this, you would be able to pass one of those two objects, which would easier to make some conditions in the method to switch some cases based on the type like: </p>\n\n<pre><code>var isInfiltration = exhaustOrInfiltration.GetType() == typeof(Infiltration);\n\nif(isInfiltration)\n{\n // do something\n}\nelse\n{\n // it's ExhaustEquipment\n}\n</code></pre>\n\n<p>here is a pseudo-code example on how your method would be if you done these suggestions :</p>\n\n<pre><code>private static List&lt;OpenXmlElement&gt; RenderTableData(MainDocumentPart mainDocumentPart, List&lt;ProjectObject&lt;IExhaustInfiltration&gt;&gt; exhaustOrInfiltration,Table table)\n{\n var exhaustOrInfiltrationTypes = ToDictionary(exhaustOrInfiltration);\n\n // to be used on notes\n var isInfiltration = exhaustOrInfiltration.GetType() == typeof(Infiltration);\n foreach(var item in exhaustOrInfiltrationTypes)\n {\n // CreateTableRow would contains the add single row, note, and run methods. \n var tableRows = CreateTableRow(item.Value, isInfiltration);\n table.Append(tableRow); // assuming there is a method accepts (IEnumerable&lt;TableRow&gt;) to add multiple rows at once. \n }\n\n return RenderNotesArray(table, notes, notesSection);\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-07T04:54:22.263", "Id": "477942", "Score": "0", "body": "Thanks for suggestion, Those two are different objects and there is no interface related with those two and I would like to make single method common among those two" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-07T07:46:05.797", "Id": "477948", "Score": "0", "body": "@EnigmaState use generics,like what Miguel answer." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-07T15:51:10.917", "Id": "477964", "Score": "0", "body": "even i am favorable with Miguel answer but stuck at passing lambda expressions as parameters to it" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-08T13:42:04.300", "Id": "478065", "Score": "0", "body": "@EnigmaState the easiest way to understand lambda expressions is to use delegate `Func<T>` if you create a delegate function that would only pass a string, and return bool `Func<string, bool>`, then just add the `RenderTextContentCell` inside it, then just pass this function as parameter." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-08T13:49:39.677", "Id": "478069", "Score": "0", "body": "thanks for suggestion I am just looking for some pseudo code" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-08T15:20:18.353", "Id": "478077", "Score": "0", "body": "if you can please provide kind of pseudo code that would be very grateful to me , thanks" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-09T02:02:43.580", "Id": "478106", "Score": "0", "body": "@EnigmaState if the lambda expressions is for the part of appending rows `RenderTextContentCell`, then you can combine both texts, separate them with an if condition to switch between them based on the object type (like in my `isInfiltration` example).. That would do the job. for lambda refer to https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/statements-expressions-operators/lambda-expressions" } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-07T04:40:33.673", "Id": "243505", "ParentId": "243478", "Score": "2" } } ]
{ "AcceptedAnswerId": "243489", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-06T15:36:50.610", "Id": "243478", "Score": "1", "Tags": [ "c#", ".net", "linq", "generics", ".net-core" ], "Title": "Building a Word document containing two different tables" }
243478
<p>I wrote a simple dice game with the purpose to practice arrays and classes. I would like some critique on my code structure and quality - as well as thoughts on my thoughts to improve it.</p> <p>Here's the code: </p> <pre><code>import java.util.Random; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.IOException; public class ceeLo { public static void main(String[] args) throws IOException { //declaration block BufferedReader BR = new BufferedReader (new InputStreamReader(System.in)); Player human = new Player(); Player computer = new Player(); double wallet = 100.0; double bet = 0.0; System.out.println("What's your name?: "); human.setName(BR.readLine()); computer.setName("Computer"); System.out.println("\nWelcome to Cee Lo " + human.getName() + "\n"); //------------------game loop------------------// do { System.out.println("\nWallet: " + wallet); System.out.println("How much would you like to bet?\n"); bet = input(wallet); human.playerRolls(); computer.playerRolls(); showRoll(human); showRoll(computer); int scoreHuman = gameLogic(human.getDieValues(), human); int scoreComputer = gameLogic(computer.getDieValues(), computer); String victor = calculateWinner(scoreHuman,scoreComputer, human, computer); System.out.println("\nThe winner is: " + victor); wallet = adjustWallet(victor, wallet, bet, human, computer); } while (wallet &gt; 0.0); System.out.println("\nWallet: " + wallet); System.out.println("Goodbye!"); } /** @param int[] array = sorted array of all die values from player class @param Player x = player object gameLogic returns an int with the score a player has based on their roll */ public static int gameLogic(int[] array, Player x) { int playerScore = 0; // 4, 5, 6 is an automatic win if(array[0] == 4 &amp;&amp; array[1] == 5 &amp;&amp; array[2] == 6) { System.out.println(x.getName() + " won!"); playerScore = 100; //high number not achieved by any other rolls } // 1, 2, 3 is an automatic loss else if (array[0] == 1 &amp;&amp; array[1] == 2 &amp;&amp; array[2] == 3) { System.out.println(x.getName() + " loses!"); playerScore = -100; //no roll can give neg value } //sorted array may either have two of same number at beginning or end - leftover is score else if (array[0] == array[1] &amp;&amp; array[1] != array[2]) { playerScore = array[2]; System.out.println(x.getName() + " got: " + playerScore); } else if (array[1] == array[2] &amp;&amp; array[2] != array[0]) { playerScore = array[0]; System.out.println(x.getName() + " got: " + playerScore); } //triple of same number worth more than above scores. Multiply score by 10 to signify this. else if (array[0] == array[1] &amp;&amp; array[1] == array[2]) { System.out.println(x.getName() + " rolled trip " + array[0] + "'s!"); playerScore = array[0] * 10; } // No score: roll, print roll, recursive call to gameLogic with new die values else { System.out.println(x.getName() + " got: nothing. Re-rolling..."); x.playerRolls(); showRoll(x); playerScore = gameLogic(x.getDieValues(), x); } return playerScore; } /** @param int a = human's score @param int b = computer's score @param Player x = human player @param Player ai = computer calculateWinner compares the scores attained by human and player and returns string with winner's name. */ public static String calculateWinner(int a, int b, Player x, Player ai) { String winner = " "; if(a &gt; b) { winner = x.getName(); } else if ( a &lt; b) { winner = ai.getName(); } else { System.out.println("Tie!"); winner = "Nobody"; } return winner; } /** @param String s = victor from main, which stores name of winner of round @param double max = wallet amount (initialized to 100 to start) @param double wager = bet amount @param Player x = human player @param Player ai = computer adjustWallet removes lost bet or adds winnings to wallet amount */ public static double adjustWallet(String s, double max, double wager, Player x, Player ai) { if (s.equals(x.getName())) { max += wager; }else if (s.equals(ai.getName())) { max -= wager; } return max; } /** @param Player x = player object instance showRoll prints out player's roll values. */ public static void showRoll(Player x) { System.out.println(x.getName() + " rolls... "); for (int i = 0; i &lt; 3; i++) { System.out.println(x.getDieValues()[i] + " "); } System.out.println(); } /** @param double max = wallet amount input takes in the amount a player wants to bet and returns it if it's more than 0 and within wallet amount */ public static double input(double max) throws IOException { BufferedReader BR = new BufferedReader(new InputStreamReader(System.in)); double value; value = Double.parseDouble(BR.readLine());; if(value &lt; 0 || value &gt; max) value = validation(value, max); return value; } /** @param double x = amount a player wants to bet @param double max = wallet amount validation tells player if they input an amount 0 or less, or more than they have in the wallet and takes in input until it meets the rules. Returns to input method. */ public static double validation(double x, double max) throws IOException { BufferedReader BR = new BufferedReader(new InputStreamReader(System.in)); while( x &lt; 0 || x &gt; max) { System.out.println("\nValue must be greater than 0! Max bet = whole wallet.\n"); x = Double.parseDouble(BR.readLine()); } return x; } } class Die { private int sides; private int value; Die(int numSides) { sides = numSides; roll(); } void roll() { Random rand = new Random(); value = rand.nextInt(sides) + 1; } int getSides() { return sides; } int getValue() { return value; } } class Player { private String name; private int[] dieValues = new int[3]; void playerRolls() { final int numDie = 3; final int numSides = 6; Die[] dieArray = new Die[numDie]; for (int i = 0; i &lt; dieArray.length; i++) { dieArray[i] = new Die(numSides); } for (int i = 0; i &lt; dieArray.length; i++) { dieValues[i] = dieArray[i].getValue(); } selectionSort(dieValues); } int[] getDieValues() { return dieValues; } void setName(String pname) { name = pname; } String getName() { return name; } /** @param int[] array = array to be sorted selectionSort sorts an array's contents from lowest to highest */ void selectionSort(int[] array) { int startScan, index, minIndex, minValue; for (startScan = 0; startScan &lt; array.length-1; startScan++) { minIndex = startScan; minValue = array[startScan]; for( index = startScan + 1; index &lt; array.length; index++) { if(array[index] &lt; minValue) { minValue = array[index]; minIndex = index; } array[minIndex] = array[startScan]; array[startScan] = minValue; } } } } </code></pre> <p>I would switch from arrays to arraylist to use the built in sort method, change the game loop to include a menu option to quit mid-game, and have better input validation perhaps with an overloaded input method to not have the program crash. Also perhaps switch from buffered reader to scanner (I just used buffered reader to see how it works as I've always used scanner up to this point)</p>
[]
[ { "body": "<p>well, your code looks fine, but there are few things I would like to talk about.</p>\n\n<ul>\n<li>The class names allways goes using UpperCamelCase, at least in Java it is very common.</li>\n<li>Usually we have the parameter name equally named to the class attribute:</li>\n</ul>\n\n<pre class=\"lang-java prettyprint-override\"><code>void setName(String pname) {\n name = pname;//you should not. plus your IDE may have getters/setters generator\n}\n\n//use instead\nvoid setName(String name) {\n this.name = name;//better, according to what most Java programmers are used to see\n //however, it is no big deal. (but more work for you)\n}\n</code></pre>\n\n<ul>\n<li>The brackets:</li>\n</ul>\n\n<pre class=\"lang-java prettyprint-override\"><code>class ceeLo\n{//C++ style\n}\n\nclass CeeLo {\n//Java style\n}\n</code></pre>\n\n<ul>\n<li>Normally variable values are assigned in the constructor instead of directly</li>\n</ul>\n\n<pre class=\"lang-java prettyprint-override\"><code>private int[] dieValues = new int[3];//no, at least if it is not constant\n\n//yes\npublic Player() {\n this.dieValues = new int[3];\n}\n</code></pre>\n\n<ul>\n<li>Finally, there:</li>\n</ul>\n\n<pre class=\"lang-java prettyprint-override\"><code>void playerRolls()\n {\n //as the method is called (and is called often)\n //the program will create and destroy these constants. so, you should declare\n //them outside the method\n final int numDie = 3;\n final int numSides = 6;\n\n//example\nprivate static final int numDie = 3;\nprivate static final int numSides = 6;\n\nvoid playerRolls()\n {//... use those here\n\n</code></pre>\n\n<p>I hope it has been helpful.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-06T17:08:09.040", "Id": "243486", "ParentId": "243479", "Score": "2" } }, { "body": "<p>Overall, a solid effort. You've already listed the major areas for improvement.</p>\n\n<ol>\n<li><p>Switch from arrays to Lists to use the built-in sort method.</p></li>\n<li><p>Change the game loop to include a menu option to quit mid-game. </p></li>\n<li><p>Validate the input.</p></li>\n</ol>\n\n<p>Now for my comments.</p>\n\n<p>The convention is that class names in Java start with a capital letter. The ceeLo class should be named CeeLo.</p>\n\n<p>Variable names and method names in Java start with a lower case letter. The</p>\n\n<pre><code>BufferedReader BR\n</code></pre>\n\n<p>should be</p>\n\n<pre><code>BufferedReader br\n</code></pre>\n\n<p>or</p>\n\n<pre><code>BufferedReader reader\n</code></pre>\n\n<p>All of the methods in the CeeLo class are static. While <code>main</code> must remain static, you should use non-static methods and create an instance of the CeeLo class to call the methods.</p>\n\n<p>Use blank lines sparingly to separate groups of code. Here's an example of what I mean from your <code>main</code> method.</p>\n\n<pre><code> do {\n System.out.println(\"\\nWallet: \" + wallet);\n System.out.println(\"How much would you like to bet?\\n\");\n bet = input(wallet);\n\n human.playerRolls();\n computer.playerRolls();\n showRoll(human);\n showRoll(computer);\n\n int scoreHuman = gameLogic(human.getDieValues(), human);\n int scoreComputer = gameLogic(computer.getDieValues(), computer);\n\n String victor = calculateWinner(scoreHuman, scoreComputer, human, computer);\n System.out.println(\"\\nThe winner is: \" + victor);\n\n wallet = adjustWallet(victor, wallet, bet, human, computer);\n } while (wallet &gt; 0.0);\n</code></pre>\n\n<p>In a Javadoc, the explanation comes first, followed by the <code>@param</code> descriptions, followed by the <code>@return</code> description.</p>\n\n<p>You can use basic HTML in your explanation.</p>\n\n<p>Here's a reworked example from your code.</p>\n\n<pre><code>/**\n * The input method takes in the amount a player wants to bet as a\n * &lt;code&gt;String&lt;/code&gt; and returns it as a &lt;code&gt;double&lt;/code&gt; if it's more than\n * zero and within the wallet amount.\n *\n * @param max = wallet amount\n * @return value\n */\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-06T17:10:13.910", "Id": "243487", "ParentId": "243479", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-06T15:37:31.010", "Id": "243479", "Score": "2", "Tags": [ "java", "object-oriented", "array" ], "Title": "Console dice game" }
243479
<p>This script looks for a data attribute applied to elements within a specified wrapper. It then sets all elements with the attribute to the same height (height of tallest div). I needed to add a wait time as the script would sometimes get the heights of the divs before the page had fully rendered. Even though the await is set to 0, it works.</p> <p>There is also an event listener to listen for resize, and adjust the elements as they change size.</p> <p>I have only been coding JS for a few weeks so I am not great at it.</p> <h3>HTML</h3> <pre><code>&lt;div id="div1"&gt; &lt;div data-equalize&gt; &lt;p&gt;Some content&lt;/p&gt; &lt;/div&gt; &lt;div data-equalize&gt; &lt;p&gt;Some content&lt;/p&gt; &lt;/div&gt; &lt;div data-equalize&gt; &lt;p&gt;Some content&lt;/p&gt; &lt;/div&gt; &lt;div data-equalize&gt; &lt;p&gt;Some content&lt;/p&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <h3>Script</h3> <pre><code>function equalizer(wrap) { const equalizeEls = Array.from(wrap.querySelectorAll(`[data-equalize]`)); const wait = (ms = 0) =&gt; new Promise(resolve =&gt; setTimeout(resolve, ms)); //get the largest height in the array function getLargestNumber(arr) { return Math.max(...arr); } //get an array of heights function getTallest(arr) { const allheights = arr.map(x =&gt; x.clientHeight); return getLargestNumber(allheights) } function equalizeHeights(els) { const largest = getTallest(els); return els.forEach(el =&gt; { el.style.minHeight = `${largest}px` }); } async function handleResize() { await wait(0); //needs a await to ensure page is fully loaded equalizeHeights(equalizeEls) } window.addEventListener('DOMContentLoaded', handleResize); window.addEventListener('resize', handleResize); } </code></pre> <h3>Running the script</h3> <pre><code>new equalizer(document.querySelector(`#div1`)) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-06T16:58:26.257", "Id": "477882", "Score": "0", "body": "Are the divs positioned side by side? Then this can be done with CSS alone using flex or grid layout." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-06T17:50:55.710", "Id": "477891", "Score": "1", "body": "Not always, I use flexbox when I can though." } ]
[ { "body": "<h1>data attribute</h1>\n\n<p>It's a bit unconventional to use a data attribute to select the affected elements. A class would be the more conventional approach.</p>\n\n<h1>Use of template strings</h1>\n\n<p>You have two places where you unnecessarily use template strings with backticks (<code>`</code>).</p>\n\n<h1>Code</h1>\n\n<p>I like the code overall very much. Nice break down into functions. Nice use of modern JS features. </p>\n\n<p>Only one small thing: The <code>return</code> in <code>equalizeHeights</code> is unnecessary.</p>\n\n<h1>Timing</h1>\n\n<p>The problem with the need for the wait may be due to contents of the divs. If they contain images or use external fonts, then they may lead to resizing of the divs while these are loading. Some points to look out for:</p>\n\n<ul>\n<li>Use the <code>load</code> event instead or additionally to <code>DOMContentLoaded</code>.</li>\n<li>Make sure images have a size assigned to them, either in the HTML (<code>height</code> and <code>width</code> attributes) or the CSS.</li>\n<li>There a ways to make sure that the text content isn't rendered until the fonts are loaded, but this is not really my area of expertise.</li>\n</ul>\n\n<h1>Possible bug/misfeature</h1>\n\n<p>There is one problem with the script: It never allows the divs to shrink if the content becomes shorter, for example due to a window resize.</p>\n\n<p>I can think of two possible solutions:</p>\n\n<ul>\n<li>Before checking the size of the divs, remove the <code>min-height</code>s and <code>wait()</code> to allow a re-render.</li>\n</ul>\n\n<p>Or</p>\n\n<ul>\n<li>add a second, inner div inside the equalize divs and use the inner divs client height to determine the largest div.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-15T13:11:35.047", "Id": "478815", "Score": "0", "body": "This is awesome, thanks so much for the feedback!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-08T09:27:50.140", "Id": "243549", "ParentId": "243483", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-06T16:33:50.480", "Id": "243483", "Score": "6", "Tags": [ "javascript" ], "Title": "Selects all elements with a specific data attribute and equalizes their heights" }
243483
<p>I have a mathematical problem about prime power. A number <span class="math-container">\$x\$</span> can be considered a prime power if <span class="math-container">\$x = p^k\$</span> where <span class="math-container">\$p\$</span> is a prime and <span class="math-container">\$k\$</span> is a non-negative integer. For example, <span class="math-container">\$81\$</span> is a prime power because <span class="math-container">\$81 = 3^4\$</span>. Now, form a sequence of numbers in the following way. Start by taking a random number. </p> <ol> <li>If the number is a prime power, end the sequence.</li> <li>If the number is not a prime power, minus that number with the biggest prime power that's not more than the number itself. Do it over and over again until a prime power is met, then stop.</li> </ol> <p>For example, 34 is not a prime power. Hence we minus it with the highest prime power that's not more than it which is <span class="math-container">\$32\$</span>, hence <span class="math-container">\$34-32=2\$</span>. <span class="math-container">\$2\$</span> is a prime power, so we stop. In this case, the length of the operation is 2 (because 34 -> 2).</p> <p>Another example is <span class="math-container">\$95\$</span>. <span class="math-container">\$95\$</span> isn't a prime power, so <span class="math-container">\$95-89=6\$</span>. <span class="math-container">\$6\$</span> is also not a prime power, so we minus it again with the highest prime power, <span class="math-container">\$6-5=1\$</span>. <span class="math-container">\$1\$</span> is a prime power (because <span class="math-container">\$2^0 = 1\$</span>), so we stop. In this case, the length of the operation is 3 (because 95 -> 6 -> 1).</p> <p>Known that:</p> <ul> <li>1 is the smallest initial number that can be formed with a length of 1 operation. </li> <li>6 is the smallest initial number that can be formed with a length of 2 operations. </li> <li>95 is the smallest initial number that can be formed with a length of 3 operations. </li> <li>360748 is the smallest initial number that can be formed with a length of 4 operations.</li> </ul> <p>I made an application using Python to find the smallest initial number that can be formed with a length of 5, 6 and 7 operations. It is using looping to solve the problem. However, to find the smallest initial number that can be formed with a length of 4 or more operations, the program takes a very very long time to run.</p> <p>Is there any way I could improve my code to make the program to run much faster? I just want to focus on getting the number with 5, 6 and 7 operations.</p> <pre><code>from sympy.ntheory import factorint def pp(q): #to check whether it is a prime power fact=factorint(q) p=int(list(fact.keys())[0]) n=int(list(fact.values())[0]) if q!=p**n: return False else: return True a=[1,6][-1] b=a*2 d=1 while d!=0: c=b-a if pp(b)==False and pp(c)==True: for i in range(b-1,c-1,-1): if i==c: d=0 elif pp(i)==True: b=i+a break elif pp(b)==False: for i in range(b-1,c-1,-1): if i==c: b=b+a+1 elif pp(i)==True: b=i+a break elif pp(b)==True: b=b+a b </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-07T04:07:26.480", "Id": "477940", "Score": "0", "body": "exactly how are you finding for 5,6,7 operations? what parameters are you changing?" } ]
[ { "body": "<p>Welcome, there are some aspects to comment about.</p>\n\n<ul>\n<li>First is that, you should use specific names for your functions <code>pp</code> is ok and sounds quite interesting, but it would be better if you use <code>is_prime_power</code> (as mentioned by <a href=\"https://codereview.stackexchange.com/users/308/konrad-rudolph\">Konrad Rudolph</a> in the comments).</li>\n<li><p>Now, for the first function, I would change only two things:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def is_prime_power(q):\n fact = factorint(q)\n p = int(list(fact.keys())[0])\n n = int(list(fact.values())[0])\n return q == p**n # this line asks 'is prime power?'\n\n# could also be:\ndef is_prime_power(q):\n return q == int(list(fact.keys())[0])**int(list(fact.values())[0])\n# but is quite strange because p,n are not specified.\n\n# this inverses the boolean answer, as you see\n if q != p**n:\n return False\n else:\n return True\n</code></pre></li>\n<li><p>For the procedure, you should avoid using comparisons with <code>True</code> and <code>False</code>. If the value is a boolean, Python deduces if it is true or false, in the case of compare with <code>False</code> use <code>not</code>:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>a = [1,6][-1]\n\nb = a*2\nd = 1\nwhile d != 0:\n c = b-a\n if not is_prime_power(b) and is_prime_power(c):\n for i in range(b-1, c-1, -1):\n if i == c:\n d = 0\n elif is_prime_power(i):\n b = i+a\n break\n elif not is_prime_power(b):\n for i in range(b-1, c-1, -1):\n if i == c:\n b = b+a+1\n elif is_prime_power(i):\n b = i + a\n break\n elif is_prime_power(b):\n b = b+a\nb\n</code></pre></li>\n</ul>\n\n<p>Well, thanks for writing easy to read code, it is so good to see something like it.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-06T19:54:27.670", "Id": "477906", "Score": "0", "body": "By indenting the following code block with four spaces you can have it inline with the bullet point. Please see my above edit to see how to do this in the future. :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-07T10:54:02.507", "Id": "477952", "Score": "1", "body": "You’re right about naming, but the names you propose are not good either. First off, Python by convention uses `snake_case`, not `camelCase`. Deviating from this is obviously totally fine, but if you’re reviewing a beginner’s code it behooves you to at least mention when you deviate from established norm. Secondly, a function such as this should almost certainly be a *verb*, not a *noun*. As such, `check_prime_power` is a better name than `prime_power_check`. But what does “check” mean? What are we checking? Use the actually matching verb: `is_prime_power`." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-06T18:05:08.463", "Id": "243491", "ParentId": "243488", "Score": "5" } }, { "body": "<p>The question seems to be related to <a href=\"https://en.wikipedia.org/wiki/Prime_gap\" rel=\"nofollow noreferrer\">prime gaps</a>.</p>\n\n<p>Some observations:</p>\n\n<ol>\n<li><p>Since we are trying to find the smallest number formed with some length operations, that means it is the first number formed with that length operations if we start our search from 1.</p></li>\n<li><p>For the number 6, the biggest prime power less than 6 is 5 i.e. 6-5 = 1 </p>\n\n<p>For the number 95, the biggest prime power less than 95 is 89 i.e. 95-89 = 6</p>\n\n<p>For the number 360748, the biggest prime power less than 360748 is 360653 i.e. 360748-360653=95.</p></li>\n</ol>\n\n<p>This shows that for the next number that will be formed using 5 length operations, the gap between that number and biggest prime power less that number must be 360748. The problem is simplified to finding the smallest number with has a prime power gap of 360748 and so on.</p>\n\n<hr>\n\n<p>Now consider the list of prime numbers and list of prime power numbers. It is obvious that prime power numbers are more frequent that prime numbers. So it is safe to assume that the <em>gaps between prime power numbers will be less than gaps between prime numbers</em>.</p>\n\n<p>Straight from Wikipedia article <a href=\"https://en.wikipedia.org/wiki/Prime_gap\" rel=\"nofollow noreferrer\">prime gaps</a>,</p>\n\n<blockquote>\n <p>As of August 2018 the largest known maximal prime gap has length 1550, found by Bertil Nyman. It is the 80th maximal gap, and it occurs after the prime 18361375334787046697.</p>\n</blockquote>\n\n<p>From <a href=\"https://mathoverflow.net/a/41222\">this post</a>, we can make a reasonable estimate for the prime number with gap 360748 i.e. <code>exp(sqrt(360748)) ~ 7*10^260</code>. (There are better estimations available in literature). </p>\n\n<p>Too big and not suitable for our Personal Computers. In general sieves are faster than checking primes directly. It is easy to make a sieve for prime power numbers, however it is impractical for current problem. To make a boolean array of length 10^260, we will need around 10^247 TeraByte.</p>\n\n<p>Even if we somehow manage to determine the result for length 5, for the next number in sequence, it should have a prime power gap of 10^260. We will probably have to wait for Personal Quantum computers for that.</p>\n\n<hr>\n\n<p><strong>EDIT</strong>: Following is the code to generate a prime power sieve.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def prime_power_sieve(limit):\n sieve = [1]*limit\n sieve[0] = 0\n p = 2\n while p&lt;limit:\n if sieve[p]&gt;0:\n # mark multiples of p\n for j in range(p*p, limit, p):\n sieve[j] = 0\n # mark powers of p\n j = p\n while j*p&lt;limit :\n j *= p\n sieve[j] = 1 \n p += 1\n return sieve\n</code></pre>\n\n<p>To find largest prime power lower than or equal to that number, we can apply a simple modification by tracking the previously encountered prime power.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def prime_power_sieve_with_previous(limit):\n sieve = list(range(0,limit))\n p = 2\n prev = p\n while p&lt;limit:\n if sieve[p]&gt;0:\n prev = p\n # mark multiples of p\n for j in range(p*p, limit, p):\n sieve[j] = 0\n # mark powers of p\n j = p\n while j*p&lt;limit :\n j *= p\n sieve[j] = j\n elif sieve[p] == 0:\n sieve[p] = prev\n p += 1\n return sieve\n</code></pre>\n\n<p>With this, largest prime power less than or equal to <code>p</code> will be <code>sieve[p]</code>.</p>\n\n<pre><code>print(prime_power_sieve(20))\nprint(prime_power_sieve_with_previous(20))\n\nOutput:\n[0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0, 1, 0, 1, 0, 0, 1, 1, 0, 1]\n[0, 1, 2, 3, 4, 5, 5, 7, 8, 9, 9, 11, 11, 13, 13, 13, 16, 17, 17, 19]\n\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-07T06:33:32.403", "Id": "243507", "ParentId": "243488", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-06T17:10:14.253", "Id": "243488", "Score": "4", "Tags": [ "python", "performance", "primes" ], "Title": "Prime power mathematical problem in Python" }
243488
<p>I wrote the following script which allows an element to be dragged and resized. I am mainly looking for suggestions regarding my JavaScript. In the future, it will also be possible to control the element externally. So the <code>init()</code> function is only temporary. </p> <p><a href="https://teiem.github.io/wm/" rel="nofollow noreferrer">Github Live Page</a><br> <a href="https://github.com/Teiem/wm" rel="nofollow noreferrer">Code on Github</a> </p> <p>JavaScript:</p> <pre><code>"use strict"; const wm = (contentNode, {resizable = true, minWidth = 100, minHeight = 100, resizewidth = 12, zIndex = 0, snapDist = 10, blurPreviewBg = true} = {}) =&gt; { const windowNode = document.createElement("div"); const resize = document.createElement("div"); const preview = document.createElement("div"); const _state = { windowIsMaximized: false, previewIsActive: false, isChanging: false, }; const _NeedsUpdate = { preview: false, window: false, }; let _windowData = { offsetX: 0, offsetY: 0, width: 0, height: 0, }; const _startState = { x: 0, y: 0, relX: 0, relY: 0, width: 0, height: 0, isLeft: false, isRight: false, isTop: false, isBottom: false, isDragging: true, }; let _nextPos = { offsetX: 0, offsetY: 0, width: 0, height: 0, }; let _previewData = { offsetX: 0, offsetY: 0, width: 0, height: 0 }; let _updateScheduled = false; const _scheduleUpdate = () =&gt; { if (_updateScheduled) return; _updateScheduled = true; requestAnimationFrame(() =&gt; { _updateScheduled = false; _testBorder(); _applyStyleWindow(); }) }; const _applyStyleWindow = () =&gt; { windowNode.style.willChange = _state.isChanging ? "transform, width, height" : ""; // does this cause some error? if (!_state.isChanging) return; preview.style.opacity = +_state.previewIsActive; if (_state.previewIsActive &amp;&amp; _NeedsUpdate.preview) { _NeedsUpdate.preview = false; _setElPos(preview, _previewData, false); preview.classList.add("_wmPreviewTransition"); } if (_state.windowIsMaximized) return; if (_startState.isDragging &amp;&amp; !_NeedsUpdate.window) { _windowData.offsetX = _nextPos.offsetX; _windowData.offsetY = _nextPos.offsetY; _setElPos(windowNode, {offsetX: _windowData.offsetX, offsetY: _windowData.offsetY}, true); } else { _NeedsUpdate.window = false; const minWidthReached = _nextPos.width &lt;= minWidth; const minHeightReached = _nextPos.height &lt;= minHeight; const newWindowData = { width: minWidthReached ? minWidth : _nextPos.width, height: minHeightReached ? minHeight : _nextPos.height, offsetX: !_startState.isDragging &amp;&amp; minWidthReached ? _startState.isLeft ? _startState.x - _startState.relX + _startState.width - minWidth : _windowData.offsetX : _nextPos.offsetX, offsetY: !_startState.isDragging &amp;&amp; minHeightReached ? _startState.isTop ? _startState.y - _startState.relY + _startState.height - minHeight : _windowData.offsetY : _nextPos.offsetY, } _windowData = {...newWindowData, isMaximized: false}; _setElPos(windowNode, newWindowData, true); } }; const _syncStyleWindow = () =&gt; { _setElPos(windowNode, _windowData, true); _nextPos = {..._windowData}; }; const _testBorder = () =&gt; { if (!_startState.isDragging) return; const borderTLBR = _getBorderTLBR(); if (borderTLBR.top || borderTLBR.left || borderTLBR.bottom || borderTLBR.right) { if (!_state.previewIsActive) { preview.classList.remove("_wmPreviewTransition"); _setElPos(preview, _windowData); // force reflow for transition void(preview.offsetHeight); } _previewData = {..._elWindowDataFromCorners(borderTLBR)}; _state.previewIsActive = true; _NeedsUpdate.preview = true; } else { _state.previewIsActive = false; } }; /*----- EventListeners -----*/ const mouseDown = e =&gt; { _state.isChanging = true; _NeedsUpdate.window = true; document.addEventListener("mousemove", move); document.addEventListener("mouseup", mouseUp, {once: true}); if (_state.windowIsMaximized) { _state.windowIsMaximized = false; _startState.relX = (e.clientX - _previewData.offsetX / 100 * window.innerWidth) / (_previewData.width / 100 * window.innerWidth) * _windowData.width; _startState.relY = (e.clientY - _previewData.offsetY / 100 * window.innerHeight) / (_previewData.height / 100 * window.innerHeight) * _windowData.height; } else { _startState.relX = e.clientX - _windowData.offsetX; _startState.relY = e.clientY - _windowData.offsetY; } _startState.isDragging = true; }; const move = e =&gt; { _nextPos.offsetX = e.clientX - _startState.relX; _nextPos.offsetY = e.clientY - _startState.relY; _scheduleUpdate(); }; const mouseUp = e =&gt; { _state.isChanging = false; document.removeEventListener("mousemove", move); const borderTLBR = _getBorderTLBR(); if (borderTLBR.top || borderTLBR.left || borderTLBR.bottom || borderTLBR.right) { _state.windowIsMaximized = true; _setElPos(windowNode, _elWindowDataFromCorners(borderTLBR), false); } }; const resizeMouseDown = e =&gt; { _state.isChanging = true; document.addEventListener("mousemove", resizeMouseMove); document.addEventListener("mouseup", resizeMouseUp, {once: true}); _startState.width = _windowData.width; _startState.height = _windowData.height; _startState.x = e.clientX; _startState.y = e.clientY; _startState.relX = e.clientX - _windowData.offsetX; _startState.relY = e.clientY - _windowData.offsetY; _startState.isTop = _startState.relY &lt;= 0; _startState.isLeft = _startState.relX &lt;= 0; _startState.isRight = _startState.relX &gt;= _windowData.width; _startState.isBottom = _startState.relY &gt;= _windowData.height; // only necessary if last was top/left and new if bottom/right to reset _nextPos.offsetX/Y _nextPos.offsetX = e.clientX - _startState.relX; _nextPos.offsetY = e.clientY - _startState.relY; _startState.isDragging = false; }; const resizeMouseMove = e =&gt; { const widthChange = e.clientX - _startState.x; const heightChange = e.clientY - _startState.y; if (_startState.isTop) { _nextPos.height = _startState.height - heightChange; _nextPos.offsetY = e.clientY - _startState.relY; } if (_startState.isRight) { _nextPos.width = _startState.width + widthChange; } if (_startState.isBottom) { _nextPos.height = _startState.height + heightChange; } if (_startState.isLeft) { _nextPos.width = _startState.width - widthChange; _nextPos.offsetX = e.clientX - _startState.relX; } _scheduleUpdate(); }; const resizeMouseUp = () =&gt; { _state.isChanging = false; document.removeEventListener("mousemove", resizeMouseMove); }; const resizeMouseMoveHover = e =&gt; { const relX = e.clientX - _windowData.offsetX; const relY = e.clientY - _windowData.offsetY; const left = relX &lt;= 0; const top = relY &lt;= 0; const right = relX &gt;= _windowData.width; const bottom = relY &gt;= _windowData.height; if ((left &amp;&amp; top) || (right &amp;&amp; bottom)) { resize.style.cursor = "nwse-resize"; } else if ((left &amp;&amp; bottom) || (right &amp;&amp; top)) { resize.style.cursor = "nesw-resize"; } else if (left || right) { resize.style.cursor = "ew-resize"; } else { resize.style.cursor = "ns-resize"; } }; /* ----- Util ----- */ const _setElPos = (el, {offsetX, offsetY, width, height} = {}, absolute = true) =&gt; { if (offsetX != undefined || offsetY != undefined) el.style.transform = `translate(${offsetX}${absolute ? "px" : "vw"}, ${offsetY}${absolute ? "px" : "vh"})`; if (width != undefined) el.style.width = width + (absolute ? "px" : "vw"); if (height != undefined) el.style.height = height + (absolute ? "px" : "vh"); }; const _elWindowDataFromCorners = ({left, right, bottom, top}) =&gt; ({ width: left || right ? 50 : 100, height: bottom || top &amp;&amp; (left || right) ? 50 : 100, offsetX: right ? 50 : 0, offsetY: bottom ? 50 : 0 }) const _getBorderTLBR = () =&gt; { const x = _nextPos.offsetX + _startState.relX; const y = _nextPos.offsetY + _startState.relY; return { left: x &lt;= snapDist, top: y &lt;= snapDist, right: x &gt;= window.innerWidth - snapDist, bottom: y &gt;= window.innerHeight - snapDist, }; }; /* ----- External/Initialization ----- */ const _init = () =&gt; { const {left, top, width, height} = contentNode.getBoundingClientRect(); _windowData.offsetX = left; _windowData.offsetY = top; _windowData.width = width; _windowData.height = height; _syncStyleWindow(); /* Wrap */ contentNode.parentNode.insertBefore(windowNode, contentNode); windowNode.appendChild(contentNode); contentNode.style.width = "100%"; contentNode.style.height = "100%"; contentNode.addEventListener("mousedown", mouseDown); windowNode.classList.add("_wm"); windowNode.style.setProperty("--zIndex", zIndex); document.body.appendChild(preview); preview.classList.add("_wmPreview"); if (blurPreviewBg) preview.classList.add("_wmPreviewBlurBg"); /* Resize */ if (!resizable) return; contentNode.parentNode.insertBefore(resize, contentNode); resize.classList.add("_wmResizer"); windowNode.style.setProperty("--resizeWidth", resizewidth + "px"); resize.addEventListener("mousemove", resizeMouseMoveHover); resize.addEventListener("mousedown", resizeMouseDown); }; _init(); return { // ... }; }; wm(document.getElementById("window")) </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-06T18:07:50.947", "Id": "243492", "Score": "2", "Tags": [ "javascript" ], "Title": "Draggable and resizeable element in JavaScript" }
243492
<p>I have a simple macro moving data from Teradata to Excel. The process normally takes me 10 minutes to perform manually, however the macro can run for hours sometimes. This is making the macro seems counterproductive. But I still want to give it a chance.</p> <p>Manually, I would just simply paste the sql to teradata, and copy/paste the results to Excel. This takes about 10 mins including the teradata run time.</p> <p>Can someone suggest any ways to improve the performance? I'm still quite new to macros, so using simple language would be very much appreciated.</p> <p>Edit - Should I put all the sql codes in cell A1 instead of A1-A44? (It didn't seem to work).</p> <pre><code>Option Explicit Global glbUN As String Global glbPWD As String Global cnEDW As ADODB.Connection Sub RefreshData() Call Open_EDWDatabase DoEvents Call BuildCode DoEvents End Sub Public Sub Open_EDWDatabase() Set cnEDW = New ADODB.Connection If glbUN = &quot;&quot; Or glbPWD = &quot;&quot; Then 'Open login screen and center the form for people with 2 monitors UserForm1.StartUpPosition = 0 UserForm1.Left = Application.Left + (0.5 * Application.Width) - (0.5 * UserForm1.Width) UserForm1.Top = Application.Top + (0.5 * Application.Height) - (0.5 * UserForm1.Height) UserForm1.Show 1 End If cnEDW.ConnectionString = &quot;Driver={Teradata};Persist Security Info=False;User ID=&quot; &amp; glbUN &amp; &quot;;Pwd=&quot; &amp; glbPWD &amp; &quot;;Data Source=teradata_PRD&quot; cnEDW.Open End Sub Public Sub Close_EDWDatabase() cnEDW.Close Set cnEDW = Nothing End Sub Sub BuildCode() Dim cmd As ADODB.Command Dim rs As ADODB.Recordset Dim LastLineofSQL As Long Dim LastLineofSQL2 As Long Dim strQry As String Dim strQry2 As String Dim x, y As Long Dim OutputAddress As String Dim iCol As Long LastLineofSQL = 44 strQry = &quot;&quot; Set cmd = New ADODB.Command cmd.ActiveConnection = cnEDW cmd.CommandTimeout = 20000000 For x = 1 To LastLineofSQL strQry = strQry + Sheets(&quot;Codes&quot;).Cells(x, 1).Value If InStr(strQry, &quot;;&quot;) &lt;&gt; 0 Then cmd.CommandText = strQry Set rs = cmd.Execute If x = LastLineofSQL Then Sheets(&quot;Data&quot;).Range(&quot;B2&quot;).CopyFromRecordset rs End If strQry = &quot;&quot; DoEvents Else If Right$(strQry, 2) &lt;&gt; vbCrLf Then strQry = strQry + vbCrLf End If End If Next x End Sub </code></pre> <p>Here's the SQL for Teradata -</p> <pre><code> SELECT Trim(pln_id) AS pln_id ,Trim(lob) AS line_of_bus ,eom ,Trim(Extract(YEAR From eom)) AS &quot;year&quot; ,Trim(pln_network) AS ACA_network ,Trim(prod_typ_cd) AS prod_type ,Trim(aca_metal) AS ACA_metal ,Trim(aca_exchange_ind) AS ACA_exchange_ind ,Trim(pln_rating_area) AS rating_area_name ,Trim(risk_bucket) AS risk_bucket ,Trim(hcc_cnt) AS hcc_cnt ,Trim(duration) AS duration ,Cast(Sum(CASE WHEN members &lt;&gt; 0 THEN age ELSE 0 END) AS DECIMAL(18,2)) AS total_age ,Cast(Sum(CASE WHEN members &lt;&gt; 0 AND dxcgEZ_risk_score IS NOT NULL THEN age_factor ELSE 0 END) AS DECIMAL(18,2)) AS total_age_fctr ,Cast(Sum(risk_adj) AS DECIMAL(18,4)) AS risk_adj ,Cast(Sum(comp_reins) AS DECIMAL(18,4)) AS comp_reins ,Sum(contracts) AS contracts ,Sum(members) AS members ,Sum(premium) AS premium ,Sum(csr_pd) AS csr_payment ,Sum(csr_ibnp) AS csr_ibnp_payment ,Sum(capitation) AS capitation ,Cast(Sum(inc_clms) AS DECIMAL(18,4)) AS inc_clms ,Cast(Sum(inc_paid_clms) AS DECIMAL(18,4)) AS inc_paid_clms ,Cast(Sum(inc_clms_med) AS DECIMAL(18,4)) AS inc_clms_med ,Cast(Sum(inc_paid_clms_med) AS DECIMAL(18,4)) AS inc_paid_clms_med ,Cast(Sum(inc_clms_rx) AS DECIMAL(18,4)) AS inc_clms_rx ,Cast(Sum(inc_paid_clms_rx) AS DECIMAL(18,4)) AS inc_paid_clms_rx ,Cast(Sum(CASE WHEN members &lt;&gt; 0 THEN dxcgEZ_risk_score ELSE 0 END) AS DECIMAL(18,4)) AS total_risk_score ,Sum(CASE WHEN dxcgEZ_risk_score IS NOT NULL AND members &lt;&gt; 0 THEN members ELSE 0 END) AS mbrs_w_risk ,Cast(Sum(rebates) AS DECIMAL(18,4)) AS total_rebates FROM Table1 WHERE premium IS NOT NULL AND eom &gt;= (SELECT Add_Months(Max(eom) + 1, -39) - 1 FROM Table1 ) And eom &lt;= (SELECT Add_Months(Max(eom) + 1, -1) - 1 FROM Table1 ) GROUP BY 1,2,3,4,5,6,7,8,9,10,11,12; </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-06T18:49:30.287", "Id": "477902", "Score": "0", "body": "Your title could apply to basically every post. Based on this site's rules, the name should state what the code does. That you are especially interested in performance tips would go into the text itself. This really helps reviewers to discover which posts they want to review. So, could you please edit this post's title so that it reflects what the code does?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-06T21:53:34.340", "Id": "477920", "Score": "0", "body": "Hours as opposed to minutes is quite stark, especially for a language like VBA which is designed to help automate manual tasks (Visual Basic for Applications). I would be interested to hear what your usual manual process would be, to see if that sheds any light on the performance issues - perhaps you could edit your question with a brief description?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-08T19:01:29.130", "Id": "478089", "Score": "0", "body": "Thank you for the comments. I have edited the post. Thanks!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-09T09:20:10.577", "Id": "478127", "Score": "0", "body": "@Pumpkin Right, so if I understand correctly, your code loops through `A1:A44` concatenating the values into a query string `strQry = strQry + [...]`. If the current query string terminates: `InStr(strQry, \";\")` then execute it, and if it's the last query then copy the results to the sheet. Is that right? I think the slowness is likely to be coming from executing the SQL line by line like this, although writing to the sheet may be slow too; if you want some help diagnosing this I think you'll need to show the SQL statement you execute as well as what your DB looks like - context is everything!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-09T20:36:35.517", "Id": "478208", "Score": "0", "body": "Hi Greedo, Yes, you're right ! And the sql statement is very simple, it just simply pulls different fields from a table in Teradata without any joins. That normally takes about 20 seconds for Teradata to run. So that piece is probably not an issue. So are you saying that I should put the whole sql query in cell A1 instead of A1-A44?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-15T17:50:54.703", "Id": "478847", "Score": "0", "body": "The question that I think needs to be answered first is, how many times is the line `Set rs = cmd.Execute` being executed. AFAICT it's only being called once. I would guess that to be the real bottleneck; concatenating 44 strings, even while reading them via the Excel Automation API, doesn't seem to me to be the issue here. We really need to see the SQL statement." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-16T16:16:04.857", "Id": "479003", "Score": "0", "body": "Ok. I have added the sql statement. Thank you!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-18T20:54:15.087", "Id": "479284", "Score": "0", "body": "@ZevSpitz I have added the sql statement. I have also tried to whole the whole sql statement in cell A1, but that didn't help." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-18T21:48:18.510", "Id": "479287", "Score": "0", "body": "(NB -- I know nothing about Teradata.) Next question: The same query takes about 20 seconds to run directly against Teradata. How have you run the query that it only takes 20 seconds? // It would seem as though something in the communication between VBA and Teradata is the issue, either the programming layers of COM, VBA, Excel Automation; or the sheer volume of data returned. Is there some kind of networking involved?" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "9", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-06T18:09:18.660", "Id": "243493", "Score": "3", "Tags": [ "beginner", "vba", "excel" ], "Title": "Looking for more efficient VBA to Move data from Teradata to Excel" }
243493
<p>I created a game which can play tic-tac-toe with: 0 players (AI vs AI), 1 player (human vs AI) or 2 player (human vs human). Here is the AI function which wraps around my innermost function. This evaluates all the candidate board positions and returns the best move.</p> <p>I searched to make sure this has not been implemented before.</p> <p>Could I have feedback on my Python code in <a href="https://github.com/jcoombes/tictactoe/tree/aeadcc95be9b0ab8ac4a8bbe91d030897750b12e" rel="nofollow noreferrer">my GitHub repo</a>.</p> <ul> <li>I would be particularly interested in knowing how to make my code clearer to read and understand.</li> <li><p>I would be interested to know how I could improve this code, or the code which evaluates a given boardstate. For example I would like to make <code>score_one_gamestate</code> be more elegant.</p></li> <li><p>I have a vague feeling that I could use something instead of creating many deepcopies of the game board in the <code>score_one_gamestate</code> function. But I do not know how to do this. Additionally I do not know whether attempting this would even be a good idea.</p></li> </ul> <pre><code>def optimal_ai_move(board: np.array, x_or_o: str, available: list): """ The heart of the robot brain. Given a board state, will return the optimal move. :param board: numpy array of the board. :param x_or_o: which side is the AI playing on? #This isn't exactly true in recursive calls. :param available: available[(row, col)] = True, if the space hasn't been taken yet. :return: best_move: (row, col). The move with the greatest number of simulated wins. """ possibility_dict = {} for candidate_move in available: deeper = copy.deepcopy(board) deeper[candidate_move] = x_or_o available = find_available_moves(deeper) possibility_dict[candidate_move] = score_one_gamestate(deeper, turn_flipper(x_or_o), available, x_or_o, score_dict=None) metric_dict = {candidate_move: (score_dict['wins'] + score_dict['draws']) / sum(score_dict.values()) for candidate_move, score_dict in possibility_dict.items()} best_move = max(metric_dict, key=metric_dict.get) return best_move, possibility_dict def score_one_gamestate(board: np.array, x_or_o: str, available: list, ai_player_choice: str, score_dict=None, weight=1) -&gt; int: if score_dict is None: score_dict = {'wins': 0, 'losses': 0, 'draws': 0} is_finished = game_over(board) if is_finished == ai_player_choice: # This might be wrong, we want ai_player_choice score_dict['wins'] += 1 / weight return score_dict elif is_finished == turn_flipper(ai_player_choice): score_dict['losses'] += 1 / weight return score_dict elif is_finished == 'draw': score_dict['draws'] += 1 / weight return score_dict else: weight *= len(available) for candidate_move in available: deeper = copy.deepcopy(board) deeper[candidate_move] = x_or_o available_moves = find_available_moves(deeper) score_dict = score_one_gamestate(deeper, turn_flipper(x_or_o), available_moves, ai_player_choice, score_dict, weight) return score_dict </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-06T18:50:45.973", "Id": "243494", "Score": "3", "Tags": [ "python", "python-3.x", "recursion", "tree", "tic-tac-toe" ], "Title": "Noughts and Crosses Terminal Game with AI" }
243494
<p>I am working on a coding challenge for Tic Tac Toe. I am calculating the results and inserting them into the database.</p> <p>However I have a long and messy if statement, which checks if the array's values match a valid win for O or X. I feel like it could be refactored down but I'm unsure on how to approach this.</p> <pre><code> /** @var int */ protected $xWins = 0; /** @var int */ protected $oWins = 0; /** @var int */ protected $draws = 0; /** */ public function __construct() { // creates a new database on object creation $this-&gt;database = new Database(); } public function winner(string $input) { $input = str_replace("\\n", "", $input); $length = strlen($input); for ($i = 1; $i &lt;= $length; $i++) { if ($i % 9 === 0) { $result = substr($input, $i - 9, 9); if ($result[0] === "X" &amp;&amp; $result[1] === "X" &amp;&amp; $result[2] === "X") { $winner = "X"; $this-&gt;database-&gt;insert($winner, $result); $this-&gt;xWins++; } else if ($result[3] === "X" &amp;&amp; $result[4] === "X" &amp;&amp; $result[5] === "X") { $winner = "x"; $this-&gt;database-&gt;insert($winner, $result); $this-&gt;xWins++; } else if ($result[6] === "X" &amp;&amp; $result[7] === "X" &amp;&amp; $result[8] === "X") { $winner = "X"; $this-&gt;database-&gt;insert($winner, $result); $this-&gt;xWins++; } else if ($result[0] === "X" &amp;&amp; $result[3] === "X" &amp;&amp; $result[6] === "X") { $winner = "X"; $this-&gt;database-&gt;insert($winner, $result); $this-&gt;xWins++; } else if ($result[1] === "X" &amp;&amp; $result[4] === "X" &amp;&amp; $result[7] === "X") { $winner = "X"; $this-&gt;database-&gt;insert($winner, $result); $this-&gt;xWins++; } else if ($result[2] === "X" &amp;&amp; $result[5] === "X" &amp;&amp; $result[8] === "X") { $winner = "X"; $this-&gt;database-&gt;insert($winner, $result); $this-&gt;xWins++; } else if ($result[0] === "X" &amp;&amp; $result[4] === "X" &amp;&amp; $result[8] === "X") { $winner = "X"; $this-&gt;database-&gt;insert($winner, $result); $this-&gt;xWins++; } else if ($result[2] === "X" &amp;&amp; $result[4] === "X" &amp;&amp; $result[6] === "X") { $winner = "X"; $this-&gt;database-&gt;insert($winner, $result); $this-&gt;xWins++; } // checks for O lines else if ($result[0] === "O" &amp;&amp; $result[1] === "O" &amp;&amp; $result[2] === "O") { $winner = "o"; $this-&gt;database-&gt;insert($winner, $result); $this-&gt;oWins++;; } else if ($result[3] === "O" &amp;&amp; $result[4] === "O" &amp;&amp; $result[5] === "O") { $winner = "o"; $this-&gt;database-&gt;insert($winner, $result); $this-&gt;oWins++; } else if ($result[6] === "O" &amp;&amp; $result[7] === "O" &amp;&amp; $result[8] === "O") { $winner = "o"; $this-&gt;database-&gt;insert($winner, $result); $this-&gt;oWins++; } else if ($result[0] === "O" &amp;&amp; $result[3] === "O" &amp;&amp; $result[6] === "O") { $winner = "o"; $this-&gt;database-&gt;insert($winner, $result); $this-&gt;oWins++; } else if ($result[1] === "O" &amp;&amp; $result[4] === "O" &amp;&amp; $result[7] === "O") { $winner = "O"; $this-&gt;database-&gt;insert($winner, $result); $this-&gt;oWins++; } else if ($result[2] === "O" &amp;&amp; $result[5] === "O" &amp;&amp; $result[8] === "O") { $winner = "O"; $this-&gt;database-&gt;insert($winner, $result); $this-&gt;oWins++; } else if ($result[0] === "O" &amp;&amp; $result[4] === "O" &amp;&amp; $result[8] === "O") { $winner = "O"; $this-&gt;database-&gt;insert($winner, $result); $this-&gt;oWins++; } else if ($result[2] === "O" &amp;&amp; $result[4] === "O" &amp;&amp; $result[6] === "O") { $winner = "O"; $this-&gt;database-&gt;insert($winner, $result); $this-&gt;oWins++; // checks for draw } else { $winner = "Draw"; $this-&gt;database-&gt;insert($winner, $result); $this-&gt;draws++; } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-06T22:41:58.180", "Id": "477925", "Score": "1", "body": "May we see a realistic sample input (a couple of games passed to this method)? I think I can reverse engineer one from your code logic, but it would be better if I could have my assumptions confirmed. Why aren't x's and o's saved to the database consistently (regarding upper/lowercase)?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-06T22:50:36.670", "Id": "477927", "Score": "0", "body": "Are unused cells of the gameboard filled with a visible character or are spaces used? I am assuming the game short-circuits to a winner as soon as a winner is determined." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-07T08:31:10.900", "Id": "477949", "Score": "0", "body": "In your next questions, please post the _complete_ code of a file. This code is missing the `class` declaration, which makes it harder than necessary for potential reviewers to run your code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-07T10:28:18.803", "Id": "477951", "Score": "1", "body": "Please don't modify your code after receiving answers." } ]
[ { "body": "<p>I wouldn't call myself an expert, but I finished a tic-tac-toe project today as well, I was writing Python, so my suggestions might not be idiomatic for PHP - but I think this will apply to your situation as well.</p>\n\n<p>Your intuition is solid. Every time you find yourself using cut and paste, this is probably a sign you can put the code inside a function.</p>\n\n<p>Idea One:</p>\n\n<p>For example, create a function inside winner - this contains the valid win matching mode. this function takes a parameter \"x_or_o\" - which is either a string 'x' or a string 'o'.</p>\n\n<p>This should be a great start because it will cut your checking code in half. Let's see if we can do better.</p>\n\n<p>Idea Two:</p>\n\n<p>I notice that your code doesn't care about whether a player has a winning row, or a winning column. In this case, you can assign your logical operators to a variable.\ne.g.</p>\n\n<pre><code>public function win_check(string $x_or_o) {\n top_row_win = $result[1] === x_or_o &amp;&amp; $result[4] === x_or_o &amp;&amp; $result[7] === x_or_o\n mid_row_win = $result[2] === x_or_o &amp;&amp; $result[5] === x_or_o &amp;&amp; $result[8] === x_or_o\n ...\n\n win = (top_row_win || mid_row_win || bottom_row_win || left_col_win || mid_col_win || right_col_win || diagonal_win || off_diagonal_win)\n\n if (win) {\n $winner = x_or_o;\n $this-&gt;database-&gt;insert($winner, $result)\n if (x_or_o == 'x'){\n xWins++ \n}\n elif (x_or_o == 'o') {\n oWins++\n}\n}\n}\n\n//Then in your outer scope, your win_check function will be called from winner like this.\n\nwin_check(x)\nwin_check(o)\n</code></pre>\n\n<p>Idea Three:</p>\n\n<p>In my project, I used a 2d array and used index slicing to do this more elegantly. I do not know what array slicing or index slicing is possible in PHP.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-06T21:55:15.810", "Id": "243497", "ParentId": "243496", "Score": "0" } }, { "body": "<p>This reminds me of a Battleship gameboard parser that I once designed. <a href=\"https://stackoverflow.com/a/47595575/2943403\">https://stackoverflow.com/a/47595575/2943403</a> a rare case where regex outperforms non-regex techniques.</p>\n\n<p>I am going to recommend a class variable that is an associative array so that variable variables can be avoided. By filling each subarray with the respective <code>$result</code> strings, you compress your required data into a single structure instead of having a collection of results and a win/draw incrementer.</p>\n\n<pre><code>protected $outcomes = [\n 'X' =&gt; [],\n 'O' =&gt; [],\n 'D' =&gt; []\n];\n</code></pre>\n\n<p>Your <code>str_replace()</code>, <code>strlen()</code>, and subsequent modulus-based looping is definitely working too hard. It will be far simpler to break the string into substrings by using:</p>\n\n<pre><code>foreach (explode('\\n', $input) as $result) {\n</code></pre>\n\n<p>Now that game results are properly separated, you can use a regular expression to concisely parse the string and return the outcome as a single letter.</p>\n\n<p>A \"branch reset\" (<code>(?|...)</code>) is used so that the matching character is always <code>\\1</code> throughout each branch versus <code>\\1</code>, <code>\\2</code>, <code>\\3</code>, <code>\\4</code>. The <code>x</code> pattern flag allows me to use spaces and comments to separate and explain pattern logic.</p>\n\n<pre><code>public assessGames($input) {\n foreach (explode('\\n', $input) as $result) {\n $outcome = preg_match(\n '~(?|\n ^(?:.{3}){0,2}(\\S)\\1{2} #horizontal win\n |(\\S)(?:.{2}\\1){2} #or vertical win\n |^(\\S)(?:.{3}\\1){2} #or diagonalLTR win\n |^.{2}(\\S)(?:.\\1){2} #or diagonalRTL win\n )~x',\n $result,\n $match\n )\n ? $match[1] // X or O\n : 'D';\n $this-&gt;outcomes[$outcome][] = $result;\n }\n}\n</code></pre>\n\n<p>Note, if you are parsing a high volume of games, you may like to refactor this approach to skip the explode&amp;iterate step and make a single <code>preg_match_all()</code> call.</p>\n\n<p>Now that your outcomes are fully evaluated, then saved to the class variable, make as few trips to the database as possible. I always discourage making looped trips to the db. I don't know what utilities you have in your database class, but using a batch insert technique will be beneficial here.</p>\n\n<p>If/When you need to know how many wins/losses/draws a player has, just count the elements in the class variable.</p>\n\n<p>Granted, the four-part pattern that I have designed may seem like incomprehensible magic to someone who is not familiar with the syntax, but by studying the pattern explanation at regex101.com, you can learn the full meaning. I have labeled each pattern to aid in understanding what each is doing.</p>\n\n<p>Be sure to break your class functionality into separate methods so that each method has a \"single responsibility\".</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-11T22:37:29.367", "Id": "478397", "Score": "0", "body": "You have \"hardcoded\" variable names like `$xWins` and `$oWins`. For my answer to cooperate with your variable naming convention, I would need to take my `$match[1]` and use dynamic variable syntax. https://stackoverflow.com/questions/9257505/using-braces-with-dynamic-variable-names-in-php This (anti-pattern) is almost always a symptom of bad code design. To prevent this, I am naming three keys in an array to store the outcomes. This is a clean and logic design because the values are sensibly related." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-11T23:28:13.013", "Id": "478405", "Score": "0", "body": "You can replace my \"you\" for \"the OP\" then. I am trying to explain. What is still foggy? I don't want to keep the OP's indidualized variables because then my `preg_` result would need to be like `++${ strtolower($match[1]) . 'Wins'};` and that is a mess. I am recommending a wholly refined storage technique and a change to what exactly is being stored in the class level variable." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-11T23:55:20.603", "Id": "478407", "Score": "0", "body": "No, I am not calling them the same thing. Variable variables are the problem. An associative array is the solution/replacement. I don't recommend the use of `$xWins` and `$oWins` -- I am recommending an associative array to eliminate those variables. `protected $outcomes`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-12T00:03:33.827", "Id": "478409", "Score": "0", "body": "No bother, maybe I didn't explain myself very well." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-07T00:10:27.747", "Id": "243502", "ParentId": "243496", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-06T19:10:17.277", "Id": "243496", "Score": "3", "Tags": [ "php", "programming-challenge", "array", "tic-tac-toe" ], "Title": "Checking if naughts or crosses win in Tic Tac Toe" }
243496
<p>To learn React I've ported a Vue combobox component into React. Because of the project it could be used in uses React 16.2 it doesn't use features like <code>React.createRef()</code> or hooks.</p> <pre><code>import React, { Component } from 'react' import PropTypes from 'prop-types' class ComboBox extends Component { constructor (props) { super(props) this.state = { active: 0, shown: false, value: props.value } this.root = null this.textbox = null this.options = new Array(props.items.length) this.setRootRef = element =&gt; this.root = element this.setTextboxRef = element =&gt; this.textbox = element this.setOptionsRef = (index, element) =&gt; this.options[index] = element this.listenForClickOut = this.listenForClickOut.bind(this) this.handleChange = this.handleChange.bind(this) this.handleClick = this.handleClick.bind(this) this.handleTextboxKeypress = this.handleTextboxKeypress.bind(this) this.handleListboxKeypress = this.handleListboxKeypress.bind(this) this.handleRootKeydown = this.handleRootKeydown.bind(this) } get items () { return this.props.items } componentDidMount () { window.addEventListener('click', this.listenForClickOut) } componentWillUnmount () { window.removeEventListener('click', this.listenForClickOut) } /* Event handlers */ listenForClickOut (click) { if (!this.root.contains(click.target)) { this.hide() } } handleChange (event) { this.setState({ value: event.target.value, }) } handleTextboxKeypress (event) { switch (event.key) { case 'ArrowDown': this.open() break } } async handleListboxKeypress (event) { switch (event.key) { case 'ArrowUp': await this.up() break case 'ArrowDown': await this.next() this.focusOption() break } } handleRootKeydown (event) { switch (event.key) { case 'Tab': case 'Escape': this.close() break } } handleClick (i) { this.props.onSelect(this.items[i]) this.close() } /* Position methods */ first () { this.setState({ active: 0 }) } previous () { return new Promise(resolve =&gt; { const previous = this.state.active - 1 if (previous &gt;= 0) { this.setState({ active: previous }, resolve) } }) } next () { return new Promise(resolve =&gt; { const max = this.items.length - 1 const next = this.state.active + 1 if (next &lt;= max) { this.setState({ active: next }, resolve) } }) } /* List control methods */ async open () { if (this.items.length === 0) { return } this.first() await this.show() this.focusOption() } close () { this.hide() this.focusTextbox() } show () { return new Promise(resolve =&gt; { this.setState({ shown: true }, resolve) }) } hide () { this.setState({ shown: false }) } async up () { if (this.state.active === 0) { this.close() return } await this.previous() this.focusOption() } async down () { await this.next() this.focusOption() } focusTextbox () { this.textbox.focus() } focusOption () { const index = this.state.active this.options[index].focus() } render () { const { items } = this.props const { active, shown, value } = this.state return ( &lt;div ref={this.setRootRef} onKeyDown={this.handleRootKeydown}&gt; &lt;input aria-autocomplete="list" aria-expanded={shown} autoComplete="off" autoCapitalize="none" className="form-control" ref={this.setTextboxRef} role="combobox" value={value} onChange={this.handleChange} onKeyDown={this.handleTextboxKeypress} /&gt; {shown &amp;&amp; &lt;div className="list-group" role="listbox" onKeyDown={this.handleListboxKeypress}&gt; {items.map((item, i) =&gt; ( &lt;button aria-selected={active === i} className={`list-group-item list-group-item-action py-1 ${active === i ? 'active' : ''}`} key={i} ref={element =&gt; this.setOptionsRef(i, element)} role="option" tabIndex="-1" onClick={() =&gt; this.handleClick(i)} &gt; {item} &lt;/button&gt; ))} &lt;/div&gt; } &lt;div aria-live="polite" role="status" className="sr-only"&gt;{items.length} results available.&lt;/div&gt; &lt;/div&gt; ) } } ComboBox.propTypes = { items: PropTypes.array, value: PropTypes.string, onSelect: PropTypes.func, } ComboBox.defaultProps = { items: [], value: '', onSelect: () =&gt; ({}) } export default ComboBox </code></pre> <p><a href="https://codepen.io/jmsfwk/full/dyGoZPz" rel="nofollow noreferrer">Demo on codepen</a></p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-06T22:08:05.183", "Id": "243498", "Score": "2", "Tags": [ "javascript", "react.js" ], "Title": "Accessible React combobox" }
243498
<p>I have collected a <code>.csv</code> file with some statistics about football games in the following format. <a href="https://www.dropbox.com/s/kpqotuuiojj1igr/epl%2018_19%20games.csv?dl=0" rel="noreferrer">Here is a sample <code>.csv</code> file</a>.</p> <pre><code>Date,Home,Away,HomeShots,AwayShots,HomeBT,AwayBT,HomeCrosses,AwayCrosses,HomeCorners,AwayCorners,HomeGoals,AwayGoals,HomeXG,AwayXG </code></pre> <p>My code does the following: </p> <ul> <li>Calculate a summary of statistics for the given subset of games,</li> <li>Calculate a summary of statistics for the each individual team,</li> <li>Filter games by date or by range of some stat, and</li> <li>Print a summary as <code>html</code> or <code>csv</code>.</li> </ul> <p>I have some questions about my code.</p> <ol> <li>How should I write unit tests for checking the correctness of functions that calculate stats? </li> <li>How to make a function that prints output to work with an arbitrary list of fields, instead of a particular one? Since I print a lot of fields, passing them one by one is tedious. Maybe I could create some common templates and pass one of them?</li> <li>Can I simplify <code>calculate_team_stats()</code>? Maybe it can be improved by using <code>Counter()</code> or some third party library.</li> </ol> <p>Any or all other feedback is welcomed!</p> <pre><code>import csv import datetime from collections import namedtuple, defaultdict from statistics import mean FILENAME = 'epl 18_19 games.csv' Game = namedtuple('Game', ['Date', 'Home', 'Away', 'HomeShots', 'AwayShots', 'HomeBT', 'AwayBT', 'HomeCrosses', 'AwayCrosses', 'HomeCorners', 'AwayCorners', 'HomeGoals', 'AwayGoals', 'HomeXG', 'AwayXG']) def csv_to_list_of_games(filename=FILENAME): """ Makes a list of Game from a csv file. """ games = [] with open(FILENAME) as f: csv_reader = csv.reader(f) next(csv_reader) for game in csv_reader: date = game[0].split('.') year = int(date[2]) month = int(date[1]) day = int(date[0]) date_object = datetime.date(year, month, day) games.append(Game(date_object, *game[1:])) return games def get_teams_list(games): """ Makes a list of teams in the given list of games. """ return list(set([game.Home for game in games] + [game.Away for game in games])) def get_games_by_team(teamname, games): """ Returns a list of Game featuring the given team. """ return [game for game in games if game.Home == teamname or game.Away == teamname] def calculate_team_stats(teams, games): """ Calculates team stats for each team in the list. """ team_stats = dict() for team in teams: team_stats[team] = defaultdict(int) team_stats[team]['HomeShotsFor'] = sum(int(game.HomeShots) for game in games if game.Home == team) team_stats[team]['HomeShotsAgainst'] = sum(int(game.AwayShots) for game in games if game.Home == team) team_stats[team]['HomeBoxTouchesFor'] = sum(int(game.HomeBT) for game in games if game.Home == team) team_stats[team]['HomeBoxTouchesAgainst'] = sum(int(game.AwayBT) for game in games if game.Home == team) team_stats[team]['HomeCrossesFor'] = sum(int(game.HomeCrosses) for game in games if game.Home == team) team_stats[team]['HomeCrossesAgainst'] = sum(int(game.AwayCrosses) for game in games if game.Home == team) team_stats[team]['HomeCornersFor'] = sum(int(game.HomeCorners) for game in games if game.Home == team) team_stats[team]['HomeCornersAgainst'] = sum(int(game.AwayCorners) for game in games if game.Home == team) team_stats[team]['HomeGoalsFor'] = sum(int(game.HomeGoals) for game in games if game.Home == team) team_stats[team]['HomeGoalsAgainst'] = sum(int(game.AwayGoals) for game in games if game.Home == team) team_stats[team]['HomeXGoalsFor'] = sum(float(game.HomeXG) for game in games if game.Home == team) team_stats[team]['HomeXGoalsAgainst'] = sum(float(game.AwayXG) for game in games if game.Home == team) team_stats[team]['HomeGames'] = sum(1 for game in games if game.Home == team) team_stats[team]['AwayShotsFor'] = sum(int(game.AwayShots) for game in games if game.Away == team) team_stats[team]['AwayShotsAgainst'] = sum(int(game.HomeShots) for game in games if game.Away == team) team_stats[team]['AwayBoxTouchesFor'] = sum(int(game.AwayBT) for game in games if game.Away == team) team_stats[team]['AwayBoxTouchesAgainst'] = sum(int(game.HomeBT) for game in games if game.Away == team) team_stats[team]['AwayCrossesFor'] = sum(int(game.AwayCrosses) for game in games if game.Away == team) team_stats[team]['AwayCrossesAgainst'] = sum(int(game.HomeCrosses) for game in games if game.Away == team) team_stats[team]['AwayCornersFor'] = sum(int(game.AwayCorners) for game in games if game.Away == team) team_stats[team]['AwayCornersAgainst'] = sum(int(game.HomeCorners) for game in games if game.Away == team) team_stats[team]['AwayGoalsFor'] = sum(int(game.AwayGoals) for game in games if game.Away == team) team_stats[team]['AwayGoalsAgainst'] = sum(int(game.HomeGoals) for game in games if game.Away == team) team_stats[team]['AwayXGoalsFor'] = sum(float(game.AwayXG) for game in games if game.Away == team) team_stats[team]['AwayXGoalsAgainst'] = sum(float(game.HomeXG) for game in games if game.Away == team) team_stats[team]['AwayGames'] = sum(1 for game in games if game.Away == team) team_stats[team]['ShotsFor'] += team_stats[team]['HomeShotsFor'] + team_stats[team]['AwayShotsFor'] team_stats[team]['ShotsAgainst'] += team_stats[team]['HomeShotsAgainst'] + team_stats[team]['AwayShotsAgainst'] team_stats[team]['CrossesFor'] += team_stats[team]['HomeCrossesFor'] + team_stats[team]['AwayCrossesFor'] team_stats[team]['CrossesAgainst'] += team_stats[team]['HomeCrossesAgainst'] + team_stats[team]['AwayCrossesAgainst'] team_stats[team]['BoxTouchesFor'] += team_stats[team]['HomeBoxTouchesFor'] + team_stats[team]['AwayBoxTouchesFor'] team_stats[team]['BoxTouchesAgainst'] += team_stats[team]['HomeBoxTouchesAgainst'] + team_stats[team]['AwayBoxTouchesAgainst'] team_stats[team]['CornersFor'] += team_stats[team]['HomeCornersFor'] + team_stats[team]['AwayCornersFor'] team_stats[team]['CornersAgainst'] += team_stats[team]['HomeCornersAgainst'] + team_stats[team]['AwayCornersAgainst'] team_stats[team]['GoalsFor'] += team_stats[team]['HomeGoalsFor'] + team_stats[team]['AwayGoalsFor'] team_stats[team]['GoalsAgainst'] += team_stats[team]['HomeGoalsAgainst'] + team_stats[team]['AwayGoalsAgainst'] team_stats[team]['XGoalsFor'] += team_stats[team]['HomeXGoalsFor'] + team_stats[team]['AwayXGoalsFor'] team_stats[team]['XGoalsAgainst'] += team_stats[team]['HomeXGoalsAgainst'] + team_stats[team]['AwayXGoalsAgainst'] team_stats[team]['Games'] += team_stats[team]['HomeGames'] + team_stats[team]['AwayGames'] team_stats[team]['HomeShotsRatio'] = team_stats[team]['HomeShotsFor'] / (team_stats[team]['HomeShotsFor'] + team_stats[team]['HomeShotsAgainst']) team_stats[team]['AwayShotsRatio'] = team_stats[team]['AwayShotsFor'] / (team_stats[team]['AwayShotsFor'] + team_stats[team]['AwayShotsAgainst']) team_stats[team]['ShotsRatio'] = team_stats[team]['ShotsFor'] / (team_stats[team]['ShotsFor'] + team_stats[team]['ShotsAgainst']) team_stats[team]['HomeCrossesRatio'] = team_stats[team]['HomeCrossesFor'] / (team_stats[team]['HomeCrossesFor'] + team_stats[team]['HomeCrossesAgainst']) team_stats[team]['AwayCrossesRatio'] = team_stats[team]['AwayCrossesFor'] / (team_stats[team]['AwayCrossesFor'] + team_stats[team]['AwayCrossesAgainst']) team_stats[team]['CrossesRatio'] = team_stats[team]['CrossesFor'] / (team_stats[team]['CrossesFor'] + team_stats[team]['CrossesAgainst']) team_stats[team]['HomeBoxTouchesRatio'] = team_stats[team]['HomeBoxTouchesFor'] / (team_stats[team]['HomeBoxTouchesFor'] + team_stats[team]['HomeBoxTouchesAgainst']) team_stats[team]['AwayBoxTouchesRatio'] = team_stats[team]['AwayBoxTouchesFor'] / (team_stats[team]['AwayBoxTouchesFor'] + team_stats[team]['AwayBoxTouchesAgainst']) team_stats[team]['BoxTouchesRatio'] = team_stats[team]['BoxTouchesFor'] / (team_stats[team]['BoxTouchesFor'] + team_stats[team]['BoxTouchesAgainst']) team_stats[team]['HomeCornersRatio'] = team_stats[team]['HomeCornersFor'] / (team_stats[team]['HomeCornersFor'] + team_stats[team]['HomeCornersAgainst']) team_stats[team]['AwayCornersRatio'] = team_stats[team]['AwayCornersFor'] / (team_stats[team]['AwayCornersFor'] + team_stats[team]['AwayCornersAgainst']) team_stats[team]['CornersRatio'] = team_stats[team]['CornersFor'] / (team_stats[team]['CornersFor'] + team_stats[team]['CornersAgainst']) team_stats[team]['HomeGoalsRatio'] = team_stats[team]['HomeGoalsFor'] / (team_stats[team]['HomeGoalsFor'] + team_stats[team]['HomeGoalsAgainst']) team_stats[team]['AwayGoalsRatio'] = team_stats[team]['AwayGoalsFor'] / (team_stats[team]['AwayGoalsFor'] + team_stats[team]['AwayGoalsAgainst']) team_stats[team]['GoalsRatio'] = team_stats[team]['GoalsFor'] / (team_stats[team]['GoalsFor'] + team_stats[team]['GoalsAgainst']) team_stats[team]['HomeXGoalsRatio'] = team_stats[team]['HomeXGoalsFor'] / (team_stats[team]['HomeXGoalsFor'] + team_stats[team]['HomeXGoalsAgainst']) team_stats[team]['AwayXGoalsRatio'] = team_stats[team]['AwayXGoalsFor'] / (team_stats[team]['AwayXGoalsFor'] + team_stats[team]['AwayXGoalsAgainst']) team_stats[team]['XGoalsRatio'] = team_stats[team]['XGoalsFor'] / (team_stats[team]['XGoalsFor'] + team_stats[team]['XGoalsAgainst']) team_stats[team]['CornersTotalPg'] = (team_stats[team]['CornersFor'] + team_stats[team]['CornersAgainst']) / team_stats[team]['Games'] team_stats[team]['HomeBoxTouchesTotal'] = (team_stats[team]['HomeBoxTouchesFor'] + team_stats[team]['HomeBoxTouchesAgainst']) team_stats[team]['AwayBoxTouchesTotal'] = (team_stats[team]['AwayBoxTouchesFor'] + team_stats[team]['AwayBoxTouchesAgainst']) team_stats[team]['HomeBoxTouchesTotalPg'] = team_stats[team]['HomeBoxTouchesTotal'] / team_stats[team]['HomeGames'] team_stats[team]['AwayBoxTouchesTotalPg'] = team_stats[team]['AwayBoxTouchesTotal'] / team_stats[team]['AwayGames'] team_stats[team]['BoxTouchesTotalPg'] = (team_stats[team]['HomeBoxTouchesTotal'] + team_stats[team]['AwayBoxTouchesTotal']) / team_stats[team]['Games'] return team_stats def print_team_stats_html(team_stats): """ Prints a subset of team stats in HTML format. """ headers = ['Team', 'HomeBoxTouchesRatio', 'AwayBoxTouchesRatio', 'HomeBoxTouchesTotalPg', 'AwayBoxTouchesTotalPg', 'HomeCornersRatio', 'AwayCornersRatio'] print('&lt;table border=1&gt;') print('&lt;tr&gt;', end='') for header in headers: print('&lt;th&gt;{}&lt;/th&gt;'.format(header), end='') print('&lt;/tr&gt;') for key, value in sorted(team_stats.items()): print('&lt;tr&gt;') print('&lt;td&gt;{}&lt;/td&gt;'.format(key)) print('&lt;td&gt;{:.2f}&lt;/td&gt;'.format(value['HomeBoxTouchesRatio'])) print('&lt;td&gt;{:.2f}&lt;/td&gt;'.format(value['AwayBoxTouchesRatio'])) print('&lt;td&gt;{:.2f}&lt;/td&gt;'.format(value['HomeBoxTouchesTotalPg'])) print('&lt;td&gt;{:.2f}&lt;/td&gt;'.format(value['AwayBoxTouchesTotalPg'])) print('&lt;td&gt;{:.2f}&lt;/td&gt;'.format(value['HomeCornersRatio'])) print('&lt;td&gt;{:.2f}&lt;/td&gt;'.format(value['AwayCornersRatio'])) print('&lt;/tr&gt;') print('&lt;/table&gt;') def find_games_by_teams_stats(home_stat, away_stat, home_value, away_value, teams_stats, games, home_epsilon=0.05, away_epsilon=0.05): """ Finds teams with home and away stat &lt;= EPSILON &lt;= and returns a list of games between those teams. """ relevant_home_teams = [] relevant_away_teams = [] for team in teams_stats: if abs(teams_stats[team][home_stat] - home_value) &lt;= home_epsilon: relevant_home_teams.append(team) if abs(teams_stats[team][away_stat] - away_value) &lt;= away_epsilon: relevant_away_teams.append(team) return [game for game in games if game.Home in relevant_home_teams and game.Away in relevant_away_teams] def calculate_sample_stats(games): """ Calculates summary statistics for the given list of Game. """ avg_home_corners = mean(int(game.HomeCorners) for game in games) avg_away_corners = mean(int(game.AwayCorners) for game in games) avg_home_bt = mean(int(game.HomeBT) for game in games) avg_away_bt = mean(int(game.AwayBT) for game in games) avg_home_goals = mean(int(game.HomeGoals) for game in games) avg_away_goals = mean(int(game.AwayGoals) for game in games) avg_home_xgoals = mean(float(game.HomeXG) for game in games) avg_away_xgoals = mean(float(game.AwayXG) for game in games) avg_home_bt_ratio = avg_home_bt / (avg_home_bt + avg_away_bt) avg_away_bt_ratio = avg_away_bt / (avg_home_bt + avg_away_bt) stats = { 'games_count': len(games), 'avg_home_corners': avg_home_corners, 'avg_away_corners': avg_away_corners, 'avg_home_bt': avg_home_bt, 'avg_away_bt': avg_away_bt, 'avg_home_goals': avg_home_goals, 'avg_away_goals': avg_away_goals, 'avg_home_xgoals': avg_home_xgoals, 'avg_away_xgoals': avg_away_xgoals, 'avg_home_bt_ratio': avg_home_bt_ratio, 'avg_away_bt_ratio': avg_away_bt_ratio, } return stats def print_sample_stats(stats): """ Prints the statistical summary of the list of Game. """ print(f'{stats["games_count"]} games have been found') print(f'Average home corners: {stats["avg_home_corners"]:.2f}') print(f'Average away corners: {stats["avg_away_corners"]:.2f}') print(f'Average home BoxTouches: {stats["avg_home_bt"]:.2f}') print(f'Average away BoxTouches: {stats["avg_away_bt"]:.2f}') print(f'Average home Goals: {stats["avg_home_goals"]:.2f}') print(f'Average away Goals: {stats["avg_away_goals"]:.2f}') print(f'Average home Xgoals: {stats["avg_home_xgoals"]:.2f}') print(f'Average away Xgoals: {stats["avg_away_xgoals"]:.2f}') print(f'Average home BoxTouches ratio: {stats["avg_home_bt_ratio"]:.3f}') print(f'Average away BoxTouches ratio: {stats["avg_away_bt_ratio"]:.3f}') if __name__ == '__main__': games = csv_to_list_of_games(FILENAME) teams = get_teams_list(games) team_stats = calculate_team_stats(teams, games) relevant_games = find_games_by_teams_stats('HomeBoxTouchesRatio', 'AwayBoxTouchesRatio', 0.55, 0.45, team_stats, games, 0.03, 0.03) relevant_stats = calculate_sample_stats(relevant_games) print_sample_stats(relevant_stats) print() print(set(game.Home for game in relevant_games)) print(set(game.Away for game in relevant_games)) print() </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-06T22:54:44.103", "Id": "477929", "Score": "0", "body": "Hey Peilonrayz, I will be happy to get any feedback! Feel free to answer only a particular question(s)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-06T23:04:26.047", "Id": "477931", "Score": "0", "body": "Ah perfect :) When going over your question I got a little confused by your second question. Could you help me figure it out? Could you possibly rephrase it. It will likely help me understand if you relate it to the code, is there a specific function or group of functions that this problem is in? Sorry to be a bother :(" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-06T23:08:57.913", "Id": "477932", "Score": "0", "body": "Sure. Please take a look at `print_team_stats_html()`, even though `team_stats` has tens of fields, the function prints only 7 of them and there is no way to specify which ones to print. I would like to parameterize it, however if to list all the fields ony be one, it would be extremely tedious. So my idea is to create some subsets of fields to print at the top-level and pass one of them as a parameter to specify which fields I would like to print." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-06T23:10:19.753", "Id": "477933", "Score": "0", "body": "For example, one template prints only home stats, whereas another one prints only stats related to scored goals, etc." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-06T23:13:30.647", "Id": "477934", "Score": "0", "body": "Thank you very much, that makes complete sense to me now! Again, sorry to have been a bother. I hope you get a good answer :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-06T23:16:57.897", "Id": "477935", "Score": "0", "body": "You are welcome! Should you need to clarify any details, feel free to ask." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-07T02:31:18.853", "Id": "477938", "Score": "1", "body": "You may take a look at [`pandas`](https://pandas.pydata.org/docs/getting_started/index.html). If you haven't heard of it that this may be a perfect oppurtunity to learn the library. It has very great tools for handling csv,xlsx,etc types of data and it works better with jupyter notebook." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-07T11:04:43.937", "Id": "477953", "Score": "0", "body": "I am aware of `pandas` though the question is how to apply it to this particular situation." } ]
[ { "body": "<p>You're already doing a lot of things well; it's nice to see a question from someone who already knows the language and is looking for ways to get better.</p>\n<ol>\n<li><em>How should I write unit tests for checking the correctness of functions that calculate stats?</em><br />\nGenerally you'll want one (or a few) &quot;happy path&quot; unit tests: hard-code some sample data as part of the unit test, and assert that the result of the calculations is whatever you've confirmed it ought to be.<br />\nYou'll <em>also</em> want a couple failure tests, that check that your program <em>fails</em> when it <em>ought to</em> fail, for example if given malformed data.</li>\n<li><em>How to make a function that prints output to work with an arbitrary list of fields, instead of a particular one?</em><br />\nYou're thinking of fields as strings. Sometimes you need that, but you'd also be well served by thinking of <em>fields as functions from a defined data structure to a contained datum or sub-structure</em>. A <code>dict</code> would be appropriate for converting from fields-as-names to fields-as-getters. Then you can just loop or use a comprehension or whatever.</li>\n<li><em>Can I simplify calculate_team_stats()?</em><br />\nYes; the reason it's so unweildly now is because you're using a flat data structure, and you're relying too much on <code>dict</code>s. Dicts aren't great for structured data because they <em>have very little structure</em>. When you know the structure in advance, a tree of NamedTuples is often better.</li>\n</ol>\n<p>Other stuff:</p>\n<ul>\n<li>You're ready for <a href=\"https://docs.python.org/3/library/typing.html\" rel=\"noreferrer\">typing</a>. Type-hinted code is easier to reason about, both for you and for your IDE. I also recommend using <a href=\"https://mypy.readthedocs.io/en/stable/\" rel=\"noreferrer\">mypy</a> in parallel with your linter and unit tests to ensure your types are correct.</li>\n<li>A function with type-hints will need fewer comments (often none) to be readable.</li>\n<li>Break up your functions even smaller. For example making a <code>Game</code> from a csv row should be its own function, and then <code>csv_to_list_of_games</code> is quite short.</li>\n<li>More generally, nest stuff more. This includes classes.</li>\n<li>Rely even more on comprehensions.</li>\n<li>Use a DictReader to parse the csv file, that way you're not relying on the order of the fields.</li>\n<li>When a function takes a lot of args, try to avoid letting the order matter by passing them as keyword args.</li>\n<li>Rely more on the libraries you're using, for example let datetime handle parsing for you.</li>\n<li>We use lists a lot because they're flexible, but if a more constrained structure will do then use that. For example if you're going to get a <code>set</code> of teams, why turn it back into a list?</li>\n<li>Do your data conversions when you parse the data, not later when you use it.</li>\n</ul>\n<p>I mocked out the parse-and-calculate half, and checked it with mypy. I didn't actually test it or attempt the filter-and-print half:</p>\n<pre class=\"lang-py prettyprint-override\"><code>import csv\nimport datetime\nimport itertools\nfrom statistics import mean\nfrom typing import Iterable, Mapping, NamedTuple, Set, Tuple\n\nFILENAME = 'epl 18_19 games.csv'\n\n\nclass IntegerStats(NamedTuple):\n shots: int\n box_touches: int\n crosses: int\n corners: int\n goals: int\n x_goals: float\n\n\ndef sum_integer_stats(*stats: IntegerStats) -&gt; IntegerStats:\n return IntegerStats( # This could be one line, but let's keep it verbose. \n shots=sum(s.shots for s in stats),\n box_touches=sum(s.box_touches for s in stats),\n crosses=sum(s.crosses for s in stats),\n corners=sum(s.corners for s in stats),\n goals=sum(s.goals for s in stats),\n x_goals=sum(s.x_goals for s in stats)\n )\n\n\nclass RatioStats(NamedTuple):\n shots: float\n box_touches: float\n crosses: float\n corners: float\n goals: float\n x_goals: float\n\n\nclass Game(NamedTuple):\n date: datetime.date\n home_team: str\n home_stats: IntegerStats\n away_team: str\n away_stats: IntegerStats\n\n def teams(self) -&gt; Tuple[str, str]:\n return (self.home_team, self.away_team)\n\n\ndef row_to_game(row: Mapping[str, str]) -&gt; Game:\n return Game(\n date=datetime.datetime.strptime(row['Date'], '%d.%m.%Y').date(),\n home_team=row['Home'],\n home_stats=IntegerStats(shots=int(row['HomeShots']),\n box_touches=int(row['HomeBT']),\n crosses=int(row['HomeCrosses']),\n corners=int(row['HomeCorners']),\n goals=int(row['HomeGoals']),\n x_goals=float(row['HomeXG'])),\n away_team=row['Away'],\n away_stats=IntegerStats(shots=int(row['AwayShots']),\n box_touches=int(row['AwayBT']),\n crosses=int(row['AwayCrosses']),\n corners=int(row['AwayCorners']),\n goals=int(row['AwayGoals']),\n x_goals=float(row['AwayXG'])),\n )\n\n\ndef csv_to_list_of_games(filename: str) -&gt; Iterable[Game]:\n with open(FILENAME) as f:\n csv_reader = csv.DictReader(f)\n return [row_to_game(row) for row in csv_reader]\n\n\ndef get_teams_set(games: Iterable[Game]) -&gt; Set[str]:\n return set(itertools.chain.from_iterable(game.teams() for game in games))\n\n\ndef get_games_by_team(teamname: str, games: Iterable[Game]) -&gt; Iterable[Game]:\n return [game for game in games if teamname in game.teams()]\n\n\nclass TeamGameSetStats(NamedTuple):\n made: IntegerStats # call it `made` because `for` is a python keyword.\n against: IntegerStats\n totals: IntegerStats\n ratios: RatioStats\n totals_per_game: RatioStats\n games: int\n\n\ndef team_gameset_stats(own_stats: Iterable[IntegerStats],\n opposing_stats: Iterable[IntegerStats]\n ) -&gt; TeamGameSetStats:\n made = sum_integer_stats(*own_stats)\n against = sum_integer_stats(*opposing_stats)\n totals = sum_integer_stats(made, against)\n game_count = len(list(itertools.chain(own_stats, opposing_stats)))\n return TeamGameSetStats(\n made=made,\n against=against,\n totals=totals,\n ratios=RatioStats(\n shots=made.shots / (made.shots + against.shots),\n box_touches=made.box_touches / (made.box_touches + against.box_touches),\n crosses=made.crosses / (made.crosses + against.crosses),\n corners=made.corners / (made.corners + against.corners),\n goals=made.goals / (made.goals + against.goals),\n x_goals=made.x_goals / (made.x_goals + against.x_goals)\n ),\n totals_per_game=RatioStats(\n shots=totals.shots / game_count,\n box_touches=totals.box_touches / game_count,\n crosses=totals.crosses / game_count,\n corners=totals.corners / game_count,\n goals=totals.goals / game_count,\n x_goals=made.x_goals / game_count\n ),\n games=game_count\n )\n\n\nclass TeamStats(NamedTuple):\n home: TeamGameSetStats\n away: TeamGameSetStats\n agregate: TeamGameSetStats\n\n\ndef team_stats(teamname: str, games: Iterable[Game]) -&gt; TeamStats:\n home_games = [g for g in games if g.home_team == teamname]\n own_home_stats = [g.home_stats for g in home_games]\n opposing_home_stats = [g.away_stats for g in home_games]\n away_games = [g for g in games if g.away_team == teamname]\n own_away_stats = [g.away_stats for g in away_games]\n opposing_away_stats = [g.home_stats for g in away_games]\n return TeamStats(\n home=team_gameset_stats(own_stats=own_home_stats, opposing_stats=opposing_home_stats),\n away=team_gameset_stats(own_stats=own_away_stats, opposing_stats=opposing_away_stats),\n agregate=team_gameset_stats(\n own_stats=own_home_stats + own_away_stats,\n opposing_stats=opposing_home_stats + opposing_away_stats\n )\n )\n\n\ndef calculate_team_stats(teams: Set[str], games: Iterable[Game]) -&gt; Mapping[str, TeamStats]:\n return {\n team: team_stats(team, games)\n for team in teams\n }\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-15T19:31:12.213", "Id": "478862", "Score": "0", "body": "Thanks for the great review, I have learned a lot! Could you elaborate on \"_fields as functions from a defined data structure to a contained datum or sub-structure_\"?" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-13T03:56:27.403", "Id": "243802", "ParentId": "243499", "Score": "5" } }, { "body": "<h3>Fields as functions from a defined data structure to a contained datum or sub-structure</h3>\n<p>Elaborating a bit on this point, which I was too abstract about.</p>\n<p>Hopefully it's intuitive that, technical details of any particular language/context aside, &quot;fields&quot;, &quot;attributes&quot;, &quot;properties&quot;, etc are all kinda synonymous. We usually visualize objects like this as either a list of ordered pairs <span class=\"math-container\">\\$(\\text{name}, \\text{value})\\$</span>, or as a table where each row is an object and the column-headers are the field-names. <em>That's fine and totally appropriate.</em></p>\n<p>But there's another way of thinking about what a field is, which is reflected in the particular &quot;property&quot; implementation in some languages including Python. (It's also how everything works in Haskell.)<br />\n<strong>A property of an object is a function <em>from objects of that type to some value which we think of as contained with those objects</em>.</strong></p>\n<p>This is relevant to your task because all the &quot;properties&quot; you had of your <code>team_stats</code> items are still conceptually valid in a nested structure like I implemented. But now instead of</p>\n<pre><code>PROPERTY(&quot;HomeBoxTouchesTotalPg&quot;)} := lambda team_stats: team_stats[&quot;HomeBoxTouchesTotalPg&quot;]\n</code></pre>\n<p>you'll have</p>\n<pre><code>PROPERTY(&quot;HomeBoxTouchesTotalPg&quot;) := lambda team_stats: team_stats.home.totals_per_game.box_touches\n</code></pre>\n<p>Writing them all out will be a bit of a chore. Sorry.</p>\n<p>But then you can do</p>\n<pre class=\"lang-py prettyprint-override\"><code>def print_sample_stats(stats: TeamStats, *fields: str) -&gt; None:\n for field in fields:\n if field not in TeamStats.fields:\n raise NotImplementedError(field)\n print(f&quot;{field}: {TeamStats.fields[field](stats)}&quot;)\n</code></pre>\n<p>Of course you'll have plenty of opportunities to make it more complicated than that if you like.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-16T18:13:46.860", "Id": "243997", "ParentId": "243499", "Score": "2" } } ]
{ "AcceptedAnswerId": "243802", "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-06T22:44:38.023", "Id": "243499", "Score": "9", "Tags": [ "python", "python-3.x" ], "Title": "Create football stats from a .csv file" }
243499
<p>This is a follow-up to <a href="https://codereview.stackexchange.com/questions/243254/finding-min-and-max-values-of-an-iterable-on-the-fly">my previous question</a> about finding min and max values of an iterable. Aho-Corasick algorithm was suggested to solve the problem. Below is my solution with the use of <a href="https://github.com/abusix/ahocorapy/blob/master/README.md" rel="nofollow noreferrer">ahocorapy library</a>.</p> <p>Short re-cap of the problem:</p> <blockquote> <p>You are given 2 arrays (<code>genes</code> and <code>health</code>), one of which have a 'gene' name, and the other - 'gene' weight (aka <em>health</em>). You then given a bunch of strings, each containing values <code>m</code> and <code>n</code>, which denote the start and end of the slice to be applied to the <code>genes</code> and <code>health</code> arrays, and the 'gene'-string, for which we need to determine healthiness. Then we need to return health-values for the most and the least healthy strings.</p> </blockquote> <p>I think there might be something off with the code, but not sure what. It works quite fine for small testcases, giving more or less same timing as previous versions of the solution showed, but when it comes to large testcases, my PC basically hangs.</p> <p>Example of a small testcase:</p> <pre><code>genes = ['a', 'b', 'c', 'aa', 'd', 'b'] health = [1, 2, 3, 4, 5, 6] gene1 = "1 5 caaab" (result = 19 = max) gene2 = "0 4 xyz" (result = 0 = min) gene3 = "2 4 bcdybc" (result = 11) </code></pre> <p>Large testcase (2 lists 100K elements each; testcase 41K+ elements): <a href="https://www.dropbox.com/s/9l566nl7ucj69ra/DNAHealth%20HR%20problem%20Large%20testcase1.txt?dl=0" rel="nofollow noreferrer">txt in my dropbox (2,80 MB)</a> (too large for pastebin)</p> <p><strong>So, I have 2 questions: 1) What is wrong with my code, how can I impore its performace 2) How do I apply the Aho-Corasick without turning to any non-standard library (because, most likely, it cannot be installed on HackerRank server)</strong></p> <pre><code>def geneshealth(genes, health, testcase): from ahocorapy.keywordtree import KeywordTree import math min_weight = math.inf max_weight = -math.inf for case in testcase: #construct the keyword tree from appropriately sliced "genes" list kwtree = KeywordTree(case_insensitive=True) fl, ceil, g = case.split() for i in genes[int(fl):int(ceil)+1]: kwtree.add(i) kwtree.finalize() #search the testcase list for matches result = list(kwtree.search_all(g)) hea = 0 for gn, _ in result: for idx, val in enumerate(genes): if val == gn: hea += health[idx] if hea &lt; min_weight: min_weight = hea if hea &gt; max_weight: max_weight = hea return(min_weight, max_weight) </code></pre>
[]
[ { "body": "<p>This code is slow because:</p>\n\n<ol>\n<li>It builds a new keyword tree for each test case. Just build it once, using all the genes.</li>\n<li>It builds a list of all the matching keywords. <code>KeywordTree.search_all()</code> is a generator, just loop over it directly. And,</li>\n<li>It loops over the list of genes to find the gene index, so that it can find the health.<br>\nInstead, build a dict with the genes as keys and an (index, health) tuple for the value. </li>\n</ol>\n\n<p>Something like this (untested):</p>\n\n<pre><code>import math\nfrom collections import defaultdict\nfrom ahocorapy.keywordtree import KeywordTree\n\n\ndef geneshealth(genes, health, testcases):\n\n # build the kwtree using all the genes \n kwtree = KeywordTree(case_insensitive=True)\n for gene in genes:\n kwtree.add(gene)\n kwtree.finalize()\n\n # build a dict that maps a gene to a list of (index, health) tuples\n index_and_health = defaultdict(list)\n for gene, data in zip(genes, enumerate(health)):\n index_and_health[gene].append(data)\n\n min_dna_health = math.inf\n max_dna_health = -math.inf\n\n for case in testcases:\n start, end, dna = case.split()\n start = int(start)\n end = int(end)\n\n dna_health = 0\n\n # search the dna for any genes in the kwtree\n # note: we don't care where the gene is in the dna\n for gene, _ in kwtree.search_all(dna):\n\n for gene_index, gene_health in index_and_health[gene]:\n\n # only genes that are within the testcase limits\n # contribute dna_health\n if start &lt;= gene_index &lt;= end:\n dna_health += gene_health\n\n # keep the min/max weight\n if dna_health &lt; min_dna_health:\n min_dna_health = dna_health\n\n if dna_health &gt; max_dna_health:\n max_dna_health = dna_health\n\n return(min_dna_health, max_dna_health)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-07T07:40:38.623", "Id": "477947", "Score": "0", "body": "Will have to test it yet, but all the suggestions seem useful, so thank you. I noticed you put imports outside the function - does that effect the performance much?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-07T15:47:01.837", "Id": "477963", "Score": "1", "body": "It is common practice to put `import` statements at the top of the file. It doesn't affect run time performance of the code. There are some cases in which it makes sense, or is necessary, to put the imports in a function." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-07T17:29:12.793", "Id": "477968", "Score": "0", "body": "I tried out your code. Firstly, `testcases` is a collection of strings, so I replaced `for start, end, dna in testcases:` with `testcases_lst = []\n\n for i in testcases:\n x,y,z = i.split()\n testcases_lst.append((int(x), int(y), z))\n\n for start, end, dna in testcases_lst:`\nPlease, advice if there's a more efficient way to do that, although I tried it out separately, and it's quite fast" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-07T17:35:13.617", "Id": "477969", "Score": "0", "body": "Secondly, there is another issue: consider 1st gene in the light testcase above, `1 5 caab`. Now, in the `genes` array there are 2 `b` genes, one at index 1, another at index 5. Both should be counted, but only the second was, giving the result of 17 instead of 19. I'm not sure how to account for that. Any suggestions?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-07T17:35:45.680", "Id": "477970", "Score": "0", "body": "Also, @RootTwo, can you explain how the line `gene_index, gene_health = index_and_health[gene]` works?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-07T23:38:44.110", "Id": "477987", "Score": "1", "body": "@DenisShvetsov I revised the code for the 1st two questions. In the old code `index_and_health[gene]` looks up `gene` in the dict and returned a 2-item tuple. The assignment uses [sequence unpacking](https://docs.python.org/3/tutorial/datastructures.html#tuples-and-sequences) to assign the item in the tuple to `gene_index` and `gene_health`. In the revised code, the dict lookup returns a list of tuples. The for-loop `for gene_index, gene_health in index_and_health[gene]:` gets the an item in the list, unpacks the values, and executes the loop body for each item in the list." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-08T08:35:14.880", "Id": "478012", "Score": "0", "body": "I tested your code, it works perfectly. Timing for the large testcase is about 10 seconds as opposed to 164 seconds for best of the earlier solutions. Too bad HackerRank can't handle non-standard libraries" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-08T14:41:15.683", "Id": "478075", "Score": "1", "body": "@DenisShvetsov you can write your own algorithm in about [50 lines of python](http://algo.pw/algo/64/python)." } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-07T06:03:08.317", "Id": "243506", "ParentId": "243500", "Score": "1" } } ]
{ "AcceptedAnswerId": "243506", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-06T23:17:23.683", "Id": "243500", "Score": "2", "Tags": [ "python", "beginner", "python-3.x", "programming-challenge" ], "Title": "Aho-Corasick algorithm to scan through a list of strings" }
243500
<p>This script takes an image copied from the clipboard and analyzes the n darkest pixels of the image. It will loop through each found value, prints out the value information and the quantity, then displays the visual location of the pixels in a tkinter window.</p> <p>There are two modes for reading the pixels. One is by simply looping through the darkest pixels given the default 0-255 value range. The other is by compressing the range to 0-100 to fit the convention of mainstream image-editing programs.</p> <p>The script seems to work through casual testing, but many parts of the script feels very brittle, awkward and hacked together. A few of my concerns:</p> <ul> <li><p>My script finds the darkest pixels, removes them, then finds the next darkest pixels. But my method of 'removal' is by assigning the value of the found pixels to '999'. Is there a better method?</p></li> <li><p>My method of visually marking the pixels is by looping through the found pixels manually. Is there a faster way?</p></li> <li><p>Is <code>min(gray.flatten())</code> a good way to find the darkest pixels?</p></li> <li><p>Any other inaccuracies regarding image handling or other bad practices</p></li> <li><p>General performance</p></li> </ul> <pre class="lang-py prettyprint-override"><code>import platform if (platform.system() != "Windows"): print("Only Windows is supported for now.") raise SystemExit() import cv2 import math import argparse import numpy as np import tkinter as tk import win32clipboard from io import BytesIO from PIL import ImageTk, Image, ImageGrab parser = argparse.ArgumentParser(description='Finds the darkest pixels of a grayscaled image pasted from the clipboard. It will output the value information, quantity and a visual pixel map. The pixel map will be copied to your clipboard.') parser.add_argument('-n', '--num', dest='num', metavar='NUM', type=int, default=5, help='The number of darkest values to find. Default=5') parser.add_argument('-a', '--acc', dest='acc', default=False, action='store_true', help='Detects values using an accurate 0-255 range, instead of a compressed 0-100 range.') parser.add_argument('-p', '--pix', dest='pix', default=False, action='store_true', help='Colorizes detected pixels, instead of drawing a circle around it.') parser.add_argument('-t', '--threshold', dest='threshold', metavar='VALUE', type=int, default=False, help='Detects only values lighter or as light as the specified threshold (0-100 range).') parser.add_argument('-c', '--col', dest='color', default=False, action='store_true', help='Outputs pixel map in the original color, instead of the grayscaled version.') args = parser.parse_args() def ordinal(n): n = int(n) suffix = ['th', 'st', 'nd', 'rd', 'th'][min(n % 10, 4)] if 11 &lt;= (n % 100) &lt;= 13: suffix = 'th' return str(n) + suffix def bmp_process(im): output = BytesIO() im.save(output, "BMP") data = output.getvalue()[14:] output.close() return data def clip_send(clip_type, data): win32clipboard.OpenClipboard() win32clipboard.EmptyClipboard() win32clipboard.SetClipboardData(clip_type, data) win32clipboard.CloseClipboard() def show_img(im, size): thumb = im.copy() thumb.thumbnail(size, Image.ANTIALIAS) window = tk.Tk() w = size[0] h = size[1] ws = window.winfo_screenwidth() hs = window.winfo_screenheight() x = (ws/2) - (w/2) y = (hs/2) - (h/2) window.geometry('%dx%d+%d+%d' % (w, h, x, y)) img = ImageTk.PhotoImage(thumb) panel = tk.Label(window, image=img) panel.pack(side="bottom", fill="both", expand="yes") window.mainloop() try: clip = ImageGrab.grabclipboard().convert('RGB') clip.copy().verify() except: print("Invalid image data!") raise SystemExit() gray = cv2.cvtColor(np.array(clip.copy()), cv2.COLOR_RGB2GRAY) if args.color: img = cv2.cvtColor(np.array(clip.copy()), cv2.COLOR_RGB2BGR) else: img = cv2.cvtColor(gray.copy(), cv2.COLOR_GRAY2BGR) if args.threshold: threshold = math.ceil(( args.threshold / 100 ) * 255) while True: rounded = int(round((threshold / 255) * 100)) if rounded &lt; args.threshold: break threshold -= 1 mask = gray &lt;= threshold gray[mask] = 999 for i in range(args.num): raw = min(gray.flatten()) value_f = (raw / 255) * 100 value = int(round(value_f)) cnt = 0 n = raw marked = img.copy() while True: rounded = int(round((n / 255) * 100)) if rounded == value: points = np.argwhere(gray == n) mask = gray == n gray[mask] = 999 for point in points: if args.pix: marked[point[0], point[1]] = [0, 0, 255] else: cv2.circle(marked, (point[1], point[0]), 5, (0, 0, 255), 2) cnt += 1 else: break n += 1 if args.acc or n &gt; 255: break if args.acc: print("The {0} darkest grayscale value is {1}% ({2}/255 or {3:.2f}%), quantity is {4}".format(str(ordinal(i + 1)), str(value), str(raw), value_f, str(cnt))) else: print("The {0} darkest grayscale value is {1}%, quantity is {2}".format(str(ordinal(i + 1)), str(value), str(cnt))) display = Image.fromarray(cv2.cvtColor(marked, cv2.COLOR_BGR2RGB)) clip_out = bmp_process(display) clip_send(win32clipboard.CF_DIB, clip_out) show_img(display, (500, 500)) if n &gt; 255: raise SystemExit() </code></pre>
[]
[ { "body": "<h1>List Unpacking</h1>\n\n<p>Instead of assigning each variable to an index of the list, you can assign both variables to the list and it will unpack each item of the list to its respective variable.</p>\n\n<pre><code>w, h = size\n</code></pre>\n\n<h1>String Formatting</h1>\n\n<p>I personally would rather use <code>f\"\"</code> since it allows you to visually see where your variables are in the string, instead of remembering which number (<code>{0}</code>, <code>{1}</code>, etc) is associated with which variable.</p>\n\n<pre><code>print(f\"The {ordinal(i + 1)} darkest grayscale value is {value}%, quantity is {cnt}.\")\n</code></pre>\n\n<h1>Unnecessary Type Conversions</h1>\n\n<p>In <code>ordinal</code>, you convert <code>n</code> to an integer. However, you already pass an integer as an argument, so no need to convert. Also, if you want to use <code>f\"\"</code>, you don't need to convert variables to strings before you format them with your strings. You can put the raw values in and python will work all of it out.</p>\n\n<h1>Constants</h1>\n\n<p>There are a lot of magic numbers in your program. Specifically, <code>255</code> and <code>100</code> show up a lot. I would define constants that contain these values and use those instead.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-07T16:20:33.167", "Id": "243520", "ParentId": "243509", "Score": "2" } }, { "body": "<p>I’ll focus solely on the image processing algorithm. You find the lowest value (N comparisons), then find which pixels have this value (another N comparisons), and repeat this until you have K values. So you do about 2NK comparisons.</p>\n<p>This is OK for small K, but as it gets larger, this becomes a very inefficient algorithm.</p>\n<p>Instead, you could sort all pixels (<code>np.argsort</code> returns the indices to the sorted pixels). Since the pixel values are integers, you can use counting sort, which takes about 2N operations, but even the general quicksort would be OK to use.</p>\n<p>Next, finding the next lowest pixel is a single operation. So your algorithm goes from about 2NK operations to 2N+K, a huge saving for larger K.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-13T19:16:49.157", "Id": "243830", "ParentId": "243509", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-07T08:17:06.850", "Id": "243509", "Score": "5", "Tags": [ "python", "image", "numpy", "opencv" ], "Title": "Analyzing the darkest pixels of an image in Python" }
243509
<p>I've implemented a barreir in C++ close to one showed <a href="https://stackoverflow.com/a/27118537/1690777">here</a>. In the project code it's used only with two threads and seems to work. A synthetic test didn't expose any flaws too. But I suspect that on some machines it segfaults and/or falls through <code>wait()</code> call. How do you think, can it fall through <code>wait</code> or is any race scenario possible with it? Used mainly on Windows machines, if it matters.</p> <pre><code>class Barrier { public: explicit Barrier(uint16_t iCount) : maxThreads(iCount), count(iCount) {} void wait(std::chrono::milliseconds = std::chrono::milliseconds(0)); private: void notifyAll(); private: std::mutex mutex; std::condition_variable cv; uint16_t maxThreads; uint16_t count; bool generation = true; }; inline void Barrier::wait(const std::chrono::milliseconds timeWait) { std::unique_lock&lt;std::mutex&gt; ulock(mutex); auto gen = generation; const auto waitCondition = [this, gen]{ return (gen != generation); }; if (0 == --count) notifyAll(); else { if (timeWait == std::chrono::milliseconds(0)) cv.wait(ulock, waitCondition); else { const auto timedOut = !cv.wait_for(ulock, timeWait, waitCondition); if (timedOut) ++count; } } } inline void Barrier::notifyAll() { generation = !generation; count = maxThreads; cv.notify_all(); } </code></pre> <p>P.S. I know that <code>generation</code> is poor naming for this particular variable. Here it's intended to express similarity to the same name variable from abovementioned SO question code.</p>
[]
[ { "body": "<p>Naming nitpicks: The relationship between <code>count</code> and <code>maxThreads</code> is not obvious. I would probably name them something like <code>threads_arrived_</code> and <code>total_threads_</code> (using the common convention of postfix-underscore for data members).</p>\n\n<p>You might like to know that there's a <a href=\"https://en.cppreference.com/w/cpp/thread/barrier\" rel=\"noreferrer\"><code>std::barrier</code></a> in C++20. Your <code>wait</code> is what C++20 calls <code>arrive_and_wait</code>. Your <code>generation</code> is what C++20 calls the \"phase.\"</p>\n\n<hr>\n\n<p>Why is your <code>notifyAll</code> a separate function, given that it's private and called only in a single place? You should just inline it. As a bonus, you could then <em>drop the mutex lock</em> before calling <code>cv.notify_all()</code> — this is widely quoted as a performance optimization.</p>\n\n<hr>\n\n<p>You wrote:</p>\n\n<pre><code>void wait(std::chrono::milliseconds = std::chrono::milliseconds(0));\n</code></pre>\n\n<p>Being as <a href=\"https://quuxplusone.github.io/blog/2020/04/18/default-function-arguments-are-the-devil/\" rel=\"noreferrer\">default arguments are the devil</a>, this is a red flag. Personally I would write this as</p>\n\n<pre><code>void arrive_and_wait();\nvoid arrive_and_wait_for(std::chrono::milliseconds timeout);\n</code></pre>\n\n<p>and continue adding an <code>arrive_and_wait_until</code> as well. I would <em>not</em> use overloading or default arguments to accomplish this, because \"wait for 0 milliseconds\" and \"wait forever\" are <em>completely different things</em>. You really really don't want someone doing, like,</p>\n\n<pre><code>barrier.wait(user_configured_timeout); // wait for 1ms\nbarrier.wait(user_configured_timeout / 2); // wait for half that\n</code></pre>\n\n<p>and getting an infinite wait instead. Follow the STL's lead here: <code>wait</code>, <code>wait_for</code>, and <code>wait_until</code> are all different operations.</p>\n\n<hr>\n\n<pre><code>if (0 == --count) notifyAll();\nelse {\n if (timeWait == std::chrono::milliseconds(0)) cv.wait(ulock, waitCondition);\n else {\n const auto timedOut = !cv.wait_for(ulock, timeWait, waitCondition);\n if (timedOut) ++count;\n }\n}\n</code></pre>\n\n<p>This is a ridiculously misindented piece of code. Try this:</p>\n\n<pre><code>if (0 == --count) {\n notifyAll();\n} else if (timeWait == std::chrono::milliseconds(0)) {\n // note that our refactored `wait_for` will not contain this branch\n cv.wait(ulock, waitCondition);\n} else {\n // note that our refactored `wait` will not contain this branch\n bool timedOut = !cv.wait_for(ulock, timeWait, waitCondition);\n if (timedOut) ++count;\n}\n</code></pre>\n\n<p>That <code>++count</code> smells like a race condition to me. Sure, we're operating under the mutex lock <em>here</em>; but I suspect it's possible that some other thread might have observed the decremented value of <code>count</code> and acted on it, which might mean that here we're bumping <code>count</code> from 0 to 1, or from <code>maxThreads</code> to <code>maxThreads+1</code>. I'm not sure that this can happen, but I would look at this codepath <em>very</em> closely if I were you.</p>\n\n<hr>\n\n<p>Consider what happens in code like</p>\n\n<pre><code>Thread A Thread B Thread C\n\nBarrier b(2);\nb.wait(); b.wait();\n &lt;notifyAll&gt;\n b.wait(); b.wait();\n &lt;notifyAll&gt;\n &lt;awaken&gt;\n&lt;awaken&gt;\n&lt;resume waiting&gt;\n</code></pre>\n\n<p>If I understand correctly, when thread A finally gets scheduled and belatedly awakens from its <code>cv.wait</code>, it will observe <code>gen == generation</code> because <code>generation</code> has been toggled <em>twice</em> since it went to sleep. So it will remain blocked, even though it should have become unblocked as a result of thread B's first <code>b.wait()</code>.</p>\n\n<p>I'm not sure how to fix this, but it might involve thread B being forced to block, <em>itself</em>, until all the other threads in the current phase have indicated that they're unblocked. In fact I'm not sure that <em>that</em> would even fix the issue.</p>\n\n<hr>\n\n<p>It's worth mentioning that it is physically possible for the programmer to destroy a <code>Barrier</code> while some other thread is still blocked waiting on it. Presumably you're okay with having this be undefined behavior.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-07T17:03:12.223", "Id": "243522", "ParentId": "243519", "Score": "6" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-07T15:55:40.193", "Id": "243519", "Score": "4", "Tags": [ "c++", "multithreading", "thread-safety" ], "Title": "Barrier implementation in C++" }
243519