body
stringlengths
25
86.7k
comments
list
answers
list
meta_data
dict
question_id
stringlengths
1
6
<p>To celebrate <a href="https://stackoverflow.blog/2019/11/13/were-rewarding-the-question-askers/?cb=1">questions getting more reputation points per upvote</a>, I revisited my previous question, <a href="https://codereview.stackexchange.com/questions/165245/plot-timings-for-a-range-of-inputs">Plot timings for a range of inputs</a>.</p> <p>Since the time of that original question (more than two years!), this code has undergone quite a few changes. I incorporated some of the advice given in <a href="https://codereview.stackexchange.com/a/165362/98493">the answer</a> by <a href="https://codereview.stackexchange.com/users/123200/maarten-fabr%C3%A9">@MaartenFabré</a>. I also added <code>multiprocessing</code> to the mix to perform the timings in parallel. I added some convenience flags as well as using the minimum time recorded as the value, instead of the mean.</p> <h3>Code:</h3> <pre><code>from __future__ import print_function from functools import partial from itertools import product, count import matplotlib.pyplot as plt import multiprocessing import numpy as np import pandas as pd import timeit from uncertainties import ufloat, unumpy as unp N_CPU = multiprocessing.cpu_count() DEBUG = False def get_time(func, *x): """Run a timer for `func` five times with the given input.""" timer = timeit.Timer(partial(func, *x)) t = timer.repeat(repeat=5, number=1) if DEBUG: print(func.__name__, np.min(t)) return ufloat(np.min(t), np.std(t) / np.sqrt(len(t))) def flatten_once(it): """For passing multiple arguments to functions, flatten each inner list.""" for x in it: yield [x[0], *x[1]] def identity(x): """The identity function.""" return x def get_timings_df(funcs, inputs, key=identity, star=False, doc=False): """Use multiprocessing to time all `funcs` using the `inputs`. key: Function that is called once on each input to determine the x-value. Default: identity star: If the functions take multiple argument, and `inputs` contains tuples of arguments, splat them out. Default: False doc: Use `func.__doc__` as plotting label instead of `func.__name__`. Default: False """ df = pd.DataFrame(list(map(key, inputs)), columns=["x"]) labels = [func.__name__ for func in funcs] if doc: labels = [func.__doc__ for func in funcs] y = product(funcs, inputs) if star: y = flatten_once(y) with multiprocessing.Pool(processes=N_CPU-1) as pool: times = np.array(pool.starmap(get_time, y)).reshape(len(funcs), -1) for label, t in zip(labels, times): df[label] = t return df def plot_times(funcs, inputs, key=identity, xlabel="x", ylabel="Time [s]", logx=False, logy=False, star=False, ratio=False, doc=False): """Plot timings of `funcs` using `inputs`. key: Function that is called once on each input to determine the x-value. Default: identity. xlabel: Label of x-axis. Default: 'x'. ylabel: Label of y-axis (may be overwritten for some flags). Default: 'Time [s]'. logx: Make x-axis logarithmic. Default: False. logy: Make y-axis logarithmic. Default: False. star: If the functions take multiple argument, and `inputs` contains tuples of arguments, splat them out. Default: False ratio: Plot timings relative to time of first function. Default: False. doc: Use `func.__doc__` as plotting label instead of `func.__name__`. Default: False """ df = get_timings_df(funcs, inputs, key, star, doc) for label in df.columns[1:]: x, y = df["x"], df[label] if ratio: y = y / df.T.iloc[1] plt.errorbar(x, unp.nominal_values(y), unp.std_devs(y), fmt='o-', label=label) plt.xlabel(xlabel) if ratio: ylabel = "{} / Time of {} [s]".format(ylabel, df.columns[1]) plt.ylabel(ylabel) if logx: plt.xscale("log") if logy: plt.yscale("log") plt.legend() plt.show() </code></pre> <p>For now, I want to keep Python 2 compatibility, so, unfortunately, no <code>f-string</code>s. I am also not a big fan of type-hints, and I don't think they would help a lot here, but I'm open to being convinced otherwise.</p> <p>If you can find a way to simplify any of the functions (or get effectively rid of them), I would love to hear it. The same is true for simplifying the interface of <code>plot_times</code>. All other recommendations are welcome as well.</p> <h3>Example usages:</h3> <p>This function is quite flexible. It allows the typical use-case of timing a bunch of single-argument functions with a bunch of inputs:</p> <pre><code>import time from timing import plot_times def linear(x): """$\mathcal{O}(n)$""" time.sleep(x) def quadratic(x): """$\mathcal{O}(n^2)$""" time.sleep(x**2) if __name__ == "__main__": x = np.arange(0, 1, 0.1) plot_times([linear, quadratic], x, doc=True) </code></pre> <p><a href="https://i.stack.imgur.com/UHOfq.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/UHOfq.png" alt="enter image description here"></a></p> <p>To timing multi-argument functions and plotting them relative to the first function:</p> <pre><code>if __name__ == "__main__": x = np.arange(0.1, 1, 0.1) plot_times([linear, quadratic], x, doc=True, ratio=True) </code></pre> <p><a href="https://i.stack.imgur.com/l8amw.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/l8amw.png" alt="enter image description here"></a></p> <p>To use a different function to map values to the x-axis and semi- or log-log plotting:</p> <pre><code>import string import random import numpy as np from timing import plot_times def count_digits(x): return sum(c.isdigit() for c in x) def count_digits2(x): return sum(1 for c in x if c.isdigit()) if __name__ == "__main__": alpha_num = string.ascii_letters + string.digits x = ["".join(random.choices(alpha_num, k=n)) for n in np.logspace(1, 5, dtype=int)] plot_times([count_digits, count_digits2], x, key=len, xlabel="len(s)", logx=True, logy=True) </code></pre> <p><a href="https://i.stack.imgur.com/2YOgq.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/2YOgq.png" alt="enter image description here"></a></p>
[]
[ { "body": "<p>These plots are a great visual aid to support algorithmic arguments. I've been guilty of creating some of them myself, although more on the go and not with a dedicated \"framework\" like yours.</p>\n\n<p>The code itself is clean and to the point. It's a great example of the power and beauty of Python. In under 100 lines of code you can create a usable tool, including documentation and multiprocessing. I'd support your opinion on that type hints would not really make it better here.</p>\n\n<p>In essence there are only a few points that I personally would change:</p>\n\n<h2><code>get_timings_df</code></h2>\n\n<ul>\n<li>I prefer list comprehensions over <code>map</code>, so I would likely use <code>df = pd.DataFrame([key(input_) for input_ in inputs], columns=[\"x\"])</code>, mainly because I find it clearer.</li>\n<li>Since we are at it, I don't like <code>key</code> as a parameter name here. I'd suggest to use something like <code>preprocess</code>, <code>input_transform</code> or another more telling name instead. I also understand that maybe one could argue that <code>key</code> is \"more in-line\" with general purpose functions like <code>sorted(...)</code>, but I reckon both versions of the data frame creation would become easier to understand with a more straightforward name.</li>\n<li><code>labels = [func.__name__ for func in funcs]</code> could be moved into an <code>else</code> branch of <code>if doc:</code> to avoid iterating over the functions twice.</li>\n<li>I'm not entirely sure how I feel about mandatory multiprocessing with a number of workers I cannot control. I think this should be optional since it may or may not influence the timing, especially if the code that is timed already uses multiprocessing, although I have no hard facts to back that up.</li>\n</ul>\n\n<h2><code>plot_times</code></h2>\n\n<ul>\n<li>The note on <code>key</code> above applies here to</li>\n<li>Maybe it would be a good idea to make the final <code>plt.show()</code> optional. IMHO that would make it easier to use this functionality in scripts without user interaction, e.g. to automatically save several plots before showing them.</li>\n<li>The documentation should explain that the function always uses <code>plt.gcf()</code>/<code>plt.gca()</code> as plotting target. This would make it more obvious for the user that they need to call <code>plt.figure()</code> manually when doing separate tests in one go in order to avoid messing up the previous plot.</li>\n</ul>\n\n<h2>\"Auto review\"</h2>\n\n<p>Just for the sake of completeness, some minor complaints from flake8:</p>\n\n<ul>\n<li><code>itertools.count</code> is imported but not used</li>\n<li>there are quite a few instances of trailing whitespace in the docstrings</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-14T17:18:51.443", "Id": "453812", "Score": "0", "body": "Thanks for the feedback! Regarding the `labels`, that's what I originally had, but somehow it ended up being a list of `None`s in that case. Not quite sure why. Making multiprocessing optional is a very good idea (I only added it recently, so I didn't yet have the need to turn it off, but it might come up eventually)." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-14T15:52:58.443", "Id": "232389", "ParentId": "232376", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-14T11:20:15.403", "Id": "232376", "Score": "3", "Tags": [ "python", "timer", "matplotlib", "multiprocessing" ], "Title": "Plot timings for a range of inputs MkII" }
232376
<p>I have a for of loop, for each item in the <code>childElements</code> HTMLCollection I want to subtract the height of the elements from the parent height.</p> <pre><code>let height = element[0].clientHeight; const childElements = &lt;[HTMLElement]&gt;element[0].children; let i = 0; for (const childElement of childElements) { if (i !== childElements.length - 1) { height -= Math.ceil(childElement.clientHeight); } i++; } return height; </code></pre> <p>But I want to exclude the last HTMLElement in the collection from the for loop. I've now created a i variable that is checked against the length of the collection minus 1. If that's not the case the height of the element is subtracted and i is increased.</p> <p>This works fine, but it feels like I'm doing two things (for of loop and while loop). Any suggestions?</p>
[]
[ { "body": "<p>It hit me,</p>\n\n<pre><code>function returnSuggestedColleaguesWithExpertiseHeight(): number {\n let height = element[0].clientHeight;\n const childElements = &lt;[HTMLElement]&gt;element[0].children;\n for (let i = 0; i &lt; childElements.length - 1; i++) {\n height -= Math.ceil(childElements[i].clientHeight);\n }\n return height;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-14T13:41:28.817", "Id": "232381", "ParentId": "232380", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-14T13:29:55.950", "Id": "232380", "Score": "0", "Tags": [ "typescript" ], "Title": "for of loop that stops at last object of array" }
232380
<p>Hello I would like to use python to change the author of an html file, in order to do so I have written a few lines.</p> <p>First I have used the <code>HTMLParser</code> class from the standard library to make a class that indicates which line of the html page needs to be changed.</p> <pre class="lang-py prettyprint-override"><code>from html.parser import HTMLParser class AuthorFinder(HTMLParser): def __init__(self): super().__init__() self._edition_line = None def handle_starttag(self, tag, attrs): ''' If the tag handled is the meta tag containing the author's name, then the value of _edition_line will be set to the current line (starting from 0) ''' if tag.lower() == 'meta': for a_tuple in attrs: name, value = (field.lower() for field in a_tuple) if name == 'name' and value == 'author': # getpos() returns (line, column) starting from (1, 1) # whereas I want the first index to be 0. self._edition_line = self.getpos()[0] - 1 @property def edition_line(self): return self._edition_line </code></pre> <p>I then use that class to get the line of the meta tag that contains the author. The following function changes the whole line and return and the new html page as a string.</p> <pre class="lang-py prettyprint-override"><code>def change_author(html_code, author): html_parser = AuthorFinder() html_parser.feed(html_code) author_line = html_parser.edition_line html_lines = html_code.splitlines() new_tag = '&lt;meta name="author" content="{}"&gt;'.format(author) html_lines[author_line] = new_tag new_html = '\n'.join(html_lines) return new_html </code></pre> <p>From there you can easily change the author of several html files with something as simple as this:</p> <pre class="lang-py prettyprint-override"><code># put the path to your html files in here html_files = ['example1.html', 'example2.html'] new_author = 'Mario Luigi' for filename in html_files: with open(filename, 'rt') as f: html_code = f.read() new_code = change_author(html_code, new_author) new_filename = '{}-NewAuthor.html'.format(filename.split('.')[0]) with open(new_filename, 'w') as f: f.write(new_code) </code></pre> <p>Here is my first, quick attempt at automating file editing. I would like, in the future, to automate more changes but for now let's focus on this one. The script works fine but I'm pretty sure it can be improved in several ways as:</p> <ul> <li>the class <code>AuthorFinder</code> will keep on parsing even though the desired <code>meta</code> tag has been found</li> <li>if no <code>meta</code> tag with the author's name has been found, no author will be added</li> <li>the previous indentation is ignored</li> <li>... </li> </ul> <p>I will try to find ways to improve this, and hope to get suggestions from here as well. Thank you for reading, and good day.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-19T14:48:46.073", "Id": "454372", "Score": "0", "body": "Do you have some example data that could be used to run the program?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-20T09:04:33.503", "Id": "454480", "Score": "0", "body": "@AlexanderCécile I have made a [github repo](https://github.com/LouisonCalbrix/tiny-html-automator) for this tiny project, it contains two html files for testing purpose." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-20T21:11:25.107", "Id": "454559", "Score": "0", "body": "Awesome, I'll check it out :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-20T21:54:14.907", "Id": "454563", "Score": "0", "body": "The tag with the author is guaranteed to always be under '/html/head', right?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-20T22:32:09.740", "Id": "454564", "Score": "0", "body": "Also, what is your reasoning for choosing html.parser over something like BeautifulSoup or lxml?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-22T10:45:25.003", "Id": "454734", "Score": "0", "body": "@AlexanderCécile First of all, `html.parser` seemed like a suitable option because it's part of the standard library and I would like to build a tiny, minimalistic program, therefore I would like it to rely on the least additional package possible. Secondly, I, indeed, assume that the meta tag (stating who the author is) will always be in the head section." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-23T01:43:58.453", "Id": "454869", "Score": "0", "body": "Are you open to solutions which don’t use `html.parser`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-24T16:04:11.823", "Id": "455015", "Score": "0", "body": "@AlexanderCécile I am not fundamentaly against a solution that doesn't use `html.parser` as long as it does actually improve the program and not just barely do it with some other tools." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-24T19:00:53.913", "Id": "455035", "Score": "0", "body": "What do you mean by _and not just barely do it with some other tools_?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-16T02:53:38.393", "Id": "457794", "Score": "0", "body": "Are you still working on this/looking for answers? :)" } ]
[ { "body": "<p>I'm going to try writing a few different versions of your program. I think it would make for a nice, basic comparison of the various alternatives.</p>\n<p>Of course, this all hinges on the number of changes, and their complexity, you wish to make. In that regard, it would be nice to get some more information on those changes, even if you haven't written the code for it yet.</p>\n<hr />\n<h3>Pure lxml, <code>.find()</code> with a simple XPath expression.</h3>\n<pre class=\"lang-py prettyprint-override\"><code>from lxml import etree\n\nparser = etree.HTMLParser()\ntree = etree.parse('../resources/author_parser_test_1.html', parser=parser)\n\nauthor_tag = tree.find(&quot;./head/meta[@name='author']&quot;)\n\nif author_tag is None:\n print(&quot;Couldn't find author tag&quot;)\nelse:\n author_tag.set('content', 'New Author')\n tree.write('../out/author_parser_test_1_res.html', method='html', pretty_print=False)\n</code></pre>\n<hr />\n<h3>BeautifulSoup using lxml as the parser</h3>\n<pre class=\"lang-py prettyprint-override\"><code>from bs4 import BeautifulSoup\n\nwith open('../resources/author_parser_test_1.html', 'r') as file_1:\n soup = BeautifulSoup(file_1, features='lxml')\n\nauthor_tag = soup.find('meta', attrs={'name': 'author'})\n\nif author_tag is None:\n print(&quot;Couldn't find author tag&quot;)\nelse:\n author_tag['content'] = 'New author'\n with open('../out/author_parser_test_1_res.html', 'w') as file_1:\n file_1.write(soup.prettify())\n</code></pre>\n<hr />\n<p>I will keep updating this post as I work.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-21T02:09:45.647", "Id": "232724", "ParentId": "232386", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "10", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-14T14:49:11.880", "Id": "232386", "Score": "3", "Tags": [ "python", "beginner", "python-3.x", "html", "automation" ], "Title": "Automate html file editing with python - Change the author" }
232386
<p>I've previously came up with the question "<a href="https://codereview.stackexchange.com/questions/232266/rolling-dice-in-a-method-chain">Rolling dice in a method chain</a>" and was interested if this could be improved. It could, so now I have this class:</p> <pre><code>public class DiceQueue : IEnumerable&lt;int&gt; { public int Sides { get; } internal Random Rnd = new Random(); public DiceQueue(int sides) { Sides = sides; } public int Roll() =&gt; Rnd.Next(Sides) + 1; public IEnumerator&lt;int&gt; GetEnumerator() { while (true) { yield return Roll(); } } IEnumerator IEnumerable.GetEnumerator() =&gt; GetEnumerator(); } </code></pre> <p>Very simple: just create a queue by calling the constructor with a number of sides and then it can be used as an infinite enumerator. But generally, you just want to take an X amount of values from the queue at once, or even just roll a single die. But this class isn't that interesting, as I want to do statistics with random rolls!<br> So, hence this class:</p> <pre><code>public class Statistics : IEnumerable&lt;Point&lt;long&gt;&gt; { public string Name { get; private set; } public long Sum { get; private set; } = 0; public long Total { get; private set; } = 0; public long Min { get; private set; } = long.MaxValue; public long Max { get; private set; } = long.MinValue; public double Average =&gt; 1.0 * Sum / Total; public double TotalOf(int value) =&gt; Totals.ContainsKey(value) ? 100.0 * Totals[value] / Total : 0.0; protected Dictionary&lt;long, long&gt; Totals { get; set; } = new Dictionary&lt;long, long&gt;(); public event EventHandler&lt;StatisticsEventArgs&gt; Added; protected virtual void OnAdded(StatisticsEventArgs e) { Added?.Invoke(this, e); } public Statistics() : this("No name") { } public Statistics(string name) { Name = name; } public Statistics Add(long value) { if (!Totals.ContainsKey(value)) { Totals.Add(value, 0); } Totals[value] += 1; Total++; Sum += value; if (Max &lt; value) { Max = value; } if (value &lt; Min) { Min = value; } OnAdded(new StatisticsEventArgs(this, value)); return this; } public IEnumerable&lt;string&gt; Report() { yield return $"Report for: {Name}"; yield return $"The total sum is {Sum} for {Total} values for an average value of {Average:0.00}."; yield return $"The values are all between {Min} and {Max}."; yield return "List of values"; foreach (var point in this) { yield return $"* Value {point.X} occurred {point.Y} times: {100.0 * point.Y / Total:00.0}%."; } yield return new string('-', 40); } public override string ToString() =&gt; string.Join(Environment.NewLine, Report()); public IEnumerator&lt;Point&lt;long&gt;&gt; GetEnumerator() { foreach (var total in Totals.OrderBy(pair =&gt; pair.Key)) { yield return new Point&lt;long&gt; { X = total.Key, Y = total.Value }; } } IEnumerator IEnumerable.GetEnumerator() =&gt; GetEnumerator(); } </code></pre> <p>It has a name and you just add values to it and it will keep various statistics about it. The Report() method will generate a textual report of the summary but it's mainly used for the ToString() method. Interesting way to make multiline reports, btw.<br> It also has an event which gets triggered whenever a new value is added, allowing the system to display a running total.<br> I have to show a few more types, though. First:</p> <pre><code>public class Point&lt;T&gt; { public T X { get; internal set; } public T Y { get; internal set; } } </code></pre> <p>Not really rocket science. And while C# does have a Point datatype somewhere, I wanted one that's more generic...</p> <pre><code>public class StatisticsEventArgs : EventArgs { public Statistics Stats { get; } public long LastValue { get; } public StatisticsEventArgs(Statistics stats, long lastValue) { Stats = stats; LastValue = lastValue; } } </code></pre> <p>Yeah, well... The event requires an argument. This one should be it. Trying to follow the standard for events here.<br> But I want to use the statistics in a chainable way and I want to do statistics on rolls of multiple dice, so I also have these extension methods:</p> <pre><code>public static class Toolkit { public static IEnumerable&lt;T&gt; Do&lt;T&gt;(this IEnumerable&lt;T&gt; data, Action&lt;T&gt; action) { foreach (var item in data) { action(item); yield return item; } } public static IEnumerable&lt;List&lt;T&gt;&gt; TakeGroup&lt;T&gt;(this IEnumerable&lt;T&gt; data, int count) { while (true) { yield return data.Take(count).ToList(); } } } </code></pre> <p>The Do() method just does some action with a value from an enumerator before passing the value on to the next method. Maybe not elegant, but I have no other options here, as far as I know.<br> The TakeGroup() method will grab an X amount of values and return them as a list, and keeps doing this until infinity. Too bad that this might cause trouble if the base enumeration is limited so I need to work out a solution for that. A Partitioner, perhaps? Well, still have to work that out but this works for my current purpose...<br> Then something to test the whole thing. </p> <pre><code>public static class StatisticsTest { public static void Execute(int count) { Console.WriteLine($"We've rolled for a total of {D6X3RollQueue.Take(count).Count()} times."); Console.WriteLine(D6Stat); Console.WriteLine(D6X3MinStat); Console.WriteLine(D6X3MaxStat); Console.WriteLine(D6X3MinMaxStat); Console.WriteLine(D6X3SumStat); } private static readonly DiceQueue D6 = new DiceQueue(6); private static readonly Statistics D6Stat = new Statistics("Rolling d6"); private static readonly Statistics D6X3MinStat = new Statistics("Minimum of 3D6 (1 to 6)"); private static readonly Statistics D6X3MaxStat = new Statistics("Maximum of 3D6 (1 to 6)"); private static readonly Statistics D6X3MinMaxStat = new Statistics("Sum(Min+Max) of 3D6 (2 to 12)"); private static readonly Statistics D6X3SumStat = new Statistics("Sum of 3D6 (3 to 18)"); private static readonly IEnumerable&lt;int&gt; D6RollQueue = D6.Do(d =&gt; D6Stat.Add(d)); private static readonly IEnumerable&lt;int&gt; D6X3RollQueue = D6RollQueue.TakeGroup(3) .Do(d =&gt; D6X3MinStat.Add(d.Min())) .Do(d =&gt; D6X3MaxStat.Add(d.Max())) .Do(d =&gt; D6X3MinMaxStat.Add(d.Min() + d.Max())) .Select(d =&gt; d.Sum()) .Do(d =&gt; D6X3SumStat.Add(d)); } </code></pre> <p>This shows why I want a dice queue. The queue allows me to collect various statistics for all the rolls made while I can roll as many times as I like. By declaring a queue like <code>D6RollQueue</code> I can take a single roll by using <code>D6RollQueue.First()</code> or an X amount of rolls by using `D6RollQueue.Take(X)' and then do something with the result, while the queue keeps track of all statistics. So when I create some dice game, I can just roll as often as I like while having various statistics about the rolls.<br> And the TakeGroup() method will allow me to maintain statistics about groups of rolls like rolling three dice and keep statistics about the minimum and maximum values. </p> <p>So, go ahead and shoot at it. Can it be improved?<br> (It's not that important that the Random generator might be predictable.)</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-14T17:37:07.570", "Id": "453818", "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": "<ul>\n<li><p>If you need to get a value of a <code>Dictionary&lt;TKey, TValue&gt;</code> you shouldn't use <code>ContainsKey()</code> together with the <code>Item</code> property getter but <code>TryGetValue()</code>, because by using <code>ContainsKey()</code> in combination with the <code>Item</code> getter you are doing the check if the key exists twice.<br>\nFrom the <a href=\"https://referencesource.microsoft.com/\" rel=\"nofollow noreferrer\">refernce source</a> </p>\n\n<p><a href=\"https://referencesource.microsoft.com/#mscorlib/system/collections/generic/dictionary.cs,22fd7cd7408aed6e,references\" rel=\"nofollow noreferrer\">ContainsKey(TKey)</a></p>\n\n<pre><code>public bool ContainsKey(TKey key) {\n return FindEntry(key) &gt;= 0;\n}\n</code></pre>\n\n<p><a href=\"https://referencesource.microsoft.com/#mscorlib/system/collections/generic/dictionary.cs,49962975508e2d83,references\" rel=\"nofollow noreferrer\">this[TKey]</a></p>\n\n<pre><code>public TValue this[TKey key] {\n get {\n int i = FindEntry(key);\n if (i &gt;= 0) return entries[i].value;\n ThrowHelper.ThrowKeyNotFoundException();\n return default(TValue);\n }\n set {\n Insert(key, value, false);\n }\n}\n</code></pre>\n\n<p><a href=\"https://referencesource.microsoft.com/#mscorlib/system/collections/generic/dictionary.cs,2e5bc6d8c0f21e67,references\" rel=\"nofollow noreferrer\">TryGetValue(TKey, out TValue)</a></p>\n\n<pre><code>public bool TryGetValue(TKey key, out TValue value) {\n int i = FindEntry(key);\n if (i &gt;= 0) {\n value = entries[i].value;\n return true;\n }\n value = default(TValue);\n return false;\n}\n</code></pre>\n\n<p>Each of these public methods is calling the private <a href=\"https://referencesource.microsoft.com/#mscorlib/system/collections/generic/dictionary.cs,bcd13bb775d408f1,references\" rel=\"nofollow noreferrer\">FindEntry(TKey)</a>. As you see a combination of <code>ContainsKey()</code> together with the <code>Item</code> getter is doing the call twice.</p>\n\n<pre><code>private int FindEntry(TKey key) {\n if( key == null) {\n ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key);\n }\n\n if (buckets != null) {\n int hashCode = comparer.GetHashCode(key) &amp; 0x7FFFFFFF;\n for (int i = buckets[hashCode % buckets.Length]; i &gt;= 0; i = entries[i].next) {\n if (entries[i].hashCode == hashCode &amp;&amp; comparer.Equals(entries[i].key, key)) return i;\n }\n }\n return -1;\n}\n</code></pre>\n\n<p>So this </p>\n\n<pre><code>if (!Totals.ContainsKey(value)) { Totals.Add(value, 0); }\nTotals[value] += 1; \n</code></pre>\n\n<p>should be written like this </p>\n\n<pre><code>Totals.TryGetValue(value, out long current);\nTotals[value] = current + 1;\n</code></pre>\n\n<p>But just looking at the above code, it just seems strange to have <code>ContainsKey(value)</code>. It would be better to rename <code>value</code> to something else.</p></li>\n<li><p>I don't like such oneliners shown in the code. IMO it is harder to read the code and grasp at first glance what it is about. </p></li>\n<li><p>The extension methods could use some improvement as well. You should add proper argument validation into the methods. Nobody wants to get a <code>NullReferenceException</code> out of a <code>public</code> method. </p></li>\n<li><p>The <code>Name</code> property doesn't need a setter because you are assigning a value only in the constructor.</p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-14T16:02:37.173", "Id": "453799", "Score": "0", "body": "I don't like to use TryGetValue() in this case as I need to create new items for the dictionary. TryGetValue() requires me to declare an extra variable. So, this perhaps? `if (Totals.ContainsKey(value)) { Totals[value] += 1; } else { Totals.Add(value, 1); }`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-14T16:05:42.150", "Id": "453800", "Score": "0", "body": "You are creating new items by the way I showed and as a bonus this part will run faster as well." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-14T16:06:46.563", "Id": "453801", "Score": "0", "body": "As for oneliners... We have different preferences as I like oneliners. It keeps the amount of lines shorter so more lines fit on the screen and they're generally very short functions so they would be 4 lines otherwise. (Plus a blank line.) But as I said, it's a personal preference..." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-14T15:34:21.627", "Id": "232388", "ParentId": "232387", "Score": "4" } }, { "body": "<ul>\n<li><s>The number of times a given value has been added to a statistics batch shouldn't be a <code>long</code>, it should be an <code>int</code> (maybe unsigned).</s> (I was mistaken about what <code>long</code> was).</li>\n<li>That would seem to break your <code>Point</code> implementation, but you probably shouldn't be using that in the first place. The items in question aren't \"points\"; they don't spatially relate to each other. Just use <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.tuple?view=netframework-4.8\" rel=\"nofollow noreferrer\">tuples</a>.</li>\n<li>The <code>DiceQueue</code> class yields <code>int</code>s, so it would be ideal if <code>Statistics</code> also handled <code>int</code>s. Can you make <code>Statistics</code> generic across numerical types?</li>\n<li>I suspect that you can shorten/simplify a lot of this using <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.linq?view=netframework-4.8\" rel=\"nofollow noreferrer\">Linq</a>, maybe to the point where it no longer needs to be wrapped up in classes the way you have it. But I don't know what that would look like exactly.</li>\n</ul>\n\n<p>It's hard to talk about the ideal way to do what you're trying to do without knowing what you're working toward. How will these tools be used?</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-14T18:14:55.890", "Id": "453827", "Score": "0", "body": "Well, the statistics are meant to be shown in a graph, so that makes them points, not tuples. After all, the statistics for the 3D6 should display a bell curve. Points could use int instead, but sum might overflow int.MaxValue so that's why I use long. Making the Statistics class more generic would be nice, but as I need T.MinValue and T.MaxValue, it would be challenging to pick a base type. Any suggestions on how to make it more numerically generic?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-14T18:18:04.610", "Id": "453828", "Score": "0", "body": "As for what I'm trying to do, simple: I'm building a library with various functions and this one is for statistical purposes. I'm also working on linear regression and other statistics that could be used in similar method chains. The method chain is technically Linq, but I want statistics to be part of any Linq query without having to walk through a list multiple times. The statistics are technically running totals." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-14T18:35:50.243", "Id": "453830", "Score": "1", "body": "I guess there's no such thing as an `INumerical` in C#; pity." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-14T18:50:17.247", "Id": "453834", "Score": "0", "body": "One suggestion, every numerical type, except perhaps BigInteger, can convert to double. That can be used to make sure you have a numerical type." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-14T21:54:59.223", "Id": "453853", "Score": "0", "body": "@tinstaafl True, I could use doubles. But floats are a bit harder to compare due to rounding errors. In floats, 1/3 and 2/6 can be different due to the binary representation. This makes the dictionary I use a bit more challenging. I tend to avoid float types, if possible, because of potential comparison problems..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-14T23:09:14.027", "Id": "453862", "Score": "0", "body": "You don't need to use them for calculations only for checking that the generic type is of a proper type. If you want the type narrowed even further you can use `ulong`." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-14T17:53:20.837", "Id": "232398", "ParentId": "232387", "Score": "4" } } ]
{ "AcceptedAnswerId": "232388", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-14T15:17:35.127", "Id": "232387", "Score": "7", "Tags": [ "c#", "functional-programming" ], "Title": "Chaining statistics in a dice queue" }
232387
<p>I've just refactored my Rust and C++ code which simulates the shoeshine shop model from <a href="https://codereview.stackexchange.com/questions/232106/shoe-shine-shop-model-in-rust">this</a> question. What else can be improved?</p> <p>C++:</p> <pre class="lang-cpp prettyprint-override"><code>#include &lt;iostream&gt; #include &lt;iomanip&gt; #include &lt;random&gt; #include &lt;numeric&gt; #include &lt;algorithm&gt; #include &lt;array&gt; #include &lt;queue&gt; #include &lt;string&gt; #include &lt;functional&gt; namespace shoeshine_shop { enum event_t { ARRIVED, FIRST_FINISHED, SECOND_FINISHED }; enum state_t { EMPTY, FIRST, SECOND, WAITING, BOTH, DROP, INVALID }; using distribution_t = std::function&lt;double()&gt;; struct pair_t { double time; event_t event; }; struct stats_t { std::array&lt;size_t, DROP&gt; state_counts; std::array&lt;size_t, DROP&gt; state_counts_with_drop; std::array&lt;double, DROP&gt; time_in_state; std::array&lt;double, 3&gt; time_in_client; double served_time; size_t served_clients, arrived_clients, dropped_clients; }; class simulation_t { private: template &lt;typename T&gt; auto print_tables(std::string_view title, T const &amp;counts) { std::cout &lt;&lt; title &lt;&lt; "\n"; auto events = std::accumulate(std::begin(counts), std::end(counts), 0.0); for (size_t i = 0; i &lt; DROP; ++i) std::cout &lt;&lt; state_names[i] &lt;&lt; ": " &lt;&lt; counts[i] / double(events) &lt;&lt; std::endl; std::cout &lt;&lt; std::endl; } void debug_view(pair_t &amp;event, state_t &amp;state) { std::cout &lt;&lt; "\t" &lt;&lt; std::setprecision(std::numeric_limits&lt;double&gt;::digits10 + 1) &lt;&lt; event.time &lt;&lt; ": [" &lt;&lt; state_names[state] &lt;&lt; "] " &lt;&lt; event_names[event.event] &lt;&lt; " ==&gt; [" &lt;&lt; state_names[event_to_state[event.event][state]] &lt;&lt; "]" &lt;&lt; std::endl; } public: simulation_t(distribution_t arrival, distribution_t first_serving, distribution_t second_serving, std::uint64_t iterations = 50) : window{queue_comparator}, iterations{1'000'000 * iterations}, distributions{arrival, first_serving, second_serving}, log_tail{0} {} auto set_tail(std::uint64_t new_tail) noexcept { log_tail = new_tail; } bool simulate() { static auto pusher = [&amp;](double t, event_t event) { double dt = distributions[event](); window.push({t + dt, event}); }; state_t state = EMPTY; double prev = 0.0; std::queue&lt;double&gt; arriving_times; window.push({0.0, ARRIVED}); for (std::uint64_t i = 0; i &lt; iterations; ++i) { auto event = window.top(); window.pop(); if (iterations - i &lt; log_tail) debug_view(event, state); switch (event.event) { case ARRIVED: ++statistics.arrived_clients; pusher(event.time, ARRIVED); break; case SECOND_FINISHED: statistics.served_time += event.time - arriving_times.front(); arriving_times.pop(); ++statistics.served_clients; } state_t new_state = event_to_state[event.event][state]; switch (new_state) { case INVALID: return false; case DROP: ++statistics.state_counts_with_drop[state]; ++statistics.dropped_clients; continue; case FIRST: case BOTH: if (event.event == ARRIVED) { arriving_times.push(event.time); pusher(event.time, FIRST_FINISHED); } break; case SECOND: pusher(event.time, SECOND_FINISHED); break; case EMPTY: case WAITING: break; } statistics.time_in_state[state] += event.time - prev; statistics.time_in_client[state_to_clients[state]] += event.time - prev; prev = event.time; state = new_state; ++statistics.state_counts[state]; } return true; } void print_report() { std::transform(std::begin(statistics.state_counts), std::end(statistics.state_counts), std::begin(statistics.state_counts_with_drop), std::begin(statistics.state_counts_with_drop), std::plus&lt;std::size_t&gt;()); print_tables("time in states: ", statistics.time_in_state); print_tables("entries in states: ", statistics.state_counts); print_tables("entries in states with dropouts: ", statistics.state_counts_with_drop); std::cout &lt;&lt; "dropout: " &lt;&lt; statistics.dropped_clients / double(statistics.arrived_clients) &lt;&lt; std::endl; std::cout &lt;&lt; "average serving time: " &lt;&lt; statistics.served_time / double(statistics.served_clients) &lt;&lt; std::endl; std::cout &lt;&lt; "average number of clients: " &lt;&lt; (statistics.time_in_client[1] + 2 * statistics.time_in_client[2]) / std::accumulate(std::begin(statistics.time_in_client), std::end(statistics.time_in_client), 0.0) &lt;&lt; std::endl; } private: static constexpr std::array&lt;const char *, 3&gt; event_names{ {"ARRIVED", "FIRST_FINISHED", "SECOND_FINISHED"}}; static constexpr std::array&lt;const char *, 7&gt; state_names{ {"EMPTY", "FIRST", "SECOND", "WAITING", "BOTH", "DROP", "INVALID"}}; // clang-format off static constexpr std::array&lt;std::array&lt;state_t, 5&gt;, 3&gt; event_to_state{ // EMPTY FIRST SECOND WAITING BOTH /* ARRIVED */ {{FIRST, DROP, BOTH, DROP, DROP}, /* FIRST_FINISHED */ {INVALID, SECOND, INVALID, INVALID, WAITING}, /* SECOND_FINISHED */ {INVALID, INVALID, EMPTY, SECOND, FIRST}}}; // clang-format on static constexpr std::array&lt;size_t, DROP&gt; state_to_clients{0, 1, 1, 2, 2}; inline static const auto queue_comparator = [](pair_t const &amp;left, pair_t const &amp;right) { return (left.time &gt; right.time); }; stats_t statistics{}; std::priority_queue&lt;pair_t, std::vector&lt;pair_t&gt;, decltype(queue_comparator)&gt; window; std::uint64_t iterations; std::array&lt;distribution_t, 3&gt; distributions; std::uint64_t log_tail; }; } // namespace shoeshine_shop int main(int argc, char **argv) { if (argc &lt; 5) { std::cerr &lt;&lt; "not enough arguments!\nlambda, m1, m2, millions of iterations"; return EXIT_FAILURE; } std::uint32_t seed = std::random_device{}(); std::mt19937 gen(seed); std::exponential_distribution arrival(std::atof(argv[1])); std::exponential_distribution first_serving(std::atof(argv[2])); std::exponential_distribution second_serving(std::atof(argv[3])); shoeshine_shop::simulation_t simul(std::bind(arrival, std::ref(gen)), std::bind(first_serving, std::ref(gen)), std::bind(second_serving, std::ref(gen)), std::atoll(argv[4])); if (argc == 6) { seed = std::atol(argv[5]); gen.seed(seed); simul.set_tail(100); } if (!simul.simulate()) { std::cerr &lt;&lt; "ERROR: INVALID STATE REACHED, SEED: " &lt;&lt; seed &lt;&lt; std::endl; return EXIT_FAILURE; } simul.print_report(); return EXIT_SUCCESS; } </code></pre> <p>Rust:</p> <pre class="lang-rust prettyprint-override"><code>use rand::{rngs::StdRng, Rng, SeedableRng}; use rand_distr::Exp; use structopt::StructOpt; mod shoeshine_shop { use std::cmp::Reverse; use std::collections::{BinaryHeap, VecDeque}; use std::convert::TryInto; use ordered_float::*; use rand::rngs::StdRng; use rand_distr::Distribution; #[derive(Copy, Clone, Debug, PartialEq, Ord, Eq, PartialOrd, enum_utils::TryFromRepr)] #[repr(usize)] enum Event { Arrived = 0, FirstFinished, SecondFinished, } #[derive(Copy, Clone, Debug, PartialEq, Ord, Eq, PartialOrd, enum_utils::TryFromRepr)] #[repr(usize)] enum State { Empty = 0, First, Second, Waiting, Both, Dropping, Invalid, } #[derive(Copy, Clone, Debug, Ord, Eq, PartialEq, PartialOrd)] struct Pair { time: OrderedFloat&lt;f64&gt;, event: Event, } #[rustfmt::skip] #[derive(Debug, Default)] struct Stats { state_counts: [u32; State::Dropping as usize], state_counts_with_drop: [u32; State::Dropping as usize], time_in_state: [f64; State::Dropping as usize], time_in_client: [f64; 3], served_time: f64, served_clients: u32, arrived_clients: u32, dropped_clients: u32, } const STATE_TO_CLIENTS: [usize; State::Dropping as usize] = [0, 1, 1, 2, 2]; #[rustfmt::skip] const EVENT_TO_STATE: [[State; 5]; 3] = [ // EMPTY FIRST SECOND WAITING BOTH /* Arrived */ [First, Dropping, Both, Dropping, Dropping], /* First_Finished */ [Invalid, Second, Invalid, Invalid, Waiting], /* Second_Finished */ [Invalid, Invalid, Empty, Second, First], ]; macro_rules! report { ($title:expr, $counts:expr) =&gt; {{ println!("{}", $title); let events: f64 = $counts.iter().copied().map(Into::&lt;f64&gt;::into).sum(); for (i, count) in $counts.iter().enumerate() { let state: State = i.try_into().unwrap(); println!("{:?}: {}", state, Into::&lt;f64&gt;::into(*count) / events); } println!(); }}; } pub struct Simulation&lt;T: Distribution&lt;f64&gt;&gt; { statistics: Stats, window: BinaryHeap&lt;Reverse&lt;Pair&gt;&gt;, iterations: u64, distributions: [T; 3], log_tail: u64, } use Event::*; use State::*; impl&lt;T&gt; Simulation&lt;T&gt; where T: Distribution&lt;f64&gt;, { pub fn new( arrival: T, first_serving: T, second_serving: T, iterations: u64, ) -&gt; Simulation&lt;T&gt; { Simulation { statistics: Stats::default(), window: BinaryHeap::new(), iterations: iterations, distributions: [arrival, first_serving, second_serving], log_tail: 0, } } pub fn set_tail(&amp;mut self, new_tail: u64) { self.log_tail = new_tail; } pub fn print_report(&amp;mut self) { for (i, element) in self .statistics .state_counts_with_drop .iter_mut() .enumerate() { *element += self.statistics.state_counts[i]; } report!("\ntime in states: ", self.statistics.time_in_state); report!("entries in states: ", self.statistics.state_counts); report!( "entries in states with dropouts: ", self.statistics.state_counts_with_drop ); println!( "dropout: {}\naverage serving time: {}\naverage number of clients: {}", (self.statistics.dropped_clients as f64) / (self.statistics.arrived_clients as f64), self.statistics.served_time / (self.statistics.served_clients as f64), (self.statistics.time_in_client[1] + 2.0f64 * self.statistics.time_in_client[2]) / self.statistics.time_in_client.iter().sum::&lt;f64&gt;() ); } pub fn simulate(&amp;mut self, prng: &amp;mut StdRng) -&gt; bool { macro_rules! pusher { ($t:expr, $event:expr) =&gt; {{ let dt: f64 = self.distributions[$event as usize].sample(prng).into(); self.window.push(Reverse(Pair { time: ($t + dt).into(), event: $event, })); }}; } let mut prev = 0f64; let mut state = State::Empty; let mut arriving_times = VecDeque::&lt;f64&gt;::new(); self.window.push(Reverse(Pair { time: 0.0.into(), event: Arrived, })); for i in 0..self.iterations { let event = self.window.pop().unwrap().0; if self.iterations - i &lt; self.log_tail { println!( "{}: [{:?}] {:?} ==&gt; [{:?}]", event.time.0, state, event.event, EVENT_TO_STATE[event.event as usize][state as usize] ); } match event.event { Arrived =&gt; { self.statistics.arrived_clients += 1; pusher!(event.time.0, Arrived); } SecondFinished =&gt; { self.statistics.served_time += event.time.0 - arriving_times.front().unwrap(); arriving_times.pop_front(); self.statistics.served_clients += 1; } _ =&gt; (), } let new_state = EVENT_TO_STATE[event.event as usize][state as usize]; match new_state { Invalid =&gt; return false, Dropping =&gt; { self.statistics.state_counts_with_drop[state as usize] += 1; self.statistics.dropped_clients += 1; continue; } First | Both if event.event == Arrived =&gt; { arriving_times.push_back(event.time.0); pusher!(event.time.0, FirstFinished); } Second =&gt; pusher!(event.time.0, SecondFinished), _ =&gt; (), } self.statistics.time_in_state[state as usize] += event.time.0 - prev; self.statistics.time_in_client[STATE_TO_CLIENTS[state as usize]] += event.time.0 - prev; prev = event.time.0; state = new_state; self.statistics.state_counts[state as usize] += 1; } true } } } ///shoe shine shop simulation /// /// Shoe shine shop has two chairs, one for brushing (1) and another for polishing (2). /// Customers arrive according to PP with rate λ, and enter only if first chair is empty. /// Shoe-shiners takes exp(μ1) time for brushing and exp(μ2) time for polishing. #[derive(StructOpt, Debug)] #[structopt(name = "sim")] struct Args { ///rate of customer arrival #[structopt(long)] lambda: f64, ///rate of serving on the first chair #[structopt(long)] mu1: f64, ///rate of serving on the second chair #[structopt(long)] mu2: f64, ///millions of events to simulate #[structopt(short)] iterations: u64, ///expilictly set seed #[structopt(short)] seed: Option&lt;u64&gt;, ///change log tail #[structopt(short, default_value = "0")] tail: u64, } fn main() { let args = Args::from_args(); let mut simulation = shoeshine_shop::Simulation::new( Exp::new(args.lambda).unwrap(), Exp::new(args.mu1).unwrap(), Exp::new(args.mu2).unwrap(), args.iterations * 1_000_000, ); let seed = args.seed.unwrap_or(rand::thread_rng().gen()); simulation.set_tail(args.tail); let mut prng: StdRng = SeedableRng::seed_from_u64(seed); if !simulation.simulate(&amp;mut prng) { panic!("Error: invalid state reached, seed: {}", seed); } simulation.print_report(); } </code></pre>
[]
[ { "body": "<p>Firstly, not all of your states are states. In particular, <code>Invalid</code> and <code>Dropping</code> are not states. Instead, they are types of transitions. The model would make more sense like this:</p>\n\n<pre><code>enum State {\n Empty,\n First,\n Second,\n Both,\n Waiting\n}\n\nenum Transition {\n NewState(State),\n Invalid,\n Dropping\n}\n</code></pre>\n\n<p>Further, I think that transition tables aren't a very Rust-y solution. Instead, I'd recommend using a match like so:</p>\n\n<pre><code>match (state, event) {\n (State::Empty, Event::Arrived) =&gt; Transition::NewState(State::First),\n (State::Second, Event::Arrived) =&gt; Transition::NewState(State::Both),\n (State::_, Event::Arrived) =&gt; Transition::Dropped,\n (State::First, Event::FirstFinished) =&gt; Transition::NewState(State::Second),\n (State::Both, Event::FirstFinished) =&gt; Transition::NewState(State::Waiting),\n (State::Second, Event::SecondFinished) =&gt; Transition::NewState(State::Empty),\n (State::Both, Event::SecondFinished) =&gt; Transition::NewState(State::First),\n (State::Waiting, Event::SecondFinished) =&gt; Transition::NewState(State::Second),\n _ =&gt; Transition::Invalid\n}\n</code></pre>\n\n<p>I would replace all of your <code>[;State::Dropping as usize]</code> arrays with <code>EnumMap</code> from the <code>enum-map</code> crate. It acts like a HashMap but is implemented in terms of an array. If you do that, your code will become somewhat simpler and you should be able to remove all conversions between usize and your state enum.</p>\n\n<p>But, it seems to me that you actually have two pieces of semi-independent state: the state of your two seats. I think your code would simpler if you split them up. Something like this:</p>\n\n<pre><code>enum SeatState {\n Empty,\n Busy,\n Waiting\n}\n\nlet mut seat_state_1 = SeatState::Empty;\nlet mut seat_state_2 = SeatState::Empty;\n\nmatch event {\n Event::Arrived =&gt; {\n if seat_state_1 == SeatState::Empty {\n seat_state_1 = SeatState::Busy;\n } else {\n // handle dropping\n }\n },\n Event::FirstFinished =&gt; {\n if seat_state_1 == SeatState::Busy {\n seat_state_1 = SeatState::Waiting;\n }\n },\n Event::SecondFinished =&gt; {\n if seat_state_2 == SeatState::Busy {\n seat_state_2 = SeatState::Waiting\n }\n }\n}\n\n// If the second seat is finished, they leave.\nif seat_state_2 == SeatState::Waiting {\n seat_state_2 = SeatState::Empty;\n}\n\n// If the first seat is finished and the second seat is free, move over.\nif seat_state_1 == SeatState::Waiting &amp;&amp; seat_state_2 == SeatState::Empty {\n seat_state_1 = SeatState::Empty;\n seat_state_2 = SeatState::Busy;\n}\n</code></pre>\n\n<p>I think this more clearly presents the logic of how the state changes in your model then a transition table.</p>\n\n<p>I would recommend against defining report as a macro as you have down. Don't use a macro when you can use a function. I think part of the reason you did this was because you ended up with a lots of traits on your generic definition. But you should be able to do it more simply:</p>\n\n<pre><code>fn report&lt;T: Copy&gt;(title: &amp;str, counts: &amp;[T]) where f64: From&lt;T&gt; {\n println!(\"{}\", title);\n let events: f64 = counts.iter().copied().map(f64::from).sum();\n\n for (i, count) in counts.iter().enumerate() {\n let state: State = i.try_into().unwrap();\n println!(\"{:?}: {}\", state, f64::from(*count) / events);\n }\n\n println!();\n}\n</code></pre>\n\n<p>You only need the T to be Copy and convertible to f64.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-16T11:16:47.917", "Id": "454019", "Score": "1", "body": "About semi-independent state: your approach is very error-prone because of not interesting/invalid states (like \"second is waiting\") that can be expressed. Also it would mean that I have to match this split state back to one just to calculate statistics. In previous question I was suggested to write a macro which translates transition table into a match statement. But I reckon table is simpler to understand, no? Thanks for enum-map, I'll look into that." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-16T14:08:55.120", "Id": "454036", "Score": "0", "body": "`Invalid` really isn't a *kind of transition* so much as the *lack of a transition*. `Option<Transition>` makes more sense to me." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-16T14:40:08.037", "Id": "454038", "Score": "0", "body": "@trentcl, that would make sense if `Invalid` was the only non-state state. But since we have `Invalid` and `Dropping` It make sense to me to use tree-state enum rather then an option." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-16T14:46:54.830", "Id": "454039", "Score": "0", "body": "True. I broke it down somewhat differently, considering `Dropping` to be an output rather than a transition. But I see where you're coming from." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-16T14:47:40.770", "Id": "454040", "Score": "1", "body": "@rogday, we need to be careful with what we mean by understand. It is very easy to look at a table and see that state `Both` with event `FirstFinished` transitions to `Waiting`. However, it is not easy to understand why that is the correct transition. One has to reverse engineer the logic of the transitions. The really compact representation in a table really doesn not help there." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-16T14:49:21.357", "Id": "454041", "Score": "1", "body": "To me, the match is easier because it is less dense, allows comments to be added for non-obvious transitions, allows the grouping of similar cases to be handled together, and doesn't require me to either count or align items in tet." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-16T14:51:08.223", "Id": "454042", "Score": "0", "body": "Yes, it is a disadvantage that it is possible to express uninteresting states. However, I think the advantage of clearer expression of logic outway that disadvantage." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-16T14:52:48.613", "Id": "454043", "Score": "1", "body": "Now, with all of that, it is subjective and you should feel free to disagree. But I hope I've at least given you an some additional insights in ways to approach these sorts of problems." } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-16T03:14:40.887", "Id": "232478", "ParentId": "232390", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-14T16:31:13.927", "Id": "232390", "Score": "5", "Tags": [ "c++", "comparative-review", "rust", "statistics" ], "Title": "Shoe shine shop model in Rust and C++ - Follow-up" }
232390
<ul> <li>Task: Find the balance point of an array; return the index that if you break the array into <code>left</code> and <code>right</code> at that point will create the same sum on both sides.<br> e.g: given the array <code>[2, 4, 5, 1, -2, 7, 2, 1, 4]</code><br> returned value should be: <code>3</code><br> left: <code>2, 4, 5, 1 = 12</code><br> right: <code>-2, 7, 2, 1, 4 = 12</code></li> </ul> <pre class="lang-js prettyprint-override"><code>public static arrayBalance(input?: number[]): any { let sum = 0; for(let i=0; i&lt;input.length; i++) { let cur = input[i]; sum += cur; } let mid = sum / 2; let sum2 = 0; let ret = 0; while(sum2 &lt; mid &amp;&amp; ret &lt; input.length) { sum2 += input[ret]; ret++; } return sum2 == mid ? (ret - 1) : -1; } </code></pre> <blockquote> <p>Time complexity: <span class="math-container">\$O(2n)\$</span>,<br> Space complexity: <span class="math-container">\$O(1)\$</span></p> </blockquote> <hr> <p>Am I right regarding the complexities?<br> Do you have different implementation suggestions?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-14T17:23:51.060", "Id": "453813", "Score": "0", "body": "Downvoter, care to explain?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-14T17:26:11.363", "Id": "453814", "Score": "3", "body": "Did you write this code? What should we review?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-14T17:43:30.533", "Id": "453820", "Score": "2", "body": "Please post 1 project at a time (unless the tasks completed are done so in a highly similar fashion perhaps, this does not apply). For a guide on posting good questions, [see our relevant FAQ](https://codereview.meta.stackexchange.com/q/2436/52915)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-14T17:43:58.463", "Id": "453821", "Score": "1", "body": "I think this should be posted as two independent questions (I haven't downvoted, but will vote to put your question on hold so you can do that in peace)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-14T18:06:41.470", "Id": "453824", "Score": "0", "body": "Thank you for the feedback, I've broke it down into separate question: https://codereview.stackexchange.com/questions/232399/choosing-between-2-fibonacci-alternatives\n@πάνταῥεῖ- yes I've wrote it. I'd be happy to get a code review and feedback." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-14T20:28:27.677", "Id": "453842", "Score": "0", "body": "How is the balance point defined if the array *cannot* be split into two halves with same sum? E.g. for `[1, 2, 3, 10]`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-14T21:00:20.777", "Id": "453847", "Score": "0", "body": "@MartinR the alg expected to return `-1` in such case" } ]
[ { "body": "<p>First, a suggestion on the interface: use <code>null</code> to represent no match rather than <code>-1</code>, since that makes it easier to force the caller to check for a no-solution case (i.e. if they try to use the unchecked return of this function as an index, a <code>-1</code> will only fail at runtime, whereas <code>null</code> will fail at transpile time).</p>\n\n<pre><code>function arrayBalance(input: number[]): number | null {\n</code></pre>\n\n<p>In reading over the code I got confused by the variable names -- <code>mid</code> isn't actually a midpoint, it's the expected sum of each half. Between all of the variables being declared with <code>let</code> rather than <code>const</code> and the uninformative names (why is there <code>sum</code> and <code>sum2</code>?), it's hard to even tell at a glance which values are being recalculated and which are constants. </p>\n\n<p>Instead of taking six lines of code to find the \"half-sum\" that we want each side of the \"split\" to have, let's just do it in one (brevity is the soul of wit, and this kind of thing is exactly what the <code>reduce</code> function is for), and declare it as <code>const</code> since it's not going to change for the rest of the function once we've computed it:</p>\n\n<pre><code>const halfSum = input.reduce((a, b) =&gt; a + b) / 2;\n</code></pre>\n\n<p>From here, all we need to do is find out how many array elements we need to total up to equal <code>halfSum</code>.</p>\n\n<p>Here's how I might write the rest, signifying the running total of the \"left\" side of the array as <code>leftSum</code> and doing a simple <code>for</code> loop over the array indices:</p>\n\n<pre><code>let leftSum = 0;\nfor (let i = 0; i &lt; input.length; i++)\n{\n leftSum += input[i];\n if (leftSum == halfSum)\n return i;\n}\nreturn null;\n</code></pre>\n\n<p>As we iterate through <code>i</code> we build a sum of everything to the left of <code>i</code> (<code>leftSum</code>). Our goal is to make <code>leftSum</code> equal <code>halfSum</code>. If no solution is found within the loop we return <code>null</code>.</p>\n\n<p>It's tempting to use inequality comparisons to try to optimize the no-solution case, but consider cases where the input array has lots of negative numbers distributed randomly! <code>halfSum</code> could be negative or zero, and <code>leftSum</code> could go up and then down and then up and then down again as you increment <code>i</code>, so unless you've gone through the entire array you can't ever be certain that a solution does not exist.</p>\n\n<p>Note also that it's possible for there to be multiple valid solutions; this implementation will always return the lowest one in that instance, but you could write a version of this function that always goes through the entire array and returns another array of all the solutions it found.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-17T18:38:54.030", "Id": "232556", "ParentId": "232393", "Score": "3" } } ]
{ "AcceptedAnswerId": "232556", "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-14T17:13:10.567", "Id": "232393", "Score": "3", "Tags": [ "interview-questions", "complexity", "typescript" ], "Title": "Algorithm to find the Array Balance Point" }
232393
<ul> <li>Task: Return the fibonacci value at a given index.<br> e.g: input: <code>6</code>, return: <code>8</code>.</li> </ul> <p>Algorithm 1:</p> <pre class="lang-js prettyprint-override"><code>public static fibonacci(input: number): any { if (input &lt;= 1) return input; return this.fibonacci(input - 1) + this.fibonacci(input - 2); } </code></pre> <blockquote> <p>Time complexity: <span class="math-container">\$O(n^2)\$</span>,<br> Space complexity: <span class="math-container">\$O(1)\$</span></p> </blockquote> <p>Algorithm 2:</p> <pre class="lang-js prettyprint-override"><code>public static fibonacci2(input: number): any { if (input &lt;= 1) return input; let a = 0; let b = 1; let n = 0; for (let i=2; i&lt;=input; i++) { n = a + b; a = b; b = n; } return n; } </code></pre> <blockquote> <p>Time complexity: <span class="math-container">\$O(n)\$</span>,<br> Space complexity: <span class="math-container">\$O(1)\$</span></p> </blockquote> <hr> <p>Am I right regarding the complexities? </p> <p>Can you suggest any alternatives that achieve the same result, with different time/space complexity?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-14T18:12:00.690", "Id": "453826", "Score": "0", "body": "wow, I've been downvoted the second I've posted it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-14T18:47:09.283", "Id": "453833", "Score": "2", "body": "I'd believe the reason you were downvoted is because this isn't really asking for a code review, but it would be more of an opinion based answer, as you've seen yourself while searching for answers. Though I'm not the downvoter." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-15T05:10:48.490", "Id": "453879", "Score": "1", "body": "Time complexity of the Algorithm 1 is \\$O(2^n)\\$." } ]
[ { "body": "<p>You can compute fibonacci numbers with both time and space complexity <code>O(1)</code>.</p>\n\n<pre><code>(n) =&gt; ((Math.Pow(phi,n) - Math.Pow(1-phi, n)) / Math.Sqrt(5);\n</code></pre>\n\n<p>where <code>phi</code> is the golden ratio:</p>\n\n<pre><code>(1 + Math.Sqrt(5)) / 2\n</code></pre>\n\n<p>But if you needed to iterate fibonacci numbers one after the other, I would use an \"iterator\", then every other number would also be generated in O(1) and it would be better then the double formula.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-14T20:29:12.530", "Id": "232405", "ParentId": "232399", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-14T18:01:14.123", "Id": "232399", "Score": "0", "Tags": [ "interview-questions", "comparative-review", "complexity", "typescript", "fibonacci-sequence" ], "Title": "Choosing between 2 Fibonacci alternatives" }
232399
<p>I have written a class to generate a unique username from the full name. The full name is the name of a company usually containing 4 to 5 words. The username generated will be of format {preffix}{username}{suffix}. The user name should not be derived from stop words. stops words are generated analysing the most common words in the list of companies name. </p> <p>To generate name I am taking the first letter from each word of name and taking remaining from the last word. For eg. if the length of the username is 5 then <em>ABC Company Limited</em> will be converted to <em>ACLIM</em>.</p> <p>kindly review the code. </p> <pre><code>class UniqueNameGenerator: def __init__(self, stop_words, suffix, prefix): self.stop_words = stop_words self.suffix = suffix self.prefix = prefix def split_full_name_and_filter_stop_word(self, full_name, size): name_words = " ".join(full_name.split(" ")).split() if len(name_words) &gt; size: name_words = name_words[:size] words_considered = [] for word in name_words: ignore_word = False if word.lower() in self.stop_words: ignore_word = True if not ignore_word: words_considered.append(word) return words_considered @staticmethod def get_name_from_list_of_words(size, list_of_words): size_counter = 1 len_words_considered = len(list_of_words) letters_left = size username = "" while size_counter &lt;= len_words_considered: current_word = list_of_words[size_counter - 1] if size_counter == len_words_considered: if len(current_word) &gt;= letters_left: username += current_word[:letters_left] else: username += current_word else: username += current_word[0] letters_left -= 1 size_counter += 1 return username def check_and_update_username_to_unique(self, username, unique_name_list): while True: s = len(username) if username in unique_name_list: char_list = list(username) char_list[random.randint(0, s)] = random.choices( string.ascii_uppercase + string.digits )[0] username = "".join(char_list) else: return username def generate_username(self, full_name, size, unique_name_list=None): if not unique_name_list: unique_name_list = [] full_name = re.sub("[^\sa-zA-Z]+", "", full_name) words_considered = self.split_full_name_and_filter_stop_word(full_name, size) username = self.get_name_from_list_of_words(size, words_considered) if self.suffix: username = username + self.suffix if self.prefix: username = self.prefix + username username = self.check_and_update_username_to_unique(username, unique_name_list) return username </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-14T21:06:40.697", "Id": "453848", "Score": "0", "body": "Can you expand on what you mean by _stop words_? Some clarification on the whole _full name_ vs _username_ vs _name_ would be good, too. For example, the sentence _The username generated will be of format {preffix}{username}{suffix}._ seems to indicate some sort of recursion in the `username`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-14T21:10:30.893", "Id": "453849", "Score": "0", "body": "what should be the result for `full_name= 'ABC Company Limited'` and `size=2` ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-14T21:12:25.203", "Id": "453850", "Score": "0", "body": "@RomanPerekhrest Good question. In the same vein, what would the username be for `full_name= 'ABC Company Limited'` and `size=10+`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-15T02:13:31.703", "Id": "453868", "Score": "0", "body": "@RomanPerekhrest username should be 'ac'." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-15T02:18:50.690", "Id": "453869", "Score": "0", "body": "@AlexanderCécile currently it would print only 'abclimited'. I missed this case." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-15T02:34:46.800", "Id": "453871", "Score": "0", "body": "@JoshiR Can you elaborate on the algorithm as a whole? It’s tough to comment on the code without knowing exactly what it’s supposed to do." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-15T03:16:54.303", "Id": "453872", "Score": "0", "body": "stop words are the words which should be filtered out from full name while generating a username. ex. 'the', 'and' etc.\nLogic I am using is first filtering out stop words. From filtered words, I am picking a letter from each word. And from last word I am picking remaining letters. This is to keep username similar to full name. Also, I shall handle the case you mentioned in the previous comment by appending some random numeric to the username. At last, I am checking for unique word from the list of existing unique names." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-15T03:20:16.660", "Id": "453873", "Score": "0", "body": "{preffix}{username}{suffix} is to indicate prefix + username + suffix. prefix and suffix will be provided to the function in case they are required by user." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-15T04:40:46.120", "Id": "453875", "Score": "0", "body": "@JoshiR _At last, I am checking for unique word from the list of existing unique names_ Could you rephrase this? What do you mean by _unique word_ versus _unique names_? Is this just checking the uniqueness of the “username” part (without the prefix or suffix)?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-15T04:49:25.467", "Id": "453876", "Score": "0", "body": "I am checking the uniqueness of with prefix and suffix. unique_name_list is a list of the existing names. username returned by this function (with prefix and suffix) should not be in unique_name_list." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-15T04:57:32.370", "Id": "453877", "Score": "0", "body": "@JoshiR Alright. If it isn’t unique, it looks like you randomly change a single character, is that correct?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-15T05:21:12.767", "Id": "453880", "Score": "0", "body": "yes. Replacing with random character at random position." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-15T21:50:53.113", "Id": "453980", "Score": "0", "body": "@JoshiR Would you be open to slight changes in the algorithm? For example, instead of changing characters randomly until it works, why not append a number sequence to every otherwise identical username?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-16T06:34:58.577", "Id": "454005", "Score": "0", "body": "there should be some similarity between full name and username." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-17T02:52:50.493", "Id": "454110", "Score": "0", "body": "@JoshiR Absolutely, which is why I asked about adding a unique number instead of changing characters randomly!" } ]
[ { "body": "<p><strong><em><h3>Areas to fix/improve:</h3></em></strong></p>\n\n<p><strong><em>Namings</em></strong></p>\n\n<p>The function names like <code>split_full_name_and_filter_stop_word</code>, <code>check_and_update_username_to_unique</code> and alike are considered as <em>anti-patterns</em> for function naming.<br>\n<code>run_and_fly</code> or <code>think_or_talk</code> like names point to ambiguity or excessive responsibilities assigned to a function.<br>A function should have a concrete responsibility. Therefore, you need to analyze those functions and apply whether <em>Rename function</em> or <em>Extract function</em> (in your case - split a function into several functions each with separate responsibility) technique.</p>\n\n<p>Some variable and function names are too verbose:<br>\n<code>name_words</code> --> just <code>names</code><br>\n<code>get_name_from_list_of_words</code> --> just <code>compose_username</code><br>\n<code>list_of_words</code> --> just a plural <code>words</code><br>\n<code>unique_name_list</code> --> just <code>unique_names</code><br> </p>\n\n<hr>\n\n<p><strong><code>def generate_username(self, full_name, size, unique_name_list=None)</code></strong> method.</p>\n\n<ul>\n<li><p>to avoid passing the same <code>unique_name_list</code> across multiple methods - it's good to pass it into <code>UniqueNameGenerator</code> constructor at once.<br></p></li>\n<li><p><code>full_name = re.sub(\"[^\\sa-zA-Z]+\", \"\", full_name)</code>. In case if <code>full_name</code> happened to be empty, to avoid redundant calls of subsequent functions - it's good to add a check for that:</p>\n\n<pre><code>...\nfull_name = re.sub(\"[^\\sa-z]+\", \"\", full_name.strip(), re.I)\nif not full_name:\n raise ValueError(f'Incorrect full name `{full_name}`')\n</code></pre></li>\n<li><p>either of these complements:</p>\n\n<pre><code>if self.suffix:\n username = username + self.suffix\nif self.prefix:\n username = self.prefix + username\n</code></pre>\n\n<p>can throw <code>TypeError</code> in case if caller would pass non-string argument for <code>prefix</code> or <code>suffix</code>.<br>Instead, use flexible <code>f-string</code> formatting:</p>\n\n<pre><code>username = f'{self.prefix}{username}{self.suffix}'\n</code></pre></li>\n</ul>\n\n<hr>\n\n<p><strong><code>def split_full_name_and_filter_stop_word(self, full_name, size)</code></strong> method</p>\n\n<ul>\n<li>the function name is better named as <code>filter_valid_words</code> or <code>select_valid_words</code> (or alike)</li>\n<li><p><code>\" \".join(full_name.split(\" \")).split()</code> - this looks like a \"5-wheel bicycle that circles rounds instead of going <em>straight</em>\".<br>Simply <code>words = full_name.split()</code></p></li>\n<li><p>the whole construction:</p>\n\n<pre><code>words_considered = []\nfor word in name_words:\n ignore_word = False\n if word.lower() in self.stop_words:\n ignore_word = True\n if not ignore_word:\n words_considered.append(word)\n</code></pre>\n\n<p>is a verbose \"invention\" of a simple list comprehension with <code>if</code> constraint:</p>\n\n<pre><code>valid_words = [w for w in words if w.lower() not in self.stop_words]\n</code></pre>\n\n<p>The restructured function would look as:</p>\n\n<pre><code>def filter_valid_words(self, full_name, size):\n words = full_name.split()\n if len(words) &gt; size:\n words = words[:size]\n\n return [w for w in words if w.lower() not in self.stop_words]\n</code></pre></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-14T22:15:01.627", "Id": "232414", "ParentId": "232404", "Score": "3" } } ]
{ "AcceptedAnswerId": "232414", "CommentCount": "15", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-14T19:39:16.600", "Id": "232404", "Score": "3", "Tags": [ "python" ], "Title": "unique username generator" }
232404
<p>I have a component, it's actually an entire screen in my application. This screen/component renders multiple other components. However, what it renders is conditional. Currently, I have an if statement, which decides which markup is returned. The only differences between the two markups is one additional <code>&lt;PDFPreview&gt;</code> component is added. I'm pretty sure this isn't the best way to go about this...</p> <pre><code>const SearchScreen = ({navigation}) =&gt; { const [ makeSelected, setMakeSelected ] = useState(null); const [ modelSelected, setModelSelected ] = useState(null); const [ yearSelected, setYearSelected ] = useState(null); const [ typeSelected, setTypeSelected ] = useState(null); const selectMakeHandler = newMakeData =&gt; { let makeId = newMakeData.id; setMakeSelected(makeId); } const selectModelHandler = newModelData =&gt; { let modelId = newModelData.id; setModelSelected(modelId); } const selectYearHandler = newYearData =&gt; { let yearId = newYearData.id; setYearSelected(yearId); } const selectTypeHandler = newTypeData =&gt; { let typeId = newTypeData.diagramTypeId; setTypeSelected(typeId); } if (typeSelected !== null) { return ( &lt;Layout style={styles.mainContainer1}&gt; &lt;Layout style={styles.pickerContainer}&gt; &lt;MakePicker onSelectMake={selectMakeHandler} /&gt; &lt;ModelPicker onSelectModel={selectModelHandler} makeId={makeSelected} /&gt; &lt;YearPicker makeId={makeSelected} modelId={modelSelected} onSelectYear={selectYearHandler} /&gt; &lt;DiagramTypePicker makeId={makeSelected} modelId={modelSelected} modelYearId={yearSelected} onSelectType={selectTypeHandler} /&gt; &lt;Layout style={styles.previewContainer}&gt; &lt;PdfPreview makeId={makeSelected} modelId={modelSelected} modelYearId={yearSelected} typeId={typeSelected} /&gt; &lt;/Layout&gt; &lt;Layout style={styles.btnContainer}&gt; &lt;Button onPress={() =&gt; navigation.navigate('Pdf')} &gt; Download &lt;/Button&gt; &lt;/Layout&gt; &lt;/Layout&gt; &lt;Layout style={styles.adContainer}&gt; &lt;Advertisement/&gt; &lt;/Layout&gt; &lt;/Layout&gt; ) } else { return ( &lt;Layout style={styles.mainContainer2}&gt; &lt;Layout style={styles.pickerContainer}&gt; &lt;MakePicker onSelectMake={selectMakeHandler} /&gt; &lt;ModelPicker makeId={makeSelected} onSelectModel={selectModelHandler} /&gt; &lt;YearPicker makeId={makeSelected} modelId={modelSelected} onSelectYear={selectYearHandler} /&gt; &lt;DiagramTypePicker makeId={makeSelected} modelId={modelSelected} modelYearId={yearSelected} onSelectType={selectTypeHandler} /&gt; &lt;/Layout&gt; &lt;Layout style={styles.adContainer}&gt; &lt;Advertisement/&gt; &lt;/Layout&gt; &lt;/Layout&gt; ) } }; </code></pre> <p><br/> When a diagram is selected from the <code>&lt;DiagramTypePicker&gt;</code>, SearchScreen should re-render, every time, only now it should additionally render the PDF preview of the diagram type selected from <code>&lt;DiagramTypePicker&gt;</code>. If no preview is available for the diagram which was selected, I would like SearchScreen to instead show the original markup, the one without the PDF preview. I know with the useState() and useEffect() hooks I can watch the state of 'typeSelected' to control the re-render, but I'm still not sure if a huge 'if' statement with two different markups is the best way to go about this. Oh, and if the preview is unavailable the additional 'download' button would also be removed. Any advice? Comments? Questions or concerns? Thanks!</p>
[]
[ { "body": "<p>You can use <code>ternary operator(?:)</code> or <code>logical AND(&amp;&amp;)</code> operator and <code>React Fragment</code> to avoid this big if-else. The if-else with repetitive code violates DRY principle and should be avoided as any update to the code will be required at 2 different places which will be prone to error in case one is missed</p>\n\n<pre><code>const SearchScreen = ({ navigation }) =&gt; {\n ...\n return (\n &lt;Layout style={typeSelected !== null ? styles.mainContainer1 : styles.mainContainer2}&gt;\n &lt;Layout style={styles.pickerContainer}&gt;\n &lt;MakePicker\n onSelectMake={selectMakeHandler}\n /&gt;\n &lt;ModelPicker\n onSelectModel={selectModelHandler}\n makeId={makeSelected}\n /&gt;\n &lt;YearPicker\n makeId={makeSelected}\n modelId={modelSelected}\n onSelectYear={selectYearHandler}\n /&gt;\n &lt;DiagramTypePicker\n makeId={makeSelected}\n modelId={modelSelected}\n modelYearId={yearSelected}\n onSelectType={selectTypeHandler}\n /&gt;\n {typeSelected !== null &amp;&amp;\n &lt;&gt;\n &lt;Layout style={styles.previewContainer}&gt;\n &lt;PdfPreview\n makeId={makeSelected}\n modelId={modelSelected}\n modelYearId={yearSelected}\n typeId={typeSelected}\n /&gt;\n &lt;/Layout&gt;\n &lt;Layout style={styles.btnContainer}&gt;\n &lt;Button\n onPress={() =&gt; navigation.navigate('Pdf')}\n &gt;\n Download\n &lt;/Button&gt;\n &lt;/Layout&gt;\n &lt;/&gt;\n }\n &lt;/Layout&gt;\n &lt;Layout style={styles.adContainer}&gt;\n &lt;Advertisement /&gt;\n &lt;/Layout&gt;\n &lt;/Layout&gt;\n )\n};\n\n</code></pre>\n\n<p>Ternary Operator can be used as:</p>\n\n<pre><code>{typeSelected !== null\n ? &lt;&gt;\n &lt;Layout style={styles.previewContainer}&gt;\n &lt;PdfPreview\n makeId={makeSelected}\n modelId={modelSelected}\n modelYearId={yearSelected}\n typeId={typeSelected}\n /&gt;\n &lt;/Layout&gt;\n &lt;Layout style={styles.btnContainer}&gt;\n &lt;Button\n onPress={() =&gt; navigation.navigate('Pdf')}\n &gt;\n Download\n &lt;/Button&gt;\n &lt;/Layout&gt;\n &lt;/&gt;\n : null\n}\n</code></pre>\n\n<p><strong>Note:</strong></p>\n\n<ul>\n<li><code>&lt;&gt;&lt;/&gt;</code> is short for React.Fragment</li>\n<li>Please try to use logical &amp;&amp; in these cases for better readability purposes.</li>\n</ul>\n\n<p>Hope it helps. Revert for any doubts</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-26T07:34:20.070", "Id": "234657", "ParentId": "232407", "Score": "2" } } ]
{ "AcceptedAnswerId": "234657", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-14T20:47:22.897", "Id": "232407", "Score": "5", "Tags": [ "javascript", "react.js", "react-native" ], "Title": "How can I implement this React Native component without relying on a conditional statement?" }
232407
<p>I've been taking a crack at Domain Driven Design, SOLID principles, and unit tests to write more maintainable code in the future.</p> <p>Though I tend to run into the same issue: While I have many classes/objects that are easy to test, and do one thing well, I'm completely stumped on how to get classes to interact with each other elegantly.</p> <p>For example, an Arcade domain, where players spend tokens to play games. The following code will be in TypeScript but I'd imagine this applies to other languages.</p> <ul> <li>First I have a class (Value Object) to keep track of Token balances:</li> </ul> <pre><code> //Value Object: Keeps track of a bag of tokens. class TokenBalance { public readonly balance:number; constructor(balance: number) { if(balance &lt; 0) { throw new Error('Token balance must be 0 or higher'); } this.balance = balance; } AddToBalance(amount: number) { return new TokenBalance(this.balance + amount); } RemoveFromBalance(amount: number) { return this.AddToBalance(-amount); } } </code></pre> <ul> <li>Next I have a player (Entity), which has a name, and holds a balance of tokens</li> </ul> <pre><code> //Value Object: Player Name class PlayerName { public readonly name: string; constructor(name: string) { if(!name.length) { throw new Error('Name cannot be blank') } this.name = name; } } //Entity (Aggregate Root?): Holds a name and tokens class Player { public readonly id: string; public readonly name:PlayerName; private tokens:TokenBalance; constructor(tokens: TokenBalance, name: PlayerName, id:string) { this.id = id; this.tokens = tokens; this.name = name; } GetTokens() { return this.tokens; } DepositTokens(amount: number) { this.tokens = this.tokens.AddToBalance(amount); } WithdrawTokens(amount: number) { this.tokens = this.tokens.RemoveFromBalance(amount); } } </code></pre> <ul> <li>A simple guessing game class (Entity as well?) to keep track of Game State (No logic regarding players at this point)</li> </ul> <pre><code> enum GameState { IN_PROGRESS, LOSS, WIN } //Entity?: Maintains invariants of guessing game logic class GuessingGame { public static MAX_GUESS_COUNT = 5; public readonly id:string; private correctNumber:number; private guesses: number; private state: GameState; constructor(correctNumber: number, guesses: number, state:GameState, id:string) { if(guesses &lt; 0) { throw new Error('Negative guesses are impossible'); } this.id = id; this.correctNumber = correctNumber; this.guesses = guesses; this.state = state; } public GetState() { return this.state; } public Guess(number: number) { if(this.state !== GameState.IN_PROGRESS){ throw new Error('Game is over'); } this.guesses++; if(this.guesses &gt;= GuessingGame.MAX_GUESS_COUNT){ this.state = GameState.LOSS; } if(this.correctNumber === number) { this.state = GameState.WIN; } return this.state; } public GetGuessCount() { return this.guesses; } } </code></pre> <ul> <li>Finally, the class that I'm most unsure about. The mediator(?) of Games and Players to be used when a player wants to play a game:</li> </ul> <pre><code> //Domain Service?: Mediates the interactions between a Player and a Game. Ensures that tokens are used before playing a game //Unsure about this class. //How can this be retrieved later from a repository when it holds references to 2 entities. How would this be saved to a repository class PlayerGuessingGameSession { private player: Player; private game: GuessingGame; private hasStarted: boolean; private tokenCost:number; constructor(player: Player, game: GuessingGame, tokenCost = 50, hasStarted = false) { this.player = player; this.game = game; this.hasStarted = hasStarted; this.tokenCost = tokenCost; } public StartGame() { if(this.hasStarted){ throw new Error('Game already started'); } this.player.WithdrawTokens(this.tokenCost); this.hasStarted = true; } public Guess(number: number) { if(!this.hasStarted) throw new Error('No tokens inserted, cannot start'); const state = this.game.Guess(number); if(state === GameState.WIN){ this.player.DepositTokens(this.tokenCost + 5); //Reward the user with 5 additional tokens } } } //Putting it all together const player = new Player(new TokenBalance(100), new PlayerName('Steven'), 'player_id'); const game = new GuessingGame(5, 0, GameState.IN_PROGRESS, 'some_id'); const gameSession = new PlayerGuessingGameSession(player, game); console.log(player.GetTokens()); // TokenBalance { balance: 100 } gameSession.StartGame(); gameSession.Guess(5); console.log(player.GetTokens()); // TokenBalance { balance: 105 } </code></pre> <p>As the comments may have pointed out, I have a lot of concerns about the last class. If a Player starts a game, leaves, and comes back to continue, I would need a way to retrieve this session from some storage system (repository). Unfortunately, the session contains a Player and a Game entity, so saving a session may cause side effects to the Player and Game entities.</p> <p>How can I ensure that a game can only be played after tokens are spent, reward players on a win, and give the ability for a player to continue a session later? </p>
[]
[ { "body": "<p>OK. Let's start with some basics, &quot;entities&quot; are just sub-classes - what you really want is aggregate to talk to each other.</p>\n<p>In simple terms.</p>\n<ul>\n<li><p>AggregateA</p>\n<ul>\n<li>EntityA1</li>\n<li>EntityA2</li>\n</ul>\n</li>\n<li><p>AggregateB</p>\n<ul>\n<li>EntityB1</li>\n<li>EntityB2</li>\n</ul>\n</li>\n</ul>\n<p>Then...</p>\n<p>Only aggregates get to talk / interact with other aggregates.\nFor example...\nDuncan [my name], is an aggregate of a person, I have entities, like a RightArm entity, a LeftArm entity.</p>\n<p>If I got to a Shop, a Shop is an aggregate of many entities.</p>\n<p>&quot;So Duncan aggregate interacts with a Shop aggregate.&quot;</p>\n<p><strong>Side Point</strong>\nShop has value objects... eg. Number of fork candles for sale.\nDuncan has value object of... cash to spend.</p>\n<hr />\n<p>In your terms, there is two aggregates...</p>\n<ul>\n<li>Player</li>\n<li>Game</li>\n</ul>\n<p>Player, has tokens.\nGame has player(s).</p>\n<p>Then work out, how they interact, I'd say Game.Start(player1)?</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-20T21:05:02.593", "Id": "245769", "ParentId": "232411", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-14T21:26:10.217", "Id": "232411", "Score": "3", "Tags": [ "object-oriented", "typescript", "ddd" ], "Title": "DDD - Interaction between 2 entities" }
232411
<p>After a test run with LoadRunner I wanted to know the average time for each transaction for each VU volume step, the LR let you create a graph for this but don't give you the point values... so it's not possible to further analyse the data. As I'm learning python I decided to write a script to do the job for me, this is my second python script, but I've been a programmer for quite a few year and I used quite a few different languages, so I'd like to understand if I'm writing python or "I'm just translating code from another language to python".</p> <p>There is no test for the data because it's copied from the LoadRunner Analysis tool. It uses tab as column separator, and it look like this</p> <pre><code>Vuser ID Group Name Transaction End Status Location Name Script Name Transaction Hierarchical Path Host Name Scenario Elapsed Time Transaction Response Time Transaction Name Vuser1 VC_AR Pass N/A VC_AR_Nuova Highest Level localhost 11,484 7,526 AR00_Homepage_AR Vuser2 VC_AR Pass N/A VC_AR_Nuova Highest Level localhost 11,512 7,525 AR00_Homepage_AR Vuser1 VC_AR Pass N/A VC_AR_Nuova Global_AREA_RISERVATA localhost 48,607 35,334 AR01_Login_AR Vuser2 VC_AR Pass N/A VC_AR_Nuova Global_AREA_RISERVATA localhost 52,098 39,043 AR01_Login_AR Vuser1 VC_AR Pass N/A VC_AR_Nuova Highest Level localhost 70,698 0,048 AR07_Logout_AR Vuser2 VC_AR Pass N/A VC_AR_Nuova Highest Level localhost 70,768 0,009 AR07_Logout_AR Vuser1 VC_AR Pass N/A VC_AR_Nuova Highest Level localhost 74,466 2,021 AR00_Homepage_AR Vuser2 VC_AR Pass N/A VC_AR_Nuova Highest Level localhost 75,752 2,199 AR00_Homepage_AR Vuser1 VC_AR Pass N/A VC_AR_Nuova Global_AREA_RISERVATA localhost 78,169 1,825 AR01_Login_AR Vuser2 VC_AR Pass N/A VC_AR_Nuova Global_AREA_RISERVATA localhost 79,203 1,096 AR01_Login_AR Vuser1 VC_AR Pass N/A VC_AR_Nuova Highest Level localhost 85,963 0,01 AR07_Logout_AR Vuser2 VC_AR Pass N/A VC_AR_Nuova Highest Level localhost 86,571 0,009 AR07_Logout_AR Vuser4 VC_AR Pass N/A VC_AR_Nuova Highest Level localhost 123,846 1,933 AR00_Homepage_AR Vuser3 VC_AR Pass N/A VC_AR_Nuova Highest Level localhost 125,49 1,939 AR00_Homepage_AR Vuser1 VC_AR Pass N/A VC_AR_Nuova Global_AREA_RISERVATA localhost 125,58 1,25 AR01_Login_AR Vuser4 VC_AR Pass N/A VC_AR_Nuova Global_AREA_RISERVATA localhost 128,174 1,598 AR01_Login_AR Vuser3 VC_AR Pass N/A VC_AR_Nuova Global_AREA_RISERVATA localhost 128,715 1,67 AR01_Login_AR Vuser2 VC_AR Pass N/A VC_AR_Nuova Highest Level localhost 132,251 0,325 AR07_Logout_AR Vuser1 VC_AR Pass N/A VC_AR_Nuova Highest Level localhost 134,641 0,016 AR07_Logout_AR Vuser4 VC_AR Pass N/A VC_AR_Nuova Highest Level localhost 135,899 0,011 AR07_Logout_AR Vuser2 VC_AR Pass N/A VC_AR_Nuova Highest Level localhost 136,427 2,002 AR00_Homepage_AR Vuser1 VC_AR Pass N/A VC_AR_Nuova Highest Level localhost 137,611 1,954 AR00_Homepage_AR Vuser4 VC_AR Pass N/A VC_AR_Nuova Highest Level localhost 139,254 1,944 AR00_Homepage_AR Vuser2 VC_AR Pass N/A VC_AR_Nuova Global_AREA_RISERVATA localhost 139,437 1,239 AR01_Login_AR Vuser1 VC_AR Pass N/A VC_AR_Nuova Global_AREA_RISERVATA localhost 140,738 1,947 AR01_Login_AR Vuser3 VC_AR Pass N/A VC_AR_Nuova Highest Level localhost 141,829 2,194 AR00_Homepage_AR Vuser4 VC_AR Pass N/A VC_AR_Nuova Global_AREA_RISERVATA localhost 142,508 1,096 AR01_Login_AR Vuser2 VC_AR Pass N/A VC_AR_Nuova Highest Level localhost 145,244 0,026 AR07_Logout_AR Vuser3 VC_AR Pass N/A VC_AR_Nuova Global_AREA_RISERVATA localhost 145,841 1,855 AR01_Login_AR </code></pre> <p>My code is here</p> <pre class="lang-py prettyprint-override"><code>""" Script to calculate the average time per Vugen volume from the raw data. LoadRunner Analysis creates the graph but don't shows the base value, that make it difficoult to do further analisys. Parameters ---------- -l, --log : str, default 'WARNING' the log level -i, --input : str, default 'raw.txt' the filepath of the input -o, --output : str, default 'out.txt' the filepath for the output """ import pandas import argparse import logging MAX_TIME_WINDOW = 10 """ The max time, in second, to count the change of Vugen volume as a single event """ def read_and_prepare(file): """ Convert the input file to a table Read the input file and convert it to a DataFrame for future work. To reduce the memory load the columns that will not be used are deleted. Parameters ---------- file : str the filepath of the data Returns ------- A DataFrame with the readed data """ df_raw = pandas.read_table(file, index_col='Scenario Elapsed Time', decimal=',', thousands='.') df_raw.columns = df_raw.columns.str.strip().str.replace(' ', '_') logging.debug('Imported column list: %s', df_raw.columns) script_name = df_raw.iat[1, 4] logging.debug('Script name: %s', script_name) del df_raw['Group_Name'] del df_raw['Transaction_End_Status'] del df_raw['Location_Name'] del df_raw['Host_Name'] del df_raw['Script_Name'] df_raw.sort_index(inplace=True) logging.debug('Removed not needed column, current columns: %s', df_raw.columns) logging.debug('Imported data sample:\n %s', df_raw) return df_raw def generate_empty_row(input_df): """ Generate the base row for the work DataFrame Generate a dictionary with a cell for each distinct value of the 'Transaction_Name' column in the input DataFrame. Parameters ---------- input_df : DataFrame The DataFrame with all the data Returns ------- dict A dictionary with a default value for all the columns. """ transactions = input_df['Transaction_Name'].unique() transactions.sort(axis=0) transactions = transactions.tolist() logging.debug('Transactions: %s', transactions) base_row = dict(zip(transactions, [0] * len(transactions))) return base_row def __average_and_append(data_totals, data_counter, out_data, new_index): """ Average the value and add the values to out_data with index new_index Divides the totals by the relative counters to get the average for the transaction, then add the new data to the out_data DataFrame with index new_index Parameters ---------- data_totals : dict A dict with the totals for each transaction, must have the same fields of data_counter data_counter : dict A dict that count the number of items added to get the totals, must have the same fields of data_totals out_data : pandas.DataFrame The DataFrame to append the new row to new_index : int The index for the new row in the DataFrame Returns ------- pandas.DataFrame The out_data DataFrame with the new row appended """ data_avg = {key: total/max(data_counter[key], 1) for (key, total) in data_totals.items()} row = pandas.DataFrame(data=data_avg, index={new_index}) out_data = out_data.append(row) return out_data def calculate_response_time(input_data, base_row): """ Calculate the response time for each transaction for each Vugen load Read each row of the input data, for each transaction add the response time to an accumulator and the number of added values to a counter. Every time the load counter increase outside the time window of MAX_TIME_WINDOW the data will be averaged and wrote to the output DataFrame Parameters ---------- input_data : DataFrame The DataFrame with all the data base_row : dict A dictionary with a cell for each transaction in the data Returns ------- DataFrame A DataFrame with the calculated average for each transaction, with the vugen volume as index """ data_counter = base_row.copy() data_adder = base_row.copy() seen_id_set = set() # Set time_last_added_id base at the time of the first row, i.e. it's index time_last_added_id = input_data.index[0] out_data = pandas.DataFrame() vugen_volume = 0 for index, row in input_data.iterrows(): is_new_step = row['Vuser_ID'] not in seen_id_set is_in_window = ((index - time_last_added_id) &lt; MAX_TIME_WINDOW) if (is_new_step and is_in_window): # Put the new Vugen ID in the set without changing the last time seen_id_set.add(row['Vuser_ID']) vugen_volume = len(seen_id_set) logging.debug("New ID %s found within %i second" % (row['Vuser_ID'], MAX_TIME_WINDOW)) elif (is_new_step): # Calculate the averages and append the new row to output logging.debug("New ID %s found outside the %i second window, " "adding a row to the output" % (row['Vuser_ID'], MAX_TIME_WINDOW)) out_data = __average_and_append(data_adder, data_counter, out_data, vugen_volume) # Set the last time a Vugen ID was added and put it in the set time_last_added_id = index seen_id_set.add(row['Vuser_ID']) # Reset the counter and the adder data_counter = base_row.copy() data_adder = base_row.copy() data_adder[row['Transaction_Name']] += row['Transaction_Response_Time'] data_counter[row['Transaction_Name']] += 1 # Add the data of the last step out_data = __average_and_append(data_adder, data_counter, out_data, vugen_volume) return out_data def response_time_under_load(input_file, output_file): """ Read the input file, calculate the response under load and save it in the output file Main procedure of the module, it uses the other function to import the raw data from LoadRunner, calculate the average response under load for each transaction, as the step in the Vugen volume are not perfectly aligned if the volume is changed multiple times in a window of XX second they will be counted as a single step. The number of second is defined as a constant Parameters ---------- input_file : string The file path of the data file, the data must be response time raw data file generated by the LoadRunner Analysis tool output_file : string The file path where to save the data calculated """ input_data = read_and_prepare(args.input_file) base_row = generate_empty_row(input_data) working_data = calculate_response_time(input_data, base_row) working_data.to_csv(path_or_buf=args.output_file, sep=';', index_label='Number of VUser') if __name__ == '__main__': parser = argparse.ArgumentParser( description='Tool that gets raw data from LoadRunner Analysis ' 'and calculate the average for transaction and Vugen running.' 'LoadRunner generate the graph but don''t share the data.') parser.add_argument('-l', '--log', dest='log_level', default='WARNING', help='Livello di log da usare') parser.add_argument('-i', '--input', dest='input_file', default='raw.txt', help='Nome del file da caricare') parser.add_argument('-o', '--output', dest='output_file', default='out.txt', help='Nome del file su cui salvare i dati elaborati') args = parser.parse_args() log_level = getattr(logging, args.log_level.upper(), None) if not isinstance(log_level, int): raise ValueError('Invalid log level: %s' % args['log_level']) logging.basicConfig(filename='reader.log', filemode='w', level=log_level, format='%(asctime)s - %(levelname)s - %(message)s') logging.debug('Script called with parameters: -l %s, -i %s, -o %s' % (args.log_level, args.input_file, args.output_file)) response_time_under_load(args.input_file, args.output_file) </code></pre> <p>I'm not sure if <code>pandas</code> is really needed, in the end I just used it to read and write csv files and remove columns that I don't need, still using a new module is fun :)</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-15T03:54:20.350", "Id": "453874", "Score": "0", "body": "High-level tip: `iterrows()` has some big disadvantages (see [the docs](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.iterrows.html)), which similar methods like `itertuples()` do not suffer from. Of course, the best is to avoid explicit iteration altogether, whenever possible. I will take a complete look at your code tomorrow :)" } ]
[ { "body": "<p>Unfortunately, I've never used <code>pandas</code> before (I've been meaning to try it for awhile), so I can't comment on its usage. Looking at how it's being used here though, it may help, but parsing a list of lines would still be fairly simple.</p>\n\n<hr>\n\n<p>Honestly, this is some clean looking code. You actually format things fairly similarly to how I like, so I don't have much to say in that regard.</p>\n\n<p>To nit pick though, here</p>\n\n<pre><code>data_avg = {key: total/max(data_counter[key], 1)\n for (key, total)\n in data_totals.items()}\n</code></pre>\n\n<p>I wouldn't break up the <code>for...in</code>. It's not that long of a line.</p>\n\n<p>I also wouldn't use a <a href=\"https://stackoverflow.com/questions/1301346/what-is-the-meaning-of-a-single-and-a-double-underscore-before-an-object-name\">double underscore prefix</a> for <code>__average_and_append</code>. If your intent was to mark it as \"private\", just use one leading underscore.</p>\n\n<hr>\n\n<p>The one suggestion I can make though is to try out <a href=\"https://docs.python.org/3/library/typing.html\" rel=\"nofollow noreferrer\">type hints</a>. Right now, you're indicating the type in the docstring, and I don't think that it's in a format that IDEs can read readily. Type hints allow some type errors to be caught as you're writing, and show up in a more readable way in docs.</p>\n\n<p>For an example of their use, you could annotate <code>response_time_under_load</code> as:</p>\n\n<pre><code>def response_time_under_load(input_file: str, output_file: str) -&gt; None:\n</code></pre>\n\n<p>This does a few things:</p>\n\n<ul>\n<li>The types show up in the docs in the signature instead of buried in the doc string</li>\n<li>If you accidentally pass something of the wrong type, a good IDE will warn you</li>\n<li>From within the function, it knows <code>input_file</code> is a string, so it can give better autocomplete suggestions</li>\n<li><p><code>-&gt; None</code> means that the function doesn't return anything (AKA, it implicitly returns <code>None</code>). If you attempt to do</p>\n\n<pre><code>some_var = response_time_under_load(inp, out)\n</code></pre>\n\n<p>You'll get a warning that <code>response_time_under_load</code> doesn't return anything.</p></li>\n</ul>\n\n<p>You can also annotate the types that dictionaries and lists hold. This allows it to know the types when you do a lookup. For example, <code>__average_and_append</code> takes two dictionaries, a <code>Dataframe</code>, and an <code>int</code>. You don't say what the dictionary is holding though. The values are numbers, but I can't tell what the keys are. Pretend for the example that the keys and values are both integers.</p>\n\n<pre><code>def _average_and_append(data_totals, data_counter, out_data, new_index):\n</code></pre>\n\n<p>Could be changed to</p>\n\n<pre><code>from typing import Dict\n\ndef _average_and_append(data_totals: Dict[int, int],\n data_counter: Dict[int, int],\n out_data: Dataframe, # Assuming Dataframe is imported\n new_index: int\n ) -&gt; Dataframe:\n</code></pre>\n\n<p>Yes, this is quite verbose, but it conveys a lot of useful information. <code>Dict[int, int]</code> can also be aliased to reduce redundancy and neaten up:</p>\n\n<pre><code>Data = Dict[int, int] # Type alias\n\ndef _average_and_append(data_totals: Data,\n data_counter: Data,\n out_data: Dataframe,\n new_index: int\n ) -&gt; Dataframe:\n</code></pre>\n\n<p><code>Dataframe</code> may be generic like <code>Dict</code> is, so you may be able to specify the types that it holds as well. The docs for the class should mention that.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-14T23:52:03.247", "Id": "453864", "Score": "0", "body": "Thanks I'll try the type hints. Yes `__average_and_append` is a private function, it started as part of `calculate_response_time` and was refactored out to get some more columns to write the code, that's the reason why the `for..in` is in two lines, initially that's the space I had. The two dict parameters are copies of base_row so the keys are the distinct values of the 'Transaction Name' columns of the input files, in `data_totals` the values are the sum of the response time so `dict[str,float]`(?), in `data_counter` the values are the number of rows added so `dict[str,int]`(?)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-15T00:01:49.050", "Id": "453865", "Score": "0", "body": "@Serpiton Yes, those would be correct, except you need `Dict` instead of `dict`. Unfortunately, the built-in types aren't yet generic themselves. I think I read that this is going to be fixed in future updates though. Type hints are still fairly new." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-14T22:28:00.290", "Id": "232415", "ParentId": "232412", "Score": "4" } } ]
{ "AcceptedAnswerId": "232415", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-14T21:35:20.460", "Id": "232412", "Score": "5", "Tags": [ "python", "python-3.x", "pandas" ], "Title": "Average row id volume" }
232412
<p>I would like to store all error messages in one file and call them for example with</p> <pre><code>if (!std::filesystem::exists(ArgFilename)) { throw std::runtime_error{error_001_nofile}; } else { //do something } </code></pre> <p>The file <code>errorcodes.h</code> is included to the main program and looks like</p> <pre><code>#ifndef SRC_ERRORCODES_H_ #define SRC_ERRORCODES_H_ #include &lt;string_view&gt; constexpr char error_001_nofile[] = "Error 001: File not found."; constexpr char error_002_nomem[] = "Error 002: Not enough memory."; #endif /* SRC_ERRORCODES_H_ */ </code></pre> <p><a href="https://cevelop.com/" rel="nofollow noreferrer">Cevelop</a> warns, that <code>constexpr char</code> is no proper <code>c++</code>, but <code>c</code> code. Is there a clean <code>c++</code> solution to manage error messages?</p> <p><a href="https://i.stack.imgur.com/mnj8J.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/mnj8J.png" alt="Cevelop warns, that constexpr char is no proper c++, but c code."></a></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-14T21:46:34.187", "Id": "453852", "Score": "1", "body": "`const` should be enough if there's nothing to evaluate." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-14T22:25:43.000", "Id": "453855", "Score": "0", "body": "Why did someone down vote? What can I improve in the question?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-14T22:26:33.237", "Id": "453856", "Score": "0", "body": "@πάνταῥεῖ Thank you. Will change that here, but I leave the question as is for the reader." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-14T23:29:08.397", "Id": "453863", "Score": "0", "body": "There's nothing wrong with using C-string constants in C++. I would write `char const* name = \"value\";`, but I think in the end it's the same." } ]
[ { "body": "<p><code>constexpr</code> is probably overkill, but not in any way wrong.</p>\n\n<p>You might consider using the C++ universal style initializisation: </p>\n\n\n\n<pre class=\"lang-c++ prettyprint-override\"><code>constexpr char error_001_nofile[]{\"Error 001: File not found.\"};\n</code></pre>\n\n<p>or using a <code>std::string</code>: </p>\n\n<pre class=\"lang-c++ prettyprint-override\"><code>constexpr std::string error_001_nofile{\"Error 001: File not found.\"};\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-15T00:29:50.827", "Id": "232417", "ParentId": "232413", "Score": "2" } } ]
{ "AcceptedAnswerId": "232417", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-14T21:42:52.870", "Id": "232413", "Score": "-1", "Tags": [ "strings", "error-handling", "c++17" ], "Title": "Provide one file where all error messages are defined in c++" }
232413
<p>This is part of a Particle Swarm Optimization algorithm, a snippet of a Particle class implementation.</p> <pre class="lang-cpp prettyprint-override"><code>/** * Particle class constructor * @param p - the position of the particle * @param v - the velocity of the particle */ Particle::Particle(std::array&lt;double, 30&gt; p, std::array&lt;double, 30&gt; v) { bestFitness = fitness = rastriginEvaluation(p); bestPosition = position = p; velocity = v; } // setter methods void Particle::setFitness(double f) { fitness = f; } void Particle::setBestFitness(double f) { bestFitness = f; } void Particle::setPosition(std::array&lt;double, 30&gt; p) { position = p; } void Particle::setBestPosition(std::array&lt;double, 30&gt; p) { bestPosition = p; } void Particle::setVelocity(std::array&lt;double, 30&gt; v) { velocity = v; } </code></pre> <p>Notice the constructor directly accesses member attributes yet I have setter methods. Should I be using the setter methods to initialize attributes? Either is fine, I wonder what is <em>more proper</em>.</p> <p>For example, instead of:</p> <pre class="lang-cpp prettyprint-override"><code>bestFitness = fitness = rastriginEvaluation(p); bestPosition = position = p; velocity = v; </code></pre> <p>I could do:</p> <pre class="lang-cpp prettyprint-override"><code>setFitness(rastriginEvaluation(p)); setBestFitness(rastriginEvaluation(p)); setPosition(p); setBestPosition(p); setVelocity(v); </code></pre> <p>For this example, <code>rastriginEvaluation()</code> is called twice, when the original code only calls it once. It is therefore slower but what is better practice?</p> <p>I could also wonder about getter methods in the mix:</p> <pre class="lang-cpp prettyprint-override"><code>setFitness(rastriginEvaluation(p)); setBestFitness(getFitness()); setPosition(p); setBestPosition(getPosition(); setVelocity(v); </code></pre> <p>If it makes a difference, all attributes are private.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-15T00:33:43.803", "Id": "453866", "Score": "1", "body": "Getters and setters are not 'object-oriented', they basically remove the encapsulation idea, and the whole 'class' becomes an empty concept." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-15T10:19:54.830", "Id": "453896", "Score": "1", "body": "The current question title, which states your concerns about the code, is too general to be useful here. Please [edit] to the site standard, which is for the title to simply state **the task accomplished by the code**. Please see [How to get the best value out of Code Review: Asking Questions](//codereview.meta.stackexchange.com/q/2436) for guidance on writing good question titles." } ]
[ { "body": "<p>As a general rule, if the only thing your getters and setters do is contain a single statement, a return or assignment respectively, there is no need to make the variable private and it should be declared public.</p>\n\n<p>Specifically to your question: <em>Neither</em> of your approaches are considered \"best\" nor \"proper\" practice. You should be using an initializer list before the constructor's body:</p>\n\n<p>Note: There is no indication of what order the variables were declared in the class declaration. I've made a guess here, but they are initialized in the order they are declared regardless of what order you put them in the list so if I've got it backwards and <code>fitness</code> is declared first things will silently break at run-time.</p>\n\n<pre><code>Particle::Particle(std::array&lt;double, 30&gt; p, std::array&lt;double, 30&gt; v)\n: bestPosition(p)\n, position(p)\n, velocity(v)\n, bestFitness(rastriginEvaluation(p))\n, fitness(bestFitness)\n{\n /* DO NOTHING */\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-15T10:21:30.023", "Id": "453897", "Score": "0", "body": "You can make the breakage non-silent with `gcc -Weffc++`, which will warn about misleading order of initializers." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-15T15:51:36.990", "Id": "453936", "Score": "0", "body": "@TobySpeight Similarly, Visual Studio treats this warning as \"Off by default\": https://docs.microsoft.com/en-us/cpp/error-messages/compiler-warnings/c5038?view=vs-2019 but can be manually turned back on by compiling with switch `/Wall` (no, never do this) or treating it as a W4 warning: `/w45038`" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-15T02:11:44.707", "Id": "232421", "ParentId": "232416", "Score": "4" } }, { "body": "<p>@Casey provided a general answer to a clean implementation. Though, decent compilers at optimization steps shouldn't be dependent on that, lest you wrote something really weird in the constructor.</p>\n\n<p>For me the number 30 seems arbitrary. Could it be the case that you frequently use only a portion of the data? Or use a portion depending on situation? Or at times use more? Consider using an image/matrix like allocation method (check out opencv) with columns being the number of Particles and rows being the number of size of data in doubles that each particle allocates. In general if the struct uses 62 doubles then its move/copy operations are somewhat slow. Consider methods of usage that avoids this problem.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-15T13:33:05.277", "Id": "232443", "ParentId": "232416", "Score": "0" } } ]
{ "AcceptedAnswerId": "232421", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-14T23:30:57.477", "Id": "232416", "Score": "1", "Tags": [ "c++", "object-oriented", "constructor" ], "Title": "Particle Swarm Optimization algorithm" }
232416
<p>I have written a custom HashSet and though it isn't completed yet (this code does not consider test cases with collisions), I would like to know if there is anything I can improve in areas of clean code conventions and logic errors. Kindly review my code. Thanks in advance.</p> <pre><code>import java.util.Arrays; public class HashSet { private int[] values; private int size; private int ratio; private int[] values_temp; private ProbeStrategy strategy; private int current_length; public HashSet(int initArrayLength, int ratio, ProbeStrategy strategy) { values = new int[initArrayLength]; Arrays.fill(values, -1); this.ratio = ratio; this.strategy = strategy; current_length = values.length; } public boolean add(int value) { if (size == 0) { int bucket = value % current_length; values[bucket] = value; size++; return true; } if (value &gt;= 0) { int bucket = value % current_length; values[bucket] = value; if (current_length &lt;= ratio * size) { int new_length = (current_length * 2) + 1; values_temp = new int[new_length]; for (int i = 0; i &lt; current_length; i++) { if (values[i] == -1) { continue; } int bucket_temp = values[i] % new_length; values_temp[bucket_temp] = values[i]; } values = values_temp; current_length = new_length; for (int i = 0; i &lt; current_length; i++) { if (values[i] == 0) { values[i] = -1; } } } size(); return contains(value); } return false; } public boolean contains(int value) { for (int i = 0; i &lt; values.length; i++) { if (values[i] == value) { return true; } } return false; } public boolean remove(int value) { for (int i = 0; i &lt; values.length; i++) { if (values[i] == value) { values[i] = -1; } } size(); return !contains(value); } public int size() { int count = 0; for (int i = 0; i &lt; current_length; i++) { if (values[i] == -1) { count++; } size = current_length - count; } return size; } public int[] toArray() { int[] result = new int[this.values.length]; for (int i = 0; i &lt; this.values.length; i++) { result[i] = this.values[i]; } return result; } public static void main(String[] args) { ProbeStrategy linear = new SimpleLinearProbe(); HashSet set = new HashSet(6, 2, linear); int[] numbers = {77254, 135170, 19331, 173763, 154470, 154471}; for (int i = 0; i &lt; numbers.length; i++) { // add the number set.add(numbers[i]); //print out the array int[] array = set.toArray(); for (int j = 0; j &lt; array.length; j++) { System.out.print(array[j] + ", "); } System.out.println(); } } </code></pre> <p>}</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-15T05:04:07.127", "Id": "453878", "Score": "2", "body": "I would suggest reading this [article](https://blog.miyozinc.com/algorithms/custom-hashset-implementation-in-java/). Your code basically is just a wrapper for an array." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-15T01:08:02.817", "Id": "232419", "Score": "1", "Tags": [ "java", "hash-map" ], "Title": "HashSet without collision" }
232419
<p>So, I was working on a dashboard for a potential customer and I needed a fake dataset with employee information to demonstrate. Mainly, I needed to know when the employee arrived the company (first swipe), when he left (last swipe) and the hours he spent in many other areas of the company (ORC is a room, DSP is another, and so on)</p> <p>Basically, I create a random hour between 8am and 10am and assign this to the first swipe. I do the same for last swipe but in a range from 5pm to 7pm. Then, I calculate how many hours he worked by subtracting one from another.</p> <p>With this information now I start to calculate how many hours he spent in every area of the company. The ORC is the working room, so I want to keep between 50% to 80% of hours worked there and the rest randomly assign to other areas.</p> <p>I spent a lot of time in this code, and it's been a while since I created it. It's not the most pythonic code you will ever see, but it worked :D</p> <pre><code>import calendar import datetime import random def random_hour(start, end): hour_rand = random.randint(start, end) minutes_rand = random.randint(0, 59) return datetime.timedelta(hours=hour_rand, minutes=minutes_rand) def random_weight(total_working_hours): working_hours_per_area = { 'in_orc': 0, 'in_cafe': 0, 'in_dsp': 0, 'in_kiosk': 0, 'in_training': 0, } whole_time = 100 total_time = datetime.timedelta() for i, area in enumerate(working_hours_per_area): if whole_time &lt; 0: whole_time = 0 if i == 0: rand_time = random.randint(50, 80) else: rand_time = random.randint(0, whole_time) whole_time -= rand_time working_hours_per_area[area] = rand_time / 100 total_aux = sum(working_hours_per_area.values()) if total_aux &lt; 1.0: diff = 1.0 - total_aux min_hour = min(working_hours_per_area.keys(), key=(lambda k: working_hours_per_area[k])) working_hours_per_area[area] += diff for area in working_hours_per_area: working_hours_per_area[area] = working_hours_per_area[area] * total_working_hours return working_hours_per_area employees = [ ['CHI-123', 'CLOVIS TONELADA'], ['CHI-456', 'JOSE DA COVA'], ['CHI-789', 'EMERSON PEDREIRA'], ['CHI-321', 'GREYCE CROQUETE'], ['CHI-654', 'ROBERTO PINGA'], ['CHI-987', 'CAROLINA DOZE AVOS'], ] days = [] cal = calendar.Calendar() for week in cal.monthdatescalendar(2020,9): for day in week: if day.weekday() &lt; 5: days.append(day) f = open('dataset.csv', 'w+') f.write('Date;Employee_Name;Employee_Code;First_Swipe;Last_Swipe;Total_Working_Hours;In_ORC;In_Cafe;In_DSP;In_Kiosk;In_Training\n') for day in days: for i in range(0, 6): date = day employee_name = employees[i][1] employee_code = employees[i][0] first_swipe = random_hour(8, 10) last_swipe = random_hour(17, 19) total_working_hours = last_swipe - first_swipe working_hours_per_area = random_weight(total_working_hours) total_working_hours_per_area = datetime.timedelta(hours=0, minutes=0) locals().update(working_hours_per_area) write = ';'.join([str(date), employee_name, employee_code, str(first_swipe), str(last_swipe), str(total_working_hours), \ str(in_orc), str(in_cafe), str(in_dsp), str(in_kiosk), str(in_training)]) f.write(write + '\n') f.close() </code></pre>
[]
[ { "body": "<p>You didn't include any specific request, so here are some general comments.</p>\n\n<h2>comments / documentation</h2>\n\n<p>You say it's been a while since you wrote it. When you look at the code now, are there places you ask yourself \"why did I do that?\" or where it takes time to figure out what is going on? If so, those are good places to add comments.</p>\n\n<p>Also docstrings could be added to the file and the functions.</p>\n\n<h2>random_hour(start, end)</h2>\n\n<p>The writeup says it returns a random time between start and end. However, it actually returns a random timedelta between start and <code>end</code> + 59 minutes. Also, similar python functions tend to include the <code>start</code> and exclude the <code>end</code> (e.g. randrange), so it would be good to document this.</p>\n\n<h2>random_weight(total_working_hours)</h2>\n\n<p>dicts() are not guaranteed to be ordered until Python 3.7. So i==0 may not correspond to <code>in_orc</code>. It would be better to iterate over the keys and check if the key=='in_orc'.</p>\n\n<p><code>min_hour</code> is calculated but never used. I think it is supposed to be <code>area</code>.</p>\n\n<h2>module level code</h2>\n\n<p>It is common to put the top level code in a function such as <code>main()</code>. And the call <code>main()</code> from code such as</p>\n\n<pre><code>if __name__ == '__main__':\n main()\n</code></pre>\n\n<h2>csv module</h2>\n\n<p>The standard library includes the <code>csv</code> module for reading a writting csv and other kinfs of delimited text files. It takes care of escaping characters or enclosing strings in quotes if needed.</p>\n\n<h2>unpacking</h2>\n\n<p>Instead of using <code>for i in range(0,6)</code> to iterate over the employees, use something like:</p>\n\n<pre><code>for employee_code, employee_name in employees:\n ...\n</code></pre>\n\n<h2>locals()</h2>\n\n<p>The python documentation says the dictionary returned by <code>locals()</code> should NOT be modified. The changes may not be picked up by the interpreter.</p>\n\n<p>That's enough for now.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-15T06:18:33.710", "Id": "232428", "ParentId": "232420", "Score": "4" } } ]
{ "AcceptedAnswerId": "232428", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-15T02:04:07.707", "Id": "232420", "Score": "4", "Tags": [ "python" ], "Title": "Algo for generating a fake, but feasable, dataset" }
232420
<p>I've read several places that say it's really bad to use <code>append</code>, and I understand why. I read somewhere that it was never even correct to use <code>append</code>. However, I was working on a textbook exercise in <em>Essentials of Programming Languages</em> (Ex 1.21 pg27) that asked me to write a Cartesian product function. I couldn't think of any other easy way than using <code>append-map</code>. Below is my working solution to the exercise. Is there a better more idiomatic way of writing this? Thanks!</p> <pre class="lang-lisp prettyprint-override"><code>; product : Listof(SchemeVal) -&gt; Listof(SchemeVal) -&gt; Listof(List(SchemeVal)) ; usage: (product '(a b c) '(x y)) -&gt; '((a x) (a y) (b x) (b y) (c x) (c y)) (define (product lox loy) (append-map (lambda (x) (scalar x loy)) lox)) (define (scalar x loy) (map (lambda (y) (list x y)) loy)) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-15T08:25:54.220", "Id": "453889", "Score": "0", "body": "Is this code copied verbatim from the text-book? How would it be used?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-15T13:02:57.240", "Id": "453918", "Score": "0", "body": "No this is my original code... Isn't copying other code against the terms of CR? And the usage is in the comment." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-15T13:04:20.143", "Id": "453919", "Score": "0", "body": "Yes it is, hence the question. Thank you for clarifying this." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-15T13:30:59.700", "Id": "453922", "Score": "1", "body": "No problem, sorry for the confusion. I've edited my question to make it more clear the code is mine, and where the question came from." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-15T02:13:09.487", "Id": "232422", "Score": "1", "Tags": [ "functional-programming", "scheme", "racket" ], "Title": "Cartesian product in racket (Is append-map okay?)" }
232422
<pre><code> public class URLBuilder { StringBuffer api_url; final String AND = "&amp;"; private String API_KEY; String parameter; public void setAPI_KEY(String API_KEY) { this.API_KEY = API_KEY; } public void setCity_name(String cityname) { parameter = "q="+ cityname; } public void setCity_id(String cityId) { parameter = "id="+cityId; } public void setLatLon(double latitude, double longitude) { parameter = "lat="+latitude + AND + "lon="+longitude; } public void build() { api_url = new StringBuffer("http://api.openweathermap.org/data/2.5/weather?"); api_url.append(parameter); api_url.append(AND); api_url.append("APPID="+API_KEY); } } </code></pre> <hr> <pre><code>public class TestClass { public static void main(String args[]) { URLBuilder u = new URLBuilder(); u.setAPI_KEY("af5f8fb56403d72444446fe7e097bef"); u.setCity_name("LONDON"); u.build(); } } </code></pre> <p>This is mycode to create a url for the openweathermap api. I am attempting to create a url builder class so the user can choose the parameters and the api key. I'd like to know how can i improve the code quality.</p> <p>Also what should i do to call all the methods as below of the class.</p> <pre><code>u.setAPI_KEY("af5f8fb56403d72444446fe7e097bef").setCity_name("LONDON").build(); </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-15T08:04:38.017", "Id": "453886", "Score": "1", "body": "This code doesn't generate a syntactically valid URL for `\"Mexico City\"`." } ]
[ { "body": "<p>Only constants should be written uppercase (and might contain underscores). Other variable names should not contain underscores rather use camelcase (e.g. apiUrl).</p>\n\n<p>Constants (in your case <code>AND</code>) should be declared final static, so Java only allocate memory once for the value (and not for every new object).</p>\n\n<p>Use explicit access modifiers for your variables and not the default one. In your case: <code>private</code>.</p>\n\n<p>The usage of blank lines in your setXXX methods are not consistent. I wouldn't use any blank lines at all in those methods but if you want to use them, use them consistently.</p>\n\n<p>Don't use underscores in your method names. </p>\n\n<p>Sometimes you surround the plus operator (+) with spaces, sometimes you don't. Do it consistently. Preferable surrounded by spaces.</p>\n\n<p><code>setCity_id</code> and <code>setCity_name</code> are no setters. They add something to a string. Either handle it like the <code>setAPI_KEY</code> method where you are storing the value in a variable which you later use to concatenate the string. Or rename the method to e.g. <code>addCity_name</code> to make it clear that there's a difference.</p>\n\n<p>You are concatenating a string with the plus operator here:</p>\n\n<pre><code>api_url.append(\"APPID=\"+API_KEY);\n</code></pre>\n\n<p>That's inconsistent. <code>API_KEY</code> should be appended on its own. Beside that since Java 9 it's most of the times better to use the plus operator instead of a StringBuffer (<a href=\"https://dzone.com/articles/jdk-9jep-280-string-concatenations-will-never-be-t\" rel=\"nofollow noreferrer\">https://dzone.com/articles/jdk-9jep-280-string-concatenations-will-never-be-t</a>)</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-15T09:14:44.400", "Id": "232431", "ParentId": "232423", "Score": "1" } }, { "body": "<p>In addition to the comments by Joachim, I would suggest getting rid of the <code>api_url</code> member variable, and change your <code>build()</code> function to return a <code>String</code>.</p>\n\n<p>I think that this class also needs some documenting comments to make it clear that you can have a city name, or a city ID, or lat/long, but if you try to use more than one, then the last one will overwrite the earlier ones.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-15T14:34:26.457", "Id": "232445", "ParentId": "232423", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-15T03:25:02.653", "Id": "232423", "Score": "-3", "Tags": [ "java" ], "Title": "Implementing a URL Builder" }
232423
<p>I tried starting off with something like below. Note that traversal etc. is not included, this is the portion for storage and modifications. It feels like this could be much more elegant at places but not exactly sure how. I'm mainly trying to improve how the code almost repeats for getters and setters for left and right subtrees.</p> <pre><code>import org.apache.commons.lang3.ArrayUtils; public class Tree { private int[] treeArray; private int depth; public Tree(int treeDepth) { this.depth = treeDepth; this.treeArray = new int[(int) Math.pow(2, treeDepth)]; treeArray[0] = Integer.MIN_VALUE; } public int returnRoot() { return treeArray[1]; } public int[] getTreeArray() { return treeArray; } public int getDepth() { return depth; } public void setTreeArray(int[] treeArray) { this.treeArray = treeArray; } public Tree returnLeftSubTree() { if (depth == 0) return null; Tree ret = new Tree(depth - 1); for (int i = 1; i &lt; depth; i ++) { for (int j = 0; j &lt; depth - 1; j ++) { ret.getTreeArray()[(int) Math.pow(2, i - 1) + j] = treeArray[(int) Math.pow(2, i) + j]; } } return ret; } public Tree returnRightSubTree() { if (depth == 0) return null; Tree ret = new Tree(depth - 1); for (int i = 1; i &lt; depth; i ++) { for (int j = 0; j &lt; depth - 1; j ++) { ret.getTreeArray()[(int) Math.pow(2, i - 1) + j] = treeArray[(int) (Math.pow(2, i) + Math.pow(2, i - 1)) + j]; } } return ret; } public void setLeftSubTree(Tree leftSub) { if (leftSub.getDepth() &gt;= depth) { this.treeArray = ArrayUtils.addAll( this.treeArray, new int[(int) (Math.pow(2, leftSub.getDepth() + 1) - Math.pow(2, depth))]); this.depth = leftSub.getDepth() + 1; } for (int i = 1; i &lt; depth; i ++) { for (int j = 0; j &lt; depth - 1; j ++) { treeArray[(int) Math.pow(2, i) + j] = leftSub.getTreeArray()[(int) Math.pow(2, i - 1) + j]; } } } public void setRightSubTree(Tree rightSub) { if (rightSub.getDepth() &gt;= depth) { this.treeArray = ArrayUtils.addAll( this.treeArray, new int[(int) (Math.pow(2, rightSub.getDepth() + 1) - Math.pow(2, depth))]); this.depth = rightSub.getDepth() + 1; } for (int i = 1; i &lt; depth; i ++) { for (int j = 0; j &lt; depth - 1; j ++) { treeArray[(int) (Math.pow(2, i) + Math.pow(2, i - 1)) + j] = rightSub.getTreeArray()[(int) Math.pow(2, i - 1) + j]; } } } } </code></pre>
[]
[ { "body": "<p>More efficient and accurate is a bit shift.</p>\n\n<pre><code>this.treeArray = new int[(int) Math.pow(2, treeDepth)];\ntreeArray = new int[1 &lt;&lt; treeDepth];\n</code></pre>\n\n<p>A test is in order for the top:</p>\n\n<pre><code>if (0 &gt; treeDepth || treeDepth &gt; 31) {\n throw new IllegalArgumentException();\n}\n</code></pre>\n\n<p>The name <code>returnRightSubTree</code> is a bit irritating because of that <code>return</code>, synonymical <code>yieldRightSubTree</code> or <code>get/create</code>.</p>\n\n<pre><code> public Tree returnLeftSubTree() {\n return yieldSubTree(false);\n }\n\n public Tree returnRightSubTree() {\n return yieldSubTree(true);\n }\n\n private Tree yieldSubTree(boolean right) {\n if (depth == 0) return null;\n\n Tree ret = new Tree(depth - 1);\n int[] trees = ret.getTreeArray();\n for (int i = 1; i &lt; depth; i++) {\n int iTarget = 1 &lt;&lt; (i - 1);\n int iSource = (1 &lt;&lt; i) + (right ? 1 &lt;&lt; (i - 1)) : 0);\n for (int j = 0; j &lt; depth - 1; j ++) {\n trees[iTarget + j] = trees[iSource + j];\n }\n }\n return ret;\n }\n</code></pre>\n\n<p>which could be faster using <code>System.arraycopy</code>:</p>\n\n<pre><code> private Tree yieldSubTree(boolean right) {\n if (depth == 0) return null;\n\n Tree ret = new Tree(depth - 1);\n int[] trees = ret.getTreeArray();\n for (int i = 1; i &lt; depth; i++) {\n int iTarget = 1 &lt;&lt; (i - 1);\n int iSource = (1 &lt;&lt; i) + (right ? 1 &lt;&lt; (i - 1)) : 0);\n System.arraycopy(trees, iSource, trees, iTarget, depth - 1);\n }\n return ret;\n }\n</code></pre>\n\n<p>The <code>i</code> dependent expression <em>before</em> the <code>j</code> loop. As you see, just as i++\none could have (but not necessarily):</p>\n\n<pre><code> for (int i = 1, iT = 1; i &lt; depth; i++, iT &lt;&lt;= 1) {\n //int iTarget = iT;\n int iSource = (iT &lt;&lt; 1) + (right ? iT : 0);\n</code></pre>\n\n<p>For the rest:</p>\n\n<p>Tab indentation in java is 4. Historically a tab size of 3 was often for C/C++,\nand for academic reasons: <em>\"there should be less long code with nesting in favour of\nmore methods\"</em> 4 was chosen; also as 8 was the archaic system tab size.</p>\n\n<p>A tab size of 2 is still seen in XML/HTML, but I would refrain from that. Especially\nas with lambdas one gets more unreadable indentations.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-15T14:35:20.517", "Id": "453929", "Score": "0", "body": "Thanks much! Never realized this was a perfect use case for bit shifts" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-15T14:39:42.760", "Id": "453930", "Score": "1", "body": "Also one could use `|` instead of `+`. Also the class `BitSet` can often be useful, and overcomes the limitation, say of `long` for its 64 bits. If the values are 0/1." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-15T09:23:07.963", "Id": "232433", "ParentId": "232424", "Score": "2" } } ]
{ "AcceptedAnswerId": "232433", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-15T04:33:44.117", "Id": "232424", "Score": "0", "Tags": [ "java" ], "Title": "Basic implicit tree implementation in Java" }
232424
<p>I made this as a personal challenge. It seems to work fine as I can't find any bugs and am happy with how it runs, but I am interested in what I should do to make the code more professional.</p> <p><em>Note: This code was tested in Python 3.7.4.</em></p> <pre><code>class TicTacToe: def __init__(self): self.p1 = '\U00002B55' self.p2 = '\U0000274C' self.draw = [0,1,2,3,4,5,6,7,8] self.counte = 0 self.Print() def fillNumber(self,inputnumber): self.counte = self.counte + 1 if self.counte % 2 == 0 : player = self.p2 else : player = self.p1 self.draw[inputnumber] = player def condition(self): if (self.draw[0] == self.draw[1] and self.draw[1] == self.draw[2]) : return self.draw[0] elif (self.draw[3] == self.draw[4] and self.draw[4] == self.draw[5]) : return self.draw[3] elif (self.draw[6] == self.draw[7] and self.draw[7] == self.draw[8]) : return self.draw[6] elif (self.draw[0] == self.draw[3] and self.draw[3] == self.draw[6]) : return self.draw[0] elif (self.draw[1] == self.draw[4] and self.draw[4] == self.draw[7]) : return self.draw[1] elif (self.draw[2] == self.draw[5] and self.draw[5] == self.draw[8]) : return self.draw[2] elif (self.draw[0] == self.draw[4] and self.draw[4] == self.draw[8]) : return self.draw[0] elif (self.draw[6] == self.draw[4] and self.draw[4] == self.draw[2]) : return self.draw[6] else: return False def Print(self): for i in range(1,10) : print(self.draw[i-1],end=" ") if i % 3 == 0 : print() class Game(TicTacToe): def start(self): try : inputnumber = int(input('Input number 0 to 8 \n')) except ValueError : self.start() if 0 &lt;= inputnumber &lt;= 8 : if (self.draw[inputnumber] == '\U00002B55') or (self.draw[inputnumber] == '\U0000274C') : print("This place is already paused") self.start() else : self.fillNumber(inputnumber) else : self.start() self.Print() self.check() def check(self): if self.condition() == False : self.start() elif self.condition() == '\U00002B55' : print(self.condition()," Player one is winner") elif self.condition() == '\U0000274C' : print(self.condition()," player two is winner") if __name__=="__main__": obj=Game() obj.start() </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-15T12:35:18.023", "Id": "453915", "Score": "6", "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>First of all, I suggest you read pep8 (<a href=\"https://pep8.org/\" rel=\"noreferrer\">https://pep8.org/</a>). I see you have violations. Understanding pep8 is a must if you want to be a pro Python developer. Better yet, use flake8 to automatically find pep8 violations in your code.</p>\n\n<p>Second, using that many <code>elif</code> statements is always a red flag, especially when they seem to be doing the same thing. Can you somehow get rid of that duplication?</p>\n\n<p>Next, put some blank lines between logical blocks of code to improve readability. In <code>Game.start</code> the try catch block is logically separate from the conditional following it, for example.</p>\n\n<p>Next, give your variables meaningful names. For example, <code>game.start</code> is much better than <code>obj.start</code>. Also, avoid using shortened version of words, like <code>object</code> -> <code>obj</code> because it doesn't add much value and can decrease readability.</p>\n\n<p>Finally, I'd like to see some tests. Not because I think your code has a bug but because I want to know how your code actually works. Because there's some logical reasoning in the nature of the problem, you can help the reader by documenting the algorithm you've implemented. Unit tests are perfect for this. They're fast, they target specific conditions one at a time, and document your code better than comments.<br>\nIf you're wondering where to start when it comes to testing your code I suggest watching some videos on TDD in action. Kent Beck and Uncle Bob have some free videos showing how to do TDD step by step.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-15T12:03:06.433", "Id": "453912", "Score": "0", "body": "There's also a very good reason for using `obj` over `object`, because the long form shadows a builtin name. And perhaps some links to those video's would help." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-15T10:55:48.087", "Id": "232438", "ParentId": "232429", "Score": "5" } }, { "body": "<p>In no particular order:</p>\n\n<ol>\n<li><p>Comments on what the variable names represent would be helpful, if for no other reason than to encourage more thought about your data model -- if it's hard to describe what each variable contains, maybe there's a way to store your data that's less confusing?</p></li>\n<li><p><code>p1</code> and <code>p2</code> look like static values, so I'd suggest making them class attributes rather than instance attributes (also it'd be good to have a comment in the code saying what these glyphs are). Better yet, this could be its own class of <code>Enum</code> called <code>Player</code>!</p></li>\n<li><p>The starting values in <code>draw</code> don't seem to have any significance, which makes the code harder to understand. I get that you did this to make sure they'd never be equal when you're testing for win conditions, but I think it would be clearer to just have a single obvious \"non-player\" value like <code>None</code> and check for that when you do your comparisons.</p></li>\n<li><p><code>counte</code>(r?) isn't a very descriptive name; maybe <code>turns</code>, or <code>turn_counter</code> if you wanted to get verbose about it?</p></li>\n<li><p>Instead of implementing a <code>Print()</code> method, implement <code>__repr__()</code> so that <code>print(your_object)</code> will do the right thing.</p></li>\n<li><p>There's no reason to make <code>Game</code> a subclass of <code>TicTacToe</code> -- indeed, there's no reason for it to even be a class/object, since it doesn't have any state. I'd just make a top-level function that creates a <code>TicTacToe</code> and runs the game.</p></li>\n<li><p>If I understand your <code>condition</code> method correctly, it's checking for a winner? I'd maybe call this <code>get_winner</code> and have it return an <code>Optional[Player]</code>.</p></li>\n<li><p>The implementation of <code>condition</code> with all the <code>if elif</code> is very repetitive, but it's also hard to visually examine it and have confidence that it's checking all the right cases. You could instead write a helper function that does the check for an arbitrary set of spaces and run that for all the winning sets, having all the winning sets lined up neatly so it's easy to visually validate them.</p></li>\n</ol>\n\n<p>Here's a rewrite of just your <code>condition</code> method with some of the suggestions I've made, so you can get an idea of what this code might look like.</p>\n\n<pre><code># Instead of self.p1 and self.p2 you can now say Player.ONE and Player.TWO,\n# and these values will both type-check as \"Player\".\nclass Player(Enum):\n ONE = '\\U00002B55'\n TWO = '\\U0000274C'\n\n...\n\n def get_winner(self) -&gt; Optional[Player]:\n \"\"\"Returns the winning player, or None if no winner yet.\"\"\"\n\n def owns_all_spaces(spaces: List[int]) -&gt; Optional[Player]:\n # Build a set of the owners of all the spaces.\n # If the set contains only one element, then either\n # one player owns all of them or they're all unclaimed.\n owners = set([self.board[space] for space in spaces])\n owner = owners.pop()\n if isinstance(owner, Player) and len(owners) == 0:\n return owner\n else:\n return None\n\n for in_a_row in [\n [0, 1, 2], # 3 horizontal\n [3, 4, 5],\n [6, 7, 8],\n [0, 3, 6], # 3 vertical\n [1, 4, 7],\n [2, 5, 8],\n [0, 4, 8], # 2 diagonal\n [2, 4, 6],\n ]:\n winner = owns_all_spaces(in_a_row)\n if winner:\n return winner\n return None\n<span class=\"math-container\">```</span>\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-15T20:16:07.473", "Id": "453973", "Score": "0", "body": "note that while it was tempting to try to implement a procedural method of checking for \"3 in a row\", I opted to restructure the way the code is written without changing the basic logic. There's definitely more than one way to skin this cat." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-15T20:14:01.933", "Id": "232463", "ParentId": "232429", "Score": "3" } }, { "body": "<p>As others have mentioned, python has a style guide, PEP8. It's very useful for yourself and people reading your code if you follow this guide as it makes your code consistent, readable and idiomatic.</p>\n\n<p>You have some typos and warnings in your code which show up immediately in my editor. It's worth looking at using an IDE to see these while you're writing. Personally I use Pycharm which has a free community edition.</p>\n\n<p>When comparing to <code>0</code> or <code>False</code>, just use <code>not</code>. It is clearer and more idiomatic. e.g. <code>if not condition(): ...</code> or <code>if not i % 2: ...</code>.</p>\n\n<p>Don't name things <code>Print()</code> or other python built-in names. Be more descriptive. e.g. <code>display_board()</code> or something similar.</p>\n\n<p>Handling user input is often where a while loop is used to set an exit condition. It's usually recommended to only take a few incorrect answers, and to have better handling of invalid inputs. Take the following for example:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>max_attempts, input_attempts = 3, 0\ninput_number = None\n\nwhile input_attempts &lt; max_attempts:\n try:\n input_number = int(input('Please select a number between 0 and 8: '))\n if 0 &lt;= input_number &lt;= 8:\n # Input is valid, exit loop\n break\n else:\n print('Invalid input, input must be between 0 and 8')\n input_number = None\n except ValueError:\n print('Invalid input, input must be an integer')\n input_attempts += 1\n\nif input_number is None:\n raise RuntimeError('No valid user input obtained.')\n</code></pre>\n\n<p>Here, I've clearly defined the maximum number of attempts, so there's no \"magic number\" 3 which may be confusing. I've handled different kinds of invalid input: not a string which can be cast to an int, or not a number between 0 and 8. I've also created an exit condition which is very clear and has a description for what is going on. This all may seem a little over the top for tic-tac-toe but it's good practice for the future.</p>\n\n<p>@Sam-Stafford has some good suggestions for an alternative implementation of <code>condition()</code>. Checking against the list of winning positions is a good idea but I would not write it as an inner function, there's also no need to <code>return None</code> if no winner is found. Just check the board from turn 5 onwards for a winner.</p>\n\n<p>It would be good to keep track of whose turn it is and exit when all of the board is filled in.</p>\n\n<p>As for the class structure, personally I would have one class which keeps track of the board, it would contain win conditions and limits on size etc. Then a separate function which handles the game itself with user input etc. Inheritance shouldn't be necessary and I would discourage it in this case.</p>\n\n<p>Hope that helps.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-18T11:35:31.113", "Id": "232585", "ParentId": "232429", "Score": "2" } }, { "body": "<p>Your code can have many improvements.</p>\n\n<h2>Fixing the bugs</h2>\n\n<pre><code>0 1 2 \n3 4 5 \n6 7 8 \nInput number 0 to 8 \nasd\nInput number 0 to 8 \nasd\nInput number 0 to 8 \n0\n⭕ 1 2 \n3 4 5 \n6 7 8 \nInput number 0 to 8 \n1\n⭕ ❌ 2 \n3 4 5 \n6 7 8 \nInput number 0 to 8 \n2\n⭕ ❌ ⭕ \n3 4 5 \n6 7 8 \nInput number 0 to 8 \n3\n⭕ ❌ ⭕ \n❌ 4 5 \n6 7 8 \nInput number 0 to 8 \n4\n⭕ ❌ ⭕ \n❌ ⭕ 5 \n6 7 8 \nInput number 0 to 8 \n5\n⭕ ❌ ⭕ \n❌ ⭕ ❌ \n6 7 8 \nInput number 0 to 8 \n6\n⭕ ❌ ⭕ \n❌ ⭕ ❌ \n⭕ 7 8 \n⭕ Player one is winner\nTraceback (most recent call last):\n File \"C:/Users/Administrator/.PyCharmCE2018.3/config/scratches/scratch_1.py\", line 43, in start\n inputnumber = int(input('Input number 0 to 8 \\n'))\nValueError: invalid literal for int() with base 10: 'asd'\n\nDuring handling of the above exception, another exception occurred:\n\nTraceback (most recent call last):\n File \"C:/Users/Administrator/.PyCharmCE2018.3/config/scratches/scratch_1.py\", line 66, in &lt;module&gt;\n obj.start()\n File \"C:/Users/Administrator/.PyCharmCE2018.3/config/scratches/scratch_1.py\", line 45, in start\n self.start()\n File \"C:/Users/Administrator/.PyCharmCE2018.3/config/scratches/scratch_1.py\", line 46, in start\n if 0 &lt;= inputnumber &lt;= 8 :\nUnboundLocalError: local variable 'inputnumber' referenced before assignment\n</code></pre>\n\n<p>After the wrong input was given, the recursive statement was stored in stack and was run later.</p>\n\n<p><code>UnboundLocalError</code> occured because <code>inputnumber</code> was used inside <code>try</code> statement. To prevent that from happening, you can just add <code>inputnumber = None</code> before the <code>try</code> statement.</p>\n\n<p>Even after that:</p>\n\n<pre><code>0 1 2 \n3 4 5 \n6 7 8 \nInput number 0 to 8 \nasd\nInput number 0 to 8 \n0\n⭕ 1 2 \n3 4 5 \n6 7 8 \nInput number 0 to 8 \n3\n⭕ 1 2 \n❌ 4 5 \n6 7 8 \nInput number 0 to 8 \n1\n⭕ ⭕ 2 \n❌ 4 5 \n6 7 8 \nInput number 0 to 8 \n6\n⭕ ⭕ 2 \n❌ 4 5 \n❌ 7 8 \nInput number 0 to 8 \n2\n⭕ ⭕ ⭕ \n❌ 4 5 \n❌ 7 8 \n⭕ Player one is winner\nTraceback (most recent call last):\n File \"C:/Users/Administrator/.PyCharmCE2018.3/config/scratches/scratch_1.py\", line 67, in &lt;module&gt;\n obj.start()\n File \"C:/Users/Administrator/.PyCharmCE2018.3/config/scratches/scratch_1.py\", line 47, in start\n if 0 &lt;= inputnumber &lt;= 8 :\nTypeError: '&lt;=' not supported between instances of 'int' and 'NoneType'\n</code></pre>\n\n<p><code>TypeError</code> occurs because <code>inputnumber</code> was <code>None</code>, as a <code>ValueError</code> was caught while converting <code>inputnumber</code> to <code>int</code>. This moves on to the next line where it compares <code>inputnumber</code> (which is <code>None</code>) to <code>0</code> and <code>8</code>.</p>\n\n<p>To prevent that, you must add <code>return</code> statement after <code>self.start()</code></p>\n\n<h2>Miscellaneous</h2>\n\n<ul>\n<li><p><strong>Don't use elif statements unnecessarily</strong></p></li>\n<li><p><strong>Parentheses for <code>if</code> statements should be avoided</strong><br>\n<code>if (self.draw[0] == self.draw[1] and self.draw[1] == self.draw[2]) :</code>\nshould be replaced with<br>\n<code>if self.draw[0] == self.draw[1] and self.draw[1] == self.draw[2]:</code></p></li>\n<li><p><strong>In python, <code>if a == b and b == c</code> can be replaced with <code>if a == b == c</code></strong></p></li>\n<li><p><strong>Use meaningful variable names</strong><br>\n<code>p1</code> can be changed to <code>player1</code>, and <code>counte</code> can be changed to <code>counter</code>, <code>draw</code> could be <code>board</code>, etc.</p></li>\n<li><p><strong><code>if somevalue == False</code> should be replaced with <code>if not somevalue</code></strong></p></li>\n</ul>\n\n<p>Here's the final code after some more small changes:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>X = '\\U00002B55'\nO = '\\U0000274C'\n\nclass TicTacToe:\n def __init__(self):\n self.player1 = X\n self.player2 = O\n self.board = list(range(9))\n\n self.counter = 0\n self.Print()\n\n def fillNumber(self,inputnumber):\n self.counter += 1\n\n if self.counter % 2:\n player = self.player1\n else:\n player = self.player2\n\n self.board[inputnumber] = player\n\n def condition(self):\n # Rows\n if self.board[0] == self.board[1] == self.board[2]: return self.board[0]\n if self.board[3] == self.board[4] == self.board[5]: return self.board[3]\n if self.board[6] == self.board[7] == self.board[8]: return self.board[6]\n\n # Columns\n if self.board[0] == self.board[3] == self.board[6]: return self.board[0]\n if self.board[1] == self.board[4] == self.board[7]: return self.board[1]\n if self.board[2] == self.board[5] == self.board[8]: return self.board[2]\n\n # Diagonals\n if self.board[0] == self.board[4] == self.board[8]: return self.board[0]\n if self.board[6] == self.board[4] == self.board[2]: return self.board[6]\n\n return False\n\n def Print(self):\n for i in range(1, 10):\n print(self.board[i - 1], end=' ')\n\n if i % 3 == 0:\n print()\n\n print()\n\nclass Game(TicTacToe):\n def start(self):\n inputnumber = None\n\n try:\n inputnumber = int(input('Input number 0 to 8: '))\n\n if not 0 &lt;= inputnumber &lt;= 8:\n raise ValueError\n\n except ValueError:\n print('Please input a valid number')\n self.start()\n\n return\n\n if (self.board[inputnumber] == X) or (self.board[inputnumber] == O):\n print('This place is already occupied')\n self.start()\n\n else:\n self.fillNumber(inputnumber)\n\n self.Print()\n self.check()\n\n def check(self):\n winner = self.condition()\n\n if not winner:\n self.start()\n\n if winner == X: print(winner, ' Player one is winner')\n if winner == O: print(winner, ' Player two is winner')\n\nif __name__ == '__main__':\n obj = Game()\n obj.start()\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-19T19:03:43.200", "Id": "232653", "ParentId": "232429", "Score": "2" } } ]
{ "AcceptedAnswerId": "232438", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-15T08:20:32.863", "Id": "232429", "Score": "4", "Tags": [ "python", "python-3.x", "tic-tac-toe" ], "Title": "Tic Tac Toe Game in Python 3" }
232429
<p>I have the below</p> <pre><code>private function yearMenu() { $m = date('m'); $y = date('Y'); if (($m&gt;3 &amp;&amp; $y==2019) || ($m&lt;4 &amp;&amp; $y==2020)){ $menu = 1; } if (($m&gt;3 &amp;&amp; $y==2020) || ($m&lt;4 &amp;&amp; $y==2021)){ $menu = 2; } if (($m&gt;3 &amp;&amp; $y==2021) || ($m&lt;4 &amp;&amp; $y==2022)){ $menu = 3; } if (($m&gt;3 &amp;&amp; $y==2022) || ($m&lt;4 &amp;&amp; $y==2023)){ $menu = 4; } if (($m&gt;3 &amp;&amp; $y==2023) || ($m&lt;4 &amp;&amp; $y==2024)){ $menu = 5; } if (($m&gt;3 &amp;&amp; $y==2024) || ($m&lt;4 &amp;&amp; $y==2025)){ $menu = 6; } return $menu; } </code></pre> <p>This code works as intended i.e. I want to be able to give each financial year an integer based on 2019-2020 being the base at value 1 and it increasing each year onward</p> <p>I was wondering if there was a more succinct and scalable way to do this?</p> <p>Thanks</p>
[]
[ { "body": "<p><em><h3>Ways of improving:</h3></em></p>\n\n<p>According to information provided the crucial function's purpose is \"to return a particular <em>menu</em> number for the current <em>year</em>\". Thus, the function name would be more descriptive with name <strong><code>getFinYearMenuNumber</code></strong>.</p>\n\n<p>The preconditions are:</p>\n\n<ul>\n<li>your financial year flows through <em>\"April to April\"</em> month periods</li>\n<li><p>there's starting year <code>2019</code> and ending year <code>2015</code> for the whole interval.<br>To make the function more unified those boundaries could be passed as input parameters:</p>\n\n<pre><code>function getFinYearMenuNumber($yearFrom, $yearTo)\n</code></pre></li>\n</ul>\n\n<p>The main issue of the current approach is that it'll inevitably perform <strong>5</strong> excessive <code>if</code> checks (they could be at least mutually exclusive <code>if ... else if ... else if ...</code>).<br></p>\n\n<p>Instead, we can just perform 2 subsequent checks: </p>\n\n<ul>\n<li>if the current year falls in the needed interval</li>\n<li>if the current month is following or preceding the starting month (April)</li>\n</ul>\n\n<hr>\n\n<p>The final version:</p>\n\n<pre><code>function getFinYearMenuNumber($yearFrom, $yearTo) {\n $curr_month = (int) date('m'); # current month number\n $curr_year = (int) date('Y'); # current year\n $curr_date = new DateTime();\n\n if ((new DateTime(\"$yearFrom-04\")) &lt;= $curr_date &amp;&amp; $curr_date &lt;= (new DateTime(\"$yearTo-04\"))) {\n if ($curr_month &gt; 3) {\n return $curr_year - $yearFrom + 1; \n } else if ($curr_month &lt; 4) {\n return $curr_year - $yearFrom; \n }\n }\n\n return 0;\n}\n\nprint_r(getFinYearMenuNumber(2019, 2025));\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-15T13:01:56.010", "Id": "232441", "ParentId": "232432", "Score": "1" } }, { "body": "<p>Your current version is very much a fixed piece of code, as you can see there is a lot of repetition and the result can be summed up as</p>\n\n<ul>\n<li>Based on 2019-04-01 being the start of the first year</li>\n<li>The year counting up as starting on the 4th month of each year.</li>\n</ul>\n\n<p>This code is very much based on that premise, taking the start date (an optional parameter to this method - defaulted to current date) the code takes the difference between the date to test and the date of 2019-04-01 (using <a href=\"https://www.php.net/manual/en/datetime.diff.php\" rel=\"nofollow noreferrer\"><code>diff()</code></a>). This returns an instance of <a href=\"https://www.php.net/manual/en/class.dateinterval.php\" rel=\"nofollow noreferrer\"><code>DateInterval</code></a>, which you can then extract the year component (<code>y</code>) and add 1 so that 2019 is year 1.</p>\n\n<p>(Altered to be a standalone function for test purposes)...</p>\n\n<pre><code>function getFinanceYear ( DateTime $dateToTest = null) {\n // Use date passed in, or default to current date\n $dateToTest = $dateToTest ?? new DateTime();\n // Calculate the difference\n $interval = $dateToTest-&gt;diff(new DateTime(\"2019-04-01\"));\n // return the difference in years (offset by 1)\n return $interval-&gt;y+1;\n}\n</code></pre>\n\n<p>A few test runs...</p>\n\n<pre><code>echo getFinanceYear().PHP_EOL; // 1\necho getFinanceYear(new DateTime(\"2029-03-01\")).PHP_EOL; // 10\necho getFinanceYear(new DateTime(\"2029-04-01\")).PHP_EOL; // 11\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-15T22:19:34.600", "Id": "453983", "Score": "0", "body": "Excellent, succinct, scalable, and unconditional (in its calculation)." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-15T15:41:36.840", "Id": "232451", "ParentId": "232432", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-15T09:21:11.507", "Id": "232432", "Score": "1", "Tags": [ "php" ], "Title": "PHP: Succint and scalable function to get what financial year we are in" }
232432
<p>I created my first JavaScript program and I feel it's all over the place. I just started it without thinking too much about it. Now, I am quite sure I should have used OO style.</p> <p>Also, it seems there is a lot of repetitive code.</p> <p>Anyway, as this is my first JS project I would be thankful for all feedback or any pointer to a topic I should look into.</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>//surpresses rightclick menu window.oncontextmenu = (e) =&gt; { e.preventDefault(); } var field = { cols: 0, rows: 0, mines: 10, markedMines: 0, bombArray: [], gameover: false //checks if every field with a mine is flagged. if not, returns false , checkWin: function () { let check = true; for (let i = 1; i &lt;= field.cols; i++) { for (let j = 1; j &lt;= field.rows; j++) { let newId = parseInt(i); newId += "/"; newId += parseInt(j); if (field.bombArray[i][j] == "x" &amp;&amp; document.getElementById(newId).style.backgroundColor != "red") check = false; } } return check; } //injects the gamefield into html- td id = i/j - left click reveals a field, right click flags a field , printTable: function (cols, rows) { let html = ''; let id = ''; html += '&lt;table class="field"&gt;'; for (i = 1; i &lt;= cols; i++) { html += '&lt;tr&gt;'; for (j = 1; j &lt;= rows; j++) { html += '&lt;td id="' + i + '/' + j + '" onclick=field.reveal(id) oncontextmenu=field.markABomb(id) align="center"&gt;'; html += '&lt;/td&gt;'; } html += '&lt;/tr&gt;'; } html += '&lt;/table&gt;'; return html; } // functioncall with rightclick on &lt;td&gt; , markABomb: function (id) { let x = id.substring(0, id.indexOf("/")); let y = id.substring((id.indexOf("/") + 1), (id.length + 1)); if (!this.gameover) { if (document.getElementById(id).style.backgroundColor != "yellow") { if (document.getElementById(id).style.backgroundColor == "red") { document.getElementById(id).style.backgroundColor = "blue"; field.markedMines--; field.mines++; } else { document.getElementById(id).style.backgroundColor = "red"; field.markedMines++; field.mines--; } } else { //if flagged mines on adjacant fields are equal to number on the field, reveal all adjacent fieds. put maybe into own funtion? if (this.bombArray[x][y] === this.countRedNeighbours(x, y)) { for (let i = -1; i &lt; 2; i++) { for (let j = -1; j &lt; 2; j++) { let id = parseInt(parseInt(x) + parseInt(i)); id += "/"; id += parseInt(parseInt(y) + parseInt(j)); this.reveal(id); } } } } this.updateShowCounter(); if (this.mines == 0) { if (this.checkWin()) { alert("congratulations. You won!"); this.gameover = true; } else alert("somethings not quite right"); } } } , updateShowCounter: function () { document.getElementById("marked").innerHTML = ("&lt;p color:white&gt;marked: " + this.markedMines + "&lt;/p&gt;"); document.getElementById("minesLayed").innerHTML = ("&lt;p color:white&gt;mines: " + this.mines + "&lt;/p&gt;"); } //counts adjacent flagged mines. what a mess. , countRedNeighbours: function (x, y) { let counter = 0; for (let i = -1; i &lt; 2; i++) { for (let j = -1; j &lt; 2; j++) { let id = ""; id = parseInt(parseInt(x) + parseInt(i)); let ix = parseInt(parseInt(x) + parseInt(i)); id += "/"; id += parseInt(parseInt(y) + parseInt(j)); let yj = parseInt(parseInt(y) + parseInt(j)); let z = field.bombArray.length - 1; if (ix &gt; 0 &amp;&amp; yj &gt; 0 &amp;&amp; ix &lt; field.bombArray.length - 1 &amp;&amp; yj &lt; this.bombArray[z].length - 1) { if (document.getElementById(id).style.backgroundColor == "red") counter++; } } } return counter; } , revealAllBombs: function (cols, rows) { for (let i = 0; i &lt;= parseInt(cols); i++) { for (let j = 0; j &lt;= (rows); j++) { if (field.bombArray[i][j] == "x") { if (i &lt; this.bombArray.length - 1 &amp;&amp; j &lt; this.bombArray[this.cols].length - 1) { let id = parseInt(i); id += "/"; id += parseInt(j); document.getElementById(id).innerHTML = "X"; document.getElementById(id).style.backgroundColor = "red"; } } } } } //functioncall from &lt;td&gt;, left-click , reveal: function (id) { if (!this.gameover) { let x = id.substring(0, id.indexOf("/")); let y = id.substring((id.indexOf("/") + 1), (id.length + 1)); if (x &gt; 0 &amp;&amp; y &gt; 0 &amp;&amp; x &lt; this.bombArray.length - 1 &amp;&amp; y &lt; this.bombArray[this.cols].length - 1) { if (document.getElementById(id).style.backgroundColor != "red") { if (field.bombArray[x][y] == "x") { field.revealAllBombs(this.cols, this.rows); alert("lost"); this.gameover = true; } else if (field.bombArray[x][y] == "0") { field.revealAll0(id); } else { document.getElementById(id).style.backgroundColor = "yellow"; document.getElementById(id).innerText = field.bombArray[x][y]; } } } } } , buildArray: function (cols, rows) { cols++; rows++; for (let i = 0; i &lt;= parseInt(cols); i++) { field.bombArray[i] = []; for (let j = 0; j &lt;= parseInt(rows); j++) { field.bombArray[i][j] = ""; } } } , setMine: function (cols, rows) { let x = Math.floor((Math.random() * cols)); let y = Math.floor((Math.random() * rows)); x++; y++; field.bombArray[x][y] = "x"; } , countMines: function (cols, rows) { let mineCounter = 0; for (let i = 1; i &lt;= cols; i++) { for (let j = 1; j &lt;= rows; j++) { if (field.bombArray[i][j] == "x") mineCounter++; } } return mineCounter; } //counts all adajacent X and writes it in bpmbArray , countNeighbours: function (cols, rows) { for (let x = 1; x &lt; cols + 1; x++) { for (let y = 1; y &lt; rows + 1; y++) { let counter = 0; for (let i = -1; i &lt; 2; i++) { for (let j = -1; j &lt; 2; j++) { let xi = x + i; let yj = y + j; if (xi &gt; 0 &amp;&amp; yj &gt; 0 &amp;&amp; xi &lt; this.bombArray.length &amp;&amp; yj &lt; this.bombArray[this.cols].length) if (this.bombArray[parseInt(x + i)][parseInt(y + j)] === "x") counter++; } } if (x &gt; 0 &amp;&amp; y &gt; 0 &amp;&amp; x &lt; this.bombArray.length &amp;&amp; y &lt; this.bombArray[this.cols].length) if (field.bombArray[x][y] != "x") field.bombArray[x][y] = parseInt(counter); } } } // if a field with 0 mines next to it is revealed, all fields with 0 are revealed , revealAll0: function (id) { let listXY = []; listXY.push([parseInt(id.substring(0, id.indexOf("/"))), parseInt(id.substring((id.indexOf("/") + 1), (id.length + 1)))]); while (listXY.length &gt; 0) { let x = parseInt(listXY[0][0]); let y = parseInt(listXY[0][1]); for (let i = -1; i &lt; 2; i++) { for (let j = -1; j &lt; 2; j++) { if ((x + i != 0 &amp;&amp; y + j != 0 &amp;&amp; (x + i) &lt;= document.getElementById("cols").value &amp;&amp; (y + j) &lt;= document .getElementById("rows").value)) { let newId = parseInt(x + i); newId += "/"; newId += parseInt(y + j); if (document.getElementById(newId).style.backgroundColor == "red") { field.mines++; field.markedMines--; this.updateShowCounter(); } if (field.bombArray[x + i][y + j] != "x" &amp;&amp; document.getElementById(newId).style.backgroundColor != "yellow") { document.getElementById(newId).style.backgroundColor = "yellow"; if (field.bombArray[x + i][y + j] != 0) document.getElementById(newId).innerText = field.bombArray[ x + i][y + j]; if (field.bombArray[x + i][y + j] == 0) { listXY.push([x + i, y + j]) } } } } } listXY.shift(); } } } //-----------------------------------Object ends here--------------------------------------------------------------------------- function insertHTML(id, html) { let el = document.getElementById(id); el.innerHTML = html; } run = () =&gt; { field.gameover = false; let cols = document.getElementById("cols").value; field.cols = cols; let rows = document.getElementById("rows").value; field.rows = rows; field.mines = document.getElementById("mines").value; field.markedMines = 0; field.updateShowCounter(); if ((field.cols * field.rows &lt; field.mines) || cols &lt;= 1 || rows &lt;= 1 || cols &gt; 100 || rows &gt; 100 || field.mines &lt; 1) { alert("so nicht Kevin") field.gameover=true; } else { let html = field.printTable(cols, rows); field.buildArray(cols, rows); while (field.countMines(cols, rows) &lt; field.mines) field.setMine(cols, rows); field.countNeighbours(cols, rows); insertHTML('table', html); } } // Run everything when the document loads. window.onload = run;</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>html { font-family: sans-serif; } .wrapper { display: grid; grid-template-columns: 200px, 8fr; grid-template-areas: "....... header" "settings content"; justify-content: left; grid-gap: 20px; white-space:nowrap; } .header { align-items: end; height: 10px; grid-area: header; color: white; margin-top: 10px; } .settings{ grid-area: settings; position: absolut; white-space: nowrap; margin-top: 50px; } input { -moz-appearance: textfield; text-align: right; text-decoration: none; border: 0; background: black; border-bottom: 1px solid; color: #ffffff; width: 75px; } input[type=number]::-webkit-inner-spin-button, input[type=number]::-webkit-outer-spin-button { opacity: 0; } .content { grid-column-start: 2; grid-area: content; margin-top: 50px; } body { background: black; } #manual{ color: white; font-size: small; opacity: 20%; } #manual:hover{ opacity: 75%; } td { background: blue; height: 20px; width: 20px; } td:hover{ background: rgba(0, 0, 255, 0.527); } h1{ text-align: right; } p { color: white; } button { margin-top: 20px; } .marked { color: red; margin-top: 25px; } .minesLayed { color: red; margin-top: 25px; } </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;Minesweeper&lt;/title&gt; &lt;link rel="stylesheet" type="text/css" href="style.css" /&gt; &lt;script language="javascript" type="text/javascript" src="script.js" &gt;&lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;div class="wrapper"&gt; &lt;div class="header"&gt;&lt;h1&gt;.Minesweeper&lt;/h1&gt;&lt;/div&gt; &lt;div id="settings" class="settings" align="right"&gt; &lt;p&gt; columns: &lt;input type="number" name="rows" id="rows" value="16" /&gt; &lt;/p&gt; &lt;p&gt; rows: &lt;input type="number" name="cols" id="cols" value="16" /&gt; &lt;/p&gt; &lt;p&gt;mines: &lt;input type="number" name="mines" id="mines" value="40" /&gt;&lt;/p&gt; &lt;button type="submit" id="submit" lang="Name" onclick="run()"&gt; Start &lt;/button&gt; &lt;div class="minesLayed" id="minesLayed"&gt;&lt;/div&gt; &lt;div class="marked" id="marked"&gt;&lt;/div&gt; &lt;/div&gt; &lt;div id="table" class="content"&gt;&lt;/div&gt; &lt;/div&gt; &lt;p id="manual"&gt;Your goal is to flag all mines. Left-click a blue square to reveal it.&lt;br&gt; Right-click a blue square to flag it. A flaged quare is red. Right-click a red quare to unflag it.&lt;br&gt; A number represants the adjacent mines. If all adjacent mines are flaged, right-click it to reveal its adjacant squares&lt;/p&gt; &lt;/body&gt; &lt;/html&gt;</code></pre> </div> </div> </p>
[]
[ { "body": "<p><strong>Definitely don't do this</strong>. The value should be on the same line as the variable being set. People read lines of code line-by-line, it's really confusing to see a lonely <code>false;</code>. Also, use line braces <code>{</code> <code>}</code> even when the code to be executed is 1 line long. And put the code all on a new line)</p>\n\n<pre><code>if (field.bombArray[i][j] == \"x\" &amp;&amp; document.getElementById(newId).style.backgroundColor != \"red\") check =\n false;\n</code></pre>\n\n<p><strong>Try to keep code separated in ways that make sense. Marking a bomb should not contain logic for checking if the player won</strong>. You also shouldn't run the <code>checkWin</code> method here. </p>\n\n<p>For game-related reasons, checking if player won when a bomb is marked doesn't make sense. Does the player need to mark all bombs to win?</p>\n\n<p><strong>Stay away from magic numbers / magic Strings</strong>, use constants instead.</p>\n\n<p><strong>Use comments</strong> to explain parts of your code. What you are doing with the <code>newId</code> variable could probably be done better/differently, but tbh It's hard to follow. You could make it into a method (And still document if the name doens't explain well enough).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-15T14:27:01.430", "Id": "453928", "Score": "0", "body": "ah yes, that line break was made by one of the beautifier i tried. did not catch them all to undo them.\n\nthe checkWin function is only called if the amount of flagged fields is equal to the amount of mines." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-15T13:29:37.627", "Id": "232442", "ParentId": "232434", "Score": "3" } }, { "body": "<h2>Code Review</h2>\n\n<p>Great work! Programming is a skill that most find near impossible to pick up. Your game clearly demonstrates you have the mind of a coder and just getting an app to work, as a beginner, deserves full points.</p>\n\n<p>I could only see one bug and that is the page will lock up if the number of mines is greater than the number of cells.</p>\n\n<p>Your code does show your lack of experience (which is not a bad thing we all started this way) so this review is rather long as there are many items to cover. The example rewrite may also be a little advanced so if you have questions please do ask in the comments and I will reply in comment or update this answer to clarify any points.</p>\n\n<p>This answer should contain many links but as there are so many I have just included this <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript\" rel=\"nofollow noreferrer\">MDN JavaScript reference</a> From that page you can find all you will need regarding and of the functions and objects mentioned in this answer.</p>\n\n<h2>Logic, layout and design.</h2>\n\n<h3>Use the DOM</h3>\n\n<p>You create a table with columns and rows however you reference (by name) the columns as row and the rows as columns. This type of missing naming can create serious problems when maintaining the code. Always be precise in your naming and abstraction.</p>\n\n<h3>Single event</h3>\n\n<p>You add events for every cell in the game. You are far better of adding one event listener to the tables and in that listener using the <code>event</code> object to get the cell that triggered the event. see example <code>field.cellClicked</code></p>\n\n<h3><code>String.split</code></h3>\n\n<p>Extracting content from a string. You get the row and column of a cell using the <code>Id</code> of an element. First the <code>id</code> should never represent any type of information, it is just an identifier. Second your method of extraction is somewhat clunky</p>\n\n<p>You have</p>\n\n<blockquote>\n<pre><code>let x = id.substring(0, id.indexOf(\"/\"));\nlet y = id.substring((id.indexOf(\"/\") + 1), (id.length + 1));\n</code></pre>\n</blockquote>\n\n<p>you could use </p>\n\n<pre><code>let [x, y] = id.split(\"/\");\n// or\nconst [x, y] = id.split(\"/\").map(Number);\n</code></pre>\n\n<h3>Keep out of global scope</h3>\n\n<p>Keep the global scope clean. Put the whole game inside a function (see example where the game is contained within the <code>load</code> event). This makes the code far more portable and safe to insert into other pages. Pages that will contain 3rd Party code.</p>\n\n<h3>Complexity is the enemy</h3>\n\n<p>Your code is in many parts very repetitive and complex (mostly due to inexperience). You often repeat the same logic to find the same state in various parts of the code.</p>\n\n<p>Your data structure is also too complex, structuring it to match the game layout rather than what you need to manage the game state. </p>\n\n<p>Always aim to keep it as simple as possible. Don't store information not needed, don't compute information more than once.</p>\n\n<h2>Warning</h2>\n\n<h3>Always in Strict mode</h3>\n\n<p>You have some undeclared variables in use (variable without <code>var</code>, <code>let</code>, or <code>const</code>). This is very dangerous as undeclared variables are created in global scope and can easily be used in various places without you noticing that they are all the same reference.</p>\n\n<p>To prevent these types of easy to make oversights always run your scripts in strict mode. To set strict mode just add the line <code>\"use strict\";</code> at the top of the JavaScript file.</p>\n\n<h3>Query the DOM</h3>\n\n<p>DOM queries are very slow compared to using a stored or direct reference to the elements.</p>\n\n<p><code>document.getElementById(newId)</code> is a DOM query and you use it all over the place. As this is not a realtime game its not that big of a deal, but it is a bad habit and should be avoided. </p>\n\n<p>Locate and store a reference to all the DOM elements you need once at the start of the code and use those references when you need to do something to an element. see example <code>field.elements</code> object that is used to store elements needed in the game</p>\n\n<h2>User friendly</h2>\n\n<p>You might create the best game ever but with a clunky and hard to use UI nobody will evry want to play it. </p>\n\n<p>Try to not give users options that are invalid. Eg you provide inputs to set the rows and columns, in the function run you then check if the values are &lt;= 1 or > 100 and display an alert. The user should never be able to add these invalid settings. This is a basic UI design rule you should always consider.</p>\n\n<p>Provide as much feedback as you can to let the user know what can and can not be done. Eg I have added mouse pointer only to cells that can be clicked. You can add more and custom pointers to.</p>\n\n<p>DO NOT use alerts. Often they can be deactivated so you can never know if the user has seen them. They are also blocking and if there are problems (repeated calls to alert) you can leave such a bad taste in the user that they will never come back.</p>\n\n<h2>CSS</h2>\n\n<p>Use CSS style rules to define styles and use these styles to modify element styles. See Example. You can access the elements class name via <code>element.className</code> and also <code>element.classList</code> for a higher level interface.</p>\n\n<h2>General style points</h2>\n\n<p>-Use object function shorthand to reduce code noise. eg <code>checkWin: function () {</code> becomes <code>checkWin() {</code></p>\n\n<ul>\n<li><p>Use function declarations eg <code>function run(</code> rather than function expressions <code>const run = () =&gt; {</code> as function declarations can be call from any point in the code while function expressions can only be called after the expression has been executed.</p></li>\n<li><p>Use <code>addEventListener</code> to add event rather than assigning to the <code>onEvent</code> property of the element.</p></li>\n<li>Use <code>const</code> for variables that do not change.</li>\n<li><p>Why are you constantly using <code>parseInt</code> (OMDG <code>parseInt(parseInt(x) + parseInt(i))</code> !!!) You only need to do this if the variable is a string representation of the number and often it is better to use <code>Number(\"1\")</code> to convert to a number than <code>parseInt</code>.</p></li>\n<li><p>`Don't create content using HTML. Use the DOM interface to create elements to add to the pages. It is 100s of times quicker and prevents a whole pile of problems with the page settings.</p></li>\n<li><p>Use strict equality and inequality <code>===</code> and <code>!==</code> rather than truthy equalities <code>==</code> and <code>!=</code>.</p></li>\n<li><p>Avoid single use variables unless they help in readability (eg make a line shorter). </p>\n\n<p>Example of poor use of variables <code>let cols = document.getElementById(\"cols\").value;</code> only used once on the next line. Much better as <code>field.cols = document.getElementById(\"cols\").value;</code></p></li>\n<li><p>DO NOT add JavaScript to the HTML. eg <code>onclick=\"run()\"</code> should be set via <code>addEventListener</code> in the JavaScript code.</p></li>\n</ul>\n\n<h2>Naming</h2>\n\n<p>Your code is full of very bad naming practices.</p>\n\n<ul>\n<li>You use <code>cols</code>, and <code>rows</code> to define row and column counts. Generally we use <code>rows</code> and <code>cols</code> to reference collections or arrays. Use <code>colCount</code> and <code>rowCount</code> to clearly define what the variables represent.</li>\n<li>You call mines <code>mine</code> and <code>bomb</code>, this makes it very difficult to know what the variable name should be. In the example I have changed the names of all bomb references to <code>mine</code>.</li>\n<li>Do not include the variables type in the name eg <code>field.bombArray</code> should be <code>field.bombs</code> the plural hits that the variable is an array or array like.</li>\n<li>You are mixing <code>field</code> and <code>this</code> within the <code>field</code> object. As field is a single instance use <code>field</code> rather than <code>this</code> <code>this</code> is used when you have many instances of an object.</li>\n</ul>\n\n<p>OK that will do it. I have not covered everything by there is a size limit to answers here.</p>\n\n<h2>Rewrite example</h2>\n\n<p>I have completely rewritten the code from the ground up (well almost). Have a look and take what you can from it. </p>\n\n<p>Some points</p>\n\n<ul>\n<li>Mines and Cells are stored in one dimensional array. X and y coords are converted to index to locate neighbors. </li>\n<li>A cell object created by <code>createCell</code> contains all the logic and states of a cell</li>\n<li>Recursive <code>reveal</code> The cell <code>reveal</code> function calls reveal on its neighbors if needed. This automatically and efficiently reveals all the neighbors without a lot of complicated repeated searches.</li>\n<li>CSS rules to reflex cell state eg <code>class=\"gameCell hidden mine marked\"</code> </li>\n<li>One event listener handles left and right clicks. Listeners are removed when not needed. </li>\n<li><code>field.reset</code> starts the game rather than a function independent of <code>field</code></li>\n<li>Some helper function, game constants are stored at the beginning of the code.</li>\n<li>\"Use strict\" at the top to ensure there are no simple typos and forgot it's in the code</li>\n<li>Used getters and setters on the cell object</li>\n<li>Used short circuit style to avoid to much code noise. Eg <code>x &lt; 0 &amp;&amp; neighbours.push(</code> is the same as <code>if (x &lt; 0) { neighbours.push(</code></li>\n<li>Used ternaries to reduce code noise. eg <code>text = mine ? \"X\" : (mineCount &gt; 0 ? mineCount : \"\");</code> is the same as if (mine) { text = \"X\" } else { if (minecount > 0) { text = mineCount } else { text = \"\" } }`</li>\n</ul>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>\"use strict\"; \naddEventListener(\"load\", () =&gt; { // isolates the game from the global scope\n\n // utility functions\n const createElement = (tag, props ={}) =&gt; Object.assign(document.createElement(tag), props);\n const byId = id =&gt; document.getElementById(id);\n \n // constants\n const MINE_CHAR = \"\\ud83d\\udca3\";\n const EXP_CHAR = \"\\ud83d\\udca5\";\n const LOSS = \"You loss!\";\n const WIN = \"You win!\";\n const PLAY_AGAIN = \"Click start?\";\n const DEBUG = false; // set to true to help debug game\n \n // The 0 timeout just waits till all the code below has been executed \n // so that the setup code can hang out at the top \n setTimeout(() =&gt; { \n newGame.addEventListener(\"click\",field.reset);\n field.reset();\n },0);\n \n function createCell(x, y) {\n var mine = false;\n var hidden = true;\n var marked = false;\n const neighbours = [];\n var element, mineCount;\n const API = {\n set element(el) { element = el }, \n get isMine() { return mine },\n get isHidden() { return hidden },\n get isMarked() { return marked },\n updateNeighbours(field) {\n x &gt; 0 &amp;&amp; neighbours.push(field.cells[x - 1 + y * field.colCount]);\n y &gt; 0 &amp;&amp; neighbours.push(field.cells[x + (y - 1) * field.colCount]);\n x &lt; field.colCount - 1 &amp;&amp; neighbours.push(field.cells[x + 1 + y * field.colCount]);\n y &lt; field.rowCount - 1 &amp;&amp; neighbours.push(field.cells[x + (y + 1) * field.colCount]);\n mineCount = neighbours.reduce((count, cell) =&gt; count + (cell.isMine ? 1 : 0), 0);\n if (DEBUG) {\n element.textContent = mine ? MINE_CHAR : (mineCount ? mineCount : \" \" );\n }\n },\n makeMine() {\n if (!mine) {\n mine = true;\n element.classList.add(\"mine\");\n return API;\n }\n },\n show(exploded = false) {\n hidden = false;\n element.classList.remove(\"hidden\");\n if (mine) {\n if (exploded) {\n element.textContent = EXP_CHAR; \n element.classList.remove(\"safe\");\n } else {\n element.textContent = MINE_CHAR;\n element.classList.add(\"safe\");\n }\n } else {\n element.textContent = mineCount &gt; 0 ? mineCount : \"\";\n }\n }, \n toggleMark(field) {\n marked = !marked;\n if (marked) {\n field.marked ++;\n element.classList.add(\"marked\");\n } else {\n field.marked --;\n element.classList.remove(\"marked\");\n }\n },\n reveal() {\n this.show();\n if (!mine &amp;&amp; mineCount === 0) {\n neighbours.forEach(cell =&gt; cell.isHidden &amp;&amp; cell.reveal()); \n }\n }\n };\n return API;\n }\n\n const field = {\n elements: {\n marked: byId(\"marked\"),\n minesLayed: byId(\"minesLayed\"),\n colCount: byId(\"colCount\"),\n rowCount: byId(\"rowCount\"),\n mineCount: byId(\"mineCount\"),\n gameField: byId(\"gameField\"),\n newGameBtn: newGame,\n },\n colCount: 0,\n rowCount: 0,\n maxMines: 10,\n marked: 0,\n mines: [],\n cells: [],\n reset() {\n field.elements.newGameBtn.textContent = \"Restart\";\n field.colCount = Number(field.elements.colCount.value);\n field.rowCount = Number(field.elements.rowCount.value);\n field.maxMines = Number(field.elements.mineCount.value);\n field.mines.length = 0;\n field.cells.length = 0;\n field.marked = 0;\n field.createBoard();\n field.updateDisplay();\n },\n endGame(message){\n field.elements.marked.textContent = message; \n field.elements.minesLayed.textContent = PLAY_AGAIN;\n field.elements.table.removeEventListener(\"click\",field.cellClicked);\n field.elements.table.removeEventListener(\"contextmenu\",field.cellClicked); \n field.elements.newGameBtn.textContent = \"Start\"; \n },\n checkWin() { \n if (field.mines.every(mine =&gt; mine.isMarked)) {\n field.showAllCells();\n field.endGame(WIN);\n }\n },\n createBoard() {\n var x,y;\n field.elements.gameField.innerHTML = \"\";\n const table = field.elements.table = createElement(\"table\",{className: \"field\"});\n for (y = 0; y &lt; field.rowCount; y++) {\n const row = table.insertRow()\n for (x = 0; x &lt; field.colCount; x++) {\n const cell = createCell(x,y);\n field.cells.push(cell);\n cell.element = Object.assign(\n row.insertCell(), {\n className: \"gameCell hidden\", \n game_cell: cell, // Use snake_case when assigning props\n }\n );\n }\n }\n while (field.mines.length &lt; field.maxMines &amp;&amp; field.mines.length &lt; field.cells.length) { \n const mine = field.cells[Math.random() * field.cells.length | 0].makeMine(); \n if (mine) { field.mines.push(mine) }\n }\n field.cells.forEach(cell =&gt; cell.updateNeighbours(field));\n field.elements.gameField.appendChild(table);\n table.addEventListener(\"click\",field.cellClicked);\n table.addEventListener(\"contextmenu\",field.cellClicked); \n },\n updateDisplay() {\n field.elements.marked.textContent = field.marked;\n field.elements.minesLayed.textContent = field.mines.length - this.marked;\n },\n showAllMines(exp = false) { field.mines.forEach(mine =&gt; mine.show(exp)) },\n showAllCells() { field.cells.forEach(cell =&gt; cell.show()) },\n cellClicked(event) {\n if (event.target.game_cell) {\n if (event.type === \"contextmenu\") {\n event.preventDefault();\n event.target.game_cell.toggleMark(field);\n field.updateDisplay();\n field.checkWin(); \n } else {\n event.target.game_cell.reveal();\n if (event.target.game_cell.isMine) {\n field.showAllMines();\n setTimeout(() =&gt; {\n field.showAllMines(true); \n field.endGame(LOSS);\n }, 1000\n );\n }\n }\n }\n },\n };\n\n});</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>html {\n font-family: sans-serif;\n }\n\n .wrapper {\n display: grid;\n grid-template-columns: 200px, 8fr;\n grid-template-areas:\n \"settings content\";\n justify-content: left;\n grid-gap: 20px;\n white-space:nowrap;\n\n }\n\n .settings{\n grid-area: settings;\n position: absolut;\n white-space: nowrap;\n margin-top: 2px;\n }\n input {\n -moz-appearance: textfield;\n text-align: right;\n text-decoration: none;\n border: 0;\n background: black;\n border-bottom: 1px solid;\n color: #ffffff;\n width: 75px;\n}\n\ninput[type=number]::-webkit-inner-spin-button,\ninput[type=number]::-webkit-outer-spin-button {\n opacity: 0;\n}\n\n .content {\n grid-column-start: 2;\n grid-area: content;\n margin-top: 2px;\n }\n\n body {\n background: black;\n }\n\n \n.gameCell {\n height: 24px;\n width: 24px;\n \n text-align: center;\n background: yellow; \n }\n\n.gameCell.hidden {\n background: blue; \n cursor: pointer;\n}\n.gameCell.hidden:hover{\n background: rgba(0, 0, 255, 0.527);\n}\n.gameCell.mine {\n background: red; \n}\n.gameCell.mine.safe {\n background: #0D0; \n}\n.gameCell.hidden.mine {\n background: blue; \n}\n.gameCell.hidden.mine.marked {\n background: red; \n cursor: pointer;\n}\n.gameCell.hidden.marked {\n background: red; \n cursor: pointer;\n}\n\n\n\n p {\n color: white;\n }\n\n button {\n margin-top: 20px;\n\n }\n\n .markedMines {\n color: white;\n margin-top: 25px;\n }\n\n .minesLayed {\n color: white;\n margin-top: 25px;\n }</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;div class=\"wrapper\"&gt;\n\n &lt;div id=\"settings\" class=\"settings\" align=\"right\"&gt;\n &lt;p&gt;columns:&lt;input type=\"number\" id=\"rowCount\" value=\"5\" min=\"2\" max=\"100\"/&gt;&lt;/p&gt;\n &lt;p&gt;rows:&lt;input type=\"number\" id=\"colCount\" value=\"5\" min=\"2\" max=\"100\"/&gt;&lt;/p&gt;\n &lt;p&gt;mines: &lt;input type=\"number\" id=\"mineCount\" value=\"5\" /&gt;&lt;/p&gt;\n &lt;button id=\"newGame\"&gt;Start&lt;/button&gt;\n &lt;div class=\"minesLayed\" id=\"minesLayed\"&gt;&lt;/div&gt;\n &lt;div class=\"markedMines\" id=\"marked\"&gt;&lt;/div&gt;\n &lt;/div&gt;\n &lt;div id=\"gameField\" class=\"content\"&gt;&lt;/div&gt;\n &lt;/div&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<h3>Update</h3>\n\n<p>I have just added some cosmetic changes. Removed the header so that the small game board fits the CodeReview snippet a little better.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-18T13:06:18.160", "Id": "454229", "Score": "0", "body": "thank you so much for the effort, thats exactly what i needed!\nThis is a lot of information, and it will take time to go through this and come up with follow up questions!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-21T13:40:55.927", "Id": "454616", "Score": "0", "body": "Although this is an excellent answer, it's still somewhat opinionated. Not everyone codes this way, and I would certainly advise not to use object literals as classes, and then wrap those in a function, in another function. It's still a bit hard to parse." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-21T14:45:42.030", "Id": "454627", "Score": "0", "body": "@Kokodoko JavaScript only has Objects, classes do not exist. All the major browsers cache functions and use references to the cached functions so there are ZERO memory and performance hits using functions within functions as opposed to defining a prototype or (the flawed) class syntax. This is code review and as such (like your comment) appraisals are subjective and thus unavoidably opinionated. It is my opinion that encapsulation is fundamental in OO design, and in JavaScript this answer's style is the most effective way (using closure) of providing robust encapsulation. No # prefixing" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-21T17:16:12.577", "Id": "454664", "Score": "0", "body": "@SaulMarquez ES6 uses the \"class\" syntax to define objects. There is no type in javascript called \"class\". `typeof something === \"class\"` will NEVER be true. References created from the class syntax are always Objects" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-05T22:33:03.693", "Id": "456485", "Score": "0", "body": "Yes, that is true, ES6 classes are not true classes. But for basic use cases they behave like classes and this is OP's first JS project. I think the useful white lie is better than the confusing truth in this case." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-06T00:32:52.627", "Id": "456491", "Score": "0", "body": "@SaulMarquez \"useful white lie\"???? I must disagree, JavaScript is a dynamically typed language. The OO concept of a `class` is effectively meaningless. I am not going to lie in my reviews" } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-17T19:06:46.820", "Id": "232558", "ParentId": "232434", "Score": "4" } } ]
{ "AcceptedAnswerId": "232558", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-15T09:34:10.223", "Id": "232434", "Score": "9", "Tags": [ "javascript", "beginner", "minesweeper" ], "Title": "Minesweeper Javascript (yes, another one)- JS Beginner, fully functional incl HTML and CSS" }
232434
<p>This is an interview question. Take a list of strings that represent port ranges like these:</p> <pre><code>const systemPorts = '11000-11001, 11100-11101, 12000-12010, 13000'; const customerports = '11000-11003, 11100-11106, 12000-12015, 13000-13003'; </code></pre> <p>And return a merged list of ports in the form of a string:</p> <pre><code>'11100-11106,12000-12015,13000-13003,11000-11003' </code></pre> <p>Please review with an eye on commenting and code density, I feel I may have gone too far.</p> <pre><code>//ranges is a list of objects with a min and max property //range is an object with a min and max property that will be merged in to ranges function mergeRange(ranges, range){ const [min,max] = range.split("-").map(s=&gt;Number(s)); //Does any existing range contain either min or max? const matches = ranges.filter(o=&gt;(o.min &lt;= min &amp;&amp; o.max &gt;= min) || (o.min &lt;= max &amp;&amp; o.max &gt;= max) || (o.min &gt; min &amp;&amp; o.max &lt; max)); //Handle the different cases if(matches.length == 0){ //Nothing matches, just add the range ranges.push({min,max}); }else if(matches.length == 1){ //One match, extend if needed matches[0].min = Math.min(matches[0].min, min); matches[0].max = Math.max(matches[0].max, max); }else{ //More than one match //Remove the matches that are there for(const match of matches){ const index = ranges.indexOf(match); ranges.splice(index, 1); } matches = matches.concat([min,max]); //Add a new range which contains all the matches ranges.push({min: Math.min(...matches.map(match=&gt;match.min)) , max: Math.max(...matches.map(match=&gt;match.max))}); } } //['11000-11001, 11100-11101, 12000-12010, 13000', '11000-11003, 11100-11106, 12000-12015, 13000-13003'] //becomes '11100-11106,12000-12015,13000-13003,11000-11003' function mergePortRanges(portRangesList){ let ranges = []; for(const portRanges of portRangesList){ for(let range of portRanges.split(",").sort().map(s=&gt;s.trim())){ //make a single number a range (13000 -&gt; 13000-13000) range = range.includes('-') ? range : `${range}-${range}`; mergeRange(ranges, range); } } return ranges.map(range =&gt; `${range.min}-${range.max}`).join(","); } const systemPorts = '11000-11001, 11100-11101, 12000-12010, 13000'; const customerports = '11000-11003, 11100-11106, 12000-12015, 13000-13003'; console.log(mergePortRanges([systemPorts, customerports])); console.log(mergePortRanges(['11000-11121, 11100-11101'])); </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-15T13:10:46.543", "Id": "453920", "Score": "1", "body": "\"I feel I may have gone too far\" - I'd say you only have started and there are lots of spaces left that you can condense further." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-15T14:04:26.717", "Id": "453924", "Score": "0", "body": "Could there be intersected ranges like `'11000-11121, 11100-11101, ...`? If so, how it would effect the final result?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-15T14:40:16.257", "Id": "453931", "Score": "0", "body": "Yup, did not test for that case, this now returns `11000-11121`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-15T22:56:14.150", "Id": "453988", "Score": "0", "body": "What about more cases like `'5-10, 4-12, 1-13'` should output `1-13` and `'5-10, 4-12, 13'` should output `4-13`" } ]
[ { "body": "<p>One criticism I will give you is I think you went overboard with the comments. Some of the code will speak for itself if it's well written. Not saying my code is well written, I'm just saying.</p>\n\n<p>Here's what I came up with. I'm afraid it's not much cleaner than your version, if at all. I spent a good amount of time on it too.</p>\n\n<pre><code>function mergePortRanges(input){\n\n //Group all ranges into one array\n let portList = [];\n input.forEach( list =&gt; {\n portList.push(...list.split(',').map( range =&gt; range.trim()));\n });\n\n //Break the ranges into objects with min max integers\n portList = portList.map( range =&gt; {\n range = range.split('-').map( s =&gt; +s );\n if(range.length === 1)\n range.push(range[0]);\n return { min: range[0], max: range[1] };\n });\n\n //Sort by mins\n portList.sort((a,b) =&gt; (a.min &gt; b.min) ? 1 : -1);\n\n //Group ranges starting with same min and grab the highest one.\n let newPortList = [];\n let curRangeMin = 0;\n for(let x = 0; x &lt; portList.length; x++){\n let range = portList[x];\n\n if(curRangeMin === range.min) continue;\n else curRangeMin = range.min;\n\n let group = portList.filter( old =&gt; range.min == old.min); //Get full range\n group.map( (a,b) =&gt; (a.max &gt; b.max) ? 1 : -1 ); //Sort by max\n newPortList.push( group[0] ); //Grab highest in range and push.\n }\n\n return newPortList.map( range =&gt; {\n if(range.min == range.max)\n return range.min;\n else\n return `${range.min}-${range.max}`;\n }).join(',');\n}\n</code></pre>\n\n<p>I still feel like this could be refined quite a bit, but I've already spent so much time on it lol. Maybe I'll try again when I'm smarter.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-15T20:58:29.830", "Id": "453978", "Score": "0", "body": "Yeah... this last for loop won't work on certain inputs. I'm working to refine it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-15T21:48:55.870", "Id": "453979", "Score": "0", "body": "Alright, I think it's looking alright. Based on what I did just now, I feel like you did a good job on yours." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-15T20:48:33.150", "Id": "232466", "ParentId": "232437", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-15T10:43:39.590", "Id": "232437", "Score": "3", "Tags": [ "javascript" ], "Title": "Merge port ranges" }
232437
<p>I'm working on a design for a video buffer in C++ that will be used by many consumers both in the native library space(C++) as well as Java side using JNI. My Idea is the following:</p> <p>Have a buffer manager that will receive frames directly from the hardware and allocate each frame only once on the heap using shared pointer if it is aware of at least one consumer for this frame. When a consumer would like to to receive video frame it will call the bind method and specify the buffer size it wants since not all consumers will process data at the same rate. I think it is better to have a dedicated buffer for each client/consumer. After binding the buffer manager returns a DataBufferStream object that will be used by the consumer to read/fetch video frames. The DataBufferStram class is nothing more than a circular buffer of certain type and size. Using JNI im planning to pass a pointer to the buffer or copy the data to a byte array </p> <p>I would like to get some feedback from people here to see if there is anything I can improve on. is there a better solution that you can recommend </p> <pre><code> class BufferManager { public: std::shared_ptr&lt;DataBufferStream&lt;SHARED_ARRAY&gt;&gt; bind(const unsigned int bufferSize,const int requestorID); void unbind(const int requestorID); std::shared_ptr&lt;BufferManager&gt; getInstance(); private: std::map&lt;int,std::shared_ptr&lt;DataBufferStream&lt;SHARED_ARRAY&gt;&gt;&gt; mDataBufferMap; std::mutex mMutex; }; std::shared_ptr&lt;DataBufferStream&lt;SHARED_ARRAY&gt;&gt; BufferManager::bind(const unsigned int bufferSize,const int requestorID) { std::lock_guard&lt;std::mutex&gt; lockGuard(mMutex); auto it = mDataBufferMap.find(requestorID); if(it == mDataBufferMap.end()){ mDataBufferMap[requestorID] = std::make_shared&lt;DataBufferStream&lt;SHARED_ARRAY&gt;&gt;(bufferSize); } return mDataBufferMap[requestorID]; } void BufferManager::unbind(const int requestorID) { std::lock_guard&lt;std::mutex&gt; lock(mMutex); mDataBufferMap.erase(requestorID); } </code></pre> <p>`</p> <pre><code> #include "../include/boost/circular_buffer.hpp" #include &lt;mutex&gt; #include &lt;array&gt; #include &lt;condition_variable&gt; #include &lt;boost/shared_array.hpp&gt; typedef boost::shared_array&lt;char&gt; SHARED_ARRAY; template &lt;class T&gt; class DataBufferStream { private: boost::circular_buffer&lt;T&gt; mCircularBuffer; std::mutex mMutex; std::condition_variable mConditionalVariable; unsigned int mIndex; public: DataBufferStream(const unsigned int bufferSize); DataBufferStream(DataBufferStream&amp; other); DataBufferStream() = delete; virtual ~DataBufferStream(); void pushData(T data); T fetchData(); T readData(unsigned int duration); T operator[](const unsigned int index); T operator*(); void operator++(); void operator--(); DataBufferStream&lt;T&gt; &amp;operator=(DataBufferStream&lt;T&gt;&amp; other); void clear(); unsigned int size(); }; </code></pre> <p>` #include "DataBuffer.h"</p> <pre><code>template &lt;class T&gt; DataBufferStream&lt;T&gt;::DataBufferStream(const unsigned int bufferSize): mCircularBuffer(bufferSize), mMutex(), mConditionalVariable(), mIndex(0) { } template &lt;class T&gt; T DataBufferStream&lt;T&gt;::fetchData() { std::lock_guard&lt;std::mutex&gt; lock (mMutex); if(mCircularBuffer.size()&gt;0) { auto ptr = mCircularBuffer.front(); mCircularBuffer.pop_front(); return ptr; } return nullptr; } template &lt;class T&gt; void DataBufferStream&lt;T&gt;::pushData(T data) { std::lock_guard&lt;std::mutex&gt; lock (mMutex); mCircularBuffer.push_back(data); mConditionalVariable.notify_all(); } template&lt;class T&gt; T DataBufferStream&lt;T&gt;::operator[](const unsigned int index) { std::lock_guard&lt;std::mutex&gt; lock (mMutex); return mCircularBuffer.size()&gt;index ? mCircularBuffer[index] : nullptr; } template&lt;class T&gt; DataBufferStream&lt;T&gt;::~DataBufferStream() { } template&lt;class T&gt; T DataBufferStream&lt;T&gt;::operator*() { std::lock_guard&lt;std::mutex&gt; lock(mMutex); return mCircularBuffer.size() &gt; mIndex ? mCircularBuffer[mIndex] : nullptr; } template&lt;class T&gt; void DataBufferStream&lt;T&gt;::operator++() { std::lock_guard&lt;std::mutex&gt; lock(mMutex); mIndex = mCircularBuffer.size() &lt; mIndex+1 ? 0 : mIndex++; } template&lt;class T&gt; void DataBufferStream&lt;T&gt;::operator--() { std::lock_guard&lt;std::mutex&gt; lock(mMutex); mIndex = mIndex &gt; 0 ? mIndex-- : 0; } template&lt;class T&gt; void DataBufferStream&lt;T&gt;::clear() { std::lock_guard&lt;std::mutex&gt; lock(mMutex); mCircularBuffer.clear(); mIndex = mCircularBuffer.size(); } template&lt;class T&gt; DataBufferStream&lt;T&gt;::DataBufferStream(DataBufferStream &amp;other): mMutex(), mConditionalVariable(){ std::lock_guard&lt;std::mutex&gt; lock(other.mMutex); this-&gt;mCircularBuffer = other.mCircularBuffer; this-&gt;mIndex = other.mIndex; } template&lt;class T&gt; DataBufferStream&lt;T&gt; &amp;DataBufferStream&lt;T&gt;::operator=(DataBufferStream&lt;T&gt; &amp;other) { if(this!=&amp;other){ std::unique_lock&lt;std::mutex&gt; myLock (mMutex,std::defer_lock); std::unique_lock&lt;std::mutex&gt; otherLock(other.mMutex,std::defer_lock); std::lock(myLock,otherLock); mCircularBuffer = other.mCircularBuffer; mIndex = other.mIndex; } return *this; } template&lt;class T&gt; unsigned int DataBufferStream&lt;T&gt;::size() { std::lock_guard&lt;std::mutex&gt; lock(mMutex); return mCircularBuffer.size(); } template&lt;class T&gt; T DataBufferStream&lt;T&gt;::readData(unsigned int duration) { auto data = fetchData(); std::unique_lock&lt;std::mutex&gt; lock(mMutex); if((data == nullptr) &amp;&amp; (mConditionalVariable.wait_for(lock,std::chrono::milliseconds(duration)) == std::cv_status::no_timeout)){ if(mCircularBuffer.size()&gt;0) { auto data = mCircularBuffer.front(); mCircularBuffer.pop_front(); } } return data; } template class DataBufferStream&lt;SHARED_ARRAY&gt;; </code></pre>
[]
[ { "body": "<p>If your system is going to be impacted by high rate operations, looks like, I recommend you to preallocate the memory on boot time of the application, so during the execution of your program you dont do any allocations, for example:</p>\n\n<pre><code>auto it = mDataBufferMap.find(requestorID);\nif(it == mDataBufferMap.end()){\n mDataBufferMap[requestorID] = std::make_shared&lt;DataBufferStream&lt;SHARED_ARRAY&gt;&gt;(bufferSize);\n}\n</code></pre>\n\n<p>will be like</p>\n\n<pre><code>auto it = mDataBufferMap.find(requestorID);\nif(it == mDataBufferMap.end()){\n mDataBufferMap[requestorID] = getDataBufferStreamFromPool();\n}\n</code></pre>\n\n<p>And on the erase release the block from the map but without free the memory. Hope it helps</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-15T20:37:16.740", "Id": "453976", "Score": "0", "body": "() thanks for the feedback" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-15T19:28:59.037", "Id": "232460", "ParentId": "232444", "Score": "2" } } ]
{ "AcceptedAnswerId": "232460", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-15T13:59:10.537", "Id": "232444", "Score": "6", "Tags": [ "c++", "android", "stream", "video", "jni" ], "Title": "Design a native video buffer in C++ to be shown on android application and shared with other modules in native space and Java" }
232444
<p>My issue that I was trying to solve was constructing a vector where the values were mirrored around the central element. The problem is here: <a href="https://stackoverflow.com/questions/58876916/construct-mirror-vector-around-the-centre-element-in-c">https://stackoverflow.com/questions/58876916/construct-mirror-vector-around-the-centre-element-in-c</a></p> <p>I solved the issue using the method in the accepted answer and am sharing my working code to hear any review suggestions or edit to make my code more efficient. </p> <p>My code solution:</p> <p><strong>filters.cpp</strong></p> <pre><code>#include &lt;iostream&gt; #include "ErrorCode.h" #include "variables.h" #include &lt;cmath&gt; #include &lt;fstream&gt; #include &lt;vector&gt; #include &lt;algorithm&gt; #include &lt;iterator&gt; #include &lt;complex&gt; using namespace std; /* * Functions for calculating the coefficients of the selected filter. * Options: Low Pass, High Pass, Band Pass, Band Reject. * * (To do: put functions in separate file, use of headers and classes - constructors?) * */ vector &lt;double&gt; lowPass (vector&lt;double&gt; hL, double fcL, int M, int N, const double PI) { std::vector&lt;int&gt; mArr; mArr.resize(N); int count; for(count = 0; count &lt; N; count++) mArr[count] = count - M; int n; for(n = 0; n &lt; M; n++) { hL[n] = (sin((fcL*mArr[n])-M))/((mArr[n]-M)*PI); } hL[M] = fcL/PI; for(n = 0; n &lt; M; n++) { hL[N-n-1] = hL[n]; } return hL; } vector &lt;double&gt; highPass (vector&lt;double&gt; hH, double fcH, int M, int N, const double PI) { std::vector&lt;int&gt; mArr; mArr.resize(N); int count; for(count = 0; count &lt; N; count++) mArr[count] = count - M; int n; for(n = 0; n &lt; M; n++) { hH[n] = -((sin((fcH*mArr[n])-M))/(mArr[n]-(M*PI))); } hH[M] = 1+(fcH/PI); for(n = 0; n &lt; M; n++) { hH[N-n-1] = hH[n]; } return hH; } vector&lt;double&gt; bandPass (vector&lt;double&gt; bp, vector&lt;double&gt; hL, vector&lt;double&gt; hH, double fcL, double fcH, int M, const double PI) { for(int n = 0; n &lt; N; n++) { bp[n] = -(hH[n]) - hL[n]; bp[M] = (fcH/PI) - (fcL/PI); } return bp; } vector&lt;double&gt; bandReject (vector&lt;double&gt; br, vector&lt;double&gt; hL, vector&lt;double&gt; hH, double fcL, double fcH, int M, const double PI) { for(int n = 0; n &lt; N; n++) { br[n] = hL[n] - (-(hH[n])); br[M] = 1 + (fcL/PI) - (fcH/PI); } return br; } /* * Functions for calculating the coefficients of the selected window filter. * Options: Rectangular, Hanning, Hamming, Blackman Harris * * (To do: put functions in separate file, use of headers and classes - constructors?) * */ vector&lt;double&gt; hanning(vector&lt;double&gt; hann, int M, int N, const double PI) { std::vector&lt;int&gt; mArr; mArr.resize(N); int count; for(count = 0; count &lt; N; count++) mArr[count] = count - M; for(int n = 0; n &lt; N; n++) { hann[n] = 0.5+(0.5*(cos((mArr[n]*PI)/M))); } return hann; } vector&lt;double&gt; hamming(vector&lt;double&gt; hamm, int N, const double PI) { for(int n = 0; n &lt; N; n++) { hamm[n] = 0.54 - (0.46*(cos(n*2*PI/N))); } return hamm; } vector&lt;double&gt; blackman (vector&lt;double&gt; bmhr, int N, const double PI) { for(int n = 0; n &lt; N; n++) { bmhr[n] = 0.42 - (0.5*(cos(2*PI*n/N))) + (0.08*cos(4*PI*n/N)); } return bmhr; } /* * Functions to calculate cut-off frequency for low and high */ double calcFcL (double f_cL, double f_s) { double fcL = f_cL/f_s; return fcL; } double calcFcH (double f_cH, double f_s) { double fcH = f_cH/f_s; return fcH; } /* * Check if cut off frequencies are lower than the sampling frequency * Check if filter length is odd */ ErrorCode checkFreq(double, double, double); ErrorCode checkN(int); ErrorCode checkNs(int); ErrorCode checkF1(double); ErrorCode checkF2(double); ErrorCode checkA1(double); ErrorCode checkA2(double); /* * User input for selecting filter type * Options: Low Pass, High Pass, Band Pass, Band Reject * Passes filter output of function by value * Output coefficients to a csv file */ vector&lt;double&gt; filterType(vector&lt;double&gt; filter, double fcL, double fcH, int M, int N, const double PI) { int choice; cout &lt;&lt;"Please select filter type: \n"; cout &lt;&lt; "1: Low Pass\n" "2: High Pass\n" "3: Band Pass\n" "4: Band Reject\n"; cout &lt;&lt; "Enter your selection (1, 2, 3 or 4): "; cin &gt;&gt; choice; switch(choice) { case 1: { vector&lt;double&gt; hL; hL.resize(N); hL = lowPass(hL, fcL, M, N, PI); ofstream lpfile ("lowpass.csv"); if (lpfile.is_open()) { for(int count = 0; count &lt; N; count++){ lpfile &lt;&lt; hL[count] &lt;&lt; "," ; } lpfile.close(); } else cout &lt;&lt; "Unable to open file"; filter = hL; break; } case 2: { vector&lt;double&gt; hH; hH.resize(N); hH = highPass(hH, fcH, M, N, PI); ofstream hpfile ("highpass.csv"); if (hpfile.is_open()) { for(int count = 0; count &lt; N; count++){ hpfile &lt;&lt; hH[count] &lt;&lt; "," ; } hpfile.close(); } else cout &lt;&lt; "Unable to open file"; filter = hH; break; } case 3: { vector&lt;double&gt; hL; hL.resize(N); vector&lt;double&gt; hH; hH.resize(N); vector&lt;double&gt; bp; bp.resize(N); hL = lowPass(hL, fcL, M, N, PI); hH = highPass(hH, fcH, M, N, PI); bp = bandPass(bp, hL, hH, fcL, fcH, M, PI); ofstream bpfile ("bandpass.csv"); if (bpfile.is_open()) { for(int count = 0; count &lt; N; count++){ bpfile &lt;&lt; bp[count] &lt;&lt; "," ; } bpfile.close(); } else cout &lt;&lt; "Unable to open file"; filter = bp; break; } case 4: { vector&lt;double&gt; hL; hL.resize(N); vector&lt;double&gt; hH; hH.resize(N); vector&lt;double&gt; br; br.resize(N); hL = lowPass(hL, fcL, M, N, PI); hH = highPass(hH, fcH, M, N, PI); br = bandReject(br, hL, hH, fcL, fcH, M, PI); ofstream brfile ("bandreject.csv"); if (brfile.is_open()) { for(int count = 0; count &lt; N; count++){ brfile &lt;&lt; br[count] &lt;&lt; "," ; } brfile.close(); } else cout &lt;&lt; "Unable to open file"; filter = br; break; } default: break; } return filter; } /* * User input for selecting window type * Options: Rectangular, Hanning, Hamming, Blackman Harris * Passes window output of function by value * Output coefficients to a csv file */ vector&lt;double&gt; windowType(vector&lt;double&gt; window, int M, int N, const double PI) { int choice; cout &lt;&lt;"Please select Window type: \n"; cout &lt;&lt; "1: Rectangular\n" "2: Hanning\n" "3: Hamming\n" "4: Blackman Harris\n"; cout &lt;&lt; "Enter your selection (1, 2, 3 or 4): "; cin &gt;&gt; choice; switch(choice) { case 1: { vector&lt;double&gt; rect; rect.assign (N, 1); ofstream rectfile ("rectangular.csv"); if (rectfile.is_open()) { for(int count = 0; count &lt; N; count++){ rectfile &lt;&lt; rect[count] &lt;&lt; "," ; } rectfile.close(); } else cout &lt;&lt; "Unable to open file"; window = rect; break; } case 2: { vector&lt;double&gt; hann = {}; hann.resize(N); hann = hanning(hann, M, N, PI); ofstream hannfile ("hanning.csv"); if (hannfile.is_open()) { for(int count = 0; count &lt; N; count++){ hannfile &lt;&lt; hann[count] &lt;&lt; "," ; } hannfile.close(); } else cout &lt;&lt; "Unable to open file"; window = hann; break; } case 3: { vector&lt;double&gt; hamm = {}; hamm.resize(N); hamm = hamming(hamm, N, PI); ofstream hammfile ("hamming.csv"); if (hammfile.is_open()) { for(int count = 0; count &lt; N; count++){ hammfile &lt;&lt; hamm[count] &lt;&lt; "," ; } hammfile.close(); } else cout &lt;&lt; "Unable to open file"; window = hamm; break; } case 4: { vector&lt;double&gt; bmhr = {}; bmhr.resize(N); bmhr = blackman(bmhr, N, PI); ofstream bmhrfile ("blackman.csv"); if (bmhrfile.is_open()) { for(int count = 0; count &lt; N; count++){ bmhrfile &lt;&lt; bmhr[count] &lt;&lt; "," ; } bmhrfile.close(); } else cout &lt;&lt; "Unable to open file"; window = bmhr; break; } } return window; } /* * Combine window filter with filter to generate FIR coefficients */ vector&lt;double&gt; finiteIR(vector&lt;double&gt; fir, vector&lt;double&gt; filter, vector&lt;double&gt; window, int N) { for(int n = 0; n &lt; N; n++) { fir[n] = filter[n]*window[n]; } ofstream firfile ("FIR.csv"); if (firfile.is_open()) { for(int count = 0; count &lt; N; count++){ firfile &lt;&lt; fir[count] &lt;&lt; "," ; } firfile.close(); } else cout &lt;&lt; "Unable to open file"; return fir; } vector&lt;complex&lt;double&gt; &gt; genSignal(vector&lt;complex&lt;double&gt; &gt; signal, double f_s, int N_s, double f1, double f2, double a1, double a2, const double PI) { complex&lt;double&gt; i = -1; i = sqrt(i); double tP = 1/f_s; vector&lt;double&gt; t; t.resize(N_s); for(int n = 0; n &lt; N_s - 1; n++) { t[n] = n*tP; } vector&lt;complex&lt;double&gt; &gt; x = {}; double x1Real; double x1Imag; double x2Real; double x2Imag; for (int n = 0; n &lt; N_s; n++) { x1Real = real(a1*exp(i*(2*PI*f1*t[n]))); x1Imag = imag(a1*exp(i*(2*PI*f1*t[n]))); x2Real = real(a2*exp(i*(2*PI*f2*t[n]))); x2Imag = imag(a2*exp(i*(2*PI*f2*t[n]))); double xreal = x1Real + x2Real; double ximag = x1Imag + x2Imag; complex&lt;double&gt; iNum(xreal, ximag); x.push_back(iNum); } ofstream sigfile ("signal.csv"); if (sigfile.is_open()) { for(int count = 0; count &lt; N_s; count++) { sigfile &lt;&lt; real(x[count]) &lt;&lt; "," ; sigfile &lt;&lt; imag(x[count]) &lt;&lt; ",\n" ; } sigfile.close(); } else cout &lt;&lt; "Unable to open file"; signal = x; return signal; } // ---------------------------------------------------------------------------------------------------------------------------------- int main() { double f_cL; double f_cH; cout &lt;&lt; "Enter Low Cut-Off frequency (Hz) [Set to 0 for the highpass filter] : "; cin &gt;&gt; f_cL; cout &lt;&lt; "Enter High Cut-Off frequency (Hz) [Set to 0 for the lowpass filter] : "; cin &gt;&gt; f_cH; // ------------------------------------------------------------------------------ cout &lt;&lt; "Enter sampling frequency (Hz): "; cin &gt;&gt; f_s; if (checkFreq(f_s, f_cL, f_cH) == ErrorCode::FAIL) { std::cout &lt;&lt; "You entered a frequency less than cut-off!\n"; cout &lt;&lt; "Fail"; return 0; } // ------------------------------------------------------------------------------ cout &lt;&lt; "Enter Order of the filter (filter length): "; cin &gt;&gt; N; if (checkN(N) == ErrorCode::FAIL) { cout &lt;&lt; "You entered an invalid number!\n"; cout &lt;&lt; "Fail"; return 0; } // ------------------------------------------------------------------------------ double fcL; double fcH; fcL = calcFcL(f_cL, f_s); cout &lt;&lt; "FcL is : " &lt;&lt; fcL &lt;&lt; endl; fcH = calcFcH(f_cH, f_s); cout &lt;&lt; "FcH is: " &lt;&lt; fcH &lt;&lt; endl; // ------------------------------------------------------------------------------ int M = (N-1)/2; vector&lt;double&gt; filter; filter.resize(N); filter = filterType(filter, fcL, fcH, M, N, PI); vector&lt;double&gt; window; window.resize(N); window = windowType(window, M, N, PI); vector&lt;double&gt; fir; fir.resize(N); fir = finiteIR(fir, filter, window, N); // ------------------------------------------------------------------------------ cout &lt;&lt; "\n\n" &lt;&lt; "Generate Signal...\n"; cout &lt;&lt; "Enter signal sample length: "; cin &gt;&gt; N_s; if (checkNs(N_s) == ErrorCode::FAIL) { cout &lt;&lt; "You entered an invalid number!\n"; cout &lt;&lt; "Fail"; return 0; } cout &lt;&lt; "Enter frequency 1 (Hz): "; cin &gt;&gt; f1; if (checkF1(f1) == ErrorCode::FAIL) { cout &lt;&lt; "You entered an invalid frequency!\n"; cout &lt;&lt; "Fail"; return 0; } cout &lt;&lt; "Enter frequency 2 (Hz): "; cin &gt;&gt; f2; if (checkF2(f2) == ErrorCode::FAIL) { cout &lt;&lt; "You entered an invalid frequency!\n"; cout &lt;&lt; "Fail"; return 0; } cout &lt;&lt; "Enter Amplitude 1: "; cin &gt;&gt; a1; if (checkA1(a1) == ErrorCode::FAIL) { cout &lt;&lt; "You entered an invalid frequency!\n"; cout &lt;&lt; "Fail"; return 0; } cout &lt;&lt; "Enter Amplitude 2 (Hz): "; cin &gt;&gt; a2; if (checkA2(a2) == ErrorCode::FAIL) { cout &lt;&lt; "You entered an invalid frequency!\n"; cout &lt;&lt; "Fail"; return 0; } vector&lt;complex&lt;double&gt; &gt; signal; signal = genSignal(signal, f_s, N_s, f1, f2, a1, a2, PI); return 0; } </code></pre> <p><strong>error.cpp</strong></p> <pre><code>#include &lt;iostream&gt; #include "ErrorCode.h" ErrorCode checkFreq(double value, double value2, double value3) { // if value is less than cut-off if (value &lt; value2 || value &lt; value3) // early return an error code return ErrorCode::FAIL; // Success return ErrorCode::SUCCESS; } ErrorCode checkN(int value) { // if value is even if(value % 2 == 0 || value &lt; 0) // early return an error code return ErrorCode::FAIL; // Success return ErrorCode::SUCCESS; } ErrorCode checkNs(int value) { // if value is negative if(value &lt; 0) // early return an error code return ErrorCode::FAIL; // Success return ErrorCode::SUCCESS; } ErrorCode checkF1(double value) { // if value is negative if(value &lt; 0) // early return an error code return ErrorCode::FAIL; // Success return ErrorCode::SUCCESS; } ErrorCode checkF2(double value) { // if value is negative if(value &lt; 0) // early return an error code return ErrorCode::FAIL; // Success return ErrorCode::SUCCESS; } ErrorCode checkA1(double value) { // if value is negative if(value &lt; 0) // early return an error code return ErrorCode::FAIL; // Success return ErrorCode::SUCCESS; } ErrorCode checkA2(double value) { // if value is negative if(value &lt; 0) // early return an error code return ErrorCode::FAIL; // Success return ErrorCode::SUCCESS; } </code></pre> <p><strong>ErrorCode.h</strong></p> <pre><code>#ifndef ERRORCODE_H_INCLUDED #define ERRORCODE_H_INCLUDED enum class ErrorCode { SUCCESS = 0, FAIL = -1 }; #endif // ERRORCODE_H_INCLUDED </code></pre> <p><strong>variables.h</strong></p> <pre><code>#ifndef VARIABLES_H_INCLUDED #define VARIABLES_H_INCLUDED double f_c = 0.0, f_s = 0.0, fc = 0.0, w_c = 0.0; double N_s = 0.0, f1 = 0.0, f2 = 0.0, a1 = 0.0, a2 = 0.0; int N = 0; const double PI = 3.141592653589793238463; #endif // VARIABLES_H_INCLUDED </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-15T16:28:44.340", "Id": "453944", "Score": "0", "body": "Welcome to code review, where we review working code to provide suggestions on how to improve the code, unfortunately this code doesn't seem to be in a function or a class, which makes the code incomplete. Could you please supply at least the entire function, and possibly the class or entire program?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-15T16:47:12.847", "Id": "453947", "Score": "1", "body": "I have edited to include my full program. Apologies there are little comments in the code at the moment, I'm working on that and will edit in due course. This is a program to produce impulse response coefficients for using in Low and High Pass filters for signal processing." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-20T14:31:27.650", "Id": "454515", "Score": "0", "body": "This won't compile as presented. lowPass has a different signature from its use in filter type, checkFreq and checkN are missing from ErrorCode.h and filterType in main.c doesn't make sense" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-20T18:30:37.563", "Id": "454543", "Score": "0", "body": "Did you test this? It looks like `lowPass` takes no arguments while you do pass those to it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-20T20:17:56.730", "Id": "454555", "Score": "0", "body": "Please [edit] the actual working code into the post; code with compile errors cannot be reviewed." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-21T09:22:29.573", "Id": "454580", "Score": "0", "body": "edits have now been made and the code is now updated, including comments." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-15T15:01:04.167", "Id": "232446", "Score": "3", "Tags": [ "c++", "vectors" ], "Title": "Program to output Low and High pass filter impulse response coefficients for signal processing" }
232446
<p>In my endeavor to learn Angular, I've created a flashcard site with an F#/Mongo backend. As I'm new to Angular, I'm going to post everything; any and all feedback is welcome.</p> <p>First, some pictures of it in action:</p> <p>This is the home page. The dropdown on the left (or top) allows you to filter the displayed decks by all categories. The settings gear brings you to the edit page, and the name is a link to the viewer component. <img src="https://i.stack.imgur.com/3QZFF.png" alt="home page"></p> <p>This is the deck-viewer component. Hovering on the card makes it flip over. <img src="https://i.stack.imgur.com/9LiXL.png" alt="viewing a card in a deck"></p> <p>This is the create/edit component. <img src="https://i.stack.imgur.com/DIY0g.png" alt="creating or editing a deck"></p> <p>Next, my file structure:</p> <pre class="lang-none prettyprint-override"><code>- Flashcard.fsproj - /ClientApp - index.html - styles.scss - /src - /app - app-routing.module.ts - app.component.ts - app.component.html - app.module.ts - /create - create.component.ts - create.component.html - create.component.scss - create.module.ts - tag-dialog.component.ts - tag-dialog.component.html - /deck-finder - deck-finder.component.ts - deck-finder.component.html - deck-finder.component.scss - /deck-viewer - deck-viewer.component.ts - deck-viewer.component.html - deck-viewer.component.scss - deck-viewer.module.ts - /home - home.component.ts - home.component.html - home.component.scss - home.module.ts - /shared - /services - flashcardDeck.service.ts - /models - flashcard.ts - flashcardDeck.ts - /Controllers - FlashcardDeckController.cs </code></pre> <p>Finally, the code. In the interest of brevity, I've left out any unchanged files, such as <code>app.component.ts</code>. This is built with Angular 8, so don't worry about recommending any newly-introduced features.</p> <p><strong>styles.scss:</strong></p> <pre><code>/* You can add global styles to this file, and also import other style files */ html, body { height: 100%; } body { margin: 0; font-family: Roboto, "Helvetica Neue", sans-serif; } @import '~@angular/material/theming'; // Plus imports for other components in your app. // Include the common styles for Angular Material. We include this here so that you only // have to load a single css file for Angular Material in your app. // Be sure that you only ever include this mixin once! @include mat-core(); // Define the palettes for your theme using the Material Design palettes available in palette.scss // (imported above). For each palette, you can optionally specify a default, lighter, and darker // hue. Available color palettes: https://material.io/design/color/ $fcd-primary: mat-palette($mat-teal); $fcd-accent: mat-palette($mat-brown, A200, A100, A400); // The warn palette is optional (defaults to red). $fcd-warn: mat-palette($mat-red); // Create the theme object (a Sass map containing all of the palettes). $fcd-theme: mat-light-theme($fcd-primary, $fcd-accent, $fcd-warn); // Include theme styles for core and each component used in your app. // Alternatively, you can import and @include the theme mixins for each component // that you are using. @include angular-material-theme($fcd-theme); </code></pre> <p><strong>app-routing.module.ts:</strong></p> <pre><code>import { NgModule } from '@angular/core'; import { Routes, RouterModule, PreloadAllModules } from '@angular/router'; const routes: Routes = [ { path: 'create', loadChildren: () =&gt; import('./create/create.module').then(m =&gt; m.CreateModule) }, { path: 'edit/deck/:id', loadChildren: () =&gt; import('./create/create.module').then(m =&gt; m.CreateModule) }, { path: 'deck/:id', loadChildren: () =&gt; import('./deck-viewer/deck-viewer.module').then(m =&gt; m.DeckViewerModule) }, { path: '**', loadChildren: () =&gt; import('./home/home.module').then(m =&gt; m.HomeModule) }, ]; @NgModule({ imports: [RouterModule.forRoot(routes, { preloadingStrategy: PreloadAllModules })], exports: [RouterModule] }) export class AppRoutingModule { } </code></pre> <p><strong>app.module.ts:</strong></p> <pre><code>import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { MatToolbarModule } from '@angular/material/toolbar'; import { MatButtonModule } from '@angular/material/button'; import { MatIconModule } from '@angular/material/icon'; import { FlexLayoutModule } from '@angular/flex-layout'; import { AppRoutingModule } from './app-routing.module'; import { AppComponent } from './app.component'; import { NoopAnimationsModule } from '@angular/platform-browser/animations'; @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, MatButtonModule, MatIconModule, MatToolbarModule, AppRoutingModule, NoopAnimationsModule, FlexLayoutModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { } </code></pre> <p><strong>app.component.html:</strong></p> <pre><code>&lt;div fxLayout="row"&gt; &lt;div fxFlex="15%"&gt;&lt;/div&gt; &lt;div fxFlex&gt; &lt;mat-toolbar&gt; &lt;button mat-button [routerLink]="['']"&gt;Flashcard&lt;/button&gt; &lt;button mat-button [routerLink]="['/create']"&gt;Create&lt;/button&gt; &lt;/mat-toolbar&gt; &lt;router-outlet&gt;&lt;/router-outlet&gt; &lt;/div&gt; &lt;div fxFlex="15%"&gt;&lt;/div&gt; &lt;/div&gt; </code></pre> <p><strong>create.module.ts:</strong></p> <pre><code>import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { CreateComponent } from './create.component'; import { TagDialog } from "./tag-dialog.component"; import { RouterModule } from '@angular/router'; import { MatButtonToggleModule } from '@angular/material/button-toggle'; import { MatButtonModule } from '@angular/material/button'; import { MatIconModule } from '@angular/material/icon'; import { MatCardModule } from '@angular/material/card'; import { MatInputModule } from '@angular/material/input'; import { MatSelectModule } from '@angular/material/select'; import { MatDialogModule, MatDialog } from '@angular/material/dialog'; import { FlexLayoutModule } from '@angular/flex-layout'; import { FlashcardDeckService } from '../shared/services/flashcardDeck.service'; import { HttpClientModule } from '@angular/common/http'; import { ReactiveFormsModule } from '@angular/forms' import { CKEditorModule } from '@ckeditor/ckeditor5-angular'; @NgModule({ declarations: [CreateComponent, TagDialog], imports: [ CommonModule, MatButtonToggleModule, MatButtonModule, MatIconModule, MatCardModule, MatInputModule, MatSelectModule, MatDialogModule, FlexLayoutModule, HttpClientModule, ReactiveFormsModule, CKEditorModule, RouterModule.forChild([ { path: '', component: CreateComponent } ]) ], providers: [FlashcardDeckService, MatDialog], entryComponents: [TagDialog] }) export class CreateModule { } </code></pre> <p><strong>create.component.ts:</strong></p> <pre><code>import { Component, OnInit, ViewEncapsulation } from '@angular/core'; import { FlashcardDeckService } from '../shared/services/flashcardDeck.service'; import { includes, trim } from 'lodash'; import { MatDialog } from '@angular/material/dialog'; import { ActivatedRoute } from '@angular/router'; import { FormGroup, FormBuilder, FormArray } from '@angular/forms'; import * as ClassicEditor from '@ckeditor/ckeditor5-build-classic'; import { TagDialog } from './tag-dialog.component'; @Component({ selector: 'fcd-create', templateUrl: './create.component.html', styleUrls: ['./create.component.scss'], encapsulation: ViewEncapsulation.None }) export class CreateComponent implements OnInit { public Editor = ClassicEditor; public allTags: string[] = []; public selectedCardId: number = 0; public form: FormGroup = this.fb.group({ id: 0, title: '', cards: this.fb.array([]), tags: this.fb.control([]) }); public get cardControls() { return this.form.get('cards') as FormArray; } public addTagDialog(): void { const dialogRef = this.dialog.open(TagDialog); dialogRef.afterClosed().subscribe(tag =&gt; { let sanitizedTag = trim(tag); if (sanitizedTag !== undefined &amp;&amp; sanitizedTag !== '' &amp;&amp; !includes(this.allTags, sanitizedTag)) { this.allTags.push(sanitizedTag); } }); } constructor(private readonly fb: FormBuilder, private readonly flashcardDeckService: FlashcardDeckService, private readonly dialog: MatDialog, private readonly route: ActivatedRoute) { } public setSelectedCard(ev: any) { this.selectedCardId = parseInt(ev.value); } public addCard() { let cards = this.form.get('cards') as FormArray; cards.push(this.fb.group({ id: 0, label: '(New Card)', front: '', back: '' })); this.selectedCardId = cards.length - 1; } public deleteCard() { let cards = this.form.get('cards') as FormArray; cards.removeAt(this.selectedCardId); if (cards.length === 0) { this.selectedCardId = 0; } else { this.selectedCardId = this.selectedCardId === 0 ? 0 : this.selectedCardId - 1; } } public saveDeck() { this.flashcardDeckService.save(this.form.value).subscribe(data =&gt; { this.form = this.fb.group({ id: data.id, title: data.title, cards: this.fb.array(data.cards.map(card =&gt; this.fb.group({ id: card.id, label: card.label, front: card.front, back: card.back }))), tags: this.fb.control(data.tags) }); this.allTags = data.tags; }); } ngOnInit() { if (!this.route.snapshot.paramMap.has('id')) { let deck = this.flashcardDeckService.getNew(); this.form = this.fb.group({ id: deck.id, title: deck.title, cards: this.fb.array(deck.cards.map(card =&gt; this.fb.group({ id: card.id, label: card.label, front: card.front, back: card.back }))), tags: this.fb.control(deck.tags) }); } else { this.flashcardDeckService .get(parseInt(this.route.snapshot.paramMap.get('id'))) .subscribe(data =&gt; { this.form = this.fb.group({ id: data.id, title: data.title, cards: this.fb.array(data.cards.map(card =&gt; this.fb.group({ id: card.id, label: card.label, front: card.front, back: card.back }))), tags: this.fb.control(data.tags) }); this.allTags = data.tags; this.selectedCardId = 0; }); } } } </code></pre> <p><strong>create.component.html:</strong></p> <pre><code>&lt;section&gt; &lt;form [formGroup]="form" (ngSubmit)="saveDeck()"&gt; &lt;mat-card&gt; &lt;mat-card-content class="card-container"&gt; &lt;mat-form-field&gt; &lt;input matInput placeholder="Deck Title" formControlName="title" /&gt; &lt;/mat-form-field&gt; &lt;div fxLayout="row" fxLayoutGap="20px"&gt; &lt;div fxFlex&gt; &lt;mat-form-field&gt; &lt;mat-label&gt;Tags&lt;/mat-label&gt; &lt;mat-select multiple [value]="allTags" formControlName="tags"&gt; &lt;mat-option *ngFor="let tag of allTags" value="{{tag}}"&gt;{{tag}}&lt;/mat-option&gt; &lt;/mat-select&gt; &lt;/mat-form-field&gt; &lt;/div&gt; &lt;div fxFlex="130px"&gt; &lt;button id="add-tag" mat-raised-button color="primary" (click)="addTagDialog()" type="button"&gt; &lt;mat-icon&gt;label&lt;/mat-icon&gt; Create Tag &lt;/button&gt; &lt;/div&gt; &lt;/div&gt; &lt;div fxLayout="row" fxLayout.sm="column" fxLayout.lt-sm="column" fxLayoutGap="20px" fxLayoutGap.sm="0" fxLayoutGap.lt-sm="0"&gt; &lt;div fxFlex="250px" fxHide fxShow.gt-sm&gt; &lt;mat-card class="flashcard-list"&gt; &lt;mat-card-content&gt; &lt;div fxLayout="column"&gt; &lt;div fxFlex&gt; &lt;mat-button-toggle-group vertical [value]="selectedCardId" (change)="setSelectedCard($event)"&gt; &lt;mat-button-toggle *ngFor="let card of form.get('cards').value; index as i" [value]="i" [checked]="i === selectedCardId"&gt; {{card.label}} &lt;/mat-button-toggle&gt; &lt;/mat-button-toggle-group&gt; &lt;/div&gt; &lt;div fxFlex="36px"&gt; &lt;button mat-raised-button color="primary" id="add-card" (click)="addCard()" type="button"&gt; &lt;mat-icon&gt;add&lt;/mat-icon&gt; Create Card &lt;/button&gt; &lt;/div&gt; &lt;/div&gt; &lt;/mat-card-content&gt; &lt;/mat-card&gt; &lt;/div&gt; &lt;div fxFlex fxHide fxShow.sm fxShow.lt-sm&gt; &lt;div fxLayout="row" class="card-select-selector"&gt; &lt;div fxFlex="25px" class="menu-icon"&gt; &lt;mat-icon&gt;menu&lt;/mat-icon&gt; &lt;/div&gt; &lt;div fxFlex&gt; &lt;mat-form-field&gt; &lt;mat-label&gt;Cards&lt;/mat-label&gt; &lt;mat-select [value]="selectedCardId" (selectionChange)="setSelectedCard($event)"&gt; &lt;mat-option *ngFor="let card of form.get('cards').value; index as i" [value]="i"&gt;{{card.label}}&lt;/mat-option&gt; &lt;/mat-select&gt; &lt;/mat-form-field&gt; &lt;/div&gt; &lt;div fxFlex="130px" class="create-card-button"&gt; &lt;button mat-raised-button color="primary" (click)="addCard()" type="button"&gt; &lt;mat-icon&gt;add&lt;/mat-icon&gt; Create Card &lt;/button&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div fxFlex formArrayName="cards"&gt; &lt;div *ngFor="let card of cardControls.controls; index as i" [formGroupName]="i" [ngSwitch]="selectedCardId"&gt; &lt;mat-card *ngSwitchCase="i"&gt; &lt;mat-card-title&gt;{{form.get('title').value}}&lt;/mat-card-title&gt; &lt;mat-card-content&gt; &lt;mat-form-field&gt; &lt;input matInput placeholder="Card Label" formControlName="label" /&gt; &lt;/mat-form-field&gt; &lt;label for="card-front"&gt;Card Front&lt;/label&gt; &lt;ckeditor [editor]="Editor" formControlName="front"&gt;&lt;/ckeditor&gt; &lt;ckeditor [editor]="Editor" formControlName="back"&gt;&lt;/ckeditor&gt; &lt;button mat-raised-button color="primary" id="delete-card" (click)="deleteCard()" type="button"&gt; &lt;mat-icon&gt;delete_outline&lt;/mat-icon&gt; Delete Card &lt;/button&gt; &lt;/mat-card-content&gt; &lt;/mat-card&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/mat-card-content&gt; &lt;mat-card-actions&gt; &lt;button mat-raised-button color="primary" type="submit"&gt; &lt;mat-icon&gt;save_alt&lt;/mat-icon&gt; Save &lt;/button&gt; &lt;/mat-card-actions&gt; &lt;/mat-card&gt; &lt;/form&gt; &lt;/section&gt; </code></pre> <p><strong>create.component.scss:</strong></p> <pre><code>section { mat-card-actions { margin: 0; &amp;:last-child { margin-bottom: 0; } } mat-form-field { width: 100%; } ckeditor div { padding-bottom: 1.25em } .flashcard-list { padding: 0; mat-button-toggle-group { width: 100%; height: 372px; overflow: auto; mat-button-toggle button { text-align: left; } } #add-card { width: 100%; } } .card-select-selector { .menu-icon { margin: auto } .create-card-button { margin-left: 20px } } } </code></pre> <p><strong>tag-dialog.component.ts:</strong></p> <pre><code>import { Component } from '@angular/core'; import { MatDialogRef } from '@angular/material/dialog'; @Component({ selector: 'tag-dialog', templateUrl: './tag-dialog.component.html', }) export class TagDialog { constructor(public dialogRef: MatDialogRef&lt;TagDialog&gt;) { } } </code></pre> <p><strong>tag-dialog.component.html:</strong></p> <pre><code>&lt;h1 mat-dialog-title&gt;Create Tag&lt;/h1&gt; &lt;div mat-dialog-content&gt; &lt;mat-form-field&gt; &lt;input matInput placeholder="Tag Name" #tag /&gt; &lt;/mat-form-field&gt; &lt;/div&gt; &lt;div mat-dialog-actions&gt; &lt;button mat-raised-button [mat-dialog-close]="tag.value" color="primary"&gt;Create&lt;/button&gt; &lt;/div&gt; </code></pre> <p><strong>deck-finder.component.ts:</strong></p> <pre><code>import { Component, OnInit } from '@angular/core'; import { FlashcardDeckService } from '../shared/services/flashcardDeck.service'; import { HttpClient } from '@angular/common/http'; import { FlashcardDeck } from '../shared/models/flashcardDeck'; @Component({ selector: 'fcd-deck-finder', templateUrl: './deck-finder.component.html', styleUrls: ['./deck-finder.component.scss'] }) export class DeckFinderComponent implements OnInit { constructor(private readonly flashcardDeckService: FlashcardDeckService, private readonly http: HttpClient) { } private _decks: FlashcardDeck[]; public get decks() { return this._decks; } public set decks(value) { this._decks = value; } public categories: string[]; public filterDecks(category: any) { this.flashcardDeckService.getAll(category).subscribe(data =&gt; { this.decks = data; }); } ngOnInit() { this.flashcardDeckService.getAll().subscribe(data =&gt; { this.decks = data; }); this.http.get&lt;string[]&gt;(`/FlashcardDeck/getAllCategories`).subscribe(data =&gt; { this.categories = data; }); } } </code></pre> <p><strong>deck-finder.component.html:</strong></p> <pre><code>&lt;section&gt; &lt;mat-card&gt; &lt;mat-card-content&gt; &lt;div fxLayout="row" fxLayout.lt-sm="column" fxLayoutGap="20px" fxLayoutGap.lt-sm&gt; &lt;div fxFlex="250px" fxFlex.lt-sm&gt; &lt;mat-form-field&gt; &lt;mat-label&gt;Categories&lt;/mat-label&gt; &lt;mat-select (selectionChange)="filterDecks($event.value)"&gt; &lt;mat-option class="unfiltered"&gt;(Unfiltered)&lt;/mat-option&gt; &lt;mat-option *ngFor="let category of categories" [value]="category"&gt; {{category}} &lt;/mat-option&gt; &lt;/mat-select&gt; &lt;/mat-form-field&gt; &lt;/div&gt; &lt;div fxLayout="row wrap" fxFlex&gt; &lt;mat-card class="deck" *ngFor="let deck of decks"&gt; &lt;mat-card-content&gt; &lt;div&gt; &lt;a id="edit-deck" mat-mini-fab [routerLink]="['/edit/deck', deck.id]"&gt; &lt;mat-icon&gt;settings&lt;/mat-icon&gt; &lt;/a&gt; &lt;/div&gt; &lt;div class="view-deck-container"&gt; &lt;a class="view-deck" [routerLink]="['/deck', deck.id]"&gt;{{deck.title}}&lt;/a&gt; &lt;/div&gt; &lt;/mat-card-content&gt; &lt;/mat-card&gt; &lt;/div&gt; &lt;/div&gt; &lt;/mat-card-content&gt; &lt;/mat-card&gt; &lt;/section&gt; </code></pre> <p><strong>deck-finder.component.scss:</strong></p> <pre><code>section { mat-card.deck { height: 150px; width: 225px; margin: 5px; background-color: whitesmoke; #edit-deck { float: right !important; } .view-deck-container { text-align: center; padding-top: 40px; } .view-deck { font-weight: bold; font-size: 200%; color: sienna; text-decoration: underline; } } } </code></pre> <p><strong>deck-viewer.module.ts:</strong></p> <pre><code>import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { RouterModule } from '@angular/router'; import { MatButtonModule } from '@angular/material/button'; import { MatIconModule } from '@angular/material/icon'; import { MatCardModule } from '@angular/material/card'; import { FlexLayoutModule } from '@angular/flex-layout'; import { HttpClientModule } from '@angular/common/http'; import { DeckViewerComponent } from './deck-viewer.component'; import { FlashcardDeckService } from '../shared/services/flashcardDeck.service'; @NgModule({ declarations: [DeckViewerComponent], imports: [ CommonModule, MatButtonModule, MatIconModule, MatCardModule, FlexLayoutModule, HttpClientModule, RouterModule.forChild([ { path: '', component: DeckViewerComponent } ]) ], providers: [FlashcardDeckService], }) export class DeckViewerModule { } </code></pre> <p><strong>deck-viewer.component.ts:</strong></p> <pre><code>import { Component, OnInit } from '@angular/core'; import { FlashcardDeckService } from '../shared/services/flashcardDeck.service'; import { ActivatedRoute } from '@angular/router'; import { FlashcardDeck } from '../shared/models/flashcardDeck'; import { Flashcard } from '../shared/models/flashcard'; @Component({ selector: 'fcd-deck-viewer', templateUrl: './deck-viewer.component.html', styleUrls: ['./deck-viewer.component.scss'] }) export class DeckViewerComponent implements OnInit { private _flashcardDeck: FlashcardDeck; public get flashcardDeck() { return this._flashcardDeck; } public set flashcardDeck(value) { this._flashcardDeck = value; } private _selectedCard: Flashcard; public get selectedCard() { return this._selectedCard; } public set selectedCard(value) { this._selectedCard = value; } constructor(private flashcardDeckService: FlashcardDeckService, private route: ActivatedRoute) { } public previousCard() { if (this.selectedCard.id === 0) { return; } document.getElementsByClassName('flip-container').item(0).classList.remove('hover'); this.selectedCard = this.flashcardDeck.cards[this.selectedCard.id - 1]; } public nextCard() { if (this.selectedCard.id === this.flashcardDeck.cards.length - 1) { return; } document.getElementsByClassName('flip-container').item(0).classList.remove('hover'); this.selectedCard = this.flashcardDeck.cards[this.selectedCard.id + 1]; } ngOnInit() { this.flashcardDeckService .get(parseInt(this.route.snapshot.paramMap.get('id'))) .subscribe(data =&gt; { this.flashcardDeck = data; this.selectedCard = this.flashcardDeck.cards[0]; }); } } </code></pre> <p><strong>deck-viewer.component.html:</strong></p> <pre><code>&lt;section&gt; &lt;mat-card&gt; &lt;mat-card-title&gt;{{flashcardDeck?.title}}&lt;/mat-card-title&gt; &lt;mat-card-content&gt; &lt;div class="flip-container" onclick="this.classList.toggle('hover');"&gt; &lt;div class="flipper"&gt; &lt;mat-card class="front" fxLayout="column"&gt; &lt;div fxFlex&gt;&lt;/div&gt; &lt;div fxFlex [innerHTML]="selectedCard?.front"&gt;&lt;/div&gt; &lt;div fxFlex&gt;&lt;/div&gt; &lt;/mat-card&gt; &lt;mat-card class="back" fxLayout="column"&gt; &lt;div fxFlex&gt;&lt;/div&gt; &lt;div fxFlex [innerHTML]="selectedCard?.back"&gt;&lt;/div&gt; &lt;div fxFlex&gt;&lt;/div&gt; &lt;/mat-card&gt; &lt;/div&gt; &lt;/div&gt; &lt;/mat-card-content&gt; &lt;mat-card-actions&gt; &lt;button mat-raised-button color="primary" (click)="previousCard()" class="nav-prev" [disabled]="selectedCard?.id === 0"&gt; &lt;mat-icon&gt;navigate_before&lt;/mat-icon&gt; Previous &lt;/button&gt; &lt;button mat-raised-button color="primary" (click)="nextCard()" class="nav-next" [disabled]="selectedCard?.id === flashcardDeck?.cards.length - 1"&gt; &lt;mat-icon&gt;navigate_next&lt;/mat-icon&gt; Next &lt;/button&gt; &lt;/mat-card-actions&gt; &lt;/mat-card&gt; &lt;/section&gt; </code></pre> <p><strong>deck-viewer.component.scss:</strong></p> <pre><code>section { mat-card-title { text-align: center; } mat-card-content { .flip-container { perspective: 1000px; margin: auto; margin-bottom: 0; .flipper { transition: 0.6s; transform-style: preserve-3d; position: relative; .front, .back { backface-visibility: hidden; position: absolute; top: 0; left: 0; text-align: center; vertical-align: middle; padding: 10px; background-color: whitesmoke; } .front { z-index: 2; transform: rotateY(0deg); } .back { transform: rotateY(180deg); } } } .flip-container:hover .flipper, .flip-container.hover .flipper { transform: rotateY(180deg); } .flip-container, .front, .back { width: 320px; height: 200px; } } mat-card-actions { width: 320px; margin: auto; padding-top: 0; .nav-next { float: right !important; } } } </code></pre> <p><strong>home.module.ts:</strong></p> <pre><code>import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { HomeComponent } from './home.component'; import { RouterModule } from '@angular/router'; import { DeckFinderComponent } from '../deck-finder/deck-finder.component'; import { MatCardModule } from '@angular/material/card'; import { MatButtonModule } from '@angular/material/button'; import { MatIconModule } from '@angular/material/icon'; import { MatGridListModule } from '@angular/material/grid-list' import { MatSelectModule } from '@angular/material/select'; import { FlashcardDeckService } from '../shared/services/flashcardDeck.service'; import { HttpClientModule } from '@angular/common/http'; import { FlexLayoutModule } from '@angular/flex-layout'; @NgModule({ declarations: [HomeComponent, DeckFinderComponent], imports: [ CommonModule, MatCardModule, MatButtonModule, MatIconModule, MatGridListModule, MatSelectModule, HttpClientModule, FlexLayoutModule, RouterModule.forChild([ { path: '', component: HomeComponent } ]) ], providers: [FlashcardDeckService] }) export class HomeModule { } </code></pre> <p><strong>home.component.html:</strong></p> <pre><code>&lt;fcd-deck-finder&gt;&lt;/fcd-deck-finder&gt; </code></pre> <p><strong>flashcardDeck.ts</strong> and <strong>flashcard.ts:</strong></p> <pre><code>import { Flashcard } from "./Flashcard"; export interface FlashcardDeck { id: number; title: string; cards: Flashcard[]; tags: string[]; } export interface Flashcard { id: number; label: string; front: string; back: string; } </code></pre> <p><strong>flashcardDeck.service.ts:</strong></p> <pre><code>import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { Observable } from 'rxjs'; import { FlashcardDeck } from '../models/flashcardDeck'; @Injectable({ providedIn: 'root' }) export class FlashcardDeckService { constructor(private http: HttpClient) { } getNew(): FlashcardDeck { return { id: 0, title: '(New Deck)', cards: [], tags: [] } } get(id: number): Observable&lt;FlashcardDeck&gt; { return this.http.get&lt;FlashcardDeck&gt;(`/FlashcardDeck/getDeck/${id}`); } getAll(category?: string): Observable&lt;FlashcardDeck[]&gt; { return category === undefined ? this.http.get&lt;FlashcardDeck[]&gt;(`/FlashcardDeck/getAllDecks`) : this.http.get&lt;FlashcardDeck[]&gt;(`/FlashcardDeck/getAllDecks?category=${category}`); } save(flashcardDeck: FlashcardDeck) { return this.http.post&lt;FlashcardDeck&gt;('/FlashcardDeck/SaveDeck', flashcardDeck); } } </code></pre> <p><strong>FlashcardDeckController.fs:</strong></p> <pre><code>namespace Flashcard.Controllers open Microsoft.AspNetCore.Mvc open Microsoft.Extensions.Configuration open FlashcardTypes open MongoDB.Driver open System.Linq type FlashcardDeckController (configuration : IConfiguration) = inherit ControllerBase() [&lt;HttpPost&gt;] member __.SaveDeck([&lt;FromBody&gt;] flashcardDeck : FlashcardDeck) = Array.iteri (fun index (item:Flashcard) -&gt; item.Id &lt;- index) flashcardDeck.Cards let client = new MongoClient(configuration.GetConnectionString("Database")) let database = client.GetDatabase("Flashcards") let collection = database.GetCollection&lt;FlashcardDeck&gt;("Decks") if flashcardDeck.Id = 0 then let nextId = if flashcardDeck.Id = 0 &amp;&amp; (collection.Find(Builders&lt;FlashcardDeck&gt;.Filter.Empty).Any() |&gt; not) then 1 else collection.Find(Builders&lt;FlashcardDeck&gt;.Filter.Empty) .SortByDescending(fun i -&gt; (i.Id :&gt; obj)) .FirstOrDefault().Id + 1 flashcardDeck.Id &lt;- nextId async { collection.InsertOneAsync(flashcardDeck) |&gt; ignore } |&gt; Async.Start else async { collection.FindOneAndReplaceAsync(Builders&lt;FlashcardDeck&gt;.Filter.Eq((fun deck -&gt; deck.Id), flashcardDeck.Id), flashcardDeck) |&gt; ignore } |&gt; Async.Start flashcardDeck [&lt;HttpGet&gt;] member __.GetDeck(id : int) : FlashcardDeck = let client = new MongoClient(configuration.GetConnectionString("Database")) let database = client.GetDatabase("Flashcards") let collection = database.GetCollection&lt;FlashcardDeck&gt;("Decks") collection.Find(Builders&lt;FlashcardDeck&gt;.Filter.Eq((fun deck -&gt; deck.Id), id)).Single() [&lt;HttpGet&gt;] member __.GetAllDecks(category : string) : FlashcardDeck[] = let client = new MongoClient(configuration.GetConnectionString("Database")) let database = client.GetDatabase("Flashcards") let collection = database.GetCollection&lt;FlashcardDeck&gt;("Decks") let filter = if System.String.IsNullOrEmpty(category) then Builders&lt;FlashcardDeck&gt;.Filter.Empty else Builders&lt;FlashcardDeck&gt;.Filter.Where(fun deck -&gt; deck.Tags.Contains(category)) collection.Find(filter).ToList() |&gt; Seq.toArray [&lt;HttpGet&gt;] member __.GetAllCategories() : string[] = let client = new MongoClient(configuration.GetConnectionString("Database")) let database = client.GetDatabase("Flashcards") let collection = database.GetCollection&lt;FlashcardDeck&gt;("Decks") collection .Find(Builders&lt;FlashcardDeck&gt;.Filter.Empty) .Project(Builders&lt;FlashcardDeck&gt;.Projection.Expression(fun s -&gt; s.Tags)) .ToList() |&gt; Seq.collect (fun s -&gt; s) |&gt; Seq.distinct |&gt; Seq.sortBy (fun s -&gt; s) |&gt; Seq.toArray </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-15T15:04:34.563", "Id": "232447", "Score": "3", "Tags": [ "f#", "typescript", "mongodb", "angular-2+", "asp.net-core" ], "Title": "Flashcard Website" }
232447
<p>I've been refactoring code today, try to implement a clean code setup using repositories. Is this on track? Can any improvements be made?</p> <pre><code>public class IndexModel : PageModel { private readonly MembershipFormRepository _membershipFormRepository; private readonly IMembershipFormViewModelService _membershipFormViewModelService; public IndexModel(IMembershipFormViewModelService membershipFormViewModelService, MembershipFormRepository membershipFormRepository) { _membershipFormViewModelService = membershipFormViewModelService; _membershipFormRepository = membershipFormRepository; } [BindProperty] public MembershipFormViewModel MembershipFormModel { get; set; } = new MembershipFormViewModel(); public async Task OnGetAsync() { MembershipFormModel = await _membershipFormViewModelService.GetViewModel(); } public async Task&lt;IActionResult&gt; OnPostAddMemberAsync() { if (!ModelState.IsValid) { return Page(); } await _membershipFormRepository.AddMember(MembershipFormModel); return RedirectToPage("Index"); } } </code></pre> <p>MembershipFormViewModelService</p> <pre><code>public class MembershipFormViewModelService : IMembershipFormViewModelService { private readonly MembershipContext _context; private readonly MembershipFormRepository _membershipFormRepository; public MembershipFormViewModelService(MembershipContext context, MembershipFormRepository membershipFormRepository) { _context = context; _membershipFormRepository = membershipFormRepository; } public async Task&lt;MembershipFormViewModel&gt; GetViewModel() { var viewModel = new MembershipFormViewModel() { Titles = await SetTitlesDropDown(), }; return viewModel; } private async Task&lt;IEnumerable&lt;SelectListItem&gt;&gt; SetTitlesDropDown() { var titlesList = new List&lt;SelectListItem&gt;(); var titles = await _membershipFormRepository.GetTitles(); titlesList.AddRange(titles.Select(title =&gt; new SelectListItem() { Value = title.TitleId.ToString(), Text = title.Title })); return titlesList; } } </code></pre> <p>IMembershipFormViewModelService</p> <pre><code>public interface IMembershipFormViewModelService { Task&lt;MembershipFormViewModel&gt; GetViewModel(); } </code></pre> <p>MembershipFormRepository</p> <pre><code>public class MembershipFormRepository : IMembershipFormRepository { private readonly MembershipContext _context; private readonly IMapper _mapper; public MembershipFormRepository(MembershipContext context, IMapper mapper) { _context = context; _mapper = mapper; } public async Task&lt;IEnumerable&lt;Title&gt;&gt; GetTitles() { return await _context.Title.ToListAsync(); } public async Task AddMember(MembershipFormViewModel membershipForm) { var membership = new Membership(); membership = _mapper.Map(membershipForm, membership); _context.Membership.Add(membership); await _context.SaveChangesAsync(); } } </code></pre> <p>IMembershipFormRepository</p> <pre><code>public interface IMembershipFormRepository { Task&lt;IEnumerable&lt;Title&gt;&gt; GetTitles(); Task AddMember(MembershipFormViewModel membershipForm); } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-15T15:59:29.220", "Id": "453939", "Score": "1", "body": "Welcome to code review. The title should reflect what the code is used for, rather than what you are trying to achieve. Know what the code does helps us give a better review." } ]
[ { "body": "<p>You are close. The only thing that jumps out at me is your use of the <code>MembershipFormRepository</code> type instead of the <code>IMembershipFormRepository</code> interface. This prevents you from being able to test consumers of it easily. For example, consider this case:</p>\n\n<p>You have an object of type <code>Foo</code> that takes an injected instance of type <code>Bar</code> that takes an injected instance of a DB context <code>context</code>. You want to test that something on the <code>Foo</code> type works. Here is your test setup:</p>\n\n<pre><code>var dbContext = new Moq&lt;DbContext&gt;();\ndbContext\n .Setup(s =&gt; s.Get())\n .Returns(new List&lt;Item&gt;());\n\nvar bar = new Bar(dbContext.Object);\nvar foo = new Foo(bar);\n\n// assert foo.DoSomething()\n</code></pre>\n\n<p>Notice how you have to mock up a full <code>Bar</code> object, and even more troublesome, rely on <code>Bar</code> working correctly, for the test to pass. If <code>Bar</code> has a bug, your test can fail; this test, because it tests <code>Foo</code>, should only fail if <code>Foo</code> has a bug. If you injected a type of <code>IBar</code> into the <code>Foo</code> instead, you could mock that, instead of the DB context:</p>\n\n<pre><code>var bar = new Moq&lt;IBar&gt;();\nbar.Setup(s =&gt; s.GetItems())\n .Returns(new List&lt;Item&gt;());\n\nvar foo = new Foo(bar.Object);\n\n// assert foo.DoSomething()\n</code></pre>\n\n<p>Now, instead of relying on <code>Bar.GetItems</code> not being buggy, you just create a mocked object that always returns the same data. This test also won't fail if <code>Bar</code> changes. The first test would fail if you changed <code>Bar.GetItems</code> to call <code>DbContext.Where</code> instead of <code>DbContext.Get</code> because you hadn't mocked the <code>Where</code> call, which would once again falsely report a bug in the <code>Foo</code> type because the <code>Bar</code> type had changed or was buggy.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-15T15:46:43.110", "Id": "453933", "Score": "0", "body": "That makes sense, thank you. I've changed the repository registration in StartUp and changed the references to use the injected instance instead, so other than that, looks good?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-15T15:47:25.830", "Id": "453934", "Score": "0", "body": "Yes, it looks good. Although, this is a simple enough app there aren't too many places to make mistakes." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-15T15:49:20.083", "Id": "453935", "Score": "0", "body": "Yeah fair enough, I'm going to be doing the rest of the application too so it's good to know I'm on the right track at least. Thanks for the input." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-15T15:26:02.560", "Id": "232450", "ParentId": "232449", "Score": "4" } } ]
{ "AcceptedAnswerId": "232450", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-15T15:11:23.327", "Id": "232449", "Score": "3", "Tags": [ "c#", "asp.net", "repository", "asp.net-core", "razor-pages" ], "Title": "Refactoring code to implement clean code using repositories" }
232449
<blockquote> <p>I initially posted this on <a href="https://stackoverflow.com/questions/58878336/clientfactory-pattern-dependency-injection-and-httpclient-socketexhaustion">Stackoverflow</a> but was recommended to try here instead. I'm looking for feedback on <em>why</em> the implementation of my ClientFactory is probably bad, from a Dependency Injection-point of view. Or if it is actually okay to use in production?</p> <p>My code below works. I know how to implement a named/typed client. Yes, I have read the <a href="https://docs.microsoft.com/en-us/dotnet/architecture/microservices/implement-resilient-applications/use-httpclientfactory-to-implement-resilient-http-requests" rel="nofollow noreferrer">docs on how to implement resilient HTTP requests</a> and yes, I have read about socket exhaustion <a href="https://aspnetmonsters.com/2016/08/2016-08-27-httpclientwrong/" rel="nofollow noreferrer">here</a> and <a href="https://josefottosson.se/you-are-probably-still-using-httpclient-wrong-and-it-is-destabilizing-your-software/" rel="nofollow noreferrer">here</a></p> </blockquote> <p>I'm creating an REST API that will communicate with various other APIs in it's &quot;backend&quot;. The APIs it will communicate with will alot of the time be the same API (same contract) but on a different instance/host. <strong>The hosts are not known to me specifically, but are retrieved from a database based upon a request is initiated</strong> for that specific system. I do not wish to create a new HttpClient for every individual request so I would like to re-use my HttpClients for some time after it's been created for subsequent requests to the same system to avoid socket exhaustion.</p> <p>To remedy this I have tried a few different approaches, but since I'm feeling unsure on the inner workings of DI I'm not sure my implementations makes sense with the concept of Dependency Injection. The DI-concept just doesn't come naturally to me at this point. Here's my examples:</p> <h2>ClientFactory:</h2> <p>I've created an Interface and ClientFactory for each API that I will use. The <code>ClientFactory.Create()</code> takes a <code>settings</code>-parameter that sets hostname and authorization headers for the specific server I need to connect to for this specific request. It looks a bit like this:</p> <p><strong>MyApiClientSettings.cs:</strong></p> <pre class="lang-cs prettyprint-override"><code>namespace MyAPI.Domain.Services.ConnectionHandler { public interface IMyApiClientSettings { string Server { get; set; } string Token { get; set; } } public class MyApiClientSettings : IMyApiClientSettings { public string Server { get; set; } public string Token { get; set; } } } </code></pre> <p><strong>MyApiClientFactory.cs:</strong></p> <p>ClientFactory sets <code>BaseAddress</code> and auth-header based on supplied <code>settings</code></p> <pre class="lang-cs prettyprint-override"><code>namespace MyAPI.Domain.Services.ConnectionHandler { public interface IMyApiClientFactory { MyApiClient CreateMyApiClient(IMyApiClientSettings settings); } public class MyApiClientFactory : IMyApiClientFactory { private const string MyApiEndpointUrl = &quot;https://{0}/MyApi/&quot;; public MyApiClient CreateMyApiClient(IMyApiClientSettings settings) { var myApiClient = new MyApiClient(); myApiClient.BaseAddress = new Uri(string.Format(MyApiEndpointUrl, settings.Server)); myApiClient.DefaultRequestHeaders.Add(&quot;Accept&quot;, &quot;application/json&quot;); myApiClient.DefaultRequestHeaders.Add(&quot;User-Agent&quot;, &quot;My-API-Consumer&quot;); myApiClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue($&quot;Bearer&quot;, $&quot;{settings.Token}&quot;); return myApiClient; } } } </code></pre> <p><strong>MyApiClient.cs:</strong></p> <p>The <code>MyApiClient</code> that is returned from ClientFactory.</p> <pre class="lang-cs prettyprint-override"><code>namespace MyAPI.Services.ConnectionHandler { public class MyApiClient : System.Net.Http.HttpClient { public async Task&lt;UserList&gt; GetUsersListAsync() { var response = await this.GetAsync($&quot;v1/users/&quot;); response.EnsureSuccessStatusCode(); var content = await response.Content.ReadAsStreamAsync(); var result = DeserializeObjectAsync&lt;UserList&gt;(content); return result; } public async Task&lt;User&gt; GetUsersByIdAsync(Guid id) { var response = await this.GetAsync($&quot;v1/users/{id}&quot;); response.EnsureSuccessStatusCode(); var content = await response.Content.ReadAsStreamAsync(); var result = DeserializeObjectAsync&lt;User&gt;(content); return result; } } } </code></pre> <p><strong>Used like this:</strong> The <code>ClientFactory</code> is injected into a service using dependecy injection. The <code>WorkerService</code> builds the <code>settings</code> for <code>MyApiClient</code> and gets the hosts IP (/BaseAddress) by quering <code>GetServerIPByToken(apiToken)</code>.</p> <pre class="lang-cs prettyprint-override"><code>namespace MyAPI.Services { public class MyService { private readonly MyApiClientFactory _myApiClientFactory; //Injected from Startup.cs via &quot;services.AddSingleton&lt;MyApiClientFactory&gt;();&quot; public MyService(MyApiClientFactory myApiClientFactory) { _myApiClientFactory = myApiClientFactory; } public void DoStuff(string apiToken) { var settings = new MyApiClientSettings { Token = apiToken, Server = GetServerIPByToken(apiToken) }; var myApiClient = _myApiClientFactory.Create(settings); var result = myApiClient.GetUsersListAsync(); /* Do stuff with result - Removed for the sake of brevity */ } } } </code></pre> <p>This way I can dynamically create my API clients for various hosts depending on the requests I recieve. But to do so I inject a <code>Singleton</code> <code>ClientFactory</code> to every service that might need it. Add a couple of worker services, and those worker services then creates its own instaces of MyApiClient by calling <code>_myApiClientFactory.Create(settings);</code> which seems potentially wasteful.</p> <p>So I added a &quot;<code>ConnectionHandler</code>&quot; that creates the <code>MyApiClient</code>-clients, and adds them to a dictonary. The <code>ConnectionHandler</code> creates/reconnects clients and adds them to the dict, disposes of clients and removes unused or failed clients from the dictonary. This way I inject the <code>MyApiClientFactory</code> only to my <code>ConnectionHandler</code> and instead injects my <code>ConnectionHandler</code> to all services, wich then use the exposed <code>clientDictonary</code>, like this:</p> <p><strong>ConnectionService.cs:</strong> Initialize clients to be used by services, handle disconnects/reconnects and dispose faulty or unused clients.</p> <pre class="lang-cs prettyprint-override"><code>namespace MyAPI.Services.ConnectionHandler { public class ConnectionService { private readonly MyApiClientFactory _myApiClientFactory; //Injected from Startup.cs via &quot;services.AddSingleton&lt;MyApiClientFactory&gt;();&quot; public ConnectionService(MyApiClientFactory myApiClientFactory) { _myApiClientFactory = myApiClientFactory; } /// &lt;summary&gt;Dictionary containing active apiClients. /// &lt;para&gt;TKey - apiToken. TValue - active MyApiClient.&lt;/para&gt; /// &lt;/summary&gt; public Dictionary&lt;string, MyApiClient&gt; clientDict = new Dictionary&lt;string, MyApiClient&gt;(); public void Initialize(string apiToken, bool reconnect = false) { var settings = new MyApiClientSettings { Token = apiToken, Server = GetServerIPByToken(apiToken) }; var myApiClient = _myApiClientFactory.Create(settings); clientDict.Add(apiToken, myApiClient); } /* Handle reconnects, disconnects, dispose of clients that have been unused for 5+ minutes etc */ } } </code></pre> <p><strong>MyService.cs updated to:</strong> Use existing <code>MyApiClient</code> or call <code>Initialize</code> if there is no existing client.</p> <pre class="lang-cs prettyprint-override"><code>namespace MyAPI.Services { public class MyService { private readonly ConnectionService _connectionHandler; //Injected from Startup.cs via &quot;services.AddSingleton&lt;ConnectionService&gt;();&quot; public MyService(ConnectionService connectionHandler) { _connectionHandler = connectionHandler; } public void DoStuff(string apiToken) { if (!_connectionHandler.clientDict.TryGetValue(apiToken, out var myApiClient)) { _connectionHandler.Initialize(apiToken); } _connectionHandler.clientDict.TryGetValue(apiToken, out myApiClient); var result = myApiClient.GetUsersListAsync(); /* Handle connection errors etc */ } } } </code></pre> <p>I personally like this approach. It feels natural for me to use and fairly easy to scale. <em><strong>I am however in-experienced</strong></em> when it comes to Dependecy Injection so I suspect this is full of anti-patterns, bad practices and probably stuff that violates the DI-concept.</p> <hr /> <p>From my understanding, &quot;the correct way&quot; to do the above would be to skip most of the code and ClientFactory, and add <code>MyApiClient</code>via Dependency Injection and then supply a <code>httpClient</code> for each request. Something similar to this:</p> <h2>The right way (ish):</h2> <p><strong>MyApiClient.cs:</strong></p> <pre class="lang-cs prettyprint-override"><code>namespace MyAPI.Services { public class MyApiClient { public async Task&lt;UserList&gt; GetUsersListAsync(HttpClient httpClient) { var response = await httpClient.GetAsync($&quot;v1/users/&quot;); response.EnsureSuccessStatusCode(); var content = await response.Content.ReadAsStreamAsync(); var result = DeserializeObjectAsync&lt;SystemApplicationList&gt;(content); return result; } public async Task&lt;User&gt; GetUsersByIdAsync(HttpClient httpClient, Guid id) { var response = await httpClient.GetAsync($&quot;v1/users/{id}&quot;); response.EnsureSuccessStatusCode(); var content = await response.Content.ReadAsStreamAsync(); var result = DeserializeObjectAsync&lt;SystemApplicationList&gt; } } } </code></pre> <p><strong>MyService.cs:</strong></p> <pre class="lang-cs prettyprint-override"><code>namespace MyAPI.Services { public class MyService { private readonly MyApiClient _myApiClient //Injected from Startup.cs via &quot;services.AddHttpClient&lt;MyApiClient&gt;();&quot; public MyService(MyApiClient myApiClient) { _myApiClient = myApiClient; } public void DoStuff(string apiToken) { var httpClient = new HttpClient(); httpClient.BaseAddress = new Uri(GetServerIPByToken(apiToken)); httpClient.DefaultRequestHeaders.Add(&quot;Accept&quot;, &quot;application/json&quot;); httpClient.DefaultRequestHeaders.Add(&quot;User-Agent&quot;, &quot;My-API-Consumer&quot;); httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue($&quot;Bearer&quot;, $&quot;{apiToken}&quot;); var result = _myApiClient.GetUsersListAsync(httpClient); /* Do stuff with result - Removed for the sake of brevity */ } } } </code></pre> <p>What I do not like or maybe do not understand fully, is that in this aproach every call to <code>DoStuff()</code> creates a new instance of a <code>httpClient</code>. This seems wasteful to me. Sure I could create and re-use the <code>httpClient</code> in a similar way that I did in my <code>ConnectionHandler</code> - but then I'd rather prefer my implementation of Interfaces &amp; Factories instead of passing a client as a parameter for every action. But I suspect the reason for my preference is based on some misunderstanding of how DI works or is supposed to be used.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-15T16:16:03.037", "Id": "453942", "Score": "4", "body": "Welcome to code review. The question does reflect good effort on your part, but some parts of the question seem to be vague. If the title indicated a little more about what the code does it might be better, also comment like `/* .... */` indicate some code is being hidden and name spaces like `foobar` make the question seem hypothetical which would make it off-topic for code review." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-15T17:06:00.320", "Id": "453949", "Score": "4", "body": "Thanks @pacmaninbw - I've updated the title and namespaces and I've updated or removed some of the comments.\nMy initial choice of namespaces and comments was an attempt to make an already long post shorter for the sake of brevity. I hope its better now." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-15T16:03:18.880", "Id": "232453", "Score": "5", "Tags": [ "c#", "dependency-injection", "rest", "asp.net-core", ".net-core" ], "Title": "Using ClientFactory-pattern with Dependency Injection" }
232453
<p>I have this below code where i am sending some content over a POST and then consuming the response. I would like to know if there can be any optimizations that can be done and is there any possibility of connection leak.</p> <pre><code>import java.io.*; import java.net.HttpURLConnection; import java.net.URL; import java.nio.charset.StandardCharsets; import java.util.Calendar; class Test implements Serializable { static String getR(String xml, String requestUrl, int retryWaitTime, int socketTimeOut) throws IOException { long startTime = Calendar.getInstance().getTimeInMillis(); StringBuilder xmlString = new StringBuilder(); String out; HttpURLConnection connection = null; try { URL url = new URL(requestUrl); connection = (HttpURLConnection) url.openConnection(); connection.setConnectTimeout(retryWaitTime); connection.setReadTimeout(socketTimeOut); connection.setDoInput(true); connection.setDoOutput(true); connection.setRequestMethod("POST"); connection.setRequestProperty("Accept", "application/xml"); connection.setRequestProperty("Content-Type", "application/xml; charset=UTF-8"); OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream(), StandardCharsets.UTF_8); writer.write(xml); writer.close(); int statusCode = connection.getResponseCode(); if (statusCode == HttpURLConnection.HTTP_OK) { BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream())); String line; while ((line = br.readLine()) != null) { xmlString.append(line); } br.close(); out = xmlString.toString(); } else { out = statusCode + "^" + xml; } if (connection.getInputStream() != null) connection.getInputStream().close(); } catch (Exception e) { out = "X^" + xml; assert connection != null; if (connection.getErrorStream() != null) connection.getErrorStream().close(); } String Response = out.replace("\n", "").replace("\r", ""); return Response; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-15T16:13:42.220", "Id": "453941", "Score": "0", "body": "Well, the `assert` probably won't work in production code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-15T16:18:14.770", "Id": "453943", "Score": "0", "body": "We can give better reviews when more of the code is provided, is there any way you could provide the entire class?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-15T16:29:13.310", "Id": "453945", "Score": "0", "body": "@pacmaninbw I have updated the code" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-15T16:37:16.533", "Id": "453946", "Score": "0", "body": "@markspace, what do you suggest ?" } ]
[ { "body": "<p>Star imports are discouraged. It's preferable to specify what classes you're importing in most cases.</p>\n\n<p><code>getR</code> is a very poor method name unless <code>R</code> is well defined inside the domain you're operating in. It's preferable to clearly express, without abbreviations, what the method will be doing. <code>get</code> is also misleading because it implies a simple local operation to retrieve a value from a class, not a remote call.</p>\n\n<p>When variables will not be reassigned, it's preferable to mark them as <code>final</code>. This expresses design intent and tells the reader they don't have to worry about the value of the variable changing.</p>\n\n<p>Minimizes scope wherever possible. <code>getR</code> should probably be either private or public. Package-private seems unlikely to be correct.</p>\n\n<p><code>startTime</code> is never used and can be removed. Rather than creating a Calendar instance, <code>System.currentTimeMillis()</code> would be preferable to find the current time.</p>\n\n<p>If <code>getR</code> needs a <code>URL</code>, it should probably take it as a parameter, rather than accepting a <code>String</code>. In particular, your error handling of a bad URL is highly dubious. The caller gets no notification of any type that the URL string was incorrect. Make them build a correct URL and handle the case where they can't before the <code>getR</code> call.</p>\n\n<p>There's an argument to be made that <code>setDoInput(true)</code> is noise, and one to be made that it makes things clearer. </p>\n\n<p>The only exception your method throws is if the error stream can't be closed. It's unclear what you expect the caller to be able to do about that.</p>\n\n<p>Use <code>try-with-resources</code> where possible to leverage automatic closing of resources. Otherwise you need to always close resources in <code>finally</code> blocks or you risk exceptions preventing you from closing them.</p>\n\n<p>Always use curly braces, even if they're not required. You prevent an annoying and difficult-to-find class of error, and you enhance readability in most cases.</p>\n\n<p>In idiomatic java, <code>catch</code> belongs on the same line as <code>}</code>.</p>\n\n<p>Always catch the most specific type of exception possible. Catching <code>Exception</code> may silently swallow current or future exceptions you didn't intend to handle.</p>\n\n<p>Using <code>assert</code> to ensure invariants in non-production environments is a good practice, but note that assertions must be engaged at both compile time and run time to function. Most production environments won't (and shouldn't) have assertions enabled. Many development environments and compilations also won't have assertions enabled, so make sure that they're correctly activated if you intend to use them.</p>\n\n<p>It's unclear to me why you're explicitly closing the error stream in that fashion, since you never need or use it otherwise. If you must close it, put it in a <code>try-with-resources</code> block.</p>\n\n<p>You should almost certainly log the exception you're handling for debugging later.</p>\n\n<p>Early returns can clarify the code. The <code>only one return location</code> paradigm is a holdover from when it was not possible to embed returns in the middle of a block of code. A helper method could do the replacements for you.</p>\n\n<p>In idiomatic java, variables start with a lowercase letter. <code>return</code> would be preferable to <code>Return</code>.</p>\n\n<p>Turning the <code>if</code> check into a guard clause would reduce indentation and simplify the logic.</p>\n\n<p>As of Java 9, I believe (but you should confirm) that string concatenation is actually faster than using a <code>StringBuilder</code> in the simple case of appending strings to one another. I think the readability is a wash.</p>\n\n<p>If you were to make all these changes, your code might look more like:</p>\n\n<pre><code>private static String getR(\n final String xml,\n final URL requestUrl,\n final int retryWaitTime,\n final int socketTimeOut) {\n\n final StringBuilder xmlString = new StringBuilder();\n HttpURLConnection connection = null;\n\n try {\n connection = (HttpURLConnection) requestUrl.openConnection();\n connection.setConnectTimeout(retryWaitTime);\n connection.setReadTimeout(socketTimeOut);\n connection.setDoInput(true);\n connection.setDoOutput(true);\n connection.setRequestMethod(\"POST\");\n connection.setRequestProperty(\"Accept\", \"application/xml\");\n connection.setRequestProperty(\"Content-Type\", \"application/xml; charset=UTF-8\");\n\n try (final OutputStreamWriter writer =\n new OutputStreamWriter(connection.getOutputStream(), StandardCharsets.UTF_8)) {\n writer.write(xml);\n }\n\n final int statusCode = connection.getResponseCode();\n if (statusCode != HttpURLConnection.HTTP_OK) {\n return sanitize(statusCode + \"^\" + xml);\n }\n\n try (final BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {\n String line;\n while ((line = br.readLine()) != null) {\n xmlString.append(line);\n }\n }\n return sanitize(xmlString.toString());\n\n } catch (final IOException e) {\n e.printStackTrace();\n return sanitize(\"X^\" + xml);\n }\n}\n\nprivate static String sanitize(final String string) {\n return string.replace(\"\\n\", \"\").replace(\"\\r\", \"\");\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-17T18:33:55.147", "Id": "454138", "Score": "0", "body": "Thanks for the review @Eric." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-16T16:51:40.423", "Id": "232508", "ParentId": "232454", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-15T16:08:17.993", "Id": "232454", "Score": "3", "Tags": [ "java" ], "Title": "HTTPUrlConnection code optimization" }
232454
<p>What do you think about this code I wrote. It reads several json files ( I attached them as pastebins) and the code outputs summary information calculated from the input.</p> <pre><code># 1) calculate the # engagement rate from the first JSON file (the user's Instagram media) # - Calculate the average number of comments - Calculate the average # number of likes - Calculate the engagement rate using (Average Likes + # Average Comments)/# of Followers which is 435 # # 2) Combine the 2 sets of JSON data (Instagram media objects with their # Instagram insights), then output a single JSON file where the insights # are paired with their media objects in a clean format. # # Question 1.json: https://pastebin.com/V3Ue87H4 # Question2A.json: https://pastebin.com/YifXzimZ # Question2B.json: https://pastebin.com/6X0JYXtD require 'json' input = JSON.parse( File.read('Question 1.json') )["data"] avg_likes = input.map { |x| x["like_count"] }. inject{ |sum, el| sum + el }.to_f / input.size avg_comments = input.map { |x| x["comments_count"] }.inject{ |sum, el| sum + el }.to_f / input.size puts "Answer for Question 1: #{avg_likes + avg_comments / 435}\n\n" input_a = JSON.parse( File.read('Question2A.json') )["data"] input_b = JSON.parse( File.read('Question2B.json') ).map { |x| x["data"] }.flatten output = input_a.map do |post| { :permalink =&gt; post["permalink"], :impressions =&gt; input_b.find { |x| x["id"] == "#{post['id']}/insights/impressions/lifetime" }["values"][0]["value"], :engagement =&gt; input_b.find { |x| x["id"] == "#{post['id']}/insights/engagement/lifetime" }["values"][0]["value"], :reach =&gt; input_b.find { |x| x["id"] == "#{post['id']}/insights/reach/lifetime" }["values"][0]["value"], :saved =&gt; input_b.find { |x| x["id"] == "#{post['id']}/insights/saved/lifetime" }["values"][0]["value"] } end puts "Answer for Question 2: " + JSON.pretty_generate(output) # EXAMPLE OUTPUT - generated by running ruby coding_test.rb # # Answer for Question 1: 22.704827586206896 # # Answer for Question 2: [ # { # "permalink": "https://www.instagram.com/p/B40LKjkAlDV/", # "impressions": 236, # "engagement": 33, # "reach": 187, # "saved": 2 # }, # { # "permalink": "https://www.instagram.com/p/B4z4Vq5Ag5g/", # "impressions": 212, # "engagement": 22, # "reach": 170, # "saved": 0 # }, # { # "permalink": "https://www.instagram.com/p/B4xnmtygmi-/", # "impressions": 297, # "engagement": 28, # "reach": 218, # "saved": 1 # }, # { # "permalink": "https://www.instagram.com/p/B4uyfrLgjVi/", # "impressions": 248, # "engagement": 21, # "reach": 194, # "saved": 0 # }, # { # "permalink": "https://www.instagram.com/p/B4nic12AFps/", # "impressions": 292, # "engagement": 15, # "reach": 219, # "saved": 0 # } # ] </code></pre>
[]
[ { "body": "<p>Good work.</p>\n\n<p>Here are some points where you can improve:</p>\n\n<ul>\n<li>You can use <code>input.sum { |x| x[\"like_count\"] }.to_f</code> instead of <code>input.map { |x| x[\"like_count\"] }.inject{ |sum, el| sum + el }</code></li>\n<li>It is a good idea to do calculations with <code>BigDecimal</code> instead of <code>Float</code>.</li>\n<li><code>435</code> is a magic number, you can put it into a constant with a good name.</li>\n<li>The spaces before the parentheses aren't usual in the Ruby community style guide.</li>\n<li>Check the <code>dig</code> method available for <code>Hash</code> instances.</li>\n<li>You can use the new syntax for <code>Hash</code> instances when the keys are symbols: <code>{ hello: \"world\" }</code></li>\n<li>Use double-quotes or single-quotes, you're mixing both.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-30T14:04:21.290", "Id": "459318", "Score": "0", "body": "hey thanks for reviewing the code" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-20T22:09:23.370", "Id": "232717", "ParentId": "232455", "Score": "2" } } ]
{ "AcceptedAnswerId": "232717", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-15T16:32:39.733", "Id": "232455", "Score": "2", "Tags": [ "ruby", "parsing" ], "Title": "Ruby code to parse and analyze social media stats in json format" }
232455
<p>When I heard about the new Linux I/O interface <code>io_uring</code> I searched about the ring buffer.</p> <p>I then thought I may replace my safe queue which is base on C++ 11 <code>std::queue</code> with a ring buffer to avoid repeated memory allocation during producing and consuming the packets between threads.</p> <p>So I wanted to implement it as an exercise and started to look for some C++ implementations and found Boost's circular buffer.</p> <p>I didn't look at its source code much but looked at the functionality it provides and tried to implement most of them but I still lack some.</p> <p>So here is what I came up with:</p> <pre><code>#pragma once #include &lt;utility&gt; #include &lt;optional&gt; #include "span.h" #include &lt;memory&gt; #define PROVIDE_CONTAINER_TYPES(T) \ using value_type = T;\ using pointer = T * ;\ using const_pointer = const T *;\ using reference = T &amp; ;\ using const_reference = const T &amp;; \ using size_type = std::size_t; \ using difference_type = std::ptrdiff_t struct no_init_t {}; constexpr no_init_t no_init; class ring_buffer_index { size_t index; public: ring_buffer_index() : index{0} {} ring_buffer_index(size_t pos) : index{pos} {} ring_buffer_index&amp; operator++() { ++index; return *this; } ring_buffer_index&amp; operator--() { --index; return *this; } ring_buffer_index operator+(size_t pos) const { return ring_buffer_index{index + pos}; } size_t operator-(ring_buffer_index other) const { return index - other.index; } bool operator==(ring_buffer_index other) const { return index == other.index; } bool operator!=(ring_buffer_index other) const { return index != other.index; } void operator+=(size_t times) { index += times; } void operator-=(size_t times) { index -= times; } void reset() { index = 0; } size_t as_index(size_t N) const { size_t pos = index; pos %= N; return pos; } }; template &lt;class T&gt; class uninitialized_array { std::unique_ptr&lt;unsigned char&gt; raw_buffer; public: uninitialized_array() noexcept = default; uninitialized_array(size_t N) : raw_buffer{ new unsigned char[sizeof(T) * N] } {} uninitialized_array(uninitialized_array&amp;&amp; other) noexcept = default; uninitialized_array&amp; operator=(uninitialized_array&amp;&amp; other) noexcept = default; void copy(const uninitialized_array&amp; other, size_t N) { raw_buffer.reset(); if (other.raw_buffer &amp;&amp; N) { raw_buffer.reset(new unsigned char[sizeof(T) * N]); std::uninitialized_copy(other.ptr(), other.ptr() + N, ptr()); } } void resize(size_t N) { raw_buffer.reset( new unsigned char[sizeof(T) * N] ); } T * ptr() noexcept { return reinterpret_cast&lt;T*&gt;(raw_buffer.get()); } const T * ptr() const noexcept { return reinterpret_cast&lt;const T*&gt;(raw_buffer.get()); } T&amp; operator[](size_t pos) noexcept { return ptr()[pos]; } }; template &lt;class T, bool reverse = false, bool const_iter = false&gt; class ring_buffer_iterator { T *ptr; ring_buffer_index index; size_t N; public: PROVIDE_CONTAINER_TYPES(T); using iterator_category = std::random_access_iterator_tag; ring_buffer_iterator(T *ptr, ring_buffer_index index, size_t N) : ptr{ ptr }, index{ index }, N{ N } {} ring_buffer_iterator&amp; operator++() { if constexpr (!reverse) ++index; else --index; return *this; } ring_buffer_iterator&amp; operator+=(size_t n) { index += n; return *this; } ring_buffer_iterator&amp; operator-=(size_t n) { return operator+=(-n); } template &lt;bool citer = const_iter, std::enable_if_t&lt;!citer, bool&gt; = true&gt; reference operator*() const { return ptr[index.as_index(N)]; } template &lt;bool citer = const_iter, std::enable_if_t&lt;citer, bool&gt; = true&gt; const_reference operator*() const { return ptr[index.as_index(N)]; } template &lt;bool citer = const_iter, std::enable_if_t&lt;!citer, bool&gt; = true&gt; reference operator[](difference_type n) { return *(*this + n); } const_reference operator[](difference_type n) const { return *(*this + n); } bool operator!=(ring_buffer_iterator other) const { return index != other.index; } bool operator==(ring_buffer_iterator other) const { return index == other.index; } friend ring_buffer_iterator operator+(const ring_buffer_iterator&amp; iter, size_t times) { return ring_buffer_iterator{iter.ptr, iter.index + times, iter.N}; } friend ring_buffer_iterator operator+(size_t times, const ring_buffer_iterator&amp; iter) { return ring_buffer_iterator{ iter.ptr, iter.index + times, iter.N }; } friend ring_buffer_iterator operator-(const ring_buffer_iterator&amp; lhs, size_t times) { return ring_buffer_iterator{lhs.ptr, lhs.index - times, lhs.N}; } friend difference_type operator-(const ring_buffer_iterator&amp; lhs, const ring_buffer_iterator&amp; rhs) { return static_cast&lt;difference_type&gt;(lhs.index - rhs.index); } }; template &lt;class T&gt; class ring_buffer { size_t N; mutable uninitialized_array&lt;T&gt; raw_buffer; ring_buffer_index read_pos, write_pos; T&amp; read_ptr() const { return raw_buffer[read_pos.as_index(N)]; } T&amp; write_ptr() const { return raw_buffer[write_pos.as_index(N)]; } bool will_remain_linearized(size_t num) { ring_buffer_index last_elem = write_pos + num - 1; return last_elem.as_index(N) &gt;= read_pos.as_index(N); } public: PROVIDE_CONTAINER_TYPES(T); using iterator = ring_buffer_iterator&lt;T&gt;; using const_iterator = ring_buffer_iterator&lt;T, false, true&gt;; using reverse_iterator = ring_buffer_iterator&lt;T, true&gt;; using const_reverse_iterator = const ring_buffer_iterator&lt;T, true, true&gt;; /* contrtuctors and assignment operators */ ring_buffer() : N{0} {} ring_buffer(size_t size) : N{ size }, raw_buffer { size } {} ring_buffer(ring_buffer&amp;&amp;) noexcept = default; ring_buffer(const ring_buffer&amp; other) { clear(); N = other.N; read_pos = other.read_pos; write_pos = other.write_pos; raw_buffer.copy(other.raw_buffer, N); } ring_buffer(std::initializer_list&lt;value_type&gt; init) : ring_buffer(init.size()) { std::uninitialized_copy(init.begin(), init.end(), raw_buffer.ptr()); } template &lt;class InputIterator&gt; ring_buffer(InputIterator first, InputIterator last) : ring_buffer(static_cast&lt;size_type&gt;(std::distance(first, last))) { std::uninitialized_copy(first, last, raw_buffer.ptr()); write_pos += capacity(); } ring_buffer&amp; operator=(ring_buffer&amp;&amp; other) noexcept { clear(); N = other.N; read_pos = other.read_pos; write_pos = other.write_pos; raw_buffer = std::move(other.raw_buffer); return *this; } ring_buffer&amp; operator=(const ring_buffer&amp; other) { clear(); N = other.N; read_pos = other.read_pos; write_pos = other.write_pos; raw_buffer.copy(other.raw_buffer, N); return *this; } ~ring_buffer() { clear(); } /* addition methods */ /* add at the back of the buffer , this is usually used rather than add at the front */ void push_back_without_checks(const value_type&amp; value) { emplace_back_without_checks(value); } void push_back_without_checks(value_type&amp;&amp; value) { emplace_back_without_checks(std::move(value)); } bool try_push_back(const value_type&amp; value) { return try_emplace_back(value); } bool try_push_back(value_type&amp;&amp; value) { return try_emplace_back(std::move(value)); } void push_back(const value_type&amp; value) { emplace_back(value); } void push_back(value_type&amp;&amp; value) { emplace_back(std::move(value)); } template &lt;class ...Args&gt; void emplace_back_without_checks(Args&amp;&amp; ... args) { new(&amp;write_ptr()) T(std::forward&lt;Args&gt;(args)...); ++write_pos; } template &lt;class ...Args&gt; bool try_emplace_back(Args&amp;&amp; ... args) { if (full()) return false; emplace_back_without_checks(std::forward&lt;Args&gt;(args)...); return true; } template &lt;class ...Args&gt; void emplace_back(Args&amp;&amp; ... args) { if (full()) pop_front(); emplace_back_without_checks(std::forward&lt;Args&gt;(args)...); } template &lt;class InputIterator&gt; void insert_back(InputIterator first, InputIterator last) { size_t num = static_cast&lt;size_t&gt;(std::distance(first, last)); if (will_remain_linearized(num)) { std::uninitialized_copy(first, last, &amp;write_ptr()); write_pos += num; } else std::copy(first, last, std::back_inserter(*this)); } /* add at the front of the buffer */ void push_front_without_checks(const value_type&amp; value) { emplace_front_without_checks(value); } void push_front_without_checks(value_type&amp;&amp; value) { emplace_front_without_checks(value); } bool try_push_front(const value_type&amp; value) { return try_emplace_front(value); } bool try_push_front(value_type&amp;&amp; value) { return try_emplace_front(value); } void push_front(const value_type&amp; value) { emplace_front(value); } void push_front(value_type&amp;&amp; value) { emplace_front(value); } template &lt;class ... Args&gt; void emplace_front_without_checks(Args&amp;&amp; ... args) { --read_pos; new (&amp;read_ptr()) T(std::forward&lt;Args&gt;(args)...); } template &lt;class ... Args&gt; bool try_emplace_front(Args&amp;&amp; ... args) { if (full()) return false; emplace_front_without_checks(std::forward&lt;Args&gt;(args)...); } template &lt;class ... Args&gt; void emplace_front(Args&amp;&amp; ... args) { if (full()) pop_back(); emplace_front_without_checks(std::forward&lt;Args&gt;(args)...); } template &lt;class InputIterator&gt; void insert_front(InputIterator first, InputIterator last) { std::copy(first, last, std::front_inserter(*this)); } /* extraction methods */ /* extract from the front of the buffer used with back insertion to make a FIFO queue */ void pop_front(value_type&amp; value) { auto&amp; elem = read_ptr(); value = std::move(elem); elem.~T(); ++read_pos; } bool try_pop_front(value_type&amp; value) { if (empty()) return false; pop_front(value); return true; } void pop_front() { read_ptr().~T(); ++read_pos; } bool try_pop_front() { if (empty()) return false; pop_front(); return true; } // dumps num of first elements into dest where dest points to initialized memory template &lt;class OutputIterator&gt; void pop_front(OutputIterator dest, size_t num) { move_from_front(dest, num); if constexpr (std::is_pod_v&lt;value_type&gt;) read_pos += num; else { while (num--) pop_front(); } } // dumps num of first elements into dest where dest points to uninitialized memory template &lt;class OutputIterator&gt; void pop_front(OutputIterator dest, size_t num, no_init_t) { move_from_front(dest, num, no_init); if constexpr (std::is_pod_v&lt;value_type&gt;) read_pos += num; else { while (num--) pop_front(); } } template &lt;class OutputIterator&gt; bool try_pop_front(OutputIterator dest, size_t num) { if (num &gt; size()) return false; pop_front(dest, num); return true; } template &lt;class OutputIterator&gt; bool try_pop_front(OutputIterator dest, size_t num, no_init_t) { if (num &gt; size()) return false; pop_front(dest, num, no_init); return true; } /* extract from the back of the buffer used with back insertion to make a LIFO queue */ void pop_back(value_type&amp; value) { --write_pos; auto&amp; elem = write_ptr(); value = std::move(elem); elem.~T(); } bool try_pop_back(value_type&amp; value) { if (empty()) return false; pop_back(value); return true; } void pop_back() { --write_pos; write_ptr().~T(); } bool try_pop_back() { if (empty()) return false; pop_back(); return true; } template &lt;class OutputIterator&gt; void pop_back(OutputIterator dest, size_t num) { move_from_back(dest, num); if constexpr (std::is_pod_v&lt;value_type&gt;) write_pos -= num; else { while (num--) pop_back(); } } template &lt;class OutputIterator&gt; void pop_back(OutputIterator dest, size_t num, no_init_t) { move_from_back(dest, num, no_init); if constexpr (std::is_pod_v&lt;value_type&gt;) write_pos -= num; else { while (num--) pop_back(); } } template &lt;class OutputIterator&gt; bool try_pop_back(OutputIterator dest, size_t num) { if (size() &lt; num) return false; pop_back(dest, num); return true; } template &lt;class OutputIterator&gt; bool try_pop_back(OutputIterator dest, size_t num, no_init_t) { if (size() &lt; num) return false; pop_back(dest, num, no_init); return true; } /* accesors */ reference front() { return read_ptr(); } reference back() { auto pos = write_pos; --pos; return raw_buffer[pos.as_index(N)]; } const_reference front() const { return read_ptr(); } const_reference back() const { auto pos = write_pos; --pos; return raw_buffer[pos.as_index(N)]; } reference operator[](size_type pos) noexcept { auto index = read_pos + pos; return raw_buffer[index.as_index(N)]; } const_reference operator[](size_type pos) const noexcept { auto index = read_pos + pos; return raw_buffer[index.as_index(N)]; } /* ^ ==&gt; read pointer &gt; ==&gt; write pointer data starts from read pointer to write pointer 1 - linearized (from empty to full) : there is one array starting from read pointer to write pointer -------------------------------------------------------------------------- | ^ | 1 | 2 | 3 | 4 | 5 | &gt; | | | | | | | | | | | | | | | | -------------------------------------------------------------------------- 2 - not linearized : the first array is from read pointer until the end of the buffer (last index N-1) the second array is from the start of the buffer until the write pointer -------------------------------------------------------------------------------------- | 6 | 7 | 8 | &gt; | | | | | | | | | | | | | | | | ^ | 1 | 2 | 3 | 4 | 5 | -------------------------------------------------------------------------------------- */ std::span&lt;value_type&gt; array_one() noexcept { pointer read_pointer = &amp;read_ptr(); if (is_linearized()) // or empty return std::span&lt;value_type&gt;{read_pointer, read_pointer + size()}; else return std::span&lt;value_type&gt;{read_pointer, raw_buffer.ptr() - read_pointer + size()}; } std::span&lt;const value_type&gt; array_one() const noexcept { pointer read_pointer = &amp;read_ptr(); if (is_linearized()) // or empty return std::span&lt;const value_type&gt;{read_pointer, read_pointer + size()}; else return std::span&lt;const value_type&gt;{read_pointer, raw_buffer.ptr() - read_pointer + size()}; } std::span&lt;value_type&gt; array_two() noexcept { if (is_linearized()) return {}; else { return std::span&lt;value_type&gt;{raw_buffer.ptr(), &amp;write_ptr()}; } } std::span&lt;const value_type&gt; array_two() const noexcept { if (is_linearized()) return {}; else { return std::span&lt;const value_type&gt;{raw_buffer.ptr(), &amp;write_ptr()}; } } void copy_from_front(value_type&amp; value) const { value = front(); } value_type copy_from_front() const { value_type value; copy_from_front(value); return value; } void move_from_front(value_type&amp; value) { value = std::move(front()); } value_type move_from_front() { value_type value; move_from_front(value); return value; } template &lt;class OutputIterator&gt; void copy_from_front(OutputIterator dest, size_t num) const { if (is_linearized()) { pointer begin_iter = &amp;read_ptr(); pointer end_iter = begin_iter + num; std::copy(begin_iter, end_iter, dest); } else { auto begin_iter = begin(); auto end_iter = begin_iter + num; std::copy(begin_iter, end_iter, dest); } } template &lt;class OutputIterator&gt; void copy_from_front(OutputIterator dest, size_t num, no_init_t) const { if (is_linearized()) { pointer begin_iter = &amp;read_ptr(); pointer end_iter = begin_iter + num; std::uninitialized_copy(begin_iter, end_iter, dest); } else { auto begin_iter = begin(); auto end_iter = begin_iter + num; std::uninitialized_copy(begin_iter, end_iter, dest); } } template &lt;class OutputIterator&gt; void move_from_front(OutputIterator dest, size_t num) { if (is_linearized()) { pointer begin_iter = &amp;read_ptr(); pointer end_iter = begin_iter + num; std::copy(std::make_move_iterator(begin_iter), std::make_move_iterator(end_iter), dest); } else { auto begin_iter = begin(); auto end_iter = begin_iter + num; std::copy(std::make_move_iterator(begin_iter), std::make_move_iterator(end_iter), dest); } } template &lt;class OutputIterator&gt; void move_from_front(OutputIterator dest, size_t num, no_init_t) { if (is_linearized()) { pointer begin_iter = &amp;read_ptr(); pointer end_iter = begin_iter + num; std::uninitialized_move(begin_iter, end_iter, dest); } else { auto begin_iter = begin(); auto end_iter = begin_iter + num; std::uninitialized_move(begin_iter, end_iter, dest); } } void copy_from_back(value_type&amp; value) const { value = back(); } value_type copy_from_back() const { value_type value; copy_from_back(value); return value; } void move_from_back(value_type&amp; value) { value = std::move(back()); } value_type move_from_back() { value_type value; move_from_back(value); return value; } template &lt;class OutputIterator&gt; void copy_from_back(OutputIterator dest, size_t num) const { if (is_linearized()) { pointer end_iter = &amp;write_ptr(); pointer first = end_iter - num; std::copy(first, end_iter, dest); } else { auto end_iter = end(); auto first = end_iter - num; std::copy(first, end_iter, dest); } } template &lt;class OutputIterator&gt; void copy_from_back(OutputIterator dest, size_t num, no_init_t) const { if (is_linearized()) { pointer end_iter = &amp;write_ptr(); pointer first = end_iter - num; std::uninitialized_copy(first, end_iter, dest); } else { auto end_iter = end(); auto first = end_iter - num; std::uninitialized_copy(first, end_iter, dest); } } template &lt;class OutputIterator&gt; void move_from_back(OutputIterator dest, size_t num) { if (is_linearized()) { pointer end_iter = &amp;write_ptr(); pointer first = end_iter - num; std::copy(std::make_move_iterator(first), std::make_move_iterator(end_iter), dest); } else { auto end_iter = end(); auto first = end_iter - num; std::copy(std::make_move_iterator(first), std::make_move_iterator(end_iter), dest); } } template &lt;class OutputIterator&gt; void move_from_back(OutputIterator dest, size_t num, no_init_t) { if (is_linearized()) { pointer end_iter = &amp;write_ptr(); pointer first = end_iter - num; std::uninitialized_move(first, end_iter, dest); } else { auto end_iter = end(); auto first = end_iter - num; std::uninitialized_move(first, end_iter, dest); } } /* range methods */ iterator begin() noexcept { return iterator{raw_buffer.ptr(), read_pos, N}; } iterator end() noexcept { return iterator{raw_buffer.ptr(), write_pos, N}; } const_iterator begin() const noexcept { return const_iterator{raw_buffer.ptr(), read_pos, N}; } const_iterator end() const noexcept { return const_iterator{raw_buffer.ptr(), write_pos, N}; } const_iterator cbegin() const noexcept { return begin(); } const_iterator cend() const noexcept { return end(); } reverse_iterator rbegin() noexcept { return reverse_iterator{ raw_buffer.ptr(), write_pos - 1, N }; } reverse_iterator rend() noexcept { return reverse_iterator{ raw_buffer.ptr(), read_pos - 1, N }; } const_reverse_iterator rbegin() const noexcept { return const_reverse_iterator{ raw_buffer.ptr(), write_pos - 1, N }; } const_reverse_iterator rend() const noexcept { return const_reverse_iterator{ raw_buffer.ptr(), read_pos - 1, N }; } const_reverse_iterator crbegin() const noexcept { return rbegin(); } const_reverse_iterator crend() const noexcept { return rend(); } /* eraser, linearization, resize and some info */ void clear() { if constexpr (std::is_pod_v&lt;value_type&gt;) { read_pos.reset(); write_pos.reset(); } else { while (!empty()) pop_front(); } } pointer linearize() { ring_buffer rbf(N); auto first_array = array_one(); rbf.insert_back(std::make_move_iterator(first_array.begin()), std::make_move_iterator(first_array.end())); auto second_array = array_two(); rbf.insert_back(std::make_move_iterator(second_array.begin()), std::make_move_iterator(second_array.end())); this-&gt;operator=(std::move(rbf)); return raw_buffer.ptr(); } template &lt;class OutputIterator&gt; void linearize(OutputIterator dest) const { auto first_array = array_one(); std::copy(first_array.begin(), first_array.end(), dest); auto second_array = array_two(); std::copy(second_array.begin(), second_array.end(), dest + first_array.size()); } void set_capacity(size_type Num) { clear(); N = Num; raw_buffer.resize(Num); } size_t capacity() const noexcept { return N; } size_t size() const noexcept { return write_pos - read_pos; } size_t available_size() const noexcept { return capacity() - size(); } size_t reserve() const noexcept { return available_size(); } bool full() const noexcept { return size() == capacity(); } bool empty() const noexcept { return !size(); } bool is_linearized() const noexcept { ring_buffer_index last_pos = write_pos - 1; return last_pos.as_index(N) &gt;= read_pos.as_index(N); } /* aliases to use the ring buffer as FIFO */ template &lt;class ...Args&gt; void emplace(Args&amp;&amp; ... args) { emplace_back(std::forward&lt;Args&gt;(args)...); } void push(const value_type&amp; value) { push_back(value); } void push(value_type&amp;&amp; value) { push_back(std::move(value)); } template &lt;class InputIterator&gt; void insert(InputIterator first, InputIterator last) { insert_back(first, last); } void pop(value_type&amp; value) { pop_front(value); } bool try_pop(value_type&amp; value) { return try_pop_front(value); } void pop() { pop_front(); } bool try_pop() { return try_pop_front(); } template &lt;class OutputIt&gt; void pop(OutputIt dest, size_t num) { pop_front(dest, num); } template &lt;class OutputIt&gt; void pop(OutputIt dest, size_t num, no_init_t) { pop_front(dest, num, no_init); } template &lt;class OutputIt&gt; bool try_pop(OutputIt dest, size_t num) { return try_pop_front(dest, num); } template &lt;class OutputIt&gt; bool try_pop(OutputIt dest, size_t num, no_init_t) { return try_pop_front(dest, num, no_init); } }; </code></pre> <p>The <code>span.h</code> header can be found <a href="https://github.com/some-coder366/ring-buffer/blob/master/span.h" rel="nofollow noreferrer">here</a>.</p> <p>I found it somewhere on the internet since some months ago, but I can't recall where did I get it from and as said in the title it's an implementation for the new C++ 20 <code>span</code> which represents a view for a range of contiguous memory, like <code>string_view</code>, but it enables to non <code>const</code> access the values if it isn't <code>const</code>.</p> <p>I want to know:</p> <ul> <li>Does the implementation misuse the concept of ring buffer?</li> <li>Do the iterators satisfy the C++ concept of iterators?</li> <li>Is there any drawbacks of using the indexes as counters and obtaining the real indexes with modulus especially for bigger values?</li> </ul>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-15T17:46:53.423", "Id": "453958", "Score": "2", "body": "The class `SomeClass` makes this question off-topic because it seems to be hypothetical. Is the class necessary to the question, and if it is could you better define it?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-15T17:52:15.793", "Id": "453959", "Score": "0", "body": "I don't understand what are you saying but I wrote it as an example to illustrate why I favored overwriting by destructing and constructing rather than by assigning . if you see it's better to reassign then I'll be pleased to hear your opinion" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-15T17:56:53.387", "Id": "453960", "Score": "1", "body": "The name of the class and possibly the usage makes it hypothetical. We review code and suggest how it can be improved. Reassigning versus destruction/construction might be considered opinion based and off-topic." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-15T18:01:15.350", "Id": "453961", "Score": "0", "body": "I don't know why it's off-topic . the boost's website claims that reassigning is more efficient" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-15T18:07:44.940", "Id": "453962", "Score": "0", "body": "https://codereview.stackexchange.com/help/how-to-ask and https://codereview.stackexchange.com/help/dont-ask." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-15T18:08:36.163", "Id": "453963", "Score": "0", "body": "@dev65 ^ Particularly check https://codereview.meta.stackexchange.com/a/3652" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-15T18:20:18.683", "Id": "453965", "Score": "0", "body": "but the page says : 'If your question was asking for a review of pseudocode, then we need you to post an implementation in a real programming language' and I don't ask about reassigning vs destruct/construct generally as each has its uses . instead I ask if the method I'm using in the code for ring buffer is better than reassigning" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-24T11:06:25.017", "Id": "455006", "Score": "0", "body": "Can you also add some test cases?" } ]
[ { "body": "<p>After some searching I found that my ring buffer is broken if its capacity isn't power of 2, because once the counter reaches its maximum (on 64-bit : 2^64 - 1) it will begin from zero the next increment so if the modulus of the counter by n isn't n-1 when it reaches the maximum unsigned integer of the architecture then the counter will misbehave because at the next step the remainder (index) will be 0 while the previous remainder (index) isn't n - 1</p>\n\n<p>this illustrates the problem :</p>\n\n<pre><code>constexpr uint64_t rem1 = std::numeric_limits&lt;uint64_t&gt;::max() % 13;\ncout &lt;&lt; \"rem1 = \" &lt;&lt; rem1 &lt;&lt; endl; // rem1 = 2\nconstexpr uint64_t rem2 = (std::numeric_limits&lt;uint64_t&gt;::max() + 1) % 13; // std::numeric_limits&lt;uint64_t&gt;::max() + 1 = 0\ncout &lt;&lt; \"rem2 = \" &lt;&lt; rem2 &lt;&lt; endl; // rem2 = 0 not 3 !\n</code></pre>\n\n<p>but for number n equals power of two the remainder will be n -1 at maximum value so no problem here</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-16T12:45:18.623", "Id": "232500", "ParentId": "232458", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-15T17:30:53.467", "Id": "232458", "Score": "2", "Tags": [ "c++", "collections", "c++17", "circular-list", "constant-expression" ], "Title": "C++ ring buffer using some C++ 17 and coming C++ 20 std::span" }
232458
<p>see: <a href="https://stackoverflow.com/questions/58882690/what-is-the-correct-way-to-pass-3-where-conditions-in-the-same-function-mult/58883277?noredirect=1#comment104033826_58883277">https://stackoverflow.com/questions/58882690/what-is-the-correct-way-to-pass-3-where-conditions-in-the-same-function-mult/58883277?noredirect=1#comment104033826_58883277</a> to better understand</p> <p>based on <a href="https://laravel.com/docs/5.7/queries#where-clauses" rel="nofollow noreferrer">laravel's documentation</a>, I came up with the following result:</p> <pre><code> public function loadpage($name, $page_name, $pcode) { $company = Company::where('name', $name)-&gt;first(); if ($company === null) { return view('company.not_register', compact('name')); } $page = Page::where([ ['name', $name], ['page_name', $page_name],])-&gt;first(); if ($page === null) { return view('company.pages.erros.404', compact('name', page)); } $pagecode = Page::where([ ['name', $name], ['page_name', $page_name], ['code', $pcode],])-&gt;first(); if ($pagecode === null) { return view('company.pages.erros.invalid_code', compact('company, name', page, pcode)); } $personality = DB::table('personalities')-&gt;where('name', $name)-&gt;first(); return view('company.pages.index', compact('company', 'name', 'personality', 'page', pcode)); } </code></pre> <p>now it's up to colleagues more experienced than me to see if that's right or is it possible to improve / simplify</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-15T19:44:47.040", "Id": "232461", "Score": "1", "Tags": [ "php", "mysql", "laravel", "eloquent" ], "Title": "what is the correct way to pass 3 where () conditions in the same function, multiple filters | eloquente - laravel" }
232461
<p>I have been trying to get the blob data from oracle into a zip file using Python. I couldn't find the answer on any of the other links. Below is the code:-</p> <pre><code>import cx_Oracle import numpy as np import pandas as pd con = cx_Oracle.connect("OPT", "OPT", "INDLIN1234:1521/OPTEPC1") cursor = con.cursor() sql_string = """SELECT F_name, F_released_data FROM epc_project where rownum&lt;5""" cursor.execute(sql_string) rows = cursor.fetchall() for row in rows: blobdata= np.array(row[1].read()) filename =str(row[0]) + ".zip" con.close() f = open(filename, "wb") binary_format = bytearray(blobdata) f.write(binary_format) f.close() </code></pre> <p>Getting below error:-</p> <pre><code> blobdata= np.array(row[1].read()) AttributeError: 'NoneType' object has no attribute 'read' </code></pre> <p>Please helpme out here</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-15T20:18:48.567", "Id": "453974", "Score": "1", "body": "Welcome to Code Review! Unfortunately your code is not quite ready for this site, since [we require that the code is working to the best of your knowledge](/help/on-topic). [so] might be a better place to look for help in your case. Be suce to check [their How to Ask page](https://stackoverflow.com/help/how-to-ask)." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-15T20:14:00.093", "Id": "232462", "Score": "1", "Tags": [ "python", "sql" ], "Title": "Blob data from Oracle to .zip file using python" }
232462
<pre><code>let formData = new FormData(); formData.append('File', document.file); formData.append('DocumentType', document.documentType); product = { ...values, productType: productT, }; for (var key in product) { if (key != 'createdDate' &amp;&amp; key != 'expirationDate') { formData.append(key, product[key]); } else { formData.append(key, new Date(product[key]).toUTCString()); } } await createproduct(formData); </code></pre> <p>I need to send file and other data about product in one request so I added all the stuffs in <code>FormData</code>, and I have issues only with <code>Dates</code>, I must convert it to <code>date</code> because somehow it get confused if I don't convert it.</p> <p>Can I somehow refactor this code to do this part about dates more elegant, <code>if condition</code> in <code>for loop</code> somehow smells bad..</p> <p>P.S EDIT:</p> <pre><code>for (var key in product) { const transform = DateTransformer[key]; formData.append(key, transform ? transform[product[key]] : product[key]); } </code></pre>
[]
[ { "body": "<h3>Transformation rules</h3>\n\n<p>Especially useful if there are many fields and each needs a unique rule.</p>\n\n<pre><code>const dateToUTCString = d =&gt; new Date(d).toUTCString();\n\nconst DataTransformer = {\n createdDate: dateToUTCString,\n expirationDate: dateToUTCString,\n};\n\n// [...]\n\nfor (const [key, calue] of Object.entries(product)) {\n const transform = DataTransformer[key];\n formData.append(key, transform ? transform(value) : value);\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-18T07:59:23.757", "Id": "454171", "Score": "0", "body": "I don't understand how this works.." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-18T08:54:43.337", "Id": "454176", "Score": "0", "body": "The code is a standard JavaScript so I'm not sure what to clarify." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-16T11:43:54.810", "Id": "232498", "ParentId": "232465", "Score": "1" } } ]
{ "AcceptedAnswerId": "232498", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-15T20:37:41.260", "Id": "232465", "Score": "1", "Tags": [ "javascript", "ecmascript-6", "react.js" ], "Title": "Adding values to FormData - javascript" }
232465
<p>I wrote a timer app in python using both twilio and the timer module; sends an sms to my phone after a certain amount of time has passed. While it works without a doubt, I wanted to gather some ideas/opinions on how to improve my program for efficiency, readability, etc...</p> <p>I'm open to all suggestions.</p> <pre><code>import time from twilio.rest import Client client = Client("KEY", "KEY") work_time = 20 * 60 break_time = 5 * 60 def _timer(workState = True): messageBody = ["Time to work", "Time to break"] if workState == True: client.messages.create(to="MYNUMBER", from_="TWILIONUMBER", body="Time To Work!") time.sleep(work_time) _timer(not workState) else: client.messages.create(to="MYNUMBER", from_="TWILIONUMBER", body="Time To Break!") time.sleep(break_time) _timer(not workState) _timer(False) </code></pre> <p>Please note: Several values have been changed for privacy sake (e.g. MYNUMBER, TWILIONUMBER, KEY)</p>
[]
[ { "body": "<p><strong><em>Ways of improving:</em></strong></p>\n\n<ul>\n<li><code>work_time</code> and <code>break_time</code> as constant values deserve to be defined as <em>CONSTANTS</em></li>\n<li><p><strong><code>_timer</code></strong> function:</p>\n\n<ul>\n<li><p><code>workState</code> should be renamed to <code>work_state</code> to follow naming conventions</p></li>\n<li><p><code>messageBody = [\"Time to work\", \"Time to break\"]</code> is not actually used (can be eliminated)</p></li>\n<li><code>if workState == True:</code> is just a verbose version of <code>if workState:</code></li>\n<li>both conditional branches <code>if/else</code> have the same common statement <code>_timer(not workState)</code> but differ in <strong><em>action</em></strong> name <code>work/break</code> and <strong><em>delay</em></strong> time <code>work_time/break_time</code>.<br>The whole condition can be restructured to reduce repetitive code and move the common statement(s) out</li>\n</ul></li>\n</ul>\n\n<hr>\n\n<p>The final optimized version:</p>\n\n<pre><code>import time\nfrom twilio.rest import Client\n\nclient = Client(\"KEY\", \"KEY\")\n\nWORK_TIME = 20 * 60\nBREAK_TIME = 5 * 60\n\n\ndef _timer(work_state=True):\n if work_state:\n action, delay_time = 'work', WORK_TIME\n else:\n action, delay_time = 'break', BREAK_TIME\n\n client.messages.create(to=\"MYNUMBER\", from_=\"TWILIONUMBER\", \n body=f\"Time To {action.title()}!\")\n time.sleep(delay_time)\n _timer(not work_state)\n\n\n_timer(False)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-15T21:57:57.357", "Id": "453981", "Score": "2", "body": "I appreciate the effort you put forward, thank you!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-15T21:47:53.277", "Id": "232469", "ParentId": "232467", "Score": "6" } }, { "body": "<p><a href=\"https://codereview.stackexchange.com/users/95789/\">RomanPerekhrest</a> has brought up several good points that you should definitely follow.</p>\n\n<p>One point that was not mentioned however, is the recursive way you call your <code>_timer(...)</code> function. As you may or may not know, Python has an upper limit on how many recursion levels are allowed. You can query the limit on your system using <code>sys.getrecursionlimit()</code> after <code>import sys</code>. Once you hit that limit, an exception will occur and end your program.</p>\n\n<p>Luckily for you, <code>time.sleep(...)</code> with the given intervals in your code is going to prevent you from hitting that limit during a normal workday. If I've not miscalculated, you would need to run your code for over 208h before getting in trouble (recursion limit of 1000 here on my machine, i.e. 500 cycles á 25min = 208,...h).</p>\n\n<p>But there are more good news here. You don't really need recursion! A simple iterative approach (based off of RomanPerekhrest's answer) should work equally well:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>import time\nfrom twilio.rest import Client\n\nWORK_TIME = 20 * 60\nBREAK_TIME = 5 * 60\n\n\ndef _timer(work_state=True):\n client = Client(\"KEY\", \"KEY\") # client does not need to be global any more\n while True:\n if work_state:\n action, delay_time = 'work', WORK_TIME\n else:\n action, delay_time = 'break', BREAK_TIME\n work_state = not work_state\n\n client.messages.create(to=\"MYNUMBER\", from_=\"TWILIONUMBER\", \n body=f\"Time To {action.title()}!\")\n time.sleep(delay_time)\n\n\nif __name__ == \"__main__\":\n _timer(False)\n</code></pre>\n\n<p>A few subtleties that I also changed: </p>\n\n<ul>\n<li><p>Since we are now always in the same function scope, <code>client</code> does not need to be a global variable anymore and can be moved into the function definition. </p></li>\n<li><p>Starting the timer is now surrounded by <code>if __name__ == \"__main__\":</code>. This line will make sure, that the code is <a href=\"https://docs.python.org/3/library/__main__.html\" rel=\"nofollow noreferrer\">only run if used as a script</a>, but not in case you would try to <code>import</code> something from that file.</p></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-15T22:52:29.077", "Id": "232471", "ParentId": "232467", "Score": "6" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-15T21:15:54.867", "Id": "232467", "Score": "5", "Tags": [ "python", "timer" ], "Title": "Productivity/Timer app that uses twilio to send SMS-reminders" }
232467
<p>If I have a method where the input is a list of integers, and within that method I convert the list to a list of strings, what is the best way to name the new list?</p> <p>For example (using <code>C#</code>):</p> <pre><code>public void DoSomething(IEnumerable&lt;int&gt; cheeseburgerToppingIds) { var cheeseburgerToppingIdsAsStrings = cheeseburgerToppingIds .Distinct() .OrderBy(p =&gt; p) .ToList() .ConvertAll(p =&gt; p.ToString()); // do some other stuff } </code></pre> <p>In this example, <code>cheeseburgerToppingIdsAsStrings</code> is descriptive, but also kind of clunky.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-15T22:33:28.393", "Id": "453985", "Score": "0", "body": "`var ids = ` and keep you method short, so it makes sense :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-16T07:10:20.387", "Id": "454006", "Score": "0", "body": "The code presented looks generic/hypothetical. Please replace it with actual code from a project where you encountered the problem." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-17T19:26:37.317", "Id": "454145", "Score": "0", "body": "@greybeard -- so, I see your point, but it is mostly hypothetical. But I'm not sure where to post this question. It will also get closed at https://softwareengineering.stackexchange.com/ because it's opinion-based. But I _want_ opinions!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-17T22:16:56.633", "Id": "454156", "Score": "1", "body": "Well, *hypothetical* is [explicitly off-topic here](https://codereview.stackexchange.com/help/on-topic)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-17T22:21:56.180", "Id": "454158", "Score": "0", "body": "(As an aside, this is one of the situations where I value languages with \"duck typing\". And all is lost where tradition mandates encoding parts of types in names as in `IEnumerable`.)" } ]
[ { "body": "<p>Seems like the context is really important, so I'm not sure your example is capturing it. If the critical difference between two variables is the type, and especially if they're both being used around each other, adding the type to the name is fine. If the issue that the ReallyLongName is obscuring the AsString suffix, I'd probably look for ways to extract the code into a simpler context where the long names aren't necessary. Like, maybe do the conversion to strings ahead of time and have this method take an <code>IEnumerable&lt;string&gt;</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-16T05:05:32.447", "Id": "453995", "Score": "1", "body": "Welcome to CodeReview. I see this as a decent answer to a question asked in an [off topic](https://codereview.stackexchange.com/help/on-topic) way: [off-topic questions should not be answered](https://codereview.stackexchange.com/help/how-to-answer). (It fails ***Is it actual code from a project** rather than pseudo-code or hypothetical code?*, and is one of the [types of questions to avoid asking: **Best practices in general**](https://codereview.stackexchange.com/help/dont-ask).)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-15T22:14:52.563", "Id": "232470", "ParentId": "232468", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-15T21:47:10.697", "Id": "232468", "Score": "-1", "Tags": [ "c#", "converting" ], "Title": "Naming convention when converting between types?" }
232468
<p>I would like to be specific in parameter types or write something like this:</p> <pre><code>Test test = (Json&lt;Test&gt;)"{\"age\": 46}"; </code></pre> <p>Where:</p> <pre><code>public class Test { public int Age { get; set; } } </code></pre> <p>My helper is:</p> <pre><code>public struct Json&lt;T&gt; { public static implicit operator string(Json&lt;T&gt; json) =&gt; json.JObject.ToString(); public static explicit operator Json&lt;T&gt;(string json) =&gt; new Json&lt;T&gt;(json); public static implicit operator T(Json&lt;T&gt; json) =&gt; json.JObject.ToObject&lt;T&gt;(); public static implicit operator Json&lt;T&gt;(T obj) =&gt; new Json&lt;T&gt;(JObject.FromObject(obj)); static readonly JObject Default = JObject.FromObject(new { }); Json(string json) : this(JObject.Parse(json)) { } Json(JObject jObject) : this() =&gt; _jObject = jObject ?? throw new ArgumentNullException(nameof(jObject)); JObject JObject =&gt; _jObject ?? Default; readonly JObject _jObject; } </code></pre>
[]
[ { "body": "<p>The missing part is a <code>JsonConverter</code>:</p>\n\n<pre><code>[JsonConverter(typeof(JsonTConverter))]\npublic struct Json&lt;T&gt; \n{\n</code></pre>\n\n<p>And:</p>\n\n<pre><code>public class JsonTConverter : JsonConverter\n{\n public override bool CanConvert(Type objectType) =&gt;\n objectType.IsConstructedGenericType &amp;&amp;\n objectType.GetGenericTypeDefinition() == typeof(Json&lt;&gt;);\n\n public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) =&gt;\n Activator.CreateInstance(objectType, reader.Value);\n\n public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) =&gt;\n writer.WriteValue(value.ToString());\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-16T00:35:22.387", "Id": "232473", "ParentId": "232472", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-15T23:58:17.070", "Id": "232472", "Score": "2", "Tags": [ "c#", "json", "json.net" ], "Title": "Strictly typed JSON representation" }
232472
<p>I was told to create a 2D array from a txt file that had the "carModel, carColor" followed by a new line. The 2D array is 8x8 and for each time a certain carmore and carcolor appear, their respective [x][y] coordinate that represents their count goes up by 1.</p> <p>So far, I have read the file, created a 2D array from the file, and have created an output with the 2D array and every slot filled with zero, but the only way I can seem to figure out to update each model,color count is if I manually make 64 if-statements to check if they appear in the list n+ times. Surely there has to be another way?</p> <p>For example, When my scanner reads through the list, I need it to check if the list repeats the carmodel, carcolor and if so, update the count of that carmake and color.</p> <p>This is the code I have thus far:</p> <pre><code>public static void main (String [] args) throws Exception { String [][] cars = new String [8][8]; ArrayList &lt;String&gt; colors = new ArrayList&lt;&gt;(); colors.add("BLUE "); colors.add("BLACK "); colors.add("BROWN "); colors.add("GREEN "); colors.add("RED "); colors.add("SILVER"); colors.add("WHITE "); Collections.sort(colors); ArrayList &lt;String&gt; models = new ArrayList&lt;&gt;(); models.add("Escape "); models.add("Explorer"); models.add("F150 "); models.add("F250 "); models.add("Flex "); models.add("Mustang "); models.add("Taurus "); Collections.sort(models); cars [0][0] = "_____ "; for (int a = 1; a &lt; cars.length; a++) { cars[0][a] = (models.get(a-1)) + " "; } for (int b = 1; b &lt; cars.length; b++) { cars[b][0] = (colors.get(b-1)) + " "; } for (int fir = 1; fir &lt; cars.length; fir++) { for (int sec = 1; sec &lt; cars[1].length; sec++) { if (cars[fir][sec] == null) { cars[fir][sec] = "0 "; } } } for (int first = 0; first &lt; cars.length; first++) { for (int second = 0; second &lt; cars[first].length; second++) { System.out.print(cars[first][second]); } System.out.println(); } File file = new File ("C:\\Users\\delta\\Documents\\NetBeansProjects\\SchoolWork\\cars.txt"); Scanner sc = new Scanner(file); String ab = sc.nextLine(); while (ab != null) { String [] nums = sc.nextLine().split(" "); for (int i = 0; i &lt; nums.length;i++) { System.out.println(nums[i]); } } } </code></pre> <p>The output is supposed to look something like this:</p> <p><a href="https://i.stack.imgur.com/P2SWm.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/P2SWm.png" alt="enter image description here"></a></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-16T01:48:59.173", "Id": "453990", "Score": "1", "body": "What is a \"carmore?\" Do you mean car model? And \"carcolor\" should be two words." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-16T01:53:24.190", "Id": "453991", "Score": "0", "body": "I'm confused where the \"64 if statements\" come into play here. Also I *think* your instructor may have intended you to use a `Map` rather than `ArrayList`, but you had better ask them about that." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-16T02:30:59.737", "Id": "453993", "Score": "0", "body": "@markspace unfortunately we have not gone over maps at all, the 64 if statements would be manually checking each options, example: create a Set of every carmodel,carcolor and say for each index if that set.contains(carmodel,carcolor) then int carmodelcarcolo +=1, which would require me to manually do that for EVERY single option" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-16T05:26:21.320", "Id": "453998", "Score": "0", "body": "Welcome to CodeReview. Unfortunately, your question is about a part of your code that is not yet written: [off topic with Code Review@SE](https://codereview.stackexchange.com/help/on-topic)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-16T05:30:04.823", "Id": "453999", "Score": "0", "body": "(Ah, and please prefer block-quoting text over inserting a pixel raster in your posting - for one thing, pixel rasters will not be found by text searches for years to come.)" } ]
[ { "body": "<ul>\n<li><a href=\"https://docs.oracle.com/javase/7/docs/api/java/util/Arrays.html#asList(T...)\" rel=\"nofollow noreferrer\">Consider using <code>Arrays.asList(\"\", ...)</code> to create lists in-line.</a></li>\n<li>Why are <code>colors</code> and <code>models</code> Lists while <code>cars</code> is an Array? It seems like you can use Arrays for all of this.</li>\n<li><a href=\"https://www.geeksforgeeks.org/anonymous-array-java/\" rel=\"nofollow noreferrer\">Consider using \"anonymous arrays\" (terrible name) to create Arrays in-line.</a> </li>\n<li>Consider first building the \"true\" data structure as <code>int[][] car_counts = new int[7][7]</code>, a zero-indexed 2D array of counts. Then treat the task of printing it as shown in the image as a separate problem. </li>\n<li>Your while loop at the end appears to be incorrectly indented.</li>\n<li>That while loop should be building a data-structure that you can neatly read the file into: a list of pairs of strings. (or even a list of pairs of ints, representing indexes into <code>models</code> and <code>colors</code>.)</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-16T18:04:34.533", "Id": "232513", "ParentId": "232474", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-16T00:37:34.143", "Id": "232474", "Score": "1", "Tags": [ "java", "array" ], "Title": "Creating a 2D array from a txt file" }
232474
<p>I was learning some DOM manipulation and interaction with third-party APIs by building a simple interface to get the people who commented on a PR on GitHub.</p> <p>I got great feedback for my initial prototype: <a href="https://codereview.stackexchange.com/questions/232195/interface-for-getting-github-prs-commenters-using-github-api">Interface for getting Github PRs commenters using Github API</a>.</p> <p>Now I am trying to get into OOP using ES6 Classes, so I build this GitHubPR class to handle all the interaction with the GitHub API:</p> <pre><code>const apiUrl = 'https://api.github.com' export default class GitHubPR { constructor(prUrl) { GitHubPR.validatePRUrl(prUrl) this.prUrl = new URL(prUrl) this.prApiUrl = GitHubPR.prUrlToApiEndpoint(prUrl) } static validatePRUrl(prUrl) { if (!GitHubPR.isValidPRUrl(prUrl)) { throw new Error('Not a valid GitHub Pull Request Url.') } return prUrl } static isValidPRUrl(prUrl) { const githubPullRequestPattern = RegExp( /^https:\/\/github.com\/[\w-_.+]+\/[\w-_.+]+\/pull\/\d+\/?$/ ) return githubPullRequestPattern.test(prUrl) } static prUrlToApiEndpoint(prUrl) { GitHubPR.validatePRUrl(prUrl) const { pathname } = new URL(prUrl) const prApiUrl = new URL( `/repos${pathname.replace('/pull/', '/pulls/')}`, apiUrl ) return prApiUrl } static async fetch(endpoint) { const apiOptions = { headers: { Accept: 'application/vnd.github.v3+json', }, } const url = endpoint.startsWith(apiUrl) ? endpoint : `${apiUrl}${endpoint}` return (await fetch(url, apiOptions)).json() } fetchInfo() { return GitHubPR.fetch(this.prApiUrl.pathname) } fetchReviews() { return GitHubPR.fetch(`${this.prApiUrl.pathname}/reviews`) } async fetchReviewers() { const reviews = await GitHubPR.fetch(`${this.prApiUrl.pathname}/reviews`) const uniqueReviewers = [...new Set(reviews.map(review =&gt; review.user.url))] return Promise.all( uniqueReviewers.map(reviewer =&gt; GitHubPR.fetch(reviewer)) ) } } </code></pre> <p>I would love to have some feedback on this. I am new to OOP and ES6 classes, so not sure if this is following good practices or if I am making good use for a class here, or how could I make this class more robust according to OOP principles.</p> <p>My idea is being able to use it in something like this:</p> <pre><code>import GitHubPR from './github-pr' document .querySelector('#pull-request-form') .addEventListener('submit', onsubmit) async function onsubmit(event) { event.preventDefault() const pr = new GitHubPR(document.querySelector('#pull-request-url').value) const [info, reviewers] = await Promise.all([ pr.fetchInfo(), pr.fetchReviewers(), ]) renderInfo(info) renderReviewers(reviewers) } </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-16T01:56:33.167", "Id": "232475", "Score": "1", "Tags": [ "javascript", "object-oriented", "ecmascript-6" ], "Title": "ES6 Class for getting GitHub PR info" }
232475
<p>A small script that simply prints a given string. It's an improved snippet that combines some recommendations given in my post on <a href="https://codereview.stackexchange.com/questions/232221/string-helper-functions-in-nasm-win16-assembly">string helper functions</a>.</p> <pre><code>org 100h mov si, hello call puts ret puts: jmp .run .putc: mov ah, 0Eh mov bx, 7 int 10h .run: lodsb cmp al, 0 jne .putc ret hello db "Hello World!", 0 </code></pre>
[]
[ { "body": "<p>You have all the elements. The only thing that can be eliminated is <strong>jmp .run</strong>, as follows:</p>\n\n<pre><code>org 0x100\n\n mov si, Prompt\n call puts\n ret\n\n puts: mov ah, 0xe\n mov bx, 7\n .read: lodsb\n or al, al\n jnz .post \n ret\n .post: int 0x10\n jmp .read\n\n Prompt: db 'Hello World', 0\n</code></pre>\n\n<p>As INT 10H does not trash AH or BX, there is no need to reinitialize them each time through the loop.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-16T04:33:14.023", "Id": "453994", "Score": "1", "body": "Use `TEST reg, reg` to check for zero in preference to `OR reg, reg`, since the former is more likely to fuse with the conditional branch. I also find it more readable." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-16T07:58:49.177", "Id": "454013", "Score": "0", "body": "@CodyGray I agree, as `test` is more representative of what is being done and I think that's what you mean by more readable. Whereas `or` implies AL is being modified for some other reason." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-16T17:24:27.353", "Id": "454052", "Score": "0", "body": "I interpret \"trashing\" as having a value reset to some default value. Would this be accurate? If so, Is there a way to efficiently determine if an interrupt trashes a register? I've been using [HelpPC](http://www.stanislavs.org/helppc/idx_interrupt.html) as a reference for interrupts, and there's no mention of trashing." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-16T17:42:46.447", "Id": "454053", "Score": "0", "body": "I use `trashing` in the context that a register has been modified by an interrupt, function or subroutine where its value upon return is indeterminate. As to the reference your using, I think it would be safe to say that if nothing is returned, then nothing is modified either or it specifically states returned values." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-16T04:29:28.293", "Id": "232481", "ParentId": "232476", "Score": "6" } } ]
{ "AcceptedAnswerId": "232481", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-16T02:15:27.780", "Id": "232476", "Score": "4", "Tags": [ "strings", "windows", "assembly", "nasm" ], "Title": "Printing a string in NASM Win16 Assembly" }
232476
<p>I am working on writing a discrete random variable generator function in excel vba. I've pulled this off a number of ways but here is the one I like the most.</p> <p>Imagine in excel we have the following in cells A1:B3</p> <pre><code>red 5 blue 7 yellow 3 </code></pre> <p>The following code is modeled as follows. Imagine drawing a line going from 0 to 15 (where 15 is 5 + 7 + 3). The line is red from [0,5) and blue from [5,12) and yellow from [12,15). And you pick a uniformly distributed random number, x, from 0 to 15. And wherever on the line x falls, that is the color that wins.</p> <p>Here is the function:</p> <pre><code>Function discrete(r1 As Range, r2 As Range) 'shrink column ranges to contiguous cells Set r1 = Range(r1(1), r1(1).End(xlDown)) Set r2 = Range(r2(1), r2(1).End(xlDown)) 'convert ranges to arrays Dim arr1, arr2 As Variant arr1 = r1.Value arr2 = r2.Value Dim n As Long n = Application.Sum(arr2) 'sum total of 2nd array Dim x As Double x = n * Rnd() 'generate a random number 0 &lt;= x &lt; n Dim min, max As Double min = 0 max = 0 Dim i As Long For i = LBound(arr1, 1) To UBound(arr1, 1) 'where on the line x falls max = max + arr2(i, 1) If x &gt;= min And x &lt; max Then discrete = arr1(i, 1) End If min = min + arr2(i, 1) Next i End Function </code></pre> <p>I'm looking for some critique of my code and approach.</p> <ol> <li><p>Assuming I'm not picking from 1000 values (column a), is it reasonable that I convert the ranges to arrays? Is this a time saving step? Or should I just work with the ranges? What I mean is, does this step pay for itself computationally given that I may always be working with only a few rows of data? Or might it be worth it solely on that basis that I may indeed supply this function with large ranges?</p></li> <li><p>Even if you supply a full column, ie. <code>discrete(range("a:a"), range("b:b"))</code>, the range inside the function is reset to only those cells that are contiguous starting from the first cells of the supplied ranges. Is that a reasonable approach?</p></li> <li><p>The algorithm itself relies on a for loop and 2 simple variables (min, max). I this a lightweight enough approach? Or are there some generally accepted practices I'm not aware of?</p></li> </ol>
[]
[ { "body": "<h2>Option Explicit</h2>\n\n<p><code>Option explicit</code>. <strong><em>Always</em></strong>.</p>\n\n<h2>Strong typing</h2>\n\n<p>VBA facilitates strong typing. This should be used because it stops VBA guessing at types which improves performance and reduces the chance of coding errors. Especially as some types/objects have default values that are not well documented!</p>\n\n<p>This is a function, so what does it return? At the moment, it returns a <code>Variant</code> which might be OK, but your code does not reflect this requirement.</p>\n\n<pre><code>Public Function discrete(r1 As Range, r2 As Range) As String\n</code></pre>\n\n<p>If you want it to be <code>Variant</code>, then be explicit and state that!</p>\n\n<p>Also, another gotcha is the way variables are declared. The following lines are not doing what you think they are doing:</p>\n\n<pre><code>Dim arr1, arr2 As Variant\nDim min, max As Double\n</code></pre>\n\n<p>In these lines, both the first variables are not declared and thus they default to <code>Variant</code>. Again, if you want a variable to be a <code>Variant</code>, then be explicit (like you tried to be in the first line above). What you really wanted was:</p>\n\n<pre><code>Dim arr1 As Variant, arr2 As Variant\nDim min As Double, max As Double\n</code></pre>\n\n<p>By the way, <strong>kudos</strong> for declaring variables near where you are using them.</p>\n\n<h2>Proper qualification</h2>\n\n<p>Always put proper qualification on your objects. Excel uses defaults for things that are not properly qualified - the active sheets and cells may not be what you want! Especially in a UDF and you could have multiple workbooks open!</p>\n\n<pre><code>Range(r2(1), r2(1).End(xlDown))\n</code></pre>\n\n<p>should be</p>\n\n<pre><code>wb.ws.Range(r2(1), r2(1).End(xlDown)) ' wb and ws is something you define here - more notes below.\n</code></pre>\n\n<h2>Default value for <code>discrete</code></h2>\n\n<p>You only set the value for <code>discrete</code> in a conditional (<code>If</code>) statement in a loop. What if it never fires? What would you like the user to see?</p>\n\n<p>A simple option is to set a default value at the beginning - the most obvious is an error message. For this to work, the UDF should return a variant:</p>\n\n<pre><code>Public Function discrete(r1 As Range, r2 As Range) As Variamt\n discrete = CVErr(xlErrValue) '&lt;-- pick an error value to suit yourself\n</code></pre>\n\n<p>Now that we have set that up - what are some other ways this can fail?</p>\n\n<ul>\n<li>user picks ranges that re not one column wide?</li>\n<li>user picks two ranges that are a different size?</li>\n</ul>\n\n<p>Now you can test for this early and then exit the function - the default value will be an error and the user will have an indicator of this.</p>\n\n<h2>Altering the parameters</h2>\n\n<p>This is bad:</p>\n\n<pre><code>Function discrete(r1 As Range, r2 As Range)\n […]\n Set r1 = Range(r1(1), r1(1).End(xlDown))\n</code></pre>\n\n<p>A big no-no. You should always consider the parameters on a UDF as immutable. If you want to reset the ranges, then use a temporary variable within the Function scope (e.g. <code>Dim tempRange1 as Range</code>).</p>\n\n<p>However, you are double-guessing the user. What if they did not want to go to the end of the page? What if they had other stuff under the table?</p>\n\n<p>By doing this manipulation, you are increasing the chances that the value arrays will be mismatched. <code>arr1(found,1)</code> may no longer have an equivalent <code>arr2(found,1)</code>!</p>\n\n<h2>Working with arrays</h2>\n\n<p>Yes, always practice working with arrays where you can. Even replace the <code>Application.Sum</code> call. You can never tell when your user is going to set up a 1000-value discrete array!</p>\n\n<h2>Some suggestions</h2>\n\n<ol>\n<li>Use only a single range in the UDF call (<code>Public Function\ndiscrete(twoColTable As Range) As Variant</code>. This reduces the\nopportunity for user error. You array will be two columns\n<code>arr(found,1)</code> will correspond with <code>arr(found,2)</code></li>\n<li>Check your user input immediately for size and values to make sure\nyou are getting what you think you should. If column count does not\nequal 2, or your second column is not ascending numbers then exit\nwith an error.</li>\n<li>Traverse the array from beginning until you find a value that is\ngreater then your <code>n</code>. The value you want will be the one before you hit that value (i.e. go back one array index). Alternatively, traverse the array from the end until you find a value that is not greater than your <code>n</code>. This way, you do not need <code>max</code> or <code>min</code>.</li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-16T19:03:03.267", "Id": "454061", "Score": "0", "body": "You've brought up a lot of interesting points. In fact all your major points give me something to think about and improve not just for my code above but in general." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-18T17:22:07.150", "Id": "454261", "Score": "0", "body": "Puzzling indeed" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-26T02:33:04.097", "Id": "455203", "Score": "0", "body": "@AJD OMG, sorry. I just realized this I inadvertently down voted this answer. Lesson learned, don't hand your toddler your phone with SO open in the background. Nice answer BTW :) +1" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-26T18:45:08.033", "Id": "455307", "Score": "0", "body": "@RyanWildry :-)" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-16T06:05:02.557", "Id": "232486", "ParentId": "232482", "Score": "4" } } ]
{ "AcceptedAnswerId": "232486", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-16T04:34:14.510", "Id": "232482", "Score": "1", "Tags": [ "algorithm", "vba", "excel" ], "Title": "excel vba discrete random variable udf" }
232482
<p>I have implemented a simple calculator using the Shunting Yard algorithm. It takes infix expression as an input "3 + 5 * 2", which evaluates and returns the value 13.</p> <pre><code>public class ShuntingYardAlgorithm{ private static Map&lt;String, Operator&gt; operatorMap = initializeOperatorMap(); private static Map&lt;String, Operator&gt; initializeOperatorMap() { operatorMap = new HashMap&lt;&gt;(); operatorMap.put(Operator.ADD.sign, Operator.ADD); operatorMap.put(Operator.SUBTRACT.sign, Operator.SUBTRACT); operatorMap.put(Operator.MULTIPLY.sign, Operator.MULTIPLY); operatorMap.put(Operator.DIVIDE.sign, Operator.DIVIDE); return operatorMap; } public ShuntingYardAlgorithm() { // Default Constructor } private enum Operator { ADD(1, "+"), SUBTRACT(2, "-"), MULTIPLY(3, "*"), DIVIDE(4, "/"); final int precedence; final String sign; Operator(int precedence, String sign) { this.precedence = precedence; this.sign = sign; } } private static boolean isHighPrecedence(String currentToken, String peekedOperator) { return operatorMap.containsKey(peekedOperator) &amp;&amp; operatorMap.get(peekedOperator).precedence &gt;= operatorMap.get(currentToken).precedence; } public static Integer evaluateExpression(String infix) { Stack&lt;String&gt; operatorStack = new Stack&lt;&gt;(); Stack&lt;Integer&gt; outputStack = new Stack&lt;&gt;(); for (String currentToken : infix.split("\\s")) { if ("(".equalsIgnoreCase(currentToken)) { operatorStack.push(currentToken); } else if (operatorMap.containsKey(currentToken)) { while (!operatorStack.isEmpty() &amp;&amp; isHighPrecedence(currentToken, operatorStack.peek())) { String higherPrecedenceOperator = operatorStack.pop(); Integer operandLeft = outputStack.pop(); Integer operandRight = outputStack.pop(); outputStack.push(evaluate(operandLeft, operandRight, higherPrecedenceOperator)); } operatorStack.push(currentToken); } else if (currentToken.equalsIgnoreCase(")")) { while (!"(".equalsIgnoreCase(operatorStack.peek())) { String higherPrecedenceOperator = operatorStack.pop(); Integer operandLeft = outputStack.pop(); Integer operandRight = outputStack.pop(); outputStack.push(evaluate(operandLeft, operandRight, higherPrecedenceOperator)); } operatorStack.pop(); } else { outputStack.push(Integer.valueOf(currentToken)); } } while (!operatorStack.empty()) { String higherPrecedenceOperator = operatorStack.pop(); Integer operandRight = outputStack.pop(); Integer operandLeft = outputStack.pop(); outputStack.push(evaluate(operandLeft, operandRight, higherPrecedenceOperator)); } return outputStack.pop(); } private static Integer evaluate(Integer operandLeft, Integer operandRight, String operator) { BigDecimal retVal = BigDecimal.ZERO; BigDecimal left = BigDecimal.valueOf(operandLeft); BigDecimal right = BigDecimal.valueOf(operandRight); if (operator.equals(Operator.MULTIPLY.sign)) { retVal = left.multiply(right); } else if (operator.equals(Operator.ADD.sign)) { retVal = left.add(right); } else if (operator.equals(Operator.SUBTRACT.sign)) { retVal = left.subtract(right); } else if (operator.equals(Operator.DIVIDE.sign)) { retVal = left.divide(right); } return retVal.intValue(); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-17T09:59:27.087", "Id": "454119", "Score": "0", "body": "the code return wrong values for input `\"1 * 5 - 3\"`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-18T16:41:48.420", "Id": "454255", "Score": "1", "body": "Since it was a minor bug I took the liberty to just fix it in your question. See edit revision to figure out what exactly I changed :)" } ]
[ { "body": "<p>Minor remarks:</p>\n\n<ul>\n<li><p>The java convention is to put the opening { on the same line, not on a new line. It's great that you're consistent in your style though!</p></li>\n<li><p>If you're doing the calculations using BigDecimal anyway, why not do that all the way and store the intermediat values as BigDecimal's as well in your stack?</p></li>\n<li><p>method name <code>isHighPrecedence</code> wasn't immediately clear to me which one was the higher precedence. Not sure how to fix this one easily though.</p></li>\n</ul>\n\n<p>Bigger idea:</p>\n\n<p>I like how you used an enum for the Operators. This gives a nice list of all the possible (known) operators and an easy place to check if things like precedence are implemented correctly.</p>\n\n<p>What I would do though, is go a step further. In java, an Enum is still a full class (except that all instances are created on class loading, you can't create new instances). This means that you can also provide methods there. I would expect the precedence comparison to be put in there. Although initially this might still be a bit clunky with the bracket handling (more on that later).</p>\n\n<p>Another nice candidate is parsing an operator from a string. This can easily be implemented as follows:</p>\n\n<pre><code> public static Operator from(String oper) {\n for (Operator operator : Operator.values()) {\n if (operator.sign.equalsIgnoreCase(oper)) {\n return operator;\n }\n }\n return NIL;\n }\n</code></pre>\n\n<p>What most people don't know, is that you can also override methods for each of the instances. The evaluate is a perfect candidate for this one. For example:</p>\n\n<pre><code>private enum Operator\n{\n ADD(1, \"+\") {\n @Override\n public BigDecimal evaluate(BigDecimal left, BigDecimal right) {\n return left.add(right);\n }\n },\n SUBTRACT(2, \"-\") {\n @Override\n public BigDecimal evaluate(BigDecimal left, BigDecimal right) {\n return left.subtract(right);\n }\n },\n ... [include all operators here]\n };\n\n final int precedence;\n final String sign;\n\n Operator(int precedence, String sign)\n {\n this.precedence = precedence;\n this.sign = sign;\n }\n\n public abstract BigDecimal evaluate(BigDecimal left, BigDecimal right);\n</code></pre>\n\n<p>That way, if you have an operator you can just call<br>\n<code>outputStack.push(higherPrecedenceOperator.evaluate(operandLeft, operandRight));</code></p>\n\n<p>Changing the operator stack to actually contain <code>Operator</code> instead of <code>String</code> got me in a little bit of trouble storing the opening bracket on there. Since the idea is to first parse the operand from the input string, let's also add an Operand for the closing bracket, and a default option for a missing operand (that we can abuse for number inputs as well).</p>\n\n<pre><code> OPEN_BRACKET(0, \"(\") {\n @Override\n public BigDecimal evaluate(BigDecimal left, BigDecimal right) {\n throw new IllegalStateException(\"Cannot apply bracket operand to left and right numbers\");\n }\n },\n CLOSE_BRACKET(0, \")\") {\n @Override\n public BigDecimal evaluate(BigDecimal left, BigDecimal right) {\n throw new IllegalStateException(\"Cannot apply bracket operand to left and right numbers\");\n }\n },\n NIL(0, \"\") {\n @Override\n public BigDecimal evaluate(BigDecimal left, BigDecimal right) {\n throw new IllegalStateException(\"trying to evaluate invalid operator\");\n }\n };\n</code></pre>\n\n<p>updating the <code>evaluateExpression</code> method to work with Operators required a little bit of reordering to handle the numbers correctly again:</p>\n\n<pre><code>public static BigDecimal evaluateExpression(String infix)\n{\n Stack&lt;Operator&gt; operatorStack = new Stack&lt;&gt;();\n Stack&lt;BigDecimal&gt; outputStack = new Stack&lt;&gt;();\n\n for (String currentToken : infix.split(\"\\\\s\"))\n {\n Operator currentOperator = Operator.from(currentToken);\n if (currentOperator == Operator.OPEN_BRACKET)\n {\n operatorStack.push(currentOperator);\n } else if (currentOperator==Operator.CLOSE_BRACKET)\n {\n while (Operator.OPEN_BRACKET.equals(operatorStack.peek())) {\n Operator higherPrecedenceOperator = operatorStack.pop();\n BigDecimal operandLeft = outputStack.pop();\n BigDecimal operandRight = outputStack.pop();\n outputStack.push(higherPrecedenceOperator.evaluate(operandLeft, operandRight));\n }\n operatorStack.pop();\n } else if (currentOperator != Operator.NIL)\n {\n while (!operatorStack.isEmpty() &amp;&amp; operatorStack.peek().isHigherPrecedence(currentOperator)) {\n Operator higherPrecedenceOperator = operatorStack.pop();\n BigDecimal operandLeft = outputStack.pop();\n BigDecimal operandRight = outputStack.pop();\n outputStack.push(higherPrecedenceOperator.evaluate(operandLeft, operandRight));\n }\n operatorStack.push(currentOperator);\n } else\n {\n outputStack.push(BigDecimal.valueOf(Integer.valueOf(currentToken)));\n }\n }\n\n while (!operatorStack.empty())\n {\n Operator higherPrecedenceOperator = operatorStack.pop();\n BigDecimal operandRight = outputStack.pop();\n BigDecimal operandLeft = outputStack.pop();\n outputStack.push(higherPrecedenceOperator.evaluate(operandLeft, operandRight));\n\n }\n return outputStack.pop();\n}\n</code></pre>\n\n<p>This got me thinking. What do we have to change to allow the bracket operantors to just evaluate similarly to the other operators instead? We could first update the current evaluate method to take the outputStack instead of a left and right operand. That way the Operator can decide how many numbers it needs. Specifically for the brackets, we also need to pass in the Operator stack so that the opening bracket can just push itself on the stack, and the closing bracket can pop the stack untill it finds an opening bracket.</p>\n\n<pre><code>private enum Operator {\n ADD(1, \"+\") {\n @Override\n public void evaluate(Stack&lt;BigDecimal&gt; numbers, Stack&lt;Operator&gt; operatorStack) {\n BigDecimal right = numbers.pop();\n BigDecimal left = numbers.pop();\n numbers.push(left.add(right));\n }\n },\n SUBTRACT(2, \"-\") {\n @Override\n public void evaluate(Stack&lt;BigDecimal&gt; numbers, Stack&lt;Operator&gt; operatorStack) {\n BigDecimal right = numbers.pop();\n BigDecimal left = numbers.pop();\n numbers.push(left.subtract(right));\n }\n },\n MULTIPLY(3, \"*\") {\n @Override\n public void evaluate(Stack&lt;BigDecimal&gt; numbers, Stack&lt;Operator&gt; operatorStack) {\n BigDecimal right = numbers.pop();\n BigDecimal left = numbers.pop();\n numbers.push(left.multiply(right));\n }\n },\n DIVIDE(4, \"/\") {\n @Override\n public void evaluate(Stack&lt;BigDecimal&gt; numbers, Stack&lt;Operator&gt; operatorStack) {\n BigDecimal right = numbers.pop();\n BigDecimal left = numbers.pop();\n numbers.push(left.divide(right));\n }\n },\n OPEN_BRACKET(Integer.MIN_VALUE, \"(\") {\n @Override\n public void evaluate(Stack&lt;BigDecimal&gt; numbers, Stack&lt;Operator&gt; operatorStack) {\n operatorStack.push(this);\n }\n },\n CLOSE_BRACKET(Integer.MAX_VALUE, \")\") {\n @Override\n public void evaluate(Stack&lt;BigDecimal&gt; numbers, Stack&lt;Operator&gt; operatorStack) {\n while (!operatorStack.isEmpty() &amp;&amp; operatorStack.peek() != OPEN_BRACKET) {\n operatorStack.pop().evaluate(numbers, operatorStack);\n }\n if (operatorStack.isEmpty()) {\n //no open bracket found!\n throw new IllegalStateException(\"closing bracket requires earlier matching opening bracket\");\n }\n operatorStack.pop();\n }\n },\n NIL(0, \"\") {\n @Override\n public void evaluate(Stack&lt;BigDecimal&gt; numbers, Stack&lt;Operator&gt; operatorStack) {\n throw new IllegalStateException(\"trying to evaluate invalid operator\");\n }\n };\n\n private final int precedence;\n private final String sign;\n\n Operator(int precedence, String sign) {\n this.precedence = precedence;\n this.sign = sign;\n }\n\n public static Operator from(String oper) {\n for (Operator operator : Operator.values()) {\n if (operator.sign.equalsIgnoreCase(oper)) {\n return operator;\n }\n }\n return NIL;\n }\n\n public boolean isHigherPrecedence(Operator other) {\n return this.precedence &lt;= other.precedence;\n }\n\n public abstract void evaluate(Stack&lt;BigDecimal&gt; numbers, Stack&lt;Operator&gt; operatorStack);\n}\n</code></pre>\n\n<p>Quick note that I also updated the priority values for the open and close brackets so that they're handled correctly while going through the stack. This way we can greatly simplify the <code>evaluateExpression</code> implementation as well:</p>\n\n<pre><code>public static BigDecimal evaluateExpression(String infix) {\n Stack&lt;Operator&gt; operatorStack = new Stack&lt;&gt;();\n Stack&lt;BigDecimal&gt; outputStack = new Stack&lt;&gt;();\n\n for (String currentToken : infix.split(\"\\\\s\")) {\n Operator currentOperator = Operator.from(currentToken);\n if (currentOperator == Operator.NIL) { //number (or error from unknown operator?)\n outputStack.push(BigDecimal.valueOf(Integer.valueOf(currentToken)));\n } else {\n while (!operatorStack.isEmpty() &amp;&amp; !operatorStack.peek().isHigherPrecedence(currentOperator)) {\n Operator higherPrecedenceOperator = operatorStack.pop();\n higherPrecedenceOperator.evaluate(outputStack, operatorStack);\n }\n operatorStack.push(currentOperator);\n }\n }\n\n while (!operatorStack.empty()) {\n operatorStack.pop().evaluate(outputStack, operatorStack);\n }\n return outputStack.pop();\n}\n</code></pre>\n\n<p>The best part about implementing the Operators this way? We can easily add new operators, and they're not limited to 2 operands either! For example, adding the following Operand to the enum class:</p>\n\n<pre><code> ABS(5, \"abs\") {\n @Override\n public void evaluate(Stack&lt;BigDecimal&gt; numbers, Stack&lt;Operator&gt; operatorStack) {\n numbers.push(numbers.pop().abs());\n }\n },\n</code></pre>\n\n<p>is all we need to do to then input things like \"abs -2\" which gets resolved to \"2\".</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-18T18:49:08.293", "Id": "232608", "ParentId": "232483", "Score": "3" } } ]
{ "AcceptedAnswerId": "232608", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-16T04:46:38.380", "Id": "232483", "Score": "4", "Tags": [ "java", "algorithm", "calculator" ], "Title": "Calculator using Shunting Yard algorithm" }
232483
<p>I have implemented Prim's Algorithm from Introduction to Algorithms. I have observed that the code is similar to Dijkstra's Algorithm, so I have used my <a href="https://github.com/programmercave0/Algo-Data-Structure/blob/master/Dijkstra%20Algorithm/C%2B%2B/dijkstra.cpp" rel="nofollow noreferrer">Dijkstra's Algorithm</a> implementation.</p> <p>Please review this code and suggest improvements.</p> <p>To compile on Linux: <code>g++ -std=c++14 prims.cpp</code></p> <pre><code>#include &lt;iostream&gt; #include &lt;map&gt; #include &lt;limits&gt; #include &lt;list&gt; #include &lt;queue&gt; class Graph { struct Vertex { std::size_t id; int distance = std::numeric_limits&lt;int&gt;::max(); Vertex * parent = nullptr; Vertex(std::size_t id) : id(id) {} }; using pair_ = std::pair&lt;std::size_t, int&gt;; std::vector&lt;Vertex&gt; vertices = {}; //adjacency list , store src, dest, and weight std::vector&lt; std::vector&lt; pair_&gt; &gt; adj_list; //to store unprocessed vertex min-priority queue std::priority_queue&lt; pair_, std::vector&lt;pair_&gt;, std::greater&lt;pair_&gt; &gt; unprocessed; public: Graph(std::size_t size); void add_edge(std::size_t src, std::size_t dest, int weight); void prim(std::size_t vertex); std::size_t minimum_cost() ; }; Graph::Graph(std::size_t size) { vertices.reserve(size); adj_list.resize(size); for (int i = 0; i &lt; size; i++) { vertices.emplace_back(i); } } void Graph::add_edge(std::size_t src , std::size_t dest, int weight) { if(weight &gt;= 0) { if (src == dest) { throw std::logic_error("Source and destination vertices are same"); } if (src &lt; 0 || vertices.size() &lt;= src) { throw std::out_of_range("Enter correct source vertex"); } if (dest &lt; 0 || vertices.size() &lt;= dest) { throw std::out_of_range("Enter correct destination vertex"); } int flag = 0, i = src; for (auto&amp; it : adj_list[i]) { if (it.first == dest) { flag = 1; break; } } if (flag == 0) { adj_list[src].push_back( {dest, weight} ); } else { throw std::logic_error("Existing edge"); } } else { std::cerr &lt;&lt; "Negative weight\n"; } } void Graph::prim(std::size_t vertex) { vertices[vertex].distance = 0; vertices[vertex].parent = &amp;vertices[vertex]; unprocessed.push( std::make_pair(vertices[vertex].distance, vertex) ); while (!unprocessed.empty()) { int curr_vertex_dist = unprocessed.top().first; std::size_t curr_vertex = unprocessed.top().second; unprocessed.pop(); for (auto&amp; ver: adj_list[curr_vertex]) { auto&amp; next_dist = vertices[ver.first].distance; const auto curr_dist = ver.second; if (curr_dist &lt; next_dist) { next_dist = curr_dist; //make src vertex parent of dest vertex vertices[ver.first].parent = &amp;vertices[curr_vertex]; unprocessed.push( std::make_pair(next_dist, ver.first)); } } } } std::size_t Graph::minimum_cost() { std::size_t cost = 0; for (auto vertex: vertices) { cost = cost + vertex.distance; } return cost; } int main() { Graph grp(9); grp.add_edge(0, 1, 4); grp.add_edge(0, 2, 8); grp.add_edge(1, 2, 11); grp.add_edge(1, 3, 8); grp.add_edge(3, 4, 2); grp.add_edge(4, 2, 7); grp.add_edge(2, 5, 1); grp.add_edge(5, 4, 6); grp.add_edge(3, 6, 7); grp.add_edge(3, 8, 4); grp.add_edge(5, 8, 2); grp.add_edge(6, 7, 9); grp.add_edge(6, 8, 14); grp.add_edge(7, 8, 10); grp.prim(0); std::cout &lt;&lt; "The total cost is : " &lt;&lt; grp.minimum_cost() &lt;&lt; "\n"; } </code></pre>
[]
[ { "body": "<h3>1. Keeping references to potentially dangling pointers</h3>\n\n<p>I can see a potential problem with the line</p>\n\n<pre><code>vertices[ver.first].parent = &amp;vertices[curr_vertex];\n</code></pre>\n\n<p>if the <code>std::vector&lt;Vertex&gt; vertices</code> would be reorganised due to changes in length.\nThe address you take there isn't stable.</p>\n\n<p>Maybe a better solution would be to keep a </p>\n\n<pre><code>std::vector&lt;std::unique_ptr&lt;Vertex&gt;&gt; vertices;\n</code></pre>\n\n<p>instead of keeping copies of the <code>Vertex</code> instances.</p>\n\n<p>Then you can change </p>\n\n<pre><code>vertices[ver.first].parent = &amp;vertices[curr_vertex];\n</code></pre>\n\n<p>to</p>\n\n<pre><code>vertices[ver.first].parent = vertices[curr_vertex].get();\n</code></pre>\n\n<p>Since all the vertices are in private scope of the <code>Graph</code> class the <code>std::unique_ptr&lt;Vertex&gt;</code> instances stored to the <code>vertices</code> vector will never invalidate, as long you guarantee to remove all child <code>Vertex</code> instances when a parent <code>Vertex</code> instane is removed from the graph (Well, that's not an operation in question here, but needs to be considered for production code).</p>\n\n<h3>2. Inconsistent error handling</h3>\n\n<p>Here</p>\n\n<pre><code>else\n{\n std::cerr &lt;&lt; \"Negative weight\\n\";\n}\n</code></pre>\n\n<p>you just use kind of errorneous input being reported to the console, while you throw exceptions for other cases.</p>\n\n<p>For this condition you should rather do</p>\n\n<ul>\n<li>throwing an exception</li>\n<li>applying an <code>assert()</code> call in 1st place</li>\n<li><p><strong>clarify from the function signature</strong></p>\n\n<p>If <em>Negative weight</em> is erroneous input you should make that clear in 1st place:</p>\n\n<pre><code> void Graph::add_edge(std::size_t src , std::size_t dest, unsigned weight)\n // ^^^^^^^^\n</code></pre>\n\n<p>This way violations would be covered by the compiler, before runtime detects that flaw.</p></li>\n</ul>\n\n<h3>3. Storing unnecessary information</h3>\n\n<p>In your code example <code>parent</code> is never used besides storing the information. I am aware that you might have been simplified the actual usage of <code>parent</code> with this review question, but with the code context you give, that member variable doesn't make any sense.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-16T08:42:58.243", "Id": "454015", "Score": "0", "body": "I do not understand. Here we are making a node/vertex as a parent to other node/vertex." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-16T08:46:24.307", "Id": "454016", "Score": "0", "body": "@coder As mentioned, the address you take there isn't stable. It points to an element address in that `std::vector`. As soon this `std::vector` will be resized, that address is invalidated." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-16T09:12:23.467", "Id": "454017", "Score": "1", "body": "@coder I realized that using `std::reference_wrapper` won't work either. `std::unique_ptr` seems to be the right tool to express ownership here." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-16T12:17:18.070", "Id": "454026", "Score": "1", "body": "`std::unique_ptr` is not the right tool. The right tool is `std::size_t`. The problem with the invalidation of iterators/references can be completely alleviated by storing the index of the member and not a reference to it. The only thing necessary is then to call `operator[]`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-16T12:24:33.020", "Id": "454027", "Score": "0", "body": "@miscco Feel free to write another answer with some example code." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-16T07:58:54.113", "Id": "232492", "ParentId": "232485", "Score": "3" } } ]
{ "AcceptedAnswerId": "232492", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-16T05:56:13.070", "Id": "232485", "Score": "2", "Tags": [ "c++", "c++11", "graph", "c++14" ], "Title": "Prim's Algorithm - Minimum Spanning Tree" }
232485
<p>I was doing container with most water question in Leetcode for which I wrote this algorithm </p> <p>Question link: <a href="https://leetcode.com/problems/container-with-most-water" rel="nofollow noreferrer">https://leetcode.com/problems/container-with-most-water</a></p> <p>Question: </p> <blockquote> <p>Given n non-negative integers a1, a2, ..., an , where each represents a point at coordinate (i, ai). n vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0). Find two lines, which together with x-axis forms a container, such that the container contains the most water.</p> <p>Note: You may not slant the container and n is at least 2.</p> </blockquote> <p>Input: [1,8,6,2,5,4,8,3,7] </p> <pre><code>/** * @param {number[]} height * @return {number} */ var maxArea = function(height) { let currentHighest=0 while(height.length) { const num = height.shift() let j=0 while(j&lt;height.length) { const lowerNum = Math.min(num, height[j]) const distance = j+1 const area = distance * lowerNum currentHighest = Math.max(currentHighest, area) j++ } } return currentHighest }; </code></pre> <p>but it appears so this code isn't opimized, Can someone help me in optimizng the above code?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-16T07:49:44.207", "Id": "454012", "Score": "0", "body": "In your solution you destroy the input array. Is it required, allowed or unwanted?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-16T08:11:57.120", "Id": "454014", "Score": "0", "body": "Nope but it reduces the iterations for inside array" } ]
[ { "body": "<p>Ok, so I made implementation very similar to yours with these modifications:</p>\n\n<ul>\n<li>input is not being destroyed (althout it can still be adjusted to destroy it, but it just feels like such algorithm should not do this)</li>\n<li>I compute maximum potential container area for values as I iterate them from left</li>\n<li>I iterate the inner loop from end towards front</li>\n<li>I use the potential to reduce the number of iterations of the inner loop.</li>\n</ul>\n\n<pre><code>function maxArea (input)\n{\n // result value will go here\n let currentMax = 0;\n\n // we will need this value at least 2*(n-1) times:\n const limit = input.length - 1;\n\n // i&lt;limit because having i=limit would always yield zero size container so skip it:\n for(let i = 0; i &lt; limit; ++i) {\n const left = input[i];\n\n // zero size edge always yields zero size container so move to next i\n // this check may be omitted as the next will exclude it as well\n //if (left == 0) continue;\n\n // the largest container we can have on the right has this area:\n let potential = left * (limit - i);\n\n // if potential is not enough to get over currentMax, just move to next i\n if (potential &lt;= currentMax) continue;\n\n // search from end towards i becase more distant j is more likely to yield larger container and only the last j can actualy yield current potential\n for (let j = limit; j &gt; i; --j) {\n const right = input[j];\n\n // if right is at least as high as left then this container has the area equal to potential and no other j will do better for current left value\n if (right &gt;= left) {\n currentMax = potential;\n break;\n }\n\n // if it is smaller we check if its area is greater then currentMax and use it if it is\n const area = right * (j - i);\n if (area &gt; currentMax) currentMax = area;\n\n //decrease potential by 1 times left value because we will reduce distance by 1 for next iteration (--j):\n potential -= left;\n\n // if new potential is not enough to get over currentMax we can stop searching further j's and move to next i\n if (potential &lt;= currentMax) break;\n }\n }\n return currentMax;\n}\n</code></pre>\n\n<p>In conjuction this algorithm is still (like yours) O(n^2) in time and O(1) in space. But it is a better n^2 then yours, I believe. And (unlike yours) the actual performance will be different for different input values, not only for different lengths of the input array. It is same as yours in worst case (ie strictly decreasing sequence) and actualy O(n) in best case (ie increasing sequence). And of course anywhere in between for most of the possible variations of input values.</p>\n\n<p>EDIT: hehe ok I benched it on random 100k value arrays and mine takes about 4ms, yours 15+ seconds :) The worst case scenario is about 15 seconds yours, 7 seconds mine. But the worst case scenario is very small set of all posibilities, so to get it from randomness is very unlikely. Randomness holds it on few ms. So improvement by factor of several thousands for random 100k value inputs :)</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-16T08:43:22.450", "Id": "232493", "ParentId": "232488", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-16T06:52:56.687", "Id": "232488", "Score": "3", "Tags": [ "javascript", "programming-challenge" ], "Title": "Leetcode container with most water" }
232488
<p>The fact is that a material object must have a field that does not make sense to an immaterial object</p> <p>Here is a class whose objects I want to divide into material and immaterial:</p> <pre><code>public class GameObject { protected boolean isHidden; protected Coordinate position; protected int pictureWidth, pictureHeight; public Object filling; protected GameObject(int pictureWidth, int pictureHeight, Coordinate position, boolean isHidden, Color filling){ this.position = position; this.pictureWidth = pictureWidth; this.pictureHeight = pictureHeight; this.isHidden = isHidden; this.filling = filling; } protected GameObject(Coordinate position, boolean isHidden, BufferedImage filling){ this.position = position; this.pictureWidth = filling.getWidth(); this.pictureHeight = filling.getHeight(); this.isHidden = isHidden; this.filling = filling; } protected GameObject(GameObject gameObject) throws IOException{ this.position = new Coordinate(gameObject.getPosition()); this.pictureWidth = gameObject.getPictureWidth(); this.pictureHeight = gameObject.getPictureHeight(); this.isHidden = gameObject.isHidden(); this.filling = gameObject.getFilling(); // передается ссылка } private GameObject getGameObject() { return this; } public void paint(Graphics gr) throws IOException{ if(filling instanceof BufferedImage) { gr.drawImage((Image) filling, position.getX(), position.getY(), null); } else if(filling instanceof Color) { gr.setColor((Color) filling); gr.fillRect(position.getX(), position.getY(), pictureWidth, pictureHeight); } else { System.err.println("programmer, you forgot to add a way to draw this object"); } } Object getFilling() { return filling; } int getPictureWidth() { return pictureWidth; } int getPictureHeight() { return pictureHeight; } boolean isHidden() { return isHidden; } Coordinate getPosition() { return position; } } </code></pre> <p>I suppose that you need to create 2 classes that inherit GameObject, and make the constructor of the GameObject class visible only for these two classes:</p> <p>1) class MaterialGameObject:</p> <pre><code> public class MaterialGameObject extends GameObject{ final int materialHeight; public MaterialGameObject(int materialHeight, int pictureWidth, int pictureHeight, Coordinate position, boolean isHidden, Color filling){ super(pictureWidth, pictureHeight, position, isHidden, filling); this.materialHeight = materialHeight; } public MaterialGameObject(int materialHeight, Coordinate position, boolean isHidden, BufferedImage filling){ super(position, isHidden, filling); this.materialHeight = materialHeight; } public MaterialGameObject(MaterialGameObject materialGameObject) throws IOException{ super(materialGameObject.getGameObject()); this.materialHeight = materialGameObject.getMaterialHeight(); } public int getMaterialHeight() { return materialHeight; } } </code></pre> <p>class ImMaterialGameObject:</p> <pre><code>public class ImMaterialGameObject extends GameObject{ public ImMaterialGameObject(int pictureWidth, int pictureHeight, int materialHeight, Coordinate position, boolean isHidden, Color filling){ super(pictureWidth, pictureHeight, position, isHidden, filling); } public ImMaterialGameObject(Coordinate position, boolean isHidden, BufferedImage filling){ super(position, isHidden, filling); } public ImMaterialGameObject(GameObject gameObject) throws IOException{ super(gameObject); } } </code></pre> <p><strong>Do you know a better way to solve the problem?</strong></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-16T21:00:50.063", "Id": "454069", "Score": "0", "body": "It's hard to offer alternatives to your problem without knowing what this is used for exactly. Could you provide an example of these GameObjects in use?" } ]
[ { "body": "<p><code>getGameObject</code> - Never used. You should remove it. You can always use <code>this</code>, no need to have a function. If you meant for this to be <code>protected</code>, still remove it. Again use the object, no need to have a function.</p>\n\n<p><code>ImMaterialGameObject</code> - Unless \"Im\" stands for something, <code>Immaterial</code> is one word.</p>\n\n<p><code>public Object filling;</code> - You've obviously noticed all classes in Java extend from Object. Taking advantage of this is hackey. Instead you could use 2 separate fields and check if one or the other is null.</p>\n\n<p><strong>Onto the question \"Is there a better approach?\"</strong></p>\n\n<p>Without knowing what you're using this for, I'd say there's nothing wrong with your approach. To make things more clear, set <code>GameObject</code> to <code>abstract</code>. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-16T17:20:59.090", "Id": "454051", "Score": "0", "body": "yes, i agree, it should be moved to GameObject. The fact is that the class material gameObject contains a field that an immaterial gameObject should not have. That is why I create the class material gameObject. U cannot use empty class - \"Implicit super constructor GameObject() is undefined for default constructor. Must define an explicit constructor\"" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-16T18:07:02.173", "Id": "454055", "Score": "0", "body": "@Miron you would have to change the `GameObject`'s constructor to `public`. You may also need to define a default constructor as your error message suggests. (A constructor with no arguments)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-16T19:31:24.207", "Id": "454063", "Score": "0", "body": "no, I want to prohibit the creation of an instance of the GameObject, since I already have a division that takes into account all the options (material, immaterial). In any case - why did we then create class constructors if we do not call them from a subclass? Creating an empty object should be prohibited, since the object must have coordinates, its own way of rendering." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-16T21:16:51.320", "Id": "454074", "Score": "0", "body": "@Miron I've updated my answer." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-17T05:22:51.440", "Id": "454112", "Score": "0", "body": "1) Yes, useful note. I did like this: super(materialGameObject); because MaterialGameObject is a subclass of GameObject.\n2) it is \"Immaterial\".\n3) But if the number of rendering methods increases greatly? Will you multiply entities? In any case, an undeclared variable cannot get into the object, and if it does, then we throw an error when trying to draw.\n4) i agree, the abstractness of a class fully describes its essence and satisfies my needs." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-17T05:58:49.033", "Id": "454114", "Score": "0", "body": "hm, сan I call a class abstract if there are no abstract methods in it? Should I call a class abstract only so that I cannot create an object of this class? I still tend to use protected constructors." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-17T16:22:40.567", "Id": "454131", "Score": "0", "body": "@Miron Yes you can have an abstract class without abstract methods. Nothing wrong with having protected constructors, you could even leave them protected and have an abstract class. Having it abstract makes it obvious the class should not be instantiated from directly. For example, the error message is more clear" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-17T16:54:47.870", "Id": "454132", "Score": "0", "body": "in continuation of this topic ... https://codereview.stackexchange.com/questions/232551/a-new-type-of-builder-pattern" } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-16T16:53:21.050", "Id": "232509", "ParentId": "232490", "Score": "1" } }, { "body": "<h1>Naming</h1>\n\n<p>I assume that you are program a game which has multiple instances of <code>GameObject</code>.</p>\n\n<p>Imagine we are program a chess game:<br>\nThere are two <code>players</code> which play on a <code>board</code> with multiple <code>pieces</code> on it.<br>\nSince <em>Chess</em> is the context, I don't need to prefix all words with <code>Chess</code>: <strike><code>Chess</code></strike><code>player</code>, <strike><code>Chess</code></strike><code>board</code> and <strike><code>Chess</code></strike><code>piece</code>.</p>\n\n<p>Now to your scenario:<br>\nSince the context is a <em>Game</em> the prefix <em>Game</em> in <code>GameObject</code> is redundant.</p>\n\n<h1>To Generell</h1>\n\n<blockquote>\n <pre class=\"lang-java prettyprint-override\"><code>public class GameObject {\n\n // ...\n public Object filling;\n\n // ...\n\n public void paint(Graphics gr) throws IOException{\n if(filling instanceof BufferedImage) {\n gr.drawImage((Image) filling, position.getX(), position.getY(), null);\n }\n else if(filling instanceof Color) {\n gr.setColor((Color) filling);\n gr.fillRect(position.getX(), position.getY(), pictureWidth, pictureHeight);\n } else {\n System.err.println(\"programmer, you forgot to add a way to draw this object\");\n }\n }\n\n // ...\n}\n</code></pre>\n</blockquote>\n\n<p>The <code>Object filling</code> is to generell. We should create an abstract <code>DrawTechnique</code> which separate te:</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>public class GameObject {\n\n // ...\n public Drawable drawable;\n\n // ...\n\n public void paint(Graphics gr) throws IOException {\n drawable.drawOn(gr);\n }\n\n // ...\n}\n\nclass Image implements Drawable {\n\n /*...*/\n\n @Override\n public void drawOn(Graphics gr) { /*...*/ }\n\n}\n\nclass Color implements Drawable {\n\n /*...*/\n\n @Override\n public void drawOn(Graphics gr) { /*...*/ }\n\n}\n</code></pre>\n\n<p>By using <a href=\"https://en.wikipedia.org/wiki/Polymorphism_(computer_science)\" rel=\"nofollow noreferrer\">polymorphism</a> you achieve a more flexible way: We don't need <code>if</code>-branches, is more type-save, we can add a new <code>Drawable</code>-type without modifying <code>GameObject</code>. Without polymorphism we need to add a new <code>if</code>-branch to check if it is a type we want to draw.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-18T10:57:56.397", "Id": "454186", "Score": "0", "body": "the fact is that the number of parameters for the fill method is different. So the interface cannot be used. for example, a BufferedImage should not use width and height for rendering." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-18T10:48:39.740", "Id": "232582", "ParentId": "232490", "Score": "0" } } ]
{ "AcceptedAnswerId": "232509", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-16T07:36:41.540", "Id": "232490", "Score": "2", "Tags": [ "java", "object-oriented" ], "Title": "This divides the class of game objects into material and immaterial" }
232490
<p>I have implemented a stack in Python 3, and it works well. If anything needs to be improved, I would appreciate the criticism.</p> <pre><code>class Stack: def __init__(self): self.stack = [] def isEmpty(self): return self.stack == [] def push(self, data): self.stack.append(data) def pop(self): data = self.stack[-1] del self.stack[-1] return data def peek(self): return self.stack[-1] def sizeStack(self): return len(self.stack) stack = Stack() stack.push(1) stack.push(2) stack.push(3) print(stack.sizeStack()) print("Popped: ", stack.pop()) print("Popped: ", stack.pop()) print(stack.sizeStack()) print("Peek:", stack.peek()) print(stack.sizeStack()) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-16T20:44:50.107", "Id": "454064", "Score": "14", "body": "You didn't implement a stack, you just delegate everything to a python list, which already implements a stack. See @rightleg answer." } ]
[ { "body": "<p>Overall looks good. Your code does assume the user is keeping accurate track of the state of the stack. I don't know the domain you're in here but that's something to keep in mind.<br>\nSome stack implementations throw a specific exception for this scenario. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-16T09:57:32.540", "Id": "232495", "ParentId": "232494", "Score": "1" } }, { "body": "<p>On the whole the code is good, but I would look for three improvements:</p>\n\n<ol>\n<li><strong>Information-hiding:</strong> I would change <code>self.stack</code> to <code>self._stack</code> to indicate to readers of the code that this is an implementation detail that should not be accessed directly. Reasons:\n\n<ol>\n<li>Mutating <code>self.stack</code> directly, for example <code>self.stack.insert(2, 42)</code> could break the expectations a client would have of the stack.</li>\n<li>You might choose to use a different data structure in the future, so clients that depended on <code>self.stack</code> being a <code>list</code> would fail.</li>\n</ol></li>\n<li><strong>Error handling:</strong> popping or peeking on an empty stack will raise an <code>IndexError</code>. It might be friendlier to raise a custom <code>EmptyStackError</code>, although a bare <code>IndexError</code> could still be ok, depending on ...</li>\n<li><strong>Documentation:</strong> ideally the code would have docstrings in accordance with <a href=\"https://www.python.org/dev/peps/pep-0257/\" rel=\"noreferrer\">PEP-257</a>. Failing that, comments in the <code>pop</code> and <code>peek</code> methods explaining that an exception will occur on an empty stack are helpful to the reader, and document that the behaviour is intentional rather than a bug.</li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-19T07:46:17.800", "Id": "454306", "Score": "0", "body": "You seem to believe that in Python, information hiding is a goal in itself. [I would like to contest that.](https://mail.python.org/pipermail/tutor/2003-October/025932.html). If someone does (1), he's probably got a good reason for it, and otherwise deserves the exceptions he's gonna get. If someone wants (2), you can do exactly that with properties later on. Is there a place for `_name` in Python? Yes. But not for these reasons." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-19T13:54:58.900", "Id": "454355", "Score": "0", "body": "@Gloweye If I don't want people to rely on an implementation detail of my code, I use the [private variable](https://docs.python.org/3/tutorial/classes.html#private-variables) convention to indicate that to readers of the code. As you say, it's up to them to respect the convention or not. On (2), I don't see how a property would help - if the replacement data structure's API differed from `list` code that relied on the `list` API would still break." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-19T14:02:24.577", "Id": "454358", "Score": "0", "body": "A property can help because you can intercept the getting of `obj.name` and do whatever you want with it. Like return a proxy object with a list interface, if you care about that. But it's mostly that in basic python design, I think classes should be as simple as possible. Part of the beauty of python is that you don't -have- to make that sort of future considerations, because you don't lose any possibilities with NOT doing it. You're free to disagree, of course." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-16T10:44:32.763", "Id": "232496", "ParentId": "232494", "Score": "14" } }, { "body": "<p>The code is clean. My major concern with how it looks is that your naming doesn't follow PEP8. <a href=\"https://www.python.org/dev/peps/pep-0008/#function-and-variable-names\" rel=\"nofollow noreferrer\">Names should be snake_case, not camelCase.</a> So <code>isEmpty</code> should be <code>is_empty</code>.</p>\n\n<p>With how it works, I'd work on giving it consistent behavior with other collections.</p>\n\n<p>Right now, you have a <code>sizeStack</code> method for returning the size. This should really be <a href=\"https://docs.python.org/3/reference/datamodel.html#object.__len__\" rel=\"nofollow noreferrer\"><code>__len__</code></a> instead:</p>\n\n<pre><code>def __len__(self):\n return len(self.stack)\n</code></pre>\n\n<p>Why? Because now you can do this:</p>\n\n<pre><code>stack = Stack()\nstack.push(1)\nstack.push(2)\nstack.push(3)\nprint(len(stack)) # Prints 3\n</code></pre>\n\n<p>You can now check the length using <code>len</code> like you can with <code>list</code> and other built-ins. <code>__len__</code> and other methods that start and end with two underscores are \"\"magic\"\"; they have special meanings behind the scenes. Here for example, <code>len</code> just delegates to a classes's <code>__len__</code> method. I'd recommend looking over that page I linked to.</p>\n\n<p><code>isEmptys</code> could also be made a little more idiomatic by making use of the fact that empty lists are falsey:</p>\n\n<pre><code>def is_empty(self):\n return not self.stack\n</code></pre>\n\n<p>The major advantage here is nearly all collections are falsey when empty. With how you have it now, if you change what underlying structure your class uses, you'll need to remember to update the <code>is_empty</code> method, or <code>self.stack == []</code> will always fail.</p>\n\n<p>And instead of having an <code>is_empty</code> method, it's more idiomatic to just have a <code>__bool__</code> method so your stack can be treated as a boolean value. See <a href=\"https://codereview.stackexchange.com/a/232563/46840\">this</a> answer to see how that can be done. </p>\n\n<hr>\n\n<p>And <code>list</code> actually already has a <code>pop</code> method that does what you want. Your <code>pop</code> can just be:</p>\n\n<pre><code>def pop(self):\n return self.stack.pop()\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-18T10:09:20.203", "Id": "454181", "Score": "7", "body": "instead of `is_empty`, one cane override the `__bool__` method. Or just leave it out, because with `__len__` implemented and no `__bool__` defined, `if stack` will internally call `if len(stack)`, which will call `if stack.__len__()` and use the fact that `0` is falsey." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-16T16:16:15.400", "Id": "232507", "ParentId": "232494", "Score": "13" } }, { "body": "<p>From a pure Python standpoint, a list is already a stack if you narrow its methods down to only <code>pop</code> and <code>append</code>.\n<code>l.append(x)</code> will put <code>x</code> at the end of the list, and <code>l.pop()</code> will remove the last element of the list and return it.</p>\n\n<p>So generally speaking, when you need a stack in Python, you'll just make a list and use <code>append</code> and <code>pop</code>.\nThe same goes for queues, but you'd use <code>l.pop(0)</code> instead of <code>l.pop()</code>.</p>\n\n<p>Considering this, I would say it's just plain unpythonic to implement a stack structure; instead, just use a <code>list</code>, that really is a dequeue and thus can be used as both a stack and a queue.</p>\n\n<hr>\n\n<p>That said, I understand that <code>append</code> is not the common naming for the stack structure, and that <code>push</code> makes the intent of the method more clear.\nTherefore, I would implement a stack as a direct subclass of <code>list</code>, and just \"rename\" the <code>append</code> method:</p>\n\n<pre><code>class Stack(list):\n def push(self, x):\n super().append(x)\n</code></pre>\n\n<p>If I wanted to make it more fool-proof, I'd also override <code>pop</code> so that it cannot take a parameter, unlike <code>list.pop</code></p>\n\n<pre><code>class Stack(list):\n ...\n def pop(self):\n return super().pop()\n</code></pre>\n\n<p>Now the operation performed by the <code>peek</code> method can usually be done by <code>stack[-1]</code> (where <code>stack</code> is an instance of <code>Stack</code>), but it could be implemented just as follows:</p>\n\n<pre><code>class Stack(list):\n ...\n def peek(self):\n return self[-1]\n</code></pre>\n\n<hr>\n\n<p><em>Addendum</em></p>\n\n<p>Some comments advising against subclassing <code>list</code> came out, notably mentioning the \"composition over inheritance\" principle.\nThat was an enriching discussion, and I'd like to amend my answer accordingly.</p>\n\n<p>I'm no expert in design patterns, but as I understand it, this principle advocates the use of composition instead of inheritance to provide more flexibility.\nOne benefit of composition here is clearly to provide a cleaner API, with only the common stack methods and not <code>insert</code>, <code>remove</code> and so on that come from <code>list</code> and have no sense for stacks.</p>\n\n<p>On the other hand, the inheritance I suggested happens to violate Liskov's substitution principle.\nAlthough there's no problem with adding <code>push</code> and <code>peek</code> methods with respect to this principle, my implementation changes the signature of the <code>pop</code> method, which is not allowed by this principle.</p>\n\n<p>From this perspective, I think that not only composition is valid here and adds in the benefit of a clean API, but also that inheritance is plain incorrect here.\nTherefore, if I were forced to implement a stack class in Python, I'd go with composition and do as follows:</p>\n\n<pre><code>class Stack:\n def __init__(self):\n self._data = []\n\n def push(self, x):\n self._data.append(x)\n\n def pop(self):\n return self._data.pop()\n\n def peek(self)\n return self._data[-1]\n\n def __len__(self):\n return len(self._data)\n</code></pre>\n\n<p>But again, as I said, I would never do that in real life because a list can already serve as a stack, and <code>stack = []</code> would perfectly convey how <code>stack</code> would be intended to be used.</p>\n\n<hr>\n\n<p><strong>References:</strong></p>\n\n<p>On the Liskov substitution principle:</p>\n\n<ul>\n<li><a href=\"https://en.wikipedia.org/wiki/Liskov_substitution_principle\" rel=\"nofollow noreferrer\">https://en.wikipedia.org/wiki/Liskov_substitution_principle</a></li>\n<li><a href=\"https://stackoverflow.com/q/56860/7051394\">https://stackoverflow.com/q/56860/7051394</a></li>\n</ul>\n\n<p>On composition over inheritance:</p>\n\n<ul>\n<li><a href=\"https://en.wikipedia.org/wiki/Composition_over_inheritance\" rel=\"nofollow noreferrer\">https://en.wikipedia.org/wiki/Composition_over_inheritance</a></li>\n<li><a href=\"https://stackoverflow.com/a/53354/7051394\">https://stackoverflow.com/a/53354/7051394</a> (also happens to mention Liskov principle)</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-17T05:50:29.060", "Id": "454113", "Score": "6", "body": "Isn't `l.pop(0)` an O(n) operation?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-17T10:28:41.610", "Id": "454121", "Score": "4", "body": "Inheriting from list to implement a stack is pretty awful. The point of APIs is to provide specific limited, documented functionality. I don't want users to be able to access or modify the middle of my stack or be confused why my stack class even has this functionality. Whether you actually *need* a stack is a different question." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-17T17:21:57.990", "Id": "454133", "Score": "3", "body": "This suggestion to inherit completely fails \"Composition over inheritance\" principle." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-17T19:30:38.687", "Id": "454146", "Score": "1", "body": "@juhist I don't deny that your point is not valid, but I'm not sure I get it. In Python, a list is a collection to which elements can be appended, and from which elements can be removed in the inverse order of insertion - among other properties of course. From this standpoint, a stack is a kind of list as defined in Python. Therefore, it looks to me that inheritance is appropriate. What would be your arguments in favor of composition over inheritance, in this specific situation?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-17T20:17:04.773", "Id": "454151", "Score": "3", "body": "Ok guys, thanks for the feedback! I updated my answer, taking all this discussion into account. That was truly enriching, and I defintely learnt things today." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-17T20:47:13.870", "Id": "454153", "Score": "2", "body": "The argument is information hiding. By making the list a hidden implementation detail (preferably prefixed with underscore), a stack can be used only via its regular interface. The implementation is easier to change, too (for example, to linked list) if the implementation is not part of the interface." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-18T11:37:10.283", "Id": "454204", "Score": "1", "body": "For a queue, [`collections.deque`](https://docs.python.org/3/library/collections.html#collections.deque) would be best to avoid O(n) operations @MeesdeVries" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-19T02:50:31.190", "Id": "454291", "Score": "0", "body": "`__len__` should be `len(self.data)`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-19T04:25:09.193", "Id": "454295", "Score": "0", "body": "@njzk2 ah definitely, my bad. Fixed it, thanks!" } ], "meta_data": { "CommentCount": "9", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-16T20:31:40.447", "Id": "232521", "ParentId": "232494", "Score": "33" } }, { "body": "<p>One suggestion I didn't see is that you can replace <code>isEmpty</code> with <code>__bool__</code>. Then, you can check whether the stack is empty with <code>if not stack</code>. This is more in line with other python collections.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-17T22:32:50.003", "Id": "232563", "ParentId": "232494", "Score": "3" } }, { "body": "<p>Pop and peek will crash with IndexError if applied to an empty stack. This may be acceptable (and is the only thing to do if you regard None as stack-able data), but otherwise you could add the lines</p>\n\n<pre><code>if not stack: # or, if stack == [] \n return None\n</code></pre>\n\n<p>and in push</p>\n\n<pre><code>if data is None:\n raise ValueError( \"Attempt to push data=None onto the stack\" )\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-19T16:50:06.503", "Id": "454405", "Score": "0", "body": "Throwing `IndexError` is what I would expect and similar to what happens if you'd try to call `pop()` on an empty list (`[].pop()` -> `IndexError: pop from empty list`)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-19T16:58:54.923", "Id": "454406", "Score": "0", "body": "Sure, but the question says \"a stack\". A refectory stack doesn't error, it just continues to exist in a state of emptyness. Neither is more correct than the other. Seems pointless to precisely re-inplement what is already provided as a standard `list` object." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-19T15:18:29.143", "Id": "232644", "ParentId": "232494", "Score": "0" } }, { "body": "<p>There are a three improvements I can think of:</p>\n\n<ul>\n<li><code>self.stack == []</code> should be <code>not self.stack</code></li>\n<li>Save the length of the list as you use the stack. That way, you can access the length in O(1)</li>\n<li>Make the variables private</li>\n</ul>\n\n<p>This is what the code would look like at the end:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>class Stack:\n def __init__(self):\n self.stack = []\n self.length = 0\n\n def isEmpty(self):\n return not self.stack\n\n def push(self, data):\n self.length += 1\n self.stack.append(data)\n\n def pop(self):\n self.length -= 1\n return self.stack.pop()\n\n def peek(self):\n return self.stack[-1]\n\n def sizeStack(self):\n return self.length\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-19T19:19:12.617", "Id": "232655", "ParentId": "232494", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-16T09:27:02.590", "Id": "232494", "Score": "17", "Tags": [ "python", "algorithm", "python-3.x", "stack" ], "Title": "Stack data structure in Python 3" }
232494
<p>I have written c++ code which performs an elevator's function like carrying people from one floor to another. It is a fun project and I have written to test my C++ skills. Please review this code and suggest improvements. Also suggest some other features I should add.</p> <pre><code>#include &lt;iostream&gt; #include &lt;algorithm&gt; #include &lt;vector&gt; #include &lt;string&gt; class Elevator { enum Direction{ UP, DOWN }; Direction direction; std::vector&lt;int&gt; requests = {}; int min_floor; //Undergroud floor will be shown using negative value int max_floor; int current_floor = 0; //ground floor std::size_t current_capacity = 0; std::size_t max_capacity; public: Elevator() = default; Elevator(int min_floor, int max_floor, std::size_t max_capacity) : min_floor(min_floor), max_floor(max_floor), max_capacity(max_capacity) {} ~Elevator() {}; void start_elevator(); private: void set_initial_request(); void set_request(); bool is_valid_request(int floor) const; void set_direction(); int get_min_floor() const { return min_floor; } int get_max_floor() const { return max_floor; } int get_current_floor() const { return current_floor; } void set_current_floor(int floor) { current_floor = floor; } std::size_t get_max_capacity() const { return max_capacity; } std::size_t get_current_capacity() const { return current_capacity; } void set_current_capacity(std::size_t cap) { current_capacity = cap; } }; void Elevator::set_initial_request() { std::size_t num_of_reqs; int dest_floor; std::cout &lt;&lt; "\nEnter number of requests \n";//&lt;&lt; get_current_floor() &lt;&lt; "\n"; std::cin &gt;&gt; num_of_reqs; std::cout &lt;&lt; "\nEnter destination floor number.\n"; std::cin &gt;&gt; dest_floor; requests.emplace_back(dest_floor); set_current_capacity(1 + get_current_capacity()); set_direction(); for (std::size_t i = 1; i &lt; num_of_reqs; ++i) { std::cin &gt;&gt; dest_floor; if (is_valid_request(dest_floor)) { requests.emplace_back(dest_floor); set_current_capacity(1 + get_current_capacity()); } if (get_current_capacity() == get_max_capacity()) { std::cout &lt;&lt; "No more entry. Elevator is full!!\n"; break; } } } void Elevator::set_request() { std::size_t num_of_reqs; int dest_floor; std::cout &lt;&lt; "\nEnter number of requests \n"; std::cin &gt;&gt; num_of_reqs; std::cout &lt;&lt; "\nEnter destination floor number.\n"; for (std::size_t i = 0; i &lt; num_of_reqs; ++i) { std::cin &gt;&gt; dest_floor; if (is_valid_request(dest_floor)) { requests.emplace_back(dest_floor); set_current_capacity(1 + get_current_capacity()); } if (get_current_capacity() == get_max_capacity()) { std::cout &lt;&lt; "No more entry. Elevator is full!!\n"; break; } } } bool Elevator::is_valid_request(int floor) const { if (get_current_capacity() &gt;= get_max_capacity()) { std::cout &lt;&lt; "Elevator is Full!!\n"; return false; } else if (direction == UP &amp;&amp; floor &lt; get_current_floor()) { std::cout &lt;&lt; "Elevator is going UP.\n"; return false; } else if (direction == DOWN &amp;&amp; floor &gt; get_current_floor()) { std::cout &lt;&lt; "Elevator is going DOWN.\n"; return false; } else if (floor &gt; get_max_floor() || floor &lt; get_min_floor()) { std::cout &lt;&lt; "This floor does not exist\n"; return false; } else { return true; } } void Elevator::set_direction() { if (requests[0] &gt; get_current_floor()) { direction = UP; } else if (requests[0] &lt; get_current_floor()) { direction = DOWN; } } void Elevator::start_elevator() { int curr_floor = get_current_floor(); std::size_t curr_capacity = get_current_capacity(); std::cout &lt;&lt; "\nThe current floor is " &lt;&lt; curr_floor &lt;&lt; " and number of person in elevator are " &lt;&lt; curr_capacity &lt;&lt;"\n"; //Entering requests for first time set_initial_request(); std::sort(requests.begin(), requests.end()); while (!requests.empty()) { if (direction == UP) { set_current_floor(requests[0]); } else if (direction == DOWN) { set_current_floor(requests[requests.size() - 1]); } curr_floor = get_current_floor(); curr_capacity = get_current_capacity(); auto curr_floor_req = std::find(requests.begin(), requests.end(), get_current_floor()); while (curr_floor_req != requests.end()) { requests.erase(curr_floor_req); //removing current floor's requests curr_capacity--; curr_floor_req = std::find(requests.begin(), requests.end(), get_current_floor()); } set_current_capacity(curr_capacity); std::string dir; if (direction == UP) { dir = "UP"; } else { dir = "DOWN"; } //Entering requests for current floor std::cout &lt;&lt; "\n=======================================================\n"; std::cout &lt;&lt; "The current floor is " &lt;&lt; curr_floor &lt;&lt; " and number of person in elevator are " &lt;&lt; curr_capacity &lt;&lt;"\n"; std::cout &lt;&lt; "\nDirection of elevator is " &lt;&lt; dir &lt;&lt; " and Total capacity of the elevator is " &lt;&lt; get_max_capacity() &lt;&lt; "\n"; std::cout &lt;&lt; "\nMinimum floor number is " &lt;&lt; get_min_floor() &lt;&lt; " and Maximum floor number is " &lt;&lt; get_max_floor() &lt;&lt; "\n"; std::cout &lt;&lt; "\n=======================================================\n"; if (curr_floor == get_max_floor()) { direction = DOWN; } else if (curr_floor == get_min_floor()) { direction = UP; } if (current_capacity == 0) //Elevator is empty { set_initial_request(); std::sort(requests.begin(), requests.end()); } else { set_request(); std::sort(requests.begin(), requests.end()); } } } int main() { int min_floor_num, max_floor_num; std::size_t max_capacity; std::cout &lt;&lt; "Enter minimum floor number, maximum floor number in the building\n"; std::cin &gt;&gt; min_floor_num &gt;&gt; max_floor_num; std::cout &lt;&lt; "Enter maximum capacity for the elevator\n"; std::cin &gt;&gt; max_capacity; Elevator elevator(min_floor_num, max_floor_num, max_capacity); elevator.start_elevator(); } </code></pre> <p>When people enter in elevator at any floor, the user should know how many people are entering and it is entered in <code>num_of_reqs</code>. How to write code such that we do not need variable <code>num_of_reqs</code>.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-16T15:52:30.137", "Id": "454044", "Score": "0", "body": ":\"How to write code such that we do not need variable `num_of_reqs`\" Asking for code not yet written is certainly _off- topic_ here. Also I miss to see any code steering your elevator," }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-17T12:36:28.740", "Id": "454124", "Score": "0", "body": "A normal elevator won't know how many people enter. All it knows is weight, and that's just for safety." } ]
[ { "body": "<p>Here are some ideas and observations that may help you improve your code. There are some good things here, too. The code uses <code>const</code> appropriately and consistently, which is good.</p>\n\n<h2>Separate input, output and calculation</h2>\n\n<p>To the degree practical it's usually good practice to separate input, output and calculation for programs like this. By putting them in separate functions, it isolates the particular I/O for your platform (which is likely to be unique to that platform or operating system) from the logic of the simulation (which does not depend on the underlying OS). For example, right now, <code>is_valid_request()</code> returns a boolean value, but also has a side effect of printing to <code>std::cout</code>. I'd suggest that a different method might be to either return a number as with many standard library calls, such that 0 means success and non-zero indicates an error. Which error is determined by the number which then could be printed to the console or displayed in a GUI dialog box.</p>\n\n<h2>Format your code consistently</h2>\n\n<p>It doesn't matter as much what style you use as it matters that you have a consistent style. Here, the formatting is not too bad, but the different indentation levels are not typical. For example, I would not indent all of those member function definitions. Also there is a spurious semicolon after the destructor:</p>\n\n<pre><code>~Elevator() {};\n</code></pre>\n\n<h2>Let the compiler create default destructor</h2>\n\n<p>The compiler will create a destructor by default which is essentially identical to what you've got, so you can simply omit both the declaraton and implementation from your code.</p>\n\n<h2>Don't write getters and setters for every class</h2>\n\n<p>C++ isn't Java and writing getter and setter functions for every C++ class is not good style. Consider these two private member functions, for example:</p>\n\n<pre><code>int get_current_floor() const\n{\n return current_floor;\n}\n\nvoid set_current_floor(int floor)\n{\n current_floor = floor;\n}\n</code></pre>\n\n<p>Since there is no error checking or enforcement of invariants here (that is, <code>set_current_floor</code> would happily accept any integer value and doesn't enforce that it must be within the elevator's range), there is no advantage over simply accessing the <code>current_floor</code> data member directly.</p>\n\n<h2>Think of the user</h2>\n\n<p>There is no graceful way to end the program. Also, there are some strange things such as when we ask to put 1000 people aboard a small elevator. It would be more sensible from the user's perspective, if they were told immediately that a maximum of <span class=\"math-container\">\\$x\\$</span> number of requests will be accepted. That also answers your question about eliminating <code>num_of_reqs</code>: just keep accepting input until either the elevator can't hold any more people <em>or</em> until the user indicates no more input such as by inputting a special <a href=\"https://en.wikipedia.org/wiki/Sentinel_value\" rel=\"noreferrer\">sentinel value</a> that indicates end of data.</p>\n\n<h2>Understand standard containers</h2>\n\n<p>The use of <code>std::vector::emplace_back</code> everywhere in this program is peculiar. Specifically <code>emplace_back</code> constructs a new object and avoids an extra copy or move versus using <code>push_back</code> which can make a difference with a vector of large or complex objects. However here, the only vector is of <code>int</code>, so <code>push_back</code> would be much more appropriate.</p>\n\n<h2>Sanitize user input better</h2>\n\n<p>If I enter a string such as \"Edward\" when asked for the minimum floor number, the program stays in an endless loop. It would be better to read a (text) line in and then convert it to a number. Also, there is no check to make sure that <code>max_floor_num</code> is actually greater than <code>min_floor_num</code>. Users can do funny things and you want your program to be robust. Even better might be to have the computer also simulate passengers and only print out results.</p>\n\n<h2>Combine stream output operations</h2>\n\n<p>The code currently contains this sequence:</p>\n\n<pre><code>std::cout &lt;&lt; \"\\n=======================================================\\n\";\nstd::cout &lt;&lt; \"The current floor is \" &lt;&lt; curr_floor &lt;&lt; \" and number of person in elevator are \" &lt;&lt; curr_capacity &lt;&lt;\"\\n\";\nstd::cout &lt;&lt; \"\\nDirection of elevator is \" &lt;&lt; dir &lt;&lt; \" and Total capacity of the elevator is \" &lt;&lt; get_max_capacity() &lt;&lt; \"\\n\";\nstd::cout &lt;&lt; \"\\nMinimum floor number is \" &lt;&lt; get_min_floor() &lt;&lt; \" and Maximum floor number is \" &lt;&lt; get_max_floor() &lt;&lt; \"\\n\";\nstd::cout &lt;&lt; \"\\n=======================================================\\n\";\n</code></pre>\n\n<p>But you don't really need to do it that way. Instead it could be written like this:</p>\n\n<pre><code>std::cout &lt;&lt; \"\\n=======================================================\\n\"\n \"The current floor is \" &lt;&lt; curr_floor \n &lt;&lt; \" and number of people in the elevator is \" &lt;&lt; curr_capacity \n &lt;&lt; \"\\n\\nDirection of elevator is \" &lt;&lt; dir \n &lt;&lt; \" and Total capacity of the elevator is \" &lt;&lt; get_max_capacity() \n &lt;&lt; \"\\n\\nMinimum floor number is \" &lt;&lt; get_min_floor() \n &lt;&lt; \" and Maximum floor number is \" &lt;&lt; get_max_floor() \n &lt;&lt; \"\\n\\n=======================================================\\n\";\n</code></pre>\n\n<p>This makes it more clear it's just one long message sent to <code>std::cout</code> and also uses constant string concatenation because the compiler automatically concatenates the first two string literals together. As a minor change, I've also changed \"number of person in elevator are\" to the grammatically correct \"number of people in the elevator is\".</p>\n\n<h2>Don't Repeat Yourself (DRY)</h2>\n\n<p>The code for <code>set_initial_request()</code> and <code>set_request()</code> is largely the same. The only differences are that the former also calls <code>set_direction()</code> and insists on getting at least one destination floor number even if the user specifies zero requests. Instead, I'd suggest that <code>set_direction()</code> could be called outside this function or called every time and that function modified to only change direction if there are no current passengers.</p>\n\n<h2>Use better naming</h2>\n\n<p>The name <code>current_capacity</code> is a bit misleading, since \"capacity\" means, in English, the maximum amount something can hold. It also means <code>max_capacity</code> is redundant. Instead, I'd suggest naming them <code>passengers</code> and <code>capacity</code>.</p>\n\n<h2>Reconsider the constructors</h2>\n\n<p>The <code>Elevator</code> class has two constructors: one with parameters and one without. I would suggest eliminating the default constructor with no parameters because it would not result in a useful object and there's no way to change the parameters after constructing the <code>Elevator</code>.</p>\n\n<h2>Consider additional refinements and features</h2>\n\n<p>I've already mentioned that it might be nice to have the computer simulate passenger behavior. Other things to consider are whether <code>UP</code> and <code>DOWN</code> are sufficient. Elevators typically have two indicator lights, one for \"up\", and one for \"down\". However, both may be off, indicating that the elevator is free to take in either direction. Also, consider gathering statistics. How far did the elevator travel in total? What was the average waiting time for passengers? What about simulating a bank of elevators? What if some are express elevators serving, for example, only the lobby and top half of the building? There are all kinds of interesting things one could do with this concept.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-16T15:59:47.703", "Id": "232506", "ParentId": "232502", "Score": "10" } } ]
{ "AcceptedAnswerId": "232506", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-16T13:34:01.123", "Id": "232502", "Score": "7", "Tags": [ "c++", "object-oriented" ], "Title": "Elevator design implementation in C++" }
232502
<p>Continuing my trend of (ab)using the Windows command-line interface to do fancy graphics-related things with my command-line-graphics library, <a href="https://codereview.stackexchange.com/questions/166712/cligl-a-library-for-command-line-graphics">CLIGL</a>, I've created an infinite procedural terrain generator, capable of generating coherent fractal noise to an appreciable distance.</p> <p>The basic structure of the project is as follows:</p> <ul> <li><p><code>EntryPoint</code>: Relatively self-explanatory. This class contains the actual entry point for the program; it performs the initialization of a CLIGL <code>RenderingWindow</code> and <code>RenderingBuffer</code>, and creates an instance of the <code>ChunkManager</code> class.</p></li> <li><p><code>Position</code>: A helper class used to store a two-dimensional position; it implements a <code>Transform()</code> function and overrides <code>Equals()</code> and <code>GetHashCode()</code>.</p></li> <li><p><code>Chunk</code>: responsible for generating, managing, and rendering a set of chunk data stored in a <code>RenderingPixel[,]</code> array; it also contains several private helper methods used in the process of terrain generation, as well as a collection of constants used for fractal noise generation and terrain detail generation.</p></li> <li><p><code>ChunkManager</code>: responsible for loading, maintaining, and rendering a dictionary of chunks, as well as moving the viewport; it will also generate a seed used for individual chunk generation. It will add chunks to the dictionary if necessary (i.e., if there <em>should</em> be a chunk loaded within the current view range, but there isn't) and will delete chunks if necessary (i.e., if there is a chunk loaded, but is outside the current view range); it should be noted that the processes of chunk addition and deletion will only occur if the position of the chunk manager (the viewport) itself is changing.</p></li> </ul> <p>A brief outline of the specific algorithm used to generate noise values:</p> <ol> <li><p>Fractal noise values <span class="math-container">\$a\$</span> and <span class="math-container">\$b\$</span> are generated with specific base frequencies <span class="math-container">\$f_1\$</span> and <span class="math-container">\$f_2\$</span>, respectively (also referred to as "noise scale"; cf. <code>NOISE_SCALE_A</code> and <code>NOISE_SCALE_B</code>).</p></li> <li><p>A third noise value, <span class="math-container">\$t\$</span>, is generated with a different base frequency (again, also referred to as "noise scale"; cf. <code>NOISE_SCALE_T</code>).</p></li> <li><p>Linear interpolation is then performed between <span class="math-container">\$a\$</span> and <span class="math-container">\$b\$</span> using <span class="math-container">\$\frac{t + 1.0}{2.0}\$</span> as the time value (note: the noise library I am using generates simplex noise in the range <span class="math-container">\$-1.0 \rightarrow 1.0\$</span>, hence the adjustment of <span class="math-container">\$t\$</span>).</p></li> <li><p>Basic terrain detail (background color) is then generated (e.g., oceans, beaches, plains, and mountains) based on specified noise thresholds, <code>OCEAN_THRESHOLD</code>, <code>BEACH_THRESHOLD</code>, <em>et al.</em></p></li> <li><p>A fourth noise value is generated using only simplex noise with no scale adjustments; this noise value is then used to generate additional terrain detail (foreground colors and characters)</p></li> </ol> <p><strong>EntryPoint.cs</strong></p> <pre><code>using System; using System.Diagnostics; using TerrainGenerator.Terrain; using CLIGL; namespace TerrainGenerator { /// &lt;summary&gt; /// Contains the entry point for the terrain generator as well as all /// requisite CLIGL initialization. /// &lt;/summary&gt; public class EntryPoint { public const int WINDOW_WIDTH = 90; public const int WINDOW_HEIGHT = 50; /// &lt;summary&gt; /// Entry point for the program. /// &lt;/summary&gt; /// &lt;param name="args"&gt;The command line arguments.&lt;/param&gt; public static void Main(string[] args) { RenderingWindow window = new RenderingWindow("Terrain Generator", WINDOW_WIDTH, WINDOW_HEIGHT); RenderingBuffer buffer = new RenderingBuffer(WINDOW_WIDTH, WINDOW_HEIGHT); Stopwatch timeAccumulator = new Stopwatch(); timeAccumulator.Start(); float previousElapsed = (float)timeAccumulator.Elapsed.TotalSeconds; float currentElapsed; float elapsedTime; float deltaTime; ChunkManager chunkManager = new ChunkManager(0, 0); while(true) { elapsedTime = (float)timeAccumulator.Elapsed.TotalSeconds; currentElapsed = elapsedTime; deltaTime = currentElapsed - previousElapsed; buffer.ClearPixelBuffer(RenderingPixel.EmptyPixel); chunkManager.Render(ref buffer); buffer.SetString(1, 1, $" T = {elapsedTime.ToString("F2")} ", ConsoleColor.White, ConsoleColor.Black); buffer.SetString(1, 2, $" DT = {deltaTime.ToString("F2")} ", ConsoleColor.White, ConsoleColor.Black); buffer.SetString(1, 3, $" FPS = {(1.0f / deltaTime).ToString("F2")} ", ConsoleColor.White, ConsoleColor.Black); buffer.SetString(1, 5, $" CMP = ({chunkManager.Position.X}, {chunkManager.Position.Y}) ", ConsoleColor.White, ConsoleColor.Black); buffer.SetString(1, 6, $" CMCC = {chunkManager.ChunkCollection.Count} ", ConsoleColor.White, ConsoleColor.Black); buffer.SetString(1, 7, $" CMSD = {chunkManager.Seed} ", ConsoleColor.White, ConsoleColor.Black); window.Render(buffer); chunkManager.Update(); previousElapsed = currentElapsed; } } } } </code></pre> <p><strong>Position.cs</strong></p> <pre><code>using System; namespace TerrainGenerator.Utilities { /// &lt;summary&gt; /// Represents a 2-dimensional position. /// &lt;/summary&gt; public class Position { public int X { get; set; } public int Y { get; set; } /// &lt;summary&gt; /// Constructor for the Position class. /// &lt;/summary&gt; /// &lt;param name="x"&gt;X-coordinate.&lt;/param&gt; /// &lt;param name="y"&gt;Y-coordinate.&lt;/param&gt; public Position(int x, int y) { this.X = x; this.Y = y; } /// &lt;summary&gt; /// Translate the X and Y components (addition). /// &lt;/summary&gt; /// &lt;param name="xOffset"&gt;The offset by which to translate X.&lt;/param&gt; /// &lt;param name="yOffset"&gt;The offset by which to translate Y.&lt;/param&gt; public void Translate(int xOffset, int yOffset) { this.X += xOffset; this.Y += yOffset; } /// &lt;summary&gt; /// Get the hash code of the position. /// &lt;/summary&gt; /// &lt;returns&gt;A hash code.&lt;/returns&gt; public override int GetHashCode() { unchecked { int hash = 17; hash = hash * 23 + this.X.GetHashCode(); hash = hash * 23 + this.Y.GetHashCode(); return hash; } } /// &lt;summary&gt; /// Check for equality. /// &lt;/summary&gt; /// &lt;param name="obj"&gt;The object with which to check for equality.&lt;/param&gt; /// &lt;returns&gt;Whether the passed object is equal to the current object.&lt;/returns&gt; public override bool Equals(object obj) { if(obj.GetType() == typeof(Position)) { Position cast = obj as Position; return this.X == cast.X &amp;&amp; this.Y == cast.Y; } return false; } } } </code></pre> <p><strong>Chunk.cs</strong></p> <pre><code>using System; using TerrainGenerator.Utilities; using CLIGL; namespace TerrainGenerator.Terrain { /// &lt;summary&gt; /// Contains all terrain data for a section of terrain (chunk). Instances of this /// struct will be managed by the ChunkManager class. /// &lt;/summary&gt; public class Chunk { public const int CHUNK_WIDTH = 16; public const int CHUNK_HEIGHT = 16; public const float NOISE_SCALE_A = 0.0015f; public const float NOISE_SCALE_B = 0.01f; public const float NOISE_SCALE_T = 0.1f; public const int NOISE_ITERATIONS = 4; public const float NOISE_PERSISTENCE = 0.6f; public const float NOISE_MULTIPLIER = 1.5f; public const float OCEAN_THRESHOLD = 0.0f; public const float BEACH_THRESHOLD = 0.1f; public const float PLAINS_THRESHOLD = 0.3f; public const float ALPINE_THRESHOLD = 0.4f; public Position Position { get; private set; } public RenderingPixel[,] Data { get; private set; } /// &lt;summary&gt; /// Constructor for the Chunk struct. /// &lt;/summary&gt; /// &lt;param name="x"&gt;The X position of the chunk.&lt;/param&gt; /// &lt;param name="y"&gt;The Y position of the chunk.&lt;/param&gt; public Chunk(int x, int y) { this.Position = new Position(x, y); this.Data = new RenderingPixel[CHUNK_WIDTH, CHUNK_HEIGHT]; } /// &lt;summary&gt; /// Constructor for the Chunk struct. /// &lt;/summary&gt; /// &lt;param name="position"&gt;&lt;/param&gt; public Chunk(Position position) { this.Position = position; this.Data = new RenderingPixel[CHUNK_WIDTH, CHUNK_HEIGHT]; } /// &lt;summary&gt; /// Generate Chunk data with 3D perlin noise, given a specific seed. /// &lt;/summary&gt; /// &lt;param name="seed"&gt;&lt;/param&gt; public void GenerateData(int seed) { for(int y = 0; y &lt; CHUNK_HEIGHT; y++) { for(int x = 0; x &lt; CHUNK_WIDTH; x++) { float noiseValueA = this.FractalNoise(this.Position.X + x + seed, this.Position.Y + y + seed, seed, NOISE_SCALE_A); float noiseValueB = this.FractalNoise(this.Position.X + x + seed, this.Position.Y + y + seed, seed, NOISE_SCALE_B); float noiseValueT = this.FractalNoise(this.Position.X + x + seed, this.Position.Y + y + seed, seed, NOISE_SCALE_T); float terrainNoise = Lerp(noiseValueA, noiseValueB, (noiseValueT + 1.0f) / 2.0f); float detailNoise = Noise.Generate(this.Position.X + x + seed, this.Position.Y + y + seed, seed); (char, ConsoleColor, ConsoleColor) generatedTile = GenerateTile(terrainNoise, detailNoise); this.Data[x, y] = new RenderingPixel(generatedTile.Item1, generatedTile.Item2, generatedTile.Item3); } } } /// &lt;summary&gt; /// Render the generated tile data. /// &lt;/summary&gt; /// &lt;param name="managerX"&gt;The X position of the chunk manager.&lt;/param&gt; /// &lt;param name="managerY"&gt;The Y position of the chunk manager.&lt;/param&gt; /// &lt;param name="buffer"&gt;The buffer to which the chunk is rendered.&lt;/param&gt; public void RenderData(int managerX, int managerY, ref RenderingBuffer buffer) { for(int y = 0; y &lt; CHUNK_HEIGHT; y++) { for(int x = 0; x &lt; CHUNK_WIDTH; x++) { buffer.SetPixel(this.Position.X + x - managerX, this.Position.Y + y - managerY, this.Data[x, y]); } } } /// &lt;summary&gt; /// Generate a tile based on a given noise value. /// &lt;/summary&gt; /// &lt;param name="terrainNoise"&gt;The noise value with which to generate terrain structure.&lt;/param&gt; /// &lt;param name="detailNoise"&gt;The nosie value with which to generate terrain detail.&lt;/param&gt; /// &lt;returns&gt;A new tile.&lt;/returns&gt; private static (char, ConsoleColor, ConsoleColor) GenerateTile(float terrainNoise, float detailNoise) { if(terrainNoise &lt;= OCEAN_THRESHOLD) { char detailCharacter = GenerateDetailCharacter(detailNoise, 0.0f, 0.75f, ' ', '-', '~'); return (detailCharacter, ConsoleColor.Blue, ConsoleColor.DarkBlue); } else if(terrainNoise &lt;= BEACH_THRESHOLD) { char detailCharacter = GenerateDetailCharacter(detailNoise, -0.25f, 0.75f, ' ', '.', '*'); return (detailCharacter, ConsoleColor.Yellow, ConsoleColor.DarkYellow); } else if(terrainNoise &lt;= PLAINS_THRESHOLD) { char detailCharacter = GenerateDetailCharacter(detailNoise, -0.25f, 0.75f, ' ', '.', '*'); return (detailCharacter, ConsoleColor.Green, ConsoleColor.DarkGreen); } else if(terrainNoise &lt;= ALPINE_THRESHOLD) { char detailCharacter = GenerateDetailCharacter(detailNoise, 0.0f, 0.75f, ' ', '`', '.'); return (detailCharacter, ConsoleColor.Gray, ConsoleColor.DarkGray); } else { char detailCharacter = GenerateDetailCharacter(detailNoise, 0.25f, 0.75f, ' ', '.', ','); return (detailCharacter, ConsoleColor.White, ConsoleColor.Gray); } } /// &lt;summary&gt; /// Generate a detail character. /// &lt;/summary&gt; /// &lt;param name="detailNoise"&gt;The noise value with which to generate detail.&lt;/param&gt; /// &lt;param name="threshold1"&gt;The first noise threshold for detail.&lt;/param&gt; /// &lt;param name="threshold2"&gt;The second noise threshold for additional detail.&lt;/param&gt; /// &lt;param name="char1"&gt;First detail character.&lt;/param&gt; /// &lt;param name="char2"&gt;Second detail character.&lt;/param&gt; /// &lt;param name="char3"&gt;Final detail character.&lt;/param&gt; /// &lt;returns&gt;A detail character.&lt;/returns&gt; public static char GenerateDetailCharacter(float detailNoise, float threshold1, float threshold2, char char1, char char2, char char3) { return detailNoise &lt;= threshold1 ? char1 : detailNoise &lt;= threshold2 ? char2 : char3; } /// &lt;summary&gt; /// Generate a fractal noise value. /// &lt;/summary&gt; /// &lt;param name="x"&gt;The X position for which to generate noise.&lt;/param&gt; /// &lt;param name="y"&gt;The Y position for which to generate noise.&lt;/param&gt; /// &lt;param name="z"&gt;The Z position for which to generate noise.&lt;/param&gt; /// &lt;param name="frequency"&gt;Initial fractal noise frequency. Equivalent to scale.&lt;/param&gt; /// &lt;remarks&gt; /// This function assumes that a noise value has already been applied to /// the position values. /// &lt;/remarks&gt; /// &lt;returns&gt;A fractal noise value.&lt;/returns&gt; private float FractalNoise(float x, float y, float z, float frequency) { float noise = 0.0f; float currentFrequency = frequency; float currentAmplitude = 1.0f; float maximumAmplitude = 0.0f; for(int i = 0; i &lt; NOISE_ITERATIONS; i++) { noise += Noise.Generate(x * currentFrequency, y * currentFrequency, z * currentFrequency) * currentAmplitude; maximumAmplitude += currentAmplitude; currentAmplitude *= NOISE_PERSISTENCE; currentFrequency *= NOISE_MULTIPLIER; } return noise / maximumAmplitude; } /// &lt;summary&gt; /// Perform linear interpolation between two values. /// &lt;/summary&gt; /// &lt;param name="a"&gt;The first value.&lt;/param&gt; /// &lt;param name="b"&gt;The second value.&lt;/param&gt; /// &lt;param name="t"&gt;The time value.&lt;/param&gt; /// &lt;returns&gt;An interpolated value.&lt;/returns&gt; private static float Lerp(float a, float b, float t) { return a + t * (b - a); } } } </code></pre> <p><strong>ChunkManager.cs</strong></p> <pre><code>using System; using System.Collections.Generic; using TerrainGenerator.Utilities; using CLIGL; namespace TerrainGenerator.Terrain { /// &lt;summary&gt; /// This class is responsible for storing and managing a collection of chunks. It /// will update the collection of chunks, deleting chunks and adding new chunks based /// on the current position of the manager. /// &lt;/summary&gt; public class ChunkManager { public const int TRANSLATE_X = 2; public const int TRANSLATE_Y = 2; public const int CHUNK_LOADING_RANGE_X = 6; public const int CHUNK_LOADING_RANGE_Y = 3; public const int SEED_BOUNDS = 1000000; public int Seed { get; private set; } public Position Position { get; private set; } public Dictionary&lt;Position, Chunk&gt; ChunkCollection { get; private set; } /// &lt;summary&gt; /// Constructor for the ChunkManager class. /// &lt;/summary&gt; /// &lt;param name="x"&gt;The X position of the manager.&lt;/param&gt; /// &lt;param name="y"&gt;The y position of the manager.&lt;/param&gt; public ChunkManager(int x, int y) { Random randomGenerator = new Random(); this.Seed = randomGenerator.Next(-SEED_BOUNDS, SEED_BOUNDS); this.Position = new Position(x, y); this.ChunkCollection = new Dictionary&lt;Position, Chunk&gt;(CHUNK_LOADING_RANGE_X * CHUNK_LOADING_RANGE_Y * 4); this.AddChunks(); } /// &lt;summary&gt; /// Render the contents of the chunk collection to a buffer. /// &lt;/summary&gt; public void Render(ref RenderingBuffer buffer) { foreach(KeyValuePair&lt;Position, Chunk&gt; chunk in this.ChunkCollection) { chunk.Value.RenderData(this.Position.X, this.Position.Y, ref buffer); } } /// &lt;summary&gt; /// Update the chunk manager; if no keys are pressed (and as a consequence, the /// position of the chunk manager remains unchanged), then AddChunks() and /// DeleteChunks() are not called. /// &lt;/summary&gt; public void Update() { if(this.AdjustPosition()) { this.DeleteChunks(); this.AddChunks(); } } /// &lt;summary&gt; /// Adjust the position of the chunk manager based on keyboard input. /// &lt;/summary&gt; /// &lt;returns&gt;Whether or not a key has been pressed.&lt;/returns&gt; private bool AdjustPosition() { if(Console.KeyAvailable) { ConsoleKey keyPressed = Console.ReadKey(false).Key; switch(keyPressed) { case ConsoleKey.UpArrow: this.Position.Translate(0, -TRANSLATE_Y); break; case ConsoleKey.DownArrow: this.Position.Translate(0, TRANSLATE_Y); break; case ConsoleKey.LeftArrow: this.Position.Translate(-TRANSLATE_X, 0); break; case ConsoleKey.RightArrow: this.Position.Translate(TRANSLATE_X, 0); break; } return true; } return false; } /// &lt;summary&gt; /// If necessary (i.e., there is a chunk that should be loaded, but isn't), add a /// new chunk into the current collection of chunks. /// &lt;/summary&gt; private void AddChunks() { for(int y = -CHUNK_LOADING_RANGE_Y; y &lt;= CHUNK_LOADING_RANGE_Y; y++) { for(int x = -CHUNK_LOADING_RANGE_X; x &lt;= CHUNK_LOADING_RANGE_X; x++) { int chunkX = this.Position.X + x * Chunk.CHUNK_WIDTH; int chunkY = this.Position.Y + y * Chunk.CHUNK_HEIGHT; int lockedChunkX = (int)(Math.Floor((decimal)chunkX / (decimal)Chunk.CHUNK_WIDTH) * (decimal)Chunk.CHUNK_WIDTH); int lockedChunkY = (int)(Math.Floor((decimal)chunkY / (decimal)Chunk.CHUNK_HEIGHT) * (decimal)Chunk.CHUNK_HEIGHT); Position position = new Position(lockedChunkX, lockedChunkY); if(!this.ChunkCollection.ContainsKey(position)) { this.ChunkCollection.Add(position, new Chunk(position)); this.ChunkCollection[position].GenerateData(this.Seed); } } } } /// &lt;summary&gt; /// If necessary (i.e., there is a chunk that is loaded, but shouldn't be), delete /// the chunk from the current collection of chunks. /// &lt;/summary&gt; private void DeleteChunks() { List&lt;Position&gt; chunksToRemove = new List&lt;Position&gt;(); foreach(KeyValuePair&lt;Position, Chunk&gt; chunk in this.ChunkCollection) { if( Math.Abs(chunk.Value.Position.X - this.Position.X) &gt; CHUNK_LOADING_RANGE_X * Chunk.CHUNK_WIDTH * 2 || Math.Abs(chunk.Value.Position.Y - this.Position.Y) &gt; CHUNK_LOADING_RANGE_Y * Chunk.CHUNK_HEIGHT * 2 ) { chunksToRemove.Add(chunk.Key); } } foreach(Position position in chunksToRemove) { this.ChunkCollection.Remove(position); } } } } </code></pre> <p>With regards to review: I am primarily concerned with memory usage and performance (and if there exist any potential problems related to either of these issues); as of right now the generator uses at least 15% of my CPU across all processors and around 11 MB of memory, with memory usage increasing the longer the program runs, peaking at around 14 MB. That said, however, I welcome any other criticisms as well!</p> <p>A few notes:</p> <ul> <li><p>The <code>Noise</code> class that I have used throughout this project is an implementation of the simplex noise algorithm in C# by Heikki Törmälä; the original source can be viewed <a href="https://github.com/Xpktro/simplexnoise/blob/master/SimplexNoise/Noise.cs" rel="noreferrer">here</a>.</p></li> <li><p>This project links a previous project of mine, <a href="https://github.com/Ethan-Bierlein/CLIGL" rel="noreferrer">CLIGL</a>; if you wish to test out this generator, you will need to download and compile CLIGL to a <code>.DLL</code> and link it accordingly.</p></li> <li><p>I <em>highly</em> recommend that, should you wish to test this project for yourself, that you set the font of your console window to a raster font with a size of <code>12x16</code>.</p></li> <li><p>For those who may not wish to go to the effort of downloading and compiling CLIGL and this project, I have uploaded a video demonstrating the generator <a href="https://www.youtube.com/watch?v=6P41fpKucUs" rel="noreferrer">here</a>.</p></li> </ul>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-09T10:55:26.607", "Id": "456841", "Score": "0", "body": "Is there a particular reason for using chunks? It looks like each pixel can be updated individually... so we could use a single toroidal buffer, and update only the exact pixels that need it due to movement (i.e. a strip along the side of our window for movement in one direction, or an L-shape for movement in two)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-09T13:20:17.330", "Id": "456855", "Score": "0", "body": "@user673679 You’re definitely right in that regard; a toroidal buffer would have been a more apt solution for this problem. I did initially try to implement something to that effect, but I could not, for the life of me, get it to work; I’ve done a pretty significant amount of work with video engines in the past, and I am used to a chunk-based model, so I stuck with that." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-13T02:54:05.743", "Id": "457471", "Score": "0", "body": "Position and Chunck classes, could possibly merged. as Position is a struct and not a class for current configuration. Also, consider moving all constants to its own `static class`, for easier maintainability, and also to ensure you'll have only one instance of them. You can also wrap everything under meaningful name ( for user-experience), it would be possible to achieve something like `var tg = new TerrainGenerator()` and then, everything I need would be accessible in `TerrainGenerator` This also will act as publish layer where you'll expose/hide what you need for the user (developer)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-15T09:17:37.253", "Id": "457705", "Score": "0", "body": "@iSR5 please don't answer in comments. Write an answer instead." } ]
[ { "body": "<p>Going from top to bottom. </p>\n\n<p><code>EntryPoint</code></p>\n\n<pre><code>Stopwatch timeAccumulator = new Stopwatch();\ntimeAccumulator.Start(); \n</code></pre>\n\n<p>can be simplified by using <code>var</code> instead of the concrete type and by using the <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.diagnostics.stopwatch.startnew?view=netframework-4.8#System_Diagnostics_Stopwatch_StartNew\" rel=\"nofollow noreferrer\"><code>static Stopwatch Stopwatch.StartNew()</code></a> method. </p>\n\n<p><code>Position</code> </p>\n\n<pre><code>public override bool Equals(object obj)\n{\n if(obj.GetType() == typeof(Position))\n {\n Position cast = obj as Position;\n return\n this.X == cast.X &amp;&amp;\n this.Y == cast.Y;\n }\n\n return false;\n} \n</code></pre>\n\n<p>can be simplified like so </p>\n\n<pre><code>public override bool Equals(object obj)\n{\n if(obj is Position cast)\n {\n return\n this.X == cast.X &amp;&amp;\n this.Y == cast.Y;\n }\n\n return false;\n} \n</code></pre>\n\n<p>You don't check wether <code>x</code> or <code>y</code> is in a valid range. I don't know if your code get problems if either of this will be negative. If yes you should check these parameters in your constructor and add validation for the property-setter as well. </p>\n\n<p><code>Chunk</code> </p>\n\n<pre><code>public Chunk(int x, int y)\n{\n this.Position = new Position(x, y);\n this.Data = new RenderingPixel[CHUNK_WIDTH, CHUNK_HEIGHT];\n} \n</code></pre>\n\n<p>can be simplified by using constructor chaining like so </p>\n\n<pre><code>public Chunk(int x, int y) : this(new Position(x, y))\n{}\n</code></pre>\n\n<p><code>ChunkManager</code> </p>\n\n<p>In <code>AdjustPosition()</code> and other methods you should place a guarding clause to return early. This saves one indentation level for the whole method like so </p>\n\n<pre><code>private bool AdjustPosition()\n{\n if(!Console.KeyAvailable) { return false; }\n\n ConsoleKey keyPressed = Console.ReadKey(false).Key;\n switch(keyPressed)\n {\n case ConsoleKey.UpArrow:\n this.Position.Translate(0, -TRANSLATE_Y);\n break;\n\n case ConsoleKey.DownArrow:\n this.Position.Translate(0, TRANSLATE_Y);\n break;\n\n case ConsoleKey.LeftArrow:\n this.Position.Translate(-TRANSLATE_X, 0);\n break;\n\n case ConsoleKey.RightArrow:\n this.Position.Translate(TRANSLATE_X, 0);\n break;\n }\n\n return true;\n}\n</code></pre>\n\n<p>and by adding the <code>ConsoleKey</code>'s and <code>Action&lt;int, int&gt;</code> to a dictionary you can replace the <code>switch</code> completely. </p>\n\n<p><code>General</code> </p>\n\n<p>The usage of <code>this</code> adds only noise to your code. Just use it only if you really need to use it. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-14T23:08:19.833", "Id": "457679", "Score": "0", "body": "I could make the `Equals` method even shorter: `return obj is Point other && X == other.X && Y == other.Y;` -- is that an idiomatic way to write an Equals method?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-15T09:19:49.800", "Id": "457706", "Score": "0", "body": "@RolandIllig good point. Make it into an answer and get my +1 and if your answer is the only one except mine yiu will earn the bounty as well." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T07:27:46.307", "Id": "233761", "ParentId": "232510", "Score": "2" } } ]
{ "AcceptedAnswerId": "233761", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-16T17:06:20.707", "Id": "232510", "Score": "7", "Tags": [ "c#", "game", "console", "simulation" ], "Title": "Generating Infinite Procedural Terrain Using Command-Line Graphics" }
232510
<p>I'm looking for any feedback in order to improve code styling, performance etc. Also I want to make sure that the way I've implemented AES here is actually secure</p> <pre><code>import os import hashlib import sys import base64 from cryptography.fernet import Fernet class Cryptor: def __init__(self, password): self.__password = password def operate(self, file_): if file_.endswith("enc"): self.decrypt(file_) else: self.encrypt(file_) def decrypt(self, file_): file_name = "".join(file_.split(".")[:-1]) with open(file_, "rb") as file_: save1 = file_.readline() save2 = file_.readline() save3 = file_.readline() salt = save3 key = base64.urlsafe_b64encode(hashlib.pbkdf2_hmac("sha256", bytes(self.__password, encoding="utf-8"), salt, 100000, dklen=32)) f = Fernet(key) decrypted = f.decrypt(save1) file_extention = f.decrypt(save2) save = decrypted with open(file_name + file_extention.decode(encoding="utf-8"), "wb") as file_: file_.write(save) os.remove(file_name + ".enc") def encrypt(self, file_): salt = os.urandom(64) key = base64.urlsafe_b64encode(hashlib.pbkdf2_hmac("sha256", bytes(self.__password, encoding="utf-8"), salt, 100000, dklen=32)) f = Fernet(key) file_name = "".join(file_.split(".")[:-1]) file_extention = "." + file_.split(".")[-1] with open(file_, "rb") as file_: file__ = file_.read() encrypted = f.encrypt(bytes(file__)) save1 = encrypted save2 = f.encrypt(bytes(file_extention, encoding="utf-8")) save3 = salt with open(file_name + ".enc", "wb") as file_: file_.write(save1) file_.write(b"\n") file_.write(save2) file_.write(b"\n") file_.write(save3) os.remove(file_name + file_extention) def main(): password = sys.argv[1] files = sys.argv[2:] crypt = Cryptor(password) for file_ in files: crypt.operate(file_) if __name__ == "__main__": main() </code></pre>
[]
[ { "body": "<p><strong><em>Ways of improving:</em></strong></p>\n\n<p><em>Splitting filename</em></p>\n\n<p>Both methods <code>encrypt</code> and <code>decrypt</code> try to split a filename into <em>\"root\"</em> part and <em>extension</em>. <br><code>encrypt</code> method makes that even worse and verbose with 2 statements:</p>\n\n<pre><code> file_name = \"\".join(file_.split(\".\")[:-1])\n file_extention = \".\" + file_.split(\".\")[-1]\n</code></pre>\n\n<p>Instead, that's easily achievable with <a href=\"https://docs.python.org/3/library/os.path.html#os.path.splitext\" rel=\"nofollow noreferrer\"><code>os.path.splittext(path)</code></a> function (split the pathname path into a pair <code>(root, ext)</code>):</p>\n\n<pre><code>file_name, file_ext = os.path.splitext(file_)\n</code></pre>\n\n<hr>\n\n<p><em>Generating <code>Fernet</code> instance</em></p>\n\n<p>Both methods <code>encrypt</code> and <code>decrypt</code> have the same 2 statements for generating <code>Fernet</code> instance (with only difference in <code>salt</code> value):</p>\n\n<pre><code>key = base64.urlsafe_b64encode(hashlib.pbkdf2_hmac(\"sha256\", bytes(self.__password, encoding=\"utf-8\"), salt, 100000, dklen=32))\nf = Fernet(key)\n</code></pre>\n\n<p>It's good to extract that common behavior into a separate <em>internal</em> function:</p>\n\n<pre><code>def _get_fernet_instance(self, salt):\n key = base64.urlsafe_b64encode(hashlib.pbkdf2_hmac(\"sha256\", bytes(self.__password, encoding=\"utf-8\"), \n salt, 100000, dklen=32))\n return Fernet(key)\n</code></pre>\n\n<hr>\n\n<ul>\n<li><p><strong><code>decrypt</code></strong> function.<br>\nThe variables <code>save1</code>, <code>save2</code>, <code>save3</code> and <code>save</code> reassignment are confusing things rather than clarify.<br>The variables <code>save1</code>, <code>save2</code>, <code>save3</code> can be renamed to <code>line1</code>, <code>line2</code> and <strong><code>salt</code></strong>.<br>\nAliasing <code>save = decrypted</code> gives no benefit - just refer <code>decrypted</code> directly.<br>Including the above mentioned optimizations the <strong><code>decrypt</code></strong> method would look as:</p>\n\n<pre><code>def decrypt(self, file_):\n file_name, _ = os.path.splitext(file_)\n\n with open(file_, \"rb\") as f:\n line1 = f.readline()\n line2 = f.readline()\n salt = f.readline()\n\n fernet_ = self._get_fernet_instance(salt)\n decrypted = fernet_.decrypt(line1)\n file_ext = fernet_.decrypt(line2)\n\n with open(file_name + file_ext.decode(encoding=\"utf-8\"), \"wb\") as f:\n f.write(decrypted)\n\n os.remove(file_)\n</code></pre></li>\n<li><p><strong><code>encrypt</code></strong> function.<br>\nThe variable <code>file__</code> in <code>file__ = file_.read()</code> does not give an explicit meaning for the <em>content</em> being read. Let the content be <code>content</code> or <code>data</code>.<br>The same issues around variables <code>save1</code>, <code>save2</code>, <code>save3</code> and redundant aliases.<br></p>\n\n<p>In case if there would be a need to refer the input argument <strong><code>file_</code></strong> (in both methods) as its original value in different places in methods <em>body</em> - you should <strong>not</strong> reassign it in context managers <code>with open(file_, \"rb\") as file_:</code>.</p>\n\n<p><code>os.remove(file_name + file_extention)</code> is essentially the same as <code>os.remove(file_)</code></p>\n\n<p>The final optimized <strong><code>encrypt</code></strong> method would look as:</p>\n\n<pre><code>def encrypt(self, file_):\n salt = os.urandom(64)\n fernet_ = self._get_fernet_instance(salt)\n file_name, file_ext = os.path.splitext(file_)\n\n with open(file_, \"rb\") as f:\n content = f.read()\n encrypted_content = fernet_.encrypt(bytes(content))\n encrypted_ext = fernet_.encrypt(bytes(file_ext, encoding=\"utf-8\"))\n\n with open(f'{file_name}.enc', 'wb') as f:\n f.write(encrypted_content)\n f.write(b\"\\n\")\n f.write(encrypted_ext)\n f.write(b\"\\n\")\n f.write(salt)\n\n os.remove(file_)\n</code></pre></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-16T23:17:54.103", "Id": "454088", "Score": "0", "body": "Cheers for taking the time and giving a thorough answer!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-17T06:30:12.687", "Id": "454115", "Score": "0", "body": "@Krishi, welcome, see my last edit for adjusting variable name for Fernet instance" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-16T19:51:03.050", "Id": "232520", "ParentId": "232511", "Score": "6" } } ]
{ "AcceptedAnswerId": "232520", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-16T17:55:29.910", "Id": "232511", "Score": "7", "Tags": [ "python", "python-3.x", "aes" ], "Title": "File(s) encrypter implementation in python" }
232511
<p>I've written my custom implementation of an <code>f""</code> / <code>.format(...)</code>. I started the project thinking it was going to be longer than three lines.</p> <pre><code>from typing import List, Union, AnyStr def format_string(string: str, variables: List[Union[str, int, float, bool, complex]]) -&gt; str: """ Formats the passed string with the passed list of variables &gt;&gt;&gt; format_string("Hello, [*]", ["Ben"]) Hello, Ben :param string -&gt; str: String to be formatted :param variables -&gt; List[Union[str, int, float, bool, complex]]: List of variables to format into string :return str: Formatted string """ for index, value in enumerate(variables): string = string.replace("[*]", str(value), 1) return string </code></pre> <p>My main question is if it's possible to make this a one-liner. It absolutely infuriates me that I have to use three. I spent a long time trying a mixture of <code>*</code> and <code>''.join</code> to no avail. The code works, I would just like to shorten it up to one line. Of course, any and all feedback is appreciated and considered.</p> <p>A secondary question is the method header. To represent <code>variables</code>, I have a <code>List</code> that can contain <em>any</em> types of variables. How would I go about representing this instead of having to list each type separately?</p>
[]
[ { "body": "<p>For the second point, since it's easier, <code>typing</code> has an <a href=\"https://docs.python.org/3/library/typing.html#typing.Any\" rel=\"nofollow noreferrer\"><code>Any</code></a>:</p>\n\n<pre><code>from typing import List, Any\n. . ., variables: List[Any], . . .\n</code></pre>\n\n<p>For the first, you're just doing a <a href=\"https://docs.python.org/3/library/functools.html#functools.reduce\" rel=\"nofollow noreferrer\">reduction</a> over <code>variables</code>:</p>\n\n<pre><code>from typing import List, Any\nfrom functools import reduce\n\n\ndef format_string(string: str, variables: List[Any]) -&gt; str:\n return reduce(lambda s, val: s.replace(\"[*]\", str(val), 1), variables, string)\n</code></pre>\n\n<p>Although really, in a real use case, I'd still split this over three lines for clarity:</p>\n\n<pre><code>def format_string(string: str, variables: List[Any]) -&gt; str:\n return reduce(lambda s, val: s.replace(\"[*]\", str(val), 1),\n variables, \n string)\n</code></pre>\n\n<p>And honestly, I might just make that function var-arg instead of grouping things in a list to make it consistent with other <code>format</code> functions:</p>\n\n<pre><code>def format_string(string: str, *variables: Any) -&gt; str:\n return reduce(lambda s, val: s.replace(\"[*]\", str(val), 1), variables, string)\n\n&gt;&gt;&gt; format_string(\"[*] Hello [*]\", 1, 2)\n'1 Hello 2'\n</code></pre>\n\n<p>Note that when annotating a a var-arg parameter, you annotate the type of each element and ignore the type of the wrapping container (a tuple iirc). That means it's <code>*variables: Any</code>, not <code>*variables: Tuple[... Any]</code>.</p>\n\n<hr>\n\n<p>Of course though, whether or not this is better is a matter of taste, but this is the ideal use-case for <code>reduce</code>. Whenever you want to constantly reassign one thing in a simple loop, <code>reduce</code> is likely a good tool to look at.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-18T00:07:08.167", "Id": "454164", "Score": "0", "body": "What a beautiful solution, I knew there was a way to one line this. Thanks!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-16T18:53:47.150", "Id": "232515", "ParentId": "232514", "Score": "3" } } ]
{ "AcceptedAnswerId": "232515", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-16T18:40:42.093", "Id": "232514", "Score": "0", "Tags": [ "python", "python-3.x", "reinventing-the-wheel" ], "Title": "Custom String Formatter" }
232514
<p>I'm new in this community and with Python 3!</p> <p>I'm trying to optimize this exercise:</p> <blockquote> <p>We have <code>n</code> strings stored in a txt file. Inside the strings a secret word is hidden as a substring of consecutive characters.</p> <p>We know with certainty that the word repeats itself exactly once in each string but we don't know where. </p> <p>Of the word we know the length <code>M</code> and we know that there are no other substrings of length <code>M</code> which are repeated only once in all strings.</p> <p>We want to know for each string the position where the first character appears of the hidden word.</p> <p>For example for the 3 strings with hidden word of length 3:</p> <pre><code>dogrtre sdfddoge bcb98xdoge42 </code></pre> <p>the hidden word is 'dog' and the positions are in the order: <code>[0, 4, 6]</code></p> <p>The information in the text file is organized as follows:</p> <ul> <li><p>the first line contains the length of the hidden word (an integer).</p></li> <li><p>then follow the character strings, each string occupies one or more consecutive lines of the file and is separated from the following string by an empty line.</p></li> </ul> <p>Each line of the file ends with a newline.</p> </blockquote> <p>This is my code now, it works, but I need to speed up the process of searching the hidden word...</p> <p>The file.txt is:</p> <pre><code>3 dogrtre sdfdd oge bc b98xdo ge42 </code></pre> <p>As you can see the string in the file can stay on different lines. Can you help me?</p> <pre><code>#n=the lenght of the hidden word #F=TextFile #lista1=list of the possible hidden word of lenght n, the substring of the #first string #k=number of times that the word is in the file #pos=list of position def es1(ftesto): def conta(F): #this function count the strings in the file F.seek(0) a=1 l=F.readline() while l!='': if l=='\n': a+=1 l=F.readline() return a def crea_chiave(F): #this function read and split the first of the file s='' #in substring of lenght n l=F.readline() while l!='\n': s=s+l[:len(l)-1] l=F.readline() for i in range(0,len(s)-(n-1)): if s[i:n+i] not in lista1: #it also control if there is lista1.append(s[i:n+i]) #already the same substring in the else: #string lista1.remove(s[i:n+i]) #and in this case the function remove #it from the list def crea_lista(F,a,lista): #this function create the list s='' l=F.readline() while l!='': s=spezza(l,s,F) if s not in lista: #if the string is already in the list,it goes lista.append(s) #to the next one else: break l=F.readline() s='' def spezza(l,s,F): #this function build the string from the file while l!='\n' and l!='': s=s+l[:len(l)-1] l=F.readline() return s def controlla_parole(i,lista,k):#this function count how many times for y in lista: #times the word repeat itself in each strings if y.count(i)!=1: #if the word repeats itself 2 or 0 times break #in the string it isn't the hidden word else: k+=1 return k def trova_chiave(F,lista1,n): #this function find the hidden word a=conta(open(ftesto,encoding='utf8')) lista=[] crea_lista(F,a,lista) k=0 for i in lista1: k=controlla_parole(i,lista,k) if a==k: # if the number of hidden word repeats break #itself in the file is the same of k=0 #the number of strings in a file it is return i #our hidden word def controllo(F,l,chiave):# finally this func ,once we have the hidden pos=[] #word,return the position of hiddenword in the s='' #strings of file while l!='': while l!='\n' and l!='': s=s+l[:len(l)-1] l=F.readline() pos.append(s.find(chiave)) s='' l=F.readline() return pos F=open(ftesto,encoding='utf8') n=int(F.readline()) F.seek(len(str(n))+1) lista1=[] crea_chiave(F) F.seek(len(str(n))+1) chiave=trova_chiave(F,lista1,n) F.seek(len(str(n))+1) return controllo(F,F.readline(),chiave) </code></pre> <p>With the given file the function does returns <code>[0, 4, 6]</code>.</p> <p>Can you help me to optimize and speed up this code? Thanks!!</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-16T21:46:09.617", "Id": "454077", "Score": "0", "body": "Will different words always be separated by a newline in the text file?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-16T21:59:39.877", "Id": "454079", "Score": "0", "body": "What if each word would have multiple common substrings of same length? Let's say, besides of `dog` - each string contains `cbd` substring. How it should handle multiple common substrings with same length per each string?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-16T22:12:32.250", "Id": "454080", "Score": "0", "body": "For the first question yes!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-16T22:13:47.297", "Id": "454081", "Score": "0", "body": "For the second we know that there is only one word with this features" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-17T00:31:16.180", "Id": "454101", "Score": "0", "body": "I think `crea_chiave()` may not work correctly if a `s[i:n+i]` is in the text more than 2 times (1st time it is added to lista1. 2nd time it is removed. 3rd time it is added again.)." } ]
[ { "body": "<p>Type annotations and more descriptive variable names (from my perspective, preferably in English, heh) would make it easier for others to navigate the code and make specific suggestions, but here's how I'd suggest splitting the task up:</p>\n\n<ol>\n<li><p>Have a function that will read the file and return a <code>List[str]</code> of all the strings (i.e. split the file on blank lines and remove all the newlines). If memory ends up being a limiting factor, you'd want to implement this as a generator instead (and you'll end up potentially doing two passes through the file), but if you can hold the whole file in memory then it's easier to just read it once and hold the whole thing as a list.</p></li>\n<li><p>Have a function that finds all the words of length M in a particular string that repeat exactly once (i.e. it returns a set of words). You can maybe do this via some tricky regexing, or just brute-force trying every M-slice of the string and looking for repeat occurrences in the remainder of the string. This will be relatively slow (the brute force method will be roughly O(n^2), a regex might be faster), but you won't have to call it very many times, hopefully.</p></li>\n<li><p>Go through the list and start using that repeating-subset-finding function. Each time you get the set of words from a substring, intersect it with your set. Once you have one (and this might happen on the first string you check), that's your secret word! You finished the hard part.</p></li>\n<li><p>Now that you know the secret word, the rest is easy. Go through the list and use the builtin <code>find</code> function to find the indices you're after.</p></li>\n<li><p>If you want to optimize further (I ended up implementing this below), do two types of search: first get a list of candidates from the shortest input string, and then go through all the other inputs and verify that each of those occurs once, eliminating bad candidates as you go. The number of <code>find()</code> operations you need to do will shrink as you eliminate candidates, and once you're down to one you're finished.</p></li>\n</ol>\n\n<pre><code>from typing import List, Set, Tuple\n\ndef get_secret_word(input_file: str) -&gt; Tuple[str, List[int]]:\n \"\"\"Returns the secret word and a list of its indices.\"\"\"\n\n def load_file(input_file: str) -&gt; Tuple[int, List[str]]:\n \"\"\"Returns length of the needle and all the haystacks.\"\"\"\n with open(input_file) as file:\n length = int(file.readline())\n strings = [\"\"]\n line = file.readline()\n while line:\n line = line.strip()\n if line:\n strings[-1] += line\n else:\n strings.append(\"\")\n line = file.readline()\n return length, strings\n\n def generate_words(length: int, haystack: str) -&gt; Set[str]:\n \"\"\"Returns words of this length that occur in this haystack.\"\"\"\n return {haystack[i:i+length] for i in range(len(haystack)-length+1)}\n\n def find_known_words(needles: Set[str], haystack: str) -&gt; Set[str]:\n \"\"\"Search the haystack for this set of needles,\n and return just the needles that were found once.\"\"\"\n found = set()\n for needle in needles:\n i = haystack.find(needle)\n if i == -1: # zero occurrences\n continue\n i = haystack.find(needle, i + len(needle))\n if i == -1: # exactly one occurrence\n found.add(needle) \n return found\n\n # Load up the file.\n length, haystacks = load_file(input_file)\n\n # Build an initial set of needles from the smallest haystack.\n needles = generate_words(length, min(haystacks, key=len))\n for haystack in haystacks:\n # Our secret word is the one that is unique\n # in ALL haystacks. Process of elimination...\n if len(needles) == 1:\n break\n needles &amp;= find_known_words(needles, haystack)\n assert len(needles) == 1, \"No secret word found!\"\n secret = needles.pop()\n\n # Return the secret word and a list of its indices in the input strings.\n return secret, [haystack.find(secret) for haystack in haystacks]\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-16T22:22:24.213", "Id": "454082", "Score": "0", "body": "Thank you very much for the answer, yes certainly I can try in this way. Would I still maintain greater efficiency knowing that in the file I can have equal strings? Because in my code I foresee this possibility." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-16T23:04:15.107", "Id": "454087", "Score": "0", "body": "It depends on how malicious the input file is in trying to make the secret word hard to find -- the worst case scenario would be one where every string has the same two repeating substrings (so that either one of them could be the secret word) until you get to the very end. :) If you wanted to optimize that case, your second function could accept the set of candidates as an argument, and use that to speed up its search a bit (i.e. it doesn't need to waste time testing any substrings that aren't already candidates)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-17T01:26:23.637", "Id": "454102", "Score": "0", "body": "Ah, re-reading the problem I realize that when you say \"repeats once\" you mean \"occurs once\" (as opposed to occurs twice, i.e. repeated). Yes, you'll definitely need to keep a set and pare it down!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-17T01:33:42.310", "Id": "454103", "Score": "0", "body": "I went ahead and wrote up an implementation to make sure my strategy made sense, adding it to my answer. :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-17T01:42:15.210", "Id": "454107", "Score": "0", "body": "I think the way to implement the optimization I mentioned would be to write another function that searches the haystack for a set of needles (returning those that were found), and then use that for every haystack after the first. Another optimization after that would be to start with the smallest haystack (rather than the one that's first in the file), since that will start you with the smallest initial set of needles to search for." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-17T01:56:01.637", "Id": "454108", "Score": "0", "body": "k I did that too, lol" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-17T09:32:54.947", "Id": "454118", "Score": "0", "body": "Thank you so much Sam!!" } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-16T22:09:07.787", "Id": "232527", "ParentId": "232516", "Score": "3" } } ]
{ "AcceptedAnswerId": "232527", "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-16T18:54:10.497", "Id": "232516", "Score": "4", "Tags": [ "python", "python-3.x", "file" ], "Title": "Python timing optimisation" }
232516
<p>I have implemented a Bubble Sort. It works well. But if you think something needs to be improved, say it. This code was tested in Python 3.7.4.</p> <pre><code>def bubble_sort(nums): for i in range(len(nums)-1): for j in range(0,len(nums)-1-i,1): if nums[j] &gt; nums[j+1]: swap(nums, j, j+1) return nums def swap(nums, i, j): temp = nums[i] nums[i] = nums[j] nums[j] = temp if __name__ == "__main__": a = [0,0,0,-1,-0,1,2,3,2,1] print(bubble_sort(a)) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-19T08:33:25.107", "Id": "454310", "Score": "0", "body": "Also you have to be aware that you modify the `a` list - this may not be intended. You might want to copy a list or create a new one and fill with results. https://stackoverflow.com/questions/2612802/how-to-clone-or-copy-a-list" } ]
[ { "body": "<h1>Unnecessary Function</h1>\n\n<p>Your <code>swap</code> function is unnecessary. Simply replace the function call with this line:</p>\n\n<pre><code>nums[j], nums[j + 1] = nums[j + 1], nums[j]\n</code></pre>\n\n<p>This does the swapping for you.</p>\n\n<h1>Spacing</h1>\n\n<p>There should be spaces between values in lists</p>\n\n<pre><code>[1, 2, 3, 4, 5]\n</code></pre>\n\n<p>between numbers/strings and operators</p>\n\n<pre><code>if nums[j] &gt; nums[j + 1]\n</code></pre>\n\n<p>and between parameters in a function call</p>\n\n<pre><code>for j in range(0, len(nums) - 1 - i, 1):\n</code></pre>\n\n<h1>Type Hints</h1>\n\n<p>Your function header can look like this:</p>\n\n<pre><code>from typing import List, Union\n\ndef bubble_sort(nums: List[Union[int, float]]) -&gt; List[Union[int, float]]:\n</code></pre>\n\n<p>What this says is that the function accepts a list of integers/floats, and returns a list of integers/floats. It adds another layer of descriptiveness to your code.</p>\n\n<h1>Docstrings</h1>\n\n<p>You should include a <a href=\"https://www.python.org/dev/peps/pep-0008/#documentation-strings\" rel=\"noreferrer\"><code>docstring</code></a> at the beginning of every class/method/module you write. This allows you to describe in words what your code is doing.</p>\n\n<pre><code>def bubble_sort(nums: List[Union[int, float]]) -&gt; List[Union[int, float]]:\n \"\"\"\n A bubble sort algorithm, etc etc etc\n\n :param nums -&gt; List: A list of integers/floats to sort\n\n :return List: The sorted list of integers/floats, from smallest -&gt; biggest\n \"\"\"\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-16T19:07:14.830", "Id": "232518", "ParentId": "232517", "Score": "5" } }, { "body": "<p>In addition to <em>Linny</em>'s answer, one can also optimize the bubble sort algorithm like this:</p>\n\n<pre><code>def bubble_sort(nums): # sorry that I am too lazy to include type hints here :)\n for i in range(len(nums) - 1):\n found = False\n for j in range(len(nums) - 1 - i): # start == 0 and step == 1 are unnecessary\n if nums[j] &gt; nums[j + 1]:\n nums[j], nums[j + 1] = nums[j + 1], nums[j]\n found = True # it means that there is at least a swap\n if not found: # if there is no swap it means that there is no need to go for next value of i\n break\n\n return nums\n</code></pre>\n\n<p>Hope it helps.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-18T16:54:04.403", "Id": "232599", "ParentId": "232517", "Score": "3" } } ]
{ "AcceptedAnswerId": "232518", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-16T18:56:40.160", "Id": "232517", "Score": "6", "Tags": [ "python", "python-3.x", "sorting" ], "Title": "Bubble Sort Implementation in Python 3" }
232517
<p>I am writing an HTTP message coder/decoder. In my decoder I parse http messages into a http_request or http_response. In my encoder I encode one of these classes.</p> <p>Representing the messages is the easy part, but I am sure I have made some mistakes. Please review and let me know what could be improved.</p> <p>Some questions:</p> <ol> <li><p>I make the base class http_message available which is probably not ideal. Should I hide this away in a different header? Or hide some other way? any ideas?</p></li> <li><p>I don't think I need copy and assignment operators because i am not using pointers. Is that correct?</p></li> <li><p>Is the testing sufficient?</p></li> </ol> <p>Header file, http_message.hpp:</p> <pre><code>#ifndef HTTP_MESSAGE_HPP_ #define HTTP_MESSAGE_HPP_ #include &lt;string&gt; #include &lt;unordered_map&gt; #include &lt;iostream&gt; class http_message { public: http_message(); void set_version(int major, int minor); const std::string get_version() const; size_t get_body_length() const; void body(const std::string&amp; data); std::string body() const; void add_header(const std::string&amp; key, const std::string&amp; value); const std::string get_header_value(const std::string&amp; key) const; typedef const std::unordered_map&lt;std::string, std::string&gt;::const_iterator const_iterator; const_iterator begin() const { return headers_.begin(); } const_iterator end() const { return headers_.end(); } protected: void set_body_length(size_t length); std::unordered_map&lt;std::string, std::string&gt; headers_; std::string body_; std::string version_; }; class http_response : public http_message { public: unsigned status = 0; }; class http_request : public http_message { public: std::string url; std::string method; std::string query; }; std::ostream&amp; operator&lt;&lt;(std::ostream&amp; os, const http_request&amp; request); std::ostream&amp; operator&lt;&lt;(std::ostream&amp; os, const http_response&amp; request); #endif // HTTP_MESSAGE_HPP_ </code></pre> <p>http_message.cpp:</p> <pre><code>#include &lt;algorithm&gt; #include "http_message.hpp" static const std::string content_length_string("Content-Length"); static bool case_insensitive_match(std::string s1, std::string s2) { // Convert complete given string to lower case std::transform(s1.begin(), s1.end(), s1.begin(), ::tolower); // Convert complete given sub-string to lower case std::transform(s2.begin(), s2.end(), s2.begin(), ::tolower); return s1.find(s2) == 0; // must be found at start of string } http_message::http_message() : version_("HTTP/1.1") {} void http_message::set_version(int major, int minor) { version_ = "HTTP/" + std::to_string(major) + '.' + std::to_string(minor); } size_t http_message::get_body_length() const { return body_.length(); } void http_message::set_body_length(size_t length) { headers_[content_length_string] = std::to_string(length); } void http_message::add_header(const std::string&amp; key, const std::string&amp; value) { // check for Content-Length - fix header key as Content-Length to ease checking header if (case_insensitive_match(key, content_length_string)) { headers_[content_length_string] = value; } else { headers_[key] = value; } } const std::string http_message::get_version() const { return version_; } void http_message::body(const std::string&amp; data) { body_ = data; if (body_.length() &gt; 0) { headers_[content_length_string] = std::to_string(body_.length()); } else { headers_.erase(content_length_string); } } std::string http_message::body() const { return body_; } const std::string http_message::get_header_value(const std::string&amp; key) const { const auto it = headers_.find(key); return it != headers_.end() ? it-&gt;second : ""; } std::ostream&amp; operator&lt;&lt;(std::ostream&amp; os, const http_request&amp; request) { os &lt;&lt; "Method=" &lt;&lt; request.method &lt;&lt; std::endl; os &lt;&lt; "url: " &lt;&lt; request.url &lt;&lt; std::endl; if (request.get_body_length() &gt; 0) { os &lt;&lt; "body: " &lt;&lt; request.body() &lt;&lt; std::endl; } if (!request.query.empty()) { os &lt;&lt; "query: " &lt;&lt; request.query &lt;&lt; std::endl; } // print all headers for (const auto&amp; header : request) { os &lt;&lt; header.first &lt;&lt; ": " &lt;&lt; header.second &lt;&lt; std::endl; } return os; } std::ostream&amp; operator&lt;&lt;(std::ostream&amp; os, const http_response&amp; response) { os &lt;&lt; "Status=" &lt;&lt; response.status &lt;&lt; std::endl; if (response.get_body_length() &gt; 0) { os &lt;&lt; "body: " &lt;&lt; response.body() &lt;&lt; std::endl; } // print all headers for (const auto&amp; header : response) { os &lt;&lt; header.first &lt;&lt; ": " &lt;&lt; header.second &lt;&lt; std::endl; } return os; } </code></pre> <p>Some testing: test.cpp:</p> <pre><code>#include "gtest/gtest.h" #include "http_message.hpp" // consider having getter functions to give user no. headers static size_t count_headers(const http_request&amp; request) { int count(0); for (const auto&amp; header : request) { count++; } return count; } TEST(http_message_tests, message_length_calculated_correctly) { http_request rq; rq.add_header("Content-Type", "text/plain"); rq.body("Text message"); EXPECT_EQ(rq.get_header_value("Content-Length"), "12"); EXPECT_EQ(rq.get_body_length(), 12); } TEST(http_message_tests, message_length_with_no_body_zero) { http_request rq; rq.add_header("Content-Type", "text/plain"); EXPECT_EQ(rq.get_header_value("Content-Length"), ""); EXPECT_EQ(rq.get_body_length(), 0); } TEST(http_message_tests, message_without_version_set_defaults_to_http_v1_1) { http_request rq; EXPECT_EQ(rq.get_version(), "HTTP/1.1"); } TEST(http_message_tests, message_version_correctly_set) { http_request rq; rq.set_version(1, 0); EXPECT_EQ(rq.get_version(), "HTTP/1.0"); } TEST(http_message_tests, message_header_correctly_set) { http_request rq; rq.add_header("Content-Type", "text/plain"); EXPECT_EQ(rq.get_header_value("Content-Type"), "text/plain"); } TEST(http_message_tests, http_response_correctly_default_initialised) { http_response rs; EXPECT_EQ(rs.get_header_value("Content-Length"), ""); EXPECT_EQ(rs.status, 0u); EXPECT_EQ(rs.get_version(), "HTTP/1.1"); } TEST(http_message_tests, http_request_correctly_default_initialised) { http_request rq; EXPECT_EQ(rq.get_header_value("Content-Length"), ""); EXPECT_EQ(rq.get_version(), "HTTP/1.1"); EXPECT_EQ(rq.get_body_length(), 0); EXPECT_EQ(count_headers(rq), 0); } TEST(http_message_tests, http_response_headers_added_correctly) { http_response rs; EXPECT_EQ(rs.get_header_value("Content-Length"), ""); EXPECT_EQ(rs.status, 0u); EXPECT_EQ(rs.get_version(), "HTTP/1.1"); } TEST(http_message_tests, http_request_headers_added_correctly) { http_request rq; rq.method = "GET"; rq.url = "/"; rq.set_version(1, 1); rq.add_header("Host", "localhost"); rq.add_header("Connection", "keep-alive"); rq.add_header("Upgrade-Insecure-Requests", "1"); rq.add_header("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML,like Gecko) Chrome/76.0.3809.132 Safari/537.36"); rq.add_header("Sec-Fetch-Mode", "navigate"); rq.add_header("Sec-Fetch-User", "?1"); rq.add_header("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3"); rq.add_header("Sec-Fetch-Site", "none"); rq.add_header("Accept-Encoding", "gzip, deflate, br"); rq.add_header("Accept-Language", "en-US,en;q=0.9"); EXPECT_EQ(rq.url, "/"); EXPECT_EQ(rq.get_version(), "HTTP/1.1"); EXPECT_EQ(rq.method, "GET"); EXPECT_EQ(rq.query, ""); EXPECT_EQ(rq.get_header_value("Content-Length"), ""); EXPECT_EQ(rq.get_header_value("Host"), "localhost"); EXPECT_EQ(rq.get_header_value("Connection"), "keep-alive"); EXPECT_EQ(rq.get_header_value("Upgrade-Insecure-Requests"), "1"); EXPECT_EQ(rq.get_header_value("User-Agent"), "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML,like Gecko) Chrome/76.0.3809.132 Safari/537.36"); EXPECT_EQ(rq.get_header_value("Sec-Fetch-Mode"), "navigate"); EXPECT_EQ(rq.get_header_value("Sec-Fetch-User"), "?1"); EXPECT_EQ(rq.get_header_value("Accept"), "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3"); EXPECT_EQ(rq.get_header_value("Sec-Fetch-Site"), "none"); EXPECT_EQ(rq.get_header_value("Accept-Encoding"), "gzip, deflate, br"); EXPECT_EQ(rq.get_header_value("Accept-Language"), "en-US,en;q=0.9"); EXPECT_EQ(rq.body(), ""); EXPECT_EQ(count_headers(rq), 10); } TEST(http_message_tests, http_request_headers_length_header_automatically_added) { http_request rq; rq.method = "POST"; rq.url = "/welcome.php"; rq.set_version(1, 0); rq.add_header("Host", "www.iteloffice.com"); rq.add_header("Content-Type", "application/x-www-form-urlencoded"); std::string body("name=Joe+Bloggs&amp;email=joe%40bloggs.com"); rq.body(body); EXPECT_EQ(rq.url, "/welcome.php"); EXPECT_EQ(rq.get_version(), "HTTP/1.0"); EXPECT_EQ(rq.method, "POST"); EXPECT_EQ(rq.query, ""); EXPECT_EQ(rq.get_header_value("Content-Length"), std::to_string(body.length())); EXPECT_EQ(rq.get_header_value("Host"), "www.iteloffice.com"); EXPECT_EQ(rq.get_header_value("Content-Type"), "application/x-www-form-urlencoded"); EXPECT_EQ(rq.body(), body); EXPECT_EQ(count_headers(rq), 3); // Content-Length automatically added } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-16T23:21:12.430", "Id": "454089", "Score": "0", "body": "Did you know the existence of boost beast?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-18T16:42:45.187", "Id": "454256", "Score": "0", "body": "Is there any possibility you could add \"gtest/gtest.h\" to the question?" } ]
[ { "body": "<h2>I make the base class http_message available which is probably not ideal. Should I hide this away in a different header? Or hide some other way? any ideas?</h2>\n\n<p>Each class should have it's own header file. Right now if any of the 3 classes are edited all files need to recompile, if each class had it's own header file, the only time every file needs to recompile is when the <code>http_message</code> class is modified. The overrides for the <code>&lt;&lt;</code> operator should be defined for <code>http_response</code> in the <code>http_response</code> header file and for the <code>http_request</code> in the <code>http_request</code> header file.</p>\n\n<h2>Is the testing sufficient?</h2>\n\n<p>Since the \"gtest/gtest.h\" file was not provided I was unable to run the unit tests, however, there are some logical extensions:\nSince <code>http_message</code> is not an abstract class there should be some unit tests for <code>http_message</code> that are independent of the <code>http_request</code> and <code>http_response</code> unit tests. The <code>http_message</code> unit tests should precede the other unit tests so that if the <code>http_message</code> unit tests fail the other tests are not executed.</p>\n\n<h2>Unused Protected Function</h2>\n\n<p>Neither <code>http_request</code> nor <code>http_response are currently using the protected function</code>http_message::set_body_length(size_t length)<code>so it is unclear that this function is needed, since it also isn't used by</code>http_message`.</p>\n\n<h2>Avoid Using Macros in C++ When Possible.</h2>\n\n<p>It is unclear that macros are used in the unit tests since \"gtest/gtest.h\" is not provided, however, <code>TEST()</code> and <code>EXPECT_EQ()</code> appears to be macros. Macros are not type safe and can might not be the best option. This may cause the unit testing to be less accurate than it could be.</p>\n\n<p>Perhaps a unit test class might be better.</p>\n\n<p>You might also want to look into using <a href=\"https://en.wikipedia.org/wiki/CppUnit\" rel=\"nofollow noreferrer\">cppunit</a>. This would tell you how much of the source code is getting test coverage.</p>\n\n<h2>Possible Optimizations</h2>\n\n<p>There are many functions in <code>http_message</code> that could be inlined. That means that the body of the functions could also be in <code>http_message.hpp</code>. In line function may be optized and speed up the code or make the executable code smaller. Candidates for inlining are\n - void set_version(int major, int minor)<br>\n - const std::string get_version()<br>\n - std::string body()<br>\n - get_header_value(const std::string&amp; key) </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-19T06:33:04.643", "Id": "454304", "Score": "2", "body": "For what it's worth, gtest/gtest.h, TEST and EXPECT_EQ are almost certainly referring to [Google Test](https://github.com/google/googletest). I generally prefer it over cppunit (though I prefer [Catch2](https://github.com/catchorg/Catch2) over either). Most unit tests use macros so (among other things) `__FILE__` and `__LINE__` will expand to the location of a failing test." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-19T15:18:21.740", "Id": "454378", "Score": "0", "body": "@JerryCoffin Thanks for the clarification." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-20T09:52:58.667", "Id": "454493", "Score": "0", "body": "Modern compilers can inline functions across compilation units. Moving the source to the header file is less desirable then simply allowing the compiler to do its job." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-18T19:52:14.867", "Id": "232610", "ParentId": "232519", "Score": "2" } }, { "body": "<p>I'll just go from top to bottom, not in the order of importance:</p>\n\n<ol>\n<li><code>size_t get_body_length() const;</code> does not make much sense. Also not clear what it does. If it is the length of body, why not just body().size()? If this is Content-Length, why is it called body length and what's wrong with getting it from the headers?</li>\n<li><code>void body(const std::string&amp; data)</code> name is inconsistent with other set_* functions. In general, prefer verb-named functions</li>\n<li>In <code>get_header_value</code> prefer <code>optional</code> to returning a special value like an empty string</li>\n<li>The ability to iterate a http_message as a list of headers is counter-intuitive to say the least.</li>\n<li>You might want to consider adding named constants for response codes and HTTP verbs</li>\n<li><code>http_message::add_header</code> treats Content-length as case-insensitive, while other headers as case-sensitive, which violates HTTP standard and is counter-intuitive to anyone not familiar with the internal implementation of your class</li>\n<li><code>case_insensitive_match</code>, though probably unneeded, I'd still like to point out that it can be simplified in several ways. One of them is using std::equal/std::mismatch with a predicate which would give you a no-copy solution</li>\n<li>Probably most important is that I don't see a use-case for this class as it is because it lacks a lot of features like serializing/deserializing to wire format.</li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-19T13:09:25.867", "Id": "454347", "Score": "0", "body": "great feedback, thanks. I am writing a separate encoder/decoder. Any more hints on how to write the case-insensitive matching with std::equal/std::mismatch?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-19T13:22:28.310", "Id": "454350", "Score": "0", "body": "@arcomber, something like this: return (s1.size() == s2.size()) && std::equal(s1.begin(), s1.end(), s2.begin(), [](char x, char y){ return std::tolower(x) == std::tolower(y); });" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-19T12:52:55.210", "Id": "232642", "ParentId": "232519", "Score": "1" } } ]
{ "AcceptedAnswerId": "232642", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-16T19:13:01.313", "Id": "232519", "Score": "5", "Tags": [ "c++", "object-oriented", "unit-testing" ], "Title": "classes to represent a HTTP request and response in C++" }
232519
<p>I have just started messing around with PHP/SQL and came up with a simple sign-in application that checks if your sign-in information is valid based on database information. Here is my code:</p> <pre><code>&lt;!DOCTYPE HTML&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt;Sample Database Page&lt;/title&gt; &lt;style&gt; body { font-family: sans-serif; } .error { display: none; margin: 10px; align-content: center; justify-content: flex-start; background-color: red; border-radius: 5px; } .error &gt; p { display: block; width: auto; } &lt;/style&gt; &lt;/head&gt; &lt;body&gt; &lt;form method="post" action="&lt;?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?&gt;" id="signInForm"&gt; Username: &lt;input type="text" name="username" maxlength="15"/&gt; Password: &lt;input type="text" name="password" maxlength="15"/&gt; &lt;input type="submit"/&gt; &lt;/form&gt; &lt;div class="errorContainer"&gt; &lt;div class="error" id="usernameError1"&gt; &lt;img src="exclamation_mark.png" width="35px"/&gt; &lt;p&gt;Your username contains invalid characters&lt;/p&gt; &lt;/div&gt; &lt;div class="error" id="passwordError1"&gt; &lt;img src="exclamation_mark.png" width="35px"/&gt; &lt;p&gt;Your password contains invalid characters&lt;/p&gt; &lt;/div&gt; &lt;div class="error" id="usernameError2"&gt; &lt;img src="exclamation_mark.png" width="35px"/&gt; &lt;p&gt;The username you enter could not be found. Please try again.&lt;/p&gt; &lt;/div&gt; &lt;div class="error" id="passwordError2"&gt; &lt;img src="exclamation_mark.png" width="35px"/&gt; &lt;p&gt;The password is incorrect. Please try again.&lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;?php require __DIR__ . "/helper_functions.php"; # Contains 7 functions # openConnection: opens the database connection # closeConnection: closes the database connection # isValidUsername: checks user input against this regex: /^[A-Za-z0-9_]+$/ # isValidPassword: checks user input against this regex: /^[A-Za-z0-9!@$#%_]+$/ # escapeSymbols: escapes $ (\$) # displayError: uses Javascript to set the display of the selected error message to flex # displayUsername: inserts the provided username back into it's input field using Javascript if an error has occurred if ($_SERVER["REQUEST_METHOD"] == "POST") { $conn = openConnection(); if ($conn-&gt;connect_error) { die("Connection failed: " . $conn-&gt;connect_error); } $return = false; if (!isValidUsername($_POST["username"])) { displayError("usernameError1"); $return = true; } if (!isValidPassword($_POST["password"])) { displayError("passwordError1"); $return = true; } if ($return) { displayUsername($_POST["username"]); closeConnection($conn); return; } $username = $_POST["username"]; $password = escapeSymbols($_POST["password"]); $sql = "SELECT * FROM `customer_data` WHERE username = '" . $username . "'"; $result = mysqli_query($conn, $sql); if (mysqli_num_rows($result) == 0) { displayError("usernameError2"); closeConnection($conn); return; } $row = $result-&gt;fetch_assoc(); $correctPassword = $row["password"]; if ($password == $correctPassword) { echo "Access granted!"; closeConnection($conn); } else { displayError("passwordError2"); displayUsername($_POST["username"]); closeConnection($conn); } } ?&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>When you submit the form, a few things happen:</p> <ol> <li>A connection to the database is set up. If the database cannot be found, the application dies.</li> <li>The application checks if the submitted fields don't contain invalid characters. If one does, an error is displayed for that field, and if both do, error messages are displayed for each. The submitted username is displayed again in it's input field. This process stops.</li> <li>The username is then checked for in the database. If it is not found, an error message is displayed, the username submitted by the user is displayed in it's input field, and this process is stopped. Otherwise, it checks if the password (with $ escaped) is the users. If it is, the program displays "Access granted!" and the input is valid. Otherwise, an error message is displayed, the previously submitted username is displayed in it's input field, and this process ends.</li> </ol> <p>What can I do to improve this program?</p> <hr> <p><strong>UPDATE:</strong></p> <p>Here is the code for helper_functions.php as requested:</p> <pre><code>&lt;?php function openConnection() { $dbhost = "localhost"; $dbuser = "root"; $dbpass = ""; $db = "online_store_database"; $conn = new mysqli($dbhost, $dbuser, $dbpass, $db) or die("Connect failed: %s\n" . $conn -&gt; error); return $conn; } function closeConnection($conn) { $conn -&gt; close(); } function isValidUsername($data) { return preg_match('/^[A-Za-z0-9_]+$/', $data); } function isValidPassword($data) { return preg_match('/^[A-Za-z0-9!@$#%_]+$/', $data); } function escapeSymbols($string) { return str_replace("$", "\$", $string); } function displayError($errorName) { echo "&lt;script type='text/javascript'&gt;document.getElementById('" . $errorName . "').style.display = 'flex';&lt;/script&gt;"; } function displayUsername($username) { echo "&lt;script async type='text/javascript'&gt;document.getElementsByName('username')[0].value = '" . $username . "';&lt;/script&gt;"; } ?&gt; </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-16T20:55:30.850", "Id": "454065", "Score": "0", "body": "Just some quick points - you should be using prepared statements and also not store plain text passwords (look into [password_hash](https://stackoverflow.com/questions/30279321/how-to-use-password-hash). Try not to mix the procedural and OO versions of the mysqli api (`mysqli_num_rows` and then `->fetch_assoc`)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-16T20:58:48.580", "Id": "454066", "Score": "0", "body": "It may be helpful to include the source code for helper_functions.php as some of these helper functions seem to serve little real purpose." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-16T21:09:02.043", "Id": "454071", "Score": "0", "body": "@NigelRen Can you explain what you're saying in regards to prepared statements and procedural/object-oriented versions of MySQLi in your first comment? I just started with PHP." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-16T21:15:14.073", "Id": "454073", "Score": "0", "body": "@Nigel please do not post review points as comments." } ]
[ { "body": "<ul>\n<li><p><code>openConnection()</code> is written to <code>die()</code> internally if there is a connection error, there is no need for you to write:</p>\n\n<pre><code>if ($conn-&gt;connect_error) {\n die(\"Connection failed: \" . $conn-&gt;connect_error);\n}\n</code></pre>\n\n<p>I do not recommend that you provide the precise mysql error when something goes wrong. It is better practice to provide a vague explanation to the end user when this occurs. They don't need the specificity -- just tell them that it wasn't their fault and that you intend to fix it / they should try again later / they should contact you (if you are not actively monitoring the site).</p>\n\n<p>Nor do I recommend that you litter your script with <code>die()</code> calls. They will break an otherwise valid markup. (<code>die()</code> will prevent the closing tags from being printed at the bottom of your document.)</p></li>\n<li><p><code>\\w</code> = <code>[A-Za-z0-9_]</code> for this reason you can simplify your code as:</p>\n\n<pre><code>function isValidUsername($data) {\n return preg_match('/^\\w+$/', $data);\n}\n</code></pre>\n\n<p>and </p>\n\n<pre><code>function isValidPassword($data) {\n return preg_match('/^[\\w!@$#%]+$/', $data);\n}\n</code></pre>\n\n<p>However, I must urge you not to limit the valid characters in a password entry -- this is simply bad practice because it will lighten the workload for someone who endeavors to brute force attack your login system. You should only be checking that it has length, and if you want to indicate password strength, implement some rules about expected characters and minimum password length.</p></li>\n<li><p>Throw <code>escapeSymbols()</code> away entirely. You should not be escaping or adjusting a user's password -- ever. If they typed it, it should be saved verbatim.</p></li>\n<li><p>Never store unencrypted passwords into your database. The guidance you require on this topic is far to vast to write into a single post here. Encryption is a subject that professionals specialize in, so the volume of understanding is yours to decide. At the very least, please <em>start but don't finish</em> reading here: <a href=\"https://stackoverflow.com/q/401656/2943403\">Secure hash and salt for PHP passwords</a></p></li>\n<li><p>Prepared statements are a must for helping to keep your site secure and stable. Please <em>start but don't finish</em> reading here: <a href=\"https://stackoverflow.com/q/1290975/2943403\">How to create a secure mysql prepared statement in php?</a></p></li>\n<li><p>In alignment with the previous item, you must not trust user input to be safe to inject into your content either. You should implement a sanitizing layer before allowing any of their data to make it to your display. Please <em>start but don't finish</em> reading here: <a href=\"https://stackoverflow.com/q/129677/2943403\">How can I sanitize user input with PHP?</a></p></li>\n<li><p>Unless your main form script is being called by a function, I don't understand why you have <code>return</code> written -- there will be no place to return to, just remove them</p></li>\n<li><p>Do not mix object-oriented with procedural mysqli syntax. Pick one and stick with it. I recommend OO because it is more succinct. You start with <code>$conn-&gt;connect_error</code> which is OO, so just use the same syntax onward. (in case you don't follow my meaning, <code>mysqli_query()</code> is procedural syntax <code>$conn-&gt;query()</code> is OO; but again, look into prepared statements.)</p></li>\n<li><p>Don't bother with closing your database connection. PHP will do it for you when your script completes.</p></li>\n<li><p>Try to structure your battery of conditions into a considerate condition block with \"failed\" outcomes written first, then the successful outcome last while avoiding any <code>exit()</code>/<code>die()</code> calls to interrupt the flow -- if this is a consistent design throughout your project, your project will be easier to read and maintain. </p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-16T21:59:01.713", "Id": "454078", "Score": "1", "body": "Thank you for accepting @Brendon, but it can be an advantageous strategy to withhold the green tick until adequate time passes to allow the submission of multiple reviews. Some people will not review a page that already has a green tick (I am not one of those people). If you would like to remove the green tick to \"keep your question in the game\", that is just fine with me. You will stand to receive more insights this way." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-16T21:51:32.483", "Id": "232525", "ParentId": "232522", "Score": "2" } }, { "body": "<p>Just a few things to add to mickmackusa's excellent answer...</p>\n\n<ul>\n<li><p>Consider using the <code>&lt;label&gt;</code> HTML tag </p>\n\n<p>In things like</p>\n\n<pre><code>Username:\n&lt;input type=\"text\" name=\"username\" maxlength=\"15\"/&gt;\n</code></pre>\n\n<p>When you click on a label, focus is sent to the input associated with it. This helps improve accessibility as well as other benefits - <a href=\"https://stackoverflow.com/questions/7636502/why-use-label\">Why use <code>&lt;label&gt;</code>?</a></p>\n\n<pre><code>&lt;label for=\"username\"&gt;Username:&lt;/label&gt;\n&lt;input type=\"text\" id=\"username\" name=\"username\" maxlength=\"15\"/&gt;\n</code></pre></li>\n<li><p>A general point about SQL</p>\n\n<pre><code>$sql = \"SELECT * FROM `customer_data` WHERE username = '\" . $username . \"'\";\n</code></pre>\n\n<p>Normally I would suggest only selecting the columns which you actually use. So in this case you would only use (including the addition of prepared statements)</p>\n\n<pre><code>$sql = \"SELECT `password` FROM `customer_data` WHERE `username` = ?\";\n</code></pre>\n\n<p>(for me) It is also worth sticking to using backticks round column and table names. If you always use them it can help as reserved words in table or column names can randomly become very useful (<code>order</code> tables can be common) and then SQL starts to complain unless it's in backticks.</p></li>\n<li><p>In the next line, you don't check if the command actually worked...</p>\n\n<pre><code>$result = mysqli_query($conn, $sql);\n</code></pre>\n\n<p>You can either use something like</p>\n\n<pre><code>if ($result = mysqli_query($conn, $sql)) {\n // process successful query\n}\n</code></pre>\n\n<p>or use</p>\n\n<pre><code>mysqli_report(MYSQLI_REPORT_STRICT);\n</code></pre>\n\n<p>which makes PHP throw an exception when any errors occur (<a href=\"https://stackoverflow.com/questions/18457821/how-to-make-mysqli-throw-exceptions-using-mysqli-report-strict\">explained here</a>)</p></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-17T07:28:02.640", "Id": "232540", "ParentId": "232522", "Score": "2" } }, { "body": "<p>I am more a man of practice than of advise. </p>\n\n<p>Maybe because I feel the responsibility for the advise I give out. Some advises are much simpler to be given than implemented. I need to make sure that my advise won't raise more questions than it does answer - otherwise it will be anything but help. It is simple to say \"use prepared statements\" but how exactly one should use it? It is simple to say \"do not provide the precise mysql error\" but how to do that? </p>\n\n<p>That's why I prefer a complete working solution to a wordy sermon. And, being obsessed with the knowledge re-use, I am writing articles that provide the full story. </p>\n\n<p>Here is one on the <a href=\"https://phpdelusions.net/articles/error_reporting\" rel=\"nofollow noreferrer\">error reporting</a>. It basically explains that your database interaction code should (almost) never handle its errors - it's just none of its business. So just leave database errors alone. You'll be to deal with them later, when you'd feel the urge to (of course it is explained in the above article how to do that) but for the moment you can put it aside.<br>\nInstead, just <em>configure your PHP</em> to handle errors uniformly, according to the server role.</p>\n\n<p>Here is one about <a href=\"https://phpdelusions.net/mysqli/mysqli_connect\" rel=\"nofollow noreferrer\">mysqli_connect()</a>. The connection code is not as simple as just a single line. There are many options to pay attention for. </p>\n\n<p>Here is one about <a href=\"https://phpdelusions.net/mysqli_examples/prepared_select\" rel=\"nofollow noreferrer\">running SELECT queries with mysqli</a> in general and <a href=\"https://phpdelusions.net/mysqli/password_hash\" rel=\"nofollow noreferrer\">checking login and password against a database</a> in particular.</p>\n\n<p>Other issues in your code are:</p>\n\n<ul>\n<li>of course, passwords <strong>must</strong> be hashed. </li>\n<li>after the successful login, you have to store the user credentials in a <strong>session</strong>. and then relocate a user to some other page. </li>\n<li>there is not much point in strictly validating the input. It makes sense for the registration but here you aren't going to record anything, so you can put aside most validations</li>\n<li>therefore, there is no point in the whole return business. The only error message you would have is one that says login or password is incorrect. </li>\n<li>there is a rule of thumb says all PHP code must go first and HTML later. It makes sense as your PHP code may want to send an HTTP header first\n\n<ul>\n<li>besides, it is always a good idea to separate HTML from PHP.</li>\n</ul></li>\n<li>escapeSymbols() is completely useless if not harmful</li>\n<li>mysqli_num_rows() is also a useless function, it could be skipped seven days in a week</li>\n<li>close connection is... also that. If your script is not supposed to work from the point where this function is called (which happens most of time) there is no point in closing the connection manually, PHP will do it for you</li>\n<li>the empty form action attribute effectively says \"sand the form to the current URL\", so it's much simpler and less error prone to leave it empty</li>\n<li>the php closing tag (?>) is also useless if it's the last thing in the file</li>\n</ul>\n\n<p>Given all the above here is your code refactored</p>\n\n<p>helper_functions.php</p>\n\n<pre><code>&lt;?php\n\nerror_reporting(E_ALL);\nini_set('display_errors', 1); // change it to 0 on production\nini_set('log_errors', 1);\n\nrequire __DIR__ . \"/mysqli.php\";\n\nfunction isValidUsername($data) {\n return preg_match('/^[A-Za-z0-9_]+$/', $data);\n}\nfunction displayError($errorName) {\n echo \"&lt;script type='text/javascript'&gt;document.getElementById('\" . $errorName . \"').style.display = 'flex';&lt;/script&gt;\";\n}\n</code></pre>\n\n<p>mysqli.php</p>\n\n<pre><code>&lt;?php\n$host = '127.0.0.1';\n$db = 'online_store_database';\n$user = 'root';\n$pass = '';\n$charset = 'utf8mb4';\n\nmysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);\ntry {\n $mysqli = new mysqli($host, $user, $pass, $db);\n $mysqli-&gt;set_charset($charset);\n} catch (\\mysqli_sql_exception $e) {\n throw new \\mysqli_sql_exception($e-&gt;getMessage(), $e-&gt;getCode());\n}\nunset($host, $db, $user, $pass, $charset); // we don't need them anymore\n</code></pre>\n\n<p>the main PHP file</p>\n\n<pre><code>&lt;?php\nif ($_SERVER[\"REQUEST_METHOD\"] == \"POST\") {\n require __DIR__ . \"/helper_functions.php\";\n\n $stmt = $conn-&gt;prepare(\"SELECT * FROM `customer_data` WHERE username = ?\");\n $stmt-&gt;bind_param(\"s\", $_POST[\"username\"]);\n $stmt-&gt;execute();\n $result = $stmt-&gt;get_result();\n $row = $result-&gt;fetch_assoc();\n if ($row &amp;&amp; password_verify($_POST[\"password\"], $row[\"password\"]))\n {\n session_start();\n $_SESSION['user'] = $row;\n header(\"Location: /\");\n exit;\n } else {\n $error = 'passwordError2';\n }\n}\ninclude 'form.php';\n</code></pre>\n\n<p>form.php</p>\n\n<pre><code>&lt;!DOCTYPE HTML&gt;\n&lt;html&gt;\n&lt;head&gt;\n&lt;title&gt;Sample Database Page&lt;/title&gt;\n&lt;style&gt;\n body {\n font-family: sans-serif;\n }\n .error {\n display: none;\n margin: 10px;\n align-content: center;\n justify-content: flex-start;\n background-color: red;\n border-radius: 5px;\n }\n .error &gt; p {\n display: block;\n width: auto;\n }\n&lt;/style&gt;\n&lt;/head&gt;\n&lt;body&gt;\n&lt;form method=\"post\" action=\"\" id=\"signInForm\"&gt;\n Username:\n &lt;input type=\"text\" name=\"username\" maxlength=\"15\"/&gt;\n Password:\n &lt;input type=\"text\" name=\"password\" maxlength=\"15\"/&gt;\n &lt;input type=\"submit\"/&gt;\n&lt;/form&gt;\n&lt;div class=\"errorContainer\"&gt;\n &lt;div class=\"error\" id=\"usernameError1\"&gt;\n &lt;img src=\"exclamation_mark.png\" width=\"35px\"/&gt;\n &lt;p&gt;Your username contains invalid characters&lt;/p&gt;\n &lt;/div&gt;\n &lt;div class=\"error\" id=\"passwordError1\"&gt;\n &lt;img src=\"exclamation_mark.png\" width=\"35px\"/&gt;\n &lt;p&gt;Your password contains invalid characters&lt;/p&gt;\n &lt;/div&gt;\n &lt;div class=\"error\" id=\"usernameError2\"&gt;\n &lt;img src=\"exclamation_mark.png\" width=\"35px\"/&gt;\n &lt;p&gt;The username you enter could not be found. Please try again.&lt;/p&gt;\n &lt;/div&gt;\n &lt;div class=\"error\" id=\"passwordError2\"&gt;\n &lt;img src=\"exclamation_mark.png\" width=\"35px\"/&gt;\n &lt;p&gt;The password is incorrect. Please try again.&lt;/p&gt;\n &lt;/div&gt;\n&lt;/div&gt;\n&lt;?php if (!empty($error)) displayError(\"passwordError2\"); ?&gt;\n&lt;/body&gt;\n&lt;/html&gt;\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-18T13:46:03.647", "Id": "232591", "ParentId": "232522", "Score": "1" } } ]
{ "AcceptedAnswerId": "232525", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-16T20:43:11.870", "Id": "232522", "Score": "4", "Tags": [ "beginner", "php", "html", "mysql", "css" ], "Title": "Simple PHP Form Application" }
232522
<p>I wanted a routine that would allow me to use the NumPad keys for directional commands. <kbd>1</kbd>-<kbd>9</kbd> for each compass point, <kbd>-</kbd> for up and <kbd>+</kbd> for down. If one of these keys are not pressed, it would act as a regular <code>readline()</code>. I threw in a few simple lines to act as timers, obviously this was just to complete it.</p> <p>This is my solution. It works fairly well, but thinking there is a better way.</p> <pre><code> string orders; bool lives = true; int counter = 0; char[] delimeterChars = { ' ', ',', '.', ':', '\t' }; Console.Write("What shall I do? "); do { string verb = ""; string noun = "game"; orders = Ask(); Console.WriteLine("You pressed " + orders); counter = 0; string[] words = orders.Split(delimeterChars); verb = words[0].ToLower(); if (words.Length &gt; 1) { noun = words[1].ToLower(); } Console.WriteLine("verb is " + verb); Console.WriteLine("noun is " + noun); if (verb == "q" || verb == "quit") { noun = "game"; lives = false; } } while (lives == true); if (lives == false) { Console.WriteLine("Game over"); } } public static string Ask() { do { ThirstTimer(); HungerTimer(); ParalysisTimer(); PoisonTimer(); AttackTimer(); SpellTimer(); } while (Console.KeyAvailable == false); var cki = Console.ReadKey(true); Console.Write(cki.Key.ToString()); string VeRb = cki.Key.ToString(); switch (VeRb) { case "NumPad1": return "go southwest"; case "NumPad2": return "go south"; case "NumPad3": return "go southeast"; case "NumPad4": return "go west"; case "NumPad6": return "go east"; case "NumPad7": return "go northwest"; case "NumPad8": return "go north"; case "NumPad9": return "go northeast"; case "Add": return "go down"; case "Subtract": return "go up"; // If numpad is not used, get letter pressed and add to input. default: string Verbage = Console.ReadLine(); string VERB = cki.Key.ToString() + Verbage; return VERB; } } public static void ThirstTimer() { //Console.WriteLine("You are thirsty."); } // Timers include current Time, target Time, and 30 second display timer } public static void HungerTimer() { //Console.WriteLine("You are hungry."); }// Timers include current Time, target Time, and 30 second display timer } public static void ParalysisTimer() { //Console.WriteLine("You are paralysed."); }// Timers include current Time, target Time, a display everytime you attempt to move while active. } public static void PoisonTimer() { //Console.WriteLine("You have been poisoned."); }// Timers include current Time, target Time, and 30 second display timer } public static void AttackTimer() { //Console.WriteLine("Checking Attack delay."); }// Timers include current Time, target Time, and 30 second display timer } public static void SpellTimer() { //Console.WriteLine("Checking Spell Delay."); }// Timers include current Time, target Time, and display timer based on mana usage } </code></pre>
[]
[ { "body": "<p>A couple of things to mention:</p>\n\n<p>Whenever you're receiving input from the user, you should write your code assuming the user will screw up and type the wrong thing. I don't see any checks to handle that.</p>\n\n<p>When your <code>switch</code> block is only converting one value to another, you should be looking for a collection to help with that. In this case, in the <code>Ask</code> method, I would suggest an enum mapped to the character code values that you'll need:</p>\n\n<pre><code>enum Directions\n{\n none = 0,\n southwest = 97,\n south,\n southeast,\n west,\n east = 102,\n northwest,\n north,\n northeast,\n up = 107,\n down = 109\n}\n</code></pre>\n\n<p>This shortens the code in the <code>Ask</code> method considerably:</p>\n\n<pre><code>public static string Ask()\n{\n do\n {\n ThirstTimer();\n HungerTimer();\n ParalysisTimer();\n PoisonTimer();\n AttackTimer();\n SpellTimer();\n } while (Console.KeyAvailable == false);\n var cki = Console.ReadKey(true);\n string keyString = cki.Key.ToString();\n Console.Write(keyString);\n Directions direction = Directions.none;\n if(Enum.TryParse&lt;Directions&gt;(((int)cki.Key).ToString(), out direction))\n {\n return $\"go {direction}\";\n }\n else\n {\n string Verbage = Console.ReadLine();\n return keyString + Verbage;\n }\n\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-20T21:16:43.797", "Id": "454560", "Score": "0", "body": "Thank you tinstaafl, That's nice and simple... I will certainly do that.\nSo much C# to learn, so little time. Now that that is settled, just for conversation and learning, are there any other methods you would consider?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-21T02:10:47.237", "Id": "454569", "Score": "0", "body": "At this time I don't see much else to change. Once you have it more fleshed out, the community will be happy to examine it more." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-21T02:48:32.087", "Id": "454570", "Score": "0", "body": "Awesome.. Thanks again" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-19T05:42:37.023", "Id": "232624", "ParentId": "232524", "Score": "3" } } ]
{ "AcceptedAnswerId": "232624", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-16T21:28:09.003", "Id": "232524", "Score": "5", "Tags": [ "c#", "beginner" ], "Title": "RPG Parser routine" }
232524
<p>This is a program that I created using Python. Please help me optimize the code.</p> <pre><code>import time import sys import socket from time import localtime, strftime # start up system def start(): print("Welcome, please choose what to do") choice = input('register/login ') if choice == 'register': register() elif choice == 'login': username() elif choice == 'admin': username() else: problems() def register(): registeragain = False global user global passs user = input('Please register your username : ') passs = input('Please register your password : ') register = input('Do you want to register another account? Y/N : ') if register == 'Y': registeragain = True register() elif register == 'N': username() else: print("Error") problems() # login system def username(): global admin admin = 'Max' userinputname = input('Please enter the username : ') if userinputname == admin or userinputname == user: password() elif userinputname != user: print('Wrong username, please try again') username() else: problems() def password(): x = 1 global adminpass adminpass = 'Luo' userinputpass = input('Please enter the password : ') if userinputpass == adminpass: adminlogin() elif userinputpass == passs: loading() elif userinputpass != passs: print('Wrong password, please try again') x += 1 if x &gt; 2: exit else: problems() # main menu def loading(): toolbar_width = 40 # setup toolbar sys.stdout.write("[%s]" % (" " * toolbar_width)) sys.stdout.flush() # return to start of line, after '[' sys.stdout.write("\b" * (toolbar_width+1)) for i in range(toolbar_width): time.sleep(0.1) # do real work here # update the bar sys.stdout.write("-") sys.stdout.flush() sys.stdout.write("]\n") # this ends the progress bar main() def main(): time.sleep(3) print("Welcome to the main screen") time.sleep(3) print("Menu: current time, ipchecker, quit") time.sleep(2) mainmenu = input('Enter: ') if mainmenu == 'current time': telldate() elif mainmenu == 'ipchecker': ipchecker() elif mainmenu == 'quit': leave() elif mainmenu == 'cal': cal() else: problems() # solutions def problems(): print("We are truly sorry that you have experienced a problem, please contact us at 123pythonlogin@gmail.com") option = input('Would you like to return to the main menu? Y/N ') if option == 'Y': main() else: exit() # admin def adminlogin(): print("Welcome admin") mainadmin = input('Enter: ') if mainadmin == 'current time': telldate() elif mainadmin == 'ipchecker': ipchecker() elif mainadmin == 'quit': leave() elif mainadmin == 'cal': cal() else: problems() # functions def telldate(): localtime = time.asctime(time.localtime(time.time())) print("Local current time :", localtime) main() def ipchecker(): hostname = socket.gethostname() IPAddr = socket.gethostbyname(hostname) print("Your Computer Name is:" + hostname) print("Your Computer IP Address is: " + IPAddr) main() def cal(): numx = int(input('Enter the first number: ')) numy = int(input('Enter the second number: ')) op = input('Enter the operation(+, -, *, /): ') if op == '+': sum = numx + numy print('Your sum is ' , sum) main() elif op == '-': diff = numx - numy print('The difference is ',diff) main() elif op == '*': mult = numx * numy print('The multiple is ' ,mult) main() elif op == '/': divd = numx / numy print('The result is ' ,divd) main() else: problems() def leave(): exit() start() </code></pre>
[]
[ { "body": "<p>Some general notes:</p>\n\n<ol>\n<li><p>Global variables are usually a bad idea; state that can be accessed from everywhere is hard to read and debug because you have no idea what random function might modify it. It's extra difficult here because your globals are declared in different places.</p></li>\n<li><p>The standard way of handling errors in Python is to raise an exception that can be caught and handled.</p></li>\n<li><p>Long sequences of <code>if/elif</code> are usually an indication that your logic can either be simplified or split up.</p></li>\n</ol>\n\n<p>Here's how I might suggest writing your <code>start</code> and <code>register</code> functions, using exceptions to handle errors, a lookup table to handle dispatching your different functions, and a single state object that collects all the random global variables:</p>\n\n<pre><code>from typing import NamedTuple\n\nclass LoginState(NamedTuple):\n admin: str\n adminpass: str\n user: str\n pass: str \n\ndef start() -&gt; None:\n state = LoginState(\"Max\", \"Luo\", \"\", \"\")\n print(\"Welcome, please choose what to do\")\n menu = {\n 'register': register\n 'login': username\n 'admin': username\n }\n choice = input('register/login ')\n try:\n menu[choice](state)\n except:\n problems()\n\ndef register(state: LoginState) -&gt; None:\n state.user = input('Please register your username : ')\n state.pass = input('Please register your password : ')\n menu = {\n \"Y\": register\n \"N\": username\n }\n choice = input('Do you want to register another account? Y/N : ')\n menu[choice](state)\n</code></pre>\n\n<p>Defining your <code>state</code> as a type means that it's easier to refactor -- for example, suppose you realize that your <code>register</code> logic overwrites the username and what you actually want to do is be able to have more than one! You could change <code>user</code> and <code>pass</code> into a collection (like a <code>Dict</code>, say), and use <code>mypy</code> to tell you all the places in your program that those attributes are used so you can make the appropriate updates. If they're defined as globals, it's a lot more difficult to make sure you've updated all the places where they're used.</p>\n\n<p>The <code>menu</code> dict is IMO a little easier to expand (and read) than the big chain of <code>if/elif</code>, by providing a single obvious place where the menu options are defined.</p>\n\n<p>Having <code>problems()</code> be an exception handler means that not only does it catch the case where the user inputs an invalid command (this will cause <code>menu[choice]</code> to raise an <code>IndexError</code>), but it will also catch any unhandled exceptions raised by your other functions, so those functions don't need to call <code>problems()</code> themselves; all they have to do is raise an exception and the control flow will end up right here. In the case of <code>register()</code> I didn't have to do anything with the error case, because if an exception is raised there I know that it will be caught in <code>start()</code>.</p>\n\n<p>Since the \"present menu, make selection\" pattern is probably going to be repeated a few times in this program, I might want to make that into a function as well:</p>\n\n<pre><code>def menu_prompt(\n menu: Dict[Text, Callable[[State], None]], \n prompt: str,\n state: LoginState\n) -&gt; None:\n choice = input(prompt)\n menu[choice](state)\n</code></pre>\n\n<p>and now this:</p>\n\n<pre><code> menu = {\n 'register': register\n 'login': username\n 'admin': username\n }\n choice = input('register/login ')\n try:\n menu[choice](state)\n except:\n problems()\n</code></pre>\n\n<p>becomes:</p>\n\n<pre><code>try:\n menu_prompt({\n 'register': register\n 'login': username\n 'admin': username\n }, 'register/login ', state)\nexcept:\n problems()\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-16T22:56:26.273", "Id": "454085", "Score": "0", "body": "and what else should I replace the global variables with?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-16T23:00:55.783", "Id": "454086", "Score": "0", "body": "You don't need to replace them with more than one thing. :) Any particular piece of state should only live in one place as a general rule." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-16T22:51:53.753", "Id": "232529", "ParentId": "232526", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-16T22:05:33.433", "Id": "232526", "Score": "3", "Tags": [ "python", "python-3.x" ], "Title": "Login system created with Python" }
232526
<p>I'm making a Mandelbrot set viewer in JavaFX. It takes a while, like maybe 5 seconds to finish. Here's my code:</p> <pre><code>package sample; import javafx.application.Application; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.canvas.Canvas; import javafx.scene.canvas.GraphicsContext; import javafx.scene.paint.Color; import javafx.stage.Stage; public class Main extends Application { private static int MAX_ITER = 80; private static double w = 10*100; private static double h = 2*Math.PI*100; static double RE_START = -2; static double RE_END = 1; static double IM_START = -1; static double IM_END = 1; public static int mandelbrot(Complex c) { Complex z = new Complex(0,0); int n = 0; while (Complex.abs(z).isLessThanOrEqual(2) &amp;&amp; n &lt; MAX_ITER) { z = Complex.add(Complex.multiply(z,z),c); n++; } return n; } public void start(Stage primaryStage) { Group root = new Group(); primaryStage.setTitle("Mandelbrot Viewer"); primaryStage.setScene(new Scene(root, w, h)); primaryStage.show(); Canvas canvas = new Canvas(); GraphicsContext gc = canvas.getGraphicsContext2D(); canvas.setWidth(w); canvas.setHeight(h); canvas.relocate(0, 0); root.getChildren().add(canvas); update(gc); } private static void update(GraphicsContext gc) { for (int x = 0; x &lt; w; x++) { for (int y = 0; y &lt; h; y++) { Complex c = new Complex(RE_START + (x / w) * (RE_END - RE_START), IM_START + (y / h) * (IM_END - IM_START)); int m = mandelbrot(c); int hue = 360 * m / MAX_ITER; System.out.println(hue); int saturation = 255; int value = 0; if (m &lt; MAX_ITER) { value = 255; } gc.setFill(Color.hsb(hue, saturation/255d, value/255d)); gc.fillRect(x, y, 1, 1); } } } public static void main(String[] args) { launch(args); } static class Complex { double r; double i; Complex(double r, double i) { this.r = r; this.i = i; } static public Complex abs(Complex c) { return new Complex(Math.abs(c.r), Math.abs(c.i)); } public boolean isLessThanOrEqual(double n) { if (r &lt;= n || i &lt;= n) { return true; } return false; } static public Complex add(Complex c1, Complex c2) { return new Complex(c1.r + c2.r, c1.i + c2.i); } static public Complex multiply(Complex c1, Complex c2) { return new Complex((c1.r*c2.r)-(c1.i*c2.i), (c1.r*c2.i)+(c1.i*c2.r)); } public String toString() { return (r + ", " + i); } } } </code></pre> <p>I eventually want it so that I can move around and zoom into the mandelbrot set with at least 10 fps. How might I be able to make it faster? Should I try switching from JavaFX to AWT or something? Should I try using the GPU? if so, what would be the most simple way to do so? (because I don't really want to spend too much time on this project)</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-17T14:43:40.463", "Id": "454126", "Score": "1", "body": "How many instances of Complex class do you create per frame?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-17T14:52:11.483", "Id": "454127", "Score": "2", "body": "From a frustrated benchmark (can't seem to get an execution profile), almost *no* time is consumed by `mandelbrot()`. (I *doubt* that the instantiation rate of small instances forgotten before the next is instantiated currently impacts time (for the record, `Color`s get instantiated frequently (less of a problem) and set for `gc` (more of one)).)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-17T15:44:34.323", "Id": "454130", "Score": "1", "body": "Thanks. Looking more closely the problem is writing single pixels using the fillRect function. Instead of operating on GraphicsContext create an array of integers to represent the image. There's a lot of info in StackOverflow about how to do that." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-17T21:37:20.553", "Id": "454155", "Score": "0", "body": "Should I try using BufferedImages and draw them on the canvas instead? would that help? @greybeard" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-17T23:14:32.033", "Id": "454162", "Score": "0", "body": "That seems to be what [SuperFractalThing](https://sourceforge.net/projects/suprfractalthng/) uses - I have never been up to speed with Java performance graphics." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-19T22:18:17.207", "Id": "454436", "Score": "0", "body": "FYI. Fields of `Complex` could be `final` (as could the class itself arguably) but I imagine that the Java runtime is bypassing heap allocation of this class entirely because it can see it is used/discarded immediately. This is \"escape analysis\": https://docs.oracle.com/javase/7/docs/technotes/guides/vm/performance-enhancements-7.html#escapeAnalysis" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-09T21:17:01.800", "Id": "456938", "Score": "0", "body": "Have you looked at https://stackoverflow.com/questions/44136040/performance-of-javafx-gui-vs-swing" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-09T14:21:09.163", "Id": "478152", "Score": "0", "body": "[This](https://github.com/james-d/ZoomingMandelbrot) is quite old and uses a `WritableImage` for the display. I didn't use a complex number representation, which helps with some optimization (caching the squares of the re and im parts, for example). It also parallelizes the computation. This achieves the frame rate you're looking for (except, of course, for very deep zooms). It could probably be made faster/cleaner using the new (JavaFX 13) support for pixel buffers." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-16T22:33:09.597", "Id": "232528", "Score": "3", "Tags": [ "java", "performance", "mathematics", "javafx", "fractals" ], "Title": "Making a fast Mandelbrot Fractal viewer" }
232528
<p>I wrote this code to read a square matrix saved as binary file, that it can be <code>int, uint, float</code> etc... to pick a value from the matrix at given row <code>y</code> and given column <code>x</code>. Could this code be faster to pick this value, better than 20 seconds. The maximum row and column number in matrix is 3601 for each one.</p> <pre><code>import struct #convert x,y indexes of 2D array into index i of 1D array #x: index for cols in the 2D #y: index for rows in the 2D def to1D(y,x,width): i = x + width*y return i def readBinary_as(filename,x,y,file_type,width=3601): with open(filename,'rb') as file_data: #initialize, how many bytes to be read nbByte = 0 #data type of the file, uint, int, float, etc... coding = '' if file_type == "signed int": nbByte = 2 coding = '&gt;h' #2B Signed Int - BE if file_type == "unsigned int": nbByte = 2 coding = '&gt;H' #2B Unsigned Int - BE if file_type == "unsigned byte": nbByte = 1 coding = '&gt;B' #1B Unsigned Byte - BE if file_type == "float": nbByte = 4 coding = '&gt;f' #4B float32 - BE #index of my value in 1D array i = to1D(y,x,width) for each_cell in range(0,i): file_data.read(nbByte) #read and save the picked value my_value_pos = file_data.read(nbByte) val = struct.unpack(coding,my_value_pos)[0] return val </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-17T06:37:35.290", "Id": "454116", "Score": "0", "body": "The title states \"picking **unique** value\" - where's *uniqueness* handled in your implementation?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-17T06:44:57.873", "Id": "454117", "Score": "0", "body": "I mean, I don't want to read the whole file, just one value, at given indexes assuming the file as 2D array (because it is matrix data)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-17T19:17:09.873", "Id": "454143", "Score": "0", "body": "I have a doubt that this logic would work correctly. Let's say we have a matrix of mixed `int` and `float` numbers with shape `10 x 10`. If I want to get item at location row=`5`, col=`4` (24th item), why should it read `54` bytes, as that would be returned by `to1D(5, 4, 10)` call ???" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-17T19:21:34.700", "Id": "454144", "Score": "0", "body": "The matrix is all int or float etc... no mixing at all, I am still beginner to such things." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-17T19:45:56.483", "Id": "454149", "Score": "0", "body": "Sorry, you have right, but this code not for general case, if you know nasadem files for DEM, I think, it works like I did and tried. I dont want to read the same file as int then as float, no! there is file as float, other as int, etc... so stand in documentation with each file, my code recognize the corresponding type to be read with the extension of file, I switch that with my if statements" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-17T22:32:30.453", "Id": "454159", "Score": "0", "body": "Ok, can you share how's the input binary file is created in your case? By `struct.pack_into` or some other way and how performance is changed after you applied `seek()`? (perhaps, there could a space for additional optimization)" } ]
[ { "body": "<p>Try using <code>seek()</code> instead of a loop that reads 1 value at a time.</p>\n\n<pre><code>import io\nimport struct\n\n#convert x,y indexes of 2D array into index i of 1D array\n#x: index for cols in the 2D\n#y: index for rows in the 2D\ndef to1D(y,x,width):\n i = x + width*y\n return i\n\n\ndef readBinary_as(filename,x,y,file_type,width=3601):\n with open(filename,'rb') as file_data:\n\n #initialize, how many bytes to be read\n nbByte = 0\n #data type of the file, uint, int, float, etc...\n coding = ''\n if file_type == \"signed int\":\n nbByte = 2\n coding = '&gt;h' #2B Signed Int - BE\n\n if file_type == \"unsigned int\":\n nbByte = 2\n coding = '&gt;H' #2B Unsigned Int - BE\n\n if file_type == \"unsigned byte\":\n nbByte = 1\n coding = '&gt;B' #1B Unsigned Byte - BE\n\n if file_type == \"float\":\n nbByte = 4\n coding = '&gt;f' #4B float32 - BE\n\n #index of my value in 1D array\n i = to1D(y,x,width)\n offset = i * nbByte\n\n # seek to byte offset of desired data\n file_data.seek(offset)\n\n #read and save the picked value\n my_value_pos = file_data.read(nbByte)\n val = struct.unpack(coding,my_value_pos)[0]\n return val\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-17T22:21:52.217", "Id": "454157", "Score": "0", "body": "Woow! that is what I searched for, thank you, I will read more about this seek(), I liked it. Thank you for your answer. But I passed oddset as parameter to seek() instead offset, I think you wrote it wrong without intention" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-17T23:08:56.887", "Id": "454160", "Score": "0", "body": "Corrected the typo." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-17T20:40:16.647", "Id": "232560", "ParentId": "232531", "Score": "3" } }, { "body": "<p>Python has an official style-guide, <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP8</a>, which reommends using <code>lower_case</code> for functions and variables.</p>\n\n<p>There is also a standard for documenting functions, called <code>docstring</code> convention, which is codified in <a href=\"https://www.python.org/dev/peps/pep-0257/\" rel=\"nofollow noreferrer\">PEP257</a>.</p>\n\n<p>In addition, you could use <code>elif</code> to avoid checking all <code>if</code> conditions if you have already found your file type. Or even better, put them all into a dictionary. Note that this now raises a <code>KeyError</code> for an undefined file type (which is a good thing). If you don't want that, use <code>FILE_TYPES.get(file_type, (0, ''))</code> instead.</p>\n\n<p>I renamed your <code>to1D</code> function to <code>ravel</code>, because <a href=\"https://docs.scipy.org/doc/numpy/reference/generated/numpy.ravel_multi_index.html#numpy.ravel_multi_index\" rel=\"nofollow noreferrer\">that is what this operation is called in <code>numpy</code></a>.</p>\n\n<pre><code>import struct\n\nFILE_TYPES = {\"signed int\": (2, '&gt;h'),\n \"unsigned int\": (2, '&gt;H'),\n \"unsigned byte\": (1, '&gt;B'),\n \"float\": (4, '&gt;f')})\n\ndef ravel(x, y, width):\n \"\"\"Convert `x`, `y` indexes of 2D array into index i of a 1D array.\n Assumes that the array is of one consistent `width`.\n\n x: index for cols in the 2D\n y: index for rows in the 2D\n \"\"\"\n return x + width * y\n\ndef read_binary_as(file_name, x, y, file_type, width=3601):\n \"\"\"Read the value at position `x`, `y` from array in `file_name`.\n Assumes that all values are of the same `file_type`\n and that each row has the same `width`.\n \"\"\"\n size, coding = FILE_TYPES[file_type]\n offset = ravel(x, y, width) * size\n with open(file_name, 'b') as file:\n file.seek(offset)\n return struct.unpack(coding, file.read(size))[0]\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-18T09:52:42.360", "Id": "232579", "ParentId": "232531", "Score": "2" } } ]
{ "AcceptedAnswerId": "232560", "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-17T00:16:14.630", "Id": "232531", "Score": "2", "Tags": [ "python", "performance", "python-3.x", "file" ], "Title": "Speed performance of picking unique value from binary matrix file" }
232531
<p>Context: I am making a website that allows people to upload their Facebook Messenger data, and see data visualizations for conversations. It is a React front-end, and a nodejs back-end. It doesn't store anything in a database at the moment, but there is a caching layer to deal with different sessions. So once the user uploads their facebook messenger data, the nodejs back-end is supposed to crunch the numbers and aggregate different statistics.</p> <p>The json looks like: </p> <pre><code>{ "participants": [{"name":"Adam"}, {"name":"Bob"}, {"name":"Chris"}], "messages": [ { "sender_name": "Adam", "timestamp_ms": 1533332999910, "content": "I am editing my stackexchange question right now", "type": "Generic" }, { "sender_name": "Bob", "timestamp_ms": 1533332999910, "content": "Okay, good luck", "type": "Generic" } ], "title": "High School Friends", "is_still_participant": true, "thread_type": "RegularGroup", "thread_path": "inbox/highschoolfriends__aAe4vb" } </code></pre> <p><code>messages</code> is an array of objects, with common text messages having the shape of the above, with other fields that are optional like photos, audio_files, etc. </p> <p>To compute the set up the data I use: </p> <pre><code>let jsonMessages = require('../analytics/message_1.json'); let participants = jsonMessages.participants; let messages = jsonMessages.messages; let people = participants.map(function(person) { return person.name; }); </code></pre> <p>So now the data is a javascript object. </p> <p>So my question: Am I missing something obvious about the <strong>map/filter/reduce</strong> powers by doing a big for loop of filters? Would this pass code review for an internal analytics tool? </p> <p>Here is what I have tried:</p> <pre><code>let people = ['Adam', 'Bob', 'Chris', 'Dave']; people.forEach(function (person) { let obj = {}; obj.name = person; obj.messageCount = messages.filter((obj) =&gt; obj.sender_name === person).length; obj.photoMessageCount = messages.filter((obj) =&gt; ((obj.sender_name === person) &amp;&amp; ((obj.photos != null) )).length; obj.videoGifMessageCount = messages.filter((obj) =&gt; ((obj.sender_name === person) &amp;&amp; ((obj.gifs !=null) || (obj.videos!= null))).length; obj.audioMessageCount = messages.filter((obj) =&gt; ((obj.sender_name === person) &amp;&amp; (obj.audio_files != null))).length; obj.richContentMessageCount = obj.photoMessageCount + obj.videoGifMessageCount + obj.audioMessageCount; stats.push(obj); }); </code></pre>
[]
[ { "body": "<p>A big inefficiency of the initial approach is that for each <code>person</code> (which is actually a <em>person's name</em>) <code>messages</code> collection will be traversed <strong>4</strong> times.</p>\n\n<p>To significantly optimize the traversal algorithm the current one is substituted with a <strong><em>single</em></strong> loop with multiple conditions per iteration.<br>\nAll the needed specific <em>counts</em> are declared beforehand and used as <em>accumulators</em>.<br>The <em>Consolidate conditional expression</em> technique is applied based on a common condition <code>m.sender_name === personName</code>.</p>\n\n<p>The final optimized version:</p>\n\n<pre><code>people.forEach((personName) =&gt; {\n let stat = {'name': personName, 'messageCount': 0, 'photoMessageCount': 0, \n 'videoGifMessageCount': 0, 'audioMessageCount': 0};\n messages.forEach((m) =&gt; {\n if (m.sender_name === personName) { \n stat.messageCount++;\n if (m.photos) stat.photoMessageCount++;\n if (m.gifs || m.videos) stat.videoGifMessageCount++;\n if (m.audio_files) stat.audioMessageCount++;\n }\n });\n stat.richContentMessageCount = stat.photoMessageCount + stat.videoGifMessageCount \n + stat.audioMessageCount;\n stats.push(stat);\n});\n</code></pre>\n\n<hr>\n\n<p>In case if your <code>stats</code> array is intended to be used only for accumulating statistics from <code>people.forEach(...)</code> iterated once - prefer <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map\" rel=\"nofollow noreferrer\"><code>Array.map</code></a> approach to create <code>stats</code> array with the results at once:</p>\n\n<pre><code>let stats = people.map((personName) =&gt; {\n let stat = {'name': personName, 'messageCount': 0, 'photoMessageCount': 0, \n 'videoGifMessageCount': 0, 'audioMessageCount': 0};\n // all the logic here\n // ...\n return stat;\n});\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-17T07:39:34.227", "Id": "232541", "ParentId": "232532", "Score": "4" } } ]
{ "AcceptedAnswerId": "232541", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-17T01:00:32.050", "Id": "232532", "Score": "2", "Tags": [ "javascript", "array", "json" ], "Title": "Javascript map/filter/reduce over facebook messenger data" }
232532
NASM is the Netwide Assembler, an open-source x86/x64 assembler. It aims at being portable, modular and at having a simple syntax.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-17T01:12:21.347", "Id": "232534", "Score": "0", "Tags": null, "Title": null }
232534
<p>I have written BST in Java for practice. How can I write better unit test cases. I am sure the way I have written them is not proper.</p> <p><a href="https://github.com/ganeshaaru/DataStructures/blob/master/src/main/java/com/r/basics/tree/BinarySearchTree.java" rel="nofollow noreferrer">Code for BST</a></p> <pre><code>package com.r.basics.tree; import org.junit.Before; import org.junit.Test; public class BinarySearchTreeTest{ private BinarySearchTree&lt;Integer&gt; binarySearchTreeSUT; @Before public void setUp() { binarySearchTreeSUT = new BinarySearchTree&lt;&gt;(); } @Test public void testShouldInsertItemToBST(){ binarySearchTreeSUT.insert(4); binarySearchTreeSUT.insert(8); binarySearchTreeSUT.insert(2); binarySearchTreeSUT.insert(3); } @Test public void testShouldGetMaxItemFromBST(){ binarySearchTreeSUT.insert(4); binarySearchTreeSUT.insert(8); binarySearchTreeSUT.insert(2); binarySearchTreeSUT.insert(3); assert(binarySearchTreeSUT.getMax() == 8); } @Test public void testShouldGetMinItemFromBST(){ binarySearchTreeSUT.insert(4); binarySearchTreeSUT.insert(8); binarySearchTreeSUT.insert(2); binarySearchTreeSUT.insert(3); assert(binarySearchTreeSUT.getMin() == 2); } @Test public void testShouldTraverseItemsFromBST(){ binarySearchTreeSUT.insert(4); binarySearchTreeSUT.insert(8); binarySearchTreeSUT.insert(2); binarySearchTreeSUT.insert(3); binarySearchTreeSUT.traversal(); } @Test public void testShouldDeleteLeafNOdeItemsFromBST(){ binarySearchTreeSUT.insert(4); binarySearchTreeSUT.insert(8); binarySearchTreeSUT.insert(2); binarySearchTreeSUT.insert(3); binarySearchTreeSUT.traversal(); binarySearchTreeSUT.delete(3); binarySearchTreeSUT.traversal(); } @Test public void testShouldDeleteParentNodeWithBothChildrenItemsFromBST(){ binarySearchTreeSUT.insert(4); binarySearchTreeSUT.insert(8); binarySearchTreeSUT.insert(2); binarySearchTreeSUT.insert(3); binarySearchTreeSUT.traversal(); binarySearchTreeSUT.delete(4); binarySearchTreeSUT.traversal(); } @Test public void testShouldDeleteParentNodeWithBothChildrenItemsFromBSTWithSuccessor(){ binarySearchTreeSUT.insert(4); binarySearchTreeSUT.insert(8); binarySearchTreeSUT.insert(2); binarySearchTreeSUT.insert(7); binarySearchTreeSUT.traversal(); binarySearchTreeSUT.delete(4); binarySearchTreeSUT.traversal(); } @Test public void testShouldDeleteParentNodeWithOneChildrenItemsFromBST(){ binarySearchTreeSUT.insert(4); binarySearchTreeSUT.insert(8); binarySearchTreeSUT.insert(2); binarySearchTreeSUT.insert(3); binarySearchTreeSUT.traversal(); binarySearchTreeSUT.delete(2); binarySearchTreeSUT.traversal(); } } </code></pre>
[]
[ { "body": "<p>Your tests seem to be of appropriate size and scope but there are a couple things I'd address. </p>\n\n<p><strong>Assertions</strong>\nFirst and foremost I don't see your code asserting on anything.<br>\nYou manipulate the binarySearch tree, which is the first step, but then you don't check the state of it afterward. As a reviewer I'd ask \"what are your tests actually testing?\"</p>\n\n<p><strong>Magic numbers</strong>\nIt's clear you thought about what each test was supposed to accomplish but the intent of the test could be clearer to the reader. You could try adding meaning to the numbers you are inserting to the tree, adding comments, or some other way of making the purpose of each test very clear to the reader. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-17T05:19:23.813", "Id": "232539", "ParentId": "232535", "Score": "5" } }, { "body": "<p>When testing functions that accept primitive number types you must always test the limits of the value space. Add tests for Integer.MAX_VALUE and Integer.MIN_VALUE in combination with each other and with smaller numbers. The point of these tests is to verify that any possible arithmetic operation there may be does not suffer from over- and underflow.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-17T14:38:09.003", "Id": "232548", "ParentId": "232535", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-17T01:48:54.880", "Id": "232535", "Score": "1", "Tags": [ "java", "unit-testing" ], "Title": "Unit Test BST in Java" }
232535
<pre><code>def draw_board(board): display_board = '' for number in list(range(len(board))): if (number + 1) % 3 == 0: if number &lt; 6: display_board += ' ' + str(board[number]) + ' \n—————————————————\n' else: display_board += ' ' + str(board[number]) + ' ' else: display_board += ' ' + str(board[number]) + ' |' return display_board def check_win(board, letter): if all(item == letter for item in board[:3]): return True elif all(item == letter for item in board[3:6]): return True elif all(item == letter for item in board[6:9]): return True elif all(item == letter for item in board[::3]): return True elif all(item == letter for item in board[1::3]): return True elif all(item == letter for item in board[2::3]): return True elif all(item == letter for item in board[::4]): return True elif all(item == letter for item in board[2:8:2]): return True x = input('Who is X? &gt; ') o = input('Who is O? &gt; ') squares = { 'nw': 0, 'n': 1, 'ne': 2, 'w': 3, 'c': 4, 'e': 5, 'sw': 6, 's': 7, 'se': 8 } directions = list(squares.keys()) tic_tac_toe_board = [ '.', '.', '.', '.', '.', '.', '.', '.', '.' ] valid_turns = 0 x_turn = True print(draw_board(tic_tac_toe_board) + '\n(Xs first) ', end='') while valid_turns &lt; 9: square = input('Exactly type in the following available directions: ' + ', '.join(directions) + ' &gt; ') if square.lower() in directions: directions.remove(square.lower()) if x_turn: tic_tac_toe_board[squares[square.lower()]] = 'X' x_turn = False else: tic_tac_toe_board[squares[square.lower()]] = 'O' x_turn = True valid_turns += 1 else: print('INVALID MOVE') print(draw_board(tic_tac_toe_board)) if check_win(tic_tac_toe_board, 'X'): print(x + ' has won!') break elif check_win(tic_tac_toe_board, 'O'): print(o + ' has won!') break if valid_turns == 9: print('DRAW!') </code></pre>
[]
[ { "body": "<h1><code>check_win</code></h1>\n\n<p>There are a lot of <code>if</code> and <code>elif</code> statements here. You can reduce this by utilizing python's <a href=\"https://www.programiz.com/python-programming/methods/built-in/any\" rel=\"nofollow noreferrer\"><code>any</code></a> built in function. This will return <code>True</code> if <em>any</em> of the values passed in are <code>True</code>. And since you have a bunch of expressions that evaluate to boolean values, this can be rewritten like so:</p>\n\n<pre><code>def check_win(board, letter):\n return any([\n (item == letter for item in board[:3]),\n (item == letter for item in board[3:6]),\n (item == letter for item in board[6:9]),\n (item == letter for item in board[::3]),\n (item == letter for item in board[1::3]),\n (item == letter for item in board[2::3]),\n (item == letter for item in board[::4]),\n (item == letter for item in board[2:8:2])\n ])\n ])\n</code></pre>\n\n<p>Since <code>all</code> has to be passed an iterable, you can create a list containing the resulting Boolean values from these expressions. If any are <code>True</code>, then the function will return <code>True</code>.</p>\n\n<p>This answer is the fastest on average (tested 1000 times).</p>\n\n<h1>Type Hinting</h1>\n\n<p>You should use type hints to make it clear what types of parameters are passed to functions, and what types are returned by functions. Lets take your <code>check_win</code> function for example:</p>\n\n<pre><code>from typing import List\n\ndef check_win(board: List[str], letter: str) -&gt; bool:\n</code></pre>\n\n<p>This makes it clear that is accepts a list of strings as the board, as string representing the letter, and returns a boolean value.</p>\n\n<h1>Docstrings</h1>\n\n<p>Lets expand upon the <code>check_win</code> function. This can be even more descriptive by using a function docstring. This will allow you to put in words what the function is supposed to do. Take a look:</p>\n\n<pre><code>def check_win(board: List[str], letter: str) -&gt; bool:\n \"\"\"\n Determines if there is a winner in the passed board\n\n :param board -&gt; List[str]: The playing board\n :param letter -&gt; str: Letter (X/O) to check\n\n :return bool: True if there is a winner, False otherwise\n \"\"\"\n</code></pre>\n\n<h1>String Formatting</h1>\n\n<p>Instead of</p>\n\n<pre><code>print(x + ' has won!')\n</code></pre>\n\n<p>consider using an <code>f\"\"</code> string. This allows you to directly implement variables in your strings:</p>\n\n<pre><code>print(f\"{x} has won!\")\n</code></pre>\n\n<h1>Additional Methods</h1>\n\n<p>Consider writing a couple more methods to reduce your open code in your program. By open I mean code that isn't contained within a function/class. Maybe a function like <code>run_game</code> that manages turns, and a <code>display_winner</code> that presents who won the game. I'll leave these up to you to implement.</p>\n\n<p><hr>\n<em>All the above suggestions can be applied to each function within your code. I used <code>check_win</code> as an example for several, but they apply to both of your functions.</em></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-17T10:20:07.043", "Id": "454120", "Score": "0", "body": "I don't agree with some of the suggestions on this answer. Type hints are not always necessary. Python didn't have them for decades. Docstrings are also another controversial topic. Usually you add them if there's nothing else you can do to make the code document itself (function name, variable names, tests, visual look of the code itself, etc.). Last, the code provided in this answer contains a lot of duplication. The list indices change, so why copy paste the whole logic with `all`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-17T23:53:58.813", "Id": "454163", "Score": "0", "body": "@MikaeilOrfanian The type hints and docstring suggestions were *suggestions*. I guess I should have made it more clear that they were optional and not imperative to the functionality of the code. Yes, I agree that the `check_win` is repetitive, but it is faster than the original code." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-17T08:37:37.540", "Id": "232543", "ParentId": "232536", "Score": "2" } }, { "body": "<p><strong><em>Ways of improving/optimizing:</em></strong></p>\n\n<ul>\n<li><p><strong><code>draw_board</code></strong> function.</p>\n\n<ul>\n<li><p>prefer <code>enumerate(board)</code> over redundant <code>list(range(len(board)))</code></p></li>\n<li><p>all conditional branches within <code>for</code> loop have the same common expression to append <code>' ' + str(board[number]) + ' '</code>. Thus, it can be moved up to reduce conditional branches</p></li>\n<li>prefer flexible <code>f-string</code> formatting over awkward string concatenation combined with casting to <code>str</code>\n<br><br></li>\n</ul>\n\n<p>Now the optimized <code>draw_board</code> function would look as:</p>\n\n<pre><code>def draw_board(board):\n display_board = ''\n\n for i, v in enumerate(board):\n display_board += f' {v} '\n if (i + 1) % 3 == 0:\n if i &lt; 6:\n display_board += '\\n—————————————————\\n'\n else:\n display_board += '|'\n\n return display_board\n</code></pre></li>\n<li><p><strong><code>check_win</code></strong> function introduces many repetitive checks <code>all(item == letter for item in board[...])</code> with the same returned value.<br>\nA more flexible way is to create an additional function to check <em>crossed</em> row:</p>\n\n<pre><code>def row_crossed(letter, row):\n return all(item == letter for item in row)\n</code></pre>\n\n<p>Then, <code>check_win</code> would call <code>any</code> function on <em>generator</em> expression that yields all the needed sub-checks:</p>\n\n<pre><code>def check_win(board, letter):\n return any((row_crossed(letter, board[:3]), row_crossed(letter, board[3:6]),\n row_crossed(letter, board[6:9]), row_crossed(letter, board[::3]),\n row_crossed(letter, board[1::3]), row_crossed(letter, board[2::3]),\n row_crossed(letter, board[::4]), row_crossed(letter, board[2:8:2])))\n</code></pre></li>\n<li><p><strong><code>square</code></strong> dictionary. To reduce quotes mess it can be composed in concise way with <code>zip</code> and <code>range</code> functions:</p>\n\n<pre><code>squares = dict(zip(('nw', 'n', 'ne', 'w', 'c', 'e', 'sw', 's', 'se'), range(9)))\n</code></pre></li>\n<li><p><code>tic_tac_toe_board</code> easily replaced with <strong><code>tic_tac_toe_board = ['.'] * 9</code></strong> </p></li>\n<li><p><code>square.lower()</code> repeats <strong>4</strong> times within main <code>while</code> loop. <br>Instead, extract that expression into a variable at once and refer it:</p>\n\n<pre><code>square = input('Exactly type in the following available directions: {} &gt; '.format(', '.join(directions)))\nsquare = square.lower()\n</code></pre></li>\n<li><p>the whole condition:</p>\n\n<pre><code>if x_turn:\n tic_tac_toe_board[squares[square.lower()]] = 'X'\n x_turn = False\nelse:\n tic_tac_toe_board[squares[square.lower()]] = 'O'\n x_turn = True\n</code></pre>\n\n<p>would be simplified as it relies on explicit <em>negation</em> of <strong><code>x_turn</code></strong> flag.<br>Getting 2 lines against 6:</p>\n\n<pre><code>tic_tac_toe_board[squares[square]] = 'X' if x_turn else 'O'\nx_turn = not x_turn\n</code></pre></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-17T11:30:16.010", "Id": "232547", "ParentId": "232536", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-17T02:37:43.573", "Id": "232536", "Score": "3", "Tags": [ "python", "beginner", "game", "tic-tac-toe" ], "Title": "Beginner Tic-Tac-Toe in Python" }
232536
<p>I've designed a database schema to store multiple translations with the objective of it being easy to retrieve data and add more translations if ever needed in the future without needing to make any change at all.</p> <p><a href="https://dbdiagram.io/d/5dd0b181edf08a25543e0336" rel="nofollow noreferrer">Here's a dbdiagram.io of the part of the database that's relevant to this post.</a> </p> <p>One of my bot commands take as input the hero name and grabs the user locale number id and pass it to the function parameters <code>i_hero_name</code> and <code>i_locale_id</code> respectively, and said function returns brief information about that hero if found.</p> <p>Most of the tables (in this case the ones that aren't being joined in this function) are lookup tables to ensure referential integrity throughout the database.</p> <p>The function I use is the following:</p> <pre><code>CREATE OR REPLACE FUNCTION Game.get_hero(i_hero_name TEXT, i_locale_id SMALLINT) RETURNS TABLE ( name TEXT, story TEXT, grade SMALLINT, face_id TEXT, attribute_id SMALLINT, attribute TEXT, role_id SMALLINT, role TEXT, zodiac_id SMALLINT, zodiac TEXT, bra SMALLINT, "int" SMALLINT, fai SMALLINT, des SMALLINT, devotion_name TEXT, devotion_slot TEXT, devotion_value FLOAT, self_devotion_name TEXT, self_devotion_value FLOAT, exclusive_equipment_name TEXT ) AS $$ #variable_conflict use_column -- TODO remake this, use better column naming. BEGIN RETURN QUERY SELECT COALESCE(c.name, b.name), COALESCE(c.story, b.story), a.grade, a.face_id, d.attribute_id, d.attribute_name, e.role_id, e.role_name, f.zodiac_id, f.zodiac_name, a.bra, a.int, a.fai, a.des, g.name, a.devotion_slot, g.effect, h.name, h.effect, i.name FROM Game.Hero a INNER JOIN ( SELECT * FROM Game.HeroTranslation WHERE locale_id = 2 ) b ON a.hero_id = b.hero_id LEFT JOIN ( SELECT * FROM Game.HeroTranslation WHERE locale_id = i_locale_id ) c ON a.hero_id = c.hero_id LEFT JOIN ( SELECT locale_id, attribute_id, attribute_name FROM Game.AttributeTranslation WHERE locale_id = i_locale_id ) d ON a.attribute_id = d.attribute_id LEFT JOIN ( SELECT locale_id, role_id, role_name FROM Game.RoleTranslation WHERE locale_id = i_locale_id ) e ON a.role_id = e.role_id LEFT JOIN ( SELECT locale_id, zodiac_id, zodiac_name FROM Game.ZodiacTranslation WHERE locale_id = i_locale_id ) f ON a.zodiac_id = f.zodiac_id LEFT JOIN ( SELECT a.devotion_id, a.effect, b.name FROM Game.HeroDevotion a LEFT JOIN ( SELECT stat_id, name FROM Game.StatTranslation WHERE locale_id = i_locale_id ) b ON a.stat_id = b.stat_id ) g ON a.devotion_id = g.devotion_id LEFT JOIN ( SELECT a.devotion_id, a.effect, b.name FROM Game.HeroDevotion a LEFT JOIN ( SELECT stat_id, name FROM Game.StatTranslation WHERE locale_id = i_locale_id ) b ON a.stat_id = b.stat_id ) h ON a.devotion_self_id = h.devotion_id LEFT JOIN ( SELECT a.hero_id, COALESCE(c.name, b.name) AS "name" FROM Game.HeroExclusive a INNER JOIN ( SELECT exclusive_id, name FROM Game.HeroExclusiveTranslation WHERE locale_id = 2 ) b ON a.exclusive_id = b.exclusive_id LEFT JOIN ( SELECT exclusive_id, name FROM Game.HeroExclusiveTranslation WHERE locale_id = i_locale_id ) c ON a.exclusive_id = c.exclusive_id ) i ON a.hero_id = i.hero_id WHERE (c.name IS NULL AND b.name ~* i_hero_name) OR (c.name ~* i_hero_name AND a.hero_id = c.hero_id); END $$ LANGUAGE plpgsql; </code></pre> <p>I have two joins for the <code>HeroTranslation(s)</code> which one holds the default (in case there's no translated data) translation and one for the translation data of the user locale and then <code>COALESCE(translation, default_translation)</code>.</p> <p>For Attribute, Role and Zodiac I don't need to do the same as above since there will always be a translation for them.</p> <p>And then every hero has two kind of devotions, one which is for the entire team, denoted as <code>devotion_id</code> on the <code>Game.Hero</code> table and one that's only for the hero which is denoted as <code>devotion_self_id</code> on the same table.</p> <p>Lastly, some heroes might or might not have an equipment, unlike Zodiac/Role/Attribute they might not be translated so I have to join both the default translations and the actual translations that the user is requesting.</p> <p>I have no issues with the design, it works the way I want and it's performant with timings varying between 1ms to 20ms. I'm not sure whether to post the PostgreSQL planning due to the length so I'll go ahead and post the timing results instead:</p> <pre><code>EXPLAIN ANALYZE SELECT * FROM Game.get_hero('Yufine', 2::SMALLINT); QUERY PLAN --------------------------------------------------------------------------------------------------------------- Function Scan on get_hero (cost=0.25..10.25 rows=1000 width=352) (actual time=18.196..18.197 rows=1 loops=1) Planning time: 0.061 ms Execution time: 18.254 ms (3 rows) </code></pre> <p>Is there any improvement I can do to the query/function?</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-17T03:02:09.950", "Id": "232537", "Score": "1", "Tags": [ "performance", "sql", "postgresql" ], "Title": "Storing multiple translations for retrieval" }
232537
<p>It's an exercise from a Swift-course I'm currently taking.</p> <blockquote> <p>You are given an array of integers. Make an additional array named computedNumbers. computedNumbers should multiply each element in the numbers array by the next following element. The last element shall be multiplied by the first element.</p> <p>Example: If numbers was equal to ... [3, 1, 4, 2] ... then the computedNumbers should computed [3 x 1, 1 x 4, 4 x 2, 2 x 3], so that they become: [3, 4, 8, 6]</p> </blockquote> <p>Here my solution:</p> <pre><code>var numbers = [45, 73, 195, 53] var computedNumbers = [Int]() let count = numbers.count var i = 0 while i &lt; count - 1 { computedNumbers.append(numbers[i] * numbers[i + 1]) i = i + 1 } computedNumbers.append(numbers[count - 1] * numbers[0]) print(computedNumbers) </code></pre> <p>It has passed the automated tests, but it isn't very elegant.</p> <p><strong>It there a better way to accomplish the task?</strong></p> <p><strong>What should I have done different and why?</strong></p> <p>Looking forward to reading your comments and answers.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-18T13:51:39.907", "Id": "454235", "Score": "2", "body": "A possible alternative one-liner: `numbers.indices.map { numbers[$0] * numbers[($0 + 1) % numbers.count] }`" } ]
[ { "body": "<h3>Handle edge cases</h3>\n\n<p>If the given <code>numbers</code> array is empty then the first loop will do nothing, but</p>\n\n<pre><code>computedNumbers.append(numbers[count - 1] * numbers[0])\n</code></pre>\n\n<p>aborts with a runtime exception. The correct result in this case would be to set <code>computedNumbers</code> to an empty array as well.</p>\n\n<h3>Better loops</h3>\n\n<p>This</p>\n\n<pre><code>var i = 0\nwhile i &lt; count - 1 {\n // ...\n i = i + 1\n}\n</code></pre>\n\n<p>is shorter and better done as</p>\n\n<pre><code>for i in 0 ..&lt; count - 1 {\n // ...\n}\n</code></pre>\n\n<p>The advantages are</p>\n\n<ul>\n<li>The scope of <code>i</code> is limited to the loop.</li>\n<li><code>i</code> is a <em>constant.</em></li>\n<li>The range of <code>i</code> is clearly seen right at the start of the loop.</li>\n</ul>\n\n<p>In this particular case we iterate of adjacent array elements, which is conveniently by by <code>zip()</code>ping the array with a shifted view of itself:</p>\n\n<pre><code>var computedNumbers = zip(numbers, numbers.dropFirst()).map(*)\ncomputedNumbers.append(numbers[count - 1] * numbers[0])\n</code></pre>\n\n<p>If we append the first element to the shifted view then the complete operation reduces to</p>\n\n<pre><code>let computedNumbers = zip(numbers, [numbers.dropFirst(), numbers.prefix(1)].joined()).map(*)\n</code></pre>\n\n<p>Note that this handles also the case of an empty array gracefully.</p>\n\n<h3>Use constants if possible</h3>\n\n<p>The <code>numbers</code> array is never mutated, therefore it should be declared as a <em>constant</em> with <code>let</code>:</p>\n\n<pre><code>let numbers = [3, 1, 4, 2]\n</code></pre>\n\n<p>Using a constant </p>\n\n<ul>\n<li>makes it clear to the reader that this value is never mutated,</li>\n<li>helps to avoid unintentional mutation,</li>\n<li>possibly allows better compiler optimization.</li>\n</ul>\n\n<h3>Make it a function</h3>\n\n<p>If we put the functionality in a separate function then</p>\n\n<ul>\n<li>it becomes reusable,</li>\n<li>test cases can be added more easily,</li>\n<li>we can give it a meaningful name,</li>\n<li>we can add documentation.</li>\n</ul>\n\n<p>In our case the function would simply be</p>\n\n<pre><code>/// Compute an array where each element in the numbers array is multipled by\n/// the next following element. The last element is multiplied by the first element.\n/// - Parameter numbers: An array of integers.\nfunc circularAdjacentProducts(of numbers: [Int]) -&gt; [Int] {\n return zip(numbers, [numbers.dropFirst(), numbers.prefix(1)].joined()).map(*)\n}\n</code></pre>\n\n<p>and would then be used as</p>\n\n<pre><code>let numbers = [3, 1, 4, 2]\nlet computedNumbers = circularAdjacentProducts(of: numbers)\nprint(computedNumbers)\n</code></pre>\n\n<h3>Make it generic on the element type</h3>\n\n<p>The same operation could be done with an array of floating point values (<code>Float</code> or <code>Double</code>), or with other integer types (e.g. <code>Int16</code>) as long as the multiplication does not overflow. Therefore we can generalize it to array of type <code>[T]</code> where <code>T</code> conforms to a protocol which required a multiplication operation.</p>\n\n<p>A possible choice is the <a href=\"https://developer.apple.com/documentation/swift/numeric\" rel=\"noreferrer\"><code>Numeric</code></a> protocol which is adopted by all floating point and integer types:</p>\n\n<pre><code>func circularAdjacentProducts&lt;T: Numeric&gt;(of numbers: [T]) -&gt; [T] {\n return zip(numbers, [numbers.dropFirst(), numbers.prefix(1)].joined()).map(*)\n}\n</code></pre>\n\n<p>Example:</p>\n\n<pre><code>let floats = [3.3, 1.1, 4, 2.2]\nlet computedFloats = circularAdjacentProducts(of: floats)\nprint(computedFloats) // [3.63, 4.4, 8.8, 7.26]\n</code></pre>\n\n<h3>Make it generic on the collection type</h3>\n\n<p>The next possible generalization is to apply this operation not only to arrays, but to arbitrary collections:</p>\n\n<pre><code>extension Collection where Element: Numeric {\n func circularAdjacentProducts() -&gt; [Element] {\n return zip(self, [dropFirst(), prefix(1)].joined()).map(*)\n }\n}\n</code></pre>\n\n<p>Example with an <code>ArraySlice</code>:</p>\n\n<pre><code>let numbers = Array(1...10).dropFirst(3)\nprint(numbers) // [4, 5, 6, 7, 8, 9, 10]\nlet computedFloats = numbers.circularAdjacentProducts()\nprint(computedFloats) // [20, 30, 42, 56, 72, 90, 40]\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-17T22:37:52.773", "Id": "232564", "ParentId": "232542", "Score": "6" } }, { "body": "<p>If I remember correctly, at the time that exercise had been given, using loops had not been covered, so you did very well to discover the while loop and how to use it.</p>\n\n<p>The point of that exercise was to show you how tedious it is to write essentially the same code for each different element:</p>\n\n<pre><code>let numbers = [3, 1, 4, 2]\nvar results = [Int]()\n\nresults.append(numbers[0] * numbers[1])\nresults.append(numbers[1] * numbers[2])\nresults.append(numbers[2] * numbers[3])\nresults.append(numbers[3] * numbers[0])\n\n// and even maybe\nprint(results[0])\nprint(results[1])\nprint(results[2])\nprint(results[3])\n\n// to print individually\n</code></pre>\n\n<p>...and that introduces the reason for using loops.</p>\n\n<p>So your solution already went way beyond what was asked, so give yourself a pat on the back for that.</p>\n\n<p>Martin's answer gives excellent advice on loops and those will also be covered in the next step of the course, but don't concern yourself too much about the more advanced stuff (like generics) for now. They are an important part of what makes Swift so expressive and so enjoyable to use, but they are an advanced topic and come later, once the basics have been addressed.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-21T16:36:10.147", "Id": "454647", "Score": "1", "body": "Welcome to [codereview.se]! This nicely explains what *not* to do but the question is asking what *to* do instead. Can you give advice on how to improve the code in the question?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-21T17:07:32.400", "Id": "454659", "Score": "0", "body": "I think the part 'Better Loops' in Martin's answer is sufficient for that. My answer was really only because I recognise the exercise from an online course, where you can submit your answers and I assume Michale may want to submit his answer and is wanting to improve it, which Martin's answer addresses. I just wanted to assure him that loops are not an expected part of that answer because the course hasn't yet introduced them. This exercise expects the answer in long form, without loops, as I showed, but the loop form passes too. If it's not an appropriate answer for here, I'm happy to delete." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-21T16:01:06.130", "Id": "232749", "ParentId": "232542", "Score": "2" } } ]
{ "AcceptedAnswerId": "232564", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-17T08:30:06.793", "Id": "232542", "Score": "3", "Tags": [ "beginner", "array", "swift" ], "Title": "Working with Arrays in Swift" }
232542
<p>I think the part to get shortest path from the cost table got pretty messy. Also can use some tips on how to avoid the extra O(V+E) work checking all edges from source to dest after getting the cost table, or have a better optimized implementation in general.</p> <h3>DirectedGraph.scala</h3> <pre><code>case class Vertex(id: String) case class Edge(source: Vertex, dest: Vertex, weight: Int) class DirectedGraph { val adjacencyTable: mutable.Map[Vertex, Array[Edge]] = new mutable.HashMap[Vertex, Array[Edge]]() def addVertex(vertex: Vertex): Unit = adjacencyTable.put(vertex, new Array[Edge](0)) def addEdge(source: Vertex, dest: Vertex, weight: Int): Unit = adjacencyTable.put(source, adjacencyTable(source) :+ Edge(source, dest, weight)) def getEdges: Array[Edge] = adjacencyTable.keys.flatMap(i =&gt; adjacencyTable(i)).toArray } </code></pre> <h3>BellmanFord.java</h3> <pre><code>public class BellmanFord { private DirectedGraph graph; public BellmanFord(DirectedGraph graph) { this.graph = graph; } public List&lt;Vertex&gt; getShortestPath(Vertex source, Vertex dest) { Map&lt;Vertex, Integer&gt; costs = getCostMap(source); List&lt;Vertex&gt; retList = new ArrayList&lt;&gt;(); Edge minEdge = null; retList.add(source); if (source == dest) return retList; if (graphHasNegativeCycle(costs)) throw new IllegalStateException(&quot;Graph cannot have negative cycles&quot;); if (costs.get(dest) == Integer.MAX_VALUE) throw new IllegalArgumentException(&quot;There are no valid paths from source to destination&quot;); for (Edge e : graph.adjacencyTable().get(source).get()) if (minEdge == null || e.weight() &lt; minEdge.weight()) minEdge = e; retList.addAll(getShortestPath(minEdge.dest(),dest)); return retList; } private Map&lt;Vertex, Integer&gt; getCostMap(Vertex source) { Map&lt;Vertex, Integer&gt; ret = initCostMap(source); for (int i = 0; i &lt; ret.size() - 1; i++) { relaxEdges(ret); } return ret; } private void relaxEdges(Map&lt;Vertex, Integer&gt; costMap) { for (Edge edge : graph.getEdges()) { if (costMap.get(edge.source()) + edge.weight() &lt; costMap.get(edge.dest())) { costMap.put(edge.dest(), costMap.get(edge.source()) + edge.weight()); } } } private boolean graphHasNegativeCycle(Map&lt;Vertex, Integer&gt; costMap) { for (Edge edge : graph.getEdges()) { if (costMap.get(edge.source()) + edge.weight() &lt; costMap.get(edge.dest())) { return true; } } return false; } private Map&lt;Vertex, Integer&gt; initCostMap(Vertex source) { Map&lt;Vertex, Integer&gt; costMap = new HashMap&lt;&gt;(); graph.adjacencyTable().foreach( kvp -&gt; costMap.put(kvp._1, kvp._1 == source ? 0 : Integer.MAX_VALUE) ); return costMap; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-13T23:45:29.640", "Id": "482018", "Score": "0", "body": "Is there a requirement to do one in Scala and the other in Java?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-13T23:56:30.800", "Id": "482019", "Score": "1", "body": "Not really, I was just mixing and matching for fun" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-17T10:47:21.120", "Id": "232544", "Score": "2", "Tags": [ "java", "algorithm", "scala" ], "Title": "Bellman-Ford Implementation in Scala/Java" }
232544
<p>In the following <a href="https://github.com/edicl/hunchentoot" rel="nofollow noreferrer">hunchentoot</a> easy-handler definition:</p> <pre class="lang-lisp prettyprint-override"><code>(define-easy-handler (new-game :uri "/new-game") () (standard-page (:title "Add a new game" :script (ps (defvar add-form nil) (defun validate-game-name (evt) (when (= (@ add-form name value) "") (chain evt (prevent-default)) (alert "Please enter a name."))) (defun init () (setf add-form (chain document (get-element-by-id "addform"))) (chain add-form (add-event-listener "submit" validate-game-name false))) (setf (chain window onload) init))) (:h1 "Add a new game to the chart") (:form :action "/game-added" :method "post" :id "addform" (:p "What is the name of the game?" (:br) (:input :type "text" :name "name" :class "txt")) (:p (:input :type "submit" :value "Add" :class "btn"))))) </code></pre> <p>What is the most straightforward and architecturally sensible way to pull out the <code>parenscript</code> (lines 3-15)?</p> <p>Is it really nothing more than creating a lisp function like so</p> <pre class="lang-lisp prettyprint-override"><code>(define-easy-handler (new-game :uri "/new-game") () (standard-page (:title "Add a new game" :script (separate-js)) ; &lt;- just call the new fn below here (:h1 "Add a new game to the chart") (:form :action "/game-added" :method "post" :id "addform" (:p "What is the name of the game?" (:br) (:input :type "text" :name "name" :class "txt")) (:p (:input :type "submit" :value "Add" :class "btn"))))) ;; Just pulled out the parenscript into a separate function, super simple: (defun separate-js () (ps (defvar add-form nil) (defun validate-game-name (evt) (when (= (@ add-form name value) "") (chain evt (prevent-default)) (alert "Please enter a name."))) (defun init () (setf add-form (chain document (get-element-by-id "addform"))) (chain add-form (add-event-listener "submit" validate-game-name false))) (setf (chain window onload) init))) </code></pre> <p>It's interesting finding that in lisp we are getting by without models, views, or controllers; just using lisp functions &amp; macros. However, these are important steps and concepts here so I wanted to proceed with caution, hence seeking comment &amp; discussion.</p> <p>The general context of the question here is how to structure a web application. These are my first baby steps doing this in lisp, in contrast to plenty of experience with a more run of the mill MVC. Hence, any illumination of differences in thinking required would be excellent.</p> <p>The first code block is from the leanpub book "Lisp for the Web". The second is my own super simple modification of that.</p> <p><em>For information: In my opinion the book "Lisp for the Web" seems great so long as you get past the introduction and first few pages, which have terrible sentence structure and seem not to have been proof read before being published. The rest of the book is much better quality! I nearly binned it and am glad I didn't.</em></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-17T11:39:55.357", "Id": "454123", "Score": "0", "body": "Can you please elaborate a bit more about what this code is suppoed to do." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-29T12:26:46.727", "Id": "455647", "Score": "0", "body": "It seems good to me. I still reason with MVC because we still need a models layer (-> put DB-related code together, and maybe give it its own namespace), we need to validate forms client and server side, etc." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-29T12:27:04.807", "Id": "455648", "Score": "0", "body": "I strongly invite you to test and use the Spinneret templating library instead of cl-who. I found Spinneret much easier to compose stuff with than cl-who, and it has some more neat features (markdown integration, knowing how down we are in the template, etc). Don't miss this list in general: https://github.com/CodyReichert/awesome-cl#html-generators-and-templates" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-29T12:27:14.377", "Id": "455649", "Score": "0", "body": "One framework that blurs even more the lines is Weblocks (which is seeing a rewrite and update those last two years): http://40ants.com/weblocks/quickstart.html It is a components, ajax-based, server-side isomorphic web framework, where we don't have to write a line of JS at all. I can't recommend it yet (it's pre-alpha, changing and needs more documentation), but you might love to explore it." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-17T11:26:52.323", "Id": "232546", "Score": "4", "Tags": [ "common-lisp" ], "Title": "Hunchentoot first steps - good ways of pulling out parenscript from an easy-handler" }
232546
<p>I am trying to remove all occurrences of the words I collect in the list <code>exclude</code> from every text note. This is my approach.</p> <pre><code>import operator,re exclude=[] for i in range(len(freq_select)): if freq_select[i][1]&lt;=25: exclude.append(freq_select[i][0]) def remove_nonfrequent(note): print(remove_nonfrequent.i) sentences=[] for sent in note.split('.'): words=sent.split(' ') #print("Before:",len(words)) for word in words: for j in exclude: if j==word: #print(j,word) words.remove(word) #print("After:",len(words)) sent=' '.join(words) sentences.append(sent) note='. '.join(sentences) remove_nonfrequent.i+=1 return '. '.join([i for i in note.split('.') if i!='']) remove_nonfrequent.i=0 jdf.NOTES=jdf.NOTES.apply(remove_nonfrequent) </code></pre> <p>I was initially looping over all the notes in pandas series. But now I am using <code>apply()</code> and I can say performance increased little bit. But it still takes a very long time.</p> <p>Each note in the <code>pandas.Series</code> is of variable length. However, an average note can contain somewhere between 3000-6000 words. One note even has 13000 words.</p> <p>I would like to get some help in this.</p>
[]
[ { "body": "<p>You currently have to loop over all exclude words to check if it is equal to the current word. If your <code>exclude</code> was a <a href=\"https://docs.python.org/3/library/stdtypes.html#types-set\" rel=\"nofollow noreferrer\"><code>set</code></a>, you could just do <code>if j in exclude</code>. This change alone should speed up your code a lot (how much depends on how large your list of exclude words actually is).</p>\n\n<p>In addition, you could simplify getting the exclude words:</p>\n\n<pre><code>from collections import Counter\nform itertools import takewhile\n\nTHRESHOLD = 25\n\nwords = Counter(whatever_generates_your_words())\nexclude = set(t[0] for t in takewhile(lambda t: t[1] &lt;= THRESHOLD,\n reversed(words.most_common())))\n</code></pre>\n\n<p>This uses the fact that <a href=\"https://docs.python.org/3/library/collections.html#collections.Counter.most_common\" rel=\"nofollow noreferrer\"><code>collections.Counter.most_common</code></a> is sorted by frequency, so reversing it starts with the least common words. <a href=\"https://docs.python.org/3/library/itertools.html#itertools.takewhile\" rel=\"nofollow noreferrer\"><code>itertools.takewhile</code></a> stops taking when the condition is no longer true, so you don't need to go through all words in the <code>Counter</code>.</p>\n\n<p>For the filtering you should probably use some <a href=\"https://www.pythonforbeginners.com/basics/list-comprehensions-in-python\" rel=\"nofollow noreferrer\">list comprehensions</a>. All three of the following functions are doing the same thing:</p>\n\n<pre><code>from itertools import filterfalse\n\ndef remove_nonfrequent(note):\n sentences = []\n for sentence in note.split('. '):\n sentence_ = []\n for word in sentence:\n if word not in exclude:\n sentence_.append(word)\n if sentence:\n sentences.append(\" \".join(sentence))\n return \". \".join(sentences)\n\ndef remove_nonfrequent(note):\n return \". \".join(\" \".join(filterfalse(exclude.__contains__,\n sentence.split(\" \")))\n for sentence in note.split('. '))\n if sentence)\n\ndef remove_nonfrequent(note): \n return \". \".join(\" \".join(word for word in sentence.split(\" \")\n if word not in exclude)\n for sentence in note.split('. ') if sentence)\n</code></pre>\n\n<p>I personally prefer the last one, as it is the most readable one to me.</p>\n\n<p>Note that Python has an official style-guide, <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP8</a>, which recommends using 4 spaces as indentation and surrounding operators with spaces.</p>\n\n<hr>\n\n<p>Since you are using this function with <code>pandas</code> later, a different approach might actually be faster. There is a <a href=\"https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.replace.html\" rel=\"nofollow noreferrer\"><code>pd.Series.replace</code></a> method that can take a dictionary of replacements. You can use it like this:</p>\n\n<pre><code>from itertools import repeat\n\nreplacements = dict(zip((fr'\\b{word}\\b' for word in exclude), repeat(\"\")))\ndf.NOTES.replace(replacements, regex=True, inplace=True)\ndf.NOTES.replace({r' +': ' ', r' +\\.': '.'}, regex=True, inplace=True)\n</code></pre>\n\n<p>The first replace does all the word replacements (using <code>\\b</code> to ensure only complete words are replaced), while the latter one fixes multiple spaces and spaces before a period.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-17T17:36:17.157", "Id": "454134", "Score": "0", "body": "Is there any way i can track how much of the execution is done instead of a blank output? i cannot insert print statements in one liners right?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-17T17:37:37.680", "Id": "454135", "Score": "0", "body": "@AdityaVartak: You can just re-insert your debug statements before the line with the `return`. Or save the output in a variable, do something else and then return it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-17T17:46:06.520", "Id": "454136", "Score": "1", "body": "This works like charm. Thanks @Graipher" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-18T09:30:14.740", "Id": "454178", "Score": "1", "body": "@AdityaVartak: I added a more vectorized version that might be even faster." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-18T10:53:30.403", "Id": "454183", "Score": "1", "body": "Thanks for the effort, but for now the original answer would suffice. Would use this if more optimization is needed." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-18T10:58:08.650", "Id": "454187", "Score": "1", "body": "@AdityaVartak: Fair enough. I just couldn't leave it be without also including a `pandas` version :). Which is also a lot shorter and could be encapsulated into its own function." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-17T15:40:34.663", "Id": "232550", "ParentId": "232549", "Score": "5" } } ]
{ "AcceptedAnswerId": "232550", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-17T15:09:38.373", "Id": "232549", "Score": "5", "Tags": [ "python", "performance", "numpy", "pandas" ], "Title": "Remove words from an exclude list in each row of a pandas.Series" }
232549
<p>The fact is that I wanted to apply the builder pattern. But this could not be achieved, since I could not create an instance of the class with an empty constructor - this is dangerous. The goal is to make the parameter list a little shorter and more meaningful. As a result, I created a new class, the builder, which sets all the fields that are in the class in the constructor.</p> <p>Why don't I want to use a builder pattern? Because the user may not use the builder at all - the required fields will be blank.</p> <p>GameObject:</p> <pre><code>public abstract class GameObject { protected boolean isHidden; protected Coordinate position; protected int pictureWidth, pictureHeight; protected Object filling; GameObject(GameObjectBuilder gameObjectBuilder) throws IOException{ this.position = new Coordinate(gameObjectBuilder.getPosition()); this.pictureWidth = gameObjectBuilder.getPictureWidth(); this.pictureHeight = gameObjectBuilder.getPictureHeight(); this.isHidden = gameObjectBuilder.isHidden(); this.filling = gameObjectBuilder.getFilling(); // link is passed } public void paint(Graphics gr) throws IOException{ if(filling instanceof BufferedImage) { gr.drawImage((Image) filling, position.getX(), position.getY(), null); } else if(filling instanceof Color) { gr.setColor((Color) filling); gr.fillRect(position.getX(), position.getY(), pictureWidth, pictureHeight); } else { System.err.println("You forgot to add a way to render filling"); } } private Object getFilling() { return filling; } int getPictureWidth() { return pictureWidth; } int getPictureHeight() { return pictureHeight; } public boolean isHidden() { return isHidden; } public Coordinate getPosition() { return position; } } </code></pre> <p>GameObjectBuilder:</p> <pre><code>public class GameObjectBuilder { protected boolean isHidden; protected Coordinate position; protected int pictureWidth, pictureHeight; public Object filling; public GameObjectBuilder(int pictureWidth, int pictureHeight, Coordinate position, boolean isHidden, Color filling){ this.position = new Coordinate(position); this.pictureWidth = pictureWidth; this.pictureHeight = pictureHeight; this.isHidden = isHidden; this.filling = filling; // link } public GameObjectBuilder(Coordinate position, boolean isHidden, BufferedImage filling){ this.position = position; this.pictureWidth = filling.getWidth(); this.pictureHeight = filling.getHeight(); this.isHidden = isHidden; this.filling = filling; // передается ссылка } public GameObjectBuilder(GameObjectBuilder gameObject) throws IOException{ this.position = new Coordinate(gameObject.getPosition()); this.pictureWidth = gameObject.getPictureWidth(); this.pictureHeight = gameObject.getPictureWidth(); this.isHidden = gameObject.isHidden(); this.filling = gameObject.getFilling(); //link is passed } public Object getFilling() { return filling; } public int getPictureWidth() { return pictureWidth; } public int getPictureHeight() { return pictureHeight; } public boolean isHidden() { return isHidden; } public Coordinate getPosition() { return position; } } </code></pre> <p>and now for dessert:</p> <p>MaterialGameObject:</p> <pre><code>public abstract class MaterialGameObject extends GameObject{ private int materialHeight, materialWidth; private Coordinate relativeCoordinateOfStartOfFilling; public MaterialGameObject(MaterialGameObjectBuilder materialGameObjectBuilder) throws IOException{ super(materialGameObjectBuilder.getGameObjectBuilder()); this.materialHeight = materialGameObjectBuilder.getMaterialHeight(); this.materialWidth = materialGameObjectBuilder.getMaterialWidth(); calculateRelativeCoordinateOfStartOfFilling(); } private int getMaterialWidth() { return materialWidth; } public int getMaterialHeight() { return materialHeight; } public Coordinate getRelativeCoordinateOfStartOfFilling() { return relativeCoordinateOfStartOfFilling; } protected abstract void calculateRelativeCoordinateOfStartOfFilling(); } </code></pre> <p>MaterialGameObjectBuilder:</p> <pre><code>public class MaterialGameObjectBuilder{ private GameObjectBuilder gameObjectBuilder; private int materialHeight, materialWidth; public MaterialGameObjectBuilder(GameObjectBuilder gameObjectBuilder, int materialHeight, int materialWidth) { this.gameObjectBuilder = gameObjectBuilder; // link this.materialHeight = materialHeight; this.materialWidth = materialWidth; } public GameObjectBuilder getGameObjectBuilder(){ return gameObjectBuilder; } public int getMaterialHeight() { return materialHeight; } public int getMaterialWidth() { return materialWidth; } } </code></pre> <p><strong>Did I choose the right path?</strong></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-18T11:17:31.007", "Id": "454194", "Score": "0", "body": "First you say you wanted to apply the builder pattern, then you say you don't. Please clarify your intentions." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-18T11:26:38.653", "Id": "454200", "Score": "1", "body": "I wantED to, but then it turned out that I could not achieve some goals. And now I do not want to use it." } ]
[ { "body": "<p>This is a <em>parameter object</em> or <em>argument object</em>, which is related to the <em>command pattern</em>.</p>\n\n<p>An example of this in the Java class library is the constraint object <code>java.awt.LayoutManager2</code> (an odd name for a JDK1.00 type).</p>\n\n<p>The Software Engineering StackExchange has the question <a href=\"https://softwareengineering.stackexchange.com/q/251939/735\">Does the pattern of passing in one object instead of many parameters to a constructor have a name?</a> [it does].</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-17T19:10:23.117", "Id": "454142", "Score": "0", "body": "What? Do you mean my abstract method?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-17T21:00:41.837", "Id": "454154", "Score": "0", "body": "He means Command Pattern. https://en.wikipedia.org/wiki/Command_pattern" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-18T05:05:03.897", "Id": "454167", "Score": "0", "body": "honestly, I don’t understand how this pattern relates here" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-18T05:31:25.697", "Id": "454169", "Score": "0", "body": "Are you saying that this is a command pattern, but instead of an action I enclose variables in it?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-18T12:44:42.423", "Id": "454219", "Score": "0", "body": "This isn't really the use case of a Command pattern though.." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-18T13:31:25.113", "Id": "454232", "Score": "0", "body": "@IEatBagels No this isn't the command pattern - it relates to the command pattern. The argument object bundles all the information necessary for the action. Only instead of providing a method to perform a particular action, it is passed to a function (constructor in this case) to do whatever." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-18T19:23:23.143", "Id": "454274", "Score": "0", "body": "Wow, this is what i was looking for. People write that this pattern, when used properly, is very good. What is your opinion on this matter, what alternatives do you see, if any?" } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-17T19:01:03.897", "Id": "232557", "ParentId": "232551", "Score": "4" } }, { "body": "<p>Yeah, this isn't a builder. I don't know if this pattern has a name, but having an intermediate data object like this which moves the complexity of multiple constructors out of the target object is a thing.</p>\n\n<p>However the builder pattern doesn't require the target object to have an empty (no-argument) constructor. Example:</p>\n\n<pre><code>public class Coordinate {\n private int x;\n private int y;\n\n public Coordinate(int x, int y) {\n this.x = x;\n this.y = y;\n }\n\n // Getters...\n}\n\npublic CoordinateBuilder {\n private Integer x = null;\n private Integer y = null;\n\n public CoordinateBuilder x(int x) {\n this.x = x;\n return this;\n }\n\n public CoordinateBuilder y(int y) {\n this.y = y;\n return this;\n }\n\n public Coordinate build() {\n if (x == null || y == null) {\n throw new IllegalStateException();\n }\n return new Coordinate(x,y);\n }\n}\n\nCoordinate a = new CoordinateBuilder().x(1).y(2).build();\n</code></pre>\n\n<hr>\n\n<p>Some general remarks about your code:</p>\n\n<ul>\n<li><p>Since this isn't a builder pattern I'd rename <code>GameObjectBuilder</code> to something like <code>GameObjectData</code>.</p></li>\n<li><p>Since <code>GameObjectBuilder/Data</code> is immutable, I'd suggest just keeping a reference of it in <code>GameObject</code> instead of coping the values out of it.</p></li>\n<li><p>Objects should have a single \"main\" constructor and other constructors should call it. </p></li>\n<li><p>Is it on purpose that one of the constructors doesn't call the copy constructor for <code>position</code>?</p></li>\n<li><p>I'm not a big fan of using a plain <code>Object</code>. </p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-17T19:39:18.240", "Id": "454148", "Score": "0", "body": "it is immutable, but in the class itself, some passed variables can change. I will take this moment into account when designing. The idea with the main constructor is very useful, I will use it. I forgot to add a constructor for position. What can you suggest instead of using object? I don’t think that a list of objects of different classes, only one of which is not null, is a good idea" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-18T20:39:03.100", "Id": "454281", "Score": "0", "body": "@Miron If anything about its state change, then it isn't immutable. I'm not sure if I understand your comment." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-19T03:25:40.180", "Id": "454292", "Score": "0", "body": "By saving a link to it in a game object, do you mean aggregation? I copy the values because otherwise we will change the fields of the builder when we change the fields of the game object" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-17T19:16:34.240", "Id": "232559", "ParentId": "232551", "Score": "8" } }, { "body": "<p>This is sure not a builder. The main characteristic of a builder is that it can build some target object.</p>\n\n<p>Your \"builder\" is just a plain data structure. And you use it a bit like a service locator (antipattern).</p>\n\n<p>The point with builders is they simplify construction of other objects. So you have some class, it has complicated constructor, maybe it accepts some abstractions and you want the builder to help you chose the correct implementations.</p>\n\n<p>Rule of thumb is the target object/class is not aware of existence of the builder class. On other hand builder must be aware of the class of the objects it builds.</p>\n\n<p>Also it is usualy not the target who has empty constructor, but often it is the builder. If the target had empty constructor you probably wouldn't need a builder to simplify the construction.</p>\n\n<p>Also a builder must have some mutating methods. It would be hard to tell builder how to do the construction if he is unable to change anything. The builder must be able to incorporate your demands into his build plan yet before he actually uses that plan to build the target in a way that it meets your demands.</p>\n\n<p>Further, the filling is where your builder can help. Dont pass just any object as filling. Create a <code>FillingInterface</code>, create one implementation of BufferedImage and one for Color. Add corresponding methods to your builder.</p>\n\n<p>So after discussion I have changed the code sample below to show a better representation of what I mean. I also got rid of the abstract classes using decorator.</p>\n\n<pre><code>interface FillingInterface\n{\n int getWidth();\n int getHeight();\n void fill(Graphics graphics, Position position);\n}\n\nclass BufferedImageFilling : FillingInterface\n{\n private BufferedImage image;\n BufferedImageFilling(image) {this.image = image;}\n\n int getWidth() {return image.getWidth();}\n int getHeight() {return image.getHeight();};\n\n void fill(Graphics gr, Position position) {\n gr.drawImage(this.image, position.getX(), position.getY(), null);\n }\n}\n\nclass ColorFilling : FillingInterface\n{\n private Color color;\n ColorFilling(Color color, int width, int height) {\n this.color = color;\n this.width = width;\n this.height = height;\n }\n\n int getWidth() {return this.width;}\n int getHeight() {return this.height;};\n\n void fill(Graphics gr, Position position) {\n gr.setColor(this.color);\n gr.fillRect(position.getX(), position.getY(), this.width, this.height);\n }\n\n}\n\ninterface GameObjectInterface\n{\n void paint(Graphics gr);\n Coordinate getPosition();\n boolean isHidden();\n int getPictureWidth();\n int getPictureHeight();\n}\n\nclass GameObject : GameObjectInterface\n{\n private FillingInterface filling;\n private Coordinate position;\n private boolean hidden;\n\n public GameObject(FillingInterface filling, Position position, boolean hidden = false) {\n this.filling = filling;\n this.position = position;\n this.hidden = hidden;\n }\n\n public Coordinate getPosition() {return this.position;} \n public boolean isHidden() {return this.hidden;}\n public int getPictureWidth() {return this.filling.getWidth();}\n public int getPictureWidth() {return this.filling.getHeight();}\n public void paint(Graphics gr) {this.filling.fill(gr, this.position);}\n}\n\nclass GameObjectBuilder\n{\n private boolean hidden = false;\n private FillingInterface filling;\n private Coordinate position;\n\n public GameObjectBuilder() {}\n\n public void setHidden(boolean hidden) {this.hidden = hidden;}\n public void setFilling(FillingInterface filling) {this.filling = filling;}\n public void setPosition(Coordinate position) {this.position = position;}\n public GameObject build() {return new GameObject(this.filling, this.position, this.hidden);}\n}\n\nclass GameObjectDecorator : GameObjectInterface\n{\n private gameObject;\n public GameObjectDecorator(GameObjectInterface gameObject) {\n this.gameObject = gameObject;\n }\n\n public boolean isHidden() {return this.gameObject.isHidden();}\n public Coordinate getPosition() {return this.gameObject.getPosition();}\n public int getPictureWidth() {return this.gameObjet.getPictureWidth();}\n public int getPictureHeight() {return this.gameObjet.getPictureHeight();}\n public void paint(Graphics gr) {this.gameObject.paint(gr);}\n}\n\nclass MaterialGameObject : GameObjectDecorator\n{\n private GameObjectInterface gameObject;\n private FillingInterface materialFilling;\n public MaterialGameObject(GameObjectInterface gameObject, FillingInterface materialFilling) {\n this.gameObject = gameObject;\n this.materialFilling = materialFilling;\n }\n\n public void paint(Graphics gr) {\n parent.paint(gr);\n this.materialFilling.fill(gr, this.getPosition());\n }\n}\n\nclass MaterialGameObjectBuilder\n{\n private GameObjectInterface gameObject;\n private FillingInterface materialFilling;\n\n public MaterialGameObjectBuilder() {}\n\n public void setGameObject(GameObjectInterface gameObject) {this.gameObject = gameObject;}\n public void setMaterialFilling(FillingInterface materialFilling) {this.materialFilling = materialFilling;}\n public MaterialGameObject build() {\n return new MaterialGameObject(this.gameObject, this.materialFilling);\n }\n}\n</code></pre>\n\n<p>Although I think at this point the builders become useless as there are now only 2-3 parameters to constructor. Should be pretty ok to use the constructors directly...</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-18T12:28:26.703", "Id": "454217", "Score": "0", "body": "Comments are not for extended discussion; this conversation has been [moved to chat](https://chat.stackexchange.com/rooms/101170/discussion-on-answer-by-slepic-a-new-type-of-builder-pattern)." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-18T07:16:51.557", "Id": "232571", "ParentId": "232551", "Score": "5" } }, { "body": "<p>By no means, this is builder. It's rather a defunct clone of the original object.</p>\n\n<p>A builder is something helping you to avoid too many constructors by letting you to build your object incrementally. You seem to need exactly three constructor for you object and your non-builder has them all.</p>\n\n<p>Typically, a builder has a single no-args constructor and a bunch of setters for the incremental build-up. Sometimes, multiple constructors are useful for setting some \"remarkable\" properties upfront.</p>\n\n<p>A builder typically has no getters, as you hardly ever care what's inside. When building the main object, it either passes all fields one-by-one or access them directly (the builder is pretty always in the same package and usually even in the same file, so it access private fields).</p>\n\n<p>A builder has pretty always a method <code>build()</code>. It gets used as it's damn convenient to write things like</p>\n\n<pre><code>Person adam = Person.builder()\n.name(\"Adam Savage\")\n.city(\"San Francisco\")\n.job(\"Mythbusters\")\n.job(\"Unchained Reaction\")\n.build();\n</code></pre>\n\n<hr>\n\n<p>A builder does make little sense without the main object being immutable. The immutability gets usually enforced by using <code>final</code> fields.</p>\n\n<p>Fields should normally be <code>private</code>. I strongly recommend making everything as private as possible; lifting restrictions later is trivial, unlike the other way round.</p>\n\n<hr>\n\n<p>When dealing with such objects, I prefer letting a tool take care of the boilerplate, e.g., a <a href=\"https://projectlombok.org/features/Builder\" rel=\"nofollow noreferrer\">Builder from Lombok</a> does a nice job. You code could be</p>\n\n<pre><code>@Value @Builder\npublic class GameObject {\n private final boolean isHidden;\n private final Coordinate position;\n private final int pictureWidth, pictureHeight;\n private final Object filling;\n\n public void paint(Graphics gr) throws IOException {\n ...\n }\n}\n</code></pre>\n\n<p>and a builder gets generated as an nested class.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-18T08:45:51.657", "Id": "232576", "ParentId": "232551", "Score": "4" } } ]
{ "AcceptedAnswerId": "232557", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-17T16:53:22.907", "Id": "232551", "Score": "8", "Tags": [ "java", "object-oriented", "design-patterns" ], "Title": "A new type of builder pattern" }
232551
<p>I'm new to the C programming language and I just made a basic version of Python's <code>split()</code> function using C.</p> <p><strong>Note:</strong> A major functionality I chose not to implement is the usage of optional delimiters.</p> <p>Official documentation of <code>split()</code> can be found <a href="https://docs.python.org/3.8/library/stdtypes.html#str.split" rel="noreferrer">here</a>.</p> <pre class="lang-c prettyprint-override"><code>#include &lt;stdlib.h&gt; #define TRUE 1 #define FALSE 0 #define DEFAULT_BUFSIZE 512 static inline int isDelimiter(char s) { return s == ' ' || s == '\t'; } // Splits a string with elements delimited by spaces or tabs into an array // of strings. It works very similarly to Python's split() function. int parser(char *source, char ***destination) { // The auxiliar variable `aux` will save the array contents, rather than // using *destination. Its elements length is initially DEFAULT_BUFSIZE // so that realloc() doesn't have to be called everytime a character // is copied. The memory used by each element will be reduced to the // minimum possible afterwards. // The most efficient solution would actually be having two buffer // variables: one for the element size and another for the array itself. // But currently this isn't neccessary. size_t bufsize = DEFAULT_BUFSIZE; char **aux = malloc(sizeof(char *)); // The source string is iterated and its contents are copied to the aux // array, so we need 3 counters: // * `len` is the array length // * `iArr` is the array's current element index. // * `iStr` is the source array's index. size_t len = 1; int iStr = 0; int iArr = 0; // If there's more than 1 delimiter in a row, a new element shouldn't be // created. This is why `newEl` has to be created. It acts as a boolean // that indicates when a new element should start. int newEl = TRUE; // The first element of the array is created. The rest will be allocated // inside the loop. aux[0] = malloc(bufsize * sizeof(char)); while (source[iStr] != '\0') { if (isDelimiter(source[iStr]) &amp;&amp; !newEl) { // The used memory is reduced to what's actually being used. aux[len-1] = realloc(aux[len-1], (iArr+1) * sizeof(char)); // The current element ends. aux[len-1][iArr] = '\0'; iArr = 0; ++len; // Don't come back here until a character other than a delimiter // is found. newEl = TRUE; // The new element is allocated. aux = realloc(aux, len * sizeof(char *)); aux[len-1] = malloc(bufsize * sizeof(char)); } else if (!isDelimiter(source[iStr])) { // The source character is copied to the destination. aux[len-1][iArr] = source[iStr]; ++iArr; // From now on, a new element can be started. newEl = FALSE; // The buffer is enlargened if neccessary. if (iArr &gt;= bufsize) { bufsize += DEFAULT_BUFSIZE; aux[len-1] = realloc(aux[len-1], bufsize * sizeof(char *)); } } ++iStr; } // The last element's size has to be reduced outside of the loop, and a // '\0' is added to finish it. If newEl is true, it means the last element // is filled with delimiters and it shouldn't be included in the array. if (newEl) { --len; } else { aux[len-1] = realloc(aux[len-1], (iArr+1) * sizeof(char)); aux[len-1][iArr] = '\0'; } // Finally, the last element is NULL. aux[len] = NULL; // Saving the destination variable and returning its length. *destination = aux; return len; } </code></pre> <p>I also made a small test file:</p> <pre class="lang-c prettyprint-override"><code>#include &lt;stdio.h&gt; // fgets()... #include &lt;string.h&gt; // strlen() #include &lt;stdlib.h&gt; // size_t, atoi... #include "parser.h" #define MAX 1024 int main() { char str[MAX]; printf("Introduce numbers delimited by spaces or tabs: "); fgets(str, MAX, stdin); // Removing the '\n' from fgets() str[strlen(str)-1] = '\0'; char **nums; size_t len = parser(str, &amp;nums); if (len == 0) { fprintf(stderr, "No input.\n"); exit(1); } int sum = 0; for (int i = 0; i &lt; len; ++i) sum += atoi(nums[i]); printf("Sum: %d\n", sum); free(nums); return 0; } </code></pre> <p>Also, <a href="https://godbolt.org/z/rGtvN9" rel="noreferrer">here's</a> a GodBolt snippet.</p>
[]
[ { "body": "<p>So, you basically rewrote the <a href=\"http://www.cplusplus.com/reference/cstring/strtok/\" rel=\"noreferrer\">strtok function</a> in ANSI C. The difference is that you allocate memory for each substring while TOK modifies the original string by adding \\0 characters in the place of delimiters. This means that you keep allocating more and more memory, while you can just make a copy of the whole string and use strtok to modify the copy you just made, keeping the original string untouched.\nWhen you write more advanced C code, try to avoid the need to allocate more memory. You know the amount of memory required is just the length of the string so make a copy of it. Then replace the tokens you want to replace with the \\0 character, walking through the string just once and returning pointers to each start of a substring. And decide if \"\\0\" is a string that you want to return or not...\nNice attempt, but it can be improved by not using realloc() in the first place... That method will slow down this function considerably...</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-17T18:12:47.133", "Id": "454137", "Score": "2", "body": "It's closer to Python's split() than to C's strtok(). Because if one of the elements had more than 1 space between them, replacing them with '\\0' wouldn't be a good idea." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-17T18:40:30.983", "Id": "454139", "Score": "1", "body": "But after finding the first delimiter, you can just keep skipping characters in the string until you find a non-delimiter. The next string would start at that location and continue until the next delimiter. But all I'm saying is that you keep reallocating memory instead of using the memory that you've already allocated. There's a good chance that your code will leak memory, as you do free nums in your example, but you're not freeing all the strings allocated inside nums. I haven't tested your code but it seems leaky at first glance." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-17T18:48:03.393", "Id": "454140", "Score": "1", "body": "Hmmm that makes more sense yeah. Also, I didn't realize the free(nums), thanks for pointing it out." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-17T18:08:27.377", "Id": "232554", "ParentId": "232552", "Score": "10" } }, { "body": "<p>Minor stuff ...</p>\n\n<p><strong>Allocate to the object, not type</strong></p>\n\n<p>The below is easier to maintain.</p>\n\n<pre><code>// char **aux = malloc(sizeof(char *))\nchar **aux = malloc(sizeof *aux)\n\n// aux[0] = malloc(bufsize * sizeof(char));\naux[0] = malloc(sizeof *(aux[0]) * bufsize);\n</code></pre>\n\n<p><strong>Avoid Exploit</strong></p>\n\n<p>Below code is undefined behavior is the first character of user input is the <em>null character</em>. It is also incorrect if a <code>'\\n'</code> was never read. (long line, or EOF before a <code>'\\n'</code>.)</p>\n\n<pre><code>// Removing the '\\n' from fgets()\nstr[strlen(str)-1] = '\\0';\n</code></pre>\n\n<p>A better approach is</p>\n\n<pre><code>str[strcspn(str, \"\\n\")] = '\\0';\n</code></pre>\n\n<p><strong>Avoid mixing types</strong></p>\n\n<p>I recommend to use the same type.</p>\n\n<pre><code>size_t len = ...\n...\n// for (int i = 0; i &lt; len; ++i)\nfor (size_t i = 0; i &lt; len; ++i)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-19T21:49:33.720", "Id": "454431", "Score": "0", "body": "Thanks for the tips! The only one I don't understand that much is the first. Why would that be better than what I did? It seems more confusing to me." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-19T22:20:41.483", "Id": "454437", "Score": "0", "body": "@Dewamuval Which code is certainly correct `pointer = malloc(sizeof *pointer * n)` vs. `pointer = malloc(sizeof(long) * n)`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-20T13:23:47.467", "Id": "454507", "Score": "1", "body": "Yeah the first one makes more sense, thanks." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-18T01:14:54.860", "Id": "232567", "ParentId": "232552", "Score": "13" } }, { "body": "<p><strong>Major issue</strong></p>\n\n<p>You allocate memory that can take a single pointer for <code>aux</code>, then start accessing off the end of it with <code>aux[len-1]</code>.</p>\n\n<p>These sort of issues create exploitable security vulnerabilities.</p>\n\n<p>For an array of pointers I would have expected to see use of <code>calloc()</code>.</p>\n\n<p>Try re-running using something like <a href=\"https://clang.llvm.org/docs/AddressSanitizer.html\" rel=\"nofollow noreferrer\">Clang's address sanitizer</a> (for example, with <code>cc split.c -fsanitize=undefined,address -o split</code>).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-19T21:51:39.347", "Id": "454435", "Score": "1", "body": "I didn't even know about calloc! And clang's addess sanitizer sounds really helpful too, thanks." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-18T13:16:27.650", "Id": "232589", "ParentId": "232552", "Score": "2" } }, { "body": "<p>Your usage of realloc is wrong:</p>\n\n<pre><code>aux = realloc(aux, len * sizeof(char *));\n</code></pre>\n\n<p>The trouble is that if <code>realloc()</code> fails (i.e. it can not find a bigger block) it does not release <code>aux</code> but returns <code>NULL</code>. So the correct usage is:</p>\n\n<pre><code>char** tmp = realloc(aux, len * sizeof(char *));\nif (tmp == NULL) {\n /* SOME ERROR HANDLING */\n // free(aux);\n exit(0); // or something approipriate\n}\naux = tmp; // Now we have handled errors we can assign to aux.\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-19T21:50:07.193", "Id": "454432", "Score": "0", "body": "Yes, I should take care of errors with malloc and realloc. Thanks!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-18T14:48:35.520", "Id": "232593", "ParentId": "232552", "Score": "4" } }, { "body": "<p>Being new to C, you probably do not know that there is C++, and moreover, all of such things, that you are looking for, like python's <code>split()</code>, etcetera - already exist and are implemented in the <a href=\"https://www.boost.org/\" rel=\"nofollow noreferrer\">boost</a> library.</p>\n\n<pre><code>#include &lt;boost/algorithm/string.hpp&gt; \n\nusing namespace std;\nusing namespace boost;\n\nstd::vector&lt; std::string &gt; python_split( std::string target, std::string substring ) {\n std::vector&lt; std::string &gt; Split;\n boost::split( Split, target, boost::is_any_of( substring ), token_compress_on );\n return Split;\n}\n\n// Usage,\nvector&lt; string &gt; s = python_split( \"ololo big-big text ololo 123\", \" \");\n// s = [ \"ololo\", \"big-big\", \"text\", \"ololo\", \"123\" ];\n</code></pre>\n\n<p>So, writing your own <code>split()</code> in C - is something like writing nowadays a web application back-end in assembler ... No sense...</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-04T10:54:29.597", "Id": "459860", "Score": "1", "body": "This post would make a half-decent comment. Given that the question is tagged [tag:reinventing-the-wheel], the only point is *where* a prominent implementation can be found." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-04T11:21:20.087", "Id": "459866", "Score": "0", "body": "@greybeard The point of this post was to learn about C, not to invent something new. The title of this post already mentions an existing implementation in Python. I don't really care if I'm reinventing the wheel, I did this to learn and improve. And I did appreciate the actual answers with tips." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-04T13:26:11.400", "Id": "459880", "Score": "0", "body": "(@Dewamuval you seem to use a very different interpretation of *post* - mine here: this *answer*, not the *question*. Consequently, I have been pointing out, not least to Straustrup, that mentioning easy access to existing solutions for a task tackled in a question tagged reinventing-the-wheel is pointless.)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-04T15:09:52.907", "Id": "459890", "Score": "0", "body": "He said, \"I'm new\", I have shown him best enter. Mostly \"Everything\" from `boost` - becomes a standard `*( std:: )` one day." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-04T16:47:51.123", "Id": "459893", "Score": "1", "body": "@StrausTrup: in general, if a question is tagged with a specific language, like \"c\" in this case, don't give an answer in a different language, it is not going to be helpful." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-07T10:19:22.230", "Id": "460245", "Score": "0", "body": "@G. Sliepen, Are u kidding me? C and C++ - is different languages? may be like U.S. English and G.B. English, same way? Are u from south / east-cost? It is one language, that is growing up, already to c++20 standard, and Boost - is main donator to this language. He, may be will u say that C++11 and C++17 - different languages? U r funny ..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-07T19:48:54.783", "Id": "460315", "Score": "0", "body": "@StrausTrup: https://stackoverflow.com/questions/14330370/is-c-c-one-language-or-two-languages" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-08T16:20:34.597", "Id": "460421", "Score": "0", "body": "`Italian/Spanish` haaaa... he jokes, you believe.. It is ONE Language! probably, Latin/Italian - this way, and not so rude. There is no 2k years between this two languages. u able to use <u>ANY</u> C library inside your C++ program. It is just a version #2. The same way, as Linux - evolution, currently to Kernel 5.x, but it support all old GNU tools, like `ls`, `find`, etc... So, is linux 2.X and linux 5.x - different OS? No, baby, it is one OS, but 10 years evolution inside one - this is only difference. Wake up!" } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-04T09:56:10.490", "Id": "235062", "ParentId": "232552", "Score": "-3" } } ]
{ "AcceptedAnswerId": "232567", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-17T17:34:07.413", "Id": "232552", "Score": "11", "Tags": [ "beginner", "c", "strings", "reinventing-the-wheel", "memory-management" ], "Title": "Python's .split() implemented in C" }
232552
<p>My React application manages some entities. I'm using Redux (with redux-thunk) to manage the application state. I've created a RESTClient based on Axios:</p> <pre><code>export class RESTClient&lt;E extends { id: number }&gt; extends Client { protected path: string; public constructor(path: string, token?: string) { super(token); this.path = path; } public index() { return this.clientInstance.get&lt;E[]&gt;(this.path); } public create(entity: Omit&lt;E, 'id'&gt;) { return this.clientInstance.post&lt;E&gt;(this.path, entity); } public update(entity: E) { return this.clientInstance.put&lt;E&gt;(`${this.path}/${entity.id}`, entity); } public delete(entity: E) { return this.clientInstance.delete&lt;E&gt;(`${this.path}/${entity.id}`); } } </code></pre> <p>This RESTClient is used by a Redux action generator:</p> <pre><code>export const createClientAction = &lt;T extends Client&gt;( type: new (token?: string) =&gt; T, action: (client: T, dispatch: Dispatch, getState: () =&gt; State) =&gt; void ) =&gt; { return async (dispatch: Dispatch, getState: () =&gt; State) =&gt; { const clientInstance = getState().session.isAuthenticated ? new type(getState().session.token) : new type(); action(clientInstance, dispatch, getState); }; }; </code></pre> <p>Now to create a delete action for the entity participant I create an action as follows:</p> <pre><code>import { createAction } from 'typesafe-actions'; const deleteParticipantSuccess = createAction('participant/DELETE', (participant: Participant) =&gt; participant)(); export const deleteParticipant = (participant: Participant) =&gt; { return createClientAction(ParticipantClient, (client, dispatch) =&gt; { client.delete(participant).then(() =&gt; { dispatch(deleteParticipantSuccess(participant)); dispatch( addEvent({ message: 'event.success.deleted', values: { entity: participant.email }, type: EventType.SUCCESS }) ); }); }); }; </code></pre> <p>Obviously for error handling I need to add a few lines.</p> <p>When I implement all CRUD-Actions with error handling I have per entity ~150 lines of code. What would you do with this, to DRY it up?</p> <ol> <li>Would you write something which generates the CRUD actions?</li> <li>Do you think I would benefit if I use sagas instead of redux-think?</li> <li>Do you think I could simplify things if I implement a custom Redux middleware, especially regarding to the event dispatches?</li> </ol>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-21T13:36:10.600", "Id": "454612", "Score": "0", "body": "Is `createAction` defined in one of the libraries you use, or custom? If custom, can you add the code of `createAction`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-21T13:41:33.753", "Id": "454617", "Score": "0", "body": "`createAction` is from `typesafe-actions`: https://github.com/piotrwitek/typesafe-actions" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-17T21:25:27.743", "Id": "232561", "Score": "2", "Tags": [ "generics", "typescript", "redux", "axios" ], "Title": "Reduce repetition in these Redux CRUD actions" }
232561
<p>I was recently going through some OpenCV code that finds the center of mass in a contour and realized there is potential room for optimisation.</p> <p>What I noticed looking back through my code is when I calculate the mass I'm using contours.size() which makes me believe that I'm calculating the moments and center of mass for all of my contours.</p> <p>In my cases this is not needed as I have a function that returns the largest contour that I have found <code>getMaxAreaContourId(contours, imageSize);</code> which returns an int that I can use like <code>contours[largestContour]</code> and <code>largestContour</code> would be set from the result of <code>getMaxAreaContourId</code></p> <p>So if I'm not mistaken would I be able to just find the moment and mass from a single contour and completely remove two for loops?</p> <p>Because Ultimately I end up doing this:</p> <p><code>int CenterOfContourX = mc[largestContour].x; int CenterOfContourY = mc[largestContour].y;</code></p> <p>Really the end goal is to end up with two integers that represent the center of mass of my contour.</p> <p>Code to optimise:</p> <pre><code>// Get the moments mu.reserve(contours.size()); for( int i = 0; i &lt; contours.size(); i++ ) { mu[i] = moments( contours[i], false ); } // Get the mass centers: std::vector&lt;cv::Point2f&gt; mc( contours.size() ); for( int i = 0; i &lt; contours.size(); i++ ) { mc[i] = cv::Point2f( mu[i].m10/mu[i].m00 , mu[i].m01/mu[i].m00 ); } </code></pre>
[]
[ { "body": "<p>It seem like you can definitely merge the two loops together.</p>\n\n<p>Also you should avoid iterating using i, instead, use iterators, or the range-based for loop (since C++11).</p>\n\n<pre><code>// if you needed this vector\nmu.reserve(contours.size());\n\n// Get the mass centers:\nstd::vector&lt;cv::Point2f&gt; mc( contours.size() );\nfor( auto&amp; c : contours )\n{\n auto m = moments(c, false); \n mu.push_back(m); // only if you need the mu vector\n mc.push_back(cv::Point2f( m.m10/m.m00 , m.m01/m.m00 )); \n}\n</code></pre>\n\n<p>And this can even be simplified to a call to <code>std::transfer</code> with <code>std::back_inserter</code>:</p>\n\n<pre><code>std::transform(\n std::begin(contours),\n std::end(contours),\n std::back_inserter(mc),\n [](const contour&amp; c) -&gt; cv::Point2f {\n auto m = moments(c, false);\n return cv::Point2f( m.m10/m.m00 , m.m01/m.m00 )\n }\n);\n</code></pre>\n\n<p>And of course if you only need to know moments of one countour, there is no need to count it for all, but since you haven't included that part of the code, it's hard to tell anything about it.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-19T00:37:24.087", "Id": "454287", "Score": "0", "body": "That helps a lot. If it's not clear I'm calculating the center of mass on a blob. And yes atm I only need to calculate the center of mass for one blob currently. In the future I might need to process the center of mass for two blobs but as long as we're talking about a small fixed known number of contours I think I can do away with the loop." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-19T00:39:05.130", "Id": "454288", "Score": "0", "body": "One thing that confuses me is how do I store a single `Moments`? Would I just use: `cv::Moments mu;` instead of: `std::vector<cv::Moments> mu;`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-19T00:51:57.047", "Id": "454290", "Score": "0", "body": "Nvm I figured it out, I'll add a answer for future readers." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-18T08:33:26.263", "Id": "232574", "ParentId": "232562", "Score": "2" } }, { "body": "<h2>This is the improvement I ended up making for anyone interested.</h2>\n\n<p><strong>Old code:</strong></p>\n\n<pre><code>std::vector&lt;std::vector&lt;cv::Point&gt; &gt; contours;\n\nint blobX; //Need to be int cannnot be Point2f\nint blobY;\n\nfindContours( frame, contours, cv::RETR_TREE, cv::CHAIN_APPROX_SIMPLE, cv::Point(0, 0) );\n\n// Get the moments\nmu.reserve(contours.size());\nfor( int i = 0; i &lt; contours.size(); i++ )\n{ mu[i] = moments( contours[i], false ); }\n\n// Get the mass centers:\nstd::vector&lt;cv::Point2f&gt; mc( contours.size() );\nfor( int i = 0; i &lt; contours.size(); i++ )\n{ mc[i] = cv::Point2f( mu[i].m10/mu[i].m00 , mu[i].m01/mu[i].m00 ); }\n\nint largestContour = getMaxAreaContourId(contours, imageSize); //Finds largest contour\nblobX = mc[largestContour].x;\nblobY = mc[largestContour].y;\n</code></pre>\n\n<p><strong>New code:</strong></p>\n\n<pre><code>std::vector&lt;std::vector&lt;cv::Point&gt; &gt; contours;\n\nint blobX; //Need to be int cannnot be Point2f\nint blobY;\n\nfindContours( frame, contours, cv::RETR_TREE, cv::CHAIN_APPROX_SIMPLE, cv::Point(0, 0) );\n\nint largestContour = getMaxAreaContourId(contours, imageSize); //Finds largest contour\ncv::Moments mu;\nmu = moments( contours[largestContour], false );\nblobX = mu.m10/mu.m00;\nblolbY = mu.m01/mu.m00;\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-19T01:01:28.793", "Id": "232621", "ParentId": "232562", "Score": "1" } } ]
{ "AcceptedAnswerId": "232574", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-17T22:14:04.993", "Id": "232562", "Score": "2", "Tags": [ "c++", "performance", "opencv" ], "Title": "OpenCV calculate center of mass for a single contour" }
232562
<p>I am attempting to train many classifiers to test their performance with classifying tweets as being from a political bot, or not (a binary <code>0 or 1</code> classifier).</p> <p>My data is being read in via a csv file, with 200,000 rows, that looks like this:</p> <pre><code>username,tweet,following,followers,is_retweet,is_bot AUSTINLOVESBEER,NHS fails to treat one in six cancer patients on time https://t.co/8M6o3wn7WG,41,34,1,1 AUSTINLOVESBEER,Real reason Alexis Sanchez walked out of Arsenal training revealed https://t.co/zNkBLkCuz9 https://t.co/S0fIhs70sv,41,34,1,1 AUSTINLOVESBEER,George Michael cause of death revealed: What is a dilated cardiomyopathy and fatty liver? https://t.co/luiDpJOc4h https://t.co/g3S2LGJ8hq,41,34,1,1 AUSTINLOVESBEER,Russian TV crew 'offer Swedish teenagers money' to cause trouble in front of cameras https://t.co/kzm7e7U5S9,41,34,1,1 AUSTINLOVESBEER,Donald Trump met Russian ambassador during election campaign https://t.co/oArd5BSGBK,41,34,1,1 AUSTINLOVESBEER,MPs raise concerns over tougher knife crime guidelines' impact on prison populations https://t.co/KJ0tkclknd,41,34,1,1 AUSTINLOVESBEER,Ex-Arsenal coach Laura Harvey blazes a trail in America https://t.co/nYllUTzEws,41,34,1,1 AUSTINLOVESBEER,Russia deploys deadly 'SIZZLER' nuclear submarines as US conflict looms https://t.co/YIqseUIyHq https://t.co/gBabIzOmRh,41,34,1,1 AUSTINLOVESBEER,#Towie: 'Nothing happened with Dan' https://t.co/YNdnqlfeaA https://t.co/DOkZ7h7Gtc,41,34,1,1 AUSTINLOVESBEER,Player ratings: Can any Arsenal players hold their heads high after last night? https://t.co/HM1aFTcIxK https://t.co/z3FmbJkLUG,41,34,1,1 AUSTINLOVESBEER,"Cannabis and prescription painkillers flooding Gaza Strip, Hamas warns https://t.co/muEYFZvx8O",41,34,1,1 </code></pre> <p>I read the data into a pandas data frame, and from there, attempt to <code>vectorize</code> the tweets with a <a href="https://en.wikipedia.org/wiki/Tf%E2%80%93idf" rel="nofollow noreferrer"><code>TFxIDF</code></a> weighting scheme using <a href="https://scikit-learn.org/stable/modules/generated/sklearn.feature_extraction.text.TfidfVectorizer.html" rel="nofollow noreferrer">sklearn's TFxIDF vectorizer</a>. It will create an insanely large feature vector, but that is OK.</p> <p>When running the code, I continuously get errors related to <code>MemoryError</code>. I am requesting a review of my code to see where I can be more memory efficient and, therefore, not have a memory error occur.</p> <p>NOTE - I initially tried to take in over ~1M tweets, and so I read those into two separate data frames and performed a <a href="https://stackoverflow.com/questions/58862819/how-can-i-stack-pandas-dataframes-with-different-column-names-vertically/58862899#58862899"><code>np.vstack</code></a> operation on them. I got the memory error there, so that is when I reduced this to only 200K samples, but am still getting the same error:</p> <pre><code>Traceback (most recent call last): File "d:\Grad School\Fall 2019\605.744.81.FA19 - Information Retrieval\Project\Data\Trainer.py", line 90, in &lt;module&gt; df = pd.DataFrame(data=test.todense(), columns=vectorizer.get_feature_names()) File "C:\Users\Kelly\AppData\Local\Programs\Python\Python37\lib\site-packages\scipy\sparse\base.py", line 849, in todense return np.asmatrix(self.toarray(order=order, out=out)) File "C:\Users\Kelly\AppData\Local\Programs\Python\Python37\lib\site-packages\scipy\sparse\compressed.py", line 962, in toarray out = self._process_toarray_args(order, out) File "C:\Users\Kelly\AppData\Local\Programs\Python\Python37\lib\site-packages\scipy\sparse\base.py", line 1187, in _process_toarray_args return np.zeros(self.shape, dtype=self.dtype, order=order) MemoryError </code></pre> <p>Codes below:</p> <pre><code>import pandas as pd, numpy as np, re, string from sklearn.model_selection import train_test_split from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.neighbors import KNeighborsClassifier from sklearn.ensemble import RandomForestClassifier from sklearn.neural_network import MLPClassifier from sklearn.metrics import confusion_matrix from nltk.corpus import stopwords stop_words = ['ourselves', 'hers', 'between', 'yourself', 'but', 'again', 'there', 'about', 'once', 'during', 'out', 'very', 'having', 'with', 'they', 'own', 'an', 'be', 'some', 'for', 'do', 'its', 'yours', 'such', 'into', 'of', 'most', 'itself', 'other', 'off', 'is', 's', 'am', 'or', 'who', 'as', 'from', 'him', 'each', 'the', 'themselves', 'until', 'below', 'are', 'we', 'these', 'your', 'his', 'through', 'don', 'nor', 'me', 'were', 'her', 'more', 'himself', 'this', 'down', 'should', 'our', 'their', 'while', 'above', 'both', 'up', 'to', 'ours', 'had', 'she', 'all', 'no', 'when', 'at', 'any', 'before', 'them', 'same', 'and', 'been', 'have', 'in', 'will', 'on', 'does', 'yourselves', 'then', 'that', 'because', 'what', 'over', 'why', 'so', 'can', 'did', 'not', 'now', 'under', 'he', 'you', 'herself', 'has', 'just', 'where', 'too', 'only', 'myself', 'which', 'those', 'i', 'after', 'few', 'whom', 't', 'being', 'if', 'theirs', 'my', 'against', 'a', 'by', 'doing', 'it', 'how', 'further', 'was', 'here', 'than'] # This function removes numbers from an array def remove_nums(arr): # Declare a regular expression pattern = '[0-9]' # Remove the pattern, which is a number arr = [re.sub(pattern, '', i) for i in arr] # Return the array with numbers removed return arr # This function cleans the passed in paragraph and parses it def get_words(para): # Split it into lower case lower = para.lower().split() # Remove punctuation no_punctuation = (nopunc.translate(str.maketrans('', '', string.punctuation)) for nopunc in lower) # Remove integers no_integers = remove_nums(no_punctuation) # Remove stop words dirty_tokens = (data for data in no_integers if data not in stop_words) # Ensure it is not empty tokens = (data for data in dirty_tokens if data.strip()) # Ensure there is more than 1 character to make up the word tokens = (data for data in tokens if len(data) &gt; 1) # Return the tokens return tokens # Function to collect required F1, Precision, and Recall Metrics def collect_metrics(actuals, preds): # Create a confusion matrix matr = confusion_matrix(actuals, preds, labels=[2, 4]) # Retrieve TN, FP, FN, and TP from the matrix true_negative, false_positive, false_negative, true_positive = confusion_matrix(actuals, preds).ravel() # Compute precision precision = true_positive / (true_positive + false_positive) # Compute recall recall = true_positive / (true_positive + false_negative) # Compute F1 f1 = 2*((precision*recall)/(precision + recall)) # Return results return precision, recall, f1 # not_bot = pd.read_csv("filepath", skiprows=1) # bot = pd.read_csv("filepath", skiprows=1) # csv_table = pd.DataFrame(np.vstack((not_bot.values, bot.values))) # csv_table.columns = ['username', 'tweet', 'following', 'followers', 'is_retweet', 'is_bot'] csv_table = pd.read_csv("filepath", dtype={'username': str, 'tweet': str, 'following': int, 'followers': int, 'is_retweet': int, 'is_bot': int}) # Create the overall corpus s = pd.Series(csv_table['tweet']) corpus = s.apply(lambda s: ' '.join(get_words(s))) # Create a vectorizer vectorizer = TfidfVectorizer() # Compute tfidf values # This also updates the vectorizer test = vectorizer.fit_transform(corpus) # Create a dataframe from the vectorization procedure df = pd.DataFrame(data=test.todense(), columns=vectorizer.get_feature_names()) # Merge results into final dataframe result = pd.concat([csv_table, df], axis=1, sort=False) labels = result['is_bot'] result = result.drop(['is_bot']) X_train, y_train, X_test, y_test = train_test_split(result, labels, test_size = 0.2) knn = KNeighborsClassifier(n_neighbors = 7) rf = RandomForestClassifier() mlp = MLPClassifier() knn.fit(X_train, y_train) rf.fit(X_train, y_train) mlp.fit(X_train, y_train) knn_preds = knn.predict(X_test) rf_preds = rf.predict(X_test) mlp_preds = mlp.predict(X_test) knn_precision, knn_recall, knn_f1 = collect_metrics(knn_preds, y_test) rf_precision, rf_recall, rf_f1 = collect_metrics(rf_preds, y_test) mlp_precision, mlp_recall, mlp_f1 = collect_metrics(mlp_preds, y_test) # Pretty print the results print("KNN | Recall: {} | Precision: {} | F1: {}".format(knn_recall, knn_precision, knn_f1)) print("MLP | Recall: {} | Precision: {} | F1: {}".format(mlp_recall, mlp_precision, mlp_f1)) print("RF | Recall: {} | Precision: {} | F1: {}".format(rf_recall, rf_precision, rf_f1)) </code></pre> <p><strong>NOTE:</strong> I can read in the data just fine...I can print it, and do some <code>pandas</code> calculations with it. It is once I use sklearn's <code>vectorizer</code> that I run into problems.</p>
[]
[ { "body": "<p>As this is <em>Code review</em> I'll provide general (but important) optimizations:</p>\n\n<ul>\n<li><p><strong><code>stop_words = [...]</code></strong>. To obtain a <strong>fast</strong> <em>membership testing</em> it should be defined as <a href=\"https://docs.python.org/3/library/stdtypes.html#set\" rel=\"nofollow noreferrer\"><code>set</code></a> object (not as list).<br>Here's <em>time performance</em> comparison:</p>\n\n<pre><code>In [262]: %timeit 'here' in stop_words \n1.83 µs ± 77.7 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)\n\nIn [263]: stop_words_set = set(stop_words) \n\nIn [264]: %timeit 'here' in stop_words_set \n33.5 ns ± 1.97 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)\n</code></pre>\n\n<p>33.5 <em>nanoseconds</em> against 1.83 <em>microseconds</em> is about <strong>54</strong> times faster.</p></li>\n<li><p><strong><code>remove_nums</code></strong> function.<br>To prevent multiple regexp pattern generation/compilation - prepare precompiled regex pattern at once with <a href=\"https://docs.python.org/3/library/re.html?highlight=re%20compile#re.compile\" rel=\"nofollow noreferrer\"><code>re.complie</code></a> function. Also, use <code>+</code> quantifier to perform substitution for 2 and more digit occurrences at once:</p>\n\n<pre><code>def remove_nums(arr): \n pattern = re.compile(r'\\d+') \n # Return the array with numbers removed\n return [pattern.sub('', i) for i in arr]\n</code></pre></li>\n<li><p><strong><code>get_words</code></strong> function.<br>The whole sequence of subsequent traversals</p>\n\n<pre><code>dirty_tokens = (data for data in no_integers if data not in stop_words)\n# Ensure it is not empty\ntokens = (data for data in dirty_tokens if data.strip())\n# Ensure there is more than 1 character to make up the word\ntokens = (data for data in tokens if len(data) &gt; 1)\n</code></pre>\n\n<p>can be effectively reduced to a single one <em>generator</em> expression:</p>\n\n<pre><code>tokens = (data for data in no_integers \n if data not in stop_words and len(data.strip()) &gt; 1)\n</code></pre></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-18T19:33:07.453", "Id": "454275", "Score": "0", "body": "Thanks for the suggestions. Unfortunately, this doesn't help the issue with the `todense()` matrix being too large, but I appreciate your input. I will implement these suggestions." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-18T19:37:33.290", "Id": "454277", "Score": "0", "body": "@JerryM., Code review is not actually about fixing/trobleshooting" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-18T22:27:31.393", "Id": "454284", "Score": "0", "body": "I've used codereview before :). But could codereview _is_, as far as I understand it, a way to make your code more efficient. If there is a more efficient method for creating the vector space I need other than doing it the way I currently am, that meets the criteria, no?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-19T06:13:08.187", "Id": "454303", "Score": "0", "body": "@JerryM. I would say that your case is specific and balancing between \"fixing\" and \"optmizing\" for now. But if, let's say the assumed workload has grown and the load is established as * +1M tweets per action*, then you'd have a constant problem/error that needs to be fixed before review." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-18T07:53:09.950", "Id": "232572", "ParentId": "232566", "Score": "1" } } ]
{ "AcceptedAnswerId": "232572", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-18T00:47:49.213", "Id": "232566", "Score": "2", "Tags": [ "python", "python-3.x", "pandas", "machine-learning", "memory-optimization" ], "Title": "Optimizing a TFxIDF vectorization - Python 3.x" }
232566
<p>I have a function that checks if a user can perform an operation based on access to a specific URL.</p> <p>The function parameters are the requested URL: <code>url</code>, and user level: <code>lv</code>. The <code>conf</code> object has stored access levels for comparison with the users access level. </p> <pre><code>function isAuthenticated(url, lv){ let conf = config.getConfig(); // Role Editor if((url === "/RoleEditor" || url === "/SaveRoles") &amp;&amp; lv &gt; conf.roleEditor) return true; // Queue if(url === "/WriteQueueData" &amp;&amp; lv &gt; conf.queuedata) return true; // Listener if((url === "/startListener" || url === "/stopListener" || url === "restartListener" || url === "/ListenerConfig" || url === "/SaveListenerConfig") &amp;&amp; lv &gt; conf.listener) return true; // Client details if(url === "/ClientInfo" &amp;&amp; lv &gt; conf.clientDetails) return true; // User information if(url === "/UserManagement" &amp;&amp; lv &gt; conf.userOverview) return true; // User Edit if((url === "/EditUser" || url === "/EditUserToDb") &amp;&amp; lv &gt; conf.userEdit) return true; // // Another 6 of this comparisons // return false; } </code></pre> <p>This seems inefficient. For example, if the url is <code>"/RoleEditor"</code> but the power level is too low, all other comparisons are still being made. This could be fixed by changing to this:</p> <pre><code>if((url === "/RoleEditor" || url === "/SaveRoles")) if(lv &gt; conf.roleEditor) return true; else return false; </code></pre> <p>But that feels even worse (more redundant).</p> <p>Is there a better way to do this?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-18T09:55:40.280", "Id": "454180", "Score": "3", "body": "The current question title, which states your concerns about the code, applies to too many questions on this site to be useful. The site standard is for the title to simply state the task accomplished by the code. Please see [How do I ask a good question?](https://codereview.stackexchange.com/help/how-to-ask) for examples, and revise the title accordingly." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-18T14:37:12.107", "Id": "454241", "Score": "0", "body": "@MartinR: Quality of phrasing aside; I don't think it's wrong for OP to specify what exactly they want reviewed (in this case the redundancy). Not every review has a universally correct answer - different priorities lead to different approaches. I do agree it's not a great title and can do with a rephrasing, but it seems to stay within range of acceptable content (stating what the code is + which specific problem OP wants to tackle)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-18T15:26:59.373", "Id": "454247", "Score": "4", "body": "@Flater: From [ask]: “State what your code does in your title, not your main concerns about it.”" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-20T03:20:00.470", "Id": "454455", "Score": "0", "body": "Not exactly a review of your code, but a review of your design - your model has a single authorization path, with escalating levels of access. It does not contemplate that someone might need to be able to access \"ClientInfo\" but not be able to start/stop listeners, or vice versa, for example. This is sufficient for a simple application, but may eventually need re-working when users can have more complex role allocations." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-20T13:56:07.787", "Id": "454521", "Score": "0", "body": "[url.trim('/') does not actually trim anything besides whitespace](https://tc39.es/ecma262/#sec-trimstring)" } ]
[ { "body": "<p>First of all. I suppose this is about authorization, not authentication.\nUser is authenticated if you were able to verify their identity. What you do there is to check if they have access to particular resources, or if they have right to perform certain action. This is called authorization.</p>\n\n<p>For your code:</p>\n\n<p>This is very bad, because brackets are missing. I wouldn't be sure whether that <code>else</code> belongs to the outer or the inner <code>if</code>.</p>\n\n<pre><code>if((url === \"/RoleEditor\" || url === \"/SaveRoles\"))\n if(lv &gt; conf.roleEditor)\n return true;\n else\n return false;\n</code></pre>\n\n<p>Other than that, there is not much you can do about this except two things:</p>\n\n<p>1) merge everything together, but that would decrease readability wastly:</p>\n\n<pre><code>return ((url === \"/RoleEditor\" || url === \"/SaveRoles\") &amp;&amp; lv &gt; conf.roleEditor)\n || (url === \"/WriteQueueData\" &amp;&amp; lv &gt; conf.queuedata)\n || ...\n</code></pre>\n\n<p>2) increase level of abstraction by creating an authorizator object capable of configuring the authorization rules</p>\n\n<pre><code>const Authorizator = function (config) {\n this.config = config;\n this.rules = {};\n}\nAuthorizator.prototype = {\n addRule : function (urls, check) {\n if (!urls instanceof Array) {\n urls = [urls];\n }\n for (let i=0; i&lt;urls.length; ++i) {\n this.rules[url] = check;\n }\n },\n\n isAuthorized: function (url, lv) {\n return this.rules[url] &amp;&amp; this.rules[url](this.config, lv);\n }\n};\nlet auth = new Authorizator(config);\nauth.addRule([\"/RoleEditor\", \"/SaveRoles\"], (lv, conf) =&gt; lv &gt; conf.roleEditor);\nauth.addRule(\"/WriteQueueData\", (lv, conf) =&gt; conf.queuedata);\n// ...\n\nconst authorized = auth.isAuthorized(url, lv);\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-18T09:26:50.630", "Id": "232578", "ParentId": "232575", "Score": "4" } }, { "body": "<p>According to your description either of <code>if</code> conditional branches should return immediately if <code>url</code> is matched and the returned value is then designated by <em>access level</em> check <code>lv &gt; conf.&lt;some_access_level&gt;</code>.</p>\n\n<p>To avoid falling into a mess on 12 conditionals a more flexible and performant way is to declare a predefined mapping: <em>\"User role name\"</em> --> <em>\"Access level name\"</em>:</p>\n\n<pre><code>const accessRolesMap = {\n \"RoleEditor\": \"roleEditor\",\n \"SaveRoles\": \"roleEditor\",\n \"WriteQueueData\": \"queuedata\",\n \"ClientInfo\": \"clientDetails\",\n \"UserManagement\": \"userOverview\",\n \"EditUser\": \"userEdit\",\n \"EditUserToDb\": \"userEdit\",\n \"startListener\": \"listener\",\n \"stopListener\": \"listener\",\n \"restartListener\": \"listener\",\n \"ListenerConfig\": \"listener\",\n \"SaveListenerConfig\": \"listener\",\n};\n\nfunction isAuthenticated(url, accessLevel) {\n let conf = config.getConfig();\n url = url.replace(/^\\//, '');\n return (accessRolesMap.hasOwnProperty(url) &amp;&amp; accessLevel &gt; conf[accessRolesMap[url]]);\n}\n</code></pre>\n\n<p><strong><code>accessRolesMap</code></strong> may seem <em>de-normalized</em> but it outweighs that with its fast <em>membership</em> check.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-18T22:59:53.547", "Id": "454285", "Score": "0", "body": "In the definition of the `accessRolesMap`, there should be exactly one entry per line of code, to keep the definition readable. Bonus points if you align the role names vertically." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-19T05:57:26.757", "Id": "454302", "Score": "0", "body": "@RolandIllig, Ok, readability is important. Check my update" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-19T08:01:09.787", "Id": "454309", "Score": "0", "body": "\"/RoleEditor\" is now the same as \"RoleEditor\". Nitpicking aside, this is probably the best solution." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-19T09:52:24.983", "Id": "454317", "Score": "0", "body": "I have 2 nitpicks with this answer: 1- As I've explained in other answers, use `url.trim(\"/\")`. In this case, if you need a deeper level in an `url` (using examples from other comments I gave), like in `\"/Admin/DeleteUser/\"`, Yours will return `\"AdminDeleteUser\"` instead of `\"Admin/DeleteUser\"`. The O.P. may like this side effect of your answer, or be surprised by it. 2- It's always a good idea to use `. hasOwnProperty()` instead of `in`. Assuming `url = \"toString\"`, your code will return `true`, which is simply wrong. [...]" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-19T09:55:42.713", "Id": "454318", "Score": "0", "body": "[...] `url in accessRolesMap && accessLevel > conf[accessRolesMap[url]]` with `url = \"toString\"` will be the same as `\"toString\" in accessRolesMap && accessLevel > conf[\"function toString() { [native code] }\"]`, which will return `true` for any `accessLevel` above 0. `\"function toString() { [native code] }\"` is the string representation of `accessRolesMap[\"toString\"]`, to be used as an index in the `conf` object. Using `accessRolesMap.hasOwnProperty(url)` will solve this issue." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-19T10:10:25.103", "Id": "454323", "Score": "0", "body": "@IsmaelMiguel, I've switched to `hasOwnProperty` to skip inherited properties, but in opposite edge cases, another thing to remember is that *\"hasOwnProperty() will return **false** for ES6 class getters and methods\"*" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-19T11:59:26.467", "Id": "454336", "Score": "0", "body": "But it is still usable. If you try to do `class X { constructor(x) {this.x = x;} } var x = new X();`, you can use `x.hasOwnProperty('x')` and it will return `true`. But it is an edge-case." } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-18T11:53:50.057", "Id": "232586", "ParentId": "232575", "Score": "9" } }, { "body": "<h2>If return true, else return false</h2>\n\n<pre><code>if(lv &gt; conf.roleEditor)\n return true;\nelse\n return false;\n</code></pre>\n\n<p>Before we delve into the contextual considerations, an <code>if</code> that returns <code>true</code> or <code>false</code> is always a redundant if. This can at all times be refactored to:</p>\n\n<pre><code>return lv &gt; conf.roleEditor;\n</code></pre>\n\n<h2>Performance</h2>\n\n<blockquote>\n <p>I see that, if the url is \"/RoleEditor\" but the power level is too low, all other comparisons will be made. A fix for this would be changing all to this:</p>\n</blockquote>\n\n<p>The first question is always \"does this performance need to be optimized?\" As these are simple value comparisons, the performance cost is likely negligible. Assuming this method isn't being called many thousands of times in a given page load.</p>\n\n<p>When performance cost is negligible, favor readability over (irrelevant) optimizations. In that regard, you're free to <em>not</em> avoid the additional checks if it makes the code more readable and doesn't meaningfully impact performance.</p>\n\n<p>That being said, the code <em>can</em> be improved here, which I will get to. The main takeaway here is that you are not forced to optimize it the way you currently wanted to if there is no proven performance issue.</p>\n\n<h2>Authentication vs authorization</h2>\n\n<p>As others have already remarked, you're dealing with authorization here, not authentication.</p>\n\n<ul>\n<li><strong>Authentication</strong> = Who is this? (it's Bob)</li>\n<li><strong>Authorization</strong> = Can Bob delete users? (yes)</li>\n</ul>\n\n<h2>Secure authorization</h2>\n\n<p>You are showing a javascript method. Presumably, this runs in the client's browser. By putting the logic in the browser, your users are able to find it and alter it if they so choose. <a href=\"https://softwareengineering.stackexchange.com/questions/200790/how-easy-is-it-to-hack-javascript-in-a-browser\"><strong>This is a bad idea for security concerns</strong></a>.</p>\n\n<p>It's not necessarily wrong to perform these checks client-side (e.g. for a fast response and thus good user experience) if they are also <strong>backed by server-side security checks</strong> (to ensure that users fiddling with the authorization logic client-side are unable to perform actions server-side).</p>\n\n<h2>Optimizing the algorithm</h2>\n\n<p>With all these sidenotes out of the way, we move on to the actual issue you were asking about, optimizing the ifs. Reading the code, there is a general pattern to be spotted:</p>\n\n<pre><code>if(url == \"MyString\" &amp;&amp; lv &gt; conf.MyStringMinimumLevel)\n</code></pre>\n\n<p>Sometimes there is more than one allowed string, so we'll account for that, but the repeating pattern is otherwise always the same. I'm going to refer to these two values as \"names\" and \"levels\" in the rest of the answer for brevity's sake.</p>\n\n<p>This immediately opens the door to abstraction by mapping these names and levels. In fact, you've already sort of done this with all your <code>conf.roleEditor</code>, <code>conf.queuedata</code>, ... values. You just haven't done it reusably, which is forcing you to manually write all your if checks. If you write it reusable, you can reduce this to a very simple process:</p>\n\n<ul>\n<li>Fetch the level based on the <code>url</code> name</li>\n<li>Check if the given user level is greater than the fetched level</li>\n</ul>\n\n<p></p>\n\n<pre><code>var mappings = \n{\n {\n \"level\" : 1\n \"names\" : [ \"RoleEditor\", \"SaveRoles\" ]\n },\n {\n \"level\" : 2\n \"names\" : [ \"WriteQueueData\" ]\n }\n};\n\nfunction isAuthorized(url, lv) {\n\n var mapping = mappings.find(m =&gt; m.names.includes(url.trim('/'));\n\n return mapping !== undefined\n &amp;&amp; lv &gt; mapping.level;\n}\n</code></pre>\n\n<p>To explain:</p>\n\n<ul>\n<li><code>.find()</code> gives us the first item which conforms to the selection logic (or <code>undefined</code> if no such item exists). </li>\n<li>The selection logic (<code>.includes()</code>) checks if a mapping contains a name that matches the <code>url</code> parameter.</li>\n<li>By using <code>url.trim('/')</code>, you omit the first and last character (the <code>/</code>) from the URL when it is a <code>/</code> (but will leave any other characters). This just makes it easier for use to not have to constantly put the <code>/</code> in the mapping names.</li>\n<li>The <code>!== undefined</code> check ensures that we return <code>false</code> if no mapping exists for the current URL. Your intended behavior may be different here - adjust it as you see fit.</li>\n</ul>\n\n<p>You'll probably want to store this mapping in your <code>conf</code> object, but I'll leave the finer points up to you. This is just a basic example of how you can reduce the method.</p>\n\n<h2>Edit: Sidenote</h2>\n\n<p>If the <code>conf</code> object should not be altered (for whatever reason), you can work around this by indirectly using the values in the mappings:</p>\n\n<pre><code>var mappings = \n{\n {\n \"level\" : conf.roleEditor,\n \"names\" : [ \"RoleEditor\", \"SaveRoles\" ]\n },\n {\n \"level\" : conf.queuedata,\n \"names\" : [ \"WriteQueueData\" ]\n }\n};\n\n// The function is unchanged\n</code></pre>\n\n<p>This is less ideal (it's better to just change the <code>conf</code> object) but if you can't change it, you can at least still work around it.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-18T17:04:43.277", "Id": "454259", "Score": "1", "body": "For the mappings, would there be a noticeable downside to just using the roles as keys and the level as values? I.e mappings = {\"RoleEditor\": 1, \"WriteQueueData\": 2}" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-18T18:38:37.927", "Id": "454270", "Score": "2", "body": "Instead of `url.substring(1)` isn't it better to do `url.trim('/')`? This way, if `url` contains `'/RoleEditor'` or `'/RoleEditor/'`, you will be sure it will match with `'RoleEditor'`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-18T22:09:08.820", "Id": "454283", "Score": "0", "body": "@Cain: It somewhat irks me to have to write multiple entries for urls with the same level; but it would work on a technical level, yes." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-20T09:28:16.703", "Id": "454488", "Score": "0", "body": "@IsmaelMiguel: Yes, it does seem to be a better approach. But if you're trying to parse any valid (partial) URL, then you could also start accounting for URL encoding (and probably other things I'm forgetting right now). Definitely a nice to have, but it depends on whether you need it or not and that isn't quite clear to me based on OP's example." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-20T09:34:13.520", "Id": "454490", "Score": "0", "body": "@Flater I don't see it as a \"nice to have\". If you notice, under the `// Listener` comment, the 3rd test is `url === \"restartListener\"` (the slash is missing). Now, it could be a mistake from the O.P. or intentional. Whichever it is, it fails with your code, which will try to match with `\"estartListener\"` instead. The `.trim` function is made to remove unnecessary characters (taken from a list or characters) from the beginning and end of the string. You method blindly drops the first character, whichever it may be." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-20T09:47:41.933", "Id": "454491", "Score": "0", "body": "@IsmaelMiguel: _That_ is a valid point, it does indeed fail for that use case. I will change the answer to at least perform the trim. But I stand by my comment that parsing wasn't particularly what I was focusing on (I'm not even ignoring string case). Not that it might not be necessary, but because it wasn't the focus of the answer." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-20T09:52:05.827", "Id": "454492", "Score": "0", "body": "@Flater But it isn't even parsing, but just a *better* way to remove the slash. Besides, if your url is \"/ABC\" or \"/ABC/\", you expect it to be the same (because it is). And if for some bizarre reason you get \"//ABC//\", it will still all match with \"ABC\", just like my other 2 examples." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-20T11:09:05.697", "Id": "454499", "Score": "0", "body": "@IsmaelMiguel: My point is that if you want to conform to any valid equivalent URL (which is the basis for your argument that \"/Foo\" and \"/Foo/\" are the same), then you should for good measure comply with the entire URL validation logic (case insensitivity, url encoding, ...). It makes little sense to specifically implement URL matching logic and then be selective about which parsing rules you want to follow. For the consumer (be it the next dev or a user), it creates an expectation (proper URL matching) that is then not delivered on." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-20T11:27:55.510", "Id": "454501", "Score": "0", "body": "urls are case sensitive" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-20T11:28:39.803", "Id": "454502", "Score": "0", "body": "but I agree that url equivalence is not the point here and should be done elsewhere anyway" } ], "meta_data": { "CommentCount": "10", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-18T14:24:36.780", "Id": "232592", "ParentId": "232575", "Score": "25" } }, { "body": "<p>Although I don't disagree with the accepted answer, I just wanted to point out another option that is more similar to the OP's original code/logic but with less redundancy.</p>\n\n<p>When one variable is continuously checked, that is a perfect case for a <code>switch</code> statement.</p>\n\n<pre><code>function isAuthenticated(url, lv){\n\n let conf = config.getConfig();\n\n switch(url){\n\n // Role Editor\n case \"/RoleEditor\":\n case \"/SaveRoles\":\n return lv &gt; conf.roleEditor;\n\n // Queue\n case \"/WriteQueueData\":\n return lv &gt; conf.queuedata;\n\n // Listener\n case \"/startListener\":\n case \"/stopListener\":\n case \"restartListener\":\n case \"/ListenerConfig\":\n case \"/SaveListenerConfig\":\n return lv &gt; conf.listener;\n\n // Client details\n case \"/ClientInfo\":\n return lv &gt; conf.clientDetails;\n\n // User information\n case \"/UserManagement\":\n return lv &gt; conf.userOverview;\n\n // User Edit\n case \"/EditUser\":\n case \"/EditUserToDb\":\n return lv &gt; conf.userEdit;\n\n }\n\n return false;\n}\n</code></pre>\n\n<p>As can be seen in the code, replacing a bunch of <code>if</code> expressions with a <code>switch</code> allows you to keep your code comments pretty much as-is, and you can mimic the <code>||</code> by using fall-through on a <code>case</code>.</p>\n\n<p>Some people prefer always having <code>default</code> case where you <code>return false;</code>, others prefer returning outside the <code>switch</code>.</p>\n\n<p>This is definitely more verbose and arguably not as elegant as other solutions, but I just thought it would be good to round out possible solutions because I think it is a perfect example of when you <em>could</em> use a <code>switch</code> statement.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-19T04:01:15.240", "Id": "454293", "Score": "4", "body": "Although logically sound, this is the start of a path that will lead to source code storing config info, which is just terrible. Nobody's going to touch a giant case structure and will simply add to it, whereas the accepted answer is literally screaming **move the mapping outside the source code**." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-19T04:03:48.847", "Id": "454294", "Score": "0", "body": "The second problem is the structure is still similar to the OP, even though it is now a case. It is still \"condition -> return, condition -> return\" structure, which is very difficult to update effectively. If there is a new condition, someone's going to cut and paste a line all over the place, and I can basically guarantee a missed condition." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-19T09:45:38.177", "Id": "454315", "Score": "1", "body": "I believe that the `case \"restartListener\":` may have been a mistake by the O.P.. Everything else starts with `/`, except that one. Also, in `switch(url){`, just like how I've suggested before, it would be better to use `switch(url.trim(\"/\")){` to remove the slashes, making it easier to write and write. Even if the `url` contains e.g.: `\"/Admin/DeleteUser/\"`, it will be `\"Admin/DeleteUser\"` after the `trim`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-19T15:18:43.043", "Id": "454379", "Score": "1", "body": "@IsmaelMiguel: *\"I believe that the `case \"restartListener\"`: may have been a mistake by the O.P.\"* I think so, too, but that's actually a good point in favor of the switch statement: That typo is now much more visible (and, thus, more likely to be found and fixed) than it was before." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-19T15:25:50.917", "Id": "454381", "Score": "1", "body": "@Nelson: I used to think so, too, but after years of maintaining software where every deployment also necessitated deploying config files *which are the same in the installation*, I see things differently: If it is **static configuration info** which is **not meant to be customizable**, it **should be in the source code** (or at least as close to the source code as possible - surely in the same source code repository). Whether it is stored as as actual programming language code or as a text file (parsed at compile time or at run time) does not matter much." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-19T15:33:06.430", "Id": "454384", "Score": "0", "body": "@Nelson, I don't really disagree with anything you are saying, however moving the mappings to an object is still managing things in source code, even if it is now a \"config file\". However, if that mapping is used anywhere else, then I totally agree that this separation is the best. What sucks about config files in general is that if they aren't program code you need to agree on their language. For instance, Is the config JS or JSON, one of which supports trailing commas and one that doesn't. I have fought that battle many times!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-20T22:59:17.050", "Id": "454566", "Score": "1", "body": "Personally, I wouldn't feel like I needed to to refactor this version of the code if I saw it (like I would with the OP's code) but I also wouldn't want to refactor _to_ it absent other considerations." } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-18T22:39:28.823", "Id": "232619", "ParentId": "232575", "Score": "12" } } ]
{ "AcceptedAnswerId": "232592", "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-18T08:42:06.730", "Id": "232575", "Score": "16", "Tags": [ "javascript", "beginner" ], "Title": "Authenticate users based on both user role, and requested operation" }
232575
<p>I am using the below code to retrieve nodes and values. It is taking 20 mins to retrieve the nodes and values of HKLM.</p> <p>I'm expecting to reduce the retrieving time </p> <p><code>Getting nodes</code></p> <pre><code> Private Function f_GetSubkeys(ByVal WindowsRegistryKey As RegistryKey) As Integer For Each subkeyName As String In WindowsRegistryKey.GetSubKeyNames Try count = count + 1 Dim vSubKey As RegistryKey = WindowsRegistryKey.OpenSubKey(subkeyName) If (vSubKey Is Nothing) Then Continue For End If If f_ToGetRegistryData(vSubKey) &lt;&gt; 0 Then Return -1 If f_getsubkeys(vSubKey) &lt;&gt; 0 Then Return -1 Catch ex As SecurityException sExceptionHandling.Append(WindowsRegistryKey.Name &amp; "\" &amp; subkeyName &amp; "," &amp; ex.Message &amp; vbNewLine) Catch ex As Exception MsgBox(ex.ToString) Return -1 End Try Next Return 0 End Function 'To get values of registry data Public Function f_ToGetRegistryData(ByVal regSubKey As RegistryKey) As Integer Try Dim SettingValue As String = "" Dim type As String = "" Dim KeyNames As New List(Of String) KeyNames = regSubKey.GetValueNames.ToList 'To get the the registry values(Name, Type &amp; data) For Each SettingName In KeyNames Dim SettingType = regSubKey.GetValueKind(SettingName) If SettingType = RegistryValueKind.Binary Then type = "REG_BINARY" Dim value = regSubKey.GetValue(SettingName) SettingValue = BitConverter.ToString(value) ElseIf SettingType = RegistryValueKind.MultiString Then type = "REG_MULTI_SZ" Dim Data As String() = regSubKey.GetValue(SettingName) SettingValue = (String.Join(" ", Data)) SettingValue = SettingValue.Replace(",", " ") ElseIf SettingType = RegistryValueKind.None Then type = "REG_NONE" Dim value = regSubKey.GetValue(SettingName) SettingValue = BitConverter.ToString(value) ElseIf SettingType = RegistryValueKind.Unknown Then 'type = "UNKNOWN TYPE" 'SettingValue = "UNKNOWN DATA" Dim proc As ProcessStartInfo = New ProcessStartInfo("cmd.exe") Dim pr As Process proc.CreateNoWindow = True proc.UseShellExecute = False proc.RedirectStandardInput = True proc.RedirectStandardOutput = True pr = Process.Start(proc) Dim paths = regSubKey.ToString Dim value = SettingName.ToString Dim fullpath = "Reg Query " &amp; Chr(34) &amp; paths &amp; Chr(34) &amp; " /v " &amp; Chr(34) &amp; value &amp; Chr(34) pr.StandardInput.WriteLine(fullpath) pr.StandardInput.Close() Dim writer As StringWriter = New StringWriter() Dim arr As String() = pr.StandardOutput.ReadToEnd.Split(CChar(vbLf)) Dim len As Integer = arr.Length Dim regval = arr(6) regval = RTrim(LTrim(regval)) Dim regValSplit = regval.Split(" ") SettingName = value type = regValSplit(regValSplit.Length - 5).ToString Dim Setting = regValSplit(regValSplit.Length - 1).ToString SettingValue = Setting.Replace(vbCr, "") Dim output As String = writer.ToString() pr.StandardOutput.Close() Else SettingValue = regSubKey.GetValue(SettingName).ToString If SettingType = RegistryValueKind.ExpandString Then SettingValue = SettingValue.Replace(",", " ") type = "REG_EXPAND_SZ" End If If SettingType = RegistryValueKind.DWord Then type = "REG_DWORD" End If If SettingType = RegistryValueKind.QWord Then type = "REG_QWORD" If SettingValue = "System.Byte[]" Then SettingValue = " " End If End If If SettingType = RegistryValueKind.String Then SettingValue = SettingValue.Replace(",", " ") type = "REG_SZ" End If End If f_AppendData(regSubKey.Name, SettingName, type, SettingValue) Next Catch ex As Exception MsgBox(ex.ToString) Return -1 End Try Return 0 End Function </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-18T10:48:07.280", "Id": "232581", "Score": "3", "Tags": [ "vb.net", "windows" ], "Title": "Retrieving Registry nodes for HKLM" }
232581
<p>I've made a controller for Python's Turtle. The controller essentially defines an 'instruction set' so that commands can be recorded in a text file and then executed sequentially by the turtle. It acts similarly to (underlying) assembly code in that it executes these instructions in order and can also do simple iteration, and has its own program counter. </p> <p>This is the Turtle class:</p> <pre><code>import turtle class Turtle(object): def __init__(self, command_filename="", turtle_name="Terry", speed=6): """Initialise turtle with filename, name and a speed.""" self.mrTurtle = turtle.Turtle() self.set_speed(speed) self.set_name(turtle_name) if command_filename: self.load_commands(command_filename) self.pc = 0 self.loop_counters = {} def load_commands(self, filename): """Load the command file and set self.commands""" lines_out = [] try: with open(filename, "r") as inFile: for line in inFile.readlines(): comment = line.find(';') if comment != -1: line = line[:comment] line = line.strip() if len(line) &gt; 0: lines_out.append(line) except FileNotFoundError: print(f"File {filename} not found.") if lines_out[0].startswith("name"): self.set_name(lines_out[0].split()[1]) lines_out = lines_out[1:] self.commands = lines_out self.queue = lines_out def Run(self): """Run all commands in buffer""" print(f"{self.name} is ready to go!") self.pc = 0 while self.pc &lt; len(self.commands): self.run_command(self.commands[self.pc]) self.pc += 1 print(f"{self.name} is finished!") def Step(self, steps=1): """Step through specified number of commands. 1 if no number specified.""" for i in range(steps): try: self.run_command(self.commands[self.pc]) self.pc += 1 except IndexError: self.pc = 0 self.run_command(self.commands[self.pc]) self.pc += 1 def StepThrough(self): """Run all commands, but wait for input between each command.""" self.pc = 0 while self.pc &lt; len(self.commands): input("Press Enter.") self.run_command(self.commands[self.pc]) self.pc += 1 def queue_command(self, command): """Add a command to the buffer""" self.commands.append(command) def run_command(self, command): """Send 1 command to turtle. Big switch case handles command.""" print(f"{self.name} is trying {command}") command = command.lower() try: command = command.split(" ") if len(command) &gt; 1: data = [convert(item) for item in command[1:]] else: data = None command = command[0] except: print(f"Error: {self.name} could not perform command {command}") return None if command in ["forward", "forwards", "f", "fwd"]: self.forward(data[0]) elif command in ["backward", "backwards", "back", "b", "bck"]: self.backward(data[0]) elif command in ["left", "l", "lft"]: self.turn(-data[0]) elif command in ["right", "r", "turn", "rgt", "trn"]: self.turn(data[0]) elif command in ["move", "goto", "mv", "mov"]: self.set_position(data) elif command in ["reset", "origin", "centre", "cnt"]: self.set_position([0, 0]) elif command in ["circle", "crc"]: self.circle(data) elif command in ["stamp", "print", "prt", "smp"]: self.stamp() elif command in ["undo", "und"]: if data is None: self.undo(1) else: self.undo(data[0]) elif command in ["face", "setheading", "fac"]: self.face(data[0]) elif command in ["loop", "startloop", "lop"]: if data[1] in self.loop_counters: pass else: self.loop_counters[data[1]] = [data[0], self.pc] elif command in ["endloop", "end"]: loop_name = data[0] loop_data = self.loop_counters[loop_name] if loop_data[0] &gt; 1: self.pc = loop_data[1] self.loop_counters[loop_name][0] -= 1 else: del self.loop_counters[loop_name] elif command in ["colour", "color", "setcolour", "clr"]: self.colour(data) elif command in ["penup", "up"]: self.penup() elif command in ["pendown"]: self.pendown() elif command in ["pen"]: self.switchpen() else: print(f"{self.name} doesn't know how to do {command}") def forward(self, data): """Go forwards a certain amount.""" self.mrTurtle.forward(data) def backward(self, data): """Go backwards""" self.mrTurtle.backward(data) def turn(self, data): """Turn clockwise specified amount in degrees. Commands 'left' and 'right' both map to this function. Commands for 'left' are made negative.""" self.mrTurtle.right(data) def face(self, data): """Face a certain heading.""" self.mrTurtle.setheading(data) def set_position(self, data): """Move turtle to coordinates""" x = data[0] y = data[1] self.mrTurtle.setposition(x, y) def circle(self, data): """Draw a circle with the built in turtle circle function.""" radius = data[0] extent = None steps = None if len(data) == 2: extent = data[1] if len(data) == 3: extent = data[1] steps = data[2] self.mrTurtle.circle(radius, extent, steps) def colour(self, data): """Modify turtle colour.""" if len(data) == 1: data = data[0] elif len(data) == 3: data = (data[0], data[1], data[2]) else: return None self.mrTurtle.colour(data) def penup(self): """Pen up.""" self.mrTurtle.penup() def pendown(self): """Pen down.""" self.mrTurtle.pendown() def switchpen(self): """Flip pen state.""" if self.mrTurtle.isdown(): self.mrTurtle.penup() else: self.mrTurtle.pendown() def stamp(self): """Stamp a copy of turtle.""" self.mrTurtle.stamp() def undo(self, num): """Undo specified number of commands""" for i in range(num): self.mrTurtle.undo() def set_speed(self, speed): """Set the movement speed of turtle.""" self.mrTurtle.speed(speed) def set_name(self, name): """Set the turtle name""" self.name = name def done(self): """Forces window to stay open after completion. Function for runturtle.py. No more commands can be executed after this one.""" turtle.done() def convert(input): """ Converts a string to an int or float. Converts a list of strings into a list of strings, ints or floats. Args: input (str, list[str]): string or list of strings to attempt to convert. Returns: (str, int, float, list[...]): Depending on data contained in input. """ if isinstance(input, str): input = [input] converted = [] for item in input: try: if "." in item: converted.append(float(item)) else: converted.append(int(item)) except ValueError: converted.append(item) if len(converted) == 1: converted = converted[0] return converted </code></pre> <p>Here is what an example of a command file looks like:</p> <pre><code>name Loopy loop 10 top ;loops MUST be named at both the top and the bottom of the loop forwards 40 loop 4 square ;loop syntax is "loop [number of iterations] [loop name]" left 90 forwards 10 endloop square left 36 endloop top </code></pre> <p>My code is contained in <a href="https://github.com/ReaM66/TurtleController" rel="nofollow noreferrer">this GitHub repo</a> if you want to download and run it. It comes with a second script that can be run from the command line. There are also example files for the turtle that show some of the exciting ways it can be used.</p> <p>I know a fat elif isn't the best way to go here, as this will be a nightmare to extend and maintain. What are some better options for how to implement this?</p> <p>I also want to extend this, so it is more of a complete language. I want to implement while loops, some form of memory (likely just storing integers), and selection. What would be the right way of doing this? </p> <p>If you think of any other features, additions or changes, I would like to hear those too :)</p>
[]
[ { "body": "<p>Classes (and functions) should ideally do one thing and do it well. The Python Zen also stipulates \"There should be one-- and preferably only one --obvious way to do it.\"</p>\n\n<p>Your class goes against this principle in two ways:</p>\n\n<ul>\n<li>You have many different ways to actually execute the commands. There is <code>Run</code>, <code>Step</code> and <code>StepThrough</code>.</li>\n<li>You have multiple keywords for the same command. Note how e.g. Python has only <code>if</code>, not also <code>when</code>, <code>case</code>, or a second syntax like <code>if ... fi</code>.</li>\n</ul>\n\n<p>Your loop structure is also a bit weird. Files like this should raise a <code>SyntaxError</code> (or your equivalent), not be silently ignored:</p>\n\n<pre><code>name ThisShouldCrashAndBurn\nloop 10 one\nloop 10 two\nforwards 1\nendloop one\nbackwards 1\nendloop two\n</code></pre>\n\n<p>I also have no idea what your code outputs for this, or should output. It will depend entirely on the implementation how this is handled.</p>\n\n<p>Instead, just keep a stack of loop counters around. You always increment the last counter and <code>pop</code> it from the loop counters if a loop ends. This way you always end the innermost loop.</p>\n\n<p>Here is a slightly simplified version, which removes duplicate keywords and uses the simplified loopcounter. It also gives the user a bit of the control back (by not providing e.g. a method to add a command).</p>\n\n<p>I also removed the other run methods. Now the <code>run</code> method <code>yield</code>s after each step, so it is the user's responsibility to loop. I did add a convenience method that does not pause.</p>\n\n<p>The whole thing directly inherits from <code>turtle.Turtle</code>, and uses the method names as keywords, where applicable. This eliminates all the trivial commands. It has a whitelist of all commands to block access to other turtle commands, although you might want to remove that to allow access to all of them directly.</p>\n\n<pre><code>import turtle\n\nclass Turtle(turtle.Turtle):\n keywords = {\"forward\", \"backward\", \"left\", \"right\", \"setposition\",\n \"reset\", \"circle\", \"colour\", \"penup\", \"pendown\",\n \"switchpen\", \"undo\", \"name\", \"done\", \"speed\", \"name\",\n \"loop\", \"endloop\"}\n\n def __init__(self, commands, speed=6):\n \"\"\"Initialise turtle with a speed.\"\"\"\n super().__init__()\n self.speed(speed)\n self.name(\"terry\")\n self.pointer = 0\n self.loops = []\n self.commands = commands\n\n @classmethod\n def from_file(cls, file_name, speed=6):\n with open(file_name) as f:\n commands = [line[:line.find(\";\")].strip().lower()\n for line in f]\n return cls(commands, speed)\n\n def run(self):\n \"\"\"Run commands in buffer, pausing after each step\"\"\"\n print(f\"{self._name} is ready to go!\")\n # need a while loop here because the pointer might be moved by the command\n self.pointer = 0\n while self.pointer &lt; len(self.commands):\n self.run_command(self.commands[self.pointer])\n yield self.pointer\n self.pointer += 1\n print(f\"{self._name} is finished!\")\n\n def run_all(self):\n \"\"\"Run all commands.\"\"\"\n for _ in self.run():\n pass\n\n def run_command(self, command):\n \"\"\"Send 1 command to turtle. Big switch case handles command.\"\"\"\n print(f\"{self._name} is trying {command}\")\n try:\n command, *data = command.split(\" \")\n data = list(map(convert, data))\n except:\n print(f\"Error: {self._name} could not perform command {command}\")\n return None\n if command in self.keywords:\n getattr(self, command)(*data)\n else:\n print(f\"{self._name} doesn't know how to do {command}\")\n\n def loop(self, iterations):\n self.loops.append([iterations, self.pointer])\n\n def endloop(self):\n try:\n n, start = self.loops[-1]\n except IndexError:\n print(\"No loop to end\")\n return\n if n == 1:\n self.loops.pop()\n else:\n self.loops[-1][0] -= 1\n self.pointer = start\n\n def reset(self):\n self.setposition(0, 0)\n\n def circle(self, radius, extent=None, steps=None):\n \"\"\"Draw a circle with the built in turtle circle function.\"\"\"\n super().circle(radius, extent, steps)\n\n def switchpen(self):\n \"\"\"Flip pen state.\"\"\"\n if self.isdown():\n self.penup()\n else:\n self.pendown()\n\n def undo(self, num=1):\n \"\"\"Undo specified number of commands\"\"\"\n for _ in range(num):\n super().undo()\n\n def name(self, name):\n \"\"\"Set the turtle name\"\"\"\n self._name = name\n\n def done(self):\n \"\"\"Forces window to stay open after completion. Function for runturtle.py. No\n more commands can be executed after this one.\"\"\"\n turtle.done()\n\n\ndef convert(input):\n \"\"\"\n Converts a string to an int or float.\n Converts a list of strings into a list of strings, ints or floats.\n Args:\n input (str, list[str]): string or list of strings to attempt to convert.\n Returns:\n (str, int, float, list[...]): Depending on data contained in input.\n \"\"\"\n if isinstance(input, str):\n input = [input]\n converted = []\n for item in input:\n try:\n if \".\" in item:\n converted.append(float(item))\n else:\n converted.append(int(item))\n except ValueError:\n converted.append(item)\n if len(converted) == 1:\n converted = converted[0]\n return converted\n\nif __name__ == \"__main__\":\n import sys\n t = Turtle.from_file(sys.argv[1])\n t.run_all()\n</code></pre>\n\n<p>Note that if <code>data</code> is the empty list (which is allowed by the extended tuple unpacking), the splatting using <code>*</code> will not interfere and allow even methods without arguments being run. I.e. the following works:</p>\n\n<pre><code>def f():\n pass\n\nf(*[])\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-18T16:34:47.330", "Id": "454254", "Score": "1", "body": "Ahhh I see that. I really like having a loop stack instead of named loops. Makes it much simpler, and you were right the program simply kills itself if you put a loop in like that currently. Can't believe I forgot about getattr! That makes it a LOT better. Thankyou" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-18T16:20:14.413", "Id": "232598", "ParentId": "232587", "Score": "2" } } ]
{ "AcceptedAnswerId": "232598", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-18T12:20:56.640", "Id": "232587", "Score": "5", "Tags": [ "python", "turtle-graphics" ], "Title": "Turtle controller with simple instruction set" }
232587
<p>I'm trying to create a timeout for a blocking operation, a <code>InputStream.read()</code> in the specific case, using a timeout thread <strong>without</strong> synchronization.</p> <p>This is needed to avoid that a blocking operation will last forever and <strong>its aim is to achieve the best performance</strong>.</p> <p>This should be a typical use case:</p> <pre><code>try(InputStream input = request.getInputStream()) { Utils.consumeWithTimeout(input, 60000, (buffer, n) -&gt; { output.write(buffer, 0, n); checksum.update(buffer, 0, n); }); } </code></pre> <p>where</p> <pre><code>public static void consumeWithTimeout(InputStream in, long timeout, BiConsumer&lt;byte[], Integer&gt; consumer) throws IOException { byte[] buf = new byte[DEFAULT_BUFFER_SIZE]; try(TimedOp timedOp = new TimedOp(timeout, () -&gt; closeQuietly(in))) { while(true) { timedOp.start(); int n = in.read(buf); timedOp.pause(); if(n &lt;= 0) { return; } consumer.accept(buf, n); } } finally { closeQuietly(in); } } </code></pre> <p>and</p> <pre><code>public static class TimedOp implements AutoCloseable { private Thread th; private volatile long last = 0; private volatile boolean paused = true; public TimedOp(long timeout, Runnable runnable) { th = new Thread(() -&gt; { try { while(!th.isInterrupted()) { long now = System.currentTimeMillis(); if(last + timeout &gt; now) { Thread.sleep(last + timeout - now); } else if(paused) { Thread.sleep(timeout); } else { runnable.run(); return; } } } catch(InterruptedException e) { return; } }); } public void start() { State state = th.getState(); if(state == State.TERMINATED) { throw new IllegalStateException(&quot;thread is terminated&quot;); } if(!paused) { throw new IllegalStateException(&quot;already running&quot;); } last = System.currentTimeMillis(); paused = false; if(state == State.NEW) { th.start(); } } public void pause() { paused = true; } @Override public void close() { th.interrupt(); try { th.join(); } catch(InterruptedException e) { throw new RuntimeException(e); } } } </code></pre> <p>do you see a problem or space for improvement?</p> <hr /> <h2>update</h2> <p>Suppose you need to care about 1GB data transfer, with a 8KB buffer.</p> <br> <p><strong>can I use an <code>ExecutorService</code> for scheduling the <code>read()</code>?</strong></p> <p>No, I can't.</p> <pre><code>public static void consumeWithExecutor(InputStream in, long timeout, BiConsumer&lt;byte[], Integer&gt; consumer) throws IOException { byte[] buf = new byte[DEFAULT_BUFFER_SIZE]; ExecutorService executor = Executors.newSingleThreadExecutor(); try { while(true) { Future&lt;Integer&gt; future = executor.submit(() -&gt; in.read(buf)); int n = future.get(timeout, TimeUnit.MILLISECONDS); if(n &lt;= 0) { return; } consumer.accept(buf, n); } } catch(InterruptedException | ExecutionException | TimeoutException e) { // do nothing, handling in finally block } finally { closeQuietly(in); executor.shutdownNow(); } } </code></pre> <p>the overhead of spawning/reusing/restarting a thread for each single read is overkill.</p> <p>Performance loss is unbearable.</p> <br> <p><strong>can I use a <code>Timer</code> for scheduling the <code>read()</code>?</strong></p> <p>No, I shouldn't.</p> <pre><code>public static void consumeWithTimer(InputStream in, long timeout, BiConsumer&lt;byte[], Integer&gt; consumer) throws IOException { byte[] buf = new byte[DEFAULT_BUFFER_SIZE]; try { while(true) { Timer timer = new Timer(); TimerTask task = new TimerTask() { @Override public void run() { closeQuietly(in); } }; timer.schedule(task, timeout); int n = in.read(buf); timer.cancel(); if(n &lt;= 0) { return; } consumer.accept(buf, n); } } finally { closeQuietly(in); } } </code></pre> <p><code>Timer</code> and <code>TimerTask</code> are not reusable, a new instance should be created for each iteration.</p> <p>Internally, <code>Timer</code> synchronizes on a <code>queue</code> of tasks, leading to unnecessary locking.</p> <p>This result in a performance loss, a little thinner than using an <code>ExecutorService</code>, nevertheless it's not as efficient as my original implementation.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-18T18:42:39.170", "Id": "454271", "Score": "1", "body": "You could put your code in an `ExecutorService`, then call `shutdownNow()` when the time out occurs. Use a regular `java.util.Timer` for the time out. Better than reinventing the wheel." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-19T10:42:16.843", "Id": "454326", "Score": "0", "body": "Too much overhead, it's not acceptable when you have to transfer data. Please see update." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-19T13:40:13.160", "Id": "454354", "Score": "0", "body": "I think you need to explain what it is you are actually trying to do. Your explanations sound like an XY Problem to me. There are ways of efficiently transferring data but the code you have written is not it. Please tell us what your real goal is. This question might be better suited to StackOverflow since you seem to have difficulty defining and approaching the problem." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-19T15:49:08.703", "Id": "454387", "Score": "0", "body": "It is a teorethical code review and I think it is crystal clear: *Efficient Timeout for a blocking operation without synchronization* and *do you see a problem or space for improvement?*; also, with all the code, it cannot possibly be more clear. Anyway, you say that this code is not efficient in transferring data: can you show an example of an efficient way? Thanks" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-19T16:02:39.047", "Id": "454392", "Score": "0", "body": "Your code is not crystal clear, in fact it's a mess. For example, what is the variable `output` and what are you doing with it? It matters if it's a file or a socket or something else. You get your variable `input` from another object `request` which makes it look like you're using a web framework, yet you haven't mentioned anything about web frameworks or which one you use. Most frameworks have an uploader for large transfers built-in, so it would matter if you're using one. Your code is basically too awful to review. You need to get a book on basic Java..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-19T16:04:26.700", "Id": "454393", "Score": "0", "body": "... like O'Reily's *Learning Java* and review basic (and some advanced) use of the API. Also review the docs for your frameworks, I'm sure you've missed some important concepts there as well." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-19T16:33:14.490", "Id": "454402", "Score": "0", "body": "Please, quote/write an *example code*. Mention of the entire book doesn't seem to be enough." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-19T17:24:46.120", "Id": "454408", "Score": "0", "body": "The problem is that **your specific requirements** are not clear. Can you please clarify some of the questions that I've asked? What is `request` and where does it come from? What are you transferring (files, socket, other?)? What frameworks / libraries are you using? The partial code snippet you have shown is not enough. Please show more of the code." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-18T13:23:07.430", "Id": "232590", "Score": "0", "Tags": [ "java", "io", "thread-safety" ], "Title": "Efficient Timeout for a blocking operation without synchronization" }
232590
<p>My goal is to implement a function that accepts a <code>Follower</code> object that will be used to report progress through a complex function (a depth-first traversal of a graph). Here's my attempt:</p> <pre class="lang-rust prettyprint-override"><code>pub trait Follower&lt;'a, N&gt; { fn root(&amp;mut self, node: &amp;'a N); } pub fn depth_first&lt;'a, N&gt;( node: &amp;'a N, follower: &amp;mut dyn Follower&lt;'a, N&gt; ) { follower.root(node); // TODO } #[cfg(test)] mod tests { use super::*; use std::fmt::Display; struct DebugFollower&lt;'a, N&gt; { nodes: Vec&lt;&amp;'a N&gt; } impl&lt;'a, N: Display&gt; DebugFollower&lt;'a, N&gt; { fn new () -&gt; Self { DebugFollower { nodes: vec![ ] } } fn to_string(&amp;self) -&gt; String { self.nodes.iter().map(ToString::to_string).collect() } } impl&lt;'a, N&gt; Follower&lt;'a, N&gt; for DebugFollower&lt;'a, N&gt; { fn root(&amp;mut self, item: &amp;'a N) { self.nodes.push(item); } } #[test] fn walks_p1() { let mut follower = DebugFollower::new(); depth_first(&amp;0, &amp;mut follower); assert_eq!(follower.to_string(), "0"); } } </code></pre> <p>The code compiles and performs as expected. However, I suspect that, in trying to silence the many compile errors I encountered, I may have added unnecessary lifetime parameters. Previous experience has shown me that it's very easy to get into a situation wherein so many useless parameters have been added that removing them one at a time isn't possible. Still, I have tried to do that and can't find any lifetime parameters that can be removed.</p> <p>In particular, I'm suspicious of the lifetime parameter on <code>Follower</code>, which appears to leak implementation details from <code>DebugFollower</code>. For example, removing the <code>nodes</code> property from <code>DebugFollower</code>, and updating the rest of the code, <code>Follower</code> no longer needs a lifetime parameter. </p> <p>Does this example follow idiomatic Rust use of lifetime parameters? If not, how can I improve the use of lifetime parameters here?</p>
[]
[ { "body": "<p>You can get rid of the lifetimes completely, just replace every instance of:</p>\n\n<pre><code>&amp;'a N\n</code></pre>\n\n<p>with just:</p>\n\n<pre><code>N\n</code></pre>\n\n<p><a href=\"https://play.rust-lang.org/?version=stable&amp;mode=debug&amp;edition=2018&amp;gist=48c01c536c25205dfeaef4c63a68fea6\" rel=\"nofollow noreferrer\">See Playground</a></p>\n\n<p>But why? Well, in your current code N is inferred to be i32. However, with my suggested changes N will be inferred to be &amp;'a i32. If you allow Rust to infer the reference it will also infer the correct lifetime for you.</p>\n\n<p>But does this, as you ask, leak implementation details of <code>DebugFollower</code>? Not from a Rust perspective. In Rust, ownership details are very much part of the interface and not just an implementation detail. The key issue is that the <code>Follower</code> trait has to specify how long the references will be valid so that <code>DebugFollower</code> knows how long it is allowed to store those references.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-20T06:28:53.430", "Id": "232683", "ParentId": "232594", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-18T14:49:29.283", "Id": "232594", "Score": "2", "Tags": [ "rust" ], "Title": "Reporting progress using a Follower" }
232594
<p>I have requirement to check list of environment variable in Linux. Based on environment variable, exit code will be different. how to optimize the below code?</p> <pre><code>def check_mandatory_envs(): if "ENVCONTEST_1" not in os.environ: exit(125) if "ENVCONTEST_2" not in os.environ: exit(126) if "ENVVIRTEST_3" not in os.environ exit(127) if "ENVVIRTEST_4" not in os.environ exit(128) if "ENVPATHTEST_5" not in os.environ exit(129) if "ENVPATHTEST_6" not in os.environ exit(130) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-18T15:22:30.220", "Id": "454246", "Score": "0", "body": "Where does `exit(...)` come from? Are you using something like `from sys import exit` at the beginning of your script?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-18T15:35:04.747", "Id": "454248", "Score": "0", "body": "@AlexV `exit` is a builtin as far as I know." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-18T15:38:51.837", "Id": "454249", "Score": "3", "body": "@JAD It is, but there are [noticeable differences](https://stackoverflow.com/a/6501134/5682996) between calling `exit`, `sys.exit`, and `os.exit`." } ]
[ { "body": "<p>You can group the messages and corresponding exit codes into a dict, and then iterate over that one:</p>\n\n<pre><code>def check_mandatory_envs():\n exit_codes = {\n \"ENVCONTEST_1\" :125,\n \"ENVCONTEST_2\" :126,\n \"ENVVIRTEST_3\" :127,\n \"ENVVIRTEST_4\" :128,\n \"ENVPATHTEST_5\":129,\n \"ENVPATHTEST_6\":130,\n }\n for variable, code in exit_codes.items():\n if variable not in os.environ:\n exit(code)\n</code></pre>\n\n<p>If the order of the iteration is important and you are on python before 3.6, you canuse a <code>collections.OrderedDict</code> or a list of tuples, without the <code>.items()</code> call</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-18T15:42:15.090", "Id": "454250", "Score": "0", "body": "Is there an advantage of using a dictionary here compared to, say, a tuple of tuples or something similar?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-18T15:46:50.417", "Id": "454252", "Score": "1", "body": "Not really, there is no real downside either as far as I know. This also conveys that a certain variable has one exit code, and it throws a `SyntaxError` at compile time if you forgot an exit code or a comma, making input errors easier to find." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-18T15:40:07.357", "Id": "232596", "ParentId": "232595", "Score": "4" } } ]
{ "AcceptedAnswerId": "232596", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-18T15:12:08.837", "Id": "232595", "Score": "1", "Tags": [ "python" ], "Title": "How to check list of environment variable in python?" }
232595
<p>This is the first time for me to ask a question in this site. Recently, I was learning python 3.x and I got a question...</p> <p>Which is faster ?</p> <pre class="lang-py prettyprint-override"><code>if n==0 or n==1: </code></pre> <p>or</p> <pre class="lang-py prettyprint-override"><code>if n*(n-1)==0: </code></pre> <p>Similarly, for a,b,c,d are numbers, which is faster?</p> <pre class="lang-py prettyprint-override"><code>if n==a or n==b or n==c or n==d: </code></pre> <p>or</p> <pre class="lang-py prettyprint-override"><code>if (n-a)*(n-b)*(n-c)*(n-d)==0: </code></pre> <p>I have been confused of this question for some time. I asked my friend but they didn't know too. Answer is appreciated. Thank you!</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-18T17:41:34.303", "Id": "454263", "Score": "0", "body": "What did your benchmark tests say?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-18T17:55:48.227", "Id": "454264", "Score": "0", "body": "There is no benchmark tests actually, I thought of myself" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-18T17:56:40.387", "Id": "454265", "Score": "1", "body": "You can easily write them yourself." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-18T17:57:39.287", "Id": "454266", "Score": "0", "body": "How to write then?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-18T17:59:05.080", "Id": "454267", "Score": "0", "body": "See the answer you got. But generally your question seems to be _off-topic_ here for various reasons." } ]
[ { "body": "<p>Python's <a href=\"https://docs.python.org/2/library/timeit.html\" rel=\"nofollow noreferrer\">timeit</a> module can help you to measure the speed of the statements:</p>\n\n<pre><code>&gt;&gt;&gt; import timeit\n&gt;&gt;&gt; timeit.timeit('n == 0 or n == 1', 'n = 42')\n0.045291900634765625\n&gt;&gt;&gt; timeit.timeit('n * (n-1) == 0', 'n = 42')\n0.0594179630279541\n</code></pre>\n\n<p>The first one is faster on <code>python 2.7.15</code>, but what is much more important is that it is less obscure and more maintainable.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-18T18:49:26.843", "Id": "454272", "Score": "1", "body": "Please refrain from answering off topic questions" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-18T17:42:11.867", "Id": "232602", "ParentId": "232601", "Score": "2" } }, { "body": "<p>Besides of searching <em>\"what is faster\"</em> always consider code readability and maintainability.</p>\n\n<p>Due to <strong><code>or</code></strong> operator nature, most of sub-checks could be just skipped on \"earlier\" match, whereas with the 2nd approach <code>(n-a)*(n-b)*(n-c)*(n-d)==0</code> whatever <strong><code>n</code></strong> value would be - the long sequence of arithmetic operations <code>(n-a)*(n-b)*(n-c)*(n-d)</code> will inevitably be performed, which obviously makes the 2nd approach less efficient. Moreover it looks more confusing in case of simple comparisons.</p>\n\n<p>As for time performance, consider the following tests:</p>\n\n<pre><code>In [121]: a,b,c,d = range(1,5) \n\nIn [122]: n=4 \n\nIn [123]: %timeit n==a or n==b or n==c or n==d \n176 ns ± 8.52 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)\n\nIn [124]: %timeit (n-a)*(n-b)*(n-c)*(n-d)==0 \n213 ns ± 6.86 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)\n\nIn [125]: n=2 \n\nIn [126]: %timeit n==a or n==b or n==c or n==d \n108 ns ± 1.9 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)\n\nIn [127]: %timeit (n-a)*(n-b)*(n-c)*(n-d)==0 \n241 ns ± 10.4 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-18T17:58:23.810", "Id": "232604", "ParentId": "232601", "Score": "1" } } ]
{ "AcceptedAnswerId": "232604", "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-18T17:22:32.243", "Id": "232601", "Score": "-3", "Tags": [ "python", "python-3.x" ], "Title": "Which is faster, (n==0 or n==1) or (n*(n-1)==0)" }
232601
<p>I'm trying to build an iterator (enumerator) that can select specific elements in an <code>Expression</code> tree by traversing the tree and deferring further iteration until needed. </p> <p>My following implementation intends to keep it simple by leveraging the <code>ExpressionVisitor</code>. But since a visitor-pattern uses recursive stack calls to keep its place, I am using a <code>Task</code> thread in a synchronous manner to store the position of the <code>IEnumerator</code> between calls to <code>MoveNext</code>.</p> <pre><code>/// &lt;summary&gt; /// Iterates through an expression tree collecting only expression elements that match the predicate. /// &lt;/summary&gt; internal sealed class ExpressionCollector : IEnumerable&lt;Expression&gt; { private ExpressionCollector(Expression root, Func&lt;Expression, bool&gt; predicate) { this.Root = root; this.Predicate = predicate; } private Expression Root { get; } private Func&lt;Expression, bool&gt; Predicate { get; } public static IEnumerable&lt;Expression&gt; Collect(Expression root, Func&lt;Expression, bool&gt; predicate) =&gt; new ExpressionCollector(root, predicate); public IEnumerator&lt;Expression&gt; GetEnumerator() =&gt; new Iterator(this); IEnumerator IEnumerable.GetEnumerator() =&gt; this.GetEnumerator(); private class Iterator : ExpressionVisitor, IEnumerator&lt;Expression&gt; { private Task itr; private CancellationTokenSource cancel; private TaskCompletionSource&lt;Expression&gt; found; private TaskCompletionSource&lt;bool&gt; isReady; public Iterator(ExpressionCollector owner) { this.Owner = owner; } public ExpressionCollector Owner { get; } public Expression Current { get; private set; } object IEnumerator.Current =&gt; this.Current; public void Dispose() =&gt; this.Reset(); public bool MoveNext() { if (this.found is null || this.found.Task.IsCompleted) this.found = new TaskCompletionSource&lt;Expression&gt;(); if (this.itr is null) this.itr = Task.Run(Iterate, (cancel = new CancellationTokenSource()).Token); this.isReady?.SetResult(true); switch (Task.WaitAny(itr, found.Task)) { case 0: this.Current = null; this.found = null; return false; case 1: this.Current = found.Task.Result; this.found = null; return true; default: throw new NotSupportedException(); } } public void Reset() { if (this.itr != null) { this.cancel.Cancel(); this.itr.Wait(); this.itr.Dispose(); this.itr = null; this.cancel.Dispose(); this.cancel = null; this.Current = null; } } private void Iterate() =&gt; this.Visit(this.Owner.Root); public override Expression Visit(Expression node) { if (cancel.IsCancellationRequested) cancel.Token.ThrowIfCancellationRequested(); if (this.Owner.Predicate(node)) { this.isReady = new TaskCompletionSource&lt;bool&gt;(); this.found.SetResult(node); this.isReady.Task.Wait(); } return base.Visit(node); } } } </code></pre> <p>My concern stems from whether or not I am using the <code>Task</code> properly. Any thoughts?</p>
[]
[ { "body": "<p>Just some thoughts:</p>\n\n<ol>\n<li>Not sure why you don't just flatten the expression tree with a visitor and then return the collection of expressions. This leads to simpler code:</li>\n</ol>\n\n<pre><code>class Program\n{\n static void Main(string[] args)\n {\n Expression&lt;Func&lt;int, int, int&gt;&gt; expr = (a, b) =&gt; ((a + b) * (a - b));\n\n //Flatten the entire tree.\n foreach (var elem in expr.Flatten())\n {\n Console.WriteLine(elem.NodeType);\n }\n\n //Use Linq to select what you want.\n foreach (var elem in expr.Flatten().Where(t =&gt; t.NodeType == ExpressionType.Parameter))\n {\n Console.WriteLine(elem.NodeType);\n }\n Console.ReadKey();\n }\n}\n\npublic static class ExpressionExtensions\n{\n public static IEnumerable&lt;Expression&gt; Flatten(this Expression expr)\n {\n return Visitor.Flatten(expr);\n }\n}\n\npublic sealed class Visitor : ExpressionVisitor\n{\n private readonly Action&lt;Expression&gt; nodeAction;\n\n private Visitor(Action&lt;Expression&gt; nodeAction)\n {\n this.nodeAction = nodeAction;\n }\n\n public override Expression Visit(Expression node)\n {\n nodeAction(node);\n return base.Visit(node);\n }\n\n public static IEnumerable&lt;Expression&gt; Flatten(Expression expr)\n {\n var ret = new List&lt;Expression&gt;();\n var visitor = new Visitor(t =&gt; ret.Add(t));\n visitor.Visit(expr);\n return ret;\n }\n}\n</code></pre>\n\n<ol start=\"2\">\n<li>Even if, for some reason, you absolutely <strong>need</strong> to have lazy execution, you're better off making your own expression iterator, rather than trying to pause the execution of a class meant to eagerly visit everything.</li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-20T15:46:51.090", "Id": "454531", "Score": "0", "body": "It is important to me that the operation be lazy, as I intend to work with some fairly large expressions and would like to take advantage of time-saving functions like `Enumerable.Any`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-20T16:11:49.730", "Id": "454533", "Score": "0", "body": "I've also tried route #2 and found that there was no easy way to store a simple stack of `Expression`s along with a detailed value of the process index of that `Expression`'s children which is necessary to continue when moving back up the stack. Because each `Expression` differs so much, the storage would require the whole set of children to be added to the stack, which requires almost as much storage as your Flatten example. Only to add the characteristic of being lazy. Whereas my `Task` example uses the storage method already present in each `Expression` as it enumerates." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-21T16:39:59.723", "Id": "454648", "Score": "0", "body": "In that case, put your code in the visitor." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-20T11:31:07.067", "Id": "232697", "ParentId": "232603", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-18T17:48:47.760", "Id": "232603", "Score": "3", "Tags": [ "c#", "thread-safety", "iterator", "task-parallel-library", "visitor-pattern" ], "Title": "Iterate through Expression Tree" }
232603
<p>Here I created a typed version of <a href="https://lodash.com/docs/4.17.15#flow" rel="nofollow noreferrer">lodash <code>flow</code></a> that offers more specific typing.</p> <p>I'm curious if this exists in any other library, which optimized in tying any way — offering mainly it up to the world as a better version of <code>flow</code>.</p> <ol> <li>The return value is set to the return in the last passed function</li> <li>The input value is set to the input of the first given function</li> <li>In between functions are checking the return types from the proceeding function match the inputs of the next.</li> </ol> <p>Here's the code:</p> <pre><code>import * as _ from 'lodash'; namespace Compose { export type ReadFuncs = readonly ((x: any) =&gt; any)[] export type Tail&lt;T extends ReadFuncs&gt; = ((...a: T) =&gt; void) extends ((h: any, ...r: infer R) =&gt; void) ? R : never; export type Func = (...any) =&gt; any export type Funcs = Func[] export type LengthOfTuple&lt;T extends any[]&gt; = T extends { length: infer L } ? L : never; export type LastInTuple&lt;T extends ReadFuncs&gt; = T[LengthOfTuple&lt;Tail&lt;T&gt;&gt;]; export type LastFnReturns&lt;Fns extends ReadFuncs&gt; = ReturnType&lt;LastInTuple&lt;Fns&gt;&gt; export type FirstFnParam&lt;Fns extends ReadFuncs&gt; = Parameters&lt;Fns[0]&gt; export type CheckFns&lt;T extends readonly ((x: any) =&gt; any)[]&gt; = { [K in keyof T]: K extends keyof Tail&lt;T&gt; ? ( [T[K], Tail&lt;T&gt;[K]] extends [(x: infer A) =&gt; infer R, (x: infer S) =&gt; any] ? ( [R] extends [S] ? T[K] : (x: A) =&gt; S ) : never ) : T[K] } } function compose&lt;T extends Compose.ReadFuncs, R extends Compose.LastFnReturns&lt;T&gt;&gt;(...t: Compose.CheckFns&lt;T&gt;) { return (...input: Compose.FirstFnParam&lt;T&gt;) =&gt; { return _.flow(t)(...input) as R } } const x = compose( (foo: string) =&gt; `wrapFoo1(${foo})`, (foo: string) =&gt; `wrapFoo2(${foo})`, (foo: string) =&gt; `wrapFoo3(${foo})`, (foo: string) =&gt; `wrapFoo4(${foo})`, (value: string): number =&gt; value.length, ) const velvet = x('meow') console.log(velvet) </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-18T18:27:04.917", "Id": "232606", "Score": "2", "Tags": [ "typescript", "lodash.js" ], "Title": "Property typed lodash compose function" }
232606
<p><strong>Question:</strong> A binary string is given with only 0's and 1's. A number <em>n</em> is also given as the length of a sub string to be considered. It is to find the number of unique substrings. Here, n=3.</p> <p><strong>My algorithm:</strong> The ways I followed: <em>(i)</em> First, I extracted out the sub string of length <em>3</em> and converted it into a number. <em>(ii)</em> Then, I stored the number in a new integer type array. In this way, I had an integer array full of numbers representing the substrings. <em>(iii)</em> Lastly, I traversed down the array, keeping track of the occurrence of the unique numbers only. The amount of unique numbers therefore correspond to the number of unique substring.</p> <pre><code>#include&lt;stdio.h&gt; #include &lt;string.h&gt; int main(void) { char arr[50]; int o[50],check[10000]; int i,j,count=1,l,k=0,sum,p; l=strlen(arr); for(i=0;i&lt;l-2;i++){ p=4;sum=0; for(j=0;j&lt;3;j++){ sum+=(arr[i+j]-'0')*p; p/=2; } o[k++]=sum; } memset(check,0,sizeof(check)); for(i=0;i&lt;k-1;i++){ for(j=i+1;j&lt;k;j++){ if(o[i]!=o[j] &amp;&amp; check[o[i]]!=1 &amp;&amp; check[o[j]]!=1){ count++; check[o[j]]=1; } } check[o[i]]=1; } printf("\n%d",count); return 0; } </code></pre> <p>I think that my code is quite long and it could be shortened with a good optimization. But I can't think of a way. </p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-18T19:35:43.983", "Id": "454276", "Score": "0", "body": "How big the string, how vast be n?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-19T11:19:40.517", "Id": "454331", "Score": "0", "body": "@chux I've edited the question..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-19T16:21:38.393", "Id": "454398", "Score": "0", "body": "@chux sorry for the discomfort...I've considered n=3 here...I've cleared the question..." } ]
[ { "body": "<p>Your code can be more efficient. For example, both nested for-loops can be replaced with single for-loops. In the first loop, the next <code>sum</code> can be calculated by left-shifting the previous sum, adding the new bit, and masking off n-bits. <code>count[sum]</code> is how many times an n-bit pattern == sum has been seen. So the second loop merely counts how many '1's are in <code>count</code>. Something like the code below (not tested).</p>\n\n<pre><code>int count_unique(char *arr, int n) {\n int mask = (1 &lt;&lt; n) - 1;\n\n /* the size needs to be 2**n. This works for n &lt;= 10 */\n int count[1024];\n memset(count, 0, sizeof(count));\n\n int sum = 0;\n\n for (int i = 0; arr[i]; i++) {\n sum = ((sum &lt;&lt; 1) | (arr[i] - '0')) &amp; mask;\n\n if (i &gt;= n - 1) {\n count[sum]++;\n }\n }\n\n int unique = 0;\n\n for (int i = 0; i &lt; sizeof(count)/sizeof(int); i++) {\n if (count[i] == 1) {\n unique++;\n }\n }\n\n return unique;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-19T23:45:57.177", "Id": "232670", "ParentId": "232607", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-18T18:30:17.770", "Id": "232607", "Score": "2", "Tags": [ "c", "strings" ], "Title": "Number of unique substrings of particular length of a binary string" }
232607
<p>I've made a small script to compile Go code with Python.</p> <p>The result is not something I'm happy with, because:</p> <ul> <li>It seems overly complicated</li> <li>I'm worried the nested if-else with f string are unreadable</li> <li>Am I using the <code>subprocess</code> module the correct way?</li> </ul> <p>Any review is welcome.</p> <pre><code>#!/usr/bin/env python3 import argparse import subprocess import os ARCHS = { "32": "386", "64": "amd64" } BUILDTYPES = ["exe", "dll"] def parse_arguments(): parser = argparse.ArgumentParser(usage='%(prog)s [options] &lt;buildtype&gt; &lt;architecture&gt;', description='Go builder', formatter_class=argparse.RawDescriptionHelpFormatter, epilog=''' Python program to build go payloads Examples: ./builder exe 32 --stripped ./builder dll 64 --upx --stripped ./builder dll 32 ''') parser.add_argument("buildtype", help="The type to build the paylopad with", type=str) parser.add_argument("architecture", help="The architecture to build the paylopad with", type=str, default="32") parser.add_argument("--stripped", "-s", help="Strip the payload of symbols", action="store_true", default=False) parser.add_argument("--upx", "-u", help="Pack the payload with upx", action="store_true", default=False) arguments = parser.parse_args() if not arguments.buildtype.lower() in BUILDTYPES: parser.error(f"{arguments.buildtype} is not a valid buildtype can only be {', '.join(BUILDTYPES)}") if not arguments.architecture.lower() in ARCHS: parser.error(f"{arguments.architecture} is not a valid architecture can only be {', '.join(ARCHS.keys())}") arguments.architecture = ARCHS[arguments.architecture] return arguments def build_go(**kwargs): enviroment = { **os.environ, "GOOS": "windows", "GOARCH": f"{kwargs['architecture']}" } if kwargs['buildtype'].lower() == "dll": enviroment["CGO_ENABLED"] = "1" enviroment["CC"] = f"{'i686' if kwargs['architecture'] == '386' else 'x86_64'}-w64-mingw32-gcc" build_type = f"go build -buildmode=c-shared" if kwargs["buildtype"].lower() == "dll" else "go build -tags exe" stripped = "-s -w" if kwargs['stripped'] else "" builder = f'''{build_type} -o GOLoader.{kwargs['buildtype']} -ldflags "-H=windowsgui {stripped}"''' subprocess.check_output(builder, shell=True, env=enviroment) if kwargs["stripped"]: stripped = f"strip GOLoader.{kwargs['buildtype']}" subprocess.check_output(stripped, shell=True) if kwargs["upx"]: upx = f"upx -f GOLoader.{kwargs['buildtype']} -9 --ultra-brute -o GOLoader.upx.{kwargs['buildtype']}" subprocess.check_output(upx, shell=True) if __name__ == '__main__': args = parse_arguments() build_go(**vars(args)) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-19T09:50:03.720", "Id": "454316", "Score": "0", "body": "I would write it using go, so it does not depend upon any runtime dependencies." } ]
[ { "body": "<p>Some minor notes.</p>\n\n<h3>I love the ternary operator and <code>f</code> strings, but...</h3>\n\n<p>Here are three ways to express the same thing. There is the original way, a DRY version of the original way, and a more traditional if/else. Which is easier to read and understand what is going on?</p>\n\n<pre><code># variant 1\nbuild_type = f\"go build -buildmode=c-shared\" if kwargs[\"buildtype\"].lower() == \"dll\" else \"go build -tags exe\"\n\n# variant 2\nbuild_type = f\"go build {'-buildmode=c-shared' if kwargs['buildtype'].lower() == 'dll' else '-tags exe'}\"\n\n# variant 3\nif kwargs[\"buildtype\"].lower() == \"dll\":\n build_type = \"go build -buildmode=c-shared\"\nelse:\n build_type = \"go build -tags exe\"\n</code></pre>\n\n<p>In this case I would argue that the third variant is <strong>MUCH</strong> easier to understand what the distinction is between the two build types. EG: What question is being asked (buildtype) and what is the difference in the result based on the answer.</p>\n\n<h3>Environment has a \"n\" after the \"o\"</h3>\n\n<p>This:</p>\n\n<pre><code>enviroment[\"CGO_ENABLED\"] = \"1\"\n</code></pre>\n\n<p>should likely be:</p>\n\n<pre><code>environment[\"CGO_ENABLED\"] = \"1\" \n</code></pre>\n\n<h3><a href=\"https://click.palletsprojects.com\" rel=\"nofollow noreferrer\">Click</a> is the thing.</h3>\n\n<p>Not sure this is immediately relevant as a code review, but...</p>\n\n<p>I much prefer <a href=\"https://click.palletsprojects.com\" rel=\"nofollow noreferrer\">click</a> to argparse. In this simple case there is not likely a huge advantage for Click, but there is little downside. And if you get comfortable with click and the size of your project increases, I think Click can be quite advantageous.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-19T06:20:12.967", "Id": "232626", "ParentId": "232609", "Score": "4" } } ]
{ "AcceptedAnswerId": "232626", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-18T19:04:49.700", "Id": "232609", "Score": "5", "Tags": [ "python", "python-3.x", "go" ], "Title": "Compiling Go with python" }
232609
<p>I'm trying to write a JavaScript BitTorrent client in Node.js to get more familiar with the language and ecosystem. I don't know how often people use classes in JavaScript since I feel like the overall approach is to try to hide the least state possible and embrace some of the functional programming styles with callbacks and so on. I'd like to know if this use of classes that I came up with is justified and what are other better design ideas.</p> <p>It is the code for my Tracker Client. It's responsible for taking to Trackers and get the list of peers that have a file. It's not accountable for downloading files.</p> <pre><code>class TrackerClient { constructor(torrent, trackerUrl, trackerPort) { this.torrent = torrent; this.trackerUrl = trackerUrl; this.trackerPort = trackerPort; this.clientName = '-VC0001-'; //vinny client version 0001 see: http://www.bittorrent.org/beps/bep_0020.html this.socket = null; this.transactionId = null; this.connectionId = null; this.peerId = null; } _buildConnectRequest() { // See: http://www.bittorrent.org/beps/bep_0015.html /* build buffer */ return buffer; } _buildAnnounceRequest() { // See: http://www.bittorrent.org/beps/bep_0015.html /* build buffer */ return buffer; } _initSocket() { this.socket = dgram.createSocket('udp4'); this.socket.on('error', (err) =&gt; { console.log(`socket error:\n${err.stack}`); this.socket.close(); }) //ok so this is very weird and i don't even know if you should do it this.socket.on('message', this._responseHandler.bind(this)); } _responseHandler(response) { console.log('response ', response); const type = response.readUInt32BE(0); if (type == 0x0) { // connect response const serverTransactionId = response.readUInt32BE(4); if (serverTransactionId != this.transactionId) { // throw exception??? console.log("server transaction id doesn't match with client's"); console.log('received ', serverTransactionId); console.log('got ', this.transactionId); } // save connection id for later this.connectionId = response.readBigUInt64BE(8); console.log('connection id ', this.connectionId); this._sendAnnounce(); } else if (type == 0x1) { // announce response const serverTransactionId = response.readUInt32BE(4); if (serverTransactionId != this.transactionId) { // throw exception??? console.log("server transaction id doesn't match with client's"); console.log('received ', serverTransactionId); console.log('got ', this.transactionId); } const interval = response.readUInt32BE(8); const leechers = response.readUInt32BE(12); const seeders = response.readUInt32BE(16); const peers = {}; console.log('number of peers ', leechers + seeders); // todo: we have to return this through getpeeers() for (let i = 20; i &lt; response.length; i += 6) { const ip_address = response.slice(i, i + 4).join('.'); const tcp_port = response.readUInt16BE(i + 4); peers[ip_address] = tcp_port; console.log('peer ip ', ip_address); console.log('peer port ', tcp_port); } } else { // Unknown } } // todo: merge send funcitons // We should probably fire a timeout after sending the messages to check later if we got a response _sendAnnounce() { const request = this._buildAnnounceRequest(); this.socket.send(request, this.trackerPort, this.trackerUrl); } _sendConnect() { const request = this._buildConnectRequest(); this.socket.send(request, this.trackerPort, this.trackerUrl); } getPeers() { if (this.socket === null) { this._initSocket(); this._sendConnect(); } // else return from the class attributes? } } </code></pre> <p>One of my concerns is in this line:</p> <pre><code>this.socket.on('message', this._responseHandler.bind(this)); </code></pre> <p>I'm binding it because I need to track the state of the connection because that's how the protocol is written. I have to check values from the responses that depend on values that happened in the past. But then, is passing state to a callback like that good design? Also, whenever I get the list of peers, how would I return it to the user? I'm on the response handler callback at that point.</p>
[]
[ { "body": "<p>A short review;</p>\n\n<ul>\n<li><p>Your implementation of <code>_buildConnectRequest</code> and <code>_buildAnnounceRequest</code> is missing, it would have been interesting to review that</p></li>\n<li><p>I am not a big fan of using underscores to denote private methods. If you run version 12 or later of Node, <a href=\"https://thecodebarbarian.com/nodejs-12-private-class-fields.html\" rel=\"nofollow noreferrer\">you can prefix with <code>#</code> to denote private functions</a>.</p></li>\n<li><p>Your code does not support <a href=\"http://www.bittorrent.org/beps/bep_0015.html#ipv6\" rel=\"nofollow noreferrer\">IPV6</a> at all. You will have to check the second parameter that <code>on.message</code> <a href=\"https://nodejs.org/api/dgram.html#dgram_event_message\" rel=\"nofollow noreferrer\">provides</a>.</p></li>\n<li><p>JsHint is almost perfect, you are missing a semicolon on line 33</p></li>\n<li><p>There seems to be no point to declare <code>this.socket = null;</code> You can just write in <code>getPeers()</code> then the following:</p>\n\n<pre><code>if (!this.socket) {\n this._initSocket();\n this._sendConnect();\n}\n</code></pre></li>\n<li><p>Don't call <code>console.log</code> directly, use an intermediary function that takes a severity (so that you can dial down the logging) and that routes logging to either <code>console.log</code> or a log file</p></li>\n<li><p>I think <code>this.socket.on('message', this._responseHandler.bind(this));</code> is fine since <code>this</code> is not set by <code>on.message</code>.</p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-19T16:25:46.897", "Id": "454400", "Score": "0", "body": "Thank you so much for the review! Yesterday I ended up doing a major refactor. Of course I hadn't seen your comment before doing it. I would be very interested in getting your opinion, could I edit the main post or maybe message you the commit url?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-19T16:29:06.897", "Id": "454401", "Score": "0", "body": "Definitely don't edit the main post, you can drop the commit URL here. I may ask you to build a new question after that." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-19T16:35:46.217", "Id": "454403", "Score": "0", "body": "Sounds good! [Here](https://github.com/vinnesc/bittorrent_client/commit/a1c49773c11a3ee564d00ae7fe31b9c3ac212c37) you have @konjin" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-20T11:01:36.053", "Id": "454497", "Score": "1", "body": "@calvines That code looks fine, I did not find any whoppers there." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-19T14:12:49.527", "Id": "232643", "ParentId": "232611", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-18T19:57:22.243", "Id": "232611", "Score": "5", "Tags": [ "javascript", "object-oriented", "node.js" ], "Title": "Writing a BitTorrent client in JavaScript" }
232611
<p>I would like to get a review of something, </p> <p>I have a function that creates an array of objects for a Drop-Down component (react-select).</p> <p>The function gets <code>data</code>, <code>valueKey</code>, <code>labelKey</code> and <code>otherInfo</code> from an object, and creates the array of objects based on the <code>valueKey</code> and the <code>labelKey</code>.</p> <pre><code>const createOptions = ({data, valueKey, labelKey, ...otherInfo}) =&gt; { return data.map(item =&gt; ({ value: item[valueKey], label: item[labelKey], ...appendOtherInfo(item, otherInfo) }) ); } </code></pre> <p>most of the time, <code>valueKey</code> and <code>labelKey</code> are enough, but there are some cases where there is additional info to add to each object, which is <code>otherInfo</code>, which is an object as well.</p> <p><code>appendOtherInfo()</code> function creates an object which is then appended to each object that <code>map</code> iteration returned.</p> <pre><code>const appendOtherInfo = (item, otherInfo) =&gt; { return Object.entries(otherInfo).reduce((total, [key, value]) =&gt; { total[key] = item[value]; return total; }, {}); } </code></pre> <p>for example, after calling <code>createOptions()</code> with the array: </p> <pre><code>const people = [ {id: '123', name: 'Dani', type: 'a', city: 'Rome'}, {id: '222', name: 'John', type: 'a', city: 'London'}, {id: '333', name: 'David', type: 'b', city: 'Madrid'} ] </code></pre> <p>and the rest of the info to create the new array,</p> <pre><code>createOptions({ data: people, valueKey: 'id', labelKey: 'name', type: 'type', capitalCity: 'city' }); </code></pre> <p>The result is: </p> <pre><code>[ { "value": "123", "label": "Dani", "type": "a", "capitalCity": "Rome" }, { "value": "222", "label": "John", "type": "a", "capitalCity": "London" }, { "value": "333", "label": "David", "type": "b", "capitalCity": "Madrid" } ] </code></pre> <p>In the <code>appendOtherInfo()</code> function, I used <code>Object.entries</code> and <code>reduce</code> to create the additional info for each object. It's working as expected, but I'd like to know if there is a better/easier way to achieve the same result.</p>
[]
[ { "body": "<p>Your solution is okay; although I'd make <code>appendOtherInfo()</code> a local function of <code>createOptions()</code>. <strong>But</strong> the problem is, in terms of <em>abstraction</em> - you build a function that you want to re-use and that gives you the <em>feeling</em> it is generic enough for all future use cases for your drop down. However, there are two problems - your <em>\"generic\"</em> function is just generic <em>enough</em> for <em>flat</em> objects and cannot easily handle nested objects.</p>\n\n<p>Furthermore because it's only argument is an object, different properties in it have different meanings - this is not good for code readability.</p>\n\n<p>So my advice is, why bother writing something that is seemingly generic, but actually not generic enough that it will ever see proper reuse.</p>\n\n<p>Instead simply use direct mappers; they are more readable and they give you the full flexibility, so instead of:</p>\n\n<pre><code>&lt;react-select options = { createOptions({\n data: people,\n valueKey: 'id',\n labelKey: 'name',\n type: 'type',\n capitalCity: 'city'\n})}&gt;/\n</code></pre>\n\n<p>Simply do:</p>\n\n<pre><code>&lt;react-select options = { people.map(peopl =&gt; {\n value: peopl.id,\n label: peopl.name,\n type: peopl.type\n capitalCity: peopl.city\n}\n}&gt;/\n</code></pre>\n\n<p><em>(I did not look up <code>&lt;react-select&gt;</code>'s API)</em>:\nDo not hide simple <em>extracting and remapping</em> behind functions if there is no need to - make code explicit and readable.</p>\n\n<p>You can happily use <em>destructuring</em> with <em>renaming</em> and <em>...</em>, if you only need to map label and value as well:</p>\n\n<pre><code>&lt;react-select options = { people.map(peopl =&gt; ({\n const {id: value, name: label, ...other} = peopl;\n return {value, name, ...other}})\n)}&gt;/\n</code></pre>\n\n<p>Or to be explicit and combining above:</p>\n\n<pre><code>&lt;react-select options = { people.map(peopl =&gt; ({\n const {id: value, name: label, type, city: capitalCity} = peopl;\n return {value, name, type, capitalCity}})\n)}&gt;/\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-29T22:50:10.860", "Id": "233178", "ParentId": "232612", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-18T20:00:50.577", "Id": "232612", "Score": "6", "Tags": [ "javascript" ], "Title": "Spread values to an object (Computed property names)" }
232612
<p>I have a binding model where at least one of two fields must be specified. I can't just set them both as <code>[Required]</code>. Here is what I came up with:</p> <pre><code>using System; using System.ComponentModel.DataAnnotations; namespace MyApp.Utils.DataAnnotations { [AttributeUsage(AttributeTargets.Class, AllowMultiple = true)] public class EitherRequiredAttribute : ValidationAttribute { private readonly string _field1; private readonly string _field2; public EitherRequiredAttribute(string field1, string field2) =&gt; (_field1, _field2) = (field1, field2); protected override ValidationResult IsValid(object value, ValidationContext validationContext) { var property1 = validationContext.ObjectType.GetProperty(_field1); if (property1 == null) return new ValidationResult(string.Format("Unknown property: {0}", _field1), new[] { _field1 }); var property2 = validationContext.ObjectType.GetProperty(_field2); if (property2 == null) return new ValidationResult(string.Format("Unknown property: {0}", _field2), new[] { _field2 }); var value1 = property1.GetValue(validationContext.ObjectInstance); if (value1 != null) return ValidationResult.Success; var value2 = property2.GetValue(validationContext.ObjectInstance); if (value2 != null) return ValidationResult.Success; return new ValidationResult(string.Format("Either or both of \"{0}\" and \"{1}\" are required", _field1, _field2), new[] { _field1, _field2 }); } } } </code></pre> <p>Use case:</p> <pre><code>[EitherRequired("A", "B")] public class SomeModel { public int? A {get; set;} public int? B {get; set;} } </code></pre>
[]
[ { "body": "<p>Your code looks almost neat and clean, but there are still some areas where you could improve it. </p>\n\n<ul>\n<li>Althought braces may be optional for single line <code>if</code> statements your code will get less error-prone by using them. </li>\n<li>Some more vertical spacing (new lines) would improve the readability of the code. </li>\n<li>The class <code>EitherRequiredAttribute</code> could be named better. I would suggest to name it <code>AtLeastOneRequiredAttribute</code>. Using this name makes the purpose of the class and the annotation more clear. </li>\n<li>You only check if <code>valueX == null</code> hence you could omit both <code>value1</code> and <code>value2</code> and just check if the call to <code>GetValue()</code> returns <code>null</code>. </li>\n<li><p>Instead of having </p>\n\n<pre><code>var property1 = validationContext.ObjectType.GetProperty(_field1);\nif (property1 == null)\n return new ValidationResult(string.Format(\"Unknown property: {0}\", _field1), new[] { _field1 }); \nvar property2 = validationContext.ObjectType.GetProperty(_field2);\nif (property2 == null)\n return new ValidationResult(string.Format(\"Unknown property: {0}\", _field2), new[] { _field2 }); \n</code></pre>\n\n<p>you could introduce a method <code>bool TryGetProperty(string, ValidationContext, out PropertyInfo)</code>. </p></li>\n</ul>\n\n<p>Implementing the mentioned points would lead to </p>\n\n<pre><code>[AttributeUsage(AttributeTargets.Class, AllowMultiple = true)]\npublic class AtLeastOneRequiredAttribute : ValidationAttribute\n{\n private readonly string _field1;\n private readonly string _field2;\n\n public EitherRequiredAttribute(string field1, string field2) =&gt; (_field1, _field2) = (field1, field2);\n\n protected override ValidationResult IsValid(object value, ValidationContext validationContext)\n {\n if (!TryGetProperty(_field1, validationContext, out var property1))\n {\n return new ValidationResult(string.Format(\"Unknown property: {0}\", _field1), new[] { _field1 });\n }\n\n if (!TryGetProperty(_field2, validationContext, out var property2))\n {\n return new ValidationResult(string.Format(\"Unknown property: {0}\", _field2), new[] { _field1 });\n }\n\n if (property1.GetValue(validationContext.ObjectInstance) != null ||\n property2.GetValue(validationContext.ObjectInstance) != null)\n {\n return ValidationResult.Success;\n }\n\n return new ValidationResult(string.Format(\"Either or both of \\\"{0}\\\" and \\\"{1}\\\" are required\", _field1, _field2), new[] { _field1, _field2 });\n }\n private bool TryGetProperty(string fieldName, ValidationContext validateionContext, out PropertyInfo propertyInfo)\n {\n return (propertyInfo = validateionContext.ObjectType.GetProperty(fieldName)) != null;\n }\n}\n</code></pre>\n\n<p>Althought methods named <code>TryGetXXX</code> are indicating that no exception should be thrown by calling them, this method will throw if <code>fieldName</code> is either <code>null</code> or <code>WhitheSpace</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-20T09:24:24.550", "Id": "454485", "Score": "0", "body": "Regarding your last comment, you probably should validate that in the constructor." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-20T07:37:17.387", "Id": "232686", "ParentId": "232614", "Score": "3" } }, { "body": "<p>Fields and properties are different things. You are mixing them up: the naming in the attribute code suggests that you want to operate on fields, but the use site is supplying property names. The naming of <code>field1</code> and <code>field2</code> should be changed to <code>propertyName1</code> and <code>propertyName2</code> respectively.</p>\n\n<p>Don't forget your <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.reflection.bindingflags?view=netframework-4.8\" rel=\"nofollow noreferrer\"><code>BindingFlags</code></a>! Right now your code will look up any public property with the given name, <em>including static properties</em>. You probably only want public <em>instance</em> properties:</p>\n\n<pre><code>var property1 = validationContext.ObjectType.GetProperty(_field1, BindingFlags.Instance | BindingFlags.Public);\n</code></pre>\n\n<p>Depending on your performance constraints, reflection might be too slow for you. If so, it's common practice to cache the results of calls to <code>GetProperty</code> since that information is unchanging at runtime.</p>\n\n<p>It's good practice to use <code>nameof</code> for getting string representations of identifiers, because if <code>SomeModel.A</code> gets renamed then the program won't compile until you also update the attribute argument.</p>\n\n<pre><code>[EitherRequired(nameof(A), nameof(B))]\npublic class SomeModel\n{\n public int? A {get; set;}\n public int? B {get; set;}\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-20T14:30:58.290", "Id": "454514", "Score": "1", "body": "I stumbled over the naming as well without mentioning it. Good call, but `propertyName1` would be better than `property1`. Nevertheless +1" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-20T15:01:36.523", "Id": "454522", "Score": "0", "body": "Agreed on `propertyName1`. Updated." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-20T14:26:07.113", "Id": "232703", "ParentId": "232614", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-18T20:21:04.617", "Id": "232614", "Score": "3", "Tags": [ "c#", ".net", "validation" ], "Title": "Validate if either or both of two fields has been provided, as a ValidationAttribute" }
232614
<p>This is really a simple affair, I just wonder if there is a better way to do it:</p> <pre><code>let el = document.querySelectorAll('#comic img'); let loadPromise = new Promise(function(resolve, reject) { let ticker = setInterval(() =&gt; { if (el[0].complete) { clearInterval(ticker); resolve(); } }, 100); setTimeout(() =&gt; { clearInterval(ticker); reject('Timeout'); }, 5000) }); loadPromise.then(() =&gt; { console.log(el[0].naturalWidth); let container = document.querySelectorAll('.main-wrapper &gt; div &gt; section &gt; section.column.column-1.grid-left-4.grid-width-16'); container[0].style.width = (el[0].naturalWidth + 420) + 'px'; }); </code></pre> <p>I must wait for the image to load, so I know its size so that I can adjust an element on the page.</p> <p>But <code>setInterval</code>(aka polling the element) seems so... medieval. Is there a nicer way in modern JS?</p>
[]
[ { "body": "<blockquote>\n <p>\"Must wait for the image to load\" ... \"Is there a nicer way?\"</p>\n</blockquote>\n\n<p>Yes, <br>\nAt first, instead of accessing the image by index <code>el[0]</code> - extract the image at once and give the variable meaningful name:</p>\n\n<pre><code>let img = document.querySelectorAll('#comic img')[0];\n</code></pre>\n\n<p>Next, you need to embed <strong><code>\"load\"</code></strong> event listener into Promise <em>executor function</em> to ensure the image has loaded:</p>\n\n<pre><code>let loadPromise = new Promise(function(resolve, reject) {\n img.addEventListener('load', function() {\n resolve();\n });\n setTimeout(() =&gt; {\n if (!img.complete) reject('Timeout');\n }, 5000)\n});\nloadPromise.then(() =&gt; {\n console.log(img.naturalWidth);\n let container = document.querySelectorAll('.main-wrapper &gt; div &gt; section &gt; section.column.column-1.grid-left-4.grid-width-16');\n container[0].style.width = (img.naturalWidth + 420) + 'px';\n});\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-19T13:27:25.983", "Id": "454351", "Score": "0", "body": "This answer is very poor -1. `Image.complete` property indicates the status of the loading process not the whether or not the image has actually loaded. As the image is queried from the page it may have already loaded in which case nether the load or timeouts will resolve the promise." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-19T13:34:47.843", "Id": "454352", "Score": "0", "body": "@Blindman67, such a comment does not consider situations when `img` element was added to the document, but its `src` attribute is set or changed/delayed in another event/function" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-19T13:39:52.607", "Id": "454353", "Score": "0", "body": "Even if you set the `src` the image can fail to load and the load event will not fire while the timeout will not detect that there was an error as `complete` will be true" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-19T14:38:29.140", "Id": "454365", "Score": "0", "body": "Ugh. Must have been really tired to not think of looking into events. The `.complete` attribute criticism is valid, though I'm not certain it is trivial to fix the promise. Arguably however it can be simplified further by not promisifying the callback, which conveniently also avoids the `.complete` issue." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-18T21:33:39.600", "Id": "232618", "ParentId": "232615", "Score": "2" } } ]
{ "AcceptedAnswerId": "232618", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-18T20:50:20.710", "Id": "232615", "Score": "4", "Tags": [ "javascript", "asynchronous" ], "Title": "Better way than setInterval to wait for an image load?" }
232615
<p>Below I created a <code>use</code> function that wraps a promise or non-promise, providing the a value callback all-while preserving the original function type.</p> <pre><code>type ThenArg&lt;T&gt; = T extends Promise&lt;infer U&gt; ? U : T type Func = (...args: any[]) =&gt; any type RelatedThen&lt;PP, V&gt; = PP extends Promise&lt;infer U&gt; ? Promise&lt;V&gt; : V function isPromise(obj: any) { return !!obj &amp;&amp; (typeof obj === 'object' || typeof obj === 'function') &amp;&amp; typeof obj.then === 'function' } function use&lt;A extends Func, G&gt;(fn: A, callback: (e: Error | null, a: ThenArg&lt;ReturnType&lt;A&gt;&gt;) =&gt; G) { return (...args: Parameters&lt;A&gt;): RelatedThen&lt;ReturnType&lt;A&gt;, G&gt; =&gt; { try { const v = fn(...args as any[]) if (isPromise(v)) { return v.then((r: any) =&gt; callback(null, r)).catch((e: Error) =&gt; callback(e, undefined as ThenArg&lt;ReturnType&lt;A&gt;&gt;)) } return callback(null, v) as RelatedThen&lt;ReturnType&lt;A&gt;, G&gt; } catch (e) { return callback(e, undefined as ThenArg&lt;ReturnType&lt;A&gt;&gt;) as unknown as RelatedThen&lt;ReturnType&lt;A&gt;, G&gt; } } } const p = async () =&gt; 'hi' const n = () =&gt; 'hi' const a = use(p, (value) =&gt; { return value + ' mom' }) const b = use(n, (value) =&gt; { return value + ' dad' }) a().then(console.log) console.log(b()) </code></pre> <p><a href="https://www.typescriptlang.org/play/?ssl=1&amp;ssc=1&amp;pln=38&amp;pc=17#code/C4TwDgpgBAKgFhAdgQQE4HMA8MB8UC8sUEAHsEgCYDOUACqgPYC2AllRJi4gGYSpQBVPAH5BUAFywAUKEhQAYgFdEAYwJQAFADodAQwxVJuxCADaAXQCUBPMZBSZ4aACUIAG13kK8JJlq0AGigANTxCf2IyShp6ZjYOLl5+IShRWNZ2TFCJEIcpbmUVYBYGRCg2dPiNBgAjACsjE2sAbykodqhUCGBFVDKAQn7auqgAMlHNWQgGbihhgnxCAHJhiCKlqAAfTagpmbn6heWC1WLSpetx3ad94a1gBDLF48KzxCWpAF8HE6KSssUmWQkXIiGoCkKQQA4jgNNxEJJkEEVLo3G4aroVABrSQaCCSACiqEY-B2iEUaKCukkPhQGEwrh6fRgTkwyBwOGs+DwUJabQ6XSZZW0egMklo+l0TG6fCobM5klcHi8tIZ3V6iBZkHl0LCeFaHUNu1QICgBqNFpUpSowCgADd1PCRVp9OgaLp3SYLJZ+RbDSxZhoKowMhANHbLHy-dHOuq+vb7o8NBpUI0QFy8Ci0RjsRpyZTOpGtCjgCo4Mn8VAiSSM1As+jMVi8UFlBQINwuBAKFAPbBHmgsIyNVqOOzOT6Yx1vpP2oKNXXUQ3c-m3EEIz2aErPF3VUPmaz2brfUbPgvS3BNBAozO5-H6zmmxAW2D253u73aQO1UKR-LORuoGULFEAYAB3Mpey3FVHm-YcDxwI9o2nKcvjyK1EBtKAwHUD0QFUTRayWOAWA+dDMKeAibCgIiSIcMjbV0dRATDMAgnDVFFCvKjmigY9bzKO0OOgABqaioCYZgPk+H0pHoqAaiY9g8zYwS3E42seL4uMBKEqBRI2ChdAoKSZN0DRLETJANDIhg3AgLQ3AYdAfRsuyHKcjQanMywgA" rel="nofollow noreferrer">Playground</a></p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-18T20:58:32.113", "Id": "232616", "Score": "1", "Tags": [ "typescript" ], "Title": "Function that provides callback for promise or non-promise" }
232616
<p>I have recently started studying JavaScript, nodeJS, and reactJS on the front-end, and I have some questions about best practices to apply in this JavaScript world. I would like to ask for opinions regarding how I could improve my code.</p> <p>Starting with an example: I have 2 functions, with different ways of handling promises</p> <p>Here I have a route to add a user:</p> <pre><code> addUsers(req,res,next) { try { const {name,email,login} = req.body; User.existLogin(req.body.login) .then(async result =&gt; { if(!result){ const password = await bcrypt.hashSync(req.body.password, 10); User.create({ name, email, login, password }).then(result =&gt; { res.status(201).json({Results: result.dataValues}) }) }else{ return res.status(409).json({message: 'Login already exists'}); } }) } catch (error) { res.status(500).json({error: error}) } } </code></pre> <p>And here I have another function to login:</p> <pre><code>async login(req,res){ const user = await User.existLogin(req.body.login); if (!user) { return res.status(400).json({result: 'Login is wrong '});} const isPassword = await User.isPassword(user.dataValues.password, req.body.password); if (!isPassword) { return res.status(400).json({result: 'Password is wrong '}); } const jwt = auth.signjwt(auth.payload(user)); console.log(jwt); res.status(200); res.json(jwt); } </code></pre> <p>Looking at this the login function seems to me to be cleaner, but I have doubts if really yours I could improve in one of two (I follow different logics to do both).</p> <p>I have an auth folder, where I export functions, such as my payload, my sign, my middlware to validate my jwt, but I don't know if this is a correct decision.</p> <pre><code>const jwt = require('jsonwebtoken'); const User = require('../models/User') const config= require('../config/dbconfig'); const moment = require('moment'); module.exports = { signjwt (payload) { return jwt.sign(payload, config.secretToken ) }, payload (usuario) { return { sub: usuario.id, name: usuario.nome, email: usuario.email, login: usuario.username, admin: true, iat: Math.floor(moment.now()/1000), // Timestamp de hoje exp: moment().add(10, 'minutes').unix() // Validade de 2 dias } }, async auth(req,res,next){ const token = req.header('Authorization'); console.log(token); if(!token) return res.status(401).json('Unauthorized'); try{ const decoded = jwt.verify(token,config.secretToken); const user = await User.findByPk(decoded.sub); console.log(user); if(!user){ return res.status(404).json('User not Found'); } res.json(user); next(); }catch(error){ console.error(error); res.status(400).json('Invalid Token'); } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-19T10:14:52.447", "Id": "454324", "Score": "1", "body": "`try {} catch {}` doesn't make sense in the first function as you need to use `.catch()` of the Promise itself (also, your function doesn't return anything because the `return` is inside a Promise). Conversely, the second function needs `try {} catch {}` because that's how async/await workflow is handled. As for \"best practices\" there's quite a few things to improve here depending on whose \"best practices\" you want to follow, but there's one universal thing: use ESLint with a popular set of rules which you like and read the usual \"best practices\" compilations." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-19T13:58:48.893", "Id": "454356", "Score": "0", "body": "thansk bro u can post awnser for give vote positive ?" } ]
[ { "body": "<h3>Initial thoughts:</h3>\n<p>This code looks very ... compressed without strictly needing to. Another thing that I notice is the level of nesting that shows in here.</p>\n<p>Generally speaking it doesn't particularly make a difference how you decide to handle Promises, in the vast majority of cases it's just a matter of personal preference.</p>\n<p>One thing you do <em>not</em> need to worry about is specially handling a promise rejection, since express automatically converts thrown errors into an appropriate response. That is what <code>login</code> takes advantage of to look so clean.</p>\n<p>One final initial thing I notice is the inconsistency that shows in the code.</p>\n<h3>Inconsistencies:</h3>\n<p>Compare the use of spaces in the following example:</p>\n<pre><code>const user = await User.existLogin(req.body.login);\nconst isPassword = await User.isPassword(user.dataValues.password, req.body.password);\n</code></pre>\n<p>Or compare the use of braces as well as whitespace for these examples:</p>\n<pre><code>if(!token) return res.status(401).json('Unauthorized');\nif (!user) { return res.status(400).json({result: 'Login is wrong '});}\nif(!user){\n return res.status(404).json('User not Found');\n}\n</code></pre>\n<p>Compare also the use of newlines and indentation levels in the following examples:</p>\n<pre><code>User.create({\n name, email, login, password }).then(result =&gt; {\n res.status(201).json({Results: result.dataValues})\n})\nreturn jwt.sign(payload,\n config.secretToken\n )\nreturn {\n sub: usuario.id,\n // ....\n exp: moment().add(10, 'minutes').unix()\n}\n</code></pre>\n<p>All this is to say: <strong>Pick one style and stick to it</strong>. Whichever style you decide on, it makes it easier to read if the style is <em><strong>consistent</strong></em>.</p>\n<p>Personally I prefer a style with more space than you've shown here for most cases.</p>\n<h3>Indentation:</h3>\n<p>You're using a strange mix of indentation styles and you're making lots of use of early returns, except in some small cases where I don't understand it. I personally prefer to almost always return early inside the request handler and if there's more complex logic I'd consider extracting that into a separate function. That yields code which will look a lot like this:</p>\n<pre><code>function addUsers(req, res) {\n const name = req.body.name;\n const email = req.body.email;\n const login = req.body.login;\n\n const exists = await User.existLogin(login);\n if (exists) {\n return res.status(409).json({ message: 'Login already exists' });\n }\n\n const password = bcrypt.hashSync(req.body.password, 10);\n const created = User.create({ name, email, login, password });\n res.status(201).json({ results: created.dataValue });\n}\n</code></pre>\n<p>Note that I removed the use of <code>await</code> with <code>hashSync</code> (should be clear why).\nAlso note that I lower-cased the member <code>results</code> in the returned JSON result.</p>\n<p>Obviously this doesn't quite have the same error behaviour as the code presented in the question, but it nicely shows how to avoid deeply nesting blocks.</p>\n<h3>HTTP / web standard authorization patterns</h3>\n<p>As a minor point I'd like to add that the <code>auth</code> middleware shown here is not quite following the common header authorization pattern. It's missing a response header indicating the expected authorization type. Since you're working with a token here, usually the header would be <code>'WWW-Authenticate: &quot;Bearer&quot;'</code>, but that would imply the expected <code>Authorization</code> header should start with <code>&quot;Bearer&quot;</code>, which is not the case here.</p>\n<p>To be more ... standard-conform I'd expect a proper bearer-token Authentication scheme to specifically define the authorization <em>type</em> used in the scheme. An option could be to explicitly specify you expect a jwt-token as type resulting in the following headers:</p>\n<pre><code>'WWW-Authenticate: &quot;jwt-token&quot;'\n---\n'Authorization: &quot;jwt-token &lt;jwt_token_goes_here&gt;&quot;'\n</code></pre>\n<p>Note that this suggestion of course would require an adjustment to the way the token is obtained, adding another way the request can be malformed :)</p>\n<h3>Conclusion:</h3>\n<p>All in all this is a solid start, to get this code to the next level just requires a few tweaks, mostly around being consistent in how the code is structured in itself.</p>\n<p>Well done :)</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-26T21:33:33.753", "Id": "260049", "ParentId": "232617", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-18T21:12:04.590", "Id": "232617", "Score": "2", "Tags": [ "javascript", "node.js" ], "Title": "User authentication, management" }
232617
<p>Here is the Egg Holder function for <span class="math-container">\$m\$</span> dimensions:</p> <p><span class="math-container">$$\displaystyle f(x)=\sum_{i=1}^{m-1}\left[-(x_{i+1}+47)\sin\sqrt{|x_{i+1}+x_i /2 + 47|} -x_i \sin\sqrt{|x_i - (x_{i+1}+47)|}\right]$$</span></p> <p>I am trying to find the global minimum of this function using hill climbing. Here's how the algorithm works:</p> <pre><code>initialize best fitness BF as arbitrarily high initialize best position BP as empty while termination condition not met: find a random position P find fitness F of P while P is within bounds: find four moves M_1 to M_4, where M = P + random summand for each M: find fitnesses MF of M if MF &lt; F: F = MF P = M if F &lt; BF: BF = F BP = P </code></pre> <p>The algorithm will find a position, generate four moves off of that position, then evaluate their fitness. If it's a better fitness than previously, that move becomes the new position and it repeats with four more moves, and so on. If the position becomes unbounded, start again with a new random initial position but keep the global bests stored. Eventually, the best position will creep towards the global best fitness (lower is better, ie. the function minimum).</p> <p>The bounds for each dimension is <code>[-512.00..512.00]</code> and the random summand is bounded within <code>[-5.00..5.00]</code>. Here's some C++ code using a hardcoded dimensionality of 2:</p> <pre class="lang-cpp prettyprint-override"><code>#include &lt;iostream&gt; #include &lt;cmath&gt; #include &lt;signal.h&gt; #include &lt;unistd.h&gt; #include &lt;pthread.h&gt; #include &lt;array&gt; #include &lt;float.h&gt; #include &lt;sstream&gt; // globals const static unsigned int DIMENSIONS = 2; // how many dimensions std::array&lt;double, DIMENSIONS&gt; bestPosition; // best position so far double bestResult = DBL_MAX; // arbitrarily large volatile bool continuing; // for thread while loop // function declarations bool checkInBounds(std::array&lt;double, DIMENSIONS&gt;, int, int); std::array&lt;double, DIMENSIONS&gt; getRandPosition(int, int); std::string printBest(); /** * Egg Holder function evaluation function * @param p - the position to evaluate * @return - the fitness of that position (lower is better) */ double eggHolderEvaluation(std::array&lt;double, DIMENSIONS&gt; p) { double sum; // to aggregate dimensions for (unsigned int i = 0; i &lt; DIMENSIONS-1; i++) { // split for readability, this is the EH summation double subSum = (p[i+1] + 47) * (std::sin(std::sqrt(std::abs((p[i]/2) + p[i+1] + 47)))); subSum -= (p[i] * std::sin(std::sqrt(std::abs(p[i] - p[i+1] - 47)))); subSum *= (-1); sum += subSum; // append it to aggregate sum } return sum; } /** * Hill Climbing worker function */ void* hillClimb(void* ignore) { std::array&lt;double, DIMENSIONS&gt; position; // position for evaluation later std::array&lt;double, DIMENSIONS&gt; stoch; // stochastic element double best, tempBest; // best of thread, temporary best used later while (continuing) { // while thread alive position = getRandPosition(-512, 512); // find a random position -512..512 for each dimension best = eggHolderEvaluation(position); // find fitness of that position while (checkInBounds(position, -512, 512)) { // while the position is within bounds for (unsigned int i = 0; i &lt; 4; i++) { // four possible moves stoch = getRandPosition(-5, 5); // stochastic summand position -5..5 std::array&lt;double, DIMENSIONS&gt; tempPos; // for adding // add the stochastic element to the position for (unsigned int j = 0; j &lt; DIMENSIONS; j++) { tempPos[j] = stoch[j] + position[j]; } tempBest = eggHolderEvaluation(tempPos); // evaluate that new position if (tempBest &lt; best) { // if better than loop position = tempPos; // overwrite best = tempBest; } } if (best &lt; bestResult) { // if better than global bestPosition = position; // overwrite bestResult = best; std::cout &lt;&lt; "New minimum: " &lt;&lt; printBest(); } } } return 0; } /** * function to find a random position * @param l - lower bound * @param h - higher bound * @return - a random position in all dimensions l..h */ std::array&lt;double, DIMENSIONS&gt; getRandPosition(int l, int h) { std::array&lt;double, DIMENSIONS&gt; p; for (unsigned int i = 0; i &lt; DIMENSIONS; i++) { // for each dimension // generate random position p[i] = l + (double)(rand() / (double)RAND_MAX) * (h - l); } return p; } /** * function to check if a position is within bounds * @param p - the position to check * @param l - lower bound * @param h - higher bound * @return - whether p is within l..h */ bool checkInBounds(std::array&lt;double, DIMENSIONS&gt; p, int l, int h) { for (unsigned int i = 0; i &lt; DIMENSIONS; i++) { // for each dimension // first dimension proc chance may come earlier; return F on per dimension basis if (p[i] &gt; h || p[i] &lt; l) { return false; } } // if it gets here, it's all within bounds return true; } /** * function to print the best to user * @return - the function with params and its evaluation */ std::string printBest() { std::stringstream toReturn; toReturn &lt;&lt; "f("; for (unsigned int i = 0; i &lt; DIMENSIONS; i++) { toReturn &lt;&lt; bestPosition[i]; if (i &lt; DIMENSIONS - 1) { toReturn &lt;&lt; ", "; } } toReturn &lt;&lt; ") = " &lt;&lt; bestResult &lt;&lt; "\n"; return toReturn.str().c_str(); } // interrupt handler void interrupted(int signal) { continuing = false; } int main (int argc, char* argv[]) { srand(time(NULL)); signal(SIGINT, interrupted); pthread_t thread; continuing = true; pthread_create(&amp;thread, NULL, &amp;hillClimb, NULL); while (continuing) { sleep(1); } std::cout &lt;&lt; "\nBest in run: " &lt;&lt; printBest(); return 0; } </code></pre> <p>Compile with <code>g++ -pthread -std=c++0x source.cpp -o eghc</code> and execute with <code>./eghc</code>. Here's a sample execution:</p> <pre><code>$ g++ -pthread -std=c++0x source.cpp -o eghc &amp;&amp; ./eghc New minimum: f(-431.589, -362.496) = 146.096 New minimum: f(-431.215, -363.239) = 137.753 New minimum: f(-432.044, -367.541) = 96.1419 New minimum: f(-433.497, -379.378) = -73.8794 New minimum: f(-433.581, -379.858) = -81.7316 New minimum: f(-429.106, -386.805) = -328.96 New minimum: f(-423.988, -389.813) = -513.774 New minimum: f(-422.713, -394.128) = -628.416 New minimum: f(-420.314, -398.311) = -726.148 New minimum: f(-416.017, -397.849) = -755.885 New minimum: f(-417.356, -401.802) = -766.056 New minimum: f(-415.791, -401.4) = -766.095 New minimum: f(-415.792, -401.024) = -766.201 New minimum: f(-417.295, -402.015) = -766.299 New minimum: f(-417.054, -402.14) = -766.429 New minimum: f(-417.055, -402.156) = -766.43 New minimum: f(-416.905, -402.017) = -766.43 New minimum: f(-417.038, -402.159) = -766.43 New minimum: f(-416.974, -402.094) = -766.431 New minimum: f(-416.962, -402.077) = -766.431 New minimum: f(-416.979, -402.091) = -766.431 New minimum: f(-416.971, -402.085) = -766.431 New minimum: f(-416.976, -402.09) = -766.431 ^C Best in run: f(-416.976, -402.09) = -766.431 </code></pre> <p>A thread is initialized to perform the hill climbing; there's no termination condition other than <code>SIGINT</code>, which will exit the program after outputting the best in run fitness. I only use a thread so it could be scaled to >1 thread at a later date if I wish.</p> <p>I can't find much literature for the function minimum for the Egg Holder function in >2 dimensions, so I can't verify how >2 dimensions performs, but for 2-dimensions, it does get caught in local minima. Optimal is <code>f(512, 404.2319) = -959.6407</code>, however.</p> <p>How could this be improved to get out of local extremum?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-19T05:27:02.870", "Id": "454296", "Score": "1", "body": "To begin with, `double sum;` is not initialized. It may also be beneficial to explain what the Egg Holder function is, a significance of `47`, and why do you expect the hill climbing to find the global minimum." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-19T05:29:16.970", "Id": "454297", "Score": "0", "body": "@vnp nice catch, but it does compile even without `double sum = 0.00;`. None of `-Wall`, `-Wpedantic`, or `-Wextra` catch it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-19T05:32:03.433", "Id": "454298", "Score": "1", "body": "A not initialized automatic variable invokes an undefined behavior, and C++ is not required to (in fact, in most cases unable to) diagnose it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-19T05:38:08.807", "Id": "454299", "Score": "0", "body": "@vnp interesting, thanks for the info!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-19T21:45:06.993", "Id": "454429", "Score": "0", "body": "Some compiler warnings are only enabled at higher optimization levels, such as `-O2`. Detection of unassigned variables may be one of them. You should also compile the code with CLang and with Intel C++ and with MSVC and enable all warnings for them as well, just to get more checks and warnings." } ]
[ { "body": "<p>The code already follows a good programming practice, which is to make all statements contained by <code>if</code>, <code>then</code> and loops logic blocks rather than single statements.</p>\n<h2>Portability</h2>\n<p>The code is specifically using Unix/Linux headers and is not portable to other systems, such as Windows. On Windows the code won't compile due to the headers <code>#include &lt;unistd.h&gt;</code> and <code>#include &lt;pthread.h&gt;</code>. The use of the function <code>sleep()</code> also prevents portability.</p>\n<h2>Use C++ Random Number Generator Over C Random Number Generator</h2>\n<p>The code is currently using the <code>C</code> programming language random number generation technique. Since C++11 the C++ programming language has had it's own random number generator that provides a better distribution of random numbers.</p>\n<pre><code>#include &lt;random&gt;\n#include &lt;iostream&gt;\n\nint main()\n{\n std::random_device dev;\n std::mt19937 rng(dev());\n std::uniform_int_distribution&lt;std::mt19937::result_type&gt; dist6(1,6); // distribution in range [1, 6]\n\n std::cout &lt;&lt; dist6(rng) &lt;&lt; std::endl;\n}\n</code></pre>\n<p>This is discussed in more detail in <a href=\"https://stackoverflow.com/questions/13445688/how-to-generate-a-random-number-in-c\">this stackoverflow question</a>.</p>\n<h2>Initialize Variables</h2>\n<p>As noted by @vnp a best practice in C++ is to always initialize variables. Local variables in a function is memory allocated from the stack and may contain previous values, the C++ programming standard does not require local variables to be initialized by the compiler. This has caused many bugs over the years. This <a href=\"https://stackoverflow.com/questions/2218254/variable-initialization-in-c\">stackoverflow question</a> discusses when a variable will or will not be initialized.</p>\n<h2>Magic Numbers</h2>\n<p>As noted by @vnp there are Magic Numbers in the <code>double eggHolderEvaluation(std::array&lt;double, DIMENSIONS&gt; p)</code> function (47), there are also magic numbers in the function <code>void* hillClimb(void* ignore)</code> (-512, 512, -5, 5 and 4). Tt might be better to create symbolic constants for them to make the code more readble and easier to maintain. These numbers may be used in many places and being able to change them by editing only one line makes maintainence easier.</p>\n<p>Numeric constants in code are sometimes referred to as <a href=\"https://en.wikipedia.org/wiki/Magic_number_(programming)\" rel=\"nofollow noreferrer\">Magic Numbers</a>, because there is no obvious meaning for them. There is a discussion of this on <a href=\"https://stackoverflow.com/questions/47882/what-is-a-magic-number-and-why-is-it-bad\">stackoverflow</a>.</p>\n<h2>Proper Include Headers</h2>\n<p>This program uses the <code>C</code> programming include files <code>#include &lt;signal.h&gt;</code> and <code>#include &lt;float.h&gt;</code>. The <code>C++</code> version of these headers can be used by removing the dot h and prepending the file name with <code>'c'</code>.</p>\n<pre><code>#include &lt;csignal&gt;\n#include &lt;cfloat&gt;\n</code></pre>\n<p>The code is missing the header file <code>ctime</code> which is used to to initialize the random number generator.</p>\n<h2>Exit Status</h2>\n<p>The <code>return 0;</code> is not absolutely necessary, C++ will do the proper thing without it. If there were possible failure modes as well as successful exits, it might be better to include <code>cstdlib</code> and use <a href=\"https://en.cppreference.com/w/cpp/utility/program/EXIT_status\" rel=\"nofollow noreferrer\">EXIT_SUCCESS and EXIT_FAILURE</a> rather than return 0.</p>\n<h2>Readability</h2>\n<p>The code might be more readable if it contained more vertical spacing. While there is vertical spacing between functions, the more complex functions could use vertical spacing to show separate logic blocks. Here is an example</p>\n<pre><code>void* hillClimb(void* ignore) {\n std::array&lt;double, DIMENSIONS&gt; position; // position for evaluation later\n std::array&lt;double, DIMENSIONS&gt; stoch; // stochastic element\n double best, tempBest; // best of thread, temporary best used later\n\n while (continuing) { // while thread alive\n position = getRandPosition(-512, 512); // find a random position -512..512 for each dimension\n best = eggHolderEvaluation(position); // find fitness of that position\n while (checkInBounds(position, -512, 512)) { // while the position is within bounds\n for (unsigned int i = 0; i &lt; 4; i++) { // four possible moves\n stoch = getRandPosition(-5, 5); // stochastic summand position -5..5\n std::array&lt;double, DIMENSIONS&gt; tempPos; // for adding\n // add the stochastic element to the position\n for (unsigned int j = 0; j &lt; DIMENSIONS; j++) {\n tempPos[j] = stoch[j] + position[j];\n }\n tempBest = eggHolderEvaluation(tempPos); // evaluate that new position\n\n if (tempBest &lt; best) { // if better than loop\n position = tempPos; // overwrite\n best = tempBest;\n }\n }\n\n if (best &lt; bestResult) { // if better than global\n bestPosition = position; // overwrite\n bestResult = best;\n std::cout &lt;&lt; &quot;New minimum: &quot; &lt;&lt; printBest();\n }\n }\n }\n\n return 0;\n}\n</code></pre>\n<p>By breaking it up this way, it becomes obvious that the variables <code>best</code>, <code>tempBest</code> <code>position</code> and <code>stoch</code> can actually be declared within the loops themselvers rather than the top of the function.</p>\n<p>If statements and loops become more readable if they are not on one line as shown above.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-19T21:20:47.130", "Id": "454426", "Score": "0", "body": "Excellent writeup, thank you. One thing: is `47` considered a magic number if it is part of the function and not arbitrary?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-19T22:47:24.623", "Id": "454439", "Score": "0", "body": "@gator The code doesn't explain what 47 is in a comment, and there is no symbolic name. Let's say you coded this professionally and then won 4 million dollars, or moved to another city; the person that has to maintain this code has no idea what that 47 represents. It wasn't clear to me or vnp." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-19T23:05:51.577", "Id": "454440", "Score": "0", "body": "That's fair. To be frank, I'm not even sure what it represents myself. It's part of the definition of the Egg Holder function, something some mathematician of antiquity came up with." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-19T23:24:15.203", "Id": "454441", "Score": "1", "body": "@gator Truly a magic number, LOL." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-19T20:19:48.237", "Id": "232658", "ParentId": "232622", "Score": "3" } } ]
{ "AcceptedAnswerId": "232658", "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-19T01:51:13.257", "Id": "232622", "Score": "7", "Tags": [ "c++", "algorithm", "ai" ], "Title": "Hill Climbing Egg Holder function - escaping local extrema" }
232622
<p>I quickly wrote this program to transform quadratic expressions in general form into vertex form.</p> <p><span class="math-container">\$ax^2 + bx + c \;=\; a(x-h)^2 + k,\quad\text{where}\quad h = -\frac{b}{2a} \quad\text{and}\quad k = c - ah^2 = c - \frac{b^2}{4a}.\$</span></p> <p>The actual conversion is easy, but with writing a lexer/parser came pain points: </p> <ul> <li><p>I tokenize with Regex, and some of the regex patterns are built dynamically using f-strings (which seems suspect). </p></li> <li><p>I use <code>eval</code> to compute terms in parentheses (to make fractions easy to input, for example).</p></li> </ul> <p>I also feel like there's probably a library for working with ASCII-fied algebraic expressions, (lots of the same kind of code populates sites like Symbolab, Cymath and Desmos,) but I do not know of it.</p> <pre class="lang-py prettyprint-override"><code>## Tests: # user_in = "(16/4)x^2 7x (3**2)" -&gt; "Result is: 4.0(x + (0.875))^2 + (5.9375)" (Passes) # user_in = "(41*4)x^2 41x 2" -&gt; "Result is: 164.0(x + (0.125))^2 + (-0.5625)" (Passes) # user_in = "x^2 4" -&gt; "Result is: (x + (2.0))^2 + (-4.0)" (Fails) # user_in = "x^2 4x 16" -&gt; "Result is (x + (2.0))^2 + 12.0" (Fails) </code></pre> <pre class="lang-py prettyprint-override"><code>import re print("""~~~Square Completer!~~~ Enter the terms of your quadratic equation in standard form Addition is implied, terms separated by spaces. Only use one kind of single-letter variable in the whole expression. Surround computations such as constant multiplication and fractions in parens. DO NOT put variables inside parens!""") user_in = input("&gt; ") # extract the variable def extract_variable(expression): letters = re.findall(r'[a-z]', expression) # all the letters if all(match == letters[0] for match in letters): # if all letters == the first one return letters[0] # we have our variable else: raise ValueError("Only use one kind of single-letter variable in the whole expression.") variable = extract_variable(user_in) # eval all things in parens and split string into terms def split_into_terms(expression): expression = re.sub(fr"\([^{variable}\)]+\)", lambda m: str(eval(m.group())), expression) print(f"working with {expression}") return expression.split(' ') terms = split_into_terms(user_in) print(terms) # sort terms into bins def bin_terms(terms): squareds, x_es, constants = [], [], [] for term in terms: term = term.strip().lower() if term.endswith('^2'): squareds.append(term[:-2]) # without trailing '^2' elif term.endswith(variable): x_es.append(term) elif bool(re.search(r"^-?[0-9\.]+$", term)): # if the term contains only numbers constants.append(term) return squareds, x_es, constants squareds, x_es, constants = bin_terms(terms) print('unprocessed:', squareds, x_es, constants, sep='\n') def sum_bins(squareds, x_es, constants): squareds = [squared[:-1] for squared in squareds if squared.endswith(variable)] # 2x -&gt; 2 print('squareds step1:', squareds, sep='\n') squareds = ['1' if squared == variable else squared for squared in squareds] # x -&gt; 1 print('step2:', squareds) print('\nprocessed:', squareds, x_es, constants, sep='\n') constant = sum(float(c) for c in constants) print('\n ***EXES: ', x_es,'***') x = sum(float(el[:-1]) for el in x_es) print('\n ***SUMX: ', x,'***') squared = sum(float(el) for el in squareds) return squared, x, constant squared, x, constant = sum_bins(squareds, x_es, constants) ##print('\ntotals:', squared, x, constant, sep='\n') ##constant = constant / squared ##x = x / squared ##squared = 1 ##print('\nover square term:', squared, x, constant, sep='\n') def complete_square(a,b,c): """ Complete the square, transforming a quadratic of form ax^2 + bx + c to form a(x + p)^2 - q """ p = b/(2*a) q = c - (b**2)/(4*a) return p, q p, q = complete_square(squared, x, constant) a = squared print(f'Result is: {a}({variable} + ({p}))^2 + ({q})') </code></pre>
[]
[ { "body": "<p>There is a library to help with this! Check out <a href=\"https://docs.sympy.org/latest/index.html\" rel=\"nofollow noreferrer\"><code>sympy</code></a>, particularly <a href=\"https://docs.sympy.org/latest/modules/core.html#sympy.core.sympify.sympify\" rel=\"nofollow noreferrer\"><code>sympify</code></a> and <a href=\"https://docs.sympy.org/latest/modules/parsing.html\" rel=\"nofollow noreferrer\"><code>parse_expr</code></a>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-19T22:14:41.063", "Id": "232665", "ParentId": "232625", "Score": "2" } } ]
{ "AcceptedAnswerId": "232665", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-19T06:15:04.457", "Id": "232625", "Score": "2", "Tags": [ "python", "python-3.x", "parsing", "mathematics", "lexer" ], "Title": "Quadratic \"Complete the Square\" Solver in Python 3" }
232625
<h3>Current State:</h3> <p>I have two CSV files, their sample attached below:</p> <ol> <li><p><code>FileOutputWithoutBuffer-Metrics.csv</code></p> <pre><code>File Length , Non-Buffered Time Taken (ns) 1000 , 5499114 2000 , 10971957 3000 , 15736008 4000 , 18970057 5000 , 22173215 6000 , 24612263 7000 , 26118520 8000 , 29934220 9000 , 31919477 10000 , 34940645 </code></pre></li> <li><p><code>FileOutputWithBuffer-Metrics.csv</code></p> <pre><code>File Length , Buffered Time Taken (ns) 1000 , 412991 2000 , 224509 3000 , 269990 4000 , 461664 5000 , 485668 6000 , 479069 7000 , 413657 8000 , 438734 9000 , 760068 10000 , 576458 </code></pre></li> </ol> <h3>What I want:</h3> <p>I want to plot a compare and contrast graph between these two CSV files corresponding to their <code>File Length</code> column.</p> <h3>What I did:</h3> <p>I wrote the below script for the same:</p> <pre><code># This line has to be updated on every place, possible. scriptPath &lt;- "XXX/XXX/XXX/XXX"; # Read in all csv files. FileOutputWithoutBufferMetrics &lt;- read.csv(file = file.path(scriptPath, "FileOutputWithoutBuffer-Metrics.csv"), header = TRUE, sep = ","); FileOutputWithBufferMetrics &lt;- read.csv(file = file.path(scriptPath, "FileOutputWithBuffer-Metrics.csv"), header = TRUE, sep = ","); FileOutputMetircs &lt;- merge(FileOutputWithoutBufferMetrics, FileOutputWithBufferMetrics, by=c('File.Length'), all=T); #colnames(FileOutputMetircs) &lt;- c("File Length", "Non-Buffered OutputStream Time", "Buffered OutputStream Time"); show(FileOutputMetircs); # Install extra packages :- ggplot2, reshape2. list.of.packages &lt;- c("ggplot2","reshape2"); new.packages &lt;- list.of.packages[!(list.of.packages %in% installed.packages()[,"Package"])]; if(length(new.packages)) { install.packages(new.packages) } require(ggplot2); require(reshape2); # Create a graph of FileOutputStream. df &lt;- melt(FileOutputMetircs, id.vars = 'File.Length', variable.name = 'Time'); ggplot(df, aes(File.Length, value)) + geom_line(aes(colour = Time)); </code></pre> <p>And got this output:</p> <p><a href="https://i.stack.imgur.com/9ze5p.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/9ze5p.png" alt="Image"></a></p> <h3>Where help is needed:</h3> <ol> <li>First, since I am very new to ggplot. Therefore, need assurity on the correctness of my R script.</li> <li>Other ways (performace-wise) to optimize the script. </li> </ol> <p>Thanks!.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-19T07:51:45.220", "Id": "454308", "Score": "0", "body": "\"First, since I am very new to ggplot. Therefore, need assurity on the correctness of my R script.\" <--- This is off-topic on this site." } ]
[ { "body": "<p>The plot looks about right with the data, and I see no egrerious errors in your code. I do have a few remarks.</p>\n\n<ul>\n<li><p>In <code>r</code> it's unnecessary to end your lines with a semi-colon, and most styleguides advise against it. The only real purpose it has is allowing multiple statements on a single line, but why would we want that.</p></li>\n<li><p>With regards to your code where you install packages. There are two ways of loading a library: <code>library(name)</code> and <code>require(name)</code>. One big difference is that <code>require</code> returns a <code>FALSE</code> when the package is missing, <code>library</code> throws an error. What you can do is try and load the library, and if it fails install it:</p></li>\n</ul>\n\n<pre><code>for(libraryName in c(\"ggplot2\", \"reshape2\")){\n if(!require(libraryName)){\n install.package(libraryName)\n require(libraryName)\n }\n}\n</code></pre>\n\n<ul>\n<li>If your csv files are going to be huge, I recommend using <code>data.table::fread</code> for reading your csv files. In my experience it is the fastest reading large datasets. It also allows for efficient dataframe operations.</li>\n<li><p>If at reading time you specify the correct columnnames, you can prevent having to do the <code>melt</code> operation later: add the argument <code>col.names = c(\"File.Length\", \"value\")</code>. Add the column <code>FileOutputWithoutBufferMetrics[\"Time\"] &lt;- \"Non.Buffered.Time.Taken..ns.\"</code> to both dataframes, and simply <code>rbind</code> them. This is most likely more efficient than <code>melt</code>, especially on big datasets.</p></li>\n<li><p><code># This line has to be updated on every place, possible.</code> This is generally accounted for using the \"working directory\" of the R process. If you run the script from commandline, the working directory is the current directory. If you run it from Rstudio you can set it using the <code>setwd(dir)</code> function, or in <code>Session -&gt; Set Working Directory -&gt; To Source File Location</code> in the Rstudio ui. Once that is set, you don't have to add that path to the filename in <code>read.csv</code>.</p></li>\n</ul>\n\n<hr>\n\n<p>In summary:</p>\n\n<pre><code>for(libraryName in c(\"ggplot2\", \"data.table\")){\n if(!require(libraryName)){\n install.package(libraryName)\n require(libraryName)\n }\n}\n\nFileOutputWithoutBufferMetrics &lt;- fread(\"FileOutputWithoutBuffer-Metrics.csv\"), col.names = c(\"File.Length\", \"value\"))\nFileOutputWithoutBufferMetrics[\"Time\"] &lt;- \"Non.Buffered.Time.Taken..ns.\"\n\nFileOutputWithBufferMetrics &lt;- fread(\"FileOutputWithBuffer-Metrics.csv\"), col.names = c(\"File.Length\", \"value\"))\nFileOutputWithBufferMetrics[\"Time\"] &lt;- \"Buffered.Time.Taken..ns.\"\n\ndf &lt;- rbind(FileOutputWithoutBufferMetrics, FileOutputWithBufferMetrics)\n\n\nggplot(df, aes(File.Length, value)) + geom_line(aes(colour = Time))\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-19T18:05:38.020", "Id": "454412", "Score": "0", "body": "Each and everything is well explained. Thanks, @JAD!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-19T07:52:49.137", "Id": "232631", "ParentId": "232627", "Score": "0" } } ]
{ "AcceptedAnswerId": "232631", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-19T06:35:27.817", "Id": "232627", "Score": "0", "Tags": [ "performance", "graph", "csv", "r" ], "Title": "Correctness and Performance of graph plotting on R" }
232627
<h1>Problem Definition</h1> <blockquote> <p>Roman numerals are represented by seven different symbols: <code>I</code>, <code>V</code>, <code>X</code>, <code>L</code>, <code>C</code>, <code>D</code> and <code>M</code>.</p> </blockquote> <p><span class="math-container">$$\begin{array}{c|ccccccc|} Symbol &amp; Value \\ \hline I &amp; 1 \\ V &amp; 5 \\ X &amp; 10 \\ L &amp; 50 \\ C &amp; 100 \\ D &amp; 500 \\ M &amp; 1000 \\ \end{array}$$</span></p> <blockquote> <p>For example, two is written as <code>II</code> in Roman numeral, just two one's added together. Twelve is written as, <code>XII</code>, which is simply <code>X</code> + <code>II</code>. The number twenty seven is written as <code>XXVII</code>, which is <code>XX</code> + <code>V</code> + <code>II</code>.</p> <p>Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not <code>IIII</code>. Instead, the number four is written as <code>IV</code>. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as <code>IX</code>. There are six instances where subtraction is used:</p> <p><code>I</code> can be placed before <code>V</code> (<code>5</code>) and <code>X</code> (<code>10</code>) to make <code>4</code> and <code>9</code>. <code>X</code> can be placed before <code>L</code> (<code>50</code>) and <code>C</code> (<code>100</code>) to make <code>40</code> and <code>90</code>. <code>C</code> can be placed before <code>D</code> (<code>500</code>) and <code>M</code> (<code>1000</code>) to make <code>400</code> and <code>900</code>. Given a roman numeral, convert it to an integer. Input is guaranteed to be within the range from <code>1</code> to <code>3999</code>.</p> <p><strong>Examples</strong>:</p> <p><strong>Input</strong>: <code>"III"</code> <strong>Output</strong>: <code>3</code></p> <p><strong>Input</strong>: <code>"IV"</code> <strong>Output</strong>: <code>4</code></p> <p><strong>Input</strong>: <code>"IX"</code> <strong>Output</strong>: <code>9</code></p> <p><strong>Input</strong>: <code>"LVIII"</code> <strong>Output</strong>: <code>58</code> (<code>L</code> = <code>50</code>, <code>V</code> = <code>5</code>, <code>III</code> = <code>3</code>).</p> <p><strong>Input</strong>: <code>"MCMXCIV"</code> <strong>Output</strong>: <code>1994</code> (<code>M</code> = <code>1000</code>, <code>CM</code> = <code>900</code>, <code>XC</code> = <code>90</code> and <code>IV</code> = <code>4</code>).</p> </blockquote> <h2>Solution</h2> <p><strong>Approach:</strong> In my solution I decided to use a simple state machine which seems elegant to me. But do you agree? Could I do better?</p> <p><strong>Criteria:</strong> Readability over performance. I care the most about the code to be easy to understand. Performance is important, but only in terms of "big-O" notation.</p> <p><strong>Note:</strong> <code>.</code> "next symbol" represents "any other case" or "otherwise" branch.</p> <pre><code>type Action = { value: number, skipNextSymbol: boolean }; type Transitions = { [nextSymbol: string]: Action }; type StateMachine = { [currentSymbol: string]: Transitions }; export const stateMachine: StateMachine = { 'I': { 'V': { value: 4, skipNextSymbol: true }, 'X': { value: 9, skipNextSymbol: true }, '.': { value: 1, skipNextSymbol: false }, }, 'V': { '.': { value: 5, skipNextSymbol: false }, }, 'X': { 'L': { value: 40, skipNextSymbol: true }, 'C': { value: 90, skipNextSymbol: true }, '.': { value: 10, skipNextSymbol: false }, }, 'L': { '.': { value: 50, skipNextSymbol: false }, }, 'C': { 'D': { value: 400, skipNextSymbol: true }, 'M': { value: 900, skipNextSymbol: true }, '.': { value: 100, skipNextSymbol: false }, }, 'D': { '.': { value: 500, skipNextSymbol: false }, }, 'M': { '.': { value: 1000, skipNextSymbol: false }, }, }; export const romanToInt = function(roman: string): number { if (!roman || !roman.length) throw new Error(`${roman} is not a Roman number.`); const symbolQueue = roman.toUpperCase().split(''); let resultNumber = 0; while (symbolQueue.length) { const currentSymbol = symbolQueue.shift()!; const transitions = stateMachine[currentSymbol]; const nextSymbol = symbolQueue[0]; const applicableTransition = transitions[nextSymbol] || transitions['.']; resultNumber += applicableTransition.value; if (applicableTransition.skipNextSymbol &amp;&amp; symbolQueue.length) symbolQueue.shift(); } return resultNumber; }; </code></pre> <h2>Tests</h2> <pre><code>import { romanToInt } from '../src/leet-code/1-easy/13-roman-to-integer'; describe(romanToInt.name, () =&gt; { it('Should work', () =&gt; { interface TestCase { input: string; expectedOutput: number; }; const testCases: TestCase[] = [ { input: 'I', expectedOutput: 1 }, { input: 'II', expectedOutput: 2 }, { input: 'III', expectedOutput: 3 }, { input: 'IV', expectedOutput: 4 }, { input: 'V', expectedOutput: 5 }, { input: 'VI', expectedOutput: 6 }, { input: 'VII', expectedOutput: 7 }, { input: 'VIII', expectedOutput: 8 }, { input: 'IX', expectedOutput: 9 }, { input: 'X', expectedOutput: 10 }, { input: 'XI', expectedOutput: 11 }, { input: 'XII', expectedOutput: 12 }, { input: 'XIII', expectedOutput: 13 }, { input: 'XIV', expectedOutput: 14 }, { input: 'XV', expectedOutput: 15 }, { input: 'XVI', expectedOutput: 16 }, { input: 'XVII', expectedOutput: 17 }, { input: 'XVIII', expectedOutput: 18 }, { input: 'XIX', expectedOutput: 19 }, { input: 'XX', expectedOutput: 20 }, { input: 'XXX', expectedOutput: 30 }, { input: 'XL', expectedOutput: 40 }, { input: 'L', expectedOutput: 50 }, { input: 'LX', expectedOutput: 60 }, { input: 'LXX', expectedOutput: 70 }, { input: 'LXXX', expectedOutput: 80 }, { input: 'XC', expectedOutput: 90 }, { input: 'C', expectedOutput: 100 }, { input: 'CC', expectedOutput: 200 }, { input: 'CCC', expectedOutput: 300 }, { input: 'CD', expectedOutput: 400 }, { input: 'D', expectedOutput: 500 }, { input: 'DC', expectedOutput: 600 }, { input: 'DCC', expectedOutput: 700 }, { input: 'DCCC', expectedOutput: 800 }, { input: 'CM', expectedOutput: 900 }, { input: 'M', expectedOutput: 1000 }, { input: 'MM', expectedOutput: 2000 }, { input: 'MMM', expectedOutput: 3000 }, { input: 'MMMM', expectedOutput: 4000 }, { input: 'MMMMM', expectedOutput: 5000 }, { input: 'MCMXCIX', expectedOutput: 1999 }, ]; testCases.forEach(testCase =&gt; { const { input, expectedOutput } = testCase; expect(romanToInt(input)).toEqual(expectedOutput); }); }); }); <span class="math-container">```</span> </code></pre>
[]
[ { "body": "<p>You don't need to define each individual transition state since there's a simple general rule: total all the numerals, but subtract the ones that occur in front of a larger numeral.</p>\n\n<pre><code>function romanToInt(roman: string): number {\n const value: {[numeral: string]: number} = {\n 'I': 1,\n 'V': 5,\n 'X': 10,\n 'L': 50,\n 'C': 100,\n 'D': 500,\n 'M': 1000,\n }\n let prev = 0;\n let total = 0;\n for (const numeral of roman.split('').reverse()) {\n const current = value[numeral]; // this will throw on an invalid numeral\n if (current &gt;= prev)\n total += current;\n else \n total -= current;\n prev = current;\n }\n return total;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-19T07:46:25.553", "Id": "454307", "Score": "0", "body": "Good observation. I can see how your code will allow invalid inputs (i.e. `IVX`). My code suffers from the same issue. But at least your code is more compact... If I was to make my code work correctly against the invalid inputs (which is throw an error), I'd actually need to define _more_ transitions -- allowed only. Thanks for the review Sam. Upvoted" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-19T15:31:23.333", "Id": "454383", "Score": "0", "body": "If you wanted to catch more invalid numbers, you could add more rules, like: when you subtract a lesser number from a greater number it has to be at least 5x smaller (i.e. no \"VX\"). Careful making it too strict, IIRC the Romans themselves would sometimes do slightly irregular things. :)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-19T07:11:45.490", "Id": "232629", "ParentId": "232628", "Score": "5" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-19T06:49:24.157", "Id": "232628", "Score": "5", "Tags": [ "programming-challenge", "typescript", "roman-numerals" ], "Title": "Roman Number to Integer" }
232628
<p>Is it possible to improve this code in terms of efficiency / line number ? (avoid nested code ...). It comes from a test I failed. I don't know how I could have done it better.</p> <pre><code>from collections import Counter def parse_molecule(molecule): array = [[]] for token in map(str, molecule): if token.isalpha() and token.istitle(): last = [token] upper = token array[-1].append(token) elif token.isalpha(): last = upper + token array[-1] = [last] elif token.isdigit(): array[-1].extend(last*(int(token)-1)) elif token == '(' or token == '[': array.append([]) elif token == ')' or token == ']': last = array.pop() array[-1].extend(last) return dict(Counter(array[-1])) </code></pre> <p>Examples of function usage are following:</p> <pre><code>&gt;&gt;&gt; water = 'H2O' &gt;&gt;&gt; parse_molecule(water) &gt;&gt;&gt;{'H': 2, 'O': 1} &gt;&gt;&gt; magnesium_hydroxide = 'Mg(OH)2' &gt;&gt;&gt; parse_molecule(magnesium_hydroxide) &gt;&gt;&gt; {'Mg': 1, 'O': 2, 'H': 2} &gt;&gt;&gt; fremy_salt = 'K4[ON(SO3)2]2' &gt;&gt;&gt; parse_molecule(fremy_salt) &gt;&gt;&gt; {'K': 4, 'O': 14, 'N': 2, 'S': 4} </code></pre> <p>This is the statement: </p> <blockquote> <p>For a given chemical formula represented by a string, count the number of atoms of each element contained in the molecule and return a dict.</p> </blockquote> <p>For example:</p> <blockquote> <pre><code>water = 'H2O' parse_molecule(water) return {'H': 2, 'O': 1} magnesium_hydroxide = 'Mg(OH)2'&lt;br&gt; parse_molecule(magnesium_hydroxide)&lt;br&gt; return {'Mg': 1, 'O': 2, 'H': 2} fremy_salt = 'K4[ON(SO3)2]2'&lt;br&gt; parse_molecule(fremy_salt)&lt;br&gt; return {'K': 4, 'O': 14, 'N': 2, 'S': 4} </code></pre> </blockquote> <p>As you can see, some formulas have brackets in them. The index outside the brackets tells you that you have to multiply count of each atom inside the bracket on this index. For example, in Fe(NO3)2 you have one iron atom, two nitrogen atoms and six oxygen atoms.</p> <p>Note that brackets may be round, square or curly and can also be nested. Index after the braces is optional.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-19T09:59:35.827", "Id": "454321", "Score": "1", "body": "Just to clarify, while you may have failed the test, does this function work as intended?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-19T10:02:43.163", "Id": "454322", "Score": "1", "body": "I'm not sure it does, since it does neither ensure the correct brackets nor that all brackets are closed. Try the non-sensical inputs `\"(H]2\"` and `\"(HO2\"`. At least `\"HO)2\"` raises an `IndexError`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-19T10:26:31.413", "Id": "454325", "Score": "1", "body": "Please update your function to cover cases mentioned in previous comments. Otherwise it's premature to review it as a \"working\" solution." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-19T11:05:25.227", "Id": "454328", "Score": "0", "body": "Yes the function work as intended (at least for the 3 usages)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-19T11:18:46.297", "Id": "454330", "Score": "0", "body": "@a.cou, Might there be 3 and more level input like `'K4[ON(S[N(O2H3)4O2]3)2]2'` ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-19T14:41:37.007", "Id": "454366", "Score": "0", "body": "@RomanPerekhrest i put the statement on my post" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-19T14:43:28.567", "Id": "454367", "Score": "1", "body": "Looks like you completely missed the “curly” braces `{}` requirement." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-19T14:46:43.507", "Id": "454370", "Score": "1", "body": "Your output is completely wrong for sugar: C12H22O11" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-19T14:46:52.423", "Id": "454371", "Score": "0", "body": "@a.cou, Again, as you mentioned \"*can also be nested*\", what result would you expect from `'K4[ON(S[N(O2H3)4O2]3)2]2'` ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-19T14:53:53.077", "Id": "454375", "Score": "2", "body": "`Li2` apparently contains one atom of `Li`, one of `L`, and one of `i`..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-19T19:12:38.023", "Id": "454416", "Score": "2", "body": "People, can I have your attention please. If the code is improperly tested, that's too bad. But it *is* tested (badly) and OP was not aware of the code being awfully broken when posting. Per our current scope, that means the code is **not** off-topic and you lot could've been pointing this out in answers instead. Thank you, have a nice day." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-20T08:11:50.190", "Id": "454474", "Score": "0", "body": "@AJNeufeld good point, I had not noticed the curly braces. C12H22O11 result is bad indeed, i don't take into consideration the second number. thank you !" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-20T09:16:30.747", "Id": "454484", "Score": "0", "body": "@Mast, I'm not sure that anyone other than OP can assert that OP was not aware of the code being awfully broken. The impression I get from \"*it comes from a test I failed*\" is that OP knew that the code *was* broken, but not specifically *how* it was broken." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-20T09:55:22.013", "Id": "454494", "Score": "0", "body": "@PeterTaylor I read that like the code was submitted as homework or during finals and *that* is what was failed." } ]
[ { "body": "<p>Just to pull a few of the comments together:</p>\n\n<ul>\n<li><p>This doesn't handle multi-digit numbers properly.</p></li>\n<li><p>This doesn't validate parentheses \"()\" and brackets \"[]\", and doesn't handle braces at all \"{}\".</p></li>\n</ul>\n\n<p>That said, making this code faster and making this code more correct go hand-in-hand, so forgive me if this answer breaks the Code Review standards a bit and attempts to correct your code while showing how to make it faster, simpler, and more elegant.</p>\n\n<p>Writing your own parser can be very hard, and doing it character-by-character is basically impossible to do correctly unless you've done this kind of thing a lot before. That said, you should look into text parsing tools, libraries, and techniques. Two main tools come to mind: regular expressions, and shift-reduce parsing. The latter is well worth understanding (IMO), but you can likely escape with just regular expressions for this task with just a little support code, since they're powerful enough to handle everything except parenthesis validation, which we'll try to sneak back in.</p>\n\n<p>First off, don't handle individual characters. We can create a simple <a href=\"https://www.w3schools.com/python/python_regex.asp\" rel=\"nofollow noreferrer\">regular expression</a> pattern that'll peel apart the individual atoms. To start with, let's not worry about parentheses. Every atom begins with an upper case letter: <code>[A-Z]</code>. It may be followed by one or zero lower-case letter: <code>[a-z]?</code>. This pattern may be followed by an integer, which is comprised of any number of digits: either <code>\\d*</code> or <code>(\\d+)?</code>, which will match the same patterns, but represent them in slightly different ways. This gives us the following regex (I'll group the atom name and number separately: <code>([A-Z][a-z]?)(\\d*)</code>.</p>\n\n<pre><code>In [1]: import re\n\nIn [2]: strings = [\n ...: 'H',\n ...: 'He',\n ...: 'H2O',\n ...: 'CO2',\n ...: 'Cu2O',\n ...: 'C12H22O11'\n ...: ]\n\nIn [3]: for s in strings:\n ...: print(re.findall(r'([A-Z][a-z]?)(\\d*)', s))\n ...:\n[('H', '')]\n[('He', '')]\n[('H', '2'), ('O', '')]\n[('C', ''), ('O', '2')]\n[('Cu', '2'), ('O', '')]\n[('C', '12'), ('H', '22'), ('O', '11')]\n</code></pre>\n\n<p>Looking pretty good so far, and the code is REALLY simple! Now we just need to handle parentheses. Unfortunately, it's a provable mathematical fact that regular expressions cannot properly handle the parentheses pairing problem. Why should that stop us, though!? We'll detect parentheses pairs from the inside-out, save the results off into arrays like you already do, and work our way out. No biggie!</p>\n\n<p>To do this, we'll create another regex that will find an un-interrupted parenthesis pair and extract the contents and, if it exists, an integer following it. This regex looks really convoluted and only handles \"()\", not brackets or braces (though the change to do so is trivial), but it demonstrates the idea, and once you understand it, it's actually pretty straightforward:</p>\n\n<pre><code>In [1]: re.search(r'\\(([^\\(\\[\\{\\)\\]\\}]+)\\)(\\d*)', 'ABC(XYZ)5').groups()\nOut[1]: ('XYZ', '5')\n</code></pre>\n\n<p><code>\\(</code> matches the opening parenthesis. <code>([^...]+)</code> selects one or more characters that AREN'T specified and saves the content into the first group, so we specify all parentheses, brackets, and braces, <code>\\(\\[\\{\\)\\]\\}</code>. We then match the closing parenthesis, <code>\\)</code>, then a trailing integer if it's there, <code>(\\d*)</code>. To match a pair of brackets or braces, just change <code>\\(</code> to <code>\\[</code> or <code>\\{</code>, along with the corresponding <code>\\)</code>.</p>\n\n<p>The <code>.search</code> function returns an object that tells you where in the searched string <code>'ABC(XYZ)5'</code> it found the match. You can now extract it from the outer string, parse its guts <code>'XYZ'</code> using the first regex, since we've guaranteed that this string contains no parentheses of its own, multiply by the integer, and repeat this process, working our way from the inner-most parenthesis pair out. Dealing with nesting is not quite trivial with this approach, but I'm sure you can make it work with a little extra cleverness. The proper general tool to parse text with things like parentheses would be to write a shift-reduce parser, but that becomes a whole new level of complicated, and isn't necessary for this simple task.</p>\n\n<p>This approach, using regular expressions, fits what you're asking about:</p>\n\n<ul>\n<li><p>Fast: Regexes are stupid fast for simple cases like this.</p></li>\n<li><p>Short: The iteration, grouping, etc. are largely handled by the <code>re</code> library and its classes, it's really easy to do complex pattern matching with one-liners.</p></li>\n<li><p>Explicit: Building this solution on regexes makes explicit what you're matching/looking for and what you're missing. Fixing minor issues (like multi-digit numbers, etc.) or finding new, but similar, patterns generally becomes trivial.</p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-20T08:29:09.167", "Id": "454477", "Score": "0", "body": "Thank you, this is very helpfull !" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-20T09:12:59.130", "Id": "454483", "Score": "0", "body": "\"*Unfortunately, it's a provable mathematical fact that regular expressions cannot properly handle the parentheses pairing problem.*\" A vanishingly small percentage of regex libraries limits itself to regular expressions. The relevant statement would be that Python regexes don't have extensions for recursion (as in Perl5 and Ruby) or balancing groups (and in .Net)." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-19T22:09:13.410", "Id": "232664", "ParentId": "232630", "Score": "4" } }, { "body": "<p>This code is confusing and inefficient:</p>\n\n<pre><code>for token in map(str, molecule):\n</code></pre>\n\n<p>It treats <code>molecule</code> as some kind of iterable object, and applies the <code>str</code> function to each element the iteration returns, an assigns each result successively to <code>token</code>. In this case, <code>molecule</code> is a string, which is already a sequence of iterable characters, and a single character is itself a string, so this map function is taking individual character strings and calling <code>str()</code> on those character strings to return the same character strings.</p>\n\n<p>The statement could be written much simpler:</p>\n\n<pre><code>for token in molecule:\n</code></pre>\n\n<hr>\n\n<p>These statements are testing for only 2 of the three grouping brackets:</p>\n\n<pre><code> elif token == '(' or token == '[':\n ...\n elif token == ')' or token == ']':\n ...\n</code></pre>\n\n<p>The correct statements would read:</p>\n\n<pre><code> elif token == '(' or token == '[' or token == '{':\n ...\n elif token == ')' or token == ']' or token == '}':\n ...\n</code></pre>\n\n<p>however, this is rather verbose. You can use the <code>in</code> operator to check if a character appears anywhere in a string, so these test could be written more compactly as:</p>\n\n<pre><code> elif token in '([{':\n ...\n elif token in ')]}':\n ...\n</code></pre>\n\n<hr>\n\n<p><code>isdigit()</code> is not the best function to use to verify a string can be parsed as an integer. It includes superscript and subscript digits, and other characters which will cause an exception when passed into <code>int(...)</code>:</p>\n\n<pre><code>&gt;&gt;&gt; \"³₂\".isdigit()\nTrue\n</code></pre>\n\n<p>Instead, use <code>isdecimal()</code>.</p>\n\n<hr>\n\n<p>As mention by scnerd in <a href=\"https://codereview.stackexchange.com/a/232664/100620\">their answer</a>, it is hard to parse strings character by character. You are detecting a lower case letter, adding it to the last token you found, and replacing the last token. You would need to do the same thing when you find a digit, and only when the current series of digits end perform the replication of the last radical, but this results in numerous special cases, which again make the parsing hard.</p>\n\n<p>It is better to break the molecule into low level tokens, not individual characters, and process complete tokens. As mention by scnerd, the regular expression engine can help. They diverted into attempt to match parenthesis in the regular expression parsing, which complicates things far too much. Here is a simpler approach:</p>\n\n<pre><code>import re\n\ndef tokenize_molecule(molecule):\n return re.findall('[A-Z][a-z]?|\\d+|.', molecule)\n\nmolecules = ['H2O', 'Mg(OH)2', 'K4[ON(SO3)2]2', 'C12H22O11']\n\nfor molecule in molecules:\n print(molecule)\n print(\"\\t\", tokenize_molecule(molecule))\n</code></pre>\n\n<p>which outputs:</p>\n\n<pre><code>H2O\n ['H', '2', 'O']\nMg(OH)2\n ['Mg', '(', 'O', 'H', ')', '2']\nK4[ON(SO3)2]2\n ['K', '4', '[', 'O', 'N', '(', 'S', 'O', '3', ')', '2', ']', '2']\nC12H22O11\n ['C', '12', 'H', '22', 'O', '11']\n</code></pre>\n\n<p>Here, the regex has 3 parts: <code>[A-Z][a-z]?</code> which matches an element, <code>\\d+</code>, which matches one or more digits, and <code>.</code> which matches any character. These are joined together with the <code>|</code> alternative operator; if the current character does not begin an element name, or a digit group, it is returned as a single character ... which is one of the bracket characters in a properly formed molecule.</p>\n\n<p>Using this initial parsing will make the parsing the molecule much easier:</p>\n\n<pre><code>def parse_molecule(molecule):\n\n # ... \n\n for token in re.findall('[A-Z][a-z]?|\\d+|.', molecule):\n\n if token.isalpha():\n # ...\n elif token.isdecimal():\n count = int(token)\n # ...\n elif token in '([{':\n # ...\n elif token in ')]}':\n # ...\n else:\n raise ValueError('Unrecognized character in molecule')\n\n # ...\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-20T08:43:19.853", "Id": "454478", "Score": "0", "body": "Thank you for the explanation, it is very helpfull and I now understand the mistakes I did" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-20T00:01:21.560", "Id": "232671", "ParentId": "232630", "Score": "9" } }, { "body": "<p>To add to AJNeufeld's answer, the regular expression scanner already knows which group matched. The matching group is available in the match object. Giving the groups names and using <code>re.finditer()</code> let's you write code like:</p>\n\n<pre><code>pattern = re.compile(r\"\"\"\n (?P&lt;element&gt;[A-Z][a-z]?)\n |(?P&lt;number&gt;\\d+)\n |(?P&lt;bracket&gt;[](){}[])\n |(?P&lt;other&gt;.)\n \"\"\", re.VERBOSE)\n\n\nfor token in pattern.finditer(molecule):\n if not token:\n ...error...\n\n if token['element']:\n ...\n\n elif token['number']: # &lt;-- this syntax available as of Python 3.6\n ...\n\n elif token['bracket']:\n ...\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-20T23:00:00.010", "Id": "454567", "Score": "0", "body": "The regex `[](){}[]` could use some demystification in your post. It is a character set regular expression `[...]` containing any one of the following characters `]` `(` `)` `{` `}` `[`. Since the `]` character normally terminates the set definition, and an empty set is useless as a character set, starting the character set with that character includes it in the regex set, instead of closing the set, and it terminates at the second `]` character." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-20T16:35:54.907", "Id": "232708", "ParentId": "232630", "Score": "3" } } ]
{ "AcceptedAnswerId": "232671", "CommentCount": "14", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-19T07:48:33.597", "Id": "232630", "Score": "7", "Tags": [ "python", "beginner", "parsing" ], "Title": "Parsing molecular formula" }
232630
<p>Below is a python script that generates the sequence <code>['a', 'b' .. 'z', 'aa', 'ab' .. 'az', 'ba', 'bb' .. 'zz', 'aaa', 'aab', ..]</code></p> <p>This is essentially counting in base 27, replacing every digit with the n-th letter of the alphabet, but skipping any number that would have a <code>'0'</code>.</p> <pre><code>import string def gen_labels(): i = 0 n = len(string.ascii_lowercase) + 1 while True: i += 1 j = i result = '' while True: c = j % n if not c: break result = string.ascii_lowercase[c-1] + result if j &lt; n: break j = j // n if c: yield result print(list(zip(gen_labels(), range(1000)))) </code></pre> <p>However, the code seems overly long to me for generating such a straightforward series and it's doing a lot of work to break down values that would have a <code>'0'</code> in them in base 27. </p> <p>What is a more efficient way of generating the exact same (infinite) series?</p> <p>Note that I'm not worried that much about speed, but mainly about the brevity / simplicity of the algorithm - it seems overly complicated, but I don't really see my way to an efficient realisation.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-19T08:38:51.817", "Id": "454311", "Score": "0", "body": "What is one of the numbers/letter combinations being skipped?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-19T11:15:49.083", "Id": "454329", "Score": "1", "body": "@Graipher he probably meant to say that no letter maps to number zero." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-19T20:30:50.117", "Id": "454423", "Score": "0", "body": "Isn't it more like counting in base 26, with `0` => `a`, `1` => `b`, etc." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-19T23:50:55.660", "Id": "454443", "Score": "0", "body": "filter out all those with a 0" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-20T02:53:01.050", "Id": "454453", "Score": "1", "body": "@Barmar, actually no. Imagine an alphabet with only [a, b]. The series would be `[a, b, aa, ab, ba, bb, aaa, etc.]` - turn that into numbers and you get `[0, 1, 00, 01, etc.]` so it's not like counting in base 26, with that mapping. Instead, if you count in base 27 `[0, 1, 2 .. p, 10, 11, 12, ..]` and leave out the numbers containing 0, you get `[1, 2 .. p, 11, 12, ..]` and then map using `1` => `a` etc., you get the correct series. That's the whole issue, I just feel there may be a more efficient modelling of the same problem." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-20T03:06:37.703", "Id": "454454", "Score": "0", "body": "Can you please name a few values that would not be present?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-20T03:56:19.920", "Id": "454459", "Score": "0", "body": "@shrivaths, if the character set would be [a, b, c] and 1 => a, 2 => b, 3=>c, with 0 missing, the values in the output are [1, 2, 3, 11, 12, 13, 21, 22, 23, 31, 32, 33, 111, etc.] - i.e. counting in base 4, skipping values that have zeroes - but see below for a different look at the same problem, looking at the series as a complete product of the character set of with an increasing number of factors." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-20T17:03:29.427", "Id": "454539", "Score": "0", "body": "@Grismar You're right. With normal numbers, `01` is the same as `1`, but your alphabet sequence doesn't have a zero that works like that." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-22T02:53:49.827", "Id": "454706", "Score": "2", "body": "Is this [bijective base-26](https://en.wikipedia.org/wiki/Bijective_numeration#The_bijective_base-26_system), as used in many spreadsheets ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-22T22:26:44.313", "Id": "454864", "Score": "1", "body": "You're right @DavidCary, thanks for putting a name to it - I wasn't aware." } ]
[ { "body": "<p>Well, what you want is just a product of the alphabet, with increasing numbers of elements. You can use <a href=\"https://docs.python.org/3.8/library/itertools.html#itertools.product\" rel=\"noreferrer\"><code>itertools.product</code></a> for this:</p>\n\n<pre><code>from itertools import product, count\nfrom string import ascii_lowercase\n\ndef generate_labels():\n \"\"\"Yields labels of the following form:\n a, b, ..., z, aa, ab, ..., zz, aaa, aab, ..., zzz, ...\n \"\"\"\n for n in count(start=1):\n yield from map(\"\".join, product(*[ascii_lowercase]*n))\n</code></pre>\n\n<p>Here is what it outputs:</p>\n\n<pre><code>from itertools import islice\n\nprint(list(islice(generate_labels(), 1000)))\n# ['a', 'b', ..., 'z', 'aa', 'ab', ..., 'az', 'ba', 'bb', ..., 'bz', ..., 'za', ..., 'zz', 'aaa', 'aab', ..., 'all']\n</code></pre>\n\n<p>This has the slight disadvantage that the list being passed to <code>product</code> gets larger every iteration. But already with <span class=\"math-container\">\\$n=5\\$</span> you can generate <span class=\"math-container\">\\$\\sum_{k=1}^n 26^k = 12,356,630\\$</span> labels, and the list is only about <code>sys.getsizeof([ascii_lowercase]*5) + sys.getsizeof(ascii_lowercase) * 5</code> = 479 bytes large, so in practice this should not be a problem.</p>\n\n<hr>\n\n<p>I also made the name a bit longer (and clearer IMO) and added a <a href=\"https://www.python.org/dev/peps/pep-0257/\" rel=\"noreferrer\"><code>docstring</code></a> to briefly describe what the function is doing.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-20T03:43:45.867", "Id": "454456", "Score": "0", "body": "You're right, it is just a full product with increasing length - exactly the fresh look at the problem I was after, thanks." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-19T08:51:04.927", "Id": "232635", "ParentId": "232632", "Score": "17" } }, { "body": "<p>The question is basically to continuously find the next lexicographically smallest string starting from 'a'</p>\n\n<p>Here's the code I created to solve with recursion:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>from sys import setrecursionlimit\nsetrecursionlimit(10 ** 9)\n\nALPS = 'abcdefghijklmnopqrstuvwxyz'\n\ndef parsed_string(l):\n return ''.join(ALPS[i] for i in l)\n\ndef solve(string=None, i=0):\n \"\"\"\n Prints the next lexicographically smallest string infinitely:\n a, b, ..., z, aa, ab, ..., zz, aaa, ..., zzz, ...\n \"\"\"\n\n # Entering a list as default parameter should be avoided in python\n if string is None:\n string = [0]\n\n # Base case\n if i == len(string):\n print(parsed_string(string))\n return\n\n # Generate values if the current element is the alphabet\n while string[i] &lt; 26:\n solve(string, i + 1)\n string[i] += 1\n\n # If the current index is the first element and it has reached 'z'\n if i == 0:\n string = [0] * (len(string) + 1)\n solve(string)\n\n else:\n string[i] = 0\n\nsolve()\n</code></pre>\n\n<p><strong>EDIT 1:</strong> </p>\n\n<ul>\n<li>This might cause <code>MemoryError</code> or <code>RecursionError</code> if the code is run for too long</li>\n<li>You can <code>yield</code> the value or <code>append</code> it to a list if you wish. The code was to provide a basic idea of how to solve the problem</li>\n</ul>\n\n<p>Hope this helps!</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-20T03:45:37.747", "Id": "454457", "Score": "0", "body": "It's not wrong, but you're right - the recursion is risky, especially when you change parameters and a large number of labels is needed for a small character set (unlike in my original example). @graipher has the better solution in that respect." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-20T03:59:49.553", "Id": "454460", "Score": "0", "body": "Of course! I agree. We just have to explore new possibilites, right? :D" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-19T19:47:46.650", "Id": "232657", "ParentId": "232632", "Score": "1" } }, { "body": "<p>I thought I might compliment the other answers with an approach that follows the OP intuition closer.</p>\n\n<p>I made it recursive, and factored out the creation of the sequence to a helper function :</p>\n\n<pre><code>def nth_label(n,symbols,accumulator=\"\"):\n q = n // len(symbols)\n m = n % len(symbols)\n if q==0:\n return symbols[m]+accumulator\n else:\n return nth_label(q-1,symbols,symbols[m]+accumulator)\n\ndef generate_labels():\n i = 0\n while True:\n yield nth_label(i, \"abcdefghijklmnopqrstuvwxyz\")\n i += 1\n</code></pre>\n\n<p>Please be aware I just tested the equivalent javascript, not this python version!</p>\n\n<p>Note that though this uses a recursive function, the depth of the recursion is only logarithmic on the number, with the base being the number of symbols (so a small number of recursions in practice).</p>\n\n<p>It's easy to convert it to an iterative function, if a little less elegant IMO. It might be easier to see how this is different from itertools.product in the explicitly iterative version:</p>\n\n<pre><code>def nth_label(n,symbols):\n result = \"\"\n q = n // len(symbols)\n m = n % len(symbols)\n while q&gt;0:\n result = symbols[m]+result\n n = q - 1\n q = n // len(symbols)\n m = n % len(symbols)\n\n return symbols[m]+result\n\ndef generate_labels():\n i = 0\n while True:\n yield nth_label(i, \"abcdefghijklmnopqrstuvwxyz\")\n i += 1\n</code></pre>\n\n<p>It's proportional to log_k of n, where k is the number of symbols, in both space and time.</p>\n\n<p>Sorry for the previous errors, this one <a href=\"https://tio.run/##dZDdTsMwDIXv@xRWJKRUK1rGJVL3FNwhhNLOtAHHbfPD6F6@ZOmEJmC5so@T7xxnnEM/8MOyHPANOPSvpBskyZWfbTOQr3TbRhtJh8HVQpSPBYBDHylADUKkbkoFw3YLhCwvr8qk26zf/ZaPvSGEaa/OpCvW5cqzfdmsWh5zmkxwD7vc3bK6YZajhuj4H3hx3rdDRqcDrkt7mbczCaV@gj65iGtSmA3S4eqPTAVCN20Cdb15/yDLwzg5H@Ln8Ws@iTVYwm3qFL8YneEgyfggT2aUf6wrcJo7lDulVJnOsnwD\" rel=\"nofollow noreferrer\">is tested ;)</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-21T07:09:10.403", "Id": "454576", "Score": "0", "body": "Yeah, it basically codes out what @Graipher also provided as a solution; your recursive solution takes the place of the `itertools.product` and your `generate_labels` routine is the outer loop increasing the count. Thanks for contributing though, it may provide some additional insight to people that aren't familiar with those Python library functions. I updated your code to follow Python naming conventions and fixed a bug in the 2nd line of your `nth_label` function and tested the code - it works." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-21T17:46:21.027", "Id": "454673", "Score": "0", "body": "@Grismar Not exactly, though. The `nthLabel` function doesn't take a concatenation of the symbols, just a single copy. If I read his code correctly, he passes a list that gets bigger on each iteration? My code does what you did as close as possible, I just simplified the part that looked overly complex to you originally." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-21T17:49:54.430", "Id": "454675", "Score": "0", "body": "@Grimar PS: your edit was rejected by the review queue, I'll change those names, not much of a pythonista myself sorry" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-22T01:28:27.247", "Id": "454703", "Score": "0", "body": "@Grismar I've updated the answer, to make it more obvious how this differs from `itertools.product`." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-21T02:07:24.957", "Id": "232723", "ParentId": "232632", "Score": "0" } } ]
{ "AcceptedAnswerId": "232635", "CommentCount": "10", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-19T08:03:23.833", "Id": "232632", "Score": "9", "Tags": [ "python", "performance" ], "Title": "Counting without zeroes" }
232632
<p>I was doing following question on leetcode: String to Integer (atoi)</p> <p>Question: </p> <blockquote> <p>Implement atoi which converts a string to an integer.</p> <p>The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by as many numerical digits as possible, and interprets them as a numerical value.</p> <p>The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function.</p> <p>If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed.</p> <p>If no valid conversion could be performed, a zero value is returned.</p> <p>Note:</p> <p>Only the space character ' ' is considered as whitespace character. Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−2<sup>31</sup>, 2<sup>31</sup> − 1]. If the numerical value is out of the range of representable values, INT_MAX (2<sup>31</sup> − 1) or INT_MIN (−2<sup>31</sup>) is returned.</p> </blockquote> <p>Question link: <a href="https://leetcode.com/problems/string-to-integer-atoi/" rel="nofollow noreferrer">https://leetcode.com/problems/string-to-integer-atoi/</a></p> <p>For the above question, I wrote the following code </p> <pre><code>/** * @param {string} str * @return {number} */ var myAtoi = function(str) { let i = 0 let output = '' const intMax = 2**31 - 1 const intMin = -intMax - 1 while (i&lt;str.length) { const char = str[i] if (!char == " ") { if (char.toLowerCase() === char.toUpperCase()) { output = output + char } else if (output) { break } if (!output) return 0 } i++ } output = parseInt(output) if (output !== null &amp;&amp; !isNaN(output)) { if (output &gt; intMax) return intMax if (output &lt; intMin) return intMin return output } return 0 } </code></pre> <p>Can someone improve upon the same and give me suggestions on how I can improve my code? </p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-19T11:27:21.860", "Id": "454332", "Score": "1", "body": "Are you sure you Are allowed to use parseInt? It Is basically atoi function... It defeats the purpose of the excercise if you use native implementation of your task..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-19T11:30:09.510", "Id": "454334", "Score": "1", "body": "Also you cannot check if number representation Is greater than the maximum representable number. Because if IT was than the number you Are checking against Is not the greatest representable number. Which Is an obvious contradiction..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-19T12:03:36.313", "Id": "454338", "Score": "0", "body": "FWIW the original condition doesn't say the environment can't **process** larger numbers outside of the specified range, it can't **store** them, which may make sense if the target is a database (or a record in memory) with fixed field types. Overall the question is open for interpretation, it's not really strict." } ]
[ { "body": "<p>If you are allowed to use <code>parseInt</code> and other built-in JS methods there's no need to skip the whitespace in a loop nor to find the sign/digits as parseInt does so by default. Here's the entire code of the function:</p>\n\n<pre><code>// only ACSII spaces are allowed at the start but parseInt also skips tabs and CR/LF\nstr = str.replace(/^ +/, '');\nconst num = /^[-+]?\\d/.test(str) ? parseInt(str, 10) : 0;\nreturn Math.max(-(2**31), Math.min(2**31 - 1, num || 0));\n</code></pre>\n\n<p>The <code>|| 0</code> will handle <code>NaN</code>.<br>\nNote, <code>parseInt</code> doesn't produce <code>null</code> so you don't need that check.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-19T10:08:23.887", "Id": "232637", "ParentId": "232633", "Score": "0" } }, { "body": "<p>Unfortunately there are several problems with your code. It only reason it works is because you are using <code>parseInt</code> which (as @wOxxOm shows) fulfills the original task requirements and thus ignores your broken attempts at cleaning the string.</p>\n\n<h1><code>!char == \" \"</code></h1>\n\n<p>This expression always returns <code>true</code>. Like in most programming languages negation (<code>!</code>) have a higher precedence than the comparison <code>==</code>, so <code>!char</code> is resolved to <code>false</code> (unless <code>char</code> were an empty string, which in this case it never is) and <code>false == \" \"</code> resolves to <code>true</code> (to be honest I'm not sure why, I'd have to look it up. JavaScript's rules for non-strict comparison (<code>==</code>) are quite complex.) </p>\n\n<p>So it should be <code>char != \" \"</code> , or even better <code>char !== \" \"</code>. Always use strict comparison, unless you have a good reason not to.</p>\n\n<h1><code>char.toLowerCase() === char.toUpperCase()</code></h1>\n\n<p>This is a strange attempt to identify digits (and <code>+</code>/<code>-</code>). There are countless other characters that are not filtered by this.</p>\n\n<h1>32-bit signed integer range</h1>\n\n<p>You are missing the point of this rule. When the system is assumed not to be able to store integers outside the range, then that means a variable can't hold such a large/low number, so a comparison such as <code>output &gt; intMax</code> can never be true, since <code>output</code> can't physically contain a number larger than <code>intMax</code>.</p>\n\n<h1>Don't reuse variables</h1>\n\n<p>In <code>output = parseInt(output)</code> you change the type and the semantics of the variable <code>output</code>. This is confusing for the reader. And the name <code>output</code> for the original use of collecting the validated string wrong anyway.</p>\n\n<h1>Don't leave out semicolons</h1>\n\n<p>JavaScript's automatic semicolon insertion is nearly as complex as its non-strict comparison rules. By leaving out the semicolons you make the code more difficult to read because the reader then has an additional thing they need to consider.</p>\n\n<h1>Finally</h1>\n\n<p>The big problem here is you using <code>parseInt</code>. For one, as mentioned it's hiding the bugs in the code, and more importantly, you are missing the whole point of this exercise, which is to understand how string to number conversion actually works. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-19T11:21:48.960", "Id": "232639", "ParentId": "232633", "Score": "7" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-19T08:15:30.247", "Id": "232633", "Score": "1", "Tags": [ "javascript" ], "Title": "String to Integer (atoi)" }
232633
<p>I've got some working code to compute the Hough transform for circles:</p> <pre><code> #include &lt;stdio.h&gt; #include &lt;opencv/cv.hpp&gt; #include &lt;math.h&gt; #include &lt;string&gt; #include &lt;iostream&gt; int *** allocate3DArray(int y, int x, int r) { int ***array = (int***)malloc(sizeof(int**)*y); for (int i = 0; i &lt; y; i++) { array[i] = (int**)malloc(sizeof(int*)*x); for (int j = 0; j &lt; x; j++) { array[i][j] = (int*)malloc(sizeof(int)*r); for(int k = 0; k &lt; r; k++) { array[i][j][k] = 0; } } } return array; } void free3d(int ***arr, int y, int x, int r) { for (int i = 0; i &lt; y; i++) { for (int j = 0; j &lt; x; j++) { free(arr[i][j]); } free(arr[i]); } free(arr); } vector&lt;Circle&gt; HoughTransformCircles(Mat image, Mat &amp;gradient_mag, Mat &amp;gradient_dir) { //Maximum circle radius is rLen = image.width / 2 int rLen = image.rows/2; int ***houghSpace = allocate3DArray(image.rows, image.cols, rLen); for (int y = 0; y &lt; image.rows; y++) { for (int x = 0; x &lt; image.cols; x++) { for (int r = 0; r &lt; rLen; r++) { int x0 = x - (int)(r*cos(gradient_dir.at&lt;double&gt;(y, x))); int y0 = y - (int)(r*sin(gradient_dir.at&lt;double&gt;(y, x))); if(x0 &gt;= 0 &amp;&amp; x0 &lt; image.cols &amp;&amp; y0 &gt;= 0 &amp;&amp; y0 &lt; image.rows ) { houghSpace[y0][x0][r]++; } x0 = x + (int)(r*cos(gradient_dir.at&lt;double&gt;(y, x))); y0 = y + (int)(r*sin(gradient_dir.at&lt;double&gt;(y, x))); if(x0 &gt;= 0 &amp;&amp; x0 &lt; image.cols &amp;&amp; y0 &gt;= 0 &amp;&amp; y0 &lt; image.rows ) { houghSpace[y0][x0][r]++; } } } } vector&lt;Circle&gt; circles; for (int y = 0; y &lt; image.rows; y++) { for (int x = 0; x &lt; image.cols; x++) { for (int r = 0; r &lt; rLen; r++) { if (houghSpace[y][x][r] &gt; 30) { Circle temp = Circle(x, y, r); circles.push_back(temp); } } } } free3d(houghSpace, image.rows, image.cols, rLen); return circles; } </code></pre> <p>How do I make this as idiomatic as possible? I am not allowed to use C++ 11 unfortunately. </p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-19T15:34:10.547", "Id": "454385", "Score": "2", "body": "Could you add a link to a description of the Hough transform algorithm? If the restriction on C++11 is a teacher/professor mandated restriction could you please add the homework tag as well." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-19T15:41:29.837", "Id": "454386", "Score": "0", "body": "@pacmaninbw hasn't the homework tag been deprecated for quite some time?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-19T15:53:09.690", "Id": "454389", "Score": "0", "body": "@Casey not that I know of on Code Review." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-19T15:59:05.347", "Id": "454390", "Score": "1", "body": "@Casey I have just searched code review meta, it is not depreciated." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-19T16:08:30.493", "Id": "454395", "Score": "1", "body": "@pacmaninbw Yeah, my mistake, I was thinking SO." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-19T16:09:23.227", "Id": "454396", "Score": "8", "body": "What is the reason for the \"not allowed to use C++11?\"" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-01T15:57:40.753", "Id": "455784", "Score": "0", "body": "Your #1 priority for improving your code is to get rid of the array of arrays of arrays, and allocate the Hough space as a single block of memory. Using a `std::vector<int>` or a `cv::Mat` or whatever else you choose. Having the data spread out through memory and needing so many pointer lookups for each bin increment is highly inefficient." } ]
[ { "body": "<p>There are a number of things I would change here:</p>\n\n<ul>\n<li><p><code>gradient_mag</code> is unused in HoughTransformCircles and should be removed.</p></li>\n<li><p><code>Mat</code> will presumably normally be a relatively large array so relatively expensive to copy, additionally you don't modify <code>image</code> or <code>gradient_dir</code> in the code. These can both be passed in as <code>const Mat &amp;</code>.</p></li>\n<li><p>You should make variables that shouldn't change e.g. <code>rLen</code>, const. This prevents you accidentally modifying them later.</p></li>\n<li><p>Similarly you should prefer <code>size_t</code> to int for variables that can't be &lt;0. In your case all the counters in the loops and rLen.</p></li>\n<li><p>Avoid c style casts e.g. <code>(int)(r*cos(gradient_dir.at&lt;double&gt;(y, x)</code>, prefer explicit <code>static_cast&lt;int&gt;()</code> instead. The c style cast will do a const cast or re-interpret cast if it thinks it needs to which can lead to unexpected results if you are not careful.</p></li>\n<li><p>I would avoid using c style arrays to store <code>houghSpace</code>. What you have done looks correct, but would be easy to break if you want to extend the code.\nIn modern c++ the obvious replacement for this is std::array, but if you are not using c++11 that is not an option.\nAnother option is to use std::vector. You can initialise the vector to zeros of the desired size. This option might have some memory overhead, but it should be small (would need testing).\nA third option as you are already using opencv would be to make houghSpace another Mat. I'm not sure what the memory/performance characteristics of Mat are, but this seems like the natural solution.</p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-19T16:02:06.777", "Id": "454391", "Score": "0", "body": "If the user can't use `std::array`, then they certainly can't use `std::vector` which they are already doing." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-19T16:08:14.940", "Id": "454394", "Score": "5", "body": "@pacmaninbw: actually, `std::array` was new in C++11, but `std::vector` existed in C++98, so nivag's answer is correct." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-19T15:42:59.677", "Id": "232645", "ParentId": "232636", "Score": "6" } }, { "body": "<p>In addition to what was mentioned in the review by @nivag.</p>\n\n<p>With the exception of the use of <code>std::vector</code> the code looks a lot more like C than any version of C++.</p>\n\n<h2>Proper Include Headers</h2>\n\n<p>The code under review does not require <code>stdio.h</code>.</p>\n\n<p>Please note that in C++ C programming include files can be included by inserting <code>'c'</code> before the header name and removing the dot h.</p>\n\n<pre><code>#include &lt;cstdio&gt;\n#include &lt;cmath&gt;\n</code></pre>\n\n<h2>Lack Of Error Checking</h2>\n\n<p>In C++ the <code>new</code> operator has replaced the call to <code>malloc(size_t size)</code>, and the <code>delete</code> operator has replaced the call to <code>free(void *object)</code>. One of the benefits of the <code>new</code> operator is that it throws an exception when the memory allocation fails, the call to <code>malloc(size_t size)</code> only returns <code>NULL</code> (in C) or <code>nullptr</code> (in C++). Accessing memory through a null pointer causes unknown behavior, the return value of <code>malloc(size_t size)</code> should always be checked before usage.</p>\n\n<pre><code>int *** allocate3DArray(int y, int x, int r) {\n int ***array = (int***)malloc(sizeof(int**)*y);\n if (array == nullptr)\n {\n std::cerr &lt;&lt; \"In allocate3DArray allocation of array failed\\n\";\n return array;\n }\n for (int i = 0; i &lt; y; i++) {\n array[i] = (int**)malloc(sizeof(int*)*x);\n if (array[i] == nullptr)\n {\n std::cerr &lt;&lt; \"In allocate3DArray allocation of array[\" &lt;&lt; i &lt;&lt; \"] failed\\n\";\n return nullptr;\n }\n for (int j = 0; j &lt; x; j++) {\n array[i][j] = (int*)malloc(sizeof(int)*r);\n if (array[i][j] == nullptr)\n {\n std::cerr &lt;&lt; \"In allocate3DArray allocation of array[\" &lt;&lt; i &lt;&lt; \"][\" &lt;&lt; j &lt;&lt; \"] failed\\n\";\n return nullptr;\n }\n for(int k = 0; k &lt; r; k++) {\n array[i][j][k] = 0;\n }\n }\n }\n return array;\n}\n</code></pre>\n\n<p>For the reasons listed above, <code>new</code> should be preferred over <code>malloc</code>.</p>\n\n<h2>Use C++ Container Classes over C Style Arrays</h2>\n\n<p>As mentioned in another review there are clear benefits of using C++ Container Classes over C Style Arrays. In addition to the proper type of memory being allocated with less code, container classes provide iterators which provide safer ways to iterate through the objects in the container, it is much more difficult to iterate off the end of an array when the iterators and container.begin() and container.end() are used.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-19T16:38:18.260", "Id": "232646", "ParentId": "232636", "Score": "7" } }, { "body": "<p>Here are some suggestions for improving the code.</p>\n\n<h2>Use all required <code>#include</code>s</h2>\n\n<p>The code uses <code>vector</code> but doesn't include the corresponding header. The code should have</p>\n\n<pre><code>#include &lt;vector&gt;\n</code></pre>\n\n<h2>Use <code>&lt;cmath&gt;</code> instead of <code>&lt;math.h&gt;</code></h2>\n\n<p>The difference between the two forms is that the former defines things within the <code>std::</code> namespace versus into the global namespace. Language lawyers have lots of fun with this, but for daily use I'd recommend using <code>&lt;cmath&gt;</code> (and also <code>&lt;cstdio&gt;</code>). See <a href=\"http://stackoverflow.com/questions/8734230/math-interface-vs-cmath-in-c/8734292#8734292\">this SO question</a> for details. </p>\n\n<h2>Avoid <code>malloc</code> and <code>free</code></h2>\n\n<p>The old C-style calls still work, of course, but are not recommended. They are error prone and tend to require more code to do correctly (i.e. checking the return value of <code>malloc</code> for <code>NULL</code>). Instead, the modern C++ idiom is to use RAII which stand for \"Resource Acquisition Is Initialization). See <a href=\"https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#Rr-mallocfree\" rel=\"nofollow noreferrer\">R.10</a> and <a href=\"https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#r1-manage-resources-automatically-using-resource-handles-and-raii-resource-acquisition-is-initialization\" rel=\"nofollow noreferrer\">R.1</a> for details.</p>\n\n<h2>Use objects</h2>\n\n<p>The 3D array would be much better implemented as an object. While you could, of course, write one (and I'd encourage you to try that as a learning exercise), there's an even smarter way to do that in the next suggestion.</p>\n\n<h2>Know your libraries</h2>\n\n<p>The code is already using the OpenCV <code>Mat</code> class, so what would make sense would be to also use that for the Hough space as well. So this line:</p>\n\n<pre><code>int ***houghSpace = allocate3DArray(image.rows, image.cols, rLen);\n</code></pre>\n\n<p>would be written instead like this:</p>\n\n<pre><code>int dims[] = { image.rows, image.cols, rLen };\nMat houghSpace(3, dims, CV_8UC(1), Scalar::all(0));\n</code></pre>\n\n<p>Since that's a properly designed C++ class, it will automatically allocate memory as needed and also de-allocate it when the <code>houghSpace</code> object's destructor is called. Using it is almost a simple:</p>\n\n<pre><code>houghSpace.at&lt;cv::Vec3i&gt;(y0,x0)[r]++;\n</code></pre>\n\n<h2>Eliminate unused variables</h2>\n\n<p>Unused variables are a sign of poor code quality, so eliminating them should be a priority. In this code, <code>gradient_mag</code> in <code>HoughTransformCircles</code> and <code>r</code> in <code>free3d</code> are unused. Your compiler is probably also smart enough to tell you that, if you ask it to do so. </p>\n\n<h2>Don't abuse <code>using namespace std</code></h2>\n\n<p>Putting <code>using namespace std</code> at the top of every program is <a href=\"http://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice\">a bad habit</a> that you'd do well to avoid. It also appears you've got <code>using namespace cv;</code> somewhere as well and it's also not a good idea for similar reasons.</p>\n\n<h2>Use variables to clarify your code</h2>\n\n<p>The code currently has this nested set of loops:</p>\n\n<pre><code>for (int y = 0; y &lt; image.rows; y++) {\n for (int x = 0; x &lt; image.cols; x++) {\n for (int r = 0; r &lt; rLen; r++) {\n int x0 = x - (int)(r*cos(gradient_dir.at&lt;double&gt;(y, x)));\n int y0 = y - (int)(r*sin(gradient_dir.at&lt;double&gt;(y, x)));\n if(x0 &gt;= 0 &amp;&amp; x0 &lt; image.cols &amp;&amp; y0 &gt;= 0 &amp;&amp; y0 &lt; image.rows ) {\n houghSpace[y0][x0][r]++;\n }\n x0 = x + (int)(r*cos(gradient_dir.at&lt;double&gt;(y, x)));\n y0 = y + (int)(r*sin(gradient_dir.at&lt;double&gt;(y, x)));\n if(x0 &gt;= 0 &amp;&amp; x0 &lt; image.cols &amp;&amp; y0 &gt;= 0 &amp;&amp; y0 &lt; image.rows ) {\n houghSpace[y0][x0][r]++;\n }\n }\n }\n}\n</code></pre>\n\n<p>Instead, I'd write it like this:</p>\n\n<pre><code>for (int y = 0; y &lt; image.rows; y++) {\n for (int x = 0; x &lt; image.cols; x++) {\n for (int r = 0; r &lt; rLen; r++) {\n int a = r * std::cos(gradient_dir.at&lt;double&gt;(y, x));\n int b = r * std::sin(gradient_dir.at&lt;double&gt;(y, x));\n int x0 = x - a;\n int y0 = y - b;\n if(x0 &gt;= 0 &amp;&amp; x0 &lt; image.cols &amp;&amp; y0 &gt;= 0 &amp;&amp; y0 &lt; image.rows ) {\n houghSpace.at&lt;cv::Vec3i&gt;(y0,x0)[r]++;\n }\n x0 = x + a;\n y0 = y + b;\n if(x0 &gt;= 0 &amp;&amp; x0 &lt; image.cols &amp;&amp; y0 &gt;= 0 &amp;&amp; y0 &lt; image.rows ) {\n houghSpace.at&lt;cv::Vec3i&gt;(y0,x0)[r]++;\n }\n }\n }\n}\n</code></pre>\n\n<p>In C++11, I'd use a range-for.</p>\n\n<h2>Provide complete code to reviewers</h2>\n\n<p>This is not so much a change to the code as a change in how you present it to other people. Without the full context of the code and an example of how to use it, it takes more effort for other people to understand your code. This affects not only code reviews, but also maintenance of the code in the future, by you or by others. One good way to address that is by the use of comments. Another good technique is to include test code showing how your code is intended to be used.</p>\n\n<h2>Use <code>const</code> where possible</h2>\n\n<p>The <code>HoughTransformCircles</code> routine does not alter the <code>image</code> passed to it, and so it should be declared as taking <code>const Mat&amp; image</code> as an argument.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-19T18:02:05.747", "Id": "232652", "ParentId": "232636", "Score": "13" } } ]
{ "AcceptedAnswerId": "232652", "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-19T09:05:36.610", "Id": "232636", "Score": "13", "Tags": [ "c++", "image" ], "Title": "Hough transform algorithm - Idiomatic c++" }
232636
<p>I'm trying to solve <a href="https://codeforces.com/contest/1243/problem/E" rel="nofollow noreferrer">P1243E</a> in an efficient manner. The problem in simple words is:</p> <blockquote> <p>Given <span class="math-container">\$k\$</span> boxes, <span class="math-container">\$i\$</span>-th box with <span class="math-container">\$n_i\$</span> numbers. All numbers are distinct. We need to select one number from each box and after permuting them in such a way that after putting exactly one number back in one box will lead to all boxes having same sum. </p> <p><strong>Input</strong>: <span class="math-container">\$k\$</span>, then each line with <span class="math-container">\$n_i\$</span> and box-<span class="math-container">\$i\$</span> elements.</p> <p><strong>Output</strong>: Yes/No - whether such a rearrangement is possible, followed by each line containing the value to choose and the box-id it will go.</p> </blockquote> <p>My solution is this:</p> <blockquote> <p>First check if average is a whole number which will be the sum of each box. Then since each number is distinct, we can draw an edge from a number <span class="math-container">\$a\$</span> in box <span class="math-container">\$i\$</span> to another number <span class="math-container">\$b\$</span> in another box <span class="math-container">\$j\$</span> if we put <span class="math-container">\$a\$</span> in box <span class="math-container">\$j\$</span> and remove <span class="math-container">\$b\$</span> then that box's sum becomes equal to average. For this we will find the difference of the current sum in box <span class="math-container">\$j\$</span> and the average sum, if this is equal to <span class="math-container">\$b-a\$</span> then this will bring the box <span class="math-container">\$j\$</span>'s sum to average. A permutation will be collection of cycles with distinct box ids covering all box ids. So we can just do DFS with backtracking to find such a collection of cycles.</p> </blockquote> <p>The <a href="https://codeforces.com/blog/entry/71216" rel="nofollow noreferrer">editorial</a> proposes an even better method:</p> <blockquote> <p>We can extract cycles from the graph and then convert cycle to a set with elements the box ids of covered numbers. We can then perform set cover for <span class="math-container">\$\{1,2,...k\}\$</span> using these sets with a dynamic programming method. </p> </blockquote> <p>So I came up with this code which is quite faithful to the editorial that takes <span class="math-container">\$\sim 9\$</span> seconds for <a href="https://codeforces.com/gym/260238/submission/65340564" rel="nofollow noreferrer">execution</a> whereas actual time limits are <span class="math-container">\$1\$</span> sec. What time performance improvements can be done: (Just to confirm, there are solutions in Java by others with same logic but <span class="math-container">\$\sim 200\$</span> ms execution time)</p> <pre class="lang-java prettyprint-override"><code>import java.io.*; import java.util.*; public class P1243E { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); Task solver = new Task(); boolean debug = !Boolean.parseBoolean(System.getProperty("ONLINE_JUDGE")); solver.solve(in, out, debug); out.close(); } static class Task { public void solve(InputReader in, PrintWriter out, boolean debug) { int k = in.nextInt(); int[][] boxes = new int[k][]; HashMap&lt;Integer, Node&gt; nodes = new HashMap&lt;&gt;(); long totSum = 0; long[] boxSums = new long[k]; for (int i = 0; i &lt; k; i++) { int n = in.nextInt(); int[] box = new int[n]; for (int j = 0; j &lt; n; j++) { int a = in.nextInt(); totSum += a; boxSums[i] += a; box[j] = a; nodes.put(a, new Node(a, i)); } boxes[i] = box; } if (totSum % k != 0) { out.println("No"); } else { /* Calculate edges */ long boxSum = totSum / k; long[] delta = new long[k]; for (int i = 0; i &lt; k; i++) { delta[i] = boxSum - boxSums[i]; } HashSet&lt;Node&gt; remaining = new HashSet&lt;&gt;(); for (int i = 0; i &lt; k; i++) { for (int boxVal : boxes[i]) { Node currNode = nodes.get(boxVal); long nextValLong = boxVal + delta[i]; if ((int) nextValLong != nextValLong) { continue; } int nextVal = (int) nextValLong; if (nodes.containsKey(nextVal)) { Node nextNode = nodes.get(nextVal); if (nextNode.boxId != i || nextVal == boxVal) { currNode.next = nextNode; remaining.add(currNode); } } } } /* Extract Cycles */ int max = (1 &lt;&lt; k) - 1; HashMap&lt;Integer, ArrayList&lt;Node&gt;&gt; cycles = new HashMap&lt;&gt;(); while (remaining.size() &gt; 0) { /* Get element */ Node top = remaining.iterator().next(); HashSet&lt;Node&gt; visited = new HashSet&lt;&gt;(); /* DFS from this element */ Node curr = top; while (true) { /* Process curr */ if (!visited.contains(curr)) { visited.add(curr); remaining.remove(curr); } else { /* Back edge */ int cycleID = 0; ArrayList&lt;Node&gt; cycle = new ArrayList&lt;&gt;(); /* Extract cycle */ Node loop = curr; boolean validCycle = true; do { if ((cycleID &gt;&gt; loop.boxId &amp; 1) == 1) { validCycle = false; /* Dont add cycle, these nodes are already visited, so they will be removed anyways*/ break; } cycleID |= 1 &lt;&lt; loop.boxId; cycle.add(loop); loop = loop.prev; } while (loop != curr &amp;&amp; loop != null); if (validCycle) { cycles.putIfAbsent(cycleID, cycle); } /* Exit DFS */ break; } /* Check &amp; Move pointer */ if (curr.next != null) { /* set prev for this run */ curr.next.prev = curr; /* move pointer */ curr = curr.next; } else { break; } } } /* Calculate Set Cover */ boolean[] covered = new boolean[max + 1]; int[] subCover = new int[max + 1]; covered[0] = true; for (int i = 0; i &lt;= max; i++) { for (int j = i; j &gt; 0; j = (j - 1) &amp; i) { if (cycles.containsKey(j) &amp;&amp; covered[remove(i, j)]) { subCover[i] = j; covered[i] = true; break; } } } /* Print Solution */ if (covered[max]) { out.println("Yes"); Queue&lt;Integer&gt; bfs = new LinkedList&lt;&gt;(); ArrayList&lt;Node&gt; solution = new ArrayList&lt;&gt;(); bfs.add(max); while (bfs.size() &gt; 0) { int top = bfs.poll(); if (cycles.containsKey(top)) { solution.addAll(cycles.get(top)); } else { int sc = subCover[top]; bfs.add(sc); bfs.add(remove(top, sc)); } } int[] resultVal = new int[k]; int[] resultId = new int[k]; for (Node p : solution) { resultVal[p.boxId] = p.value; resultId[p.next.boxId] = p.boxId + 1; } for (int i = 0; i &lt; k; i++) { out.println(resultVal[i] + " " + resultId[i]); } } else { out.println("No"); } } } private int remove(int i, int j) { return i &amp; (~j); } private static class Node { int value; int boxId; Node next; Node prev; Node(int value, int boxId) { this.value = value; this.boxId = boxId; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null) { return false; } Node node = (Node) o; return value == node.value; } @Override public int hashCode() { return value; } @Override public String toString() { return (value % 1000) + "[" + boxId + "]"; } } } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public String nextLine() { try { return reader.readLine(); } catch (IOException e) { throw new RuntimeException(e); } } public int[] nextIntArray(int n) { int[] arr = new int[n]; for (int i = 0; i &lt; n; i++) { arr[i] = nextInt(); } return arr; } public long[] nextLongArray(int n) { long[] arr = new long[n]; for (int i = 0; i &lt; n; i++) { arr[i] = nextLong(); } return arr; } } } </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-19T11:07:08.633", "Id": "232638", "Score": "4", "Tags": [ "java", "performance", "programming-challenge", "time-limit-exceeded" ], "Title": "Extracting cycles from directed graph with max degree 1 and then performing set cover on cycles" }
232638
<p>This actually works nicely (we have > 2k repos) but I would really like it to start producing results right away as soon as it has any. Mostly so it seems faster than it is (by being more responsive).</p> <pre><code> bbrepos(){ #clone[1] is ssh using a filter made the escaping really ugly. #If it becomes necessary we can use a jq arg # get max number of repos, ceil(repos / 50), then create a page #sequence and curl them all local url=https://api.bitbucket.org/2.0/repositories/twengg local project=${1:+"q=project.key=\"$1\""} curl -snL "$url?pagelen=0&amp;page=1" | jq '"$(((\(.size) / 50) + 1 ))"' \ | xargs bash -c 'eval "echo $1"' _ | xargs seq 1 | xargs -L 1 printf "?pagelen=50&amp;page=%s&amp;${1:-$project}\n" \ | xargs -I {} -L 1 -P 20 -I {} bash -c 'curl -snL "$1/$2" | jq -er .values[].links.clone[1].href' _ $url {} \ #clone[1] is ssh | sort -u } </code></pre> <p>Sample workflow:</p> <pre><code>bbsearch something | xargs -P 20 git clone </code></pre> <p>Alternatively, it might also be handy to have these other workflows:</p> <pre><code>bbsearch something other thing | xargs -P 20 git clone cat things-to-find.txt | bbsearch | xargs -P 20 git clone </code></pre> <p>Sample payload (it's normally huge, so I stripped it down to what is needed):</p> <pre><code>{ "pagelen": 1, "size": 3054, "values": [ { "links": { "clone": [ { "href": "https://chb0bitbucket@bitbucket.org/twengg/development-process.git", "name": "https" }, { "href": "git@bitbucket.org:twengg/development-process.git", "name": "ssh" } ], "self": { "href": "https://api.bitbucket.org/2.0/repositories/twengg/development-process" } } } ], "page": 1, "next": "https://api.bitbucket.org/2.0/repositories/twengg?page=2" } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-19T12:25:25.563", "Id": "454342", "Score": "1", "body": "Please describe the flow appropriately and add a sample fragment of `.values[].links` structure" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-19T15:28:38.293", "Id": "454382", "Score": "1", "body": "This could be a great question if it described the work flow. Who doesn't want to speed up their workflow. A real example might also be nice." } ]
[ { "body": "<h3><code>eval</code> is evil</h3>\n\n<p>Always look for ways to avoid <code>eval</code>.</p>\n\n<p>Relevant snippet from the posted code:</p>\n\n<blockquote>\n<pre><code>curl -snL \"$url?pagelen=0&amp;page=1\" \\\n | jq '\"$(((\\(.size) / 50) + 1 ))\"' \\\n | xargs bash -c 'eval \"echo $1\"' _\n</code></pre>\n</blockquote>\n\n<p>The code uses <code>jq</code> to create a formatted expression to evaluate by Bash,\nwith <code>.size</code> injected in the middle of the expression.</p>\n\n<p>A better way to achieve the same thing would be to make <code>jq</code> simply output the variable itself, and then write the expression in Bash:</p>\n\n<pre><code>curl -snL \"$url?pagelen=0&amp;page=1\" \\\n | jq -r .size \\\n | xargs bash -c 'echo $((($1 / 50) + 1))' _\n</code></pre>\n\n<h3>Unnecessary pipeline</h3>\n\n<p>It's strange to use <code>xargs</code> to process one line of input,\nand it's strange to spawn another Bash just to evaluate an expression.\nThere's really no need to force a chain of operations in a single pipeline.</p>\n\n<p>I'd rewrite the above snippet like this:</p>\n\n<pre><code>repos_count=$(curl -snL \"$url?pagelen=0&amp;page=1\" | jq -r .size)\n((pages_count = (repos_count / 50) + 1))\n</code></pre>\n\n<h3>Store positional arguments in variables with descriptive names</h3>\n\n<p>It's a mental burden to have to remember what <code>$1</code> and <code>$2</code> mean.\nI'd store them in local variables with descriptive names at the beginning of the function.</p>\n\n<h3>Avoid <code>seq</code></h3>\n\n<p>Is it obsolete, and not available in all systems.\nUse a Bash counting loop instead:</p>\n\n<pre><code>for ((page = 1; page &lt;= pages_count; page++)); do\n ...\ndone \\\n| xargs -L 1 ...\n</code></pre>\n\n<h3>Break lines in long pipelines</h3>\n\n<p>It's easier to read code when there's one statement per line.\nThis is especially true when a line is so long you have to scroll to the right to see it.\nSo instead of this:</p>\n\n<blockquote>\n<pre><code>| xargs bash -c 'eval \"echo $1\"' _ | xargs seq 1 | xargs -L 1 printf \"?pagelen=50&amp;page=%s&amp;${1:-$project}\\n\" \\\n| xargs -I {} -L 1 -P 20 -I {} bash -c 'curl -snL \"$1/$2\" | jq -er .values[].links.clone[1].href' _ $url {} \\ #clone[1] is ssh\n| sort -u\n</code></pre>\n</blockquote>\n\n<p>I recommend to write like this:</p>\n\n<pre><code>| xargs bash -c 'eval \"echo $1\"' _ \\\n| xargs seq 1 \\\n| xargs -L 1 printf \"?pagelen=50&amp;page=%s&amp;${1:-$project}\\n\" \\\n| xargs -I {} -L 1 -P 20 -I {} bash -c 'curl -snL \"$1/$2\" \\\n| jq -er .values[].links.clone[1].href' _ $url {} \\\n| sort -u\n</code></pre>\n\n<h3>Always double-quote variables used as command line arguments</h3>\n\n<p>In <code>| jq -er .values[].links.clone[1].href' _ $url {}</code>\nyou forgot to double-quote <code>$url</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-07T20:11:52.927", "Id": "456698", "Score": "0", "body": "This is good feedback and I will incorporate it - however, it doesn't address how I get this to output immediately more input comes" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-28T19:42:56.463", "Id": "233132", "ParentId": "232640", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-19T11:41:42.350", "Id": "232640", "Score": "4", "Tags": [ "bash", "curl" ], "Title": "Code to fetch BitBucket repos" }
232640
<p>Today I found myself in need of programmatically getting a recursive list of the files on a remote FTP server to look for some data archives. Much to my surprise, I could not find this functionality implemented in some kind of Python library. So I decided to write a simple recursive version of <a href="https://docs.python.org/3/library/ftplib.html#ftplib.FTP.mlsd" rel="nofollow noreferrer"><code>ftplib.mlsd</code></a>, that can be found below:</p> <h3>ftphelper.py</h3> <pre><code>def recursive_mlsd(ftp_object, path="", maxdepth=None): """Run the FTP's MLSD command recursively The MLSD is returned as a list of tuples with (name, properties) for each object found on the FTP server. This function adds the non-standard property "children" which is then again an MLSD listing, possibly with more "children". Parameters ---------- ftp_object: ftplib.FTP or ftplib.FTP_TLS the (authenticated) FTP client object used to make the calls to the server path: str path to start the recursive listing from maxdepth: {None, int}, optional maximum recursion depth, has to be &gt;= 0 or None (i.e. no limit). Returns ------- list the recursive directory listing See also -------- ftplib.FTP.mlsd : the non-recursive version of this function """ if maxdepth is not None: maxdepth = int(maxdepth) if maxdepth &lt; 0: raise ValueError("maxdepth is supposed to be &gt;= 0") def _inner(path_, depth_): if maxdepth is not None and depth_ &gt; maxdepth: return inner_mlsd = list(ftp_object.mlsd(path=path_)) for name, properties in inner_mlsd: if properties["type"] == "dir": rec_path = path_+"/"+name if path_ else name res = _inner(rec_path, depth_+1) if res is not None: properties["children"] = res return inner_mlsd return _inner(path, 0) </code></pre> <p>A very basic example usage could be like:</p> <pre class="lang-py prettyprint-override"><code>import ftplib import getpass import pprint import sys import ftphelper host = "ftp1.at.proftpd.org" # from the Python docs directory = "historic" print(f"Login to '{host}' to list '{directory}'", file=sys.stderr) default_user = "" # getpass.getuser() could also be used where appropriate prompt = f"Username (default: '{default_user}'): " if sys.stdout.isatty(): user = input(prompt) else: print(prompt, end="", file=sys.stderr) user = input() user = user.strip() user = user if user else default_user with ftplib.FTP(host=host) as ftp: ftp.login(user=user, passwd=getpass.getpass()) listing = ftphelper.recursive_mlsd(ftp, directory) pp = pprint.PrettyPrinter(indent=2) pp.pprint(listing) </code></pre> <p>As always, every kind of feedback is welcome and much appreciated.</p>
[]
[ { "body": "<p>Seems good except for a few small improvements:</p>\n\n<ul>\n<li><code>path_+\"/\"+name</code> is better perceived with <code>f-string</code> formatting: <strong><code>f'{path_}/{name}</code></strong> </li>\n<li><code>user if user else default_user</code> is a verbose version of <strong><code>user or default_user</code></strong></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-19T20:15:06.403", "Id": "454421", "Score": "1", "body": "`user or default_user` is a cool \"trick\". Will definitely use it in the future!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-19T17:23:33.283", "Id": "232650", "ParentId": "232647", "Score": "5" } } ]
{ "AcceptedAnswerId": "232650", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-19T16:41:16.563", "Id": "232647", "Score": "5", "Tags": [ "python", "python-3.x", "ftp" ], "Title": "Recursively listing the content of an FTP server" }
232647
<p>I have the following function to save points cloud in PLOT3D format:</p> <pre class="lang-py prettyprint-override"><code>def write(filename, mesh): """ Write the mesh to filename in PLOT3D format. filename: is the name of the output file. mesh: is a numpy array of size (N,2) or (N, 3) where N is the number of points. mesh[i] is a numpy array coordinates of the i'th point. """ points = mesh.points imax = np.unique(points[:, 0]).size jmax = np.unique(points[:, 1]).size _2d = False if points.shape[1] == 2: _2d = True elif np.unique(points[:, 2]).size == 1: _2d = True with open(filename, "w") as p3dfile: if not _2d: kmax = np.unique(points[:, 2]).size print(imax, jmax, kmax, file=p3dfile) for value in points.flatten(order="F"): print(value, file=p3dfile) else: print(imax, jmax, file=p3dfile) for value in points[:, 0:2].flatten(order="F"): print(value, file=p3dfile) </code></pre> <p>For large number of points this function is very slow. </p> <p>I appreciate any suggestion to improve the code above.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-19T17:00:03.887", "Id": "454407", "Score": "1", "body": "Welcome to Code Review! A few quick questions that came to my mind reading your question: How slow is slow? How fast do you need/expect it to be? Have you already done sone profiling?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-19T17:44:31.157", "Id": "454411", "Score": "0", "body": "@AlexV: Someone reviewed my code on github, and told that this is super slow." } ]
[ { "body": "<h3>Optimizations/improvements:</h3>\n\n<p><em>Namings</em></p>\n\n<ul>\n<li><code>write</code> is too generic name for specific function. The one of better names is <strong><code>write_points</code></strong></li>\n<li><code>_2d</code>. Even if a variable is marked as \"protected\" <code>_...</code>, starting its name with a digit is a bad naming pattern. As it's a <em>boolean</em> flag a meaningful name would be <strong><code>is_2dim</code></strong> (<em>is 2-dimensional space</em>)</li>\n</ul>\n\n<p>Since <code>mesh</code> argument is only used to access its inner property <code>points</code> it's better to pass the target <em>points</em> data structure directly (It's called <em>Replace Query with Parameter</em> technique)</p>\n\n<p>In current approach, when reaching the condition <code>if not _2d:</code> the expression <code>np.unique(points[:, 2]).size</code> will be calculated repeatedly, instead: <br>\nsince <code>points</code> array is expected to be <em>2d</em> array with either 2 or 3 columns we can collect <em>unique counts</em> across all columns at once (instead of declaring <code>imax</code>, <code>jmax</code>):</p>\n\n<pre><code>col_counts = [np.unique(row).size for row in points.T]\n</code></pre>\n\n<p><br>\nThe whole conditional:</p>\n\n<pre><code>_2d = False\nif points.shape[1] == 2:\n _2d = True\nelif np.unique(points[:, 2]).size == 1:\n _2d = True\n</code></pre>\n\n<p>is now replaced with a single statement:</p>\n\n<pre><code>is_2dim = points.shape[1] == 2 or col_counts[2] == 1\n</code></pre>\n\n<p><br>\nCalling <code>print</code> function at each iteration to write the data into file:</p>\n\n<pre><code>for value in points.flatten(order=\"F\"):\n print(value, file=p3dfile)\n</code></pre>\n\n<p>is definitely <strong>less</strong> efficient and performant than calling <a href=\"https://docs.python.org/3/library/io.html#io.IOBase.writelines\" rel=\"nofollow noreferrer\"><strong><code>writelines()</code></strong></a> on <em>generator</em> expression at once.</p>\n\n<hr>\n\n<p>The final optimized function:</p>\n\n<pre><code>def write_points(filename, points):\n \"\"\"\n Write the mesh points to filename in PLOT3D format.\n filename: is the name of the output file.\n mesh: is a numpy array of size (N,2) or (N, 3) where N is the number of points. mesh[i] is a numpy array coordinates of the i'th point.\n\n \"\"\"\n col_counts = [np.unique(row).size for row in points.T]\n is_2dim = points.shape[1] == 2 or col_counts[2] == 1\n\n with open(filename, \"w\") as p3dfile:\n pd3file.write(' '.join(map(str, col_counts)))\n pd3file.writelines(f'{num}\\n' for num in points.flatten(order=\"F\"))\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-19T21:33:17.443", "Id": "232661", "ParentId": "232648", "Score": "3" } } ]
{ "AcceptedAnswerId": "232661", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-19T16:49:15.557", "Id": "232648", "Score": "4", "Tags": [ "python", "performance", "numpy" ], "Title": "Save points cloud in PLOT3D format" }
232648